var fontSize = 0;
pricesToChange = new Array();

$(document).ready(function(){
	$('.qtymod').click(function(){
		if($(this).attr('id').substring(0,4)=='inc_'){
			$(this).prev().val(parseInt($(this).prev().val())+1);
		}
		if($(this).attr('id').substring(0,4)=='dec_'){
			if(parseInt($(this).next().val())>0){
				$(this).next().val(parseInt($(this).next().val())-1);
			}
		}
	});
});

function logout() {
	document.getElementById('logoutForm').submit();
}

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 hideElement( id ) {
	document.getElementById( id ).style.display = 'none';
}
function showElement( id ) {
	document.getElementById( id ).style.display = '';
}

function correctPNG( imageId ) // correctly handle PNG transparency in Win IE 5.5 , 6 & 7.
{
	var arVersion = navigator.appVersion.split("MSIE")
	var version = parseFloat(arVersion[1])
	if ((version >= 5.5) && (version < 7) && (document.body.filters)) 
	{
		var img = document.getElementById( imageId );
		var imgName = img.src.toUpperCase()
		var imgID = (img.id) ? "id='" + img.id + "' " : "";
		var imgClass = (img.className) ? "class='" + img.className + "' " : ""
		var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' "
		var imgStyle = "display:inline-block;" + img.style.cssText 
		if (img.align == "left") imgStyle = "float:left;" + imgStyle
		if (img.align == "right") imgStyle = "float:right;" + imgStyle
		if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle
		var strNewHTML = "<span " + imgID + imgClass + imgTitle
		+ " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";"
		+ "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
		+ "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>" 
		img.outerHTML = strNewHTML
	}
}

function correctPNGBackground( divId, imgURL ) // correctly handle PNG transparency in Win IE 5.5 , 6 & 7.
{
	var arVersion = navigator.appVersion.split("MSIE")
	var version = parseFloat(arVersion[1])
	if ((version >= 5.5) && (version < 7) && (document.body.filters)) 
	{
		var div = document.getElementById( divId );
		div.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+imgURL+"', sizingMethod='scale')";
		div.style.background = '';
	}
}

function doSearch() {
	var searchText = document.getElementById( 'searchText' ).value;
	if ( searchText == 'Product Search' ) {
		searchText = '';
	}
	if ( searchText != '' ) {
		document.location = '/products/%20search::' + document.getElementById( 'searchText' ).value;
	} else {
		alert( "Please enter search text" );
	}
	return false;
}

function doQuickAdvancedSearch() {
	var queryString = '/products';
	var base = document.getElementById('advanced_search_base').value;
	var equivalentWattage = document.getElementById('advanced_search_equivalent_wattage').value;
	var wattage = document.getElementById('advanced_search_wattage').value;
	var doSearch = false;
	
	if ( base != '' ) {
		queryString += '/%20Base::' + base;
		doSearch = true;
	}
	if ( equivalentWattage != '' ) {
		queryString += '/%20Equivalent To::' + equivalentWattage;
		doSearch = true;
	}
	if ( wattage != '' ) {
		queryString += '/%20Wattage::' + wattage;
		doSearch = true;
	}
	if ( doSearch ) {
		document.location = queryString;
	} else {
		alert('Please select some search criteria');
	}
	return false;
}

function doAdvancedSearch() {
	var queryString = '/products';
	
	var bulbType = document.getElementById('advanced_search_page_bulb_type').value;
	var base = document.getElementById('advanced_search_page_base').value;
	var equivalentWattage = document.getElementById('advanced_search_page_equivalent_wattage').value;
	var wattage = document.getElementById('advanced_search_page_wattage').value;
	var voltage = document.getElementById('advanced_search_page_voltage').value;
	var colour = document.getElementById('advanced_search_page_colour').value;
	
	var doSearch = false;
	
	if ( bulbType != '' ) {
		queryString += '/%20Bulb Type::' + bulbType;
		doSearch = true;
	}
	if ( base != '' ) {
		queryString += '/%20Base::' + base;
		doSearch = true;
	}
	if ( equivalentWattage != '' ) {
		queryString += '/%20Equivalent To::' + equivalentWattage;
		doSearch = true;
	}
	if ( wattage != '' ) {
		queryString += '/%20Wattage::' + wattage;
		doSearch = true;
	}
	if ( voltage != '' ) {
		queryString += '/%20Voltage::' + voltage;
		doSearch = true;
	}
	if ( colour != '' ) {
		queryString += '/%20Colour::' + colour;
		doSearch = true;
	}
	if ( document.getElementById('dimmable_yes').checked ) {
		queryString += '/%20Dimmable::Yes';
		doSearch = true;
	}
	if ( document.getElementById('dimmable_no').checked ) {
		queryString += '/%20Dimmable::No';
		doSearch = true;
	}
	
	if ( doSearch ) {
		document.location = queryString;
	} else {
		alert('Please select some search criteria');
	}
	return false;
}

function setCookie( name, value ) {
	var cookieString = name + '=' + value + ';';
	if(name == 'showVat') {
		var date = new Date();
		date.setTime(date.getTime()+1800000);
		cookieString += 'expires='+date.toGMTString()+';';
	}
	cookieString += 'path=/;';
	document.cookie = cookieString;
}

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 hideAllPrices() {
	if ( typeof pricesToChange != 'undefined' ) {
		var currencies = new Array( 'Pounds', 'Euros' );
		var vats = new Array( 'incVat', 'exVat' );
		var strId = '';
		
		for ( var i in pricesToChange ) {
			for ( var vat = 0; vat < vats.length; vat++ ) {
				for ( var currency = 0; currency < currencies.length; currency++ ) {
					strId = pricesToChange[i] + '_currency' + currencies[currency] + '_' + vats[vat];
					if ( document.getElementById( strId ) ) {
						document.getElementById( strId ).style.display = 'none';
					}
				}
				labelId = pricesToChange[i] + '_label_' + vats[vat];
				if ( document.getElementById( labelId ) ) {
					document.getElementById( labelId ).style.display = 'none';
				}
			}
		}
	}
}

function getCurrentCurrency() {
	var curr = getCookie( 'currencyViewing' );
	if ( !curr ) {
		setCookie( 'currencyViewing', 'Pounds' );
		return 'Pounds'; // show pounds by default
	} else {
		return curr;
	}
}

function getCurrentVat() {
	var vat = getCookie( 'showVat' );
	if ( vat == 'false' ) {
		return false;
	} else {
		setCookie( 'showVat', true );
		return true; // show vat by default
	}
}

function doChangeCurrency( selectedCurrency ) {
	if ( typeof pricesToChange != 'undefined' ) {
		var currentVAT = ( getCurrentVat() ) ? 'incVat' : 'exVat';
		for ( var i in pricesToChange ) {
			document.getElementById( pricesToChange[i] + '_currency' + selectedCurrency + '_' + currentVAT ).style.display = '';
			if ( document.getElementById( pricesToChange[i] + '_label_' + currentVAT ) ) {
				document.getElementById( pricesToChange[i] + '_label_' + currentVAT ).style.display = '';
			}
		}
	}
	// call a custom function on the page if it exists
	if ( typeof onChangeCurrency == 'function' ) {
		onChangeCurrency( selectedCurrency );
	}
}

function doChangeVat( showVat ) {
	if ( typeof pricesToChange != 'undefined' ) {
		// change the top option
		//document.getElementById( 'option_hideVat' ).style.display = ( showVat ) ? '' : 'none';
		//document.getElementById( 'option_showVat' ).style.display = ( showVat ) ? 'none' : '';
		
		var currentCurrency = getCurrentCurrency();
		var currentVAT = showVat ? 'incVat' : 'exVat';
		
		for ( var i in pricesToChange ) {
			try{
				document.getElementById( pricesToChange[i] + '_currency' + currentCurrency + '_' + currentVAT ).style.display = '';
				if ( document.getElementById( pricesToChange[i] + '_label_' + currentVAT ) ) {
					document.getElementById( pricesToChange[i] + '_label_' + currentVAT ).style.display = '';
				}
			}
			catch(err){
				alert(pricesToChange[i]);
			}
		}
	}
	// call a custom function on the page if it exists
	if ( typeof onChangeVat == 'function' ) {
		onChangeVat( showVat );
	}
}

// changeCurrency called from website
function changeCurrency( selectedCurrency ) {
	// hide all the prices
	hideAllPrices();
	// show the correct currency/vat combination
	doChangeCurrency( selectedCurrency );
	// store the current currency in a cookie
	setCookie( 'currencyViewing', selectedCurrency );
}

// changeVat called from website
function changeVat( showVat ) {
	// hide all the prices
	hideAllPrices();
	// show the relevant prices
	doChangeVat( showVat );
	// store the current vat option in a cookie
	setCookie( 'showVat', showVat );
}

// called onLoad to show relevant vat and currency selections
function changeAllPrices() {
	// hide all the prices
	hideAllPrices();
	// show correct vat prices
	doChangeVat( getCurrentVat() );
	// show correct currency
	doChangeCurrency( getCurrentCurrency() );
}


function subscribeUserInline(){
	var validateform = new validateForm();
	// check we have name, email
	var emailAddress = document.getElementById('cmsContentSubscribe-emailAddressInline');
	if(( emailAddress.value != 'enter email address' ) && ( emailAddress.value != '' )){
		// check email address is an email address
		validateform.validateEmailAddress( emailAddress.value );
		if( validateform.numberOfErrors() > 0 ) {
			validateform.displayErrors();
			return false;
		} else {
			return true;
		}
	} else {
		validateform.addCustomError( 'Please enter your email address.' );
		validateform.displayErrors();
		emailAddress.focus();
		return false;
	}
}

function doValidateEmailAddress( email ){
	emailAddress = document.getElementById( email ).value;
	var filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	if ( !filter.test( emailAddress )){
		return false;
	} else {
		return true;
	}
}

var anim;
var anim2;

function addToBasket( productId, productName, qty, img, onProductPage ) {

	var handleSuccess = function(o){
		window.scrollTo( 0, 0 );
		document.getElementById( 'topCheckoutLink' ).style.display = '';
		document.getElementById( 'miniBasketDynamic' ).innerHTML = o.responseText;
		// show the "item added" bubble
		document.getElementById('itemAdded').style.display = '';
		document.getElementById('itemAddedImage').innerHTML = '<img src="' + ( ( img != '' ) ? img : '/custom/images/noimage42.gif' ) + '" />';
		document.getElementById('itemAddedName').innerHTML = productName;
		document.getElementById('itemAddedQty').innerHTML = 'Qty ' + qty;
		var price = ( getCurrentVat() ) ? document.getElementById('itemAddedPriceHiddenIncVAT').value : document.getElementById('itemAddedPriceHidden').value;
		document.getElementById('itemAddedPrice').innerHTML = '&pound;' + price;
		anim = new YAHOO.util.Anim('itemAdded', { opacity: { from: 0, to: 1 } }, 0.5, YAHOO.util.Easing.easeOut);
		anim.animate();
		setTimeout( 'fadeOutItemAdded()', 5000 )
		changeAllPrices();
	};
	var handleFailure = function(o){
		alert( 'error' );
	};
	var callback =
	{
		success:handleSuccess,
		failure:handleFailure
	};
	// argument formId can be the id or name attribute value of the
	// HTML form, or an HTML form object.
	if( onProductPage ) {
		var formObject = document.getElementById( 'productForm' );
	} else {
		// hide the select drop down list, we have layering issues with the fallout basket
		var formObject = document.getElementById( 'form_' + productId );
	}
	YAHOO.util.Connect.setForm(formObject);
	// This example facilitates a POST transaction.
	// An HTTP GET can be used as well.
	var cObj = YAHOO.util.Connect.asyncRequest('POST', '/manage_basket.php', callback);
}

function hideItemAdded() {
	document.getElementById('itemAdded').style.display = 'none';
}

function fadeOutItemAdded() {
	anim2 = new YAHOO.util.Anim('itemAdded', { opacity: { to: 0 } }, 0.5, YAHOO.util.Easing.easeOut);
	anim2.animate();
	anim2.onComplete.subscribe(hideItemAdded);
}
function showLargeImage( imageNo ) {
	imageStartingNumber = imageNo;
	$('#productDetailImagePanel').dialog('open');
};
// onBefore moves the images into the centre of the frame
function onBefore( curr, next, opts ) {
	var $slide = $(next);
	var w = $slide.outerWidth();
	var h = $slide.outerHeight();
	$slide.css({
		marginTop: ( 600 - h ) / 2,
		marginLeft: ( 600 - w ) / 2
	});
};
// paginationAssigner turns the thumbnails into pagination links for the slideshow
function paginationAssigner( i, el ) {
	return $('#productDetailImagePanelThumb' + i);
}
function closeLargeImagePanel() {
	$('#productDetailImagePanel').dialog('close');
}
function showAlternate(onoff) {
	if(onoff == 1) {
		document.getElementById('deliveryAddressArea').style.display = '';
	}
	else {
		document.getElementById('deliveryAddressArea').style.display = 'none';
	}
}
function changeFontSize(fontSize) {
	// update the fontSizer link to the new style sheet
	document.getElementById( 'fontSizer' ).href = '/custom/css/' + fontSize + '.css';
	setCookie( 'fontSize', fontSize );
}
function checkFontSize() {
	var cookieVal = getCookie( 'fontSize' );
	// if val is true or not previously been set...
	if ( parseInt( cookieVal ) >= 0 ) {
		// update the fontSizer link to the new style sheet
		fontSize = cookieVal;
		document.getElementById( 'fontSizer' ).href = '/custom/css/' + fontSize + '.css';	
	}
}
function showPreview(element, image) {
	var elementTop  = $(element).offset().top;
	var elementLeft = $(element).offset().left;
	$('#previewPopup').css('top',elementTop-18);
	$('#previewPopup').css('left',elementLeft-21);
	$('#previewPopup').css('background-image','url('+image+')');
	$('#previewPopup').show();
}
function hidePreview() {
	$('#previewPopup').hide();
}
YAHOO.util.Event.on(window,"load",changeAllPrices);
YAHOO.util.Event.on(window,"load",checkFontSize);

$(document).ready( function() {
	$('.glower').mouseenter( function() {
		$(this).addClass('glow');
	} );
	$('.glower').mouseleave( function() {
		$(this).removeClass('glow');
	} );
} );