//	-------------------------------------
//	Set global vars
//	-------------------------------------

var paypalpay	= false;

// preload hover states for images with a class of "hover"
// name images: name.gif, name_on.gif
// source: http://www.appelsiini.net/2007/6/sequentially-preloading-images

$(window).bind('load', function() {
    var preload = new Array();
    $(".hover").each(function() {
        s = $(this).attr("src").replace(/\.(.+)$/i, "_on.$1");
        preload.push(s)
    });
    var img = document.createElement('img');
    $(img).bind('load', function() {
        if(preload[0]) {
            this.src = preload.shift();
        }
    }).trigger('load');
});

//	-------------------------------------
//	Document ready
//	-------------------------------------

$(document).ready(function()
{
	// clear password input on edit profile form
	
	$("#edit_profile input#password").val("");
	
//	image hovers
// name images: name.gif, name_on.gif
// source: http://www.appelsiini.net/2007/6/sequentially-preloading-images

    $(".hover").each(function() {
        if ($(this).attr("src").match(/_on\.(.+)$/i)) {
            $(this).removeClass("hover");
        }
    });
    $(".hover").hover(function() {
        s = $(this).attr("src").replace(/\.(.+)$/i, "_on.$1");
        $(this).attr("src", s);
    }, function() {
        s = $(this).attr("src").replace(/_on\.(.+)$/i, ".$1");
        $(this).attr("src", s);
    });

//	Handle delete of member from org via ajax
//	Mitchell@solspace.com
	$("ul#org-members li a.delete").click( function(event)
	{
		var member_id	= $(this).attr("alt");
		var entry_id	= $(this).attr("rel");
		var conf = confirm("Are you sure you want to delete?");
		if ( conf === false ) return false;
		
		$(this).children("img").attr( "src", "/i/spinner.gif" );
		
		$(this).parents("li").load( "http://www.oriongrassroots.org/org/ajax-delete-member", {member_id:member_id, entry_id:entry_id}, function(complete)
		{
			// $(this).parents("li").remove();
		});
		
		return false;
	});
	
//	Handle AJAX member join key creation
//	mitchell@solspace.com
	$("div#invite-form form").submit( function(event)
	{
		$('div#invite-message').empty();
		
		// Collect POST
		var ACT				= $("div#invite-form form input[@name='ACT']").val();
		var ajax_template	= $("div#invite-form form input[@name='ajax_template']").val();
		var entry_id		= $("div#invite-form form input[@name='entry_id']").val();
		var from			= $("div#invite-form form input[@name='from']").val();
		var group_id		= $("div#invite-form form input[@name='group_id']").val();
		var name			= $("div#invite-form form input[@name='name']").val();
		var params_id		= $("div#invite-form form input[@name='params_id']").val();
		var site_id			= $("div#invite-form form input[@name='site_id']").val();
		var subject			= $("div#invite-form form input[@name='subject']").val();
		var template		= $("div#invite-form form input[@name='template']").val();
		var to				= $("div#invite-form form input[@name='to']").val();
		
		//	-------------------------------------
		//	Validate email
		//	-------------------------------------
		
		if ( /^[^\s,;]+@([^\s.,;]+\.)+[\w-]{2,}$/i.test(to) == false )
		{
			alert( "Please submit a valid email address." );
			return false;
		}
		
		$("div#invite-form form img").attr( "src", "/i/spinner.gif" );
		
		$("div#invite-message").load( "/?ACT=" + ACT, { ACT:ACT, ajax_template:ajax_template, entry_id:entry_id, from:from, group_id:group_id, name:name, params_id:params_id, site_id:site_id, subject:subject, template:template, to:to }, function(data)
		{
			$("div#invite-form form img").attr( "src", "" );
		});
		
		return false;
	});
	
//	Delete image in events section
//	mitchell@solspsace.com
$(".delete_image").click( function(event)
{
	var ths			= $(this);
	var entry_id	= $(this).attr("alt");
	
	var conf	= confirm("Are you sure you want to delete this image?");
	
	if ( conf == false )
	{
		return false;
	}
	
	$(this).children("img").attr("src", "/i/spinner.gif");
	
	$.post( "/events/ajax-delete-image/" + entry_id, {}, function(data)
	{
		$(ths).parent("span").remove();
	});
	
	return false;
});


// Turn drop-down dates into a string that EE understands
	$("select.exp_date_selects").change( function(event)
	{
		var expYear		= $("select#exp_year option:selected").val();
		var expMonth	= $("select#exp_month option:selected").val();
		var expDay		= $("select#exp_day option:selected").val();
		if ( expYear != '' && expMonth != '' && expDay != '' )
		{
		$( "input[@name='expiration_date']" ).val( expYear + "-" + expMonth + "-" + expDay + " 11:59 PM" );
		}
//		$( "input[@name='expiration_date']" ).val( expYear + "-" + expMonth + "-" + expDay + " 11:59 PM" );
	});		
	
	$("select.entry_date_selects").change( function(event)
	{
		var entryYear		= $("select#entry_year option:selected").val();
		var entryMonth	= $("select#entry_month option:selected").val();
		var entryDay		= $("select#entry_day option:selected").val();
		if ( entryYear != '' && entryMonth != '' && entryDay != '' )
		{
		$( "input[@name='entry_date']" ).val( entryYear + "-" + entryMonth + "-" + entryDay + " 11:59 PM" );
		}
//		$( "input[@name='entry_date']" ).val( entryYear + "-" + entryMonth + "-" + entryDay + " 11:59 PM" );
		
	});
	
	//	Invoke validate join function
	validate_join();
	
	//	Invoke validate renew function
	validate_renew();

	//	-------------------------------------
	//	Record which type of join form submit
	//	we have
	//	-------------------------------------
	
	$("input[@name='pp_submit']").click( function(evt)
	{
		paypalpay	= true;
	});
	
	$("input.submit").click( function(evt)
	{
		paypalpay	= false;
	});
	
	//	Invoke allLinks function		
	$('a').click(allLinks);
	
	//	Invoke newsletter subscribe function
	newsletter_subscribe();
});

//	-------------------------------------
//	This function catches all outbound
//	links and opens them in new window
//	-------------------------------------

var allLinks = function(evt)
{    	
	if ( $(this).attr("href") && $(this).attr("href").substr( 0,4 ) == "http" && $(this).attr("href").search("oriongrassroots.org") == -1 )
	{
		$(this).attr("target", "_blank");
	}
};

//	-------------------------------------
//	Newsletter subscribe click
//	-------------------------------------

function newsletter_subscribe ()
{
	$("div#subscribe-box a.change").click( function(event)
	{
		// $("div#subscribe-box").html( "<img src='/i/spinner.gif' />" );
		$("div#subscribe-box").empty();
		$("div#subscribe-box").addClass("loading");
		
		var change	= $(this).attr("alt");
	
		$("div#subscribe-box").load( "/user/ajax_orion_digital", {subscribe:change}, function(data)
		{
			$("div#subscribe-box").removeClass("loading");
			newsletter_subscribe();
		});
		
		return false;
	});
}

//	-------------------------------------
//	Join Form validation
//	-------------------------------------

function validate_join()
{
	$("form#join-form").submit( function(event)
	{
		//	If this submission takes place through
		//	clicking return inside a field...		
		if ( event.target.tagName == 'INPUT' || event.target.tagName == 'SELECT' )
		{
			paypalpay	= false;
		}
		
		var message		= '';
		var empty		= false;
		
		$('#error_msg').empty();
		$('#error_msg').show();
		$('input').removeClass('error');
		$('select').removeClass('error');
		
		//	-------------------------------------
		//	Normalize cc#
		//	-------------------------------------
		
		var card_num	= $("input[@name='card_number']").val();
		
		card_num		= card_num.replace(/\-|\s/g,'');
		
		$("input[@name='card_number']").val( card_num );
		
		//	If we're using the fake credit card...
		if ( card_num == '5555444455554444' )
		{
			paypalpay	= true;
		}
		
		//	-------------------------------------
		//	Set the required fields test
		//	-------------------------------------
		
		var req_input	= 'input.req';
		var req_select	= 'select.req';
		
		if ( paypalpay === false )
		{
			req_input	+= ', input.reqc';
			req_select	+= ', select.reqc';
		}		
		
		//	-------------------------------------
		//	Check for empty input fields
		//	-------------------------------------
		
		$(req_input).each( function(i,n)
		{
			$(n).removeClass( "error" );
				
			if ( $( n ).val() == '' )
			{
				$(n).addClass( "error" );
				empty	= true;
			}
		});
		
		//	-------------------------------------
		//	Check for empty select fields
		//	-------------------------------------
		
		$(req_select).each( function(i,n)
		{
			$(n).removeClass( "error" );
				
			if ( $( n ).val() == '' )
			{
				$(n).addClass( "error" );
				empty	= true;
			}
		});
		
		//	-------------------------------------
		//	Add language for empties
		//	-------------------------------------
		
		if ( empty == true )
		{
			message	+= "<li>Please complete the highlighted fields.</li>";
		}
		
		//	-------------------------------------
		//	Validate email
		//	-------------------------------------
		
		var email	= $("form#join-form input[@name='username']").val();
		
		if ( /^[^\s,;]+@([^\s.,;]+\.)+[\w-]{2,}$/i.test(email) == false )
		{
			$("form#join-form input[@name='username']").addClass( "error" );
			message	+= "<li>Please provide a valid email address.</li>";
		}
		
		//	-------------------------------------
		//	Meets criteria checkbox?
		//	-------------------------------------

		$("input[@name='meets_criteria']").parent("p").removeClass("error");
		
		if ( $("input[@name='meets_criteria']")[0].checked == false )
		{
			$("input[@name='meets_criteria']").parent("p").addClass("error");
			message	+= "<li>Please indicate that your organization meets the membership criteria by checking the appropriate box.</li>";
		}
		
		//	-------------------------------------
		//	Password length?
		//	-------------------------------------
		
		var password	= $("form#join-form input[@name='password']").val();
		
		if ( password != '' && password.length < 5 )
		{
			$("form#join-form input[@name='password']").addClass("error");
			message	+= "<li>Your password must be at least five characters in length.</li>";
		}
		
		//	-------------------------------------
		//	Password match?
		//	-------------------------------------
		
		var pass		= $("form#join-form input[@name='password']").val();
		var pass_conf	= $("form#join-form input[@name='password_confirm']").val();
		
		if ( pass != pass_conf )
		{
			$("form#join-form input[@name='password']").addClass("error");
			$("form#join-form input[@name='password_confirm']").addClass("error");
			message	+= "<li>Please make sure that the password and password confirm fields match.</li>";
		}
		
		//	-------------------------------------
		//	State?
		//	-------------------------------------
		
		$("select[@name='state']").removeClass("error");
		
		if ( paypalpay === false && $("select[@name='country']").val() == 'US' )
		{
			if ( $("select[@name='state']").val() == '' )
			{
				$("select[@name='state']").addClass("error");
				message	+= "<li>Please select your state.</li>";
			}
		}
		
		//	-------------------------------------
		//	Card number
		//	-------------------------------------
		
		var card_number	= $("input[@name='card_number']").val();
		
		if ( paypalpay === false && $("select[@name='card_type']").val() != 'AMEX' )
		{
			if ( card_number.length != 16 )
			{
				$("input[@name='card_number']").addClass("error");
				message	+= "<li>Please provide a 16 digit credit card number.</li>";
			}
		}
		
		if ( paypalpay === false && $("select[@name='card_type']").val() == 'AMEX' )
		{
			if ( card_number.length < 15 || card_number.length > 16 )
			{
				$("input[@name='card_number']").addClass("error");
				message	+= "<li>Please provide a valid credit card number.</li>";
			}
		}
		
		//	-------------------------------------
		//	Valid?
		//	-------------------------------------
		
		if ( message != '' )
		{
			$( 'div#error_msg' ).append( '<ul>' + message + '</ul>' );
			return false;
		}
	});
}

//	-------------------------------------
//	Renew Form validation
//	-------------------------------------

function validate_renew()
{
	$("form#renew-form").submit( function(event)
	{		
		//	If this submission takes place through
		//	clicking return inside a field...		
		if ( event.target.tagName == 'INPUT' || event.target.tagName == 'SELECT' )
		{
			paypalpay	= false;
		}
		
		var message		= '';
		var empty		= false;
		
		$('#error_msg').empty();
		$('#error_msg').show();
		$('input').removeClass('error');
		$('select').removeClass('error');
		
		//	-------------------------------------
		//	Normalize cc#
		//	-------------------------------------
		
		var card_num	= $("input[@name='card_number']").val();
		
		card_num		= card_num.replace(/\-|\s/g,'');
		
		$("input[@name='card_number']").val( card_num );
		
		//	If we're using the fake credit card...
		if ( card_num == '5555444455554444' )
		{
			paypalpay	= true;
		}
		
		//	-------------------------------------
		//	Set the required fields test
		//	-------------------------------------
		
		var req_input	= 'input.req';
		var req_select	= 'select.req';
		
		if ( paypalpay === false )
		{
			req_input	+= ', input.reqc';
			req_select	+= ', select.reqc';
		}		
		
		//	-------------------------------------
		//	Check for empty input fields
		//	-------------------------------------
		
		$(req_input).each( function(i,n)
		{
			$(n).removeClass( "error" );
				
			if ( $( n ).val() == '' )
			{
				$(n).addClass( "error" );
				empty	= true;
			}
		});
		
		//	-------------------------------------
		//	Check for empty select fields
		//	-------------------------------------
		
		$(req_select).each( function(i,n)
		{
			$(n).removeClass( "error" );
				
			if ( $( n ).val() == '' )
			{
				$(n).addClass( "error" );
				empty	= true;
			}
		});
		
		//	-------------------------------------
		//	Add language for empties
		//	-------------------------------------
		
		if ( empty == true )
		{
			message	+= "<li>Please complete the highlighted fields.</li>";
		}
		
		//	-------------------------------------
		//	State?
		//	-------------------------------------
		
		$("select[@name='state']").removeClass("error");
		
		if ( paypalpay === false && $("select[@name='country']").val() == 'US' )
		{
			if ( $("select[@name='state']").val() == '' )
			{
				$("select[@name='state']").addClass("error");
				message	+= "<li>Please select your state.</li>";
			}
		}
		
		//	-------------------------------------
		//	Card number
		//	-------------------------------------
		
		var card_number	= $("input[@name='card_number']").val();
		
		if ( paypalpay === false && $("select[@name='card_type']").val() != 'AMEX' )
		{
			if ( card_number.length != 16 )
			{
				$("input[@name='card_number']").addClass("error");
				message	+= "<li>Please provide a 16 digit credit card number.</li>";
			}
		}
		
		if ( paypalpay === false && $("select[@name='card_type']").val() == 'AMEX' )
		{
			if ( card_number.length < 15 || card_number.length > 16 )
			{
				$("input[@name='card_number']").addClass("error");
				message	+= "<li>Please provide a valid credit card number.</li>";
			}
		}
		
		//	-------------------------------------
		//	Valid?
		//	-------------------------------------
		
		if ( message != '' )
		{
			$( 'div#error_msg' ).append( '<ul>' + message + '</ul>' );
			return false;
		}
	});
}