var aeOL = [];
function addEvent(o, n, f, l)
{
 var a = 'addEventListener', h = 'on'+n, b = '', s = '';
 if (o[a] && !l) return o[a](n, f, false);
 o._c |= 0;
 if (o[h])
 {
  b = '_f' + o._c++;
  o[b] = o[h];
 }
 s = '_f' + o._c++;
 o[s] = f;
 o[h] = function(e)
 {
  e = e || window.event;
  var r = true;
  if (b) r = o[b](e) != false && r;
  r = o[s](e) != false && r;
  return r;
 };
 aeOL[aeOL.length] = { o: o, h: h };
};
addEvent(window, 'unload', function() {
 for (var i = 0; i < aeOL.length; i++) with (aeOL[i])
 {
  o[h] = null;
  for (var c = 0; o['_f' + c]; c++) o['_f' + c] = null;
 }
});

function cancelEvent(e, c)
{
if(e){
 e.returnValue = false;
 if (e.preventDefault) e.preventDefault();
 if (c)
 {
  e.cancelBubble = true;
  if (e.stopPropagation) e.stopPropagation();
 }
 }
};

var fiesbt = 0;
function fixIESelectBug(){
    var objs = document.getElementsByTagName('select');
    for(var i=0; i<objs.length; i++){
        var obj = objs[i];
        obj.style.visibility = fiesbt==0 ? "hidden":"visible";
    }
    fiesbt = 1 - fiesbt;
}

/************************************
 * Focus on the field with error
 */
function focusError(id) {
    try {
        getAspObj(id).focus();
        window.scrollBy(0,50);
    } catch(e) {}
}
/*****************
 * restrics the chars that are valid to enter in a textbox
 ******************
 ** e : keypress event of the element
 ** validchar: list of valid chars in string (eg. '0123456789')
 ***
 */
function keyRestrict(e, validchars) {
 var key='', keychar='';
 key = getKeyCode(e);
 if (key == null) return true;
 keychar = String.fromCharCode(key);
 keychar = keychar.toLowerCase();
 validchars = validchars.toLowerCase();
 if (validchars.indexOf(keychar) != -1)
  return true;
 if ( key==null || key==0 || key==8 || key==9 || key==13 || key==27 )
  return true;
 return false;
}

function keyRestrictAR(e){
    var key='', 
        keychar='';
    key = getKeyCode(e);
    if (key == null) 
        return true;
    keychar = String.fromCharCode(key); 
    if ( key==null || key==0 || key==8 || key==9 || key==13 || key==27 || key==32 )  
        return true; 
    if(key>=1523) // Arabic Characters
        return true; 
    if(keychar >= '0' && keychar <= '9')  // Numbers
        return true; 
    if(keychar == '.' || keychar == '-' || keychar == ',') // Special characters . - ,
        return true;
    return false;
}

/**************
 * Formatting the currency
 * *************
 */
function round_decimals(original_number, decimals) {
    var result1 = original_number * Math.pow(10, decimals)
    var result2 = Math.round(result1)
    var result3 = result2 / Math.pow(10, decimals)
    return pad_with_zeros(result3, decimals)
}

function pad_with_zeros(rounded_value, decimal_places) {
    var value_string = rounded_value.toString()
    var decimal_location = value_string.indexOf(".")
    if (decimal_location == -1) {
        decimal_part_length = 0
        value_string += decimal_places > 0 ? "." : ""
    }
    else {
        decimal_part_length = value_string.length - decimal_location - 1
    }
    var pad_total = decimal_places - decimal_part_length
    if (pad_total > 0) {
        for (var counter = 1; counter <= pad_total; counter++) 
            value_string += "0"
        }
    return value_string
}

/************
 * Format number (eg. 12.095 => 12.10)
 ***********************
 *** n => floating point number
 **********
 */
function formatNumber(n){
    n = round_decimals(n,2);
    var result = '';
    var txt = n + '';
    result = txt.substring(txt.indexOf('.'),txt.length);
    txt = txt.substring(0,txt.indexOf('.'));
    while(txt.length>3){
        
        if(result.indexOf('.')>0) result = ',' + result;
        result = txt.substring(txt.length-3,txt.length) + result;
        txt = txt.substring(0,txt.length-3);
    }
    if(result.indexOf('.')>0) result = ',' + result;
    result = 'AED ' + txt + result;
    return result;
}

/***********
 * Read number from text
 */
function readNumber(txt){
    if(txt==null || txt=='') return 0;
    var v = removeFormat(txt);
    v = parseFloat(v);
    if(v!=0 && !v) return 0;
    return v;
}

/****************
 * returns key code of the key event
 ***
 */
function getKeyCode(e)
{
 if (window.event)
    return window.event.keyCode;
 else if (e)
    return e.which;
 else
    return null;
}

/**********
 * Removes characters like AED or comma(',') from input string
 ***********
 */
function removeFormat(n){
    var txt = n + '';
    var AED = /AED/;
    var comma = /,/g;
    txt = txt.replace(AED,'').replace(comma,'');
    return (txt);
}

/*
* required field validator for text, checkbox and select fields.
*/
function requiredFieldValidator(id) {
    var obj = getAspObj(id);  
    if(obj == null) {return true;}
    if(obj){
        switch(obj.type){
            case 'text': return (obj.value.length != 0);
            case 'textarea': return (obj.value.length != 0);
            case 'select-one':
                return (obj.selectedIndex!=0);
            default: return (checked(id));
        }
    }else return 0;
}

/******************************
 * URL Validator
 #NOTE#######################
 # No need to use it directly. Validate function will use it.
 ############################
 */
function urlValidator(id){
    var url = getAspObj(id).value;
    if(!url || url.length==0) return 1;
    var RegExp = /^(([\w]+:)?\/\/)?(([\d\w]|%[a-fA-f\d]{2,2})+(:([\d\w]|%[a-fA-f\d]{2,2})+)?@)?([\d\w][-\d\w]{0,253}[\d\w]\.)+[\w]{2,4}(:[\d]+)?(\/([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)*(\?(&?([-+_~.\d\w]|%[a-fA-f\d]{2,2})=?)*)?(#([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)?$/;
    if(RegExp.test(url)){
        return 1;
    }else{
        return 0;
    } 
}

/******************************
 * Email Address Validator
 #NOTE#######################
 # No need to use it directly. Validate function will use it.
 ############################
 */
function emailAddressValidator(id){
    var email = getAspObj(id).value;
    if(!email || email.length==0) return 1;
    var RegExp = /^((([a-z]|[0-9]|!|#|$|%|&|'|\*|\+|\-|\/|=|\?|\^|_|`|\{|\||\}|~)+(\.([a-z]|[0-9]|!|#|$|%|&|'|\*|\+|\-|\/|=|\?|\^|_|`|\{|\||\}|~)+)*)@((((([a-z]|[0-9])([a-z]|[0-9]|\-){0,61}([a-z]|[0-9])\.))*([a-z]|[0-9])([a-z]|[0-9]|\-){0,61}([a-z]|[0-9])\.)[\w]{2,4}|(((([0-9]){1,3}\.){3}([0-9]){1,3}))|(\[((([0-9]){1,3}\.){3}([0-9]){1,3})\])))$/
    if(RegExp.test(email)){
        return 1;
    }else{
        return 0;
    } 
}

/*
* test a value versus a specific format if they match or not.
*/
function formatValidator(id, format){
    var obj = getAspObj(id).value;
    try{
    if(!obj || obj.length==0) return true;
    }catch(e){}
    if(format.test(obj)) {
        return true;
    } else {
        return false;
    } 
}

 /**************
 * returns checked-state of the specified checkbox
 */
function checked(id){
    try{
        return getAspObj(id).checked;
    }catch(e){return false;}
}

/*
*   returns the object specified by id.
*/
function getObj(id) {
    return document.getElementById(id);
}

function getAspObj(id){
    var result = document.getElementById(id);
    if(result!=null) return result;
    var tagsName = ['select','input','div','span','textarea','label'];
    var k = 0;
    for(k=0; k<tagsName.length; k++){
        var objs = document.getElementsByTagName(tagsName[k]);
        var i;
        for(i=0; i<objs.length; i++){
            var obj = objs[i];
            var objid = null;
            try{
                objid = obj.getAttribute('id');
            }catch(e){}
            if(objid!=null && objid.indexOf(id)!=-1) return obj;
        }
    }
    return null;
}

/*
*   Form Validations
*/
var Validation_Enabled = true; 
function Validate(i){
    var result = null;
    try{
        switch(validators[i][1])
        {
            default:
                result = eval(validators[i][1] + "('" + validators[i][2] + "')");
                break;
        } 
    }catch(e){}
    return result;
}
function checkRealTime(){
    var result = true;
    for(var j=0; j<arguments.length; j++) {
        for(var i=0; i<validators.length; i++){
            if(validators[i][0]==arguments[j]){
                var eobj = getAspObj('e_' + validators[i][2]);
                if(Validate(i) && result){
                    if(eobj) if(eobj.className) eobj.className = eobj.className.replace(/error/g,"");
                }else{
                    if(eobj) eobj.className += " error";
                    result = false; 
                }                     
                break;   
            }
        }
    }
}
function onSubmit(){
    if(!Validation_Enabled) return true;            
    var i;
    var errArea = getAspObj('ErrorArea');
    var errBody = getAspObj('ErrorBody');
    errBody.innerHTML = "";
    var _continue = true;
    for(i=0; i<validators.length; i++){
        var eobj = getAspObj(validators[i][4]);
        if(Validate(i)){
            if(eobj) if(eobj.className) eobj.className = eobj.className.replace("error","");
        }else{
            if(eobj) eobj.className += " error";
            errBody.innerHTML += "<li><a class=\"error\" href=\"javascript:focusError('" + validators[i][2] + "')\">" + validators[i][3] + "</a></li>";
            _continue = false;
        }
    }
    if(!_continue){
        errArea.style.display = "inline";
        window.scroll(0,250);
    }else{
        errArea.style.display = "none";
    }
    return _continue;
} 
/*
*   End Form Validations
*/

function TreeMenuToggle(id){
    var obj = document.getElementById(id);
    var objImg = document.getElementById(id + "_link");
    if(obj){
        if(obj.className.indexOf("hidden")>-1){
            obj.className = obj.className.replace("hidden", "visible");
            objImg.style.backgroundPosition = "0px -240px";
        }
        else{
            obj.className = obj.className.replace("visible","hidden");
            objImg.style.backgroundPosition = "0px -200px";
        }
    }
}

/*
Review Control
*/
var approvedHTML = '<div class="approveIcon" style="margin-right:3px;">&nbsp;</div><span class="approvedText">Reviewed and according to requirements</span><a class="cancel" href="javascript:void(0);" onclick="goToHistory(\'#id#\')">Cancel</a>';
var infoHTML = '<div class="infoIcon"></div><span class="infoText">&nbsp;#MSG#</span><a class="cancel" href="javascript:void(0);" onclick="goToHistory(\'#id#\')">Cancel</a><a class="edit" href="javascript:void(0);" onclick="editAdditionaInfo(\'#id#\')">Edit</a>';
function approved(id){
    var msg = $(id + '_msg');
    var value = $(id+'_value');
    value.value = '';
    msg.innerHTML = approvedHTML.replace('#id#',id);
    $(id + '_flag').value = 'true';
}
var dialog = null;
var currentActionTarget = null;

function additionalInfo(id){
    currentActionTarget = id;
    dialog = new Control.Modal(false,
    {
        iframe:true,
        href:'additionalInfoMessage.aspx',
        closeOnClick:false,
        width:340,
        height:205
    });
    dialog.open();
}

function editAdditionaInfo(id){
    var msg = $(id + '_value').value;
    currentActionTarget = id;
    dialog = new Control.Modal(false,
    {
        iframe:true,
        href:'additionalInfoMessage.aspx?msg=' + encodeURIComponent(msg),
        closeOnClick:false,
        width:340,
        height:205
    });
    dialog.open();
}
function goToHistory(id){
    var objs = $(document.body).select('input[name*=' + id + ']');
    if(objs.length==0) return;
    var historyItemIndex = -1;
    for(var i =0; i<historyValues.length; i++){
        if(historyValues[i][0]==id){
            historyItemIndex = i;
            break;
        }
    }
    for(var i=0; i<objs.length; i++){
        objs[i].checked = (i+1)==historyValues[historyItemIndex][1] ? 'checked' : '';
    }
    $(id + '_msg').innerHTML = historyValues[historyItemIndex][3];
    $(id + '_value').value = historyValues[historyItemIndex][2];
    $(id + '_flag').value = 'false';
}
function dialogResult(result){
    if(dialog) dialog.close();
    dialog.destroy();
    if(result=='#CANCEL#' || result.length==0){
        // rollback to history
        goToHistory(currentActionTarget);
    }else if(result=='#CANCEL#__'){
        currentActionTarget = null;
    }else{
        $(currentActionTarget + '_msg').innerHTML = infoHTML.replace('#MSG#',result).replace(/#id#/g,currentActionTarget);
        $(currentActionTarget + '_value').value = result;
        $(currentActionTarget + '_flag').value = 'true';
    }
    currentActionTarget = null;
}

function msgToNew(id){
    currentActionTarget = id;
    var stringVal = $(currentActionTarget + '_value').value;
    dialog = new Control.Modal(false,
    {
        iframe:true,
        href:'Modules/Messaging/selectto.aspx?cv=' + currentActionTarget + '_value',
        closeOnClick:false,
        width:470,
        height:205
    });
    dialog.open();
}

function msgdialogResult(result){
    if(dialog) dialog.close();
    dialog.destroy();
    if(result=='#CANCEL#' || result.length==0){
        currentActionTarget = null;
    }else{
        var divVal = "";
        var vals = result.split('|');
        for(var i=0; i<vals.length; i++){
            if(vals[i].length==0) continue;
            divVal += vals[i].substring(0,vals[i].indexOf('-_-'));
            divVal +='; ';
        }
        $(currentActionTarget + '_text').value = divVal;
        $(currentActionTarget + '_value').value = result;
    }
    currentActionTarget = null;
}

function tmpNew(id){
    currentActionTarget = id;
    dialog = new Control.Modal(false,
    {
        iframe:true,
        href:'Modules/Messaging/selecttemplates.aspx',
        closeOnClick:false,
        width:470,
        height:340
    });
    dialog.open();
}

function tmpdialogResult(result){
    if(dialog) dialog.close();
    dialog.destroy();
    if(result=='#CANCEL#' || result.length==0){
        currentActionTarget = null;
    }else{
        var oEditor = FCKeditorAPI.GetInstance(currentActionTarget);
        oEditor.InsertHtml(result);
        
        
    }
    currentActionTarget = null;
}