


var AJAX_REQUEST = {
    DEBUG:           false,
    DEFAULT_ASYNC:   false,
    DEFAULT_METHOD:  'POST',
    DEFAULT_URL:     'rpcServer.php',
    MAX_REQUESTS:    10,
    REQUEST_TIMEOUT: 30000
}
if (!window.ajax)  {
    window.ajax = {
        NEXT_ID:        0,
        COUNT:          0,
        MAX_CONCURRENT: AJAX_REQUEST.MAX_REQUESTS
    };
}

function AjaxRequest(method, url, async, requestTimeout, user, password) {

    this.abort = function() {
        if (AJAX_REQUEST.DEBUG && typeof(writeDebug) == 'function') writeDebug('AjaxRequest.abort() called.');
        if (this.request && this.busy) {
            if (window.ajaxRequests && window.ajaxTimers && this.requestId >= 0) {
                if (AJAX_REQUEST.DEBUG && typeof(writeDebug) == 'function') writeDebug('abort(): clearing timeout: '+self.requestId+', timerId: '+window.ajaxTimers[self.requestId]);
                clearTimeout(window.ajaxTimers[this.requestId]);
                window.ajaxTimers[this.requestId] = null;
                window.ajaxRequests[this.requestId] = null;
            }
            this.request.onreadystatechange = function() { }; // Clear it for IE
            this.request.abort();
            this.request = null;
            this.busy    = false;
            window.ajax.COUNT--;
        }
    }
    this.send  = function() {
        try {
            this.request = new ActiveXObject('Msxml2.XMLHTTP');
        } catch (e) {
            try {
                this.request = new ActiveXObject('Microsoft.XMLHTTP');
            } catch (e) {
                try {
                    this.request = new XMLHttpRequest();
                } catch (e) {
                    this.request = null;
                }
            }
        }
        if (this.request) {
            var url     = this.url;
            if (this.async && this.callback) {
                this.request.onreadystatechange = this.onStateChange;
                if (this.requestTimeout != null && this.timeout > 0 && this.requestId == null) {
                    if (window.ajax.COUNT < window.ajax.MAX_CONCURRENT) {
                        this.requestId = window.ajax.NEXT_ID++;
                        window.ajax.COUNT++;
                    } else {
                        alert('Too many concurrent ajax requests.');
                        return false;
                    }
                    if (AJAX_REQUEST.DEBUG && typeof(writeDebug) == 'function') writeDebug('XmlHttpRequest '+this.requestId+' setting timeout: '+this.requestTimeout);
                    self.requestTimer = setTimeout(function() { self.abort(); self.requestTimer = null; if (typeof(writeDebug) == 'function') writeDebug('XmlHttpRequest '+self.requestId+' aborted.'); }, this.requestTimeout);
                }
            }
            if (this.method == 'POST') {
                this.request.open(this.method, this.url, this.async, this.user, this.password);
                this.request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
                this.busy = true;
                this.request.send(this.params.join('&'));
            } else {
                url = this.url+(this.params.length > 0 ? '?'+this.params.join('&') : '');
                this.request.open(this.method, url, this.async, this.user, this.password);
                this.busy = true;
                this.request.send('');
            }

            if (!this.async) {
                this.busy = false;;
                return this.request.responseXML;
            }
        }
    }

    this.setParameter = function(name, value) {
        if (AJAX_REQUEST.DEBUG && typeof(writeDebug) == 'function') writeDebug('AjaxRequest.setParameter('+name+', '+value+') called.');
        this.params.push(name+'='+encodeURIComponent(value));
    }

    this.setResponseType = function(ResponseType){
       this.ResponseType = (ResponseType=='html' ? 'html' : 'xml');
    }

    this.setCallback = function(func) {
        if (typeof(func) == 'function') this.callback = func;
        else                            alert('Unable to set callback handler. Must be a function.');
    }

    this.onStateChange = function() {
        if (self.request && self.request.readyState && self.request.readyState == 4) {
            if (self.requestTimer && self.requestId) {
                if (AJAX_REQUEST.DEBUG && typeof(writeDebug) == 'function') writeDebug('XmlHttpRequest '+this.requestId+' clearing timeout.');
                clearTimeout(self.requestTimer);
                self.requestTimer = null;
                self.requestId    = null;
            }
            self.busy = false;
            if (AJAX_REQUEST.DEBUG && typeof(writeDebug) == 'function') writeDebug('XmlHttpRequest.reponseText: '+self.request.responseText);
//			console.log(self.request.responseText);
            if(self.ResponseType && self.ResponseType=='html'){
               self.callback(self.request.responseText);
            }else{
               self.callback(self.request.responseXML);
            }
        }
    }



    this.method         = method          || AJAX_REQUEST.DEFAULT_METHOD;
    this.url            = url             || AJAX_REQUEST.DEFAULT_URL;
    this.async          = async           || AJAX_REQUEST.DEFAULT_ASYNC;
    this.requestTimeout = requestTimeout  || AJAX_REQUEST.REQUEST_TIMEOUT;
    this.user           = user            || null;
    this.password       = password        || null;
    this.callback       = null;
    this.params         = new Array;
    this.request        = null;
    this.requestTimer   = null;
    this.ResponseType   = 'xml'; // html or xml



    /**
     * JavaScript Closure Variable
     */
    var self = this;

}

function submitSearchRequest(page_id, requestParams, vendorIds, st, sv){

	var keyword = document.getElementById('shopForInput').value;
	var ajax = new AjaxRequest('POST', '/rpc_searchRequest.php', true, 3000);
	ajax.setParameter('keyword', keyword);
	if(page_id){
		ajax.setParameter('page_id', page_id);
	}
	if(requestParams){
		ajax.setParameter('requestParams', requestParams);
	}
	if(vendorIds){
		ajax.setParameter('vendorIds', vendorIds);
	}
    if( st ) {
		ajax.setParameter('st', st);
    }
    if( sv ) {
		ajax.setParameter('sv', sv);
    }

	var searchBar = document.getElementById('pgSiteSearch');
	if(searchBar && searchBar.getElementsByTagName('select')[0]){
		var searchSelect = searchBar.getElementsByTagName('select')[0].value;
		ajax.setParameter('searchLocation', searchSelect);
	}

	ajax.setCallback(getSearchAction);
	ajax.send();

	return false;

}

function getSearchAction(xml){

	var search_action = xml.getElementsByTagName('search_action');
	var json = search_action[0].firstChild; 
	var url = eval(json.firstChild.nodeValue);
    var a = document.createElement('a');
    //Non-IE Browsers (click is IE-specific)
    if( !a.click ) {
        location.href = url;
        return url;
    }
    //Workaround to make IE pass a referrer
    else {
        a.setAttribute('href', url);
        a.style.display = 'none';
        document.body.appendChild(a);
        a.click();
    }
}
