/************************************************************************
Validation funcs
************************************************************************

--------GUIDELINES FOR USAGE OF FUNCTIONS ----------------------
set the id of form elements as directed here and 
call the CheckEntireForm(objForm) in the form submit evet
i.e. <form onSubmit = "return CheckEntireForm(MyFormName)" ... >

RQ-Y/N REQUIRED(SHOULD NOT BE BLANK)
NM-Y/N NAME
NU-Y/N NUMERIC
FN-Y/N FLOAT NUMERIC
NUR-Y/N NUMERIC RANGE
NURMX-n MAX NUMERIC RANGE
NURMN-n MIN NUMERIC RANGE
NRC-Y/N CHECK NUMEIC RANGE
PH-Y/N PHONE
EM-Y/N EMAIL
CMX-n CONTROL HAS n AS MAX RANGE
CMN-n CONTROL HAS n AS MIN RANGE
CRC - Y/N CHECK CONTROL LENGTH RANGE
LBC-Y/N- CONTROL IS A LIST BOX CONTROL AND CHECK THAT A SELECTON IS MADE
MSS - XYZ... MESSAGE TO THROW IF VALIDATION FAILED
SPA - Y/N space is not allowed
FUP - Y/N if a file upload comp
TFP - P/C p=picture ; c = cv
URL-Y/N - For Url

A SAMPLE ID IS SHOWN HERE
RQ-Y|NU-Y|CMN-3|CMX-8|MSS-EMPLYOEE_INCOME_LEVEL
this field is a required field, it can only accept
numeric data and can contain only 3 to 8 char length number
it is EMPLYOEE INCOME LEVEL (notice underscore as space is not allowwd)
***********************************************************************************
*/


//Global constants for message throwing
var MESS_BLANK = new String("Please specify a value for the field: ")
var MESS_RANGE = new String("Please specify a value in the valid range for the field: ")
var MESS_NUMERIC = new String("Please specify a valid numeric value for the field: ")
var MESS_NAME = new String("Please specify a valid name for the field, only alphabets and numbers allowed: ")
var MESS_NUMERIC_RANGE = new String("Please specify a numeric value in the given range for the field: ")
var MESS_PHONE = new String("Please specify a valid phone number in the format xxx-xxx-xxxxxxxx for the field: ")
var MESS_EMAIL = new String("The email address you have entered seems to be invalid. Please enter a valid email address. If you believe you got this message in an error, please call us and someone will assist you personally : ")
var MESS_CHAR_DATA = new String("Please specify a value with the specified min/max length for the field: ")
var MESS_LIST = new String("Please select an option from the list : ")
var MESS_START = new String("PLEASE FILL THIS FORM AS SPECIFIED HERE :\n--------------------------------------------------------------------")
var MESS_FUP = new String("The file you have selected for upload is not a valid file for the field: ")
var MESS_STRICTNUMERIC = new String("Please enter a whole number for the field : ")
//var MESS_PASSWORD = new String("Please enter a valid value (Alphabets,numbers, _ are allowed) for the field :")
var MESS_PASSWORD = new String("Space,single and double quotes characters are not allowed for the field :")
var MESS_URL = new String("Invalid format for the field :")
//x



//Function to search  through an entire select list and highlight a specific option value based on passed arguement ObjList = Name of select list
function SelectListOption(ObjList, StrOptionValue) {
    for (i = 0; i < ObjList.length; i++) {
        if (ObjList.options[i].text == StrOptionValue) {
            ObjList.options[i].selected = "1";
            return true;
        }
    }
    return false;
}

//Function to check / uncheck checkbox form control
function SelectCheckBox(ObjCheckBox, boolCheck) {
    if (boolCheck) {
        ObjCheckBox.checked = true;
        return true;
    }
    else {
        ObjCheckBox.checked = false;
        return false;
    }
}

//get ascii char code of arg
function GetAsciiCode(argChar) {
    var s = new String(argChar);
    return parseInt(s.charCodeAt(0));
}

//check if arg is pure numeric and a +ive whole number 
function IsNumeric(sText) {
    var ValidChars = "0123456789.";
    var IsNumber = true;
    var Char;

    if (isNaN(sText) == true)
        return false;

    for (i = 0; i < sText.length && IsNumber == true; i++) {
        Char = sText.charAt(i);
        if (ValidChars.indexOf(Char) == -1) {
            IsNumber = false;
        }
    }
    return IsNumber;

}
//check valid password
//------Space,single and double quotes will not allowed -------------------------   
function IsPassword(sText) {
    if (sText.match(/\s|\"|\'/g) == null)
        return true;
    else
        return false
}
//check if arg is pure numeric and a +ive whole number 
function IsStrictNumeric(sText) {
    var ValidChars = "0123456789";
    var IsNumber = true;
    var Char;


    for (i = 0; i < sText.length && IsNumber == true; i++) {
        Char = sText.charAt(i);
        if (ValidChars.indexOf(Char) == -1) {
            IsNumber = false;
        }
    }
    return IsNumber;

}
//func for char checking 
function IsValid(argValue, argValidChars) {
    var ValidChars = argValidChars;
    var ret = true;
    var Char;

    for (i = 0; i < argValue.length && ret == true; i++) {
        Char = argValue.charAt(i);
        if (ValidChars.indexOf(Char) == -1) {
            ret = false;
        }
    }
    return ret;
}
//check if arg is  numeric and a +ive decimal number
function IsFloatOrNumeric(argStr) {
    var s = new String(argStr);
    var cnt = 0;
    len = s.length;
    if (IsBlank(argStr)) { return false; }
    for (i = 0; i < len; i++) {
        intCh = GetAsciiCode(s.charAt(i));

        if (intCh == 46) //there can't be more than one decimal
        {
            cnt++;
            if (cnt > 1)
                return false;
        }

        if (intCh == 46 && (i == 0 || i == len - 1))//first char and last char cannot be decimal
        {
            return false;
        }

        if (!((intCh >= 48 && intCh <= 57) || (intCh == 46))) {
            return false;
        }
    }
    return true;
}

//check if a string contains whitespaces or nothing ...
function IsBlank(argStr) {
    var s = new String(argStr);
    var cnt = 0;
    len = s.length;

    for (i = 0; i < len; i++) {
        intCh = GetAsciiCode(s.charAt(i));
        if (intCh == 32) {
            cnt++;
        }
    }
    if ((cnt == len) || (cnt == 0 && len == 0)) {
        return true;
    }
    return false;
}

//check if a string contains special characters
function IsSpecialCharacter(argStr) {
    var s = new String(argStr);
    var cnt = 0;
    len = s.length;
    if (IsBlank(argStr)) { return false; }

    for (i = 0; i < len; i++) {
        intCh = GetAsciiCode(s.charAt(i));
        if ((intCh >= 0 && intCh <= 31) || (intCh >= 127 && intCh <= 255)) {
            return true;
        }
    }
    return false;
}

//check if a string abides to a min , max range rule for an input field
function IsLengthBetweenRange(argStr, MIN, MAX) {
    var s = new String(argStr)
    len = s.length;
    if (len < MIN || len > MAX) {
        return false;
    }
    return true;
}

//check valid international phone number xxx-xxx-xxxxxxxx
function IsValidInternationalPhoneFaxNumber(argStr) {
    var s = new String(argStr);
    var cnt = 0;
    len = s.length;

    if (IsThereAnyWhiteSpace(argStr) == true) {
        return false;
    }

    if (!(s.indexOf("-") >= 0)) {
        return false;
    }

    arr = s.split("-")

    if (arr.length != 3) {
        return false;
    }

    var countrycode = new String(arr[0]);
    var statecode = new String(arr[1]);
    var localcode = new String(arr[2]);

    if (IsNumeric(countrycode) == false || IsNumeric(statecode) == false || IsNumeric(localcode) == false) {
        return false;
    }

    if (IsLengthBetweenRange(countrycode, 2, 3) == false || IsLengthBetweenRange(statecode, 2, 3) == false || IsLengthBetweenRange(localcode, 4, 8) == false) {
        return false;
    }

    return true;
}

//check if arg contains no white spaces
function IsThereAnyWhiteSpace(argStr) {
    var s = new String(argStr);
    var cnt = 0;
    len = s.length;
    if (IsBlank(argStr)) {
        return false;
    }

    if (s.indexOf(" ") >= 0) {
        return true;
    }
    return false;
}
//check if number is between given range
function CheckNumericRange(argStr, MIN, MAX) {
    if (IsNumeric(argStr) == true) {
        var n = new Number(argStr);

        if (n < MIN || n > MAX) {
            return false;
        }
        else {
            return true;
        }
    }
    else {
        return false;
    }
}
function IsValidName(argStr) {
    var s = new String(argStr);
    var cnt = 0;
    len = s.length;

    for (i = 0; i < len; i++) {
        intCh = GetAsciiCode(s.charAt(i));
        if (!((intCh >= 48 && intCh <= 57) || (intCh >= 65 && intCh <= 90) || (intCh >= 97 && intCh <= 122))) {
            return false;
        }
    }
    return true;
}
function IsValidEmail(argStr) {
    var s = new String(argStr);
    s = trim(s);
    if (IsBlank(s) == true) { return true; }

    if (CheckEmail(argStr) == false)
        return false;
    else
        return true;

    /*if(IsThereAnyWhiteSpace(s)==true) { return false;}
    if(IsValid(s,"qwertyuiopasdfghjklzxcvbnm0123456789-@_.QWERTYUIOPASDFGHJKLZXCVBNM")==false) return false;
    if(s.indexOf('@')<1) { return false;}
	
    var dotCount;
    var id = new String();
    var dom = new String();
	
    arr=s.split('@')
	
    id  = arr[0];
    dom = arr[1];
		
    if (id.length<1) { return false;}
    if (dom.length<4) { return false;}
    if (dom.indexOf('.')<1) { return false;}
    return true;*/
}

function IsValidScreenName(val) {
    trim(val);
    var reg = /^[\w]+$/gi;
    if (val == "")
        return false;
    else if (reg.test(val))
        return true;
    else
        return false;
}

function CheckEmail(val) {
    if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(val))
        return (true);
    else
        return (false);
}
function IsValidUrl(value) {
    var s = trim(value);
    if (IsBlank(s) == true) { return true; }

    // var tomatch = /^(https?):\/\/(www\.)?[a-z0-9\-\.\/]{2,}$/;
    // var tomatch = /(ht|f)tp(s?)\:\/\/[0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*(:(0-9)*)*(\/?)([a-zA-Z0-9\-\.\?\,\'\/\\\+&amp;%\$#_]*)?$/;
    var strREg = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;
    if (strREg.test(s)) {
        return true;
    }
    else {
        return false;
    }
}
function IsListBoxSelected(objListBox) {
    if (objListBox.options.length == 0)
        return false;
    if (objListBox.options[objListBox.selectedIndex].value == 0) {
        return false;
    }
    return true;
}
//resolve extra data passed with a control to the form and get name - value pairs 
function GetCommand(CONTROL_DATA, MKEY) {
    arr = CONTROL_DATA.split("|")
    for (i = 0; i < arr.length; i++) {
        arr2 = arr[i].split("-");
        if (arr2[0] == MKEY) {
            return arr2[1];
        }
    }
}
/*fn :: restrict the user to select only gif,jpe,png files for photo uploading */
function IsValidFile(argStr, type) {
    var fileExt = new Array();
    if (type.toUpperCase() == 'P')//picture
    {
        fileExt[0] = "GIF";
        fileExt[1] = "JPEG";
        fileExt[2] = "PNG";
        fileExt[3] = "JPG";
        fileExt[4] = "BMP";
    }
    if (type.toUpperCase() == 'C')//cv
    {
        fileExt[0] = "TXT";
        fileExt[1] = "DOC";
        fileExt[2] = "XLS";
        fileExt[3] = "ZIP";
        fileExt[4] = "HTM";
        fileExt[5] = "HTML";
        fileExt[5] = "DOCX";
        fileExt[5] = "PDF";
    }

    dt = argStr;
    if (dt.length > 0) {
        dotpos = dt.lastIndexOf(".");
        ext = dt.substr(dotpos + 1);
        for (i = 0; i < fileExt.length; i++) {
            if (ext.toUpperCase() == fileExt[i]) {
                return true;
            }
        }
        return false;
    }
    else {
        //if no file is selected then return true as there is nothin to check
        return true;
    }
    return false;
}
//***********************************************************************************************
//This function takes the form obj as arg and processes all it's elements by the ids passed to it
//***********************************************************************************************

function CheckEntireForm(objForm) {
    var intFormElements = new Number(); 	//number of form elements
    var obj; 							//pointer to particular object of form
    var i; 								//loop var
    var COMMAND_STRING = new String(); 	//command string of form control
    var FINAL_MESSAGE = new String(); 	//message to throw if validation fails


    var RQ; 								//required field
    var NM; 								//name field
    var NU; 								//numeric fields
    var FN; 								//float numeric
    var NUR; 							//numeric range
    var NURMX; 							//if nur then max numeric range
    var NURMN; 							//if nur then min numeric range
    var PH; 								//phone field
    var EM; 								//email field

    var CMX; 							//field max length
    var CMN; 							//field min length
    var LBC; 							//control is a list box select
    var MSS_CONTROL; 					//mss associated with a control(message)
    var SPA; 							//spaces not allowed

    var NRC;
    var CRC;
    var FUP;
    var TFP;
    var STN; 							//STRICT NUMERIC NO DECIMALS
    var PWD; 							//password field

    var YES = "Y"; 						//constants for the ease of distinguishing
    var NO = "N"; 							//constants for the ease of distinguishing
    var URL; 							    //URL field
    var CONTROL_VALUE;
    var m;

    //get number of form elements
    intFormElements = objForm.elements.length;

    //seperate messages for all elements
    var MESSAGE_ARRAY = new Array(intFormElements)

    //Add new field for focus by ashok kumar
    var focusField = "";

    //loop through all elements
    for (i = 0; i < intFormElements; i++) {
        obj = objForm.elements[i]

        COMMAND_STRING = obj.lang;
        //alert(COMMAND_STRING);
        COMMAND_STRING = COMMAND_STRING.toUpperCase();

        //get custom validation

        RQ = GetCommand(COMMAND_STRING, "RQ");
        NM = GetCommand(COMMAND_STRING, "NM");
        NU = GetCommand(COMMAND_STRING, "NU");
        FN = GetCommand(COMMAND_STRING, "FN");
        NUR = GetCommand(COMMAND_STRING, "NUR");
        NURMX = GetCommand(COMMAND_STRING, "NURMX");
        NURMN = GetCommand(COMMAND_STRING, "NURMN");
        PH = GetCommand(COMMAND_STRING, "PH");
        EM = GetCommand(COMMAND_STRING, "EM");
        CMX = GetCommand(COMMAND_STRING, "CMX");
        CMN = GetCommand(COMMAND_STRING, "CMN");
        LBC = GetCommand(COMMAND_STRING, "LBC");
        MSS_CONTROL = GetCommand(COMMAND_STRING, "MSS");
        SPA = GetCommand(COMMAND_STRING, "SPA");
        NRC = GetCommand(COMMAND_STRING, "NRC");
        CRC = GetCommand(COMMAND_STRING, "CRC");
        FUP = GetCommand(COMMAND_STRING, "FUP")
        TFP = GetCommand(COMMAND_STRING, "TFP")
        STN = GetCommand(COMMAND_STRING, "STN")
        PWD = GetCommand(COMMAND_STRING, "PWD")
        URL = GetCommand(COMMAND_STRING, "URL")


        //= Added new line by ashok,removing all trailing space and blank line before checking constraints =====================				
        if (COMMAND_STRING != "" && (obj.type == "text" || obj.type == "textarea")) {
            Trimmer(obj);
        }
        if (obj.style.display.toLowerCase() == "none") {
            MESSAGE_ARRAY[i] = "";
            continue;
        }
        //===========================================================================================================

        CONTROL_VALUE = obj.value
        MESSAGE_ARRAY[i] = ""

        //check required
        if (RQ == YES) {
            if (IsBlank(CONTROL_VALUE) == true) {
                MESSAGE_ARRAY[i] = MESS_BLANK + MSS_CONTROL
            }
        }
        //check name
        if (NM == YES) {
            if (IsValidName(CONTROL_VALUE) == false && MESSAGE_ARRAY[i].length == 0) {
                MESSAGE_ARRAY[i] = MESS_NAME + MSS_CONTROL;
            }
        }
        //check strict numeric
        if (STN == YES) {
            if (IsStrictNumeric(CONTROL_VALUE) == false && MESSAGE_ARRAY[i].length == 0) {
                MESSAGE_ARRAY[i] = MESS_STRICTNUMERIC + MSS_CONTROL;
            }
        }
        //check numeric
        if (NU == YES) {
            if (IsNumeric(CONTROL_VALUE) == false && MESSAGE_ARRAY[i].length == 0) {
                MESSAGE_ARRAY[i] = MESS_NUMERIC + MSS_CONTROL;
            }
        }
        //check float numeric
        if (FN == YES) {
            if (IsFloatOrNumeric(CONTROL_VALUE) == false && MESSAGE_ARRAY[i].length == 0) {
                MESSAGE_ARRAY[i] = MESS_NUMERIC + MSS_CONTROL;
            }
        }
        //check password
        if (PWD == YES) {
            if (IsPassword(CONTROL_VALUE) == false && MESSAGE_ARRAY[i].length == 0) {
                MESSAGE_ARRAY[i] = MESS_PASSWORD + MSS_CONTROL;
            }
        }
        //check numeric with range
        if (NUR == YES) {
            if (STN == YES) {
                if (IsStrictNumeric(CONTROL_VALUE) == false && MESSAGE_ARRAY[i].length == 0) {
                    MESSAGE_ARRAY[i] = MESS_NUMERIC + MSS_CONTROL;
                }
            }
            else {
                if (IsNumeric(CONTROL_VALUE) == false && MESSAGE_ARRAY[i].length == 0) {
                    MESSAGE_ARRAY[i] = MESS_NUMERIC + MSS_CONTROL;
                }
            }
        }

        if (NRC == YES && MESSAGE_ARRAY[i].length == 0) {
            if (CheckNumericRange(CONTROL_VALUE, NURMN, NURMX) == false && MESSAGE_ARRAY[i].length == 0) {
                MESSAGE_ARRAY[i] = MESS_NUMERIC_RANGE + MSS_CONTROL + "[Range: " + NURMN + " to " + NURMX + " ]";
            }
        }

        //check phone number
        if (PH == YES && MESSAGE_ARRAY[i].length == 0) {
            if (IsValidInternationalPhoneFaxNumber(CONTROL_VALUE) == false && MESSAGE_ARRAY[i].length == 0) {
                MESSAGE_ARRAY[i] = MESS_PHONE + MSS_CONTROL;
            }
        }

        //check email
        if (EM == YES && MESSAGE_ARRAY[i].length == 0) {
            if (IsValidEmail(CONTROL_VALUE) == false && MESSAGE_ARRAY[i].length == 0) {
                MESSAGE_ARRAY[i] = MESS_EMAIL + MSS_CONTROL;
            }
        }
        //check Url

        if (URL == YES && MESSAGE_ARRAY[i].length == 0) {
            if (IsValidUrl(CONTROL_VALUE) == false) {
                MESSAGE_ARRAY[i] = MESS_URL + MSS_CONTROL;
            }
        }
        //check length for character data
        if (CRC == YES && MESSAGE_ARRAY[i].length == 0) {
            if (IsLengthBetweenRange(CONTROL_VALUE, parseInt(CMN), parseInt(CMX)) == false && MESSAGE_ARRAY[i].length == 0) {
                MESSAGE_ARRAY[i] = MESS_CHAR_DATA + MSS_CONTROL + " Range (" + CMN + " to " + CMX + " )";
            }
        }
        //check if value  from a list is selectd
        if (LBC == YES && MESSAGE_ARRAY[i].length == 0) {
            if (IsListBoxSelected(obj) == false && MESSAGE_ARRAY[i].length == 0) {
                MESSAGE_ARRAY[i] = MESS_LIST + MSS_CONTROL;
            }
        }
        //check file upload is havin a valid file upload

        if (FUP == YES && MESSAGE_ARRAY[i].length == 0) {
            if (IsValidFile(CONTROL_VALUE, TFP) == false) {
                if (TFP == 'P') { var e = new String("GIF,JPG,PNG,BMP") }
                if (TFP == 'C') { var e = new String("TXT,DOC,HTM,CSV,ZIP,XLS,DOCX,PDF") }
                MESSAGE_ARRAY[i] = MESS_FUP + MSS_CONTROL + " Valid file formats are : " + e;
            }
        }

    }

    //end checking form controls
    m = "";
    for (i = 0; i < intFormElements; i++) {
        m += MESSAGE_ARRAY[i];
    }

    if (m != "") {
        FINAL_MESSAGE += MESS_START + "\n\n"

        for (i = 0; i < intFormElements; i++) {
            if (MESSAGE_ARRAY[i] != "") {
                //FINAL_MESSAGE+="("+parseInt(i+1)+") "+MESSAGE_ARRAY[i]+"\n";
                FINAL_MESSAGE += '» ' + MESSAGE_ARRAY[i] + "\n";

                //Focus handling
                if (focusField == "") {
                    focusField = objForm.elements[i];
                }
            }
        }
        alert(FINAL_MESSAGE);
        try {
            focusField.focus();
        }
        catch (ex) {
        }
        return false;
    }
    else {
        return true;
    }
}
// Removes leading whitespaces
function LTrim(value) {
    var re = /\s*((\S+\s*)*)/;
    return value.replace(re, "$1");

}

// Removes ending whitespaces
function RTrim(value) {
    var re = /((\s*\S+)*)\s*/;
    return value.replace(re, "$1");

}

// Removes leading and ending whitespaces
function trim(value) {
    return LTrim(RTrim(value));

}

//function to trim a string
function Trimmer(controlName) {
    pVal = controlName.value;
    TRs = 0;
    for (i = 0; i < pVal.length; i++) {
        if (pVal.substr(i, 1) == " " || pVal.charCodeAt(i) == 13 || pVal.charCodeAt(i) == 10) {
            TRs++;
        }
        else
        { break; }
    }

    TRe = pVal.length - 1;
    for (i = TRe; i > TRs - 1; i--) {
        if (pVal.substr(i, 1) == " " || pVal.charCodeAt(i) == 13 || pVal.charCodeAt(i) == 10) {
            TRe--;
        }
        else
        { break; }
    }
    controlName.value = pVal.substr(TRs, TRe - TRs + 1);
}
//function to ltrim a string and remove double space to single space
function Trimmer1(ctrl) {
    ctrl.value = LTrim(ctrl.value);
    ctrl.value = replaceAll(ctrl.value, "  ", " ");
}
//end trim function

function isAlphaNum(str) {
    if (str != "") {
        var regex = /^[0-9a-z]+$/i;
        return regex.test(str);
    }
}
function isAlpha(str) {
    if (str != "") {
        var regex = /^[a-z]+$/i;
        return regex.test(str);
    }
}
//--------Take into into dd-MM-yyyy format and give a date object.
function cDate(val) {
    var tmpDate = val.split('-');
    //var rtnDate = new Date(tmpDate[2],tmpDate[1],tmpDate[0]);
    //Javascript months starts from 0 // parseInt(tmpDate[1]) gives an error,so always use second parameter also
    var rtnDate = new Date(tmpDate[2], tmpDate[1] - 1, tmpDate[0]);
    return rtnDate;
}


//Select/Unselect all checkboxes array
function SelectAll(cntrl, flag) {
    if (cntrl.length == undefined)
        cntrl.checked = flag;
    else {
        for (i = 0; i < cntrl.length; i++) {
            cntrl[i].checked = flag;
        }
    }
}


//--------- Select all checkbox list --------------------------
function SelectChkAll(cntrl, length, flag) {
    var i = 0
    for (i = 0; i < length; i++) {
        document.getElementById(cntrl + "_" + i).checked = flag;
    }
}
//----------------------------------------------------

//Select-Unselect all checkboxes In Datagrid
function SelectDgAll(dgName, chkId, start, length, flag) {
    var i = 0, Id, j = 0;
    for (i = 0; i < length; i++) {
        j = i + parseInt(start);
        j = (j < 10 ? "0" : "") + j;
        Id = document.getElementById(dgName + "_ctl" + j + "_" + chkId);
        Id.checked = flag;
    }
}

//Atleast one check box should be checked in Datagrid
function checkDgAll(dgName, chkId, start, length) {
    var flag = false;
    var i = 0, Id, j = 0;
    for (i = 0; i < length; i++) {
        j = i + parseInt(start);
        j = (j < 10 ? "0" : "") + j;
        Id = document.getElementById(dgName + "_ctl" + j + "_" + chkId);
        if (Id.checked == true) {
            flag = true;
            break;
        }
    }
    return flag;
}

//Atleast one check box should be checked in checkbox Array
function checkAll(cntrl) {
    var error = 0;
    if (cntrl.length == undefined) {
        if (cntrl.checked == true)
            error = 1;
    }
    else {
        for (i = 0; i < cntrl.length; i++) {
            if (cntrl[i].checked == true) {
                error = 1;
                break;
            }
        }
    }
    if (error == 0) {
        return false
    }
}


//------ Check radiobutton or checkbox list that atleast one record should selected
function CheckBoxList(strId, length) {
    var flag = false;
    var i = 0, chkId;
    for (i = 0; i < length; i++) {
        chkId = document.getElementById(strId + "_" + i);
        if (chkId.checked == true) {
            flag = true;
            break;
        }
    }
    return flag;
}
//------------------------------------------------------------------------------

//Confirm deletion
function confirmDel(msg) {
    var tmpMsg = "Do you really want to delete the record ?";
    if (msg && msg != "")
        tmpMsg = msg;
    if (confirm(tmpMsg))
        return true;
    else
        return false;
}
function confirmMsg(msg) {
    if (confirm("Do you really want to " + msg + " it?"))
        return true;
    else
        return false;
}

// ----------- Validate time values ----------------------------------------------
function ValidateTime(ctlTime) {
    var str_time = ctlTime.value;
    var rtnTime = "";
    var RE_NUM = /^\-?\d+$/;
    var arr_time = String(str_time ? str_time : '').split(':');

    if (RE_NUM.exec(arr_time[0]))
        if (arr_time[0] < 24)
            rtnTime = arr_time[0];
        else
            return ("Invalid hours value: '" + arr_time[0] + "'.\nAllowed range is 00-23.");
    else
        return ("Invalid hours value: '" + arr_time[0] + "'.\nAllowed values are unsigned integers.");

    if (!arr_time[1])
        rtnTime += ":0";
    else if (RE_NUM.exec(arr_time[1]))
        if (arr_time[1] < 60)
            rtnTime += ":" + arr_time[1]
        else
            return ("Invalid minutes value: '" + arr_time[1] + "'.\nAllowed range is 00-59.");
    else
        return ("Invalid minutes value: '" + arr_time[1] + "'.\nAllowed values are unsigned integers.");

    if (!arr_time[2]);
    else if (RE_NUM.exec(arr_time[2]))
        if (arr_time[2] < 60)
            rtnTime += ":" + arr_time[2]
        else
            return ("Invalid seconds value: '" + arr_time[2] + "'.\nAllowed range is 00-59.");
    else
        return ("Invalid seconds value: '" + arr_time[2] + "'.\nAllowed values are unsigned integers.");

    ctlTime.value = rtnTime;
    return "";
}

//--------------------------------------------------------------------------------------

function checkfext(frm) {
    Trimmer(frm.file1);
    if (frm.file1.value != '') {
        var dotpos = frm.file1.value.lastIndexOf(".");
        var ext = frm.file1.value.substr(dotpos + 1);
        if (ext.toUpperCase() == 'PDF' || ext.toUpperCase() == 'DOC' || ext.toUpperCase() == 'GIF' || ext.toUpperCase() == 'JPG' || ext.toUpperCase() == 'JPEG') {
            return true;
        }
        else {
            alert("Upload File type is PDF,DOC,GIF & JPEG");
            frm.file1.focus();
            return false;
        }
    }
}

//========== Highlight current row color for given id table=========================
//blid = Table Id
function tableRuler(tblId) {
    if (document.getElementById && document.createTextNode) {
        var tables = document.getElementById(tblId);
        if (tables) {
            var trs = tables.getElementsByTagName('tr');
            for (var j = 0; j < trs.length; j++) {
                if (trs[j].parentNode.nodeName == 'TBODY' && trs[j].className.indexOf("dgh") == -1) {
                    trs[j].onmouseover = function () { this.oldClass = this.className; this.style.backgroundColor = 'green'; return false }
                    trs[j].onmouseout = function () { this.className = this.oldClass; this.style.backgroundColor = ''; return false }
                }
            }
        }
    }
}

//-------- Calucalte two date difference in years -------------
function CalculateAge(fromDate, toDate) {
    var age = toDate.getFullYear() - fromDate.getFullYear();
    if (fromDate.getMonth() > toDate.getMonth() || (fromDate.getMonth() == toDate.getMonth() && fromDate.getDate() > toDate.getDate()))
        age -= 1

    return age;
}
//-------------------------------------------------------------

//=================================================================================
// Show user details in intranet --------------------------------------------- //
function ShowUserDetails(val, userType) {
    var path = "userDetails.aspx?id=" + val + "&userType=" + userType;
    showWindow(path, 600, 500);
}
//---------------------------------------------------------------------------- //
//<!----================================================================================================-->
function replaceAll(str, find, replace) {
    var reg = new RegExp(find, "gi");
    str = str.replace(reg, replace)
    return str;
}


//=============== HightLight Current Menu =============
function PageName(strPage) {
    var sPage = strPage.substring(strPage.lastIndexOf('/') + 1);
    return sPage.toLowerCase();
}
function highlightMenu(pageName) {
    var i;
    try {
        var totLinks = document.links.length;
        for (i = 0; i < totLinks; i++) {
            if (PageName(document.links[i].href) == pageName)
            //if(pageName.indexOf( PageName(document.links[i].href)) != -1)
            {
                document.links[i].className = "highlightMenu";
                break;
            }
        }
    }
    catch (ex) {
        //		alert(ex.description);
    }
}
//=====================================================

function showWindow(page, width, height, left, top, isScroll) {

    var winWidth = 500;
    var winHeight = 200;
    var winLeft = 280;
    var scroll = "yes";
    var winTop = 50;
    //----Set width height,top and bottom position ----------------
    if (width)
        winWidth = width;
    if (height)
        winHeight = height;

    if (left)
        winLeft = left;
    if (top)
        winTop = top;
    if (isScroll)
        scroll = "no";
    //------------------------------------------------------------	
    var str = "width=" + winWidth + ",height=" + winHeight + ",menubar=no,scrollbars=" + scroll + ",toolbar=no,location=no,directories=no,resizable=1,top=" + winTop + " ,left=" + winLeft + "";

    //---------- Unique window name ---------------
    //---Replace all non character data
    var exp = new RegExp(/[^a-z]/gi);
    var winName = page.replace(exp, "");
    //----------------------------------------------

    win = window.open(page, winName, str);
    if (win && !win.closed) win.focus();
}
function showModalWindow(page, width, height, left, top) {
    var winWidth = 500;
    var winHeight = 200;
    var winLeft = 280;
    var scroll = "yes";
    var winTop = 50;
    //----Set width height,top and bottom position ----------------
    if (width)
        winWidth = width;
    if (height)
        winHeight = height;

    if (left)
        winLeft = left;
    if (top)
        winTop = top;
    //------------------------------------------------------------	

    //---------- Unique window name ---------------
    //---Replace all non character data
    var exp = new RegExp(/[^a-z]/gi);
    var winName = page.replace(exp, "");
    //----------------------------------------------

    if (window.showModalDialog) {
        win = showModalDialog(page, winName, "dialogWidth:" + winWidth + "px; toolbar:0; dialogHeight:" + winHeight + "px;top=" + winTop + " ,left=" + winLeft + ",status:0; resizable=0;");
    }
    else {
        var str = "width=" + winWidth + ",height=" + winHeight + ",menubar=no,toolbar=no,location=no,directories=no,resizable=1,top=" + winTop + " ,left=" + winLeft + ",dialog=YES,modal=YES";
        win = window.open(page, winName, str);
    }
    if (win && !win.closed) win.focus();
}

function showPrivacyPolicy() {
    showWindow('privacyPolicy.aspx', 700, 300);
}
function showStayLoggedinHelp() {
    showWindow('logged_help.html', 500, 300);
}

function AddFormElement(eleName, eleType, eleValue, eleParent) {
    var ele = document.createElement(eleType);
    ele.setAttribute("type", "hidden");
    ele.name = eleName;
    ele.value = eleValue;
    if (eleParent)
        eleParent.appendChild(ele);

    return ele;
}

function ShowWaitMessage(msgDivId) {
    var IW = window.innerWidth ? window.innerWidth : document.body.clientWidth;
    var posLeft = (IW - 300) / 2;
    // var IH = self.outerheight;
    self.scrollTo(0, 0);

    var divId = "";
    divId = document.getElementById(msgDivId);
    divId.style.left = posLeft + "px";
    divId.style.visibility = "visible";
    divId.style.zIndex = 99;
}

function adjustAreaSize(area, defaultSize, maxSize) {
    //  area.setRows(2);    // Min height, and causes shrink
    /*  area.rows = 2;
    while (area.getScrollHeight() > area.getOffsetHeight())
    {
    //area.setRows(area.getRows() + 1);
    area.rows = area.rows + 1;
    }*/

    if (!defaultSize)
        defaultSize = "30";
    if (!maxSize)
        maxSize = "200";

    area.style.height = defaultSize + "px";
    if ((area.scrollHeight + 12) > area.offsetHeight) {
        var tmpHeight = (area.scrollHeight + 16);
        if (tmpHeight > maxSize)
            tmpHeight = maxSize;

        area.style.height = tmpHeight + "px";
    }
}

function SetFieldTitle(id) {
    var fld = document.getElementById(id);
    if (fld && fld.title != "") {
        Trimmer(fld);
        if (fld.value == "") {
            fld.value = fld.title;
            fld.className = "tt1";
        }
        //$(fld).addClass('text-label');


        fld.onfocus = function () {
            if (this.value.toLowerCase() == this.title.toLowerCase()) {
                this.value = '';
                this.className = "tt1";
                //$(this).removeClass('text-label');
            }
        };

        fld.onblur = function () {
            Trimmer(this);
            if (this.value == '') {
                this.value = this.title; // $(this).attr('title');
                this.className = "tt1";
                //$(this).addClass('text-label');
            }
        };
    }
}
//=============== Copy data into clipboard -===========
function CopyUrl(data) {
    window.clipboardData.setData("text", data);
    alert("URL is successfully copied.");
}
//=====================================================
function CheckFieldTitle(id) {
    var fld = document.getElementById(id);
    if (fld && fld.title != "") {
        if (fld.value.toLowerCase() == fld.title.toLowerCase()) {
            fld.value = '';
            fld.className = "";
        }
    }
}

function CountMaxChar(val, fldCount, maxChars) {

    fldCount.innerHTML = maxChars - parseInt(val.value.length);
    /*if(parseInt(fldCount.value) < 0 && maxChars > 0 )
    {       
    val.value = val.value.substring(0,maxChars);
    fldCount.value = 0;                     
    }    */
}

function CountMinChar(val, fldCount, maxChars) {
    fldCount.innerHTML = parseInt(val.value.length);

}
function FieldEntered(elem_id, default_text) {
    var elem = document.getElementById(elem_id)
    var curr_text = elem.value;
    elem.style.color = 'black';
    if (curr_text == default_text) {
        elem.value = '';
    }
}
function FieldExited(elem_id, default_text) {
    var elem = document.getElementById(elem_id)
    var curr_text = elem.value;
    if (curr_text == '') {
        elem.style.color = 'black';
        elem.value = default_text;
    }
}
function ShowTwiiterDateFormat(dt) {

    var rtnStr = dt;



    try {

        var curDate = new Date();

        var offset = curDate.getTimezoneOffset();

        var curTimeSpan = curDate.getTime() - offset;

        var entryTimeSpan = Date.parse(dt);



        var delta = Math.floor((curTimeSpan - entryTimeSpan) / 1000);



        if (delta < 0) {

        }

        else if (delta < 60)

            rtnStr = (delta <= 1 ? "1 second ago" : delta + " seconds ago");

        else if (delta < 3600) {

            var mintues = Math.floor(delta / 60);

            rtnStr = mintues + " minute" + (mintues > 1 ? "s" : "") + " ago";

        }

        else if (delta < 86400) {

            //24 * 60 * 60

            var hours = Math.floor(delta / (60 * 60));

            rtnStr = hours + " hour" + (hours > 1 ? "s" : "") + " ago";

        }

        else if (delta < 2592000) {

            // 30 * 24 * 60 * 60

            var days = Math.floor(delta / (24 * 60 * 60));

            rtnStr = days + " day" + (days > 1 ? "s" : "") + " ago";

        }

        else if (delta < 31104000) {

            //12 * 30 * 24 * 60 * 60

            var months = Math.floor(delta / (30 * 24 * 60 * 60));

            rtnStr = months + " month" + (months > 1 ? "s" : "") + " ago";

        }

    }

    catch (ex) {

    }

    return rtnStr;

}


