(function($){

	// Applies a change select to the select of the class
	$.fn.changeselect = function(options) {
	
		var defaults = {	appendUrl: '' }
		var options = $.extend(defaults, options);
		
		$(this).each(function() {
			$(this).change(function() {
				window.location.href= $(this).val();
			});
		});
	}

	// Captures the title tag of an image and adds a div to 
	$.fn.caption = function (options) {
	
		// Default settings
		var defaults = {	wrapperElement: 'div',
							wrapperClass: 'caption',
							captionElement: 'p',
							imageAttr: 'alt',
							requireText: true,
							copyStyle: false,
							removeStyle: true,
							removeAlign: true,
							copyAlignmentToClass: false,
							copyFloatToClass: true,
							autoWidth: true,
							animate: true,
							show: {opacity: 'show'},
							showDuration: 200,
							hide: {opacity: 'hide'},
							hideDuration: 200	};
							
		var options = $.extend(defaults, options);
		
		$(this).each(function(){
		//Only add the caption after the image has been loaded.  This makes sure we can know the width of the caption.
			
			$(this).bind('load', function(){
				
				//Make sure the captioning isn't applied twice when the IE fix at the bottom is applied
				if($(this).data('loaded')) return false;
				$(this).data('loaded', true);
			
				//Shorthand for the image we will be applying the caption to
				var image = $(this);
				
				//Only create captions if there is content for the caption
				if(image.attr(options.imageAttr).length > 0 || !options.requireText){
					
					//Wrap the image with the caption div
					image.wrap("<" + options.wrapperElement + " class='" + options.wrapperClass + "'></" + options.wrapperElement + ">");
					
					//Save Image Float
					var imageFloat = image.css('float')
					
					//Save Image Style
					var imageStyle = image.attr('style');
					if(options.removeStyle) image.removeAttr('style');
					
					//Save Image Align
					var imageAlign = image.attr('align');
					if(options.removeAlign) image.removeAttr('align');
					
					//Put Caption in the Wrapper Div
					var div = $(this).parent().append('<' + options.captionElement + '>' + image.attr(options.imageAttr) + '</' + options.captionElement + '>');
					
					if(options.animate){
						$(this).next().hide();
						$(this).parent().hover(
						function(){
							//$(this).find('p').animate(options.show, options.showDuration);
							$(this).find('p').slideDown();
						},
						function(){
							//$(this).find('p').animate(options.hide, options.hideDuration);
							$(this).find('p').slideUp();
						});
					}
					
					//Copy Image Style to Div
					if(options.copyStyle) div.attr('style',imageStyle);
					
					//If there is an alignment on the image (for example align="left") add "left" as a class on the caption.  This helps deal with older Text Editors like TinyMCE
					if(options.copyAlignmentToClass) div.addClass(imageAlign);
					
					//Transfers the float style from the image to the caption container
					if(options.copyFloatToClass) div.addClass(imageFloat);
					
					//Properly size the caption div based on the loaded image's size
					if(options.autoWidth) div.width(image.width());
				}
			});
			
			//if the image has already loaded (due to being cached), force the load function to be called
			if (this.complete || this.naturalWidth > 0){
				$(this).trigger('load');
			}
			
		});
	}
	
	$.fn.populate = function ( user_options ) {
		
		var defaults = {}, settings = $.extend({}, defaults, user_options);
		
		this.each(function() {
			
			var $this = $(this);
			var title = this.title;
			var color = $this.css('color');
			
			if ( $this.val() == '' || $this.val() == title ) {
				$this.val(title);
				if ( settings.color != '' ) {
					$this.css('color', settings.color);
				}
			}
			
			$this.blur(function(){
				if ( $this.val() == '' ) {
					$this.val(title);
					if ( settings.color != '' ) {
						$this.css('color', settings.color);
					}
				}
			});
			
			$this.focus(function(){
				if ( $this.val() == title ) {
					$this.val('');
					$this.css('color', color);
				}
			});
			
			$this.closest("form").submit(function() { 
				if ($this.val() == title) {
					$this.val('');
				}
			});
			
		});
		return this;
	}	
	
	$.fn.populateForm = function ( user_options ) {
		
		var defaults = {}, settings = $.extend({}, defaults, user_options);
		
		
		$(this).find("[type=text]").each(function() {
			
			var $this = $(this);
			var title = this.title;
			var color = $this.css('color');
			
			if ( $this.val() == '' || $this.val() == title ) {
				$this.val(title);
				if ( settings.color != '' ) {
					$this.css('color', settings.color);
				}
			}
			
			$this.blur(function(){
				if ( $this.val() == '' ) {
					$this.val(title);
					if ( settings.color != '' ) {
						$this.css('color', settings.color);
					}
				}
			});
			
			$this.focus(function(){
				if ( $this.val() == title ) {
					$this.val('');
					$this.css('color', color);
				}
			});
			
		});
		
		$(this).submit(function() { 
			$(this).children().each(function() {
				var $this = $(this);
				var title = this.title;
				if ($this.val() == title) {
					$this.val('');
				}
			});
		});
		
		return this;
	}
	
	$.fn.alternateRowColours = function() {
		$('tbody tr:odd', this).removeClass('even').addClass('odd');
		$('tbody tr:even', this).removeClass('odd').addClass('even');
		return this;
	}

	$.fn.tableSort = function() {
		this.each(function() {
			var $table = $(this);
			$table.alternateRowColours();
			$('th', $table).each(function(column) {
				var $header = $(this);
				if($header.hasClass('.sort-alpha')) { 
					$header.addClass('clickable').hover(function() {
						$header.addClass('hover');
					}, function() {
						$header.removeClass('hover');
					}).click(function() {
						var sortDir = 1;
						if($header.is('.sorted-asc')) {
							sortDir = -1;
						}
						var rows = $table.find('tbody > tr').get();
						rows.sort(function(a, b) {
							var keyA = $(a).children('td').eq(column).text().toUpperCase();
							var keyB = $(b).children('td').eq(column).text().toUpperCase();
							
							if(keyA < keyB) return -sortDir;
							if(keyA > keyB) return sortDir;
							return 0;
						});
						$.each(rows, function(index, row) {
							$table.children('tbody').append(row);
						});
						$table.find('th').removeClass('sorted-asc').removeClass('sorted-desc');
						if(sortDir == 1) {
							$header.addClass('sorted-asc');
						} else {
							$header.addClass('sorted-desc');
						}
					});
				}
			});
		});
		return this;
	}

	$.fn.paginate = function(options) {
		
		// Default settings
		var defaults = { 	pagelabel: "Pages: " };
							
		var options = $.extend(defaults, options);
		
		this.each(function() {
			var currentPage = 0;
			var numPerPage = 10;
			var $table = $(this);

			$table.bind('repaginate', function() {
				$table.find('tbody tr').hide().slice(currentPage * numPerPage, (currentPage + 1) * numPerPage).show();
			});

			var numRows = $table.find('tbody tr').length;
			var numPages = Math.ceil(numRows / numPerPage);
			var $pager = $('<div class="pager"></div>');

			for(var page = 0; page < numPages; page++) {
				$('<span class="page-number"></span>').text(page + 1).bind('click', {newPage:page}, function(event) {
					currentPage = event.data['newPage'];
					$table.trigger('repaginate');
					$(this).addClass('active').siblings().removeClass('active');
				}).appendTo($pager).addClass('clickable');
			}
			
			if(numPages > 1) {
				$pager.insertBefore($table).find('span.page-number:first').addClass('active');
				$('<span class="pagelabel">' + options.pagelabel + '</span>').insertBefore('span.page-number:first');
				$table.find('tbody tr').hide().slice(currentPage, numPerPage).show();
			}
		});
		return this;
	}
	
	$.fn.formValidator = function (options, callBack) {
		
		// Default settings
		var defaults = { 	useAjax: false,
							showAlert: true,
							message: "Thank you",
							keepLocked: false };
							
		var options = $.extend(defaults, options);
		
		// result boolean
		var boolValid = false;
		
		// Stop the form from submitting unless all information is filled in
		$(this).submit(function() {
		
			// result error message
			var errorMsg = '';
			
			// Get rid of the error message box
			$(".error_msg", this).remove();
			
			var boolValid = true;
			
			var radNames = '';
			
			$(this).find(":input").each(function() {
				$(this).attr("disabled", true); 
				
				if($(this).hasClass("required")) {
				
					$(this).removeClass("invalid");
					
					if($(this).attr("name").indexOf("email") >= 0) {
						var mail_filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
						var tmpResult = mail_filter.test($(this).val());
						
						if(!tmpResult) {
							boolValid = false;
							errorMsg += "Email Address is not valid\n";
							$(this).addClass("invalid").fadeIn("slow");
							$(this).after("<span class=\"error_msg\">*</span>").fadeIn("slow");
						}
					}
					else {
						if ($(this).val() == "" || $(this).val() == $(this).attr("title")) {
							boolValid = false;
							errorMsg += $(this).attr("title") + "\n";
							$(this).addClass("invalid").fadeIn("slow");
							$(this).after("<span class=\"error_msg\">*</span>").fadeIn("slow");
						}
						else {
							if($(this).attr("type") == "radio") {
								var selected = true;
								if($('input[name=' + $(this).attr("name") + ']:checked').length == 0) {
									selected = false;
									radNames += $(this).attr("name");
								}
									
								if(!selected && $(this).attr("name").indexOf(radNames) < 0) {
									boolValid = false;
									errorMsg += $(this).attr("title") + "\n";
									$(this).addClass("invalid").fadeIn("slow");
								}
							}
							else if($(this).attr("type") == "checkbox") {
								if($(this).attr("checked")===false) {
									boolValid = false;
									errorMsg += $(this).attr("title") + "\n";
									$(this).addClass("invalid").fadeIn("slow");
								}							
							}
						}
					}	
				}
			});
			
			$(this).find("div.checkboxgroup").each(function() {
				var chkBoxCount = $(this).find(":input:checkbox").size();
				var notChecked = 0;
				$(this).find(":input:checkbox").each(function() { 
					if($(this).attr("checked")===false) {
						notChecked++;
					}
					if(notChecked == chkBoxCount) {
						boolValid = false;
						errorMsg += $(this).attr("title") + "\n";
					}
				});
			});
			
			if (!boolValid && options.showAlert) {
				alert("The following information is missing:\n\n" + errorMsg);
			}
			
			if(!options.keepLocked) {
				$(this).find(":input").each(function() {
					$(this).attr("disabled", false); 
				});
			}
			
			if(boolValid && options.useAjax) {
				//
				// Use an ajax method to post the information to the forms target
				$.ajax({
						type: $(this).attr("method"),
						url: $(this).attr("action"),
						data: $(this).serialize(),
						success: function(html) {
							
							// Get rid of the error message box and reset
							$(".error_msg", this).remove();
							$("form").each(function() { this.reset(); });
							
							// now we are calling our own callback function
							if(typeof callBack == 'function'){
								callBack.call(this, html);
							}
							else {
								//display message back to user here
								if(html.indexOf("|") > -1) {
									// Split the returned result
									var res = html.split("|");
									
									if(res[0] == "response") {
										alert(res[1]);
									} else {
										window.location.href = res[1];
									}
									
								} else {
									alert(options.message);
								}
							}
						}
					});
				return false;
			} else if (options.useAjax) {
				if(boolValid) {
					// Process normally
					var submitButton = $(this).find("input[type='submit']");
					$(submitButton).attr("value", "Please Wait...");
					$(submitButton).attr("disabled", "true");
				}
				return boolValid;
			} else {
				return boolValid;
			}
		});
	};
	
	$.fn.numberCheck = function() {
		$(this).bind('keypress', function(e) {
			if((e.which!=8 && e.which!=0 && (e.which<48 || e.which>57))) {
				return false;
			}
			else {
				return true;
			}
		});
	}
	
	$.fn.imageFader = function(options) {
	
		var options = $.extend({	pauseTime: 5000, 
									transitionTime: 500,
									targetObj: "img" }, options);
		
		Trans = function(obj) {
			var timer = null;
			var current = 0;
			var els = $(options.targetObj, obj).css("display", "none").css("position", "absolute");
			//$(obj).css("position", "relative");
			$(els[current]).css("display", "block");
			
			function transition() {
				var next = (current + 1) % els.length | 0;
				$(els[current]).fadeOut(options.transitionTime);
				$(els[next]).fadeIn(options.transitionTime);
				current = next;
				cue();
			};
			
			function cue() {
			
				if ($("> *", obj).length < 2) {
					return false;
				}
				if (timer) {
					clearTimeout(timer);
				}
				
				timer = setTimeout(transition, options.pauseTime);
			};

			cue();
		};

		return this.each(function() {
			var t = new Trans(this);
		});
	}
	
	$.fn.populateDropDown = function (options) {
	
		// Default settings
		var defaults = { target: "", targetval: "OTH", addFirst: true, firstDesc: "Please select", removeOnChange: true, noSelect: false, targetId: Math.round(Math.random() * 1000000000), removeAtStart: false };
		var options = $.extend(defaults, options);
		var _target = $(options.target);
		var _option_list;
		
		if(_target != "undefined") {
			$(this).ready(function() {
				_target.wrap('<span class="dropdown-wrap" id="' + options.targetId + '"></span>');
				
				// Get the object and clone it for re-use
				_option_list = _target.parent().html();
				
				// Remove options
				if(options.removeAtStart) {
					$("option", _target).remove();
				}
			});
		}
		
		$(this).change(function() {

			// Get the target value
			var val = $("option:selected", this).val();
			var _name = $(_target).attr('name');
			var _id = $(_target).attr('id');
			var _class = $(_target).attr('class');
			// If the amount of target elements is zero, change element into a text box
			if(val == options.targetval && val != $("option:first", this).val()) {
				// Create a text input and replace the span wrapper of the parent element
				var html = '<input type="hidden" id="' + _name + '" name="' + _name + '" value="OTH" /><input type="text" id="which" name="which" class="' + _class + ' required" title="Please explain where you heard about us" />';
				$("#" + options.targetId).html(html); // add new, then remove original input
			} else {				
				// Fill list with original option list
				$("#" + options.targetId).html(_option_list);				
				if(val != "") {
					// Show selected elements
					if(options.removeOnChange) {
						$("#" + options.targetId + " select" + options.target + " option:not(.category" + val + ")").remove();
					}
					else {
						if(val != $("option:first", this).val()) {
							$("#" + options.targetId + " select" + options.target + " option:not(.category" + val + ")").remove();
						}
					}
				}
					
				// Add a default value
				
				if(options.addFirst) {
					$("#" + options.targetId + " select" + options.target + "").prepend("<option value=\"\" selected=\"selected\">" + options.firstDesc + "</option>");
					$("#" + options.targetId + " select option:first").attr('selected', 'selected');
				}
				else {
					if(val != "") {
						$("#" + options.targetId + " select" + options.target + "").prepend("<option value=\"\" selected=\"selected\">" + options.firstDesc + "</option>");
						$("#" + options.targetId + " select option:first").attr('selected', 'selected');
					}
				}				
			}
			
		});
	}
	
	$.fn.simpleDropDown = function (options) {
	
		// Default settings
		var defaults = { optval: "OTH", optname: "which" };
		var options = $.extend(defaults, options);
		
		$(this).change(function() {
		
			var val = $("option:selected", this).val();

			// If the amount of target elements is zero, change element into a text box
			if(val == options.optval && val != $("option:first", this).val()) {
				
				// Create a text input and replace the span wrapper of the parent element
				var html = '<input type="text" id="' + options.optname + '" name="' + options.optname + '" class="required dropdowntemp" title="Please explain where you heard about us" />';
				$(this).after(html); // add new, then remove original input

			} else {
				
				// Fill list with original option list
				$(".dropdowntemp").remove();
				
			}
			
		});
	}
	
	$.fn.toggleCheckbox = function () {
		
		$(this).click(function() {
			var val = $(this).is(':checked');
			var myVal = $(this).val();
			var myName = $(this).attr('name');
			if(val) {
				// Remove any hidden fields with the element name in the class
				$(".hiddenCheckbox").remove();
			}
			else {
				// Add a hidden field after the element with the inverse
				var defaultVal = $("#default_" + myName).val();
				var checkBox = '<input type="hidden" name="' + myName + '" value="' + defaultVal + '" class="hiddenCheckbox" />';
				$(this).after(checkBox);
			}
		});
		
		var val = $(this).is(':checked');
		var myVal = $(this).val();
		var myName = $(this).attr('name');
		if(!val) {
			// Add a hidden field after the element with the inverse
			var defaultVal = $("#default_" + myName).val();
			var checkBox = '<input type="hidden" name="' + myName + '" value="' + defaultVal + '" class="hiddenCheckbox" />';
			$(this).after(checkBox);
		}
	}
	
	
	$.fn.expandable = function () {
		
		var parent = $(this);
		
		$(this).ready(function() {
			parent.find(".inner").hide();
			parent.find("span.indicator").text("[+]");
		});
		
		$(this).find(".expand").click(function() {
			parent.find(".inner").slideToggle("slow");
		}).toggle( function() {
			$(this).children("span.indicator").text("[-]");
		}, function() {
			$(this).children("span.indicator").text("[+]");
		});
	}
	
	$.fn.SU = function (options) {
	
		// Default settings
		var defaults = { target: "" };
		var options = $.extend(defaults, options);
		
		$(this).click(function() {
			$(options.target).slideUp();
		});
		
		return false;
	}
	
	//
	// Booking process functions
	$.fn.addCustomerDetails = function(options) {
	
		// Default settings
		var defaults = { parent: "" };
		var options = $.extend(defaults, options);
		
		var button = $(this);
		
		// Objects click function
		button.click(function() {
			// Hide the parent of the control if needed
			if(options.parent != "") {
				if($(options.parent)) {
					$(options.parent).slideUp();
				}
			}
			
			// Gets the customer data as a JSON object
			$.getJSON("/tabs_site/includes/getCusData.php", {}, function(results) {
				$.each(results, function(key,item){
					// Check to see if the element is a select box
					if($("select#"+key.toLowerCase())) {
						$("select#"+key.toLowerCase()+" option").each(function() { this.selected = (this.text == item); });
					}
					// Check for elements of type input
					if($("input#"+key.toLowerCase())) {
						$("input#"+key.toLowerCase()).val(item);
					}
				});
			});
			return false;
		});
	}
	
	$.fn.popup = function(options) {
		var defaults = {
			width: screen.width/2,
			height: screen.height/2,
			titlebar: true,
			status: true,
			resizable: true,
			toolbar: true,
			scrollbars: true,
			menubar: true
		};
		var options = $.extend(defaults, options);
	
		Boolean.prototype.setProperty = function() {
			if (this == true) { return "yes"; } else { return "no"; }
		};
	
		return this.each( function() {
			jQuery(this).click( function() {
				var target = this.target;
				var href = this.href;
				var posY = (parseInt(screen.height/2)) - (parseInt(options.height/2));
				var posX = (parseInt(screen.width/2)) - (parseInt(options.width/2));
				var win = window.open(href, target, 'titlebar=' + options.titlebar.setProperty() + ', screenX='+ posX +', screenY='+ posY +', left='+ posX +', top='+ posY +', status=' + options.status.setProperty() + ', resizable=' + options.resizable.setProperty() + ', toolbar=' + options.toolbar.setProperty() + ', scrollbars=' + options.scrollbars.setProperty() + ', menubar=' + options.menubar.setProperty() + ', width='+ options.width +', height='+ options.height);
				win.focus();
				return false;
			});
		});
	}
	
	jQuery.preloadImages = function() {   
		for(var i = 0; i<arguments.length; i++) {
			jQuery("<img>").attr("src", arguments[i]);   
		}
	}
	
})(jQuery);


	
	function GetExtraVal(options) {
		// Default settings
		var defaults = { ExtraCode: "", Amount: 1, FromDate: "", ToDate: "", PropRef: "", Remove: false };
		var options = $.extend(defaults, options);
		
		// Get the price of the extra
		$.get("/includes/getExtraData.php", options, function(data) {
			AddExtra(options.ExtraCode, parseInt(data), options.Amount, options.Remove)
			//return parseInt(data);
		});
	}
	
	function CalcDeposit(PropRef, FromDate, ToDate, TotalCost, BasicCost, ExtraPrice) {
		// Create the URL to calc the deposit
		var url="/includes/getDeposit.php"
		url = url + "?fromdate=" + FromDate
		url = url + "&todate=" + ToDate
		url = url + "&propref=" + PropRef
		url = url + "&totalprice=" + TotalCost
		url = url + "&basiccost=" + BasicCost
		url = url + "&extracost=" + ExtraPrice
		
		$.get("/includes/getDeposit.php", {fromdate: FromDate, todate: ToDate, propref: PropRef, totalprice: TotalCost, basiccost: BasicCost, extracost: ExtraPrice}, function(depPrice) {
			$("#depositprice").val(depPrice);
		});
	}
	
	var lastextraval = [];
	
	function AddExtra(extracode, value, quantity, remove, addtoadditionalextras) {
		if(value == 0) {
			value = GetExtraVal({ExtraCode: extracode, Amount: quantity, FromDate: $("#startdatehid").val(), ToDate: $("#todatehid").val(), PropRef: $("#propref").val(), Remove: false});
		}
		else {
			if(quantity === undefined) {
				quantity = 1;
				value = value * quantity;
			}
			else {
				value = value * quantity;
			}
		}
		
		if(!value) {
			value = 0;
		}
		
		if(remove) {
			if($("#additionalextras").val().indexOf(extracode) != -1) {
				var TEprice = parseInt($("#VALUE_" + extracode).val());
				if(TEprice != "") {
					RemoveExtra(extracode, TEprice);
				}
				$("#VALUE_" + extracode).value = parseInt(value);
			}
			else {
				if(lastextraval[extracode] === undefined) {
					RemoveExtra(extracode, 0, 0);
				}
				else {
					RemoveExtra(extracode, lastextraval[extracode], lastextraval[extracode]);
				}
			}
		}
		
		if(parseInt(value) >= 0) {
			var extrasprice = parseInt($("#extrasprice").val());
			var totalprice = parseInt($("#totalprice").val());
			var basicprice = parseInt($("#basicprice").val());
			
			// Set the value of the extra to equal the new value
			try {
				$("VALUE_" + extracode).val() = parseInt(value);
			} catch(e) {}
			
			extrasprice = extrasprice + parseInt(value);
			totalprice = totalprice + parseInt(value);
			
			$("#extrasprice").val(extrasprice)
			$("#totalprice").val(totalprice);
			$("#total_price").html(totalprice);
			$("#total_price3").html(totalprice)
			
			if(addtoadditionalextras !== undefined) {
				var extras = $("#additionalextras").val();				
				if(extras == "") {
					extras = extracode;
				}
				else {
					extras = extras + "," + extracode;
				}				
				$("#additionalextras").val(extras);
			}
			lastextraval[extracode] = value;
			CalcDeposit($("#propref").val(), $("#startdatehid").val(), $("#todatehid").val(), (totalprice + extrasprice), basicprice, extrasprice);
		}
	}

	function RemoveExtra(extracode, value, uselastextra) {
		var extrasprice = parseInt($("#extrasprice").val());
		var totalprice = parseInt($("#totalprice").val());
		var basicprice = parseInt($("#basicprice").val());
	
		if(uselastextra !== undefined) {
			if(lastextraval[extracode] !== undefined) {
				value = lastextraval[extracode];
			}
			else {
				value = 0;
			}
		}
		else {
			var extras = $("#additionalextras").val();			
			if(extras != "") {
				extras = extras.replace(extracode + ",", "");
				extras = extras.replace("," + extracode, "");
				extras = extras.replace(extracode, "");
			}
			$("#additionalextras").val(extras);
		}
		
		extrasprice = extrasprice - parseInt(value);
		totalprice = totalprice - parseInt(value);
		
		$("#extrasprice").val(extrasprice)
		$("#totalprice").val(totalprice)
		$("#total_price").html(totalprice)
		$("#total_price3").html(totalprice)
		
	
		
		CalcDeposit($("#propref").val(), $("#startdatehid").val(), $("#todatehid").val(), (totalprice + extrasprice), basicprice, extrasprice);
	}

	function RemoveAllExtras() {
		var extrasprice = parseInt($("#extrasprice").val());
		var totalprice = parseInt($("#firsttotalprice").val());
		
		$("#extrasprice").val(extrasprice);
		$("#totalprice").val(totalprice);
		$("#total_price").html(totalprice);
		$("#additionalextras").val("");
	}
	
	function formResponse(args) {
		$("#responsediv").slideUp().text(args).slideDown();
	}

	
	function shortListHandle(html) {
		if(html == "false") {
			alert("Sorry, there was a problem sending your shortlist, please try again");
			return false;
		}
		else if(html == "noprops") {
			alert("You do not have any properties selected");
			return false;
		}
		else {
			alert("Thank you, your email has been sent.");
			return true;
		}
	}
	
	function clear_form_elements(ele) {
		$(ele).find(':input').each(function() {
			switch(this.type) {
				case 'password':
				case 'select-multiple':
				case 'select-one':
				case 'text':
				case 'textarea':
					$(this).val('');
					break;
				case 'checkbox':
				case 'radio':
					this.checked = false;
			}
		});
	}
	
	function window_display(strurl) {
		confirmWin = window.open(strurl,'theconfirmWin','toolbar=no,location=no,directories=no,status=yes,scrollbars=no,menubar=no,width=400,height=400,left=20,top=20');
		
		if(confirmWin.opener==null)	{
			confirmWin.opener=window;
		}
	}

$(document).ready(function(){
	
	$(".populate").populate();
	$(".populateform").populateForm();
	$(".catdropdown").populateDropDown({target: ".sourcedropdown", addFirst: false });
	$("#areadropdown").populateDropDown({target: "#locationdropdown", addFirst: true, firstDesc: "Any Location"});
	$(".simpledropdown").simpleDropDown({optval: "OTH"});
	$(".simpledropdown_owner").simpleDropDown({optval: "OTH", optname: "whichone" });
	$('table.customers').paginate();
	$(".validate").formValidator({useAjax: true, showAlert: false});
	$(".validatelocked").formValidator({useAjax: true, showAlert: true, keeplocked: true});
	$(".shortlistvalidate").formValidator({useAjax: true, showAlert: true, message: "Thank you, your email has been sent." }, shortListHandle);
	$(".simplevalidate").formValidator({useAjax: false, showAlert: true});
	$(".numeric").numberCheck();
	$(".caption").caption();
	$(".changeselect").changeselect();
	$(".testvalidate").formValidator({useAjax: true, showAlert: false}, formResponse);
	$("input:checkbox.checkbox").toggleCheckbox();
	$(".popup").popup({ width: 320, height: 480, titlebar: false, status: false, resizable: true, toolbar: false, scrollbars: true, menubar: false });
	$(".expandable").expandable();
	
	$(".submitform").click(function() { 
		$(".submitform").closest("form").submit();
		return false;
	});

});

/**
* Json Count function
*/
function countJson(obj) {
	var prop;
	var count = 0;
	for (prop in obj) {
		count++;
	}
	return count;
}


(function(jQuery){jQuery.fn.customFadeIn=function(speed,callback){$(this).fadeIn(speed,function(){if(jQuery.browser.msie)
jQuery(this).get(0).style.removeAttribute('filter');if(callback!=undefined)
callback();});};jQuery.fn.customFadeOut=function(speed,callback){jQuery(this).fadeOut(speed,function(){if(jQuery.browser.msie)
jQuery(this).get(0).style.removeAttribute('filter');if(callback!=undefined)
callback();});};jQuery.fn.customFadeTo=function(speed,opacity,callback){jQuery(this).fadeTo(speed,opacity,function(){if(jQuery.browser.msie)
jQuery(this).get(0).style.removeAttribute('filter');if(callback!=undefined)
callback();});};jQuery.fn.featureCarousel=function(options){options=jQuery.extend({},jQuery.fn.featureCarousel.defaults,options||{});return jQuery(this).each(function(){var pluginData={currentCenterNum:options.startingFeature,containerWidth:0,containerHeight:0,largeFeatureWidth:0,largeFeatureHeight:0,smallFeatureWidth:0,smallFeatureHeight:0,totalFeatureCount:jQuery(this).children("div").length,currentlyMoving:false,featuresContainer:jQuery(this),featuresArray:[],containerIDTag:"#featureCarousel",timeoutVar:null,rotationsRemaining:0,itemsToAnimate:0,borderWidth:0,largeFontSize:"120%",smallFontSize:"80%"};preload(function(){setupFeatureDimensions();setupCarousel();setupFeaturePositions();setupBlips();initiateMove(true,1);});function preload(callback){if(options.preload==true){var $imageElements=pluginData.featuresContainer.find("img");var loadedImages=0;var totalImages=$imageElements.length;$imageElements.each(function(){jQuery(this).load(function(){loadedImages++;if(loadedImages==totalImages){callback();}});if(this.complete){jQuery(this).trigger('load');}});}else{callback();}}
function getContainer(featureNum){return pluginData.featuresArray[featureNum-1];}
function getBySetPos(position){$.each(pluginData.featuresArray,function(){if(jQuery(this).data().setPosition==position)
return jQuery(this);});}
function getPreviousNum(num){if((num-1)==0){return pluginData.totalFeatureCount;}else{return num-1;}}
function getNextNum(num){if((num+1)>pluginData.totalFeatureCount){return 1;}else{return num+1;}}
function setupFeatureDimensions(){pluginData.containerWidth=pluginData.featuresContainer.width();pluginData.containerHeight=pluginData.featuresContainer.height();var $firstFeatureImage=$(pluginData.containerIDTag).find("div img:first");if(options.largeFeatureWidth>1)
pluginData.largeFeatureWidth=options.largeFeatureWidth;else if(options.largeFeatureWidth>0&&options.largeFeatureWidth<1)
pluginData.largeFeatureWidth=$firstFeatureImage.width()*options.largeFeatureWidth;else
pluginData.largeFeatureWidth=$firstFeatureImage.outerWidth();if(options.largeFeatureHeight>1)
pluginData.largeFeatureHeight=options.largeFeatureHeight;else if(options.largeFeatureHeight>0&&options.largeFeatureHeight<1)
pluginData.largeFeatureHeight=$firstFeatureImage.height()*options.largeFeatureHeight;else
pluginData.largeFeatureHeight=$firstFeatureImage.outerHeight();if(options.smallFeatureWidth>1)
pluginData.smallFeatureWidth=options.smallFeatureWidth;else if(options.smallFeatureWidth>0&&options.smallFeatureWidth<1)
pluginData.smallFeatureWidth=$firstFeatureImage.width()*options.smallFeatureWidth;else
pluginData.smallFeatureWidth=$firstFeatureImage.outerWidth()/2;if(options.smallFeatureHeight>1)
pluginData.smallFeatureHeight=options.smallFeatureHeight;else if(options.smallFeatureHeight>0&&options.smallFeatureHeight<1)
pluginData.smallFeatureHeight=$firstFeatureImage.height()*options.smallFeatureHeight;else
pluginData.smallFeatureHeight=$firstFeatureImage.outerHeight()/2;}
function setupCarousel(){if(options.displayCutoff>0&&options.displayCutoff<pluginData.totalFeatureCount){pluginData.totalFeatureCount=options.displayCutoff;}
pluginData.featuresContainer.children("div").each(function(index){if(index<pluginData.totalFeatureCount){pluginData.featuresArray[index]=jQuery(this);}});if(pluginData.featuresContainer.children("div").first().css("borderLeftWidth")!="medium"){pluginData.borderWidth=parseInt(pluginData.featuresContainer.children("div").first().css("borderLeftWidth"))*2;}
pluginData.featuresContainer.children("div").each(function(){jQuery(this).css({'left':(pluginData.containerWidth/2)-(pluginData.smallFeatureWidth/2)-(pluginData.borderWidth/2),'width':pluginData.smallFeatureWidth,'height':pluginData.smallFeatureHeight,'top':options.smallFeatureOffset+options.topPadding,'opacity':0});}).find("img:first").css({'width':pluginData.smallFeatureWidth});if(pluginData.totalFeatureCount<4){pluginData.itemsToAnimate=pluginData.totalFeatureCount;}else{pluginData.itemsToAnimate=4;}
pluginData.featuresContainer.find("div > div.desc").hide();$("div.featureddesc").hide();}
function setupFeaturePositions(){jQuery.each(pluginData.featuresArray,function(i){jQuery(this).data('setPosition',i+1);});var oneBeforeStarting=getPreviousNum(options.startingFeature);pluginData.currentCenterNum=oneBeforeStarting;var $centerFeature=getContainer(oneBeforeStarting);$centerFeature.data('position',1);var $prevFeatures=$centerFeature.prevAll();$prevFeatures.each(function(i){jQuery(this).data('position',(pluginData.totalFeatureCount-i));});var $nextFeatures=$centerFeature.nextAll();$nextFeatures.each(function(i){if(jQuery(this).data('setPosition')!=undefined){jQuery(this).data('position',(i+2));}});if(options.counterStyle==3){jQuery.each(pluginData.featuresArray,function(){var pos=getPreviousNum(jQuery(this).data('position'));var $numberTag=jQuery("<span></span>");$numberTag.addClass("numberTag");$numberTag.html("("+pos+" of "+pluginData.totalFeatureCount+") ");jQuery(this).find('div p').prepend($numberTag);});}}
function setupBlips()
{if(options.counterStyle==1||options.counterStyle==2){var $list=jQuery("<ul></ul>");$list.addClass("blipsContainer");for(var i=0;i<pluginData.totalFeatureCount;i++){var counter;if(options.counterStyle==2)
counter="";else
counter=i+1;var $blip=jQuery("<div>"+counter+"</div>");$blip.addClass("blip");$blip.css("cursor","pointer");$blip.attr("id","blip_"+(i+1));var $listEntry=jQuery("<li></li>");$listEntry.append($blip);$listEntry.css("float","left");$listEntry.css("list-style-type","none");$list.append($listEntry);}
jQuery(pluginData.containerIDTag).append($list);$list.hide().show();}}
function changeBlip(oldCenter,newCenter)
{var $blipsContainer=pluginData.featuresContainer.find(".blipsContainer");var $oldCenter=$blipsContainer.find("#blip_"+oldCenter);var $newCenter=$blipsContainer.find("#blip_"+newCenter);$oldCenter.removeClass("blipSelected");$newCenter.addClass("blipSelected");}
function autoPlay(){if(pluginData.timeoutVar!=null){pluginData.timeoutVar=clearTimeout(pluginData.timeoutVar);}
if(options.autoPlay!=0){var autoTime=(Math.abs(options.autoPlay)<options.carouselSpeed)?options.carouselSpeed:Math.abs(options.autoPlay);pluginData.timeoutVar=setTimeout(function(){if(options.autoPlay>0)
initiateMove(true,1);else if(options.autoPlay<0)
initiateMove(false,1);},autoTime);}}
function rotatePositions(direction){jQuery.each(pluginData.featuresArray,function(){var newPos;if(direction==false){newPos=getNextNum(jQuery(this).data().position);}else{newPos=getPreviousNum(jQuery(this).data().position);}
jQuery(this).data('position',newPos);});}
function animateFeature($feature,direction)
{var new_width,new_height,new_top,new_left,new_zindex,new_padding,new_fade,new_font_size;var oldPosition=$feature.data('position');var newPosition;if(direction==true)
newPosition=getPreviousNum(oldPosition);else
newPosition=getNextNum(oldPosition);if(newPosition==1){new_width=pluginData.largeFeatureWidth;new_height=pluginData.largeFeatureHeight;new_top=options.topPadding;new_zindex=$feature.css("z-index");new_left=(pluginData.containerWidth/2)-(pluginData.largeFeatureWidth/2)-(pluginData.borderWidth/2);new_fade=1.0;new_font_size=pluginData.largeFontSize;}else{new_width=pluginData.smallFeatureWidth;new_height=pluginData.smallFeatureHeight;new_top=options.smallFeatureOffset+options.topPadding;new_zindex=1;new_fade=1;new_font_size=pluginData.smallFontSize;if(newPosition==pluginData.totalFeatureCount){new_left=options.sidePadding;}else if(newPosition==2){new_left=pluginData.containerWidth-pluginData.smallFeatureWidth-options.sidePadding-pluginData.borderWidth;}else{new_left=(pluginData.containerWidth/2)-(pluginData.smallFeatureWidth/2)-(pluginData.borderWidth/2);new_fade=0;}}
if(newPosition!=1){$feature.find("div.desc").hide();$("div.featureddesc").hide();}
$feature.animate({width:new_width,height:new_height,top:new_top,left:new_left,opacity:new_fade,fontSize:new_font_size},options.carouselSpeed,options.animationEasing,function(){if(newPosition==1){$feature.find("div").customFadeTo("fast",1);$("div#"+$feature.attr("id")+"desc").customFadeTo("fast",1);}
pluginData.rotationsRemaining=pluginData.rotationsRemaining-1;$feature.css("z-index",new_zindex);if($.browser.msie){this.style.removeAttribute('filter');}
if(options.counterStyle==1||options.counterStyle==2){if(newPosition==1){var newCenterItemNum=pluginData.featuresContainer.children("div").index($feature)+1;var oldCenterItemNum;if(direction==false)
oldCenterItemNum=getNextNum(newCenterItemNum);else
oldCenterItemNum=getPreviousNum(newCenterItemNum);changeBlip(oldCenterItemNum,newCenterItemNum);}}
var divide=pluginData.rotationsRemaining/pluginData.itemsToAnimate;if(divide%1==0){pluginData.currentlyMoving=false;rotatePositions(direction);if(pluginData.rotationsRemaining>0)
move(direction);}
autoPlay();}).find("img:first").animate({width:new_width,height:new_height},options.carouselSpeed,options.animationEasing).end();}
function move(direction)
{pluginData.currentlyMoving=true;var $newCenter,$newLeft,$newRight,$newHidden;if(direction==true){$newCenter=getContainer(getNextNum(pluginData.currentCenterNum));$newLeft=getContainer(pluginData.currentCenterNum);$newRight=getContainer(getNextNum(getNextNum(pluginData.currentCenterNum)));$newHidden=getContainer(getPreviousNum(pluginData.currentCenterNum));pluginData.currentCenterNum=getNextNum(pluginData.currentCenterNum);}else{$newCenter=getContainer(getPreviousNum(pluginData.currentCenterNum));$newLeft=getContainer(getPreviousNum(getPreviousNum(pluginData.currentCenterNum)));$newRight=getContainer(pluginData.currentCenterNum);$newHidden=getContainer(getNextNum(pluginData.currentCenterNum));pluginData.currentCenterNum=getPreviousNum(pluginData.currentCenterNum);}
if(direction){$newLeft.css("z-index",3);}else{$newRight.css("z-index",3);}
$newCenter.css("z-index",4);animateFeature($newLeft,direction);animateFeature($newCenter,direction);animateFeature($newRight,direction);if(pluginData.totalFeatureCount>3){animateFeature($newHidden,direction);}}
function initiateMove(direction,rotations){if(pluginData.currentlyMoving==false){var queue=rotations*pluginData.itemsToAnimate;pluginData.rotationsRemaining=queue;move(direction);}}
function findShortestDistance(from,to){var goingToLeft=1,goingToRight=1,tracker;tracker=from;while((tracker=getPreviousNum(tracker))!=to){goingToLeft++;}
tracker=from;while((tracker=getNextNum(tracker))!=to){goingToRight++;}
return(goingToLeft<goingToRight)?goingToLeft*-1:goingToRight;}
$(".leftButton").click(function(){initiateMove(true,1);return false;});$(".rightButton").click(function(){initiateMove(false,1);return false;});pluginData.featuresContainer.children("div").click(function(){var position=jQuery(this).data('position');if(position==2){initiateMove(true,1);}else if(position==pluginData.totalFeatureCount){initiateMove(false,1);}}).mouseover(function(){if(pluginData.currentlyMoving==false){var position=jQuery(this).data('position');if(position==2||position==pluginData.totalFeatureCount){jQuery(this).css("opacity",1.0);}}}).mouseout(function(){if(pluginData.currentlyMoving==false){var position=jQuery(this).data('position');if(position==2||position==pluginData.totalFeatureCount){jQuery(this).css("opacity",1.0);}}});jQuery("a",pluginData.containerIDTag).live("click",function(event){var $parents=jQuery(this).parentsUntil(pluginData.containerIDTag);$parents.each(function(){var position=jQuery(this).data('position');if(position!=undefined){if(position!=1){if(position==pluginData.totalFeatureCount){initiateMove(false,1);}else if(position==2){initiateMove(true,1);}
event.preventDefault();return false;}}});});jQuery(".blip").live("click",function(){var goTo=jQuery(this).attr("id").substring(5);var whereIsIt=pluginData.featuresContainer.children("div").eq(goTo-1).data('position');var currentlyAt=pluginData.currentCenterNum;if(goTo!=currentlyAt){var shortest=findShortestDistance(1,whereIsIt);if(shortest<0){initiateMove(false,(shortest*-1));}else{initiateMove(true,shortest);}}});});};jQuery.fn.featureCarousel.defaults={largeFeatureWidth:"120px",largeFeatureHeight:1,smallFeatureWidth:.5,smallFeatureHeight:.5,topPadding:20,sidePadding:30,smallFeatureOffset:50,startingFeature:1,carouselSpeed:500,autoPlay:0,counterStyle:1,preload:true,displayCutoff:0,animationEasing:'swing',largeFontSize:"16px",smallFontSize:"8px"};})(jQuery);

$(document).ready(function(){
	if($.datepicker) {
		$(".hasDatePicker").datepicker( {dateFormat: 'dd M yy' });
	}
	$("#spDiv2").css("left", ($(window).width()-114) + "px");
});
$(window).scroll(function(e) {
	$("#spDiv2").css("top", $(window).scrollTop() + "px");
	$("#spDiv2").css("left", ($(window).width()-114) + "px");
});

jQuery(document).ready(function() {
	jQuery("#featureCarousel").featureCarousel({
		smallFeatureWidth: 60,
		smallFeatureHeight: 60,
		topPadding: 0,
		sidePadding: 20,
		smallFeatureOffset: 20
	});
});



