/**
 * A simple jQuery plugin to convert labels into placeholder text.
 */
(function($) {
	$.fn.labelToPlaceholder = function(settings) {

		if ( this.length == 0 ) return this;

		settings = $.extend({
			overflow : 'hidden',
			opacity : 0.6
		}, settings);

		var $set = this.add('input,textarea',this);

		$set.each(function(){

			var $this = $(this);
			var $label = $('label[for="' + $this.attr('id') + '"]');

			if ( $label.length == 0 ) return;

			$label.css({
				position: 'absolute',
				overflow: settings.overflow,
				margin: 0,
				padding: 0,
				display: 'block',
				width: $this.width(),
				height: $this.height(),
				lineHeight: $this.height() + 'px',
				fontSize: $this.css('fontSize'),
				opacity: settings.opacity,
				'float': 'none'
			}).addClass('placeholder');

			var input_position = $this.position();
			var inner_offset = $this.innerOffset();
			
			$label.css({
				top: input_position.top + inner_offset.top,
				left: input_position.left + inner_offset.left
			});
			if ($this.val() != '') $label.hide();

			$this.focus(function(){
				$label.hide();
			});

			$this.blur(function(){
				if ($($this).val() == '') $label.show();
			});
		});
		return this;
	};
})(jQuery);

/**
 *  A jQuery plugin that returns the 'innerOffset' of an element. That is,
 *  the difference between the outside and the inside of a container for
 *  each of the sides (i.e. the sum of the border width and padding).
 */
(function($) {
	$.fn.innerOffset = function(){
		if (this.length == 0) return null;
		var $first = $(this.get(0));
		
		// TODO: Deal with IE returning text values like 'medium' for border width.
		
		return {
			top : parseFloat($first.css('paddingTop').replace(/px/, '')) + parseFloat($first.css('borderTopWidth').replace(/px/, '')),
			right : parseFloat($first.css('paddingRight').replace(/px/, '')) + parseFloat($first.css('borderRightWidth').replace(/px/, '')),
			bottom : parseFloat($first.css('paddingBottom').replace(/px/, '')) + parseFloat($first.css('borderBottomWidth').replace(/px/, '')),
			left : parseFloat($first.css('paddingLeft').replace(/px/, '')) + parseFloat($first.css('borderLeftWidth').replace(/px/, ''))
		}
	}
})(jQuery);

// Fire up the JS
var base = function($){

	$(function(){
		
		$('#utils').labelToPlaceholder();
		

		$('input[type=file]').each(function(){
				var $input = $(this);
				var $related = $('<input id="browseFileName" name="browseFileName" type="text" readonly class="text"/>');
				var $container = $('<span class="file"><img src="/themes/default/images/button-browse.gif" alt="browse"/></span>');

				$input.change(function() {
						var filestring = $(this).val();
						if (filestring.indexOf('\\') > 0) {
								// Trim it down if we have a path.
								filestring = filestring.substr(filestring.lastIndexOf('\\') + 1);
						}

						$related.val(filestring);
				});

				$container.prepend($related).insertAfter($input);
				$input.css({'opacity':0, cursor: 'pointer'});
		});
		
		$('#banners').cycle({slideExpr: '.banner', pager: $('<div id="banners-pager" class="pager">').appendTo('#banners'), pause: true});
		
		$('#page-images-home').cycle({
			pager: $('<div id="images-pager" class="pager">').insertAfter('#page-images-home'), 
			pause: true, 
			cleartype: true, 
			cleartypeNoBg: true
		});
		
		$('#page-images').cycle();
		
		$('#soilmate-login').addClass('popup').appendTo('body').hide();
		$('a.soilmate-login').click(function(){
			//add modal background
            $('<div>').addClass('dropsheet').appendTo('body').click(hide_login).fadeIn('fast');
            //add modal window
            $('#soilmate-login').fadeIn();
		});
		$(document).keypress(function(e){
			if (e.keyCode == 27) {
				hide_login();
			}
		});
		
		var hide_login = function() {
			$('#soilmate-login').hide();
			$('.dropsheet').fadeOut().remove(); 
		}
		
		// Equal height boxes for the home page.
		var maxHeight = 0;
		var list = $(".home-panel").each(function() {
			if($(this).height() > maxHeight)
			{
				maxHeight = $(this).height();
			}
		});
		list.height(maxHeight);
		
		// Basic validation for SoilMate login
		$('#soilmate-login').submit(function(){

			var valid = true,
				$username = $('#soilmate-username'),
				$password = $('#soilmate-password');

			if ( $username.val().length < 1 ) {
				valid = false;
				$username.parent('div').addClass('error');
			}
			if ( $password.val().length < 1 ) {
				valid = false;
				$password.parent('div').addClass('error');
			}
			
			if (!valid) {
				$(this).append('<p style="position: absolute; right: 20px; color: rgb(255, 0, 0); width: 190px; font-size: 80%; line-height: 1em; top: 150px;"  class="error-message">Please enter your SoilMate username and password.</p>');
			}
			
			return valid;
		});
		
	});
	
		

	// Some public functions that are used site wide.
	return {
		invalidHandler : function(e, validator) {
			var errors = validator.numberOfInvalids();
			if (errors) {

				if ( !$('form p.error').length ) {
					$('<p class="message error">').hide().prependTo(validator.currentForm);
				}

				var message = errors == 1
						? "You missed 1 field. It has been highlighted below"
						: "You missed " + errors + " fields.  They have been highlighted below.";
				$("form p.error").html(message).slideDown();
			} else {
				$("form p.error").slideUp('fast', function() {$(this).remove();});
			}
		}
	}

}(jQuery);
