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(){
		pattern = /(http(s)?|ftp(s)?)(.*)/gi;			//basic regex patterm case insensitive and multiple matches
		results = $(this).attr('href').match(pattern);
			
		// for each
		for ( var i in results )
		{
			
			// extract domain name from url
			var domain = $(this).attr('href').toString().split("//")[1].split("/")[0];
			var localDomainArray = ['.camfinancial.co.uk','.mrbdigital.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(){
	
	// image preload function
	function preloadImages()
	{
		var imageObject = arguments[0]; // take of the first argurment which is the object
		//alert(arguments[0]);
		$.each(imageObject.imageList, function(key, value) {  		
			jQuery("<img>").attr("src", imageObject.imagePath + value);
		});
	}
	
	if(jQuery.fn.bgAnimate){
	
		// only browsers taht don't support css transitions
		if($('.no-csstransitions #top-heading nav.nav ul > li a').length > 0){
			$('#top-heading nav.nav ul > li:not(.selected)').bgAnimate({
				outPosition:'0px 99px',
				overPosition:'0px 0px',
				easingType: 'linear',
				target:'a',
				speedIn: 800,	
				speedOut: 800
			});
		}
	
	}
	
	// home page only
	if(jQuery.fn.cycle){
	
		if($('#home #carousel').length > 0){
								
			function onBefore(incomingSlide, outgoingSlide, options, isForwardNav) { 
			    /*$(outgoingSlide).children('div.overlay').animate({bottom:-80}, {easing: 'easeInCubic'},{duration:100}, function(){$(this).remove();});*/
				$(outgoingSlide).children('h3').animate({opacity:0, 'filter': ''}, {easing: 'swing'},{duration:10});
				$(outgoingSlide).children('p').animate({opacity:0, 'filter': ''}, {easing: 'swing'},{duration:10});
			} 
			function onAfter(incomingSlide, outgoingSlide, options, isForwardNav) { 
				
				$(this).children('h3').animate({opacity:1, 'filter': ''}, {easing: 'swing'},{duration:200});
				$(this).children('p').animate({opacity:1, 'filter': ''}, {easing: 'swing'},{duration:350});
				
			}
			function hideBannerText(){
				$('#home #carousel li').each(function(){
					$(this).children('h3').css({'opacity':0});
					$(this).children('p').css({'opacity':0});
				});
				
			}
			// hide all banner text to initialise
			hideBannerText();
			
			$('#home #carousel').cycle({ 
			    fx:     'fade', 
			    timeout: 5000,
			    speed: 800,
			    fit: 1,
			    pause: 1, // enable pause on hover
			    next:   '#prev-next li.next a', 
			    prev:   '#prev-next li.prev a',
			    cleartype: true,
			    cleartypeNoBg: true,  
			    before:  onBefore, 
			    after:   onAfter
			});
		}
	}
	
	//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();
				},
				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','#F7F7F7'); //green background for valid data
						$(element).css('border-color','#C6D880'); //green border for valid data
					});
				}
			});

			if($('#SiteContactForm').length > 0 ){ // check if element is on page
				
				$("#SiteContactForm").validate({
					rules: {
						txt_name: {  
							required: true          
						},
						txt_email: {
							required: true,
							email: true
						},
						txt_company: {  
							required: true          
						},
						txt_telephone: {  
							required: true,  
							phoneUK: true          
						}
					},
					messages: {
						txt_name: "Please enter your name.",
						txt_email: {
									required: "Please enter your email.",
									email: "Email address is invalid."
								   },
						txt_company: "Please enter your surname.",
						txt_telephone: {
										required: "Please enter your telephone number.",
										phoneUK: "Invalid telephone number."
									   }
					}

				});
			}
		}
	}

	//fire off validation setup
	jqueryValidate();
	
	if($('#top-heading nav.nav').length > 0){ // check if element is on page
		
		var parent_ul = $('#top-heading nav.nav > ul');
		
		$('#top-heading nav.nav ul > li').each(function(){
		
			if($(this).children('ul').length > 0){
				
				// assign vars
				var parent_li = $(this);
				var child_ul = $(this).children('ul');
				var child_width = 0;
				
				// set child width by cuumulative value of each child li's width
				child_ul.children('li').each(function(){
					child_width += $(this).width();	
				});
				
				// calculate remaining horizontal space from parent li left position
				horizontal_space = parent_ul.width() - parent_li.position().left;
				
				// if child ul is wider
				if(horizontal_space < child_width){
					
					// calculate left offset
					width_offset = child_width - horizontal_space;
					// reset the child ul left position
					child_ul.css({'left':'-'+width_offset+'px'});
				}				
			}
			// don't run for ie 6		
			if(!($.browser.msie && $.browser.version == 6)){
				// bind mouseover behaviour
				if($(this).hasClass('selected') == false){
					
					var hide;
				
					function hideSelected(){
					
						$('#top-heading nav.nav ul li.selected').addClass('unselected');
						$('#top-heading nav.nav ul li.selected').removeClass('selected');
					}
					
					$(this).hover(function(){
						hide = setTimeout(hideSelected, .5*100);
					},function(){
						clearTimeout(hide);
					});
				}
			}
			
		});
		
		// don't run for ie 6
		if(!($.browser.msie && $.browser.version == 6)){
			var show;
			
			function showSelected(){
				$('#top-heading nav.nav ul li.unselected').addClass('selected');
				$('#top-heading nav.nav ul li.unselected').removeClass('unselected');
			}
			
			$('#top-heading nav.nav ul:first').mouseleave(function(){
				show = setTimeout(showSelected, .5*500);
			});
		}
	}
	
	// about us page only
	if($('#home #expandable #expandable-items').length > 0){ // check if element is on page
		
		var expandable = $('#expandable');
		var closer = $('#closer a');
		var hasGallery = false;		
		
		// check if the carousel exists
		if($('#carousel').length > 0){
			hasGallery = true;
		}
			
		function hideSiblings(e){
			$(e).siblings('li').each(function(){
				$(this).children('div.content').hide();
				$(this).removeClass('selected');
			});
		}
		
		function homeSlideOut(e){
			// add animating class to expnadable
			expandable.addClass('animating');
			
			// hide siblings
			hideSiblings(e);
			
			// add selected class to clicked li
			$(e).addClass('selected').fadeIn();
			
			// changed speed of animation for ie6 			
			if($.browser.msie && $.browser.version=="6.0"){
				var duration = 0;
			}else{
				var duration = 500;
			}
			
			
			expandable.stop().animate(
				{ width: 654, left: -398, top:0}, // what we are animating
				{
					duration: duration, // how fast we are animating
					easing: 'easeInCubic', // the type of easing
					complete: function() { // the callback
						// Animation complete.
						$(this).addClass('open');
						$(e).children('div.content').fadeIn();
						// bind closing animation to closer link
						closer.unbind();
						closer.bind('click', function(){ homeSlideIn(e); return false;});
						
						// pause the carousel
						if(hasGallery === true){
							$('#carousel').cycle('pause');							
						}
						
				   	}
			});
			
		}
		
		function homeSlideIn(e){
			
			// changed speed of animation for ie6 	
			if($.browser.msie && $.browser.version=="6.0"){
				var duration = 0;
			}else{
				var duration = 500;
			}
			
			// hide content
			$(e).children('div.content').fadeOut('fast');
			
			// hide siblings
			hideSiblings(e);
			
			expandable.stop().animate(
				{ width: 255, left:0, top:0}, // what we are animating
				{
					duration: duration, // how fast we are animating
					easing: 'easeInCubic', // the type of easing
					complete: function() { // the callback
						// Animation complete
						//$(this).removeClass('selected');
						$(e).removeClass('selected');
						$(this).removeClass('open animating');
						
			
						// resume the carousel
						if(hasGallery === true){
							$('#carousel').cycle('resume');							
						}

				   	}
			});	
		}

	
		$('#home #expandable #expandable-items li > a').each(function(){
			
			$(this).bind({
				keydown: function() {								
					if($(this).parent('li').hasClass('selected') == false){
						// slide up if active
						homeSlideOut($(this).parent('li'));			
					}else{
						// slide down
						homeSlideIn($(this).parent('li'));
					}
					
					return false;
				},
				click: function() {
					if($(this).parent('li').hasClass('selected') == false){
						// slide up if active
						homeSlideOut($(this).parent('li'));			
					}else{
						// slide down
						homeSlideIn($(this).parent('li'));
					}
					
					return false;
				}
			});
            
		});
	}
	
	
	// about us page only
	if($('#inner .our-team ul.accordian li').length > 0){ // check if element is on page
		
		var duration = 500;
		
		function teamSlideDown(e){
			$(e).children('div.content').css({'visibility':'visible'});			
			
			$(e).addClass('animating');
			
			$(e).stop().animate(
				{ height: 363 }, // what we are animating
				{
					duration: duration, // how fast we are animating
					easing: 'easeInCubic', // the type of easing
					complete: function() { // the callback
						// Animation complete.
						$(this).removeClass('animating');
						$(this).addClass('active');
				   	}
			});
			
			// hide all others
			teamSlideUp($(e).siblings('li.active'));
			
		}
		
		function teamSlideUp(e){
			
			$(e).addClass('animating');
			
			$(e).stop().animate(
				{ height: 71 }, // what we are animating
				{
					duration: duration, // how fast we are animating
					easing: 'easeInCubic', // the type of easing
					complete: function() { // the callback
						// Animation complete
						$(this).removeClass('animating');
						$(this).removeClass('active');
						$(e).children('div.content').css({'visibility':'hidden'});

				   	}
			});	
		}

	
		$('#inner .our-team ul.accordian li .title').each(function(){
			
			// bind click behaviour to contact link
			$(this).bind('click', function(){
			
				if($(this).parent('li').hasClass('active')){
					// slide up if active
					teamSlideUp($(this).parent('li'));			
				}else{
					// slide down
					teamSlideDown($(this).parent('li'));
				}
				
				return false;
			});
            
		});
	}
	
	if($('#image-map').length > 0){ // check if element is on page
		
		var areaImages = {
			imagePath: '/img/content/',
			imageList: ["life-capital.gif", "life-capital-02.gif", "life-capital-03.gif", "life-capital-04.gif", "life-capital-05.gif"]
		}
		
		// preload images with literal object passed in
		preloadImages(areaImages);
		
		
		
		// attach mouseover events
		if($('map[name="life-capital-map"]').length > 0){
						
			$('map[name="life-capital-map"]').children('area').each(function(){			
				
				$(this).bind('mouseenter', function(){
					
					var index = $("area").index(this); // get the index for the current selector
					// if the image exists in the iamge array then use it
					if(typeof(areaImages.imageList[index]) !== 'undefined'){
						$('#image-map').attr('src', areaImages.imagePath + areaImages.imageList[index]);
					}

				});
				
			});
			
			// attach show hide functionality
			if($('map[name="life-capital-map"] area.showhide').length > 0 ){
				$('map[name="life-capital-map"] area.showhide').showhide({
					animate:true,
					event:'mouseover'
				});
			}
		}
	}
	
	if($('#sub-nav').length > 0){ // check if element is on page
		// attach show hide functionality
		if($('.csstransforms #sub-nav a.showhide').length > 0 ){
			$('#sub-nav a.showhide').showhide({
				animate:true,
				event:'click',
				linkOpacity: '0.7',
				selectedLinkOpacity: '1.0'
			});
		}
		// IE non-opacity animation type
		if($('.no-csstransforms #sub-nav a.showhide').length > 0 ){
			$('#sub-nav a.showhide').showhide({
				animate:true,
				animate_type:'show',
				event:'click',
				linkOpacity: null,
				selectedLinkOpacity: null
			});
		}
	}

});
