/*
 * DEALER LOCATOR AJAX PARTIE CLIENT
 */

var url = "DLAjaxServlet";

var COUNTRY = "country";
var REGION = "region";
var DEPARTMENT = "department";
var CITY = "city";
var ZIPCODE = "zipcode";

var VALIDATE = "btvalider";

/*
 * Sur chargement du formulaire on evalue les combo qui doivent disabled
 */
function dl_init()
{
    evaluateCombos([COUNTRY, REGION, DEPARTMENT, CITY]);
    evaluateValider();

	// GBN : Remise à vide des champs du formulaire à l'initialisation
	// resetCombos();
	// resetInput();

        // reselect
        var node = $(COUNTRY);
        if (node != null && node != undefined && node.options.length == 2 && node.options.selectedIndex != 1) {
	        node.options.selectedIndex = 1;
	        try {
    	        eval('countryChanged()');
        	} catch(ex) {
	            //On peut avoir une exception si la mÃ©ode n'existe pas
    	    }
    	}
}

function resetInput(){
	$(ZIPCODE).value = "";
}

function resetCombos(){
	$(REGION).options.length = 0;
	$(DEPARTMENT).options.length = 0;
	$(CITY).options.length = 0;
}

function evaluateValider()
{
    function selectionDone(param) {
        var target = $(param);
        var result = false;
        
        if (target == null) { result = false; }
        
    	if (target != null && target.options.selectedIndex != 0 && target.value != "") {
    		result = true;
    	}
        return result
    };
    
    function inputDone(param) {
        var target = $(param);
        var result = false;
        if (target == null) {
        	result = true;
        }
    	if (target != null && target.value != "") {
    		result = true;
    	}
        return result
    };
    
    if (selectionDone(COUNTRY)
    	|| selectionDone(REGION)
    	|| selectionDone(DEPARTMENT) 
    	|| selectionDone(CITY) 
    	|| inputDone(ZIPCODE))
    {
		$(VALIDATE).disabled = false;
        $(VALIDATE).style.backgroundColor='#FFFFFF';
        
   	} else {
    	var target = $(VALIDATE);
    	if (target != null) {
    	   	target.disabled = true;
    	    $(VALIDATE).style.backgroundColor='#C5C9D6';
    	}
    }
}


function evaluateCombos(params)
{
    for (var i = 0; i < params.length; i++)
    {
        evaluateCombo(params[i]);
    }
}

function evaluateCombo(comboId)
{
   
    var target = $(comboId);
    
    if (target != null && target.options.length <= 1) {
        target.disabled = true;
        target.style.backgroundColor='#C5C9D6';
    }
    if (target != null && target.options.length > 1) {
        target.disabled = false;
        target.style.backgroundColor='#FFFFFF';
    }
}

/*
* Fonction qui déselectionne la combo et la met en attente
*/
function deselectAndPauseCombo(comboId)
{
    var target = $(comboId);
    if (target != null) {
		// vidage de la combobox
		target.style.backgroundColor='#EDEEF2';
		target.options.length = 0;
		target.disabled = true;
    }
}



function loadFromXml(originalRequest)
{
    //put returned XML in the textarea
    result = originalRequest.responseText;    
    //parsing XML
    try {
        // xmlDoc.LoadXML result;   // parse JS
        var xmlError
        var xmlDoc = new XMLDoc(result, xmlError);
        var action = xmlDoc.docNode;
    }
    catch (e) {
        alert('exception sur parseXML ' + result + ' ' + e);
        return;
    }
    populateComboBoxTarget(action);
}

function populateComboBoxTarget(node)
{
    id = node.getAttribute("type");
    
    target = $(id);    
    // vidage de la combobox
    target.options.length = 0;

    // remplissage dynamique de la combobox
    var values = node.getElements("value");
    for (j = 0; j < values.length; j++) {
    
        var value = values[j];
        //alert('value '+ value.getText() + '\n escapedvalue '+ escape(value.getText()) + '\n unescapedvalue '+ unescape(value.getText()));
        var val = urldecode(value.getText());
        var tex = capitalize(urldecode(value.getText()));
        if(id == 'date' ) {
			tex = formatDate(tex);
        }
        target.options[j] = new Option(tex, val);
    }
    //    target.disabled = false;
    evaluateCombos([COUNTRY, REGION, DEPARTMENT, CITY]);

    //Si un seul élément, on le sélectionne et on appelle l'évènement de modification de l'élément
    if (values.length == 2) {
        target.options.selectedIndex = 1;
        try {
            eval(id + 'Changed()');
        } catch(ex) {
            //On peut avoir une exception si la méthode n'existe pas
        }
    }
    //On évalue la possibilité d'utiliser le bouton valider
    evaluateValider();
}

function formatDate(t) {
	
	var position = t.indexOf("-", 0);
    if (position != -1) {
        var partie2 = t.substring((position + 1), t.length);
        if ("0/0" == partie2)
            t = t.substring(0, position + 1) + "...";
    }
    return t;
}

function capitalize(val) {
        newVal = '';
        val = val.split(' ');
        for(var c=0; c < val.length; c++) {
                newVal += val[c].substring(0,1).toUpperCase() + val[c].substring(1,val[c].length).toLowerCase() + ' ';
        }
        return newVal;
}

function urldecode(ch) {
    ch = ch.replace(/[+]/g, " ")
    return unescape(ch)
}

function getCountries()
{
    var pars = "action=getCountries";
    var myAjax = new Ajax.Request(
            url,
    {
        method: 'get',
        parameters: pars,
        onComplete: loadFromXml
    });
}

function getRegions(country)
{
    var pars = "action=getRegions&country=" + country;
    var myAjax = new Ajax.Request(
            url,
    {
        method: 'get',
        parameters: pars,
        onComplete: loadFromXml
    });
}

function getDepartments(country, region)
{
    var pars = "action=getDepartments&country=" + country + "&region=" + region;
    var myAjax = new Ajax.Request(
            url,
    {
        method: 'get',
        parameters: pars,
        onComplete: loadFromXml
    });
}

function getCities(country, region, department)
{
    var pars = "action=getCities&country=" + country + "&region=" + region + "&department=" + department + "&format=lower";
    var myAjax = new Ajax.Request(
            url,
    {
        method: 'get',
        parameters: pars,
        onComplete: loadFromXml
    });
}

function hasDivision(divname) 
{
    target = $(divname);    
	return target != null;
}

function divValue(divname) {
	if (hasDivision(divname))
		return $F(divname);
	
	return "";
}

function countryChanged()
{
	deselectAndPauseCombo(REGION);
	deselectAndPauseCombo(DEPARTMENT);
	deselectAndPauseCombo(CITY);
	if (hasDivision(REGION))
		getRegions(divValue(COUNTRY));
	else if (hasDivision(DEPARTMENT))
		getDepartments(divValue(COUNTRY), divValue(REGION));
	else if (hasDivision(CITY))
		getCities(divValue(COUNTRY), divValue(REGION), divValue(DEPARTMENT));
}


function regionChanged()
{
	deselectAndPauseCombo(DEPARTMENT);
	deselectAndPauseCombo(CITY);
	if (hasDivision(DEPARTMENT))
		getDepartments(divValue(COUNTRY), divValue(REGION));
	else if (hasDivision(CITY))
		getCities(divValue(COUNTRY), divValue(REGION), divValue(DEPARTMENT));
}


function departmentChanged()
{
	deselectAndPauseCombo(CITY);
	if (hasDivision(CITY))
		getCities(divValue(COUNTRY), divValue(REGION), divValue(DEPARTMENT));
}


function cityChanged()
{
	evaluateValider();
}

function zipcodeChanged() 
{
	evaluateValider();
}


