/** 
* Ajax callback function for when an error occurs.
**/
function xhrError(xhrReq) {
	var mssg = 'XHR Error - Code '+xhrReq.status+' ';
	switch (xhrReq.status) {
		case 301: mssg += 'Content Moved';	break;
		case 400: mssg += 'Bad Request';	break;
		case 401: mssg += 'Unauthorized';	break;
		case 403: mssg += 'Forbidden';		break;
		case 404: mssg += 'Not Found';		break;
		case 500: mssg += 'Internal Server Error';		break;
		case 503: mssg += 'Service Unavailable';		break;
		case 504: mssg += 'Gateway Timeout';			break;
		case 505: mssg += 'HTTP Version Not Supported';	break;
	}
	mssg += "\n\nPlease clear your browser's cache,\nreload the page and try your request again.";
	alert(mssg);
}

function PopupWindow(theURL,winName,features) {
	window.open(theURL,winName,features);
}

function bodyElement(){
	return (!window.opera && document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body;
}

function getCookie(name){
	if (document.cookie.length>0){
  		start=document.cookie.indexOf(name + "=")
  		if (start!=-1){ 
    		start=start + name.length+1;
    		end=document.cookie.indexOf(";",start);
    		if (end==-1) {
    			end=document.cookie.length;
    		}
    		return unescape(document.cookie.substring(start,end));
    	}
  	}
	return '';
}

function toggleCustomRadio(formEle, checkedEle) {
	var radios = formEle.elements[checkedEle.name];
	for(var i=0; i<radios.length; i++){
		radios[i].checked=(radios[i].id == checkedEle.id ? true:false);
		$(radios[i].id+"Label").className=(radios[i].checked? 'radioon' :'radiooff');
	}
}

function positionPopup(parentEle, popupEle, relativeLeft, relativeTop) {
	if(parentEle && popupEle) {
		// temporary unhide the parent element to get the offsets
		if(parentEle.style.display=='none') {
			parentEle.style.display='block';
			var pos=Position.cumulativeOffset(parentEle);
			parentEle.style.display='none';
		} else {
			var pos=Position.cumulativeOffset(parentEle);
		}
		var left=(pos[0]+relativeLeft)+"px";
		var top=(pos[1]+relativeTop)+"px";
		popupEle.style.left=left;
		popupEle.style.top=top;
		
		//console.log(parentEle.id+' - '+left+' x '+top);
		
		if($(popupEle.id+"IFrame")) {
			var iFrame=$(popupEle.id+"IFrame");
			iFrame.style.left=left;
			iFrame.style.top=top;
		}
	}
}

function buildPopupIFrame(popupEle, allBrowsers) {
	if( (navigator.appName=="Microsoft Internet Explorer" || allBrowsers) && popupEle && !$(popupEle.id+"IFrame")) {
		var iFrame = document.createElement("iframe");
		iFrame.id=popupEle.id+"IFrame";
		iFrame.src="blank.html";	
		iFrame.style.display="none";
		iFrame.style.position="absolute";
		iFrame.style.filter='progid:DXImageTransform.Microsoft.Alpha(style=0,opacity=0)';
		document.body.appendChild(iFrame);
	}
}

function togglePopup(popupEle, newState, zIndex) {
	if($(popupEle)) {		
		if(newState) {
			newState = (newState=="block"?"block":"none");
		}else {
			newState = (popupEle.style.display == "block" ? "none" : "block");
		}
		popupEle.style.display=newState;	
		
		var popupIFrame = $(popupEle.id+"IFrame");
		if(popupIFrame) {
			if(!popupIFrame.style.width) {
				Element.clonePosition(popupIFrame, popupEle);
				if (zIndex) popupEle.style.zIndex=zIndex;
				popupIFrame.style.zIndex=popupEle.style.zIndex-1;
			}
			popupIFrame.style.display=newState;
		}
	}
}

function fixSafariEncode(fixedString){
	try {
		fixedString = decodeURI(escape(fixedString));
	}
	catch(err){
		//the decode from utf8 failed
	}
	return fixedString;
}



// lazy loads the required control panel scripts
document.observe("dom:loaded", function() {	
	if($("ControlPanelToggle") && !$("controlPanelLocation1")) {
		$("ControlPanelToggle").observe("click", ControlPanel.lazyLoadControlPanel);
	}
});

var ControlPanel = {
	lazyLoadControlPanel: function() {
		// stop observing clicks to the control panel link
		$("ControlPanelToggle").stopObserving("click");
		LazyLoad.loadJS("/js/ajax_controlpanel.js", function() {
			ControlPanelAjax.init();
		}, "controlPanel:loaded");
    
        // if the adv search is open, close it
        if ($('SearchBarContainerAdvanced').visible()) {
            $('SearchBarContainerBasic').show();
            togglePopup($('SearchBarContainerAdvanced'), 'none');
            $('AdvancedSearchLoading').hide();
        }
	}
};

/**
 * user_view.php -> financial's tab -> changing default credit type
 */
function uv_updateCreditPlan(userID, updateCP) {
	if($("uv_defaultPlan")) {
		var newVal = $F("uv_defaultPlan");
		
		// as an admin, you might not want to change your own control panel setting
		if(updateCP && $("CONTROL_SETTING_DEFAULT_CREDIT_TYPE")) {
			$("CONTROL_SETTING_DEFAULT_CREDIT_TYPE").value = newVal;
		}
		
		// save the setting	
		var URL = "ajax_class_creator.php?ajax_action=save&ajax_class=controlpanel&setting=CONTROL_SETTING_DEFAULT_CREDIT_TYPE&value="+newVal+"&userID="+userID;
		var myAjax =new Ajax.Request(URL, {method: 'get'});
	}
}


function getRealOffsetLeft(element) {
	var offset = 0;
	do {
		offset += element['offsetLeft'];
		element = element.offsetParent;
	} while (element != document.body && element != null);
	return offset;
}

/**
 * Lazy loading for JS and CSS
 */
var LazyLoad = {

	/**
	 * loads a javascript file
	 *
	 * @param string urls  The script's url in string format
	 * @param object callback	The function to call once the script has finished loading
	 * @param string customEvt	The name of the custom event to observe when the event is fired.
	 */
	loadJS: function(url, callback, customEvt) {
		
		// converts a string into an array if not array in array format
		var url = url.replace(/[^a-zA-Z0-9.\-_\/]/g, "");
		if(!url) return;
		
		// no surprise, ie 6 is an exception
		if(navigator.userAgent.match(/MSIE 6.0/)) {
			var llIE = new LazyLoadIE6(url, callback);
			llIE.load();
		}
		else {
            // Zend framework homed scripts are prepended with /static/ - do not pass these through the jsCache.
            if (url.indexOf('/static/') === -1) {
                var script = new Element("script", { type: "text/javascript", src: istock.jsCacheURL + url });
            } else {
                // parse the cache serial# and extract the digits
                var jsPcs = istock.jsCacheURL.split('/');
                var cacheSerial = (jsPcs[2]) ? jsPcs[2] : 1234;
                url = url.replace('/js', '/' + cacheSerial + '/js');
                var script = new Element("script", { type: "text/javascript", src: url });
            }
		
			// if a call back is defined
			if(callback && customEvt) {
			    document.stopObserving(customEvt);//we have ensure that only one call back is registered at once, otherwise they stacking resulting in multiple calls
				document.observe(customEvt, callback);				
			}
			
			// appends the script to the body
			// this should be faster than appending it to the head
			document.body.appendChild(script);
		}
	},
	
	
	/**
	 * loads a css file
	 *
	 * @param string url  The css's url in string format
	 */
	loadCSS: function(url) {
		var url = url.replace(/[^a-zA-Z0-9.\-_\/]/g, "");
		if(!url) return;
		
		var head = $$("head")[0];
        // Zend framework homed scripts are prepended with /static/ - do not pass these through the cssCache.
        if (url.indexOf('/static/') === -1) {
            var css = new Element("link", {type: "text/css", rel: "stylesheet", href: istock.cssCacheURL + url});
        } else {
            // parse the cache serial# and extract the digits
            var jsPcs = istock.jsCacheURL.split('/');
            var cacheSerial = (jsPcs[2]) ? jsPcs[2] : 1234;
            url = url.replace('/css', '/' + cacheSerial + '/css');            
            var css = new Element("link", {type: "text/css", rel: "stylesheet", href: url});
        }
		head.appendChild(css);
	}
}

/**
 * lazy loading class for IE 6 only
 *
 */
var LazyLoadIE6 = Class.create();
LazyLoadIE6.prototype = {
	
	/**
	 * constructor
	 *
	 * @param string url  		The script's url
	 * @param object callback	The function to call once the script has finished loading
	 */
	initialize: function(url, callback) {
		// the max number of tries to load unsucessful script
		this.maxTries = 3;
	
		// currenty number of tries.
		this.numTries = 0;
		
		// the js url
		this.url = url.replace(/[^a-zA-Z0-9.\-_\/]/g, "");
		
		// the callback function
		this.callback = callback;
	},
	
	/**
	 * loads the js for IE6 only
	 *
	 * ie 6 will read from the cache, if it finds a similar copy of the js file, the ready state will say loaded even when it is not.
	 * therefore, we\'ll use the try-catch method to test if the callback function is ready. If not ready, reload the script to a max of 3 times
	 */
	load: function() {	
        // Zend framework homed scripts are prepended with /static/ - do not pass these through the jsCache.
        if (this.url.indexOf('/static/') === -1) {
            var script = new Element("script", { type: "text/javascript", src: istock.jsCacheURL + this.url });
        } else {
            // parse the cache serial# and extract the digits
            var jsPcs = istock.jsCacheURL.split('/');
            var cacheSerial = (jsPcs[2]) ? jsPcs[2] : 1234;
            this.url = this.url.replace('/js', '/' + cacheSerial + '/js');
            var script = new Element("script", { type: "text/javascript", src: this.url });
        }
		script.onreadystatechange = function() {
		
			if(script.readyState === "loaded" || script.readyState === "complete") {
				try {
					// try to call the callback function
					this.callback();
				} catch(e) { 
					if(this.maxTries <= this.numTries) {
						// too many tries.
						return;
					}
					this.numTries++;
					// load it again
					this.load();
				}
			}
		}.bind(this);
		
		// appends the script to the body
		// this should be faster than appending it to the head
		document.body.appendChild(script);
	}
}


/**
 * Logout over-ride
 * Security-Paul has requested that all logouts go through a CSRF-protected POSTed form
 * This script traps the click on the Logout button and triggers the submission of the logout 
 * form, whcih also happens to contain a security token
 *
 * @see htdocs/template/template_bottom.inc.php
 */
document.observe("dom:loaded", function() {
    if ($('logoutBtn')) {
        $('logoutBtn').observe('click', function(e) {
            e.stop();
            $('logoutForm').action = '/istock_logout.php';
            $('logoutForm').submit();
        });
    }
});
