/*
 *  general functions
 */
//return the index of elem in vect, or -1 if not found (use binary search)
//input: vect -> an array
//       elem -> element to search in the array
function SG_getIndex(vect, elem) {
    i = 0;
    j = vect.length -1;
    while (i<j) {
        if (vect[i] == elem) return i;
	if (vect[j] == elem) return j;
	i++;
        j++;
    }
    return -1;
}

/*
 *  additional string methods
 */
//trim method for strings
// create the prototype on the String object
String.prototype.SG_trim = function() {

 // skip leading and trailing whitespace
 // and return everything in between
  return this.replace(/^\s*(\b.*\b|)\s*$/, "$1");

}

//isEmpty method for strings. Check if a string is Empty or contains only spaces
String.prototype.SG_isEmpty = function() {
    if (this.length == 0 || this.SG_trim() == "")
        return true;
    else
        return false;
}


/*
 *  form functions
 */
//this function is used to simulate the behaviour of a combo box
//input: formname   -> string containing the form name
//       textname   -> text field name in the form
//       selectname -> select field name in the form
//this callback must be called in the text field on a keyup event:
//onKeyUp="return changedText('FrmName', 'TextFieldName', 'SelectFieldName');"
function SG_changedText(formname, textname, selectname) {
    var textref = eval("document." + formname + "." + textname);
    var selectref = eval("document." + formname + "." + selectname);
    var i = 0;
    var pos = 0;
    for (i=0; i<selectref.length; i++){
        if (selectref.multiple)
            selectref.options[i].selected=false;
        if ((textref.value <= selectref.options[i].text) && pos == 0)
            pos = i;
    }
    if (pos==0)
        pos = i;
    if (pos==selectref.length || (textref.value != selectref.options[pos].text && pos != 0))
        pos--;
    if (pos<selectref.length-1)
        pos++;
    selectref.options[pos].selected=true;
    return false;
}

//this function changes set the focus to a form field
//input: formname  -> string containing the form name
//       fieldname -> field that has to receive the focus
//       selected  -> bool field if true fieldname is selected, otherwise get the focus
function SG_setFocus(formname, fieldname, selected) {
    var fieldref = eval("document." + formname + "." + fieldname);
    if (selected)
        fieldref.select();
    else
        fieldref.focus();
    return false;
}

//this function set the values selected in inputfield in outputfield and in hiddenfield.
//In outputfield set the description of the selected field (the text value of an option tag)
//while in hiddenfield set the value of the selected field
//input: formname  -> string containing the form name
//       inputfield -> select field that has the selected values
//       outputfield -> text field where put the description of the selected values separated by "; "
//       hiddenfield -> hidden field where put the selected values separated by "; "
function SG_setValue(formname, inputfield, outputfield, hiddenfield) {
    var inputref = eval("document." + formname + "." + inputfield);
    var outputref = eval("document." + formname + "." + outputfield);
    var hiddenref = eval("document." + formname + "." + hiddenfield);
    var value=outputref.value;
    for (var i=0; i<inputref.length; i++) {
        if (inputref.options[i].selected==true) {      //set description in outputref and value in hiddenref
            if (value == "") {
                value = inputref.options[i].text;
                hiddenref.value = inputref.options[i].value;
             } else {
                value += "; " + inputref.options[i].text;
                hiddenref.value += "; " + inputref.options[i].value;
            }
        }
    }
    //alert(hiddenref.value);
    outputref.value = value;
}

//set the value of input field to ""
//input: formname   -> string containing the form name
//       inputfield -> field to change
function SG_resetValue(formname, inputfield) {
    var inputref = eval("document." + formname + "." + inputfield);
    inputref.value = "";
}

//submit form "formname" setting action to "action"
//input: formname -> string containing the form name
//       action   -> action for the form
function SG_submitForm(formname, action) {
    var formref = eval("document." + formname);
    formref.action = action;
    formref.submit();
    //the return value avoid a double submit
    return false;
}

//select and deselect all fields "checkboxfield" in form "formname"
//input: formname      -> string containing the form name
//       checkboxfield -> checkbox field to select or deselect
//       sel_desel     -> bool field if true all checkboxes are selected else all are deselected
function SG_selectAll(formname, checkboxfield, sel_desel) {
    var checkref = eval("document." + formname + "." + checkboxfield);
    for (var i=0; i<checkref.length; i++) {
        if (sel_desel)
            checkref[i].checked = true;
        else
            checkref[i].checked = false;
    }
    return false;
}

//check all elements in "formname" and if an element is empty raise an alert box
//if other arguments are passed, only the corresponding form elements are checked
//input: formname         -> string containing the form name
//       lang             -> language for messages. At the moment only 'it' and 'en'
//       other_parameters -> optional. name of the elements to check
function SG_checkForm(formname, lang) {
    if (arguments.length > 1) {
        for (var i=2; i<arguments.length; i++) {
            var elref = eval("document." + formname + "." + arguments[i]);
            if (elref.value.SG_isEmpty()) {
                if (elref.title && elref.title != "")
                    if (lang=='it')
                        alert("Inserire un valore nel campo " + elref.title);
                    else if (lang == 'en')
                        alert("Fill in field " + elref.title);
                    else if (lang == 'fr')
                        alert("Complétez le champ " + elref.name);
                else
                    if (lang=='it')
                        alert("Inserire un valore nel campo " + elref.name);
                    else if (lang == 'en')
                        alert("Fill in field " + elref.name);
                    else if (lang == 'fr')
                        alert("Complétez le champ " + elref.name);
                elref.focus();
                return false;
            }
        }
    } else {
        var formref = eval("document." + formname);
        for (var i=0; i<formref.elements.length; i++) {
            if (formref.elements[i].value.SG_isEmpty()) {
                if (lang=='it')
                    alert("Inserire un valore nel campo " + formref.elements[i].name);
                else if (lang == 'en')
                    alert("Fill in field " + formref.elements[i].name);
                else if (lang == 'fr')
                    alert("Complétez le champ " + formref.elements[i].name);
                formref.elements[i].focus();
                return false;
            }
        }
    }
    return true;
}

//check in "formname" if element1 and element2 are equal and not empty
//input: formname -> string containing the form name
//       lang     -> language for messages. At the moment only 'it'
//       element1 -> string containing the name of the first element
//       element2 -> string containing the name of the second element
function SG_checkPassword(formname, lang, element1, element2) {
    var elref1 = eval("document." + formname + "." + element1);
    var elref2 = eval("document." + formname + "." + element2);
    if (SG_checkForm(formname, lang, element1, element2)) {
        if (elref1.value != elref2.value) {
            if (lang=='it')
                alert("Le due password non coincidono");
            else if (lang == 'en')
                alert("Password are not identical");
            else if (lang == 'fr')
                alert("Password are not identical");
            elref1.focus();
            return false;
        }
    } else {
        return false
    }
    return true;
}

/*
 *  DHTML style/layout functions
 */
//get the src attribute of "idElement" image
//(works with Mozilla, Netscape 6, Internet Explorer 5)
//input:  idElement -> string containing the id of the element to show
//output: string containing the src attribute if idElement
function SG_getImageSrc(idElement) {
    return document.getElementById(idElement).src;
}
function SG_getImageWidth(idElement) {
    return document.getElementById(idElement).width;
}
function SG_getImageHeight(idElement) {
    return document.getElementById(idElement).height;
}

//change style class associated to the element "idElement" between "class1" and "class2" 
//(works with Mozilla, Netscape 6, Internet Explorer 5)
//input: idElement -> string containing the id of the element
//       class1    -> name of a class style
//       class2    -> name of the other class style
function SG_changeClass(idElement, class1, class2) {
    if (document.getElementById(idElement).className == class1)
        document.getElementById(idElement).className = class2;
    else
        document.getElementById(idElement).className = class1;
}

//switch display status of the element "idElement" between "block" and "display" 
//(works with Mozilla, Netscape 6, Internet Explorer 5)
//input: idElement -> string containing the id of the element
function SG_hide_showElement(idElement) {
    var elref = document.getElementById(idElement)
    if (elref.style.display == "block")
        elref.style.display = "none";
    else
        elref.style.display = "block";
}

//show the "idElement": set display property of "idElement" to "block" and display property of other elements passed to "none" 
//(works with Mozilla, Netscape 6, Internet Explorer 5)
//input: idElement        -> string containing the id of the element to show
//       other_parameters -> optional. name of the elements to hide
function SG_showElement_hideOthers(idElement) {
    var el_to_show = document.getElementById(idElement)
    el_to_show.style.display = "block";
    for (var i=1; i<arguments.length; i++) {
        var el_to_hide = document.getElementById(arguments[i])
        el_to_hide.style.display = "none";
    }
    return true;
}

//open the image in the visible layer in a new window. Layer id must be a common string vollowed by an integer 
//(i.e. Layer1, Layer2, ecc...). The same for the image id (i.e. imgLayer1, imgLayer2, ecc...). 
//The function loops trough the Layers and check if the style is set to block (i.e Layer3). 
//When found get image src of the image imgLayer3 and open it in a new window. 
//(works with Mozilla, Netscape 6, Internet Explorer 5)
//input: idLayerBaseName -> string containing the base name id of the elements
//       idImageBaseName -> string containing the base name id of the images
//       lang            -> optional. lang to pass to the detail page
function SG_openVisibleLayer(idLayerBaseName, idImageBaseName) {
    for (var i=1; i<Number.MAX_VALUE; i++) {
        var layer_ref = document.getElementById(idLayerBaseName + i.toString());
        if (typeof layer_ref == 'undefined')
            return false;
        if (layer_ref.style.display == "block") {
            image_src = SG_getImageSrc(idImageBaseName + i.toString());
            new_img_src = image_src.substring(0, image_src.length-4) + "G.jpg";
            option_str = "scrollbars,resizable"
            //the escape function below has been deprecated in favor of encodeURI and encodeURIComponent
            //these works only in Explorer 5.5 for Win and Mozilla
            if (arguments.length >= 3)
                new_win = window.open("detail/?img=" + escape(new_img_src) + "&lang=" + arguments[2], "Detail", option_str);
            else
                new_win = window.open("detail/?img=" + escape(new_img_src), "Detail", option_str);
            new_win.focus();
            return false;
        }
    }
}

//open the new window "win_name" with location "an_url" and give it focus
//if a third argument is present it is passed to the window.open function
//input: an_url   -> url to open
//       win_name -> window name
function SG_openWindow_giveFocus(an_url, win_name) {
    if (arguments.length == 3)
        var new_win = window.open(an_url, win_name, arguments[2]);
    else
        var new_win = window.open(an_url, win_name, "");
    new_win.focus();
    return false;
}

/*
 *  HTML functions
 */

//build a link using the prompt function. Returns a string with the link or null.
//(works with Mozilla, Netscape 6, Internet Explorer 5)
//input: className -> optional first argument. Link class name
//       target    -> optional second argument. Link target (default=_blank)
function SG_buildLink() {
    var linkurl = "";
    var linkword = "";
    var target = "_blank";
    var className = "";
    if (arguments.length == 2) {
        className = arguments[0];
        target = arguments[1];
    } else if (arguments.length == 1) {
        className = arguments[0];
    }
    linkurl = prompt("Inserire una URL valida", "http://www.sgconsulting.it/");
    if (linkurl == null || linkurl == "")
        return null;
    linkword = prompt("Inserire le parole da linkare", "Clicca qui");
    if (linkword == null || linkword == "")
        return null;
    if (className != "")
        return '<a href="' + linkurl + '" class="' + className + '" target="' + target + '">' + linkword + '</a>';
    else
        return '<a href="' + linkurl + '" target="' + target + '">' + linkword + '</a>';
}

//append a link to element 'elementid'. Uses SG_buildLink to get the link
//(works with Mozilla, Netscape 6, Internet Explorer 5)
//input: elementid -> string containing the id name of the element where the link must be added.
//       className -> optional first argument. Link class name
//       target    -> optional second argument. Link target (default=_blank)
function SG_addLink(elementid) {
    if (arguments.length == 1)
        var linkstr = SG_buildLink();
    else if (arguments.length == 2)
        var linkstr = SG_buildLink(arguments[1]);
    else
        var linkstr = SG_buildLink(arguments[1], arguments[2]);
    if (linkstr == null) {
        alert("link non valido");
        return false;
    }
    if (document.getElementById(elementid).value) {
        alert(typeof document.getElementById(elementid).value);
        document.getElementById(elementid).value += linkstr;
        return false;
    }
    if (document.getElementById(elementid).innerHTML) {
        document.getElementById(elementid).innerHTML += linkstr;
        return false;
    }
    document.getElementById(elementid).value = linkstr;
    return false;
}

//append <br> tag to element 'elementid'.
//(works with Mozilla, Netscape 6, Internet Explorer 5)
//input: elementid -> string containing the id name of the element where the <br> must be added.
function SG_addBr(elementid) {
    if (document.getElementById(elementid).value) {
        document.getElementById(elementid).value += "<br>";
        return false;
    }
    if (document.getElementById(elementid).innerHTML) {
        document.getElementById(elementid).innerHTML += "<br>";
        return false;
    }
    document.getElementById(elementid).value = "<br>";
    return false;
}

