//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($searchBox, searchText) {
	//var $searchBox = $('.searchBox');
	$searchBox.attr('value', searchText).css('color', '#888888');
	
	var searchValue = searchText;
	
	$searchBox.blur(function() {
		searchValue = $searchBox.attr('value');
		searchHasValue(searchValue, searchText) == true ? $(this).css('color', '#1B242A') : $(this).attr('value', searchText).css('color', '#888888');
	});
	$searchBox.focus(function() {
		searchValue = $searchBox.attr('value');
		searchHasValue(searchValue, searchText) == false ? $(this).attr('value', '').css('color', '#1B242A') : $(this).css('color', '#1B242A');
	});
}

function searchHasValue(myValue, searchText) {
	if (myValue == '' || myValue == searchText) {
		return false;
	}else{
		return true;
	};
}

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

function initCufon() {
}

function suppressIEThickbox(){
}

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

}

jQuery(function($) {
	jQuery('ul.dropdownMenu').hide();
	
	jQuery('div.dropdownTitle').click(function(){
		$(this).next().slideToggle("fast");
		return false;
	})
	jQuery('ul.dropdownMenu').click(function(){
		jQuery('ul.dropdownMenu').hide();
	})

	jQuery('div.dropdown').hover(function() {
		clearTimeout(jQuery.data(this,'timeout'));
	}, function() {
		jQuery.data(this,'timeout',setTimeout($.proxy(function() {
			jQuery('div.dropdown').find('>ul').slideUp('fast');
		}, this), 500));
	});
})


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