//var ActiveCommerce = {};

// safely establish namespaces...
if (typeof ActiveCommerce == 'undefined')
	ActiveCommerce = {};

if (typeof ActiveCommerce.Config == 'undefined')
	ActiveCommerce.Config = {};

if (typeof ActiveCommerce.Config.Global == 'undefined')
	ActiveCommerce.Config.Global = {};

ActiveCommerce.Global = {
    config: {},

    reValidate: false,

    init: function () {
        with (ActiveCommerce.Global) {

            // init display states 
            if (jQuery(".hide").length) {
                jQuery(".hide").each(function () {
                    jQuery(this).hide();
                    jQuery(this).removeClass('hide');
                });
            }
            // focus/blur form fields
            jQuery(document).delegate('input.has-default', 'focusin focusout', function (e) {
                if (e.type == 'focusin') {
                    if (this.value == this.defaultValue) { this.value = ""; }
                } else {
                    if (!this.value.length) { this.value = this.defaultValue; }
                }
            });

            // form button hover
            jQuery(document).delegate('input.bttn, input.bttn-sm', 'hover', function (e) {
                jQuery(this).toggleClass("hover");
            });

            // enable dropdown menus 
            if (jQuery('a.dropdown').length) {

                jQuery('a.dropdown').each(function () {
                    var dropdown = jQuery(this).parent().find('div.dropdown-menu');

                    // look for a submenu
                    var hasSubmenu = false;
                    if (dropdown.find('ul.submenu').length > 0) {
                        hasSubmenu = true;
                        dropdown.find('ul.buttons a').hover(function () {
                            showDropDownSubmenu(dropdown, this);
                        });
                    }

                    var trigger = jQuery(this);

                    trigger.hover(function () {
                        // when over the products nav button clear hide timeout  
                        clearTimeout(trigger.data('hideMenuTimeout'));
                        showDropDown(dropdown, trigger, hasSubmenu);
                    }, function () {
                        // on rollout clear any existing timeouts and set new hide timeout
                        clearTimeout(trigger.data('hideMenuTimeout'));
                        var hideMenuTimeout = setTimeout(function () { hideDropDown(dropdown); }, 400);
                        trigger.data('hideMenuTimeout', hideMenuTimeout);
                    });
                });
            }

            // enable add to cart button(s) 
            // add to cart url + productId is stored in the rel of the link... 
            if (jQuery("#btn-add-to-cart a").length) {
                jQuery('#btn-add-to-cart').delegate('a', 'click', function (e) { onFormSubmit(e) });
            }

            // options 
            if (jQuery("div.purchase-options").length) {
                var options = jQuery('div.purchase-options');
                options.delegate('select', 'change', function (e) { if (reValidate) { validateForm(e); } });
                options.delegate('select', 'change', changeOption);
            }

            // standard accordion menu 
            if (jQuery("div.content-accordion").length) {
                jQuery("div.content-accordion div.accordion").accordion({
                    collapsible: true,
                    active: false,
                    autoHeight: false
                });
            }

            // standard photo gallery 
            jQuery('div.content-photo-gallery').each(function () {
                var $gallery = jQuery(this);

                // set all current slide numbers 
                var current_slide = 1;
                $gallery.find('div.caption-nav span.current-slide').each(function () {
                    jQuery(this).html(current_slide);
                    current_slide++;
                });
                // set all total slide numbers
                var total_slides = $gallery.find('div.photo-gallery img').length;
                $gallery.find('div.caption-nav span.total-slides').each(function () {
                    jQuery(this).html(total_slides);
                });

                $gallery.find('div.photo-gallery').nivoSlider({
                    effect: 'fade', // Specify sets like: 'fold,fade,sliceDown'
                    animSpeed: 250, // Slide transition speed
                    pauseTime: 5000, // How long each slide will show
                    directionNav: true, // Next & Prev navigation
                    directionNavHide: true, // Only show on hover
                    controlNav: true, // 1,2,3... navigation
                    controlNavThumbs: false, // Use thumbnails for Control Nav
                    keyboardNav: false, // Use left & right arrows
                    manualAdvance: true, // Force manual transitions
                    captionOpacity: 1 // Universal caption opacity
                });
            });

            if (jQuery('div.content-tabs').length) {
                jQuery('div.content-tabs').tabs({
                    fx: { opacity: 'toggle', duration: 'fast' },
                    cookie: { expires: 1} // Remember selected tab (for a day?)
                });
            }

            // Keypress for input fields (Form submit)
            jQuery('#mainform').bind('keypress', function (e) {
                var key = e.charCode || e.keyCode || e.which || 0,
					target = e.target.tagName.toLowerCase();

                if (key == 13 /* Enter */ && target == 'input') {
                    var $submit = jQuery(e.target).closest('.form').find('input.submit');
                    if ($submit.length > 0) {
                        e.preventDefault();
                        $submit.click();
                    }
                }
            });

            // Search box
            jQuery('#search-box')
                .next('input.submit')
                .click(function (e) {
                    e.preventDefault();
                    search();
                });
        }
    },

    /* 
    ** showDropDown()
    ** menuId : String identifies the menu ID
    ** trigger : Object that triggered the call
    */
    showDropDown: function (dropdown, trigger, hasSubMenu) {

        if (hasSubMenu) {
            var activeState;
            // if there is an active button  
            if (dropdown.find('a.active').length > 0) {
                activeState = dropdown.find('a.active');
            } else {
                activeState = null;
            }
            // show initial active state 
            ActiveCommerce.Global.showDropDownSubmenu(dropdown, activeState);
        }

        // show menu and set rollovers for dropdown menu 
        dropdown.slideDown("fast", function () {
            dropdown.hover(function () {
                clearTimeout(trigger.data('hideMenuTimeout'));
            }, function () {
                clearTimeout(trigger.data('hideMenuTimeout'));
                var hideMenuTimeout = setTimeout(function () { ActiveCommerce.Global.hideDropDown(dropdown); }, 400);
                trigger.data('hideMenuTimeout', hideMenuTimeout);
            });
        });
    },

    /* 
    ** hideDropDown()
    ** menuId : String identifies the menu ID
    */
    hideDropDown: function (dropdown) {
        dropdown.slideUp('fast');
    },

    /* 
    ** showDropDownSubmenu()
    ** menuId : String identifies the menu ID
    ** trigger : Object that triggered the call
    */
    showDropDownSubmenu: function (dropdown, activeState) {

        // clear any active buttons 
        dropdown.find('ul.buttons a').each(function () {
            jQuery(this).removeClass("active");
        });

        if (activeState == null) {
            // set to collapsed state
            dropdown.animate({ 'width': '155px' }, 0);
        } else {
            // check to see if collapsed
            if (dropdown.width() < 400) {
                dropdown.animate({ 'width': '468px' }, 150);
            }
            // activate current button 
            var trigger = jQuery(activeState);
            trigger.addClass("active");
            // hide all submenus			
            dropdown.find('.col ul.submenu').each(function () { jQuery(this).hide(); });
            var index = trigger.parent().index() + 1;
            dropdown.find('.col ul.submenu:nth-child(' + index + ')').show();

        }
    },

    onFormSubmit: function (e) {
        e.preventDefault();

        if (ActiveCommerce.Global.validateForm(e)) {
            var url = jQuery(e.currentTarget).attr('rel');
            ActiveCommerce.Global.addProductToCart(url);
            var analyticsProduct = jQuery(e.currentTarget).attr('data-analytics-id');
            var analyticsCategory = jQuery(e.currentTarget).attr('data-analytics-category');
            ActiveCommerce.Global.Analytics.productAddedToCart(analyticsCategory, analyticsProduct);

        } else {
            alert("Please select an option");
        }
        return false;
    },


    validateForm: function (e) {

        // indicates form has been validated atleast once already  
        ActiveCommerce.Global.reValidate = true;

        // find validation group 
        var group = jQuery('div.purchase-options');
        var isValid = true;

        // loop through and validate each element 
        group.find('input,select,textfield').each(function (i, item) {
            var itm = jQuery(item);
            if (!itm.hasClass('novalidate') && !itm.valid())
                isValid = false;
        });

        return isValid;

    },

    changeOption: function (e) {
        var option = jQuery('div.purchase-options select option:selected');
        var addToCart = jQuery('#btn-add-to-cart a');
        var path = '/cart/addtocart/';
        path += option.val();
        addToCart.attr('rel', path);
    },


    /* 
    ** addProductToCart()
    ** addToCartUrl : String identifies the add to cart url for this product
    */

    addProductToCart: function (addToCartUrl) {
        jQuery('#added-to-cart').fadeOut("fast");
        jQuery.ajax({
            url: addToCartUrl,
            dataType: 'json',
            cache: false,
            success: ActiveCommerce.Global.onAddedToCart
        });
    },

    /* onAddedToCart(); 
    -  gets json feed and displays popup 
    ----------------------------------------------------------------- */
    onAddedToCart: function (data, textStatus, jqXHR) {

        // set currentProduct to json feed
        var currentProduct = data;

        //update header
        jQuery('#header-cart-count').text(currentProduct.totalCount);

        // replace popup info with current product
        jQuery('#added-product-container').empty().append(jQuery('#product-template').tmpl(currentProduct));

        //show added-to-cart popup		
        jQuery('#added-to-cart').fadeIn("fast", function () {
            // enable close button 
            jQuery("#added-to-cart a.close-button, #added-to-cart a.continue-shopping").click(function (e) {
                e.preventDefault(e);
                ActiveCommerce.Global.hideAddedToCart();
            });
        });
    },

    /* hideAddedToCart(); 
    -  hides added-to-cart popu; 
    ----------------------------------------------------------------- */
    hideAddedToCart: function () {
        //hide added-to-cart popup		
        jQuery('#added-to-cart').fadeOut("fast");
    },

    /* 
    ** search()
    */
    search: function () {
        var $searchBox = jQuery('#search-box'),
            term = jQuery.trim($searchBox.val());

        if (term.length == 0 || term == $searchBox[0].defaultValue) {
            return;
        }

        location.href = encodeURI((searchUrl || "/Search") + "?term=" + term);
    }


}

ActiveCommerce.Global.Analytics = {
    config: {
        analyticsTrackEvent: '_trackEvent',
        analyticsCategory: 'ActiveCommerce-Global',
        analyticsAddToCart: 'Cart-Add',
        analyticsProductAddedClose: 'Product-Added-Close',
        analyticsProductAddedViewCart: 'Product-Added-View-Cart',
        analyticsProductAddedContinueShopping: 'Product-Added-Continue-Shopping'
    },

    init: function () {
        ActiveCommerce.Global.Analytics.attachCartAddedAnalytics();
    },

    productAddedToCart: function (category, product) {
        //get category dynamically so we can track the event on the page it happened
        if (typeof (_gaq) != 'undefined') {
            var config = ActiveCommerce.Global.Analytics.config;
            _gaq.push([config.analyticsTrackEvent, category, config.analyticsAddToCart, product]);
        }
    },

    attachCartAddedAnalytics: function () {
        if (typeof (_gaq) != 'undefined') {
            var config = ActiveCommerce.Global.Analytics.config;
            var addedContainer = jQuery('#added-to-cart');
            addedContainer.delegate('a.close-button', 'click', function () {
                _gaq.push([config.analyticsTrackEvent, config.analyticsCategory, config.analyticsProductAddedClose]);
            });
            addedContainer.delegate('a.continue-shopping', 'click', function () {
                _gaq.push([config.analyticsTrackEvent, config.analyticsCategory, config.analyticsProductAddedContinueShopping]);
            });
            addedContainer.delegate('a.view-cart', 'click', function () {
                _gaq.push([config.analyticsTrackEvent, config.analyticsCategory, config.analyticsProductAddedViewCart]);
            });
        }
    }
}

jQuery(ActiveCommerce.Global.init);
jQuery(ActiveCommerce.Global.Analytics.init);


