// JQuery Scripts
$(document).ready(function(){
	
	// Is it a mobile Device?
	if (navigator.userAgent.match(/Android/i) || navigator.userAgent.match(/webOS/i) || navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPod/i) || navigator.userAgent.match(/iPad/i) || navigator.userAgent.match(/BlackBerry/)) {
		$('html').addClass('mobile');
		
		$('.sf-menu > li > a').each(function() {
			$(this).attr('href', 'javascript:return(false)');
		})
	} else {
		$('html').addClass('desktop');
	}
	
	
	// Current Page URL
	var $page_url = document.location.href;
	
	/* Superfish Dropdown Menu */
	$("html.desktop #navigation .sf-menu").supersubs({ 
    	minWidth:    10,   // minimum width of sub-menus in em units 
    	maxWidth:    15   // maximum width of sub-menus in em units 
                            // due to slight rounding differences and font-family 
    }).superfish();  // call supersubs first, then superfish, so that subs are 
                     // not display:none when measuring. Call before initialising 
                    // containing tabs for same reason. 
	
	
	/* Form Radio Buttons */
	
	// Stylized Radio Button Toggler
	$('.radio_stylized').live('click',function() {
		var $radio = $(this);
		
		if($radio.hasClass('checked')) {
			
		} else {
			$radio.parent().find('input').removeAttr('checked');
			$radio.next('input').attr('checked','checked');
			$radio.parent().find('.radio_stylized').removeClass('checked');
			$radio.addClass('checked');
		}
		
		//ed adds
		$('.donation_amount_other .donation_field').attr('value', '');
	
	});
	
	// Stylized Checkbox Toggler
	$('.checkbox_stylized').live('click',function() {
		var $radio = $(this);
		
		if($radio.hasClass('checked')) {
			$radio.removeClass('checked');
			$radio.next('input').removeAttr('checked');
		} else {
			$radio.addClass('checked');
			$radio.next('input').attr('checked','checked');
		}
	
	});
	
	$('.read-expand').bind('click',function() {
		if($(this).text() !== 'Collapse') {
			window.expandText = $(this).text();
		}
		
		var expand_container = $(this).parent().prev();
		
		if($(expand_container).is(':visible')) {
			$(expand_container).slideUp('slow');
			$(this).text(window.expandText);
		} else {
			$(expand_container).slideDown('slow');
			$(this).text('Collapse');
		}
	});
	
	
	/***********************************************************************
	 * Top Right Search Area
	 **********************************************************************/
	
	// Shows the search overlay
	$('.top-menu .search-button').live('click',function() {
		$('.search-overlay').fadeIn();
		$(this).addClass('search-submit');
		$(this).removeClass('search-button');
	});
	
	// If the search overlay is showing then the search button turns into a submit
	$('.top-menu .search-submit').live('click',function() {
		if($('.search-overlay-field input').val() == 'Search Site' || $('.search-overlay-field input').val() == '') {
			$(this).addClass('search-button');
			$(this).removeClass('search-submit');
			$('.search-overlay').fadeOut();
		} else {
			document.forms["mainSearchForm"].submit();
		}
	});
	
	// Shows the advanced search overlay
	$('.top-menu .advanced-filter-text').bind('click',function() {
		if($('.advanced-filter-overlay').is(':visible')) {
			$('.advanced-filter-overlay').slideUp('fast');
		} else {
			$('.advanced-filter-overlay').slideDown('fast');
		}
	});
	
	// The search overlay field focus
	$('.top-menu .search-overlay-field input').bind('focus',function() {
		if($(this).val() == 'Search Site') {
			$(this).val('');
		} else {

		}
	});
	
	/***********************************************************************
	 * Active Menu Class
	 **********************************************************************/

	 // Add active class to Main Navigation items based upon page url
	$('#navigation ul li, #sub-navigation ul li, #media-types ul li').each(function(index) {
		$menu_item = $(this);
		$menu_item_parent = $menu_item.parent('ul').attr('class');
		$menu_item_link = $menu_item.children('a').attr('href');
		var re = new RegExp($menu_item_link+'$', 'gi');
		if($page_url.match(re)) {
			// console.log($menu_item_link);
			$menu_item.addClass('active');
			if($menu_item_parent) {
				$('#navigation li.' + $menu_item_parent).addClass('active');
			}
		}
	});
	
	
	/***********************************************************************
	 * Top Overlay Area
	 **********************************************************************/
	
	// 	Show Overlay
	function show_overlay($new_overlay) {
		
		// If an Overlay is already showing, run the hide_overlays() function which hides the current overlay and shows the new one.
		if(check_if_overlays_are_showing() == true) {
			// If an overlay is already showing, hide it first, and then show the new one.
			hide_overlays($new_overlay);
		} else {
			$('.top-overlay').hide();
			$new_overlay.show();
			var overlay_height = $('#top-overlay-container').height();
			
			$('#top-overlay-container').show();
			$('#top-overlay-container').css({ top: -overlay_height});
			$('#top-overlay-container').animate({top: 41}, 700, 'swing');
		}
	}
		
	// Hides all Overlays, if new $new_overlay is provided than show it by envoking show_overlay() function.
	function hide_overlays($new_overlay) {
		var overlay_height = $('#top-overlay-container').height();
		$('#top-overlay-container').animate({top: -overlay_height}, 700, 'swing', 
		
		// After overlay animation has been completed
		function() { 
			$('#top-overlay-container').hide();
			$('.top-overlay').hide();
			if($new_overlay) {
				show_overlay($new_overlay);
			}
			
		});
	}
	
	// Checks to see if Overlay is already showing. Returns Bool.
	function check_if_overlays_are_showing() {
		return $('#top-overlay-container').is(':visible') ? true : false;
	}
	
	// Adds Click Event Handler to 'Member Center' and 'Visitor Center' to show intended Overlay.
	$('.top-menu .member-center, .top-menu .visitor-center').bind('click', function() {
		var $menu_item = $(this);
		var $overlay = $('#' + $(this).attr('class') + '-overlay');
		
		if($menu_item.is('.active')) {
			hide_overlays()
			$('.top-menu li').removeClass('active');	
		} else {
			$('.top-menu li').removeClass('active');
			$menu_item.addClass('active');
			show_overlay($overlay);
		}
	});
	
	// Adds Click Event Handler to the Overlay hide button.
	$('.hide-overlay').bind('click',function() {
		hide_overlays();
		$('.top-menu li').removeClass('active');
	});

		
	

	/***********************************************************************
	 * Prayer Center Area
	 **********************************************************************/
	
	/*** Prayer Center - Rotating Prayer Requests and Praise Reports ***/
	prayer_entry_amount 			= $('#continual-prayer .continual-prayer-entry').length;
	prayer_entry_group_amount 		= Math.round($('#continual-prayer .continual-prayer-entry').length / 4);
	prayer_entry_group_index 		= 2;
	prayer_entry_timer 				= setInterval(show_prayer_entries, 12000);	
		
	// Show the initial 4 requests by default
	$('#continual-prayer .continual-prayer-entry').slice(0, 4).show();
	
	function show_prayer_entry_group(group_index) {

		if((typeof prayer_entry_start === 'undefined') || (prayer_entry_start == null)) {
			// At what index do we need to start showing entries
			var prayer_entry_start = ((4 * group_index) - 4);
		}
		
		// Get an array of all current visible entries then fade them out at specific intervals
		var visible_requests = $('#continual-prayer .continual-prayer-entry:visible'); 
				
		$(visible_requests).eq(0).delay(1500).fadeOut();
		$(visible_requests).eq(1).delay(3000).fadeOut();
		$(visible_requests).eq(2).delay(4500).fadeOut();
		$(visible_requests).eq(3).delay(6000).fadeOut();
		
		// Fade in specific entries based upon group index
		$('#continual-prayer .continual-prayer-entry').eq(prayer_entry_start).delay(1500).fadeIn();
		$('#continual-prayer .continual-prayer-entry').eq(prayer_entry_start + 1).delay(3000).fadeIn();
		$('#continual-prayer .continual-prayer-entry').eq(prayer_entry_start + 2).delay(4500).fadeIn();
		$('#continual-prayer .continual-prayer-entry').eq(prayer_entry_start + 3).delay(6000).fadeIn();
	}
	
	function show_prayer_entries() {
		if(prayer_entry_group_index == prayer_entry_group_amount+1) {
			prayer_entry_group_index = 1;
		} else {
			show_prayer_entry_group(prayer_entry_group_index);
			// console.log(prayer_entry_group_index);
			prayer_entry_group_index++;		
		}
	}
	
	/*** Prayer Center - Controls ***/
	
	// Adds Click functionality to control tabs
	$('#prayer-center-controls .button').bind('click',function() {
		$button = $(this);
		if($button.is('.active')) {
			// If button is already active do nothing
		} else {
			
			// Stop prayer feed
						
			$('#prayer-center-controls .button').removeClass('active');			
			$button.addClass('active');
			$('#prayer-center div.panel').each(function(index) {
				$panel = $(this);
				if($button.hasClass($panel.attr('id'))) {
					$panel.show();
					
					// Stop queue
					clearInterval(prayer_entry_timer);
					$('#continual-prayer .continual-prayer-entry').stop();
					$('#continual-prayer .continual-prayer-entry').animate({ opacity: 1 });
					$('#continual-prayer .continual-prayer-entry').hide();
					
								
					// If switching back to the continual prayer panel, then restart prayer feed
					if($panel.attr('id') == 'continual-prayer') {						

						prayer_entry_amount 			= $('#continual-prayer .continual-prayer-entry').length;
						prayer_entry_group_amount 		= Math.round($('#continual-prayer .continual-prayer-entry').length / 4);
						prayer_entry_group_index 		= 2;
						prayer_entry_timer = setInterval(show_prayer_entries, 12000);	

						// Show the initial 4 requests by default
						$('#continual-prayer .continual-prayer-entry').slice(0, 4).show();
					}
					
				} else {
					$panel.hide();
				}
			});
		}
	});

	
	/*** Prayer Center - Prayer Request Form functionality ***/
	
	// Create variables with default field content
	var prayer_request_email_field = 'Email Address (will not be made public)';
	var prayer_request_first_name_field = 'First Name or leave blank for \'Anonymous\'';
	var prayer_request_textarea_text = 'Type your prayer request here...\n\nPlease bear in mind that not all prayer requests will be displayed on the website prayer scroll.\nAll submitted prayers and testimonies will be screened and approved for inclusion.';
	var praise_report_textarea_text = 'Type your praise report here...\n\nPlease bear in mind that not all praise reports will be displayed on the website prayer scroll. All submitted prayers and testimonies will be screened and approved for inclusion.';
	
	// Text Area Object
	var $prayer_request_textarea = $('.prayer-request-textarea textarea');
	
	// Set Prayer Request Textarea Default Value
	$prayer_request_textarea.val(prayer_request_textarea_text);
	
	// Hide default text in Textarea on Focus
	$('.prayer-request-textarea textarea').bind('focus', function() {
		$(this).css('color','#000');
		
		var $prayer_request_textarea_text = $(this).val();
		
		// check to make sure that the textarea contains the default text before hiding it all.
		if(($('.prayer-request-select-1').is(':checked')) && ($prayer_request_textarea.val() == prayer_request_textarea_text)) {
			$prayer_request_textarea.val('');
		}
		
		// check to make sure that the textarea contains the default text before hiding it all.
		if(($('.prayer-request-select-2').is(':checked')) && ($prayer_request_textarea.val() == praise_report_textarea_text)) {
			$prayer_request_textarea.val('');
		}
	});
		
	// Show default text in Textarea on Blur
	$('.prayer-request-textarea textarea').bind('blur',function() {
		$(this).css('color','#939598');
		
		if(($('.prayer-request-select-1').is(':checked')) && ($prayer_request_textarea.val() == '')) {
			$prayer_request_textarea.val(prayer_request_textarea_text);
		}
		
		if(($('.prayer-request-select-2').is(':checked')) && ($prayer_request_textarea.val() == '')) {
			$prayer_request_textarea.val(praise_report_textarea_text);
		}
	});
			
	// Hide default text in E-mail Field on Focus
	$('.prayer-request-email input').bind('focus',function() {
				
		// check to make sure that the textarea contains the default text before hiding it all.
		if($(this).val() == prayer_request_email_field) {
			$(this).val('');
		}
	});
	
	// Show default text in E-mail Field on Blur
	$('.prayer-request-email input').bind('blur',function() {
		if($(this).val() == '') {
			$(this).val(prayer_request_email_field);
		}
	});
	
	// Hide default text in First Name Field on Focus
	$('.prayer-request-first-name input').bind('focus',function() {
				
		// check to make sure that the textarea contains the default text before hiding it all.
		if($(this).val() == prayer_request_first_name_field) {
			$(this).val('');
		}
	});
	
	// Show default text in First Name Field on Blur
	$('.prayer-request-first-name input').bind('blur',function() {
		if($(this).val() == '') {
			$(this).val(prayer_request_first_name_field);
		}
	});
	
	// jQuery Validator Plugin to Validate 'prayer-request-form' Form
	var validator_prayer_request = $("#prayer-request-form").validate({ 
        rules: { 
			prayer_request_email: { 
                required: true, 
                email: true
            }, 
			prayer_request_textarea: 'check_textarea'
		}, 
		debug:true,
		
        // specifying a submit handler
        submitHandler: function() { 
			
			// If user submits form with default name field, clear it.
			if($('.prayer-request-first-name input').val() == prayer_request_first_name_field) {
				$('.prayer-request-first-name input').attr('value','');
			}
			
			// Serialize Form
			var prayer_request_form = $('#prayer-request-form').serialize();

			$.ajax({
			 type: 'POST',
			 url: '/includes/theme/prayer-request-center-submit.php',
			 data: prayer_request_form,
			 success: function(json){alert(json); $('#prayer-request-form')[0].reset(); }
			 });
		}, 
        		
        // set this class to error_labels to indicate valid fields 
        success: function(label) { 
            // removes error label if field passes validation
            label.remove();
        } 
    });
	
	// Custom validation method to check if the text area has been filled out approriately
	jQuery.validator.addMethod("check_textarea", function(value, element) { 
		if(($prayer_request_textarea.val() == prayer_request_textarea_text) || ($prayer_request_textarea.val() == praise_report_textarea_text) || ($prayer_request_textarea.val() == '')) {
		 	return false; 
		} else {
			return true;
		}
	}, jQuery.format("This field is required"));

	// Reset Prayer Request Form back to defaults
	function reset_prayer_request_form() {
		// Reset everything else back to normal - Clears everything
		$(':input','#prayer-request-form')
		.not(':button, :submit, :reset, :hidden')
		.val('')
		.removeAttr('checked')
		.removeAttr('checked');
				
		// Reset fields to the defaults
		$('.prayer-request-select-1').attr('checked','checked');
		
		// Reset fields to the defaults
		$('.prayer-request-select-1').attr('checked','checked');
		$('.prayer-request-email input').val(prayer_request_email_field);
		$('.prayer-request-first-name input').val(prayer_request_first_name_field);
		$('.prayer-request-gender input:first').attr('checked','checked');
		$prayer_request_textarea.val(prayer_request_textarea_text);
		$('label.error').remove();
		$('#prayer_request .error').removeClass('error');
		
		// Resets text area char counter
		reset_char_counter();		
		
	}		
	
	// Reset the text area char counter back to default amount
	function reset_char_counter() {
		$('.prayer-request-char-counter-number').text('140');
	}
	
	// Prayer Request character counter
	$prayer_request_textarea.bind('keydown keyup',function() {
		inputValue = $(this).val();
		if(inputValue.length == 140 || inputValue.length > 140) {
			inputValue = inputValue.slice(0, 140);
			$(this).val(inputValue);
		}
		
		$('.prayer-request-char-counter-number').text(140 - inputValue.length);
	});

	
	// Adds Click Event to Reset form.
	$('#prayer-request-reset').bind('click',function() {
		reset_prayer_request_form();
	});

	// Adds Click Event to 'Prayer Request' radio button. Resets Textarea to show default text.
	$('.prayer-request-select-1').bind('click',function() {
		$prayer_request_textarea.val(prayer_request_textarea_text);
		reset_char_counter();		
	});
	
	// Adds Click Event to 'Praise Report' radio button. Resets Textarea to show default text.
	$('.prayer-request-select-2').bind('click',function() {
		$prayer_request_textarea.val(praise_report_textarea_text);
		reset_char_counter();		
	});
	
	
	/***********************************************************************
	 * Generic Form Validator
	 **********************************************************************/
	
	// Get Form ID
	var formid = $('#contact-form-container').attr('class');

	// jQuery Validator Plugin to Validate 'Get Involved' Form on Ministry Pages
	var validator_main_form = $("form#contact-form").validate({ 
	rules: { 
		email: { 
            required: true, 
            email: true
        }
	}, 

	debug:true,

	// the errorPlacement has to take the table layout into account 
	invalidHandler: function(e, validator_main_form) {
				
		var errors = validator_main_form.numberOfInvalids();

		if (errors) {
			var message = errors == 1
				? 'You missed 1 field. It has been highlighted below'
				: 'You missed ' + errors + ' fields.  They have been highlighted below';
			var message = '<p class=ErrorMessage style=width:588px;>' + message + '<\/p>';
			$("." + formid + " div.validate_error_message").html(message);
			$("." + formid + " div.validate_error_message").show();
		} else {
			$("." + formid + " div.validate_error_message").hide();
		}
	},

	// specifying a submitHandler prevents the default submit, good for the demo 
	submitHandler: function(e, validator_main_form) { 
		$("." + formid + " div.validate_error_message").html('');
		// Build JS Object of all Custom Fields
		var custom_fields = {};
		
		$('form#contact-form .custom-field').each(function(index) {
			var field = $(this);
			var	field_name,
				field_rel,
				field_value;
			
			field_name 	= $(field).attr('name');
			field_rel 	= $(field).attr('rel');
			field_value = $(field).attr('value');
			
			// If field is Checkbox, do special stuff.
			if ($(field).is(':checkbox')) {
				if ($(field).is(':checked')) {
					field_value = 'Yes';
				} else {
					field_value = '';
				}
			}
			
			custom_fields[field_name] = { 
				name: field_name,
				rel: field_rel,
				value: field_value
			} 
		})
				
		// Build a JS Object of all Normal Fields
		var normal_fields = $('form#contact-form *:not(.custom-field)').serializeArray();
		
		// Combine Custom Fields Object and Normal Fields object into one big object
		var all_fields = { normal_fields: normal_fields, custom_fields: custom_fields, recaptcha_challenge_field: $('#recaptcha_challenge_field').val(), recaptcha_response_field: $('#recaptcha_response_field').val() }
		
		$.ajax({
			type: "POST",
			url: "../includes/form-submit.php",
			dataType: "html",
			data: all_fields,
			success: function(data) {
				$("." + formid + " div.form_confirm").html(data);
				if ( data.indexOf( "SuccessMessage" ) !== -1 ) {

					$("." + formid + " div.validate_error_message").hide();
					
					$("." + formid + " #mainform_holder").html("");
					window.scrollTo(0, $('a[name="formtop"]').offset().top);

				} else if (data.indexOf("CAPTCHA") !== -1){
					Recaptcha.reload();
					window.scrollTo(0, $('a[name="formtop"]').offset().top);
				}
			}

		});
		
	}, 
	// set this class to error_labels to indicate valid fields 
	success: function(label) { 
		// set as text for IE 
		label.html(" ").addClass("checked"); 
	} 
	}); 
	

});

