/**
 * @author Tim Hooijmans
 */
addLoadEvent(function(){

	// shoppingSessionManager.initCookie();
	 productTypeTabs.init();
	 subscribe.init();
	 BrowserDetect.init(); 
	// pngFix();
})
function pngFix(){

	if(BrowserDetect.browser=="Explorer"&&BrowserDetect.version<7){
	
		var script = document.createElement("script");
		script.setAttribute("type","text/javascript");
		script.setAttribute("src","script/pngFix.js");	


		var head = document.documentElement.getElementsByTagName("HEAD")[0];
		head.appendChild(script);
	
	}	

}
var subscribe = {

	init:function(){
		
		if(!document.formNewsLetterSubscribe)return;
		
		document.formNewsLetterSubscribe.reset();
		
		document.formNewsLetterSubscribe.submit.onmouseup = function(){
			
			var email = encodeURIComponent(document.formNewsLetterSubscribe.email.value);
			
			var xhr = new xmlHttpRequest();
			xhr.onreadystatechange = function(){
				
				if(xhr.readyState==4){
					
					if(xhr.responseText=="subscribed"){
						
						var returnLabel =  document.createElement("label");
						returnLabel.innerHTML = "Bedankt voor uw inschrijving";
						
						for(x=0;x<document.formNewsLetterSubscribe.childNodes.length;x++){
							
							document.formNewsLetterSubscribe.innerHTML = "";
							
						}
						
						document.formNewsLetterSubscribe.appendChild(returnLabel);
						
					}else if(xhr.responseText=="doubleEntry"){
						
						document.formNewsLetterSubscribe.reset();
						
					}
					
				}
				
			}
			xhr.open("GET","phpModules/subscribe.php?email="+email+"&shoppingSessionID="+shoppingSessionManager.readCookie("johnDoeID"),true);
			xhr.send(null);			
			
		}
		
	}
	
}; 
var shoppingSessionManager = {
	
	initCookie:function(){

		var location = window.location.href;
		location = (!location||location==null) ? document.getElementById("base").href : location ;
		
		if(location.search(/winkelmandje/) == -1){
			
			this.ereaseCookie("previousPage");
			this.createCookie("previousPage", location);
			
		}
			
		if (!this.readCookie("johnDoeID")) {
			
			 var johnDoeID = this.createJohnDoeID();
					
			 var xhr = new xmlHttpRequest();
			 xhr.onreadystatechange = function(){
			 	if(xhr.readyState==4){
					
					if(xhr.responseText.search(/error/)!=-1){
						
						shoppingSessionManager.ereaseCookie("johnDoeID");
						
					}else{
					
						shoppingSessionManager.createCookie("johnDoeID",xhr.responseText, 0);
						
					}
				}
			 }
			 xhr.open("GET","phpModules/checkInJohn.php?johnDoeID="+johnDoeID,true);			 
			 xhr.send(null);
			 			 		 
		}	

	},
	
	addProduct:function(productID){
		
	   var xhr = new xmlHttpRequest();
	   xhr.onreadystatechange = function(){
	   	if(xhr.readyState==4){
	
	      window.location = "/winkelmandje";
		  	
		}		
	   }
	   xhr.open("GET","phpModules/addProduct.php?shoppingSessionID="+this.readCookie("johnDoeID")+"&productID="+productID,true);
	   xhr.send(null);	
		
	},
	
	createJohnDoeID:function(l){
		
		if(l=="undefined"||l==0||!l||l==null)var l=8;
		var bin = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
		var x,y = null;
		var result = "";	
		
		for(x=0;x<l;x++){
			
			y = Math.floor(Math.random()*bin.length);
			result = result + bin.substring(y,parseInt(y)+1);
		
		 }	
		 
		 return result;		
			
		},	
	
	createCookie:function(name,value,days){
		
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
	},

	readCookie:function(name){
		
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return false;
	},

    ereaseCookie:function(name){
		
	 this.createCookie(name,"",-1);
	 
	}	
};
var top5 = {
	
	init:function(){
		
		if(document.getElementById("topProductWrapper")==null)return;

		document.getElementById("topProductOrderNowButton").onmouseup = function(){
			 	shoppingSessionManager.addProduct(this.name);
			}
		document.getElementById("topProductMoreInfoButton").onmouseup = function(){
			 	window.location = this.name;
			}			
		
	}	
	
	
}; 
function initShoppingCart(){

 var shoppingCartAnchor = document.getElementById("shoppingCartAnchor");
 
 if(shoppingCartAnchor)shoppingCartAnchor.href = "winkelwagen.php";
 
 var xhr = xmlHttpRequest();
 xhr.onreadystatechange = function(){
 	if(xhr.readyState==4){

		var num = xhr.responseText;
		var inject = "Winkelwagen<br />";
		
		if(num==0||num=="undefined"){			
			inject = inject + "Geen producten";	
			shoppingCartAnchor.href = "";
		}else if(num==1){			
			inject = inject + num + "&nbsp;product";		
		}else{			
			inject = inject + num + "&nbsp;producten";		
		}

		shoppingCartAnchor.innerHTML = inject;
		
	}
 }
 xhr.open("GET","phpModules/getItemAmount.php?shoppingSessionID="+shoppingSessionManager.readCookie("johnDoeID"),true);
 xhr.send(null);

}
var productTypeTabs = {
 
 me:function(){return document.getElementById("productTypeTabsHolder")},
 init:function(){
 
 	for ( x in this.me().childNodes){
		
		currentNode = this.me().childNodes[x];
		
		if(currentNode.nodeName == "INPUT"){
			
			currentNode.onmouseup = function(){
			
				window.location.pathname = this.id;
				
			}
			
		}
		
		
	}
 
 }
};
var pages = {
	
	activePage:"page1", 
	init:function(){

		var PN = document.getElementById("pageNumber");

		if( PN ){

			this.activePage = "page"+PN.value;

		}

		this.zipperBody = document.getElementById("productZipperBody");
		this.indexWrapper = document.getElementById("pageIndexWrapper");
		var pageCount = 1;
		
		this.indexWrapper.innerHTML = "Pagina:&nbsp;";
		
		for( x in this.zipperBody.childNodes ){
			
			var currentNode = this.zipperBody.childNodes[x];
			
			if(currentNode.id&&currentNode.id.search(/page[0-9]/)!=-1){
				
				var anchor = document.createElement("input");
				anchor.setAttribute("type","button");
				//anchor.className = (currentNode.id=="page1") ? "pageButtonActive" : "pageButton";
				anchor.value = pageCount;
				anchor.onmouseup = this.refresh;
				
				this.indexWrapper.appendChild(anchor);
				if(currentNode.id!=this.activePage)currentNode.style.display = "none";
				
				pageCount++;
			
			}
		}
	
		this.refreshIndex();
	},
	refreshIndex:function(){
		
		
		for( x in this.indexWrapper.childNodes){
			
			var currentNode = this.indexWrapper.childNodes[x];
		
			
			if (currentNode.nodeName == "INPUT") {
				
				currentNode.className = (this.activePage == "page" + currentNode.value) ? "pageButtonActive" : "pageButton";
				
			}
					
		}
		
		
	},
	refresh:function(){

		pages.activePage = "page"+this.value
		pages.refreshIndex();
		
		for( x in pages.zipperBody.childNodes){
			
			var currentNode = pages.zipperBody.childNodes[x];
			
			if(currentNode.id&&currentNode.id.search(/page[0-9]/)!=-1){
				
				currentNode.style.display = (currentNode.id == pages.activePage) ? "block" : "none";
					
			}
			
		}
		
	}
	
};

var uri = {
 get:function(varName){  
 
  var x,y=null;
  x = window.location.search.substring(1);
  x = x.split(/&/);
  
  for(y=0;y<x.length;y++){
    
	 if(x[y].search(varName)!=-1){	 
	  x[y] = x[y].replace(varName+"=","");
	  var varFound = true;
	  return x[y];		 
    }
   }
   if(!varFound)return "undefined";
 }	
};
function xmlHttpRequest() {
  var xmlHTTP;
  try {xmlHTTP = new XMLHttpRequest();}
  catch(e) {
    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;
      }
    }
  }
  return xmlHTTP;
}
function addLoadEvent(func) {

  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      if (oldonload) {
        oldonload();
      }
      func();
    }
  }
}

function formatPrice(num){ 
 
 if(!num)return "-";
 var valuta = "&euro;&nbsp;";
 var x,y,dotLoc,cents,euros = null;
 var azPatt = /[a-zA-Z]/;
 if(num===0)return valuta+num+",-"; 	 
 if(typeof(num)!="string")num=num.toString();
 var Target = num.length;
 for(x=0;x<Target;x++){num=num.replace(azPatt,"")}	 
 if(num.indexOf('.')==-1&&num.indexOf(',')==-1)return valuta+num+",-";
 num=num.replace(".",",");
 dotLoc = num.indexOf(",");
 cents = (num.substring(dotLoc,dotLoc+3).length==2) ? num.substring(dotLoc,dotLoc+3)+"0" : num.substring(dotLoc,dotLoc+3); 
 euros = num.substring(0,dotLoc);     
 return valuta+euros+cents;	 
	 
}
function getElementPosition(elmntId){

 var object = document.getElementById(elmntId);
 if(!object)return "undefined";	
 var x = null; 
 var Left = 0;
 var Top = 0;  
 do{ 
   Left += object.offsetLeft;
   Top += object.offsetTop; 	     	
 }while(object = object.offsetParent); 
 var x = {l:Left,t:Top};  
 return x;
  
}
var addHelpLabel = function(elmntId, caption){
	
	if(!elmntId)return;	
	
	var elmnt = document.getElementById(elmntId);
	
	elmnt.onmouseover = function(){
		
		var label = document.createElement("div");
	    label.className = "helpLabel";
	    label.innerHTML = (caption) ? caption : "&nbsp;";
		label.id = this.id+"HelpLabel";
		var elmntPosition = getElementPosition(this.id);
		label.style.left = elmntPosition.l+20+"px";
		label.style.top = elmntPosition.t-7+"px";
		document.body.appendChild(label)
		
	}
	elmnt.onmouseout = function(){
		
		var helpLabel = document.getElementById(this.id+"HelpLabel");
		document.body.removeChild(helpLabel);
		
	}
	
}
function getCurrentDate(format){
	
	var d = new Date();
    var day = d.getUTCDate();
	var month = parseInt(d.getUTCMonth())+1;
	var year = d.getUTCFullYear();
	if(format == "dashed"){
		return day+"-"+month+"-"+year;
	}else{		
		return day+""+month+""+year;		
	}
	
	
}
function getCurrentTime(){
	
	var d = new Date();
	var hour = d.getUTCHours();
	var minutes = d.getUTCMinutes();
	var seconds = d.getUTCSeconds();
	return hour+":"+minutes+":"+seconds;
	
}
function calcDiscount(price, amount, type){
	
	switch(type) {
	case "percent":
	
		var discount = price / 100 * amount;
		var result = price - discount;
		result = result+"";
		if(result.search(/[.]/)!=-1){
			var dotLocation = result.search(/[.]/);			
			result = result.substring(0,parseInt(dotLocation)+3);
		}		
		return result;
	
		break;
 }
		
}
function writeHistory(caption,type){
	
	if(!caption||!type)return false;
	var params = "?caption="+caption+"&type="+type;
	var xhr = xmlHttpRequest();
	xhr.open("GET","phpModules/writeHistory.php"+params,true);
	xhr.send(null);
	
}
function countProducts(){
	
		var x = null;
		var c = 0;
		var target = document.getElementById("productZipperBody");
		
		for(x=0;x<target.childNodes.length;x++){
			  
		var currentNode = target.childNodes[x];
			  
		if(currentNode.id&&currentNode.id!="pageIndexWrapper"&&currentNode.nodeName=="DIV"){
				 
		for( y in currentNode.childNodes){
						
			if(currentNode.childNodes[y].id&&currentNode.childNodes[y].nodeName=="DIV"){
			
				c = c + 1;
			
			}
						
		}
				  
	 }				 
  }	
  return c;
	
}
var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{
			string: navigator.userAgent,
			subString: "Chrome",
			identity: "Chrome"
		},
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari",
			versionSearch: "Version"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			   string: navigator.userAgent,
			   subString: "iPhone",
			   identity: "iPhone/iPod"
	    },
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};






