﻿/// <reference path="jquery-vsdoc.js" />

String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g, ""); };
String.prototype.replaceAll = function(find, replacement) { return this.replace(new RegExp(find, 'g'), replacement); };

$(document).ready(function() {
    var wPath = window.location.pathname.toString();
    //    if (wPath.indexOf("search.aspx") > -1 || wPath.indexOf("cart.aspx") > -1) {
    //        var ancNIDlgMenu = $('#ancNIDlg');
    //        ancNIDlgMenu.css('color', '#f5f5f5');
    //        ancNIDlgMenu.click(function() { displayNoninventoryDlg(); });
    //    }
    if (wPath.indexOf("nonInventory.aspx") > -1) {
        var spaceSep = "```";

        var isbn = $('#txtNIIsbn');
        var qty = $('#txtNIQty');
        var title = $('#txtNITitle');
        var author = $('#txtNIAuthor');
        var publisher = $('#txtNIPublisher');
        var comment = $('#txtNIComment');
        var itemid = '';
        var mode = '';
        var cartid = '';

        var url = window.location.href;
        url = url.substr(url.indexOf("nonInventory.aspx") + 17);
        url = ((url.indexOf('?') == 0) ? url.substr(1) : '');
        if (url.length > 0) {
            url = url.replaceAll(spaceSep, ' ');
            var aparams = url.split('&');
            for (var i = 0; i < aparams.length; i++) {
                var key_value = aparams[i].split('=');
                key_value[0] = key_value[0].replaceAll('\%20', ' ').replaceAll('[+]', ' ').replaceAll('```', ' ');
                key_value[1] = key_value[1].replaceAll('\%20', ' ').replaceAll('[+]', ' ').replaceAll('```', ' ');
                switch (key_value[0].toLowerCase()) {
                    case "isbn":
                        isbn.val(key_value[1]);
                        displayCharsLeft(isbn.get(0), key_value[1]);
                        break;
                    case "qty":
                        qty.val(key_value[1]);
                        displayCharsLeft(qty.get(0), key_value[1]);
                        break;
                    case "title":
                        title.val(key_value[1]);
                        displayCharsLeft(title.get(0), key_value[1]);
                        break;
                    case "author":
                        author.val(key_value[1]);
                        displayCharsLeft(author.get(0), key_value[1]);
                        break;
                    case "publisher":
                        publisher.val(key_value[1]);
                        displayCharsLeft(publisher.get(0), key_value[1]);
                        break;
                    case "comment":
                        comment.val(key_value[1]);
                        displayCharsLeft(comment.get(0), key_value[1]);
                        break;
                    case "itemid":
                        itemid = key_value[1];
                        break;
                    case "mode":
                        mode = key_value[1];
                        break;
                    case "cartid":
                        cartid = key_value[1];
                        break;
                }
            }
        }
        $('#divParent').attr('__itemid', itemid);
        $('#divParent').attr('__cartid', cartid);
        if (mode == 'edit item') mode = 'save';
        toggleNIEditPrompt(mode, false);
        toggleNIAddCancelBtns(checkNIRequiredFields(false));
    }
});

function displayCharsLeft(obj, stext) {
    var jqObj = $(obj);
    var textLen = stext.length;
    var maxChars = jqObj.attr("maxlength");
    var charsLeftLabel = jqObj.parent(1).next(1);
    var charsOrDigits = charsLeftLabel.text().split(' ')[1];
    var charsLeft = maxChars - textLen;
    charsLeft = (charsLeft < 0) ? 0 : charsLeft;
    charsLeftLabel.text(charsLeft.toString() + ' ' + charsOrDigits + ' left');
}

function finalizeCart(cartid) {
    var result;
    $.get('cartUpdate.aspx', {
        'action': 'finalize',
        'cart': cartid,
        'dts': (new Date()).toString()
    }, function(data) {        // data = <true> for success, or <false> for failure
        result = data;
    });
    $().ajaxComplete(function() {
        if (result == "success") {
            alert("Finalized Successfully.");
            window.location.href = "Default.aspx";
        } else {
            alert("Failed to finalize.");
        }
    });
}

function deptSelectionChange(obj) {
    window.location.href = "groupCarts.aspx?list=departments&id=" + $(obj).val();
}

function teacherSelectionChange(obj) {
    window.location.href = "groupCarts.aspx?list=teachers&id=" + $(obj).val();
}
    
function qtyKeyPress(e) {
    var key = window.event ? e.keyCode : e.which;
    var keychar = String.fromCharCode(key);
    reg = /\d/;
    return reg.test(keychar);
}

//function displayNoninventoryDlg() {
//    var isbn = $('#txtNIIsbn');
//    var qty = $('#txtNIQty');
//    var title = $('#txtNITitle');
//    var author = $('#txtNIAuthor');
//    var publisher = $('#txtNIPublisher');
//    var comment = $('#txtNIComment');
//    
//    // clear all text fields in case there is any old text
//    isbn.val('');
//    qty.val('1');
//    title.val('');
//    author.val('');
//    publisher.val('');
//    comment.val('');

//    // reset the 'chars left' count
//    isbn.parent(1).next(1).text('13 chars max');
//    qty.parent(1).next(1).text('3 chars left');
//    title.parent(1).next(1).text('100 chars max');
//    author.parent(1).next(1).text('100 chars max');
//    publisher.parent(1).next(1).text('100 chars max');
//    comment.parent(1).next(1).text('300 chars max');
//    
//    $('#divNIIsbn').css('display', 'none');
//    isbn.css('display', '');
//    $('#tdNIIsbn').css('color', '#000000');
//    $('#spnAddBlurb').css('display', '');
//    var nidlg = $('#ctl00_cphBody_dlgNI').dialog({ modal: true, minHeight: 300, width: 430, position: [200, 200] });
//    // creating then closing the dialog box is a fix for the initial load
//    // of the dialog box that appears with a height that is too big
//    nidlg.dialog('close');
//    nidlg.dialog('option', 'buttons', {
//        "Cancel": function() {
//            $(this).dialog("destroy");
//        },
//        "Add to cart": function() {
//            if (checkNIRequiredFields()) {
//                addNoninventoryItem(false);
//                $(this).dialog("destroy");
//            }
//        }
//    });
//    nidlg.dialog('option', 'title', 'Non-inventory Title');
//    nidlg.dialog('open');
//}

function tryToAddNIItem(obj, cartid) {
    if ($(obj).attr('__enabled') == 'true') {
        if (checkNIRequiredFields()) {
            addNoninventoryItem(false, cartid);
        }
    }
}

function checkNIRequiredFields(displayDlg) {
    var isbn = $('#txtNIIsbn');
    var qty = $('#txtNIQty');
    var title = $('#txtNITitle');
    var author = $('#txtNIAuthor');
    var publisher = $('#txtNIPublisher');
    var comment = $('#txtNIComment');
    var errMsg = '';

    if (+(qty.val()) == 0)
        errMsg += '"Quantity:" cannot be less than "1"';

    if (isbn.val().trim() == '' &&
        title.val().trim() == '' &&
        author.val().trim() == '' &&
        comment.val().trim() == '') {
        errMsg += ((errMsg !== '') ? '\r\n\r\nalso\r\n\r\n' : '') + 'Not enough information...\r\n  At least the "ISBN:", "Title:", or "Auhtor:" must be filled-in  '
    }
    if (errMsg !== '') {
        if (displayDlg)
            alert(errMsg);
    } else {
        return true;
    }
}

function sendNIInfoToPage(isbn, qty, title, author, publisher, comment, mode, itemid, cartid) {
    var spaceSep = "```";
    window.location.href = 'nonInventory.aspx?isbn=' + $('#' + isbn).text().replaceAll(' ', spaceSep) +
                                             '&qty=' + $('#' + qty).text().replaceAll(' ', spaceSep) +
                                             '&title=' + $('#' + title).text().replaceAll(' ', spaceSep) +
                                             '&author=' + $('#' + author).text().replaceAll(' ', spaceSep) +
                                             '&publisher=' + $('#' + publisher).text().replaceAll(' ', spaceSep) +
                                             '&comment=' + $('#' + comment).text().replaceAll(' ', spaceSep) +
                                             '&itemid=' + itemid +
                                             '&cartid=' + cartid +
                                             '&mode=edit item';
}

//function displayNoninventoryDlgForEdit(obj) {
//    $('#divNIIsbn').css('display', '');
//    $('#txtNIIsbn').css('display', 'none');
//    $('#tdNIIsbn').css('color', 'Gray');
//    $('#spnAddBlurb').css('display', 'none');
//    var cartid = $('table[__cartid]').attr('__cartid');
//    var td = $(obj).parent(1);
//    var objSibs = td.siblings();
//    var itemid = td.parent(1).attr('__itemid');
//    td.parent(1).parent(1).parent(1).attr('__cur_itemid', itemid);

//    var isbn = $('#divNIIsbn');
//    var qty = $('#txtNIQty');
//    var title = $('#txtNITitle');
//    var author = $('#txtNIAuthor');
//    var publisher = $('#txtNIPublisher');
//    var comment = $('#txtNIComment');
//    
//    isbn.text(objSibs.eq(1).text());
//    qty.val(objSibs.eq(2).text());
//    title.val(objSibs.eq(3).text());
//    author.val(objSibs.eq(4).text());
//    publisher.val(objSibs.eq(5).text());
//    comment.text(objSibs.eq(6).text());

//    $('#tdQtyCharsLeft').text((100 - title.val().length) + " chars left");
//    $('#tdTitleCharsLeft').text((100 - title.val().length) + " chars left");
//    $('#tdAuthorCharsLeft').text((100 - author.val().length) + " chars left");
//    $('#tdPublisherCharsLeft').text((100 - publisher.val().length) + " chars left");
//    $('#tdCommentCharsLeft').text((300 - comment.text().length) + " chars left");
//    
//    var nidlg = $('#ctl00_cphBody_dlgNI').dialog({ modal: true, minHeight: 300, width: 430, position: [200, 200] });
//    // creating then closing the dialog box is a fix for the initial load
//    // of the dialog box that appears with a height that is too big
//    nidlg.dialog('close');
//    nidlg.dialog('option', 'buttons', {
//        "Cancel": function() {
//            $(this).dialog("destroy");
//        },
//        "Save": function(itemid) {
//            if (checkNIRequiredFields()) {
//                updateNoninventoryItem();
//                $(this).dialog("destroy");
//            }
//        }
//    });
//    nidlg.dialog('option', 'title', 'Editing Non-inventory Title');
//    nidlg.dialog('open');
//}

function updateNoninventoryItem() {
    var qty = $('#txtNIQty').val();
    var title = $('#txtNITitle').val();
    var author = $('#txtNIAuthor').val();
    var publisher = $('#txtNIPublisher').val();
    var comment = $('#txtNIComment').val();
    var itemid = $('#divParent').attr('__itemid');
    var cartid = $('#divParent').attr('__cartid');
    $.get('cartUpdateNoninventoryItem.aspx', {
        'itemid': itemid,
        'newqty': qty,
        'newtitle': title.replaceAll(' ', '```').replaceAll('\'', ''),  // so that browsers don't change spaces to other chars
        'newauthor': author.replaceAll(' ', '```').replaceAll('\'', ''),
        'newpublisher': publisher.replaceAll(' ', '```').replaceAll('\'', ''),
        'newcomment': comment.replaceAll(' ', '```').replaceAll('\'', ''),
        'cartid': cartid,
        'dts': (new Date()).toString()
    }, function(data) {        // data = <true> or <false>
        result = data;
    });
    $().ajaxComplete(function() {
        var trItemChildren = $('tr[__itemid="' + itemid + '"]').children();
        trItemChildren.eq(2).text(qty);
        trItemChildren.eq(4).text(title);
        trItemChildren.eq(5).text(author);
        trItemChildren.eq(6).text(publisher);
        trItemChildren.eq(7).text(comment);
    });
}

function removeNoninventoryItemDlgConfirm(obj) {
    var td = $(obj).parent(1);
    var objSibs = td.siblings();
    var itemNumber = objSibs.eq(0).text().replaceAll(' - ', '');
    var itemid = td.parent(1).attr('__itemid');
    td.parent(1).parent(1).parent(1).attr('__cur_itemid', itemid);
    var caption = "Please Confirm...";
    var msg = "Remove Non-Inventory Item #" + itemNumber + "?";
    var btn1 = "Yes";
    var btn1f = function() { removeNoninventoryItem(); window.location.reload(); };
    var btn2 = "No";
    var btn2f = function() { window.location.reload(); };
    jqDialog(caption, msg, btn1, btn1f, btn2, btn2f);
}

function removeNoninventoryItem() {
    var itemid = $('table[__cur_itemid]').attr('__cur_itemid');
    var cartid = $('table[__cartid]').attr('__cartid');
    $.get('cartRemoveNoninventoryItem.aspx', {
        'itemid': itemid,
        'cartid': cartid,
        'dts': (new Date()).toString()
    }, function(data) {        // data = <true> or <false>
        result = data;
    });
    $().ajaxComplete(function() {
        $('tr[__itemid="' + itemid + '"]').remove();
    });
}

// a very simple and generic function to put up a modal dialog with up to 4 buttons
// and bind them to their respective functions
function jqDialog(dlgCaption, msg, btn1c, btn1Func, btn2c, btn2Func, btn3c, btn3Func, btn4c, btn4Func) {
    $('#divJqDialogInternalDomElement').remove();
    var divDlg = $(document.createElement('div'));
    divDlg.attr('id', 'divJqDialogInternalDomElement');
    btn1c = (btn1c) ? btn1c : "Ok";
    btn1Func = (btn1Func) ? btn1Func : function() { return; };
    btn2Func = (btn2Func) ? btn2Func : function() { return; };
    btn3Func = (btn3Func) ? btn3Func : function() { return; };
    btn4Func = (btn4Func) ? btn4Func : function() { return; };
    var dlgBtn1Func = function() { btn1Func(); $(this).dialog("destroy"); };
    var dlgBtn2Func = function() { btn2Func(); $(this).dialog("destroy"); };
    var dlgBtn3Func = function() { btn3Func(); $(this).dialog("destroy"); };
    var dlgBtn4Func = function() { btn4Func(); $(this).dialog("destroy"); };
    divDlg.html(msg);
    divDlg.css('font-family', 'Verdana').css('font-size', '9pt').css('font-weight', 'normal');
    var jqdlg = new $(divDlg).dialog({ modal: true, position: 'center' });
    jqdlg.dialog('option', 'title', dlgCaption);
    jqdlg.dialog('close');
    var buttons = {};
    if (btn4c) buttons[btn4c] = dlgBtn4Func;
    if (btn3c) buttons[btn3c] = dlgBtn3Func;
    if (btn2c) buttons[btn2c] = dlgBtn2Func;
    if (btn1c) buttons[btn1c] = dlgBtn1Func;
    jqdlg.dialog("option", "buttons", buttons);
    jqdlg.dialog('open');
}

function addNoninventoryItem(addEvenIfIsbnFound, cartid) {
    addEvenIfIsbnFound = (addEvenIfIsbnFound);
        
    var jqIsbn = $('#txtNIIsbn');
    var isbn = jqIsbn.text();
    isbn = ((!isbn) || (isbn == '')) ? jqIsbn.val() : isbn;
    isbn = (isbn) ? isbn : '';

    var jqQty = $('#txtNIQty');
    var qty = jqQty.text();
    qty = ((!qty) || (qty == '')) ? jqQty.val() : qty;
    qty = (qty) ? qty : '';
    
    var jqTitle = $('#txtNITitle');
    var title = jqTitle.text();
    title = ((!title) || (title == '')) ? jqTitle.val() : title;
    title = (title) ? title : '';
    title = title.replaceAll(' ', '```').replaceAll('\'', '');  //so that browsers wouldn't translate spaces to other chars

    var jqAuthor = $('#txtNIAuthor');
    var author = jqAuthor.text();
    author = ((!author) || (author == '')) ? jqAuthor.val() : author;
    author = (author) ? author : '';
    author = author.replaceAll(' ', '```').replaceAll('\'', '');

    var jqPublisher = $('#txtNIPublisher');
    var publisher = jqPublisher.text();
    publisher = ((!publisher) || (publisher == '')) ? jqPublisher.val() : publisher;
    publisher = (publisher) ? publisher : '';
    publisher = publisher.replaceAll(' ', '```').replaceAll('\'', '');

    var jqComment = $('#txtNIComment');
    var comment = jqComment.text();
    comment = ((!comment) || (comment == '')) ? jqComment.val() : comment;
    comment = (comment) ? comment : '';
    comment = comment.replaceAll(' ', '```').replaceAll('\'', '');

    var result = 'undetermined';
    $.get('cartAddNoninventoryItem.aspx', {
        'isbn': isbn,
        'qty': qty,
        'title': title,
        'author': author,
        'publisher': publisher,
        'comment': comment,
        'cartid': cartid,
        'addevenifisbnfound': addEvenIfIsbnFound.toString(),
        'dts': (new Date()).toString()
    }, function(data) {        // data = <true> or <false>
        result = data;
    });
    $().ajaxStop(function(e, xhr, settings) {
        if (addEvenIfIsbnFound || result.toLowerCase().indexOf('added') == 0) {
            if (result.toLowerCase().indexOf('added') == 0) {
                var results = result.split(',');
                var cookie = results[1];
                var cartid = results[2];
                if (cookie.length > 0) {
                    var now = new Date();
                    var oneMinute = 60 * 1000  // milliseconds in a minute
                    var oneHour = oneMinute * 60
                    var oneDay = oneHour * 24
                    var oneWeek = oneDay * 7
                    var today = new Date()
                    var dateInMS = today.getTime() + oneWeek * 27
                    var targetDate = new Date(dateInMS)
                    setCookie("abccart", cookie, targetDate, "", "", false)
                }
                window.location.href = 'cart.aspx?cartid=' + cartid;
            }
        } else {
            var caption = "Please note...";
            if (result.toString().trim().toLowerCase() == 'added') {
                window.location.href = 'cart.aspx?cartid=' + cartid;
            } else if (result.toString().trim().toLowerCase().indexOf('exact isbns found') == 0) {
                toggleNIEditPrompt('examine', true);
            } else if (result.toString().trim().toLowerCase().indexOf('partial isbns found') == 0) {
                toggleNIEditPrompt('prompt', true);
            }
        }
        $().unbind('ajaxStop');
    });
}

function listMatches() {
    window.location.href = 'search.aspx?search=' + $('#txtNIIsbn').val() + '&isbnsearch=true';
}

function addNIItemRegardless(obj, cartid){
    addNoninventoryItem(true, cartid);
}

function backToEdit() {
    toggleNIEditPrompt('edit', true);
}

function saveNIItem(obj, cartid) {
    if (checkNIRequiredFields()) {
        updateNoninventoryItem();
        window.location.href = 'cart.aspx?cartid=' + cartid;
    }
}

function toggleNIEditPrompt(whichTable, blink) {
    var tblEdit = $('#tblSearch');
    var tblSave = $('#tblSave');
    var tblPrompt = $('#tblPrompt');
    var tblExamine = $('#tblExamine');

    tblEdit.css('display', (whichTable == 'edit' ? '' : 'none'));
    tblSave.css('display', (whichTable == 'save' ? '' : 'none'));
    tblPrompt.css('display', (whichTable == 'prompt' ? '' : 'none'));
    tblExamine.css('display', (whichTable == 'examine' ? '' : 'none'));

    toggleNIEdit(whichTable == 'edit' || whichTable == 'save');
    var divaddtocart = $('#divAddToCart');
    
    switch (whichTable) {
        case 'edit':
            $('#tdEditPrompt').text('Please tell us something about the item.  Fill-in as many fields as you can');
            divaddtocart.click(function() { tryToAddNIItem(divaddtocart.get(0), $('#divParent').attr('__cartid')); });
            $('#txtNIIsbn').attr('disabled', '');
            if (blink)
                tblEdit.fadeOut(80).fadeIn(80)
                       .fadeOut(80).fadeIn(80);
            break;
        case 'prompt':
            $('#tdPromptCaption').text('There were partial matches to ISBN ' + $('#txtNIIsbn').val() + ' in our inventory. What would you like to do?');
            divaddregardless = $('#divAddRegardless');
            divaddregardless.click(function() { addNIItemRegardless(divaddtocart.get(0), $('#divParent').attr('__cartid')); });
            if (blink)
                tblPrompt.fadeOut(80).fadeIn(80)
                         .fadeOut(80).fadeIn(80)
                         .fadeOut(80).fadeIn(80)
                         .fadeOut(80).fadeIn(80)
                         .fadeOut(80).fadeIn(80)
                         .fadeOut(80).fadeIn(80);
            break;
        case 'examine':
            $('#tdExamineCaption').text('ISBN ' + $('#txtNIIsbn').val() + ' matches a title in our inventory. Please examine that title first');
            if (blink)
                tblExamine.fadeOut(80).fadeIn(80)
                          .fadeOut(80).fadeIn(80)
                          .fadeOut(80).fadeIn(80)
                          .fadeOut(80).fadeIn(80)
                          .fadeOut(80).fadeIn(80)
                          .fadeOut(80).fadeIn(80);
            break;
        case 'save':
            $('#tdEditPrompt').text('Edit Item');
            $('#txtNIIsbn').attr('disabled', 'disabled');
            divsave = $('#divSave');
            divsave.click(function() { saveNIItem(divaddtocart.get(0), $('#divParent').attr('__cartid')); });
            if (blink)
                tblSave.fadeOut(80).fadeIn(80)
                       .fadeOut(80).fadeIn(80);
            break;
    }
}

function toggleNIEdit(state) {
    var disabled = (state ? '' : 'disabled');
    $('#trEditCaption').attr('disabled', disabled);
    $('#trEditPrompt').attr('disabled', disabled);
    $('#trEditIsbn').attr('disabled', disabled);
    $('#trEditQty').attr('disabled', disabled);
    $('#trEditTitle').attr('disabled', disabled);
    $('#trEditAuthor').attr('disabled', disabled);
    $('#trEditPublisher').attr('disabled', disabled);
    $('#trEditComment').attr('disabled', disabled);

    $('#txtNIIsbn').attr('disabled', disabled);
    $('#txtNIQty').attr('disabled', disabled);
    $('#txtNITitle').attr('disabled', disabled);
    $('#txtNIAuthor').attr('disabled', disabled);
    $('#txtNIPublisher').attr('disabled', disabled);
    $('#txtNIComment').attr('disabled', disabled);
}

function isBrowser() {
    var retVal = Object();
    var uaText = navigator.userAgent.toLowerCase();
    retVal.chrome = (uaText.indexOf("webkit") > -1);
    retVal.firefox = (uaText.indexOf("firefox") > -1);
    retVal.safari = (uaText.indexOf("safari") > -1);
    retVal.ie = (uaText.indexOf("msie") > -1);
    return retVal
}

function checkLength(e) {
    var evt = (!e) ? window.event : e;
    var jqObj = $(evt.srcElement);
    var textLen = Math.max(jqObj.text().length, jqObj.val().length);
    var key = Math.max(Math.max(evt.keyCode, evt.which), evt.charCode);

    //some ie quirk...max(int,NaN) returns NaN, other browsers return int
    key = (key.toString().toLowerCase() == 'nan') ? evt.keyCode : key;

    var evtType = evt.type.toLowerCase();
    var charsInQty = '1234567890';
    if (jqObj.attr("id").toLowerCase() == 'txtniqty' && evtType == 'keypress') {
        if (charsInQty.indexOf(String.fromCharCode(key)) == -1)
            return false;
    }

    var charsNotInIsbn = 'abcdefghijklmnopqrstuvwyz`~!@#$%^&*()_-+=|\\}]{["\';:?/>.<,';
    if (jqObj.attr("id").toLowerCase() == 'txtniisbn') {
        if (charsNotInIsbn.indexOf(String.fromCharCode(key).toLowerCase()) > -1)
            return false;
    }

    if (evtType != 'keypress' && evtType != 'blur' && evtType != 'keyup')
        return true;

    var maxChars = jqObj.attr("maxlength");
    if (evt.type.toLowerCase() == "blur") {
        if (textLen > maxChars) {
            alert("Too many characters. " + maxChars + " max.");
            jqObj.focus();
            return false;
        }
    }

    if (textLen > maxChars && evtType != 'keyup')
        return false;

    var charsLeftLabel = jqObj.parent(1).next(1);
    var charsOrDigits = charsLeftLabel.text().split(' ')[1];
    var charsLeft = maxChars - (textLen + ((key > 0 && evtType != 'keyup') ? 1 : 0));
    charsLeft = (charsLeft < 0) ? 0 : charsLeft;
    charsLeftLabel.text(charsLeft.toString() + ' ' + charsOrDigits + ' left');

    toggleNIAddCancelBtns(checkNIRequiredFields(false));

    return true;
}

function toggleNIAddCancelBtns(enable) {
    var divAdd = $("#divAddToCart");
    var divSave = $("#divSave");
    if (enable) {
        divAdd.css('background-color', '#bbccdd');
        divAdd.css('color', '#000000');
        divAdd.css('cursor', 'pointer');
        divAdd.attr('__enabled', 'true');

        divSave.css('background-color', '#bbccdd');
        divSave.css('color', '#000000');
        divSave.css('cursor', 'pointer');
        divSave.attr('__enabled', 'true');
    } else {
        divAdd.css('background-color', '#dddddd');
        divAdd.css('color', '#999999');
        divAdd.css('cursor', 'default');
        divAdd.attr('__enabled', 'false');

        divSave.css('background-color', '#dddddd');
        divSave.css('color', '#999999');
        divSave.css('cursor', 'default');
        divSave.attr('__enabled', 'false');
    }
}

function descTextChanged(cartid) {
    if (!cartid)
        cartid = 'none';
    var xhr = createXhr();
    xhr.open("GET", "cartUpdate.aspx?action=update&clientid=1001035&cartid=" + cartid + "&cartDescription=" + document.getElementById("ctl00_cphBody_txtCartDesc").value);
    xhr.send(null);
    xhr.close;
}

function processEnterKey(evt) {
    var characterCode;
    if (evt && evt.which) { //if which property of event object is supported (NN4)
        evt = evt;
        characterCode = evt.which; //character code is contained in NN4's which property
    } else {
        evt = event;
        characterCode = evt.keyCode; //character code is contained in IE's keyCode property
    }
    if (characterCode == 13) { //if generated character code is equal to ascii 13 (if enter key)
        $("#btnUpdate").focus();
        return false;
    }
}

function qtyTextChanged(control, sortorder, cartid) {
    var qty = control.value.toString();
    if (qty === "0") {
        removeCartItem(sortorder);
        return;
    }

    if (!cartid)
        cartid = 'none';

    var xhr = createXhr();
    xhr.onreadystatechange = processQtyTextChangeResponse;
    xhr.open("GET", "cartUpdate.aspx?action=update&clientid=1001035&cartid=" + cartid + "&sortorder=" + sortorder + "&field=quantity&value=" + control.value + "&dts=" + new Date().toString(), true);
    xhr.send(null);

    function processQtyTextChangeResponse() {
        var sortorder = 0;
        var appliedprice = 1;
        var applieddiscount = 2;
        var qty = 3;
        var linetotal = 4;
        var total = 0;
        var itemsQty = 0;
        if (xhr.readyState == 4) {
            var data = xhr.responseText;
            xhr.close;
            var rows = data.split("~~~");
            for (var i = 0; i < rows.length - 2; i++) {
                var fields = rows[i].split("(;|;)");
                var ordinal = (fields[sortorder] - 1).toString();
                var priceCell = document.getElementById("ctl00_cphBody_price" + ordinal);
                priceCell.innerHTML = fields[appliedprice];
                var qtyBox = document.getElementById("ctl00_cphBody_txtQty_" + ordinal);
                qtyBox.value = fields[qty];
                var lnTotalCell = document.getElementById("ctl00_cphBody_lineTotal" + ordinal);
                lnTotalCell.innerHTML = fields[linetotal] + "&nbsp;&nbsp;";
            }

            document.getElementById("ctl00_cphBody_grandTotal").innerHTML = "$" + rows[rows.length - 2] + "&nbsp;&nbsp;";
            $("#ctl00_divCartInfo").html("<a href='javascript:goToPage(\"cart.aspx\");'>Shopping Cart</a>&nbsp;|&nbsp;Total: $" + rows[rows.length - 2] + "&nbsp;|&nbsp;Items: " + rows[rows.length - 1]);
        }
    }
}

function createXhr() {
    var xhr = null;
    try {
        xhr = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e1) {
        try {
            xhr = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (e2) {
            xhr = false;
        }
    }
    if (!xhr && typeof XMLHttpRequest != "undefined") {
        xhr = new XMLHttpRequest()
    }
    return xhr;
}

function createXMLHttpRequest(){
    var xmlHttp = null;
    if(typeof XMLHttpRequest != "undefined"){
        xmlHttp = new XMLHttpRequest();
    } else if(typeof window.ActiveXObject != "undefined"){
        try {
            xmlHttp = new ActiveXObject("Msxml2.XMLHTTP.4.0");
        } catch(e){
            try {
                xmlHttp = new ActiveXObject("MSXML2.XMLHTTP");
            } catch(e){
                try {
                    xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
                } catch(e){
                    xmlHttp = null;
                }
            }
        }
    }
    return xmlHttp;
}

function confirmRemove(item) {
    item--;
    var itemId = "ctl00_cphBody_txtQty_" + item.toString();
    var qty = document.getElementById(itemId).value;
    var itemTitle = "ctl00_cphBody_title_" + item.toString();
    //var title = document.getElementById(itemTitle).innerText;
    var title = $("#" + itemTitle).text();
    var msg = "";
    if (qty == "1" || qty == "0")
        msg = "Remove the item titled '" + title + "' from the shopping cart?";
    else if (qty == "2")
        msg = "Remove both items titled '" + title + "' from the shopping cart?";
    else
        msg = "Remove all " + qty + " items titled '" + title + "' from the shopping cart?";
    return confirm(msg);
}

function noteTextChanged(control, sortorder, cartid) {
    if (!cartid)
        cartid = $('table[__cartid]').attr('__cartid');
    var xhr = createXhr();
    xhr.open("GET", "cartUpdate.aspx?action=update&clientid=1001035&cartid=" + cartid + "&sortorder=" + sortorder + "&field=itemnote&value=" + control.value + "&dts=" + new Date().toString());
    xhr.send(null);
    xhr.close;
}

function removeCartItem(sortorder, cartid) {
    if (!cartid)
        cartid = $('table[__cartid]').attr('__cartid');
    if (!confirmRemove(sortorder))
        return;
    window.location = "cartUpdate.aspx?action=remove&clientid=1001035&cartid=" + cartid + "&sortorder=" + sortorder;
}

function dupeCartItem(sortorder, cartid) {
    if (!cartid)
        cartid = $('table[__cartid]').attr('__cartid');
    window.location = "cartUpdate.aspx?action=duplicate&clientid=1001035&cartid=" + cartid + "&sortorder=" + sortorder;
}

function addToCartWithQty(pmfid) {
    var qty = $("#ctl00_cphBody_txtQuantity").val();
    if (xhr) xhr.abort();
    var nowDate = new Date();
    var xhr = createXMLHttpRequest();
    xhr.open("GET", "cartUpdate.aspx?action=add&clientid=1001035&pmfid=" + pmfid + "&quantity=" + qty + "&dts=" + nowDate.toString());
    xhr.onreadystatechange = function() { processCartItemQueryResponse(screen.width/2, screen.height/2, pmfid); };
    xhr.send(null);

    function processCartItemQueryResponse(x, y, pmfid) {
        if (xhr.readyState == 4) {
            var data = xhr.responseText;
            xhr.close;
            if (data.length !== null || data.trim() !== "") {
                var separator = ";";
                if (data.indexOf("~~~") > -1)
                    separator = "~~~";
                var rows = data.split(separator);
                var title = rows[1];
                var cartid = rows.length > 2 ? rows[2] : "";
                var cookie = rows.length > 3 ? rows[3] : "";
                if (cookie.length > 0) {
                    var now = new Date();
                    var oneMinute = 60 * 1000  // milliseconds in a minute
                    var oneHour = oneMinute * 60
                    var oneDay = oneHour * 24
                    var oneWeek = oneDay * 7
                    var today = new Date()
                    var dateInMS = today.getTime() + oneWeek * 27
                    var targetDate = new Date(dateInMS)
                    setCookie("abccart", cookie, targetDate, "", "", false)
                }
                if (rows[0] == "added") {
                    $("#ctl00_divCartInfo").html("<a href='javascript:goToPage(\"cart.aspx\");'>Shopping Cart</a>&nbsp;|&nbsp;Total: $" + rows[rows.length - 2] + "&nbsp;|&nbsp;Items: " + rows[rows.length - 1]);
                    goToPage('cart.aspx');
                } else
                    returnItemChoice(data, x, y);
            } else {
                alert("This item could not be added at the present time");
            }
        }
    }
}

function addToCart(pmfid, evt) {
    var clickX;
    var clickY;
    if (navigator.appName == "Microsoft Internet Explorer") {
        clickX = window.event.clientX + document.documentElement.scrollLeft;
        clickY = window.event.clientY + document.documentElement.scrollTop;
    } else {
        clickX = evt.pageX;
        clickY = evt.pageY;
    }
    if (xhr) xhr.abort();
    var nowDate = new Date();
    var xhr = createXMLHttpRequest();
    xhr.open("GET", "cartUpdate.aspx?action=add&clientid=1001035&pmfid=" + pmfid + "&dts=" + nowDate.toString());
    xhr.onreadystatechange = function() { processCartItemQueryResponse(clickX, clickY, pmfid); };
    xhr.send(null);

    function processCartItemQueryResponse(x, y, pmfid) {
        if (xhr.readyState == 4) {
            var data = xhr.responseText;
            xhr.close;
            if (data.length !== null || data.trim() !== "") {
                var separator = ";";
                if (data.indexOf("~~~") > -1)
                    separator = "~~~";
                var rows = data.split(separator);
                var title = rows[1];
                var cartid = rows.length > 2 ? rows[2] : "";
                var cookie = rows.length > 3 ? rows[3] : "";
                if (cookie.length > 0) {
                    var now = new Date();
                    var oneMinute = 60 * 1000  // milliseconds in a minute
                    var oneHour = oneMinute * 60
                    var oneDay = oneHour * 24
                    var oneWeek = oneDay * 7
                    var today = new Date()
                    var dateInMS = today.getTime() + oneWeek * 27
                    var targetDate = new Date(dateInMS)
                    setCookie("abccart", cookie, targetDate, "", "", false)
                }
                if (rows[0] == "added") {
                    $("#ctl00_divCartInfo").html("<a href='javascript:goToPage(\"cart.aspx\");'>Shopping Cart</a>&nbsp;|&nbsp;Total: $" + rows[rows.length - 2] + "&nbsp;|&nbsp;Items: " + rows[rows.length - 1]);
                    goToPage('cart.aspx');
                } else
                    returnItemChoice(data, x, y);
            } else {
                alert("This item could not be added at the present time");
            }
        }
    }
}

function setCookie(name, value, expires, path, domain, secure) {
    var curCookie = name + "=" + escape(value) +
					((expires) ? "; expires=" + expires.toUTCString() : "") +
					((path) ? "; path=" + path : "") +
					((domain) ? "; domain=" + domain : "") +
					((secure) ? "; secure" : "");
    document.cookie = curCookie;
}

function addToCartById(pmfid) {
    var xhr = createXhr();
    xhr.onreadystatechange = processAddToCartByIdResponse;
    xhr.open("GET", "cartUpdate.aspx?action=add&clientid=1001035&pmfid=" + pmfid + "&dts=" + new Date().toString());
    xhr.send(null);

    function processAddToCartByIdResponse() {
        if (xhr.readyState == 4) {
            var data = xhr.responseText.split(";");
            xhr.close;
            var state = data[0];
            var title = data[1];
            $("#ctl00_divCartInfo").html("<a href='javascript:goToPage(\"cart.aspx\");'>Shopping Cart</a>&nbsp;|&nbsp;Total: $" + data[data.length - 2] + "&nbsp;|&nbsp;Items: " + data[data.length - 1]);

            if (state == "added")
                alert('"' + title + '" was added to the shopping cart successfully.');
            else
                alert('Failed to add "' + title + '" to the shopping cart at this time.  Please try later.');
        }
    }
}

function returnItemChoice(data, x, y) {
    var records = data.split("~~~");
    var slct = $("#slctItems");
    slct.html("");
    var size = 0;
    for (var i = 0; i < records.length; i++) {
        var choice = $(document.createElement("option"));
        choice.attr("id", "option" + i);
        var fields = records[i].split("(;|;)");
        choice.attr("value", fields[0]);
        if (i == 0)
            choice.attr("selected", "true");
        if (fields[1] == null || fields[1].trim() == "") fields[1] = "[No Description]";
        choice.text(fields[0] + ", " + fields[1].substr(0, 50) + ", Qty: " + fields[2] + ", Subtotal: " + fields[3]);
        choice.appendTo(slct);
        size++;
    }
    slct.attr("size", size.toString());
    var dlg = $("#divChoice").dialog({ modal: true, width: 400, title: "Add it to which line item?" }).dialog("close");
    dlg.dialog("option", "buttons", {
        "Cancel": function() { dlg.dialog("close"); },
        "OK": function() {
            addToCartBySortorder(slct.val());
            dlg.dialog("destroy");
            var x = 1;
        }
    });
    dlg.dialog("open");
}

function addToCartBySortorder(sortorder) {
    var qty = 1;
    if (window.location.href.indexOf("details.aspx") > -1)
        qty = +($("#ctl00_cphBody_txtQuantity").val());
    var xhr = createXhr();
    xhr.onreadystatechange = processAddToCartBySortorderResponse;
    xhr.open("GET", "cartUpdate.aspx?action=add&clientid=1001035&sortorder=" + sortorder + "&quantity=" + qty + "&dts=" + new Date().toString());
    xhr.send(null);

    function processAddToCartBySortorderResponse() {
        if (xhr.readyState == 4) {
            var data = xhr.responseText.split(";");
            xhr.close;
            var state = data[0];
            var title = data[1];
            if (state == "added") {
                $("#ctl00_divCartInfo").html("<a href='javascript:goToPage(\"cart.aspx\");'>Shopping Cart</a>&nbsp;|&nbsp;Total: $" + data[data.length - 2] + "&nbsp;|&nbsp;Items: " + data[data.length - 1]);
                goToPage('cart.aspx');
            } else
                alert('Could not add "' + title + '" to the shopping cart at this time.  Please try again later.');
        }
    }
}

function validateCheckoutInfo(evt) {
    if (validateAccountInfo(evt, false)) {
        if (validateShipAddressType(evt)) {
            if (validatePurchaseInfo(evt))
                document.getElementById("aspnetForm").submit();
        }
    }
}

function validateShipAddressType(evt) {
    var radSchoolCheckedState = $("#ctl00_cphBody_radSchool:checked").val();
    var radBusinessCheckedState = $("#ctl00_cphBody_radBusiness:checked").val();
    var radResidenceCheckedState = $("#ctl00_cphBody_radResidence:checked").val();
    var radOtherCheckedState = $("#ctl00_cphBody_radOther:checked").val();
    var somethingIsChecked = (radSchoolCheckedState || radBusinessCheckedState || radResidenceCheckedState || radOtherCheckedState)

    var clickX;
    var clickY;
    if (navigator.appName == "Microsoft Internet Explorer") {
        clickX = window.event.clientX + document.documentElement.scrollLeft;
        clickY = window.event.clientY + document.documentElement.scrollTop;
    } else {
        clickX = evt.pageX;
        clickY = evt.pageY;
    }

    if (!somethingIsChecked) {
        msgBox("Must specify Shipping Address Type", clickX, clickY);
        return false;
    }

    if (radOtherCheckedState) {
        if ($("#ctl00_cphBody_txtOther").val().trim() == "") {
            msgBox("Must specify Shipping Address Type description if \"Other\"", clickX, clickY);
            return false;
        }
    }
    return true;
}

function checkout(evt) {
    if (validatePurchaseInfo(evt))
        document.getElementById("aspnetForm").submit();
}

function validatePurchaseInfo(evt) {
    var poExists = validateSchoolPO();
    var ccExists = creditCardExists();
    var errmsg = "";
    if (ccExists) {
        if (!isValidCCType())
            errmsg += "Invalid \"Credit Card Type\"<br/>";
        if (!isValidCCNumber())
            errmsg += "Invalid \"Credit Card Number\"<br/>";
        if (!isValidCCName())
            errmsg += "Invalid \"Name on Card\"<br/>";
        if (!isValidCCCVV())
            errmsg += "Invalid \"CVV\" number<br/>";

        var expMsg = isValidCCExpDate();
        if (expMsg.trim() != "") {
            if (expMsg.toLowerCase() == "expired") {
                errmsg += "\"Expiration\" date is in the past.  Please select another Credit Card or payment method<br/>";
            } else if (expMsg.toLowerCase() == "too close") {
                errmsg += "Orders placed after 12 PM (Noon) are processed on the next business day.  Card expiration date will come to pass by then.  Please select another Credit Card or payment method<br/>";
            }
        }
    } else {
        var ortype = document.getElementById("ctl00_cphBody_lstOrgType").value;
        if (ortype === "Individual") {
            errmsg += "This type of purchase requires a credit card";
        } else if (ortype === "Public School" || ortype === "School District") {
            if (!poExists) {
                errmsg += "This type of transaction requires<br/>";
                errmsg += "a purchase order and/or a credit card";
            }
        }
    }

    if (errmsg.length > 0) {
        var clickX;
        var clickY;
        if (navigator.appName == "Microsoft Internet Explorer") {
            clickX = window.event.clientX + document.documentElement.scrollLeft;
            clickY = window.event.clientY + document.documentElement.scrollTop;
        } else {
            clickX = evt.pageX;
            clickY = evt.pageY;
        }
        cartmsgBox(errmsg, clickX, clickY);
        return false;
    }
    return true;
}

function validateSchoolPO(value) {
    var poValue = document.getElementById("ctl00_cphBody_txtSchoolPO").value;
    return (poValue.trim() !== "");
}

function creditCardExists() {
    var ccValue = document.getElementById("ctl00_cphBody_txtCardNumber").value;
    return (ccValue.trim() !== "");
}

function getCCType() {
    if (document.getElementById("ctl00_cphBody_radVisa").checked)
        return "visa";
    if (document.getElementById("ctl00_cphBody_radMasterCard").checked)
        return "mc";
    if (document.getElementById("ctl00_cphBody_radAmex").checked)
        return "amex";
    else
        return "";
}

function isValidCCType() {
    var ccType = getCCType();
    if (ccType.trim() !== "")
        return true;
    else
        return false;
}

function isValidCCNumber() {
    var ccNumber = document.getElementById("ctl00_cphBody_txtCardNumber").value;
    return (isValidCC(getCCType(), document.getElementById("ctl00_cphBody_txtCardNumber").value));
}

function isValidCC(type, ccnum) {
    // Remove all dashes and spaces for the checksum checks to eliminate negative numbers
    ccnum = ccnum.split("-").join("");
    ccnum = ccnum.split(" ").join("");
    if (type == "visa") {
        // Visa: length 16, prefix 4, dashes optional.
        var re = /^4\d{15}$/;
    } else if (type == "mc") {
        // Mastercard: length 16, prefix 51-55, dashes optional.
        var re = /^5[1-5]\d{14}$/;
    } else if (type == "amex") {
        // American Express: length 15, prefix 34 or 37.
        var re = /^3[4,7]\d{13}$/;
    }
    if (!re.test(ccnum))
        return false;
    // Checksum ("Mod 10")
    // Add even digits in even length strings or odd digits in odd length strings.
    var checksum = 0;
    for (var i = (2 - (ccnum.length % 2)); i <= ccnum.length; i += 2) {
        checksum += parseInt(ccnum.charAt(i - 1));
    }
    // Analyze odd digits in even length strings or even digits in odd length strings.
    for (var i = (ccnum.length % 2) + 1; i < ccnum.length; i += 2) {
        var digit = parseInt(ccnum.charAt(i - 1)) * 2;
        if (digit < 10) {
            checksum += digit;
        } else {
            checksum += (digit - 9);
        }
    }
    return ((checksum % 10) == 0);
}

function isValidCCName() {
    return (new RegExp(/^[a-zA-Z]{1,}[ ][a-zA-Z ]{1,}/).test(document.getElementById("ctl00_cphBody_txtNameOnCard").value));
}

function isValidCCCVV() {
    return (new RegExp(/\d{3,4}/).test(document.getElementById("ctl00_cphBody_txtCVV").value));
}

function isValidCCExpDate() {
    var month = $("#ctl00_cphBody_lstExpirationMonth").val();
    var year = $("#ctl00_cphBody_lstExpirationYear").val();
    var goodThruDate = new Date(Date.parse(month.toString() + "/01/" + year.toString() + " 00:00:00 AM") - 1);
    var now = new Date();
    var timeLeft = (goodThruDate.getTime() - now.getTime());
    if (timeLeft < 0) {
        return "expired";
    } else if (timeLeft < 12 * 60 * 60 * 1000) {
        return "too close";
    } else {
        return "";
    }
}

function cartmsgBox(msg, x, y) {
    var msgBox = $(document.createElement("div")).attr("id", "divMsg").html(msg);
    msgBox.dialog({ modal: true, width: 400, title: "Error..." }).dialog("close");
    msgBox.dialog("option", "buttons", { "OK": function() { msgBox.dialog("destroy"); } });
    msgBox.dialog("open");
}

function textboxSelectText(id) {
    document.getElementById(id).select();
}

function shipMethodChanged(radButton) {
    var cartTotal = +document.getElementById("ctl00_cphBody_hdnCartTotal").value
    if (radButton === document.getElementById("ctl00_cphBody_radGround")) {
        shipping = cartTotal * 0.08;
        if (shipping < 8)
            shipping = 8;
    } else if (radButton === document.getElementById("ctl00_cphBody_rad2Day")) {
        shipping = 30 + (cartTotal * 0.15);
    } else if (radButton === document.getElementById("ctl00_cphBody_radNextDay")) {
        shipping = 50 + (cartTotal * 0.25);
    }

    document.getElementById("ctl00_cphBody_spnShipping").innerHTML = "shipping: $" + CurrencyFormatted(shipping);
    document.getElementById("ctl00_cphBody_spnTotalCharge").innerHTML = "&nbsp;= $" + CurrencyFormatted(cartTotal + shipping);

    document.getElementById("ctl00_cphBody_spnShipping").style.color = "FFAA00";
    document.getElementById("ctl00_cphBody_spnTotalCharge").style.color = "FFAA00";

    setTimeout("setToBlack();", 2000);
}

function setToBlack() {
    document.getElementById("ctl00_cphBody_spnShipping").style.color = "000000";
    document.getElementById("ctl00_cphBody_spnTotalCharge").style.color = "000000";
}

function CurrencyFormatted(amount) {
    var i = parseFloat(amount);
    if (isNaN(i)) { i = 0.00; }
    var minus = '';
    if (i < 0) { minus = '-'; }
    i = Math.abs(i);
    i = parseInt((i + .005) * 100);
    i = i / 100;
    s = new String(i);
    if (s.indexOf('.') < 0) { s += '.00'; }
    if (s.indexOf('.') == (s.length - 2)) { s += '0'; }
    s = minus + s;
    return s;
}

function applyNYStateWarning() {
    var shipZipControl = $("#ctl00_cphBody_txtShipZip");
    var billZipControl = $("#ctl00_cphBody_txtBillZip");
    var shipSameAsbillControl = $("#ctl00_cphBody_chkSameAsBillingInfo:checked");
    var nyStateWarningControl = $("#ctl00_cphBody_divNyStateWarning");
    if (shipZipControl.val().trim() != "") {
        $.get("ajxGetStateByZip.aspx", { "zip": shipZipControl.val(), "dts": (new Date()).toString() }, function(data) {
            if (data.toLowerCase() == "ny") {
                nyStateWarningControl.fadeOut(80).fadeIn(80)
                    .fadeOut(80).fadeIn(80)
                    .fadeOut(80).fadeIn(80)
                    .fadeOut(80).fadeIn(80)
                    .fadeOut(80).fadeIn(1500);
            } else {
                nyStateWarningControl.fadeOut(80);
            }
        });
    } else {
        var checkedState = shipSameAsbillControl.val();
        checkedState = checkedState ? "true" : "false";
        if (checkedState == "false") {
            nyStateWarningControl.fadeOut(80);
        } else {
            $.get("ajxGetStateByZip.aspx", { "zip": billZipControl.val(), "dts": (new Date()).toString() }, function(data) {
                if (data.toLowerCase() == "ny") {
                    nyStateWarningControl.fadeOut(80).fadeIn(80)
                        .fadeOut(80).fadeIn(80)
                        .fadeOut(80).fadeIn(80)
                        .fadeOut(80).fadeIn(80)
                        .fadeOut(80).fadeIn(1500);
                } else {
                    nyStateWarningControl.fadeOut(80);
                }
            });
        }
    }
}

function addressTypeChanged(obj) {
    var jobj = $("#ctl00_cphBody_txtOther");
    jobj.attr("disabled", obj.id == "ctl00_cphBody_radOther" ? "" : "disabled");
    jobj.css("border-bottom", obj.id == "ctl00_cphBody_radOther" ? "solid 1px #000000" : "solid 1px #aaaaaa");
}
