var IE = document.all?true:false;

var windowX = 0;
var windowY = 0;
var scrollY = 0;
var php = new PHP_Serializer();

		
var Window = Class.create();

Window.prototype = {
  
  	pageSize: {},
  	windowScroll: {},
  	initialize: function() {
  	  	this.eventOnLoad   = this.windowOnLoad.bindAsEventListener(this);
  	  	this.eventOnResize = this.windowOnResize.bindAsEventListener(this);
  	  	this.eventDocumentReady = this.windowOnReady.bindAsEventListener(this);

		Event.observe(window, 'load', this.eventOnLoad);
		Event.observe(window, 'resize', this.eventOnResize);
		Event.observe(window, 'scroll', this.eventOnResize);
	},

	windowOnLoad: function(){
	  	this.windowScroll = this.getWindowScroll();
		updateLayersPosition();		
	},
	
	windowOnResize: function(){
	  	this.windowScroll = this.getWindowScroll();
		updateLayersPosition();
	},
	
	windowOnReady: function(){
		alert('Ready');  
	},

	// From script.aculo.us
    getWindowScroll: function() {
        var w = window;
            var T, L, W, H;
            with (w.document) {
                if (w.document.documentElement) {
                    T = documentElement.scrollTop;
                    L = documentElement.scrollLeft;
                } else if (w.document.body) {
                    T = body.scrollTop;
                    L = body.scrollLeft;
                }
                if (w.innerWidth) {
                    W = w.innerWidth;
                    H = w.innerHeight;
                } else if (w.document.documentElement && documentElement.clientWidth) {
                    W = documentElement.clientWidth;
                    H = documentElement.clientHeight;
                } else {
                    W = body.offsetWidth;
                    H = body.offsetHeight
                }
            }
            return { top: T, left: L, width: W, height: H };
        
    }

}

var Win = new Window;


Event.onDOMReady(function() {
  	Win.eventOnLoad();
  	changeInputClasses();
  	buildMultiLevelMenu(["multiLevelMenuTree"]);
  	updateAds();
});

function updateLayersPosition(){
   	if($('siteNotification')){
   	  	elementSize = Element.getDimensions('siteNotification');
		$('siteNotification').style.top = Math.round(((Win.windowScroll['height']  - elementSize['height']) / 2) + Win.windowScroll['top']) + 'px';
  		$('siteNotification').style.left = Math.round(((Win.windowScroll['width'] - elementSize['width']) / 2) + Win.windowScroll['left']) + 'px';
  	}
   	if($('popup_ads')){
   	  	elementSize = Element.getDimensions('popup_ads');
		$('popup_ads').style.top = Math.round(((Win.windowScroll['height']  - elementSize['height']) / 2) + Win.windowScroll['top']) + 'px';
  		$('popup_ads').style.left = Math.round(((Win.windowScroll['width'] - elementSize['width']) / 2) + Win.windowScroll['left']) + 'px';
  	}
}

String.prototype.trim = function() { return this.replace(/^\s+|\s+$/, ''); };

function updateAds(){
	var myAjax = new Ajax.Request(
			"index.php", 
			{
				method: 'post', 
				parameters: 'act=ads&do=check&url='+document.location, 
				onComplete: function(ajaxReq){
					if(ajaxReq.responseText!=''){
					  	info = php.unserialize(ajaxReq.responseText.trim());
					  	$('popup_ads_title').innerHTML = info['name'];
					  	$('popup_ads_content').innerHTML = info['content'];
					  	updateLayersPosition();
					  	$('popup_ads').style.display = 'block';
					  	if(info['duration']!='') setTimeout(closeAds, info['duration']*1000);				  	
					}
				}
			});	
}

function closeAds(){
  	$('popup_ads').style.display = 'none';
}

function checkUncheckAll(form_id, checkbox_id) {
  
	var theCheckboxes = eval("document.forms." + form_id + "." + checkbox_id);

	if(theCheckboxes.length){
		for(i=0; i<theCheckboxes.length; i++) {	  	
			theCheckboxes[i].checked = (theCheckboxes[i].checked==false) ? true : false;
		}  
	}
	else{
	  	theCheckboxes.checked = (theCheckboxes.checked==false) ? true : false;
	}

}

function showError(error_mess){
	if(error_mess.indexOf('UL') == -1){
	  error_mess = "<UL><LI>" + error_mess + "</LI></UL>";
	}
	showNotification('e', error_mess, '');
	
}


function selectOptionInList(lstSelectList, intID )
{
    var intIndex = 0;
    // Loop through all the options
    for( intIndex = 0; intIndex < lstSelectList.options.length; intIndex++ )
    {
        // Is this the ID we are looking for?
        if( lstSelectList.options[intIndex].value == intID )
        {
            // Select it
            lstSelectList.selectedIndex = intIndex;
            // Yes, so stop searching
            break;
        }
    }

}
      
function setCookie(cName, cValue, cExpires, cPath, cDomain, cSecure) {
    document.cookie= cName + "=" + escape(cValue) +
        ((cExpires) ? "; expires=" + cExpires.toGMTString() : "") +
        ((cPath) ? "; path=" + cPath : "") +
        ((cDomain) ? "; domain=" + cDomain : "") +
        ((cSecure) ? "; secure" : "");
}

function getCookie(cName) {
    var dc = document.cookie;
    var prefix = cName + "=";
    var begin = dc.indexOf("; " + prefix);
    if (begin == -1) {
        begin = dc.indexOf(prefix);
        if (begin != 0) return null;
    } else {
        begin += 2;
    }
    var end = document.cookie.indexOf(";", begin);
    if (end == -1) {
        end = dc.length;
    }
    return unescape(dc.substring(begin + prefix.length, end));
}

function deleteCookie(cName, cPath, cDomain) {
    if (getCookie(cName)) {
        document.cookie = cName + "=" +
            ((cPath) ? "; path=" + cPath : "") +
            ((cDomain) ? "; domain=" + cDomain : "") +
            "; expires=Thu, 01-Jan-70 00:00:01 GMT";
    }
}

var nHideTimeout;
var nCloseTimeout;
var opacityTimeout;

function showNotification(nType, nContent, cFunc2Do){
  	clearTimeout(nHideTimeout);
  	clearTimeout(nCloseTimeout);
	clearTimeout(opacityTimeout);
  	
	if(cFunc2Do=="") cFunc2Do = "doCloseNotification()";
    cFunc2Do = cFunc2Do.replace(/'/gmi, "\\'");

  	var nData = new Array();
  	nData['n'] = new Array();
  	nData['p'] = new Array();
  	nData['e'] = new Array();
  	nData['c'] = new Array();
  	nData['u'] = new Array();
  	nData['m'] = new Array();
  	
  	nData['n']['title'] = new Array("notification.gif", "notificationTitle", "Site Notification");
  	nData['n']['pre_content'] = "";
  	nData['n']['end_content'] = "";
  	nData['n']['buttons'] = new Array(new Array("OK", "doConfirmedProcess('" + cFunc2Do + "')"));
  	
  	nData['p']['title'] = new Array("notification.gif", "notificationTitle", "Processing...");
  	nData['p']['pre_content'] = "";
  	nData['p']['end_content'] = "";
  	nData['p']['buttons'] = new Array();
  	
	nData['e']['title'] = new Array("error.gif", "notificationTitleError", "ERROR!");
	nData['e']['pre_content'] = "There is some errors ocurred while processing your request, please correct them before continuing:<div class=\"errorMess\">";
	nData['e']['end_content'] = "</div>";
	nData['e']['buttons'] = new Array(new Array("OK", "doConfirmedProcess('" + cFunc2Do + "')"));
	
	nData['c']['title'] = new Array("warning.gif", "notificationTitleWarning", "Warning!");
	nData['c']['pre_content'] = "";
	nData['c']['end_content'] = "";
	nData['c']['buttons'] = new Array(new Array("OK", "doConfirmedProcess('" + cFunc2Do + "')"), new Array("Cancel", "doCloseNotification()"));

	nData['m']['title'] = new Array("massAction.gif", "notificationMass", "With Selected:");
	nData['m']['pre_content'] = "";
	nData['m']['end_content'] = "";
	nData['m']['buttons'] = "";
	
	if(nData[nType]){
	  
	  	nTitleInfo = nData[nType]['title'];
	  		
	  	$('nTitle').className = nTitleInfo[1];

	  	$('nTitle').innerHTML = "<img src=\"img/" + nTitleInfo[0] + "\" style=\"vertical-align:middle\">&nbsp;&nbsp;" + nTitleInfo[2];
	  	
	  	$('nContent').innerHTML = nData[nType]['pre_content'] + nContent + nData[nType]['end_content'];
	  
	  	$('nButtons').innerHTML = "";

	  	for(i=0; i<nData[nType]['buttons'].length; i++){
	  	  
				$('nButtons').innerHTML	+= "<input id=\"notificationButton["+i+"]\" type=\"button\" value=\"  "+nData[nType]['buttons'][i][0]+"  \" class=\"button\" onclick=\""+nData[nType]['buttons'][i][1]+"\">&nbsp;&nbsp;&nbsp;";
		    
		}	
		
		$('siteNotification').style.display = 'block';
		opacity('siteNotification', 0, 100, 0);
		
		Event.observe($('notificationCloseImg'), "click", doCloseNotification);
		
		updateLayersPosition();
	}
	
}

function doCloseNotification(){
  	
  	clearTimeout(nHideTimeout);
  	opacity('siteNotification', 100, 0, 400);
  	nHideTimeout = setTimeout(hideNotification, 200);
}
function hideNotification(){
  	$('siteNotification').style.display = 'none';
}

function doConfirmedProcess(func2Do){		 
	nCloseTimeout = setTimeout(doCloseNotification, 0);
	eval(func2Do); 	
}

function opacity(id, opacStart, opacEnd, millisec) { 
    //speed for each frame 
    var speed = Math.round(millisec / 100); 
    var timer = 0; 
    clearTimeout(opacityTimeout);
	if(millisec==0) changeOpac(opacEnd, id);
	else{
	    //determine the direction for the blending, if start and end are the same nothing happens 
	    if(opacStart > opacEnd) { 
	        for(i = opacStart; i >= opacEnd; i=i-4) { 
	            opacityTimeout = setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed)); 
	            timer++; 
	        } 
	    } else if(opacStart < opacEnd) { 
	        for(i = opacStart; i <= opacEnd; i=i+4) 
	            { 
	            opacityTimeout = setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed)); 
	            timer++; 
	        } 
	    } 	  
	}

} 

//change the opacity for different browsers 
function changeOpac(opacity, id) { 
    var object = $(id).style; 
    object.opacity = (opacity / 100); 
    object.MozOpacity = (opacity / 100); 
    object.KhtmlOpacity = (opacity / 100); 
    object.filter = "alpha(opacity=" + opacity + ")"; 
} 

function doDeleteConfirm(cContent, cUrl){
  	showNotification("c", cContent, "documentGo('"+cUrl+"')");
}


function changeInputClasses()
{
	var els = document.getElementsByTagName('input');
	var elsLen = els.length;
	var i = 0;
		for ( i=0;i<elsLen;i++ )
		{
			if ( els[i].getAttribute('type') )
			{
				if ( els[i].getAttribute('type') != "") els[i].className += ' ' + els[i].getAttribute('type');
				
			}
		}
}

function sprintf(){
	if (!arguments || arguments.length < 1 || !RegExp)
	{
	  	return;
	}
	var str = arguments[0];
	var re = /([^%]*)%('.|0|\x20)?(-)?(\d+)?(\.\d+)?(%|b|c|d|u|f|o|s|x|X)(.*)/;
	var a = b = [], numSubstitutions = 0, numMatches = 0;
	while (a = re.exec(str))
	{
		var leftpart = a[1], pPad = a[2], pJustify = a[3], pMinLength = a[4];
		var pPrecision = a[5], pType = a[6], rightPart = a[7];
		
		//alert(a + '\n' + [a[0], leftpart, pPad, pJustify, pMinLength, pPrecision);
	
		numMatches++;
		if (pType == '%')
		{
			subst = '%';
		}
		else
		{
			numSubstitutions++;
			if (numSubstitutions >= arguments.length)
			{
	alert('Error! Not enough function arguments (' + (arguments.length - 1) + ', excluding the string)\nfor the number of substitution parameters in string (' + numSubstitutions + ' so far).');
			}
			var param = arguments[numSubstitutions];
			var pad = '';
			       if (pPad && pPad.substr(0,1) == "'") pad = leftpart.substr(1,1);
			  else if (pPad) pad = pPad;
			var justifyRight = true;
			       if (pJustify && pJustify === "-") justifyRight = false;
			var minLength = -1;
			       if (pMinLength) minLength = parseInt(pMinLength);
			var precision = -1;
			       if (pPrecision && pType == 'f') precision = parseInt(pPrecision.substring(1));
			var subst = param;
			       if (pType == 'b') subst = parseInt(param).toString(2);
			  else if (pType == 'c') subst = String.fromCharCode(parseInt(param));
			  else if (pType == 'd') subst = parseInt(param) ? parseInt(param) : 0;
			  else if (pType == 'u') subst = Math.abs(param);
			  else if (pType == 'f') subst = (precision > -1) ? Math.round(parseFloat(param) * Math.pow(10, precision)) / Math.pow(10, precision): parseFloat(param);
			  else if (pType == 'o') subst = parseInt(param).toString(8);
			  else if (pType == 's') subst = param;
			  else if (pType == 'x') subst = ('' + parseInt(param).toString(16)).toLowerCase();
			  else if (pType == 'X') subst = ('' + parseInt(param).toString(16)).toUpperCase();
		}
		str = leftpart + subst + rightPart;
	}
return str;
}

function formError(eText, field){
  	showError(eText); 
	formVal.highlight(field, true);
	Element.scrollTo(field);
}

function documentGo(url){
	document.location = _base_url+url;
}

function massPrompt(theForm, html){
  	act = "document.forms['"+theForm+"'].submit();";
  	showNotification('m', html, act);
}

function countCheckBoxes(elem){
  	if(elem.length) {
	  	for(j = cnt = 0; j < elem.length; j++) {
		    if(elem[j].checked) cnt++;
		}
	}
	else cnt = elem.checked ? 1 : 0;
	
	return cnt;
}

function loginRequired(){
  	showError("You have to login before downloading our article. If you don't have a member account, please <a href='?act=users&do=signup'>click here</a> to sign up");
}

function buildMultiLevelMenu(menuids){	
	for (var i=0; i<menuids.length; i++){
		
		if($(menuids[i])){
			var ultags=$(menuids[i]).getElementsByTagName("ul");
		    
			for (var t=0; t<ultags.length; t++){
		    	ultags[t].parentNode.getElementsByTagName("a")[0].className="subfolderstyle";
		    	ultags[t].parentNode.getElementsByTagName("a")[0].getAttributeNode('href').value = "javascript:void(0);";
		    	
				if (ultags[t].parentNode.parentNode.id==menuids[i]) ultags[t].style.left=ultags[t].parentNode.offsetWidth+"px";
				else ultags[t].style.left=ultags[t-1].getElementsByTagName("a")[0].offsetWidth+"px";
		
			    ultags[t].parentNode.onmouseover=function(){
			    	this.getElementsByTagName("ul")[0].style.display="block";
			    }
			    ultags[t].parentNode.onmouseout=function(){
			    	this.getElementsByTagName("ul")[0].style.display="none";
			    }
		    }
		    
			for (var t=ultags.length-1; t>-1; t--){ 
			  //loop through all sub menus again, and use "display:none" to hide menus (to prevent possible page scrollbars
				ultags[t].style.visibility="visible";
				ultags[t].style.display="none";
			}		  
		}
		
	}
}

function blinkingText(element){
 	setInterval(function(){Element.toggle(element)}, 700); 	
}

function shoppingCart(pid, ptype){
  	showNotification('n', 'Processing...Please wait...<div><img src="img/updating.gif" /></div>', '');
  	var actionName;
  	var typeName;

  	if(pid > 0) actionName="addtocart";
  	else if(pid < 0){
		actionName="removefromcart";
		pid = -pid;  
	}else{
	  	actionName="clearcart";
	}
  	
  	var myAjax = new Ajax.Request(
			"index.php", 
			{
				method: 'post', 
				parameters: 'act=products&do='+actionName+'&type='+ptype+'&id='+pid, 
				onComplete: function(ajaxReq){
					total = ajaxReq.responseText;
					if(total!=""){
					  	$('shopping-cart-num-item').innerHTML = total;
					  	if(total=='0') showNotification('n', 'Your <a href="?act=products&do=cart">Shopping Cart</a> is empty.', '');
					  	else{
						    if(actionName=="addtocart") showNotification('n', 'This '+ptype+' has been added to your <a href="?act=products&do=cart">Shopping Cart</a>.', '');
						    else if(actionName=="removefromcart") showNotification('n', 'This '+ptype+' has been removed from your <a href="?act=products&do=cart">Shopping Cart</a>.', '');
						}
					}else{
					  	if(actionName=="addtocart") showError('This '+ptype+' has already existed in your <a href="?act=products&do=cart">Shopping Cart</a>');
					}
					
					if($('shopping-cart-num-item').innerHTML > 0){					  	
					  	Element.show($('checkout'));
					}else Element.hide($('checkout'));
				}
			});	
}
