(function($){

	$.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() {
		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');
			}
			$pager.insertBefore($table).find('span.page-number:first').addClass('active');
			
			$table.find('tbody tr').hide().slice(currentPage, numPerPage).show();
		});
		return this;
	}
	
	$.fn.formValidator = function (options) {
		
		// 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 = '';
			
			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");
						}
					}
					else {
						if ($(this).val() == "" || $(this).val() == $(this).attr("title")) {
							boolValid = false;
							errorMsg += $(this).attr("title") + "\n";
							$(this).addClass("invalid").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");
								}							
							}
						}
					}	
				}
			});
			
			if (!boolValid && options.showAlert) {
				alert("The following information is missing:\n\n" + errorMsg);
			}
			
			if(!boolValid && !options.showAlert) {
				// Get rid of the error message box
				$(".error_msg", this).remove();
				
				// Append a new one and show
				$(":submit", this).after("<span class=\"error_msg\" style=\"display: none;\">You have some missing information in your form, please check and re-submit</span>");
				
				// Fade in
				$(".error_msg", this).fadeIn();
			}
			
			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(); });
							
							//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 {
				// Process normally
				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 };
		var options = $.extend(defaults, options);
		var _target = $(options.target);
		var _option_list;
		
		$(this).ready(function() {
			_target.wrap('<span class="dropdown-wrap"></span>');
			
			// Get the object and clone it for re-use
			_option_list = _target.parent().html();
			
			// Remove options
			if(options.removeOnChange) {
				$("option", _target).remove();
			}
			
			// Add Basic Please Select if required
			if(options.addFirst) {
				_target.prepend("<option value=\"\">" + options.firstDesc + "</option>");
				$("option:first", _target).attr('selected', 'selected');
			}
		});
		
		$(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" />';
				$("span.dropdown-wrap").html(html); // add new, then remove original input

			} else {
				
				// Fill list with original option list
				$("span.dropdown-wrap").html(_option_list);
				
				// Show selected elements
				if(options.removeOnChange) {
					$("span.dropdown-wrap select option:not(.category" + val + ")").remove();
				}
				else {
					if(val != $("option:first", this).val()) {
						$("span.dropdown-wrap select option:not(.category" + val + ")").remove();
					}
				}
				
				// Add a default value
				if(options.addFirst) {
					$("span.dropdown-wrap select").prepend("<option value=\"\">" + options.firstDesc + "</option>");
					$("span.dropdown-wrap 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.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("/tabssite/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;
		});
	}
	
})(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("/tabssite/includes/getExtraData.php", options, function(data) {
			AddExtra(options.ExtraCode, data, options.Amount, options.Remove)
		});
	}
	
	function CalcDeposit(PropRef, FromDate, ToDate, TotalCost, BasicCost, ExtraPrice) {
		// Create the URL to calc the deposit
		var url="/tabssite/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("/tabssite/includes/getDeposit.php", {fromdate: FromDate, todate: ToDate, propref: PropRef, totalprice: TotalCost, basiccost: BasicCost, extracost: ExtraPrice}, function(depPrice) {
			$("#depositprice").val(depPrice);
		});
	}
	
	function AddExtra(extracode, value, quantity, remove) {
		if(value == 0) {
			value = GetExtraVal({ExtraCode: extracode, Amount: quantity, FromDate: $("#startdatehid").val(), ToDate: $("#todatehid").val(), PropRef: $("#propref").val(), Remove: false});
		}
	
		if(remove) {
			if($("additionalextras").value.indexOf(extracode) != -1) {
				var TEprice = parseInt($("#VALUE_" + extracode).value);
				if(TEprice != "") {
					RemoveExtra(extracode, TEprice);
				}
				$("#VALUE_" + extracode).value = parseInt(value);
			}
		}
		
		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).value = 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)
			
			var extras = $("#additionalextras").val();
			
			if(extras == "") {
				extras = extracode;
			}
			else {
				extras = extras + "," + extracode;
			}
			
			$("#additionalextras").val(extras);
			
			CalcDeposit($("#propref").val(), $("#startdatehid").val(), $("#todatehid").val(), (totalprice + extrasprice), basicprice, extrasprice);
		}
	}

	function RemoveExtra(extracode, value) {
		var extrasprice = parseInt($("#extrasprice").val());
		var totalprice = parseInt($("#totalprice").val());
		var basicprice = parseInt($("#basicprice").val());
		
		extrasprice = extrasprice - parseInt(value);
		totalprice = totalprice - parseInt(value);
		
		$("#extrasprice").val(extrasprice)
		$("#totalprice").val(totalprice)
		$("#total_price").html(totalprice)
		$("#total_price3").html(totalprice)
		
		var extras = $("#additionalextras").value;
		
		if(extras != "") {
			extras = extras.replace(extracode + ",", "");
			extras = extras.replace("," + extracode, "");
			extras = extras.replace(extracode, "");
		}
		
		$("#additionalextras").val(extras);
		
		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("");
	}


$(document).ready(function(){
	
	$(".populate").populate();
	$(".populateform").populateForm();
	$(".maindropdown").populateDropDown({target: ".sourcedropdown"});
	$(".simpledropdown").simpleDropDown({optval: "OTH"});
	$(".simpledropdown_owner").simpleDropDown({optval: "OTH", optname: "whichone" });
	$('table.customers').paginate();
	$(".validate").formValidator({useAjax: true, showAlert: false});
	$(".simplevalidate").formValidator({useAjax: false, showAlert: true});
	$(".numeric").numberCheck();
	
});