jQuery.timer = function(time,func,callback){
	var a = {timer:setTimeout(func,time),callback:null}
	if(typeof(callback) == 'function'){a.callback = callback;}
	return a;
};

jQuery.clearTimer = function(a){
	clearTimeout(a.timer);
	if(typeof(a.callback) == 'function'){a.callback();};
	return this;
};

function optionsCompile(){
	
	var QRY = '';
	$("#message-form input, #message-form textarea, #message-form select").each(function(){
	QRY += $(this).attr('name') + '=' + $(this).val() + '&';
	});
	
	$.ajax({
	  type: "GET",
	  data: QRY,
	  url: 'http://'+document.location.host+'/classifieds/events/optionConstruct.php',
	  success: function(data) {
		$('.result').html(data);
	  }
	});
}

function compileHorseClasses(){
var tb_sbFields = "<option value='1'>Weanling - Yearling</option><option value='15'>2 and 3 year olds</option><option value='2'>Brood Mare</option><option value='3'>Racehorse</option><option value='4'>Horse Training</option><option value='5'>Trialed</option><option value='16'>Untried</option><option value='6'>Stallion</option><option value='7'>Stallion Nomination</option><option value='8'>Syndication / Shares</option>";	
var eqFields = "<option value='9'>Horses</option><option value='13'>Western</option><option value='14'>Sporthorse</option><option value='10'>Ponies</option><option value='11'>Young Stock</option><option value='12'>Minatures</option>";
var classification = $(".horseClass option:selected").val();
if (classification == 2) $(".horseClassification").html(eqFields);
else $(".horseClassification").html(tb_sbFields);// sporthorse, reset to default fields
if (classification == 3) $("tr.sbReveal").show();
else $("tr.sbReveal").hide(); // reveal alt class2 
}

function homeToggle(){
var value = $("#sel1.housetype option:selected").val();
if (value != 1) $("tr.landhide").hide(); else $("tr.landhide").show();
}


function newsComment(){
	
	var QRY2 = '';
	$("#comment-form input").each(function(){
	QRY += $(this).attr('name') + '=' + $(this).val() + '&';
	});
	
	$.ajax({
	  type: "GET",
	  data: QRY,
	  url: 'http://'+document.location.host+'/includes/events/newscomment.php',
	  success: function(data) {
		$('#form-success').html(data);
	  }
	});
}

function watchlistAdd($itemID){
	itemID = 'itemID=' + $itemID;
	var resultF = 'li.watchlistresult#' + $itemID;
	$.ajax({
	  data: itemID,
	  url: 'http://'+document.location.host+'/classifieds/events/addToWatchlist.php',
	  success: function(data) {
		$(resultF).html('<img src="http://'+document.location.host+'/images/loading.gif" height="20">');
		myTimer = $.timer(1000,function(){
			$(resultF).html(data); // hide the loading gif after 2 seconds
		});
	  }
	});
}

function likeListing($itemID2){

	itemID2 = 'itemID=' + $itemID2;
	var resultF = 'li.likeresult' + $itemID2 ;
	$.ajax({
	  data: itemID2,
	  url: 'http://'+document.location.host+'/classifieds/events/likeListing.php',
	  success: function(data) {
		$(resultF).html('<img src="http://'+document.location.host+'/images/loading.gif" height="20">');
		myTimer = $.timer(1000,function(){
			$(resultF).html(data); // hide the loading gif after 2 seconds
		});
	  }
	});
}

// JavaScript Document
$().ready(function() {
	$(".sbReveal").hide();
	$('#salePreviewTable tr:even').addClass('even');
	
	if ($('input.vendorReveal2:checked').val() !== null){
		$('tr.vendorHide').toggleClass("vendorShow");
	}

	$('input.vendorReveal2').click(function(){
		$('tr.vendorShow').toggleClass("x");
		$('tr#vendorField input').toggleClass("required");
	});

	$("#sideBar.horse li:even").attr("style", "background: #333;");

	$('#imageThumbs a').each(function(){
		$(this).click(function(){
			$("#footageDiv").hide();
			$("a#imageReveal").addClass("current");
			$("a#footageReveal").removeClass("current");
			$("#imagesDiv").fadeTo(200,1.0);
			/*
			$(this).fadeTo(400,0.6);
			$(this).fadeTo(300,1.0);
			var imageHref = $(this).attr('rel');
			$('#mainImage img').attr('src', imageHref);*/
			});
	})
		
	
	$("#footageDiv").hide();
	//$("#imageThumbs").hide();
	
	$("a#imageReveal").click(function(){
		$("#imagesDiv").fadeTo(200,1.0);
		$("#imageThumbs").show();
		$("li.footage").removeClass("current");
		$("li.image").addClass("current");
		$("#footageDiv").hide();
	});
	
	$("a#footageReveal").click(function(){
		$("#imagesDiv").hide();
		$("li.image").removeClass("current");
		$("li.footage").addClass("current");
		$("#footageDiv").fadeTo(200,1.0);
	});
	
	
	$("a#addReplyBtn").each(function(){
			$(this).click(function(){
				$("#addReplyWrap").slideDown();
				var yLoc = $("#addReplyWrap");
				$.scrollTo(yLoc,1000)
				$.scrollTo("+=300",1000);
				});
			});	
	
});

/*ajax form*/
$().ready(function() {

	//ajax form submit

	$("div#form-error").hide();
	$("div#form-message").hide();
	$("div#form-success").hide();
	
	var x = $("#jqresetINI").val();
	// dont reset after submit
	if (x = "NR") {
		var options = { 
			target:        '#form-success',   // target element(s) to be updated with server response 
			beforeSubmit:  showRequest,  // pre-submit callback 
			success:       showResponse,  // post-submit callback 
			resetForm: false
			// other available options: 
			//url:       url         // override for form's 'action' attribute 
			//type:      type        // 'get' or 'post', override for form's 'method' attribute 
			//dataType:  null        // 'xml', 'script', or 'json' (expected server response type) 
			//clearForm: true        // clear all form fields after successful submit 
			//resetForm: true        // reset the form after successful submit 
	 
			// $.ajax options can be used here too, for example: 
			//timeout:   3000 
		}; 
	};
	// reset after submit
	if (!x) {
		var options = { 
			target:        '#form-success',   // target element(s) to be updated with server response 
			beforeSubmit:  showRequest,  // pre-submit callback 
			success:       showResponse,  // post-submit callback 
			resetForm: true
		}; 
	};


	// pre-submit callback 
	function showRequest(formData, jqForm, options) { 
	    // formData is an array; here we use $.param to convert it to a string to display it 
	    // but the form plugin does this for you automatically when it submits the data 
	    var queryString = $.param(formData); 

	    // jqForm is a jQuery object encapsulating the form element.  To access the 
	    // DOM element for the form do this: 
	    // var formElement = jqForm[0]; 
		
		$("div#form-error").hide();
		$("div#form-loading").show().html('<img src="http://'+document.location.host+'/images/loading.gif" height="23">');
		myTimer = $.timer(2000,function(){
			$("div#form-loading").fadeOut("fast"); // hide the loading gif after 2 seconds
		});

	    // here we could return false to prevent the form from being submitted; 
	    // returning anything other than false will allow the form submit to continue 
	    return true; 
	} 

	// post-submit callback 
	function showResponse(responseText, statusText)  { 
	    // for normal html responses, the first argument to the success callback 
	    // is the XMLHttpRequest object's responseText property 

	    // if the ajaxSubmit method was passed an Options Object with the dataType 
	    // property set to 'xml' then the first argument to the success callback 
	    // is the XMLHttpRequest object's responseXML property 

	    // if the ajaxSubmit method was passed an Options Object with the dataType 
	    // property set to 'json' then the first argument to the success callback 
	    // is the json data object returned by the server 

	    /*alert('status: ' + statusText + '\n\nresponseText: \n' + responseText + 
	        '\n\nThe output div should have already been updated with the responseText.'); 
		*/
		myTimer = $.timer(2000,function(){
			$("div#form-success").fadeOut("fast").fadeIn("fast").fadeTo(3000, 1.0); // reveal the success after 2 seconds (e.g. when the loading gif has gone)
		});
		
	}

	
	// validate the comment form when it is submitted
	$("#message-form #topicTitle").blur(function(){
		if($(this).attr("value") == ""){
			$(this).attr("value","Title");
		}
	});
	
	$("#message-form #topicTitle").focus(function(){
		if($(this).attr("value") == "Title"){
			$(this).attr("value","");
		}
	});
	
	var password = $("#message-form #password").val();
	if (password == "") $("#message-form #password").attr("value", "Password");
	
	$("#message-form #password").focus(function(){
		if($(this).attr("value") == "Password"){
			$(this).attr("value","");
		}
	});
	
	$("#message-form #password").blur(function(){
		if($(this).attr("value") == ""){
			$(this).attr("value","Password");
		}
	});

	//default states for form fields
	$("#message-form #name").blur(function(){
		if($(this).attr("value") == ""){
			$(this).attr("value","Name");
		}
	});
	
	$("#message-form #name").focus(function(){
		if($(this).attr("value") == "Name"){
			$(this).attr("value","");
		}
	});
	
	$("#message-form #phone").blur(function(){
		if($(this).attr("value") == ""){
			$(this).attr("value","Phone");
		}
	});
	
	$("#message-form #phone").focus(function(){
		if($(this).attr("value") == "Phone"){
			$(this).attr("value","");
		}
	});	
	$("#message-form #email").blur(function(){
		if($(this).attr("value") == ""){
			$(this).attr("value","Email");
		}
	});
	
	$("#message-form #email").focus(function(){
		if($(this).attr("value") == "Email"){
			$(this).attr("value","");
		}
	});
	
	$("#message-form #message").blur(function(){
		if($(this).attr("value") == ""){
			$(this).attr("value","Message");
		}
	});
	
	$("#message-form #message").focus(function(){
		if($(this).attr("value") == "Message"){
			$(this).attr("value","");
		}
	});

	jQuery.validator.addMethod("nameRequired", function(value, element) {
		return value != "";
	}, "");

	jQuery.validator.addMethod("messageRequired", function(value, element) {
		return value != element.defaultValue;
	}, "");
	
	// var RTEval = $("#msgpost.RTE").val(); // update fields, for RTE checking the new value is different from default value
	
	jQuery.validator.messages.required = ""; 
	//$("#message-form").validate();
	$("form#message-form").each(function(){
		$(this).validate({
			rules: {
				message: "messageRequired",
				email: {
					required: true,
					email: true
				}
			},
			invalidHandler: function(e, validator) {
				var errors = validator.numberOfInvalids();
				if (errors) {
					var message = errors == 1
					? 'You missed 1 field. It has been highlighted above'
					: 'You missed ' + errors + ' fields. They have been highlighted above';
					$("div#form-error").html('<p>'+message+'</p>');
					$("div#form-message").hide();
					$("div#form-error").fadeIn("fast");
				}
			},
			onkeyup: false,
			submitHandler: function(form) {
				$("div#form-error").fadeOut("fast");
				$(form).ajaxSubmit(options); 
				
				
				//alert("submit! use link below to go to the other step");
			},
			messages: {
				name: "",
				password: "",
				message: "",
				email: ""
				},
					debug: true
				});
			});	
		});
/*ajax form*/

;(function(d){var k=d.scrollTo=function(a,i,e){d(window).scrollTo(a,i,e)};k.defaults={axis:'xy',duration:parseFloat(d.fn.jquery)>=1.3?0:1};k.window=function(a){return d(window)._scrollable()};d.fn._scrollable=function(){return this.map(function(){var a=this,i=!a.nodeName||d.inArray(a.nodeName.toLowerCase(),['iframe','#document','html','body'])!=-1;if(!i)return a;var e=(a.contentWindow||a).document||a.ownerDocument||a;return d.browser.safari||e.compatMode=='BackCompat'?e.body:e.documentElement})};d.fn.scrollTo=function(n,j,b){if(typeof j=='object'){b=j;j=0}if(typeof b=='function')b={onAfter:b};if(n=='max')n=9e9;b=d.extend({},k.defaults,b);j=j||b.speed||b.duration;b.queue=b.queue&&b.axis.length>1;if(b.queue)j/=2;b.offset=p(b.offset);b.over=p(b.over);return this._scrollable().each(function(){var q=this,r=d(q),f=n,s,g={},u=r.is('html,body');switch(typeof f){case'number':case'string':if(/^([+-]=)?\d+(\.\d+)?(px|%)?$/.test(f)){f=p(f);break}f=d(f,this);case'object':if(f.is||f.style)s=(f=d(f)).offset()}d.each(b.axis.split(''),function(a,i){var e=i=='x'?'Left':'Top',h=e.toLowerCase(),c='scroll'+e,l=q[c],m=k.max(q,i);if(s){g[c]=s[h]+(u?0:l-r.offset()[h]);if(b.margin){g[c]-=parseInt(f.css('margin'+e))||0;g[c]-=parseInt(f.css('border'+e+'Width'))||0}g[c]+=b.offset[h]||0;if(b.over[h])g[c]+=f[i=='x'?'width':'height']()*b.over[h]}else{var o=f[h];g[c]=o.slice&&o.slice(-1)=='%'?parseFloat(o)/100*m:o}if(/^\d+$/.test(g[c]))g[c]=g[c]<=0?0:Math.min(g[c],m);if(!a&&b.queue){if(l!=g[c])t(b.onAfterFirst);delete g[c]}});t(b.onAfter);function t(a){r.animate(g,j,b.easing,a&&function(){a.call(this,n,b)})}}).end()};k.max=function(a,i){var e=i=='x'?'Width':'Height',h='scroll'+e;if(!d(a).is('html,body'))return a[h]-d(a)[e.toLowerCase()]();var c='client'+e,l=a.ownerDocument.documentElement,m=a.ownerDocument.body;return Math.max(l[h],m[h])-Math.min(l[c],m[c])};function p(a){return typeof a=='object'?a:{top:a,left:a}}})(jQuery);

// face book submit
function fbs_click(){u=location.href;t=document.title;window.open('http://www.facebook.com/sharer.php?u='+encodeURIComponent(u)+'&t='+encodeURIComponent(t),'sharer','toolbar=0,status=0,width=626,height=436');return false;}
	/*buttons*/
$().ready(function() {	
	$("#addTopicBtn").hover(function(){
			$(this).attr('src', 'http://'+document.location.host+'/forum/images/buttons/newtopicH.jpg');
			});
	$("#addTopicBtn").mouseout(function(){
			$(this).attr('src', 'http://'+document.location.host+'/forum/images/buttons/newtopic.jpg');
			});
	
	$("#addReplyBtn").hover(function(){
			$(this).attr('src', 'http://'+document.location.host+'/forum/images/buttons/addReplyH.jpg');
			});
	$("#addReplyBtn").mouseout(function(){
			$(this).attr('src', 'http://'+document.location.host+'/forum/images/buttons/addReply.jpg');
			});	
	
	$("#addTopicBtn").click(function(){
			$("#addThreadWrap").slideDown();
			});	
	
	$("img#fb").hover(function(){
			$(this).attr('src', 'http://'+document.location.host+'/images/icons/addFBH.jpg');
			});

	$("img#fb").mouseout(function(){
			$(this).attr('src', 'http://'+document.location.host+'/images/icons/addFB.jpg');
			});

	$("img#twitter").hover(function(){
			$(this).attr('src', 'http://'+document.location.host+'/images/icons/addTH.gif');
			});

	$("img#twitter").mouseout(function(){
			$(this).attr('src', 'http://'+document.location.host+'/images/icons/addT.gif');
			});

});
// jQuery Captify Plugin
// Copyright (C) 2009 Brian Reavis
// Licenced under the MIT license
// $Date: 2009-11-30 [Mon, 30 Nov 2009] $
jQuery.fn.extend({
	captify: function(uo) {
		var o = $.extend({
			speedOver: 'fast',				// speed of the mouseover effect
			speedOut: 'normal',				// speed of the mouseout effect
			hideDelay: 500,					// how long to delay the hiding of the caption after mouseout (ms)
			animation: 'slide',				// 'fade', 'slide', 'always-on'
			prefix: '',						// text/html to be placed at the beginning of every caption
			opacity: '0.45',				// opacity of the caption on mouse over
			className: 'caption-bottom',	// the name of the CSS class to apply to the caption box         
			position: 'bottom',				// position of the caption (top or bottom)         
			spanWidth: '100%'				// caption span % of the image
		}, uo);
		$(this).each(function() {
			var img = this;
			$(this).load(function() {
				if (img.hasInit){ return false; }
				img.hasInit = true;
				var over_caption = false;
				var over_img = false;

				//pull the label from another element if there is a 
				//valid element id inside the rel="..." attribute, otherwise,
				//just use the text in the alt="..." attribute.
				var captionLabelSrc = $('#' + $(this).attr('rel'));
				var captionLabelHTML = !captionLabelSrc.length ? $(this).attr('alt') : captionLabelSrc.html();
				captionLabelSrc.remove();
				var toWrap = this.parent && this.parent.tagName == 'a' ? this.parent : $(this);
				
				var wrapper = 
					toWrap.wrap('<div></div>').parent()
					.css({
						overflow: 'hidden',
						padding: 0,
						fontSize: 0.1
					})
					.addClass('caption-wrapper')
					.width($(this).width())
					.height($(this).height());

				//transfer the margin and border properties from the image to the wrapper
				$.map(['top', 'right', 'bottom', 'left'], function(i) {
					wrapper.css('margin-' + i, $(img).css('margin-' + i));
					$.map(['style', 'width', 'color'], function(j) {
						var key = 'border-' + i + '-' + j;
						wrapper.css(key, $(img).css(key));
					});
				});
				$(img).css({ border: '0 none' });

				//create two consecutive divs, one for the semi-transparent background,
				//and other other for the fully-opaque label
				var caption = $('div:last', wrapper.append('<div></div>'))
					.addClass(o.className);
					
				var captionContent = $('div:last', wrapper.append('<div></div>'))
					.addClass(o.className)
					.append(o.prefix)
					.append(captionLabelHTML);

				//override hiding from CSS, and reset all margins (which could have been inherited)
				$('*', wrapper).css({ margin: 0 }).show();

				//ensure the background is on bottom
				var captionPositioning = jQuery.browser.msie ? 'static' : 'relative';
				caption.css({
					zIndex: 1,
					position: captionPositioning,
					opacity: o.animation == 'fade' ? 0 : o.opacity,
					width: o.spanWidth
				});

				if (o.position == 'bottom'){
					var vLabelOffset = 
						parseInt(caption.css('border-top-width').replace('px', '')) + 
						parseInt(captionContent.css('padding-top').replace('px', '')) - 1;
					captionContent.css('paddingTop', vLabelOffset);
				}
				//clear the backgrounds/borders from the label, and make it fully-opaque
				captionContent.css({
					position: captionPositioning,
					zIndex: 2,
					background: 'none',
					border: '0 none',
					opacity: o.animation == 'fade' ? 0 : 1,
					width: o.spanWidth
				});
				caption.width(captionContent.outerWidth());
				caption.height(captionContent.height());

				// represents caption margin positioning for hide and show states
				var topBorderAdj = o.position == 'bottom' && jQuery.browser.msie ? -4 : 0;
				var captionPosition = o.position == 'top'
				   ? { hide: -$(img).height() - caption.outerHeight() - 1, show: -$(img).height() }
				   : { hide: 0, show: -caption.outerHeight() + topBorderAdj };
				
				//pull the label up on top of the background
				captionContent.css('marginTop', -caption.outerHeight());
				caption.css('marginTop', captionPosition[o.animation == 'fade' || o.animation == 'always-on' ? 'show' : 'hide']);
				
				//function to push the caption out of view
				var cHide = function() {
					if (!over_caption && !over_img){
						var props = o.animation == 'fade'
							? { opacity: 0 }
							: { marginTop: captionPosition.hide };
						caption.animate(props, o.speedOut);
						if (o.animation == 'fade'){
							captionContent.animate({opacity: 0}, o.speedOver);
						}
					}
				};

				if (o.animation != 'always-on'){
					//when the mouse is over the image
					$(this).hover(
						function() {
							over_img = true;
							if (!over_caption) {
								var props = o.animation == 'fade'
									? { opacity: o.opacity }
									: { marginTop: captionPosition.show };
								caption.animate(props, o.speedOver);
								if (o.animation == 'fade'){
									captionContent.animate({opacity: 1}, o.speedOver/2);
								}
							}
						},
						function() {
							over_img = false;
							window.setTimeout(cHide, o.hideDelay);
						}
					);
					//when the mouse is over the caption on top of the image (the caption is a sibling of the image)
					$('div', wrapper).hover(
						function() { over_caption = true; },
						function() { over_caption = false; window.setTimeout(cHide, o.hideDelay); }
					);
				}
			});
			//if the image has already loaded (due to being cached), force the load function to be called
			if (this.complete || this.naturalWidth > 0) {
				$(img).trigger('load');
			}
		});
	}
});
