/**** SimpleSearch ***/

/**
 * Get Carross Values
 * 
 * @return array
 */
function getCdcarrossValues() {
	var checked_values = new Array();
	$$("li#carros input[type=checkbox]").each(function(c) { 
		if(c.checked == true)
			checked_values.push(c.value); 
	})
	
	return checked_values;
}

/**
 * Update form with xhttpRequest
 * 
 * @param JSON xhr
 */
function refreshForm(xhr, which_field) {
	/************ Nb vehicules ****/
	$("preview_nb_result").innerHTML = xhr.nbVehicules;
	
	/************ Marques ****/
	if (which_field == "all" || which_field == "marque")
	{
		update_select($("marque"), xhr.cdmarque);
	}
	/************ Modèles ****/
	if (which_field == "all" || which_field == "modele")
	{
		update_select($("modele"), xhr.cdgamme);
	}
	/************ Carburant ****/
	if (which_field == "all" || which_field == "carburant")
	{
		update_select($("carburant"), xhr.modeles_cdcarbur);
	}
	
	/************ button href ****/
	var target = $("rechercher").readAttribute('target');
	if(target != null)
	{
		$("rechercher").onclick = function(){ ($("rechercher").readAttribute('target') == 'top' ? top : document ).location = xhr.url_for_search  };
	}
	/************ Bouton alerte arrivage **/
	$("btn_save_alerte_arrivage").remove();
}

function reset_select(o_select) {
	try {
		/*reset element*/
		o_select.childElements().each(function(c) {
			if(c != o_select[0])	
				c.remove();
		});
	} catch (ex) {
	}
}

/**
 * Update select tag with JSON data
 * 
 * @param obj o_select
 * @param json a_json_select
 */
function update_select(o_select, a_json_select) {
	var is_selected = false;
	
	reset_select(o_select);
	
	try {
		a_json_select.each(function(r) {
			var new_option 		= document.createElement("option");
			
			if(r.optgroup) {
				new_option.appendChild(document.createTextNode(r.optionLabel)); 	// IE only
			} else {
				new_option.text = r.optionLabel;									// standards compliant; doesn t work in IE
			}
			
			if(r.selected == 1) {
				is_selected = true;
			}
			
			
			try {
				if(r.optgroup) {
					my_optgroup = false;
					
					ao_optgroup = o_select.getElementsByTagName("optgroup");
					
					try {
						for (var i = 0; i < ao_optgroup.length; i++) {
							if(ao_optgroup[i].label == r.optgroup) {
								my_optgroup = ao_optgroup[i];
							}
						}
					} catch (ex) {
					}
					
					if(!my_optgroup) {
						my_optgroup 		= document.createElement("optgroup");
						my_optgroup.label 	= r.optgroup;
						o_select.appendChild(my_optgroup);
						
					}
					
					my_optgroup.appendChild(new_option);
					
				} else {
					try {
						o_select.add(new_option, null); 	// standards compliant; doesn t work in IE
					} catch(ex)	{
						o_select.add(new_option); 		// IE only
					}
				}
			} catch(ex) {
			}
			
			/** Values setting at the end for IE6 **/
			new_option.value 	= r.optionValue;
			new_option.selected = r.selected;
		});
	
	} catch (ex) {
	}
	
	try {
	
		if(is_selected == false) {
			o_select.options[0].selected = true;
			update_select_text(o_select, true);
		} else {
			update_select_text(o_select);
		}
	} catch (ex) {
	}
}

/**
 * Select an option in select tag or the first one if undefined
 * 
 * @param obj o_select
 * @param str value2select
 * @return true
 */
function selectValue(o_select, value2select) {
	try {
		if( value2select == null || value2select == "" ) {
			o_select.options[0].selected = true;
		} else {
			o_select.getElementsBySelector("options").each(function(item) {
				if(item.value == value2select)
					return item.selected = true;
			});
			update_select_text(o_select);
		}
	} catch (ex) {
	}
}
	

/**
 * Reset the form and select none or param filled
 * 
 * @param str cdmarque
 * @param str cdgamme
 * @param str modeles_cdcarbur
 * @param str budget
 * @param array a_modeles_cdcarross
 */
function resetForm(cdmarque, cdgamme, modeles_cdcarbur) {
	selectValue($("marque"), cdmarque);
	selectValue($("modele"), cdgamme);
	selectValue($("carburant"), modeles_cdcarbur);
}

function disableAllCarrosserie() {
	$$("li#carros input[type=checkbox]").each(function(c) {	
		c.disable();
	});
	
	$$("label").each(function(c) { c.setOpacity(0.5); });
}




/*********************************/
/* Manage history library */
/*********************************/

/**
 * Add listener to swfadress event
 */
if( typeof( SWFAddress ) != "undefined" )
{
	SWFAddress.addEventListener(SWFAddressEvent.CHANGE, handleSWFAddressChange);
}

/**
 * Add a new url to the ajax history
 * 
 * @author  Christophe Dolivet
 * @since   1.0 - 21 janv. 09 - Christophe Dolivet
 * @version 1.0 - 21 janv. 09 - Christophe Dolivet
 */
function addNewHistoryUrl( newHistoryUrl )
{
	if( typeof( SWFAddress ) != "undefined" )
	{
		SWFAddress.setValue( newHistoryUrl );
	}
}


/**
 * Manage change detected by swfAdresse
 */
function handleSWFAddressChange(event) {
	
	// check that we have no "noredirect" option
	if( window.location.search.search(/(\?|&)noRedirect(=|&|$)/i) != -1 )
		return;
	
	// get url parameters
	var parameters = '';
	for (var p in event.parameters) {
	    parameters += '&' + p + '=' + event.parameters[p];
	}
	if( parameters.substr( 0, 1) == '&' )
		parameters= '?' + parameters.substr( 1 );

	var path	=  event.path + parameters;
	if( path.substr( 0, 1 ) == '/' )
		path	= path.substr( 1 );

	if( typeof( changeHashUrl ) != "undefined" )
	{
		changeHashUrl( path );
	}
}

function addToFavorite(_url, _titre) {
	if (navigator.appName != 'Microsoft Internet Explorer') {
		window.sidebar.addPanel(_titre, _url, "");
	}
	else if (typeof (window.external.AddToFavoritesBar) != "undefined") { //IE8
		window.external.AddToFavoritesBar(_url, _titre);
	}
	else { // Other IE browser
		window.external.AddFavorite(_url, _titre);
	}
}

/**
 * Fill area with 'text' after replacing %l_s_NOM% and %l_s_PRENOM% of IES cookie
 */
function writeTextWithIESCookie(id, text)
{
	key = 'IES=';
	a_infos_cookie = Array();
	a_infos_cookie['l_s_APPELATION'] = '';
	a_infos_cookie['l_s_NOM'] = '';
	a_infos_cookie['l_s_PRENOM'] = '';
	a_infos_cookie['l_s_EmailAddress'] = '';
	a_infos_cookie['l_s_ADRESSE1'] = '';
	a_infos_cookie['l_s_CODEPOSTAL'] = '';
	a_infos_cookie['l_s_VILLE'] = '';
	a_infos_cookie['l_s_TEL2'] = '';
	a_infos_cookie['l_s_DATE_LIV_SOUHAIT'] = '';
	a_infos_cookie['l_s_NEWSLETTER'] = '';

	var is_exist_ies_cookie = false;
	document.cookie.split(';').invoke('strip').each(function(this_cookie){
        if (this_cookie.startsWith(key)) {
        	is_exist_ies_cookie = true;

	        value_cookie = unescape(this_cookie.substring(key.length, this_cookie.length));
            a_infos_cookie_get = value_cookie.toQueryParams();
            Object.keys(a_infos_cookie_get).each(function(cle){
            	a_infos_cookie[cle] = Url.encode(a_infos_cookie_get[cle]);
            });
            
            throw $break;
        }   
    });

	if( is_exist_ies_cookie )
	{
		if( a_infos_cookie['l_s_NOM'] == '' || a_infos_cookie['l_s_PRENOM'] == '' )
		{
			return false;
		}
		
		text = text.replace(/%l_s_PRENOM%/g, Url.decode(a_infos_cookie['l_s_PRENOM'].capitalize()));
		text = text.replace(/%l_s_NOM%/g, Url.decode(a_infos_cookie['l_s_NOM'].toUpperCase()));
		
		$(id).innerHTML = text;
	}

}

function goTo(url) {
	document.location.href=url;
	return false;
}


function afficheTri()
{
	$('ul_liste').toggle();
}

