
function jAlert(strTitle, strContent){
	
	showdeadcenterdiv('jAlert_box',300);
	
	$('#jAlert_title').html(strTitle);
	$('#jAlert_content').html(strContent);
	$('#jAlert_box').fadeIn();
}


function roundNumber(num, dec) {
	var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
	return result;
}
	
function scroll_brands(){
		
	var speed = 1;
	
	if($('#brands_inner').css('margin-left')!=undefined){
		var leftPos = $('#brands_inner').css('margin-left');
		
		leftPos = leftPos.replace('px','').replace('auto','0');
		
		leftPos = leftPos - speed;
		
		$('#brands_inner').css('margin-left',leftPos+'px');
		
		var ImageWidth = $('#brands_inner a:eq(0)').width();
		
		if(leftPos<=(ImageWidth*-1)){
			var newLeftPos = parseInt(leftPos+ImageWidth+1);
			$('#brands_inner a:eq(0)').remove().appendTo('#brands_inner');
			$('#brands_inner').css('margin-left',newLeftPos+'px');
		}
		
		var divWidth = $('#brands').width();
	}
	
}
	













// populate colours based on sub category
function populateSubCategoryColours(sub_id, selectedColours)
{
	var x = new Hijax(); x.setContainer( document.getElementById('sub_id'));
	x.setUrl("/p/populateSubCategoryColours.php?sub_id=" + sub_id + '&selectedColours=' + selectedColours);
	x.setCanvas(document.getElementById('colourSelectWrapper')); x.captureData();
}


// populate sizes based on sub category
function populateSubCategorySizes(sub_id, product_id)
{
	var x = new Hijax(); x.setContainer( document.getElementById('sub_id'));
	x.setUrl("/p/populateSubCategorySizes.php?sub_id=" + sub_id + "&product_id=" + product_id);
	x.setCanvas(document.getElementById('sizeSelectWrapper')); x.captureData();
}






// to populate sub categories
function populateSubCategories(category_id, selected_sub_id)
{
	var x = new Hijax(); x.setContainer( document.getElementById('category_id'));
	x.setUrl("/p/populateSubCategories.php?category_id=" + category_id + '&selected_sub_id=' + selected_sub_id);
	x.setCanvas(document.getElementById('subCategorySelectWrapper')); x.captureData();
}



// to populate sub sub categories
function populateSubSubCategories(sub_id, selected_sub_id, selected_subsub_id)
{
	var x = new Hijax(); x.setContainer( document.getElementById('sub_id'));
	x.setUrl("/p/populateSubSubCategories.php?sub_id=" + sub_id + '&selected_sub_id=' + selected_sub_id + '&selected_subsub_id=' + selected_subsub_id);
	x.setCanvas(document.getElementById('subSubCategorySelectWrapper')); x.captureData();
}






// to populate ranges froma brand_id
function populateRanges(brand_id, selected_range_id)
{
	var x = new Hijax(); x.setContainer( document.getElementById('brand_id'));
	x.setUrl("/p/populateRanges.php?brand_id=" + brand_id + '&selected_range_id=' + selected_range_id);
	x.setCanvas(document.getElementById('rangeSelectWrapper')); x.captureData();
}











function AddProductSizeColourPriceRow()
{
	//var clonedRow = $('table#productSizeColourPriceTable tr:last').clone();
	//$('table#productSizeColourPriceTable').append(clonedRow);
	
	
	//$('table#productSizeColourPriceTable').append($('table#productSizeColourPriceTable tr:last').clone());
	$('table#sizeSelectWrapper').append($('table#sizeSelectWrapper tr:last').clone());
	// highlight the new row so we know which one is the clone...
	$('table#sizeSelectWrapper tr:last td:first strong').text('New Size');
	$('table#sizeSelectWrapper tr:last td strong').css('color', 'red');
	
	
}






function doSlideToggle(subcatClick, arrowId)
{
	$(subcatClick).slideToggle(function()
	{
		var s = $(arrowId).attr('src');
		if ( s == 'img/arrow_down.gif' )
		{
			$(arrowId).attr('src', 'img/arrow_right.gif');
		}
		else
		{
			$(arrowId).attr('src', 'img/arrow_down.gif');
		}
	});
}






// fucntion to prepare links based on dic.layoutBlock
function prepareLayoutBlockLinks()
{
	$('.layoutBlock').click(function()
	{
		window.location = $(this).attr('title');
	});
	
}







// populate delivery address from previous address list
function populateDeliveryAddress(whichAddress)
{
	$.getJSON('/p/getDeliveryAddress.php?address_id=' + whichAddress, function(data)
	{
		var theForm = $('#customerRegistrationForm'); 
		for (var i=0; i<data.length; i++) 
		{ 
		    for ( key in data[i] )
		    { 
		            var value = eval('data[i].' + key); // the cheek ;)
		            $('#' + key, theForm).attr({value:value}); 
		    } 
		}
	});
	// lush!!!
}








// copy address details into delivery address fields...
function copyAddressToDelivery()
{
	// rewrite this you lazy ****. 
	// note to self:
	// surely it took longer to type out that it would to write a nice loop (like above)
	$('#cust_del_title').attr('value', 	$('#cust_title').attr('value'));
	$('#cust_del_first_name').attr('value', $('#cust_first_name').attr('value'));
	$('#cust_del_last_name').attr('value', 	$('#cust_last_name').attr('value'));
	$('#cust_del_address1').attr('value', 	$('#cust_address1').attr('value'));
	$('#cust_del_address2').attr('value', 	$('#cust_address2').attr('value'));
	$('#cust_del_town').attr('value', 	$('#cust_town').attr('value'));
	$('#cust_del_county').attr('value', 	$('#cust_county').attr('value'));
	$('#cust_del_postcode').attr('value', 	$('#cust_postcode').attr('value'));
	// $('#cust_del_country_id').attr('value', $('#cust_country_id').attr('value') == 183 ? '183' : '' ); // 183 is UK in our db of coutries...
	$('#cust_del_telephone').attr('value', 	$('#cust_telephone').attr('value'));
	$('#cust_del_mobile').attr('value', 	$('#cust_mobile').attr('value'));
	$('#cust_del_fax').attr('value', 	$('#cust_fax').attr('value'));
	$('#cust_del_email').attr('value', 	$('#cust_email').attr('value'));
}









function checkRequiredFields()
{
	if ( $('#cust_first_name').val() == '' )
	{
		jAlert('ShopForLeather.co.uk','Please enter your first name');
		return false;
	}

	if ( $('#cust_last_name').val() == '' )
	{
		jAlert('ShopForLeather.co.uk','Please enter your last name');
		return false;
	}

	if ( $('#cust_telephone').val() == '' )
	{
		jAlert('ShopForLeather.co.uk','Please enter your telephone number');
		return false;
	}

	if ( $('#cust_email').val() == '' )
	{
		jAlert('ShopForLeather.co.uk','Please enter your email address');
		return false;
	}

	
	
	
	if ( $('#cust_del_first_name').val() == '' )
	{
		jAlert('ShopForLeather.co.uk','Please enter your first name for delivery');
		return false;
	}

	if ( $('#cust_del_last_name').val() == '' )
	{
		jAlert('ShopForLeather.co.uk','Please enter your last name for delivery');
		return false;
	}

	if ( $('#cust_del_address1').val() == '' )
	{
		jAlert('ShopForLeather.co.uk','Please enter your address (line 1) for delivery');
		return false;
	}

	if ( $('#cust_del_town').val() == '' )
	{
		jAlert('ShopForLeather.co.uk','Please enter your address town for delivery');
		return false;
	}

	if ( $('#cust_del_postcode').val() == '' )
	{
		jAlert('ShopForLeather.co.uk','Please enter your address postcode for delivery');
		return false;
	}

	if ( $('#cust_del_telephone').val() == '' )
	{
		jAlert('ShopForLeather.co.uk','Please enter your telephone number for delivery');
		return false;
	}

	if ( $('#cust_del_email').val() == '' )
	{
		jAlert('ShopForLeather.co.uk','Please enter your email address for delivery');
		return false;
	}

	if ( $('#cust_del_country_id').val() == '' )
	{
		jAlert('ShopForLeather.co.uk','Please select delivery country');
		return false;
	}

	
	return true;
}


function showdeadcenterdiv(divid,Xwidth) { // First, determine how much the visitor has scrolled

	$('#'+divid).width(Xwidth);
	Yheight = $('#'+divid).height();
	
	var scrolledX, scrolledY;
	if( self.pageYOffset ) {
		scrolledX = self.pageXOffset;
		scrolledY = self.pageYOffset;
	} else if( document.documentElement && document.documentElement.scrollTop ) { scrolledX = document.documentElement.scrollLeft;
	scrolledY = document.documentElement.scrollTop;
	} else if( document.body ) {
		scrolledX = document.body.scrollLeft;
		scrolledY = document.body.scrollTop;
	}

	// Next, determine the coordinates of the center of browser's window

	var centerX, centerY;
	if( self.innerHeight ) {
		centerX = self.innerWidth;
		centerY = self.innerHeight;
	} else if( document.documentElement && document.documentElement.clientHeight ) { centerX = document.documentElement.clientWidth;
	centerY = document.documentElement.clientHeight;
	} else if( document.body ) {
		centerX = document.body.clientWidth;
		centerY = document.body.clientHeight;
	}

	// Xwidth is the width of the div, Yheight is the height of the // div passed as arguments to the function:
	var leftOffset = scrolledX + (centerX - Xwidth) / 2; 
	var topOffset = scrolledY + (centerY - Yheight) / 2; 
	
	// The initial width and height of the div can be set in the 
	// style sheet with display:none; divid is passed as an argument to 
	// the function 

	$('#'+divid).css('top',(topOffset-50)+'px');
	$('#'+divid).css('left',leftOffset+'px');
	
}



// do this lot on dom load...
$(function()
{

	$('#brand_cycle, #home_brand_cycle').cycle({
		cleartype:  1 // enable cleartype corrections
	}).css('display','block');
	
	$('#brand_cycle').height($('#brand_cycle div:eq(0)').height());
	
	// top menu
	$('#navigationOne > li')
	.mouseover(function() 
	{
		var t = $(this).attr('title');
		$(".subMenu").not('#' + t).css('display', 'none');
		$('#' + t).css('display', 'block').mouseover(function()
		{
			$(this).css('display', 'block');
		})
		.mouseout(function()
		{
			//$(".subMenu").css('display', 'none');
			var t = $(this).attr('title');
			$(".subMenu").not('#' + t).css('display', 'none');
		});
	});
	
	
	
	
	// populate sub categories from main top-level category
	$('#category_id').change(function(event, selected_sub_id)
	{
		populateSubCategories(this.options[this.options.selectedIndex].value, selected_sub_id);
	});
	
	
	// populate sub sub categories from sub categories
	$('#sub_id').change(function(event, product_id, selectedColours, selected_sub_id, selected_subsub_id)
	{
		populateSubSubCategories(this.options[this.options.selectedIndex].value, selected_sub_id, selected_subsub_id);
		
		// we need to also populate colours when sub cat is selected
		populateSubCategoryColours(this.options[this.options.selectedIndex].value, selectedColours);
		
		// populate sizes when subcat is selected
		//populateSubCategorySizes(this.options[this.options.selectedIndex].value, product_id);
		
	});
	
	
	
	
	
	// populate ranges from brand dropdown
	$('#brand_id').change(function(event, selected_range_id)
	{
		populateRanges(this.options[this.options.selectedIndex].value, selected_range_id);
	});
	
	
	
	
	
	/*
	// table row hovers - front end basket table
	$('table#productSizePriceTable tr.productPriceRow').mouseover(function()
	{
		$(this).addClass('basketRowHover').prev().addClass('basketRowHover');
	}).mouseout(function()
	{
		$(this).removeClass('basketRowHover').prev().removeClass('basketRowHover');
	});
	$('table#productSizePriceTable tr.productSizeRow').mouseover(function()
	{
		$(this).addClass('basketRowHover').next().addClass('basketRowHover');
	}).mouseout(function()
	{
		$(this).removeClass('basketRowHover').next().removeClass('basketRowHover');
	});
	
	$('span.productPriceRRP').mouseover(function()
	{
		$(this).css('text-decoration', 'none');
	}).mouseout(function()
	{
		$(this).css('text-decoration', 'line-through');
	});;
	*/
	
	
	
	// do the layoutblock links (cat, sub, subsub etc)
	prepareLayoutBlockLinks();
	
	
	
	
	
	// ie fixes
	if ( $.browser.msie )
	{
		// padding in sheet is 22px 0 21px 21px. lose 1px off the top for ie.
		$('#breadcrumbWrap').css('padding-top', '21px');
		
		// productImage needs float:left in ie
		$('#productImage').css('float', 'left');

		// sidebar h3 - 1px too high...
		$('#sidebar h3').css('margin', '13px 0 14px 0');

		// shitty ie 7 positioning
		if ( $.browser.version > 6 )
		{
			$('#shopOnlineThing').css({'top':'80px'});
		}

		//  ie 6 
		if ( $.browser.version == 6 )
		{
			$('#shopOnlineThing').css({'position':'relative', 'top':'5px', 'left':'-143px'});
			
			$('.layoutBlockWrap h3 a').css({'display':'block', 'padding':'0 0 0 0', 'margin':'0 0 0 0'});
			// padding:0 0 20px 0; margin:10px 0 0 0;

			$('#breadcrumbWrap').css('padding-top', '21px');
			
			
		}

	}
	
	
	
	// safari fixes
	if ( $.browser.safari )
	{
		// padding in sheet is 22px 0 21px 21px. lose 1px off the top for ie.
		$('#breadcrumbWrap').css('padding-top', '20px');
		
		// safari 3.1 on macbook
		$('#navigationWrap').css({'width':'100%'});
		
	}
	
	
	
	
	
	
	
	// copy address to delivery address handler
	$('#copyAddressToDeliveryButton').click(function()
	{
		copyAddressToDelivery();
		// select top option in the previous address dropdown now
		$('option:first', 'select#delivery_address_id').attr('selected','selected');
	});
	
	
	
	// clickable h1
	$('#header h1').click(function()
	{
		window.location = '/';
	});
	
	var current = '';
	var zindex = 100;
	
	$('.image_zoom').lightBox({fixedNavigation:true});
	
	$('#big_image').cycle({
		speed:    	800,
		timeout:	3000,
		pager:		'#detail_thumbs',
		next:		'#next_image',
		prev:		'#prev_image',
		pagerAnchorBuilder: function(idx, slide) { 
			
			var imgNo = idx + 1;
			imageLoc = $('img:eq(0)',slide).attr('src').replace('l.jpg','s.jpg');
	        return '<img id="thumb'+idx+'" alt="Image '+imgNo+'" src="'+imageLoc+'" />'; 
	    }
	}).css('display','block');
	
	$('#featured_image').cycle({
		speed:    	800,
		timeout:	3000,
		pager:		'#featured_thumbs',
		pagerAnchorBuilder: function(idx, slide) { 
			
			var imgNo = idx + 1;
			var imageLoc = slide.src.replace('l.jpg','xs.jpg');
	        return '<img id="thumb'+idx+'" alt="Image '+imgNo+'" src="'+imageLoc+'" />'; 
	    }
	});
	
	$('#featured_thumbs img:eq(2)').css('margin','0 0 2px 0');
	$('#featured_thumbs img:eq(5)').css('margin','0 0 2px 0');
	$('#detail_thumbs   img:eq(3)').css('margin','0 0 1px 0');
	$('#detail_thumbs   img:eq(7)').css('margin','0 0 1px 0');
	
	/*
	if($('#featured_container').height() > $('#right_column_home').height()){
		$('#right_column_home').height($('#featured_container').height() + 10);
	}
	*/
	$('#featured_thumbs img:eq(0)').trigger('click');
	
	$('#search img').click(function(){
		$('#search').submit();
	}).css('cursor','pointer');
	
	if($.browser.msie && $.browser.version < 7){
		$('#lfade, #rfade').css('display','none');
	}	

	speed = 40;
	setInterval('scroll_brands()',speed);

	/*
	$('#add_to_basket_link').click(function(){

		var dp_height = $('#detail_price').height();
		var dpp_height = $('#detail_price_p').height();
		var dpi_height = $('#detail_price_inner').height();
		
		if(dpp_height == dp_height){
			$('#detail_price').animate({height:dpi_height},350,function(){
				$('#detail_price input:eq(0)').focus();
			});
		}
		
		return false;
	});
	*/
	/*
	$('#add_to_basket').submit(function(){
		
		$('.colourOption').each(function(){
			
			var qty = $(this).val();
			var id = $(this).attr('id').replace('colourOption_','');
			
			var result = '';
			
			$.get('p/add.to.basket.php?id='+id+'&qty='+qty,function(strHtml){
				result = strHtml;
			}
		});
		
		return false;
		
		var qty = $('#add_to_basket_qty').val();
		var id = $('#add_to_basket_qty').attr('name');
		
		$.get('p/add.to.basket.php?id='+id+'&qty='+qty,function(strHtml){
			
			if(strHtml.indexOf("OOS|")==-1){
				
				var itemName = $('h1.product_title:eq(0)').html();
				var realColor = $('#items_in_basket').css('color');
				var newColor = '#ff0000';
				$('#items_in_basket').css('color',newColor).animate({'color':realColor},5000);
				
				$('#items_in_basket').html(strHtml);
				jAlert(itemName,'Thank you. Your basket has been updated.<br /><br />'+
									'<a href="basket.php">Click here to view the contents of your basket.</a>');
				
			}else{
				
				var maxStock = strHtml.replace('OOS|','');
				
				jAlert('Stock limitation','Sorry. Due to stock limitations, the maximum quantity of this product that you can purchase is '+maxStock);
			}
		});
		
		return false;
	});
	*/
	$('#jAlert_close').click(function(){
		
		if($('#jAlert_box').css('opacity')==1){
			$('#jAlert_box').fadeOut();
		}
		
		return false;
	});
	/*
	var footerHeight = $('#footer_home').height();
	
	$('#footer_left').height(footerHeight);
	$('#footer_right').height(footerHeight);
	$('#footer_middle').height(footerHeight);
	*/
	
	$('#checkout_secure').click(function(){
		
		if(checkRequiredFields()){
			jAlert('ShopForLeather.co.uk','Submitting your order...');
			$(this).css('display','none');
			$('#customerRegistrationForm').submit();
		}else{
			return false;
		}
	});
	
	$('#submit_register').click(function(){
		if(checkRequiredFields()){
			$('#customerRegistrationForm').submit();
		}else{
			return false;
		}
	});
	
	$('tr.order_row').mouseover(function(){
		$('td',this).css({
			'background':'#ccc',
			'cursor':'pointer'
		});
	}).mouseout(function(){
		$('td',this).css({
			'background':'#E9E2D2',
			'cursor':'default'
		});
	}).click(function(){
		var ref = $(this).attr('id').replace('order','');
		if($('#order_detail'+ref).css('display') == 'none'){
			if($.browser.msie){
				$('#order_detail'+ref).css('display','block');
			}else{
				$('#order_detail'+ref).css('display','table-row');
			}
		}else{
			$('#order_detail'+ref).css('display','none');
		}
	});
	
	$('#notify').click(function(){
		var id = $(this).val();
		if($(this).attr('checked')==true){
			$.get('p/stock.notify.php?v=1&p='+id,function(){
				jAlert('ShopForLeather.co.uk','Thank you. You will be notified when this product is in stock.');
			});
		}else{
			$.get('p/stock.notify.php?v=0&p='+id,function(){
				jAlert('ShopForLeather.co.uk','Thank you. You will now not be notified when this product is in stock.');
			});
		}
	});
	
	if($.browser.msie){
		$('#feat_price').css('margin','15px 0 0 0');
	}
	
	if($.browser.msie && $.browser.version <= 7){
		$('#detail_price').css('display','block');
	}
	
	$('img').each(function(){
		if($(this).attr('title')=='' || $(this).attr('title')==undefined){
			$(this).attr('title',$(this).attr('alt'));
		}
	});
	
	$('#enlarge_image').click(function(){
		
		$('#big_image div').each(function(){
			if($(this).css('opacity')=='1'){
				var i = $(this).attr('id').replace('big_image','');
				$('#image_zoom'+i).trigger('click');
			}
		});
		
		return false;
	});
	
	$('#privacy_policy').click(function(){
		
		jAlert('Privacy Policy','Any email address that you register with ShopForLeather.co.uk will '+
								'only be used by ShopForLeather for marketing purposes and will NOT '+
								'be passed on to any other third party.');
		
		return false;
	});



	
	$('#cust_del_country_id').change(function()
	{
		// update delivery charge
		if ( $(this).val()=='OtherEU' )
		{
			$.get('p/update.delivery.country.php?del=' + $(this).val(), function(html)
			{
				var delCost = html;
				var del =  $('#wtfTheDelivery').html();
				var tot = $('#wtfTheTotal').html() - del;
				// alert(tot);
                                $('#wtfTheDelivery').html(delCost);
				$('#wtfTheTotal').html( roundNumber(parseFloat(tot) + parseFloat($('#wtfTheDelivery').html()),2) );
			});
		}
		else if ( $(this).val()=='183' )
		{
			$.get('p/update.delivery.country.php?del=183', function(html)
			{
				var delCost = html;
				var del =  $('#wtfTheDelivery').html();
				var tot = $('#wtfTheTotal').html() - del;
				// alert(tot);
                                $('#wtfTheDelivery').html(delCost);
				$('#wtfTheTotal').html( roundNumber(parseFloat(tot) + parseFloat($('#wtfTheDelivery').html()),2) );
			});
		}
		else if ( $(this).val()=='OutsideEU' )
		{
			jAlert('ShopForLeather.co.uk','If you would like your order delivered outside of the European Union,'+
	                       ' please contact us at <a href="mailto:enquiries@shopforleather.co.uk">enquiries@shopforleather.co.uk</a>');
			$('#checkout_secure').css('display','none');
		}else{
			$('#checkout_secure').css('display','block');
		}
	});



	
	$('input.delivery').click(function(){
		$.get('p/update.delivery.php?del='+$(this).val(),function(html){
			if(html != ''){
				
				var delCost = html;
				var subTotal = $('#subtotal').html().replace('£','');
				$('#delivery_total').html('&pound;'+roundNumber(html,2));
				$('#total_cost strong').html('&pound;'+roundNumber(parseFloat(parseFloat(delCost) + parseFloat(subTotal)),2));
			}
		});
	}).css('outline','none');
		
	
	
});

