//Global JavaScript Document

/********************************

	Notes:
		+ I rely on JQuery v1.4.2
		+ Trying v1.4.2 - keep your fingers crossed

********************************/

// Global variables
var menuSpeed = 150; //menu animation speed in milliseconds
var menuSpeedMedium = 350; //menu animation speed in milliseconds
var menuSpeedSlow = 550; //menu animation speed in milliseconds
var hideDelay = 500; //delay to hide menus in milliseconds

var productSearchText = 'Enter Keyword / SKU'; //search input placeholder text

// Fix JS flash of unstyled content by hiding all descendents of HTML until DOM is loaded.
// Check for class of "no-position-fix" on HTML element. If present, we don't run this.
if(!jQuery('html.no-position-fix').length) {
	jQuery('html').addClass('js');
}

// Prevent console commands from throwing errors in IE
try { console.log('init console... done'); } catch(e) { console = { log: function() {} }; }

// Global variable assignment
function setGlobals() {
}

function initGatewayStyle(){
	$('ul.clLanguages').each(function(){
		var $list = $(this);
		var $items = $list.children('li');
		var size = (($items.size())-1);
		var $first = $($items[0]);
		var $last = $($items[size]);		
		$first.css("padding-left","0px");
		$last.css("border","none");	
	});
}

// Reset func for standard button elements
function resetForm(form) {
	$(form).find(':input').each(function() {
		switch(this.type) {
		  case 'password':
		  case 'select-multiple':
		  case 'select-one':
		  case 'text':
		  case 'textarea':
	      $(this).val('');
		    break;
		  case 'checkbox':
		  case 'radio':
			  this.checked = false;
		}
	});
}

// Setup structure for CSS buttons
function initButtons() {
	$('.button').each(function(){if ($('.buttonInner', this).length){} else {$(this).wrapInner('<span class="buttonInner" />');}});
}

// Setup structure for content modules
function initModules() {
	$('.module').wrapInner('<div class="moduleInner" />')
	.append('<div class="moduleBottom" />');
}

// Function to open PDFs in a new window
function pdfLinks() {
	$('a[href$=".pdf"]').click(function(){
		window.open(this.href);
		return false;
	});
}

// Add classes to form inputs for css use
function addFormClasses() {
	if(jQuery('input').length) {
		jQuery('input').each(function(){
			jQuery(this).addClass(this.type);
		});
	}
}

function initMenus() {

	$('#mainNav > li').each(function(){
		
		//set variables to reference main nav link and subnav menu so that we only traverse the DOM once
		var $trigger = $('> .mainNavItem', this);
		var $menu = $('> ul.subnav', this);
		
	
		//alert($menu.length);
		
		if($menu.length > 0) { //test if subnav menu exists for this item
		
			//declare variables to track menu status and timer for menu closing
			var menuHideTimer = null;
			var isAnimating = false;
			var isShown = false;
			
			var menuHeight = $menu.height();
			
			$menu.hide();
		
			$([$trigger.get(0), $menu.get(0)]).hover(
				function() {
				
					if (menuHideTimer) clearTimeout(menuHideTimer);
					
					if (isAnimating || isShown) {
						// don't trigger the animation again
						return;
					} else {
						// reset position of info box
						isAnimating = true;
						
						var delay = 100; // variable to stagger fade of menu links

						$trigger.addClass('hover');
						$('a', $menu).css({ opacity: 0 });
						$menu
						.css({
							height: '0px'
						}).show()
						.animate({
							height: menuHeight
						}, 250, 'easeOutQuad', function() {
							isAnimating = false;
							isShown = true;
							
						});

						$('a', $menu).each(function(){
							$(this).animate({
								opacity: 0
							}, delay);
							$(this).animate({
								opacity: 1
							}, 200);
							
							delay += 50;
						});

					}

					return false;
					
				},
				function(){
				
					if (menuHideTimer) clearTimeout(menuHideTimer);
					
					menuHideTimer = setTimeout(function () {
						menuHideTimer = null;
						$menu.animate(
							{ 
								height: '0px'
							}, 
							menuSpeed, 
							function () {
								$menu.hide();
								isShown = false;
								$trigger.removeClass('hover');							
							});
					}, hideDelay);

					return false;
				}
			
			);
		}
		
	});
	
	// $('#mainNavProducts > a').click(function(){ return true; });
	
}


function trim(str) {
	if (str == null || str == undefined) return str;
	return str.replace(/^\s+|\s+$/g, '');	
}

function getParms(parmString) {
	return getParms(parmString, null);
}
function getParms(parmString, optionalToArray) {
    var ret = optionalToArray;
    if (ret == null || ret == undefined) {
    	ret = new Array();
    }
    if (parmString == null || (parmString = trim(parmString)) == '') {
    	return ret;
    }
    if (parmString.charAt(0) == '#' || parmString.charAt(0) == '?') parmString = trim(parmString.substring(1));
    if (parmString == '') {
    	return ret;
    }
    var args = parmString.split('&');
    var parts;
    var value;
    for(var i=0;i<args.length;i++) {
    	parts = args[i].split('=');
    	if (parts.length > 0 && (parts[0] = trim(parts[0])) != '') {
	    	value = null;
	    	if (parts.length > 1) {
	    		value = trim(parts[1]);
	    	}
	    	ret[parts[0]] = value;
    	}
    }
    return ret;
}
function makeParmString(parmArray) {
	var ret = '';
	var first = true;
	for(var i in parmArray) {
		if (parmArray[i] != undefined) {
			if (first) {
				first = false;
			} else {
				ret = ret + '&';
			}
			ret = ret + i + (parmArray[i] == null ? '' : '=' + parmArray[i]);
		}
	}
	return ret;
}
function mergeParms(parmString1, parmString2) {
	return makeParmString(getParms(parmString2, getParms(parmString1)));
}
function removeMatchingParms(parmString, removeString) {
	var parms = getParms(parmString);
	var remove = getParms(removeString);
	for(var i in remove) {
		if (trim(parms[i]) == trim(remove[i])) {
			parms[i] = undefined;
		}
	}
	return makeParmString(parms);
}

function searchFocus() {
	var $searchBox = $('#mainSearchBox');
	var searchValue = $.url.param("query");
	
	if(!searchValue)
		searchValue = 'Enter Keyword/SKU'; 
	else
		searchValue = decodeURIComponent(replacePluses(searchValue));
	$searchBox.attr('value',searchValue).css('color', '#999');
	$searchBox.blur(function() {
		searchValue = $searchBox.attr('value');
		searchHasValue(searchValue) == true ? $(this).css('color', '#525D58') : $(this).attr('value', 'Enter Keyword/SKU').css('color', '#999');
	});
	$searchBox.focus(function() {
		searchValue = $searchBox.attr('value');
		searchHasValue(searchValue) == false ? $(this).attr('value', '').css('color', '#525D58') : $(this).css('color', '#525D58');
	});
	
	$('#searchForm').submit(function(){
		
		//alert('start submit');
		
		var searchValue = $searchBox.val();
		
		//alert(searchValue);
		
		if( searchHasValue(searchValue) ) {
			
		} else {
			$searchBox.focus();
			return false;
		}	
	});	
}

function searchHasValue(myValue) {
	if (myValue == "" || myValue == "Enter Keyword/SKU") {
		return false;
	}else{
		return true;
	};
}

function setExtLinks() {
	$('.extLink').attr('target', '_blank');
}

function initCufon() {
	Cufon.replace('#featuresTab h2, #guideTab h2, #specsTab h2, #supportTab h2, #relatedAcc h2, .subContent h2, .graphicHeader h1, #contactBody h2, #descriptionTop h1, h3.breadcrumb, #topFAQs, #stillNeedHelp, #callUs, h4#emailUsLink, h1#BVQASummaryBoxTitleID, #picturesBody h2,#three60Body h2,#videosBody h2,#emailBody h1,#contactBody h1, h1.searchResultsHead, h1#selectCountry, h4#availableIn, .contentBlockDefault h2.avenirBlocks, h2.supportHeadings, h2.breadcrumbSupport, h3.breadcrumbSupport, h3.supportHeadings, legend.cufonLegends', { fontFamily: 'Avenir Medium' });
	Cufon.replace('p#thumbnailSizeText, span.menuTitle, #tabAnchors li, .thumbBoxSmall p.thumbDiscontinued, .graphicHeader h2, .thumbBoxLarge p.thumbDiscontinued, .resultBox .resultDiscontinued, #description span#discontinuedText, #tabLinks li a, p.footerSubText', { fontFamily: 'Avenir Heavy', hover: true});
	
	Cufon.replace('#shareLinks li a, #countryTitle', { fontFamily: 'Avenir Black', hover: true, lineHeight: '30px'});
	Cufon.replace('legend.cufonLegends, a.button .buttonInner, label.buttonInner', { fontFamily: 'Avenir Black', textShadow: '#300 1px 1px 1px', hover: true});
	Cufon.replace('#mainNav .mainNavItem', { fontFamily: 'Avenir Black', textShadow: '#300 1px 1px 1px', hover: true});
	// Global Gateway Selectors Below
	Cufon.replace('span.clName.regularTextCufonMe', { fontFamily: 'Avenir Medium' });
	Cufon.replace('ul.clLanguages li a.regularTextCufonMe', { fontFamily: 'Avenir Heavy', hover: true});
}

function suppressIEThickbox(){
	if($('#linkEmail').length) {
		setTimeout(function(){
			if(!jQuery.support.hrefNormalized && parseInt(jQuery.browser.version, 10) < 8) {
				$('#linkEmail a').removeClass('thickbox').unbind().click(function(){
					window.open(this.href, 'emailPopup', 'width=660,height=610,resizable=yes,scrollbars=yes,status=no');
					return false;
				});
			}
		}, 500);
	}
}

function addPrintLink(){
		
	if(window.print){
		var $printLink = $('<a></a>').text('Print')
			.css({cursor:'pointer'}).click(function(e){
			window.print();
			e.preventDefault();
		});
	
		$('#linkPrint').append($printLink);
	}

}

function replacePluses(sIn){
	var sOut=sIn;
	while(sOut.indexOf("+")>=0)sOut=sOut.replace("+"," ");
	return sOut;
}

// Initialize JS functions
$(document).ready(function(){
	jQuery('html').removeClass('js');
	setGlobals();
	initGatewayStyle();
	initButtons();	
	initModules();
	pdfLinks();
	addFormClasses();
	initMenus();
	searchFocus();
	setExtLinks();
	initCufon();
	suppressIEThickbox();
	addPrintLink();
});
