/*  CCL JS 
    Author : Andrew Scott (Companion Computers Limited [www.compan.net]) */

CCLApp = {
    common: {
        init: function () {

            // attach to the AJAX onload event
            if (!this.initialized && typeof Sys != "undefined") { Sys.WebForms.PageRequestManager.getInstance().add_endRequest(function () { UTIL.init(); }); this.initPageLoad(); }
            this.initialized = true;
            this.showPopups();

            //            $(".date").datepicker({dateFormat:"dd/mm/yy"});
            //            $(".date-post").datepicker({dateFormat:"dd/mm/yy", minDate:"-3M", maxDate:"0D"});

            // Disable non numeric / control key on money inputs
            $(".mny").keydown(function (evt) {
                if ($.inArray(evt.keyCode, UTIL.numKeys) != -1 ||
                    $.inArray(evt.keyCode, UTIL.ctrlKeys) != -1) { return true; }
                return false;
            });
            // automatically select the value in a money field - highlights the text in the textbox
            $(".mny").focus(function () { var self = this; setTimeout(function () { self.select(); }, 100); });
            // Fill empty money fields
            $(".mny").blur(function () { if ($(this).val() == "") { $(this).val("0.00"); } });

            $("#featured > ul").tabs({ fx: { opacity: "toggle"} }).tabs("rotate", 5000, true);

            if (typeof cWorldPayForm != "undefined" && cWorldPayForm == "yes") {
                if (window.navigator.appName.toLowerCase().indexOf("microsoft") > -1) {
                    theform = document.form1;
                }
                else {
                    theform = document.forms["form1"];
                }
                theform.action = "https://secure.worldpay.com/wcc/purchase";
                //                    theform.action = "https://select-test.wp3.rbsworldpay.com/wcc/purchase";
                theform.submit();
            }

            $("#searchbox input[type=text]").keydown(function (e) {
                if (e.keyCode == 13) {
                    //e.preventDefault = true;
                    $("#searchbox input[type=submit]").click();
                    return false;
                }
            });

        },
        initialized: false,
        initPageLoad: function () {
           /* if ($("iframe").length > 0) { return; }
            setTimeout(CCLApp.ecommerce.updateHeaderBasket, 500);*/
        },
        showPopups: function () {
            this.getPopupBG();
            this.hidePopupBG();
            if ($(".popup").length != 0) {
                this.showPopupBG();
                var top = (Math.floor((($("body").height() / 2) - ($(".popup").height() / 2)) / 60) * 60); // Rounds to the nearest 60px
                if (top <= 10) { top = 10; }


                $(".popup").css({
                    display: "block",
                    left: ($("body").width() / 2) - ($(".popup").width() / 2) + "px",  					// Assumes the popup conforms to the 960 factors
                    top: top + "px",
                    zIndex: 99000
                });


            }
        },
        elPopupBG: null,
        getPopupBG: function () {
            if (this.elPopupBG == null) {
                this.elPopupBG = $(".popupbg");
            }
        },
        showPopupBG: function () {
            this.elPopupBG.css({
                display: "block",
                height: $(document).height() + "px"
            });

            this.elPopupBG.unbind().click(function () {
                $(".ui_mechs input[type=submit][value=closePopup]").click();
            });

        },
        hidePopupBG: function () {
            this.elPopupBG.css({
                display: "none"
            });
        }
    },

    ecommerce: {

        hStoreTimeout: null,
        nStoreTimeout: 1.5, // No of Seconds before Address is stored

        init: function () {
            // controller-wide code
            $("p.addressError").hide();
        },

        initAddresses: function () {
            this.initRadiobuttons();
            this.initRequired();
            this.initAutoStoreAddress();
        },

        initRequired: function () {
            var self = this;

            $("tr.required").each(function (i, elRef) {
                self.bindrequired(elRef);
            });

        },

        initRadiobuttons: function () {
            $("table.radio input").unbind().change(function () {
                if ($("table.radio input[value=\"delivery\"]").is(":checked")) {
                    $("tbody.deliveryaddress").show("fast");
                }
                else {
                    $("tbody.deliveryaddress").hide("fast");
                }
            });
        },

        initAutoStoreAddress: function () {
            var self = this;
            $("tr input[type=text]").keyup(function () {
                self.setStoreTimeout();
            });
        },

        bindrequired: function (elRef) {

            var self = this;
            var oRow = $(elRef);

            if (oRow.find("input ~ img").length > 0) { return; }

            var oInput = oRow.find("input");

            oInput.after("<img src=\"/images/cross.gif\" class=\"cross\" />");
            oInput.after("<img src=\"/images/tick.gif\" class=\"tick\" />");

            $("<span class=\"required\">*</span>").appendTo(oRow.find("td.legend"));

            oInput.unbind().blur(function () {
                self.checkRequired($(this), oRow, false);
            });

            this.checkRequired(oInput, oRow, true);
        },

        checkRequired: function (oInput, oRow, lSetup) {
            var oSpanRequired = oRow.find("span.required");
            var oTick = oRow.find("img.tick");
            var oCross = oRow.find("img.cross");

            if (oSpanRequired.length > 0) { oSpanRequired.hide(); }
            if (oTick.length > 0) { oTick.hide(); }
            if (oCross.length > 0) { oCross.hide(); }

            if (oInput.val().length > 0) {
                oTick.show();
            } else {
                oSpanRequired.show();
                if (!lSetup) { oCross.show(); }
            }
        },

        updateHeaderBasket: function () {
            $("#shoppingcartstatus input[type=submit]").click();
        },

        showMessage: function () {
            var msg = $("#hErrorMessage").val();
            if (msg == "") { return; }
            alert(msg);
        },

        updateshoppingbasket: function () {
            var cStatus = $(".statustext").val()
            $(".shoppingitems").text(cStatus);
        },

        showdelivery: function () {
            $("tbody.deliveryaddress").show();
            $("table.radio input[value=\"delivery\"]").attr("checked", "checked");
        },

        addressError: function () {
            $("p.addressError").show();
        },

        bindStoreAddress: function (elRef) {
            var self = this;
            $(elRef).unbind().blur(function (e) {
                self.setStoreTimeout();
            });
        },
        setStoreTimeout: function () {
            clearTimeout(this.hStoreTimeout);
            this.hStoreTimeout = setTimeout(this.storeAddress, this.nStoreTimeout * 1000);
        },
        storeAddress: function () {
            $("input[type=submit][value=StoreAddress]").click();
        }

    },
    products: {
        openZoomPopup: function () {
            $("input[type=submit].openZoom").click();
        }
    }

}

        

UTIL = {
    exec: function (controller, action, popupaction) {
        var ns = CCLApp;
        action = (action === undefined) ? "init" : action;
        popupaction = (popupaction === undefined) ? "popupinit" : popupaction;
    
        if (controller !== "" && ns[controller] && typeof ns[controller][action] == "function") {
            ns[controller][action]();
        }
        if (controller !== "" && ns[controller] && typeof ns[controller][popupaction] == "function") {
            ns[controller][popupaction]();
        }
    },

    init: function () {
        var body = document.body,
        controller = body.getAttribute("data-controller"),
        action = body.getAttribute("data-action");

        UTIL.exec("common");
        UTIL.exec(controller);
        UTIL.exec(controller, action);

        // Local AJAX updates
        $(".ui_mechs").each(function(i, el){

            // or could have done this :- var jqInst = $(el);

            var ctrl = el.getAttribute("data-controller"),
            actn = el.getAttribute("data-action");
            popactn = el.getAttribute("data-popupaction");
            
            // Unset the values
            el.setAttribute("data-action", "");
            el.setAttribute("data-controller", "");
            el.setAttribute("data-popupaction", "");

            // exec the init of the controller, if not already been done
            if( ctrl != "" && ctrl != controller ){ UTIL.exec(ctrl); }

            // exec the actn of the controller
            UTIL.exec(ctrl, actn, popactn);
 
        })
        
    }, 
    
    setDisabled:function(elRef){
        elRef.attr("disabled", "disabled" );
        elRef.addClass("ro");
    },
    setEnabled:function(elRef){
        elRef.attr("disabled", "" );
        elRef.removeClass("ro");
    },
    numKeys:[
        48,49,50,51,52,53,54,55,56,57,      // Numerics
        96,97,98,99,100,101,102,103,104,105,
        110, 190 // (.)
    ],
    ctrlKeys:[
        37,38,39,40,        // cursor
        27,                 // escape
        8,                  // backspace
        9,                  // tab
        46                  // del
    ]
};

// Defines
window["SOME_TYPE"] = 1001;

$(document).ready(UTIL.init);


