var widgetHeaderSearchProcessing = false;
var headerSearchWidgetimeoutId = null;
var headerSearchWidgeHidetimeoutId = null;
function doHeaderSearchWidgetDynamicSearch(){
	//console.log('doHeaderSearchWidgetDynamicSearch triggered');
	headerSearchWidgetimeoutId = null;
	searchTerm = document.getElementById('searchPhrase').value;
	if(!widgetHeaderSearchProcessing){
		widgetHeaderSearchProcessing = true;
		x_getProductSearchResult('', '', '', searchTerm, '', processHeaderSearchWidgetProductSearchResultResponse);
	}
}
function x_getProductSearchResult() {
	sajax_do_call("getProductSearchResult", x_getProductSearchResult.arguments);
}
function processHeaderSearchWidgetProductSearchResultResponse(response){
	//console.log('process response triggered');
	widgetHeaderSearchProcessing = false;
	responseArr = response.split('<_|_>');
	if(responseArr[0] == 'success'){
		//console.log('successfule response triggered');
		$('#headerSearchWidgetDynamicResults').show();
		responseArr.shift();
		$('#headerSearchWidgetDynamicResults').html(decodeURIComponent(responseArr.join('<br />')));
	}
}

function hideDynamicSearch() {
	if(headerSearchWidgeHidetimeoutId){
		clearTimeout(headerSearchWidgeHidetimeoutId);
		headerSearchWidgeHidetimeoutId = null;
	}
	$('#headerSearchWidgetDynamicResults').hide();
}


$(document).ready(function() {
	$('div#viewCart form, #clientAccount div.logout').css('display','block');
	$('#clientAccount input#orderSearch').parent('div').addClass('hideme').hide();
	var signUpField = $('input#signUpEmail');
	var signUpHelpText = 'email address';
	var searchHelpText = 'Keyword, Title, Author, ISBN';
	var searchField = $('input#searchPhrase');
	
	function undoHeaderSearchWidgetDynamicSearch(){
		//console.log('undo triggered');
		if(headerSearchWidgetimeoutId){
			clearTimeout(headerSearchWidgetimeoutId);
		}
		if(headerSearchWidgeHidetimeoutId){
			clearTimeout(headerSearchWidgeHidetimeoutId);
		}
		$('#headerSearchWidgetDynamicResults').hide();
	}
	
	$('input#searchPhrase').keyup(function() {
		//initiateHeaderSearchWidgetDynamicSearch()
		//console.log('keyup triggered');
		undoHeaderSearchWidgetDynamicSearch();
		if(searchField.val() == ''){
			return;
		}
		headerSearchWidgetimeoutId = setTimeout("doHeaderSearchWidgetDynamicSearch()", 300);
	}).blur(function(){
		headerSearchWidgeHidetimeoutId = setTimeout("hideDynamicSearch()", 500);
		
	});
	
	if (location.search.indexOf('m=search_results') >= 0) {
		var searchPhrase = location.search.split('&')[1].split('=')[1];
		// since spaces aren't escaped correctly, i have to replace the plus they turn into with a normal space
		searchPhrase = searchPhrase.replace(/\+/g, ' ');
		// i have to reverse the special character escaping that the form is doing
		searchPhrase = unescape(searchPhrase);
		searchField.val(searchPhrase);
	}
	
	//evaluate the search box value
	//add a class if it still has the default text
	function checkHelpText(thisField, thisHelpText) {
		if (thisField.val() == '' || thisField.val() == thisHelpText) {
			thisField.addClass('helpText').val(thisHelpText);
		} else {
			thisField.removeClass('helpText');
		}
	}

	checkHelpText(searchField, searchHelpText);
	checkHelpText(signUpField, signUpHelpText);
	
	//put the default text back in on blur, if null and add class
	searchField.blur(function() {
		checkHelpText(searchField, searchHelpText);
	});
	signUpField.blur(function() {
		checkHelpText(signUpField, signUpHelpText);
	});

	//remove class on focus and remove help text if its there
	searchField.focus(function() {
		$(this).removeClass('helpText');
		if ($(this).val() == searchHelpText) {
			$(this).val('');
		}
	});
	signUpField.focus(function() {
		$(this).removeClass('helpText');
		if ($(this).val() == signUpHelpText) {
			$(this).val('');
		}
	});
	
	//updating price for multi-format products cuz stock doesnt work too well
	/*$('div.personalizationContainer select').change(function() {
		var selection = $(this).find('option:selected');
		if(selection.val() != "" && selection.text().match(/\(Add\s([$\.0-9]+)\)/)){
			//console.log('yep');
			var optPrice = selection.text().replace(/.+\s\(Add\s([$\.0-9]+)\)/, "$1");
			//console.log('optPrice: '+optPrice);
			var curPrice = $('div#price');
			//console.log('curPrice: '+curPrice.text());
			if(optPrice != curPrice.text()){
				//console.log('forcing Change');
				curPrice.text(optPrice);
			}
		} else {
			//console.log('nope');
		}
	}); */
	
	
	//turning on product detail modules if they have content
	if ($('div#bundle div#productBundle').length > 0) {
		var bundleImgs = $('div#bundle div#bundlePhotos td.bundlePhoto');
		var guts = '';
		bundleImgs.each(function(index, element) {
			guts += '<td class="bundlePhoto">'+$(this).html()+'</td>';
		});
		$('div#bundlePhotos').html('<table cellspacing="0" cellpadding="0"><tbody><tr>'+guts+'</tr></tbody></table>').find('td.bundlePhoto:first-child').addClass('first');
		$('div#bundlePrice div.batchAddToCartButton').addClass('addToCartBtn').find('a').addClass('sublink');
		$('div#bundle').show();
	}
	
	
	//cleaning up customer reviews
	var reviewDivs = $('div#productReviews form > div.body');
	reviewDivs.addClass('review');
	reviewDivs.first().removeClass('review').attr('id','overallRating');
	reviewDivs.last().removeClass('review').attr('id','addReviewLink');
	var reviews = $('div#productReviews div.review');
	var reviewCount = reviews.length;
	var reviewString = "";
	if (reviewCount == 1) {
		reviewString = reviewCount+" review";
	} else {
		reviewString = reviewCount+" reviews";
	}
	
	if (reviewCount > 0) {
		reviews.each(function (i) {
			var myName = $(this).find('div.form-label:contains("Name") + div.form-field').text();
			var myDate = $(this).find('div.form-label:contains("Date") + div.form-field').text();
			var myRating = $(this).find('div.form-label:contains("Rating") + div.form-field img').attr('src');
			var myCopy = $(this).find('div.form-label:contains("Review") + div.form-field').html();
			var newStuff = '<div class="reviewerInfo"><p class="name">'+myName+'</p><p class="date weak">'+myDate+'</p><p class="rating"><img src="'+myRating+'"/></p></div><p class="reviewBody">'+myCopy+'</p>';
			$(this).html(newStuff);
		});
	
		if ($('div#overallRating').length > 0) {
			$('div#overallRating div div.form-field').prepend('<span>Average Rating:</span>').append('<span class="reviewsCount">('+reviewString+')</span>');
			var oarImg = $('div#overallRating img').attr('src');
			var overallRatingLink = '<div id="overallRatingLink"><img src="'+oarImg+'"/>&nbsp;<a href="#reviews">'+reviewString+'</a></div>';
			$('div#productDetails').append(overallRatingLink);
		}
	}
	$('div#addReviewLink a, div#productReviewsAddNote a, div#productReviewsAdd div.hdr-title-text').text('Write a review');
	
	$('div#addReviewLink a').click(function() {
		$('div#addReviewLink').hide();
	});
	
	$('div#productReviewsAdd input[name="reviewName"]').addClass('text');

	//related products
	if ($('div#relatedProducts div#productsRelated').length > 0) {
		var relProds = $('div#productsRelated > div:not(.hdr-title) div[class*="content"]');
		relProds.addClass('relatedProduct');
		var guts = '';
		relProds.each(function(i) {
			var myImg = $(this).find('div.photo').html();
			var myTitle = $(this).find('div.title').html();
			var myPrice = $(this).find('div.sprice').text();
			guts += '<td><div class="relatedProduct">'+myImg+'<p class="relatedProductTitle">'+myTitle+'</p><p class="relatedProductPrice">Price: <span class="price">'+myPrice+'</span></p></div></td>';
		});
				
		$('div#relatedProducts div.wrapper').html('<table cellspacing="0" cellpadding="0"><tbody><tr>'+guts+'</tr></tbody></table>');
		$('div#relatedProducts').show();
	}
		
	//tabs
	$('#pd_infoNav li').click(function() {
		if (!$(this).hasClass('currentTab')) {
			//switch details tab
			var oldTab = $('div#pd_infoNav li.currentTab');
			var oldTabIndex = $('div#pd_infoNav ul li').index(oldTab);
			var newIndex = $('div#pd_infoNav ul li').index(this);
			oldTab.removeClass('currentTab');
			$(this).addClass('currentTab');
			//turn off old content and show new one
			$('div.tabContent').hide();
			$('div.tabContent:eq(' + newIndex + ')').show();
			$('#pd_scroller').scrollTop(0);
		}
	});
	
	// if you just hit search without entering anything on the form we have to prevent a search of 'Keyword, Title, Author, ISBN'
	$('div#productSearch form').submit(function(e) {
		if (searchField.val() == searchHelpText) { e.preventDefault(); }
	})
	
	$('p#writeReview a, p#cancelReview a').click(function(e) {
		e.preventDefault();
		$('div#addReview').toggle();
	})
	
	$('p#readAll a').click(function(e) {
		e.preventDefault();
		$('div.review').show();
	})

	$("div#cartButtons input[value='Checkout']").addClass("checkoutBtn");
	
	// this function captures the click of the add to cart button for
	// a bundle and then sets the useBundle hidden input to Y and
	// submits the form
	$('input#bundleSubmit').click(function() {
		$('input#bundleAdd').val('Y');
		$('input#addToCartButton').click();
	})

	// this function captures the click of the add to cart button on
	// the carousel, creates the productID hidden input and sets the
	// right productID on it before submitting the form
	$('form#carouselItems div.slide input.addToCart').click(function() {
		var inputId = $(this).attr('id');
		var productId = inputId.substring(10, inputId.length)
		$('form#carouselItems').append('<input type="hidden" name="productID" value="' + productId + '" />');
	})
	
	// adding this to fix the anonymous checkout page
	$('div#checkoutOnePage div#information_div').show();
	
	// adding this for CP so that Google Analytics will work correctly during checkout 
	var gaFormInfo = $('body#cart div#viewCart form[name="digiSHOP"]');
	$('body#cart div#viewCart form[name="digiSHOP"] div#cartButtons input[value="Checkout"]').click(function() {
		_gaq.push(['_linkByPost', gaFormInfo]);
	});
}); // end of the ready function

function validateReviewRating() {
	if ($('input#reviewSubject').attr('value') == '') {
		if(!document.reviewForm.reviewRating.value || isNaN(document.reviewForm.reviewRating.value) || document.reviewForm.reviewRating.value < 1 || document.reviewForm.reviewRating.value > 5 || !document.reviewForm.reviewName.value || !document.reviewForm.reviewBody.value){
			alert("All Review Fields are Required Fields");
			return false;
		}
		return true;
	}
}
