﻿/// <reference path="../../Scripts/jquery-1.7.1-vsdoc.js" />

var myViewModel = {};

// Google Analytics - ASynchronous Code
var _gaq = _gaq || [];
if (typeof googleAnalytics != "undefined") {
    _gaq.push(['_setAccount', googleAnalytics]);
    _gaq.push(['_setDomainName', 'none']);
    _gaq.push(['_setAllowLinker', true]);
    _gaq.push(['_trackPageview']);
}

// Update our cart from the database
function updateCart(callback) {
    $.ajax({
        type: "GET",
        url: cartURL + "GetJSONPCart",
        data: {
            "websiteID": websiteID
        },
        dataType: "jsonp",
        cache: false,
        jsonpCallback: callback,
        contentType: "application/json; charset=utf-8",
        crossDomain: true
    });
}

// Initial load of the cart data back from the shopping cart, define all functions underneath
function gotCartCheckout(data) {
    myViewModel = ko.mapping.fromJS(data);
    myViewModel.myPostProcessingLogic = function (elements) {
        $('.currency').formatCurrency({ roundToDecimalPlace: 2, colorize: false, negativeFormat: '-%s%n' });
    }
    myViewModel.myPostProcessingLogicShipping = function (elements) {
        $('.currency').formatCurrency({ roundToDecimalPlace: 2, colorize: false, negativeFormat: '-%s%n' });
    }
    myViewModel.removeItem = function (objectID) {
        $.ajax({
            type: "GET",
            url: cartURL + "JSONPItemRemove",
            data: {
                "objectID": ko.utils.unwrapObservable(objectID.objectID),
                "websiteID": websiteID
            },
            dataType: "jsonp",
            cache: false,
            jsonpCallback: "gotCartCheckoutUpdate",
            contentType: "application/json; charset=utf-8",
            crossDomain: true
        });
        _gaq.push(['_trackEvent', 'Products', 'Remove from Cart', ko.utils.unwrapObservable(objectID.objectID)]);
    }
    myViewModel.updateItem = function (objectID) {
        $.ajax({
            type: "GET",
            url: cartURL + "JSONPItemUpdate",
            data: {
                "objectID": ko.utils.unwrapObservable(objectID.objectID),
                "websiteID": websiteID,
                "quantity": ko.utils.unwrapObservable(objectID.quantity)
            },
            dataType: "jsonp",
            cache: false,
            jsonpCallback: "gotCartCheckoutUpdate",
            contentType: "application/json; charset=utf-8",
            crossDomain: true
        });
        _gaq.push(['_trackEvent', 'Products', 'Update Quantity', ko.utils.unwrapObservable(objectID.objectID), ko.utils.unwrapObservable(objectID.quantity)]);
    }

    myViewModel.clearShippingAddress = function () {
        $.ajax({
            type: "POST",
            url: cartURL + "JSONPCartUpdateAddress",
            data: {
                "AddressShipping.nameFirst": "",
                "AddressShipping.nameLast": "",
                "AddressShipping.address1": "",
                "AddressShipping.address2": "",
                "AddressShipping.city": "",
                "AddressShipping.state": "",
                "AddressShipping.zipcode": "",
                "AddressShipping.country": "",
                "AddressShipping.phone": "",
                "AddressShipping.email": "",
                "shippingmethod": "",
                "websiteID": websiteID
            },
            dataType: "jsonp",
            cache: false,
            jsonpCallback: "gotCartCheckoutUpdate",
            contentType: "application/json; charset=utf-8",
            crossDomain: true
        });
    }

    myViewModel.updateCartAddress = function (shipmethod) {
        $.ajax({
            type: "POST",
            url: cartURL + "JSONPCartUpdateAddress",
            data: {
                "AddressShipping.nameFirst": ko.utils.unwrapObservable(myViewModel.AddressShipping.nameFirst),
                "AddressShipping.nameLast": ko.utils.unwrapObservable(myViewModel.AddressShipping.nameLast),
                "AddressShipping.address1": ko.utils.unwrapObservable(myViewModel.AddressShipping.address1),
                "AddressShipping.address2": ko.utils.unwrapObservable(myViewModel.AddressShipping.address2),
                "AddressShipping.city": ko.utils.unwrapObservable(myViewModel.AddressShipping.city),
                "AddressShipping.state": ko.utils.unwrapObservable(myViewModel.AddressShipping.state),
                "AddressShipping.zipcode": ko.utils.unwrapObservable(myViewModel.AddressShipping.zipcode),
                "AddressShipping.country": ko.utils.unwrapObservable(myViewModel.AddressShipping.country),
                "AddressShipping.phone": ko.utils.unwrapObservable(myViewModel.AddressShipping.phone),
                "AddressShipping.email": ko.utils.unwrapObservable(myViewModel.AddressShipping.email),
                "shippingmethod": shipmethod,
                "websiteID": websiteID
            },
            dataType: "jsonp",
            cache: false,
            jsonpCallback: "gotCartCheckoutUpdate",
            contentType: "application/json; charset=utf-8",
            crossDomain: true
        });
    }

    ko.applyBindings(myViewModel);
    if (typeof updateShippingOptions == 'function') {
        updateShippingOptions();
    }

    $('.currency').formatCurrency({ roundToDecimalPlace: 2, colorize: false, negativeFormat: '-%s%n' });
}

// When we get an updated cart back we just need to update the data not rebuild the full cart object
function gotCartCheckoutUpdate(data) {
    ko.mapping.fromJS(data, myViewModel);
    if (typeof updateShippingOptions == 'function') {
        updateShippingOptions();
        $('#cart-shipping-content-' + ko.utils.unwrapObservable(data.selectedShippingMethod.shippingMethodID)).css({ 'background-color': '#ddd', 'border': '1px dashed #BB0C11' });
        $('#' + ko.utils.unwrapObservable(data.selectedShippingMethod.shippingMethodID) + '_button').hide();
    }
    $('#item_added_to_cart-carttotal').text(data.costSubTotal);
    $('.currency').formatCurrency({ roundToDecimalPlace: 2, colorize: false, negativeFormat: '-%s%n' });
}

$(document).ready(function () {
    // Google Analytics - ASynchronous Code for better loading times
    var ga = document.createElement('script');
    ga.type = 'text/javascript';
    ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0];
    s.parentNode.insertBefore(ga, s);

    updateCart("gotCartCheckout");
});

