function showhide(id) {
    var ctrl = document.getElementById(id);
    showhideCtrl(ctrl);
}

function showhideCtrl(ctrl) {
    ctrl.style.display = (ctrl.style.display == 'none' ? 'block' : 'none');
}

function showhideAll(elementName, count) 
{
    var state = '';
    var arSibling = new Array();
    for (var i = 1; i <= count; ++i) 
    {
        var idCtrl = elementName + i;
        var ctrl = document.getElementById(idCtrl);
        if (0 == state.length) {
            state = (ctrl.style.display == 'none' ? 'block' : 'none');
        }
        arSibling.push(ctrl);
    }

    if (0 < state.length) 
    {
        count = arSibling.length;
        for (var i = 0; i < count; ++i) {
            var ctrl = arSibling[i];
            ctrl.style.display = state;
        }
    }
}

function ShowHideDialog(ctrlName) 
{
    var dialog = $(ctrlName);
    if (0 < dialog.length) {
        var control = dialog[0];
        if (control.style.display == 'none') {
            control.style.display = 'block';
            //dialog.dialog();
        }
        else {
            control.style.display = 'none';
            //dialog.dialog('close');            
        }
    }
}

function _ShowHideDialog(page, largeur, hauteur, callback) 
{
    var dlgElement = document.getElementById('dialogALCP');
    if (null == dlgElement) 
    {
        scrollY = f_scrollTop();
        scrollX = f_scrollLeft();
        scrollWidth = f_scrollWidth();
        scrollHeight = f_scrollHeight();

        var modal_element = document.createElement('div');
        modal_element.id = 'modal_dialogALCP';
        modal_element.style.width = scrollWidth + 'px';
        modal_element.style.height = scrollHeight + 'px';
        modal_element.className = 'modal'; 

        var element = document.createElement('div');
        element.id = 'dialogALCP';
        element.style.position = 'absolute';

        var dlg_largeur = 665;
        var dlg_hauteur = 415;
        if (null != largeur) {
            dlg_largeur = largeur;
        }
        if (null != hauteur) {
            dlg_hauteur = hauteur;
        }
        element.style.width = dlg_largeur + 'px';
        element.style.height = dlg_hauteur + 'px';

        var dlg_top = scrollY + ((screen.height - dlg_hauteur) / 2);
        var dlg_left = scrollX + ((screen.width - dlg_largeur) / 2);
        element.style.top = dlg_top + 'px';
        element.style.left = dlg_left + 'px';
        element.style.display = 'none';
		element.style.zIndex = "1010";

        var dlg_contenu = document.createElement("div");
        dlg_contenu.id = 'dlg_contenu';

        element.appendChild(dlg_contenu);
        if (null == page) {
            page = 'test.php?width=' + width + '&height=' + height;
        }
        getPage(page, function result(data) {
            dlg_contenu.innerHTML = data;
        });

        document.body.appendChild(modal_element);
        document.body.appendChild(element);

		$("#dialogALCP").slideToggle("slow");
		var ctrl = $("#btnClose")[0];
		if (null != ctrl) ctrl.focus();
    }
    else 
    {
        $("#dialogALCP").slideToggle("slow", function endEffect() {
            var modal_dlgElement = document.getElementById('modal_dialogALCP');
            document.body.removeChild(modal_dlgElement);
            document.body.removeChild(dlgElement);
			if ( null != callback ) {
				eval(callback);
			}
        });
   }
}

function hideDialogTimer() 
{
	var dlgElement = document.getElementById('dialogALCP');
    if (null != dlgElement) 
	{
        $("#dialogALCP").fadeOut('fast', function endEffect() {
            var modal_dlgElement = document.getElementById('modal_dialogALCP');
            document.body.removeChild(modal_dlgElement);
            document.body.removeChild(dlgElement);
        });
	}
}

function _ShowHideDialogFX(page, largeur, hauteur) 
{
	var dlgElement = document.getElementById('dialogALCP');
    if (null == dlgElement) 
    {
        scrollY = f_scrollTop();
        scrollX = f_scrollLeft();
        scrollWidth = f_scrollWidth();
        scrollHeight = f_scrollHeight();

        var modal_element = document.createElement('div');
        modal_element.id = 'modal_dialogALCP';
        modal_element.style.width = scrollWidth + 'px';
        modal_element.style.height = scrollHeight + 'px';
        modal_element.className = 'modal'; 

        var element = document.createElement('div');
        element.id = 'dialogALCP';
        element.style.position = 'absolute';

        var dlg_largeur = 350;
        var dlg_hauteur = 80;
        if (null != largeur) {
            dlg_largeur = largeur;
        }
        if (null != hauteur) {
            dlg_hauteur = hauteur;
        }
        element.style.width = dlg_largeur + 'px';
        element.style.height = dlg_hauteur + 'px';

        var dlg_top = scrollY + ((screen.height - dlg_hauteur) / 2);
        var dlg_left = scrollX + ((screen.width - dlg_largeur) / 2);
        element.style.top = dlg_top + 'px';
        element.style.left = dlg_left + 'px';
        element.style.display = 'none';

        var dlg_contenu = document.createElement("div");
        dlg_contenu.id = 'dlg_contenu';

        element.appendChild(dlg_contenu);
        getPage(page, function result(data) {
            dlg_contenu.innerHTML = data;
        });

        document.body.appendChild(modal_element);
        document.body.appendChild(element);
		$("#dialogALCP").fadeIn("fast");
		setTimeout("hideDialogTimer()", 2000);
	}
	else 
	{
        $("#dialogALCP").fadeOut('fast', function endEffect() {
            var modal_dlgElement = document.getElementById('modal_dialogALCP');
            document.body.removeChild(modal_dlgElement);
            document.body.removeChild(dlgElement);
        });
	}
}

function f_clientWidth() {
    return f_filterResults(
		window.innerWidth ? window.innerWidth : 0,
		document.documentElement ? document.documentElement.clientWidth : 0,
		document.body ? document.body.clientWidth : 0
	);
}
function f_clientHeight() {
    return f_filterResults(
		window.innerHeight ? window.innerHeight : 0,
		document.documentElement ? document.documentElement.clientHeight : 0,
		document.body ? document.body.clientHeight : 0
	);
}

function f_scrollLeft() {
    return f_filterResults(
		window.pageXOffset ? window.pageXOffset : 0,
		document.documentElement ? document.documentElement.scrollLeft : 0,
		document.body ? document.body.scrollLeft : 0
	);
}
function f_scrollTop() {
    return f_filterResults(
		window.pageYOffset ? window.pageYOffset : 0,
		document.documentElement ? document.documentElement.scrollTop : 0,
		document.body ? document.body.scrollTop : 0
	);
}
function f_scrollWidth() {
    return f_filterResults(
		/*window.pageXOffset ? window.pageXOffset :*/ 0,
		/*document.documentElement ? document.documentElement.scrollLeft :*/ 0,
		document.body ? document.body.scrollWidth : 0
	);
}
function f_scrollHeight() {
    return f_filterResults(
		/*window.pageYOffset ? window.pageYOffset :*/ 0,
		/*document.documentElement ? document.documentElement.scrollTop :*/ 0,
		document.body ? document.body.scrollHeight : 0
	);
}
function f_filterResults(n_win, n_docel, n_body) {
    var n_result = n_win ? n_win : 0;
    if (n_docel && (!n_result || (n_result > n_docel)))
        n_result = n_docel;
    return n_body && (!n_result || (n_result > n_body)) ? n_body : n_result;
}


function AddNewProduct(libelle, prix, ctrlColor) 
{
    // transforme les caract�res & en %26
    libelle = escape(libelle).replace(/\&/g, '%26');
	if ( null != ctrlColor ) 
	{
		var _ident = '#' + ctrlColor;
		var _idColor = $(_ident)[0];
		if ( null != _idColor ) 
		{
			var color = _idColor.options[_idColor.selectedIndex].value;
			libelle += "|" + color;
		}
	}
    var values = '_action=ajout&l=' + libelle+ '&q=1&p=' + prix;
    if (postPage('panier/panier.php', values, function updatePanier(data) {
        var ctrlPanier = $('#panier')[0];
        ctrlPanier.innerHTML = data;
    })) {
        alert('produit ajout� avec succ�s.');
    }
}

/************************************************
|
|   httpRequest manager
|
 ************************************************/
function createXHR()
{
    var xhr_object = null; 
     
    if(window.XMLHttpRequest) // Firefox 
        xhr_object = new XMLHttpRequest(); 
    else if(window.ActiveXObject) // Internet Explorer 
        xhr_object = new ActiveXObject("Microsoft.XMLHTTP"); 
    else { // XMLHttpRequest non support� par le navigateur 
        alert("Votre navigateur ne supporte pas les objets XMLHTTPRequest..."); 
        return;
    }

    return xhr_object;
}

function getPage(page, callback) 
{
    var pageFile = createXHR();
    pageFile.open("GET", page, true);
    pageFile.onreadystatechange = function() {
        if (pageFile.readyState == 4) {  // Makes sure the document is ready to parse.
            if (pageFile.status == 200) {  // Makes sure it's found the file.
                allText = pageFile.responseText;
                if (null != callback) {
                    callback(allText);
                }
            }
            else {
                var msg = "file not found<br><strong>Error : " + pageFile.status + "</strong>";
                container.innerHTML = msg;
            }
        }
    }
    pageFile.send(null);
}

function postPage(file, values, callback) 
{
    var bError = false;
    var pageFile = createXHR();

    pageFile.open("POST", file, true);
    pageFile.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    pageFile.send(values);

    pageFile.onreadystatechange = function() {
        if (pageFile.readyState === 4) {  // Makes sure the document is ready to parse.
            if (pageFile.status === 200) {  // Makes sure it's found the file.
                allText = pageFile.responseText;
                if (0 < allText.length) {
                    if (null != callback) {
                        callback(allText);
                    }
                }
            }
            else {
                alert('file not found');
                bError = true;
            }
        }
    }
    
    return bError;
}

var menuActive = "menuAccueil";
function activateMenu(idCtrl, page) 
{
    var obj = document.getElementById(idCtrl);
    if (menuActive != obj.id) {
        var oldCtrl = document.getElementById(menuActive);
        oldCtrl.className = '';
        menuActive = obj.id;
        obj.className = 'current';
    }

    activatePage(page);
    scrollcontainer(true);
}

function manageResult(result) 
{
    var index = result.lastIndexOf("id='__errorMsg'");
    if (-1 == index) {
        $("#pages").empty();
    }

    var count = result.length;
    if (count > 0) 
    {
    	msg = "<div>" + result + "</div>";
    	$(msg).prependTo("#pages");
    }
    else 
    {
        $("#pages").empty();
        $("Loading page failed!").prependTo("#pages");    
    }
}

function activatePage(page) 
{
    var pageFile = createXHR();
    pageFile.open("GET", page, true);

    pageFile.onreadystatechange = function() {
        if (pageFile.readyState === 4) {  // Makes sure the document is ready to parse.
            if (pageFile.status === 200) {  // Makes sure it's found the file.
                manageResult(pageFile.responseText);
            }
            else {
                var msg = "file not found\nError :\nStatus : " + pageFile.status + "\nMessage: " + pageFile.responseText;
                alert(msg);
            }
        }
    }
    pageFile.send(null);
}

function onFocusInput(control) 
{
    if (null != control) {
        if ( (control.className == 'inputDisabled') && (0 < control.value.length) ) {
            control.className = "inputEnabled";
            control.value = '';
        }
    }
}

function onBlurInput(control, value)
{
    if (null != control) {
        if ( (control.className == 'inputEnabled') && (0 == control.value.length) ) {
            control.className = "inputDisabled";
            control.value = value;
        }
    }
}

function onFocusInputPwd(control)
{
	if ( null != control ) 
	{
		if ((control.id == '_password') && (0 < control.value.length)) 
		{
			var ctrl = $('#password')[0];
			ctrl.style.display = 'inline';
			control.style.display = 'none';
			ctrl.value = '';
			ctrl.focus();
		}
	}
}

function onBlurInputPwd(control)
{
    if (null != control) 
	{
		if ( control.id=="password" && (0 == control.value.length)) 
		{
			var ctrl = $('#_password')[0];
			ctrl.style.display = 'inline';
			control.style.display = 'none';
		}
    }
}

function resultSubmitNew(flux) 
{
    alert(flux);
}

function onSubmitNews()
{
    values = new String();
    if (!ParseForm('news_letter')) {
        if (postPage(fileSubmit, values, resultSubmitNew)) {
            alert('Error');
        }
    }
    delete values;
    values = null;
    fileSubmit = null;
}

function onSubmitConnexion() 
{
    values = new String();
    if (!ParseForm('connexion_customer')) {
        if (postPage(fileSubmit, values, manageResult)) {
            alert('Error');
        }
    }
    delete values;
    values = null;
    fileSubmit = null;
}

var values = null;
var fileSubmit = null;
function onRefreshBuy(file, in_values)
{
    if (postPage(file, in_values, function resultCaddie(data) {
        if (postPage('panier/panier.php', null, function updatePanier(data) {
            var ctrlPanier = $('#panier')[0];
            ctrlPanier.innerHTML = data;
        }));

        manageResult(data);
    })) {
        alert('Error');
    }
}

function doAction(file, libelle, selQte, defaultQte)
{
    var values = '_action=';
    diff = defaultQte - selQte;
    if (0 != selQte) {
        values += 'refresh';
    }
    else {
        values += 'suppression';
    }
    values += '&l=' + libelle;
    values += '&q=' + selQte;
    values += '&p=0';

    onRefreshBuy(file, values);
}

function resultIdentification(data)
{
	manageResult(data);
	
	if (postPage('left_menu_container2.php', null, function update(flux) {
		var ctrlLeft = document.getElementById('left_menu2');
		ctrlLeft.innerHTML = flux;
	}));
}

function onSubmitUserIdentification() 
{
    values = new String();
    if (!ParseForm('__user_identification')) {
        if (postPage(fileSubmit, values, resultIdentification)) {
			alert('Error'); 
		}
    }

    delete values;
    values = null;
    return false;
}

function onSubmitNewCustomer() 
{
    values = new String();
    if (!ParseForm('account_customer')) {
        var form = document.forms.namedItem('account_customer');
        if (form['password'].value != form['confirm_password'].value) {
            form['confirm_password'].className = 'input_error';
        }
        else {
            if (postPage(fileSubmit, values, manageResult)) {
                alert('Error'); 
            }
        }
    }

    delete values;
    values = null;
    return false;
}

function resultSubmitMdp(flux) {
    alert(flux);
}

function onSubmitMdp()
{
    values = new String();
    if (!ParseForm('mdp_user_send')) {
        if (postPage(fileSubmit, values, resultSubmitMdp)) {
            alert('Error');
        }
    }

    delete values;
    values = null;
    return false;
}

function onSubmitNewDestinataire(form) 
{
    values = new String();
    if (!ParseForm(form.name)) {
        if (postPage(fileSubmit, values, manageResult)) {
            alert('Error');
        }
    }

    delete values;
    values = null;
    return false;
}

function onSubmitPaiement(form) {
    values = new String();
    if (!ParseForm(form.name)) {
        if (postPage(fileSubmit, values, manageResult)) {
            alert('Error');
        }
    }

    delete values;
    values = null;
    return false;
}

function onSubmitCodePromo(form) 
{
    values = new String();
    if (!ParseForm(form.name)) {
        if (postPage(fileSubmit, values, function onResult(data) {
            var container = document.getElementById('pages');
            container.innerHTML = data;
        } )) {
            alert('Error');
        }
    }

    delete values;
    values = null;
    return false;
}

function onSubmitIdentite(form) 
{
    var bError = false;

    var count = form.length;
    if (0 < count) {
        for (var i = 0; i < count; ++i) {
            var ctrl = form[i];
            if (ctrl.value == null || ctrl.value == '') {
                alert('Tous les champs doivent �tre renseign� et valide');
                return false;
            }
        }
        
        values = new String();
        if (!ParseForm(form.name)) {
            if (postPage(fileSubmit, values, function onResult(data) {
                var container = document.getElementById('pages');
                container.innerHTML = data;
            } )) {
                alert('Error');
            }
        }

        delete values;
        values = null;
        return false;
    }
    
    return false;
}

function onSubmitUpdateCustomer(form) 
{
    values = new String();
    if (!ParseForm(form.name)) {
        if (postPage(fileSubmit, values, manageResult)) {
            alert('Error');
        }
    }

    delete values;
    values = null;
    return false;
}
/*********************************************************/
/* Form Manager                                          */
/*                                                       */
/* Purpose: Parse and extract all data and validate      */
/* fields before sending page                            */
/*                                                       */
/*********************************************************/
function ParseForm(formName) 
{
    var bError = false;
    var form = document.forms.namedItem(formName);
    fileSubmit = form.action;

    var count = form.length;
    for (var i = 0; i < count; ++i) {
        var ctrl = form[i];
        var objValidator = Validator.createValidator(ctrl);
        if (objValidator.isValidFormat()) {
            ctrl.className = '';
            values += ctrl.name;
            values += '=';
            values += objValidator.getValue();
            values += '&';
        }
        else {
            ctrl.className = 'input_error';
            if (!bError) {
                ctrl.select();
                bError = true;
            }
        }
    }

    return bError;
}

//---------------------------------------------------
// Create un object validator (factory)
// Used to validate data field and extract the value
// selected
//---------------------------------------------------
function ValidatorFactory() {
}
ValidatorFactory.prototype = {
    createValidator: function(ctrl) {
        return this.create(ctrl);
    },
    create: function(ctrl) {
        var instance = null;
        try {
            var className = ctrl.name + 'Validator';
            if (eval('typeof ' + className) == 'undefined') {
                className = ctrl.type + 'Validator';
            }
            if (typeof(eval(className)) !== "undefined") {
                instance = eval('new ' + className + '()');
                instance.ctrl = ctrl;
            }
        }
        catch (e) {
            instance = new defaultValidator(ctrl);
        }

        return instance;
    }
}

var Validator = new ValidatorFactory();

function heriter(destination, source) {
    for (var element in source) {
        if (destination[element] === undefined) {
            destination[element] = source[element];
        }  
    }  
}  

function defaultValidator(ctrl) {
    this.ctrl = ctrl;
    if (defaultValidator.caller != null) {
        heriter(defaultValidator.caller.prototype, defaultValidator.prototype);
    }
}

defaultValidator.prototype = {
    isValidFormat: function() {
        return true;
    },
    getValue: function() {
        try {
            var objCtrl = eval('new ' + className + '()');
            return objCtrl.getValue(this.ctrl);
        }
        catch (e) {
            return this.ctrl.value;
        }
    }
}

function emailValidator() {
    defaultValidator.call(this);
}

emailValidator.prototype.isValidFormat = function() {
    var re = new RegExp("^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z]{2,4})+$");
    return re.test(this.ctrl.value);
}

function passwordValidator() {
    defaultValidator.call(this);
}

passwordValidator.prototype.isValidFormat = function() {
    var re = new RegExp("^[a-zA-Z0-9]{6,16}$");
    return re.test(this.ctrl.value);
}

passwordValidator.prototype.getValue = function() {
    return this.ctrl.value;
}

function nomValidator() {
    defaultValidator.call(this);
}

nomValidator.prototype.isValidFormat = function() 
{
	if ( 0 == this.ctrl.value.length ) {
		return false;
	}
	
	if ( 0 == trim(this.ctrl.value).length ) {
		return false;
	}
	
	return true;
}

function prenomValidator() {
    defaultValidator.call(this);
}

prenomValidator.prototype.isValidFormat = function() 
{
	if ( 0 == this.ctrl.value.length ) {
		return false;
	}
	
	if ( 0 == trim(this.ctrl.value).length ) {
		return false;
	}
	
	return true;
}

function checkboxValidator() {
    defaultValidator.call(this);
}
checkboxValidator.prototype.getValue = function() {
    return this.ctrl.checked;
}

function trim(string)
{
	var rtrn = "";
	var max = string.length;
	var j=0;
	//On d�cale le premier index pour la copie
	while (j<max && string.charAt(j) == " ")++j;
	//on d�cale le dernier index pour la copie
	while (max>0 && string.charAt(max-1) == " ")--max;
	//On effectue la copie
	while (j<max){
		rtrn += string.charAt(j);
		++j;
	}
	return rtrn;
}

function scrollcontainer(scroll)
{
    var ctrlPage = $('#pages')[0];
    //ctrlPage.style.overflow = (scroll == true ? 'auto' : 'hidden');
    ctrlPage.style.height = (scroll == true ? 'auto' : 'inherit');
    window.scrollTo(0, 0);
}

function OpenBrowser(url, largeur, hauteur)
{
    // Largeur et hauteur de la fen�tre
    var Popup_largeur = 750;
    var Popup_hauteur = 560;
    if (null != largeur) {
        Popup_largeur = largeur;
    }
    if (null != hauteur) {
        Popup_hauteur = hauteur;
    }

    // Position haut et gauche de la fen�tre SPPLUS pour affichage centr� dans l'�cran
    var Popup_top = ((screen.height - Popup_hauteur) / 2);
    var Popup_left = ((screen.width - Popup_largeur) / 2);

    // Ouverture du popup SPLUS avec barre �tat uniquement et focus sur la fen�tre
    //var win = window.open(url, "SPPLUS", "status=yes,top=" + Popup_top + ",left=" + Popup_left + ",width=" + Popup_largeur + ",height=" + Popup_hauteur);
    var win = window.open(url, "SPPLUS", "status=yes,top=" + Popup_top + ",left=" + Popup_left + ",width=" + Popup_largeur + ",height=" + Popup_hauteur);
    win.focus();
}

function SelectedImage(id, img)
{
	var _ident = '#' + id;  
	var ident = $(_ident)[0];
	ident.style.display = 'none';
	ident.src = img;
	$(ident).fadeIn("slow");
}

function ConfirmSuppression(msg, page)
{
	var ret = confirm(msg);
	if ( ret ) { // Clic sur OK
		activatePage(page);
	}
	
	return ret;
}