// http://simon.incutio.com/archive/2004/05/26/addLoadEvent
function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      oldonload();
      func();
    }
  }
}

// Assign a javascript namespace
if (!GARDO) var GARDO = new Object();

/******************************************************************************
 GARDO.Display module v1.1
 
 This module handles the changes of the Display like resizing.
 
 v1.1 : Added resize image if there is a id products
 v1.2 : Add a cookie with the last fontSize to prevent resizing on load the
 cookie can be read with php in a css file which is faster. 
******************************************************************************/

GARDO.Display = {
	resize			:	function (){
		var oldFontSize = "62.5";			
		var bodyElm = document.getElementsByTagName("body")[0];
		// Detect the body width of the browser in px
		var clientWidth = document.documentElement.clientWidth;
		// Calculate the new font-size based on the clientWidth
		var newFontSize = Math.round(oldFontSize / (800 / clientWidth)*10)/10;
		// Set the new font-size if the size is bigger then the old font-size
		if(newFontSize > oldFontSize && newFontSize != bodyElm.style.fontSize){
			bodyElm.style.fontSize = newFontSize + "%";
			/*var products = document.getElementById("resize");
			// If there is a div/element with the id products change the image size
			if(products){
				var img = products.getElementsByTagName("img");
				for(var i = 0; i < img.length; i++){
					if(window.getComputedStyle) {
						var imgStyle = window.getComputedStyle(img[i], null);	
					} else {
						var imgStyle = GARDO.ImgStyle;
						imgStyle.getComputedStyle(img[i]);
					}
					var imgsrc = img[i].getAttribute('src');
					var bigimage = 'resize.php?img=bigimage' + imgsrc.substr(imgsrc.lastIndexOf("/")) + '&newwidth=' + imgStyle.getPropertyValue("width") + '&newheight=' + imgStyle.getPropertyValue("height"); 
					img[i].setAttribute('src', bigimage);
				}
			}*/
			document.cookie = "fontSize="+ newFontSize + "; path=/";			
		} else {
			bodyElm.style.fontSize = oldFontSize + "%";
			document.cookie = "fontSize="+ oldFontSize + "; path=/";
		}
	}
};

/******************************************************************************
 GARDO.ImgStyle module v1.0
 
 IE (and maybe others ) don't support getComputedStyle so the values had to make 
 manual i could  have put the not DOM style but browsers react differend e.g 
 Opera compute the image real size with img[0].width, FF and IE the size on the 
 screen the same as getComputedStyle
******************************************************************************/

GARDO.ImgStyle = {
	element					: 	null,
	getComputedStyle		:	function(element) {
		this.element = element;

	},
	getPropertyValue		:	function(style) {
		var result;
		//document.getElementById('footer').innerHTML = "test: " +  this.element;		
		switch (style) {
		   case 'width':
			 result = this.element.width;
		   case 'height':
			 result = this.element.height;
		}
		return result;	
	}
}

/******************************************************************************
 GARDO.SVG module v1.1
 
 This module check if SVG is supported and if not it looks if flash is supported
 if SVG is not supported but flash does. The SVG object converts to Flash
 
 v1.1 IE needs to embed svg with the embed element
 v1.2 IE doen't cache the SVG right so first provide flash.
 
******************************************************************************/
 
GARDO.SVG = {
	checkSVG		:	function () {
		/*@cc_on @*/
		/*@if (@_jscript_version >= 5)	
		if(GARDO.SVG.hasPlugin('application/x-shockwave-flash', 'ShockwaveFlash.ShockwaveFlash.6')){
			GARDO.SVG.SVG2SWF();
		} else {
		@end @*/
		if(!GARDO.SVG.hasPlugin('image/svg-xml', 'Adobe.SVGCtl')){	
			// Only convert to flash if flash is supported
			if(GARDO.SVG.hasPlugin('application/x-shockwave-flash', 'ShockwaveFlash.ShockwaveFlash.6')){
				GARDO.SVG.SVG2SWF();
			}
		} else {
			// Place the embed element for IE
			/*@cc_on @*/
			/*@if (@_jscript_version >= 5)	
				var svgObject = document.getElementsByTagName("b")
					for (var i=0; i < svgObject.length; i++){	
						if(svgObject[i].getAttribute("type") == "image/svg+xml"){
							 var classname = svgObject[i].getAttribute("className");
						  var objectInnerHTML = svgObject[i].innerHTML;
						 svgObject[i].innerHTML = '<embed src="/catalogus/templates/gardo/svg/'+ classname +'.svg" type="image/svg-xml" class="'+ classname +'" wmode="transparent"  />' +
						 '<noembed>' +
						 '' + objectInnerHTML + '</noembed>';
						}
					}
			@end @*/		
		}
		/*@cc_on @*/
		/*@if (@_jscript_version >= 5)	
			}
		@end @*/
	},	
	hasPlugin		:	function (mimeType, activeX) {
		var plugin = false;
		/*@cc_on @*/
		/*@if (@_jscript_version >= 5)
		// M.b.v. JScript wordt dit enkel uitgevoerd in IE.
			var testPlugin;
			try {
				testPlugin = new ActiveXObject(activeX);
			}
			catch (e) {
				testPlugin = false;
			}
			if (testPlugin){
				var plugin = true;
			}
		@end @*/
		if(GARDO.SVG.hasMimeType(mimeType)) {
				plugin = true; 
		}
		return plugin;
	},
	hasMimeType		:	function (mimeType) {	
		// TODO FF dont detect the flash plugin
	
		var mimeType = false;
		// Plugin support		
		if(navigator.mimeTypes && navigator.mimeTypes[mimeType]){
			var mimeType = true;	
		}
		
		// Native support for SVG
		if(typeof window.SVGElement != 'undefined'){
			var mimeType = true;	
		}
		
		return mimeType;
	},
	SVG2SWF		:	function () {
		var svgObject = document.getElementsByTagName("object");
		/*@cc_on @*/
		/*@if (@_jscript_version >= 5)
			var svgObject = document.getElementsByTagName("b");
		@end @*/
		for (var i=0; i < svgObject.length; i++){	
			if(svgObject[i].getAttribute("type") == "image/svg+xml"){
				classname = svgObject[i].getAttribute("class");
				/*@cc_on @*/
				/*@if (@_jscript_version >= 5)				
					classname = svgObject[i].getAttribute("className");
				@end @*/
				var objectInnerHTML = svgObject[i].innerHTML;
				// Must be one string because += doesn't work. The object close before the inner elements are put inside
									var linka = svgObject[i].parentNode.getAttribute("href");
									if(linka === null){
										linka = "http://www.gardo.nl";
									}
						 
				svgObject[i].innerHTML = '<object data="/catalogus/templates/gardo/flash/'+ classname +'.swf" type="application/x-shockwave-flash" class="'+ classname +'">' +
				'<param name="movie" value="/catalogus/templates/gardo//flash/'+classname+'.swf" />' +
				'<param name="wmode" value="transparent" />' + objectInnerHTML + '</object>';
	
			}	
		}
	}
};

/******************************************************************************
GARDO.Request module v1.0

AHAH is a very simple technique for dynamically updating web pages using JavaScript. 
It involves using XMLHTTPRequest to retrieve (X)HTML fragments which are then 
inserted directly into the web page, whence they can be styled using CSS.
See for more information: http://microformats.org/wiki/rest/ahah
* ******************************************************************************/

GARDO.Request = {
	ahah 			:	function(url,target) {
	   // native XMLHttpRequest object
	   document.getElementById(target).innerHTML = 'Bezig met laden.';
	   if (window.XMLHttpRequest) {
	       req = new XMLHttpRequest();
	       req.onreadystatechange = function() {GARDO.Request.ahahDone(target);};
	       req.open("GET", url, true);
	       req.send(null);
	   // IE/Windows ActiveX version
	   } else if (window.ActiveXObject) {
	       req = new ActiveXObject("Microsoft.XMLHTTP");
	       if (req) {
	           req.onreadystatechange = function() {GARDO.Request.ahahDone(target);};
	           req.open("GET", url, true);
	           req.send();
	       }
	   }
	},
	
	ahahDone		: 	function(target) {
		// Preloader
		document.getElementById(target).innerHTML += ".";
		
	    // only if req is "loaded"
	    if (req.readyState == 4) {
	        // only if "OK"
		    if (req.status == 200 || req.status == 304 || req.status == 0) {
		        results = req.responseText;
		        document.getElementById(target).innerHTML = results;
		    } else {
		        document.getElementById(target).innerHTML = "Er is een fout gevonden:\n" +
		                req.statusText;
	        }
	    }
	}
}

/******************************************************************************
GARDO.Photo module v1.0

Loads a large resolution photo based on the tumbernail photo
* ******************************************************************************/

GARDO.Photo = {
	tumbClick		:	function(){
		if(getElementsByClass("tumb")){
			var tumbs = getElementsByClass("tumb");
			for (var i = 0; i <tumbs.length; i++) {
				var tumb = tumbs[i].firstChild;
				tumb.onclick = function(){
					var imageDiv = document.createElement("div");
					var clientWidth = document.documentElement.clientWidth;
					var clientHeight = document.documentElement.clientHeight;
					imageDiv.style.padding = "1em";
					imageDiv.style.backgroundColor = "#000";
					imageDiv.style.position = "absolute";
					imageDiv.style.top = clientHeight/2- 250 +  document.documentElement.scrollTop + "px";
					imageDiv.style.left = clientWidth/2- 255  + "px";
					var bigImage = document.createElement("img");
					bigImage.style.display = "block";
					var bigImgURL = this.getAttribute("href")
					bigImage.setAttribute("src", bigImgURL);			
					var closeBigImage = document.createElement("a");
					closeBigImage.style.display = "block";
					closeBigImage.style.textAlign = "right";
					closeBigImage.style.backgroundColor = "#FFF";
					closeBigImage.style.padding = "0.5em";
					this.onclick = closeBigImage.onclick = function(){
						document.body.removeChild(imageDiv);
						GARDO.Photo.tumbClick();
						return false;
					}
					var closeText = document.createTextNode("sluiten");
					closeBigImage.setAttribute("title", "sluit deze afbeelding");
					closeBigImage.setAttribute("tabindex", "1");
					closeBigImage.setAttribute("href", "#");			
					imageDiv.appendChild(bigImage);
					closeBigImage.appendChild(closeText);
					imageDiv.appendChild(closeBigImage);
					document.body.appendChild(imageDiv);
					
					return false;
				}
			}
		}
	}
}

/******************************************************************************
GARDO.Location module v1.0

Only show the selected location
* ******************************************************************************/

GARDO.Location = {
	init		:	function() {
		var map = document.getElementById("map");
		if(map){
		var anchorLink = map.getElementsByTagName("a");
			for (var i=0; i < anchorLink.length; i++){	
				anchorLink[i].onclick = function(){
					var href = this.getAttribute("href");
					var vcardElm = href.substring(href.lastIndexOf("#") + 1);
					if(document.getElementById(vcardElm).style.display == "none"){
						document.getElementById(vcardElm).style.display = "block";		
					} else {
						document.getElementById(vcardElm).style.display = "none";		
					}
				}
			}
			
			var branchinfo = document.getElementById("branchinfo");
			var vcard = branchinfo.getElementsByTagName("li")
			for (var i=0; i < vcard.length; i++){	
				vcard[i].style.display = "none";
			}	
		}
	}
}

/******************************************************************************
GARDO.Collapse module v1.0

collapse information blocks
* ******************************************************************************/

GARDO.Collapse = {
	init		:	function() {
		var collapse = document.getElementById("taginformation");
		if(collapse){
			var info = collapse.getElementsByTagName("dd");
				for (var i=1; i < info.length; i=i+2){	
					info[i].style.display = "none";
				}
			var header = collapse.getElementsByTagName("dd");
			
			for (var i=0; i < header.length; i=i+2){	
				header[i].style.cursor = "pointer";
				var collapseLink = document.createElement("a");
				var moreIcon = document.createTextNode(" + ");
				
				/* a element must have a href element to tab to it */
				collapseLink.setAttribute("id", "link_" + i);
				//collapseLink.setAttribute("title", "Uitklappen/Inklappen " + header[i].previousSibling.previousSibling.firstChild.getAttribute("alt"));			
				collapseLink.setAttribute("href", document.URL +  "#link_" + i);
				
				collapseLink.style.fontSize = "0.8em";
				collapseLink.style.color = "#1CADD4";
				
				collapseLink.appendChild(moreIcon);
				header[i].appendChild(collapseLink);
				header[i].onclick = function(){
					var pElm = this.nextSibling.nextSibling;
					/*@cc_on @*/
					/*@if (@_jscript_version >= 5)	
						var pElm = this.nextSibling				
					@end @*/	
					if(pElm.style.display == "none"){
						pElm.style.display = "block";		
					} else {
						pElm.style.display = "none";		
					}
				}
			}
		}
	}
}


/******************************************************************************
GARDO.Validate module v1.0

Client side validation handling
* ******************************************************************************/

GARDO.Validate = {
	valide		: 	true,
	init		:	function(){
		
		if (document.getElementById("validate")){
			if(document.getElementById("date")){
				date = document.getElementById("date");
				date.value = "26/06/1981";
				date.style.color = "#CCC";
				date.onfocus = function() {
					if(date.value == "26/06/1981"){
						date.value = "";
						date.style.color = "#000";	
					}
				}
				date.onblur = function() {
					if(date.value == ""){
						date.value = "26/06/1981";
						date.style.color = "#CCC";							
					}
				}	
			}

			document.getElementById("submit").onclick = function(){
				var errors = getElementsByClass("error");
				for (var i = 0; i <errors.length; i++) {
					errors[i].innerHTML = "";
					errors[i].parentNode.style.backgroundColor = "#FFF";
					errors[i].parentNode.style.borderStyle = "none";
				}
				
				GARDO.Validate.valide = true;
				GARDO.Validate.doValidate();
				return GARDO.Validate.valide;
			}
		}
	},
	doValidate		:	function() {
		GARDO.Validate.input();
		if(document.getElementById("date")){
			GARDO.Validate.date();
		}
		if(document.getElementById("password") && document.getElementById("confirmation")){
			GARDO.Validate.password();
		}
		if(document.getElementById("email_address")){
			GARDO.Validate.email();
		}		
	},
	input		: 	function(){
		var inputElm = document.getElementById("validate").getElementsByTagName("input");
		for(var i=0; i < inputElm.length-1; i++){
			if (inputElm[i].value == "" && inputElm[i] !=  document.getElementById("date")){
				GARDO.Validate.createError(inputElm[i], "<p><em>Dit veld dient ingevuld te worden!</em></p>");
			} 
		}
	},
	date		:	function(){
		if(/^([0-9]){2}(\/){1}([0-9]){2}(\/)([0-9]){4}$/.test(document.getElementById("date").value) == false){
				GARDO.Validate.createError(document.getElementById("date"), "<p><em>Datum is ongeldig! Juist voorbeeld: 26/06/1981</em></p>");
			}
	},
	password	:	function(){
		if(document.getElementById("password").value != document.getElementById("confirmation").value){
			GARDO.Validate.createError(document.getElementById("confirmation"), "<p><em>Wachtwoord is niet het zelfde als de Wachtwoord bevestiging!</em></p>");			
		} else if(/^.{5,99}$/.test(document.getElementById("password").value) == false) {
			GARDO.Validate.createError(document.getElementById("password"), "<p><em>Wachtwoord dient minimaal 5 karakters te bevatten</em></p>");				
		}		
	},
	email		:	 function() {
		if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(document.getElementById("email_address").value) == false){
			GARDO.Validate.createError(document.getElementById("email_address"), "<p><em>E-mail adres is niet geldig!</em></p>");		
		}
	},
	createError	:	function(inputElm, errorMessage){

			var errorDiv = document.createElement("div");
			errorDiv.setAttribute("class", "error");
			inputElm.parentNode.appendChild(errorDiv);
	
			inputElm.parentNode.style.backgroundColor = "#FF9598";
			inputElm.parentNode.style.borderWidth = "1px";
			inputElm.parentNode.style.borderStyle = "solid";
			inputElm.parentNode.style.borderColor = "#F00";
			inputElm.parentNode.style.color = "#F00";

			errorDiv.innerHTML = errorMessage;
		

	
		GARDO.Validate.valide = false;
	}
}


/******************************************************************************
DOM Extension - getElementsByClass
http://www.dustindiaz.com/getelementsbyclass
* ******************************************************************************/


function getElementsByClass(searchClass,node,tag) {
	var classElements = new Array();
	if ( node == null )
		node = document;
	if ( tag == null )
		tag = '*';
	var els = node.getElementsByTagName(tag);
	var elsLen = els.length;
	var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
	for (i = 0, j = 0; i < elsLen; i++) {
		if ( pattern.test(els[i].className) ) {
			classElements[j] = els[i];
			j++;
		}
	}
	return classElements;
}



window.onresize = GARDO.Display.resize;
addLoadEvent(GARDO.Display.resize);
addLoadEvent(GARDO.SVG.checkSVG);
addLoadEvent(GARDO.Photo.tumbClick);
//addLoadEvent(GARDO.Location.init);
addLoadEvent(GARDO.Validate.init);
//addLoadEvent(GARDO.Collapse.init);

