/***************************************************\
|***** Version detection
\***************************************************/

var iN = navigator.userAgent.toLowerCase();
var appVer = navigator.appVersion.toLowerCase();
var iDB = (document.compatMode && document.compatMode.toLowerCase() != "backcompat")?document.documentElement:(document.body || null);
var iOP = !!(window.opera && document.getElementById);
var isIE = !!(iN.indexOf("msie") >= 0 && document.all && iDB && !iOP);
var isIE7 = !!(isIE && appVer.indexOf("msie 7.") >= 0);
var isIEmac = !!(isIE && iN.indexOf("mac") >= 0);

/***************************************************\
|***** MISC FUNCTIONS
\***************************************************/

var e = window.encodeURIComponent ? encodeURIComponent : escape;
var uE = window.decodeURIComponent ? decodeURIComponent : unescape;

function addLoadEvent(func)
{
  var oldonload = window.onload;
  if (typeof window.onload != "function") {
    window.onload = func;
  } else {
    window.onload = function() {
      if (oldonload) {
        oldonload();
      }
      func();
    }
  }
}

function IsEmpty(variable) {
    if ((variable.length==0) || (variable==null)) { return true; }
    else { return false; }
}

function isSet (variable) {
	return(typeof(variable) != "undefined");
}

function findObj(n, d) {
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

//Get all the elements of the given classname of the given tag.
function getElementsByClassName(classname,tag) {
	if(!tag) tag = "*";
	var anchs =  document.getElementsByTagName(tag);
	var total_anchs = anchs.length;
	var regexp = new RegExp("\\b" + classname + "\\b");
	var class_items = new Array()

	for(var i=0;i<total_anchs;i++) { //Go thru all the links seaching for the class name
		var this_item = anchs[i];
		if(regexp.test(this_item.className)) {
			class_items.push(this_item);
		}
	}
	return class_items;
}

function getElement(id) {
	if (document.getElementById) {
		return document.getElementById(id);
	}
	else if (document.all) {
		return document.all[id];
	}
	else if (document.layers) {
		return document.layers[id];
	}
}

function isValidXMLObject (res) { // V 2.0
	try {
		if (typeof res.getElementsByTagName("isError")[0] != "undefined") {
			return true;
		}
	} catch (e) {
		//
	}
	return false;
}

function isValidEmail (str) {
	return (str.indexOf(".") > 2) && (str.indexOf("@") > 0);
}

function functionName (res) { // V 2.2
	var longstring = new String(res);
	var brokenstring = longstring.split(" ");
	return brokenstring[1];
}

function isValidResource (res) { // V 2.1
	return (typeof res == "undefined" || res == null) ? false : true;
}

/*
// convert all characters to lowercase to simplify testing
var agt = navigator.userAgent.toLowerCase();
var appVer = navigator.appVersion.toLowerCase();

// *** BROWSER VERSION ***

var is_minor = parseFloat(appVer);
var is_major = parseInt(is_minor);
var is_opera = (agt.indexOf("opera") != -1);
var iePos  = appVer.indexOf('msie');
var is_ie   = ((iePos!=-1) && (!is_opera));
var is_ie7up = (is_ie && (agt.indexOf("msie 7.") != -1));
*/

/***************************************************\
|***** Threadsafe asynchronous XMLHTTPRequest
\***************************************************/

var TAVersion = "2.4";

function requestData (url, data, callback, dType, cApply) {
    resXML = (dType == "XML" ? true : false);
    // we use a javascript feature here called "inner functions"
    // using these means the local variables retain their values after the outer function
    // has returned. this is useful for thread safety, so
    // reassigning the onreadystatechange function doesn\'t stomp over earlier requests.
    function ajaxBindCallback() {
        if (ajaxRequest.readyState == 4) {
            if (ajaxRequest.status == 200) {
                if (ajaxCallback) {
                    if (resXML) {
                        eval(ajaxCallback + "(ajaxRequest.responseXML.documentElement, ajaxApply)");
                    } else {
                        eval(ajaxCallback + "(ajaxRequest.responseText, ajaxApply)");
                    }
                } else {
                    alert("No callback defined!");
                }
            } else {
                alert("There was a problem retrieving the XML data!\n\nStatus: " + ajaxRequest.statusText + " (" + ajaxRequest.status + ")\n\nResponse:\n" + ajaxRequest.responseText);
            }
        }
    }
    
    // use a local variable to hold our request and callback until the inner function is called...
    var ajaxRequest = false;
    var ajaxCallback = callback;
    var ajaxApply = cApply;
    
    // bind our callback then hit the server...
    ajaxRequest = getHTTPObject(resXML);
    
    if (!ajaxRequest) {
        return false;
    } else {
        ajaxRequest.onreadystatechange = ajaxBindCallback;
        try {
            ajaxRequest.open("POST", url, true);
        } catch (e) {
        	alert(e);
            return false;
        }
        ajaxRequest.setRequestHeader("X-Requested-With", "XMLHttpRequest");
        ajaxRequest.setRequestHeader("X-Prototype-Version", TAVersion);
        ajaxRequest.setRequestHeader("Connection", "close");
        ajaxRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        ajaxRequest.send(data);
        return true;
    }
    return false;
}

function getHTTPObject (resXML) {
	var xO = false;
	if (typeof XMLHttpRequest != "undefined") {
		try {
			xO = new XMLHttpRequest();
			if (resXML) {
				xO.overrideMimeType("text/xml");
			} else {
				xO.overrideMimeType("text/html");
			}
			return xO;
		} catch (e) {
			if (isIE7) {
				xO = false;
				xO = new XMLHttpRequest();
				return xO;
			} else {
				xO = false;
			}
		}
	} 
	if(!xO) {
		var msxmls = new Array(
			"Msxml2.XMLHTTP",
			"Msxml2.XMLHTTP.5.0",
			"Msxml2.XMLHTTP.4.0",
			"Msxml2.XMLHTTP.3.0",
			"Microsoft.XMLHTTP"
		);
		for (var i = 0; i < msxmls.length; i++) {
			var msxml = msxmls[i]; 
			try {
				xO = new ActiveXObject(msxml);
				return xO;
			} catch(e) {
				xO = false;
			}
		}
		
	}
	return xO;
}

/***************************************************\
|***** Search specific functions
\***************************************************/

function removeProtection (fID) {
	var rs = fID + "Results";
	var wi = fID + "Waitimage";
	
	var rsm = document.getElementById(rs);
	rsm.className = "";
	
	var wim = document.getElementById(wi);
	wim.style.display = "none";
}

function protectElement (fID) {
	var rs = fID + "Results";
	var wi = fID + "Waitimage";
	
	var rsm = document.getElementById(rs);
	rsm.className = "opacityOn";
	
	var wim = document.getElementById(wi);
	wim.style.display = "block";
}

function advanceSearchPage (itemID, page, resContainerID) {
	window.status = "Palun oodake...";
	protectElement(resContainerID);
	
	if (IsEmpty(resContainerID)) {
        return false;
    }
	
	var Data = "id=" + itemID + "&post[onlySearchResults]=1&post[page]=" + page + "&post[searchType]=" + resContainerID;
    
	return !requestData(pathToIndex, Data, "advanceSearchPageResults", "TEXT", resContainerID);
}

function advanceSearchPageResults (res, fID) {
	window.status = "Done";
	removeProtection(fID);
	
	document.getElementById(fID + "Results").innerHTML = res;
}

/***************************************************\
|***** Main menu specific functions
\***************************************************/

var hideTimer=false;
function show_hide (cur, mid, act, curID) {
	var obj,oid,i=1;
	if(hideTimer){clearTimeout(hideTimer);}
	do{
		oid="subMenu" + i;
		obj=findObj(oid);
		if(obj!=null) {
			if(i==cur){
				if(act=="show"){
					obj.style.display="";
				}else{
					hideTimer=setTimeout("hide_all(" + curID + ")", 500);
				}
			}else{
				obj.style.display="none";
			}
		}
	}while (++i&&obj!=null);
}

function hide_all (curID) {
	var obj,oid,i=1;
	do{
		oid="subMenu" + i;
		obj=findObj(oid);
		if(obj!=null) {
			if (curID > 0 && i == curID) {
				obj.style.display="";
			} else {
				obj.style.display="none";
			}
		}
	}while (++i&&obj!=null);
}

/***************************************************\
|***** Countdown functions
\***************************************************/

var timeLeft = 0;
var days = 0;
var hours = 0;
var minutes = 0;
var seconds = 0;
var tc;

function sessionCountDown(timeLeft) {
	timeLeft = parseInt(timeLeft);
	if(document.getElementById("countDay")){
		if (timeLeft > 0) {
			days = Math.floor(timeLeft / 60 / 60 / 24);
			
			hours = Math.floor((timeLeft / 60 / 60) - (days * 24));
			
			minutes = Math.floor((timeLeft / 60) - ((hours * 60) + (days * 24 * 60)));
			
			document.getElementById("countDay").innerHTML = days;
			
			if (isSet(dayEnd[days])) {
				document.getElementById("countDayN").innerHTML = dayEnd[days];
			} else {
				document.getElementById("countDayN").innerHTML = dayEnd[0];
			}
			
			document.getElementById("countHour").innerHTML = hours;
			
			if (isSet(hourEnd[hours])) {
				document.getElementById("countHourN").innerHTML = hourEnd[hours];
			} else {
				document.getElementById("countHourN").innerHTML = hourEnd[0];
			}
			
			document.getElementById("countMin").innerHTML = minutes;
			
			tc = setTimeout("sessionCountDown(" + (timeLeft - 1) + ")", 1000);
		} else {
			document.getElementById("countDay").innerHTML = "";
			document.getElementById("countHour").innerHTML = "";
			document.getElementById("countMin").innerHTML = "";
			clearTimeout(tc);
		}
	}
}

/***************************************************\
|***** Event specific functions
\***************************************************/

var eventViewActive = false;
var eventObj;
var selEvTyObj;

function getEvent (itemID, event) {
	try {
		var Data = "id=" + itemID + "&e=" + event + "&getEvent=1";
    	
		requestData(pathToIndex, Data, "showEvent", "TEXT");
	} catch (e) {
		alert(e + ":" + e.description);
	}
	return false;
}

function showEvent (res) {
	if(eventObj!=null) {
		eventViewActive = true;
		
		if (!selEvTyObj) {
			selEvTyObj = findObj("selectEventType");
		}
		if(selEvTyObj != null) {
			selEvTyObj.style.display = "none";
		}
		
		eventObj.innerHTML = res;
		eventObj.style.display = "block";
		
		prepZooms();
	}
}

function closeEvent () {
	if(eventObj!=null) {
		eventViewActive = false;
		
		eventObj.innerHTML = "";
		eventObj.style.display = "none";
		
		if (!selEvTyObj) {
			selEvTyObj = findObj("selectEventType");
		}
		if(selEvTyObj != null) {
			selEvTyObj.style.display = "block";
		}
	}
	return false;
}

/***************************************************\
|***** Cart functions
\***************************************************/

function cartItem (Url, ID, prodID, Verifier, Quantity, Price) {
	Quantity = parseInt(Quantity);
	if (Quantity) {
		msg = msgAdd;
	} else {
		msg = msgRemove;
	}
	window.status = msg;
	getElement("infoStr").innerHTML = msg;
	initLayer("infoStr", 120, 40);
	
	data = "id=" + ID;
	data = data + "&prodID=" + prodID;
	data = data + "&changeQuantity[" + (Verifier != "" ? e(Verifier) : prodID) + "]=" + Quantity;
	if (!Price) {
		selObj = getElement("price" + prodID);
		Price = selObj.options[selObj.selectedIndex].value;
	}
	data = data + "&itemPrice[" + (Verifier != "" ? e(Verifier) : prodID) + "]=" + Price;

	sendData = data + "&XMLHttpRequest=1";
	if (requestData(Url, sendData, "cartItemCallback", "TEXT") == true) {
//		alert("Andmed (cartItem) saadetud.");
	} else {
//		alert("Andmete (cartItem) saatmine ebaġnnestus!");
		document.location = Url + "?" + data;
	}
	return false;
}

function cartItemCallback (response) {
	window.status = "Done";
	
//	alert("callBackRecved :)");
	getElement("cartTotalCost").innerHTML=response;
	if (isNaN(response)) {
		getElement("infoStr").innerHTML = msgError + response;
	} else {
		getElement("infoStr").innerHTML = msgDone;
		
	}
	
	initLayer("infoStr", 120, 40);
	
	updateCartInfoMsg();
}

function updateTransportCost (selected) {
	bCa = 0;
	bTq = 0;
	bVq = 0;
	if(document.getElementById("getCartWovat").value) {
		bTq = parseFloat(document.getElementById("getCartWovat").value);
	}
	if(document.getElementById("getCartVat").value) {
		bVq = parseFloat(document.getElementById("getCartVat").value);
	}
	if(document.getElementById("getCartTotal").value) {
		bCa = parseFloat(document.getElementById("getCartTotal").value);
	}
	tSum = 0;
	tVat = 0;
	tTot = 0;
	if (selected) {
		if (transport[selected]) {
			tTot = parseFloat(transport[selected]);
			vat = 18;
            vat = (vat / 100);
            vat = (1 + vat);
			tVat = tTot - (tTot / vat);
			tSum = tTot - tVat
		}
	}
	tSum = (bTq + tSum);
	tVat = (bVq + tVat);
	tTot = (bCa + tTot);
	
	tSum = tSum.toFixed(2);
	tVat = tVat.toFixed(2);
	tTot = tTot.toFixed(2);
	document.getElementById("cartTotSum").innerHTML = tSum;
	document.getElementById("cartTotVat").innerHTML = tVat;
	document.getElementById("cartTotAll").innerHTML = tTot;
}

function updateCartInfoMsg () {
	bCa = 0;
	bTq = 0;
	bVq = 0;
	for (var i = 0; i<document.editCart.elements.length; i++) {
		if (document.editCart.elements[i].type == "text") {
			if (document.editCart.elements[i].name.indexOf("changeQuantity") > -1) {
				sbid = document.editCart.elements[i].name.substring(15, (document.editCart.elements[i].name.length - 1));
    			bQl = "changeQuantity[" + sbid + "]";
    			ql = 0;
    			if(document.getElementById(bQl).value) {
    				ql = parseInt(document.getElementById(bQl).value);
    				if(!ql) ql = 0;
    			}
				
				bPz = "prodPrice[" + sbid + "]";
    			price = 0;
    			if(document.getElementById(bPz).value) {
    				price = document.getElementById(bPz).value;
    			}
    			bTo = parseFloat(ql * price);
				
				bVt = "prodVAT[" + sbid + "]";
    			vaO = 0;
    			if(document.getElementById(bVt).value) {
    				vaO = document.getElementById(bVt).value;
    			}
				
                vat = (vaO / 100);
                vat = (1 + vat);
				bVo = bTo - (bTo / vat);

    			bTq += ql;
    			bCa += bTo;
				bVq += bVo;
			}
		}
	}
	bCa = bCa.toFixed(2);
	bVq = bVq.toFixed(2);
	woV = (bCa - bVq);
	woV = woV.toFixed(2);

/*

bQl: changeQuantity[74affa40d584f4beae7273395a0338cd0de2293d] & 
ql: 1 & 
bPz: prodPrice[74affa40d584f4beae7273395a0338cd0de2293d] & 
price: 21.97 & 
bVt: prodVAT[74affa40d584f4beae7273395a0338cd0de2293d] & 
vaO: 1.15 & 
bCa: 21.97 & 
bVq: 0.25 & 
woV: 21.72





Total: 18.62 EUR
VAT: 3.35 EUR
Grand total: 21.97 EUR

*/

//	var str = "bQl: " + bQl + " & ql: " + ql + " & bPz: " + bPz + " & price: " + price + " & bVt: " + bVt + " & vaO: " + vaO + " & bCa: " + bCa + " & bVq: " + bVq + " & woV: " + woV;
//	alert(str);
//	document.write(str);

	document.getElementById("cartTotSum").innerHTML = woV;
	document.getElementById("cartTotVat").innerHTML = bVq;
	document.getElementById("cartTotAll").innerHTML = bCa;
}

var xz = new Object;

xz.Obj = 0;
xz.Width = 0;
xz.Height = 0;

xz.reSizeTimer = 0;
xz.hideLayerTimer = 0;

xz.ScreenWidth = 0;
xz.ScreenHeight = 0;

xz.scrollTop = 0;
xz.scrollLeft = 0;

function initLayer(Id, thisWidth, thisHeight) {
    if (initObject(Id)) {
		showLayer();
		
		setObjectDimensions(thisWidth, thisHeight);
				
		reScalSize();
		
		XPosition = xz.scrollLeft + ( (xz.ScreenWidth - xz.Width) / 2);
		YPosition = xz.scrollTop + ( (xz.ScreenHeight - xz.Height) / 2);
		
		moveLayerTo(XPosition, YPosition);
		
		if (xz.hideLayerTimer) {
			clearTimeout(xz.hideLayerTimer);
		}
		xz.hideLayerTimer = setTimeout("hideLayer()", 1500);
	}
}

function setObjectDimensions (thisWidth, thisHeight) {
	if (xz.Obj.scrollHeight) {
		xz.Height = parseInt(xz.Obj.scrollHeight);
	} else if (xz.Obj.offsetHeight) {
		xz.Height = parseInt(xz.Obj.offsetHeight);
	} else {
		xz.Height = parseInt(thisHeight);
	}
	xz.Width = parseInt(thisWidth);
}

function initObject (Id) {
	if (document.getElementById) {
		xz.Obj = document.getElementById(Id);
		if (xz.Obj) {
			return true;
		}
	}
	return false;
}

function hideLayer () {
	xz.Obj.style.display = "none";
}

function showLayer () {
	xz.Obj.style.display = "block";
}

function moveLayerTo(x, y) {
	xz.Obj.style.left = parseInt(x) + "px";	
	xz.Obj.style.top = parseInt(y) + "px";
}

function reScalSize () {
	if ( typeof( window.innerWidth ) == 'number' ) {
		frameWidth = window.innerWidth;
		frameHeight = window.innerHeight;
	} else if ( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
		frameWidth = document.documentElement.clientWidth;
		frameHeight = document.documentElement.clientHeight;
	} else if ( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
		frameWidth = document.body.clientWidth;
		frameHeight = document.body.clientHeight;
	} else {
		frameWidth = window.screen.width;
		frameHeight = window.screen.height;
	}
	
	xz.ScreenWidth = frameWidth;
	xz.ScreenHeight = frameHeight;
	
	setMyScrolling();
	
	xz.reSizeTimer = setTimeout("reScalSize()", 500);
}

function setMyScrolling () {
	var posY = 0, posX = 0;
	if ( typeof( window.pageYOffset ) == 'number' ) {
		posY = window.pageYOffset;
		posX = window.pageXOffset;
	} else if ( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
		posY = document.documentElement.scrollTop;
		posX = document.documentElement.scrollLeft;
	} else if ( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
		posY = document.body.scrollTop;
		posX = document.body.scrollLeft;
	}
	xz.scrollTop = posY;
	xz.scrollLeft = posX;
}

