﻿/*****************
 * 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;
}

/**************
 * 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 = 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);
}