function async_submit(id, updateEl){
	$('#'+id).bind('submit',function(){
		if(validateOnSubmit(this)) {
			var new_ID = this.id;
			var inputs = [];
			$(':input', this).each(function() {
				inputs.push(this.name + '=' + escape(this.value));
			});
			inputs.push('type=async');
		  
			jQuery.ajax({
				type: this.method, 
				data: inputs.join('&'),
				url: this.action,
				timeout: 2000,
				error: function(textStatus) {
					alert("Your form could not be completed, please contact TJS to report this error.");
				},
				success: function(html) { 
					$(updateEl).html(html);
					async_submit(new_ID, updateEl);
				}
			});
		}
		return false;
	});
}

/***********************************************************
* Form Validation
************************************************************/
var node_text = 3;	// DOM text node-type
var emptyString = new RegExp(/^\s*$/ );

function trim(str){
	return str.replace(/^\s+|\s+$/g, '');
}

function msg(fld, msgtype, messtext, messnumber){
	var dispmessnumber;
	if (emptyString.test(messtext))
		dispmessnumber = String.fromCharCode(160);
	else
		dispmessnumber = messtext;
	var elem = document.getElementById(fld);
	elem.innerHTML = dispmessnumber;
	elem.className=msgtype;
}

var proceed = 2;
	
function commonCheck(valfield, infoID)
{
	//alert('Value Field: '+valfield+', Info Field: '+infoID);
	if (!document.getElementById)
		return true;  // not available on this browser - leave validation to the server
	var elem = document.getElementById(infoID);
	//if (!elem.firstChild) return true;  // not available on this browser
	//if (elem.firstChild.nodeType != node_text) return true;  // infoID is wrong type of node
	return proceed;
}

function validaterequired(valfield, infoID)
{
  var stat = commonCheck (valfield, infoID);
  if (stat != proceed) return stat;

    if (emptyString.test(valfield.value)) {
      msg (infoID, "warning", 'This is a required field', 1);
      return false;
    }

  msg (infoID, "valid", "", 3);
  return true;
}

function validateemail  (valfield, infoID)
{
  var stat = commonCheck (valfield, infoID);
  if (stat != proceed) return stat;

  var tfld = trim(valfield.value);  // value of field with whitespace trimmed off
  var email = new RegExp(/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i);
  if (!email.test(tfld)) {
    msg (infoID, "warning", 'Please enter a valid email address', 1);
    return false;
  } else {
  	msg (infoID, "valid", "", 3);
  	return true;
	}
}

function validatenumber (valfield, infoID)
{
	var stat = commonCheck (valfield, infoID);
	if (stat != proceed) return stat;

	var tfld = trim(valfield.value);

	if (emptyString.test(valfield.value)) {
		//msg (infoID, "warning", 'This is not a valid number', 1);
		//return false
		msg (infoID, "valid", "", 3);
  		return true;
	}

	var numberRE = new RegExp(/^[0-9 ]*$/);
	if (!numberRE.test(tfld)) {
		msg (infoID, "warning", 'This is not a valid number', 1);
		return false;
	}
	msg (infoID, "valid", "", 3);
	return true;
}

function validateagreed (valfield, infoID)
{
	var stat = commonCheck (valfield, infoID);
	if (stat != proceed) return stat;

	if (valfield.checked!=true) {
		msg (infoID, "warning", valfield.title, 1);
		return false;
	}
	msg (infoID, "valid", "", 3);
	return true;
}

function validateOnSubmit(form) {
	var elem;
	var errs=0;
	
	id = $(form).attr('id');

	var infoLinks = $('#'+id+' span.required');
	infoLinks.each(function(i) {
		//alert(infoLinks[i].id);
		$(this).innerHTML = '';
	});

	var dateLinks = $('#'+id+' input.date');
	dateLinks.each(function(i) {
		//alert('info_'+dateLinks[i].name);
		el = document.getElementById($(this).attr('id'));
		if (!validatedate(el, 'info_'+$(this).attr('name'))) errs +=1;
	});

	var numberLinks = $('#'+id+' input.number');
	numberLinks.each(function(i) {
		//alert('info_'+numberLinks[i].name);
		el = document.getElementById($(this).attr('id'));
		if (!validatenumber(el, 'info_'+$(this).attr('name'))) errs +=1;
	});

	var emailLinks = $('#'+id+' input.email');
	emailLinks.each(function(i) {
		//alert('info_'+emailLinks[i].name);
		el = document.getElementById($(this).attr('id'));
		if (!validateemail(el, 'info_'+$(this).attr('name'))) errs +=1;
	});

	var requireLinks = $('#'+id+' input.require');
	requireLinks.each(function(i) {
		//alert(requireLinks[i].id);
		el = document.getElementById($(this).attr('id'));
		if (!validaterequired(el, 'info_'+$(this).attr('name'))) errs +=1;
	});
	
	var requireLinks1 = $('#'+id+' textarea.require');
	requireLinks1.each(function(i) {
		//alert('info_'+requireLinks[i].name);
		el = document.getElementById($(this).attr('id'));
		if (!validaterequired(el, 'info_'+$(this).attr('name'))) errs +=1;
	});

	var agreeLinks = $('#'+id+' input.agree');
	agreeLinks.each(function(i) {
		//alert('info_'+agreeLinks[i].name);
		el = document.getElementById($(this).attr('id'));
		if (!validateagreed(el, 'info_'+$(this).attr('name'))) errs +=1;
	});

	return (errs==0);
};

/***********************************************************
* Set up the links in the page with their onblur and onsubmit handlers
************************************************************/
function preparePage(){

	//var forms = getElementsByClassName('validate','form');
	var forms = $('form.validate');
	//for (var i=0; i < forms.length; i++){
	forms.each(function(i) {
		$(this).bind('submit',function(){	
			return validateOnSubmit(this);
		});
	});
	
	// Toggle
	if ($("#header_title") && $("#header_content")) {
		//Handled in sifr-config.js to prevent problems with IE6
		/*$("#header_title").bind('click',function(){
			$("#header_content .content").slideToggle("normal");
		});*/
		//$("#header_title div").css('cursor', 'pointer');
		$("#header_content .content").hide();
		createCookie('hide', 1, 1);
	}
	
	$(".services li .title a").each(function () {
		anchor = getAnchor();
		//alert(anchor);
		uri_parts = $(this).attr('href').split('#');
		
		$(this).parent().siblings(".summary").each(function(){
			/*var content = document.getElementById($(this).attr('id')).textContent;
						
			//alert($(this).parent().html());		
			if(content == undefined){
				content = document.getElementById($(this).attr('id')).innerHTML;
			}
			
			if(content == ''){
				alert($(this).get());		
			}
			//alert(content);
		
			$(this).parent().append(content);*/
			//alert(uri_parts[1]);
			if(uri_parts.length==0 || uri_parts[1]!=anchor){
				$(this).hide();
			} else {
				$(this).show();
				$(this).parent().toggleClass("active");	
			}
			//$(this).remove();
		});
	});
	
	if ($(".services li .title a")) {
		$(".services li .title a").click(function () {
			$(this).parent().parent().toggleClass("active");
			$(this).parent().siblings(".summary").slideToggle("normal");
			return false;
		});
		//$(".services li .summary").hide();
		//createCookie('hide', 1, 1);
	}
    
    /*$(".tooltip").attr('alt', '');

	$(".tooltip").tooltip({ 
		t: '',
		tip: '.tip_wrapper',
		position: ['top', 'center'], 
		offset: [170, -75],
		opacity: 1
	})*/;
	
	//Open all links rel="nofollow" in a new window
	$("a[rel*='nofollow']").click(function() { window.open($(this).attr('href')); return false; });
	
	//Open all links rel="external" in a new window
	$("a[rel*='external']").click(function() { window.open($(this).attr('href')); return false; });
	
	$("#footer input").labelify();
	$("#footer label").hide();
	
	var asyncforms = $('form.async');
	asyncforms.each(function(i) {
		if($(this).attr('id') == 'comment_form'){
			async_submit(this.id, '#comment_form_container');
		}
	});	
	
	//Preload all images for featured
	if($('.featured')){
		$.getJSON('/featured/', { fetch: "true" },
			function(json){
				for(var i=0;i < json.length;i++) {
					$("<img>").attr("src", json[i]);
				}
			}
		);
		asyncFeatured();
	}
	
	//These elements need to wait until images have loaded to know the true height
	$(window).load(function(){
		//Set each row of teasers to be equal height
		$("ul.three_column").each(function(){
			var childCount = 0;
			var childArray = [];
			$(this).children('li').children('.paddingtonbear').each(function(){
				childCount++;
				childArray.push($(this));
				if(childCount==3){
					equalHeight(childArray);
					childCount = 0;
					childArray = [];
				}
			});
			if(childCount!=0){
				equalHeight(childArray);
			}
		});
		
		//Set all heights of footer elements to be equal
		equalHeight($("#footer div.list_position"));
		
		//Resize window	to force footer to bottom
		if($(window).height()>=$(document).height()){
			var increase_height = ($(window).height()-$('#wrapper').height());
			var current_height = $('#content').height();
			$('#content').height(current_height+increase_height);
		}
	});
		
	//Happy Easter
	$(window).konami(function(){ $('body').css('background', 'url(/images/rainbow_loop.gif)'); });
}


$.fn.konami = function(callback, code) {
	if(code == undefined) code = "38,38,40,40,37,39,37,39,66,65";
	
	return this.each(function() {
		var kkeys = [];
		$(this).keydown(function(e){
			kkeys.push( e.keyCode );
			if ( kkeys.toString().indexOf( code ) >= 0 ){
				$(this).unbind('keydown', arguments.callee);
				callback(e);
			}
		}, true);
	});
}

function equalHeight(group) {
    tallest = 0;
    
    $(group).each(function() {
        thisHeight = $(this).height();
        if(thisHeight > tallest) {
            tallest = thisHeight;
        }
    });
    $(group).each(function() {
    	$(this).height(tallest);	
	});
}


function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

jQuery.fn.labelify = function(settings) {
  settings = jQuery.extend({
    text: "label",
    labelledClass: ""
  }, settings);
  var lookups = {
    title: function(input) {
      return $(input).attr("title");
    },
    label: function(input) {
      return $("label[for=" + input.id +"]").text();
    }
  };
  var lookup;
  var jQuery_labellified_elements = $(this);
  return $(this).each(function() {
    if (typeof settings.text === "string") {
      lookup = lookups[settings.text]; // what if not there?
    } else {
      lookup = settings.text; // what if not a fn?
    };
    // bail if lookup isn't a function or if it returns undefined
    if (typeof lookup !== "function") { return; }
    var lookupval = lookup(this);
    if (!lookupval) { return; }

    // need to strip newlines because the browser strips them
    // if you set textbox.value to a string containing them    
    $(this).data("label",lookup(this).replace(/\n/g,''));
    $(this).focus(function() {
      if (this.value === $(this).data("label")) {
        this.value = this.defaultValue;
        $(this).removeClass(settings.labelledClass);
      }
    }).blur(function(){
      if (this.value === this.defaultValue) {
        this.value = $(this).data("label");
        $(this).addClass(settings.labelledClass);
      }
    });
    
    var removeValuesOnExit = function() {
      jQuery_labellified_elements.each(function(){
        if (this.value === $(this).data("label")) {
          this.value = this.defaultValue;
          $(this).removeClass(settings.labelledClass);
        }
      })
    };
    
    $(this).parents("form").submit(removeValuesOnExit);
    $(window).unload(removeValuesOnExit);
    
    if (this.value !== this.defaultValue) {
      // user already started typing; don't overwrite their work!
      return;
    }
    // actually set the value
    this.value = $(this).data("label");
    $(this).addClass(settings.labelledClass);

  });
};

//Returns anchor from current url
function getAnchor(){
	/*var regexS = "([\\#][^]*)";
	var regex = new RegExp(regexS);
	var results = regex.exec( window.location.href );*/
	var url = window.location.href;
	var url_parts = url.split('#');
	//alert(url_parts);
	//alert(url_parts[1]);
	//return false;
	if(url_parts[1] == '') return "";
	else return url_parts[1];
}

function asyncFeatured(){	
	$('.featured div.next a').bind('click',function(){
		asyncFeaturedSubmit(this, 'forward');
		return false;
	});
	
	$('.featured div.prev a').bind('click',function(){
		asyncFeaturedSubmit(this, 'back');
		return false;
	});
}

function asyncFeaturedSubmit(el, direction){
	$.get($(el).attr('href'), { async: "true" },
		function(xml){ //Success
			if(!xml){
				return true;
			} else {
				$(xml).find('prev').each(function(){
					var url = $(this).attr('url');
					if(url!=''){
						$('.featured div.prev').html('<a href="'+url+'">View Newer Posts</a>');
					} else {
						$('.featured div.prev').html('<span>View Newer Posts</span>');
					}
				});

				$(xml).find('current').each(function(){
					var title = $(this).find('title').text();
					var url = $(this).attr('url');
					$('.featured h2').fadeOut('normal', function(){
						$(this).html('<a href="'+url+'">'+title+'</a>');
						$('.home .featured h2').removeClass("sIFR-replaced");
						$(this).fadeIn();
						sIFR.replace(prelo_slab, {
						  selector: '.home .featured h2',
						  css: [
								'.sIFR-root { color: #264e0b; background-color: #ffffff; font-size: 36px; leading: -5; }',
								'a { color: #264e0b; text-decoration: none; }',
								'a:link { color: #264e0b; }',
								'a:hover { color: #264e0b; }'
						  ],
						  wmode: 'transparent'
						});
					});
					
					var strapline = $(this).find('strapline').text();
					$('.featured a.strapline').fadeOut('normal', function(){
						$(this).html(strapline).fadeIn();
						$(this).attr('href', url);
					});

					var intro = $(this).find('intro').text();					
					$('.featured div.intro').fadeOut('normal', function(){
						$(this).html(intro).fadeIn();
					});
					
					var source = $(this).find('image').attr('src');
					var alt = $(this).find('image').attr('alt');
					
					var featured_image = $('.featured_image a');
					
					if(direction == 'forward'){
						start_left = '470';
						end_left = "-500";
					} else {
						start_left = '-470';	
						end_left = "500";
					}
					
					$('.featured_image').append('<a href="'+url+'" style="left: '+start_left+'px;"><img src="'+source+'" alt="'+alt+'"/></a>');
				
					featured_image.animate({ left: end_left }, 500, function(){
						$(this).remove();
						setTimeout("$('.featured_image a').animate({ left: '0' },500)", 300);	
					});
				});

				$(xml).find('next').each(function(){
					var url = $(this).attr('url');
					if(url!=''){
						$('.featured div.next').html('<a href="'+url+'">View Older Posts</a>');
					} else {
						$('.featured div.next').html('<span>View Older Posts</span>');
					}
				});				
				asyncFeatured();
			}
		}, 'xml');
	return false;	
}

$(document).ready(preparePage);
