$(document).ready(function()
{
    // NOTE: These are pulled from Validate and backslashes doubled to conform with needs of the RegExp class
    var VALIDATE_NUM =          '0-9';
    var VALIDATE_SPACE =        '\\s';
    var VALIDATE_ALPHA_LOWER =  'a-z';
    var VALIDATE_ALPHA_UPPER =  'A-Z';
    var VALIDATE_ALPHA =        VALIDATE_ALPHA_LOWER + VALIDATE_ALPHA_UPPER;
    var VALIDATE_EALPHA_LOWER = VALIDATE_ALPHA_LOWER + 'áéíóúýàèìòùäëïöüÿâêîôûãñõ¨åæç½ðøþß';
    var VALIDATE_EALPHA_UPPER = VALIDATE_ALPHA_UPPER + 'ÁÉÍÓÚÝÀÈÌÒÙÄËÏÖÜ¾ÂÊÎÔÛÃÑÕ¦ÅÆÇ¼ÐØÞ';
    var VALIDATE_EALPHA =       VALIDATE_EALPHA_LOWER + VALIDATE_EALPHA_UPPER;
    var VALIDATE_PUNCTUATION =  VALIDATE_SPACE + '\\.,;\\:&"\'\\?\\!\\(\\)';
    var VALIDATE_NAME =         VALIDATE_EALPHA + VALIDATE_SPACE + "'" + "-";
    var VALIDATE_STREET =       VALIDATE_NUM + VALIDATE_NAME + "/\\\\ºª\\.";

	$("form").inputHintOverlay(0,0,'div','hint');
	
	$.validator.addMethod("anyPhoneNumber", function(phone_number, element) {
        return phone_number.length == 0 || (phone_number.length >= 7 && phone_number.match(new RegExp('^[' + VALIDATE_NUM + VALIDATE_SPACE + '-\\(\\)' + ']*$')));
	}, "Please specify a valid phone number");

	$.validator.addMethod("validname", function(name, element) {
	    return name.match(new RegExp('^[' + VALIDATE_NAME + ']*$'));
	}, "Please specify a valid name (certain punctuation is not allowed)");

	$.validator.addMethod("validstreet", function(name, element) {
		return name.match(new RegExp('^[' + VALIDATE_STREET + '#' + ']*$'));
	}, "Please specify a valid street address (certain punctuation is not allowed)");

	$.validator.addMethod("validzip", function(name, element) {
		return name.match(new RegExp('^[' + VALIDATE_NUM + VALIDATE_SPACE + "-" + ']*$'));
	}, "Please specify a valid zip code");


	// rss scrolling
	window.setTimeout(function() 
	{ 
		$("div.rss").each(function(i)
		{
			$(this).load("/ajax.blog.php", { whichFeed:$(this).attr("id"), whichSettings:$(this).attr("settings") }, function() 
			{
				$(this).find(".scrollable").scrollable({size:1,vertical:true}).circular().navigator().autoscroll({autoplay:true,interval:5000});
				if ($(this).hasClass("round"))
				{
					$(this).backgroundCanvas();
					$(this).backgroundCanvasPaint(RoundBorder); 
				}
			});
		});
	}, 100);
	
	// generic dialog
	$("#statusdialog").dialog( { autoOpen: false, modal: true, resizable: false } );
	
	// contact form
	function HiliteFieldOnError(element,errorClass)
	{
		$(element).closest("div.element").addClass('qferror');
	}

	function UnhiliteFieldOnError(element,errorClass)
	{
		$(element).closest("div.element").removeClass('qferror');
	}

	$(".contactformbtn").each(function()
	{
		$(this).closest('form').validate(
		{
			highlight:HiliteFieldOnError, 
			unhighlight:UnhiliteFieldOnError, 
			submitHandler:SubmitHandler,
			debug:false
		});
	});

	function SubmitHandler(theForm)
	{
		$(theForm).ajaxSubmit(
		{
			beforeSubmit:function(data,$form,options)
			{
				$("#statusdialog").html("<h2>Please Wait</h2><p>We are processing your request.</p>");
				$("#statusdialog").dialog('option','buttons',{});
				$("#statusdialog").dialog('open');
				return true;
			},
			dataType: 'json',
			url:"/form_submit.php",
			success:function(response)
			{
				$("#statusdialog").html(response.message);
				$("#statusdialog").dialog('open');
				$("#statusdialog").dialog('option','buttons',{OK:function(){ $("#statusdialog").dialog('close'); }});

				if (response.action != 'retry' && response.action != 'stay')
					$("#statusdialog").dialog('option','close',function(){ window.location = "/" });
			}
		})
	}

	// Songs
	var clipOptions = 
	{
		clip:
		{
			autoPlay: 	false,
			onStart: 	function(clip) { pageTracker._trackEvent("Videos","Play",clip.url); },
			onPause: 	function(clip) { pageTracker._trackEvent("Videos","Pause",clip.url, parseInt(this.getTime())); },
			onResume: 	function(clip) { pageTracker._trackEvent("Videos","Resume",clip.url, parseInt(this.getTime())); },
			onStop: 	function(clip) { pageTracker._trackEvent("Videos","Stop",clip.url, parseInt(this.getTime())); },
			onFinish: 	function(clip) { pageTracker._trackEvent("Videos","Finish",clip.url); }
		},
		
		plugins: { controls: { stop: true, fullscreen:false }}
	};
	
	$("div.song div.player").each(function(i)
	{
		clipOptions.clip.url = $(this).attr("song");
		$(this).flowplayer({src:"/tools/flowplayer/flowplayer-3.1.5.swf",wmode:'opaque'},clipOptions);
	});
	
	$("div.song").hoverIntent(
		function() { $(this).find('div.songinfo').slideDown('normal'); },
		function() { $(this).find('div.songinfo').slideUp('normal'); }
	);
	
	// Find a parish
	$("a.findparish").click(function(){ $("#parishdialog").dialog('open'); return false; });
	$("#parishdialog").dialog({ autoOpen: false, closeOnEscape: true, draggable: true, resizable: false, title: "Find Nearby Parishes" });
	
	$("#parishdialog form").submit(function()
	{
		var ZIP = $(this).find('input').val();
		$("#parishdialog").dialog("close");
		window.open("/tools/findaparish.php?zip="+ZIP);
		
		return false;
	});

	// Keep Me Updated
	$(".signuplink").click(function(){ $("#updateddialog").dialog('open'); return false; });
	$("#updateddialog").dialog(
	{ 
		autoOpen: false, 
		width:420, 
		closeOnEscape: true, 
		modal: true, 
		draggable: true, 
		resizable: false, 
		title: "Keep Me Updated", 
		buttons: 
		{
			"Sign Up": function() { $("#updateddialog form").submit(); },
			"Cancel":function() { $(this).dialog('close'); }
		}
	});

	function UpdateFormSubmitHandler(theForm)
	{
		$(theForm).ajaxSubmit(
		{
			beforeSubmit:function(data,$form,options)
			{
				$("#updateddialog").dialog('close');
				$("#statusdialog").html("<h2>Please Wait</h2><p>We are processing your request.");
				$("#statusdialog").dialog('option','buttons',{});
				$("#statusdialog").dialog('open');
				return true;
			},
			dataType: 'json',
			url:"/form_submit.php",
			success:function(response)
			{
				$("#statusdialog").html(response.message);
				$("#statusdialog").dialog('open');
				$("#statusdialog").dialog('option','buttons',{OK:function(){ $("#statusdialog").dialog('close'); }});

				if (response.action != 'retry' && response.action != 'stay')
					$("#statusdialog").dialog('option','close',function(){ window.location = "/" });
			}
		})
	}
	
	function PlaceError(error,$element)
	{
		var $batchElem = $element.closest('fieldset').children('.batcherror');
		if ($batchElem.length)
			error.appendTo($batchElem);
		else
			error.prependTo($element.closest('div.qfrow'));
	}

	function HiliteFieldOnError2(element,errorClass)
	{
		$(element).closest("div.qfelement").addClass('qferror');
	}

	function UnhiliteFieldOnError2(element,errorClass)
	{
		$(element).closest("div.qfelement").removeClass('qferror');
	}

	$("#updateddialog form").validate(
	{
		errorPlacement:PlaceError, 
		highlight:HiliteFieldOnError2, 
		unhighlight:UnhiliteFieldOnError2, 
		submitHandler:UpdateFormSubmitHandler,
		debug:false
	});
	
	
	// Round rects
	$(".round").backgroundCanvas();
	DrawBackground();
	
	// Question/answer dialog
	$("#question img.answer").each(function(i){ var $d = $(this).next('a').next('div'); $d.addClass('answer'+i); });
	$("#question > div").dialog( { autoOpen: false, closeOnEscape: true, draggable: true, resizable: false, width: 850, dialogClass: 'answer dialog smalltext' });
	$("#question img.answer").click(function() 
	{
		var i = $(this).parent().find('img.answer').index(this);
		$("div.answer"+i).dialog('option','title',$(this).next('a').text()).dialog('open');
		$('a').blur();
	});

	// Read More dialog
	$(".addin").click(function(e) { $($(this).attr('rel')).dialog({ show:'fast', hide:'fast', closeOnEscape: true, draggable: true, resizable: false, width: 840, title: $(this).attr("title") }).dialog('open'); });

	// Shipping section toggle
	$('#shipping-0').add('#shipping-1').change(AdjustShipping);
	
	jQuery.fx.off = true;
	AdjustShipping();
	jQuery.fx.off = false;
	
	// Credit card dialog
	$('#whatisthis').dialog({ autoOpen: false, closeOnEscape: true, draggable: true, resizable: false, title: 'CVV2 Information', width: 450, buttons: { 'Close Window': function(){$(this).dialog('close');}}});
	$('.whatisthisbtn').live("click",function(){ $('#whatisthis').dialog('open'); return false; });
	$('.explainthis').live("click",function(){
		$("#statusdialog").html($(this).attr("ref"));
		$("#statusdialog").dialog('open');
		$("#statusdialog").dialog('option','buttons',{OK:function(){ $("#statusdialog").dialog('close'); }});
		return false;
	})
});

function AdjustShipping() { $("#shipping-1").attr('checked') ? $('fieldset#shipping_info').slideDown() : $('fieldset#shipping_info').slideUp(); }

function DrawBackground()
{
	$(".round").backgroundCanvasPaint(RoundBorder); 
}

$(window).load(function () { DrawBackground(); }); 
$(window).resize(function() { DrawBackground(); });

function RoundBorder(context, width, height, elementInfo)
{
	var borderColor = "#d7d7d7";
	var innerColor = "#ffffff";
	var options = {x:0, y:0, height: height, width: width, radius:5, border: 0 };

	// Draw the border (entire rect)
	context.fillStyle = borderColor;
	$.canvasPaint.roundedRect(context,options);
	
	// Draw the gradient filled inner area
	options.border = 1;
	context.fillStyle = innerColor;
	$.canvasPaint.roundedRect(context,options);
}

function RoundWithShadow(context, width, height, elementInfo) 
{
	var shadowSize = 5;
	var borderColor = "#b7b7b7";
	var innerColor = "#ffffff";
	var options = {x:shadowSize, y:shadowSize, height: height, width: width, radius:20, border: 0 };

	// Draw shadow border
	options.border = 0;
	context.fillStyle = borderColor;
	$.canvasPaint.roundedRect(context,options);
	
	// Draw the shadow content
	options.border = 2;
	context.fillStyle = innerColor;
	$.canvasPaint.roundedRect(context,options);
	

	options.x -= shadowSize;
	options.y -= shadowSize;

	// Draw the border (entire rect)
	context.fillStyle = borderColor;
	$.canvasPaint.roundedRect(context,options);
	
	// Draw the gradient filled inner area
	options.border = 2;
	context.fillStyle = innerColor;
	$.canvasPaint.roundedRect(context,options);
}
