/**
    @fileoverview
    In general, the tools in this file wrap an instance
    of XMLHttpRequest object and provide utility methods for gather data from
    form elements to be sent to the server as par of an Ajax request.
 */

var ELEMENT_NODE_TYPE = 1;
var	CDATA_SECTION_NODE_TYPE = 4;
var statstr = "";
var statswitch = false;
var statAutoSaveFunctionName = "statAutoSave";
var statAutoSaveEnabled = false; // must set to true somwhere, if enabled
var statAutoSaveID = null;
var statAutoSaveInterval = 480000; // 8 min

function handleStateChange(ajaxRequest, postRequest ) {
    var ro = ajaxRequest.getXMLHttpRequestObject();
    if(ro.readyState == 4 && ro.status == 200) {
        ajaxRequest.setHtmlResponse("");
        ajaxRequest.setScriptResponse("");
        if(ro.responseXML && ro.responseXML.documentElement) {
            var nodes = ro.responseXML.documentElement.childNodes;
            for(var i = 0; i < nodes.length; i++) {
                var element1 = nodes[i];
                if(element1.nodeType != ELEMENT_NODE_TYPE) {
                    continue;
                }
                var tagName = element1.tagName.toLowerCase();
                var polymetaHtmlType = (tagName=="polymeta-html");
                var polymetaScriptType = (tagName=="polymeta-script");
                if(polymetaHtmlType || polymetaScriptType){
                    for(var y = 0; y < element1.childNodes.length; y++) {
                        var element2 = element1.childNodes[y];
                        if(element2.nodeType==CDATA_SECTION_NODE_TYPE) {
                            if(polymetaHtmlType) {
                                ajaxRequest.setHtmlResponse(ajaxRequest.getHtmlResponse() + element2.data );
                            } else if (polymetaScriptType) {
                                ajaxRequest.setScriptResponse(ajaxRequest.getScriptResponse() + element2.data );
                            }
                        }
                    }
                }
            }
        } else {
            ajaxRequest.setHtmlResponse( ro.responseText );                    
        }
        postRequest(ajaxRequest);   
    }
}


function AjaxRequest(url, postRequestFunction) {

    /** @private */
    var self = this;

    /** @private */
    var xmlHttp = createXMLHttpRequest();

    /** @private */
    var queryString = "";

    /** @private */
    var requestURL = url;

    /** @private */
    var method = "POST";

	/** @private */
    var async = true;

    /** @private */
    var postRequest = postRequestFunction ? postRequestFunction : null;

    /** @private */
    var requestID = null;

    /** @private */
    var htmlResponse = null;

    /** @private */
    var scriptResponse = null;

    this.getXMLHttpRequestObject = function() {
        return xmlHttp;
    }

    this.getRequestID = function() {
        return requestID;
    }

    this.setRequestID = function(reqID) {
        requestID = reqID;
    }

    this.setPostRequest = function(func) {
        postRequest = func;
    }

    this.setUsePOST = function() {
        method = "POST";
    }

    this.setUseGET = function() {
        method = "GET";
    }

    this.getHtmlResponse = function() {
        return htmlResponse;
    }

    this.getScriptResponse = function() {
        return scriptResponse;
    }

    this.setHtmlResponse = function(newval) {
        htmlResponse = newval;
    }

    this.setScriptResponse = function(newval) {
        scriptResponse = newval;
    }

    this.addFormElements = function(formID) {
        var formElements = document.getElementById(formID).elements;
        var values = toQueryString(formElements);
        accumulateQueryString(values);
    }

    this.addFormElements_FormObj = function(formObj) {
        var formElements = formObj.elements;
        var values = toQueryString(formElements);
        accumulateQueryString(values);
    }

	this.getASync = function() {
        return async;
    }

    this.setASync = function(a) {
        async = a;
    }

    /** @private */
    function accumulateQueryString(newValues) {
        if(queryString == "") {
            queryString = newValues; 
        }
        else {
            queryString = this.queryString + "&" +  newValues;
        }
    }

    this.addNamedFormElements = function() {
        var elementName = "";
        var namedElements = null;

        for(var i = 0; i < arguments.length; i++) {
            elementName = arguments[i];
            namedElements = document.getElementsByName(elementName);

            elementValues = toQueryString(namedElements);

            accumulateQueryString(elementValues);
        }

    }

    this.addFormElementsById = function() {
        var id = "";
        var element = null;
        var elements = new Array();

        for(var h = 0; h < arguments.length; h++) {
            element = document.getElementById(arguments[h]);
            if(element != null) {
                elements[h] = element;
            }
        }

        elementValues = toQueryString(elements);
        accumulateQueryString(elementValues);
    }

    /**  Send the Ajax request.  */
    this.sendRequest = function() {
        var st = statstr;
        statstr = "";
        xmlHttp.onreadystatechange = function () { handleStateChange(self, postRequest) };
        requestURL = requestURL + (requestURL.indexOf("?")>=0 ? "&" : "?") + "ts=" + new Date().getTime() + (st!="" ? ("&stat="+st) : "");/* + (ssid ? "&ssid=" + ssid : "");*/
		if (statAutoSaveID != null) {
			clearTimeout(statAutoSaveID);
		}
		if (statAutoSaveEnabled) {
			statAutoSaveID = setTimeout(statAutoSaveFunctionName + "();", statAutoSaveInterval);
		}
		
        if(method == "GET") {
            requestURL = requestURL + "&" + queryString;
            xmlHttp.open(method, requestURL, async);
            xmlHttp.send(null);
        } else {
            xmlHttp.open(method, requestURL, async);
            xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); 
            xmlHttp.send(queryString);
        }
    }

    /** @private */
    function toQueryString(elements) {
        var qs = "";
        for(var i = 0; i < elements.length; i++) {
            var tempString = "";
            var node = elements[i];
            var name = node.getAttribute("name");
            var tagName = node.tagName.toLowerCase();
            if(tagName == "input") {
                var nt = node.type.toLowerCase();
                if( nt=="radio" || nt=="checkbox") {
                    if(node.checked) {
                        tempString = name + "=" + node.value;
                    }
                }
                if(nt == "text" || nt == "hidden") {
                    tempString = name + "=" + encodeURIComponent(node.value);
                }
            }
            else if(tagName == "select") {
                tempString = getSelectedOptions(node);
            }
            else if(tagName == "textarea") {
                tempString = name + "=" + encodeURIComponent(node.value);
            }

            if(tempString != "") {
                if(qs == "") {
                    qs = tempString;
                }
                else {
                    qs = qs + "&" + tempString;
                }
            }
        }
        return qs;
    }

    /** @private */
    function getSelectedOptions(select) {
        var options = select.options;
        var option = null;
        var qs = "";
        var tempString = "";

        for(var x = 0; x < options.length; x++) {
            tempString = "";
            option = options[x];

            if(option.selected) {
                tempString = select.name + "=" + option.value;
            }

            if(tempString != "") {
                if(qs == "") {
                    qs = tempString;
                }
                else {
                    qs = qs + "&" + tempString;
                }
            }
        }
        return qs;
    }

}


function createXMLHttpRequest() {
    if (window.ActiveXObject) {
        return new ActiveXObject("Microsoft.XMLHTTP");
    }
    else if (window.XMLHttpRequest) {
        return new XMLHttpRequest();
    }
}

function addStat(instr) {
    if(statswitch) statstr += (statstr!='' ? "|" : "" ) + instr;
}

function sStrip(instr) {
    instr = instr.replace(/!/g, " ");
    instr = instr.replace(/\|/g, " ");
    return instr;
}

function reloadIfBackButton() {
    var f_obj = document.getElementById("historyStorageForm");
    if(f_obj) {
        if (f_obj.historyStorageField.value == "") {
            f_obj.historyStorageField.value = "true";
        } else {
            loc = location.href;
            if( loc.indexOf("#") == (loc.length-1) ) {
                location.href = loc.substring(0,loc.length-1);
            } else {
                location.href = loc;
            }		
        }
    }
}

function boldQueryInText(query, text){
    if (text == ""){
        return "";
    }else{
      var counter = 0;
      var newText = "";
      while (counter < text.length){
        var startHtmlTag = text.indexOf("<", counter);
        var endHtmlTag = text.indexOf(">", startHtmlTag);
        if (startHtmlTag > -1 && endHtmlTag > -1){
          if (startHtmlTag > counter){
              var startQuery = text.substring(counter,startHtmlTag).toLowerCase().indexOf(query.toString().toLowerCase());
              if (startQuery > -1){
                  //found query
                  newText += text.substring(counter, counter + startQuery) + "<strong>" + text.substring(counter + startQuery, counter + startQuery + query.length) + "</strong>" + text.substring(counter + startQuery + query.length);
                  return newText;
              }else{
                  newText += text.substring(counter, endHtmlTag);
                  counter = endHtmlTag;
              }
          }else{
              newText += text.substring(counter, endHtmlTag);
              counter = endHtmlTag;
          }
        }else{
          var startQuery2 = text.substring(counter).toLowerCase().indexOf(query.toString().toLowerCase());
          if (startQuery2 > -1){
              //found query
              newText += text.substring(counter, counter + startQuery) + "<strong>" + text.substring(counter + startQuery, counter + startQuery + query.length) + "</strong>" + text.substring(counter + startQuery + query.length);
              return newText;
          }else{
              newText += text.substring(counter);
              return newText;
          }
        }
      }
      return newText;
    }
}

