﻿/// <reference path="jquery-1.5.1.min.js" />
/// <reference path="date.format.js" />

var OrderID, UserLogin;

function SaveCart() {
    $.ajax({ url: "/AJAXHandlers/CartHandler.ashx"
            , global: false
            , async: true
            , cache: false
            , data: ("reqtype=cartupdate&Cart=" + $('#PopupContent').html())
            , type: "post"
            , dataType: "text"
            , error: function(xmlBack) { alert($("#result", xmlBack).text()); }
    });
}
function GetTax() {
    $.ajax({ url: "http://www.barns.com/salestax/lookup.php"
            , global: false
            , async: true
            , cache: false
            , data: ("qzip=90202")
            , type: "post"
            , dataType: "html"
            , error: function(xmlBack) { alert($("#result", xmlBack).text()); }
            , success: function(dataBack) { alert(dataBack); }
    });
}
function Logout() {
    UserLogin = ''
    CheckLogin('');
}
function Login() {
    var sData = 'reqtype=memberlogin&Email=' + $('#Email').val() + '&PWD=' + $('#PWD').val() + '&remember=' + $('#RememberMe').attr('checked');
    $.ajax({ url: "/AJAXHandlers/ServiceCalls.ashx"
            , global: false
            , async: true
            , cache: false
            , data: (sData)
            , type: "post"
            , dataType: "xml"
            , error: function(xmlBack) { alert($("#result", xmlBack).text()); }
            , success: function(xmlBack) {
                if ($('result User', xmlBack).attr('SYS_ID') > 0) {
                    UserLogin = $('result User', xmlBack).attr('UID');
                    CheckLogin(UserLogin);
                } else {
                    alert('User Account/Password combination is invalid.');
                    $('#PWD').val('');
                }
            }
    });
}
function CheckLogin(LoginName) {
    if (LoginName == '') {
        $('#LoginFields').css('display', 'block');
        $('#LoggedIn').css('display', 'none');
        $('#LoggedIn').text('');
        $('.ObjectDiv').css('display', 'none');
        $('.SignUpDiv').css('display', 'inline');
    } else {
        $('#LoginFields').css('display', 'none');
        $('#LoggedIn').css('display', 'block');
        $('#LoggedIn').html('Logged in as ' + LoginName + '<br /><a href="#" onclick="Logout()">Logout</a><a href="AccountSettings.aspx" target="_blank">My Account Settings</a>');
        $('.ObjectDiv').css('display', 'inline');
        $('.SignUpDiv').css('display', 'none');
    }
}
function GetCart() {
    $.ajax({ url: "/AJAXHandlers/CartHandler.ashx"
            , global: false
            , async: true
            , cache: false
            , data: ("reqtype=getcart")
            , type: "post"
            , dataType: "text"
            , error: function(xmlBack) { alert($("#result", xmlBack).text()); }
            , success: function(dataBack) {
                if (dataBack != '') {
                    $('#PopupContent').html(dataBack);
                    CalcTotals();
                }
            }
    });
}
function GetOrderNumbers() {
    if (UserLogin != '') {
        
        $.ajax({ url: "/AJAXHandlers/CartHandler.ashx"
            , global: false
            , async: true
            , cache: false
            , data: ("reqtype=getprevordernumbers")
            , type: "post"
            , dataType: "xml"
            , error: function(xmlBack) { alert($("result", xmlBack).text()); }
            , success: function(xmlBack) {
                if ($('error', xmlBack).text() == '') {
                    sOpts = new Array();
                    $('Order', xmlBack).each(function() {
                    sOpts[sOpts.length] = '<option value="' + $(this).attr('SYS_ID') + '">' + $(this).attr('ORDER_ID') + ' on ' + $(this).attr('ORDER_DATE').substr(0, 10) + '</option>';
                    });
                    $('#slPrevOrders').html(sOpts.join(''));
                } else { alert('There was an error getting your previous order numbers or else you don\'t have any'); }
            }
        });
    } else {
        alert('Please login to view your previous orders');
    }
}
function LoadOrder() {
    $('#PopupContent').html($('#OrderContent').html());
    CalcTotals();
    document.location = 'Default.aspx';
}
function GetOrderDetail() {
    $.ajax({ url: "/AJAXHandlers/CartHandler.ashx"
            , global: false
            , async: true
            , cache: false
            , data: ("reqtype=getprevorder&SYS_ID=" + $('#slPrevOrders option:selected').val())
            , type: "post"
            , dataType: "xml"
            , error: function(xmlBack) { alert($("#result", xmlBack).text()); }
            , success: function(xmlBack) {
                if ($('#error', xmlBack).text() == '') {
                    $('#OrderContent').html($('Order', xmlBack).attr('ORDER_CONTENTS'));
                } else { alert('There was an error getting your previous order numbers or else you don\'t have any'); }
            }
    });
}
function BuildCartPopup() {
    $("#ShoppingCart").jqm({
        overlay: 50,
        overlayClass: 'overlay',
        onShow: function(h) {
            /* callback executed when a trigger click. Show notice */
            h.w.css('opacity', 0.75).fadeIn(200);
        },
        onHide: function(h) {
            /* callback executed on window hide. Hide notice, overlay. */
            h.w.fadeOut(300, function() { if (h.o) h.o.remove(); });
        }
    });
}
function CalcTotals() {
    var iTotal = 0.00;
    var iCnt = 0;
    var iSH = 0.0;
    var TotalOut = 0.00;
    var iH = 0.00;
    var SHPercent = 0.00;
    var iTax = 0.00;
    var LI = $('#LineItems tbody tr');
    SHPercent = $('#ShipChoice').val();
    $('#sShip').text($('#ShipChoice option:selected').text());
    LI.each(function() {
        iTotal = iTotal + Number($('td', this).eq(4).text());
        iCnt++;
    });
    iH = iTotal * 0.07
    iTax = (Number($('#StateSel').val() / 100) * iTotal);
    $('#sTax').text($('#StateSel option:selected').text());
    $('#cSubTotal').text(iTotal.toFixed(2));
    $('#cTax').text(iTax.toFixed(2));
    TotalOut = (Number(iSH) + Number(iTotal) + Number(iTax)).toFixed(2);
    if (LI.length > 0) {
        switch (SHPercent) {
            case '0':
                if (TotalOut < 125) {
                    iSH = 5.95;
                    $('#ShipMessage').text('Order another $' + (Number(125.00 - TotalOut).toFixed(2)) + ' of product and get FREE Standard Shipping!');
                } else {
                    $('#ShipMessage').text('Your order was over $125.00 - you get FREE Standard Shipping!');
                }
                break;
            case '6':
                SHPercent = SHPercent / 100
                iSH = ((TotalOut * SHPercent) > 8 ? (TotalOut * SHPercent) : 8.00)
                break;
            case '10':
                SHPercent = SHPercent / 100
                iSH = ((TotalOut * SHPercent) > 16 ? (TotalOut * SHPercent) : 16.00)
                break;
            case '17.5':
                SHPercent = SHPercent / 100
                iSH = ((TotalOut * SHPercent) > 20 ? (TotalOut * SHPercent) : 20.00)
                break;
        }
    }
    TotalOut = (Number(iH) + Number(iSH) + Number(iTotal) + Number(iTax)).toFixed(2);
    $('#SandH').text(iSH.toFixed(2));
    $('#cHandling').text(iH.toFixed(2));
    $('#cTotal').text(TotalOut);
    $('#FloatingTotal').text(TotalOut);
    $('#ItemCount').text(iCnt);
    SaveCart();
    $('#State').val($('#StateSel option:selected').text());
}
function CalcLine(LineNo) {
    var LI = $('#LineItems tbody tr[id="' + LineNo + '"]');
    $('td', LI).eq(4).text((Number($('td', LI).eq(3).text()) * $('input', LI).val()).toFixed(2));
    CalcTotals();
}
function AddToCart(itemID) {
    ItemDiv = $('#ProductInfo #' + itemID + ' .ObjectDiv');
    var Price = Number($('div[name="itmPrice"]', ItemDiv).eq(0).text()).toFixed(2);
    var optPrice = Number(GetOptionsPrice($('.ProductOptions Select', ItemDiv))).toFixed(2);
    var Qty = $('input', ItemDiv).val()
    var li = '<tr id="' + $('#LineItems tr').length + '"><td class="RemoveItem"><a href="#" onClick="RemoveItem(' + $('#LineItems tr').length + ')">remove</a></td><td><input type="text" value="' + Qty + '" class="Qty" onblur="CalcLine(' + $('#LineItems tr').length + ')" />'
    + '</td><td class=Description>' + $('div[name="shortName"]', ItemDiv).text() + ':' +$('div[name="itmStkNum"]', ItemDiv).text() + ' ' + GetOptionsText($('.ProductOptions Select', ItemDiv))
    + '</td><td>' + (Number(Price) + Number(optPrice)).toFixed(2)
    + '</td><td>' + ((Number(Price) + Number(optPrice)) * Number(Qty)).toFixed(2).toString() + '</td></tr>';
    $('#LineItems tbody').append(li)
    CalcTotals();
}
function GetOptionsText(SelectsIn) {
    sOpts = new Array();
    sOpts[sOpts.length] = " - Options: ";
    $(SelectsIn).each(function() {
        sOpts[sOpts.length] = ' ' + $('option:selected', this).text() + ':' + $('option:selected', this).attr('Title');
    });
    if (sOpts.length > 1) {
        return sOpts.join('');
    }
    else {
        return '';
    }
}
function GetOptionsPrice(SelectsIn) {
    optPrice = new Number();
    optPrice = 0.00
    $(SelectsIn).each(function() {
        if ($('option:selected', this).val() != undefined) {
            optPrice = Number(optPrice) + Number($('option:selected', this).val());
        }
    });
    return Number(optPrice).toFixed(2);
}

function ShowCart() {
    GetCart();
    $("#ShoppingCart").jqmShow();
}
function HideCart() {
    $("#ShoppingCart").jqmHide();
}
function RemoveItem(itemID) {
    $('#LineItems tr[id="' + itemID + '"]').remove();
    CalcTotals();
}
function ValidateCheckout() {
    var sOut = '';
    $('Table.CustomerInfo input').each(function() {
        if ($(this).val() == '') {
            sOut += $(this).attr('id') + '\r\n';
        }
    });
    if ($("#StateSel").attr("selectedIndex") == 0) {
        sOut += 'State';
    }
    if (sOut != '') {
        alert('The following fields are not filled out\r\n' + sOut + '\r\nPlease fill them out to proceed.');
        return false;
    }
    return true;
}
function validateEmail(elementValue) {
    var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
    if (!emailPattern.test(elementValue)) {
        if (confirm('Please enter a valid email address. If you do NOT have an email address please click cancel and we will use a default')) {
            $('#Email').focus();
        }
        else {
            $('#Email').val('VickyHale@MyDreamDiet.com');
        }
    }
}

function GetOrderText() {
    var sOrdDet = $('#OrderContent').clone();
    $('thead td.RemoveButton', sOrdDet).remove();
    $('td', sOrdDet).remove(':contains("remove")');
    $('td input', sOrdDet).each(function() {
        $(this).replaceWith($(this).val());
    });
    $('td.Description', sOrdDet).css({ width: '650px' });
    //$('td #ShippingType', sOrdDet).text($('#sShip', sOrdDet).text());
    //$('td #Tax', sOrdDet).text($('#sTax', sOrdDet).text());
        $('#Total select', sOrdDet).each(function() {
            $(this).replaceWith($('option:selected', this).text());
        });
    $('#Total td[colspan=3]', sOrdDet).css({ width: '750px' });
    return sOrdDet.html();
}

function MoneyOrder() {
    if (ValidateCheckout()) {
        $('#Processing').show();
        SendEmail('MoneyOrder');
        return true;
    }
    return false;
}

function SendEmail(PaymentType) {
    var sData = 'reqtype=sendemail&Email=' + $('#Email').val()
                    + '&Telephone=' + $('#Telephone').val()
                    + '&OrderDetail=' + escape(GetOrderText())
                    + '&OrderContents=' + escape($('#OrderContent').html())
                    + '&First=' + $('#First').val()
                    + '&Last=' + $('#Last').val()
                    + '&OrderNumber=' + $('#INVOICENO').val()
                    + '&CustomerNumber=' + $('#CUSTNO').val()
                    + '&Address=' + $('#Address').val()
                    + '&City=' + $('#City').val()
                    + '&State=' + $('#State').val()
                    + '&Zip=' + $('#Zip').val()
                    + '&PaymentType=' + PaymentType
                    + '&Notes=' + $('#taShipAddress').val();
    $.ajax({ url: '/AJAXHandlers/CartHandler.ashx'
                , global: false
                , async: false
                , cache: false
                , data: (sData)
                , type: 'post'
                , dataType: 'xml'
                , error: function() { $('#Processing').hide(); }
                , success: (function(xmlBack) {
                    $('#Processing').hide();
                    OrderID = $('OrderInsert', xmlBack).attr('SYS_ID');
                })
    });
}

function MakePayment() {
    if (ValidateCheckout()) {
        $('#Processing').show();
        SendEmail('CreditCard');
        $('#hEmail').val($('#Email').val());
        $('#hFirst').val($('#First').val());
        $('#hLast').val($('#Last').val());
        $('#hAddress').val($('#Address').val());
        $('#hCity').val($('#City').val());
        $('#hState').val($('#State').val());
        $('#hZip').val($('#Zip').val());
        $('#hTelephone').val($('#Telephone').val());
        $('#1-cost').val($('#cTotal').text());
        window.document.forms('MainForm').submit();
    }
}

function AddReferral() {
    if ($("#txtRefName").val() == '') {
        alert('Be sure and add your Name or your Login so we know who your referrals came from');
    }
    else {
        var sdata = "reqtype=addreferral&FName=" + $("#txtFName").val() + "&LName=" + $("#txtLName").val() + "&Email=" + $("#txtEmail").val() + "&Phone=" + $("#txtPhone").val() + "&RefByName=" + $("#txtRefName").val() + "&GENDER=" + $("#Sex").val();
        $.ajax({ url: "/AJAXHandlers/CartHandler.ashx"
            , global: false
            , async: true
            , cache: false
            , data: sdata
            , type: "POST"
            , dataType: "xml"
            , error: function() { alert("Update Failed"); }
            , success: function(xmlBack) {
                if ($("result", xmlBack).text() != "Error Writing Info") {
                    $("#Data P").show().append($("#txtFName").val() + " " + $("#txtLName").val() + ", " + $("#txtEmail").val() + ", " + $("#txtPhone").val() + "<br />");
                    $("#txtFName").val("");
                    $("#txtLName").val("");
                    $("#txtEmail").val("");
                    $("#txtPhone").val("");
                    $("#txtRefName").val("");
                }
            }
        });
    }
}
function GetReferrals(){
    if (UserLogin != '') {
        $.ajax({ url: "/AJAXHandlers/CartHandler.ashx"
            , global: false
            , async: true
            , cache: false
            , data: 'reqtype=getreferrals'
            , type: "POST"
            , dataType: "xml"
            , error: function() { alert("Update Failed"); }
            , success: function(xmlBack) {
                if ($("result", xmlBack).text() != "Error Writing Info") {
                    var sOut = new Array();
                    $('Referral', xmlBack).each(function() {
                        sOut[sOut.length] = $(this).attr('FName') + ' ' + $(this).attr('LName') + ', ' + $(this).attr('Phone') + ', ' + $(this).attr('Email') + '<br />'
                    });
                    $("#Data P").show().append(sOut.join(''));
                }
            }
        });
    }
}

