var oEvent = new olEvent();
var oFieldsCheck = new cmsFormFieldsCheck();
var oBasket = new cmsShopBasket();

oEvent.observe(window,"load",function(){
	oFieldsCheck.load();
	oBasket.load();
});

var $ = function(id){return document.getElementById(id);};
var _0 = function(str){return document.getElementsByTagName(str)[0];};
var $_ = function(name,pos){
	var elem_name = name;
	var i = 0;

	if(pos) i = parseInt(pos);

	if(document.getElementsByName(name)[i])
		return document.getElementsByName(name)[i++];
	return null;
};

function _(o){
	var dbg = "dbg";
	if(!$(dbg)){
		el = _0("body").appendChild(document.createElement("div"));
		//el.style.color = "white";
		el.id = dbg;
	}

	if(o!=undefined && (typeof o)=="object"){
		if(o[0])
			for(var i=0; i<o.length; i++) $(dbg).innerHTML += "<br>"+i+"="+o[i];
		else
			for(var i in o) $(dbg).innerHTML += "<br>"+i+"="+o[i];
	}else
		$(dbg).innerHTML += "<br>"+o;

	$(dbg).innerHTML += "<br><br>";
}

function set_cursor(name){_0("body").style.cursor = name; }

function select_input_text(e){try{e.target.select();}catch(e){}}

function get_address(start,end){return unescape(start+'@'+end);}

function display_div(type,text){document.writeln('<div class="'+type+'">'+text+'</div>');}

function clear_input_text(o,v){
	try{if(o.value==v) o.value='';return false;}catch(e){}
	return true;
}

var swfObject = function(id, swf, w, h, bg){
	this.obj = "swfObj"; eval(this.obj + "=this");
	this.el_parent = id;
	this.el_swf = id + '_swf';
	this.swf = swf;
	this.fv = (arguments[5]) ? arguments[5] : "";
	this.msg = (arguments[6])
		? arguments[6]
		: 'Please install the latest version of <a href="http://www.adobe.com/go/getflashplayer">Adobe Flash Player</a>.';

	this._init = function(w, h, bg){
		if (navigator.appName.indexOf("Microsoft") != -1){
			$(this.el_parent).innerHTML='<OBJECT CLASSID="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" '+
				'CODEBASE="http://active.macromedia.com/flash/cabs/swflash.cab#version=9,0,0,0" '+
				'WIDTH="'+w+'" HEIGHT="'+h+'" ID="'+this.el_swf+'" BGCOLOR="'+bg+'">'+
				'<param name="movie" value="'+this.swf+'"> '+
				'<param name="Flashvars" value="'+this.fv+'"> '+
				'<param name="allowScriptAccess" value="always"></OBJECT>';
		} else {
			if (navigator.mimeTypes && navigator.mimeTypes["application/x-shockwave-flash"]){
				$(this.el_parent).innerHTML='<embed src="'+this.swf+'" bgcolor="'+bg+'" width="'+w+'" height="'+h+'" '+
					'name="'+this.el_swf+'" Flashvars="'+this.fv+'" type="application/x-shockwave-flash" '+
					'allowScriptAccess="always" pluginspage="http://www.adobe.com/go/getflashplayer" />';
			} else
				$(this.el_parent).innerHTML = this.msg;
		}
	}

	this._init(w, h, bg);
	return this;
}

function cmsFormFieldsCheck(){
	var i = 0,k = 0;
	var obj;
	var ok = false;
	var check_flds = new Array();
	var ef = new Array();
	var elem_id_output = "syserror";
	var elem_name_check = "check";
	var elem_name_error = "error";

	this.check = function(e){
		if(!e.target || !e.target.elements[elem_name_check]) return false;

		obj = e.target;
		check_flds = e.target.elements[elem_name_check].value.split(',');

		if($(elem_id_output)) $(elem_id_output).innerHTML = "";
		ef = new Array();

		if(check_flds.length==0) return true;
		for(i=0;i<check_flds.length;i++){
			if(!obj.elements[check_flds[i]]) continue;
			var el = obj.elements[check_flds[i]];
			ok = false;

			if(!el.nodeName && el[0] && el[0].nodeName){
				for(k=0;k<el.length;k++){
					if(el[k].type && (el[k].type=="radio" || el[k].type=="checkbox")){
						//alert(check_flds[i]+"["+el[k].nodeName+"]="+el[k].checked);
						if(el[k].checked){
							ok = true;
							break;
						}
					}
				}
			}else if(el.nodeName.toLowerCase()=="input"){
				//alert(check_flds[i]+"["+el.nodeName+"]="+el.value);
				if(el.type=="radio" || el.type=="checkbox"){
					if(el.checked) ok = true;
				}else{
					if(el.value && el.value.length>0) ok = true;
				}
			}else if(el.nodeName.toLowerCase()=="textarea"){
				if(el.value && el.value.length>1) ok = true;
			}else if(el.nodeName.toLowerCase()=="select"){
				//alert(check_flds[i]+"["+el.nodeName+"]="+el.selectedIndex);
				if(el.selectedIndex>0) ok = true;
			}
			if(!ok){
				if(el.title)
					ef.push(el.title);
				else
					ef.push(check_flds[i]);
			}
		}

		if(ef.length>0){
			if(!$(elem_id_output)){
				var error_output = document.createElement("div");
				error_output.id = elem_id_output;
				error_output.className = elem_id_output;
				if(obj.childNodes[0])
					obj.insertBefore(error_output,obj.childNodes[0]);
				else
					obj.appendChild(error_output);
			}
			$(elem_id_output).innerHTML = e.target.elements[elem_name_error].value + ef.join(", ");
		}
		if(ef.length>0) oEvent.stop(e);
	};

	this.load = function(){
		var tmp = document.getElementsByTagName("input");
		for(i=0;i<tmp.length;i++){
			if(tmp[i].type.toLowerCase()!="text") continue;
			if(tmp[i].onFocus) continue;
			oEvent.observe(tmp[i],"focus",select_input_text);
		}

		tmp = document.getElementsByTagName("textarea");
		for(i=0;i<tmp.length;i++){
			if(tmp[i].onFocus) continue;
			oEvent.observe(tmp[i],"focus",select_input_text);
		}

		tmp = document.getElementsByTagName("form");
		for(i=0;i<tmp.length;i++){
			if(tmp[i].onSubmit) continue;
			if(tmp[i].elements[elem_name_check] && tmp[i].elements[elem_name_error]){
				oEvent.observe(tmp[i],"submit",oFieldsCheck.check);
			}
		}
	};
}

//--------------- Cookies -----------------
function set_cookie(name,value) {
	var arg_length = set_cookie.arguments.length;
	var path = (arg_length > 2) ? set_cookie.arguments[2] : null;
	var expires = (arg_length > 3) ? set_cookie.arguments[3] : null;
	var domain = (arg_length > 4) ? set_cookie.arguments[4] : null;
	var secure = (arg_length > 5) ? set_cookie.arguments[5] : false;
	document.cookie = name + "=" + escape(value) +
		((expires == null) ? "" : ("; expires=" +
		expires.toGMTString())) +
		((path == null) ? "" : ("; path=" + path)) +
		((domain == null) ? "" : ("; domain=" + domain)) +
		((secure == true) ? "; secure" : "");
}

function get_cookie(name){
	name += "=";
	var i = 0;
	while (i < document.cookie.length){
		var j = i + name.length;
		if (document.cookie.substring(i,j) == name)
		return get_cookie_value(j);
		i = document.cookie.indexOf(" ", i) + 1;
		if (i == 0) break;
	}
	return null;
}

function get_cookie_value(position){
	var end = document.cookie.indexOf (";", position);
	if (end == -1) end = document.cookie.length;
	return unescape(document.cookie.substring(position, end));
}

function clear_cookie_value(name){
	var exp = new Date();
	exp.setTime(exp.getTime() - 1);
	var value = get_cookie(name);
	if(value != null) document.cookie = name + "=" + value + ";expires=" + exp.toGMTString();
}

function show(msg_id,msg,btns,pel){//btns = [{'value':'ok','onclick':'return false;'}];
	if(msg_id==undefined) return pos.clear();

	var div = $(msg_id);
	if(!div){
		div = _0("body").appendChild(document.createElement("div"));
		div.id = msg_id;
		div.className = "js_msg";
	}
	div.innerHTML = "";

	if(div.childNodes.length==0){
		var div_content = div.appendChild(document.createElement("div"));
		div_content.className = "js_msg_content";
	}
	div.childNodes[0].innerHTML = msg;

	/*if((typeof btns)!="object")
		btns = [{'value':'close','onclick':"this.parentNode.style.display='none';"}];*/
	if(btns && (typeof btns)=="object"){
		for(var i=0; i<btns.length; i++){
			var btn = document.createElement("input");
			btn.type = "button";
			btn.value = btns[i].value ? btns[i].value : "ok";
			var btn_onclick = document.createAttribute("onclick");
			btn_onclick.nodeValue = (btns[i].onclick ? btns[i].onclick : "")+"return false;";
			btn.setAttributeNode(btn_onclick);
			btn.className = "js_btn";
			div.appendChild(btn);
		}
	}

	pos.init(div,pel);
	return false;
}

var pos = {
	div:undefined,
	el:undefined,
	tm:undefined,

	win_w:function(){return parseInt(window.innerWidth);},
	win_h:function(){return parseInt(window.innerHeight);},

	w:function(el){
		if(el==undefined) el = pos.div;
		if(el==undefined) return;
		return parseInt(el.offsetWidth!=undefined ? el.offsetWidth : el.width);
	},
	h:function(el){
		if(el==undefined) el = pos.div;
		if(el==undefined) return;
		return parseInt(el.offsetHeight!=undefined ? el.offsetHeight : el.height);
	},

	l:function(){return parseInt(_0("body").scrollLeft + (pos.win_w() - pos.w())/2);},
	t:function(){return parseInt(_0("body").scrollTop + (pos.win_h() - pos.h())/2);},

	set:function(){
		if(pos.div==undefined) return pos.clear();

		var l = pos.l();
		var t = pos.t();

		if(pos.el!=undefined){
			xy = getXYpos(pos.el);
			l = xy.x + pos.w(pos.el);
			t = xy.y - pos.h()/2;
		}
		pos.div.setAttribute("style","left:"+l+"px;top:"+t+"px;display:block;");
	},

	clear:function(){
		if(pos.tm!=undefined) window.clearTimeout(pos.tm);
		if(pos.div!=undefined) pos.div.style.display = "none";

		pos.tm = undefined;
		pos.div = undefined;
		pos.el = undefined;
		return false;
	},

	init:function(div,pel){
		pos.clear();
		pos.div = div;
		if(pel && pel!=undefined){
			pos.el = pel;
			pos.tm = window.setTimeout("pos.set()",1000);
		}else
			pos.set();
	}
}

/**
 * @purpose            : Get the (x,y) coordinate of a DOM element
 * @param  object elem : a DOM element or null
 * @return object      : an associative array, where indicies "x"
 *                       and "y" hold their respective coordinates
 * @note               : function is recursive
 */
function getXYpos(elem){
	if (!elem) return {"x":0,"y":0};

	var xy = {"x":(elem.offsetLeft ? elem.offsetLeft : elem.clientLeft),
		"y":(elem.offsetTop ? elem.offsetTop : elem.clientTop)};

	var par = getXYpos(elem.offsetParent);
	for (var key in par) xy[key] += par[key];

	return xy;
}

function cmsShopBasket(){
	var el_id = 'div_err';
	var ajax;

	this.load = function(){
		this.base = _0('base').href;
		ajax = new olAjax(this.base + "main_dyns.php");
		ajax.onError = function (content){
			set_cursor("default");
			show(el_id,"Error: " + content);

			return false;
		};
	};

	this.add = function(){
		if(arguments.length==0) return false;

		var cnt = !arguments[1] || arguments[1]==undefined ? 0 : arguments[1];
		set_cursor("wait");

		ajax.onComplete = function(content){
			set_cursor("default");
			var result = content.split("#L#");
			if (result[0] != "ok") return ajax.onError(content);

			show();
			if ($("cart")) $("cart").innerHTML = result[3];
			if (cnt!=0) document.location.reload(true);
		};

		show(el_id,"Adding article...");
		ajax.send("?actid=add&add="+arguments[0]+(cnt!=0 ? "&cnt="+cnt : ""),$(el_id));

		return false;
	};

	this.del = function(){
		if(arguments.length==0) return false;
		set_cursor("wait");

		var p_el = null;
		if(arguments[1] && arguments[1].parentNode.parentNode)
			p_el = arguments[1].parentNode.parentNode;

		ajax.onComplete = function(content){
			set_cursor("default");

			var result = content.split("#L#");
			if (result[0] != "ok") return ajax.onError(content);

			show();
			if ($("cart")) $("cart").innerHTML = result[3];

			if(parseInt(result[1])==1 && p_el!=null){
				p_el.parentNode.removeChild(p_el);
				document.location.reload(true);
			}
		};

		show(el_id,"Removing article...");
		ajax.send("?actid=del&del="+arguments[0],$(el_id));

		return false;
	};

	this.clear = function(){
		set_cursor("wait");

		ajax.onComplete = function(content){
			set_cursor("default");

			var result = content.split("#L#");
			if (result[0] != "ok") return ajax.onError(content);

			show();
			if ($("cart")) $("cart").innerHTML = result[3];
			document.location.reload(true);
		};

		show(el_id,"Emptying basket...");
		ajax.send("?actid=clear_basket",$(el_id));

		return false;
	};
}

function check_password(el){
	var _self = this;

	var safe = false;
	var el = el;
	var ch_el = null;
	var err_el_id = 'div_err';
	var err = {
		'not_ident':'given passwords are not identical.',
		'too_short':"given password is too short.\nPlease use one with at least 6 characters."
	};

	var _init = function(){
		if($(el.id+'_check')){
			ch_el = $(el.id+'_check');
			ch_el.parentNode.parentNode.className = ch_el.parentNode.parentNode.className.replace(/hidden/,'');
			//ch_el.setAttribute('onchange') = "return check_password().check;";
			oEvent.observe(ch_el,'change',_self.check);
			ch_el.focus();
		}
	};

	var _check_err_key = function(){
		if(!arguments[0]) return false;

		for(var i in err) if(i==arguments[0]) return true;
		return false;
	};

	var save_password = function(){
		var el_id = 'div_err';

		if(!arguments[0] || (typeof arguments[0])!=='string'){
			show(el_id,"Error: empty password",[{'value':'ok','onclick':"this.parentNode.style.display='none';"}]);
			return false;
		}

		var base = _0('base').href;
		var ajax = new olAjax(base+"main_dyns.php");
		set_cursor("wait");

		ajax.onComplete = function(content){
			set_cursor("default");

			var result = content.split("#L#");
			if (result[0] != "ok") return ajax.onError(content);

			show();
			ch_el.parentNode.parentNode.className += " hidden";
		};

		ajax.onError = function (content){
			set_cursor("default");
			show(el_id,"Error: " + content);

			return false;
		};

		show(el_id,"Saving password...");
		ajax.send("?actid=save_password&value="+arguments[0],$(el_id));

		return false;
	};

	this.set_msg = function(){
		if(!arguments[0] || (!_check_err_key(arguments[0]))) return;
		if(!arguments[1] || (typeof arguments[1])!=='string') return;

		err[arguments[0]] = arguments[1];
	};

	this.check = function(){
		if(el.value!=ch_el.value){
			show(err_el_id,err.not_ident,[
				{'value':'ok','onclick':"this.parentNode.style.display='none';$('"+el.id+"').focus();"}
			]);
			return false;
		}
		if(el.value.length<6){
			show(err_el_id,err.too_short,[
				{'value':'ok','onclick':"this.parentNode.style.display='none';$('"+el.id+"').focus();"}
			]);
			return false;
		}
		safe = true;
		save_password(el.value);
		return safe;
	};

	this.is_safe = function(){return safe;};

	this.reset_view = function(){
		oEvent.remove(ch_el,'change',_self.check);
		ch_el.className = "hidden";

		safe = false;
		el = null;
		ch_el = null;
		err_el_id = 'div_err';
		err = {
			'not_ident':'given passwords are not identical.',
			'too_short':"given password is too short.\nPlease use one with at least 6 characters."
		};
	};

	_init();
}
