$(document).ready(function(){

	/* SUGGESTIVE SEARCH start ***********************************************************/
	var $searchbox = $('input#searchstring');
	var $suggestions = $('div#search_suggestions');
	var $searchform = $('form#searchform');

	$searchbox.bind('keyup', function(){
		if($.trim($searchbox.val()) != '')
		{
			$.post(
				'/search/ajax.cfm',
				{ searchstring : $searchbox.val() },
				function(data){
					$suggestions
						.html(data)
						.show()
						.find('div.suggestion')
							.bind('click', function(){
								var $this = $(this);
								$suggestions.hide();
								$searchbox.val($this.text());
								$searchform.submit();
							});
				}
			);
		}
		else
		{
			$suggestions.html('').hide();
		}
	});

	
	/* EXTERNAL LINKS start ***********************************************************/
	$('a[rel="external"]').click(function(){
		this.target = "_blank";
	});	
	/* EXTERNAL LINKS end *************************************************************/
	
	/* CAROUSEL ITEMS */
	 if($("#carousel-items .scroll").length >0){
    	$("#carousel-items .scroll").jCarouselLite({ btnNext: ".down", btnPrev: ".up", vertical:true, mouseWheel: true, speed: 1000, circular: true, visible: 4, scroll: 3});	
	 }
	$('#carousel-items .nav ul li a').click(function(){
		$('#carousel-items .nav ul li').removeClass('active');
		$('#carousel-items .display p.active').addClass('last-active').removeClass('active');
		
		$display = $($(this).attr('href'));
		$display.css({opacity: 0.0})
			.addClass('active')
			.animate({opacity: 1.0}, 400, function() {
			$('#carousel-items .display p').removeClass('last-active');
		});
			$(this).parent().addClass('active');
		return false;
	});
	/* CAROUSEL ITEMS */
	
	
	/* SLIDESHOW start ***************************************************************/
	setInterval( "slideSwitch()", 5000 );
	/* SLIDESHOW end *****************************************************************/

	/*SEARCH*/
	$('#search input.text').focus(function(){	if(this.value=='Keyword') {	$(this).val('');} });
	$('#search input.text').blur(function(){ if(this.value =='') {	$(this).val('Keyword');}	});
	/*SEARCH*/
	
	/* NAVIGATION start ***************************************************************/
	$('#nav ul > li.level1 > ul').prepend('<li class="top first"></li>');
	$('#nav ul ul ul').prepend('<li class="top"></li>');
	$('#nav ul ul').append('<li class="bottom"></li>');
	$('#nav ul ul').hide();
	//hover show next level
	$('#nav ul > li').hover(function() { $('ul:first', this).show(); $('a:first',this).addClass('hover'); },function() {$('ul:first', this).hide(); $('a:first',this).removeClass('hover'); });
	//add class for flyouts
	if ($('#nav ul ul ul').length > 0) { $('#nav ul ul ul').prev().addClass('flyout'); }
	
	$('#nav li.level1:first').addClass('first');
	$('#nav li.level1:last,#nav-cart li:last').addClass('last');
	/* NAVIGATION end ****************************************************************/
	
	
	/*RELATED ITEMS*/
	 if($("#related .scroll").length >0){
    	$("#related .scroll").jCarouselLite({ btnNext: ".next", btnPrev: ".prev", mouseWheel: true, speed: 1000, circular: true, visible: 5, scroll: 4});	
	 }
	/*RELATED ITEMS*/
/*
	$("#brands").jCarouselLite({
		auto: 2500,
		visible: 1,
		circular: true
	});
*/
		
}); //close document.ready

/* sIFR RGB conversion function start **********************************************/
function RGBstring(str) {
	str1 = str.replace("#","");
	str2 = str1.replace("rgb(","");
	str2 = str2.replace(")","");
	str2 = str2.split(",");
	if(navigator.appName == "Microsoft Internet Explorer"){ return str1; }
	else { return toHex(str2[0])+toHex(str2[1])+toHex(str2[2]); }
}
function toHex(N) {
 if (N==null) return "01";
 N=parseInt(N); if (N==0 || isNaN(N)) return "00";
 N=Math.max(0,N); N=Math.min(N,255); N=Math.round(N);
 return "0123456789ABCDEF".charAt((N-N%16)/16)
      + "0123456789ABCDEF".charAt(N%16);
}
/* sIFR RGB conversion function end *************************************************/

/* SLIDESHOW function start *********************************************************/
function slideSwitch() {
	var $active = $('#slideshow span.active');

	if ( $active.length == 0 ) $active = $('#slideshow span:last');

	var $next =  $active.next('span').length ? $active.next()
			: $('#slideshow span:first');

	$active.addClass('last-active');
	
	$next.css({opacity: 0.0})
			.addClass('active')
			.animate({opacity: 1.0}, 500, function() {
			 $active.removeClass('active last-active');
	});
	
}
/* SLIDESHOW function end ***********************************************************/


/*ADD TO CART*/
function addToCart(formID,internalID) {
	$('.output').fadeOut('').html('');
	$("#bSubmitButton_"+internalID).attr('disabled',true).html('').addClass('loading');

	$.post("/checkout/basket_includes.cfm", $('#'+formID).serialize(),function(data,status) {
		//$("#basket-contents").load("/includes/nav/basket-contents.cfm",{box_cart_show: 1});
		$("#bSubmitButton_"+internalID).attr('disabled',false).removeClass('loading').html('<span class="button"><span>Add To Cart</span></span>');
		$("#output_"+internalID).fadeIn().html('<p class="success-sm">Item was successfully added to your cart. <a class="button button-sm" href="/checkout/basket.cfm"><span>View Cart</span></a></p>');
	});
	return false;
}
/*ADD TO CART*/

/* QUICK VIEW DETAILS */
function quickDetails(internalID){
	
	var _docHeight = (document.height !== undefined) ? document.height : document.body.offsetHeight;
	var _docWidth = (document.width !== undefined) ? document.width : document.body.offsetWidth;
	
	$('body').prepend('<div id="popup-bg"></div><div id="quick-details"></div>');

	//centering 
	$("#quick-details").css({ "top": getYX("Y")+20,	"left": (document.documentElement.clientWidth/2)-($("#quick-details").width()/2) });
	$("#popup-bg").css({ width:$('html').width(),height: getYX('Y'),opacity:0.5  });
	
	$("#quick-details").addClass('loading');
	$("#quick-details").load("/detail/view-quick-details.cfm?quickDetails=1&nPID="+internalID,function(){	
		$("#quick-details").removeClass('loading');
		$('#popup-bg').click(function(){ popUpClose(); });
		$('#quick-details .close').click(function(){ popUpClose(); });
	});
	$("#popup-bg").css({ width:$('html').width(),height: _docHeight,opacity:0.5  });
	return false;
	
}
/* QUICK VIEW DETAILS */

function popUpClose(){
	$('#popup-bg').fadeOut();
	$('#popup-bg').next().fadeOut().remove();
	return false;
}

function detailTab(displayBlock){
	$('.tab-block').removeClass('active');
	$('.tab').removeClass('active');
	$('#'+displayBlock+'-tab').addClass('active');
	$('#'+displayBlock).addClass('active');
	$('.tab-blocks').css({ "height": $('.tab-blocks .active').height()+50 }); //keep overflow visible
}

function galleryPopup(id,width,height){
	var image = $('#'+id).attr('src');
	var description = $('#'+id).attr('title');
	$('body').prepend('<div id="popup-bg"></div><div id="gallery-image"><a class="close" onclick="popUpClose();">close [X]</a><img src="'+image+'" width="'+width+'" height="'+height+'"><p>'+description+'</p></div>');

	$("#popup-bg").css({ width:$('html').width(),height: $('html').height(),opacity:0.5  });
	$("#gallery-image").css({ "top": getYX("Y")+40,	"left": (document.documentElement.clientWidth/2)-($("#gallery-image").width()/2) });
	$('#popup-bg').click(function(){ popUpClose(); });
	$('#gallery-image .close').click(function(){ popUpClose(); });
	return false;
}

function getYX(coord){
	var scrOfX = 0, scrOfY = 0;
  if( typeof( window.pageYOffset ) == 'number' ) {
    //Netscape compliant
    scrOfY = window.pageYOffset;
    scrOfX = window.pageXOffset;
  } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
    //DOM compliant
    scrOfY = document.body.scrollTop;
    scrOfX = document.body.scrollLeft;
  } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
    //IE6 standards compliant mode
    scrOfY = document.documentElement.scrollTop;
    scrOfX = document.documentElement.scrollLeft;
  }
	if(coord=="X"){
		return scrOfX;
	}
	else if(coord=="Y"){
		return scrOfY;
	}
}

function errorInputText(id,str){
	if(!id.hasClass('error-display')){ //prevent multiple error displays on same element
		id.addClass('error-display'); //prevent displaying error twice
		id.parent().append('<span class="error"><span>'+ str +'</span></span>');
		
	}
	if(!window.focused){ id.focus(); window.focused = true; } //focused on first error
	return true;
}

/*VALIDATE FORM*/
function validateForm(nonempty,matches,select_nonempty,checkbox,valid_email){
	$('.error').remove();
	$('input,select,textarea').removeClass('error-display'); //prevent multiple error displays on same element
	 window.focused = false; //remove true
	var errors = false;
	//validate nonempty fields
	if(nonempty !=''){
		var nonempty_array = nonempty.split( "," );
		for( var i=0; i < nonempty_array.length; i++ ){
			var nonempty_set = nonempty_array[i].split( ":" );
			if( $('#'+nonempty_set[0]).val().length < nonempty_set[1] ){
				errors = errorInputText($('#'+nonempty_set[0]),$('#'+nonempty_set[0]).attr('title') +' must be at least '+ nonempty_set[1] +' characters');
			}
		}
	}
	
	//validate matching fields
	if(matches !=''){
		var matches_array = matches.split( "," );
		for( var j=0; j < matches_array.length; j++ ){
			var matches_pair = matches_array[j].split( ":" );
			if($('#'+matches_pair[0]).val() != $('#'+matches_pair[1]).val()){
				errors = errorInputText($('#'+matches_pair[1]),$('#'+matches_pair[1]).attr('title') +' did not match '+ $('#'+matches_pair[0]).attr('title'));
			}		
		}
	}
	
	//validate matching fields
	if(select_nonempty !=''){
		var select_nonempty_array = select_nonempty.split( "," );
		for( var k=0; k < select_nonempty_array.length; k++ ){
			if( $('#'+select_nonempty_array[k]).val() ==''){
				errors = errorInputText($('#'+select_nonempty_array[k]),$('#'+select_nonempty_array[k]).attr('title') +' must be selected</span>');
			}
		}
	}
	if(checkbox !=''){
		var checkbox_array = checkbox.split( "," );
		for( var l=0; l < checkbox_array.length; l++ ){
			if( $('#'+checkbox_array[l]).is(":not(:checked)")){
				errors = errorInputText($('#'+checkbox_array[l]),$('#'+checkbox_array[l]).attr('title') +' must be checked to continue');
			}
		}		
	}
	//validate email address
	if(valid_email !=''){
		var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);  
		if(!pattern.test( $('#'+valid_email).val() )){
			errors = errorInputText($('#'+valid_email),$('#'+valid_email).attr('title') +' is not valid');
		}  
	}
	if(errors){	return false; } 
	else {return true; }
}
/*VALIDATE FORM*/

function validateFormShipping(nonempty,matches,select_nonempty,checkbox,valid_email) {
  var errors = false;
  var noerrors = false;
	noerrors = validateForm(nonempty,matches,select_nonempty,checkbox,valid_email);
	
	if(noerrors) { //first validation cycle came back positive;
		var errorStartPos = 0;
		var intlCountry = 0;
		
		var countrySelected = $("#CountryID").val();			
		if (countrySelected != 'US' && countrySelected != 'CA' && countrySelected != 'AU') {
			intlCountry = 1;
		}
		
		// validate state, select menu as well as intl state text box
		if (($("#StatePU").val().length < 1) && ($("#StateTX").val().length < 1)) {

			if (intlCountry == 1) {
				errorInputText($('#StateTX'),'Please enter your State');
				errors = true;
			}
			else {						
				errorInputText($('#StatePU'),'Please select your State');
				errors = true;
				if (countrySelected == 'US') {
					$("#stShipUS").attr('selected',true);
					$("#StateTX").val('');
				}
				else if (countrySelected == 'CA') {
					$("#stShipCA").attr('selected',true);
					$("#StateTX").val('');
				}
				else if (countrySelected == 'AU') {
					$("#stShipAU").attr('selected',true);
					$("#StateTX").val('');
				}
			}
		}
		
		//validate if us state selected, country is United States
		if ( ($("#StatePU").val().length == 2) && (countrySelected != 'US' && countrySelected != 'CA') ) {
			if ($("#StateTX").val().length < 1) {
				errorInputText($('#StateTX'),'You have selected a North American State but an International Country');
				errors = true;
				$("#stShipIntl").attr('selected',true);
			}
		}
		// validate 2 char state is selected from state select menu for Country US
		if (countrySelected == 'US' && $("#StatePU").val().length != 2) {
			errorInputText($('#StatePU'),'Please select a valid US State');
			errors = true;
			$("#stShipUS").attr('selected',true);
			$("#StateTX").val('');
		}
		else if (countrySelected == 'CA' && $("#StatePU").val().length != 2) {
			errorInputText($('#StatePU'),'Please select a valid Canadian State');
			errors = true;
			$("#stShipCA").attr('selected',true);
			$("#StateTX").val('');
		}
}
else{errors = true}; //errors returned from validateForm() check

if (errors) {	return false;	}
else { return true; }

}
function validateFormBilling(nonempty,matches,select_nonempty,checkbox,valid_email) {
  	var errors = false;
  	var noerrors = false;
	noerrors = validateForm(nonempty,matches,select_nonempty,checkbox,valid_email);
	
	if(noerrors) { //first validation cycle came back positive;
		var errorStartPos = 0;

	  // check for a shipping selection if appropriate
	  /*
	  var shipSelectionArray = getElementById("rShipSelection");
	  if (shipSelectionArray && getElementById("rShipSelection").length >= 1) {
		  for (i=0;i<document.fBilling.rShipSelection.length;i++) {
				if (document.fBilling.rShipSelection[i].checked) {
					shippingSelection = document.fBilling.rShipSelection[i].value;
					if (!shippingSelection) {
						errorAlert += "- Please make a shipping selection before continuing\n";
					}
				}
		  }
	  }
	  */
	}
}