/*------------------ iPhone fix ------------------*/

function touchHandler(event)
{
    var touches = event.changedTouches,
    first = touches[0],
    type = "";
     switch(event.type)
    {
       case "touchstart": type = "mousedown"; break;
       case "touchmove":  type="mousemove"; break;        
       case "touchend":   type="mouseup"; break;
       default: return;
    }

         //initMouseEvent(type, canBubble, cancelable, view, clickCount, 
         //           screenX, screenY, clientX, clientY, ctrlKey, 
        //           altKey, shiftKey, metaKey, button, relatedTarget);

      var simulatedEvent = document.createEvent("MouseEvent");
      simulatedEvent.initMouseEvent(type, true, true, window, 1, 
                          first.screenX, first.screenY, 
                          first.clientX, first.clientY, false, 
                          false, false, false, 0/*left*/, null);

first.target.dispatchEvent(simulatedEvent);
   event.preventDefault();
}

function init() 
{
    document.addEventListener("touchstart", touchHandler, true);
    document.addEventListener("touchmove", touchHandler, true);
    document.addEventListener("touchend", touchHandler, true);
    document.addEventListener("touchcancel", touchHandler, true);    
}



/* -------------------------------------------------- *
 * JQuery Hints
 * -------------------------------------------------- *
 * Author: Ross Riley
 * License: MIT License
** -------------------------------------------------- */

(function($) {
	$.fn.hint = function(defaults) {
		// check whether we want real options, or to destroy functionality
		if(!defaults || typeof(defaults) == "object") {
			defaults = $.extend({
				focus_class: "hint_focus", // class during focus
				changed_class: "hint_changed", // class after focus
				populate_from: "default", // choose from: default, label, custom, or alt
				text: null, // text to use in conjunction with populate_from: custom
				remove_labels: false // remove labels associated with the fields
			}, defaults);
		}
		else if(typeof(defaults) == "string" && defaults.toLowerCase() == "destroy") {
			var destroy = true;
		}
		return this.each(function() {
			// unbind everything if we're destroying, and stop executing the script
			if(destroy) {
			  jQ(this).unbind("focus.hint").unbind("blur.hint").removeData("defText");
				return false;
			}
		  hint_setup(jQ(this));
		});
	  function hint_setup(ele){ 
	    // define our variables
			var defText = "";

			// let's populate the text, if not default
			switch(defaults.populate_from) {
				case "alt":
					defText = ele.attr("alt");
					ele.val(defText);
					break;
				case "label":
					defText = jQ("label[for='" + ele.attr("id") + "']").text();
					ele.val(defText);
					break;
				case "custom":
					defText = defaults.text;
					ele.val(defText);
					break;
				default:
					defText = ele.val();
			}

			// let's give this field a special class, so we can identify it later
			// also, we'll give it a data attribute, which will help jQuery remember what the default value is
			ele.addClass("hint").data("defText", defText);
			// now that fields are populated, let's remove the labels if applicable
			if(defaults.remove_labels == true) { jQ("label[for='" + ele.attr("id") + "']").remove(); }

			// Handles password fields by creating a clone that's a text field.
			if(ele.attr("type")=="password") {
			  var eledef = ele.data("defText");
        var el = jQ('<input type="text"/>');
        el.attr( 'name', ele.attr('name') );
        el.attr( 'size', ele.attr('size') );
        el.attr( 'class', ele.attr('class') );
        el.val( ele.val() );
        el.data("defType", "password").data("defText", eledef);
        ele.replaceWith(el);
        var ele = el;
		  }
			hint_focus(ele);
			hint_blur(ele);
	  };
	  function hint_focus(ele){ 
	    ele.bind("focus.hint",function(ele){
        var ele = jQ(this);
	      if(ele.val() == ele.data("defText")) { ele.val(""); }
				// add the focus class, remove changed_class
				ele.addClass(defaults.focus_class).removeClass(defaults.changed_class);
	      if(ele.data("defType")=="password") {
  			  var eledef = ele.data("defText");
          var el = jQ('<input type="password"/>');
          el.attr( 'name', ele.attr('name') );
          el.attr( 'size', ele.attr('size') );
          el.attr( 'class', ele.attr('class') );
          el.val( ele.val() );
          el.data("defType", "password").data("defText", eledef);
          ele.replaceWith(el);
          var ele = el;
          ele.focus();
          hint_blur(ele);
  			}
			});
	  };
	  function hint_blur(ele){ 
	    ele.bind("blur.hint",function(){
        var ele = jQ(this);
	      if(ele.val() == "") { ele.val(ele.data("defText")); }
				// remove focus_class, add changed_class.
				ele.removeClass(defaults.focus_class);
				if(ele.val() != ele.data("defText")) { ele.addClass(defaults.changed_class); }
					else { ele.removeClass(defaults.changed_class); }
				if(ele.data("defType")=="password" && ele.val()==ele.data("defText")) {
				  var eledef = ele.data("defText");
          var el = jQ('<input type="text"/>');
          el.attr( 'name', ele.attr('name') );
          el.attr( 'size', ele.attr('size') );
          el.attr( 'class', ele.attr('class') );
          el.val( ele.val() );
          el.data("defType", "password").data("defText", eledef);
          ele.replaceWith(el);
          var ele = el;
          hint_focus(el);
				}
	    });
	  };
	};
	var jQ = jQuery;
})(jQuery);
//---------------------------------- END HINTS ---------------------------------------

jQuery(document).ready(function() {
  jQuery("input[type='text']:not([value!=\"\"]), input[type='password']").hint({populate_from:"label", remove_labels:true});
	jQuery("input[type='text']:not([value=\"\"])").prev().hide();
});

//Remove skype
$(document).ready(function() {
		window.setTimeout(function() {
			$('.skype_pnh_container').html('');
			$('.skype_pnh_print_container').removeClass('skype_pnh_print_container');
		}, 800);
	});

//Startup
jQuery(function($){
	checkHash();
	//Startup if Javascript Enabled
	$("label[for!='other']").hide();
	$('.jQuerySelectorMain').css("display", "block");
	$(".jQuerySelectorMain").html("Please enter a postcode.");
	$(".jQuerySelectorMain").css("border", "3px solid red");
	$("#add-selector").css("display", "none");
	//$(".report-form").css("height", "393px");
	if($.browser.msie && $.browser.version=="6.0")
	{
			$(".report-form").css("background", "url('/wp-content/themes/ratesrecovery/images/business-rates-form-bg.gif') repeat-x top center");
	}
	else
	{
			$(".report-form").css("background", "url('/wp-content/themes/ratesrecovery/images/business-rates-form-bg.png') repeat-x top center");
	}
	$("#page-bottom-section").css("height", "425px");
	$("#page-bottom-section").css("background", "url('/wp-content/themes/ratesrecovery/images/bottom-section-bg.png') repeat-x top center");
	$(".t-as-seen-on").css("width", "auto");
	$(".t-as-seen-on").css("margin-top", "0px");
	$(".testimonials").css("top", "-30px")
	$(".testimony-holder").css("display", "block");
	$(".expanded, .expanded-text").css("display", "none");
	$(".agree_tandc").css("display", "none")
	$(".cs-counter-0, .cs-counter-1, .cs-counter-2, .cs-counter-3, .cs-counter-4").css("background", "url('/wp-content/themes/ratesrecovery/images/counter.png') no-repeat top center");
	$(".cs-counter-0, .cs-counter-1, .cs-counter-2, .cs-counter-3, .cs-counter-4").text("");
	if((navigator.userAgent.match(/iPad/i)) || (navigator.userAgent.match(/iPod/i)) || (navigator.userAgent.match(/iPhone/i))) {
		 {
			$("#add-selector").css("display", "block");
			$('.jQuerySelectorMain').css("display", "none");
		}
	}
	
});

//Open form up.
jQuery(function($){
	$(".postcode").focus(function(){
		var curheight = $(".report-form").css('height');
		if(!(curheight == "643px") && !(curheight == "783px")){
			$(".report-form").css("height", "643px");
			if($.browser.msie && $.browser.version=="6.0")
			{
					$(".report-form").css("background", "url('/wp-content/themes/ratesrecovery/images/expanded-form.gif') repeat-x top center");
			}
			else
			{
					$(".report-form").css("background", "url('/wp-content/themes/ratesrecovery/images/expanded-form.png') repeat-x top center");
			}
			$("#page-bottom-section").css("height", "624px");
			$("#page-bottom-section").css("background", "url('/wp-content/themes/ratesrecovery/images/expanded-bg.png') repeat-x top center");
			$(".t-as-seen-on").css("width", "100%");
			$(".t-as-seen-on").css("margin-top", "31px");
			$(".testimonials").css("top", "-230px");
			$(".testimony-holder").css("display", "block");
			$(".amnt_per_year").css("display", "none");
			$(".expanded, .expanded-text").css("display", "block");
			$(".agree_tandc").css("display", "block");
		}
	});
});

jQuery(function($){
	$("#rent").click(function() {
		$(".amnt_per_year").css("display", "block");
		$(".report-form").css("height", "783px");
		if($.browser.msie && $.browser.version=="6.0")
		{
				$(".report-form").css("background", "url('/wp-content/themes/ratesrecovery/images/very-expanded-form.gif') repeat-x top center");
		}
		else
		{
				$(".report-form").css("background", "url('/wp-content/themes/ratesrecovery/images/very-expanded-form.png') repeat-x top center");
		}
		$(".testimonials").css("top", "-330px");
		$("#page-bottom-section").css("height", "764px");
		$("#page-bottom-section").css("background", "url('/wp-content/themes/ratesrecovery/images/very-expanded-bg.png') repeat-x top center");
	});
	$("#own").click(function() {
		$(".amnt_per_year").css("display", "none");
		$(".report-form").css("height", "643px");
		if($.browser.msie && $.browser.version=="6.0")
		{
				$(".report-form").css("background", "url('/wp-content/themes/ratesrecovery/images/expanded-form.gif') repeat-x top center");
		}
		else
		{
				$(".report-form").css("background", "url('/wp-content/themes/ratesrecovery/images/expanded-form.png') repeat-x top center");
		}
		$(".testimonials").css("top", "-230px");
		$("#page-bottom-section").css("height", "624px");
		$("#page-bottom-section").css("background", "url('/wp-content/themes/ratesrecovery/images/expanded-bg.png') repeat-x top center");
	});
});

//Counter functionality and animation.
jQuery(function($){
	var cnt = 79000;
	cnt = cnt + Math.floor(Math.random()*1001);
	var currentCounta = cnt.toString().substring(0,2) + "," + cnt.toString().substring(2,5);
	
	var currentPlace = parseInt(cnt.toString().substring(0,1));
	var csctr0 = currentPlace;
	$(".cs-counter-0").css({"background-position": "0px " + ((currentPlace * -44)+5) + "px" });
	
	currentPlace = parseInt(cnt.toString().substring(1,2));
	var csctr1 = currentPlace;
	$(".cs-counter-1").css({"background-position": "0px " + ((currentPlace * -44)+5) + "px" });
	
	currentPlace = parseInt(cnt.toString().substring(2,3));
	var csctr2 = currentPlace;
	$(".cs-counter-2").css({"background-position": "0px " + ((currentPlace * -44)+5) + "px" });	
	
	currentPlace = parseInt(cnt.toString().substring(3,4));
	var csctr3 = currentPlace;
	$(".cs-counter-3").css({"background-position": "0px " + ((currentPlace * -44)+5) + "px" });
	
	currentPlace = parseInt(cnt.toString().substring(4,5));
	var csctr4 = currentPlace;
	$(".cs-counter-4").css({"background-position": "0px " + ((currentPlace * -44)+5) + "px" });
	
	//Needs cleaning up and drastically shortening.
	// var counter = setInterval(function() {
	// 	if(cnt < 100000) {
	// 		cnt++;
	// 			$(".cs-counter-4").animate({"background-position-y": "-=44px" });
	// 			csctr4++;
	// 			if(csctr4 == 10)
	// 			{
	// 				csctr4 = 0;
	// 				$(".cs-counter-4").animate({"background-position-y": "+=440px" }, 1);
	// 				$(".cs-counter-3").animate({"background-position-y": "-=44px" });
	// 				csctr3++;
	// 				if(csctr3 == 10)
	// 				{
	// 					csctr3 = 0;
	// 					$(".cs-counter-3").animate({"background-position-y": "+=440px" }, 1);
	// 					$(".cs-counter-2").animate({"background-position-y": "-=44px" });
	// 					csctr2++;
	// 					if(csctr2 == 10)
	// 					{
	// 						csctr2 = 0;
	// 						$(".cs-counter-2").animate({"background-position-y": "+=440px" }, 1);
	// 						$(".cs-counter-1").animate({"background-position-y": "-=44px" });
	// 						csctr1++;
	// 						if(csctr1 == 10)
	// 						{
	// 							csctr1 = 0;
	// 							$(".cs-counter-1").animate({"background-position-y": "+=440px" }, 1);
	// 							$(".cs-counter-0").animate({"background-position-y": "-=44px" });
	// 							csctr0++;
	// 							if(csctr0 == 10)
	// 							{
	// 								csctr0 = 0;
	// 								$(".cs-counter-0").animate({"background-position-y": "+=440px" }, 1);
	// 							}
	// 						}
	// 					}
	// 				}
	// 			}
	// 		}else {clearInterval(counter);}}, 1000);
		
});

//AJAX call from postcode.
jQuery(function($){
	
	$('#postcode').ajaxStart(function() {
	  $(this).css('background',"#FFF url(/wp-content/themes/ratesrecovery/images/indicator.gif) no-repeat center right");
	});
	$('#postcode').ajaxStop(function() {
		$(this).animate({marginTop:'0px'},400, function() {
			$(this).delay(400).css('background',"#FFF");
		});
	});
	
	var timeout = 0;
	
	$("#postcode").keyup(function(){
		
	});
	
	$('.jQuerySelectorMain').click(function(){
		$("#new_selector").slideDown("slow");
	});
	
	$("#new_selector li").live('click', function(){
		$("#new_selector").slideUp("slow");
		$(".jQuerySelectorMain").css("border", "5px solid #88B0B9");
		try {
		      $("#add-selector").val($(this).attr("id")); 
		   }
		   catch(ex) {
		      setTimeout("$('#add-selector').val('" + $(this).attr("id") + "')",1); 
		   }
		$(".jQuerySelectorMain").html($(this).text());
	});
	
	//Data validation.
	$(".report-form form").submit(function(){
		var curheight = $(".report-form").css('height');
		if((curheight == "643px") || (curheight == "783px"))
		{
				if($('#agree').attr('checked'))
				{
					var errorstring = "";
					var fields = ["#full_name","#company_address","#company_name","#email","#telephone","#postcode","#ratable_value"];
					var errors=[];
					if($(this).find("#full_name").val().length <4 || $(this).find("#full_name").val()==$(this).find("#full_name").data("defText")) { errors.push({"#full_name":" is a required field "}); errorstring += "You must supply your name.\n"; }
					if($(this).find("#postcode").val().length <5 || $(this).find("#postcode").val()==$(this).find("#postcode").data("defText")) { errors.push({"#postcode":" is a required field and needs a space in the correct place."}); errorstring += "Postcode is a required field and needs a space in the correct place.\n"; }
					if(!$(this).find("#email").val().match('^[_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)+$')) { errors.push({"#email":" is not a valid email"}); errorstring += "Email is not a valid email.\n"; }
					if($(this).find("#ratable_value").val().length <4 || $(this).find("#ratable_value").val()==$(this).find("#ratable_value").data("defText")) { errors.push({"#ratable_value":" is a required field "}); errorstring += "You must supply your Ratable Value.\n"; }
					if($(this).find("#company_name").val().length <4 || $(this).find("#company_name").val()==$(this).find("#company_name").data("defText")) { errors.push({"#company_name":" is a required field "}); errorstring += "You must supply your Company Name.\n"; }
					if($(this).find("#company_address").val().length <4 || $(this).find("#company_address").val()==$(this).find("#company_address").data("defText")) { errors.push({"#company_address":" is a required field "}); errorstring += "You must supply your Company Address.\n"; }
					if($(this).find("#telephone").val().length <4 || $(this).find("#telephone").val()==$(this).find("#telephone").data("defText")) { errors.push({"#telephone":" is a required field "}); errorstring += "You must supply your Telephone Number.\n"; }

					if(errors.length > 0 ) {
						for(var field in fields) $(field).css("border","5px solid #88B0B9");
						for(var error in errors) {
							for(var field in errors[error]) $(field).css("border","5px solid red");
						}
						alert("There were errors in your submission.\n" + errorstring); 
						return false;
					}
					else
					{
						return true;
					}
				}
				else
				{
					alert("You must agree to the terms and conditions.\n");
					return false;
				}
			}
			else
			{
				alert("Please fill in the form to access your report.");
				return false;
			}
	});
	
});

function wopen(url, name, w, h)
{
w += 32;
h += 96;
 var win = window.open(url,
  name, 
  'width=' + w + ', height=' + h + ', ' +
  'location=no, menubar=no, ' +
  'status=no, toolbar=no, scrollbars=no, resizable=no');
 win.resizeTo(w, h);
 win.focus();
}

function checkHash()
{
	if(window.location.hash)
	{
		$("#post-wrapper").css("padding-top", "50px");
		$("#primary, #secondary").css("padding-top", "70px");
	}
}
