Array.prototype.inArray = function (value)
// Returns true if the passed value is found in the
// array. Returns false if it is not.
{
	//console.log(value);
	var i;
	for (i=0; i < this.length; i++) {
		// Matches identical (===), not just similar (==).
		if (this[i] === value) {
			return true;
		}
	}
	return false;
};

//xhtml work around to open all links with re=new-window as new tab or window
$(function(){	
	//check all hrefs, if external, open in blank window
	$('a').filter(function(){
		if(typeof($(this).attr('href')) != 'undefined'){
			pattern = /(http(s)?|ftp(s)?)(.*)/gi;			//basic regex patterm case insensitive and multiple matches
			results = $(this).attr('href').match(pattern);
			//console.log(results);	
			// for each
			for ( var i in results )
			{
				
				// extract domain name from url
				var domain = $(this).attr('href').toString().split("//")[1].split("/")[0];
				var localDomainArray = ['.insure4retirement.co.uk'];
				
				// only open non-current domain urls in new window.
				if(!localDomainArray.inArray(domain.substring(3))){
					// open in new window
					$(this).attr({
						target: "_blank", 
						title: "Opens in a new window"
					});
				}
			}
		}
	});

});



$(document).ready(function(){
	
	var quoteBtnUrl = $('#pgExternalUrl').val()+$('#campaignCookie').val();
	$('.quotebtn-needsupdate a').attr('href', quoteBtnUrl)
		.parents('.quotebtn-needsupdate').removeClass('quotebtn-needsupdate');
	
	if (jQuery.fn.inputfocus)
	{
		if ($('#header-outer-wrapper .col-2 .cell-2 .form-search .input').length > 0 ){ // check if element is on page
			//apply form field effect
			$('#header-outer-wrapper .col-2 .cell-2 .form-search .input').inputfocus({
				bgColourFocus:'#ffffff',
				bgColour:'none',
				animate:false
			});
		}
	}

	if(jQuery.fn.showhide){
		//apply show hide plugin for use in gallery
		if($('a.showhide').length > 0 ){
			$('a.showhide').showhide({
				animate:true,
				event:'click'
			});
		}
	}
	
	//apply form validation
	function jqueryValidate(){
		
		if(jQuery.fn.validate){
			
			//setup default actions for validate plugin
			$.validator.setDefaults({
				submitHandler: function(form) {
					//on submit make sure that any inputs that have the same value as their label then blank the value
					
					//pass form id to local var
					var formId = jQuery(form).attr('id');

					//iterate through submit elements
					$('#'+formId+' input[type=text],select,textarea,radio,checkbox').each(function(){
						
						//get current_input 
						var current_input = $(this);
						//get label for current_input 
						var current_label = $('label[for=' + current_input.attr('id') + ']');
						//check that the element is either a text or textarea
						if(current_input.attr('type') == 'text' || current_input.attr('cols')){
							//if label and input the same then blank the value
							if(current_label.text() == current_input.val()){	
								current_input.val('');
							}
						}
					});

					//submit form
					form.submit();
				}
			});

			$.validator.addMethod("notLabelText",
					
				function(value, element) {
					// compate elements value with its label 
					// excluding the error label generated by the validation script
					// usin jQuery selector filter element[attribute!=value]
					var result = ($(element).val() == $('label[for=' + $(element).attr('id') + '][generated!=true]').text()) ? false : true;
					return result;
				} 		
			);

			$.validator.addMethod("emailConfirmation", 
				function(value, element) {
					var result = true;
					if ($("#FormCallmebackEmail").val() != $("#FormCallmebackConfirmEmail").val())
						result = false;
			    	return result;
				}
			);

			$.validator.addMethod("emailFriendConfirmation", 
				function(value, element) {
					var result = true;
					if ($("#FormRecommendafriendEmail").val() != $("#FormRecommendafriendConfirmEmail").val())
						result = false;
			    	return result;
				}
			);

			$.validator.addMethod("emailFriendFriendConfirmation", 
				function(value, element) {
					var result = true;
					if ($("#FormRecommendafriendFriendEmail").val() != $("#FormRecommendafriendFriendConfirmEmail").val())
						result = false;
			    	return result;
				}
			);

			if($('#form-search').length > 0 ){ // check if element is on page

				$("#form-search").validate({
					highlight: function(element, errorClass) {
						$(element).animate({
							opacity: 0.9
						}, 400, function () {
							$(element).css('color','#000000'); //red background for invalid data
							$(element).css('background-color','#FBE3E4'); //red background for invalid data
							$(element).css('border-color','#FBC2C4'); //red border for invalid data
						});
					},
					unhighlight: function(element, errorClass) {
						$(element).animate({
							opacity: 1.0
						}, 400, function () {
							$(element).css('color','#000000'); //red background for invalid data
							$(element).css('background-color','#E6EFC2'); //green background for valid data
							$(element).css('border-color','#C6D880'); //green border for valid data
						});
					},
					rules: {
						"data[FormSearch][searchtext]": {  
							required: true,  
							notLabelText: true            
						}
					},
					messages: {
						"data[FormSearch][searchtext]": "Type your search."
					}

				});
			}

			if($('#form-callback').length > 0 ){ // check if element is on page
				
				$("#form-callback").validate({
					highlight: function(element, errorClass) {
						$(element).animate({
							opacity: 0.9
						}, 400, function () {
							$(element).css('color','#000000'); //red background for invalid data
							$(element).css('background-color','#FBE3E4'); //red background for invalid data
							$(element).css('border-color','#FBC2C4'); //red border for invalid data
						});
					},
					unhighlight: function(element, errorClass) {
						$(element).animate({
							opacity: 1.0
						}, 400, function () {
							$(element).css('color','#000000'); //red background for invalid data
							$(element).css('background-color','#E6EFC2'); //green background for valid data
							$(element).css('border-color','#C6D880'); //green border for valid data
						});
					},
					rules: {
						"data[FormCallmeback][firstname]": {  
							required: true,  
							notLabelText: true            
						},
						"data[FormCallmeback][surname]": {  
							required: true,  
							notLabelText: true            
						},
						"data[FormCallmeback][telephone]": {  
							required: true,  
							phoneUK: true,
							notLabelText: true            
						},
						"data[FormCallmeback][email]": {
							required: true,
							email: true
						},
						"data[FormCallmeback][confirm_email]": {
							required: true,
							email: true,
						    emailConfirmation: true            
						}
					},
					messages: {
						"data[FormCallmeback][firstname]": "Please enter your first name.",
						"data[FormCallmeback][surname]": "Please enter your surname.",
						"data[FormCallmeback][telephone]": {required: "Please enter your telephone number.",
													 	 phoneUK: "Invalid telephone number."
													    },
						"data[FormCallmeback][email]": {required: "Please enter your email.",
													 email: "Email address is invalid."
													 },
						"data[FormCallmeback][confirm_email]": {required: "Please enter your confirmation email.",
													 email: "Email address is invalid.",
													 emailConfirmation: "Confirmation email must be the same as your email."
													 }
					}

				});
			}

			if($('#form-friend').length > 0 ){ // check if element is on page
				
				$("#form-friend").validate({
					highlight: function(element, errorClass) {
						$(element).animate({
							opacity: 0.9
						}, 400, function () {
							$(element).css('color','#000000'); //red background for invalid data
							$(element).css('background-color','#FBE3E4'); //red background for invalid data
							$(element).css('border-color','#FBC2C4'); //red border for invalid data
						});
					},
					unhighlight: function(element, errorClass) {
						$(element).animate({
							opacity: 1.0
						}, 400, function () {
							$(element).css('color','#000000'); //red background for invalid data
							$(element).css('background-color','#E6EFC2'); //green background for valid data
							$(element).css('border-color','#C6D880'); //green border for valid data
						});
					},
					rules: {
						"data[FormRecommendafriend][firstname]": {  
							required: true,  
							notLabelText: true            
						},
						"data[FormRecommendafriend][surname]": {  
							required: true,  
							notLabelText: true            
						},
						"data[FormRecommendafriend][telephone]": {  
							required: true,  
							phoneUK: true,
							notLabelText: true            
						},
						"data[FormRecommendafriend][policy_number]": {  
							required: true,  
							notLabelText: true            
						},
						"data[FormRecommendafriend][email]": {
							required: true,
							email: true
						},
						"data[FormRecommendafriend][confirm_email]": {
							required: true,
							email: true,
						    emailFriendConfirmation: true            
						},
						"data[FormRecommendafriend][postcode]": {  
							required: true,  
							notLabelText: true            
						},
						"data[FormRecommendafriend][friend_firstname]": {  
							required: true,  
							notLabelText: true            
						},
						"data[FormRecommendafriend][friend_surname]": {  
							required: true,  
							notLabelText: true            
						},
						"data[FormRecommendafriend][friend_telephone]": {  
							required: true,  
							phoneUK: true,
							notLabelText: true            
						},
						"data[FormRecommendafriend][friend_email]": {
							required: true,
							email: true
						},
						"data[FormRecommendafriend][friend_confirm_email]": {
							required: true,
							email: true,
						    emailFriendFriendConfirmation: true            
						},
						"data[FormRecommendafriend][friend_postcode]": {  
							required: true,  
							notLabelText: true            
						}
					},
					messages: {
						"data[FormRecommendafriend][firstname]": "Please enter your first name.",
						"data[FormRecommendafriend][surname]": "Please enter your surname.",
						"data[FormRecommendafriend][telephone]": {required: "Please enter your telephone number.",
													 	 phoneUK: "Invalid telephone number."
													    },
						"data[FormRecommendafriend][policy_number]": "Please enter your policy number.",
						"data[FormRecommendafriend][email]": {required: "Please enter your email.",
													 email: "Email address is invalid."
													 },
						"data[FormRecommendafriend][confirm_email]": {required: "Please enter your confirmation email.",
													 email: "Email address is invalid.",
													 emailFriendConfirmation: "Confirmation email must be the same as your email."
													 },
						"data[FormRecommendafriend][postcode]": "Please enter your postcode.",
						"data[FormRecommendafriend][friend_firstname]": "Please enter your friends first name.",
						"data[FormRecommendafriend][friend_surname]": "Please enter your friends surname.",
						"data[FormRecommendafriend][friend_telephone]": {required: "Please enter your friends telephone number.",
													 	 phoneUK: "Invalid telephone number."
													    },
						"data[FormRecommendafriend][friend_email]": {required: "Please enter your friends email.",
													 email: "Email address is invalid."
													 },
						"data[FormRecommendafriend][friend_confirm_email]": {required: "Please enter your friends confirmation email.",
													 email: "Email address is invalid.",
													 emailFriendFriendConfirmation: "Your  friends confirmation email must be the same as your friends email."
													 },
						"data[FormRecommendafriend][friend_postcode]": "Please enter your friends postcode."
					}

				});
			}
			
		}
	}
	
	//fire off validation setup
	jqueryValidate();
	
	//run rotations
	if(jQuery.fn.cycle){
		if($('div#testimonials').length > 0 ){ // check if element is on page

			$('div#testimonials').css('height','400px');//set height of quotes box
			$('div#testimonials').cycle({fx:'fade',timeout:'7000'});
		}
	}

	function toggleStyle(e){		

		//place state class
		if($(this).siblings('a.head').hasClass('selected')){
			$(this).siblings('a.head').removeClass('selected');
		}else{
			$(this).siblings('a.head').addClass('selected');
		}
	}

	/* define bound function call */
	function showAdditionalInfoBox(e){
		
		//hide all other items except the current one
		$('.accordion div.content').not(e.siblings('div.content:first')).hide();

		//place state class from all other items except the current one
		$('a.head').not(e).removeClass('selected');
		
		// toggle the panel
		e.siblings('div.content:first').fadeToggle(800, null, toggleStyle);

		return false;
	}
	
	//apply accordian behaviour to ul li structure
	if($('.accordion').length > 0 ){ // check if element is on page
		
		$i = 1;

		$('a.head').each(function(){
			
			var additionalPanel = $(this);

			/* bind event handler  for toggle behaviour*/
			$(this).bind({
				keydown: function() {								
					return showAdditionalInfoBox(additionalPanel);
				},
				click: function() {
					return showAdditionalInfoBox(additionalPanel);
				}
			});		
			
			//hide all content boxes by default
			$(this).siblings('div.content').hide();
			
			//by default show the selected item
			if($i == $('#accordionDefaultSelected').val()){
				$(this).siblings('div.content').show();
				$(this).addClass('selected');
			}

			$i ++;
		});
	}
	
	
	if($('#main-outer-wrapper #main #main-left-panel .col-2 #content_for_layout ul').length > 0){
		if($('#main-outer-wrapper #main #main-left-panel .col-2 #content_for_layout ul').hasClass('no-columns') ==  false){		
			var cnt = 1;
			$('#main-outer-wrapper #main #main-left-panel .col-2 #content_for_layout ul li').each(function(){
				if((cnt % 6) == 0){
					$(this).addClass('reset');
				}			
				if(cnt <= 5){
					$(this).addClass('column1');
				}
				if(cnt > 5){
					$(this).addClass('column2');
				}
				if(cnt > 10){
					$(this).addClass('column3');
				}
				cnt ++;
			});	
		}
	}
	
});
$(window).load(function() {
	// Activate rolling updates scrollers
	if (jQuery.fn.slide) {
		$('.rollingupdates-scroller').slide();
	}
});


/* CUFON FONT REPLACEMENT */
if (window.navigator.appName == "Microsoft Internet Explorer") {
   var engine = null;
   if (document.documentMode) {
      engine = document.documentMode;
   } else {
      engine = 5;
      if (document.compatMode)
      {
         if (document.compatMode == "CSS1Compat")
            engine = 7;
      }
   }
   if (engine === 9) {
       Cufon.set('engine', 'canvas');
   }
}
Cufon.replace('#header-outer-wrapper .col-2 .cell-1 .contact h2', { fontFamily: 'Futura', hover: true });
Cufon.replace('#header-outer-wrapper .col-2 .cell-1 .contact h3', { fontFamily: 'Futura', hover: true });
Cufon.replace('#banner-outer-wrapper #banner h2', { fontFamily: 'Futura', hover: true });
Cufon.replace('#banner-outer-wrapper #banner h3', { fontFamily: 'Futura', hover: true });
Cufon.replace('#banner-outer-wrapper #banner h4', { fontFamily: 'Futura', hover: true });
Cufon.replace('.box-1 h2, #main-outer-wrapper #main #main-left-panel .col-2 .box-1 h2', { fontFamily: 'Futura', hover: true });
Cufon.replace('.roundbox-purple-content h2', { fontFamily: 'Futura', hover: true });
Cufon.replace('.box-2 h2, #inner #main-outer-wrapper #main #main-left-panel .col-2 .box-2 h2', { fontFamily: 'Futura', hover: true });
Cufon.replace('.box-2 h2, #inner #main-outer-wrapper #main #main-left-panel .col-2 .box-2 h3', { fontFamily: 'Futura', hover: true });
Cufon.replace('.box-2 h2, #inner #main-outer-wrapper #main #main-left-panel .col-2 .box-2 h4', { fontFamily: 'Futura', hover: true });
