var editors = Array();

function AJAXCall(div, url) {
	//AJAXCallSyncNop(div,url);
	AJAXCallAsync(div, url);
}

function beginProcess() {
	return true;
}

function endProcess() {
}

function AJAXCallAsync(div, url) {
	var xmlHttp;
	try {
		// Firefox, Opera 8.0+, Safari		
		xmlHttp=new XMLHttpRequest();
	} catch (e) {
		// Internet Explorer
		try {
  			xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
  		} catch (e) {
  			try {
    				xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
    			} catch (e) {
    				alert("Your browser does not support AJAX!");
    				return false;
    			}
  		}
	}
	
	/*var element = document.getElementById(div);
	if(element) {
		element.style.backgroundColor = "#a0a0a0";
	}*/

	xmlHttp.onreadystatechange=function() {
		if(xmlHttp.readyState == 4) {
			var element = document.getElementById(div);
			if(element) {
				element.innerHTML = xmlHttp.responseText;
				//element.style.backgroundColor = "";
			}			
		}
	}
	
	xmlHttp.open("GET",url,true);
	xmlHttp.send(null);
}

function AJAXCallSyncNop(div, url) {
	var xmlHttp;
	try {
		// Firefox, Opera 8.0+, Safari
		xmlHttp=new XMLHttpRequest();
	} catch (e) {
		// Internet Explorer
		try {
  			xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
  		} catch (e) {
  			try {
    				xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
    			} catch (e) {
    				alert("Your browser does not support AJAX!");
    				return false;
    			}
  		}
	}

	/*xmlHttp.onreadystatechange=function() {
		if(xmlHttp.readyState == 4)
			document.getElementById(div).innerHTML = xmlHttp.responseText;
	}*/
	
	xmlHttp.open("GET",url,false);
	//xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    //  	xmlHttp.setRequestHeader("Content-length", parameters.length);
	xmlHttp.send(null);
	element = document.getElementById(div);
	if(element) element.innerHTML = xmlHttp.responseText;
}

function AJAXCallSync(div, url, parameters) {
	var xmlHttp;
	try {
		// Firefox, Opera 8.0+, Safari
		xmlHttp=new XMLHttpRequest();
	} catch (e) {
		// Internet Explorer
		try {
  			xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
  		} catch (e) {
  			try {
    				xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
    			} catch (e) {
    				alert("Your browser does not support AJAX!");
    				return false;
    			}
  		}
	}

	/*xmlHttp.onreadystatechange=function() {
		if(xmlHttp.readyState == 4)
			document.getElementById(div).innerHTML = xmlHttp.responseText;
	}*/
	
	xmlHttp.open("POST",url,false);
	xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
      	xmlHttp.setRequestHeader("Content-length", parameters.length);
	xmlHttp.send(parameters);
	document.getElementById(div).innerHTML = xmlHttp.responseText;
}

function flashCart(flash) {
	var cart = document.getElementById("cart");
	switch(flash) {
		case 1: cart.className = 'flash1'; break;
		case 2: cart.className = 'flash2'; break;
		case 0: cart.className = 'flash3'; break;
	}
}

function requireField(form,field,title,msg) {
	f = document.forms[form];
	for(i=0; i<f.elements.length; i++) {
		e = f.elements[i];
		if(e.name==field) {
			if(e.value=="") {
				alert(title+" "+msg);
				return false;
			}
		}
	}
	return true;
}

function cartAnimate(type) {
	setTimeout("flashCart(1);",10);
	setTimeout("flashCart(2);",100);
	setTimeout("flashCart(0);",400);
}

function addEditor(name) {
	toggleEditor(name);
	editors[editors.length] = name;
}

function closeEditors() {
	//while(editors.length>0)
//		toggleEditor(editors.pop());
    if (typeof tinyMCE != "undefined") {
        for(id in tinyMCE.editors){
            tinyMCE.execCommand('mceRemoveControl', false, id);
        }
    }
}

function changeCategory(catid) {
	if(!beginProcess()) return;
	
	window.category = catid;
	closeEditors();
	AJAXCall("categories","part.php?part=category&id=" + catid);
	AJAXCall("content","part.php?part=products&id=" + catid);
	AJAXCall("pagetitle","part.php?part=title&type=category&id=" + catid);
	AJAXCall("navitree","part.php?part=navitree");
	
	endProcess();
}

function changeProductPage(catid, begin, count) {
	if(!beginProcess()) return;
	
	window.category = catid;
	closeEditors();
	AJAXCall("content","part.php?part=products&id=" + catid + "&b=" + begin + "&c=" + count);
	
	endProcess();
}

function changeOnlyCategory(catid) {
	if(!beginProcess()) return;
	
	window.category = catid;
	closeEditors();
	AJAXCall("categories","part.php?part=category&id=" + catid);
	AJAXCall("navitree","part.php?part=navitree");
	
	endProcess();
}

function changePage(page) {
	if(!beginProcess()) return;
	
	window.content = page;
	window.category = 0;
	window.product = 0;
	closeEditors();
	AJAXCall("categories","part.php?part=category&id=0");
	AJAXCall("content","part.php?part=content&id=" + page);
	AJAXCall("pagetitle","part.php?part=title&type=content&id=" + page);
	AJAXCall("navitree","part.php?part=navitree");
	
	endProcess();
}

function changeProduct(prodid,catid) {
	if(!beginProcess()) return;
	
	window.product = prodid;
	window.category = catid;
	window.content = 0;
	closeEditors();
	AJAXCall("categories","part.php?part=category&id=" + catid);
	AJAXCall("content","part.php?part=product&id=" + prodid);
	AJAXCall("navitree","part.php?part=navitree&id=" + catid);
	
	endProcess();
}

function showCart() {
	if(!beginProcess()) return;
	
	closeEditors();
	window.content = 0;
	window.category = 0;
	window.product = 0;
	AJAXCallSync("content","part.php","part=fullcart");
	AJAXCall("categories","part.php?part=category&id=0");
	AJAXCall("pagetitle","part.php?part=title&type=cart");
	AJAXCall("navitree","part.php?part=navitree");
	AJAXCall("cart","part.php?part=cart");
	
	endProcess();
}

function changePageByName(name) {
	if(!beginProcess()) return;
	
	window.content = 0;
	window.category = 0;
	window.product = 0;
	AJAXCall("content","part.php?part=content&name=" + name);
	
	endProcess();
}

function reloadAll(content) {
	if(!beginProcess()) return;
	
	window.content = 0;
	window.category = 0;
	window.product = 0;
	AJAXCall("categories","part.php?part=category&id=0");
	AJAXCall("content","part.php?part=content&name=" + content);
	AJAXCall("pagetitle","part.php?part=title&type=content&name=" + content);
	AJAXCall("navitree","part.php?part=navitree");
	AJAXCall("cart","part.php?part=cart");
	
	endProcess();
}

function showMain() {
	reloadAll("home");
}

function showProductMain() {
	reloadAll("product_home");
}

function showSearch() {
	if(!beginProcess()) return;
	window.content = 0;
	window.category = 0;
	window.product = 0;
	AJAXCall("content","part.php?part=searchform");
	endProcess();
}


function listFormat(format, catid) {
	if(!beginProcess()) return;
	window.category = catid;
	closeEditors();
	AJAXCall("content","part.php?part=products&id=" + catid + "&listformat=" + format);
	endProcess();
}

function buyProduct(prodid, amount, special) {
	if(!beginProcess()) return;
	AJAXCall("cart","part.php?part=cart&buy=" + prodid + "&quantity=" + amount + special);
	cartAnimate("new");
	endProcess();
}

function doSearch(query) {
	if(!beginProcess()) return;
	closeEditors();
	AJAXCall("content","part.php?part=search&q=" + query);
	endProcess();
}

function showOrderForm() {
	if(!beginProcess()) return;
	closeEditors();
	AJAXCall("content","part.php?part=orderform");
	endProcess();
}

function koriPoista(id) {
	if(!beginProcess()) return;
	AJAXCallSync("content","part.php","part=fullcart&kori_poista=" + id);
	AJAXCall("cart","part.php?part=cart");
	endProcess();
}

function koriToimiTapa(id) {
    if(!beginProcess()) return;
    AJAXCallSync("content","part.php","part=fullcart&kori_toitapa=" + id);
    AJAXCall("cart","part.php?part=cart");
    endProcess();
}

function AJAXWait(text) {
	document.getElementById("waitdivtext").innerHTML = text;
	document.getElementById("waitdiv").style.visibility = "visible";
}

function showElement(id) {
	var element = document.getElementById(id);
	if(element) element.style.display="block";
}

function hideElement(id) {
	var element = document.getElementById(id);
	if(element) element.style.display="none";
}

function disableElement(id) {
	var element = document.getElementById(id);
	if(element) element.style.backgroundColor="#fec";
}

function SetCookie(cookieName,cookieValue,nDays) {
	var today = new Date();
	var expire = new Date();
	if (nDays==null || nDays==0) nDays=1;
	expire.setTime(today.getTime() + 3600000*24*nDays);
	document.cookie = cookieName+"="+escape(cookieValue)+ ";expires="+expire.toGMTString();
}

function popup(thelink, thewindow, width, height) {
	if (!window.focus) return true;
	var href;
	if (typeof(thelink) == 'string')
   		href=thelink;
	else
		href=thelink.href;
	window.open(href, thewindow, 'width=' + width + ',height=' + height + ',scrollbars=yes');
	return false;
}

function asetakuva(url) {
	var scaleurl = 'img.php?url=' + url + '&resample=1&width=256&height=256';
	var bigscaleurl = 'img.php?url=' + url + '&resample=1&width=640&height=640';
	document.getElementById("tuotekuva").src= scaleurl;
	document.getElementById("tuoteref").href= bigscaleurl;
}


function getFormData(formid) {
	var f = document.forms[formid];
	if(!f) return "";
	var parameters = "";
	for(i=0; i<f.elements.length; i++) {
		parameters += "&" + f.elements[i].name;
		if(f.elements[i].type == "checkbox")
			parameters += "=" + (f.elements[i].checked?"1":"0");
		else
			parameters += "=" + escape(f.elements[i].value);
	}
	return parameters;
}

function submitForm(formid) {
	request = "part.php";
	var f = document.forms[formid];
	var catid = window.category;
	var prodid = window.product;
	var contid = window.content;
	var parameters = "";
	for(i=0; i<f.elements.length; i++) {
		parameters += "&" + f.elements[i].name;
		if(f.elements[i].type == "checkbox")
			parameters += "=" + (f.elements[i].checked?"1":"0");
		else
			parameters += "=" + encodeURIComponent(f.elements[i].value);
		if(f.elements[i].name == "cat")
			catid = f.elements[i].value;
		else if(f.elements[i].name == "pid")
			prodid = f.elements[i].value;
		else if(f.elements[i].name == "cid")
			contid = f.elements[i].value;
	}
	AJAXCallSync("hidden",request,parameters);
}

// insert window size to a cookie
SetCookie('windwidth',screen.width,1);
SetCookie('windheight',screen.height,1);
/*
window.onbeforeunload = function () {
   //location.replace('http://www.google.com');
   alert("Hello! I'm here to give a lecture on the Back button.\nYou see, in the modern day, most Internet applications are built using AJAX. That's short for Asynchronous JavaScript And XML. In real life, this means that the page address doesn't necessarily change when, what appears to you, you're browsing a web site. However, there's a side-effect: your browser history seizes to work. Therefore, clicking on the Back button will slingshot you right back to the previous web site you came from.");
}*/

function openAJAXPage() {
	/* Activate current AJAX page by anchor */
	if(window.location.hash!="") {
		hash = window.location.hash;
		
		hash = hash.replace("#","");
		
		window.current = hash;
		
		vars = hash.split("&");
		for(i=0;i<vars.length;i++) {
			vals=vars[i].split("=");
			key=vals[0]; value="";
			if(vals.length>1) value=vals[1];
			switch(key) {
				case "cart":
					showCart();
					break;
				case "search":
					showSearch();
					break;
				case "pid":
					changePage(value);
					break;
				case "id":
					changeProduct(value);
					break;
				case "cid":
					changeCategory(value);
					break;
			}
		}
	} else {
		if(window.product > 0 || window.category > 0 || window.content > 0) {
			reloadAll("home");
		}
	}
}

function checkAJAX(timeout) {
/*	if(typeof(window.current)!="undefined" && typeof(window.location.hash)!="undefined") {
		currentpage = window.current.split("&")[0];
		currenthash = window.location.hash.split("&")[0].replace("#","");
		if(currentpage != currenthash) {
			openAJAXPage();
		}
	}
	setTimeout("checkAJAX(" + timeout + ")",timeout);*/
}


