var serialObj = null;
var uServer = ['addRemove', 'addRemoveU', 'quickInfo', 'homeLogged', 'inbox', 'showMessage', 'find', 'listFavorites', 'listLabels', 'personalEvents', 'shareMain', 'share2', 'landing', 'favoritesTab', 'personalEventsTab', 'labelsTab', 'savedScheduleList','share'];
var aServer = ['unsavedScheduleList','addRemove', 'quickInfo', 'helpOnline', 'findMain', 'moreInfo', 'pQuickInfo', 'pMoreInfo', 'search', 'listResults', 'browseDepartments', 'filter', 'build', 'buildMain', 'savedPoss'];
var uaServer = ['addRemoveChained'];

var appServerPrefix, userServerPrefix;

if(window.location.hostname=="dev1.coursetopia.com" && getURLParam('cross')!="y")
{
  appServerPrefix="apps/";
  userServerPrefix="users/";
}
else
{
  appServerPrefix="http://app.coursetopia.com/apps/";
  userServerPrefix="users/";
}

function getURLParam(strParamName){
  var strReturn = "";
  var strHref = window.location.href;
  if ( strHref.indexOf("?") > -1 ){
    var strQueryString = strHref.substr(strHref.indexOf("?")).toLowerCase();
    var aQueryString = strQueryString.split("&");
    for ( var iParam = 0; iParam < aQueryString.length; iParam++ ){
      if (
aQueryString[iParam].indexOf(strParamName.toLowerCase() + "=") > -1 ){
        var aParam = aQueryString[iParam].split("=");
        strReturn = aParam[1];
        break;
      }
    }
  }
  return unescape(strReturn);
} 

//Initialize the server communication object depending on browser
var xmlHttp;
// Firefox, Opera 8.0+, Safari
try{xmlHttp=new XMLHttpRequest();}
catch (e) {
	// Internet Explorer
	try {xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");}
	catch (e) {
		try {xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");}
		catch (e) {alert("Your browser does not support AJAX!");}
	}
}
var xmlHttp2;
// Firefox, Opera 8.0+, Safari
/*
try{xmlHttp2=new XMLHttpRequest();}
catch (e) {
	// Internet Explorer
	try {xmlHttp2=new ActiveXObject("Msxml2.XMLHTTP");}
	catch (e) {
		try {xmlHttp2=new ActiveXObject("Microsoft.XMLHTTP");}
		catch (e) {alert("Your browser does not support AJAX!");}
	}
}
*/

xmlHttp2 = new flensed.flXHR({ autoUpdatePlayer:true, instanceId:"myproxy1", xmlResponseText:false});//, loadPolicyURL:"http://test.getify.com/policy.php" });


/** Queuing **/
var callArray = Array();
var responseArray = Array();
var queueIndex = 0;
//1 - Queue Ready; 2 - Queue Busy
var queueState = 1;

function simpleQueue(call, response) {
    callArray[queueIndex] = call;
	responseArray[queueIndex] = response;
	queueIndex++;
	if(queueState != 2) {
		runQueue();
	}
}

function runQueue() {
    if(queueState==2 || queueIndex > 0){
		if(queueState == 1) {
			queueState = 2;
			serverCall(callArray[0], responseArray[0]);
			for(i = 1; i < queueIndex; i++) {
				callArray[i - 1] = callArray[i];
				responseArray[i - 1] = responseArray[i];
			}
			queueIndex--;
			callArray[queueIndex] = null;
			responseArray[queueIndex] = null;
		}
		if(queueState == 2) { //have somebody look out for completetion.
			setTimeout("runQueue()", 50);
		}
	}
}

function serverCall(call, response) {
	if(serialObj == null && call.match("action=login")==null && call.match("action=checkEmail")==null && document.getElementById("initialSerialization") != null)
	    serialObj = document.getElementById("initialSerialization").innerHTML.parseJSON();
	
	var page = call.substring(0, call.indexOf('.'));
	var loc = page.lastIndexOf('/');
	if(loc != -1)
		page = page.substring(loc + 1);
	
	var u = arrayContains(uServer, page);
	var a = arrayContains(aServer, page);
	var ua = arrayContains(uaServer, page);
		
	if(ua) {
	    f = function() {
	        // store the result of the first call and then once the second call finishes, prepend it
	        // to the result
	        var lastChar = httpResult.charAt(httpResult.length - 1);
	        httpResult = httpResult.substring(0, httpResult.length - 1);
	        httpResultTemp = httpResult;

	        if(lastChar == "1") {
	            makeServerCall("S", call, function () {httpResult = httpResultTemp +httpResult; response(); queueState=1;});
	        } else {
	            response();
	            queueState = 1;
	        }	        
	    }
	    makeServerCall("U", call, f);
	} else if(u && a){		   // both servers simultaneously
	    makeServerCall("U", call, null);
	    makeServerCall("S", call, function () {response(); queueState=1;});
	} else if(u) {            // only user server
	    makeServerCall("U", call, function () {response(); queueState=1;});
	} else if(a) {            // only app server
	    makeServerCall("S", call, function () {response(); queueState=1;});
	}
}

//Make a call to the server communication object
function makeServerCall(server, call, response) {
	var ajax;
	if(server == "U") ajax = xmlHttp;
	else ajax = xmlHttp2;
	
	var thisCall = call;
	var params;
	
	if(call.indexOf('?') == -1) thisCall += "?";
	else thisCall += "&";
	thisCall += "server=" + server + "&random=" + Math.random();


	var callbackU =  function() {
        if(ajax.readyState==4) {
             if(ajax.getResponseHeader("Set-Cookie") != null && ajax.getResponseHeader("Set-Cookie").indexOf("FAIL=true") != -1){       
		        location.href = "";		          
             }
             else{ 	
                var resp = ajax.responseText;
                if(server == "U" && resp.substring(resp.length - 2) == "GO") {
                    var indx1 = resp.lastIndexOf('--SERIAL_TYPE--');
                    var indx2 = resp.lastIndexOf('--SERIAL--');
                    var type = resp.substring(indx1 + 15, indx2);
                    var serial = resp.substring(indx2 + 10, resp.length - 2);
                    
                    //alert(type + "+++" + serial);
                    
                    if(type == "personal") {
                        //alert(serial.parseJSON().id);
                        _serial_putPersonalEvent(serialObj, serial.parseJSON());
                    } else if(type == "filters") {
                        _serial_putFilters(serialObj, serial.parseJSON());
                    } else if(type == "filter") {
                        //alert(serial);
                        _serial_putFilter(serialObj, serial.parseJSON());
                    } else if(type == "schedule") {
                        _serial_putSchedule(serialObj, serial.parseJSON());
                    } else if(type == "user") {
                    	serialObj = serial.parseJSON();
                    }
               
                    resp = resp.substring(0, indx1);
                }
         		
         	//	alert('note: ' + response);
         	if(response != null)  { 
         	    httpResult = resp;
         	    response();
                }
             }
	    }
	}

	var appSuccess = function() {
	  if(ajax.readyState == 4) {	  
		if(response != null) {
	  		httpResult = ajax.responseText;
			response();
		}
	  }
	}

	var appFail = function(o) {}

	var callbackS = {
	  success:appSuccess,
	  failure:appFail,
	  xdr: true,
	  scope: this
	}	

	//ajax.open
	if(server == "U") {
		ajax.open("GET",userServerPrefix+thisCall,true);
		ajax.onreadystatechange = callbackU;
		ajax.send(null);
	}
	else {
	    ajax.open("POST",appServerPrefix+thisCall,true);
	    params = "userial=" + serialObj.toJSONString();


		
	    //Send the proper header information along with the request
        //ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        //ajax.setRequestHeader("Content-length", params.length);
        //ajax.setRequestHeader("Connection", "close");

	ajax.onreadystatechange = appSuccess;
	ajax.send(params);
	}
	
}

