/* 
 * Create global 'sdg' object - this is the only global object we create.
 * All other functions and objects should be apart of this.
 */

if(!window.sdg){
  sdg = {};
}


/*
 * Reassign the core jQuery object to avoid any
 * future conflicts with other javascript libraries.
 */
 
$sd = jQuery.noConflict();

$sd(function(){

	/*
	 * Get the height of the topNav element and apply that value to its
	 * children - to straighten out mixed height navigation elements without
	 * messing up the dynamic menu display
	 */

	var navigationContainerHeight = $sd('#topNav').height() - 7;
	var navigation_DOM = $sd('#topNav li');
	
	navigation_DOM.find('a').height(navigationContainerHeight);
	navigation_DOM.find('.subNav li a').removeAttr('style');
	
	if ($sd.browser.mozilla) {
		var stringToTest = navigator.userAgent.toLowerCase();
		var patternToMatch = new RegExp('mac');
		var isMac = patternToMatch.test(stringToTest);
		if (isMac) {
			navigation_DOM.find('a').css('letter-spacing', '-0.007em');
		}
	}

	/*
	 * IE6 bgd image caching fix (#4341)
	 */

	if ($sd.browser.msie && parseInt($sd.browser.version) == 6){
		try {
			document.execCommand("BackgroundImageCache",false,true);
		} catch(err) {}
	}

	/*
	 * Check to see if there's only default text in the search box
	 * and apply a class if so.
	 */

	if ($sd('#headerContent form input[type=text]').val() == 'Search or enter catalogue number'){
	    if (!$sd('#headerContent form input[type=text]').hasClass('empty')){
	        $sd('#headerContent form input[type=text]').addClass('empty');
	    }
	}
	
	
	/*
	 * Setup functions to add/remove the 'empty' class as a user
	 * adds or removes text in the box.
	 */

	$sd('#headerContent form input[type=text]').focus(function(){
	    if ($sd(this).val() == 'Search or enter catalogue number'){
	        $sd(this).val('');
	        $sd(this).toggleClass('empty');
	    }
	});

	$sd('#headerContent form input[type=text]').blur(function(){
	    if ($sd(this).val() == ''){
	        $sd(this).toggleClass('empty');
	        $sd(this).val('Search or enter catalogue number');
	    }
	});
	
	
	/*
	 * Display a validation message if there are any invalid (non-word)
	 * characters in the search terms or the search terms were empty
	 */
	
	$sd('#keywordSearchForm').submit(function(){
		var searchValue = $sd('#keywordSearchForm input[type=text]').val();
        var spaces = / /gi;
        var truncatedSearchValue = searchValue.replace(spaces,"");
		if ($sd('#keywordSearchForm input[type=text]').val() == 'Search or enter catalogue number' || truncatedSearchValue == '') {
			alert('You must enter a search description, please try again!');
			return false;
		}        

		if ($sd('#keywordSearchForm input[type=text]').val().match(/[^-& \w]/)) {
			alert('Your search contains illegal characters');
			return false;
		}
	});


	/*
	 * Check to see if there's only default text in the newsletter
	 * subscription box and apply a class if so.
	 */

	if ($sd('#footer form input[type=text]').val() == 'Enter e-mail address'){
	    if (!$sd('#footer form input[type=text]').hasClass('empty')){
	        $sd('#footer form input[type=text]').addClass('empty');
	    }
	}


	/*
	 * Setup functions to add/remove the 'empty' class as a user
	 * adds or removes text in the box.
	 */

	$sd('#footer form input[type=text]').focus(function(){
	    if ($sd(this).val() == 'Enter e-mail address'){
	        $sd(this).val('');
	        $sd(this).toggleClass('empty');
	    }
	});

	$sd('#footer form input[type=text]').blur(function(){
	    if ($sd(this).val() == ''){
	        $sd(this).toggleClass('empty');
	        $sd(this).val('Enter e-mail address');
	    }
	});
	
	
	/*
	 * For any popup windows which have a close button we
	 * add an event to try and close the window.
	 */

	$sd('.actions .close').click(function(){
		window.close();
	});


	/*
	 * Work out how wide the dropdown needs to be. Basically
	 * it just works out the widths of the columns and adds
	 * them all together.
	 */

	$sd("#topNav .subNav").each(function(){
		var totalColWidth = 0;

		$sd(this).css({
			left: '-9999px',
			display: 'block'
		});
		
		$sd(this).find('div .col').each(function(i, e){
			width = $sd(e).width();

			if (width > 150) {
				width = 150;
			}
			
			$sd(e).width(width);
			
			totalColWidth += width + 24;
		});
		
		$sd(this).css({
			left: '0',
			display: 'none'
		});

		$sd(this).children('div').width(totalColWidth);
	});
	
	
	/*
	 * Adds an on click function to all elements with a logoffLink class
	 * 
	 */
	
	$sd('.logoffLink').live('click',function(){
		$sd('#headerContent ul #logoffButton').click();
		return false;
	});
	
	/*
	 * If the customer has auto-logged on and wants to be fully logged off.
	 * 
	 */
	
	$sd('#forgetMeLink').click(function(){
		$sd('#forgetMeButton').click();
		return false;
	});


	/*
	 * Show the sub-menu on hover.
	 */

	var subnavtimer;
	
	$sd("#topNav > li").hover(
	    function(){

			var el = this;

			/*
			 * We set a timeout because there should be a delay
			 * before showing the menu to stop it becoming annoying
			 * to the user.
			 */

			subnavtimer = setTimeout(function() {

		        $sd(el).children('.subNav').each(function() {

		        	$sd(el).addClass('hover');

					var margin = ($sd('#header').width() - ($sd(this).width() + $sd(el).position().left)) + 1;

					if(margin < 0) {
						$sd(this).css('margin-left', margin + 'px');
					}				

					$sd(this).css('top', ($sd(el).height() + 1) + 'px');
					$sd(this).show();


					/*
					 * IE doesn't implement z-index functionality correctly so
					 * we need to hack it for the one instance where this matters.
					 * (It's on the product detail page - the back/next/previous)
					 */

					if($sd.browser.msie) {

						if ($sd('#productsNav').length) {

							var navPos = ($sd('#productsNav').position().top);

							$sd('#productsNav').data('position', { 
								right: $sd('#productsNav').css('right'), 
								top: $sd('#productsNav').css('top') 
							});

							$sd('#header').append($sd('#productsNav'));
							$sd('#productsNav').css({ top: $sd('#header').outerHeight()+navPos, right: '6px' });
						}

						$sd('#header').css('z-index', '1');

						
						/*
						 * For IE6 we need to stick an IFRAME behind the menu
						 * so that select boxes and Flash don't show through.
						 */

						if (parseInt($sd.browser.version) == 6) {
							
							if ($sd(this).height()) {
								$sd(this).prepend(
									'<iframe src="#none" style="position:absolute; z-index:-1;">' +
									'&nbsp;' + 
									'</iframe>'
								);
							}

							$sd(this).children('iframe').css({
								display: 'block',
								top: 0,
								height: $sd(this).height() + 'px',
								width: ($sd(this).width() + 1) + 'px',
								margin: '0 0 0 -1px'
							});
						}
					}
				});
			}, 700);	       
	    },
	    function(){

	    	/*
	    	 * If the user has hovered off the menu then we want
	    	 * to cancel the setTimeout call otherwise we'll still
	    	 * see the menu.
	    	 */

	    	clearTimeout(subnavtimer);

	    	//$sd(this).children('iframe').remove();
	        //$sd(this).children('.subNav').hide();
			
	        $sd(this).removeClass('hover');
			
	        /*
	         * Revert the changes to the product nav
	         * that we made for IE on hover.
	         */

	        if ($sd.browser.msie) {
				
				if ($sd('#productsNav').length) {
					$sd('#productDetails').prepend($sd('#productsNav'));
					$sd('#productsNav').css($sd('#productsNav').data('position'));
				}

				$sd('#header').css('z-index', '0');
			}
	    }
	);
});


/*
 * Cause an element to blink.
 *
 * @param int start 
 */
 
jQuery.fn.blink = function(numBlinks) { 

	start = 1;
	finish = numBlinks;

	var doBlink = function(obj, start, finish) { 
		$sd(obj).fadeOut(200).fadeIn(200); 
		if(start!=finish) {
			start=start+1;
			doBlink(obj,start,finish); 
		} 
	} 

	return this.each(
		function() { 
			doBlink(this,start,finish) 
		}
	); 
}


/*
 * Launch a popup
 * Launch a window with the given height and width
 * and center it on the screen.
 *
 *  - url: the page to launch
 *  - name: the unique name for the window
 *  - height: the height of the window in pixels
 *  - width: the width of the window in pixels
 */

sdg.launchPopup = function(url, width, height, extras) {
	window.open(
		url, 
		null, 
		(extras ? extras : 'location=no,scrollbars=yes') + 
		',width=' + width +  
		',height=' + height + 
		',left=' + (screen.width / 2 - width / 2) + 
		',top=' + Math.abs((screen.height / 2 - height / 2) - 40)
	);
	
	return false;
}



sdg.limitChars = function(textObj, limit) {
	var text = textObj.val();
	var textlength = text.length;
	if (textlength > limit) {
		alert('This field cannot exceed ' + limit + ' characters');
		textObj.val(text.substr(0, limit));
		return false;
	} else {
		return true;
	}

}


sdg.hoverInfo = function(trigger, content) {

	offset = trigger.offset();

	$sd('body').append(content);

	content.css({
		position: 'absolute',
		left: '-9999px',
		display: 'block'
	});
	
	height = content.outerHeight();
	
	content.css({
		left: offset.left - 160,
		top: offset.top - height
	});
	
	content.mousemove(function(){
		clearTimeout(hoverInfoTimeout);
		
		hoverInfoTimeout = setTimeout(function(){
			content.hide();
		}, 1500);
	});
	
	hoverInfoTimeout = setTimeout(function(){
		content.hide();
	}, 5000);
}

function CountText(field, countField, maxLimit) {
	if (field.value.length > maxLimit)
	field.value = field.value.substring(0, maxLimit);
	else 
	countField.value = maxLimit - field.value.length;
}

