var check_req;
function check_Initialize(){
	try{
		check_req=new ActiveXObject("Msxml2.XMLHTTP");
	}
	catch(e){
		try{
			check_req=new ActiveXObject("Microsoft.XMLHTTP");
		}
		catch(oc){
			check_req=null;
		}
	}
	if(!check_req&&typeof XMLHttpRequest!="undefined"){
		check_req= new XMLHttpRequest();
	}
}

function showMenu(){
     if(this.childNodes[1].style.display=="none") {
          this.childNodes[1].style.display="";
          this.childNodes[1].style.visibility="visible";
     }
     else {
          this.childNodes[1].style.display="none";
          this.childNodes[1].style.visibility="hidden";          
     }
}
// variable for the image object we are throwing around
var objId = '';
//change the opacity for different browsers
function changeOpac(opacity, id) {
    var notObject = id;
    if(typeof(notObject) != "object") 
         notObject = document.getElementById(id);
    if(typeof(notObject) != "undefined"){
         notObject.style.opacity = (opacity / 100);
         notObject.style.MozOpacity = (opacity / 100);
         notObject.style.KhtmlOpacity = (opacity / 100);
         notObject.style.filter = "alpha(opacity=" + opacity + ")";
    }
} 

// pretty fade in and out
function opacity(id, opacStart, opacEnd, millisec) {
    //speed for each frame
    var speed = Math.round(millisec / 100);
    var timer = 0;
    //determine the direction for the blending, if start and end are the same nothing happens
    if(opacStart > opacEnd) {
        for(i = opacStart; i >= opacEnd; i--) {
             if(typeof(id) == "object"){
                  objId = id;
                  setTimeout("changeOpac(" + i + ", objId );",(timer * speed));
             }
             else
                  setTimeout("changeOpac(" + i + ",'" + id + "');",(timer * speed));
            timer++;
        }
    } else if(opacStart < opacEnd) {
        for(i = opacStart; i <= opacEnd; i++){
             if(typeof(id) == "object"){ 
                  objId = id;
                  setTimeout("changeOpac(" + i + ", objId );",(timer * speed));
             }
             else
                  setTimeout("changeOpac(" + i + ",'" + id + "');",(timer * speed));
            timer++;
        }
    }
}

 

function addThirdImage(node) {
     var imgWidth = node.width;
     var imgHeight = node.height;
     if(imgHeight == 0 || imgWidth == 0){
          imgHeight = node.scrollHeight;
          imgWidth = node.scrollWidth;
     }
     if(imgHeight > 0 && imgWidth > 0){
          var ratio = imgHeight/imgWidth;
          if((ratio*280) > 185){ // check if the image is too high
               node.height = 185;
               node.width = ((1/ratio)*185);
          } else {
               node.width = 280;
               node.height = (280*ratio);
          }
     }
     
     changeOpac("0",node);
     node.style.display = "";
     opacity(node,0,100,1500);
} 
               

/**
* function removeChildren()
*
*/

function removeChildren(id, type){
	
	var addClassFlag = false; // if we need to add a class list, set to true
	var children = document.getElementById("choose"+type).childNodes;
	for(node in children){
		// also need to remove choosetype && choosemlg
		if(children[node].tagName != "UL" && addClassFlag == false)
			addClassFlag = true;
		if((children[node].tagName == "UL") && (children[node].attributes['id'] != (type+id))){ 
			addClassFlag = true;
			document.getElementById("choose"+type).removeChild(children[node]);
		}
	}
	return addClassFlag;
}

/**
* function getElementsByClassName(classname, node)
* 
* returns an array of all elements with classname and belonging to node.
* if node is not specified, node = body
*/

function getElementsByClassName(classname, node) {
   if(!node) node = document.getElementsByTagName("body")[0];
   var a = [];
   var re = new RegExp('\\b' + classname + '\\b');
   var els = node.getElementsByTagName("*");
   for(var i=0,j=els.length; i<j; i++)
        if(re.test(els[i].className))
        a.push(els[i]);
   return a;
}



function updateSelection(id, type, baseurl){
     
     // get the correct items from the event listeners
     var node = document.getElementById(type+id);
     if(type == 'type'){
		if(typeof(chosenType) != "undefined" && chosenType != id && chosenType != ''){
               if(null != document.getElementById("type"+chosenType)){
                    document.getElementById("type"+chosenType).style.backgroundColor = "transparent";
               }
          }
          
          chosenType = id;
          node.className = node.className + " selecteditem";
          node.parentNode.parentNode.firstChild.childNodes[1].innerHTML = "Geselecteerd: " + node.innerHTML; // set button innerhtml
          var typeDiv = document.getElementById('choosetype').firstChild;
          typeDiv.className = typeDiv.className + " selected";
          
          var mlgDiv = document.getElementById("choosemlg");
          mlgDiv.firstChild.childNodes[1].innerHTML = "KIES HET AANTAL KILOMETERS"; // reset mlg button inner html
          
          var choice = document.getElementById("yourchoice");
          var removeFlag = true;
          if(choice.hasChildNodes()){
               for(choices in choice.childNodes){
                    if(typeof(choice.childNodes[choices]) != "undefined"){
                         if(choice.childNodes[choices].id == "selecteer_uw_shortlease")
                              removeFlag = false
                   }
               }
               if(removeFlag){
               while(choice.hasChildNodes()){
                    choice.removeChild(choice.firstChild);
               }
                    var br = document.createElement("br");
                    var newH2 = document.createElement("h2");
                    newH2.innerHTML = "Uw shortlease in 3 stappen";
                    choice.appendChild(br);
                    choice.appendChild(newH2);
                    var br2 = document.createElement("br");
                    choice.appendChild(br2);
                    var newImage = new Image();
                    newImage.id = "selecteer_uw_shortlease";
                    choice.appendChild(newImage);
                    newImage.onload = new Function("opacity('selecteer_uw_shortlease',0,100,1500)"); 
                    newImage.src = baseurl + "/templates/alg/images/selecteer_uw_shortlease.jpg";
                    newImage.alt = "Uw shortlease in 3 stappen";
                    
                    changeOpac(0, "selecteer_uw_shortlease");
               }
          }
          // add old image back in
          
          
          // remove stylings for mlg
          document.getElementById('choosemlg').firstChild.className = "selbutton selbuttonActive";
          
          var children = document.getElementById("mlgul");
          if(typeof(chosenMLG) != "undefined"){
               for(node in children.childNodes){
                    if(typeof(children.childNodes[node]) != "undefined" && typeof(children.childNodes[node].style) != "undefined")
                         children.childNodes[node].style.backgroundColor = "transparent";
               }
               
          }
          chosenMLG = '';
          var mlgDiv = document.getElementById("choosemlg");
         
         mlgDiv.onclick = showMenu;
          
     } else if(type == 'mlg'){

          if(typeof(chosenMLG) != "undefined" && chosenMLG != id && chosenMLG != ''){
               document.getElementById("mlg"+chosenMLG).style.backgroundColor = "transparent";
          }
          chosenMLG = id;

          node.className = node.className + " selecteditem";
          node.parentNode.parentNode.firstChild.childNodes[1].innerHTML = "Geselecteerd: " + node.innerHTML; // set button innerhtml
          if(typeof(node.style) != "undefined")
               node.removeAttribute("style");
          var mlgDiv = document.getElementById('choosemlg').firstChild;
          mlgDiv.className = mlgDiv.className + " selected";
     } 
}


// this function sets the content for the page, whether it is div info
// or if it is iframe info
function set_content(type, target, content){
	if(type == 'div'){
		document.getElementById(target).innerHTML = content.replace(/\r|\n|\r\n/g,"");;
	} else if(type == 'iframe'){
		var div = document.getElementById(target);
		div.setAttribute('src', content);
		div.setAttribute('height', div.attributes['height'].value);
		div.setAttribute('width', div.attributes['width'].value);
          div.style.display = '';
	}
}

// add function to resize the fixed scroll table

function changeHeight(){
     var myHeight = 0;
     if( typeof( window.innerHeight ) == 'number' ) {
         //Non-IE
         myHeight = window.innerHeight;
     } else if(document.documentElement && document.documentElement.clientHeight) {
         //IE 6+ in 'standards compliant mode'
         myHeight = document.documentElement.clientHeight;
     } else if( document.body && document.body.clientHeight ) {
         //IE 4 compatible
         myHeight = document.body.clientHeight;
     }
     var scTable = document.getElementById("scrollContentContainer");
     var prcTable = document.getElementById("prices");
     var conHeight = document.getElementById("container").clientHeight;
     if(conHeight < myHeight) {
         // need to subtract 83px for the footer
         prcTable.style.height = (prcTable.clientHeight + (myHeight - conHeight)) - 83 + "px";
         scTable.style.height = (scTable.clientHeight + (myHeight - conHeight)) - 83 + "px";
     }
}

/**
* function gdCallback()
*
* This is the callback function for calls to get_data.php. This function will
* parse the data returned and modify the DOM accordingly.
* 
* @param JSON jsonObject The json object returned from the request
* 
*/
var chosenClass;
var chosenType;
var chosenMLG;



function chooseItem(item, id){
	switch(item){
		case 'class':
			chosenClass = id;
			break;
		case 'type':
			//chosenType = id;
			break;
		case 'mlg':
			chosenMLG = id;
			break
		default:
			alert('error!');
			break;
	}
	check_Initialize();
     
	var url = "<?php echo URI::base(); ?>/includes/get_data.php?item=" + item + "&id=" + id;
     if(item == "type") {
          url = url + "&typeid="+chosenType;
     }
	if(check_req!=null){
		check_req.onreadystatechange = function() {
			if(check_req.readyState == 4){
				if(check_req.status == 200){
					eval(check_req.responseText);
				} else {
					alert("error getting data");
				}
			}
		}
		check_req.open("GET", url, true);
		check_req.send(null);
	}
	
	
	
}
function gdCallback(jsonObject, type, baseurl){
	
	switch(type){
		case 'class': // check if there is a selection, remove it
			if(document.getElementById("chooseclass").hasChildNodes()){
				var addClassFlag = false; // if we need to add a class list, set to true
				var children = document.getElementById("chooseclass").childNodes;
				addClassFlag = removeChildren(chosenClass, 'class');
				removeChildren('', 'type');
				removeChildren('', 'mlg');
                    
                    var choice = document.getElementById("yourchoice");
                    var removeFlag = true;
                    if(choice.hasChildNodes()){
                         for(choices in choice.childNodes){
                              if(typeof(choice.childNodes[choices]) != "undefined"){
                                   if(choice.childNodes[choices].id == "selecteer_uw_shortlease")
                                        removeFlag = false
                              }
                         }
                         if(removeFlag){
                              while(choice.hasChildNodes()){
                                   choice.removeChild(choice.firstChild);
                              }
                              var br = document.createElement("br");
                              var newH2 = document.createElement("h2");
                              newH2.innerHTML = "Uw shortlease in 3 stappen";
                              choice.appendChild(br);
                              choice.appendChild(newH2);
                              var br2 = document.createElement("br");
                              choice.appendChild(br2);
                              var newImage = new Image();
                              newImage.id = "selecteer_uw_shortlease";
                              newImage.src = baseurl + "/templates/alg/images/selecteer_uw_shortlease.jpg";
                              newImage.alt = "Uw shortlease in 3 stappen";
                              choice.appendChild(newImage);
                              changeOpac(0, "selecteer_uw_shortlease");
                              newImage.onload = new Function("opacity('selecteer_uw_shortlease',0,100,1500)");
                         }
                    }
                    
                    var typeDiv = document.getElementById("choosetype"); // reset the inner 
                    typeDiv.firstChild.childNodes[1].innerHTML = "KIES EEN AUTO";
                    var mlgDiv = document.getElementById("choosemlg");
                    mlgDiv.firstChild.childNodes[1].innerHTML = "KIES HET AANTAL KILOMETERS";
                    
				if(addClassFlag){ // need to add type and mlg selections
					var classDiv = document.getElementById("chooseclass");
                         
					// create the class ul. it's only one li, but use ul for styling
					var classUlist = document.createElement("ul");
					classUlist.setAttribute('id','class'+chosenClass);
					var classLitem = document.createElement("li");
					classLitem.innerHTML = jsonObject[chosenClass][0]['CLSNAME'];
					classUlist.appendChild(classLitem);
                         
					// append the ul to the class div
					var clsSelected = getElementsByClassName("selbutton",classDiv);
                         if(typeof(clsSelected) != "undefined"){
                              currClass = clsSelected[clsSelected.length-1].className;
                              clsSelected[clsSelected.length-1].className = currClass + " selected";
                              clsSelected[clsSelected.length-1].childNodes[1].innerHTML = "Geselecteerd: Klasse " +jsonObject[chosenClass][0]['CLSNAME'];
                         }
                         
					// add types ul
					var typeUlist = document.createElement("ul");
                         
                         typeUlist.style.display = 'none';
                         typeUlist.style.visibility = "hidden";
                       
                         typeDiv.onclick = showMenu;
					typeUlist.setAttribute('id','typeul');
                         
                         
					for(types in jsonObject[chosenClass]){
						var typeLitem = document.createElement("li");
                              
						typeLitem.innerHTML = jsonObject[chosenClass][types]['BNDNAME'] + " " + jsonObject[chosenClass][types]['MDLNAME'];
                              if(null != jsonObject[chosenClass][types]['NAME'])
                                   typeLitem.innerHTML = typeLitem.innerHTML + " " + jsonObject[chosenClass][types]['NAME'];
                               
                              typeLitem.setAttribute('id', "type" + jsonObject[chosenClass][types]['TYP_ID']);
                              typeLitem.onclick = new Function("updateSelection("+jsonObject[chosenClass][types]['TYP_ID']+", 'type','<?php echo URI::base(true); ?>');");
						typeUlist.appendChild(typeLitem);
					}
					var typeDiv = document.getElementById("choosetype");
                         
                         typeDiv.appendChild(typeUlist);
                         
                         typeDiv.firstChild.className = "selbutton selbuttonActive";
                         
                         // add mileage
					var mlgUlist = document.createElement("ul");
                         
					mlgUlist.setAttribute('id', 'mlgul');
                         
                         mlgUlist.style.display = 'none';
                         mlgUlist.style.visibility = 'hidden';
					
					for(mlgs in jsonObject['MLG']){
						var mlgLitem = document.createElement("li");
						mlgLitem.innerHTML = jsonObject['MLG'][mlgs]['NAME'];
						mlgLitem.setAttribute('id','mlg'+jsonObject['MLG'][mlgs]['MLG_ID']);
						mlgLitem.onclick = new Function("updateSelection("+jsonObject['MLG'][mlgs]['MLG_ID']+",'mlg','<?php echo URI::base(true); ?>'); chooseItem('type',"+jsonObject['MLG'][mlgs]['MLG_ID']+")");
						mlgUlist.appendChild(mlgLitem);
					}
					var mlgDiv = document.getElementById("choosemlg");
                         mlgDiv.firstChild.className = "selbutton";
                         mlgDiv.appendChild(mlgUlist);

				}
			}
               Shadowbox.close();
			break;
          case 'type': // if we get this command, we want to choose a type and load it into 
                         //the right place on the page. This command is executed when you choose a mileage
                         // from the three step
		
               var yourChoice = document.getElementById("yourchoice");
          
               if(document.getElementById("yourchoice").hasChildNodes()){
                    var choice = document.getElementById("yourchoice");
                    while(choice.hasChildNodes()){
                         choice.removeChild(choice.firstChild);
                    }
               }
                          
               var header = document.createElement("h2");
               header.innerHTML = 'uw keuze';
               
               var carName = document.createElement("h2");
               var cName = jsonObject['BNDNAME'] + " " + jsonObject['MDLNAME'];
               if(null != jsonObject['NAME'])
                    cName = cName + " " +jsonObject['NAME'];
               carName.innerHTML = cName; 
               
               var leasePrice = document.createElement("p");
               var table = '';
               var rowCount = 0;
               for(fuel in jsonObject['PRICE']){
                    table = table + "<tr>";
                    if(rowCount == 0)
                         table = table + "<td>Leaseprijs:&nbsp;</td>";
                    else
                         table = table + "<td>&nbsp;</td>";
                    table = table + "<td>" + fuel + "</td><td>" + jsonObject['PRICE'][fuel]['PRICE'] + "&nbsp;(per maand)</td>";
                    table = table + "</tr>";
                    rowCount ++;
               }
               leasePrice.innerHTML = "<table class='fuelPrice' cellspacing='0' cellpadding='0' style='margin:0px;padding:0px;display:inline;font-size:12px;'>" + table + "</table>";
               
               var img = new Image();
               var altNew = jsonObject['MDLNAME'];
               if(null != jsonObject['NAME'])
                    altNew = altNew + " " + jsonObject['NAME'];
               img.alt = altNew;
               img.id = "image123";
               img.onclick = new Function("buildGallery('"+jsonObject['IMG_NAME']+"','"+jsonObject['IMG_ID']+"', '"+jsonObject['PATH']+jsonObject['URL_LARGE']+"')");
               img.style.display = "none";
               
               
               var node = document.getElementById("yourchoice");
               var offerDiv = document.createElement("div");
               offerDiv.className = "buttonLink";
               var offerA = document.createElement("a");
               offerA.innerHTML = "offerte aanvragen";
               offerA.setAttribute('href',baseurl + "/index.php/offerte_aanvragen/?rqtype=req&class="+chosenClass+"&type="+chosenType+"&mileage="+chosenMLG);
               offerA.setAttribute('href',baseurl + "/index.php/offerte_aanvragen/?rqtype=req&class="+chosenClass+"&type="+chosenType+"&mileage="+chosenMLG);
               offerDiv.appendChild(offerA);
                 
                 node.appendChild(header);
                 node.appendChild(img);
                 img.onload = new Function("addThirdImage(this);");
                 img.src = jsonObject['PATH'] + jsonObject['URL_LARGE'];
                 node.appendChild(carName);
                 node.appendChild(leasePrice);
                 node.appendChild(offerDiv);
                 break;
               default:
                    break;

	}
	
}


/**
* function chooseItem
* 
* This function sends an ajax request to update the 3 step on the front page
*/ 

function chooseItem(item, id){
	switch(item){
		case 'class':
			chosenClass = id;
			break;
		case 'type':
			//chosenType = id;
			break;
		case 'mlg':
			chosenMLG = id;
			break
		default:
			alert('error!');
			break;
	}
	check_Initialize();
     
	var url = "<?php echo URI::base(); ?>/includes/get_data.php?item=" + item + "&id=" + id;
     if(item == "type") {
          url = url + "&typeid="+chosenType;
     }
	if(check_req!=null){
		check_req.onreadystatechange = function() {
			if(check_req.readyState == 4){
				if(check_req.status == 200){
					eval(check_req.responseText);
				} else {
					alert("error getting data");
				}
			}
		}
		check_req.open("GET", url, true);
		check_req.send(null);
	}
	
	
	
}

function windowPop(url){
	if(url.match(/[a-zA-Z0-9]+\.[a-zA-Z0-9]+/)){ // check if it is a url link
		if(!url.match(/http/)) // if it already has http in front, don't add it
			url = "http://" + url;
	}
	else
		url = baseurl + "/index.php/"+url; // else it's a link on the page
	window.open(url, "New Window", '<?php echo get_pop_prop(); ?>');
}
function detectBrowser(){
BrowserDetect.init();
     if(BrowserDetect.browser.toLowerCase() == "safari" && BrowserDetect.version == "3"){ // fix safari margin and padding
          var searchbox = document.getElementById('searchBox');
          searchbox.setAttribute("style", "background:url(<?php echo URI::base(true); ?>/templates/alg/images/shortlease_navbalk.png) left no-repeat; padding:12px 0 12px 0; margin-top: -18px; padding-top: 30px;");
     }
      if(BrowserDetect.browser.toLowerCase() == "safari" && BrowserDetect.version == "4"){
           var searchbox = document.getElementById('searchBox');
           searchbox.setAttribute("style", "background:url(<?php echo URI::base(true); ?>/templates/alg/images/shortlease_navbalk.png) left no-repeat; padding:12px 0 12px 0; margin-top: -11px; padding-top: 30px;");
      }
}
