﻿$j = jQuery.noConflict();

function setCookie(c_name, value, expiredays) {
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + expiredays);
    document.cookie = c_name + "=" + escape(value) +
                ((expiredays == null) ? "" : ";expires=" + exdate.toGMTString());
}

function getCookie(c_name) {
    if (document.cookie.length > 0) {
        c_start = document.cookie.indexOf(c_name + "=");
        if (c_start != -1) {
            c_start = c_start + c_name.length + 1;
            c_end = document.cookie.indexOf(";", c_start);
            if (c_end == -1) c_end = document.cookie.length;
            return unescape(document.cookie.substring(c_start, c_end));
        }
    }
    return "";
}

var Model = {};
var View = {};
var Controller = {};

/*
    Model
*/
Model.Basket = Class.create({
    initialize: function (basketId) {
        this.id = basketId;
    },
    setOrderCode: function (orderCode) {
        this.orderCode = orderCode;
    },
    setDeliveryLocation: function (deliveryLocation) {
        this.deliveryLocation = deliveryLocation;
    },
    addToBasket: function (productId, quantity) {
        var post = { basketId: this.id, productId: productId, quantity: quantity };
        var url = "/Data/WS/Basket.asmx/AddProductToBasket";

        new Ajax.Request(url, {
            postBody: Object.toQueryString(post),
            onSuccess: function (response) {
                //alert("addToBasket");
                this.getBasket();
            } .bind(this),
            onFailure: function (response) {
                alert("ERROR: If the problem persists please contact us via the contact page.");
            }
        });
    },
    getBasket: function () {
        //alert("getBasket: Order Code = " + this.orderCode + " Shipping Location = " + this.deliveryLocation);
        var post = { basketId: this.id };
        var url = "/Data/JSON/GetBasket.ashx";

        if (this.orderCode) Object.extend(post, { orderCode: this.orderCode });
        if (this.deliveryLocation) Object.extend(post, { deliveryLocation: this.deliveryLocation });

        new Ajax.Request(url, {
            postBody: Object.toQueryString(post),
            onSuccess: function (response) {
                $j(this).trigger("Basket:Updated", response.responseJSON);
            } .bind(this),
            onFailure: function (response) {
                alert("ERROR: If the problem persists please contact us via the contact page.");
            }
        });
    },
    deleteProduct: function (productId) {
        var post = { basketId: this.id, productId: productId };
        var url = "/Data/WS/Basket.asmx/RemoveProductFromBasket";

        new Ajax.Request(url, {
            method: "post",
            postBody: Object.toQueryString(post),
            onSuccess: function (response) {
                //alert("deleteProduct");
                this.getBasket();
            } .bind(this),
            onFailure: function (response) {
                alert("ERROR: If the problem persists please contact us via the contact page.");
            }
        });
    },
    clearBasket: function () {
        var post = { basketId: this.id };
        var url = "/Data/WS/Basket.asmx/ClearBasket";

        new Ajax.Request(url, {
            method: "post",
            postBody: Object.toQueryString(post),
            onSuccess: function (response) {
                //alert("clearBasket");
                this.getBasket();
            } .bind(this),
            onFailure: function (response) {
                alert("ERROR: If the problem persists please contact us via the contact page.");
            }
        });
    },
    updateProductQuantity: function (product, quantity) {
        var post = { basketId: this.id, productId: product, quantity: quantity };
        var url = "/Data/WS/Basket.asmx/UpdateProductQuantityInBasket";

        new Ajax.Request(url, {
            method: "post",
            postBody: Object.toQueryString(post),
            onSuccess: function (response) {
                //alert("updateProductQuantity");
                this.getBasket();
            } .bind(this),
            onFailure: function (response) {
                alert("ERROR: If the problem persists please contact us via the contact page.");
            }
        });
    }
});

/*
    Controller
*/
Controller.Basket = Class.create({
    initialize: function (data) {
        this.data = data;
        //$j(this.data).bind("Basket:Updated", function (event, data) { alert("Basket Event: " + Object.toJSON(data)); });
        $j(this.data).bind("Basket:Updated", this.render);
    },
    refresh: function () {
        //alert("refresh: ");
        Object.extend(this.data, { orderCode: $F("orderCode") });
        Object.extend(this.data, { deliveryLocation: $F("deliveryLocation") });
        //        this.data.deliveryLocation = $F("deliveryLocation");
        this.data.getBasket();
    },
    render: function (event, basket) {
        //alert("render: " + Object.toJSON(basket));

        //var productTemplate = new Template("<div class=\"content_wrapper\"><div class=\"column_two\"><h2>#{Name}</h2><p>#{ShortDescription}</p></div><div class=\"content_column_right\"><div class=\"price_column\"><p>#{TotalPriceAsString}</p></div><div class=\"price_column\"><div class=\"quantity_float\"><p>#{Quantity}</p></div><div class=\"delete_float\"><a title=\"Delete Item\" href=\"./ShoppingBasket.aspx?delete=#{ProductID}\"><img alt=\"Delete Item\" src=\"images/delete_item.png\"></a></div></div></div><div class=\"clear\"></div></div>");
        var productTemplate = new Template("<div class=\"content_wrapper\"><div class=\"column_two\"><h2>#{Name}</h2><p>#{ShortDescription}</p></div><div class=\"content_column_right\"><div class=\"price_column\"><p>#{TotalPriceAsString}</p></div><div class=\"price_column\"><div class=\"quantity_float\"><select id=\"quantity_#{ProductID}\" name=\"quantity_#{ProductID}\" class=\"quantity\"><option>0</option><option>1</option><option>2</option><option>3</option><option>4</option><option>5</option><option>6</option><option>7</option><option>8</option><option>9</option><option>10</option></select></div></div></div><div class=\"clear\"></div></div>");

        // Hide products
        $j("#products").hide("blind");
        
        // Clear products
        var products = $("products");
        products.update();

        // Update products
        basket.BasketItems.each(function (item) {
            products.insert(productTemplate.evaluate(item));
        });

        // Set the drop-down to the correct quantity
        basket.BasketItems.each(function (item) {
            $("quantity_" + item.ProductID).setValue(item.Quantity);
        });

        // Free product template
        productTemplate = new Template("<div class=\"content_wrapper\"><div class=\"column_two\"><h2>#{Name}</h2><p>#{ShortDescription}</p></div><div class=\"content_column_right\"><div class=\"price_column\"><p>#{TotalPriceAsString}</p></div><div class=\"price_column\"><div class=\"quantity_float\"><p>#{Quantity}</p></div></div></div><div class=\"clear\"></div></div>");

        // Add free products
        basket.OfferProducts.each(function (item) {
            products.insert(productTemplate.evaluate(item));
        });

        // Display products
        $j("#products").show("blind");

        // Product total price
        $("productTotal").update("<p><strong>" + basket.TotalProductPriceAsString + "</strong></p>");

        // Offer details
        var offerDetails = $("offerDetails");
        offerDetails.hide();
        offerDetails.update();
        basket.Offers.each(function (item) {
            offerDetails.insert(item.Description + "<br/>");
        });
        offerDetails.show();

        // Update discounts
        $("discount").update("<p><strong>" + basket.DiscountAsString + "</strong></p>");

        // Update delivery
        $("delivery").update("<p><strong>" + basket.ShippingAsString + "</strong></p>");

        // Update total
        $("orderTotal").update("<p><strong>" + basket.TotalPriceAsString + "</strong></p>");

        // Update total items
        var items = "";
        if (basket.TotalItems == 1)
            items = " Item";
        else
            items = " Items";

        $("totalItems").update("<p>" + basket.TotalItems + items + "</p>");

        // Set up event handlers
        $j("select.quantity").change(this, function (event) {
            if (this.getValue() == 0) {
                // Confirm user wants to remove product
                $j("#dialog-confirm").data("Product", { "ID": this.id.substr(9), "Qty": this.getValue() }).dialog({
                    resizable: false,
                    height: 140,
                    modal: true,
                    buttons: {
                        "Delete product": function () {
                            // Delete product from basket
                            event.data.deleteProduct($j(this).data("Product").ID);
                            $j(this).dialog("close");
                        },
                        Cancel: function () {
                            // Reload the existing shopping basket
                            event.data.getBasket();
                            $j(this).dialog("close");
                        }
                    }
                });
            } else {
                // Update the product quantity
                event.data.updateProductQuantity(this.id.substr(9), this.getValue());
            }
        });

        // Update render
        $j("form").form();

    }
});

Controller.MiniBasket = Class.create({
    initialize: function (data) {
        this.data = data;
        //$j(this.data).bind("Basket:Updated", function (event, data) { alert("Basket Event: " + Object.toJSON(data)); });
        $j(this.data).bind("Basket:Updated", this.render);
    },
    render: function (event, basket) {
        var control = $j("#shopping_basket_contents");
        control.hide("highlight", null, null, function () {
            if (basket.BasketItems.length > 0) {
                control.html("<strong>" + basket.TotalItems + "</strong> Items - <strong>" + basket.TotalProductPriceAsString + "</strong>");
            } else {
                control.html("The shopping basket is empty.");
            }
            control.show("highlight");
        });
    }
});

Controller.Checkout = Class.create({
    initialize: function () {
        this.emailValidation = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
    },
    validatePersonalDetails: function () {
        var valid = true;
        var errorMsg = "<div><p>Please correct the following personal information:</p><ul>";

        if ($F("personal_title").blank()) {
            valid = false;
            $("personal_title").addClassName("ui-state-error");
            errorMsg += "<li>Please enter your title.</li>";
        } else {
            $("personal_title").removeClassName("ui-state-error");
        }
        if ($F("personal_firstname").blank()) {
            valid = false;
            $("personal_firstname").addClassName("ui-state-error");
            errorMsg += "<li>Please enter your first name.</li>";
        } else {
            $("personal_firstname").removeClassName("ui-state-error");
        }
        if ($F("personal_surname").blank()) {
            valid = false;
            $("personal_surname").addClassName("ui-state-error");
            errorMsg += "<li>Please enter your surname.</li>";
        } else {
            $("personal_surname").removeClassName("ui-state-error");
        }
        if ($F("personal_email").blank()) {
            valid = false;
            $("personal_email").addClassName("ui-state-error");
            errorMsg += "<li>Please enter your email address.</li>";
        } else if (!this.emailValidation.test($F("personal_email"))) {
            valid = false;
            $("personal_email").addClassName("ui-state-error");
            errorMsg += "<li>Please enter a valid email address.</li>";
        } else {
            $("personal_email").removeClassName("ui-state-error");
        }
        if ($F("personal_phone").blank()) {
            valid = false;
            $("personal_phone").addClassName("ui-state-error");
            errorMsg += "<li>Please enter your contact phone number.</li>";
        } else {
            $("personal_phone").removeClassName("ui-state-error");
        }
        if ($F("personal_address").blank()) {
            valid = false;
            $("personal_address").addClassName("ui-state-error");
            errorMsg += "<li>Please enter your address.</li>";
        } else {
            $("personal_address").removeClassName("ui-state-error");
        }
        if ($F("personal_postcode").blank()) {
            valid = false;
            $("personal_postcode").addClassName("ui-state-error");
            errorMsg += "<li>Please enter your postcode.</li>";
        } else {
            $("personal_postcode").removeClassName("ui-state-error");
        }

        if (!valid) {
            errorMsg += "</ul></div>";
            $j("#dialog").html(errorMsg).dialog("option", "title", "Personal Details Error").bind("dialogclose", this.focusFirstError).dialog("open");
        }

        return valid;
    },
    validateDeliveryDetails: function () {
        var valid = true;
        var errorMsg = "<div><p>Please correct the following delivery information:</p><ul>";

        if ($F("delivery_address").blank()) {
            valid = false;
            $("delivery_address").addClassName("ui-state-error");
            errorMsg += "<li>Please enter your title.</li>";
        } else {
            $("delivery_address").removeClassName("ui-state-error");
        }
        if ($F("delivery_postcode").blank()) {
            valid = false;
            $("delivery_postcode").addClassName("ui-state-error");
            errorMsg += "<li>Please enter your postcode.</li>";
        } else {
            $("delivery_postcode").removeClassName("ui-state-error");
        }

        if (!valid) {
            errorMsg += "</ul></div>";
            $j("#dialog").html(errorMsg).dialog("option", "title", "Delivery Details Error").bind("dialogclose", this.focusFirstError).dialog("open");
        }

        return valid;
    },
    updateDelivery: function () {
        if ($F("delivery_identical")) {
            $("delivery_address").value = $F("personal_address");
            $("delivery_postcode").value = $F("personal_postcode");
            $("delivery_country").value = $F("personal_country");

            $("delivery_address").disable();
            $("delivery_postcode").disable();
            $("delivery_country").disable();
        }
        else {
            $("delivery_address").enable();
            $("delivery_postcode").enable();
            $("delivery_country").enable();
        }
    },
    convertToPayPalForm: function (order) {
        var form = $("aspnetForm");
        form.action = "https://www.paypal.com/cgi-bin/webscr";

        // Remove obsolete form content
        form.select("#personal_details", "#delivery_details", "#payment_details").each(function (element) {
            element.remove();
        });

        // Add PayPal specific input
        var e = new Element("input", { "type": "text", "name": "cmd", "value": "_xclick" });
        form.insert(e);
        e = new Element("input", { "type": "text", "name": "business", "value": "ebay@cobb-bbq.co.uk" });
        form.insert(e);
        e = new Element("input", { "type": "text", "name": "charset", "value": "utf-8" });
        form.insert(e);
        e = new Element("input", { "type": "text", "name": "return", "value": "http://" + window.location.host + "/thankyou.aspx" });
        form.insert(e);
        e = new Element("input", { "type": "text", "name": "currency_code", "value": "GBP" });
        form.insert(e);
        e = new Element("input", { "type": "text", "name": "invoice", "value": order.ID });
        form.insert(e);
        e = new Element("input", { "type": "text", "name": "item_name", "value": "Cobb (GB) Ltd. - Order No: " + order.ID });
        form.insert(e);
        e = new Element("input", { "type": "text", "name": "quantity", "value": "1" });
        form.insert(e);
        e = new Element("input", { "type": "text", "name": "amount", "value": order.Total });
        form.insert(e);
        e = new Element("input", { "type": "text", "name": "shipping", "value": order.Basket.Shipping });
        form.insert(e);
        e = new Element("input", { "type": "text", "name": "no_shipping", "value": "1" });
        form.insert(e);
        e = new Element("input", { "type": "text", "name": "no_note", "value": "1" });
        form.insert(e);
        e = new Element("input", { "type": "text", "name": "cbt", "value": "Cobb" });
        form.insert(e);
        e = new Element("input", { "type": "text", "name": "cancel_return", "value": "http://" + window.location.host + "/cancelled.aspx" });
        form.insert(e);
        // Personal information
        e = new Element("input", { "type": "text", "name": "email", "value": order.Customer.EmailAddress });
        form.insert(e);
        e = new Element("input", { "type": "text", "name": "first_name", "value": order.Customer.Forename.truncate(32) });
        form.insert(e);
        e = new Element("input", { "type": "text", "name": "last_name", "value": order.Customer.Surname.truncate(64) });
        form.insert(e);

        e = new Element("input", { "type": "text", "name": "address1", "value": order.PaymentAddress.AddressLine1.truncate(100) });
        form.insert(e);
        e = new Element("input", { "type": "text", "name": "address2", "value": order.PaymentAddress.AddressLine2.truncate(100) });
        form.insert(e);
        e = new Element("input", { "type": "text", "name": "city", "value": order.PaymentAddress.City.truncate(100) });
        form.insert(e);
        e = new Element("input", { "type": "text", "name": "zip", "value": order.PaymentAddress.Postcode });
        form.insert(e);
        e = new Element("input", { "type": "text", "name": "country", "value": order.PaymentAddress.CountryAlpha2 });
        form.insert(e);

        e = new Element("input", { "type": "text", "name": "json", "value": Object.toJSON(order) });
        form.insert(e);

        // Submit form to PayPal
        form.submit();
    },
    convertToEPDQForm: function (order) {
        var form = $("aspnetForm");
        form.action = "https://secure2.epdq.co.uk/cgi-bin/CcxBarclaysEpdq.e";

        // Remove obsolete form content
        form.select("#personal_details", "#delivery_details", "#payment_details").each(function (element) {
            element.remove();
        });

        // Add ePDQ specific input
        var e = new Element("input", { "type": "text", "name": "returnurl", "value": "http://" + window.location.host + "/thankyou.aspx" });
        form.insert(e);
        e = new Element("input", { "type": "text", "name": "merchantdisplayname", "value": "Cobb (GB) Limited" });
        form.insert(e);
        // ePDQ secure content
        form.insert(order.ePDQForm);
        // Payment details
        e = new Element("input", { "type": "text", "name": "email", "value": order.Customer.EmailAddress.truncate(64) });
        form.insert(e);
        e = new Element("input", { "type": "text", "name": "baddr1", "value": order.PaymentAddress.AddressLine1.truncate(60) });
        form.insert(e);
        e = new Element("input", { "type": "text", "name": "baddr2", "value": order.PaymentAddress.AddressLine2.truncate(60) });
        form.insert(e);
        e = new Element("input", { "type": "text", "name": "bcity", "value": order.PaymentAddress.City.truncate(25) });
        form.insert(e);
        e = new Element("input", { "type": "text", "name": "bpostalcode", "value": order.PaymentAddress.Postcode });
        form.insert(e);
        e = new Element("input", { "type": "text", "name": "bcountry", "value": order.PaymentAddress.CountryCode });
        form.insert(e);

        // Delivery details
        e = new Element("input", { "type": "text", "name": "saddr1", "value": order.DeliveryAddress.AddressLine1.truncate(60) });
        form.insert(e);
        e = new Element("input", { "type": "text", "name": "saddr2", "value": order.DeliveryAddress.AddressLine2.truncate(60) });
        form.insert(e);
        e = new Element("input", { "type": "text", "name": "scity", "value": order.DeliveryAddress.City.truncate(25) });
        form.insert(e);
        e = new Element("input", { "type": "text", "name": "spostalcode", "value": order.DeliveryAddress.Postcode });
        form.insert(e);
        e = new Element("input", { "type": "text", "name": "scountry", "value": order.DeliveryAddress.CountryCode });
        form.insert(e);

        e = new Element("input", { "type": "text", "name": "cpi_textcolor", "value": "#666666" });
        form.insert(e);
        e = new Element("input", { "type": "text", "name": "json", "value": Object.toJSON(order) });
        form.insert(e);

        // Submit form to PayPal
        form.submit();
    },
    focusFirstError: function (event) {
        // Focus on first error element
        $j(".ui-state-error")[0].focus();
        // Remove close dialog event handler
        $j("#dialog").dialog().unbind("dialogclose", this.focusFirstError);
    }
});

/*
    View
*/
View.Generic = Class.create({
    initialize: function (basketId) {
        $j(document).ready(function () {
            var data = new Model.Basket(basketId);
            var miniBasket = new Controller.MiniBasket(data);
            data.getBasket();

            // format the form elements
            $j("form").form();
        });
    }
});

View.Basket = Class.create({
    initialize: function (basketId) {
        Event.observe(window, 'load', function () {
            var data = new Model.Basket(basketId);
            var ui = new Controller.Basket(data);
            var miniBasket = new Controller.MiniBasket(data);

            // Set the order details previously set
            $("orderCode").value = getCookie("orderCode");
            if (getCookie("deliveryLocation").length > 0) $("deliveryLocation").value = getCookie("deliveryLocation");

            // Update the basket
            ui.refresh(getCookie("orderCode"), $("deliveryLocation").value);

//            $("orderCode").observe("keyup", function (event) {
//                setCookie("orderCode", this.value, null);
//                ui.refresh(this.value, $F("deliveryLocation"));
//            });

            $("orderCodeUpdate").observe("click", function (event) {
                setCookie("orderCode", $("orderCode").value, null);
                ui.refresh($("orderCode").value, $F("deliveryLocation"));
                $j(event).preventDefault();
            });

            $("deliveryLocation").observe("change", function (event) {
                setCookie("deliveryLocation", this.value, null);
                ui.refresh($F("orderCode"), this.value);
            });

            $j("#products_clear").click(function (event) {
                data.clearBasket();
                event.preventDefault();
            });

            // format the form elements
            $j("form").form();

            $j("#orderCodeUpdate").button({
                icons: {
                    primary: "ui-icon-arrowrefresh-1-e"
                },
                text: false
            }).css({
                width: "18px",
                height: "18px"
            });

            $j("#products_clear").button({
                icons: {
                    primary: "ui-icon-trash"
                }
            }).css({color:"white"});

            $j("#checkout").button({
                icons: {
                    primary: "ui-icon-cart"
                }
            }).css({ color: "white" }).addClass("ui-priority-primary");
        });
    }
});

View.Products = Class.create({
    initialize: function (basketId) {
        $j(document).ready(function () {
            var data = new Model.Basket(basketId);
            var miniBasket = new Controller.MiniBasket(data);
            data.getBasket();

            $j(".more_link").click(function () {
                for (var i = 0; i < products.length; i++) {
                    if ((products[i].ProductID == this.title) && (products[i].Description != null)) {
                        // log event
                        _gaq.push(['_trackEvent', 'Products', 'More Link', products[i].Name]);
                        // open dialog box
                        $j.fancybox({
                            "content": "<div id=\"more_link\">" + products[i].Description + "</div>",
                            "title": products[i].Name
                        },
                        {
                            "hideOnOverlayClick": false,
                            "hideOnContentClick": false,
                            "showCloseButton": true,
                            "enableEscapeButton": true
                        });
                    }
                }
            });

            $j("img.product_image, span.product_image_zoom").click(function () {
                // generate productid from id of image
                var productId = this.id.substring(6);
                // retrieve images associated with product
                $j.ajax({
                    type: "GET",
                    url: "Data/JSON/GetProductImages.ashx?productID=" + encodeURIComponent(productId),
                    dataType: "json",
                    success: function (data, status) {
                        if (data.length > 0) {
                            // log event
                            _gaq.push(['_trackEvent', 'Products', 'Images', productId]);
                            // prefix href with image location
                            for (var i = 0; i < data.length; i++) {
                                if (!data[i].href.startsWith("http"))
                                    data[i].href = "images/products/" + data[i].href;
                            }
                            // display images
                            $j.fancybox(data);
                        }
                    }
                });
            });

            $j("div.price_column select").change(function (event) {
                // generate productid from id of quantity field
                var productId = this.id.substring(9);

                var product = $j.grep(products, function (n, i) {
                    return (n.ProductID == productId);
                });

                if (product.length == 1 && $j(this).val() > 0) {
                    if (!product[0].AvailableStock) {
                        $j(this).val(0);
                        productAvailabilityAlert(product[0]);
                    }

                    if (product[0].SubProducts != null) {
                        var subProductId = $j("#group_" + productId).val();

                        var subProduct = $j.grep(product[0].SubProducts, function (n, i) {
                            return (n.ProductID == subProductId);
                        });

                        if (subProduct.length == 1) {
                            if (!subProduct[0].AvailableStock) {
                                $j(this).val(0);
                                productAvailabilityAlert(subProduct[0]);
                            }
                        }
                    }
                }
            });

            $j("div.content_column_mid select").change(function () {
                var productId = this.id.substring(6);

                $j("#quantity_" + productId).val(0);
            });

            $j(".add_link").button({
                icons: {
                    primary: "ui-icon-plus"
                },
                text: true
            }).click(function (event) {
                // Prevent default post
                event.preventDefault();

                var productId = this.id.substr(4);
                var qty = $j("#quantity_" + productId).val();

                // Add product to basket if quantity specified
                if (qty > 0) {
                    // Identify if product is a group
                    var subProductId = $j("#group_" + productId).val();

                    // Add product
                    if (subProductId)
                        data.addToBasket(subProductId, qty);
                    else
                        data.addToBasket(productId, qty);
                }
            });

            // format the form elements
            $j("form").form();

            $j("#products_basket").button({
                icons: {
                    primary: "ui-icon-cart"
                }
            }).css({ color: "white" });
        });

        function productAvailabilityAlert(product) {
            $j.fancybox({
                "content": "<p>Temporarily out of stock until approx. " + product.AvailableDateAsString + "</p>",
                "title": product.Name
            },
            {
                "hideOnOverlayClick": false,
                "hideOnContentClick": false,
                "showCloseButton": true,
                "enableEscapeButton": true
            });
        }
    }
});

View.MediaVideos = Class.create({
    initialize: function (basketId) {
        $j(document).ready(function () {
            var data = new Model.Basket(basketId);
            var miniBasket = new Controller.MiniBasket(data);
            data.getBasket();

            var params = {
                allowFullScreen: "true",
                allowscriptaccess: "always"
            };
            swfobject.embedSWF("http://www.youtube.com/p/8B8DC1B4C68F372B&amp;hl=en_GB&amp;fs=1&amp;color1=dfefe2&amp;color2=dfefe2", "video", "480", "385", "10.0.22", false, {}, params);
        });
    }
});

View.MediaImages = Class.create({
    initialize: function (basketId) {
        $j(document).ready(function () {
            var data = new Model.Basket(basketId);
            var miniBasket = new Controller.MiniBasket(data);
            data.getBasket();

            var flashvars = {
                host: "picasaweb.google.co.uk",
                captions: "1",
                hl: "en_US",
                feat: "flashalbum",
                RGB: "0xdfefe2",
                feed: "http%3A%2F%2Fpicasaweb.google.co.uk%2Fdata%2Ffeed%2Fapi%2Fuser%2F115884158434194202892%2Falbumid%2F5469352611701707841%3Falt%3Drss%26kind%3Dphoto%26authkey%3DGv1sRgCIiXr_THjbmuTQ%26hl%3Den_US"
            };
            swfobject.embedSWF("http://picasaweb.google.co.uk/s/c/bin/slideshow.swf", "slideshow", "800", "533", "10.0.22", false, flashvars);
        });
    }
});

View.Checkout = Class.create({
    initialize: function (basketId) {
        $j(document).ready(function () {
            var data = new Model.Basket(basketId);
            var miniBasket = new Controller.MiniBasket(data);
            data.getBasket();

            var ui = new Controller.Checkout();

            // Setup dialog box
            $j("#dialog").dialog({ autoOpen: false, show: "scale", hide: "scale", modal: true });

            // Setup navigation
            var validationOverride = false;
            var offlineOrder = (document.domain == "offline.cobb-bbq.co.uk" || document.domain == "localhost");

            $j("#personal_next").click(function (event) {
                if (validationOverride || ui.validatePersonalDetails()) {
                    $j("#personal_details").hide("slide", null, null, function () {
                        $j("#delivery_details").show("slide");
                        ui.updateDelivery();
                        // Track page change
                        _gaq.push(['_trackPageview', '/Checkout_Delivery.aspx']);
                    });
                }
                event.preventDefault();
            });

            $j("#delivery_previous").click(function (event) {
                if (validationOverride || ui.validateDeliveryDetails()) {
                    $j("#delivery_details").hide("slide", null, null, function () {
                        $j("#personal_details").show("slide");
                        // Track page change
                        _gaq.push(['_trackPageview', '/Checkout.aspx']);
                    });
                }
                event.preventDefault();
            });

            $j("#delivery_next").click(function (event) {
                if (validationOverride || ui.validateDeliveryDetails()) {
                    $j("#delivery_details").hide("slide", null, null, function () {
                        $j("#payment_details").show("slide");
                        // Track page change
                        _gaq.push(['_trackPageview', '/Checkout_Payment.aspx']);
                    });
                }
                event.preventDefault();
            });

            $j("#payment_previous").click(function (event) {
                $j("#payment_details").hide("slide", null, null, function () {
                    $j("#delivery_details").show("slide");
                    // Track page change
                    _gaq.push(['_trackPageview', '/Checkout_Delivery.aspx']);
                });
                event.preventDefault();
            });

            $j("#payment_next").click(function (event) {
                $j("#payment_details").hide("slide", null, null, function () {
                    $j("#dialog").html("Please wait while order is processed.").dialog("option", "title", "Please wait...").dialog("open");
                    $("aspnetForm").request({
                        parameters: { checkout: "_convert" },
                        evalJSON: "force",
                        onSuccess: function (response) {
                            // Return success message to client
                            $j("#dialog").dialog("option", "title", "Complete").html("Order saved!");
                            // Track page change
                            _gaq.push(['_trackPageview', '/Checkout_Complete.aspx']);
                            // Convert the form into gateway required post
                            var order = response.responseJSON;
                            // Offline orders don't transfer for payment
                            if (offlineOrder) {
                                $j("#dialog").html("Order No: " + order.ID);
                            } else {
                                if (order.PaymentMethod == "PayPal")
                                    ui.convertToPayPalForm(order);
                                else
                                    ui.convertToEPDQForm(order);
                            }
                        },
                        onFailure: function (response) {
                            $j("#dialog").dialog("option", "title", "Complete").html("Order failed!");
                        }
                    });
                });

                event.preventDefault();
            });

            // Personal details
            $j("#personal_origin").keypress(function () {
                return (this.value.length < 255);
            });

            // Delivery details
            $j("#delivery_identical").click(function (event) {
                ui.updateDelivery();
            });

            $j("#delivery_different").click(function (event) {
                ui.updateDelivery();
            });

            // format the form elements
            $j("form").form();

            // personal details step
            $j("#personal_next").button({
                icons: {
                    secondary: "ui-icon-carat-1-e"
                }
            })

            // delivery details step
            $j("#delivery_options").buttonset();

            $j("#delivery_next").button({
                icons: {
                    secondary: "ui-icon-carat-1-e"
                }
            })

            $j("#delivery_previous").button({
                icons: {
                    primary: "ui-icon-carat-1-w"
                }
            })

            // payment details step
            if (offlineOrder) {
                $j("#payment_options > label").filter(":odd").removeAttr("style");
                $j("#payment_options").append(
                    $j("<label/>").append($j("<input/>").attr({ "id": "payment_cheque", "name": "payment_option", "type": "radio", "value": "cheque" })),
                    $j("<label>").attr({ "for": "payment_cheque" }).text("Cheque"),
                    $j("<label/>").append($j("<input/>").attr({ "id": "payment_cash", "name": "payment_option", "type": "radio", "value": "cash" })),
                    $j("<label>").attr({ "for": "payment_cash" }).text("Cash"),
                    $j("<label/>").append($j("<input/>").attr({ "id": "payment_mepos", "name": "payment_option", "type": "radio", "value": "mepos" })),
                    $j("<label>").attr({ "for": "payment_mepos" }).text("MEPOS")
                );

                $j("#payment_card_logo, #payment_paypal_logo").hide();
            }

            $j("#payment_options").buttonset();

            $j("#payment_next").button({
                icons: {
                    secondary: "ui-icon-carat-1-e"
                }
            })

            $j("#payment_previous").button({
                icons: {
                    primary: "ui-icon-carat-1-w"
                }
            })
        });
    }
});

// Form formatting widget
$j.widget("ui.form", {
    _init: function () {
        var object = this;
        var form = this.element;
        var inputs = form.find("input, select, textarea, button");

        $j.each(inputs, function () {
//            $j(this).addClass('ui-widget ui-state-default ui-corner-all');
//            $j(this).wrap("<label />");

            if ($j(this).is(":reset ,:submit"))
                object.buttons(this);
            else if ($j(this).is(":checkbox"))
                object.checkboxes(this);
            else if ($j(this).is("input[type='text']") || $j(this).is("textarea") || $j(this).is("input[type='password']"))
                object.textelements(this);
            else if ($j(this).is(":radio"))
                object.radio(this);
            else if ($j(this).is("select"))
                object.selector(this);

            if ($j(this).hasClass("date"))
                $j(this).datepicker();
        });
    },

    textelements: function (element) {
        $j(element).addClass('ui-widget ui-state-default ui-corner-all');
        $j(element).wrap("<label />");

        $j(element).bind({
            focusin: function () {
                $j(this).toggleClass('ui-state-focus');
            },
            focusout: function () {
                $j(this).toggleClass('ui-state-focus');
            }
        });
    },

    buttons: function (element) {
        $j(element).button();
    },

    checkboxes: function (element) {
        $j(element).parent("label").after("<span />");
        var parent = $j(element).parent("label").next();
        $j(element).addClass("ui-helper-hidden");
        parent.css({ width: 16, height: 16, display: "block" });
        parent.wrap("<span class='ui-state-default ui-corner-all' style='display:inline-block;width:16px;height:16px;margin-right:5px;'/>");
        parent.parent().addClass('hover');
        parent.parent("span").click(function (event) {
            $j(this).toggleClass("ui-state-active");
            parent.toggleClass("ui-icon ui-icon-check");
            $j(element).click();
        });
    },

    radio: function (element) {
        //        $j(element).parent("label").after("<span />");
        //        var parent = $j(element).parent("label").next();
        //        $j(element).addClass("ui-helper-hidden");
        //        parent.addClass("ui-icon ui-icon-radio-off");
        //        parent.wrap("<span class='ui-state-default ui-corner-all' style='display:inline-block;width:16px;height:16px;margin-right:5px;'/>");
        //        parent.parent().addClass('hover');
        //        parent.parent("span").click(function (event) {
        //            $j(this).toggleClass("ui-state-active");
        //            parent.toggleClass("ui-icon-radio-off ui-icon-bullet");
        //            $j(element).click();
        //        });
    },

    selector: function (element) {
        $j(element).addClass('ui-widget ui-state-default ui-corner-all');
        $j(element).wrap("<label />");
    }
});

