
/**
 * prodgridjs.ftl
 * 
 *  Javascript to serve the adidas Product Catalog grid page.
 *  @author ncooley
 */

if(window['console'] === undefined)
  window.console = { log: function(){} };

var adiPC = {	
	processedUrl: 'la'|| false,
	view: 'products',
	jsQSObj: {ajax:true},	
	
	refreshListener: function(newLocation, historyData){		
		if(global.currentLoc != newLocation){		
			adiPC.updateFilters(newLocation);  // Listener for RSH.  Will be fired any time RSH detects update to url				
		}
	},
	
	init: function(){	
		var self = this;
		this.jsObj = {};
			
		if(($pC('#searchResults ul li').size() > 0)){
			if(global.columns != getColumnNumbers()){
			//If the initialized column count doesn't match the window's size	
				self.productGridResize();
			}
			$pC(window).resize(function(){self.productGridResize();});
			//Injecting porthole for ajax transfer
			$pC('<div id="porthole"></div>').insertAfter('#pageContent');																	
			
			var hash = (document.location.toString().indexOf('#') != -1);
			if((hash && (global.redirected === 'n' || ($pC.browser.opera || navigator.userAgent.toString().indexOf('Chrome')!= -1)))){							
				var pattern =  new RegExp("/#");  //
				var slashPattern = new RegExp("^/")
				var parsedURL = document.location.toString().split(pattern)[1];
				parsedURL = (slashPattern.test(parsedURL))?parsedURL:"/" + parsedURL;
				self.updateFilters(parsedURL);
			}									
		}			
		else{
			//This is for the "Products Not Found" error state... 				
			$pC('#pagiContainer, #footerPag').remove();
						
		}
		self.setFilters();															
		processNewNav({newWidth: ($pC('#pageContent').width() + 20), animDuration: 0, easing:'Cubic.easeOut'})					
	}, 
	
	setFilters: function(){
		var self = this;
		
		assignMO();	
		setSearch();
			
		if($pC.browser.msie){
			$pC('#sortNav select option, #footerPag select option').each(function(i,el){
				if(el.className.indexOf('selected') > -1){
					el.selected = true;					
				}			
			})
		}						
		
		$pC('#sortNav select option, #footerPag select option').attr('value', function(){
			var $this = $pC(this);
			var pattern =  new RegExp("/#"); 
			var operand = ($this.parents('form').attr('action').indexOf('?') === -1)?'?':'&';
			var newURL = $this.parents('form').attr('action')+ operand + $pC(this).parent().attr('id')+'='+ $pC(this).attr('value');
			
			return newURL;
		}) 					
		
		$pC('#filters a, #breadcrumbs a, #pagiContainer a, #footerPag a, #footerPag select, #sortNav select').each(function(el){
			var $this = $pC(this);					
			var eventType = (this.nodeName==="A")?"click":"change";
			
			$this.addClass('modified link').bind(eventType, function(event){
				event.preventDefault();
				
				if(this.nodeName === "A"){
					var oldUrl = $this.attr('href');								
				}
				else if(this.nodeName === "SELECT"){
					var oldUrl = this[this.selectedIndex].value; 														
				}				
				if(document.location.toString().indexOf('#') === -1 ){
					var cols = (oldUrl.toString().indexOf('?') == -1)?'?':'&';
					cols+='columns='+getColumnNumbers()
					document.location = '/catalogue/redirect.do?destUrl=' + encodeURIComponent(oldUrl+cols);							
					
				}
				else{
					self.updateFilters(oldUrl);
				}																				
			})
		})																					
	
		function assignMO(){
			if(!($pC.browser.msie && $pC.browser.version === '6.0')){
			var $thumbs = $pC('.articles:has(a:gt(0)) a');
			    $thumbs.find('img').each(function(i,el){
			    	var newImg = $pC(el).attr('src').replace(/_c1/, '_t1');
			    	$pC(el).clone().css({display:'none'}).insertAfter(el).attr('src', newImg ).addClass('helperImage');
			    });
			    $thumbs.mouseover(function(){
			        var newImg = $pC(this).find('img').attr('src').replace(/_c1/, '_t1');
			        var newLink = $pC(this).attr('href').toString();
			    				    				   			    	
			    	$pC(this).addClass('over')
			    	.siblings().removeClass('over').end()
			    	.parent().parent().find('.display a').attr('href', newLink)
			    	.find('img').replaceWith($pC(this).find('img.helperImage').clone().show());
				})	
			}
		}
		
		function setSearch(){
			$pC('<div class="icnSearch"></div>').insertAfter('#search #keywords');
			$pC('#search input').click(function(){
				if($pC(this).val() === global.productSearch){								
						$pC(this).val('');
				}							
			})
			$pC('#search input').blur(function(){
				if($pC(this).val() === ''){
					$pC(this).val(global.productSearch);
				}							
			})
			$pC('#search div.icnSearch').click(function(){								
				var $this = $pC(this);
				if(($this.siblings('input#keywords').val() != global.productSearch) && ($this.siblings('input#keywords').val() != ""))
				{
					$this.parents('form').submit();		
				}								
			})
			//$pC('#search input').autocomplete("/catalogue/auto.do", 
			//	{minChars:3, timeout:3000,validSelection:false, })				
		}						
	},
	
	updateFilters: function(el){
		var self=this;
		var destURL = parseLink(el);
						
		if(destURL!== "undefined" && destURL!== "null" ){
			var $gridHeight = $pC('#content');			
			
			setLoading();			
			dhtmlHistory.add(destURL); //this is where the serialized querystring values go... 					
			
			var newLoc = "/catalogue/la/products" + adiPC.destUrl;
			adiPC.jsQSObj.ajax = true;
			adiPC.jsQSObj.columns= getColumnNumbers("","measure") //adding column numbers to the request			
			
			$pC.ajaxSetup({
				url:  newLoc   /*  '/catalogue/bob'  */,
				data: adiPC.jsQSObj, 
				dataType: 'html',
				error:function(info, xhr){
						if($pC('.ajaxError').size() < 1){
							$pC('<div class="ajaxError">' + global.ajaxErrorMsg + '</div>').hide().insertBefore('#loadResults').slideDown('slow');						
						}
						$pC('.loading').remove();							
						$pC('#grayShade').css({'height': $gridHeight.height()}).hide();
						},
				success: function(info){
					$porthole = $pC('#porthole');
					$body = $pC('body');
					$search = $pC('#pageContent #search')
					$pageContent = $pC('#pageContent');
					
					$porthole.append(info);
					/* 
					
					Error state:  When error messages comes back from ajax response, handle it here... 
					
					*/
					 if($porthole.find('.mainErrorPage').size() > 0 && $body.find('.error').size() === 0 ){
						$body.addClass('errorState');
						$porthole.find('.errorPage').hide().insertBefore('#loadResults').slideDown('slow');							
						
						if($porthole.find('#breadcrumbs').size > 0){
							$pageContent.find('#breadcrumbs').replaceWith($porthole.find('#breadcrumbs'));}
						else{
							$pageContent.find('#breadcrumbs').empty();
						}
						if($porthole.find('#filters').size()>0){
							$pageContent.find('#filters').replaceWith($porthole.find('#filters'));
						}
						else{
							$pageContent.find('#filters').empty();
						}
						
						if($porthole.find('#pagiContainer').size()>0){
							$pageContent.find('#pagiContainer').empty();
							$pageContent.find('#footerPag').empty();
						}
						else{
							$pageContent.find('#pagiContainer').empty();
						}
						
						$pageContent.find('#loadResults').empty();
						
					}
					else{
					/* 
						
					This represents the OK case
						
					*/
											
						$body.find('.ajaxError').remove().end().removeClass('errorState').find('.errorState').remove();
						
						$pageContent.find('#loadResults').replaceWith($porthole.find('#pageContent #loadResults').clone());
						$pageContent.find('#breadcrumbs').replaceWith($porthole.find('#pageContent #breadcrumbs').clone());
						$pageContent.find('#search').replaceWith($porthole.find('#pageContent #search').clone());
						$pageContent.find('#filters').replaceWith($porthole.find('#pageContent #filters').clone());
						$pageContent.find('#pagiContainer').replaceWith($porthole.find('#pageContent #pagiContainer').clone()); 
						$pageContent.find('#footerPag #pagiContainer').replaceWith($porthole.find('#pageContent #pagiContainer').clone()); 
						moveFooter();
						self.setFilters();
					}
					
					$porthole.empty(); 
					
					$pC('.loading').remove();							
					$pC('#grayShade').css('height', function(){
						var $gridHeight = $pC('#content');
						if($pC(window).height() < $gridHeight.height())
							{console.log('grid height ' + $gridHeight.height());
							
							return $gridHeight.height() + $pC('#footer').height();
							
							}
						else{
							console.log('window height');
							return $pC(window).height();
							}
					}).hide(function(){					
						if($pC.browser.msie && $pC.browser.version == '6.0'){
							$pC('select').show();						
						}
					});						
					console.log('grayshade height: ' + $pC('#grayShade').height());
					global.currentLoc = destURL;
					self.jsQSObj = {ajax:true};					
				
				}			
			})
			$pC.ajax(function(){})						
		}
		 											
		function setLoading(){		
			var $gridHeight = $pC('#footer').position().top - $pC('#wrapper').outerHeight();
			if($pC.browser.msie && $pC.browser.version == '6.0'){
				$pC('select').hide();
			}			
			$pC('<div class="loading"><div class="loadingSlide"></div><p>' + global.loadingProducts + '</p></div>').css(
			{ 'top' : function(){return ($pC(window).height()/2)},
			  'left' : function(){return ($pC(window).width()/2)-50}
			}).appendTo('#content');
			$pC('#grayShade').css({'top': $pC('#content').position().top ,'height': $gridHeight,'opacity':.5}).show();								
		}
		
		function parseLink(el){
			var newUrlwQS = (el.indexOf(adiPC.view)== -1)?el:el.substr(el.indexOf(adiPC.view) + adiPC.view.length, el.length);
			var newUrlwQS = (newUrlwQS == "")?"/":newUrlwQS;						
			adiPC.destUrl = newUrlwQS;
			return newUrlwQS;		
		}		
	},
																			
										
						
	productGridResize: function(){				
		var $content = $pC('#columncontainer');
		var $filters = $pC('#filters');
		var availableSpace = $content.width() - ($filters.outerWidth({margin:true}));
		var gridItemWidth = $pC('#searchResults li').outerWidth({margin:true});
		var updatedGWidth = getColumnNumbers(availableSpace) * gridItemWidth;
		var updatedMGWidth = updatedGWidth + ($filters.outerWidth({margin:true}) + 3)
		
		if(global.columns != getColumnNumbers()){								
			var $window =  $pC('#pageContent');
			var $searchResults = $pC('#searchResults');
			var $resizeValues = $pC('#header');
						
			global.columns = getColumnNumbers();
			
			$content.removeClass().addClass('clearfix columns'+global.columns);
			processNewNav({newWidth: ($pC('#pageContent').width() + 20), animDuration: 0, easing:'Cubic.easeOut'})				
		}		
											
		//Calculations
		function resizeMainGrid(value){
			resizeElement($window, value);
			processNewNav({newWidth: (value + 1), animDuration: 1, easing:'Cubic.easeOut'}) 
		}
		function resizeGrid(value){
			resizeElement($searchResults, value);			
		}
		function resizeElement(el, value){
			$pC(el).css({'width': value});
			//$pC(el).animate({'width': value}, 'slow');			
		}				
	}				
}

function getColumnNumbers(){	
	var $window = jQuery(window);
	var $content = jQuery('#content');
	var $filters = jQuery('#filters');
	var availableSpace = $window.width() - 20 - ($filters.outerWidth({margin:true}));
	var gridItemWidth = jQuery('#searchResults li').outerWidth({margin:true});
	var rows = (gridItemWidth === 0)?4:parseInt(availableSpace/gridItemWidth);
	if (rows < 4){
		return 4;
	}
	else if(rows > 7){
		return 7;
	}
	else {
		return rows;
	}	
}								

if (document.location.toString().indexOf('#') > -1) {	
	window.dhtmlHistory.create({
		toJSON: function(o){
			return JSON.stringify(o);
		},
		fromJSON: function(s){
			return JSON.parse(s);
		}
	});
	
	$pC(window).load(function(){								
			dhtmlHistory.initialize();
			dhtmlHistory.addListener(adiPC.refreshListener);											
		}); 
}	

$pC().ready(function(){
	adiPC.init();																							
})

