var oldOnClickEvent; // added the construct because IE7 can't handle the onChange within a onClick
var activeSearchbox;
var selected = "kenteken";
var activeSearchbox;
var activeInfo = 0;
var totalSum = 0;
var selectorActive = 0;
var clDebug = 0; /* Flag for debugging over Firebug */

function showError(msg, value){
	//  if(window.console) console.log("msg="+ msg +" value="+ value);
	$('formSubmit').setStyle('display', 'none');
	$('searchStatus').set('html', msg);
	$('searchStatus').setStyle('display', 'block');
}

function startSearch(method){
  var t;
  
  if(activeSearchbox == "boxKenteken"){
    t = $('kenteken').value.trim(); 
  
    if(!(t.length==6 || t.length==8)){
      showError("Vul alstublieft een geldig kenteken in.", t);
      // $("kenteken").focus();
      // $("kenteken").tween('border', '1px dashed RED');
      return false;
    } 
  } else if(activeSearchbox == "boxMVS"){
    t = $('mvs').value.trim(); 
  
    if(t.length<7 || t.length>9){
      showError("Dit is helaas geen geldige MVS code.", t);
      // $("mvs").focus();
      // $("mvs").tween('border', '1px dashed RED');
      return false;
    }
  } else { // boxZoeken
    if($('zoekenModel').value==0){
      showError("Kies alstublieft een model.");
      // $("zoekenModel").focus();
    
    } 

/* SELECTOR
	else if($('zoekenModelType').value==0){
      showError("Kies alstublieft een type.");
      // $("zoekenModelType").focus();
      return false; 
    }
*/ 
 }
  
  var kmJaar = $("kmjaar").value.trim().toInt();
  if(!kmJaar || kmJaar=="NaN"){
    showError("Vul alstublieft een correct kilometeraantal in.");
    $("kmjaar").focus();
    return false; 
  } else { 
    $("kmjaar").value = kmJaar;
  }  
    
	$('formSubmit').setStyle('display', 'none');
	$('searchStatus').set('html', 'Een moment alstublieft...');
	$('searchStatus').setStyle('display', 'block');

	if($('tableComplete')){
		$('tableComplete').remove();
	}

	var myRequest = new Request({
		url: 'getParts.inc.php',
		data: {
		    "kenteken": encodeURI($("kenteken").value),
		    "mvs": encodeURI($("mvs").value),
		    "kmjaar": encodeURI( kmJaar),
		    "selected": encodeURI($("selected").value)
		},
		onComplete: doOnreadystatechange,

		//Execute scripts in the response text onComplete.
		evalScripts: true
	});
	myRequest.send();	
}

doOnreadystatechange = function(responseText, responseXML){
  if(typeof foundModel!="undefined" && foundModel!=0){
  	$('result').setStyle('display', 'block');
  	$('result').set('html', responseText);
  	$('tableComplete').injectInside('result');
  
    $('mvs').value = foundMVS;
    foundCar = "Resultaten voor <b>"+ foundModel +"</b> (Modelcode: "+ foundMVS +")";

	$('tableComplete').getElements('input').addEvent('click', function(e){
  		var tSum = new Number();
  		var form = $("tableComplete"); 
      
      	form.getElements("input[class=calculator]").each(function(el){	
  			if (el.checked) {
  				tSum += Number(el.value); // getValue());
  			}
  		});

  		// Number
  		cl('tSum', tSum);
  		$('calcSum').set('html', "Totaal: &euro; "+ tSum.toFixed(2));
  	});
  } else {
    foundCar = "Helaas, we konden geen passend model vinden, controleer alstublieft uw gegevens.</b>";
  }
					 
  $('searchStatus').set('html', foundCar);
};

OLDsetSearchMVS = function(mvsREF){
	prepareNewSearch();	

	// if(window.console) console.log("mvsREF.value="+ mvsREF.value);
	if(mvsREF.value!=0){
		setSelected('zoeken');
		$('mvs').setProperty('value', mvsREF.value);
	}
};

setSearchMVS2 = function(mvsREF){
	prepareNewSearch();	
	
	if(typeof mvsREF!=="undefined" && mvsREF.value!=0){
		// if(window.console) console.log("mvsREF.value="+ mvsREF.value);
		
		setSelected('zoeken');
		$('mvs').setProperty('value', mvsREF.value);
	}
};

function OLDstyleBox(which, mode){
	var myObj = document.getElementById(which);

	if(myObj){
		var color = (mode==1) ? "#333" : "#DDD";
		myObj.style.color = color;

		if(mode==0){
			myObj.value="";
		}
	}
}

searchbox = function(that){
	// remove choosen car and put default text back
	if(that.id !== 'boxZoeken'){
		$('zoekenModel').set('html', labels.NL.chooseCar);
		$('zoekenModel').setStyle('margin-top', '0');
	}

	if($(activeSearchbox)){
		$(activeSearchbox).removeClass('selected');
		var t = $(activeSearchbox).id;
			
	  	$(that.id).addClass('selected');
	  	activeSearchbox = that.id;
	} else if(activeSearchbox == 0) {
	  	$(that.id).addClass('selected');
	  	activeSearchbox = that.id;		
	}
}

setSearchbox = function(newId){
	if($(activeSearchbox)){
		$(activeSearchbox).removeClass('selected');
		
		if(activeInfo!=0){
			$("info_"+ activeInfo).setStyle('display', 'none');
			$("but_"+ activeInfo).removeClass('selected');
		}
			
	  	$(newId).addClass('selected');
	  	activeSearchbox = newId;
	}
}

setSelected = function(which){
	var myObj = document.getElementById("selected");
	prepareNewSearch();

	if(myObj){
		myObj.value = which;
	}
}

prepareNewSearch = function(){
	$('formSubmit').setStyle('display', 'inline');
	$('searchStatus').setStyle('display', 'none');
	$('result').innerHTML = " &nbsp; ";
}

showInfo = function(newId){  	
	if(activeInfo!=0){
		$("info_"+ activeInfo).setStyle('display', 'none');
		$("but_"+ activeInfo).removeClass('selected');
	}	
	
  	activeInfo = newId;
	$("info_"+ activeInfo).setStyle('display', 'block');
	$("but_"+ activeInfo).addClass('selected');
}


/* ---  SELECT --- */
init = function(){
	cl("init added");
	activeSearchbox = 0;
}
window.addEvent('domready', init);

var currentModel;
var currentType;
var currentCar;
var myLang = "NL";
var labels = new Array();
labels['NL'] = new Array();
labels['FR'] = new Array();

labels.NL.chooseCar = "Modellen lijst &#9660;";
labels.NL.chooseModel = "%1";
labels.NL.headerTypes = "Kies uw Type %1";

// flag for adding the events to the types
var addedEventsToTypes = 0;

cl = function(param, value){
	if(clDebug && window.console){
		var msg = param
	
		if(typeof value !== "undefined"){
			msg += "=\""+ value +"\"";
		}

		console.log(msg);
	}
}

// cl("labels.NL.chooseModel", labels.NL.chooseModel);
// cl("labels.NL.chooseModel replace", labels.NL.chooseModel.replace("%1", "Test") );

showModelTypesSelect = function(responseText, responseXML){
	// $('zoekenModelType').removeProperty('disabled');
	// $('zoekenModelType').setStyles('display: inline;');
	
	cl("currentModel="+ currentModel);
	cl("currentType="+ currentType);
	cl("currentCar="+ currentCar);
	
 	var header = "<li id=\"mvs_header\">"+ labels.NL.headerTypes.replace("%1", currentModel) +"</li>";
	
	$('listTypes').set('html', header + responseText);
	$('listModellen').setStyle('display', 'none');
	$('listTypes').setStyle('display', 'block');
	
	cl("showModelTypesSelect listTypes >"+ $('listTypes').getStyle('display')  );
	
	$('listTypes').getElements('li').addEvent('click',  function(){
		prepareNewSearch();	

		cl("---- setSearchMVS3 > this.value="+ this.id);	

		var newMVS = this.id.substring(4);
			
		// IE does not cope
		if(typeof this.currentType == "undefined"){
			currentType = this.innerText;
		} else {
			currentType = this.textContent;
		}
		
		showCurrentCar = currentCar = currentModel +" "+ currentType;
		
		if(showCurrentCar.length >= 33){
			$('zoekenModel').setStyle('margin-top', '-6px');

			if(showCurrentCar.length >= 57){
				showCurrentCar = showCurrentCar.substring(0, 52) +"...";
			}
		} else {
			$('zoekenModel').setStyle('margin-top', '0');
		}

		$('zoekenModel').set('text', showCurrentCar);

		if(typeof newMVS!=="undefined" && newMVS.value!=0){
			setSelected('zoeken');
			$('mvs').setProperty('value', newMVS);
			$('listTypes').setStyle('display', 'none');
			selectorActive=1;
		}
	});	

	if($('mvs_0')){
		$('mvs_0').removeEvents('click').addEvent('click', function(){ return false; });
	}	
	if($('mvs_header')){
		$('mvs_header').removeEvents('click').addEvent('click', function(){ return false; });
	}
};

showBoxModel = function(e){
	cl("showBoxModel listModellen >"+ $('listModellen').getStyle('display')  +" selectorActive="+ selectorActive);	
	
	if( $('listModellen').getStyle('display') == "block" || selectorActive==1){	
		cl("zoekenModelTypeNieuw block");	
	
		$('listModellen').setStyle('display', 'none');
		selectorActive = 0;
	} else {		
		cl("zoekenModelTypeNieuw none");
		
		$('listModellen').setStyle('display', 'block');
		
		if(!addedEventsToTypes){
			$('listModellen').getElements('li').addEvent('click', function(){
				cl("---- in added this.id >"+ this.id);
			
				setSelected('zoeken');
				
				// IE does not cope
				if(typeof this.textContent == "undefined"){
					currentModel = this.innerText;
				} else {
					currentModel = this.textContent;
				}
				
				$('zoekenModel').set('text', currentModel); //labels.NL.chooseModel.replace("%1", currentModel) );

				cl("showBoxModel this.value", this.value)

				var myRequest = new Request({
					url: 'getModel.inc.php',
					data: { 
						"ModelcodeRef": this.id
					},
					onComplete: showModelTypesSelect,

					//Execute scripts in the response text onComplete.
					evalScripts: true
				});
				myRequest.send();
			});
			
			addedEventsToTypes = 1;
			cl("addedEventsToTypes", addedEventsToTypes);
		}

		if($('model_0')){
			$('model_0').removeEvents('click').addEvent('click', function(){ return false; });
		}
		
		searchbox(e);
	}
}