/*
 * All java script logic for the search result and refinement
 * handling.
 *
 * The logic extends the JS namespace app.*
 */

(function(app){
	if (app) {
		// add search to namespace
		app.search = {
				
			initContent: function() {
				app.search.updateBindings();
				if ($.formidable) {
					$('.formidable').formidable();
				}
				app.hiddenData();
			},
			
			// updates all bindings for changed DOM elements
			updateBindings : function() {
				app.search.bindCompare();
				app.search.bindRefineLinks();
				app.search.bindRefineSelects();
				app.search.bindSwatches();
				app.search.bindPagination();
				app.search.bindSortBy();
				app.search.bindItemsPerPage();
				app.search.bindNavGroup();
				app.search.bindQuickView();
			},
			
			updateContent: function( url, sbox ) {
				if( null == url ) {
					return;
				}
				
				// indicate progress
				$("#content").append( '<div class="loading"><img class="indicator" src="' + app.URLs.loadingBigImg + '"/></div>' );
				$("#content .loading").css( {opacity: 0} ).animate( {opacity: 0.75}, "slow" );
				
				url = app.util.appendParamToURL(url, "format", "ajax");

				$("#content").load( url, function() {
					$("#content").fadeIn( "normal", app.search.initContent );
				});
			},
			
			trackRefine: function( url , sbox) {
				
				if(typeof(wt_sendinfo)) {
					//var wtParams = url.substring(url.indexOf('?'));
					var sel_val = sbox.options[sbox.options.selectedIndex].text;
					if (sbox.options.selectedIndex == 0)
						sel_val = "off";
					
					var wtUrl = webtrekkUrl + "?ClickType=click&ClickID=" + sbox.id + "&CustomClickParameter=ck4=" + sel_val + "&wtTrackingType=standardclick";
					//alert(wtUrl);
					
					$.getJSON(wtUrl, function(data){
						app.webtrekk.trackingHandler(data);
					});
				}
			},
			
			bindCompare: function() {
				$(".compareCheck").click(function() {
					var params = $.extend( {
						img: $(this).parent().siblings("div.image").find("p.productimage a img")
					}, $(this).data("data") );

					if (this.checked === true) {
						app.compare.addProduct(params);
					} else {
						app.compare.removeProduct(params);
					}
				});
			},
			
			getWebtrekkJSON: function(rurl,url, callback){
			    
			    $.getJSON(url, function(data)
				  {
			    	callback(data);
			    	app.search.updateContent( rurl );
			    });
			 },				
			
			bindRefineLinks: function() {
				$( "div.refineattributes ul li a, " +
				   "#searchrefinements div.refinedclear a, " +
				   ".refinementsDisplay a.relax" ).click(function() {
					var url = $(this).attr('href');
					var wtUrl;
					if ($(this).parents('li').attr('class')=="selected")
						wtUrl = webtrekkUrl + "?ClickType=click&ClickID=filter_" + $(this).parents('li').attr('name') + "_off&CustomClickParameter=ck4=" + $(this).attr('name') + "&wtTrackingType=standardclick";
					else
						wtUrl = webtrekkUrl + "?ClickType=click&ClickID=filter_" + $(this).parents('li').attr('name') + "_on&CustomClickParameter=ck4=" + $(this).attr('name') + "&wtTrackingType=standardclick";
						
					app.search.getWebtrekkJSON(url,wtUrl, function(data){
						app.webtrekk.trackingHandler(data);
					});
					//&					
					return false;
				});
				
			},
			
			// add change handler for all select filters
			bindRefineSelects : function() {
				jQuery("div.refineattributes select").change(function(e) {
					var url = jQuery(this).val();
					app.search.trackRefine( url, this );					
					app.search.updateContent( url , this);
					return false;
				});
			},
			
			
			
			bindSwatches: function() {
				// prepare swatch palettes and thumbnails
				jQuery("#content .swatches .invisible").hide();

				// show the palette
				jQuery("#content .swatches > a").click(function(e) {
					var cont = jQuery(this).parent().find(".palette");
					cont.show().focus();
					return false;
				});
				
				// hide the palette
				jQuery("#content .swatches .invisible").mouseout(function(e) {
					// fix for event bubbling (http://www.quirksmode.org/js/events_mouse.html)
					if(!e) var e = window.event;
					var tg = (window.event) ? e.srcElement : e.target;
					if(tg.nodeName != 'DIV') return;
					var reltg = (e.relatedTarget) ? e.relatedTarget : e.toElement;
					while(reltg != tg && reltg.nodeName != 'BODY')
						reltg = reltg.parentNode
					if (reltg == tg) return;
					
					// mouseout took place when mouse actually left layer
					// handle event now
					jQuery(this).hide();
					return false;
				});
				// toggle thumbnail
				jQuery("#content .swatches .palette .swatchanchor").bind("mouseover mouseout", function(e) {
					var swatch = jQuery(this);
					app.producttile.toggleVariationThumbnail(swatch);
				});
				// change thumbnail
				jQuery("#content .swatches .palette a.swatch").click(function(e) {
					if ((app.resources["LISTING_SWATCH_CLICK_BEHAVIOUR"] != null) &&  (app.resources["LISTING_SWATCH_CLICK_BEHAVIOUR"] == "true")) {
						// open the product detail page, if configured
						return true;
					} else {
						// default behaviour just changes the color in the product tile
						var swatch = jQuery(this);
						app.producttile.selectVariation(swatch);
						// omit following the swatch link
						return false;
					}
				});
			},
			
			// add click handler to each pagination link (only refreshes grid)
			bindPagination : function() {
				jQuery(".searchresultsheader .pagination a," +
					   ".searchresultsheader .itemsperpage a").click(function(e) {
					var url = $(this).attr('href');
					app.search.updateContent( url );
					return false;
				});
			},
			
			// add change handler for sortby menu
			bindSortBy : function() {
				jQuery(".sortby select").change(function(e) {
					var url = jQuery(this).val();
					app.search.updateContent( url );
					return false;
				});
			},
			
			// add change handler for items per page menu
			bindItemsPerPage : function() {
				jQuery(".itemsperpage select").change(function(e) {
					var url = jQuery(this).val();
					app.search.updateContent( url );
					return false;
				});
			},
			
			bindNavGroup : function() {
				jQuery("#searchrefinements .navgroup h3").click(function(e) {
					jQuery(this).toggleClass("collapsed");
					jQuery(this).nextAll("div.refineattributes").toggle();
				});
			},
			
			bindQuickView : function() {
				var quickViewOptions = {
					buttonSelector: "#content .quickviewbutton",
					imageSelector: "#content .product .image",
					buttonLinkSelector: "#content .quickviewbutton a",
					productNameLinkSelector: "#content .product .name a"
				};

				app.quickView.bindEvents(quickViewOptions);
			}

		}; // end search
	} else {
		alert("app namespace is not loaded yet!");
	}
})(app);

$(function() {
	app.search.updateBindings();
});

