//Basic Ajax Routine- Author: Dynamic Drive (http://www.dynamicdrive.com)
//Last updated: Jan 15th, 06'

function createAjaxObj() {
	var httprequest=false
	if (window.XMLHttpRequest) { // if Mozilla, Safari etc
		httprequest=new XMLHttpRequest()
		if (httprequest.overrideMimeType)
			httprequest.overrideMimeType('text/xml')
	} else if (window.ActiveXObject) { // if IE
		try {
			httprequest=new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				httprequest=new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {
			}
		}
	}
	return httprequest
}

var ajaxpack=new Object()
//ajaxpack.basedomain="http://"+window.location.hostname
//19 May 2010 15:06:03 - Cipri: use this as it is using for sure an ending '/' !
ajaxpack.basedomain=_QBOX_WEB_ROOT
if(!ajaxpack.basedomain == ''){
    ajaxpack.basedomain="http://"+window.location.hostname

    //19 May 2010 15:09:33 - Cipri: test for ending '/'
    var chk_slash = new RegExp('/\/$');
    if(!chk_slash.test(ajaxpack.basedomain)){
        ajaxpack.basedomain += '/';
    }
}

ajaxpack.ajaxobj=createAjaxObj()
ajaxpack.filetype="txt"
ajaxpack.addrandomnumber=0 //Set to 1 or 0. See documentation.
ajaxpack.returndiv = '';



ajaxpack.getAjaxRequest = function(url, parameters, callbackfunc, filetype) {
	ajaxpack.ajaxobj=createAjaxObj() //recreate ajax object to defeat cache problem in IE
	if (ajaxpack.addrandomnumber==1) //Further defeat caching problem in IE?
		var parameters=parameters+"&ajaxcachebust="+new Date().getTime()
	if (this.ajaxobj) {
		this.filetype=filetype
		this.ajaxobj.onreadystatechange=callbackfunc
		this.ajaxobj.open('GET', url+"?"+parameters, true)
		this.ajaxobj.send(null)
	}
}

ajaxpack.postAjaxRequest = function(url, parameters, callbackfunc, filetype) {
	ajaxpack.ajaxobj=createAjaxObj() //recreate ajax object to defeat cache problem in IE
	if (this.ajaxobj) {
		this.filetype=filetype
		this.ajaxobj.onreadystatechange = callbackfunc;
		this.ajaxobj.open('POST', url, true);
		this.ajaxobj.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		this.ajaxobj.setRequestHeader("Content-length", parameters.length);
		this.ajaxobj.setRequestHeader("Connection", "close");
		this.ajaxobj.send(parameters);
	}
}

//02 Apr 2010 15:24:18 - Cipri: add this function to have a operation confirmationnn feedback as well
//the DIV that contain my response opperation message is named: result_msg_div (we chould parametrized this in future)
function ajaxConfirmationCallback() {
    var myajax=ajaxpack.ajaxobj;
    var destination_div=ajaxpack.filetype;
    if (myajax.readyState == 4) { //if request of file completed
        if (myajax.status==200 || window.location.href.indexOf("http")==-1) {
            if (myajax.responseText=="") {

            } else {
                var myObjResp = eval('(' + myajax.responseText + ')');

                var op_res      = myObjResp.op_result;
                var op_res_msg  = myObjResp.op_result_msg;
                var resp_txt    = myObjResp.op_response;

                //used for filtering
                allposkeys      = myObjResp.op_allposkeys;
                akarr = allposkeys.split("|");
                //alert(allposkeys);

                if(op_res == '1'){
                    document.getElementById('result_msg_div').innerHTML = '<font color="blue">'+op_res_msg+'</font>';
                }
                else{
                    document.getElementById('result_msg_div').innerHTML = '<font color="red">'+op_res_msg+'</font>';
                }

                document.getElementById(destination_div).innerHTML = resp_txt;
            }
        } else {
            document.getElementById('result_msg_div').innerHTML = '<font color="red">There was a problem retrieving data!</font>';
            document.getElementById(__divContent).innerHTML = resp_txt;
        }
        ajaxrunning = false;
    }
}


// ================= Emil code =================================
function ajaxCallback() {
	var myajax=ajaxpack.ajaxobj;
	var myfiletype=ajaxpack.filetype;
	if (myajax.readyState == 4) { //if request of file completed
		if (myajax.status==200 || window.location.href.indexOf("http")==-1) {
			if (myajax.responseText=="") {

			} else {
				var ind = myajax.responseText.indexOf( "+@+" );
				if (ind >= 0) {
					var jscode = myajax.responseText.substr(0, ind);
					var jsrest = myajax.responseText.substring(ind+3, myajax.responseText.length);
					document.getElementById(__divContent).innerHTML = jsrest;
                    eval(jscode);
				} else {
					// no javascript included in response
					document.getElementById(__divContent).innerHTML = myajax.responseText;
				}
			}
		} else {
			document.getElementById(__divContent).innerHTML = "There was a problem retrieving data:<br>"+ myajax.responseText;
			//alert("There was a problem with the AJAX call...");
		}
		ajaxrunning = false;
		runNextFromQueue();
	}
}

ajaxpack.targetQueue = new Array();
ajaxpack.urlQueue = new Array();
ajaxpack.paramQueue = new Array();
ajaxpack.filetypeQueue = new Array();
ajaxpack.loadingmsgQueue = new Array();
var ajaxrunning = false;
var __divContent="";

ajaxpack.queuePostAjaxRequest = function(url, parameters, filetype, targetDiv, loadingMsg) {
	ajaxpack.targetQueue.push(targetDiv);
	ajaxpack.urlQueue.push(url);
	ajaxpack.paramQueue.push(parameters);
	ajaxpack.filetypeQueue.push(filetype);
	ajaxpack.loadingmsgQueue.push(loadingMsg);
	if (!ajaxrunning)
		runNextFromQueue();
}
function runNextFromQueue() {
	if (ajaxrunning)
		return;
	if (ajaxpack.urlQueue.length <= 0)
		return;
	var thisTarget = ajaxpack.targetQueue.shift();
	var thisUrl = ajaxpack.urlQueue.shift();
	var thisParams = ajaxpack.paramQueue.shift();
	var thisFiletype = ajaxpack.filetypeQueue.shift();
	var thisLoadMsg = ajaxpack.loadingmsgQueue.shift();
	__divContent = thisTarget;
	ajaxpack.addrandomnumber=1;
	var destdiv = document.getElementById(__divContent);
	if (thisLoadMsg != null) {
		if (thisLoadMsg != "none")
			destdiv.innerHTML = thisLoadMsg;
	} else {
		destdiv.innerHTML = "<img src='" + _QBOX_WEB_ROOT + "images/indicator.gif'>";
	}
	ajaxrunning = true;
	ajaxpack.postAjaxRequest(thisUrl, thisParams, ajaxCallback, thisFiletype);
}
// ================= Emil code =================================

//ACCESSIBLE VARIABLES (for use within your callback functions):
//1) ajaxpack.ajaxobj //points to the current ajax object
//2) ajaxpack.filetype //The expected file type of the external file ("txt" or "xml")
//3) ajaxpack.basedomain //The root domain executing this ajax script, taking into account the possible "www" prefix.
//4) ajaxpack.addrandomnumber //Set to 0 or 1. When set to 1, a random number will be added to the end of the query string of GET requests to bust file caching of the external file in IE. See docs for more info.

//ACCESSIBLE FUNCTIONS:
//1) ajaxpack.getAjaxRequest(url, parameters, callbackfunc, filetype)
//2) ajaxpack.postAjaxRequest(url, parameters, callbackfunc, filetype)

///////////END OF ROUTINE HERE////////////////////////


//////EXAMPLE USAGE ////////////////////////////////////////////
/* Comment begins here

//Define call back function to process returned data
function processGetPost(){
var myajax=ajaxpack.ajaxobj
var myfiletype=ajaxpack.filetype
if (myajax.readyState == 4){ //if request of file completed
if (myajax.status==200 || window.location.href.indexOf("http")==-1){ if request was successful or running script locally
if (myfiletype=="txt")
alert(myajax.responseText)
else
alert(myajax.responseXML)
}
}
}

/////1) GET Example- alert contents of any file (regular text or xml file):

ajaxpack.getAjaxRequest("example.php", "", processGetPost, "txt")
ajaxpack.getAjaxRequest("example.php", "name=George&age=27", processGetPost, "txt")
ajaxpack.getAjaxRequest("examplexml.php", "name=George&age=27", processGetPost, "xml")
ajaxpack.getAjaxRequest(ajaxpack.basedomain+"/mydir/mylist.txt", "", processGetPost, "txt")

/////2) Post Example- Post some data to a PHP script for processing, then alert posted data:

//Define function to construct the desired parameters and their values to post via Ajax
function getPostParameters(){
var namevalue=document.getElementById("namediv").innerHTML //get name value from a DIV
var agevalue=document.getElementById("myform").agefield.value //get age value from a form field
var poststr = "name=" + encodeURI(namevalue) + "&age=" + encodeURI(agevalue)
return poststr
}

var poststr=getPostParameters()

ajaxpack.postAjaxRequest("example.php", poststr, processGetPost, "txt")
ajaxpack.postAjaxRequest("examplexml.php", poststr, processGetPost, "xml")

Comment Ends here */