document.onmousedown = right;
document.onmouseup = right;
if (document.layers) window.captureEvents(Event.MOUSEDOWN);
if (document.layers) window.captureEvents(Event.MOUSEUP);
window.onmousedown = right;
window.onmouseup = right;

// *****   to check if Date  Entered is Valid or not 		*********
//Function to Validate date
//Parameters: Takes 2 Parameteres
//		1 - The value to validate

function IsValidDate(strDate) {

    //First Parameter is Date String
    //date Format Assumed is mm/dd/yyyy (Ex : 01/01/2000 is 1st Jan 2000)
    //date has only the seperators (/) or (-)
    var year, month, day, strSep, i;
    //strDate=trim(strDate)
    //assigning the seperator
    for (i = 0; i < strDate.length; i++) {
        if (strDate.charAt(i) == "/" || strDate.charAt(i) == "-") {
            strSep = strDate.charAt(i)
            break;
        }
    }
    //Seperate Year,Month,Day
    day = strDate.split(strSep)[0];
    month = strDate.split(strSep)[1];
    year = strDate.split(strSep)[2];

    var months = new Array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);

    //Check for Leap Year & Adjust The days in Feb accordingly
    if (year % 4 == 0) {
        months[1] = 29;
    }

    //Check For Length of Date String
    if (strDate.length < 8 || strDate.length > 10) {

        return false;
    }

    //Check for valid Numbers(Day,month,year)
    if (isNaN(day) || isNaN(month) || isNaN(year)) {
        return false;
    }
    //Check for Valid Month
    if (month > 12 || month < 1) {
        return false;

    }
    //Check For Valid Days
    if (day < 1 || day > months[month - 1]) {
        return false;
    }
    for (var i = 1; i <= strDate.length; i++) {
        if (!((i == 3) || (i == 6))) {
            num = strDate.substring(i, i - 1)

            if (isNaN(num) == true) {
                return false;
            }
        }
        if (((i == 3) || (i == 6))) {
            if (strDate.substring(i, i - 1) != strSep) {
                return false
            }
        }
        return true
    }

    //added here an another condition for seperator
    //Check For Seperators
    if ((strDate.charAt(2) == "/") && (strDate.charAt(5) == "/")) {
        return true
    } else {
        if ((strDate.charAt(2) == "-") || (strDate.charAt(5) == "-")) {
            return true;
        } else {

            return false;
        }
    }

}

function emailValidation(entered) {
    var intCnt
    intCnt = 0;

    apos = entered.indexOf("@");
    dotpos = entered.lastIndexOf(".");
    lastpos = entered.length - 1;
    if (apos < 1 || (dotpos - apos) < 2 || lastpos - dotpos > 3 || (lastpos - dotpos) < 2) {
        return false
    }

    //no dots continuous
    if (entered.charAt(dotpos - 1) == ".") {
        return false
    }

    //counter for @
    for (var j = 0; j < entered.length; j++) {
        if (entered.charAt(j) == "@") {
            intCnt++;
        }
    }

    //only one @ allowed
    if (intCnt != 1) {
        return false
    }

    //checking for speacial characters
    for (var i = 0; i < entered.length; i++) {
        //ascii from 33 to 45, 33- 45, 58-63, 123-126 are checked
        //if (((entered.charAt(i) >= "!") && (entered.charAt(i) <= "-")) ||
        if (((entered.charAt(i) >= "!") && (entered.charAt(i) < "-")) || ((entered.charAt(i) >= "[") && (entered.charAt(i) <= "^")) || ((entered.charAt(i) >= ":") && (entered.charAt(i) <= "?")) || ((entered.charAt(i) >= "{") && (entered.charAt(i) <= "~"))) {
            return false
        }
    }

    return true
}

function right(e) {
    if (navigator.appName == 'Netscape' && (e.which == 3 || e.which == 2)) return false;
    else if (navigator.appName == 'Microsoft Internet Explorer' && (event.button == 2 || event.button == 3)) {
        alert("Sorry, you do not have permission to right click.");
        return false;
    }
    return true;
}

function emailCheck(emailStr) {
/* The following pattern is used to check if the entered e-mail address
       fits the user@domain format.  It also is used to separate the username
       from the domain. */
    var emailPat = /^(.+)@(.+)$/
/* The following string represents the pattern for matching all special
       characters.  We don't want to allow special characters in the address. 
       These characters include ( ) < > @ , ; : \ " . [ ]    */
    var specialChars = "\\(\\)<>@,;:\\\\\\\"\\.\\[\\]"
/* The following string represents the range of characters allowed in a 
       username or domainname.  It really states which chars aren't allowed. */
    var validChars = "\[^\\s" + specialChars + "\]"
/* The following pattern applies if the "user" is a quoted string (in
       which case, there are no rules about which characters are allowed
       and which aren't; anything goes).  E.g. "jiminy cricket"@disney.com
       is a legal e-mail address. */
    var quotedUser = "(\"[^\"]*\")"
/* The following pattern applies for domains that are IP addresses,
       rather than symbolic names.  E.g. joe@[123.124.233.4] is a legal
       e-mail address. NOTE: The square brackets are required. */
    var ipDomainPat = /^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/
/* The following string represents an atom (basically a series of
       non-special characters.) */
    var atom = validChars + '+'
/* The following string represents one word in the typical username.
       For example, in john.doe@somewhere.com, john and doe are words.
       Basically, a word is either an atom or quoted string. */
    var word = "(" + atom + "|" + quotedUser + ")"
    // The following pattern describes the structure of the user
    var userPat = new RegExp("^" + word + "(\\." + word + ")*$")
/* The following pattern describes the structure of a normal symbolic
       domain, as opposed to ipDomainPat, shown above. */
    var domainPat = new RegExp("^" + atom + "(\\." + atom + ")*$")


/* Finally, let's start trying to figure out if the supplied address is
       valid. */

/* Begin with the coarse pattern to simply break up user@domain into
       different pieces that are easy to analyze. */
    var matchArray = emailStr.match(emailPat)
    if (matchArray == null) {
/* Too many/few @'s or something; basically, this address doesn't
         even fit the general mould of a valid e-mail address. */
        alert("Email address seems incorrect (check @ and .'s)");
        document.frmEnquiry.txtemail.focus();
        return false
    }
    var user = matchArray[1]
    var domain = matchArray[2]

    // See if "user" is valid 
    if (user.match(userPat) == null) {
        // user is not valid
        alert("The Username doesn't seem to be valid.")
        document.frmEnquiry.txtemail.focus();
        return false
    }

/* if the e-mail address is at an IP address (as opposed to a symbolic
       host name) make sure the IP address is valid. */
    var IPArray = domain.match(ipDomainPat)
    if (IPArray != null) {
        // this is an IP address
        for (var i = 1; i <= 4; i++) {
            if (IPArray[i] > 255) {
                alert("Destination IP address is invalid!")
                document.frmEnquiry.txtemail.focus();
                return false
            }
        }
        return true
    }

    // Domain is symbolic name
    var domainArray = domain.match(domainPat)
    if (domainArray == null) {
        alert("The domain name doesn't seem to be valid.")
        document.frmEnquiry.txtemail.focus();
        return false
    }

/* domain name seems valid, but now make sure that it ends in a
       three-letter word (like com, edu, gov) or a two-letter word,
       representing country (uk, nl), and that there's a hostname preceding 
       the domain or country. */

/* Now we need to break up the domain to get a count of how many atoms
       it consists of. */
    var atomPat = new RegExp(atom, "g")
    var domArr = domain.match(atomPat)
    var len = domArr.length
    if (domArr[domArr.length - 1].length < 2 || domArr[domArr.length - 1].length > 3) {
        // the address must end in a two letter or three letter word.
        alert("The address must end in a three-letter domain, or two letter country.")
        document.frmEnquiry.txtemail.focus();
        return false
    }

    // Make sure there's a host name preceding the domain.
    if (len < 2) {
        var errStr = "This address is missing a hostname!"
        document.frmEnquiry.txtemail.focus();
        alert(errStr)
        return false
    }

    // If we've gotten this far, everything's valid!
    return true;
}

function textCounter(field, countfield, maxlimit) {
    if (field.value.length > maxlimit) { // if too long...trim it!
        field.value = field.value.substring(0, maxlimit);
    }
    // otherwise, update 'characters left' counter
    else {
        countfield.value = maxlimit - field.value.length;
    }
}

var win = null;

function winpopup(mypage, myname, w, h, pos, infocus, scrollbr) {
    if (pos == "random") {
        myleft = (screen.width) ? Math.floor(Math.random() * (screen.width - w)) : 100;
        mytop = (screen.height) ? Math.floor(Math.random() * ((screen.height - h) - 75)) : 100;
    }
    if (pos == "center") {
        myleft = (screen.width) ? (screen.width - w) / 2 : 100;
        mytop = (screen.height) ? (screen.height - h) / 2 : 100;
    } else if ((pos != 'center' && pos != "random") || pos == null) {
        myleft = 0;
        mytop = 20
    }
    settings = "width=" + w + ",height=" + h + ",top=" + mytop + ",left=" + myleft + ",scrollbars=" + scrollbr + ",location=no,directories=no,status=yes,menubar=no,toolbar=no,resizable=no";
    win = window.open(mypage, myname, settings);
    win.focus();
}

function popupwin(name, width, height, scrollbars) {
    var w = width;
    var h = height;
    var t = (screen.height - h) / 2
    var l = (screen.width - w) / 2
    NewWin = window.open('' + name + '', 'NewWin', 'toolbar=no,status=no, width=' + w + ',height=' + h + ', scrollbars=' + scrollbars + ' ,left=' + l + ',top=' + t + '');
    //return true;
}

function isMobile(obj) {
    obj.value = trimString(obj.value);
    var mobile = obj.value;
    var moblen = obj.value.length;


    if (isNaN(mobile) == true) {
        alert("Invalid Mobile No.");
        obj.focus();
        return false;
    }

    var iszero = mobile.charAt(0);
    //iszero = obj.value.charAt(0);
    //alert (iszero);
    if (iszero == 0) {
        obj.value = mobile.replace(iszero, '');
        obj.focus();
        //alert("SS");
        //return false;
    }

    for (j = 0; j <= moblen; j = j + 1) {
        if ((mobile.charAt(j)) == ".") {
            alert("Decimal not allowed!");
            //document.frmRegt.txtPin.value = "";
            obj.value = mobile.replace('.', '');
            obj.focus();
            return false;
        }
    }

    if ((+moblen) != 10) {
        alert("Mobile No. should be 10 digits long");
        obj.focus();
        return false;
    }
    return true;
}

function DateDifference(varyear, varmonth, varday) {

    var date1 = new Date(varyear, varmonth, varday);
    var curr_date = new Date();
    var date1D = date1.getDate();
    var date1M = date1.getMonth();
    var date1Y = date1.getFullYear();

    var curr_dateD = curr_date.getDate();
    var curr_dateM = curr_date.getMonth();
    var curr_dateY = curr_date.getFullYear();

    if (curr_dateY >= date1Y) {
        //alert("year");
        //return true;
        if (curr_dateY > date1Y) {
            curr_dateM = curr_dateM + 12;
        }

        if (curr_dateM >= date1M) {
            //alert("month");
            //return true;
            if (curr_dateY > date1Y) {
                curr_dateD = curr_dateD + 30;
            }

            if (curr_dateD >= date1D) {
                //alert("day");
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    } else {
        return false;
    }
}






//	****************************************************************************************************************************************

function trimString(str) {
    str = this != window ? this : str;
    return str.replace(/^\s+/g, '').replace(/\s+$/g, '');
}

function AlphaSpace(evt) {
    var charCode = (evt.which) ? evt.which : event.keyCode
    if ((charCode != 32) && (charCode < 65 || charCode > 90) && (charCode < 97 || charCode > 122)) return false;

    return true;
}

function AlphaNumSpace(evt) {
    var charCode = (evt.which) ? evt.which : event.keyCode
    if ((charCode != 32) && (charCode < 48 || charCode > 57) && (charCode < 65 || charCode > 90) && (charCode < 97 || charCode > 122)) return false;

    return true;
}

/* Based on: Travis Beckham ::
http://www.squidfingers.com | http://www.podlob.com
Based on: Manzi Olivier :: http://www.imanzi.com/
Based on: jgw (jgwang@csua.berkeley.edu )/ */

function checkCapsLock(e) {
    var myKeyCode = 0;
    var myShiftKey = false;

    // Internet Explorer 4+
    if (document.all) {
        myKeyCode = e.keyCode;
        myShiftKey = e.shiftKey;

        // Netscape 4
    } else if (document.layers) {
        myKeyCode = e.which;
        myShiftKey = (myKeyCode == 16) ? true : false;

        // Netscape 6
    } else if (document.getElementById) {
        myKeyCode = e.which;
        myShiftKey = (myKeyCode == 16) ? true : false;

    }

    // Upper case letters are seen without depressing the Shift key, therefore Caps Lock is on
    if ((myKeyCode >= 65 && myKeyCode <= 90) && !myShiftKey) {
        alert(errormsg[100]);

        // Lower case letters are seen while depressing the Shift key, therefore Caps Lock is on
    } else if ((myKeyCode >= 97 && myKeyCode <= 122) && myShiftKey) {
        alert(errormsg[100]);

    }
}

function CalcKeyCode(aChar) {
    var character = aChar.substring(0, 1);
    var code = aChar.charCodeAt(0);
    return code;
}

function checkNumber(val) {
    var strPass = val.value;
    var strLength = strPass.length;
    var lchar = val.value.charAt((strLength) - 1);
    var cCode = CalcKeyCode(lchar);


/* Check if the keyed in character is a number
     do you want alphabetic UPPERCASE only ?
     or lower case only just check their respective
     codes and replace the 48 and 57 */

    if (cCode < 48 || cCode > 57) {
        var myNumber = val.value.substring(0, (strLength) - 1);
        val.value = myNumber;
    }
    return false;
}

function isEmpty(str) {
    return (str == null) || (str.length == 0);
}
// returns true if the string is a valid email


function isEmail(str) {
    if (isEmpty(str)) return false;
    var re = /^[^\s()<>@,;:\/]+@\w[\w\.-]+\.[a-z]{2,}$/i
    return re.test(str);
}
// returns true if the string only contains characters A-Z or a-z


function isAlpha(str) {
    var re = /[^a-zA-Z]/g
    if (re.test(str)) return false;
    return true;
}
// returns true if the string only contains characters 0-9


function isNumeric(str) {
    var re = /[\D]/g
    if (re.test(str)) return false;
    return true;
}
// returns true if the string only contains characters A-Z, a-z or 0-9


function isAlphaNumeric(obj) {
    var val = trimString(obj.value);
    if (val.match(/^[a-zA-Z0-9' ']+$/)) {
        return true;
    } else {
        return false;
    }
}
// returns true if the string's length equals "len"


function isLength(str, len) {
    return str.length == len;
}
// returns true if the string's length is between "min" and "max"


function isLengthBetween(str, min, max) {
    return (str.length >= min) && (str.length <= max);
}
// returns true if the string is a US phone number formatted as...
// (000)000-0000, (000) 000-0000, 000-000-0000, 000.000.0000, 000 000 0000, 0000000000


function isPhoneNumber(str) {
    var re = /^\(?[2-9]\d{2}[\)\.-]?\s?\d{3}[\s\.-]?\d{4}$/
    return re.test(str);
}
// returns true if the string is a valid date formatted as...
// mm dd yyyy, mm/dd/yyyy, mm.dd.yyyy, mm-dd-yyyy


function isDate(str) {
    var re = /^(\d{1,2})[\s\.\/-](\d{1,2})[\s\.\/-](\d{4})$/
    if (!re.test(str)) return false;
    var result = str.match(re);
    var y = parseInt(result[3]);
    var m = parseInt(result[1]);
    var d = parseInt(result[2]);
    if (m < 1 || m > 12 || y < 1900 || y > 2100) return false;
    if (m == 2) {
        var days = ((y % 4) == 0) ? 29 : 28;
    } else if (m == 4 || m == 6 || m == 9 || m == 11) {
        var days = 30;
    } else {
        var days = 31;
    }
    return (d >= 1 && d <= days);
}
// returns true if "str1" is the same as the "str2"


function isMatch(str1, str2) {
    return str1 == str2;
}
// returns true if the string contains only whitespace
// cannot check a password type input for whitespace


function isWhitespace(str) { // NOT USED IN FORM VALIDATION
    var re = /[\S]/g
    if (re.test(str)) return false;
    return true;
}
// removes any whitespace from the string and returns the result
// the value of "replacement" will be used to replace the whitespace (optional)


function stripWhitespace(str, replacement) { // NOT USED IN FORM VALIDATION
    if (replacement == null) replacement = '';
    var result = str;
    var re = /\s/g
    if (str.search(re) != -1) {
        result = str.replace(re, replacement);
    }
    return result;
}
// validate the form


function validateForm(f, preCheck, newClass, alerttype) {
    var errors = '';
    var errorsa = '';
    if (preCheck != null) errors += preCheck;
    var i, e, t, n, v;
    for (i = 0; i < f.elements.length; i++) {
        e = f.elements[i];

        if (e.optional) continue;
        t = e.type;
        n = e.id;
        v = e.value;
        if (t == 'text' || t == 'password' || t == 'textarea') {

            if (isEmpty(v)) {
                errors += n + errormsg[1] + '<br>';
                errorsa += n + errormsg[1] + '\n';
                e.className = newClass;
                continue;
            } else {
                e.className = 'checkit';
            }
            if (v == e.defaultValue) {
                errors += n + errormsg[2] + '<br>';
                errorsa += n + errormsg[2] + '\n';
                e.className = newClass;
                continue;
            } else {
                e.className = 'checkit';
            }
            if (e.isAlpha) {
                if (!isAlpha(v)) {
                    errors += n + errormsg[3] + '<br>';
                    errorsa += n + errormsg[3] + '\n';
                    overlib('eaaaa');
                    e.className = newClass;
                    continue;
                } else {
                    e.className = 'checkit';
                }
            }
            if (e.isNumeric) {
                if (!isNumeric(v)) {
                    errors += n + errormsg[4] + '<br>';
                    errorsa += n + errormsg[4] + '\n';
                    e.className = newClass;
                    continue;
                } else {
                    e.className = 'checkit';
                }
            }
            if (e.isAlphaNumeric) {
                if (!isAlphaNumeric(v)) {
                    errors += n + errormsg[5] + '<br>';
                    errorsa += n + errormsg[5] + '\n';
                    e.className = newClass;
                    continue;
                } else {
                    e.className = 'checkit';
                }
            }
            if (e.isEmail) {
                if (!isEmail(v)) {
                    errors += v + errormsg[6] + '<br>';
                    errorsa += n + errormsg[6] + '\n';
                    e.className = newClass;
                    continue;
                } else {
                    e.className = 'checkit';
                }
            }
            if (e.isLength != null) {
                var len = e.isLength;
                if (!isLength(v, len)) {
                    errors += n + errormsg[7] + len + '<br>';
                    errorsa += n + errormsg[7] + '\n';
                    e.className = newClass;
                    continue;
                } else {
                    e.className = 'checkit';
                }
            }
            if (e.isLengthBetween != null) {
                var min = e.isLengthBetween[0];
                var max = e.isLengthBetween[1];
                if (!isLengthBetween(v, min, max)) {
                    errors += n + errormsg[8] + min + '-' + max + '<br>';
                    errorsa += n + errormsg[8] + min + '-' + max + '\n';
                    e.className = newClass;
                    continue;
                } else {
                    e.className = 'checkit';
                }
            }
            if (e.isPhoneNumber) {
                if (!isPhoneNumber(v)) {
                    errors += v + errormsg[9] + '<br>';
                    errorsa += n + errormsg[9] + '\n';
                    e.className = newClass;
                    continue;
                } else {
                    e.className = 'checkit';
                }
            }
            if (e.isDate) {
                if (!isDate(v)) {
                    errors += v + errormsg[10] + '<br>';
                    errorsa += n + errormsg[10] + '\n';
                    e.className = newClass;
                    continue;
                } else {
                    e.className = 'checkit';
                }
            }
            if (e.isMatch != null) {
                if (!isMatch(v, e.isMatch)) {
                    errors += n + errormsg[11] + '<br>';
                    errorsa += n + errormsg[11] + '\n';
                    e.className = newClass;
                    continue;
                } else {
                    e.className = 'checkit';
                }
            }
        }
        if (t.indexOf('select') != -1) {
            if (isEmpty(e.options[e.selectedIndex].value)) {
                errors += n + errormsg[12] + '<br>';
                errorsa += n + errormsg[12] + '\n';
                e.className = newClass;
                continue;
            } else {
                e.className = 'checkit';
            }
        }
        if (t == 'file') {
            if (isEmpty(v)) {
                errors += n + errormsg[13] + '<br>';
                errorsa += n + errormsg[13] + '\n';
                e.className = newClass;
                continue;
            } else {
                e.className = 'checkit';
            }
        }
    }
    div = document.getElementById('errordiv');
    if (errors != '') {
        if (alerttype == '2' || alerttype == '3') {
            alert(errorsa);
        }
        if (alerttype == '1' || alerttype == '3') {
            return dispErr(errors, div);
        }
    }
    div.style.display = "none";
    return errors == '';
}

dispErr = function (error, divo) {
    divo.style.display = "block";
    divo.innerHTML = error;
    return false;
}


/*
The following elements are not validated...

button   type="button"
checkbox type="checkbox"
hidden   type="hidden"
radio    type="radio"
reset    type="reset"
submit   type="submit"

All elements are assumed required and will only be validated for an
empty value or defaultValue unless specified by the following properties.

isEmail = true;          // valid email address
isAlpha = true;          // A-Z a-z characters only
isNumeric = true;        // 0-9 characters only
isAlphaNumeric = true;   // A-Z a-z 0-9 characters only
isLength = number;       // must be exact length
isLengthBetween = array; // [lowNumber, highNumber] must be between lowNumber and highNumber
isPhoneNumber = true;    // valid phone number. See "isPhoneNumber()" comments for the formatting rules
isDate = true;           // valid date. See "isDate()" comments for the formatting rules
isMatch = string;        // must match string
optional = true;         // element will not be validated

alerttype = 0            // no error msg
alerttype = 1            // error msg in div
alerttype = 2            // error msg in alert
alerttype = 3            // error msg in div and alert
*/

//============================
// error msg depends on the language
var errormsg = new Array();
errormsg[0] = 'Select at least one checkbox!';
errormsg[1] = ' cannot be empty!';
errormsg[2] = ' cannot use the default value!';
errormsg[3] = ' can only contain characters A-Z a-z!';
errormsg[4] = ' can only contain characters 0-9!';
errormsg[5] = ' can only contain characters A-Z a-z 0-9!';
errormsg[6] = ' is not a valid email!';
errormsg[7] = ' character number must be less than ';
errormsg[8] = ' character number must be between ';
errormsg[9] = ' is not a valid US phone number!';
errormsg[10] = ' is not a valid date!';
errormsg[11] = ' does not match!';
errormsg[12] = ' needs an option selected!';
errormsg[13] = ' needs a file to upload!';
errormsg[99] = 'All form information will be erased!';
errormsg[100] = 'Caps Lock is On.\n\nTo prevent entering your password incorrectly,\nyou should press Caps Lock to turn it off.';



/**************************************************************
 Split: Returns a zero-based, one-dimensional array containing 
        a specified number of substrings

 Parameters:
      Expression = String expression containing substrings and 
                   delimiters. If expression is a zero-length 
                   string(""), Split returns an empty array, 
                   that is, an array with no elements and no 
                   data.
      Delimiter  = String character used to identify substring 
                   limits. If delimiter is a zero-length 
                   string (""), a single-element array 
                   containing the entire expression string 
                   is returned.

 Returns: String
***************************************************************/

function Split(Expression, Delimiter) {
    var temp = Expression;
    var a, b = 0;
    var array = new Array();

    if (Delimiter.length == 0) {
        array[0] = Expression;
        return (array);
    }

    if (Expression.length == '') {
        array[0] = Expression;
        return (array);
    }

    Delimiter = Delimiter.charAt(0);

    for (var i = 0; i < Expression.length; i++) {
        a = temp.indexOf(Delimiter);
        if (a == -1) {
            array[i] = temp;
            break;
        } else {
            b = (b + a) + 1;
            var temp2 = temp.substring(0, a);
            array[i] = temp2;
            temp = Expression.substr(b, Expression.length - temp2.length);
        }
    }

    return (array);
}

