
$(function() {
	$("#tabs").tabs();
});

$(document).ready(function() {

	$("#brochureRequestForm").validate({
		rules:{name:"required",address1:"required",city:"required",county:"required",postcode:"required",telephone:"required",email:{required:true,email:true},response_method:"required"},
		messages: {
		name: "Please enter your name",
		address1: "Please enter the first line of your address",
		city: "Please enter your city",
		county: "Please enter your county",
		postcode: "Please enter your postcode",
		telephone: "Please enter your telephone number",
		email:
		{
			required: "Please enter your email address",
			email: "Please enter a valid email address"
		},
		response_method: "Please let us know how you would like us to get in touch"}
	});

	$("#contactForm").validate({
		rules:{name:"required",telephone:"required",email:{required:true,email:true},response_method:"required"},
		messages: {
		name: "Please enter your name",
		telephone: "Please enter your telephone number",
		email:
		{
			required: "Please enter your email address",
			email: "Please enter a valid email address"
		},
		response_method: "Please let us know how you would like us to get in touch"}
	});

	$("#guaranteeActivation").validate({
		rules:{name:"required",surname:"required",address1:"required",city:"required",county:"required",postcode:"required",email:{required:true,email:true},purchased:"required",range:"required",type:"required",finish:"required"},
		messages: {
		name: "Please enter your name",
		surname: "Please enter your surname",
		address1: "Please enter the first line of your address",
		city: "Please enter your city",
		county: "Please enter your county",
		postcode: "Please enter your postcode",
		email:
		{
			required: "Please enter your email address",
			email: "Please enter a valid email address"
		},
		purchased: "Please enter the date of your purchase",
		range: "Please select from the list of ranges",
		type: "Please enter the type of shower enclosure you purchased",
		finish: "Please select from the list of finishes"}
	});

	$("#specifierForm").validate({
		rules:{name:"required",telephone:"required",email:{required:true,email:true}},
		messages: {
		name: "Please enter your name",
		telephone: "Please enter your telephone number",
		email:
		{
			required: "Please enter your email address",
			email: "Please enter a valid email address"
		}}
	});


	if ($.browser.msie && $.browser.version=="6.0") {
	//	alert("IE6");
	}

	else {
	
		$("#tab_desc").click(function(){
			$(".ui-widget-header").css("background-image","url(http://www.profileshowers.co.uk/themes/profileshowers/images/tab1_bg.png)");									
		});
	
		$("#tab_feat").click(function(){
			$(".ui-widget-header").css("background-image","url(http://www.profileshowers.co.uk/themes/profileshowers/images/tab2_bg.png)");									
		});
	
		$("#tab_spec").click(function(){
			$(".ui-widget-header").css("background-image","url(http://www.profileshowers.co.uk/themes/profileshowers/images/tab3_bg.png)");									
		});

	}

	//findShowroom left column
	
	
	temp = $("#showroomLocatorForm").html();
	$("#showroomLocatorForm").remove();
	
	$("#showlocator").after('<div id="findShowroom"></div>');
	
	$("#showroomLocator").prepend('<h2>Enter your location to find your nearest Profile Showers stockist</h2><form id="showroomLocatorForm" method="post" action="#"><div class="formRow"><label for="location">Location: </label><input type="text" name="location" id="location" /></div><div class="formRow"><label for="radius">Radius: </label><select name="radius" id="radius" ><option value="5" selected="selected">5 miles</option><option value="20">20 miles</option><option value="50">50 miles</option><option value="100">100 miles</option></select></div><button type="submit" id="btnFindShowroomSubmit">Search</button></form><ul id="locatedShowrooms"></ul>');
	
	$("#showroomLocatorForm").append('<img src="/themes/profileshowers/images/spinnerGrey.gif" width="24" height="24" id="showroomLocatorSpinner" alt="Loading..." style="display:none;"/>');
	
	$("#findShowroom").html('<p>Use the showroom locator to find your nearest Profile Showers stockist.<a href="#" id="btnFindShowroom">Find a showroom near you</a></p>');


	$("#showlocatorProduct").after('<div id="findShowroomProduct"></div>');
	$("#findShowroomProduct").html('<div><a href="#" id="btnFindShowroom">Find a showroom near you</a></div>');

	//hide form
//	$("#newsletterForm").hide();
	
	//add button to show form
//	$("#newsletter-signup.index").append('<p><a href="#newsletterSignup" id="btnEnterEmail">Enter your details</a></p>');
	
	//Form placeholders
	$("#nlName").focus(function(){
		if($(this).val() == "Name")
			$(this).val("");
	});
	
	$("#nlEmail").focus(function(){
		if($(this).val() == "Email")
			$(this).val("");
	});
	
	if($("#nlName").val() == "")
		$("#nlName").val("Name");
	
	$("#nlName").blur(function(){
		if($(this).val() == "")
			$(this).val("Name");
	});

	if($("#nlEmail").val() == "")
		$("#nlEmail").val("Email");

	$("#nlEmail").blur(function(){
		if($(this).val() == "")
			$(this).val("Email");
	});
		
	$("#btnEnterEmail").click(function(){
		$(this).fadeOut(400);
		$("#newsletterForm").slideDown(1000);
		
		$("#newsletterForm").validate({
			rules:{nlName:"required", nlEmail:{required:true,email:true}},
			messages: {
			nlName: "Please enter your name.",
			nlEmail:
			{
				required: "Please enter your email address.",
				email: "Please enter a valid email address."
			}},

			submitHandler: function(form)
			{
				if($("#nlName").val() == "Name")
				{
					$("#nlName").parent().append('<label for="nlName" generated="true" class="error" style="display: block;">Please enter your name.</label>')
					$("#nlName").val("");
				}
				else
				{
					$("#spinner").show();
					$("#btnNewsletterSubmit").remove();
					
					var name = $("#nlName").val();
					var email = $("#nlEmail").val();
					
					$.ajax({
						type: "POST",
						url: "newsletter_post.php",
						data: "nlName="+name+"&nlEmail="+email+"&ajax=true",
						success: function(msg){
							$("#keepInTouch").html(msg);
						}
					});	
				}
			},
			invalidHandler:function(form,validator)
			{
				if($("#nlName").val() == "Name")
				{
					$("#nlName").parent().append('<label for="nlName" generated="true" class="error" style="display: inline;">Please enter your name.</label>')
					$("#nlName").val("");
				}
			}
		});
		
		$("#btnNewsletterSubmit").prev().after('<img src="/themes/profileshowers/images/spinner.gif" width="24" height="24" id="spinner" alt="Loading..." style="display:none;"/>');
		return false;
	});
	
	
	//maps & showroom locator
	
	var map;
    var geocoder;
	var depth = 5;
	
	//showroom locator
	
	$("#btnFindShowroom").click(function(){
		$("#showroomLocator").modal({closeHTML:'<a href="#">Close</a>', closeClass:('modalCloseImg'), overlayCss:({'background-color':'#000000'})});
		if (GBrowserIsCompatible()) {
			
			geocoder = new GClientGeocoder();
			map = new GMap2(document.getElementById('map'));
			map.addControl(new GSmallMapControl());
			map.addControl(new GMapTypeControl());
			map.setCenter(new GLatLng(53.923024, -3.012721), depth);
		}
		return false;
	});
	
	//showroom search
	$("#showroomLocatorForm").submit(function(){

//if empty don't submit
if($("#location").val()!='')
                                {

		$('#btnFindShowroomSubmit').attr('disabled', 'disabled');
		$("#btnFindShowroomSubmit").hide();
		$("#showroomLocatorSpinner").show();

// end  if empty
}
		//reset
		$("#locatedShowrooms").html('');
		map.clearOverlays();
		
		loc = $("#location").val();
		radius = $("#radius").val();
		
		geocoder.getLatLng(loc, function(center) {
			if (!center) {
				$("#btnFindShowroomSubmit").show();
				$("#showroomLocatorSpinner").hide();			
				map.setCenter(new GLatLng(53.923024, -3.012721), 5);
				$("#locatedShowrooms").append('<li class="last">The location you have entered could not be found.</li>');
			}
			else {
				//alert("lat="+center.y+"&lng="+center.x+"&radius="+radius);
				$.ajax({
					type: "GET",
					url: "/inc/gen_xml.php",
					data: "lat="+center.y+"&lng="+center.x+"&radius="+radius,
					dataType: "xml",
					success: function(xml){
						//parse xml
						//name
						var name = new Array();
						//address
						var address1 = new Array();
						var address2 = new Array();
						var city = new Array();
						var county = new Array();
						//postcode
						var postcode = new Array();
						//contact
						var telephone = new Array();
						var mobile = new Array();
						//var email = new Array();
						//geo
						var latitude = new Array();
						var longitude = new Array();
						//premium
						var priority = new Array();
						
						var minLat = null;
						var maxLat = null;
						
						var minLng = null;
						var maxLng = null;
						
						//xml into arrays
						$('marker',xml).each(function(i){
							name[i] = $(this).attr("name");
							address1[i] = $(this).attr("address1");
							address2[i] = $(this).attr("address2");
							city[i] = $(this).attr("city");
							county[i] = $(this).attr("county");
							postcode[i] = $(this).attr("postcode");
							telephone[i] = $(this).attr("telephone");
							mobile[i] = $(this).attr("mobile");
							//name[i] = $(this).attr("email");
							latitude[i] = $(this).attr("lat");
							if(minLat == null || $(this).attr("lat") < minLat)
							{
								minLat = $(this).attr("lat");
							}
							if(maxLat == null || $(this).attr("lat") > maxLat)
							{
								maxLat = $(this).attr("lat");
							}
							longitude[i] = $(this).attr("lng");
							if(minLng == null || $(this).attr("lng") < minLng)
							{
								minLng = $(this).attr("lng");
							}
							if(maxLng == null || $(this).attr("lng") > maxLng)
							{
								maxLng = $(this).attr("lng");
							}
							priority[i] = $(this).attr("priority");
						});
						
						if(name.length > 0)
						{
							//add markers to map & results to list
							for(var i=0; i < name.length; i++)
							{
								//result
								result = '<p class="name">'+name[i]+'</p><p class="address">';
								if(address1[i] != "")
								{
									result += address1[i] + ', ';
								}
								if(address2[i] != "")
								{
									result += address2[i];
								}
								if(city[i] != "")
								{
									result += '<br />'+city[i];
								}
								if(county[i] != "")
								{
									result += ', ' + county[i];
								}
								if(postcode[i] != "")
								{
									result += ' ' + postcode[i];
								}
								result += '</p><p class="contact">';
								if(telephone[i] != "")
								{
									result += '<span>T: </span>' + telephone[i];
								}
								if(mobile[i] != "")
								{
									result += '<br /><span>M: </span>' + mobile[i];
								}
								result += '</p>';
								
								if(priority[i] == 0)
								{
									//marker
									var point = new GLatLng(parseFloat(latitude[i]),parseFloat(longitude[i]));
									var marker = createMarker(point, result);
									//TODO: Custom Markers
									map.addOverlay(marker);
									result = '<li>\n' + result + '</li>';
								}
								else
								{
									//marker
									var point = new GLatLng(parseFloat(latitude[i]),parseFloat(longitude[i]));
									var marker = createPremiumMarker(point, result);
									//TODO: Custom Markers
									map.addOverlay(marker);
									result = '<li>\n<div class="premium">\n<h3 class="premiumHeader">Premium Showroom</h3>\n' + result + '</div>\n</li>';	
								}
								
								
								$("#locatedShowrooms").append(result);
								
							}
							
							
							
							miles = (3958.75 * Math.acos(Math.sin(minLat / 57.2958) * Math.sin(maxLat / 57.2958) + Math.cos(minLat / 57.2958) * Math.cos(maxLat / 57.2958) * Math.cos(maxLng / 57.2958 - minLng / 57.2958)));
							
							centerLatitude = ((parseFloat(maxLat) - parseFloat(minLat)) / 2) + parseFloat(minLat);
							centerLongitude = ((parseFloat(maxLng) - parseFloat(minLng)) / 2) + parseFloat(minLng);
							
							var zoom = Math.floor(8 - Math.log(1.6446 * miles / Math.sqrt(2 * (400 * 400))) / Math.log (2));
							
							if(radius == 100)
							{
								zoom = 7;	
							}
							else if(radius == 50)
							{
								zoom = 8;
							}
							else if(radius == 20)
							{
								zoom = 8;
							}
							else
							{
								zoom = 12;	
							}
							
							
							map.setCenter(new GLatLng(centerLatitude,centerLongitude), zoom);

						}
						else
						{
							$("#btnFindShowroomSubmit").show();
							$("#showroomLocatorSpinner").hide();
							$("#locatedShowrooms").append('<li class="last">No showrooms found.</li>');
							map.setCenter(new GLatLng(53.923024, -3.012721), 5);
						}
						
						$("#btnFindShowroomSubmit").show();
						$("#showroomLocatorSpinner").hide();
						$('#btnFindShowroomSubmit').removeAttr('disabled');
						},
					error: function (XMLHttpRequest, textStatus, errorThrown) {
						$("#locatedShowrooms").append('<li class="last">An error has occurred. Please try again.</li>');
						//$("#locatedShowrooms").append('<li class="last">'+textStatus+': '+errorThrown+'</li>');
						$("#btnFindShowroomSubmit").show();
						$("#showroomLocatorSpinner").hide();
						map.setCenter(new GLatLng(53.923024, -3.012721), 5);
						
					}
				});
			}
		});
		return false;
	});
	
	function createMarker(point, html) {
		var myIcon = new GIcon();
		myIcon.image = '/themes/profileshowers/images/markers/standard/image.png';
		myIcon.printImage = '/themes/profileshowers/images/markers/standard/printImage.gif';
		myIcon.mozPrintImage = '/themes/profileshowers/images/markers/standard/mozPrintImage.gif';
		myIcon.iconSize = new GSize(20,29);
		myIcon.shadow = '/themes/profileshowers/images/markers/standard/shadow.png';
		myIcon.transparent = '/themes/profileshowers/images/markers/standard/transparent.png';
		myIcon.shadowSize = new GSize(35,29);
		myIcon.printShadow = '/themes/profileshowers/images/markers/standard/printShadow.gif';
		myIcon.iconAnchor = new GPoint(10,29);
		myIcon.infoWindowAnchor = new GPoint(10,0);
		myIcon.imageMap = [14,0,15,1,16,2,17,3,18,4,19,5,19,6,19,7,19,8,19,9,19,10,19,11,19,12,19,13,19,14,19,15,18,16,17,17,16,18,15,19,15,20,14,21,14,22,13,23,12,24,12,25,11,26,11,27,10,28,8,28,8,27,7,26,7,25,6,24,6,23,5,22,4,21,4,20,4,19,2,18,1,17,1,16,0,15,0,14,0,13,0,12,0,11,0,10,0,9,0,8,0,7,0,6,0,5,1,4,1,3,2,2,4,1,4,0];
		var marker = new GMarker(point, myIcon);
		
		GEvent.addListener(marker, 'click', function() {
			marker.openInfoWindowHtml(html);
		});
		return marker;
	}
	
	function createPremiumMarker(point, html) {
		var myIcon = new GIcon();
		myIcon.image = '/themes/profileshowers/images/markers/premium/image.png';
		myIcon.printImage = '/themes/profileshowers/images/markers/premium/printImage.gif';
		myIcon.mozPrintImage = '/themes/profileshowers/images/markers/premium/mozPrintImage.gif';
		myIcon.iconSize = new GSize(29,48);
		myIcon.shadow = '/themes/profileshowers/images/markers/premium/shadow.png';
		myIcon.transparent = '/themes/profileshowers/images/markers/premium/transparent.png';
		myIcon.shadowSize = new GSize(53,48);
		myIcon.printShadow = '/themes/profileshowers/images/markers/premium/printShadow.gif';
		myIcon.iconAnchor = new GPoint(15,48);
		myIcon.infoWindowAnchor = new GPoint(10,0);
		myIcon.imageMap = [17,0,20,1,22,2,23,3,24,4,25,5,26,6,26,7,27,8,27,9,28,10,28,11,28,12,28,13,28,14,28,15,28,16,28,17,27,18,27,19,27,20,26,21,26,22,25,23,24,24,23,25,22,26,21,27,21,28,21,29,20,30,20,31,20,32,19,33,19,34,19,35,18,36,18,37,18,38,17,39,17,40,17,41,16,42,16,43,16,44,15,45,15,46,15,47,15,47,14,46,14,45,13,44,13,43,13,42,12,41,12,40,11,39,11,38,11,37,10,36,10,35,10,34,9,33,9,32,8,31,8,30,8,29,7,28,7,27,6,26,5,25,4,24,3,23,2,22,2,21,1,20,1,19,0,18,0,17,0,16,0,15,0,14,0,13,0,12,0,11,0,10,1,9,1,8,2,7,2,6,3,5,4,4,5,3,6,2,8,1,10,0];

		var marker = new GMarker(point, myIcon);
		
		GEvent.addListener(marker, 'click', function() {
			marker.openInfoWindowHtml(html);
		});
		return marker;
	}
	
	

	//alert("END");
});


