
/*
 * Extensions to built-in objects:
 *  - in IE Array lacks the push method
 */

if (!Array.prototype.push) {
    Array.prototype.push = function(elem) {
        this[this.length] = elem;
    };
}


/*
 * Wrap everything in a namespace to avoid naming conflicts
 */

var h_art = {
    byId: function(id) {
        if (document.getElementById) {
            return document.getElementById(id);
        } else {
            return document.all[id];
        }
    },
	
	byTagName: function(elem, name) {
		if (elem.getElementsByTagName) {
			return elem.getElementsByTagName(name);
		} else {
			return elem.all.tags(name);
		}
	},
	
    /*
    objDump: function(obj, recursive, indent, repr) {
        var recur = recursive ? true : false;
        var ind = indent || 0;
        var rep = repr || "{";
        for (var p in obj) {
            //
        }
        return rep;
    },
    */

    addLoadEvent: function(foo) {
        var prev = window.onload;
        window.onload = function() {
            if (prev) prev();
            foo();
        }
    },

    getValue: function(field) {
        if ((field.length) && (!field.type)) {
            for (var i = 0; i < field.length; ++i) {
                if (field[i].checked)
                    return field[i].value;
            }
            return null;
        }
        return field.value;
    },

    getValueById: function(id) {
        var elem = this.byId(id);
        return this.getValue(elem.form[elem.name]);
    },

    // Si assume la localizzazione italiana. Quella inglese, per esempio, rompe
    // il giocattolo.
    getNumericValue: function(value) {
        return Number(value.split('.').join('').replace(',','.'));
    },

    setCap: function(cap, id)
    {
        this.byId(id).value=cap;
    },

    popUp: function (link, width, height, name, idDomanda) {
        
        name = name || ('id' + Math.floor(Math.random()*1000));

        // NB: funziona solo con le domande semplici, non quelle composte
        // da piu campi di input.
        if (idDomanda) {
            var sep = link.indexOf('?') >= 0 ? '&' : '?';
            link += sep + this.byId(idDomanda).name + '=' + escape(this.getValueById(idDomanda));
        }
        
        var popup = window.open(link, name, 'height='+height+',width='+width+',toolbars=no,menubar=no,statusbar=no');
        return popup;
    },
    
    popUpUpload: function (link, width, height, name, idDomanda) {
        
        name = name || ('id' + Math.floor(Math.random()*1000));

        // NB: funziona solo con le domande semplici, non quelle composte
        // da piu campi di input.
        if (idDomanda) {
            var sep = link.indexOf('?') >= 0 ? '&' : '?';
            link += sep + this.byId(idDomanda).name + '=' + escape(this.getValueById(idDomanda));
        }
        
        var popup = window.open(link, name, 'height='+height+',width='+width+',toolbars=no,menubar=no,statusbar=yes');
        return popup;
    },

    popUpContent: "",

    onClickHelp: function(id) {
        /** GESI **/ var popup = window.open('/preventivi/help', 'Help', 'height=400,width=535,toolbars=no,menubar=no,statusbar=no,scrollbars=yes');//this.popUp('/preventivi/help', 600, 400, 'Help');
        /** H-ART **/ //var popup = window.open('popUpHelp.html', 'Help', 'height=400,width=535,toolbars=no,menubar=no,statusbar=no,scrollbars=yes');//this.popUp('popUpHelp.html', 600, 400, 'Help');
        this.popUpContent = this.byId(id).innerHTML;
    },

    onClickStepTab: function(formName, formType, stepNum) {
        var form = document.forms[formName];
        form.formType.value = formType;
        form.step.value = stepNum;
        form.submit();
    },

    stampa: function() {
        var NS = (navigator.appName == "Netscape");

        if (window.print) {
             window.print();
        }
        else {
             this.printitIE4();
        }
    },

    printitIE4: function(){

        var OLECMDID_PRINT = 6;
        var OLECMDEXECOPT_DONTPROMPTUSER = 2;
        var OLECMDEXECOPT_PROMPTUSER = 1;
        var WebBrowser = '\<OBJECT ID="WebBrowser1" WIDTH=0 HEIGHT=0 CLASSID="CLSID:8856F961-340A-11D0-A96B-00C04FD705A2"\>\<\/OBJECT\>';
        document.body.insertAdjacentHTML('beforeEnd', WebBrowser);
        oldHandler = window.onerror;
        window.onerror = deal;
        WebBrowser1.ExecWB(OLECMDID_PRINT,OLECMDEXECOPT_PROMPTUSER);
        WebBrowser1.outerHTML = "";
        window.onerror = oldHandler;

        function deal()
        {
          WebBrowser1.outerHTML = "";
          window.onerror = oldHandler;
          return true;
        }

    },

    /**
     * esegue fun solo se il browser e` safari. viene utilizzata per esempio
     * per i bottoni "indietro" e "continua", che su safari non sono "skinnabili"
     * come negli altri browser (IE 4 in particolare)
     */
    ifSafari: function(fun) {
        if ((/Safari/i).test(navigator.userAgent) && typeof fun == "function") {
            fun();
        }
    },

    bookmark: function(link)
    {
        var url = '/bookmark?from=http://'+location.hostname+link;
        h_art.popUp(url,500,400,'bookmark');
    },
    
    openPopUpCercaModello: function(page, params)
    {
    	/*
    	Questa funzione viene chiamata esclusivamente dal link per la ricerca
    	del modello di auto. Apre una popUp passando:
    	- il value del campo con id=idMarcaAuto 
    	- l'etichetta dell'elemento selezionato del campo con id=idMarcaAuto
    	- l'id del campo relativo al modello, il cui valore verrą impostato dalla popUp
    	*/
        var name = 'id' + Math.floor(Math.random()*1000);
        
        //id campo modello
		var paramIdModello = 'id=' + params.id;

		//etichetta marca auto selezionata
		var marcaAuto = this.byId(params.ref);
		var marcaAutoSelectedIndex = marcaAuto.options.selectedIndex; 
    	var marcaAutoLabel = marcaAuto.options[marcaAutoSelectedIndex].text;
    	var paramLabelMarcaAuto = 'marca=' + escape(marcaAutoLabel);
    	
    	//codice marca auto selezionata
    	var paramCodMarcaAuto = 'cod=' + escape(this.getValue(marcaAuto));
    	
		link = page + "?" + paramIdModello + "&" + paramCodMarcaAuto + "&" + paramLabelMarcaAuto
		
        var popup = window.open(link, name, 'height='+params.height+',width='+params.width+',toolbars=no,menubar=no,statusbar=no');
    }

};


/*
 * Drop down boxes dependecy system:
 *  - Only pairs of select elements are allowed at the moment
 *  - The external data structure expected by these routines is
 *    similar to the following:
 *      var h_art.selectDependencies = {
 *          'name_of_parent_select': {
 *              name: 'name_of_child_select',
 *              dependencies: [
 *                  [ { label: 'first_element_full_label',
 *                      shortLabel: 'firs_element_short_label',
 *                      value: 'first_element_value'
 *                    },
 *                    ...
 *                  ],
 *                  ...
 *              ],
 *              ...
 *          },
 *          ...
 *      };
 */

h_art.selectDependsOnSelect = function(parentSelect) {
    var child = this.selectDipendencies[parentSelect.name];

    if (child) {
        var childSelect = parentSelect.form[child.name];
        var parentSelectedIndex = parentSelect.selectedIndex;

        this.clearSelect(childSelect);

        //var childValues = parentSelectedIndex > 0 ? child.dipendencies[parentSelectedIndex-1] : [];
        var childValues = child.dipendencies[parentSelectedIndex];
        //var childValues = parentSelectedIndex > 0 ? child.dipendencies[parentSelectedIndex-1] : child.dipendencies[parentSelectedIndex];
        
        
        //var childValues = (parentSelect[parentSelectedIndex].text !="Seleziona")?child.dipendencies[parentSelectedIndex-1]:[];
        
        
        this.setLongLabels(childSelect, childValues);
    }

    for (var i = Function.length; i < arguments.length; ++i) {
        var name = arguments[i];
        var select = parentSelect.form[name];
        if (select)
            h_art.clearSelect(select, true);
    }
}

h_art.selectDependsOnSelectSettoreAva = function(parentSelect) {
//alert('selectDependsOnSelectSettore('+parentSelect.name+')');
    var child = this.selectDipendenciesSettoreAva[parentSelect.name];
//alert('child='+child);
    if (child) {
        var childSelect = parentSelect.form[child.childName];
        var childChildSelect = parentSelect.form[child.childChildName];
//alert('childSelect='+childSelect);        
        var parentSelectedIndex = parentSelect.selectedIndex;
//alert('parentSelectedIndex='+parentSelectedIndex);
        this.clearSelect(childSelect);
        this.clearSelect(childChildSelect);

        //var childValues = parentSelectedIndex > 0 ? child.dipendencies[parentSelectedIndex-1] : [];
        var childValues = child.dipendencies[parentSelectedIndex];
        //var childValues = parentSelectedIndex > 0 ? child.dipendencies[parentSelectedIndex-1] : child.dipendencies[parentSelectedIndex];
        
        
        //var childValues = (parentSelect[parentSelectedIndex].text !="Seleziona")?child.dipendencies[parentSelectedIndex-1]:[];
        
        
        this.setLongLabels(childSelect, childValues);
    }

    /*for (var i = Function.length; i < arguments.length; ++i) {
        var name = arguments[i];
        var select = parentSelect.form[name];
        if (select)
            h_art.clearSelect(select, true);
    }*/
}

h_art.selectDependsOnSelectClasseAva = function(parentSelect) {
//alert('parentSelect.name'+parentSelect.name);
        var child = this.selectDipendenciesClasseAva[parentSelect.name];
    if (child) {
        var childSelect = parentSelect.form[child.childName];
//alert('childSelect.name='+childSelect.name);
        var parentSelectedIndex = parentSelect.selectedIndex;
//alert('parentSelectedIndex='+parentSelectedIndex);
        this.clearSelect(childSelect);
        
        var parentParentSelect = parentSelect.form[child.parentParentName];
//alert('parentParentSelect.name='+parentParentSelect.name);
        var parentParentSelectedIndex = parentParentSelect.selectedIndex;
//alert('parentParentSelectedIndex='+parentParentSelectedIndex);

        //var childValues = parentSelectedIndex > 0 ? child.dipendencies[parentSelectedIndex-1] : [];
        var childValues = child.dipendencies[parentParentSelectedIndex][parentSelectedIndex-1];
        //var childValues = parentSelectedIndex > 0 ? child.dipendencies[parentSelectedIndex-1] : child.dipendencies[parentSelectedIndex];
//alert('childValues='+childValues);
//alert('childValues.length='+childValues.length);
/*for(var i = 0; i < childValues.length; i++)
{
    alert('childValues['+i+']='+childValues[i]);
}*/
        
        //var childValues = (parentSelect[parentSelectedIndex].text !="Seleziona")?child.dipendencies[parentSelectedIndex-1]:[];
        
        
        this.setLongLabels(childSelect, childValues);
    }

    /*for (var i = Function.length; i < arguments.length; ++i) {
        var name = arguments[i];
        var select = parentSelect.form[name];
        if (select)
            h_art.clearSelect(select, true);
    }*/
}

h_art.clearSelect = function(select, disable) { // select can be a DOM/DHTML object or its id
    if (typeof select == "string") {
        select = this.byId(select);
    }

    if (select.options.length <= 1) return;

    var firstOption = select.options[0];
    select.options.length = 0;
    select.options[0] = firstOption;

    this.onChangeSelectShortLabel(select);

    if (disable)
        select.disabled = true;
}

h_art.onChangeSelectShortLabel = function(select) {
    var textcnt = select.form[select.name+'_longLabel']; // this.byId(select.name+'_longLabel');
    if (!textcnt) return;
    var longLabel = select.options[select.selectedIndex].longLabel;
    if (longLabel) {
        //textcnt.innerHTML = longLabel;
        textcnt.value = longLabel;
        textcnt.style.display = "block";
    } else {
        //textcnt.innerHTML = "";
        textcnt.value = "";
        textcnt.style.display = "none";
    }
}

h_art.setLongLabels = function(select, optionValues) {
    if (typeof select == "string") {
        select = this.byId(select);
    }

    var selectedIndex = 0;
    var i;
    for (i = 0; i < optionValues.length; ++i) {
        var text = optionValues[i].shortLabel || optionValues[i].label;
        var option = new Option(text, optionValues[i].value);
        if (optionValues[i].shortLabel) {
            option.longLabel = optionValues[i].label;
        }
        if (optionValues[i].selected) {
            option.selected = true;
            selectedIndex = select.options.length;
        }
        select.options[select.options.length] = option;
    }
    select.selectedIndex = selectedIndex;

    this.onChangeSelectShortLabel(select);
    /*
    if (select.options.length <= 1) select.disabled = true;
    else select.disabled = false;
    */
}
    /*
    Funzione utilizzata per impostare il valore dell'option "seleziona"
    a "ALLEST_NON_TROVATO"
    */
    impostaAllestimentoNonTrovato = function (idDomandaAllestimento) {
	    if (document.getElementById) {
	        select =  document.getElementById(idDomandaAllestimento);
	    } else {
	        select =  document.all[idDomandaAllestimento];
	    }
        select.options[0].value = 'ALLEST_NON_TROVATO';
    }
