
function IsNumeric(strValue) {
    //if the value is null the return false
    if (!strValue)
        return false;

    //check every digit in strValue to make sure it is numeric
    for (i = 0; i < strValue.length; i++) {
        if (strValue.charAt(i) < "0" || strValue.charAt(i) > "9") {
            return false;
        }
    }

    return true;
}

function Trim(strText) {

    var strWork = new String();

    for (i = 0; i < strText.length; i++) {
        if (strText.charCodeAt(i) != 10
			&& strText.charCodeAt(i) != 13) {

            strWork += strText.charAt(i);
        }
    }

    // this will get rid of leading spaces 
    while (strWork.substring(0, 1) == ' ')
        strWork = strWork.substring(1, strWork.length);

    // this will get rid of trailing spaces 
    while (strWork.substring(strWork.length - 1, strWork.length) == ' ')
        strWork = strWork.substring(0, strWork.length - 1);

    return strWork;
}

function ReplaceChar(strSource, strReplaceChar, strReplaceWith) {
    var strTemp = "";

    if (strSource == "")
        return strSource;

    for (i = 0; i < strSource.length; i++) {
        strTemp += strSource.charAt(i) == strReplaceChar ? strReplaceWith : strSource.charAt(i);
    }

    return strTemp;
}

function IsDate(strDate) {
    return !(isNaN(Date.parse(strDate)));
}

function getAge(dateString) {
    var arrDate = dateString.split("/");

    if (arrDate.length != 3) {
        return "";
    }

    var iMonth = arrDate[0] - 1;
    var iDay = arrDate[1];
    var iYear = arrDate[2];

    if (!IsNumeric(iMonth) || !IsNumeric(iDay) || !IsNumeric(iYear)) {
        return "";
    }

    var now = new Date();
    var today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
    var yearNow = now.getFullYear();
    var monthNow = now.getMonth();
    var dateNow = now.getDate();

    var dob = new Date(iYear, iMonth, iDay);

    if (isNaN(dob))
        return "";

    var yearDob = dob.getFullYear();
    var monthDob = dob.getMonth();
    var dateDob = dob.getDate();

    yearAge = yearNow - yearDob;

    if (monthNow >= monthDob) {
        var monthAge = monthNow - monthDob;
    }
    else {
        yearAge--;
        var monthAge = 12 + monthNow - monthDob;
    }

    if (dateNow >= dateDob) {
        var dateAge = dateNow - dateDob;
    }
    else {
        monthAge--;
        var dateAge = 31 + dateNow - dateDob;

        if (monthAge < 0) {
            monthAge = 11;
            yearAge--;
        }
    }

    return yearAge;
}

function ShowRecentTransactions(ar) {
    //shows the Recent Transactions dialog box and allows the user to optionally reverse transactions
    //ar indicates whether viewing recent ADD transactions (1) or recent REMOVE transactions (0)

    //      var strDlgRet = showModalDialog('recent_transactions.asp?ar=' + ar, null, "dialogHeight: 490px; dialogWidth: 770px; resizable: yes;  status: yes; help: no");
    //      
    //      while (typeof(strDlgRet) != "undefined") {
    //            var strPrevRetVal = strDlgRet;
    //            strDlgRet = showModalDialog('recent_transactions.asp?ar=' + ar + '&' + strPrevRetVal, null, "dialogHeight: 490px; dialogWidth: 770px;  resizable: yes; status: yes; help: no");
    //          }

    var strDlgRet = showModalDialog('Recent_Transactions_dlg.aspx?modal=1&ar=' + ar, "", "dialogHeight: 490px; dialogWidth: 770px; resizable: 1");

    while (typeof (strDlgRet) != "undefined") {
        var strPrevRetVal = strDlgRet;
        strDlgRet = showModalDialog('Recent_Transactions_dlg.aspx?modal=1&ar=' + ar + '&' + strPrevRetVal, "", "dialogHeight: 490px; dialogWidth: 770px;  resizable: 1");
    }
}


function StripChars(str) {
    //strips all of the alphabetic characters from a string, 
    //and returns the resulting digits (0-9) contained within the string, 
    //or an empty string

    var strRet = "";

    //if the value is null the return empty string
    if (!str)
        return strRet;

    //check every character in str to see if it is numeric
    for (i = 0; i < str.length; i++) {
        if (str.charAt(i) >= '0' && str.charAt(i) <= '9') {
            strRet += str.charAt(i);
        }
    }

    return strRet;

}


function NumDigits(strValue) {
    //returns the number of digits (numbers) found in a string
    var iDigitCount = 0;

    //if the value is null the return false
    if (!strValue)
        return iDigitCount;

    //check every digit in strValue to see if it is numeric
    for (i = 0; i < strValue.length; i++) {
        if (strValue.charAt(i) >= '0' && strValue.charAt(i) <= '9') {
            iDigitCount++;
        }
    }

    return iDigitCount;
}

function IsValidPhoneNumber(strPhone) {
    //determines whether a string is a valid phone number (contains 9 or 10 digits)
    var iNumDigits = NumDigits(strPhone);

    if (iNumDigits != 10 && iNumDigits != 11) {
        //alert("invalid phone number!");
        return false;
    }
    else {

        //if there are ten digits, return true
        if (iNumDigits == 10) {
            return true;
        }
        else { //if there are eleven digits, check to be sure first number is 1
            var strNoChars = StripChars(strPhone);

            if (strNoChars.charAt(0) == '1') {
                return true;
            }
            else {
                return false;
            }
        }
    }

    return true;
}

function ValidateExpirationDate(strDate) {
    if (!IsDate(strDate) && strDate != '') {

        //check to see whether strDate may have been passed in as MM/YYYY (if so, use 1 as the day)
        var strMonth, strDay, strYear;
        var arrDate = strDate.split("/");

        //if the length of the array is 2, assume that the 
        //second element is the year, and insert a "1" for the day.
        if (arrDate.length == 2) {
            strMonth = arrDate[0];
            strDay = 1;
            strYear = arrDate[1];

            if (!IsNumeric(strMonth) || !IsNumeric(strYear))
                return false;

            strDate = strMonth + "/" + strDay + "/" + strYear;
        }

        if (!IsDate(strDate)) {
            return false;
        }
    }

    var dt = new Date(Date.parse(strDate));
    var dtNow = new Date();

    var iYear = dt.getFullYear();
    var iCurrentYear = dtNow.getFullYear();

    if ((iYear < iCurrentYear - 5) || (iYear > iCurrentYear + 20)) {
        return false;
    }

    return true;
}

function NewValidateExpirationDate(strDate) {
    if (!IsDate(strDate) && strDate != '') {
        //check to see whether strDate may have been passed in as MM/YYYY (if so, use 1 as the day)
        var strMonth, strDay, strYear;
        var arrDate = strDate.split("/");

        //if the length of the array is 2, assume that the 
        //second element is the year, and insert a "1" for the day.
        if (arrDate.length == 2) {
            strMonth = arrDate[0];
            strDay = "01";
            strYear = arrDate[1];

            if (!IsNumeric(strMonth) || !IsNumeric(strYear))
                return false;

            strDate = strMonth + "/" + strDay + "/" + strYear;
        }

        if (!IsDate(strDate)) {
            return false;
        }
    }
    
    // check the digit validation.
    if (!check_date(strDate)) {
        return false;
    }

    var dt = new Date(Date.parse(strDate));
    var dtNow = new Date();

    var iYear = dt.getFullYear();
    var iCurrentYear = dtNow.getFullYear();

    if ((iYear < iCurrentYear - 5) || (iYear > iCurrentYear + 20)) {
        return false;
    }

    return true;
}

function check_date(strDate) {
    var checkstr = "0123456789";
    var Datevalue = "";
    var DateTemp = "";
    var seperator = ".";
    var day;
    var month;
    var year;
    var leap = 0;
    var err = 0;
    var i;
    err = 0;
    DateValue = strDate;
    
    //convert the data to 8 digit date
    var arrDate = strDate.split("/");
    for (i = 0; i < arrDate.length; i++) {
        if (arrDate[i].length == 1) {
            arrDate[i] = "0" + arrDate[i];
        }
    }
    DateValue = arrDate[0] + "/" + arrDate[1] + "/" + arrDate[2];    
    
    /* Delete all chars except 0..9 */
    for (i = 0; i < DateValue.length; i++) {
        if (checkstr.indexOf(DateValue.substr(i, 1)) >= 0) {
            DateTemp = DateTemp + DateValue.substr(i, 1);
        }
    }
    DateValue = DateTemp;
    /* Always change date to 8 digits - string*/
    /* if year is entered as 2-digit / always assume 20xx */
    if (DateValue.length == 6) {
        DateValue = DateValue.substr(0, 4) + '20' + DateValue.substr(4, 2);
    }
    if (DateValue.length != 8) {
        err = 19;
    }
    /* year is wrong if year = 0000 */
    year = DateValue.substr(4, 4);
    if (year == 0) {
        err = 20;
    }
    /* Validation of month*/
    month = DateValue.substr(0, 2);
    if ((month < 1) || (month > 12)) {
        err = 21;
    }
    /* Validation of day*/
    day = DateValue.substr(2, 2);
    if (day < 1) {
        err = 22;
    }
    /* Validation leap-year / february / day */
    if ((year % 4 == 0) || (year % 100 == 0) || (year % 400 == 0)) {
        leap = 1;
    }
    if ((month == 2) && (leap == 1) && (day > 29)) {
        err = 23;
    }
    if ((month == 2) && (leap != 1) && (day > 28)) {
        err = 24;
    }
    /* Validation of other months */
    if ((day > 31) && ((month == "01") || (month == "03") || (month == "05") || (month == "07") || (month == "08") || (month == "10") || (month == "12"))) {
        err = 25;
    }
    if ((day > 30) && ((month == "04") || (month == "06") || (month == "09") || (month == "11"))) {
        err = 26;
    }
    /* if 00 ist entered, no error, deleting the entry */
    if ((day == 0) && (month == 0) && (year == 00)) {
        err = 0; day = ""; month = ""; year = ""; seperator = "";
    }
    
    /* if error return false */
    if (err != 0) {
        return false;
    }
    return true
}

function FormatPhoneNumber(strPhone) {
    var strRet = "";

    if (!IsValidPhoneNumber(strPhone)) {
        return strRet;
    }

    var strNewPhone = StripChars(strPhone);

    if (strNewPhone.length == 10) {
        strRet = "(";
        strRet += strNewPhone.substr(0, 3).toString();
        strRet += ") ";
        strRet += strNewPhone.substr(3, 3).toString();
        strRet += "-";
        strRet += strNewPhone.substr(6, 4).toString();
    }
    else if (strNewPhone.length == 11) {
        strRet = "(";
        strRet += strNewPhone.substr(1, 3).toString();
        strRet += ") ";
        strRet += strNewPhone.substr(4, 3).toString();
        strRet += "-";
        strRet += strNewPhone.substr(7, 4).toString();
    }

    return strRet;
}

function IsValidCurrency(currencyVal) {

    currencyVal = currencyVal.replace(/\s/g, ""); //remove whitespace

    if (currencyVal == "") {
        return false;
    }

    return (currencyVal.search(/^\$?\d{0,3}(,?\d{3})*(\.\d{1,2})?$/) != -1)
}

function Left(str, n) {
    if (n <= 0)
        return "";
    else if (n > String(str).length)
        return str;
    else
        return String(str).substring(0, n);
}

function Right(str, n) {
    if (n <= 0)
        return "";
    else if (n > String(str).length)
        return str;
    else {
        var iLen = String(str).length;
        return String(str).substring(iLen, iLen - n);
    }
}

function URLencode(sStr) {
    return escape(sStr).replace(/\+/g, '%2B').replace(/\"/g, '%22').replace(/\'/g, '%27');
}

function isValidDate(dateStr) {

    var datePat = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/;
    var matchArray = dateStr.match(datePat); // is the format ok?

    if (matchArray == null) {
        alert("Please enter date as mm/dd/yyyy");
        return false;
    }

    month = matchArray[1]; // p@rse date into variables
    day = matchArray[3];
    year = matchArray[5];

    if (month < 1 || month > 12) { // check month range
        alert("Month must be between 1 and 12.");
        return false;
    }

    if (day < 1 || day > 31) {
        alert("Day must be between 1 and 31.");
        return false;
    }

    if ((month == 4 || month == 6 || month == 9 || month == 11) && day == 31) {
        alert("Month " + month + " doesn`t have 31 days!")
        return false;
    }

    if (month == 2) { // check for february 29th
        var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
        if (day > 29 || (day == 29 && !isleap)) {
            alert("February " + year + " doesn`t have " + day + " days!");
            return false;
        }
    }
    return true; // date is valid
}



function RequestData(linkId, cellElement, evt) {
    var evtSource;

    evt = (evt) ? evt : window.event;
    evtSource = (evt.srcElement) ? evt.srcElement : evt.target;

    //When a hyperlink is clicked, Safari returns the text node as the source element rather
    //than the hyperlink. parentNode will give us the hyperlink element.
    //ref: http://developer.apple.com/internet/webcontent/eventmodels.html

    if (evt.target) {
        if (evt.target.nodeType == 3) {
            evtSource = evtSource.parentNode;
        }
    }

    //If event was raised from an element other than the LinkButton
    if ((evtSource.getAttribute("id") != linkId) && (evt.type == "click")) {
        //Get a collection of "a" tags inside the cell        
        var linkCollection = cellElement.getElementsByTagName("a");

        for (var i = 0; i < linkCollection.length; i++) {
            //If the link button has an onclick attribute, call the onclick.
            //The onclick attribute is present when the GridView is using callback
            //example: onclick="java script:__gvGridSort1_GridView1.callback(...); return false;"
            var onClickAttribute = linkCollection[i].getAttribute("onclick");

            if (onClickAttribute != null) {
                linkCollection[i].onclick();
                break;
            }

            //If the link button has a href attribute, set the location of the page
            //to the href value.
            //The href attribute is used when the GridView is not using callbacks
            //example: href="java script:__doPostBack('GridSort1$GridView1','Sort$UnitsOnOrder')" 

            var hrefAttribute = linkCollection[i].getAttribute("href");
            this.location.href = hrefAttribute;
            break;
        }
    }
}


function checkKey(e) {
    var key;
    if (window.event) {
        key = window.event.keyCode;
    }    //IE
    else {
        key = e.which;
    }       //firefox

    if (key == 13) {

        __doPostBack('divShowMultipleProductIds', 'tab');
        return false;
    }
    else {

    }
}

function ShowStatus(bShow, strMsg) {

    var strHTML;
    strHTML = "<div style=\"width: 350; position: absolute; top: 150; left: 0;\" align=center>";
    strHTML += "<div align=\"center\" valign=\"middle\" style=\"width: 200; font-size: 14; ";
    strHTML += "font-family: MS Sans Serif; border: 1; background-color: lightgrey; border-style: ridge;\">";
    strHTML += "<br>" + strMsg + "</br><br></div></div>";

    divStatus.innerHTML = strHTML;

    if (bShow) {

        divStatus.style.overflow = "visible";
        divStatus.style.visibility = "visible";
        window.focus();
    }
    else {
        divStatus.style.display = "none";
        divStatus.visibility = "hidden";
    }
}

function HandleMultiUPN(strUPN) {
    event.srcElement.href = "javascript: ShowStatus(true, 'Searching for Product ID match...');";

    __doPostBack('divShowMultipleProductIds', strUPN);
}

function OnConsignmentEdit(link, strProductID) {
    var strDilogBox = showModalDialog("set_consigned_qty_frame.asp?pid=" + ReplaceChar(escape(strProductID), "+", "%2B"), null, "dialogHeight: 7; dialogWidth: 11; status: no; help: no");
    if (typeof (strDilogBox) != "undefined") {

        var strLinkText;

        if (strDilogBox.length == 0) {
            link.innerText = "Set consigned quantity";
        }
        else {
            link.innerText = strDilogBox;
        }
    }

    return false;
}
function DisplayDetail(ProductID) {
    __doPostBack('divRow', ProductID);
}

//Validates Search Form
function OnLocationSearch() {

    if (frmlocsearch && frmlocsearch.txtSearchText) {
        if (Trim(frmlocsearch.txtSearchText.value) == "") {
            alert("Please enter the text to find.");
            frmlocsearch.txtSearchText.focus();
            return false;
        }
        else {
            if (Trim(frmlocsearch.txtSearchText.value) != "") {
                var searchTemp = Trim(frmlocsearch.txtSearchText.value);
                var searchTemp2 = frmlocsearch.txtSearchText.value.replace(/"/g, "");

                if (searchTemp2.length == 0 && (searchTemp.length % 2) <= 0) {
                    alert("Invalid search text.  Please try again.");
                    frmlocsearch.txtSearchText.focus();
                    return false;
                }
                else if (searchTemp2.length > 0 && Trim(searchTemp2).length == 0) {
                    alert("Invalid search text.  Please try again.");
                    frmlocsearch.txtSearchText.focus();

                    return false;
                }
            }
        }
        if (frmlocsearch.ddlSearchOnlyIn.options[frmlocsearch.ddlSearchOnlyIn.selectedIndex].value == "<%Response.Write(loc_search.PRICE_ITEM_INDEX);%>" && !IsValidCurrency(frmlocsearch.txtSearchText.value)) {
            alert("Invalid search text.  Please enter a valid currency value when searching by List Price");
            return false;
        }
    }
    return true;
}

function ClearLocationForm() {
    frmlocsearch.txtSearchText.value = "";
    frmlocsearch.selectedIndex = 0;
    frmlocsearch.txtSearchText.focus();
}

