/**
 * Utility za validaciju formi
 *
 * by Matija Tomaskovic
 */

/**
 * Npr:
 * <a href="javascript: validirajFormu(document.MainForm);">Validiraj</a>
 */
function validirajFormu(forma) {
  forma.akcija.value="validiraj";
  forma.submit();
}



/**
 * Validacija decimalni polja.
 *
 * Ako je polje prazno - ništa ne radi.
 * Ako je polje popunjeno:
 *      "1234" -> "1.234,00"
 *      "1234,56" -> "1.234,56"
 *      "tekst" -> javlja grešku da nije dobro upisan broj
 */
function provjeriDecimale(textObject) {
    provjeriDecimaleEx(textObject, 2);
}


/**
 * Validacija decimalni polja.
 *
 * Ako je polje prazno - ništa ne radi.
 * Ako je polje popunjeno:
 *      "1234" -> "1.234,00"
 *      "1234,56" -> "1.234,56"
 *      "tekst" -> javlja grešku da nije dobro upisan broj
 */
function provjeriDecimaleEx(textObject, iBrojDecimala, vLang) {
    var s = textObject.value;
    if (s == "")
        return;
    //alert("Vrijednost:" + s);

    var sPredznak = "";
    if (s.charAt(0) == '-') {
        sPredznak = "-";
        s = s.substring(1);
    }

    if (s == "") {
        if (vLang == "en")
            alert("Bad number value!.");
        else
            alert("Broj je pogresno upisan!\nUpisan je samo predznak.");
        textObject.focus();
        return;
    }

    // Preskaniraj string i sve brojeve do prvog zareza, bez tocki, stavi u cijeli dio
    // a sve brojeve nakon zareza u decimalni dio

    var sCijeli = "";
    var sDecimalni = "";
    var bNasaoZarez = false;
    for (i=0; i<s.length; i++) {
        var c = s.charAt(i);
        //alert("c=" + c + "; nasao zarez=" + bNasaoZarez + "; Cijeli=" + sCijeli + "; Decimalni=" + sDecimalni);
        if (!bNasaoZarez) {
            if (c == ',') {
                bNasaoZarez = true;
                continue;
            }
            else {
                if (c == '.')
                    continue;
                if (!isDigit(c)) {
                    if (vLang == "en")
                        alert("Bad number value!\nCharacter '" + c + "' is not allowed");
                    else
                        alert("Broj je pogresno upisan!\nZnak '" + c + "' nije dozvoljen u cijelom dijelu broju");
                    textObject.focus();
                    return;
                }
                sCijeli = sCijeli + c;
            }
        }
        else {
            if (!isDigit(c)) {
                if (vLang == "en")
                    alert("Bad number value!\nCharacter '" + c + "' is not allowed");
                else
                    alert("Broj je pogresno upisan!\Znak '" + c + "' nije dozvoljen u decimalnom dijelu broja");
                textObject.focus();
                return;
            }
            sDecimalni = sDecimalni + c;
        }
    }

    //alert("Formatiram: Cijeli=" + sCijeli + "; Decimalni=" + sDecimalni);
    // Sad nadodaj cijelom dijelu broja tocke ("12345" -> "12.345")
    var sFormatirani = "";
    for (t=0; t<sCijeli.length; t++) {
        //alert("Formatiram: " + t + "; " + sFormatirani);
        if ((sCijeli.length - t) % 3 == 0 && sFormatirani.length > 0)
            sFormatirani = sFormatirani + ".";
        sFormatirani = sFormatirani + sCijeli.charAt(t);
    }

    // Nadodaj do trazenog broja decimale
    if (iBrojDecimala > 0) {
        sFormatirani = sFormatirani + ",";
        t=0;
        while(t<iBrojDecimala) {
            //alert("Formatiram dec.: " + t + "; " + sFormatirani);
            if (t<sDecimalni.length)
                sFormatirani = sFormatirani + sDecimalni.charAt(t);
            else
                sFormatirani = sFormatirani + "0";
            t++;
        }
    }

    textObject.value = sPredznak + sFormatirani;
}

function isDigit(c) {
    if (c>='0' && c<='9')
        return true;
    else
        return false;
}


function selectVrijednost(selectObj, vrijednost) {
    if (typeof(selectObj) == "undefined") {
        alert("Select objekt '" + selectObj + "' nije definiran");
        return;
    }
    if (typeof(selectObj.options) == "undefined") {
        alert("Select objekt '" + selectObj.name + "' nema definirane options.");
        return;
    }
    for (var i=0; i<selectObj.options.length; i++) {
        //alert("COMPARE: " + selectObj.options[i].value + " :: " + vrijednost);
        if (selectObj.options[i].value == vrijednost) {
            selectObj.selectedIndex = i;
            return;
        }
    }
}

function selectRadioVrijednost(radioObj, vrijednost) {
    if (typeof(radioObj) == "undefined") {
        alert("Radio objekt '" + radioObj + "' nije definiran");
        return;
    }
    for (var i=0; i<radioObj.length; i++) {
        if (radioObj[i].value == vrijednost) {
            radioObj[i].checked = true;
        }
        else {
            radioObj[i].checked = false;
        }
    }
}

function getRadioValue(radioObj) {
    for (i=0; i<radioObj.length; i++) {
        if (radioObj[i].checked)
            return radioObj[i].value;
    }
    return null;
}

function toggleAllCheckBoxes(strNameFilter, checkboxTemplateObject, objSrcForm) {

    var checkedValue = checkboxTemplateObject.checked;
    for (var i=0; i<objSrcForm.elements.length; i++) {
        var strVar = objSrcForm.elements[i].name;
        if (strVar.indexOf(strNameFilter) == -1)
            continue;
        var strVal = objSrcForm.elements[i].value;
        var strType = objSrcForm.elements[i].type;
        if (strType == "checkbox") {
            objSrcForm.elements[i].checked = checkedValue;
        }
    }
}

function setCheckboxValue(checkboxObj, v_value, v_on_value) {
    checkboxObj.checked = v_on_value;
}


function preslikajCheckboxVrijednost(checkboxObj, targetField, strValueOn, strValueOff) {
    if (checkboxObj.checked)
        targetField.value = strValueOn;
    else
        targetField.value = strValueOff;
}

function makeReadonly(obj) {
    var strVar = obj.name;
    var strVal = obj.value;
    var strType = obj.type;
    if (strType == "text") {
        obj.className = "readonly";
        obj.disabled = true;
    }
    else if (strType == "textarea") {
        obj.className = "readonly";
        obj.disabled = true;
    }
    else if (strType == "checkbox") {
        // obj.className = "readonly";
        obj.disabled = true;
    }
    else if (strType.indexOf("select") == 0) {
        obj.className = "readonly";
        obj.disabled = true;
    }
}

function makeAllReadonly(objSrcForm) {

    for (var i=0; i<objSrcForm.elements.length; i++) {
        var obj = objSrcForm.elements[i];
        makeReadonly(obj);
    }
}


function izvrsiAkciju(objForm, v_akcija) {
  objForm.akcija.value=v_akcija;
  objForm.submit();
  return false;
}



function execMainFormAction(v_action) {
    document.MainForm.akcija.value = v_action;
    //document.MainForm.submit();
    doSubmit();
}


function disableButtons() {

    var allInputElements = document.getElementsByTagName('input');
    for( x=0; x<allInputElements.length; x++ ) {
        var v_element = allInputElements[x];
        if ((v_element.type == "submit") || (v_element.type == "button")) {
            v_element.disabled = true;
            v_element.onclick = function() { window.status = 'disabled'; /* alert('disabled'); */ };
        }
    }

    var allHrefs = document.getElementsByTagName('a');
    for( x=0; x<allHrefs.length; x++ ) {
        var v_a = allHrefs[x];
        v_a.disabled = true;
        v_a.href = "#";
        v_a.onclick = function() { window.status = 'disabled'; /* alert('disabled'); */ };
    }

    if (document.images["img_button_insert"]) {
        document.images["img_button_insert"].src = img_insert_d.src; // "modules/m_discover/images/title_icon_new_d.gif";
        document.images["img_button_insert"].className = "imgbutton_d";
        document.images["img_button_insert"].parentNode.className = "title_icon_link_d";
    }

    if (document.images["img_button_save"]) {
        document.images["img_button_save"].src = img_save_d.src; // "modules/m_discover/images/title_icon_save_d.gif";
        document.images["img_button_save"].className = "imgbutton_d";
        document.images["img_button_save"].parentNode.className = "title_icon_link_d";
    }

    if (document.images["img_button_delete"]) {
        document.images["img_button_delete"].src = img_delete_d.src; // "modules/m_discover/images/title_icon_delete_d.gif";
        document.images["img_button_delete"].className = "imgbutton_d";
        document.images["img_button_delete"].parentNode.className = "title_icon_link_d";
    }

    if (document.images["img_button_close"]) {
        document.images["img_button_close"].src = img_close_d.src; // "modules/m_discover/images/title_icon_close_d.gif";
        document.images["img_button_close"].className = "imgbutton_d";
        document.images["img_button_close"].parentNode.className = "title_icon_link_d";
    }

    return true;

}


function execMainFormSubaction(v_subaction, v_row) {
    //alert(v_row);
    if (typeof(document.MainForm.row) != "undefined") {
        //alert(v_row);
        document.MainForm.row.value = v_row;
    }
    document.MainForm.podakcija.value = v_subaction;
    //document.MainForm.submit();
    doSubmit();
}

/**
 * Use this method to properly encode unicode characters from javascript
 * for URLs as CP1250. Tomcat can't handle %xxxx encoding in parameter values
 * but only %xx. If Tomcat finds %xxxx, it will ignore such parameter, and servlet
 * code will not be able to get value with request.getParameter("naslov").
 *
 * Here is sample:
 * location.href = "app?module=bastina.portal.ShowMessage&amp;naslov=" + escape_to_cp1250(v_naslov);
 */
function escape_to_cp1250(strIn) {
    if (strIn == null)
        return null;
    strOut = "";
    s = "";
    for (i=0; i<strIn.length; i++) {
        ch = strIn.charAt(i);
        c = strIn.charCodeAt(i);
        s += ch;
        s += "("+c+");";
        if (ch==' ') ch = "%20";
        else if (ch>='0' && ch<='9') {
            // it is same
        }
        else if (ch>='a' && ch<='z') {
            // it is same
        }
        else if (ch>='A' && ch<='Z') {
            // it is same
        }
        else if (c==353) ch = "%9A"; // 154;   // sh
        else if (c==273) ch = "%F0"; // 240;   // dj
        else if (c==269) ch = "%E8"; // 232;   // c"h
        else if (c==263) ch = "%E6"; // 230;   // c'h
        else if (c==382) ch = "%9E"; // 158;   // zh
        else if (c==352) ch = "%8A"; // 138;   // SH
        else if (c==272) ch = "%D0"; // 208;   // DJ
        else if (c==268) ch = "%C8"; // 200;   // C"h
        else if (c==262) ch = "%C6"; // 198;   // C'h
        else if (c==381) ch = "%8E"; // 142;   // Zh
        else {
            var lo = c & 15;
            var hi = (c >> 4) & 15;
            var strHex = "0123456789ABCDEF";
            ch = "%" + strHex.charAt(hi) + strHex.charAt(lo);
        }
        strOut += ch;
    }
    //alert(strIn + " -> " + strOut);
    return strOut;
}


function openTranslatorById(v_table_name, v_column_name, v_field) {
    wnd_openDialog(new Array(), 780, 550,
        "app?module=admin.Translator&amp;popup=da&amp;akcija=define_data_label" +
        "&amp;data_label_area=data." + v_table_name + "." + v_column_name +
        "&amp;data_label_key=data." + v_table_name + ".id." + escape_to_cp1250(document.MainForm.id.value) +
        "&amp;data_label_original=" + escape_to_cp1250(v_field.value));
}

function prepare_for_url(strIn) {
    var s = remove_xml_markup(strIn);
    return escape_to_cp1250(s);
}

/**
 * Use this method to get valid value in javascript code
 * from value from XSL:
 *
 * In XSL:
 * var v_name = remove_xml_markup('<xsl:value-of select="@name"/>');
 *
 * In XHTML result:
 * var v_name = remove_xml_markup('Test &amp; &lt;> &#34; &amp;amp;');
 */
function remove_xml_markup(strIn) {
    if (strIn == null)
        return null;
    var strOut = "";
    var i=0;
    while(i<strIn.length) {
        ch = strIn.charAt(i++);
        if (ch == '&') {
            if (i >= strIn.length) {
                strOut += ch;
            }
            else {
                if (strIn.indexOf("lt;", i) == i) {
                    strOut += "<";
                    i += 3;
                }
                else if (strIn.indexOf("gt;", i) == i) {
                    strOut += ">";
                    i += 3;
                    alert(strOut);
                }
                else if (strIn.indexOf("amp;", i) == i) {
                    strOut += "&";
                    i += 4;
                }
                else if (strIn.charAt(i) == '#') {
                    ch = strIn.charAt(i++);
                    if (i == strIn.length) {
                        strOut += ch;
                        continue;
                    }
                    var hi = strIn.charAt(i++);
                    if (i == strIn.length) {
                        strOut += ch + hi;
                        continue;
                    }
                    var lo = strIn.charAt(i++);
                    if (i == strIn.length) {
                        strOut += ch + hi + lo;
                        continue;
                    }
                    var d = strIn.charAt(i++);
                    if (d != ';') {
                        strOut += ch + hi + lo + d;
                        continue;
                    }
                    var b = ((hi - '0') * 10) + (lo-'0');
                    //alert ("HI: " + hi + "; LO: " + lo + " B=" + b + "; " + String.fromCharCode(b));
                    strOut += String.fromCharCode(b);
                }
                else {
                    // continue - unknown sequence
                    strOut += ch;
                }
            }
        }
        else {
            strOut += ch;
        }
    }
    //alert("REMOVED: " + strIn + " -> " + strOut);
    return strOut;
}

function chr(c) {
    var h = c.toString (16);
    h = unescape ('%'+h);
}

function doDeleteSelected() {
    if (confirm("Da li ste sigurni da želite obrisati označeno?\nPritisnite Ok za da, Cancel za ne")) {
        execMainFormAction("delete_selected");
    }
}
