var showVat = true;
var searchtimer;

function inputBoxFocus( input, defaultText, passwordField ) {
	if( typeof passwordField != 'undefined' ) {
		document.getElementById( passwordField ).style.display = '';
		document.getElementById( passwordField+'_text' ).style.display = 'none';
		document.getElementById( passwordField ).focus();
	} else {
		if( input.value == defaultText ) {
			input.value = '';
		}
	}
}

function inputBoxBlur( input, defaultText, passwordField ) {
	if( input.value == '' ) {
		if( typeof passwordField != 'undefined' ) {
			document.getElementById( passwordField ).style.display = 'none';
			document.getElementById( passwordField+'_text' ).style.display = '';
		} else {
			input.value = defaultText;
		}
	}
}

function validateLoginPopup() {
	var validator = new validateForm();
	validator.checkText( 'clientLogin_username', 'Email Address', '- Enter your email address...*' );
	validator.checkText( 'clientLogin_password', 'Password');
	if ( validator.numberOfErrors() > 0 ) {
		validator.displayErrors();
		return false;
	} else {
		return true;
	}
}

function validateContact() {
	var validator = new validateForm();
	validator.checkText( 'contact_first_name', 'First Name', '- First Name...' );
	validator.checkText( 'contact_last_name', 'Last Name', '- Last Name...');
	validator.validateEmailAddress( 'contact_email', 'Email Address', '- Email Address...' );
	validator.checkText( 'contact_message', 'Message', '- Enter message here...' );
	if ( validator.numberOfErrors() > 0 ) {
		validator.displayErrors();
		return false;
	} else {
		return true;
	}
}

function validateCatalogue() {
	var validator = new validateForm();
	validator.checkText( 'contact_first_name', 'First Name', '- First Name...' );
	validator.checkText( 'contact_last_name', 'Last Name', '- Last Name...');
	validator.validateEmailAddress( 'contact_email', 'Email Address', '- Email Address...' );
	validator.checkText( 'contact_message', 'Message', '- Enter message here...' );
	validator.checkText( 'contact_address', 'Address Lines', '- Address Lines...' );
	validator.checkText( 'contact_town', 'Town', '- Town...' );
	validator.checkText( 'contact_county', 'County', '- County...' );
	validator.checkText( 'contact_postcode', 'Postcode', '- Postcode...' );
	if ( validator.numberOfErrors() > 0 ) {
		validator.displayErrors();
		return false;
	} else {
		return true;
	}
}

function addToBasket( id ) {
	var productFormName = 'productForm';
	if( typeof id != 'undefined' ) {
		// product section addtobasket
		productFormName = 'productForm_' + id;
	}
	$.post( '/manage_basket.php', $('#' + productFormName ).serialize(),
		function( data ){
			if ( data.substr( 0, 6 ) == 'ERROR:' ) {
				alert( data.substr( 6 ) );
				return false;
			}
			// scroll to the top of the window
			window.scrollTo( 0, 0 );
			// update the basket contents
			$('#minibasket').html( data );
			// show the item added popup
			var addedProductImage = $('#minibasket').find('.hiddenBasketProductImage').val();
			var addedProductName = $('#minibasket').find('.hiddenBasketProductName').val();
			var addedProductPrice = $('#minibasket').find('.hiddenBasketProductPrice').val();
			var addedProductPriceIncVAT = $('#minibasket').find('.hiddenBasketProductPriceIncVAT').val();
			$('#itemAddedImage').css( 'background-image', 'url("' + addedProductImage + '")' );
			$('#itemAddedName').html( addedProductName );
			$('#itemAddedPrice').html( '&pound;' + addedProductPrice );
			$('#itemAddedPriceIncVAT').html( '&pound;' + addedProductPriceIncVAT );
			$('#itemAddedPopup').fadeIn( 200 ).delay( 3000 ).fadeOut( 200 );
			
			checkVATCookie();
		}
		, 'html' 
	);
}

function doSearch() {
	if (( $('#search_trig').val() != '' ) && ( $('#search_trig').val() != '- Product search...' )) {
		document.location = '/products/%20search::' + $('#search_trig').val();
	} else {
		alert( "Please enter search text" );
	}
	return false;
}
function triggerSearch() {
	// cancel the last search
	clearTimeout( searchtimer );
	// instead do one in 1/2 a second
	searchtimer = setTimeout( "quickSearch();", 500 );
}

function quickSearch()
{
	var limit = 3;
	var searchText = $('#search_trig').val();
	// ensure we have at least 3 characters
	if( searchText != '- Product search...' && searchText.length > 2 ) {
		// send the query
		var sUrl = "/xmlservice.php?service=quickSearch&query=" + searchText + "&getPrice=1&limit=" + limit;
		$.ajax({
			type: "GET",
			url: sUrl,
			success: function( result ){
				// got results, set the list to empty
				$('#quickSearchResults').html('');
				if( result.ResultSet.Result ) {
					var recordCount = 0;
					for( var product in result.ResultSet.Result ) {
						recordCount++;
					}
					var html = '';
					if( recordCount > 0 ) {
						var resultNum = 0;
						html += '<ul>';
						for( var product in result.ResultSet.Result ) {
							if(typeof(result.ResultSet.Result[product]) == 'object') {
								resultNum++;
								
								var imagePath = '/custom/images/no-image-86.gif';
								if(result.ResultSet.Result[product]['media']['0']) {
									if(result.ResultSet.Result[product]['media']['0']['preview_url']) {
										imagePath = result.ResultSet.Result[product]['media']['0']['preview_url'];
									}
								}
								
								priceIncVAT = new Number(result.ResultSet.Result[product]['calculated']['priceIncVAT']);
								priceExVAT = new Number(result.ResultSet.Result[product]['calculated']['price']);
								
								if(resultNum%2 == 0) {
									html += '<li class="even">';
								}
								else {
									html += '<li>';
								}
								html += '<div class="left_sec"><a href="' + result.ResultSet.Result[product]['path'] + '" title="' + result.ResultSet.Result[product]['display'] + '"><img src="' + imagePath + '" alt="' + result.ResultSet.Result[product]['display'] + '"/></a></div>';
								html += '<div class="right_sec1">';
								html += '<h4><a href="' + result.ResultSet.Result[product]['path'] + '" title="' + result.ResultSet.Result[product]['display'] + '">' + result.ResultSet.Result[product]['display'] + '</a></h4>';
								html += '<span>Product number:</span>';
								html += '<span class="pad">' + result.ResultSet.Result[product]['code'] + '</span>';
								
								html += '<strong class="price_incVAT">&pound;' + priceIncVAT.toFixed(2) + ' inc.</strong>';
								html += '<strong class="price_exVAT">&pound;' + priceExVAT.toFixed(2) + ' ex.</strong>';
								
								html += '</div>';
								html += '</li>';
							}
						}
						html += '</ul>';
					}
					else {
						html += '<ul><li style="text-align: center;"><h4>No results!</h4></li></ul>';
						//html += '<div class="quickSearchNothing">No products found!</div>';
					}
					$('#quickSearchResults').append( html );
					updateVAT(showVat);
					$('#search_pop').show();
				}
			},
			error : function( result ){
			},
			dataType: "json"
		});
	}
}
function triggerHideSearch() {
	searchtimer = setTimeout( "hideSearch();", 500 );
}
function hideSearch() {
	$('#quickSearchResults').empty();
	$('#search_pop').hide();
}

function setCookie( name, value ) {
	document.cookie = name + '=' + value + ';path=/;';
}
function getCookie( name ) {
	var start = document.cookie.indexOf( name + "=" );
	var len = start + name.length + 1;
	if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) {
		return null;
	}
	if ( start == -1 ) {
		return null;
	}
	var end = document.cookie.indexOf( ";", len );
	if ( end == -1 ) {
		end = document.cookie.length;
	}
	return unescape( document.cookie.substring( len, end ) );
}
function checkVATCookie() {
	var cookieVal = getCookie( 'showVATInBasket' );
	// if val is true or not previously been set...
	if ( cookieVal == 'true' ) {
		updateVAT( true );
	} else {
		updateVAT( showVat );
	}
}
function updateVAT( vat ) {
	showVat = vat;

	if( showVat ) {
		$('.price_incVAT').show();
		$('.price_exVAT').hide();
	} else {
		$('.price_incVAT').hide();
		$('.price_exVAT').show();
	}
	
	setCookie( 'showVATInBasket', showVat );
}
function switchVAT() {
	updateVAT(!showVat);
}

function logout() {
	$('#logout_form').submit();
}

function validateComment() {
	var validator = new validateForm();
	validator.checkText( 'comment_first_name', 'First Name', '- First Name...' );
//	validator.checkText( 'comment_email', 'Email', '- Email...');
	validator.validateEmailAddress( 'comment_email','Email');
	validator.checkText( 'comment_message', 'Message', '- Enter message here...' );
	if ( validator.numberOfErrors() > 0 ) {
		validator.displayErrors();
		return false;
	} else {
		return true;
	}
}

function addFavourite( productId ) {
	var jsonUrl = "/xmlservice.php";
	$.getJSON(
		jsonUrl,
		{
			service: 'addToWishList',
			itemID: productId,
			overwrite_quantity: '1',
			itemType: '1'
		},
		function(json) {
			var result = json.ResultSet.Result[0].result;
			if(result == 'success') {
				alert('Item successfully added');
			}
			else if (result == 'unauthenticated') {
				alert('You must be logged in to add favourites');
			} 
			else {
				alert('Could not add item');
			}
		}
	);
}

function removeFavourite( productId, removeListItem ) {
	var jsonUrl = "/xmlservice.php";
	$.getJSON(
		jsonUrl,
		{
			service: 'removeFromWishList',
			itemID: productId,
			itemType: '1'
		},
		function(json) {
			var result = json.ResultSet.Result[0].result;
			if(result == 'success') {
				alert('Item successfully removed');
			}
			else {
				alert('Could not remove item');
			}
		}
	);
	if(typeof(removeListItem) != 'undefined') {
		$('#favourite_'+removeListItem).hide();
	}
}

$(document).ready(function(){
	$("a.show-panel, span.show-panel").click(function(event){
		$("#lightbox, #lightbox-panel").fadeIn(300);
		event.preventDefault();
	});
	$("a#close-panel").click(function(event){
		$("#lightbox, #lightbox-panel").fadeOut(300);
		event.preventDefault();
	});
	$('#scrollbar1').tinyscrollbar();

	$('.tab_link ul li').click(function(){
		$('.tab_link ul li').children('a').removeClass('active');
		$(this).children('a').addClass('active');
		for(var i=1;i<5;i++){
		                      $('#content'+i).hide();	
		}
		$('#conten'+$(this).children('a').attr('rel')).show();
	});
	
	$('.no_items span').each(function() {
		if($(this).text() < 10) {
			$(this).text('0'+$(this).text());
		}
	});
	var a;
	$('.no_items .plus_v').click(function(){
		a = $(this).parent().children('input:hidden').val();
		a++;
		if(a >= 1 && a < 10)
		{
			$(this).parent().children('span').text('0'+ a);
		}
		else
		{
			$(this).parent().children('span').text(a);
		}
		$(this).parent().children('input:hidden').val(a);
	});
	$('.no_items .minus_v').click(function(){
		a = $(this).parent().children('input:hidden').val();
		if(a > 1)
		{
			a--;
			if(a >= 1 && a < 10)
			{
				$(this).parent().children('span').text('0'+ a);
			}
			else
			{
				$(this).parent().children('span').text(a);
			}
			$(this).parent().children('input:hidden').val(a);;
		}
	});
	$('.custom_select_box').sSelect();
	$('.navigation ul li.navItem').each(function(){
		var leftPos = $(this).position().left - $('.navigation').position().left;
		if(leftPos > 494) {
			$(this).find('.top_part').css('left','auto').css('right','0px');
		}
	});
});
