function displayFormError(element, message){
	var height = parseInt( $(element).outerHeight() - 5 );
	
	var forID = element.attr('id');
	var error = $('<label></label>').addClass('error');
	if( forID ){
		error.attr('for', forID);
	}
	$('label.error[for=' + forID + ']').remove();
	error.text(message).css({bottom:height, opacity:0}).insertAfter(element).animate({opacity:1}, 200);
	element.focus(function(){
		error.remove();
	});
};

function handleJSON(data, form){
	if( data.redirect ){
		// reply is a redirect
		window.location.href = data.redirect;
	} else if( data.errors ){
		// reply contains errors
		//$(form).before('<div class="form_errors">' + data.errors + '</div>');
		//console.log(data);
		// trigger errors
		$('#' + data.errors[0].field).focus();
		for( var key in data.errors ){
			//console.log(data.errors[key].field + ": " + data.errors[key].msg);
			displayFormError( $('#' + data.errors[key].field), data.errors[key].msg );
		}		
	} else if( data.newBox ){
		// open a new fancyBox
		$.fancybox.close(function(){
			$.fancybox({
				href:data.newBox,
				overlayColor:'#fff', 
				ajax:{
					type:"GET"
				}, 
				autoScale:false,
				scrolling: 'no',
				enableKeyboardNav:false,
				enableMouseNav:false
			});
		});
	} else if( data.callBack ){
		var cb = eval(data.callBack);
		cb;
	}
};

function togglePostcode(t,postcode) {
	$('#postcode').val(postcode);
	$('.postcode_toggle').css('color','rgb(128, 128, 128)');
	t.css('color','#000');
	return false;
}

// form plugins
(function($){
	
	$.fn.TitlePlaceholder = function(){
		
		function _init(obj){
			obj.each(function(){
				var title = $(this).attr('title');
				
				var float = $(this).css("float");
				var display = $(this).css("display");
				var wrap = $('<span></span>');
				wrap.css({position:"relative", display:display, width:"auto", height:"auto", float:float});
				
				var floatLabel = $('<label></label>');
				floatLabel.attr('for', $(this).attr('id')).addClass('lblFloat').css({ 
															position:"absolute", 
															left:0, 
															top:0,
															cursor:"text",
															zIndex:1,
															display:"none"
														}).html(title);
				
				$(this).wrap(wrap);
				$(this).after(floatLabel);
				
				if( title != '' && $(this).val() == '' ){
					floatLabel.show();
				}

				$(this).focus(function(){
					floatLabel.hide();
				});
				$(this).blur(function(){
					if( $(this).val() == '' || $(this).val() == $(this).attr('title') ){
						floatLabel.show();
					}
				});
				$(this).change(function(){
					if( $(this).val() == '' || $(this).val() == $(this).attr('title') ){
						floatLabel.show();
					} else {
						floatLabel.hide();
					}
				});
			});
		}
		
		return _init(this);
	};
})(jQuery);

(function($){
	
	$.fn.TextCheckbox = function(settings){
		settings = jQuery.extend({
			myclass: 'txtchk', // class added to label and input
			classChecked: 'txtchk_sel' // class added to label for checked box
		},settings);
		
		function _init(obj){
			obj.each(function(){
				var input = $(this);
				var label = $(this).parent('label');
				var text = label.text();
				var name = input.attr('name');
				
				label.addClass(settings.myclass).css({position:"relative"});
				
				input.css({
						padding:0,
						margin:0,
						width:"100%",
						height:"100%",
						opacity:0,
						position: "absolute",
						left:0,
						top:0,
						cursor:"pointer"
					});
				
				if( input.is(':checked') ){
					label.addClass(settings.classChecked);
				}
				
				input.change(function(){
					if( input.is(':checked') ){
						if( input.is(':radio') ){
							var name = input.attr('name');
							$('[name=' + name + ']').closest('label').removeClass(settings.classChecked);
						}
						label.addClass(settings.classChecked);
					} else {
						label.removeClass(settings.classChecked);
					}
				})
				
			});
		};
		
		return _init(this);
	};
})(jQuery);

$(function() {	
	
	var default_postcode = 'Enter postcode';
	$('#location-search-form').submit(function() {
		var postcode = $('#postcode').val();
		if (!postcode || postcode == default_postcode || postcode.length > 8 || postcode.match(/[^A-Za-z0-9 ]/) ) {
			//alert("Please enter a postcode");
			displayFormError( $('#postcode'), "Please enter a valid postcode");
			return false;
		}		
	});
	$('#postcode').blur(function() {
		if ($(this).val() == '') {
			$(this).val(default_postcode);
		}
	});
	$('#postcode').focus(function() {
		if ($(this).val() == default_postcode) {
			$(this).val('');
		}
	});
	
	$('a.new-search').click(function() {
		$(this).fadeOut('fast');
		$('form#location-search-form').slideDown();
		return false;
	});
	
	$('a.pop').click(function() {
		var href = $(this).attr('href');
		window.open(href,'popup','width=500,height=500,scrollbars=yes');
		return false;
	});
	

	// $('ul.accordion').accordion({ 
	// 		autoheight: false,
	// 		header: ".opener",
	// 		active: '.selected',
	// 		selectedClass: 'active',
	// 		alwaysOpen: false,
	// 		event: "click"
	// 	});

	// helpful/not helpful buttons
	$('div.vote a.opinion').click(function() {

		var href = $(this).attr('href');
		var parameters = href.substr(1);
		var p = parameters.split('_');
		
		var inputs = new Object;
		inputs['review'] = p[0];
		inputs['helpful'] = p[1];
		
		target = $(this).parents('div.vote');
		
		$.ajax({
			data: inputs,
			url: "/ajax/helpful.php",
			type: "POST",
			timeout: 2000,
			error: function() {
				console.log("Failed to submit, or the response could not be read");
			},
			success: function(xml) { 
				var status = $("status",xml).text();	
				var message = $("message",xml).text();								
				var html = $("html",xml).text();		
				if (status != 0) {
					target.html('<strong>Thank you for your feedback</strong>');
				}		
				else {
					console.log("Zero status: " + message);
				}
			}
		});		
		return false;
	});

	// Allow search results to be nested:
	$('ul.results li').not('.has_children').click(function() {
		// Also needs to follow 'onclick="document.location=\'/locations/location.php?o='.$outlet['ID'].'\'; return false"'
		// Where /locations/location.php?o='.$outlet['ID'] is also the href attr of the child 'a' element
		var location = ($(this).children('a').attr('href'));
		document.location = location;
		return false;
	});
	
	$('ul.results li.has_children').click(function() {
		var li = $(this).nextUntil(':not(".nested")');
		if( $(this).hasClass('selected') ){
			$(this).removeClass('selected');
			li.hide();
		} else {
			$(this).addClass('selected');
			li.show();
		}
				// 
				// $(this).nextAll('li').each(function (i) {
				// 	var classname = this.className;
				// 	if (classname.match('nested') != null) {
				// 		this.style.display = 'block';	
				// 		// alert (classname.match('nested'));
				// 	}
				// 	else {
				// 		// alert("none");
				// 		return false;
				// 	}
				//     	});

		return false;
	});
	
	$('ul.results li a').click(function() {
		// Just cancel the original a tag; we leave it in place as it holds location, above
		// We should really trigger the parent li click event here, but we can tidy this up later
		return false;
	});

	// fancybox forms
	$('a.fancybox').fancybox({
		overlayColor:'#fff', 
		ajax:{
			type:"GET"
		}, 
		autoScale:false,
		scrolling: 'no',
		enableKeyboardNav:false,
		enableMouseNav:false
	});

	// let's try to get map links to go in lightbox...
	$('#map .fancybox').live("click", function(){
		var href = $(this).attr('href');
		$.fancybox({
			href: href,
			overlayColor:'#fff', 
			ajax:{
				type:"GET"
			}, 
			autoScale:false,
			scrolling: 'no',
			enableKeyboardNav:false,
			enableMouseNav:false
		});
		return false;
	});
	
	// new login form...
	$('.btn-login').click(function(){
		var url = $(this).attr('href');
		$.get(url, function(data){
			$('.log-block').append(data);
			$(document).mouseup(function(e){
				if( $(e.target).closest('#login_box').length == 0 ){
					$('#login_box').remove();
				};
			})
		});
		return false;
	});
	
	// open fancybox or other window on page load
	// links to trigger are ID'd with #link_{linkname} and triggered with a hash of #open-{linkname}
	// NOTE: make sure this code is last in the JS!!!
	var hash = window.location.hash;
	if( hash.match('#open-') ){
		var target = hash.replace('#open-', '');
		$('#link_' + target).trigger('click');
	}
});

