/**
 * jQuery.ScrollTo - Easy element scrolling using jQuery.
 * Copyright (c) 2007-2009 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com
 * Dual licensed under MIT and GPL.
 * Date: 5/25/2009
 * @author Ariel Flesler
 * @version 1.4.2
 *
 * http://flesler.blogspot.com/2007/10/jqueryscrollto.html
 */
;(function(d){var k=d.scrollTo=function(a,i,e){d(window).scrollTo(a,i,e)};k.defaults={axis:'xy',duration:parseFloat(d.fn.jquery)>=1.3?0:1};k.window=function(a){return d(window)._scrollable()};d.fn._scrollable=function(){return this.map(function(){var a=this,i=!a.nodeName||d.inArray(a.nodeName.toLowerCase(),['iframe','#document','html','body'])!=-1;if(!i)return a;var e=(a.contentWindow||a).document||a.ownerDocument||a;return d.browser.safari||e.compatMode=='BackCompat'?e.body:e.documentElement})};d.fn.scrollTo=function(n,j,b){if(typeof j=='object'){b=j;j=0}if(typeof b=='function')b={onAfter:b};if(n=='max')n=9e9;b=d.extend({},k.defaults,b);j=j||b.speed||b.duration;b.queue=b.queue&&b.axis.length>1;if(b.queue)j/=2;b.offset=p(b.offset);b.over=p(b.over);return this._scrollable().each(function(){var q=this,r=d(q),f=n,s,g={},u=r.is('html,body');switch(typeof f){case'number':case'string':if(/^([+-]=)?\d+(\.\d+)?(px|%)?$/.test(f)){f=p(f);break}f=d(f,this);case'object':if(f.is||f.style)s=(f=d(f)).offset()}d.each(b.axis.split(''),function(a,i){var e=i=='x'?'Left':'Top',h=e.toLowerCase(),c='scroll'+e,l=q[c],m=k.max(q,i);if(s){g[c]=s[h]+(u?0:l-r.offset()[h]);if(b.margin){g[c]-=parseInt(f.css('margin'+e))||0;g[c]-=parseInt(f.css('border'+e+'Width'))||0}g[c]+=b.offset[h]||0;if(b.over[h])g[c]+=f[i=='x'?'width':'height']()*b.over[h]}else{var o=f[h];g[c]=o.slice&&o.slice(-1)=='%'?parseFloat(o)/100*m:o}if(/^\d+$/.test(g[c]))g[c]=g[c]<=0?0:Math.min(g[c],m);if(!a&&b.queue){if(l!=g[c])t(b.onAfterFirst);delete g[c]}});t(b.onAfter);function t(a){r.animate(g,j,b.easing,a&&function(){a.call(this,n,b)})}}).end()};k.max=function(a,i){var e=i=='x'?'Width':'Height',h='scroll'+e;if(!d(a).is('html,body'))return a[h]-d(a)[e.toLowerCase()]();var c='client'+e,l=a.ownerDocument.documentElement,m=a.ownerDocument.body;return Math.max(l[h],m[h])-Math.min(l[c],m[c])};function p(a){return typeof a=='object'?a:{top:a,left:a}}})(jQuery);


(function($){
	
	// ============================================== //
	
			// Branch List Accordian //
	
	// ============================================== //
	
	
	$.fn.initAccordian = function(){
		var target = this;
		
		target.find('li h3 a').each(function(i){
			$(this).data('thisnum',i).hover(function(){
				var myNum = $(this).data('thisnum');
				showMapTip($('#map_nav').children('a').eq(myNum).attr('xpos'), $('#map_nav').children('a').eq(myNum).attr('ypos'), $('#map_nav').children('a').eq(myNum).html());
			}, function(){
				hideMapTip();
			}).click(function() {  
				clickAccordian($(this))
				return false;  
			});
		
		});

		clickAccordian  = function(thisTarget){
			if(thisTarget.parent().parent().hasClass('current')) {  
				thisTarget.parent().siblings('ul').slideUp(400,function() {  
					//$.scrollTo(target,1000);  
				}).parent().removeClass('current');  ;
			} else {
				target.find('li.current ul').slideUp(400,function() { 
				}).parent().removeClass('current');  
				
				thisTarget.parent().siblings('ul').slideToggle(400, function() {
				}).parent().toggleClass('current');
				//$.scrollTo(target,1000);
			}
		}
	};
	
	// ============================================== //
	
			// Map Navigation //
	
	// ============================================== //
	
	$.fn.initMapNav = function(){
		var target = this;
		
		
		var mapArrow = $('#map_pointer');
		mapArrow.animate({opacity: 0}, 0.001, function(){
			$(this).show();
		});
		
		//
		target.find('a').each(function(i){
			$(this).data('thisnum',i).hover(function() {
				$('#branch_list').children('li').eq($(this).data('thisnum')).children('h3').children('a').addClass('active');
				showMapTip($(this).attr('xpos'), $(this).attr('ypos'), $(this).html());
			}, function() {
				$('#branch_list').children('li').eq($(this).data('thisnum')).children('h3').children('a').removeClass('active');;
				hideMapTip();
			}).click(function(){
				clickAccordian($('#branch_list').children('li').eq($(this).data('thisnum')).children('h3').children('a'));
			})
		});
		
		showMapTip = function(thisX, thisY, placeName){
			mapArrow.css({'left':parseInt(thisX), 'top':parseInt(thisY)}).find('span').html(placeName).parent().stop().animate({opacity: 1}, 200);
		};
		
		hideMapTip = function(){
			mapArrow.stop().animate({opacity: 0}, 300);
		};
		
	};
	
	// ============================================== //
	
			// Get a quote //
	
	// ============================================== //
	
	$.fn.initQuote = function(){
		
		function echeck(str) {
			var at="@";
			var dot=".";
			var lat=str.indexOf(at);
			var lstr=str.length;
			var ldot=str.indexOf(dot);
			if (str.indexOf(at)==-1){
				return false;
			};
			if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
				return false;
			};
			if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
				return false;
			};
			if (str.indexOf(at,(lat+1))!=-1){
				return false;
			};
			if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
				return false;
			};
			if (str.indexOf(dot,(lat+2))==-1){
				return false;
			};
			if (str.indexOf(" ")!=-1){
				return false;
			};
			return true;				
		};
		
		$('p#quote_js').hide();
		$('ul#quote_list').show();
		
		// --------------- 25, 35, 50, 75, 100, 120, 125, 140, 150, 200
		var priceChelt = [45,68,90,130,150,false,175,false,false,false];
		var priceCiren = [47,false,100,125,155,false,193,false,217,280];
		var priceEdin = [40,45,80,100,120,false,false,false,false,false];
		var priceLeeds = [45,60,90,120,150,false,180,false,200,false];
		var priceLough = [52,67,98,150,191,false,227,false,247,288];
		var priceManc = [50,78,95,142,174,200,false,240,250,325];
		
		branchList = [priceChelt,priceCiren,priceEdin,priceLeeds,priceLough,priceManc];
		
		var target = this;
		
		var sendBranch = '';
		var sendBranchEmail = '';
		var branchNum = '';
		var branchArray = '';
		
		var sendMonthPrice = 0;
		var sendSubPrice = 0;
		var sendTotalPrice = 0;
		var sendVat = 0;
		var discount = 0;
		var priceHtml = '';
		
		var vatPercentage = 20;
		
		$('.form_error').hide();
		
		var unitHtml = '';
		var unitSelected = false;
		
		// hide items
		target.children('li').eq(1).children('ul').hide();
		target.children('li').eq(2).children('ul').hide();
		
		// Branch LIst
		
		target.find('ul#quote_branches li#branch_list a').each(function(i){
			$(this).click(function(){
				target.find('ul#quote_branches li#branch_address ul li:visible').hide();
				target.find('ul#quote_branches li#branch_address ul li').eq(i).show();
				//
				target.find('ul#quote_branches li#branch_hours ul li:visible').hide();
				target.find('ul#quote_branches li#branch_hours ul li').eq(i).show();
				//
				target.find('ul#quote_branches li#branch_list a.active').removeClass('active');
				$(this).addClass('active');
				//
				sendBranch = $(this).html();
				sendBranchEmail = $(this).attr('rel');
				branchNum = i;
				target.parent().parent().find('li').eq(0).find('h3 a').html('Step 1 - Branch Chosen - '+sendBranch);
				return false;
			});
		});
		
		$('#next_branch').click(function(){
			if(sendBranch == ''){
				alert('Please select a branch first')
			}else{
				// If that branch doesnt have that size unit hide dropdown
				branchArray = branchList[branchNum];
				target.find('ul#quote_size li#size_select ul li').each(function(i){
					if(branchArray[i]==false){
						target.find('ul#quote_size li#size_select ul li').eq(i).hide();	
					}else{
						target.find('ul#quote_size li#size_select ul li').eq(i).show();
					}
				});
				//
				target.children('li').eq(0).children('ul').slideUp(400);
				target.children('li').eq(1).children('ul').slideDown(400);
			}
			//
			target.find('h3#quote_branches_title a').addClass('title_active');
			target.find('h3#quote_branches_title a').click(function(){
				sendBranch = '';
				target.children('li').eq(0).children('ul').slideDown(400);
				target.children('li').eq(1).children('ul').slideUp(400);
				target.children('li').eq(2).children('ul').slideUp(400);
				$(this).removeClass('title_active').unbind('click');
				return false;
			});
			//
			return false;
		});
		
		// Unit Selector
		
		target.find('ul#quote_size li#size_select ul li').each(function(i){
			$(this).hover(function() {
				$(this).css({'background-color':'#dddddd'});
				target.find('ul#quote_size li#size_info ul li').eq(i).show();	
			}, function() {
				$(this).css({'background-color':''})
				target.find('ul#quote_size li#size_info ul li').eq(i).hide();	
			})									
		});
		
		target.find('ul#quote_size li#size_select ul li select').each(function(i){
			$(this).change(function(){
				checkSizes();
			}); 
		});
		
		checkSizes = function(){
			unitHtml='';
			sendMonthPrice=0;
			priceHtml = '';
			unitSelected = false;
			target.find('ul#quote_size li#size_select ul li select').each(function(i){
				if($(this).val()!='0'){
					// set squarefoot
					unitSelected = true;
					var sqftNum = $(this).attr('id')
					sqftNum = sqftNum.substring(4);
					//sqftQuant = $(this).val();
					unitHtml += $(this).val()+' x '+sqftNum+' sqft<br \/>'
					// Set price parseInt
					sendMonthPrice+=(branchArray[i]*$(this).val());
					priceHtml = '&pound;'+sendMonthPrice+'.00';
				}
				target.find('ul#quote_size li#size_chosen p#size_total').html(unitHtml);
				target.find('ul#quote_size li#size_chosen p#size_price').html(priceHtml);
			});
			
			if(!unitSelected){
				target.find('ul#quote_size li#size_chosen p#size_total').html('No units selected.');
				target.find('ul#quote_size li#size_chosen p#size_price').html('&pound;0.00');
			}
		}
		
		$('#next_size').click(function(){
			if(!unitSelected){
				alert('Please select at least 1 unit')
			}else{
				setFinalPrice();
				target.children('li').eq(1).children('ul').slideUp(400);
				target.children('li').eq(2).children('ul').slideDown(400);
				//
				target.find('h3#quote_size_title a').addClass('title_active');
				target.find('h3#quote_size_title a').click(function(){
					target.children('li').eq(0).children('ul').slideUp(400);
					target.children('li').eq(1).children('ul').slideDown(400);
					target.children('li').eq(2).children('ul').slideUp(400);
					$(this).removeClass('title_active').unbind('click');
					return false;
				});
			}
			return false;
		});
		
		target.find('ul#quote_contact select#quote_store_duration').change(function(){
			setFinalPrice();
		});
		
		setFinalPrice = function(){
			var thisDur = target.find('ul#quote_contact select#quote_store_duration').val();
			
			if(thisDur>11){
				// wants more than a year
				target.find('ul#quote_contact p#final_quote_sub').html('We have special rates for customers wishing to store for more than 6 months. After submitting this form one of our representatives will be in touch to discuss your requirements.');
				target.find('ul#quote_contact p#final_quote_vat').hide();
				target.find('ul#quote_contact p#final_quote').hide();
				target.find('ul#quote_contact p.sub_text').hide();
				
			}else{
				if(thisDur>2){
					discount = sendMonthPrice;
				}else{
					discount=0;
				}
				sendSubPrice = (sendMonthPrice*thisDur)-discount;
				sendVat = (sendSubPrice/100)*vatPercentage;
				sendVat = Math.round(sendVat*100)/100;
				sendTotalPrice = sendSubPrice+sendVat;
				sendTotalPrice = sendTotalPrice.toFixed(2);
				var subHtml = 'Monthly cost: &pound;'+sendMonthPrice+'.00<br />3 month discount: -&pound;'+discount+'.00<br />Subtotal: &pound;'+sendSubPrice+'.00';
				var vatHtml = 'VAT (@20%): &pound;'+sendVat;
				
				var totalHtml = '<strong>Total:</strong> &pound;'+sendTotalPrice;
				//
				target.find('ul#quote_contact p#final_quote_sub').html(subHtml);
				target.find('ul#quote_contact p.sub_text').show();
				target.find('ul#quote_contact p#final_quote_vat').show().html(vatHtml);
				target.find('ul#quote_contact p#final_quote').show().html(totalHtml);
				/*
				sendVat vatPercentage
				<p><strong>Your quote:</strong></p>
				<p id="final_quote_sub">
                Monthly cost: &pound;0.00<br />
                3 month discount: &pound;0.00<br />
                Subtotal: &pound;0.00</p>
                <p id="final_quote_vat">VAT (@17.5%): &pound;0.00</p>
				<p id="final_quote"><strong>Total:</strong> &pound;30.00</p>
									*/
			}
		};
		// Form validate
		$('#quote_fin').click(function(){
			var formValid = true;
			$('.form_error').hide();
			// start date
			var send_start_date_day = $("select#quote_start_date_day").val();
			var send_start_date_month = $("select#quote_start_date_month").val(); 
			var send_start_date_year = $("select#quote_start_date_year").val(); 
			if (send_start_date_day == "" || send_start_date_month == "" || send_start_date_year=="" ) {  
				$("p#start_date_error").show(); 
				formValid = false;
				//$("input#name").focus();   
			};
			//  storage duration
			var send_store_duration = $("select#quote_store_duration").val();
			if (send_store_duration == ""){
				$("p#store_duration_error").show();
				formValid = false;
			};
			//Insurance Value
			var send_ins_value = $("input#quote_ins_value").val();
			if (send_ins_value == ""){
				$("p#ins_value_error").show();
				formValid = false;
			};
			// First name
			var send_firstname = $("input#quote_firstname").val();
			if (send_firstname == ""){
				$("p#firstname_error").show();
				formValid = false;
			};
			// surname
			var send_surname = $("input#quote_surname").val();
			if (send_surname == ""){
				$("p#surname_error").show();
				formValid = false;
			};
			// email
			var send_email = $("input#quote_email").val();
			if (send_email == "" || echeck(send_email)==false){
				$("p#email_error").show();
				formValid = false;
			};
			// confirm email
			var send_conf_email = $("input#quote_conf_email").val();
			if (send_conf_email != send_email){
				$("p#email_conf_error").show();
				formValid = false;
			};
			//
			var send_phone = $("input#quote_phone").val();
			var send_mobile = $("input#quote_mobile").val();
			var send_contact_method = $("select#quote_contact_method").val();
			var send_contact_time = $("select#quote_contact_time").val();
			var send_referral = $("select#quote_referral").val();
			//
			if(formValid){
				var dataString = '&chosenbranch='+sendBranch+'&branchemail='+sendBranchEmail+'&monthprice='+sendMonthPrice+'&discount='+discount+'&subPrice='+sendSubPrice+'&vat='+sendVat+'&totalPrice='+sendTotalPrice+'&start_day='+send_start_date_day+'&start_month='+send_start_date_month+'&start_year='+send_start_date_year+'&store_duration='+send_store_duration+'&ins_value='+send_ins_value+'&firstname='+send_firstname+'&surname='+send_surname+'&email='+send_email+'&phone='+send_phone+'&mobile='+send_mobile+'&contact_method='+send_contact_method+'&contact_time='+send_contact_time+'&referral='+send_referral;
				//
				$.ajax({  
					type: "POST",  
					url: "includes/php/process.php",  
					data: dataString,
					error: function(XMLHttpRequest, textStatus, errorThrown){ 
						alert(errorThrown); 
					},
					success: function() {
						var thanksMessage = '<h2>Get a quote<\/h2><p>Thank you for your enquiry. A max representative will be in touch shortly.</p>';
						$('#column_a').html(thanksMessage);  
						//$('#thanks_message').html("<h3>Thank you for your enquiry</h3>").append("<p>A max representative will be in touch shortly.</p>");
					}
				});
			};
			return false;
		});
	};
	

})(jQuery);		  
		  
$(document).ready(function(){
	
	if($('#branch_list').length){
		$('#branch_list').initAccordian();
	}
	
	if($('#map_nav').length){
		$('#map_nav').initMapNav();
	}
	
	if($('#quote_list').length){
		$('#quote_list').initQuote();
	}
	
});

