
// SET MAGAZINE VARIABLES
//------------------------------
// turn on debug window feedback
// i will want to disable this in the live version 
var httpTesting = false;
// set my request object
var http = createRequestObject();
// variable to track if we are currently in a call
var inCall = false;
// queue for calls
var callToArray = new Array();
// queue for function to execute when call complete
var returnToArray = new Array();

// COPY AND PASTE FOLLOWING INTO BODY FOR DEBUGGING
/*
debug<br>
queueTest: <div id="queueTest"></div><br>
queueInCall: <div id="queueInCall"></div><br>
queueReadyState: <div id="queueReadyState"></div><br>
queueMsg: <div id="queueMsg"></div><br>
*/


// PRELOAD LOADER IMAGES
//------------------------------
if (document.images){
	preloader_img0 = new Image(40,40); 
	preloader_img0.src="quotes/images/loader0.gif";
	preloader_img1 = new Image(40,40); 
	preloader_img1.src="quotes/images/loader1.gif";
}


// CREATE REQUEST OBJECT
//------------------------------
function createRequestObject() {
  var reqObj;
  var browser = navigator.appName;
  if(browser == "Microsoft Internet Explorer"){
    reqObj = new ActiveXObject("Microsoft.XMLHTTP");
    isIE = true;
  }else{
    reqObj = new XMLHttpRequest();
  }
  return reqObj;
}


// SEND CALL
//------------------------------
// insert calls to the queue
function sendCall(whereTo, returnTo){
  // GET THE NEXT ARRAY ITEM AND REMOVE FROM THE ARRAY
  callToArray.push(whereTo);
  returnToArray.push(returnTo);
}


// WATCHER FUNCTION
//------------------------------
// called on intervals to set out queued calls based on inCall variable
function callQueue(){
  // IF WE HAVE A WAY OF MONITORING THE QUEUE, UPDATE IT
  if(httpTesting){
    calls = "";
    for(i=0;i<callToArray.length;i++){
      calls += callToArray[i] + "n";
    }
  	
  	document.getElementById("queueTest").innerHTML = calls;
    document.getElementById("queueInCall").innerHTML = inCall;
    document.getElementById("queueReadyState").innerHTML = http.readyState;
  
  }
  // CHECK THE QUEUE AND SEND THE NEXT CALL IN LINE
  if(!inCall && callToArray.length > 0){
    // DO WE HAVE ANYTHING IN THE QUEUE?
    if(callToArray.length > 0){
      // WE DO, SO GET THE FIRST ITEM IN THE CALL ARRAY AND REMOVE IT
      whereTo = callToArray.shift();
      returnTo = returnToArray.shift();
      // SEND THAT CALL
      doCall(whereTo, returnTo);
    }else{
      // UPDATE DEBUG QUEUE
      if(httpTesting){
      	document.getElementById("queueMsg").innerHTML = "no items in queue.";
      }
    }
  }else{
    // UPDATE DEBUG QUEUE
    if(httpTesting){
      if(inCall){
        document.getElementById("queueMsg").innerHTML = "currently in a call.";
      }else{
        document.getElementById("queueMsg").innerHTML = "no items in queue.";
      }
    }
  }
}


// DO CALL
//------------------------------
// If we are not currently in a call and have a pending request, the call URL is sent here
function doCall(whereTo, returnTo){
  inCall = true;
  http.open('get', whereTo);
  // DO WE HAVE A FUNCTION TO CALL ONCE CALL IS COMPLETED?
  if(returnTo.length > 0){
    eval("http.onreadystatechange = "+returnTo);
  }
  // SEND CALL
  http.send(null);
}


// CLEAR CALL
// This is a generic return function intended to just clear the inCall variable when we have a call type that we don t need/expect a response from:
//------------------------------
function clear_inCall(){
  if(http.readyState == 4){
    inCall = false;
  }
}


// START QUEUE ENGINE
//------------------------------
var queueWatcher = setInterval(callQueue, 100);


// SAMPLE REQUEST FUNCTION
//------------------------------
function sampleRequest(){
  username = document.getElementsByName("loginEmail")[0].value;
  password = document.getElementsByName("loginPassword")[0].value;
  document.getElementById("loginSubmit").innerHTML = "Checking Login...";
  sendCall("req/getLogin.php?username=" + username + "&password=" + password, "sampleResponse");
  // notice when sendCall has sampleResponse as the second parameter, which, once the call is complete, will be called.
}

// SAMPLE RESPONSE FUNCTION
//------------------------------
function sampleResponse(){
  if(http.readyState == 4){
    inCall = false;
    response = http.responseText
    if(response != "0"){
      document.getElementById("loginArea").innerHTML = "Login successful. Welcome back. <A href='projects.php'>Projects</a>";
    }else{
      document.getElementById("loginSubmit").innerHTML = "<font color='red'>Login Failed</font>";
    }
  }
}


//-----------------------------------------------------------------------------------------------------------------------------


// REPLACE CHARS
//------------------------------
function replaceChars(s) {

	s = s.replace(/&/g,"*am*");
	s = s.replace(/=/g,"*eq*");
	s = s.replace(/\+/g,"*pl*");
	
	return s;
}

function addToRecentlyViewed(symbol){

 		symbol = symbol.toUpperCase();
 		var limit = 20;
 		var ckx_txt = "";
 		var ck_out = "";
 		var ck_in = readCookie("th_recently_viewed");
 		
 		// if none exist
 		if(ck_in == null){
 			ck_out = symbol + ",";
 			ckx_txt = '<a href=\'javascript:sndReq("get_chart","' + symbol + '","")\' target="_self">' + symbol + "</a> &nbsp;";
 		}else{
 			
 			// create array
 			var cka = ck_in.split(",");
 			// check if we already don't have one
 			var haveit = -1;
 			for(i=0; i < cka.length; i++){
 				if(cka[i] == symbol){
 					haveit = i;
 					break;
 				}
 			}
 			
 			// if we don't have one
 			if(haveit == -1){
 				// add new one to the beginning of array
 				cka.unshift(symbol);
 			}else{
 				
 				// remove last
 				cka.splice(haveit,1); //index,howmany
 				
 				// add it to the front
 				cka.unshift(symbol);
 				
 				//alert(cka);
 			}
 			
    		// check limit
    		if(cka.length > limit){
    			// remove last
 				cka.splice(limit-1,1000);
    		}
 			
 			for(i=0; i < cka.length; i++){
 				
    			ckx_txt += '<a href=\'javascript:sndReq("get_chart","' + cka[i] + '","")\' target="_self">' + cka[i] + "</a> &nbsp;";
    		} 
    		
    		
    		// prepare string for cookie
    		ck_out = cka.join(",");
    		
 		}
	
		
 		parent.document.getElementById("recently_viewed").innerHTML = "Recent Quotes: " + ckx_txt;
 		createCookie("th_recently_viewed",ck_out,"30");

}
function showRecentlyViewed(){
		
		var ckx_txt = "";
 		var ck_in = readCookie("th_recently_viewed");
 		
 		//alert("ck_in" + " - " + ck_in);
 		
 		if(ck_in != null){
 		
			// create array
 			var cka = ck_in.split(",");
 			for(i=0;i<cka.length;i++){
    			ckx_txt += '<a href=\'javascript:sndReq("get_chart","' + cka[i].toUpperCase() + '","")\' target="_self">' + cka[i].toUpperCase() + "</a> &nbsp;";
    		}  		
 		
 		document.getElementById("recently_viewed").innerHTML = "Recent Quotes: " + ckx_txt;
 		}
}


// IMAGE LOADED
//------------------------------
// called when called image will be fully loaded
// must add onload="imageLoaded()" to requested image
function imageLoaded(what,arg1,arg2) {

 	if(what == "chart"){
 		//alert("hi there:" + arg1);
 		//sendCall('includes/rpc.php?action=' + 'get_data' + '&arg1=' + arg1 + '&arg2=' + arg2, "handleResponse");
 		
 		document.getElementById("loader").innerHTML = "";
 		addToRecentlyViewed(arg1);


		// put call for data here
		//alert("image loaded");
		sndReq("get_data",arg1,arg2);

 	}
 
 
	//alert("image loaded");
	//document.images.loader.src = preloader_img0.src;

}

// SEND REQUEST
//------------------------------
function sndReq(action,arg1,arg2) {

	// this is here becuse of Safari :80 problem
	var domain = "http://" + window.location.toString().split("//")[1].split("/")[0] + "/";
	
	// if there is some quote symbol in q text field, set it as arg1 and clear the field
	if(!arg1){	
		arg1 = document.q_form.q.value;
		document.q_form.q.value = "";
	}

//alert(action +":"+ arg1 +":"+ arg2);
	
	// clear previous data
	//document.getElementById("get_data").innerHTML = "";
	
	
	// hide chartline
	//document.getElementById("chartline").style.visibility = "hidden";

	// replace &,=,+ characters because http wont accept them
	if(arg2){
		arg2 = replaceChars(arg2);
	}

	
	if(action == 'get_chart'){
		
		//hide joomla template center and right sections
		//document.getElementById("content_outer").innerHTML = ""; //(commented out as it didn't work in firefox)
		
		// action,symbol,label   
    	sendCall(domain + 'quotes/includes/rpc.php?action=' + action + '&arg1=' + arg1 + '&arg2=' + arg2, "handleResponse");

	}
	
	if(action == 'get_data'){
		
		// action,symbol,label   
    	sendCall('./rpc.php?action=' + action + '&arg1=' + arg1 + '&arg2=' + arg2, "handleResponse");
	}
	
		if(action == 'get_indexes'){
		//alert(location.href);
		//alert(window.location);
		
		
		//alert(domain);
		
		// action 
    	//sendCall('quotes/includes/rpc.php?action=' + action, "handleResponse");
		sendCall(domain + 'quotes/includes/rpc.php?action=' + action, "handleResponse");
	}
	
	
}




// HANDLE RESPONSE
//------------------------------
function handleResponse() {
    if(http.readyState == 4){
    	inCall = false;
        var response = http.responseText;
        
        //alert("response:" + response);
        
        var update = new Array();

        if(response.indexOf('|' != -1)) {
            update = response.split('|');
            
            
            document.getElementById(update[0]).innerHTML = update[1];
            //document.images.loader.src = pic0.src;
            
            
            // populate hot spots oon image map
            if(update[0] == 'data_area'){
            
            	var hotspots = new Array();
            	hotspots = update[2].split(':');
            	
            	
            	
            	//document.getElementById("hotSpot0").innerHTML = "<a href='#'><span>Date: yeehaa</span></a>";
            
            	    for(i=0;i<hotspots.length;i++){
            	    
            	    //alert("data:" + hotspots[i]);
            	    
      					//calls += hotspots[i] + "n";
      					//document.getElementById("hotSpot"+i).innerHTML = "<a href='#'><span>Date: yeehaa</span></a>";
      					//document.getElementById("hotSpot"+i).innerHTML = "<a href='#'><span>"+ hotspots[i] +"<span></a>";
    				
    					document.getElementById("hotSpotSpan"+i).innerHTML =  hotspots[i];
    				}
            
            }
        }
    }
}

//------------------------------
// COOKIES
//------------------------------
function createCookie(name,value,days) {
        if (days) {
                var date = new Date();
                date.setTime(date.getTime()+(days*24*60*60*1000));
                var expires = "; expires="+date.toGMTString();
        }
        else var expires = "";
        document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {

		//alert("heeey");

        var nameEQ = name + "=";
        var ca = document.cookie.split(';');
        for(var i=0;i < ca.length;i++) {
                var c = ca[i];
                while (c.charAt(0)==' ') c = c.substring(1,c.length);
                if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
        }
        return null;
}

function eraseCookie(name) {
        createCookie(name,"",-1);
}

function initQuickChart(){
	
//	alert("init");
	showRecentlyViewed();
	//sendCall('includes/tabs/market_tab.php', "handleResponse");
	
	sndReq("get_indexes");
}





/*
onmousedown=function(e){
  //  N4.captureEvents(Event.MOUSEMOVE);
  //  N4x=e.x;
  //  N4y=e.y;
}


document.onmousedown=blah;

function blah(){

	alert("blah");
}
*/
