

(function () {

    var $ = jQuery.noConflict(),
        $j = jQuery,
        site = window.site = {};


    /*
    Page Specific Functionality 
    */

    // The base Page class. Common functions for pages should go in its prototype.
    site.Page = function (customMembers) {
        this.$I = $(this);

        $.extend(this, customMembers);
    };

    site.Page.prototype = site.Page.fn = {
        $I: null,
        delayTime: 2000,
        pageForm: null,

        init: null,
        load: null,
        delay: null,

        submit: function () {
            return this.pageForm.submit();
        },

        bind: function () {
            this.$I.bind.apply(this.$I, arguments);
            return this;
        },

        trigger: function () {
            this.$I.trigger.apply(this.$I, arguments);
            return this;
        }
    };

    //Declare the unique and prominent pages of the site and their members
    site.pages = {

        common: new site.Page({
            init: function () {
                this.prepNav();
				
				$("div.features-banner").featuresBanner();
				$("ul.list-ticker").tickerList();

            },
            load: function () {

            },
            delay: function () {

            },
            prepNav: function () {
                var P = this,
					hoverOverWait = 100,
					hoverOutWait = 800,
					staticDisplayDepth = 1,
					navArea = $("#siteNav").children(".nav-panel1"),
					navLevels = navArea.find("ul"),
					navItems = navLevels.children("li"),
					navLinks = navItems.children("a");
				
				var clearTimeouts = function(){    		
					this.each(function(i, li){
						clearTimeout($(li).data("moverTimeout"));
						clearTimeout($(li).data("moutTimeout"));
					});
					return this;
				};
				var navResetTimer = null;
				var toggleItem = function(isToggleOn){
					//navItems.removeClass("hover");
					this.each(function(i, li){
						var $li = $(this);    				
						if(isToggleOn===false || (!arguments.length && $li.hasClass("hover"))){         				
							$li.removeClass("hover");
						}else{          				
							$li.siblings("li").removeClass("active-parent active static");        				
							$li.addClass("hover");
						}
					}); 
					//Reset item classes if no other item is hovered
					clearTimeout(navResetTimer);
					var lis = this.filter("li").add(this.siblings("li"));
					if(lis.filter(".hover").length == 0){
						navResetTimer = setTimeout(function(){
							lis.each(function(){
								$(this).addClass($(this).data("origClass"));
							});
						}, hoverOutWait/4);
					}
					return this;
				};
				
				
				//Get the link in the nav that matches the current page url
				var activeNavLinks = navLinks.filter(gf.utils.filterActiveLinks).filter(function(i){
						return $(this).data("matchLevel") >= gf.utils.splitUrl(window.location.href).length;
					}).each(function(i, a){
						//Add active and active-parent classes.
						var $this = $(this);
						$this.addClass("active");
						$this.closest("li").addClass("active").parents("li").removeClass("active").addClass("active-parent");    			
					}),
					activeNavItems = navItems.filter(".active"),
					activeNavParents = navItems.filter(".active-parent");    		
				
				//Override sibling static links if specific items are active parents or active
				var staticOverrides = activeNavParents.add(activeNavItems).filter(":has(>a.item-designing),:has(>a.item-visiting)");
				if(staticOverrides.length) staticOverrides.siblings(".static").removeClass("static");
				
				
				navItems.filter(function(i){
					return $(this).closest("#categoryNav").length;
				}).each(function(i, li){	    			
					var $li = $(li),
						$a = $li.children("a");
					$li.hover(function(){
						toggleItem.call($li.siblings("li.hover"), false);
						clearTimeouts.call($li.add($li.siblings()));
						$li.data("moverTimeout", setTimeout(function(){
							toggleItem.call($li, true);
						}, hoverOverWait));
					}, function(){        			
						clearTimeouts.call($li);
						$li.data("moutTimeout", setTimeout(function(){
							toggleItem.call($li, false);
						}, hoverOutWait));
					});
				});
				
				//Capture all item classes as they are now so we can reset them when needed.
				navItems.each(function(i, li){
					$(li).data("origClass", $(li).attr("class"));
				});
            },

            prepQuickSearch: function () {

                return this;
            },

            inputStyles: function () {
                $("*:input").each(function (i, input) {
                    var $input = $(input);
                    if ($input.is("textarea")) { $input.addClass("input-textarea"); }
                    else if ($input.is("select")) { $input.addClass("input-select"); }
                    else { $input.addClass("input-" + $input.attr("type")); }
                    //create placeholder text
                    if ($input.is(":text[placeholder]")) {
                        $input.placeholderText();
                    }
                });

                return this;
            },

            equalizeColumns: function () {
                var sitePage = $("#sitePage"),
                    inners = sitePage.find("aside.page-left,article.page-main,aside.page-right").find(">div:first");
                inners.css({ minHeight: sitePage.height() });
            },

            toggleFirefoxFonts: function (items) {
                if (!$.browser.mozilla) {
                    //Don't need to delay display for fonts outside of Firefox
                    items.css({ visibility: "visible" });
                } else {
                    items.css({ visibility: "hidden" });
                    $(window).load(function () {
                        setTimeout(function () {
                            //We can display the fonts in Firefox now
                            items.css({ visibility: "visible" });
                        }, 2000);
                    });
                }
                return this;
            }
        }),

        "cms-home": new site.Page({
            init: function () {
                var P = this;
				P.setupBottomFeatures();
				$("ul.feature-buttons > li:eq(1)").addClass("middle");
				
            },
            load: function () {

            },
            delay: function () {

            },
			setupBottomFeatures:function(){
				var ulCallouts = $("ul.list-callouts");
				ulCallouts.each(function(u, ul){		
					var $ul = $(ul),
						items = $ul.children("li");
					items.each(function(l, li){
						var $li = $(li),
							$a = $li.find("a:first"),
							actIcon = $("<span class='action-icon'>&gt;</span>");
						//Create a new row every 2 items, if a static <li class="new-row"/> does not already exist
						if(l > 0 && l % 2 === 0 && !$li.next("li:first").hasClass("new-row")){
							$li.before("<li class='new-row'></li>");
						}
						//Make the whole items "hoverable"
						$li.hover(function(evt){
							$li.addClass("hover");
						}, function(evt){
							$li.removeClass("hover");
						});
						if($a.text().length){
							$a.append(actIcon);
						}else{
							$li.find("h2").append(actIcon);	
						}
						$a.click(function(evt){
							window.location = this.href;
							evt.stopPropagation();
							return false;
						});
						$li.click(function(evt){
							$a.click();
						});
					});
					
				});
			}
        }),
		
		"catalog-product-view": new site.Page({
			init:function(){
				var P = this;
				
				setInterval(function(){
					$("#main-image").css({height:null, width:null});
				}, 500);
				
			},
			print:function(){
				/*var win = gf.utils.popupHtml($("html").html(), {scrollbars:true});
	
				$(win.document).ready(function(){
					var doc = $(win.document),
						remAttrsOn = doc.find("#collateral-tabs > dd, #main-image, #main-image > img"),
						printSheets = doc.find("link[media='print']");
					remAttrsOn.removeAttr("style").removeAttr("width").removeAttr("height");
					printSheets.attr("media","all");	
					win.print();	
				});
				
				
				//return win;*/
				
				$("#main-image").css({height:null, width:null});
				
				window.print();
				/*toggleStylesOn.each(function(){
					$(this).attr("style", $(this).data("origStyle"));
				});*/
				//return window.printHtml($("div.main").html(), {scrollbars:true});	
			}
		})


    };



    






    /*
    CUSTOM JQUERY PLUGINS
    */
	
	
	/**
    @method jQuery.fn.featuresBanner
    @description Creates a feature banner sequence like that on the home page.
    @author Stephen Rushing, eSiteful
    */
	$.fn.featuresBanner = function(){
		
		this.each(function(e, element){
			var $element = $(element),
				$ulBanners = $element.children("ul.banners"),
				$ulControls = $element.children("ul.controls"),
				$liPager = $("<li class=\"item-pager\" />").appendTo($ulControls);
				$play = $ulControls.find(".item-play"),
				$pause = $ulControls.find(".item-pause");
			
			$ulBanners.cycle({
				activePagerClass:"active",
				pager:$liPager,
				pagerAnchorBuilder:function(index, el){
					var $item = $("<a>"+(index+1)+"</a>").appendTo($liPager);					
					$item.click(function(){
						$ulBanners.cycle(index);
					});
				}
			});
			
			$play.click(function(){
				$ulBanners.cycle("resume");
				$pause.removeClass("active");
				$play.addClass("active");
			}).addClass("active");
			
			$pause.click(function(){
				$ulBanners.cycle("pause");
				$pause.addClass("active");
				$play.removeClass("active");
			});

			/*
			var sequence = new esf.widget.DisplaySequence({
				ul: ulBanners
			});
			
			var controlBar = new esf.widget.DisplaySequenceControlBar({
				sequence: sequence,
				ul: ulControls,
				btnPlay: ulControls.children("li.item-play"),
				btnPause: ulControls.children("li.item-pause")
			});
			*/
			
		});
		
		return this;
	};
	
	
	/**
    @method jQuery.fn.tickerList
    @description Creates a scrolling horizontal ticker like that on the home page.
    @author Stephen Rushing, eSiteful
    */
	$.fn.tickerList = function(){
		
		var animateOpts = {
			duration:null,
			easing:"linear",
			queue:false
		};
			
		
		this.each(function(u, ul){
			var $ul = $(ul),
				wrap = $ul.closest("div.list-ticker"),
				aopts = $.extend({}, animateOpts, {duration:(9000 * $ul.children("li").length)});
			
			if(!wrap.length){
				wrap = $ul.wrap("<div class='list-ticker'/>").closest("div");
			}
			
			var width=0;
			$ul.children("li").each(function(l, li){
				width += $(li).outerWidth(true);
			});
			
			$ul.css({position:"absolute", width:width});
			
			aopts.complete = function(){ $ul.css({left:wrap.width()}); $ul.animate({left: -$ul.width()}, $.extend({}, aopts)); };			
			
			$ul.animate({left: -$ul.width()}, aopts);
		});
		
				
		
		
			/*
		var initX=0;
		this.children("li").each(function(e, element){
			var $element = $(element);
			$element.css({position:"absolute", left:initX});
			initX+=$element.width();
		});*/
		
		return this;
	};



    /**
    @method jQuery.fn.placeholderText
    @description Uses the "placeholder" attribute on a text input to overlay a label or message while the field is not in focus. This is supposed to mimic the HTML5 input's placeholder attribute.
    @author Stephen Rushing, eSiteful
    */
    $.fn.placeholderText = function (opts) {
        if (("placeholder" in $('<input>')[0])) return;

        var I = this,
            options = I.options = $.extend({
                spanHtml: "<span class='input-placeholder'></span>",
                position: "left"
            }, opts);

        I.each(function (i, input) {
            var $input = $(input),
                phText = $input.attr("placeholder");

            if (phText !== null && phText.length) {
                var placeholder = $(options.spanHtml).insertAfter(input).html(phText).css("display", "none");

                $input.data("placeholderText", placeholder);

                $input.blur(function (evt) {

                    if ($.trim($input.val()).length) return true;

                    var pos = $input.position();
                    if (options.position === "right") {
                        pos.left += $input.width() - placeholder.width();
                    } else if (options.position === "center") {
                        pos.left += ($input.width() - placeholder.width()) / 2;
                    }

                    placeholder.css({ display: "", position: "absolute", left: pos.left, top: pos.top });

                }).blur();

                $input.focus(function (evt) {
                    placeholder.css({ display: "none" });
                });

                placeholder.click(function (evt) {
                    $input.focus();
                });

            }
        });


        return I;
    };


    /**
    *   @method jQuery.fn.buildFaqAnchors
    *   @description 
    *   @author Stephen Rushing, eSiteful
    */
    $.fn.buildFaqAnchors = function (ol) {
        if (!(ol instanceof $)) ol = $(ol);

        this.each(function (i, dl) {
            var $q = $(this).children("dt").clone(),
                $a = $(this).children("dd");

            $q.children("a").remove();
            var item = $("<li><a href='#" + $(this).attr("id") + "'>" + $q.html() + "</a></li>").appendTo(ol);

            item.find("a>a").remove();

        });

    };


    /**
    *   @method jQuery.fn.blinkCss
    *   @description 
    *   @author Stephen Rushing, eSiteful
    */
    $.fn.blinkCss = function (css, showTime, hideTime, count) {

        var B = this;
        showTime = showTime != null ? showTime : 500;
        hideTime = hideTime != null ? hideTime : showTime / 2;
        count = count != null ? count : 3;

        this.each(function (n, node) {
            var $node = $(node),
				orig = isClass ? $node.attr("class") : $node.attr("style");
            $node.data("blinkCssOrig", orig || "");
        });

        var isClass = typeof (css) === "string",
			counted = 0,
			showTimer = null,
			hideTimer = null;

        function show() {
            B.each(function (n, node) {
                if (isClass) {
                    $(node).addClass(css);
                } else {
                    $(node).css(css);
                }
                counted++;
            });
            hideTimer = setTimeout(hide, showTime);
        }

        function hide() {
            B.each(function (n, node) {
                var counted = 0,
					$node = isClass ? $(node).addClass(css) : $(node).css(css),
					orig = $node.data("blinkCssOrig") || "";
                $node.attr(isClass ? "class" : "style", orig);
            });
            if (counted < count) {
                setTimeout(show, hideTime);
            }
        }

        show();


    };


    /**
    *   @method jQuery.fn.getLabels
    *   @description 
    *   @author Stephen Rushing, eSiteful
    */
    $.fn.getLabels = function () {
        var labels = $([]),
			all = $("label");

        this.each(function (n, node) {
            var $node = $(node),
				lbl = all.filter("[for='" + node.id + "']");
            if (!lbl.length) lbl = $node.closest("label");
            if (lbl.length) labels = labels.add(lbl);
        });
        return labels;
    };


    /**
    *   @method imgToSprite
    *   @description converts <img/> tags to a specified element with the img src as the background. The original use case is for creating rounded corners on images with the border-radius property, which Firefox and IE+css3pie do not render correctly.
    *   @author Stephen Rushing, eSiteful
    */

    $.fn.imgToSprite = function (opts) {
        var I = this,
            defaults = {
                container: $("<div class='img-sprite'/>"),
                height: -1, //-1 dimension indicates that we should use the current dimension of the image
                width: -1,
                manipulator: "before"
            },
            o = $.extend({}, defaults, opts),
            images = this.filter("img");

        //search for child images if there are no images in this set
        if (!images.length) {
            images = this.find("img");
        }

        function replace(img) {
            var c = o.container.clone(true),
                $img = $(img),
                height = o.height !== -1 ? o.height : $img.height(),
                width = o.width !== -1 ? o.width : $img.width(),
                bgSize = ((height !== null && width !== null) ? height + "px " + width + "px" : null),
                bgUrl = "url('" + img.src + "')",
                cssAttrs = {
                    backgroundImage: bgUrl,
                    height: height,
                    width: width,
                    backgroundRepeat: "no-repeat",
                    backgroundSize: height + "px " + width + "px",
                    visibility: "",
                    display: ""
                };

            //We must remove any scaling from the image until browsers support background scaling better
            if (!$.browser.safari) {
                $img.removeAttr("height").removeAttr("width").css({ height: "auto", width: "auto" });
                cssAttrs.height = img.height;
                cssAttrs.width = img.width;
            }

            c.addClass($img.attr("class"));
            c.attr("style", $img.attr("style"));
            c.css(cssAttrs);

            $img[o.manipulator](c);
        }

        images.each(function (i, img) {
            var $img = $(img);
            if (!img.complete) {
                $img.load(function (evt) {
                    replace(img);
                });
            } else {
                setTimeout(function () { replace(img); }, 1); //IE needs the delay for some reason
            }
        });

        return this;
    };


})();













/*
OVERRIDE STUFF
*/

Enterprise.Bundle.initialize = function(){
	
	Enterprise.BundleSummary.initialize();
	//$('options-container').show();
}


Enterprise.Bundle.start = function(){
	
	window.location.hash = "options-container";
	
	//$('bundle-product-wrapper').setStyle({height: 'auto'});
	//$('productView').hide();
	//$('bundle-product-wrapper').removeClassName('moving-now');
	
	/*
	if (!$('bundle-product-wrapper').hasClassName('moving-now')) {
		new Effect.Move(this.slider, {
			x: -this.xOffset, y: 0, mode: 'relative', duration: 1.5,
			beforeStart: function (effect) {
				$('bundle-product-wrapper').setStyle({height: $('productView').getHeight() + 'px'});
				$('options-container').show();
				
				$('bundle-product-wrapper').addClassName('moving-now');
			},
			afterFinish: function (effect) {
				
			}
		});
	 }*/	
	
}

Enterprise.Bundle.end = function(){
	//Enterprise.BundleSummary.exitSummary();	
}


