/**
 * The custom JavaScript used for the added functionality.
 *
 * @author Dan Hensby <dan@betterbrief.co.uk>
 * @author Josh Holloway <josh@betterbrief.co.uk>
 * @author Will Morgan <will@betterbrief.co.uk>
 * @version 1.1
 * @copyright 2010 Better Brief LLP
 *
 */

//Load jQuery
google.load("jquery", "1.6");

// effectively 'on document ready'
google.setOnLoadCallback(function() {

	(function($) {

		//search text
		var $searchBox = $('#SearchForm_SearchForm_Search');
		if (!$searchBox.val()) {
			$searchBox.val('Search the site...');
		}
		$searchBox.focus(function() {
			if ($searchBox.val() == 'Search the site...') {
				$searchBox.val('');
			}
		}).blur(function() {
			if (!$searchBox.val()) {
				$searchBox.val('Search the site...');
			}
		}).closest('form').submit(function() {
			if ($searchBox.val() == 'Search the site...') {
				return false;
			}
		});


	//lazy load

		 $("img").lazyload({
             placeholder : "assets/lazy.gif",
             effect      : "fadeIn",
			 failurelimit : 10,
			threshold : 800 

          });
	


		//tabs
		  $("#usual1 ul").idTabs();
		
			//fittext
				$("#fittext1").fitText();
				$("#fittext2").fitText(1.2);
				$("#fittext3").fitText(1.1, { minFontSize: 11, maxFontSize: '30px' });
				$("#fittext4").fitText(1.1, { minFontSize: 20, maxFontSize: '25px' });

		//carosel
		var $slider = $('div.featuredPages');
		if ($slider.length) {
			$.getScript('/mysite/javascript/jquery.tools.min.js',function() {
				$slider.before('<div class="BackButton"><a href="#" class="prev browse left"></a></div>').after('<div class="NextButton"><a href="#" class="next browse right"></a></div>').scrollable();
			});
		}


		


		var $callback = $('#callback');
		if ($callback.length) {
			$.getScript('/mysite/javascript/jquery.tools.min.js',function() {
				$callback.overlay({

					onBeforeLoad: function() {
						this.getOverlay().addClass('callback');

						// grab wrapper element inside content
						/*var wrap = this.getOverlay().find(".wrap");

						// load the page specified in the trigger
						wrap.load(this.getTrigger().attr("href"));*/
						var $overlay = $('<div id="BackgroundOverlay" style="display:none;background:black;height:'+$(document).height()+'px;width:100%;position:absolute;top:0;left:0;z-index:9001"></div>').css('opacity', '0.6');
						$overlay.bind('click.close', function(ev) {
							if(ev.target === this) {
								$('#SubFrame a.close').trigger('click');
							}
						});
						$(document.body).prepend($overlay);
						$overlay.fadeIn();
						$(window).bind('resize.overlay', function() { $overlay.height($(this).height()); });
					},

					onLoad: function() {
						var $form = $('#Form_Form');
						$form.submit(function() {
							if (!$form.hasClass('sending')){
								$.ajax({
									beforeSend: function() {
										$form.addClass('sending');
										$form.fadeOut();
									},
									cache: false,
									data: $form.serialize(),
									dataType: 'text',
									error: function(request,textStatus,error) {
										$form.parent().append('<h2 stlye="display:none;">Sorry, there was an error.</h2>').children('h2').fadeIn();
									},
									success: function(data,textStatus,request) {
										$form.parent().append('<h2 stlye="display:none;">' + data + '</h2>').children('h2').fadeIn();
									},
									type: $form.attr('method'),
									url: $form.attr('action')
								});
							}
							return false;
						});
					},
					onClose: function() {
						this.getOverlay().removeClass('callback');
						$callback.trigger('onClose');
						//$('h2',$form).html('You have already submitted a request');
						$('#BackgroundOverlay').fadeOut(function() {
							$(this).remove();
						});
					}
				});
			});


			var $buynow = $('div.buyNowiFrame a');
			if ($buynow.length) {
				$.getScript('/mysite/javascript/jquery.tools.min.js',function() {
					$buynow.overlay({
						onBeforeLoad: function() {
							this.getOverlay().addClass('buyNow');
							// Trigger original beforeLoad and then extend it below:
							$buynow.trigger('onBeforeLoad');
							$($buynow.attr('rel') + ' iframe').show();
							var $overlay = $('<div id="BackgroundOverlay" style="display:none;background:black;height:'+$(document).height()+'px;width:100%;position:absolute;top:0;left:0;z-index:9001"></div>').css('opacity', '0.6');
							$overlay.bind('click.close', function(ev) {
								if(ev.target === this) {
									$('a.close').trigger('click');
								}
							});
							$(document.body).prepend($overlay);
							$overlay.fadeIn();
							$(window).bind('resize.overlay', function() { $overlay.height($(this).height()); });
						},
						onClose: function() {
							this.getOverlay().removeClass('buyNow');
							$buynow.trigger('onClose');
							$($buynow.attr('rel') + ' iframe').hide();
							$('#BackgroundOverlay').fadeOut(function() {
								$(this).remove();
							});
						}
					});
				});
			}
		}

	})(jQuery);

});

function validateForm(theform) {
	for (var i=0; i<theform.elements.length; i++) {
		var element = theform.elements[i];
		if (element.className.indexOf("subrequired") !=-1) {
			element.className = "subrequired";
			if (!isFilled(element)) {
				alert("Please enter your " +element.id);
				element.className += " error";
				element.focus();
				return false;
			}
		}
		if (element.className.indexOf("email") != -1) {
			element.className = "subrequired";
			if (!isEmail(element)) {
				alert("Please check you have entered a valid email address");
				element.className += " error";
				element.focus();
				return false;
			}
		}
	}
	return true;
}

function isFilled(field) {
	return !(field.value.length < 1);
}
function isEmail(field) {
	return !(field.value.indexOf("@") == -1 || field.value.indexOf(".") == -1);
}


$("h2").each(function() {
        var wordArray = $(this).text().split(" ");
        wordArray[wordArray.length-2] += "&nbsp;" + wordArray[wordArray.length-1];
        wordArray.pop();
        $(this).html(wordArray.join(" "));
});

	//$('img').hide();
	$(window).load(function() {
		$('.ex1').hoverizr({speedOut: 'slow',effect:"blur",overlay: "bottom",container: "pipa",width: "100px", height: "100px",stretch: "yes"});
		$('.ex2').hoverizr({speedOut: 'slow'});
		$('#ex3').hoverizr({speedIn: 'slow',effect:"invert"});
	});


	// Create the dropdown base
	$("<select />").appendTo("nav");

	// Create default option "Go to..."
	$("<option />", {
	   "selected": "selected",
	   "value"   : "",
	   "text"    : "Go to..."
	}).appendTo("nav select");

	// Populate dropdown with menu items
	$("nav a").each(function() {
	 var el = $(this);
	 $("<option />", {
	     "value"   : el.attr("href"),
	     "text"    : el.text()
	 }).appendTo("nav select");
	});
	
	$("nav select").change(function() {
	  window.location = $(this).find("option:selected").val();
	});
