//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|ftp(s)|\/track-redirect?/i;			//basic regex patterm case insensitive
		result = pattern.test($(this).attr('href'));	//rung using test method
				
		if(result == true){
			$(this).attr({
				target: "_blank", 
				title: "Opens in a new window"
			});
		}
	});
});

$(document).ready(function(){
	//-------------------------------------------------------------------------------------------------
	//--- EMBED MOVIES - flv/flash ---
	
	//replace all html editor inserted movies with swfobject
	//needed for accessibility options
	var cnt = 1;
	var next_img = null;
	//find all embed objects
	$('div.flash-movie').each(function()
	{								   
		flash_preview_img = '/content/images/flash-default.gif';
		var next_img = $(this).siblings('img');
		var flash_preview_img = null;
		var flash_div = $(this).children("a");
		var flash_href = flash_div.attr('href');
		var flash_extension = flash_div.attr('href').substring(flash_div.attr('href').lastIndexOf(".")+1,flash_div.attr('href').length);
		var flash_preview_img = '/content/images/flash-default.gif';
		
		/**/
		switch (flash_extension)
		{
			case "flv":
			//case "swf":
				if (next_img.length > 0 && next_img.attr('src').length > 0)
				{
					flash_preview_img = next_img.attr('src');
					//remove the image from the page
					next_img.remove();
				}
				flash_href = flash_href + '&image=' + flash_preview_img;
				flash_div.attr('href',flash_href);	
				//alert(flash_href);
			break;
		}
		
		flash_div.media();				
		//if there is an img next to the flash video then use that image as the image preview
		/*
		if(next_img.length > 0 && next_img.attr('src').length > 0){
			flash_preview_img = next_img.attr('src');
			//remove the image from the page
			next_img.remove();
		}
		*/
							
		//set default player location
		//$.fn.media.defaults.flvPlayer = '/css/skins/default/flash/player.swf';
		//run media plugin on all a links with media class
		//$('#'+flash_div+' a').media();
	});
	

	//replace all fck inserted movies with swfobject
	//needed for accessibility options
	var cnt = 1;
	//find all embed objects
	$('embed').each(function(){
			//if they are flash movies
			if ($(this).attr('type') == 'application/x-shockwave-flash')
			{				
				//get the source fo the flash movie
				if ($(this).attr('src'))
				{	
					//get width and height of movie to use for replacement below
					flash_width = $(this).attr('width');
					flash_height = $(this).attr('height');
					//alert(flash_width+":"+flash_height);
					
					embed_type = $(this).attr('type');
					flash_src = $(this).attr('src');
					flash_div = 'flash-'+cnt;
					flash_extension = $(this).attr('src').substring($(this).attr('src').lastIndexOf(".")+1,$(this).attr('src').length);
					flash_preview_img = '/content/images/flash-default.gif';
					//alert("type:"+embed_type+"ext:"+flash_extension+"flash_src:"+flash_src);
	
					//give the element an id
					$(this).attr('id','embed-'+cnt);	

					switch (flash_extension)
					{						
						/*case "flv":
							alert(flash_height);
							
							if (jQuery.fn.media)
							{	
								//replace the embed obect with a holding div
								$(this).replaceWith('<div id="'+flash_div+'"></div>');

								//use swfobject to embded the flash movie
								$('#'+flash_div).flash({ 
									// test.swf is the flash document 
									swf: flash_src,
									play: false,
									width : flash_width,
									height : flash_height
									//width : 425,
									//height : 344
								});
								
								//alert(flash_height);
								
								//set default player location
								$.fn.media.defaults.flvPlayer = '/css/skins/default/flash/mediaplayer.swf';
								//run media plugin on all a links with media class
								//$('#'+flash_div+' a').media();
							}
							else
							{
								alert('You need to have the media and meta plugins installed.');
							}
						break;*/
						case "swf":
							if (jQuery.fn.flash)
							{
								//alert("swf");	
									
								//replace the embed obect with a holding div
								$(this).replaceWith('<div class="flash-movie"><div id="'+flash_div+'"></div></div>');
								//use swfobject to embded the flash movie
								$('#'+flash_div).flash({ 
									// test.swf is the flash document 
									swf: flash_src//,
									//width : 425,
									//height : 344
								}); 
							}
							else
							{
								alert('You need to have the swfobject plugins installed.');
							}
						break;
						default:
						break;
					}
				}
			}
		cnt++;
	});
	//--- EMBED MOVIES - flv/flash ---
	//-------------------------------------------------------------------------------------------------


	//-------------------------------------------------------------------------------------------------
	/* EMBED MEDIA */
	if (jQuery.fn.media){
		//set default player location
		$.fn.media.defaults.flvPlayer = '/css/skins/default/flash/mediaplayer.swf';
		//run media plugin on all a links with media class
		$('a.media').media();
	}
	//-------------------------------------------------------------------------------------------------

	
	//apply form validation
	if(jQuery.fn.validate){			
		if($('#SiteContactForm').length > 0 ){ // check if element is on page

			//custom validation rule - text is not the prefilled content     
			$.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;
				} 		
			);
			
			
			
			var options = { 
				target:         '#response',   // target element(s) to be updated with server response 
				beforeSubmit:   showRequest,  // pre-submit callback 
				success:        showResponse,  // post-submit callback 
		 
				// other available options: 
				url:       	    '?send=1&get_xml=1',        // override for form's 'action' attribute this means that only a javascript call can request this URL
				type:           'post',  // 'get' or 'post', override for form's 'method' attribute 
				dataType:       'xml',   // 'xml', 'script', or 'json' (expected server response type) 
				clearForm:	    false,   // clear all form fields after successful submit 
				resetForm:		false,       // reset the form after successful submit 
		 
				// $.ajax options can be used here too, for example: 
				timeout:   		10000,	//set timeout to 10 seconds
				error:			showError //call error function to display error
				
			};

			$("#SiteContactForm").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: {
					txt_firstname: {  
						required: true,  
						notLabelText: true            
					},
					txt_lastname: {  
						required: true,  
						notLabelText: true            
					},
					txt_email: {
						required: true,
						email: true
					}
				},
				messages: {
					txt_firstname: "Please enter your first name.",
					txt_lastname: "Please enter your last name.",
					txt_email: "Please enter your email."
				},
				submitHandler: function(form) { //use validate event handle to submit form
					jQuery(form).ajaxSubmit(options);
				}

			});

		}
	}
	
	// pre-submit callback 
	function showRequest(formData, jqForm, options) { 
		// formData is an array; here we use $.param to convert it to a string to display it 
		// but the form plugin does this for you automatically when it submits the data 
		var queryString = $.param(formData); 
	 
		// jqForm is a jQuery object encapsulating the form element.  To access the 
		// DOM element for the form do this: 
		// var formElement = jqForm[0]; 
		
		//remove any old error messages
		if($("#error")){
			$("#error").remove();
		}
		//remove any old success messages
		if($("#success")){
			$("#success").remove();
		}
	 
		var message = 'Please wait whilst the page loads';
		
		//$('#response').hide();
		$(options.target).html("<p><img src='/img/jquery/ajax-loader.gif' alt='page loading' alrign='left' style='margin-right:10px;' />"+message+"</p>"); //fill contents of #reponse div
		$(options.target).fadeIn('slow'); //fade in div
		// here we could return false to prevent the form from being submitted; 
		// returning anything other than false will allow the form submit to continue 
		return true; 
	}


	// post-submit callback 
	function showResponse(responseXML, statusText)  { 
		// for normal html responses, the first argument to the success callback 
		// is the XMLHttpRequest object's responseText property 
	 
		// if the ajaxForm method was passed an Options Object with the dataType 
		// property set to 'xml' then the first argument to the success callback 
		// is the XMLHttpRequest object's responseXML property 
	 
		// if the ajaxForm method was passed an Options Object with the dataType 
		// property set to 'json' then the first argument to the success callback 
		// is the json data object returned by the server  
		
	  /**/
		
		$("#response").fadeOut('slow'); //continue fade out of div
		
		var message = $('message', responseXML).text(); //assign XML message node to variable
		var user = $('user', responseXML).text(); //assign XML message node to variable
		var status = $('status', responseXML).text(); //assign XML message node to variable
		var timestamp = $('timestamp', responseXML).text(); //assign XML message node to variable

		if(status==0){
			//$("#form").replaceWith("<div class='response'>" + message + "</div>");
		 
			var html = "<div class='success' id='success'><p>"+message+"</p></div><div id='response'></div><div id='error'></div>"; //pass message from XML into variable
			
			$("#response").replaceWith(html); //replace <div id='response'> div with content of html var
			var message = $("#response").prev(); //get the last <div class='message'> using the .prev traverse command
		}else{
			showError(responseXML, statusText);
			return false;
		}
					  
				  
					  
	}

	// post-submit callback 
	function showError(responseXML, statusText)  { 
		// for normal html responses, the first argument to the success callback 
		// is the XMLHttpRequest object's responseText property 
	 
		// if the ajaxForm method was passed an Options Object with the dataType 
		// property set to 'xml' then the first argument to the success callback 
		// is the XMLHttpRequest object's responseXML property 
	 
		// if the ajaxForm method was passed an Options Object with the dataType 
		// property set to 'json' then the first argument to the success callback 
		// is the json data object returned by the server  	
		$("#response").fadeOut('slow');
		var err_msg = $('message', responseXML).text(); 
		
		if(err_msg){
			var message = err_msg;
		}else{
			var message = 'Error : The operation you requested has failed. Please try again';
		}
		
		var html = "<div id='response'></div><div class='error' id='error'><p>"+message+"</p></div>"; //pass message var into variable
		
		$("#response").replaceWith(html); //replace <div id='response'> div with content of html var
		
		$("#error").fadeIn('slow');	//fade in error div
	}
	
	if(jQuery.fn.showhide){
		//apply show hide plugin for use in gallery
		if($('a.showhide').length > 0 ){
			$('a.showhide').showhide({
				animate:true,
				event:'click',
				target:'#large_img'
			});
		}
	}
	
	
	if(jQuery.fn.inputfocus){
		if($('#header-outer-wrapper form div.input').length > 0 ){ // check if element is on page
			//apply form field effect
			$('#header-outer-wrapper form div.input').inputfocus({
				bgColourFocus:'#EEEAE8',
				bgColour:'none',			
				animate:true
			});
		}
	}
	
	if(jQuery.fn.cycle){
		if($('#quotes').length > 0 ){ // check if element is on page
			$('#quotes').css('height','110px');//set height of quotes box
			$('#quotes').cycle();
		}
		/* home banner rotator */
		if($('#home #main #main-center-panel #banner-wrapper div.col-1 img').length > 0 ){ // check if element is on page
			$('#main #main-center-panel #banner-wrapper div.col-1').css('height','222px');//set height of quotes box
			$('#main #main-center-panel #banner-wrapper div.col-1').cycle({fx:'fade',timeout:'12000'});
		}
		if($('#home #main #main-center-panel #banner-wrapper div#quotes').length > 0 ){ // check if element is on page
			$('#home #main #main-center-panel #banner-wrapper div#quotes').css('height','222px');//set height of quotes box
			$('#home #main #main-center-panel #banner-wrapper div#quotes').cycle({fx:'fade',timeout:'12000'});
		}
		/* inner banner rotator */
		if($('#banner-outer-wrapper div.col-1 img').length > 0 ){ // check if element is on page
			$('#banner-outer-wrapper div.col-1').css('height','126px');//set height of quotes box
			$('#banner-outer-wrapper div.col-1').cycle({fx:'fade',timeout:'12000'});
		}
		if($('#banner-outer-wrapper div.col-2 div.content').length > 0 ){ // check if element is on page
			$('#banner-outer-wrapper div.col-2 div.content').css('height','126px');//set height of quotes box
			$('#banner-outer-wrapper div.col-2 div.content').cycle({fx:'fade',timeout:'12000'});
		}
	}
	
	
	//if the livequery plugin is detected and not IE	
	jQuery.each(jQuery.browser, function(i) {
		//IE7 & less
		if($.browser.msie && parseInt($.browser.version) <= 8){
			is_IE = true;
	  	}
	  	else{
			is_IE = false;
		}
	});
	
	if(is_IE == false){
		if(jQuery.fn.ajaxify){
			if($('div#load-content').length > 0 ){ // check if element is on page
		
				$('#main #main-center-panel').css({'position':'relative'});			 
				
				
				//use jQuery live method to bind click event to ajaxify behaviour
				$('a.ajax').live('mousedown', function(event) {	
					
					$(this).ajaxify({
						'submit': { // events to be carried out onclick/submit
						  'disable': {  // disable any inputs (form only)
							'selector': null,
							'className': null
						  },
						  'message': {  // display a message when the click event is fired
							'text': 'Page loading...',
							'className': 'ajaxify-loading'
						  },          
						  'waiting': { // if nothing happens after timeout * 1000 ms, update the message and re-enable the buttons
							'timeout': 0, // seconds
							'message': 'It looks like there was a problem with the request, please try again.',
							'className': 'error'
						  }
						},
						'update': '#load-content' // determine the update area automatically
						
					  });
	
					
					
				});
			}
		}
	}
	
});