/*var params = document.location.search;
var target = "";
var task = "";
params = params.substring(1);
var param_array = params.split("&");
for(i=0;i<param_array.length; i++){
	if (param_array[i].indexOf("target") != -1){
		target = param_array[i].split("=")[1];
	}
	if (param_array[i].indexOf("task") != -1){
		task = param_array[i].split("=")[1];
	}
}*/
var main_path;

if (location.host == "199.1.1.60"){
	main_path = location.protocol+"//"+location.host+"/slc/";
}else{
	main_path = location.protocol+"//"+location.host+"/";
}

var preLoadImg = [main_path+"images/info.gif", main_path+"images/exclaim.gif"];

preLoadImg.each(
	function(path){
		img = new Image();
		img.src= path;
	}
);

var url = 'includes/ajax.php';

function formObjToStr(tagName, form_name){
	fields = "";
	var obj = document.getElementsByTagName(tagName);
	for(i=0;i<obj.length;i++){
		if (obj[i].name == form_name){
			var frmObj = document.forms[form_name];
			for(j=0;j<frmObj.length; j++){
				amp = (j==0) ? "?" : "&";
				if (frmObj[j].type != "button"){
					if ((frmObj[j].type == "radio" || frmObj[j].type == "checkbox") && frmObj[j].checked==true){
						if (typeof frmObj[j].name != "undefined")
						fields += amp+frmObj[j].name+'='+escape(frmObj[j].value);	
					}else{
						if (typeof frmObj[j].name != "undefined")
						if (frmObj[j].type != "radio" && frmObj[j].type != "checkbox"){
							fields += amp+frmObj[j].name+'='+escape(frmObj[j].value);
						}
					}
				}
			}
		}
	}
	return fields;
}

function _load(param){
	var pars = param+'&hash='+Math.random();
	var head = document.getElementsByTagName("head")[0];
	
	var current_target = null;
	var tmp_target = null;
	var param_array = param.split("&");//target=user, 
	for(i=0;i<param_array.length; i++){
		if (param_array[i].indexOf("target") != -1){
			tmp_target = param_array[i].split("=")[1];
			break;
		}
	}
	
	var current_target = (tmp_target) ? tmp_target : "";

	if (!current_target){
		pars = pars.substring(1);
		pars_array = pars.split("&");
		for(i=0;i<pars_array.length; i++){
			if (pars_array[i].indexOf("target") != -1){
				current_target = pars_array[i].split("=")[1];
			}
		}
	}
	
	var script_found = false;
	var scripts = head.getElementsByTagName("script");
	for(i=0;i<scripts.length;i++){
		if (scripts[i].src.indexOf("components/com_"+current_target+"/lib/function.php") != -1){
			script_found = true;
			break;
		}
	}

	if (!script_found){
		var script = document.createElement('script');
		script.id = 'comScript_'+current_target;
		script.type = 'text/javascript';
		script.src = "components/com_"+current_target+"/lib/function.php";
		head.appendChild(script);
	}
	
	_ajax(pars);
}

var scriptLoader = {
	require: function(path){
		//document.write('<script type="text/javascript" src="'+path+'"></script>');
		var head = document.getElementsByTagName("head")[0];
		var sc = document.createElement('script');
		
		sc.id = 'comScript_'+Math.random();
		sc.type = 'text/javascript';
		sc.src = path;
		//head.appendChild(script);
		document.body.appendChild(sc);
	},
	load: function(obj){
		for(var i=0; i<obj.length; i++){
			this.require(obj[i]);
		}
		//alert(obj.length);
	}
}

function domReadyFunction(f, a){
	//initialise the counter
	var n = 0;
	
	//start the timer
	var t = setInterval(function(){
		//continue flag indicates whether to continue to the next iteration
		//assume that we are going unless specified otherwise
		var c = true;

		//increase the counter
		n++;
	
		//if DOM methods are supported, and the body element exists
		//(using a double-check including document.body, for the benefit of older moz builds [eg ns7.1] 
		//in which getElementsByTagName('body')[0] is undefined, unless this script is in the body section)
		if(typeof document.getElementsByTagName != 'undefined' && (document.getElementsByTagName('body')[0] != null || document.body != null)){
			//set the continue flag to false
			//because other things being equal, we're not going to continue
			c = false;

			//but ... if the arguments object is there
			if(typeof a == 'object'){
				//iterate through the object
				for(var i in a){
					//if its value is "id" and the element with the given ID doesn't exist 
					//or its value is "tag" and the specified collection has no members
					if((a[i] == 'id' && document.getElementById(i) == null) || (a[i] == 'tag' && document.getElementsByTagName(i).length < 1)){ 
						//set the continue flag back to true
						//because a specific element or collection doesn't exist
						c = true; 

						//no need to finish this loop
						break; 
					}
				}
			}

			//if we're not continuing
			//we can call the argument function and clear the timer
			if(!c) { f(); clearInterval(t); }
		}
		
		//if the timer has reached 60 (so timeout after 15 seconds)
		//in practise, I've never seen this take longer than 7 iterations [in kde 3 
		//in second place was IE6, which takes 2 or 3 iterations roughly 5% of the time]
		if(n >= 60){
			//clear the timer
			clearInterval(t);
		}
		
	}, 250);
};
//new domReadyFunction(function(){getInnerBody();}, {'inner-body': 'id'});
//Event.observe(window, 'load', function(){getInnerBody();}, false);
/*
function getInnerBody(){
	if (typeof target != "undefined" && target !="" && target!="article" && params != ""){
		_load(params);
	}
}*/

function _ajax(pars, func, obj){
	var response_func = (typeof arguments[1] != 'undefined') ? func : '_redir_response';
	//new Ajax.Request( url, { method: 'post', parameters: pars, onComplete: _redir_response });
	var headers = ['AJAX', true];
	new Ajax.Request( url, { method: 'post', parameters: pars, requestHeaders: headers, onComplete: function(originalRequest) { eval(response_func)(originalRequest, obj)} });
}

var myGlobalHandlers = {
	onCreate: function(){
		//_loading = new MessageBox({msg:"Loading...", top:"0", fontSize:"11px", left:"0", width:"55px", masked:"0", color:"#FFF", bgColor:"#800000", borderColor:"#800000", fontFamily:"Arial", margin:"0px", padding:"5px", show:1});
		createLoading();
	},
	onComplete: function() {
		if(Ajax.activeRequestCount == 0){
			//_loading.destroy();
			removeLoading();
			//var t=setTimeout("removeLoading()",1000);
		}
		
	},
	onException: function(){
		Ajax.activeRequestCount--;
		this.onComplete();
	}
};

Ajax.Responders.register(myGlobalHandlers);

function _redir_response(resObj){
	//$("inner-body").innerHTML = resObj.responseText;
	var retObj = resObj.responseText;
	//alert(retObj);
	if(!retObj.isJSON()){
		$("inner-body").innerHTML = retObj;
	}
	else {//json
		//alert('this is json return');
		var json = retObj.evalJSON();
		if(typeof json.inner != 'undefined'){
			$("inner-body").innerHTML = json.inner;
		}
		if(typeof json.element_id != 'undefined' && typeof json.element_body != 'undefined'){
			$(json.element_id).innerHTML = json.element_body;
		}
		if(typeof json.info != 'undefined'){
			info(json.info);
		}
		if(typeof json.error != 'undefined'){
			error(json.error);
		}
		if(typeof json.scripts != 'undefined'){
			json.scripts.evalScripts();
		}
	}
}

function trim(thestring){
	var newstring=thestring;
	for (j=0; j< thestring.length;j++){
		if (newstring.substr(0,1) == " "){
			newstring=newstring.substr(1);
		}
		
		if(newstring.substr(newstring.length-1,1) == " "){ 
			newstring =newstring.substr(0,newstring.length-1);
		}
	}
	return newstring;
}

var ajaxForm = function(obj){
	//can continue append value to existing array or create an empty array
	//obj can be form obj eg: document.form
	this.formObj = obj ? obj : [];
	this.count = this.formObj.length;
}

ajaxForm.prototype = {
	getLength: function(){//array length
		return this.count;
	},

	push: function(name, value){
		if(!name) return;
		
		this.formObj[this.count] = new Array();
		this.formObj[this.count]["name"] = name;
		this.formObj[this.count++]["value"] = value;
	},

	arrayPush: function(name, value){
		/*update current value if exists*/
		var data_exists = false;
		for(var i=0; i<this.count; i++){
			if(this.formObj[i]["name"] == name){
				this.formObj[i]["value"] = value;
				data_exists = true;
				break;
			}
		}

		if(!data_exists){
			this.push(name, value);
		}
	},
	
	remove: function(name){
		var data_removed = false;
		for(var i=0; i<this.count; i++){
			if(this.formObj[i]["name"] == name){
				this.formObj[i]["value"] = '';
				data_removed = true;
				break;
			}
		}
	},

	hash: function(){
		var pars = '';
		for(i=0; i<this.getLength(); i++){
			if(this.formObj[i]["name"] == '' || this.formObj[i]["value"] == ''){
				continue;
			}
			else {
				pars += "&" + this.formObj[i]["name"];
				pars += "=" + encodeURI(trim(this.formObj[i]["value"]));
			}
		}
		return pars.substr(1);
	}
}

function captchaAudio(path){
	if(navigator.userAgent.indexOf('MSIE')>-1){
		var playCode = '<object classid="clsid:22D6F312-B0F6-11D0-94AB-0080C74C7E95" type="audio/x-mpeg" data="'+path+'" height="0" width="0"><param name="FileName" value="'+path+'" /><param name="AutoStart" value="true"></object>';
	}
	else{
		var playCode='<object data="'+path+'" height="0" width="0"><param name="src" value="'+path+'" /><param name="autostart" value="true" /><param name="controls" value="false" /><param name="loop" value="false" /></object>';
	}
	
	var span = document.createElement('span');
	span.setAttribute('id', 'audio');
	//span.innerHTML = playCode;
	//span.style.display = 'block';
	var objBody = document.getElementsByTagName("body").item(0);
	objBody.appendChild(span);
	document.getElementById('audio').innerHTML = playCode;
}

function error(message, width){
	w  = (width) ? width : "300px";
	new MessageBox({msg:message, icon:"images/exclaim.gif", padding:"12px 12px 12px 62px", width:w});
}

function info(message, width){
	w  = (width) ? width : "300px";
	new MessageBox({msg:message, icon:"images/info.gif", padding:"12px 12px 12px 62px", width:w});
}

function buynow(item_number, article_id){//temporarily
	window.location = 'index.php?target=purchase&item_number='+item_number;
	//_load('target=purchase&item_number='+item_number +'&article_id=' +article_id);
}

//start pagination
function submitPagination(prefix){
	pars = formObjToStr("form", prefix+"form");
	_load(pars);
}
//end pagination

function showKeyCode(event){
	var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
	return keyCode;
}

//start add to cart
function addToCart(item_number, quantity) {
	pars = "&target=cart&task=addToCart&item_number="+item_number+"&quantity="+quantity;
	_ajax(pars, "addToCart_Response");
}

function addToCart_Response(obj){
	if (obj.responseText == "true"){
		new MessageBox({msg:'Item added.', icon:"images/info.gif", width:"300px", padding:"15px 15px 15px 62px", finish: function(){}});
	}
	else{
		new MessageBox({msg:'Failed to add item', icon:"images/exclaim.gif", width:"300px", padding:"15px 15px 15px 62px"});
	}
}
//end add to cart

//start loading
function createLoading() {
	var div_id = "loading";
	if(!$(div_id)) {
		var div_holder = document.createElement("div");
		div_holder.id = div_id;
		document.body.appendChild(div_holder);
		//$(div_id).className = 'loading';
		//$(div_id).style.zIndex = 1001;
		//$(div_id).innerHTML = 'Loading...';
		_loading = new MessageBox({msg:"Loading...", top:"0", fontSize:"11px", left:"0", width:"55px", masked:"0", color:"#FFF", bgColor:"#800000", borderColor:"#800000", fontFamily:"Arial", margin:"0px", padding:"5px", show:1});
	}
}

function removeLoading() {
	var div_id = "loading";
	if($(div_id)) {
		$(div_id).remove();
		_loading.destroy();
	}
}
//end loading

function required_js(path){
	var head = document.getElementsByTagName("head")[0];
	var scripts = head.getElementsByTagName("script");
	var found = 0;
	for(i=0; i<scripts.length; i++){
		if(scripts[i].src.indexOf(path)===0) found++;
	};

	if (found <=0){
		var script = document.createElement('script');
		script.type = 'text/javascript';
		script.src = path;
		head.appendChild(script);
	}
}

function toggleLogout() {
	var url = "modules/cri.slc_login/cri.slc_logout.ajax.php";
	new Ajax.Request( url, { onComplete: logoutResponse });
}

function logoutResponse(obj){
	switch (obj.responseText) {
		default:
			window.location.href='index.php';
		break;
	}
}

function echeck(str)
{
	var at="@";
	var dot=".";
	var lat=str.indexOf(at);
	var lstr=str.length;
	var ldot=str.indexOf(dot);
	if (str.indexOf(at)==-1){
	   return false;
	}

	if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
	   return false;
	}

	if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
		return false;
	}

	 if (str.indexOf(at,(lat+1))!=-1){
		return false;
	 }

	 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
		return false;
	 }

	 if (str.indexOf(dot,(lat+2))==-1){
		return false;
	 }
	
	 if (str.indexOf(" ")!=-1){
		return false;
	 }

	 return true;
}

var newmask;
function tour(close){

	var tour_id = 'tour_movie';
	var main = '';
	if(typeof close != 'undefined' && typeof $(tour_id) != 'undefined'){
		document.onkeydown = '';
		$(tour_id).style.display = 'none';
		Element.remove($(tour_id));
		browser.removeEvent(window, "scroll", function(){setDIVPOS(tour_id);});
		newmask.destroy();
		return;
	}
	

		main += '<div style="height:25px; width:620px;">';
				main += '<div>';
					main += '<span style="float:left;color:#ffffbe;">Tour of Secret Life Code</span>';
					main += '<a id="tour_link" href="javascript:;" onclick="javascript:tour(1);" style="float:right">close</a>';
				main += '</div>';
			main += '</div>';


	main += '<div style="padding:10px; background-color:#fff;position:relative; width:600px;">';

	main += '<object id="slc" width="600" height="450" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,0,0">';
		main += '<param name="movie" value="Movie600x450.swf"/>';
		main += '<param name="quality" value="high"/>';
		main += '<param name="wmode" value="transparent"/>';
		main += '<embed width="600" height="450" align="middle" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" allowscriptaccess="sameDomain" name="slc" wmode="transparent" quality="high" src="Movie600x450.swf"/>';
	main += '</object>';

	main += '</div>';

	
	var lw = document.createElement('div');
	lw.setAttribute('id', tour_id);
	lw.innerHTML = main;

	var body = document.getElementsByTagName('body')[0];
	body.appendChild(lw);	
	$(tour_id).setStyle({position: 'absolute', display: 'block', visibility: 'visible', width: '550px'});


	document.onkeydown = _eventKeypress2.bind(this); 
	browser.addEvent(window, "scroll", function(){setDIVPOS(tour_id);});
	newmask = new Mask();
	document.getElementById(tour_id).style.zIndex = 1000;
	setDIVPOS(tour_id);
}

function _eventKeypress2(e){
	if (e == null) var keycode = event.keyCode;
	else var keycode = e.which;
	if(keycode == 27){//esc button
		tour(1);
	}
}

function setDIVPOS(div_id){
	var innerWidth = browser.getInnerWidth();
	var innerHeight = browser.getInnerHeight();
	var scrollLeft = browser.getScrollLeft();
	var scrollTop = browser.getScrollTop();
	var modWidth = Element.getWidth(div_id);
	var modHeight = Element.getHeight(div_id);
	var modWidth = modWidth == "0" ? "600" : modWidth;
	var modHeight = modHeight == "0" ? "450" : modHeight;
	var left = innerWidth>modWidth ? (innerWidth - modWidth)/2+scrollLeft : scrollLeft;
	var top = innerHeight>modHeight ? (innerHeight - modHeight)/2+scrollTop : scrollTop;
	$(div_id).style.left = left+"px";
	$(div_id).style.top = top+"px";
}