//Global
if (document.all) {
    var agt = navigator.userAgent.toLowerCase();
    ie  = true; moz = false; op = false;
    if (agt.indexOf("opera") != -1) { op = true; ie = false; moz = false; }
} else {
    ie = false; op = false; moz = true;
}

if (moz) {
    emulateEventHandlers(["click", "mousemove", "keypress", "keyup", "keydown", "mouseover", "mouseout", "mouseup", "mousedown", "focus", "load"]);
}

function emulateEventHandlers(eventNames) {
    for (var i = 0; i < eventNames.length; i++) {
        document.addEventListener(eventNames[i], function (e) {window.event = e;}, true);
    }
}

function attachObjEvent(obj, sEvent, sFunction) {
    if (moz) {
        obj.addEventListener(sEvent, sFunction, false);
    } else {
        obj.attachEvent("on" + sEvent, sFunction);
    }
}

function cancelEvent(objEvent) {
    objEvent.cancelBubble = true;
    objEvent.returnValue = false;

    return false;
}

function ensureMultipartFormData(objInput) {
    if (objInput.form.enctype.toLowerCase() != "multipart/form-data") {
        alert("File will not be accepted by server because form has not multipart/form-data enctype.\nPlease notify that at site administrator.");
    }
}

function getChild(oParent, iIndex) {
    var iCount = 0;

    for (var i = 0; i < oParent.childNodes.length; i++) {
        if (oParent.childNodes[i].nodeType == 1) {
            if (iCount == iIndex) {
                return oParent.childNodes[i];
            }

            iCount++;
        }
    }
}

function LTrim(value) {
    var re = /\s*((\S+\s*)*)/;
    return value.replace(re, "$1");
}

function RTrim(value) {
    var re = /((\s*\S+)*)\s*/;
    return value.replace(re, "$1");
}

function trim(value) {
    return LTrim(RTrim(value));
}

function nl2br(str) {
    return str.replace(/(\r\n)|(\n\r)|\r|\n/g,"<br>");
}

function br2nl(str) {
    return str.replace(/(<br>)|(<br \/>)/g,"\r");
}

function hasValue(arrArray, strValue) { 
    for (var i = 0; i < arrArray.length; i++) { 
        if (arrArray[i] == strValue) { 
            return true;  
        }
    } 
    
    return false; 
}

function replaceAll(strValue, strOld, strNew) {
    strNew = "" + strNew;
    if (strNew.indexOf(strOld) < 0) {
        while (strValue.indexOf(strOld) > -1) {
            strValue = strValue.replace(strOld, strNew); 
        } 
    }

    return strValue; 
}

function number_format(strValue, intDecimals, strGroupSep, strDecSep) {
    strValue = Math.round(strValue * Math.pow(10, intDecimals)) / Math.pow(10, intDecimals);

    if (parseFloat(strValue) >= 0) {
        e = strValue + '';
        n = false;
    } else {
        e = (strValue * -1) + '';
        n = true;
    }
    
    f = e.split('.');

    if (!f[0]) { f[0] = '0';}
    if (!f[1]) { f[1] = ''; }
    if (f[1].length < intDecimals) {
        g = f[1];

        for (i=f[1].length + 1; i <= intDecimals; i++) {
            g += '0';
        }

        f[1] = g;
    }

    if(strGroupSep != '' && f[0].length > 3) {
        h = f[0];
        f[0] = '';

        for(j = 3; j < h.length; j+=3) {
            i = h.slice(h.length - j, h.length - j + 3);
            f[0] = strGroupSep + i +  f[0] + '';
        }

        j = h.substr(0, (h.length % 3 == 0) ? 3 : (h.length % 3));
        f[0] = j + f[0];
    }

    strDecSep = (intDecimals <= 0) ? '' : strDecSep;

    if (n) { f[0] = "-" + f[0]; };
    return f[0] + strDecSep + f[1];
}

//Input controls
function checkCapsLock(objMsgAlert, e)
{
    var keyCode=0;
    var myShiftKey=false;
    var ctl = document.getElementById(objMsgAlert);

    if (objMsgAlert && ctl != null)
    {
        if ( document.all ) {mykeyCode=e.keyCode;myShiftKey=e.shiftKey;}
        else if ( document.layers ) {mykeyCode=e.which;myShiftKey=( mykeyCode == 16 ) ? true : false;}
        else if ( document.getElementById ) {mykeyCode=e.which;myShiftKey=( mykeyCode == 16 ) ? true : false;}

        if ( ( mykeyCode >= 65 && mykeyCode <= 90 ) && !myShiftKey ) {ctl.style.display="block";}
        else if ( ( mykeyCode >= 97 && mykeyCode <= 122 ) && myShiftKey ) {ctl.style.display="block";}
        else {ctl.style.display="none";}
    }
}

function checkTextareaMaxlength(obj, maxlength) {
    if (obj.value.length > maxlength) {
        obj.value = obj.value.substring(0, maxlength);
    }
}

function customValuesKeyPress(id, event) {
    var keyCode = (event.keyCode ? event.keyCode : event.wich);

    switch (keyCode) {
        case 13:
            customValuesCommand(id, "add");
            return cancelEvent(event);
            break;

    }
}

function customValuesCommand(id, command) {
    var objInput = document.getElementById(id + "_input");
    var objSelect = document.getElementById(id + "_select");
    var objHidden = document.getElementById(id);
    var objOption, index, value;

    switch (command) {
        case "add":
            if (objInput && objInput.value && objSelect) {
                objSelect.options[objSelect.options.length] = new Option(objInput.value, 0);
                objInput.value = '';
            }
            objInput.focus();
            break;

        case "up":
            if (objSelect && objSelect.selectedIndex > 0) {
                index = objSelect.selectedIndex;

                objOption = objSelect.options[index - 1];
                objSelect.options[index - 1] = new Option(objSelect.options[index].text, objSelect.options[index].value);
                objSelect.options[index] = objOption;

                objSelect.selectedIndex = index - 1;
            }
            objSelect.focus();
            break;

        case "down":
            if (objSelect && objSelect.selectedIndex < objSelect.options.length - 1) {
                index = objSelect.selectedIndex;

                objOption = objSelect.options[index + 1];
                objSelect.options[index + 1] = new Option(objSelect.options[index].text, objSelect.options[index].value);
                objSelect.options[index] = objOption;

                objSelect.selectedIndex = index + 1;
            }
            objSelect.focus();
            break;

        case "delete":
            if (objSelect && objSelect.selectedIndex > -1) {
                objSelect.options[objSelect.selectedIndex] = null;
            }
            objSelect.focus();
            break;
    }

    if (objSelect && objHidden) {
        value = "";

        for (var i = 0; i < objSelect.options.length; i++) {
            value += objSelect.options[i].value + "||" + objSelect.options[i].text.replace("||", "|") + "||";
        }

        objHidden.value = value;
    }
}

function commandSetLocaleClick(strId) {
    var objCmd = document.getElementById('commandSetLocale');
    var objLoading = document.getElementById(strId + '_loading');

    if (objLoading) {
        objLoading.style.visibility = "visible";
    }

    if (objCmd) {
        objCmd.click();
    }
}

function setInitialControl(sId) {
    attachObjEvent(window, "load", function(event) {
        var o = document.getElementById(sId);
        if (o) o.focus();
    });
}

function submitInNewWindow(strFormId, strName, strParams) {
    var objForm = document.getElementById(strFormId);
    
    if (objForm) {
        var objWindow = window.open("about:blank", strName, strParams);

        if (objWindow) {
            objForm.target = strName;
        } else {
            objForm.target = "_blank";
        }
    }   
}

//HtmlInputImagesControl
function hiic_upload(strId, strUploadSrc) {
	var par = window.parent.document;

	// hide old iframe
	var iframes = par.getElementsByTagName('iframe');
	var iframe = iframes[iframes.length - 1];
	iframe.style.visibility = 'hidden';
    iframe.style.width = '0px';
    iframe.style.height = '0px';

	// create new iframe
	var new_iframe = par.createElement('iframe');
	new_iframe.src = strUploadSrc;
	new_iframe.frameBorder = '0';
	iframe.parentNode.appendChild(new_iframe);

	// add image progress
	var images = par.getElementById(strId + '_container');
	var new_div = par.createElement('div');
	var new_img = par.createElement('img');
	new_img.src = 'src/images/loading.gif';
	new_img.className = 'load';
	new_div.appendChild(new_img);
	images.appendChild(new_div);
	
	// send
	var imgnum = images.getElementsByTagName('div').length - 1;
	document.iform.imgnum.value = imgnum;
	setTimeout("document.iform.submit();", 5000);
}

function hiic_sortable(strId) {
    Sortable.create(strId + "_container", {tag:'div',overlap:'horizontal',constraint:false});
}

function hiic_delete(objImageCont) {
    Effect.Fade(objImageCont, {delay: 0, duration: .2, afterFinish: function() {objImageCont.parentNode.removeChild(objImageCont);} });
}

//ItemsListEditor
function ile_add(strIdItemsListEditor) {
    var objILE = $(strIdItemsListEditor);
    var objChild = getChild(objILE, 0);
    var objInput;

    var objNew = objChild.cloneNode(true);
    _ile_resetRecursive(objNew, "_0", "_" + objILE.getElementsByTagName("li").length, true);

    objILE.appendChild(objNew);

    objInput = objNew.getElementsByTagName("input");
    objInput[0].focus();
}

function ile_delete(strIdItemsListEditor, strIdRow) {
    var objILE = $(strIdItemsListEditor);
    var objRow = $(strIdRow);
    var strOldId, strNewId;

    if (objILE.getElementsByTagName("li").length > 1) {
        objILE.removeChild(objRow);

        for (var i = parseInt(strIdRow.substring(strIdRow.indexOf("_") + 1)); i < objILE.getElementsByTagName("li").length; i++) {
            strOldId = replaceAll(strIdRow, strIdRow.substring(strIdRow.indexOf("_")), "_" + (i + 1));
            _ile_resetRecursive($(strOldId), "_" + (i + 1), "_" + i, false);
        }
    }
}

function ile_up(strIdItemsListEditor, strIdRow) {
    var current = parseInt(strIdRow.substring(strIdRow.indexOf("_") + 1));
    var prefix = strIdRow.substring(0, strIdRow.indexOf("_") + 1);
    
    var objILE = $(strIdItemsListEditor);
    var objRow = $(strIdRow);
    var objRowChange = $(prefix + "" + (current - 1));

    if (objRow != null && objRowChange != null && current > 0) {
        objILE.removeChild(objRow);
        objILE.insertBefore(objRow, objRowChange);

        _ile_resetRecursive(objRow, "_" + current, "_" + (current - 1), false);
        _ile_resetRecursive(objRowChange, "_" + (current - 1), "_" + current, false);
    }
}

function ile_down(strIdItemsListEditor, strIdRow) {
    var current = parseInt(strIdRow.substring(strIdRow.indexOf("_") + 1));
    var prefix = strIdRow.substring(0, strIdRow.indexOf("_") + 1);

    ile_up(strIdItemsListEditor, prefix + "" + (current + 1));
}

function ile_empty(strIdItemsListEditor) {
    var objILE = $(strIdItemsListEditor);
    var objChild = getChild(objILE, 0);
    var strId = objChild.id.substring(0, objChild.id.indexOf("_") + 1);

    while (objILE.getElementsByTagName("li").length > 1) {
        ile_delete(strIdItemsListEditor, strId + "1");
    }

    _ile_resetRecursive(objChild, strId + "0", strId + "0", true);
}

function _ile_resetRecursive(obj, strOldId, strNewId, blnResetValues) {
    var arrAttrs = ["id", "name", "for", "href", "onclick", "onchange", "onfocus", "onblur"];

    for (var a in arrAttrs) {
        if (obj.getAttribute(arrAttrs[a]) && obj.getAttribute(arrAttrs[a]).indexOf(strOldId) > -1) {
            obj.setAttribute(arrAttrs[a], replaceAll(obj.getAttribute(arrAttrs[a]), strOldId, strNewId));
        }
    }

    if (blnResetValues) {
        if (obj.tagName.toLowerCase() == "input" && (obj.type.toLowerCase() == "text" || obj.type.toLowerCase() == "password" || obj.type.toLowerCase() == "hidden" || obj.type.toLowerCase() == "file")) {
            obj.value = "";
        } else if (obj.tagName.toLowerCase() == "input" && (obj.type.toLowerCase() == "checkbox" || obj.type.toLowerCase() == "radio")) {
            obj.checked = false;
        } else if (obj.tagName.toLowerCase() == "textarea" || obj.tagName.toLowerCase() == "select") {
            obj.value = "";
        }
    }

    for (var i = 0; i < obj.childNodes.length; i++) {
        if (obj.childNodes[i].nodeType == 1) {
            _ile_resetRecursive(obj.childNodes[i], strOldId, strNewId, blnResetValues);
        }
    }
}

//Lists an edits
function toggleListCheck(objSource) {
    var i = 0;
    var chk = objSource.checked;

    while (objChild = objSource.form.elements[i]) {
        if (objChild.tagName.toLowerCase() == "input" && objChild.name.indexOf(objSource.name) > -1) {
            objChild.checked = chk;
        }

        i++;
    }
}

function verifyOneChecked(objButton, strPrefix) {
    var i = 0;

    while (objChild = objButton.form.elements[i]) {
        if (objChild.tagName.toLowerCase() == "input" && objChild.name != strPrefix && objChild.name.indexOf(strPrefix) > -1 && objChild.checked == true) {
             return true;
        }

        i++;
    }

    return false;
}

function confirmCommand(strQuestion, objEvent) {
    if (!confirm(strQuestion)) {
        return cancelEvent(objEvent);
    } else {
        return true;
    }
}

function confirmVerifyOneCheckedCommand(objButton, strPrefix, strQuestion, strNoChecked, objEvent) {
    if (verifyOneChecked(objButton, strPrefix)) {
        return confirmCommand(strQuestion, objEvent);
    } else {
        alert(strNoChecked);
        return cancelEvent(objEvent);
    }
}

//Footer
attachObjEvent(window, "load", function() { attachObjEvent(window.document.body, "click", function() { setTimeout('if(document.getElementById(\'footer\')) {document.getElementById(\'footer\').className=\'\';document.getElementById(\'footer\').className=\'footer\';}', 50); } ); } )
