(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");
								}							
							}
						}
					}	
				}
			});
			
			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'){
								if(html.indexOf("|") > -1) {
									// Split the returned result
									var res = html.split("|");	
									callBack.call(this, res[1]);						
								} else {
									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(boolValid) {
					// Process normally
					var submitButton = $(this).find("input[type='submit']");
					$(submitButton).attr("value", "Please Wait...");
					$(submitButton).attr("disabled", "true");
				}
				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.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.SU = function (options) {
	
		// Default settings
		var defaults = { target: "" };
		var options = $.extend(defaults, options);
		
		$(this).click(function() {
			$(options.target).slideUp();
		});
		
		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;
			});
		});
	}
	
	$.fn.idle = function(time) {
		var o = $(this);
		o.queue(function() {
			 setTimeout(function() {
				o.dequeue();
			 }, time);
		});
		return this;
    }
	
})(jQuery);
	
	function formResponse(args) {
		$("#responsediv").fadeOut('slow', function() {
			$(this).text(args).fadeIn('slow');
		});
	}


$(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();
	$(".caption").caption({animate: false, width: 160});
	$(".changeselect").changeselect();
	$(".testvalidate").formValidator({useAjax: true, showAlert: true}, formResponse);
	$("input:checkbox").toggleCheckbox();
	$(".popup").popup({ width: 320, height: 480, titlebar: false, status: false, resizable: true, toolbar: false, scrollbars: true, menubar: false });
	
	$(".submitbutton").click(function() {
		$(this).closest("form").submit();
		return false;
	});
	
	$("#tabs").tabs();
	
	$(".menu-item-700").append("<span class='new'></span>");

});
