﻿/// <reference path="jquery-1.3.2-vsdoc.js" />

function ClientServerMessage() {
    this.Error = "";
    this.ClientAction = "";
    this.Action = "";
    this.Content = "";
    this.PostValues = "";
}
var message = new ClientServerMessage();
var processAfter = function () { };

function ContentObject() {
    this.pageName = "";
    this.tableName = "";
    this.loaded = "";
}
var content = new ContentObject();
var defaultContent;
var cartItem = new Object();
var cartRow;
var loggedIn = false;
var userInfo = new Object();
var ajaxOperation = null;
var jsGrid;

String.prototype.trim = function () {
    return this.replace(/^(\s|\xA0)+|(\s|\xA0)+$/g, "");
};

$(document).ready(function () {
    checkCookies();
    $('#txtPassword').keypress(logInKeyPress);
    initHome();
    populateField1Combo(defaultContent.list);
    var pn = $('#txtPartNumber').val();
    if (pn)
        performSearch();
    callServerMethod('GetSmallCart', message);

    if (userInfo.userName)
        setLoggedIn(userInfo.userName);
});

function goHome() {
    enableButton('searchButton', true);
    loadContent('home.html');
}

function showWaitLogo() {
    var tblPos = getPosition($('.pagetable').get(0));
    if (tblPos.x <= 0)
        tblPos.x = $('.pagetable').get(0).offsetLeft;
    $('#waitLogo').css('display', '');
    var logoPos = getPosition($('#waitLogo').get(0));
    $('#waitLogo').css('left', tblPos.x + tblPos.width - logoPos.width - 10 + 'px');
    $('#waitLogo').css('top', tblPos.y + 10 + 'px');
}

function hideWaitLogo() {
    $('#waitLogo').css('display', 'none');
}

function isNumberKey(evt) {
    var charCode = (evt.which) ? evt.which : event.keyCode
    if (charCode === 45) return true;
    if (charCode > 31 && (charCode < 48 || charCode > 57))
        return false;
    return true;
}

function getParent(el, pTagName) {
    if (!el)
        return null;
    else if (el.nodeType == 1 && el.tagName.toLowerCase() == pTagName.toLowerCase())
        return el;
    else
        return getParent(el.parentNode, pTagName);
}

function getScrollPos() {
    var x = 0, y = 0;
    if ($.browser.msie && $.browser.version < 7) {
        y = Math.max($(document.documentElement).scrollTop(), $(document.body).scrollTop(), $(window).scrollTop());
        x = Math.max($(document.documentElement).scrollLeft(), $(document.body).scrollLeft(), $(window).scrollLeft());
    }
    return { x: x, y: y };
}

function callServerMethod(serverMethod, data) {
    if (ajaxOperation && ajaxOperation.readyState != 4 && ajaxOperation.readyState != 0) {
        setTimeout(function () { callServerMethod(serverMethod, data) }, 1);
        return;
    }
    showWaitLogo();
    if (typeof data != 'string')
        data = JSON.stringify(data);
    data = encodeURIComponent(data);
    ajaxOperation = $.post('Default.aspx', 'WebMethod=' + serverMethod + '&' + 'WebMethodRequest=' + data, processResponse);
}

function doLogIn() {
    var un = $('#txtUserName').val();
    var pw = $('#txtPassword').val();
    if (!un && !pw) {
        $('#pnlLogin').slideUp();
        return;
    }
    message.Action = 'LogIn';
    message.PostValues = JSON.stringify({ UserName: un, Password: pw });
    callServerMethod('LogIn', message);
    $('#txtUserName').val('');
    $('#txtPassword').val('');
}

function showLogin(elem) {
    if ($('#lnkLogin').text().toLowerCase() == 'log out') {
        message.Action = 'LogOut';
        message.PostValues = '';
        callServerMethod('LogOut', message);
        return;
    }
    var link = jQuery(elem);
    var x = link.position().left + link.width() - $("#pnlLogin").width();
    var y = link.position().top + link.height();
    $("#pnlLogin").css('zIndex', 500);
    $("#pnlLogin").css('top', y + getScrollPos().y + 'px').css('left', x + getScrollPos().x + 'px');
    if ($("#pnlLogin").css('display').toLowerCase() == 'none')
        $("#pnlLogin").slideDown("slow", function () { $('#txtUserName').get(0).focus(); });
    else
        $('#pnlLogin').slideUp();
}

function getPosition(elem) {
    var pos = new Object();
    var link = jQuery(elem);
    pos['x'] = link.position().left + getScrollPos().x;
    pos['y'] = link.position().top + getScrollPos().y;
    pos['width'] = link.width();
    pos['height'] = link.height();
    return pos;
}

function setLoggedIn(userName) {
    $('#lnkLogin').text('Log Out');
    $('#lnkCustomerName').text(userName);
    $('#pnlLogin').slideUp();
    $('#sep1').hide();
    $('#lnkSignUp').hide();
    $('#lnkCustomerName').show();
    loggedIn = true;

    if (content.pageName.toLowerCase() == 'shoppingcart.html') {
        loadContent(content.pageName);
    }
    else {
        if (jsCartGrid.getRowCount() > 0) {
            message.PostValues = '';
            callServerMethod('GetSmallCart', message);
        }

        if (userInfo.skipHome && userInfo.skipHome.toLowerCase() == 'y')
            userInfo.skipHome = '';
        else {
            goHome();
        }
    }

}

function logInKeyPress(e) {
    if (e.keyCode == 13)
        doLogIn();
}

function initHome() {
    var chk = document.getElementById('rotator');
    if (!chk) return;
    $('#rotator').cycle({ fx: 'fade', timeout: 5000, speed: 1000, pause: 1, sync: 1 });
    $('#rotator').click(function () { loadContent('products.html', 'Parts'); });
    $('#rotator').css('cursor', 'pointer');
}

function populateField1Combo(list) {
    if (typeof list == 'string')
        list = eval('(' + list + ')');
    $('#cboManufacturer').html('');
    for (var i = 0, l = list.length; i < l; i++) {
        var opt = document.createElement('option');
        opt.text = list[i];
        opt.value = list[i];
        $('#cboManufacturer').get(0).options.add(opt);
    }
}

function populateCombo(combo, list) {
    if (typeof list == 'string')
        list = eval('(' + list + ')');
    $(combo).html('');
    for (var i = 0, l = list.length; i < l; i++) {
        var opt = document.createElement('option');
        opt.text = list[i];
        opt.value = list[i];
        $(combo).get(0).options.add(opt);
    }
}

function setSelected(combo, val) {
    for (var i = 0, l = combo.options.length; i < l; i++) {
        if (combo.options[i].value == val)
            combo.selectedIndex = i;
    }
}

function performSearch() {
    if (content.pageName.toLowerCase() == 'products.html')
        loadContent(content.pageName, content.tableName, $('#cboManufacturer').val(), $('#txtPartNumber').val(), $('#txtDescription').val(), 0);
    else {
        loadContent('products.html', defaultContent.tableName, $('#cboManufacturer').val(), $('#txtPartNumber').val(), $('#txtDescription').val(), 0);
    }
}

function getMore() {
    var rows = jsGrid.getRowCount();
    loadContent(content.pageName, content.tableName, $('#cboManufacturer').val(), $('#txtPartNumber').val(), $('#txtDescription').val(), rows);
}

function showSmallCart(cartData) {
    var grdTbl = getParent($('#jsCartGrid').get(0), 'table');
    jsCartGrid.clearGrid();
    var cols = eval('(' + cartData.gridColumns + ')');
    jsCartGrid.popGridColumns(cols);
    var data = eval('(' + cartData.gridData + ')');
    jsCartGrid.popGridFromJson(data, true, null, true);
    $('#smallCartTotal').html('Total: ' + cartData.total);
    data = (data != '') ? eval('(' + data + ')') : null;
    if (data.rows.length > 0) {
        $('#lblSmallCart').css('display', 'none');
        $('#smallCartTotal').css('display', '');
        $('#linkCartDetails').show();
        grdTbl.style.display = '';
    }
    else {
        $('#lblSmallCart').css('display', 'block');
        $('#smallCartTotal').css('display', 'none');
        $('#linkCartDetails').hide();
        grdTbl.style.display = 'none';
    }
    jsCartGrid.refreshGrid();
}

function logOut() {
    $('#lnkLogin').text('Log In');
    $('#lnkCustomerName').hide();
    $('#lnkSignUp').show();
    $('#pnlLogin').slideUp();
    loggedIn = false;
    if (jsCartGrid.getRowCount() > 0) {
        message.PostValues = '';
        callServerMethod('GetSmallCart', message);
    }
    if (content.pageName.toLowerCase() == 'shoppingcart.html') {
        loadContent(content.pageName);
    }
    if (content.pageName.toLowerCase() == 'products.html') {
        goHome();
    }
}

function enableButton(id, trueFalse) {
    var jq = '#' + id;
    var cls = $(jq).get(0).className;
    var clsName = 'btn';
    if (cls && cls.toLowerCase().indexOf('small') > -1)
        clsName += 'Small';
    if (trueFalse) {
        $(jq).get(0).className = clsName;
        $(jq).get(0).disabled = false;
    }
    else {
        $(jq).get(0).className = clsName + 'Disabled';
        $(jq).get(0).disabled = true;
    }
}

function showProducts(productData) {
    var bfirst = false;
    if (productData.more.toLowerCase() == 'n') {
        bfirst = true;
        $('#mainContent').html(productData.content);
        $('#productHeader span').html(productData.header);
        $('#moreButton').get(0).onclick = getMore;

        populateField1Combo(productData.field1List);
        jsGrid = new jsWebGrid('jsGrid', '{clientSort:"false",rowClass:"normalRow",altRowClass:"altRow",bodyCellClass:"bodyCell",selectedRowClass:"selRow",sortASCImage:"/WebResource.axd?d=gBxyIzHvuUEh4937CGqB7zOx489r7YPw6DesMtTT1Bc1&t=634085929225127688",sortDESCImage:"/WebResource.axd?d=gBxyIzHvuUEh4937CGqB7z1d5RVkyoTlSDvdw5QDfp01&t=634085929225127688",rowSelection:"None",rowDoubleClickLink:""}');

        var grdTbl = getParent($('#jsGrid').get(0), 'table');
        if (!grdTbl) return;

        var h = $('#mainContent').height() - 15;
        h -= $('#productHeader').height();
        h -= $('#productFooter').height();
        grdTbl.style.height = h + 'px';
        $('#jsGrid').get(0).style.height = h + 'px';

        jsGrid.clearGrid();
        var cols = eval('(' + productData.gridColumns + ')');
        jsGrid.popGridColumns(cols);
    }
    $('#cboManufacturer').val(productData.search1);
    $('#txtPartNumber').val(productData.search2);
    $('#txtDescription').val(productData.search3);

    var data = eval('(' + productData.gridData + ')');
    jsGrid.popGridFromJson(data, true, null, bfirst);
    data = (data != '') ? eval('(' + data + ')') : null;
    if (data.rows.length < 25)
        enableButton('moreButton', false);

    if (jsGrid.getRowCount() < 1) {
        $('#gridContainer').css('display', 'none');
        $('#lblMainProducts').css('display', '');
        $('#productFooter').css('display', 'none');
    }
    enableButton('searchButton', true);

}

function addToCart(e) {
    if (!e) e = window.event;
    var elem = e.target != null ? e.target : e.srcElement;
    if (elem.nodeType == 3) elem = elem.parentNode; // defeat Safari bug

    var inp = getParent(elem, 'td').getElementsByTagName('input')[0];
    var qty = inp.value;
    if (!qty) return;
    var row = getParent(elem, 'tr');
    cartRow = row;
    var rowID = row.getAttribute('rowid');
    var id = jsGrid.getCellValueByColName(rowID, 'ID');
    var options = jsGrid.getCellValueByColName(rowID, 'Options');
    if (options.toLowerCase() == '&nbsp;') options = '';

    cartItem['qty'] = qty;
    cartItem['id'] = id;
    cartItem['tableName'] = content.tableName;
    inp.value = '';
    if (options && options.trim().length > 0) {
        ieSelectFix(false);
        showOptions(options);
        $("#optionsDialog").attr('title', 'Item Options');
        $("#optionsDialog").dialog({
            bgiframe: true, draggable: false, resizable: false,
            height: 240, position: 'center',
            modal: true,
            close: function (event, ui) { ieSelectFix(true); $(this).dialog("destroy"); },
            buttons: { "Cancel": function () {
                ieSelectFix(true);
                $(this).dialog("destroy");
            }, "Ok": function () {
                getSelectedOptions();
                doCartAddition();
                ieSelectFix(true);
                $(this).dialog("destroy");
            }
            }
        });
    }
    else {
        doCartAddition();
    }
}

function getSelectedOptions() {
    var sels = document.getElementById('optionsDialog').getElementsByTagName('select');
    var opts = '';
    for (var i = 0, l = sels.length; i < l; i++) {
        opts += sels[i].getAttribute('valuename') + ' = ' + sels[i].value + ', ';
    }
    opts = opts.trim();
    if (opts) opts = opts.substr(0, opts.length - 1);
    cartItem['options'] = opts;
}

function doCartAddition() {
    var options;
    if (cartItem['options'])
        options = cartItem['options'];
    else
        options = '';

    message.PostValues = JSON.stringify({ qty: cartItem['qty'], tableName: cartItem['tableName'], id: cartItem['id'], options: options });
    callServerMethod('AddToCart', message);
    cartItem = new Object();
    animateCart();
}

function animateCart() {
    $('#cartAnimationBox').css('display', '');
    var rowPos = getPosition(cartRow);
    var cartBoxPos = getPosition($('#smallCart').get(0));
    $('#cartAnimationBox').css('left', rowPos.x + 'px');
    $('#cartAnimationBox').css('top', rowPos.y + 'px');
    $('#cartAnimationBox').css('width', rowPos.width + 'px');
    $('#cartAnimationBox').css('height', rowPos.height + 'px');
    $('#cartAnimationBox').animate({ left: cartBoxPos.x, top: cartBoxPos.y, width: cartBoxPos.width, height: cartBoxPos.height },
                                          500,
                                          function () { $('#cartAnimationBox').css('display', 'none'); }
                                          );
}

function showOptions(options) {
    options = options.split(':');
    if (options.length <= 0) return;
    var tbl = '<table cellpadding="0" cellspacing="5" border="0" align="center">';
    for (var i = 0, l = options.length; i < l; i++) {
        var label = options[i].substr(0, options[i].indexOf('=', 0)).trim();
        var parts = options[i].substr(options[i].indexOf('=', 0) + 1).trim();
        var items = parts.split(';');
        tbl += '<tr><td>' + label + '</td><td>';
        tbl += '<select valuename="' + label + '">';
        for (var x = 0, y = items.length; x < y; x++) {
            tbl += '<option value="' + items[x].trim() + '">' + items[x].trim() + '</option>';
        }
        tbl += '</td></tr>';
    }
    tbl += '</table>';
    $('#optionsDialog').html(tbl);
}

function loadContent(page, tableName, search1, search2, search3, index) {
    $('#mainContent').css('overflow', 'auto');
    $('#rotator').cycle('stop');
    message.Action = 'loadContent';
    if (typeof tableName == 'undefined')
        tableName = '';
    if (typeof search1 == 'undefined')
        search1 = '';
    if (typeof search2 == 'undefined')
        search2 = '';
    if (typeof search3 == 'undefined')
        search3 = '';
    if (typeof index == 'undefined')
        index = 0;
    if (index <= 0) {
        if (page.toLowerCase() != 'products.html')
            populateField1Combo(defaultContent.list);
    }
    content.pageName = page;
    content.tableName = tableName;
    message.PostValues = JSON.stringify({ page: page, tableName: tableName, search1: search1, search2: search2, search3: search3, index: index });
    callServerMethod('LoadContent', message);
}

function formSubmit() {
    var form = getFormObject();
    if (form['error']) {
        alert(form['error']);
        return;
    }
    var sm = $('#contentServerMethod').val();
    message.PostValues = JSON.stringify(form);
    callServerMethod(sm, message);
}

function getFormObject() {
    var jinp, id, val, i;
    var form = new Object();
    var inps = $('#mainContent input,#mainContent select,#mainContent textarea');
    for (i = 0, l = inps.length; i < l; i++) {
        jinp = jQuery(inps[i]);
        id = jinp.attr('id');
        val = jinp.val();
        if (jinp.attr('required') == 'true' && !val.trim() && !jinp.get(0).disabled)
            form['error'] = 'Required value was not provided.';
        if (inps[i].type && inps[i].type.toLowerCase() == 'checkbox') {
            if (inps[i].checked)
                val = 'true';
            else
                val = 'false';
        }
        if (id.trim())
            form[id] = val;
    }
    return form;
}

function populateForm(formObject) {
    if (typeof formObject == 'string')
        formObject = eval('(' + formObject + ')');
    for (var name in formObject) {
        var elem = $('#' + name).get(0);
        if (elem && formObject[name]) {
            if (elem.type && elem.type.toLowerCase() == 'checkbox') {
                elem.checked = formObject[name].toLowerCase() == 'true';
            }
            else
                $('#' + name).val(formObject[name]);
        }
    }
}

function showShoppingCart(cartData) {
    $('#mainContent').html(cartData.content);

    if (!loggedIn) {
        $('#userCart').hide();
        $('#saveCartButton').hide();
        $('#deleteCartButton').hide();
    }

    var h = $('#mainContent').height() - 15;
    h -= $('#cartHeader').height();
    h -= $('#cartFooter').height();

    if (cartData.cartList) {
        if ($('#userCartSelect').get(0))
            populateCombo($('#userCartSelect').get(0), cartData.cartList);
    }
    if (cartData.selectedCart) {
        $('#userCartSelect').get(0).value = cartData.selectedCart;
        if (cartData.selectedCart.toLowerCase().trim() == '<new cart>') {
            enableButton('saveCartButton', true);
            enableButton('deleteCartButton', false);
        }
        else {
            enableButton('saveCartButton', false);
            enableButton('deleteCartButton', true);
        }
    }

    var cd = (cartData.gridData != '') ? eval('(' + cartData.gridData + ')') : null;
    if (typeof cd == 'string')
        cd = eval('(' + cd + ')');
    if (cd.rows.length < 1) {
        $('#gridContainer').css('display', 'none');
        $('#lblMainCart').css('display', '');
        if (!loggedIn || cartData.selectedCart.toLowerCase() == '<new cart>')
            $('#cartFooter').css('display', 'none');
        else {
            enableButton('checkOutButton', false);
            enableButton('saveCartButton', false);
            enableButton('deleteCartButton', true);
            enableButton('updateCartButton', false);
            $('#lblMainCart').css('height', h + 'px');
            $('#printFriendlyLink').hide();
            $('#cartTotalRow').hide();
        }
    }
    else {
        $('#gridContainer').css('display', '');
        $('#lblMainCart').css('display', 'none');
        $('#cartFooter').css('display', '');

        jsGrid = new jsWebGrid('jsGrid', '{clientSort:"false",rowClass:"normalRow",altRowClass:"altRow",bodyCellClass:"bodyCell",selectedRowClass:"selRow",sortASCImage:"/WebResource.axd?d=gBxyIzHvuUEh4937CGqB7zOx489r7YPw6DesMtTT1Bc1&t=634085929225127688",sortDESCImage:"/WebResource.axd?d=gBxyIzHvuUEh4937CGqB7z1d5RVkyoTlSDvdw5QDfp01&t=634085929225127688",rowSelection:"None",rowDoubleClickLink:""}');

        var grdTbl = getParent($('#jsGrid').get(0), 'table');
        if (!grdTbl) return;
        grdTbl.style.height = h + 'px';
        $('#jsGrid').get(0).style.height = h + 'px';

        jsGrid.clearGrid();
        var cols = eval('(' + cartData.gridColumns + ')');
        jsGrid.popGridColumns(cols);

        var data = eval('(' + cartData.gridData + ')');
        jsGrid.popGridFromJson(data, true, null, true);

        if (cartData.total)
            $('#cartTotal').html('Current Total:&nbsp;' + cartData.total + '&nbsp;');
        if (cartData.weight)
            $('#cartWeight').html('&nbsp;Current Weight:&nbsp;' + cartData.weight + '&nbsp;LB.');
    }


    callServerMethod('GetSmallCart', message);
}

function openCart(e) {
    if (!e) e = window.event;
    var elem = e.target != null ? e.target : e.srcElement;
    if (elem.nodeType == 3) elem = elem.parentNode; // defeat Safari bug
    var cart = $(elem).val();
    message.Action = 'OpenCart';
    message.PostValues = JSON.stringify({ cartName: cart });
    callServerMethod('OpenCart', message);
}

function saveCart() {
    var cart = $('#userCartSelect').val();
    if (cart.toLowerCase().trim() != '<new cart>') return;
    ieSelectFix(false);
    $('#saveCartDialog').dialog({
        bgiframe: true, draggable: false, resizable: false,
        height: 160, position: 'center',
        modal: true,
        close: function (event, ui) { ieSelectFix(true); $(this).dialog("destroy"); },
        open: function (event, ui) { setTimeout(function () { try { $('#txtCartName').get(0).focus(); } catch (e) { } }, 1000); },
        buttons: { "Cancel": function () {
            ieSelectFix(true);
            $(this).dialog("destroy");
        }, "OK": function () {
            var cart = $('#txtCartName').val();
            var x = $('#userCartSelect').get(0);
            for (i = 0; i < x.length; i++) {
                if (cart.trim().toLowerCase() == x.options[i].text.trim().toLowerCase()) {
                    alert('A shopping cart with this name already exists.\r\nPlease use a unique name for this shopping cart.');
                    return;
                }
            }
            message.Action = 'SaveCart';
            message.PostValues = JSON.stringify({ cartName: cart });
            callServerMethod('SaveCart', message);
            ieSelectFix(true);
            $(this).dialog("destroy");
        }
        }
    });
}

function deleteCart() {
    var cart = $('#userCartSelect').val();
    if (cart.toLowerCase().trim() == '<new cart>') return;
    ieSelectFix(false);
    $('#deleteCartDialog').dialog({
        bgiframe: true, draggable: false, resizable: false,
        height: 160, position: 'center',
        modal: true,
        close: function (event, ui) { ieSelectFix(true); $(this).dialog("destroy"); },
        buttons: { "No": function () {
            ieSelectFix(true);
            $(this).dialog("destroy");
        }, "Yes": function () {
            var cart = $('#userCartSelect').val();
            message.Action = 'DeleteCart';
            message.PostValues = JSON.stringify({ cartName: cart });
            callServerMethod('DeleteCart', message);
            ieSelectFix(true);
            $(this).dialog("destroy");
        }
        }
    });
}

function removeFromCart(e) {
    if (!e) e = window.event;
    var elem = e.target != null ? e.target : e.srcElement;
    if (elem.nodeType == 3) elem = elem.parentNode; // defeat Safari bug
    if (!confirm('Are you sure you want to remove this item?'))
        return;
    var row = getParent(elem, 'tr');
    var rowID = row.getAttribute('rowid');
    var id = jsGrid.getCellValueByColName(rowID, 'ID');
    message.Action = 'removeFromCart';
    message.PostValues = JSON.stringify({ id: id });
    callServerMethod('removeFromCart', message);
}

function updateCartQty() {
    var cartData = jsGrid.serializeData(false);
    message.Action = 'updateCart';
    message.PostValues = cartData;
    callServerMethod('UpdateCart', message);
}


function processResponse(data, textStatus) {
    hideWaitLogo();
    $('#mainContent').show();
    if (textStatus.toLowerCase() == 'success') {
        var returnMessage;
        try { returnMessage = eval('(' + data + ')') } catch (e) { goHome(); return; }

        if (returnMessage.error) {
            hideWaitLogo();
            if (returnMessage.logOut.toLowerCase() == 'y')
                logOut();
            alert(returnMessage.error);
            return;
        }

        if (returnMessage.messageType) {
            if (returnMessage.messageType.toLowerCase() == 'simpleaction') {
                if (returnMessage.action.toLowerCase() == 'logout')
                    logOut();
                else if (returnMessage.action.toLowerCase() == 'login') {
                    setLoggedIn(returnMessage.content);
                }
                else if (returnMessage.action.toLowerCase() == 'staticpage') {
                    $('#mainContent').css('overflow', 'auto');
                    $('#mainContent').html(returnMessage.content);
                }
                else if (returnMessage.action.toLowerCase() == 'homepage') {
                    $('#mainContent').css('overflow', 'hidden');
                    $('#mainContent').html(returnMessage.content);
                    initHome();
                }
            }
            else if (returnMessage.messageType.toLowerCase() == 'products') {
                $('#mainContent').css('overflow', 'hidden');
                showProducts(returnMessage);
            }
            else if (returnMessage.messageType.toLowerCase() == 'shoppingcart') {
                $('#mainContent').css('overflow', 'hidden');
                showShoppingCart(returnMessage);
            }
            else if (returnMessage.messageType.toLowerCase() == 'smallcart') {
                showSmallCart(returnMessage);
            }
            else if (returnMessage.messageType.toLowerCase() == 'profile') {
                $('#mainContent').html(returnMessage.content);
                populateForm(returnMessage.userData);
            }
            else if (returnMessage.messageType.toLowerCase() == 'billto') {
                $('#mainContent').html(returnMessage.content);
                populateForm(returnMessage.userData);
            }
            else if (returnMessage.messageType.toLowerCase() == 'ordersummary') {
                $('#mainContent').html(returnMessage.content);
                showOrderSummaryPage(returnMessage);
            }
        }
        if (returnMessage.script)
            eval(returnMessage.script);

        if (returnMessage.logOut.toLowerCase() == 'y')
            logOut();

        if (returnMessage.refreshCart && returnMessage.refreshCart.toLowerCase() == 'y')
            callServerMethod('GetSmallCart', message);

        if (processAfter)
            processAfter();
        processAfter = null;
    }

}

function showImage(imageFile, width, height) {
    $('#optionsDialog').html('<img src="' + imageFile + '" border="0" alt="" />');
    ieSelectFix(false);
    $("#optionsDialog").attr('title', 'Image View');
    $("#optionsDialog").dialog({
        bgiframe: true, draggable: false, resizable: false,
        height: height + 130, position: 'center', width: width + 30,
        modal: true,
        close: function (event, ui) { ieSelectFix(true); $(this).dialog("destroy"); },
        buttons: { "Ok": function () { ieSelectFix(true); $(this).dialog("destroy"); }
        }
    });
}

function ieSelectFix(trueFalse) {
    if (jQuery.browser.msie && jQuery.browser.version < 7) {
        if (!trueFalse)
            $('select').css('visibility', 'hidden');
        else
            $('select').css('visibility', '');
    }
}

function showMaps() {

    var dropdown = '<div style="text-align:center;"><center><span class="formLabel">Select a warehouse location:</span><br/><select id="selectShippingState" onchange="changeMap();">';
    dropdown += '<option value="FedEx_CA">California using FedEx</option><option value="FedEx_IL">Illinois using FedEx</option><option value="FedEx_KS">Kansas using FedEx</option><option value="FedEx_PA">Pennsylvania using FedEx</option><option selected value="FedEx_SC">South Carolina using FedEx</option>';
    dropdown += '<option value="UPS_CA">California using UPS</option><option value="UPS_IL">Illinois using UPS</option><option value="UPS_KS">Kansas using UPS</option><option value="UPS_PA">Pennsylvania using UPS</option><option value="UPS_SC">South Carolina using UPS</option>';
    dropdown += '</select><br/><img border="0" src="fedex/FedEx_SC.png" id="shippingMap"/></center></div>';
    $('#optionsDialog').html(dropdown);
    ieSelectFix(false);
    $("#optionsDialog").attr('title', 'Shipping Map');
    $("#optionsDialog").dialog({
        bgiframe: true, draggable: false, resizable: false,
        height: 530, position: 'center', width: 560,
        modal: true,
        close: function (event, ui) { ieSelectFix(true); $(this).dialog("destroy"); },
        buttons: { "Ok": function () { ieSelectFix(true); $(this).dialog("destroy"); }
        }
    });
    $('#selectShippingState').show();

}

function changeMap(e) {
    var state = $('#selectShippingState').val();
    $('#shippingMap').get(0).src = 'fedex/' + state + '.png';
}

function openFile(winurl, winname, winfeatures) {
    var hK = window.open(winurl, winname, winfeatures);
}

function checkCookies() {
    Set_Cookie('test', 'none', '', '/', '', '');
    if (Get_Cookie('test')) {
        cookie_set = true;
        Delete_Cookie('test', '/', '');
    }
    else {
        alert('This site requires cookies be enabled.\r\nPlease enable cookies and try again.');
        cookie_set = false;
    }
}

function Set_Cookie(name, value, expires, path, domain, secure) {
    var today = new Date();
    today.setTime(today.getTime());
    if (expires) {
        expires = expires * 1000 * 60 * 60 * 24;
    }
    var expires_date = new Date(today.getTime() + (expires));

    document.cookie = name + "=" + escape(value) + ((expires) ? ";expires=" + expires_date.toGMTString() : "") + ((path) ? ";path=" + path : "") + ((domain) ? ";domain=" + domain : "") + ((secure) ? ";secure" : "");
}

function Get_Cookie(check_name) {
    var a_all_cookies = document.cookie.split(';');
    var a_temp_cookie = '';
    var cookie_name = '';
    var cookie_value = '';
    var b_cookie_found = false;

    for (i = 0; i < a_all_cookies.length; i++) {
        a_temp_cookie = a_all_cookies[i].split('=');
        cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');
        if (cookie_name == check_name) {
            b_cookie_found = true;
            if (a_temp_cookie.length > 1) {
                cookie_value = unescape(a_temp_cookie[1].replace(/^\s+|\s+$/g, ''));
            }
            return cookie_value;
            break;
        }
        a_temp_cookie = null;
        cookie_name = '';
    }
    if (!b_cookie_found) {
        return null;
    }
}

function Delete_Cookie(name, path, domain) {
    if (Get_Cookie(name))
        document.cookie = name + "=" + ((path) ? ";path=" + path : "") + ((domain) ? ";domain=" + domain : "") + ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}
