var theory = (function(jQuery){	
	// theory namespace private members go here	

	// theory namespace public
	return {
		contextId: "", // id of the current page we are on e.g. Address, Personal Information
		folderId: "", // folder id of the customer service folders
		slideSpeed: "fast", // spped flag for the slide affects
		maxChars: 250, // max chars for a message box used for contact us textarea
		
		// initialize the theory namespace/instance
		init: function(){
			
			var that = this;
			
			// attach ajaxComplete handler
			jQuery(document.body).bind('ajaxComplete', function	(event){
				that.execUjs();
		    });
			
			// execute unobtrusive js
			this.execUjs();
			
			// init chars left message xxx of yyy left
			this.initCharsLeftMsg();
		},
		
		// all unobtrusive code goes here
		execUjs: function() {
			
			// make global nav drop downs with superfish jquery plugin
			jQuery('.categorymenu ul').addClass('sf-menu');			
			jQuery('ul.sf-menu').superfish({autoArrows	: false, dropShadows : false}).find('ul').bgIframe();
			
			// hightlight the current page link in left nav on account pages
			jQuery("#" + this.contextId).toggleClass("active");
			
			// hightlight the current page link in left nav on account pages
			jQuery("#" + this.folderId).slideToggle(this.slideSpeed);
			jQuery("#" + this.folderId).parent().children("h3").toggleClass("expanded");
			
			// remove the last You May also like item, we only need to show 2, this is done here since slots do not take params
			if (jQuery('.pt_productdetails .maywerecommend .productlisting .producttile').length > 2) {
				jQuery('.pt_productdetails .maywerecommend .productlisting .producttile:last').remove();
			}
			
			// bind events handlers
			this.bindEvents();
			
			// grab all copyhtml dom elements and fill in their html 
			// from the container specified in the data attribute
			// for sample usage check categoryproducthits file
			jQuery.each(jQuery(".copyhtml"), function(){
				var dataobj = jQuery(this).data("data");
				
				if (dataobj == undefined || dataobj == "undefined") {
					return false;
				}
				
				var source = jQuery(dataobj);
				
				if (source.length > 0) {
					jQuery(this).html(source.html());
				}
			});
			
			// default the country selection to US
			jQuery(".country select").val("US");
			
			// convert privacy policy contents into a dialog/hopup contents
			jQuery('#privacypolicy').dialog({
	 			bgiframe: true,
				autoOpen: false,
				modal: false,
		    	height: 480,
		    	width: 600,
		    	title: app.resources.PRIVACY_POLICY,
		    	resizable: false
			});
			
			if (!jQuery('#horicarousel').hasClass('jcarousel-list')) {
				jQuery('#horicarousel').jcarousel({
					scroll: 1,
					itemVisibleInCallback: app.captureCarouselRecommendations
		    	});
			}
			// hide recently viewed items by default on product details pages
			jQuery('.productdetailcolumn .recentlyvieweditems').hide();
			
			this.tooltipDefault();			
		},
		
		// event bindings
		bindEvents: function() {
			// preserve this instance
			var that = this;
			
			///////////////////// SG BEGIN ////////////////////////
			// initialize any product tiles on the page
			// bind quick view button toggling and click
			var options = {
				buttonSelector: "div.producttile div.quickviewbutton",
				imageSelector: "div.producttile div.image",
				buttonLinkSelector: "div.producttile div.quickviewbutton a"
			};			
			
			// hide quickview buttons
			jQuery(options.buttonSelector).hide();

			// hovering
			jQuery(options.imageSelector).unbind("hover").hover(
				function(e) {
					jQuery(this).children(options.buttonSelector).show();
					return false;
				},
				function(e) {
					jQuery(this).children(options.buttonSelector).hide();
					return false;
				}
			);

			// click binding for quick view
			jQuery(options.buttonLinkSelector).unbind("click").click(function(e) {
				app.quickView.show({url: this.href, source: "quickview"});
				return false;
			});
			
			// prev and next product links click handler
			jQuery(".productprevious a, .productnext a").unbind("click").click(function(e) {
				app.getProduct({url: this.href, source: "search"});
				return false;
			});
			
			// quick view show api override 
			app.quickView.show = function(options) {
				app.createDialog({id: 'QuickViewDialog', options: {
			    	height: 605,
			    	width: 725,
			    	dialogClass: 'quickview',
			    	title: 'Product Quickview',
			    	resizable: false
				}});

			    jQuery('#QuickViewDialog').dialog('open');
			    app.getProduct({containerId: "QuickViewDialog", source: options.source, url: options.url, label: options.label});
			}
			
			///////////////// SG END /////////////////////
			
			// swatches click, hover and mouseleave event handlers
			jQuery(".variationattributes .swatches").each(function(){
				var thisSwatch 	= jQuery(this);
				var pdpVarId = thisSwatch.data("data"); // data is id which is set via app.hiddenData onload
				
				if (pdpVarId === "color" && (typeof(USE_DHTML_ZOOM) === 'undefined' || !USE_DHTML_ZOOM)) {
					var varJqryObjs = thisSwatch.find("a.swatchanchor");
					
					varJqryObjs.click(function(){
						
						if (!jQuery(this).parent().hasClass("selected")) {
							return false;
						}
						
						var swfUrl = jQuery(this).next().data("data");
						// load variant image set (flash viewer) if the product is NOT a product set
						if (app.ProductCache.subProducts.length <= 0 && swfUrl != null && swfUrl != '') {
							var so = new SWFObject(swfUrl, "", "320", "560", "9", "#FFFFFF");
							so.addParam("wmode", "transparent");
							so.addParam("allowScriptAccess", "always");
							so.addParam("flashVars", "allowScriptAccess=always");
							so.write("flashcontent");
						}
					})
					.hover(function(e){
						
					}).mouseleave(function(e) {
						
					});
				}
			});
			
			jQuery(".recentlyviewed a").unbind("click").click(function(){
				jQuery(".recentlyvieweditems").slideToggle(that.slideSpeed);
				jQuery(this).toggleClass("expanded");
			});
			
			jQuery(".pt_account .navgroup li a, .pt_customerservice .navgroup li a").unbind("click").click(function(){
				var hrefStr = jQuery(this).attr("href");
				var pageId = jQuery(this).parent().attr("id");
				if (pageId && pageId != null && pageId != "") {
					hrefStr = hrefStr + (hrefStr.indexOf("contextId") < 0 ? (hrefStr.indexOf("?") < 0 ? "?":"&") +"contextId=" + jQuery(this).parent().attr("id"):"");    
					jQuery(this).attr("href", hrefStr);
				}
			});
			
			jQuery(".searchrefinemessage").unbind("click").click( function(event){
				
				// 1. change the arrow down or sideways TODO
				that.toggleShopBy();
				
				// 2. toggle the refinements container
				jQuery(".searchrefinements-attributes").length > 0 ? jQuery(".searchrefinements-attributes").slideToggle(that.slideSpeed) : jQuery(".searchrefinements").slideToggle(that.slideSpeed);				
			});
				
			jQuery(".pt_customerservice .navgroup h3").unbind("click").click( function(event){
				 // jQuery(this).toggleClass("expanded");
				 // jQuery(this).parent().children('ul').slideToggle(that.slideSpped);

				 jQuery(".pt_customerservice .navgroup ul").hide()
				 jQuery(this).siblings('ul').toggleClass("expanded").show();
			});
			
			// override default send to friend action from product detail page
			// pass in pid to display product details in hopup
			jQuery(".productactions .sendtofriend").unbind("click").click(function(e) {
				var pid = app.ProductCache.pid;
				// if the product is a master or a variant then grab the pid from the selected variant
				if (app.ProductCache.master || app.ProductCache.variant) {
					if (app.ProductCache.selectedVar != null) {
						pid = app.ProductCache.selectedVar.id;
					}
					else {
						//return false; // do not allow master product to be shared
					}
				}
				// append the pid to the url
				app.dialog.open(app.URLs.sendToFriend+"?"+jQuery.param({"pid": pid}), app.resources.SEND_TO_FRIEND);
				return false;
			} );
			
			// message character limitation
			jQuery(".contactus textarea").unbind("keyup keydown").bind("keyup keydown", function() {
				var value = jQuery(this).val();
		
				var left = that.maxChars - value.length;
				if(left < 0) {
					jQuery(this).val( value.slice(0, left) );
					left = 0;
				}
				jQuery(".contactus span.count").text(left);

			});
			
			jQuery('.privacyPolicy').unbind("click").click( function() {
				jQuery('#privacypolicy').show();
				jQuery('#privacypolicy').dialog('open');
			});
			
			jQuery('#emailsignup').unbind("click").click(function(){
				// show email signup dialog box.
				app.dialog.open(app.URLs.emailSignup, app.resources.EMAIL_SIGNUP);
				
				// size the dialog
				/*jQuery(document).bind('dialogopen', function(event, msg) {
					console.debug("dialogopen "+msg);
					jQuery('#dialogcontainer').dialog('option', 'height', 200);
					jQuery('#dialogcontainer').css('height', 200+'px');
				});*/
				return false;
			});
			
			jQuery('#acctEmailSignup').unbind("click").click(function(){
				// show email signup dialog box.
				app.dialog.open(app.URLs.acctEmailSignup, app.resources.EMAIL_SIGNUP);
				return false;
			});
			
			
			jQuery('#cartEmailSignup').unbind("click").click(function(){
				// show email signup dialog box.
				app.dialog.open(app.URLs.cartEmailSignup, app.resources.EMAIL_SIGNUP);
				return false;
			});
			
			jQuery('#checkoutEmailSignup').unbind("click").click(function(){
				// show email signup dialog box.
				app.dialog.open(app.URLs.checkoutEmailSignup, app.resources.EMAIL_SIGNUP);
				return false;
			});
			
			jQuery('#specialsignup').unbind("click").click(function(){
				// show email signup dialog box.
				app.dialog.open(app.URLs.specialSignup, app.resources.EMAIL_SIGNUP);

				return false;
			});
		},
				
		/**
		 * TODO REMOVE IT ONCE 2.10.1 is incorporated
		 * Unobtrusively build tooltips on the page.
		 * it looks for a tooltip class anchor which contains a div with tooltip-body class as the body container.
		 */
		tooltipDefault: function () {	 
			jQuery(".tooltip").tooltip(jQuery.extend({}, app.tooltipSettings, {	
					bodyHandler: function() {
						return jQuery(this).children(".tooltip-body").html();
					}
				}
			));
		},
		
		// toggle shop by arrow icon
		toggleShopBy: function() {
			jQuery(".searchrefinemessage").toggleClass("expanded");
		},
		
		// initialize the char left message xxx from yyy
		initCharsLeftMsg: function() {
			var text = jQuery(".contactus span.caption").html();
			
			if (!text) { return false; }
			
			jQuery(".contactus span.caption").html( text.replace("XXX", "<span class=\"count\"><\/span>").replace("YYY", this.maxChars) );	
			jQuery(".contactus span.count").text(this.maxChars - jQuery(".contactus textarea").val().length);
		},
		
		// wrapper helper method to launch quick view window
		// param: pid - product id
		showQuickView: function(pid) {
			app.quickView.show({url: app.util.appendParamToURL(app.URLs.getProductUrl, "pid", pid), source: "quickview"});
			return false;
		}
	}
})(jQuery);

// application initialization on dom ready
jQuery(document).ready(function(){
	theory.init();
});
