/**
 * @author adidas
 */

$a('html').addClass('load');  //resolves issues with flickering discreet nav

if (window.self != window.top) window.top.location = window.self.location;

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

$a(document).ready(function(){
  
  ADIDAS.init();
  
  resizeFlash();	
  moveFooter();
  navShift ( $a(window).width() );
	moveFooter();
	$a(window).bind('resize',function(){
		navShift ( $a(window).width() );
		resizeFlash();
		moveFooter();
	});
	ADIDAS.initSearch();
		
});

var ADIDAS = {

	init: function(){
		var obj = this;
		(function($){
			var $mode = $a('#hdn_headerType');
			if($mode.attr('value') === 'discreet'){
				$a('.header-nav').addClass('discreet');							
			}
			$a('body').addClass(browserDetect());
			
					
			
			var $brands = $a('#hdn_adidascomBrand');
			var $apps = $a('#hdn_app');
			
			if($brands.size() > 0 && $mode.attr('value')!= 'discreet'){
				$a('.button').each(function(i, el){
					var $el = $(el);
					if($el.hasClass($brands.attr('value'))){
						$el.find('.nav-button').wrap('<div class="current"></div>' )
					}
				})
			}
			$a('html').removeClass('load');
			
			
			
			//update for width here
			
			var $shopTD = $a('.shop .dropdown .listwrap td')
			if($shopTD.size() > 2){
				$shopTD.parents('.dropdown').addClass('col3');

			}
			var $appNav = $a('.secondaryNavWrapper .applications li:first');
			if($appNav.attr('class') != 'adidastv'){
				$appNav.find('.layer-text a').width($appNav.width() -1);
			}
			
			if($apps.attr('value')!= ''){
				$a('ul.applications li.' + $apps.attr('value') + " a").addClass('current');
			}
			
			
			//number the li.button elements
			$("li.button").each(function(index, domEle){
				$(this).attr("id", 'button' + (index + 1));
			});			
			
			$a('<div id="grayShade"></div>').css('opacity','0').hide().insertBefore('#wrapper');
			
			
			// Mainmenu dropdown
			if (checkWMode() == false && $a('#noWmodeShade').size() == 0) {
				$a("<div id='noWmodeShade' class='default'></div>").insertAfter('div#grayShade');
				$a("#noWmodeShade").hide();
			}
			$a('div#grayShade, div#noWmodeShade').bgiframe();
			
			$a('.button .parent, .listwrap li a').hover(function(){
				$a(this).addClass('hover')
			}, function(){
				$a(this).removeClass('hover')
			})
			
			$a('.button .parent').click(function(){
				handleMenus(this)								
			})
			
			$a('.primaryNav').mouseleave(function(){
				var $this = $a(this);
				if ($this.find('.click').size() > 0) {
					var c = setTimeout(function(){
						pullShade('up'); 
						$this.find('.dropdown').hide().end().find('.click').removeClass('click');
						
						if(checkWMode() == false){
							showWOWmode('hide');
						}
						resumeFlash();
						$a('applet').css({marginLeft:'0px'});
						
						$('.adidasLogos, .adidasLogos .ui-accordion *').unbind('mouseenter');
					},500)	
					var d = $this.find('.adidasLogos, .adidasLogos .ui-accordion *').mouseenter(function(){
							clearTimeout(c); 
							$a('.adidasLogos, .adidasLogos .ui-accordion *').unbind('mouseenter');
						});
				}
				
			}); 			
			
			var $ulFeatured = $a('ul.featured-perf');
			var imgHeight = $ulFeatured.find('img').attr('height'); 		
			
			$ulFeatured.accordion({
				header: 'a:not(.dropdown2 a)',
				collapsible:true,
				active: false, 
				alwaysOpen:false,
				autoheight: true,
				animated: false,
				event: 'mouseover'
			}).mouseleave(function(){
				$ulFeatured.accordion('option', 'collapsible', true);
				$ulFeatured.accordion('activate', 'sldkfjlksd');
			}).each(function(i, el){
				var $el = $a(el);
				$el.height($el.height() + imgHeight).addClass('adjustedheight');
			})
			
			$ulFeatured.mouseenter(function(){
				$ulFeatured.accordion('option', 'collapsible', false)
				
			})
			
			addDate();
			
			function addDate(){
				var d=new Date(); 
				yr="&copy;" + d.getFullYear() + " adidas";
			
				$a('#footer li.copy-text').append(yr);
			}																	
		})($a);		
	}, // end of init()	
	
	
	//New object for search elements... 
	initSearch: function(){
		(function($){
			var $txt = $('#txtProductSearch');
			var $but = $('#btnProductSearch');
			var $form = $('#frmProductSearch');
			
			initEuroEcomm();
			var $searchField = $('#txtProductSearch');
			setSearchSize();
			
			
			
			if($form.size() === 0){
				$('.countrySelect').addClass('noSearch');
			}
			
			$txt.addClass('default');
			$txt.focus(function(e){
				focusSearch(e);
			}).blur(function(e){
				focusSearch(e);
			})
			
			if($('body').hasClass('ie6')){
				$('#btnProductSearch').click(function(){
					$form.submit();
				})
			}
			
			function initEuroEcomm(){
						

						if($txt.attr('name')==='categories'){
							var act = $form.attr('action');
							var tar = $form.attr('target');
							
							$form.removeAttr('action').removeAttr('target');
							$form.attr('onSubmit','return false;')
							
							$form.submit(function(){
								var qs = $(this).serialize().split("+").join("'").replace('=','=,') + "&" + "cm_mmc=adidas dot com-_-topNav-_-product search-_-" + $txt.val();
								var loc = (act.indexOf('?') === -1)? act + "?" + qs: act + "&" + qs;
								if (tar === '_adiBlank') {
									window.open(encodeURI(loc));									
								}
								else{
									document.location = encodeURI(loc);
								}
								return false;				
							})
						}
						
					}
		
		function checkTitle(){
			var $long = $searchField.siblings('.longText');
			if($long.size() === 1 && $searchField.siblings('.shortText').size() === 1){
				if($long.width() < $searchField.width() && ($searchField.val() === $searchField.attr('title'))){
					$searchField.attr('title', $long.text()).val($long.text());
				}
			}
		}
	
		function focusSearch(e){
			var newV;
			
			if(e.type === 'focus'){
				newV = ($searchField.val()===$searchField.attr('title'))?'':$searchField.val();
				$searchField.val(newV);
			}
			else if(e.type === 'blur'){
				newV = ($searchField.val()==='')?$searchField.attr('title'):$searchField.val();
				$searchField.val(newV);
			}
			if($searchField.val()===$searchField.attr('title')){
				$searchField.addClass('default');				
			}
			else {
				$searchField.removeClass('default');
			}
		}
		function setSearchSize(){
					var $txt = $('#wrapper #txtProductSearch');
					setFormWidth();

					var utilNav = 0;
					$('.secondaryNav ul.utilities li').each(function(){
						utilNav+= $(this).outerWidth();
					})

					var txtSearch = $('#wrapper #txtProductSearch').width();
					var availSpace = $('.secondaryNavWrapper').width() - utilNav;
					var newWidth = (txtSearch + availSpace > 135)?135:txtSearch + availSpace;

					if (availSpace > 0) {
						$txt.width(newWidth - 15);
					}
					setFormWidth();
					checkTitle();

					function setFormWidth(){
						var formWidth = $txt.width() + $('#btnSearchField').width() + 24;			
						$('body.ie7 #wrapper #frmProductSearch, body.ie6 #wrapper #frmProductSearch ').width(formWidth);	
					
						if($a.browser.msie == true && ($a.browser.version < 8.0) && $('.discreet').size() > 0){
							var newWidth = ($a('.countrySelect a').outerWidth() + $a('.productSearch form').outerWidth()) + 20;
							$a('ul.utilities').css('width', newWidth);
						}
					
					}
				}

		
		
		})($a)		
	}
}

function pullShade(action){
	var $shade = $a('#grayShade')
	switch (action) {
		case 'up':
			$a('#grayShade').fadeTo(0, '0', function(){
				$a(this).hide()
			});
			resumeFlash ();
			
			break;
			
		case 'down':
			pauseFlash ();
			$shade.css({
				'display': 'block'							
			}).fadeTo(0, '.5')												
			break;
	}
}

function handleMenus(el){
		if (!$a(el).hasClass('click')) {
			pullShade('down');
			$a(el).parents('li.button').siblings().find('.parent').removeClass('click').end().end().end().removeClass('hover').addClass('click').find('.dropdown').hide().show();
		}
		if (!($a.browser.opera == true && $a.browser.version < 9)) {										
			if(checkWMode() == false){
				showWOWmode('show');						
			}
			if (!($a.browser.mozilla == true && $a.browser.version.substr(0,3) < "1.9" )) {
				$a("#grayShade").show();
			}
		}
	$a('applet').css({marginLeft:'-4000px'});	
}


//once we know whether or not there's flash and no wmode set, we need to show/hide flash appropriately

function showWOWmode(action){
	if (action == 'show') {
		$a("#flashcontent object, #flashcontent embed, #FlashContent object, #FlashContent embed").css({marginLeft: '-5000px'})
		//$a("#FlashContent, #flashcontent").css({visibility:'hidden'}).find('embed').hide();
		$a("#noWmodeShade").show();
		//
	}
	else {
		$a("#flashcontent object, #flashcontent embed, #FlashContent object, #FlashContent embed").css({marginLeft: '0'})	
		
		$a("#noWmodeShade").hide();
		//$a("#FlashContent, #flashcontent").css({visibility:'visible'}).find('embed').show();	
	}	
}

// checking for the existence of a wmode
function checkWMode(){
	
	var embeds = $a('embed, object');
	if (embeds.length > 0) {
		//IE type 
		if ($a("object").size() > 0 && (($a("object")[0].innerHTML.toString().toLowerCase().indexOf('wmode') == -1)|| $a("object")[0].innerHTML.toString().toLowerCase().indexOf('<param name="wmode" value="window">') != -1)) {
			return false;
		}
		else if ($a("embed").size() > 0) {
		//FF type
			try{ 
				var j = $a('embed').attr('wmode').toString().length; 
				return; 
			} 
			catch(err){ return false; }			
		}
		else{
			
			return; }
	}
	else {
		
		return;
	}					
}


function processNewNav(obj){
	var newWidth = obj.newWidth + 'px';
	var duration = obj.animDuration;
	var easing = obj.easing.split('.').reverse().join(''); // Cubic.easeOut -> easeOutCubic
	
	$a('div.header-nav,#footer dl.nav').animate({width: newWidth},duration,easing);

	navShift(obj.newWidth);
}

function navShift(newWidth){
	if (newWidth<=190) 	$a('#wrapper').addClass('smallWindow');
	else $a('#wrapper').removeClass('smallWindow');
}




// TODO: add possibility to add a different threshold by adding optional parameter to function
function resizeFlash(){
	(function($){
		//var footerheight = $('#footer').height() + parseInt($('#footer').css('paddingTop'), 10) + parseInt($('#footer').css('paddingBottom'), 10);
		var footerheight = $('#footer').outerHeight()
		var windowheight = $(window).height();
		var wrapper = $('#wrapper').outerHeight();
		var flashheight = windowheight - wrapper - footerheight;
	
	if ($a('embed, object').size() > 0) {
		if ($("#homepage").size() > 0) {

			if (flashheight > 588) {
				$('#FlashContent, #flashcontent').css('height', flashheight);
				return flashheight;
			}
			else {
				$('#FlashContent, #flashcontent').css('height', 588);
				return 588;
			}
		}
		if ($('.fullFlash').size() > 0) {
			$('#FlashContent, #flashcontent').css('height', flashheight);
			return flashheight;
		}
	}
	})($a)
}

function thisMovie( movieName ) {
		if ( navigator.appName.indexOf("Microsoft") != -1 ) return window[movieName];
        else return document[movieName];	    
}


function pauseFlash ( ) {      
     try{
	 	if($a('#homepage #flashLayer').size() > 0){
            thisMovie("flashLayer").pause();          
      	} 
	 }
	 catch(err){
	 	
	 } 
	  
}

	
	
function resumeFlash ( ) {
      try{
	  	 if($a('#homepage #flashLayer').size() > 0){
            thisMovie("flashLayer").resume();
      }
		
	  }
	  catch(err){
	  	
	  }
	 
}

function moveFooter(){
  var wrapper = $a('#wrapper').outerHeight();
  //var footerheight = $a('#footer').height() + parseInt($a('#footer').css('paddingTop'),10)  + parseInt($a('#footer').css('paddingBottom'),10);
  var footerheight = $a('#footer').outerHeight();
  var flashHeight = $a('#FlashContent, #flashcontent').outerHeight() + wrapper;
  var windowheight = $a(window).height();
  var embeds = $a('embed, object');
  var totalPageHeight = $a('#content, #homepage').outerHeight() + wrapper + footerheight;
  
  
    function getFooterOffset(){
    	var offset; 
        
		if ( $a('#homepage').size() > 0 && ($a(window).height() <  footerheight + 588) ){ // basically when the flash stops resizing to be smaller.
	     
		  //offset = 613;
		  offset = 600;
		  
	    } else {
	      offset = $a(window).height() - footerheight;
		  
	    }	
		return offset + 'px'  	
	}
	function updateFooter(type){
		switch (type){
			case "abs":
			$a('#footer').css({position: 'absolute',top: getFooterOffset()}) 	
			break;
			
			case "static":
			$a('#footer').css({position: 'static'})
			break;
		}
	}
  

  if (($a('#homepage').size() > 0 && embeds.length > 0) || (embeds.length == 0 && $a('#content').size > 0 && ($a('#content').height() + wrapper + footerheight) < $a(window).height())) 
  {	 

  	updateFooter("abs");  	
  }
  else if (($a('#homepage').size() > 0 && embeds.length == 0)){
  	updateFooter("static"); 
  }  
  else if (embeds.length > 0 && totalPageHeight < windowheight|| embeds.length == 0 && (totalPageHeight < windowheight))  
  {
	updateFooter("abs");
  }
  else if (embeds.length > 0 && totalPageHeight > windowheight || embeds.length == 0 && totalPageHeight > windowheight){
  
	updateFooter("static");	
  }     
}


// JavaScript Document




/* Copyright (c) 2006 Brandon Aaron (http://brandonaaron.net)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) 
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 *
 * $LastChangedDate: 2007-07-21 18:44:59 -0500 (Sat, 21 Jul 2007) $
 * $Rev: 2446 $
 *
 * Version 2.1.1
 */

(function($){

$.fn.bgIframe = $.fn.bgiframe = function(s) {
	// This is only for IE6
	if ( $.browser.msie && /6.0/.test(navigator.userAgent) ) {
		s = $.extend({
			top     : 'auto', // auto == .currentStyle.borderTopWidth
			left    : 'auto', // auto == .currentStyle.borderLeftWidth
			width   : 'auto', // auto == offsetWidth
			height  : 'auto', // auto == offsetHeight
			opacity : true,
			src     : 'javascript:false;'
		}, s || {});
		var prop = function(n){return n&&n.constructor==Number?n+'px':n;},
		    html = '<iframe class="bgiframe"frameborder="0"tabindex="-1"src="'+s.src+'"'+
		               'style="display:block;position:absolute;z-index:-1;'+
			               (s.opacity !== false?'filter:Alpha(Opacity=\'0\');':'')+
					       'top:'+(s.top=='auto'?'expression(((parseInt(this.parentNode.currentStyle.borderTopWidth)||0)*-1)+\'px\')':prop(s.top))+';'+
					       'left:'+(s.left=='auto'?'expression(((parseInt(this.parentNode.currentStyle.borderLeftWidth)||0)*-1)+\'px\')':prop(s.left))+';'+
					       'width:'+(s.width=='auto'?'expression(this.parentNode.offsetWidth+\'px\')':prop(s.width))+';'+
					       'height:'+(s.height=='auto'?'expression(this.parentNode.offsetHeight+\'px\')':prop(s.height))+';'+
					'"/>';
		return this.each(function() {
			if ( $('> iframe.bgiframe', this).length == 0 )
				this.insertBefore( document.createElement(html), this.firstChild );
		});
	}
	return this;
};

})($a);

function browserDetect(){
	var $browser = $a.browser;		
	if($a.browser.msie){
		if($a.browser.version == '6.0'){
			return "ie6";
		}
		if($a.browser.version == '7.0'){
			return 'ie7';
		}
		if($a.browser.version == '8.0'){
			return 'ie8';
		}		
	}
	else if($a.browser.mozilla){
		var ver = $a.browser.version.toString().substr(0,3);
		if(ver < "1.8"){
			return "ff1";
		}
		else if(ver == 1.8 ){
			return "ff2";
		}
		else if(ver == 1.9 ){
			return "ff3";				
		}		
	}
	else if($a.browser.safari){
		return 'safari';
	}
	else if($a.browser.opera){
		return 'opera';
	}			
}	

