/***********************************
**
**	Heat Pumps Direct
**	Copyright 2010+
**
**	Michael Wright
**	michael@michaelwright.me
**
***********************************/

var rand = Math.floor(Math.random()*(new Date().getTime()));

/**
*	Unique Checkboxes
**/
function unique(x, y){
	z = (typeof x == "object" ? '#' + x.parentNode.id : (!x.match(/^\./)? '#' : '') + x);
	y = (typeof y == 'undefined'? 1 : y);
	if(y == 1){
		$(z + " input:not(:submit)").each(function(){
			if($(this).val() != $(x).val())
				$(this).removeAttr("checked");
		});
		$('#pump_form').submit();
	}else{
		if($(z + " input:checked").length == y)
			$(z + " input:not(:checked):not(:submit)").attr("disabled", "disabled");
		else
			$(z + " input:not(:checked):not(:submit)").removeAttr("disabled");
	}
}

/**
*	'Help Me Choose' Boxes
**/
function toggle(y){
	if(y.name == 'other'){
		$(".other").slideDown();
		$("#application-check").attr("checked", "true");
		$("#application input").each(function(){
			$(this).removeAttr("disabled");
			$(this).removeAttr("checked");
		});
	}else if(y.name == 'other2'){
		$(".other2").slideDown();
		$("#type-check").attr("checked", "true");
	}else{
		if(y.value == 'heating-hot-water|efficient')
			$(".other").slideUp();
		if(y.id == 'as')
			$(".other2").slideUp();
		if(y.value == 'heating-hot-water|efficient')
			$("#other-check").attr("checked", "true");
		if(y.id == 'as')
			$("#other2-check").attr("checked", "true");
		$("#" + y.name + " input").each(function(){
			if($(this).val().match(new RegExp("^(" + y.value + ")$"))){
				$(this).next().fadeOut("slow", function(){
					$(this).prev().attr("checked", "true");
					$(this).fadeIn("slow");
				});
			}else{
				$(this).removeAttr("checked");
			}
		});
	}
}

/**
*	Add Commas to Price
**/
function formatPrice(x){
	x = Math.round(x*100)/100;
	while(/(\d+)(\d{3})/.test(x))
		x = x.toString().replace(/(\d+)(\d{3})/, "$1" + "," + "$2");
	return x.toString().replace(/\.([0-9])$/, ".$10");
}

/**
*	Remove Item
**/
function removeItem(x){
	$("#" + x).val(0);
	calcPrice('#' + x);
}

/**
*	Products page toggle
**/
function tabLoad(x, y) {
    $.get("./ajax/product." + x + ".php", {id: y}, 
		function(data){
			$('#tab_holder').html(data);
		}
	);
}

/**
*	Update Price
**/
function calcPrice(x){
	$(x).val($(x).val().replace(/[^0-9]/, ''));
	$.getJSON('./ajax/basket-information.php', {id: $(x).attr("id"), qty: $(x).val()}, function(d){
		if(parseInt($(x).val()) != '0' && $(x).val() != '')
			$(x).parent().next().addClass("highlight").html(d.item);
		else{
			$(x).parent().next().html(0);
			$(x).parent().parent().fadeOut("fast", function(){
				$(this).remove();	
			});
		}
		$("#total").html(formatPrice(d.total)).parent().addClass('highlight');
		$("#qty").html(d.qty).addClass('highlight');
		$("#subtotal").html(formatPrice(d.subtotal)).parent().addClass('highlight');
		$("#saving").html(formatPrice(d.saving)).parent().addClass('highlight');
		$('#basket').html(formatPrice(d.qty) + " item" + (d.qty == 1? '' : 's') + " - &pound;" + formatPrice(d.total));
		$('#vat').html(formatPrice(d.vat)).parent().addClass('highlight');;
		$('#supertotal').html(formatPrice(d.supertotal)).parent().addClass('highlight');;
		setTimeout(function(){
			$("#total, #subtotal, #saving, #vat, #supertotal").parent().removeClass('highlight');
			$("#qty").removeClass('highlight');
			$(x).parent().next().removeClass("highlight");
		}, 700);
	});
}

/**
*	Checkout Login Toggle - Yes
**/
function togglePassYes(x){
	if($(x).attr('checked')){
		$('#pass').fadeIn();
		$('.register').fadeOut();
	}
}

/**
*	Checkout Login Toggle - No
**/
function togglePassNo(x){
	if($(x).attr('checked')){
		$('#pass').fadeOut(); 
		$('.register').fadeIn();
	}
}
/**
*	Send Contact Form
**/
function sendContact(){
	$('#submit').attr("disabled", "true");
	$.get("./ajax/contact.php", {name: $('#name').val(), email: $('#email').val(), telephone: $('#telephone').val(), message: $('#message').val()},
		function(data){
			$('#result').html(data);
			$('#submit').removeAttr("disabled");
			if(data.match(/sent/))
				$('#contact input[type=text], #contact textarea').val('');
			setTimeout(function(){
				$('#result div').slideUp("slow");
			}, 2000);
		}
	);
}

/**
*	Get Address
**/
function getAddress(x){
	$.get("./ajax/address.php", {id: $(x).val()},
		function(data){
			$('#address').html(data).addClass("highlight");
			setTimeout(function(){
				$("#address").removeClass("highlight");
			}, 700);
		}
	);
}
/**
*	Countdown
**/
function updateTime(x){
	var n = new Date();
	$.get("./ajax/countdown.php", {id: n.getTime()},
		function(data){
			$('#countdown').html(data);
			setTimeout(function(){
				updateTime();
			}, 800);
		}
	);
}

/**
*	Add Item to Basket
**/
function basket(x){
	$.get("./ajax/basket.php", {id: x}, 
		function(data){
			$('#basket').html(data);
			$('#add-to-basket').html("<em>Added</em>");
			setTimeout(function(){
				$('#add-to-basket').html("<a href='javascript: void(0);' onclick='basket(" + x + ");'>Add to basket</a>");
			}, 700);
		}
	);
}

/**
*	Add Item to Basket
**/
function basketCompare(x){
	$.get("./ajax/basket.php", {id: x}, 
		function(data){
			$('#basket').html(data);
			$('#add-to-basket' + x).html("<em>Added</em>");
			window.location = $('#link-' + x).attr('href') + '-accessories';
		}
	);
}

/**
*	Add Accessories to Basket
**/
function basketUpdate(){
	var x = []; var y = [];
	$('.qty').each(function(){
		x.push($(this).attr('name'));
		y.push($(this).val());
	});
	$.get("./ajax/basket.php", {id: x.join(","), val: y.join(","), stamp: rand}, 
		function(data){
			$('#basket').html(data);
		}
	);
}

/**
*	Dropdown Toggle
**/
function showMore(x){
	$(x).parent().next().slideToggle();
	$(x).children().attr("src", "./images/" + ($(x).children().attr("src").match(/down/)? 'up' : 'down') + ".png");
}

/**
* 	Help me choose
**/
var hmcimages = ['ground-loops', 'vertical-boreholes'];
function hmcImage(){
	$('#image1').fadeOut(1500, function(){
		$(this).attr("src", "./images/" + ($(this).attr('src').match(hmcimages[0])? hmcimages[1] : hmcimages[0]) + ".gif").fadeIn(1500, function(){
			setTimeout(function(){
				hmcImage();
			}, 2000);
		});
	});
}

/**
*	Accessories Micro Basket
**/
function microBasket(){
	var qty = 0; 
	var price = 0;
	var total = 0;
	var discount = 0;
	var hp = 0;
	$(".qty").each(function(){
		$(this).val($(this).val().replace(/[^0-9]/g, '')*1);
		qty += parseInt($(this).val());
		price = $('span', $(this).parent().prev()).last().text().replace(/\,/g, '');
		total += price * parseInt($(this).val());
		if($(this).attr('class').match(/heatpump_item/))
			hp = price*1;
		if($(this).attr('class').match(/related_cylinder/) && price > discount){
			if(parseInt($(this).val()) != 0){
				discount = price*1;	
				$('.saving').show();
			}else
				discount = 0;
		}
	});
	if(discount == 0)
		$('.saving').hide();
	else
		discount = (hp+discount)-((hp+discount)/0.8)*0.775;
	$('#saving').html(formatPrice(discount));
	$("#total").html(formatPrice(total-discount));
	$("#subtotal").html(formatPrice(total));
}



$(window).load(function(){
	$('#slideshow-1').slideShow();
	$('#slideshow-2').children('img:gt(0)').hide();
	setTimeout(function(){
		$('#slideshow-2').slideShow();
	}, 4000);
	setTimeout(function(){
		hmcImage();
	}, 1000)
});

/**
*	SlideShow jQuery Plugin v1.2
*	Michael Wright
*	http://michaelwright.me
**/
var slideShows = [];
$.fn.slideShow = function(){
	$(this).children('img:gt(0)').hide();
	slideShows[$(this).attr('id')] = {'imgs': $(this).children('img'), 'i': 0};
	changeImages($(this).attr('id'));
};
function changeImages(x){
	$(slideShows[x]['imgs'][slideShows[x]['i']]).fadeOut(1500,
		function(){
			slideShows[x]['i'] = (slideShows[x]['i'] < slideShows[x]['imgs'].length-1? slideShows[x]['i'] + 1 : 0);
			$(slideShows[x]['imgs'][slideShows[x]['i']]).fadeIn(1500, 
				function(){
					setTimeout(function(){
						changeImages(x);
					}, 5000);
				}
			);
		}
	);
}
function qualifications(){
	var quals = [];
	$('.qual:checked').each(function(){
		quals.push($(this).val());
	});
	if($('.qual:checked').length < 1){
		if($('#type-person option:selected').val().match(/(private|contractor)/))
			alert('Please confirm your installer\'s qualifications.');
		else
			alert('Please confirm your qualifications.');
		return false;
	}else{
		$.get("./ajax/qualifications.php", {quals: quals.join(','), type: $('#type-person option:selected').val(), nocache: rand}, 
			function(data){
				$('#result').html(data).slideDown();
			}
		);
	}
}


$(document).ready(function(){
	$('.search input').click(function(){
		(this.value == search? this.value = '' : void(0));
	}).blur(function(){
		this.value = (this.value == ''? search : this.value);
	});
	$('.clicktab').click(function(){
		if($(this).children('a').length)
			location.href = $(this).children("a:eq(0)").attr("href");	
	});
	setTimeout(function(){
		if($('#countdown').length == 1)
			updateTime();
	}, 100);
	$('#as, #ai').click(function(){
		hmcimages = ['inside-heat-pump', 'outside-heat-pump'];
		$('#image1').attr("src", "./images/" + hmcimages[0] + ".gif");
	});
	$('#gs').click(function(){
		$('#image1').parent().hide();
		$('#air-source, #ground-source, #water-source').each(function(){
			$(this).removeAttr('checked');
		});
	});
	$('#gr, #ai').click(function(){
		$('#help_text').slideUp();
		$('#image1').parent().show();
	});
	$('#gr').click(function(){
		$('#meow').slideUp();	
	});
	$('#ai').click(function(){
		$('#meow').slideDown();	
	});
	var x;
	$('.picker input[type=checkbox]').mouseover(function(){
		if(!$(this).attr("checked")){
			x = 1;
			$(this).attr("checked", "true");
		}else
			x = 0;
	}).click(function(){
			if(x){
				$(this).attr("checked", "true");
				x = 0;
			}else
				$(this).removeAttr("checked");
		if(!$(this).attr('name').match(/manufacturer/))
			unique(this);
		else
			$("#pump_form").submit();
	}).mouseleave(function(){
		if(x == 1)
			$(this).removeAttr("checked");
	});
	$('.picker label').mouseover(function(){
		if(!$(this).prev().attr("checked")){
			x = 1;
			$(this).prev().attr("checked", "true");
		}else
			x = 0;
	}).mouseleave(function(){
		if(x == 1)
			$(this).prev().removeAttr("checked");
	}).click(function(y){	
			y.preventDefault();
			if(x){
				$(this).prev().attr("checked", "true");
				x = 0;
			}else
				$(this).prev().removeAttr("checked");
		if(!$(this).prev().attr('name').match(/manufacturer/))
			unique(this.previousSibling);
		else
			$("#pump_form").submit();
	});
	$('.stage').hover(function(){
		var n = ($(this).attr('class').match(/stage_off/)? '_on' : '_off');
		$(this).removeClass('stage_off').removeClass('stage_on').addClass('stage' + n);
		$(this).children('img').each(function(){
			$(this).attr('src', $(this).attr('src').replace(/_o(n|ff)/, n));
		});	
	}).click(function(){
		$('#lolimages').slideUp();
		$('#stage_text p').not($('#stage_text p:eq(' + $(this).index() + ')')).slideUp();
		$('#stage_text p').eq($(this).index()).slideDown();
	});
	$('#type-person').change(function(){
		$('.question, #result, #using, #installer-details, #they').hide();
		$('#i').show();
		switch($(this).val()){
			case 'accredited':
				$('#numbers').slideDown();
				break;
			case 'engineer':
				$('#accredited').val('');
				$('#accredited-question').slideDown();
				break;
			case 'contractor':			
			case 'private':
				$('#i').hide();
				$('#accredited').val('');
				$('#accredited-question').slideDown();
				$('#using, #they').show();
				$('#installer-details').slideDown();
				
				break;
		}
	});
	$('#accredited').change(function(){
		if($(this).val() == 'yes'){
			$('#numbers').slideDown();
			$('#not-accredited').slideUp();
		}else if($(this).val() == 'no'){
			$('#numbers').slideUp();
			$('#not-accredited').slideDown();
			$('#not-accredited input:checked').each(function(){
				$(this).removeAttr('checked');
			});
		}else
			$('#numbers, #not-accredited').slideUp();
	});
	$('#submit-button').click(function(){
		var proceed = false;
		switch($('#type-person option:selected').val()){
			case 'accredited':
				if($('#dimplex-accred').val() == '' && $('#ecodan-accred').val() == ''){
					alert('Please ensure you have entered your accreditation number(s).');
					proceed = false;
				}else{
					proceed = true;
				}
			break;
			case 'engineer':
				if($('#accredited').val() == 'yes'){
					if($('#dimplex-accred').val() == '' && $('#ecodan-accred').val() == ''){
						alert('Please ensure you have entered your accreditation number(s).');	
					}else{
						proceed = true;
					}
				}else if($('#accredited').val() == 'no'){
					if($('#result').html().match(/do(es)?\snot\shave/)){
						proceed = false;
					}else{
						if($('#commission:checked').length > 0)
							proceed = true;
						else
							proceed = false;
					}
				}
			break;
			case 'contractor':
			case 'private':
				if($('#installer-name').val() == '' || $('#installer-number').val() == ''){
					alert('Please enter installer details');
					return false;
				}else if($('#accredited').val() == 'yes'){
					if($('#dimplex-accred').val() == '' && $('#ecodan-accred').val() == ''){
						alert('Please ensure you have entered your accreditation number(s).');	
						proceed = false;
					}else{
						proceed = true;
					}		
				}else{
					if($('#result').html().match(/do(es)?\snot\shave/)){
						proceed = false;
					}else{
						if($('#commission:checked').length > 0)
							proceed = true;
						else
							proceed = false;
					}
				}
			break;
			default:
				alert('Please ensure you have completed your profile type.');
	
		}
		var quals = [];
		$('.qual:checked').each(function(){
			quals.push($(this).val());
		});
		if(proceed){
			$.get("./ajax/savequals.php", {quals: quals.join(','), type: $('#type-person option:selected').val(), dimplex: $('#dimplex-accred').val(), ecodan: $('#ecodan-accred').val(), accredited: $('#accredited').val(), installerName: $('#installer-name').val(), installerNumber: $('#installer-number').val(), commission: ($('#commission:checked').length > 0? 'yes' : 'no')}, 
				function(data){
					if(data.match(/success/))
						window.location = location.href.replace(/basket/, 'my-account/login');					
				}
			);
			return false; 
		}else{
			return false;
		}
	});
});
