/**
 * jQuery for the Healthy Interactions website.
 * 
 * @author		Healthy Interactions team
 * @copyright	2009 (c) Healthy Interactions, Inc.
 */
// Stuff that needs to wait for the document ready call
$(document).ready( function(){
	// Notify
	$('#notify').hide();

	// Hide the dropdown menus
	$('#navigation #dropdown div').hide();

	// Set the blank image src
	HI.blank.src = '/images/blank.gif';

	// PNG fix for IE 5/6
	var badBrowser = (/MSIE ((5\.5)|6)/.test(navigator.userAgent) && navigator.platform == "Win32");
	if (badBrowser) {
	// get all pngs on page
		$('img[src$=.png]').each(function() {
			// Checks for loading completion
			if (!this.complete) {
				this.onload = function() {HI.fixPng(this)};
			} else {
				HI.fixPng(this);
			}
		});
	}

	// Prefills input boxes
	$( '#LoginEmail' ).prefill();
	$( '#LoginPassword' ).prefill();
	$( '#LoginEmailP' ).prefill();
	$( '#LoginPasswordP' ).prefill();
	$( '#SearchInput' ).prefill();

	// Show the right login section
	if( $('#LoginParticipant').hasClass('active') ){
		$( '#LoginFacilitation' ).hide();
		$( '#login' ).addClass('participant');
	} else {
		$( '#LoginParticipant' ).hide();
	}

	// Open up active disclosure arrows
	var active = $('.disclosure').parent('li').children('a.active');
	$(active).each( function(){
		$(this).siblings('.arrow').addClass('open');
		$(this).siblings('.info').show();
	});

});

// Main actions
$( function(){
	// Login form submission
	$('#login form').submit( function(e){
		// Cancel the submission
		e.preventDefault();

		// Check for errors
		var errors = [];
		if(this.Email.value == ''){
			errors.push('Email Address');
		}
		if(this.Password.value == ''){
			errors.push('Password');
		}

		if(errors.length == 0){
			// No errors, try and submit
			var data = {
				Email: this.Email.value,
				Password: this.Password.value
			};

			// Turn off the submit
			$('#login :submit').attr('disabled', true);
			// Post the form
			$.post(this.action, data, function(response){
			// The response
				response = jsonParse(response);

				if( response.success ){
				// All good
					window.location = response.redirect;
				}	else {
				// Login error
					$('#login :submit').attr('disabled', false);
					$('#notify').notify( response.message, { css:'error' });
					//$('#login .message').addClass('error').html( response.message );
				}

			});

		} else {
		// Errors
			$('#notify').notify( 'Please enter your ' + errors.join(' and ') + '.', { css:'error' });
			//$('#login .message').addClass('error').html( 'Please enter your: ' + errors.join(', ') + '.' );
		}
	});

	/**
	 * Dropdown menu.
	 */
	// Attach hover + show on the links
	$('#nav li').each( function( i ){
		$(this).hover( 
		// Roll over
			function(){
				$(this).addClass('hover');

				if( ! $(this).hasClass('active') ){
					HI.showDropdown( this, i );
				} else {
					HI.hideDropdown();
				}

			},
		// Roll out
			function(){ $(this).removeClass('hover'); }
		);

	});

	// Close dropdown on click
	$(document).click( function(){
		$('#navigation #dropdown div:visible').hide();
	} );

	// The login box
	$('#login ul a').click( function(e){
		// Stop the link
		e.preventDefault();
		$( '#login' ).removeClass();
		$( '#login .message' ).removeClass('error').html('');

		if( this.name == 'Facilitation' ) {
		// Facilitator
			$( '#LoginFacilitation' ).show();
			$( '#LoginParticipant' ).hide();
		} else {
		// Participant
			$( '#LoginFacilitation' ).hide();
			$( '#LoginParticipant' ).show();
			$('#login').addClass('participant');
		}

	});

	// Talk to us and Tell a friend
	$('a[rel^="modal"]').click( function(e){
		e.preventDefault(); // Cancel click

		var args = $(this).attr('rel').split('_');

		// Get the page
		$.get('/ajax' + $(this).attr('href'), {}, function(content){
			if( content ) {
				// Resize
				if( args.length > 1 )
				{
					$('#simplemodal-container').css('width', args[1] + 'px');
					$('#simplemodal-container').css('height', args[2] + 'px');
				}

				$.modal( content );
			}
		});
	});

	// Disclosure Arrows
	$('.disclosure').click( function(){
		if( $(this).hasClass('open') ){
			// Shut em down
			$(this).removeClass( 'open' );
			$(this).siblings('.info').hide();
		} else {
			// Open it up
			$(this).addClass( 'open' );
			$(this).siblings('.info').show();
		}
	});

	// Popup windows
	$('a[rel^=popup]').click( function(e){
		// Cancel link
		e.preventDefault();

		var args = this.rel.split('_');

		window.open( $(this).attr('href') , 'popup', 'width='+args[1]+',height='+args[2]);
	});

	// Stripe all tables
	$('.stripe').stripe();

});

/**
 * Prefills a form element
 * 
 * @author	Dave Widmer
 */
( function($){
	/**
	 * Prefills the selected form element with text
	 * 
	 * @param 	css			CSS classs to apply
	 * @return	this
	 */
	$.fn.prefill = function(css){
		// Set default values
		css = css || 'prefill';

		return this.each( function(){
			// Find the label
			var label = $('label[for=' + this.id + ']');

			// Apply the style to the label
			$(label).addClass( css );

			// Check for a value
			if( this.value != '' ){
				$( label ).hide();
			}

			// Add focus to input
			$( this ).focus( function(){
				$( label ).hide();
			});

			// Add blur
			$( this ).blur( function(){
				if( this.value == '' ){
					$( label ).show();
				}
			});

		});

	};

})(jQuery);

/**
 * Validation used with the form builder
 */
( function($){
	/**
	 * Validation function
	 *
	 * @param	url		ajax url for validation checks
	 * @param	file	file to validate
	 */
	$.fn.validate = function( url, file ){
		// Process the fields
		return this.each( function(){
			// Split the rules
			this.rules = $(this).attr('rel');
			this.span = $(this).parent('div').children('span[class=message]');

			// Add Blur
			$(this).blur( function(){

				// Checking the rules
				var data = {
					rules: this.rules,
					value: this.value,
					file: file,
					name: this.name
				};

				// Needed for ajax call
				var input = this;

				$.post( url, data, function( response ){
					// Response
					response = jsonParse(response);

					// Check the stuff
					if( response.success ){
						$(input.span).removeClass('error').html( ' ' ).addClass('success');
					} else {
						$(input.span).removeClass('success').html( response.message ).addClass('error');
					}
					
				});

			});
		});

	};

})(jQuery);

/**
 * Delay Plugin for jQuery
 * 
 * @author	Evan Byrne
 * @link		http://www.evanbot.com
 * @copyright	2008 (c) Evan Byrne
 */
( function($){
	/**
	 * Delay function.
	 * 
	 * @param	time		Time to wait
	 * @param	callback	Callback function
	 * @return this
	 */
	$.fn.delay = function(time, callback){
		return $(this).each( function(){
			setTimeout(callback, time);
		});
	};

})(jQuery);

/**
 * Zebra Striping Plugin
 *
 * @author 		Dave Widmer
 * @version		v1.3		2008-12-03
 * @url			http://www.davewidmer.net
 *
 * @usage		Add .stripe() to your jQuery chain
 */
(function($){
	/**
	* The zebra striping function
	*
	* @param options	Options for the zebra striping
	*/
	$.fn.stripe = function(options){
		// First element is an empty object so it won't override the defaults object
		options = $.extend( {}, $.fn.stripe.defaults, options );
		// Add in some properties
		options.stripes = options.classes.length;
		options.css = options.classes.join( ' ' );

		return this.each(function(){
			$(options.selector,this).each(function(i){
				$(this).removeClass( options.css );
				$(this).addClass( options.classes[ i % options.stripes ] );
			});
		});
	};

	$.fn.stripe.defaults = {
		selector: 'tr:visible',
		classes: ['odd','even']
	};

})(jQuery);

/**
 * Notification system for jQuery
 *
 * @author	Dave Widmer
 */
( function($){
	/**
	 * Notification system.
	 *
	 * @param	message		Message to set
	 * @param	options		Extra options
	 */
	$.fn.notify = function(message, options){
		// First element is an empty object so it won't override the defaults object
		options = $.extend( {}, $.fn.notify.defaults, options );
		options.id = this;
		options.message = message;
		$.fn.notify.options = options;

		// Show the notification
		$(this).html(message).addClass(options.css).slideDown('normal');

		// Set the timer
		window.setTimeout( $.fn.notify.close, options.time );

		// Return for chaining
		return this;
	};

	/**
	 * Defaults.
	 */
	$.fn.notify.defaults = {
		time: 3000,
		css: 'message'
	};
	
	// Options
	$.fn.notify.options = {};

	/**
	 * Close function
	 */
	$.fn.notify.close = function() {
		var opts = $.fn.notify.options;
		$(opts.id).slideUp('normal', function(){
			$(this).removeClass( opts.css );
		});
	};

})(jQuery);


/**
 * HI object
 */
var HI = {
	// Blank gif
	blank: new Image(),

	/**
	 * IE PNG fix
	 *
	 * @see	http://docs.jquery.com/Tutorials:PNG_Opacity_Fix_for_IE6
	 */
	fixPng: function( png ) {
		// get src
		var src = png.src;
		// set width and height
		if (!png.style.width) {png.style.width = $(png).width();}
		if (!png.style.height) {png.style.height = $(png).height();}
		// replace by blank image
		png.onload = function() { };
		png.src = HI.blank.src;
		// set filter (display original image)
		png.runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "',sizingMethod='scale')";
	},

	// Active Dropdown
	activeDropdown: -1,

	/**
	 * Shows the drop down.
	 *
	 * @param	link	Navigation link
	 * @param	i		Index number
	 */
	showDropdown: function( link, i ){
		if( HI.activeDropdown != i ) {
			// Get the dropdown
			HI.activeDropdown = i;
			var dropdown = $('#navigation #dropdown div:eq('+ i +')');
			var nav = $(link).parent('li');

			// Hide any open dropdown
			$('#navigation #dropdown div:visible').hide();

			// Now open the dropdown (if doesn't have class hide)
			if( ! $(dropdown).hasClass('hide') ){
				$(dropdown).show();
				$(dropdown).hover(
					// Nothing on hover
					function(){},

					function(){
						$(link).parent('li').removeClass('hover');
						$(dropdown).hide();
						HI.activeDropdown = -1;
					}
				);
			}

		}
	},

	/**
	 * Hides the dropdown
	 */
	hideDropdown: function(){
		$('#dropdown div:visible').hide();
		$('#navigation li.hover').removeClass('hover');
		HI.activeDropdown = -1;
	},

	/**
	 * Checks for matching emails or passwords in field
	 *
	 * @param	field	Field name
	 */
	match: function(field){
		var self = $('#fbRegistration input[name="' + field + '"]');
		var match = $('#fbRegistration input[name="' + field + 'Confirm"]');

		var error = ( ! $(match).val() ) ? 'not_empty' : 'matches';
		
		if( $(self).val() != $(match).val() || $(match).val() == '') {
			$.post( '/ajax/get_error', {field: field + "Confirm", file: 'registration', error: error}, function(msg){
				$(match).siblings('.message').removeClass('success').addClass('error').html( msg );
			});
		} else {
			
			$(match).siblings('.message').removeClass('error').addClass('success').html( '' );
		}
	}

};

/* Copyright (c) 2006-2007 Mathias Bank (http://www.mathias-bank.de)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 *
 * Version 2.1
 *
 * Thanks to
 * Hinnerk Ruemenapf - http://hinnerk.ruemenapf.de/ for bug reporting and fixing.
 * Tom Leonard for some improvements
 *
 */
jQuery.fn.extend({
/**
* Returns get parameters.
*
* If the desired param does not exist, null will be returned
*
* To get the document params:
* @example value = $(document).getUrlParam("paramName");
*
* To get the params of a html-attribut (uses src attribute)
* @example value = $('#imgLink').getUrlParam("paramName");
*/
 getUrlParam: function(strParamName){
	  strParamName = escape(unescape(strParamName));

	  var returnVal = new Array();
	  var qString = null;
	  var strHref = '';
	  var strQueryString = '';

	  if ($(this).attr("nodeName")=="#document") {
	  	//document-handler

		if (window.location.search.search(strParamName) > -1 ){

			qString = window.location.search.substr(1,window.location.search.length).split("&");
		}

	  } else if ($(this).attr("src")!="undefined") {

	  	strHref = $(this).attr("src")
	  	if ( strHref.indexOf("?") > -1 ){
	    	strQueryString = strHref.substr(strHref.indexOf("?")+1);
	  		qString = strQueryString.split("&");
	  	}
	  } else if ($(this).attr("href")!="undefined") {

	  	strHref = $(this).attr("href");
	  	if ( strHref.indexOf("?") > -1 ){
	    	strQueryString = strHref.substr(strHref.indexOf("?")+1);
	  		qString = strQueryString.split("&");
	  	}
	  } else {
	  	return null;
	  }


	  if (qString==null) return null;


	  for (var i=0;i<qString.length; i++){
			if (escape(unescape(qString[i].split("=")[0])) == strParamName){
				returnVal.push(qString[i].split("=")[1]);
			}

	  }


	  if (returnVal.length==0) return null;
	  else if (returnVal.length==1) return returnVal[0];
	  else return returnVal;
	}
});
