// mod choix_voiture javascript functions
var kscl = { serie:'', model:'',anne:'',typ:'',cv:''}

var GETDATA = new Array();

sGet = window.location.search;
if (sGet) { // if has a value...

  // Drop the leading "?"
  sGet = sGet.substr(1);
  sNVPairs = sGet.split("&");
  for (var i = 0; i < sNVPairs.length; i++)
  {
      // So, sNVPairs[i] contains the current element...
      // Split it at the equals sign.
      sNV = sNVPairs[i].split("=");
      // Assign the pair to the GETDATA array.
      sName = sNV[0];
      sValue = sNV[1];
      GETDATA[sName] = sValue;
  }
}


function kscl_init() {
  
  // object detection
  if (!document.getElementById) return;
  
  
  // remove go button on car selector form
  sub_btn = document.getElementById('ks_submit');
  if (sub_btn) sub_btn.style.display = 'none';
  
  // set nojs field to 0
  if ( document.ks_choix_voiture && document.ks_choix_voiture.nojs ) document.ks_choix_voiture.nojs.value = '0';
  
  // cancel normal form submition
  
  // get data from cookie
  cookiestring = kscl_readcookie();
  //alert(cookiestring);
  if (cookiestring != undefined) eval('kscl = ' + cookiestring);
  //alert('after eval line 23 ' + kscl.toSource());
  
  // get data from querystring
  readQueryVars();
  
  
  //alert('after readQV line 29 ' + kscl.toSource());
  
}


function ks_serie_selected(serie) {

  kscl.serie = serie;

  // delete the anne, type, & cv select boxes
  document.getElementById('ajax_ks_carros').innerHTML = '';
  document.getElementById('ajax_ks_typ').innerHTML = '';
  
  // if --choisir-- is set delete the model select
  if (kscl.serie == '') {
    document.getElementById('ajax_ks_model').innerHTML = '';
  }
  else {
    // replace the last select with a button
    //kscl_btn_ajax('choix_voiture/ajaxrequest.php?btn=serie&cPath=' + GETDATA['cPath'] + '&ks_serie=' + kscl.serie , 'ajax_ks_serie');
    // get next select box and insert it into the page
    kscl_getajax('choix_voiture/ajaxrequest.php?select=model&cPath=' + GETDATA['cPath'] + '&ks_serie=' + kscl.serie , 'ks_model');
    
  }
}


function ks_model_selected(model) {
  kscl.model = model;
  
  // delete the type & cv select boxes
  document.getElementById('ajax_ks_carros').innerHTML = '';
  
  // if --choisir-- is set delete the anne select
  if (kscl.model == '') {
    document.getElementById('ajax_ks_typ').innerHTML = '';
  }
  else {
     // replace the last select with a button
    ajaxurl = 'choix_voiture/ajaxrequest.php?btn=model&cPath=' + GETDATA['cPath'] + '&ks_serie=' + kscl.serie + '&ks_model=' + kscl.model;
    //alert(ajaxurl);
    //kscl_btn_ajax(ajaxurl, 'ajax_ks_model'); 
    // get next select box and insert it into the page
    kscl_getajax('choix_voiture/ajaxrequest.php?select=typ&cPath=' + GETDATA['cPath'] + '&ks_serie=' + kscl.serie + '&ks_model=' + kscl.model, 'ks_typ');

  }
}

function ks_typ_selected(typ) {

  kscl.typ = typ;
    
  // if --choisir-- is set delete the cv select
  if (kscl.typ == '') {
    document.getElementById('ajax_ks_carros').innerHTML = '';
  }
  else { 
    // replace the last select with a button
    //kscl_btn_ajax('choix_voiture/ajaxrequest.php?btn=typ&cPath=' + GETDATA['cPath'] + '&ks_serie=' + kscl.serie + '&ks_model=' + kscl.model + '&ks_typ=' + kscl.typ, 'ajax_ks_typ');
    // get next select box and insert it into the page
    kscl_getajax('choix_voiture/ajaxrequest.php?select=carros&cPath=' + GETDATA['cPath'] + '&ks_serie=' + kscl.serie + '&ks_model=' + kscl.model + '&ks_typ=' + kscl.typ, 'ks_carros' );

  } 
}



function ks_carros_selected(carros) {

  kscl.carros = carros;
  document.ks_choix_voiture.submit();
    // replace the last select with a button
    //kscl_btn_ajax('choix_voiture/ajaxrequest.php?btn=carros&ks_serie=' + kscl.serie + '&ks_model=' + kscl.model + '&ks_typ=' + kscl.typ + '&ks_carros=' + kscl.carros, 'ajax_ks_carros');

  if (kscl.carros != '') { 
      //kscl_writecookie();
      document.ks_choix_voiture.submit();
  }
}

function ks_mag_on(i) {
  var popup_cont = document.getElementById('ks_popup_container');
  if (popup_cont) popup_cont.innerHTML = '<img src="../images/m-'+ i +'.jpg" alt="'+ i.toUpperCase() +'" /><br />' + i.toUpperCase();
}

function ks_mag_off() {
  var popup_cont = document.getElementById('ks_popup_container');
  if (popup_cont) popup_cont.innerHTML = '';
}

// ----- private functions ------ //


function kscl_getajax(url,id_elem) {

  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) {
        // no ajax submit form normally
        document.ks_choix_voiture.submit();
      }
    }
  }
  
  // get result from server & inject results into page
  xmlHttp.open("GET",url,true);
  xmlHttp.onreadystatechange=function() {
    if(xmlHttp.readyState==4) {
			if (xmlHttp.responseText == '') {
				
				document.ks_choix_voiture.submit();
				return;
			}
      selectcontainer = document.getElementById('ajax_' + id_elem);
      selectcontainer.innerHTML =  xmlHttp.responseText;
      
      //check to see if cust is changing car and call the next func if nessessary
      if (kscl.changecar == 1) {
        
        objmember = id_elem.substring(3, id_elem.length);

        // select the correct result
        selectelem = document.ks_choix_voiture.elements[id_elem];
        if (selectelem) {
          selectelem.value = kscl[objmember];
          // call next function
          eval(id_elem + '_selected("' + kscl[objmember] + '");');
        }
      }
      else {
        // check length and select model if only 1 option
        selectelem = document.ks_choix_voiture.elements[id_elem];
        if (selectelem) {
          if(selectelem.options.length == 2) {  // option --chosir-- + one other option
            // select the option
            selectelem.selectedIndex = 1;
            // get next select box 
            funcname = id_elem + '_selected';
            eval(funcname + '("' + selectelem.value + '");');
          }
        }
        else { 
          typ_divs_holder = document.getElementById('kscl_typs_holder');
          //typ_divs_holder = document.getElementById('ajax_ks_typ');
          if (typ_divs_holder) { 
            typ_divs = typ_divs_holder.getElementsByTagName('div'); 
            if ( typ_divs.length == 1 ) {                     
              //typ_divs[0].onclick();
            }
          } 
        }
      } 
    }
  }
  xmlHttp.send(null); 
}

function kscl_btn_ajax(url, id_elem) {

  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) {
        // no ajax do nothing
      }
    }
  }
  
  // get result from server & inject results into page
  xmlHttp.open("GET",url,true);
  xmlHttp.onreadystatechange=function() {
    if(xmlHttp.readyState==4) {
       
      btn_container = document.getElementById(id_elem);
      btn_container.innerHTML =  xmlHttp.responseText;
      btn_container.className = 'ks_pval';
    }
  }
  xmlHttp.send(null);
}

function kscl_writecookie() {
  
  //set the values to a json string
/*
  cookieval = '{ serie:"' + kscl.serie + 
                '",model:"' + kscl.model + '",anne:"' + kscl.anne + 
                '",typ:"' + kscl.typ + '",cv:"' + kscl.cv + '" }';
*/
  cookieval = kscl.toSource();  
  setCookie('kscl', cookieval, 365, '/');	                
}

function kscl_readcookie() {
  cookieval = getCookie( 'kscl' );
  if (cookieval) 
  return cookieval;
}

function setCookie( name, value, expires, path, domain, secure ) {
	var today = new Date();
	today.setTime( today.getTime() );
	if ( expires ) {
		expires = expires * 1000 * 60 * 60 * 24;
	}
	var expires_date = new Date( today.getTime() + (expires) );
	document.cookie = name+'='+escape( value ) +
		( ( expires ) ? ';expires='+expires_date.toGMTString() : '' ) + //expires.toGMTString()
		( ( path ) ? ';path=' + path : '' ) +
		( ( domain ) ? ';domain=' + domain : '' ) +
		( ( secure ) ? ';secure' : '' );
}

function getCookie( name ) {
	var start = document.cookie.indexOf( name + "=" );
	var len = start + name.length + 1;
	if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) {
		return null;
	}
	if ( start == -1 ) return null;
	var end = document.cookie.indexOf( ';', len );
	if ( end == -1 ) end = document.cookie.length;
	return unescape( document.cookie.substring( len, end ) );
}

function deleteCookie( name, path, domain ) {
	if ( getCookie( name ) ) document.cookie = name + '=' +
			( ( path ) ? ';path=' + path : '') +
			( ( domain ) ? ';domain=' + domain : '' ) +
			';expires=Thu, 01-Jan-1970 00:00:01 GMT';
}

function readQueryVars() {
  var query = window.location.search.substring(1);
  var parms = query.split('&');
  for (var i=0; i<parms.length; i++) {
    var pos = parms[i].indexOf('=');
    if (pos > 0) {
      var key = parms[i].substring(0,pos);
      var val = parms[i].substring(pos+1);
      //alert('key='+key+' val='+val);
      if (key == 'ks_serie') kscl.serie = val;
      if (key == 'ks_model') kscl.model = val;
      if (key == 'ks_typ') kscl.typ = val;
      if (key == 'ks_carros') kscl.carros = val;
    }
  }
  
}
/**
*
* UTF-8 data encode / decode
* http://www.webtoolkit.info/
*
**/

var Utf8 = {

    // public method for url encoding
    encode : function (string) {
        string = string.replace(/\r\n/g,"\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) {

            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }

        return utftext;
    },

    // public method for url decoding
    decode : function (utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;

        while ( i < utftext.length ) {

            c = utftext.charCodeAt(i);

            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else if((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i+1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = utftext.charCodeAt(i+1);
                c3 = utftext.charCodeAt(i+2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }

        }

        return string;
    }

}

function ksmovebox() {
/*
	if (!document.getElementById) return;
	var cvo = document.getElementById('ks_cvc_outer');
	if (!cvo) return;
	cvo.style.position = 'fixed';
	cvo.style.top = '150px';
	cvo.style.backgroundColor = '0235EF';
*/
}

xAddEventListener(window, 'load', kscl_init, false);

