function lookupPostcode( prefix, defaultText ) {
	if(!defaultText){
		defaultText = '- Postcode*'
	}
	var postcode = $( document.getElementById( prefix + 'postcode' ) ).val();
	if ( postcode != defaultText && postcode != '' ){
		var dropdownEl = document.getElementById( prefix + 'postcode_lookup' );
		dropdownEl.options.length = 0;
		$( dropdownEl ).append( '<option value="-1">Searching...</option>' );
		$.get( '/xmlservice.php?service=postcodeLookup&postcode=' + escape(postcode),
			function( result ){
				dropdownEl.options.length = 0;
				$( dropdownEl ).append( '<option value="-1">- Choose one...</option>' );
				$( result.ResultSet.Result ).each( function(index,item){
					if(typeof(item.id) != 'undefined') {
						$( dropdownEl ).append( '<option value="' + item.id + '">' + item.description + '</option>' );
					}
				});
				$( dropdownEl ).append( '<option value="-1">Other (Please Specify)</option>' );
				$( dropdownEl ).change( function(){
					lookupAddress( $(this).val(), prefix );
				});
				$( document.getElementById( prefix + 'postcode_lookup_wrapper' ) ).show();
				
			}
			, 'json' 
		);
	} else {
		alert( 'Please enter valid postcode');
	}
}
function logout(){
	$('#logout_form').submit();
}
function lookupAddress( addressId, prefix ) {
	if ( addressId == '-1' ) {
		return;
	}
	$.get( '/xmlservice.php?service=addressLookup&addressId=' + escape(addressId),
		function( result ){
			var item = result.ResultSet.Result[0];
			$( document.getElementById( prefix + 'company' ) ).val(item.organisation_name);
			$( document.getElementById( prefix + 'address1' ) ).val(item.line1);
			$( document.getElementById( prefix + 'address2' ) ).val(item.line2);
			$( document.getElementById( prefix + 'town' ) ).val(item.post_town);
			$( document.getElementById( prefix + 'county' ) ).val(item.county);
		}
		, 'json'
	);
}
function openWindow( url, width, height ) {
	window.open( url, 'newWin','menubar=0,resizable=1,scrollbars=1,width='+width+',height='+height);
}
function openInvoice( invoiceId ) {
	var invoiceWindow = window.open( '/invoice/' + invoiceId, 'invoiceWin', 'menubar=0,location=0,toolbar=0,resizable=1,width=800,height=600,scrollbars=1' );
} 
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 logoutUser () {
	$('#logout_form').submit();
}
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 doSimpleSearch(  ) {
	if( document.getElementById('productSearch').value != '- Product Search' ){
		document.location = '/products/%20search::' + document.getElementById('productSearch').value + '?cmsCatalogueProductSection[perPage]=9';
	} else {
		alert( "Please enter a search term" );
	}
	return false;
}
var basketPopupTimeout ;
function addToBasket( id, prefix ) {
	var productFormName = prefix + 'Form_' + 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 );
			clearTimeout( basketPopupTimeout );
			if(	!$.browser.msie ) {
				basketPopupTimeout = setTimeout( function() { $( "#miniBasketPopup" ).fadeOut(1000); } , 3000 );
			} else {
				basketPopupTimeout = setTimeout( function() { $( "#miniBasketPopup" ).hide(); } , 3000 );
			}
		}
		, 'html' 
	);
	return false;
}	
function checkProductForm( id, prefix ) {
	var validate = new validateForm();
	validate.checkNumeric( prefix + 'Qnty_' + id, 'Quantity' );
	if( validate.numberOfErrors() > 0 ) {
		validate.displayErrors();
		return false;
	}

	addToBasket( id, prefix );
	return false;
}
function setCookie( name, value ) {
	document.cookie = name + '=' + value + ';path=/;';
}

function unsetCookie( name ) {
	document.cookie = name + '=; expires=Thu, 2 Aug 2001 20:47:11 UTC; 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 changePriceVAT ( showVAT ) {
	if ( showVAT ) {
		$( '.priceExVAT' ).hide();
		$( '.priceIncVAT' ).show();
		setCookie( 'showVatInBasket', true );
	} else {
		$( '.priceIncVAT' ).hide();
		$( '.priceExVAT' ).show();
		setCookie( 'showVatInBasket', false );
	}
}

var menuLoaded = [];
var menuShowing = {};
var menuHidding ;
var menuLoading = 0; 
var maxLvl = 1;
var menuKilled = false;
function killAllLvl( lvl ){
	menuLoading = 0;
	while( maxLvl > lvl ){	
		$( '.categories_menu_lvl' + maxLvl ).hide();
		maxLvl -= 1;
		delete menuShowing[maxLvl];
	}
}
function showMenuItem ( id , lvl ) {
	menuKilled = false;
	clearTimeout( menuHidding );
	if( menuShowing[lvl]!= id ){
		killAllLvl( lvl );	
		maxLvl = lvl + 1;
		menuShowing[lvl] = id;
		$( '#p' + id ).show();
	}
	menuLoading = id;
}
function hideMenuItem () {
	menuKilled = true;
	menuHidding = setTimeout( function () { 
		killAllLvl( 1 );
	}, 800, false);
}
function createMenuHtml ( categoryInfo, lvl){
	lvl++;
	var counter;
	var aTagClass = '';
	$.each( categoryInfo , function ( parentIndex, value ){
		$( '#p' + parentIndex )  .addClass( 'categories_menu_lvl'+ lvl )
								.hide()
								.append('<div class="thisLvlTop"></div>')
								.append('<div class="thisLvlMenu"></div>');
		$.each( value , function ( currentId, values ){
			counter ++;
			if ( counter != value.length ) {
				aTagClass = 'item';
			} else {
				aTagClass = 'item last';
			}
			$( '#p' + parentIndex + ' div.thisLvlMenu' ).append( $( document.createElement('div') )			
						.addClass( 'item_wrapper' )
						.mouseenter( function () {
							getMenuItems( currentId, lvl  );
						}).append( $( document.createElement('a') )
								.addClass( aTagClass )
								.attr( { href: values['path'] } )
								.html( values['title'] )
						).append( $( document.createElement('div') )
								.attr( { id: 'p' + currentId } )
						)
			);
			
		});
		$( '#p' + parentIndex ).append('<div class="thisLvlBottom"></div>');
		if( menuLoading == parentIndex  && menuKilled == false){
			menuShowing[lvl-1] = false;
			showMenuItem( parentIndex, lvl-1 );
		}
		
	});
}
function fetchChildMenus ( parent_ids, lvl ) {
	menuLoaded[parent_ids] = true;
	killAllLvl(lvl);
	menuLoading = parent_ids;
	var useThis = parent_ids.replace('_sec','');
	$.ajax({
		type: 'GET',
		url: '/xmlservice.php',
		dataType: 'json',
		data: {
			service:'fetchMenus',
			parent: [useThis]},
			success: function ( results ) {
				if(! $.isEmptyObject( results.ResultSet.Result[0] ) ){			
					createMenuHtml(results.ResultSet.Result[0], lvl);
				}
			}
		});	
}
function getMenuItems( parent_id, lvl ) {
	if( typeof( menuLoaded[parent_id] ) == 'undefined' ){
		fetchChildMenus ( parent_id, lvl );
	} else {
		showMenuItem( parent_id, lvl );
	}
}

function checkLoginForm( prefix ) {
	var validate = new validateForm();
	
	validate.validateEmailAddress( prefix + 'clientLogin_username', 'Email Address is not a valid email address' );
	validate.checkText( prefix + 'clientLogin_password', 'Password', '-Password*' );
	if( validate.numberOfErrors() > 0 ) {
		validate.displayErrors();
		return false;
	}
	return true;
}

function showPopup ( id ) {
	$('#' + id ).dialog('open');
}
function checkRegistrationForm( prefix ) {
	var validate = new validateForm();
	if( prefix == 'basket_change_details_myBasket_' || prefix == 'popup_' || prefix == 'myBasket_' ){
		if(document.getElementById(prefix + 'terms_conditions')) {
			validate.checkChecked( prefix + 'terms_conditions','Accept the Terms and Conditions');
		}
	}
	
	if( prefix != 'quick_myBasket_' && prefix != 'basket_change_details_myBasket_' ){
//		register form field validation
		validate.checkText( prefix + 'cmsUserAdmin_user_firstname', 'First Name', '- First Name*');
		validate.checkText( prefix + 'cmsUserAdmin_user_surname', 'Last Name', '- Last Name*' );
		if( document.getElementById( prefix + 'cmsUserAdmin_user_email' ).value != document.getElementById( prefix + 'cmsUserAdmin_user_confirm_email_confirm' ).value ){
			validate.addCustomError( 'Email addresses do not match' );
		}
		if( $( '#'+ prefix + 'cmsUserAdmin_user_password' ).val() != $( '#'+ prefix + 'cmsUserAdmin_user_confirm_password2' ).val() ){
			validate.addCustomError( 'Passwords do not match' );
		}
		if($('#'+prefix+'cmsUserAdmin_user_password').val() != '' && $('#'+prefix+'cmsUserAdmin_user_password').val().length < 6) {
			validate.addCustomError( 'Password must be at least 6 characters');
		}
		validate.validateEmailAddress( prefix + 'cmsUserAdmin_user_confirm_email_confirm', 'Confirm Email Address is not a valid email address' );
		if ( prefix != "edit_" ){
			validate.checkText( prefix + 'cmsUserAdmin_user_password', 'Password', '' );
			validate.checkText( prefix + 'cmsUserAdmin_user_confirm_password2', 'Confirm Password', '' );
		}		
		validate.checkSelect( prefix + 'cmsUserAdmin_user_title', '- title*', 'Title' );
	} else {
		validate.checkText( prefix + 'CMSCatalogueProcessOrder_orderDetail_contact_name', 'Contact Name', '- Contact Name*');
	}
	
	validate.validateEmailAddress( prefix + 'cmsUserAdmin_user_email', 'Email Address is not a valid email address' );
	validate.checkText( prefix + 'cmsUserAdmin_user_telephone', 'Telephone', '- Contact Telephone*' );
	
	validate.checkText( prefix + 'cmsUserAdmin_user_billing_address1', 'Billing Address Line One', '- Address Line One*' );
	validate.checkText( prefix + 'cmsUserAdmin_user_billing_town', 'Billing Town or City', '- Town or City*' );
	validate.checkText( prefix + 'cmsUserAdmin_user_billing_county', 'Billing County', '- County*' );
	validate.validatePostCode( prefix + 'cmsUserAdmin_user_billing_postcode', 'Billing Postcode is not a valid postcode' );
	
	validate.checkText( prefix + 'cmsUserAdmin_user_billing_postcode', 'Billing Postcode', '- Postcode*' );
	
	validate.checkText( prefix + 'cmsUserAdmin_user_delivery_address1', 'Delivery Address Line One', '- Address Line One*' );
	validate.checkText( prefix + 'cmsUserAdmin_user_delivery_town', 'Delivery Billing Town or City', '- Town or City*' );
	validate.checkText( prefix + 'cmsUserAdmin_user_delivery_county', 'Delivery Billing County', '- County*' );
	validate.validatePostCode( prefix + 'cmsUserAdmin_user_delivery_postcode', 'Delivery Billing Postcode is not a valid postcode' );
	
	if( validate.numberOfErrors() > 0 ) {
		validate.displayErrors();
		return false;
	} else {
		/* clearing inputs without users data entry */
		$.each( $('#' + prefix + 'registerForm input'), function(key, item) { 
			if ( ( $( item ).val().substring(0,1)=='-' ) && ( $( item ).attr('type') != 'password') && ( $( item ).val().substring(-1) != '*') ){
				$( item ).val( '' );			
			}  
		});		
		return true;
	}
	return false;
}

function checkAddressDetails() {
	var validate = new validateForm();
	var prefix = 'basket_change_details_myBasket_';
	
	validate.checkText( prefix + 'CMSCatalogueProcessOrder_orderDetail_contact_name', 'Contact Name', '- Contact Name*');
	validate.validateEmailAddress( prefix + 'cmsUserAdmin_user_email', 'Email Address is not a valid email address' );
	validate.checkText( prefix + 'cmsUserAdmin_user_telephone', 'Telephone', '- Contact Telephone*' );
	
	validate.checkText( prefix + 'cmsUserAdmin_user_billing_address1', 'Billing Address Line One', '- Address Line One*' );
	validate.checkText( prefix + 'cmsUserAdmin_user_billing_town', 'Billing Town or City', '- Town or City*' );
	validate.checkText( prefix + 'cmsUserAdmin_user_billing_county', 'Billing County', '- County*' );
	validate.validatePostCode( prefix + 'cmsUserAdmin_user_billing_postcode', 'Billing Postcode is not a valid postcode' );
	
	validate.checkText( prefix + 'cmsUserAdmin_user_billing_postcode', 'Billing Postcode', '- Postcode*' );
	
	validate.checkText( prefix + 'cmsUserAdmin_user_delivery_address1', 'Delivery Address Line One', '- Address Line One*' );
	validate.checkText( prefix + 'cmsUserAdmin_user_delivery_town', 'Delivery Billing Town or City', '- Town or City*' );
	validate.checkText( prefix + 'cmsUserAdmin_user_delivery_county', 'Delivery Billing County', '- County*' );
	validate.validatePostCode( prefix + 'cmsUserAdmin_user_delivery_postcode', 'Delivery Billing Postcode is not a valid postcode' );
	
	if( validate.numberOfErrors() > 0 ) {
		validate.displayErrors();
		return false;
	} else {
		return true;
	}
}

function syncRegisterAddresses( sync, prefix ) {
	if ( sync ) {
		$('#'+prefix+'cmsUserAdmin_user_billing_address1').change(function(){ 
			$('#'+prefix+'cmsUserAdmin_user_delivery_address1').val($(this).val());   
		});
		$('#'+prefix+'cmsUserAdmin_user_billing_address2').change(function(){ 
			$('#'+prefix+'cmsUserAdmin_user_delivery_address2').val($(this).val());   
		});
		$('#'+prefix+'cmsUserAdmin_user_billing_town').change(function(){ 
			$('#'+prefix+'cmsUserAdmin_user_delivery_town').val($(this).val());   
		});
		$('#'+prefix+'cmsUserAdmin_user_billing_county').change(function(){ 
			$('#'+prefix+'cmsUserAdmin_user_delivery_county').val($(this).val());   
		});
		$('#'+prefix+'cmsUserAdmin_user_billing_postcode').change(function(){ 
			$('#'+prefix+'cmsUserAdmin_user_delivery_postcode').val($(this).val());   
		});
		
		$('#'+prefix+'cmsUserAdmin_user_delivery_address1').change(function(){ 
			$('#'+prefix+'cmsUserAdmin_user_billing_address1').val($(this).val());   
		});
		$('#'+prefix+'cmsUserAdmin_user_delivery_address2').change(function(){ 
			$('#'+prefix+'cmsUserAdmin_user_billing_address2').val($(this).val());   
		});
		$('#'+prefix+'cmsUserAdmin_user_delivery_town').change(function(){ 
			$('#'+prefix+'cmsUserAdmin_user_billing_town').val($(this).val());   
		});
		$('#'+prefix+'cmsUserAdmin_user_delivery_county').change(function(){ 
			$('#'+prefix+'cmsUserAdmin_user_billing_county').val($(this).val());   
		});
		$('#'+prefix+'cmsUserAdmin_user_delivery_postcode').change(function(){ 
			$('#'+prefix+'cmsUserAdmin_user_billing_postcode').val($(this).val());   
		});
		
		$('#'+prefix+'cmsUserAdmin_user_delivery_address1').val($('#'+prefix+'cmsUserAdmin_user_billing_address1').val());
		$('#'+prefix+'cmsUserAdmin_user_delivery_address2').val($('#'+prefix+'cmsUserAdmin_user_billing_address2' ).val());
		$('#'+prefix+'cmsUserAdmin_user_delivery_town').val($('#'+prefix+'cmsUserAdmin_user_billing_town' ).val());
		$('#'+prefix+'cmsUserAdmin_user_delivery_county').val($('#'+prefix+'cmsUserAdmin_user_billing_county' ).val());
		$('#'+prefix+'cmsUserAdmin_user_delivery_postcode').val($('#'+prefix+'cmsUserAdmin_user_billing_postcode' ).val());
	} else {
		$('#'+prefix+'cmsUserAdmin_user_billing_address1').unbind('change');
		$('#'+prefix+'cmsUserAdmin_user_billing_address2').unbind('change');
		$('#'+prefix+'cmsUserAdmin_user_billing_town').unbind('change');
		$('#'+prefix+'cmsUserAdmin_user_billing_county').unbind('change');
		$('#'+prefix+'cmsUserAdmin_user_billing_postcode').unbind('change');
		$('#'+prefix+'cmsUserAdmin_user_delivery_address1').unbind('change');
		$('#'+prefix+'cmsUserAdmin_user_delivery_address2').unbind('change');
		$('#'+prefix+'cmsUserAdmin_user_delivery_town').unbind('change');
		$('#'+prefix+'cmsUserAdmin_user_delivery_county').unbind('change');
		$('#'+prefix+'cmsUserAdmin_user_delivery_postcode').unbind('change');
		$('#'+prefix+'cmsUserAdmin_user_delivery_address1').val('').blur();
		$('#'+prefix+'cmsUserAdmin_user_delivery_address2').val('').blur();
		$('#'+prefix+'cmsUserAdmin_user_delivery_town').val('').blur();
		$('#'+prefix+'cmsUserAdmin_user_delivery_county').val('').blur();
		$('#'+prefix+'cmsUserAdmin_user_delivery_postcode').val('').blur();
	}
}

var pageLoaded = false;

function doOnLoad(){
	var showVatInBasket = getCookie( 'showVatInBasket' );
	if ( showVatInBasket == 'true' ) {
		$( '#showVATCheckbox' ).attr( 'checked', true );
		changePriceVAT( true );
	}
	pageLoaded = true;
	$('.sidebar .categories .names .item_wrapper').each( function(index){
		$(this).mouseenter( function() {
				getMenuItems( $(this).find( '>div' ).attr('id').substring(1), 1 ); 
		});
	});
	$('.sidebar .categories .names').mouseleave( function () { hideMenuItem(); } );
	$('#popup_contact_form').dialog({
									dialogClass: 'popup_contact_form_bg',
									title: null,
									autoOpen: false,
									draggable: false,
									resizable: false,
									hide:true,
									modal:true,
									stack: false,
									show: 'show',
									width: 362,
									height: 277
	});
	$('#popup_login_form').dialog({ 
									dialogClass: 'popup_login_form_bg',
									title: null,
									autoOpen: false,
									draggable: false,
									resizable: false,
									hide:true,
									modal:true,
									stack: false,
									show: 'show',
									width: 317,
									height: 192
	});
	$('#popup_register_form').dialog({ 
									dialogClass: 'popup_register_form_bg',
									title: null,
									autoOpen: false,
									draggable: false,
									resizable: false,
									hide:true,
									modal:true,
									stack: false,
									show: 'show',
									width: 741,
									height: 402
	});	
	
}
$( function () {
	doOnLoad();
});
