(function(jQuery) {
	
	// Applies a change select to the select of the class
	jQuery.fn.suggest = function(options) {
	
		var defaults = { target: "#search_suggest", suggestitem: "div.suggestitem" , suggestbox: "#suggestbox" }
		var options = jQuery.extend(defaults, options);
		var globalPosition = -1;
		$input = jQuery(this);
		
		$input.each(function() {
			// Check for the value of the input element, only search for 2 characters or more
			$input.keyup(processKey);
			
			$input.closest("form").bind("keypress", function(e) {
				if(e.keyCode) {
					key = e.keyCode; // Normal browsers
				}
				else {
					key = String.fromCharCode(e.which);	// IE
				}
				if(key == 13) {
					SubmitForm(e);
					return false;
				}
			});
		});
		
		
		function processKey(e) {
			if($input.val().length > 2) {
				// Test for keycodes
				if(e.keyCode) {
					key = e.keyCode; // Normal browsers
				}
				else {
					key = String.fromCharCode(e.which);	// IE
				}
				
				if(key == 40) { // Down
					highlightSuggestItem(e, "down");
				}
				else if(key == 38) { // Up
					highlightSuggestItem(e, "up");
				}
				else if(key == 13) { // Enter
					SubmitForm(e);
					return false;
				} else if(key == 27) { //Escape
					jQuery('#suggestbox').val(''); //Clear the input box
					clearSuggest(e); //Remove the suggestions
				}
				else {
					suggestitem(e);
				}
			}
			else {
				if(key == 13) {
					SubmitForm(e);
					return false;
				}
				else {
					clearSuggest(e);
				}
			}
		}
		
		function SubmitForm(e) {
			if(globalPosition > -1) {
				window.location = "/cottage-details/" + jQuery(options.target + " " + options.suggestitem).eq(globalPosition).attr("propertyref");
			}
			else {
				jQuery(options.suggestbox).closest("form").submit();
			}
		}
		
		function suggestitem(e) {
			if($input.val().length > 2) {
				jQuery.get("/includes/custom/suggest.php", {text: $input.val()}, function(suggestdata) {
					if(suggestdata != "") {
						// Reset global position
						globalPosition = -1;
						jQuery(options.target).css({'display': 'block'});
						jQuery(options.target).html(suggestdata);
						
						// Add mouse bind
						jQuery(options.target + " " + options.suggestitem).each(function(index) {
							// Bind mouse function
							jQuery(options.target + " " + options.suggestitem).eq(index).bind("mouseover", function() {
								highlightItem(index);
							});
						});
					}
					else {
						clearSuggest(e);
					}
				}); 
			}
			else {
				clearSuggest(e);
			}
		}
		
		function clearSuggest(e) {
			jQuery(options.target).css({'display': 'none'});
			jQuery(options.target).html("");
			globalPosition = -1;
		}
		
		function highlightSuggestItem(e, direction) {
			// Remove css
			jQuery(options.target + " " + options.suggestitem).removeClass("suggestselected");
			
			if(direction == "down") {
				globalPosition++;
			}
			else {
				globalPosition--;
			}
			
			// Reset if out of bounds
			if(globalPosition >= $(options.target + " " + options.suggestitem).length) {
				globalPosition = 0;
			}
			else if(globalPosition < 0) {
				globalPosition = $(options.target + " " + options.suggestitem).length - 1;
			}
			
			// Add css based on index
			jQuery(options.target + " " + options.suggestitem).each(function(index) {
				if(index == globalPosition) {
					jQuery(options.target + " " + options.suggestitem).eq(index).addClass("suggestselected");
				}
			});
		}
		
		// Overide function
		function highlightItem(index) {
			// Remove css
			jQuery(options.target + " " + options.suggestitem).removeClass("suggestselected");
			// Overide global position
			globalPosition = index;
			// Add Class
			jQuery(options.target + " " + options.suggestitem).eq(index).addClass("suggestselected");
		}
	}
	
	// Applies a change select to the select of the class
	jQuery.fn.changeselect = function(options) {
	
		var defaults = {	appendUrl: '' }
		var options = jQuery.extend(defaults, options);
		
		jQuery(this).each(function() {
			jQuery(this).change(function() {
				window.location.href= jQuery(this).val();
			});
		});
	}

	// Captures the title tag of an image and adds a div to 
	jQuery.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 = jQuery.extend(defaults, options);
		
		jQuery(this).each(function(){
		//Only add the caption after the image has been loaded.  This makes sure we can know the width of the caption.
			
			jQuery(this).bind('load', function(){
				
				//Make sure the captioning isn't applied twice when the IE fix at the bottom is applied
				if(jQuery(this).data('loaded')) return false;
				jQuery(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 = jQuery(this).parent().append('<' + options.captionElement + '>' + image.attr(options.imageAttr) + '</' + options.captionElement + '>');
					
					if(options.animate){
						jQuery(this).next().hide();
						jQuery(this).parent().hover(
						function(){
							jQuery(this).find('p').slideDown();
						},
						function(){
							jQuery(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){
				jQuery(this).trigger('load');
			}
			
		});
	}
	
	jQuery.fn.populate = function ( user_options ) {
		
		var defaults = {}, settings = jQuery.extend({}, defaults, user_options);
		
		this.each(function() {
			
			var $this = jQuery(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;
	}	
	
	jQuery.fn.populateForm = function ( user_options ) {
		
		var defaults = {}, settings = jQuery.extend({}, defaults, user_options);
		
		
		jQuery(this).find("[type=text]").each(function() {
			
			var $this = jQuery(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);
				}
			});
			
		});
		
		jQuery(this).submit(function() { 
			jQuery(this).children().each(function() {
				var $this = jQuery(this);
				var title = this.title;
				if ($this.val() == title) {
					$this.val('');
				}
			});
		});
		
		return this;
	}
	
	jQuery.fn.alternateRowColours = function() {
		jQuery('tbody tr:odd', this).removeClass('even').addClass('odd');
		jQuery('tbody tr:even', this).removeClass('odd').addClass('even');
		return this;
	}

	jQuery.fn.tableSort = function() {
		this.each(function() {
			var $table = jQuery(this);
			$table.alternateRowColours();
			jQuery('th', $table).each(function(column) {
				var $header = $jQuery(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 = jQuery(a).children('td').eq(column).text().toUpperCase();
							var keyB = jQuery(b).children('td').eq(column).text().toUpperCase();
							
							if(keyA < keyB) return -sortDir;
							if(keyA > keyB) return sortDir;
							return 0;
						});
						jQuery.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;
	}

	jQuery.fn.paginate = function(options) {
		
		// Default settings
		var defaults = { 	pagelabel: "Pages: " };
							
		var options = jQuery.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 = jQuery('<div class="pager"></div>');

			for(var page = 0; page < numPages; page++) {
				jQuery('<span class="page-number"></span>').text(page + 1).bind('click', {newPage:page}, function(event) {
					currentPage = event.data['newPage'];
					$table.trigger('repaginate');
					jQuery(this).addClass('active').siblings().removeClass('active');
				}).appendTo($pager).addClass('clickable');
			}
			
			if(numPages > 1) {
				$pager.insertBefore($table).find('span.page-number:first').addClass('active');
				jQuery('<span class="pagelabel">' + options.pagelabel + '</span>').insertBefore('span.page-number:first');
				$table.find('tbody tr').hide().slice(currentPage, numPerPage).show();
			}
		});
		return this;
	}
	
	jQuery.fn.formValidator = function (options, callBack) {
		
		// Default settings
		var defaults = { 	useAjax: false,
							showAlert: true,
							message: "Thank you",
							keepLocked: false,
							showInvalid: false };
							
		var options = jQuery.extend(defaults, options);
		
		// result boolean
		var boolValid = false;
		
		// Stop the form from submitting unless all information is filled in
		jQuery(this).submit(function() {
		
			// result error message
			var errorMsg = '';
			
			// Get rid of the error message box
			jQuery(".error_msg", this).remove();
			
			var boolValid = true;
			
			var radNames = '';
			
			jQuery(this).find(":input").each(function() {
				jQuery(this).attr("disabled", true); 
				
				if(jQuery(this).hasClass("required")) {
				
					jQuery(this).removeClass("invalid");
					
					if(jQuery(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(jQuery(this).val());
						
						if(!tmpResult) {
							boolValid = false;
							errorMsg += "Email Address is not valid\n";
							jQuery(this).addClass("invalid").fadeIn("slow");
							if(options.showInvalid) {
								jQuery(this).after("<span class=\"error_msg\">*</span>").fadeIn("slow");
							}
						}
					}
					else {
						if (jQuery(this).val() == "" || jQuery(this).val() == jQuery(this).attr("title")) {
							boolValid = false;
							errorMsg += jQuery(this).attr("title") + "\n";
							jQuery(this).addClass("invalid").fadeIn("slow");
							if(options.showInvalid) {
								jQuery(this).after("<span class=\"error_msg\">*</span>").fadeIn("slow");
							}
						}
						else {
							if(jQuery(this).attr("type") == "radio") {
								var selected = true;
								if(jQuery('input[name=' + jQuery(this).attr("name") + ']:checked').length == 0) {
									selected = false;
									radNames += jQuery(this).attr("name");
								}
									
								if(!selected && jQuery(this).attr("name").indexOf(radNames) < 0) {
									boolValid = false;
									errorMsg += jQuery(this).attr("title") + "\n";
									jQuery(this).addClass("invalid").fadeIn("slow");
								}
							}
							else if(jQuery(this).attr("type") == "checkbox") {
								if(jQuery(this).attr("checked")===false) {
									boolValid = false;
									errorMsg += jQuery(this).attr("title") + "\n";
									jQuery(this).addClass("invalid").fadeIn("slow");
								}							
							}
						}
					}	
				}
			});
			
			jQuery(this).find("div.checkboxgroup").each(function() {
				var chkBoxCount = jQuery(this).find(":input:checkbox").size();
				var notChecked = 0;
				jQuery(this).find(":input:checkbox").each(function() { 
					if(jQuery(this).attr("checked")===false) {
						notChecked++;
					}
					if(notChecked == chkBoxCount) {
						boolValid = false;
						errorMsg += jQuery(this).attr("title") + "\n";
					}
				});
			});
			
			if (!boolValid && options.showAlert) {
				alert("The following information is missing:\n\n" + errorMsg);
			}
			
			if(typeof callBack == 'function' && !boolValid){
				callBack.call(this, 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
				jQuery.ajax({
						type: jQuery(this).attr("method"),
						url: jQuery(this).attr("action"),
						data: jQuery(this).serialize(),
						success: function(html) {
							
							// Get rid of the error message box and reset
							jQuery(".error_msg", this).remove();
							jQuery("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']");
					jQuery(submitButton).attr("value", "Please Wait...");
					jQuery(submitButton).attr("disabled", "true");
				}
				return boolValid;
			} else {
				return boolValid;
			}
		});
	};
	
	jQuery.fn.numberCheck = function() {
		jQuery(this).bind('keypress', function(e) {
			if((e.which!=8 && e.which!=0 && (e.which<48 || e.which>57))) {
				return false;
			}
			else {
				return true;
			}
		});
	}
	
	jQuery.fn.imageFader = function(options) {
	
		var options = jQuery.extend({	pauseTime: 5000, 
									transitionTime: 500,
									targetObj: "img",
									captionTarget: ""}, options);
		
		Trans = function(obj) {
			var timer = null;
			var current = 0;
			var els = jQuery(options.targetObj, obj).css("display", "none").css("position", "absolute");
			jQuery(els[current]).css("display", "block");
			
			function transition() {
				var next = (current + 1) % els.length | 0;
				jQuery(els[current]).fadeOut(options.transitionTime);
				
				//If a captionTarget has been specified then put the images title text in to the specified element
				if (options.captionTarget != '') {
					jQuery(options.captionTarget).html(jQuery(els[next]).attr('title'));
				}
				jQuery(els[next]).fadeIn(options.transitionTime);
				current = next;
				cue();
			};
			
			function cue() {
			
				if (jQuery("> *", obj).length < 2) {
					return false;
				}
				if (timer) {
					clearTimeout(timer);
				}
				
				timer = setTimeout(transition, options.pauseTime);
			};

			cue();
		};

		return this.each(function() {
			var t = new Trans(this);
		});
	}
	
	jQuery.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") {
			jQuery(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) {
					var val = jQuery("option:selected", _target).val();
					jQuery("option option:not(.category" + val + ")", _target).remove();
				}
			});
		}
		
		jQuery(this).change(function() {

			// Get the target value
			var val = jQuery("option:selected", this).val();
			var _name = jQuery(_target).attr('name');
			var _id = jQuery(_target).attr('id');
			var _class = jQuery(_target).attr('class');
			// If the amount of target elements is zero, change element into a text box
			if(val == options.targetval && val != jQuery("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" />';
				jQuery("#" + options.targetId).html(html); // add new, then remove original input
			} else {				
				// Fill list with original option list
				jQuery("#" + options.targetId).html(_option_list);				
				if(val != "") {
					// Show selected elements
					if(options.removeOnChange) {
						jQuery("#" + options.targetId + " select" + options.target + " option:not(.category" + val + ")").remove();
					}
					else {
						if(val != jQuery("option:first", this).val()) {
							jQuery("#" + options.targetId + " select" + options.target + " option:not(.category" + val + ")").remove();
						}
					}
				}
					
				// Add a default value
				
				if(options.addFirst) {
					jQuery("#" + options.targetId + " select" + options.target + "").prepend("<option value=\"\" selected=\"selected\">" + options.firstDesc + "</option>");
					jQuery("#" + options.targetId + " select option:first").attr('selected', 'selected');
				}
				else {
					if(val != "") {
						jQuery("#" + options.targetId + " select" + options.target + "").prepend("<option value=\"\" selected=\"selected\">" + options.firstDesc + "</option>");
						jQuery("#" + options.targetId + " select option:first").attr('selected', 'selected');
					}
				}				
			}
			
		});
	}
	
	jQuery.fn.simpleDropDown = function (options) {
	
		// Default settings
		var defaults = { optval: "OTH", optname: "which" };
		var options = jQuery.extend(defaults, options);
		jQuery(this).change(function() {
			var val = jQuery("option:selected", this).val();
			// If the amount of target elements is zero, change element into a text box
			if(val == options.optval && val != jQuery("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" />';
				jQuery(this).after(html); // add new, then remove original input
			} else {
				// Fill list with original option list
				jQuery(".dropdowntemp").remove();
			}
		});
	}
	
	jQuery.fn.toggleCheckbox = function () {
		
		jQuery(this).click(function() {
			var val = jQuery(this).is(':checked');
			var myVal = jQuery(this).val();
			var myName = jQuery(this).attr('name');
			if(val) {
				// Remove any hidden fields with the element name in the class
				jQuery(".hiddenCheckbox").remove();
			}
			else {
				// Add a hidden field after the element with the inverse
				var defaultVal = jQuery("#default_" + myName).val();
				var checkBox = '<input type="hidden" name="' + myName + '" value="' + defaultVal + '" class="hiddenCheckbox" />';
				jQuery(this).after(checkBox);
			}
		});
		
		var val = jQuery(this).is(':checked');
		var myVal = jQuery(this).val();
		var myName = jQuery(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" />';
			jQuery(this).after(checkBox);
		}
	}
	
	
	jQuery.fn.expandable = function () {
		
		var parent = $(this);
		
		jQuery(this).ready(function() {
			parent.find(".inner").hide();
			parent.find("span.indicator").text("[+]");
		});
		
		jQuery(this).find(".expand").click(function() {
			parent.find(".inner").slideToggle("slow");
		}).toggle( function() {
			jQuery(this).children("span.indicator").text("[-]");
		}, function() {
			jQuery(this).children("span.indicator").text("[+]");
		});
	}
	
	jQuery.fn.SU = function (options) {
	
		// Default settings
		var defaults = { target: "" };
		var options = jQuery.extend(defaults, options);
		
		jQuery(this).click(function() {
			jQuery(options.target).slideUp();
		});
		
		return false;
	}
	
	//
	// Booking process functions
	jQuery.fn.addCustomerDetails = function(options) {
	
		// Default settings
		var defaults = { parent: "" };
		var options = jQuery.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
			jQuery.getJSON("/tabs_site/includes/getCusData.php", {}, function(results) {
				jQuery.each(results, function(key,item){
					// Check to see if the element is a select box
					if(jQuery("select#"+key.toLowerCase())) {
						jQuery("select#"+key.toLowerCase()+" option").each(function() { this.selected = (this.text == item); });
					}
					// Check for elements of type input
					if(jQuery("input#"+key.toLowerCase())) {
						jQuery("input#"+key.toLowerCase()).val(item);
					}
				});
			});
			return false;
		});
	}
	
	jQuery.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 = jQuery.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
		jQuery.get("/test_sites/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="/test_sites/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
		
		jQuery.get("/test_sites/includes/getDeposit.php", {fromdate: FromDate, todate: ToDate, propref: PropRef, totalprice: TotalCost, basiccost: BasicCost, extracost: ExtraPrice}, function(depPrice) {
			jQuery("#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(jQuery("#additionalextras").val().indexOf(extracode) != -1) {
				var TEprice = parseInt($("#VALUE_" + extracode).val());
				if(TEprice != "") {
					RemoveExtra(extracode, TEprice);
				}
				jQuery("#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);
			
			jQuery("#extrasprice").val(extrasprice)
			jQuery("#totalprice").val(totalprice);
			jQuery("#total_price").html(totalprice);
			jQuery("#total_price3").html(totalprice)
			
			if(addtoadditionalextras !== undefined) {
				var extras = jQuery("#additionalextras").val();				
				if(extras == "") {
					extras = extracode;
				}
				else {
					extras = extras + "," + extracode;
				}				
				jQuery("#additionalextras").val(extras);
			}
			lastextraval[extracode] = value;
			CalcDeposit(jQuery("#propref").val(), jQuery("#startdatehid").val(), jQuery("#todatehid").val(), (totalprice + extrasprice), basicprice, extrasprice);
		}
	}

	function RemoveExtra(extracode, value, uselastextra) {
		var extrasprice = parseInt(jQuery("#extrasprice").val());
		var totalprice = parseInt(jQuery("#totalprice").val());
		var basicprice = parseInt(jQuery("#basicprice").val());
	
		if(uselastextra !== undefined) {
			if(lastextraval[extracode] !== undefined) {
				value = lastextraval[extracode];
			}
			else {
				value = 0;
			}
		}
		else {
			var extras = jQuery("#additionalextras").val();			
			if(extras != "") {
				extras = extras.replace(extracode + ",", "");
				extras = extras.replace("," + extracode, "");
				extras = extras.replace(extracode, "");
			}
			jQuery("#additionalextras").val(extras);
		}
		
		extrasprice = extrasprice - parseInt(value);
		totalprice = totalprice - parseInt(value);
		
		jQuery("#extrasprice").val(extrasprice)
		jQuery("#totalprice").val(totalprice)
		jQuery("#total_price").html(totalprice)
		jQuery("#total_price3").html(totalprice)
		
	
		
		CalcDeposit(jQuery("#propref").val(), jQuery("#startdatehid").val(), jQuery("#todatehid").val(), (totalprice + extrasprice), basicprice, extrasprice);
	}

	function RemoveAllExtras() {
		var extrasprice = parseInt(jQuery("#extrasprice").val());
		var totalprice = parseInt(jQuery("#firsttotalprice").val());
		
		jQuery("#extrasprice").val(extrasprice);
		jQuery("#totalprice").val(totalprice);
		jQuery("#total_price").html(totalprice);
		jQuery("#additionalextras").val("");
	}
	
	function formResponse(args) {
		jQuery("#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) {
		jQuery(ele).find(':input').each(function() {
			switch(this.type) {
				case 'password':
				case 'select-multiple':
				case 'select-one':
				case 'text':
				case 'textarea':
					jQuery(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;
		}
	}

jQuery(document).ready(function(){
	
	jQuery(".populate").populate();
	jQuery(".populateform").populateForm();
	jQuery(".catdropdown").populateDropDown({target: ".sourcedropdown", addFirst: false });
	jQuery("#areadropdown").populateDropDown({target: "#locationdropdown", addFirst: true, firstDesc: "Any Location"});
	jQuery(".simpledropdown").simpleDropDown({optval: "OTH"});
	jQuery(".simpledropdown_owner").simpleDropDown({optval: "OTH", optname: "whichone" });
	jQuery('table.customers').paginate();
	jQuery(".validate").formValidator({useAjax: true, showAlert: false});
	jQuery(".validatelocked").formValidator({useAjax: true, showAlert: true, keeplocked: true});
	jQuery(".shortlistvalidate").formValidator({useAjax: true, showAlert: true, message: "Thank you, your email has been sent." }, shortListHandle);
	jQuery(".simplevalidate").formValidator({useAjax: false, showAlert: true});
	jQuery(".numeric").numberCheck();
	jQuery(".caption").caption();
	jQuery(".changeselect").changeselect();
	jQuery(".testvalidate").formValidator({useAjax: true, showAlert: false}, formResponse);
	//jQuery("input:checkbox.checkbox").toggleCheckbox();
	jQuery(".popup").popup({ width: 320, height: 480, titlebar: false, status: false, resizable: true, toolbar: false, scrollbars: true, menubar: false });
	jQuery(".expandable").expandable();
	
	jQuery(".submitform").click(function() { 
		jQuery(".submitform").closest("form").submit();
		return false;
	});

	jQuery('#slider').imageFader({ transitionTime: 1000 });
	
	
	
});
