

// Create closed namespace for jQuery code.
(function($) {


	// Extend the string object
	if(typeof String.prototype.trim !== 'function') { 
		String.prototype.trim = function() { 
		return this.replace(/^\s+|\s+$/g, '');  
		} 
	}

       //capitalise..
       String.prototype.capitalise = function(){
            return this.charAt(0).toUpperCase() + this.slice(1);
       }
        


	// Attach close action to Flash message
	var hook_up_flash_close = function() {
		$("#flash-message a").click(
			function()
			{
				$("#flash-message").remove();
			}
		);
	}


	$(document).ready(function() {


		if ( $('.homeFeatureBoxLast').length > 0 ) { 
			
			setInterval(function(){changeTweet();}, 5000);
			$('#twitter_stream li').hide();
			$('#twitter_stream li').filter(':first').addClass('current').show();
		} 
		
			                     
		function changeTweet()
		{
			
			var currentElem = $('#twitter_stream li.current');
			var currentID = currentElem.attr('id');
			var currentIndex = parseInt(currentID.substring(5,6));
			var tweets = $('#twitter_stream li');

			if(currentIndex == 5)
			{ 
				next = 1 
			} else {
				next = currentIndex + 1;
			}
			
			var nextElem = $('#twitter_stream li#tweet'+next);
			
			// Set all panels to hide
			tweets.hide();
			nextElem.fadeIn('slow');
			
			// Remove the active class from all links
			$('#twitter_stream li').removeClass('current');
			nextElem.addClass('current');
			
		}
		
		function process_form_return(json)
		{
			// Do we have an error
			if(json.errors.length == 0)
			{
				form_complete();
			}
			else
			{
				if(json.success)
				{
					alert(json.errors)
				}
				else
				{
					write_form_error(json.errors);
				}
			}		
		}


		function write_form_error(id)
		{
			$obj = $('#' + id);
			$theError = "Please " + $obj.attr("title").toLowerCase() + "|";
			$addError($obj);
			$displayErrorMessage($theError);
		}


		function form_complete()
		{
			// Close the modal
			$("#schemeInfoMsg").overlay().close();
			//$("#schemeJoinMsg").overlay().close(); // #schemeJoinMsg Div removed from DOM 
			
			// Create the Flash message
			html = '<div class="confirm" id="flash-message"><p>Thank you, your message has been sent</p><a href="#">Close</a></div>';
			
			// Add the flash message to the page
			$('#header').prepend(html);
			
			hook_up_flash_close();
		}


		 $("#contactSchemeForm button").live("click",
			function() 
			{
				var self = $(this);
				var theForm = self.parents("form");
				var doAJAX = true;

				// If the parent form has the validate class - run this process *before* firing the AJAX
				if(theForm.hasClass("validate")) doAJAX = $validateInputs(theForm);

				if(doAJAX)
				{
					// Hide any error
					$hideErrorMessage();
		
					var data_string = theForm.serialize();
					var ajax_url = theForm.attr('action');

					$.ajax({
						type: "POST",
						timeout: 5000, // May need to adjust time allowance here
						url: ajax_url,
						data: data_string,
						dataType: "json",
						success: function(json) {
							process_form_return(json);
						},
						error: function() {
							alert("Error");
						}
					});
					
				}

				// Always return false, we don't want this form submitted
				return false;
			}
		);

		// Hook up Flash close
		hook_up_flash_close();


		// Print this page link
		$(".backToTop").after("| <a href=\"#\" onclick=\"window.print();\">Print</a>");
		$(".printShare").prepend(" <span class=\"printLink\"><a href=\"#\" onclick=\"window.print();\">Print</a> | </span> ");


		// Remove search term onfocus
		$.fn.search = function() {
			return this.focus(function() {
				if( this.value == this.defaultValue ) {
					this.value = "";
				}
			}).blur(function() {
				if( !this.value.length ) {
					this.value = this.defaultValue;
				}
			});
		};
		$(".smallSearch input").search();


		// Edit Resource online - Textarea maxlength counter
		$(".maxlength").each(function() {

			//get maxlength value

			var className=$(this).attr('class').trim();
			var classes = className.split(' ');  
			var maxlength_value = null;
			var options;

			$(classes).each(function()
			{
				if (/^maxlength\-/)
				{
					maxlength_value = parseInt(this.replace(/^maxlength\-/,''));            
			 		options = {  
					'maxCharacterSize': maxlength_value,  
					'originalStyle': 'originalDisplayInfo',  
					'warningStyle': 'warningDisplayInfo',  
					'warningNumber': 40,  
					'displayFormat': ' #left Characters Left'  
					};
				}
			});

			//initialise the character counter
			$(this).textareaCount(options);

		});



          /* Brandcentre/form */ 


          //Colour selection behaviour
 
          if ($("#resCreateForm input[name=input_colourRadio]").size() > 0){
              set_label_colour = function(){
                  var class_prefix="resFormImgPreviewColour";
                  $("#resFormImgPreviewColour").attr("class", class_prefix + $("input:checked",$('#resFormColourSelect')).val().capitalise());
              }

              //set example poster label with the colour of the selected radio input 
              
             set_label_colour();  
             
             $("#resCreateForm input[name=input_colourRadio]").change(function(){ 
                set_label_colour();
             });

             //assign a specific class to the input elements that have already a default value set
             $("#resCreateForm input[type=text], textarea").each(function(){
                  if (this.value.length > 0){
                   $(this).addClass('hasDefaultValue');
                   $(this).focus(function(){
                          $(this).removeClass('hasDefaultValue');   
                   });
                 }
             });
             //remove this class on focus
             
          }

        /* end brandcentre */

	});




})(jQuery);

