$(document).ready(function(){
	var postType 			= '';
	var pageDepth 			= 1;
	var IPrayedForID		= 0;
	var prayerGenerator		= 'COMPUTER';
	var emailGenerator		= 'COMPUTER';
	var scheme				= $("#page-scheme").html();
	var prayerFormOptions = { 
	        					target:        '#overlay-page-msg',   // target element(s) to be updated with server response 
		        				beforeSubmit:  showRequest,  // pre-submit callback 
		        				success:       showResponse,  // post-submit callback 
								type: 		   'POST'
								// other available options: 
		        				//url:       url         // override for form's 'action' attribute 
		        				//type:      type        // 'get' or 'post', override for form's 'method' attribute 
		        				//dataType:  null        // 'xml', 'script', or 'json' (expected server response type) 
		        				//clearForm: true        // clear all form fields after successful submit 
		        				//resetForm: true        // reset the form after successful submit 
							
		        				// $.ajax options can be used here too, for example: 
		        				//timeout:   3000 
	    					};
	//BIND FORMS
	$("#loading").ajaxStart(function(){
	   $(this).show();
	 });
	$("#loading").ajaxStop(function(){
	      $(this).hide();
	      placeOverlayedPage();
	});
	$('#prayerForm').ajaxForm(prayerFormOptions); 
	$('.prayedForForms').ajaxForm(prayerFormOptions); 
	// BTN ROLLOVERS
	$("img[type='btn'], input#submit, input.iPrayedSubmit").mouseover(function(){
		var id = this.id;
		switchImageSource(this.id);
		$("#"+id).css({
			"cursor":"pointer"
		});
	});
	$("img[type='btn'], input#submit, input.iPrayedSubmit").mouseout(function(){
		switchImageSource(this.id);
	});
	$("input.iPrayedSubmit").mouseup(function(){
		switchAndClearImageSource(this.id, 'Images/'+scheme+'/Graphics/Utility/btn-clicked-prayedFor.gif');
		IPrayedForID = this.id;		
	});
	//BACK BTN
	$("#btn-back").mouseup(function(){
		var currentPageID;
		var destinationPageID;
		
		if(pageDepth == 1){
			currentPageID = "page1";
			destinationPageID = "page1";
			switchPage(currentPageID, destinationPageID);
			pageDepth = 1;
			$("#btn-back").css({
				"display":"none"
			});
		}else if(pageDepth == 2){
			currentPageID = "page2";
			destinationPageID = "page1";
			switchPage(currentPageID, destinationPageID);
			pageDepth = 1;
			$("#btn-back").css({
				"display":"none"
			});
		}else if(pageDepth == 3 && postType == 'anonymous'){
			currentPageID = "page3";
			destinationPageID = "page1";			
			switchPage(currentPageID, destinationPageID);
			pageDepth = 1;
			$("#btn-back").css({
				"display":"none"
			});
		}else if(pageDepth == 3 && postType == 'semianonymous'){
			currentPageID = "page3";
			destinationPageID = "page2";
			switchPage(currentPageID, destinationPageID);
			pageDepth = 2;
		}
	});	
	//GENERAL CLICK FUNCTIONS
	$("input[type='checkbox']").click(function(){
		var state = $("input:checkbox:checked").val();
		var id = this.id;
		if(state == 'Y'){//selected
			$('input[id=email]').attr({value: 'Enter your email here...'});
			$("#email-div").slideDown(300);
			emailGenerator = 'COMPUTER';
		}else{//not selected
			$("#email-div").slideUp(300);
			$('input[id=email]').attr({value: ''});
		}
	});
	$("input#submit").mouseup(function(){
		var pageInfo = "";
		var pageTitle = "Prayer Report";
		var currentPageID 		= 'page3';
		var destinationPageID 	= 'page1';		
		$("#overlay-page-title").html(pageTitle);
		displayPageOverlay();	
	});
	$("a#link-one").mouseup(function(){
		$("#overlay-page-title").html('');
		$("#overlay-page-msg").html('');
		$("#overlay-page-title").load("linkOne.php?content=title");
		$("#overlay-page-msg").load("linkOne.php?content=pageContent");
		displayPageOverlay();
	});
	$("a#our-sponsors-link").mouseup(function(){
		$("#overlay-page-title").html('');
		$("#overlay-page-msg").html('');
		$("#overlay-page-title").load("sponsor-list.php?content=title");
		$("#overlay-page-msg").load("sponsor-list.php?content=pageContent");
		displayPageOverlay();
	});
	$("a#link-two").mouseup(function(){
		$("#overlay-page-title").html('');
		$("#overlay-page-msg").html('');
		$("#overlay-page-title").load("linkTwo.php?content=title");
		$("#overlay-page-msg").load("linkTwo.php?content=pageContent");
		displayPageOverlay();
	});
	$("textarea#prayer").focus(function(){
		if(prayerGenerator =='COMPUTER'){
			setPrayerBox('');
			prayerGenerator = 'HUMAN';
		}
	});
	$("#prayerForm #email").focus(function(){
		if(emailGenerator =='COMPUTER'){
			$("#prayerForm #email").attr({value: ''});		
			emailGenerator = 'HUMAN';
		}
	});
	$(".iPrayedSubmit").mouseup(function(){
		var id 			= this.id;
		var count 		= "";
		var finalCount 	= "";
		id 				= $("#"+id).attr("id");
		count 			= $("#"+id+"-read-count-tokens h1").text();
		count 			= Number(count);
		finalCount 		= count+1;
		if(finalCount == 1){
			$("#"+id+"-persons-tag").attr('src','Images/'+scheme+'/Graphics/Utility/tag-person.gif');
			$("#"+id+"-read-count").fadeIn();
		}else if(finalCount == 2){
			$("#"+id+"-persons-tag").attr('src','Images/'+scheme+'/Graphics/Utility/tag-people.gif');
		}
		$("#"+id+"-read-count-tokens h1").text(finalCount);			

	});
	// BTN CLICK FUNCTIONS -- PAGE 1
	$("#btn-semi-anonymously").mouseup(function(){
		if(prayerGenerator=='COMPUTER'){
			setPrayerBox('Click here to begin!\r\rFor easy reading we convert CAPITAL LETTERS to lowercase.\r-God Bless');
		}
		currentPageID 		= 'page1';
		destinationPageID 	= 'page2';
		switchPage(currentPageID, destinationPageID);
		postType = 'semianonymous';
		pageDepth = 2
		$("#btn-back").css({
			"display":"block"
		});
	});
	$("#btn-anonymously").mouseup(function(){
		clearFormElements();
		if(prayerGenerator=='COMPUTER'){
			setPrayerBox('Click here to begin!\r\rFor easy reading we convert CAPITAL LETTERS to lowercase.\r-God Bless');
		}
		currentPageID 		= 'page1';
		destinationPageID 	= 'page3';
		switchPage(currentPageID, destinationPageID);
		postType = 'anonymous';
		pageDepth = 3
		$("#btn-back").css({
			"display":"block"
		});		
	});
	$("#overlay-page-close-btn, #overlay-page-close-top").mouseup(function(){hideOverlayedPage();});
	// BTN CLICK FUNCTIONS -- PAGE 2
	$("#btn-start-my-prayer").mouseup(function(){
		currentPageID 		= 'page2';
		destinationPageID 	= 'page3';
		switchPage(currentPageID, destinationPageID);
		pageDepth = 3
	//	alert(prayerGenerator);
	});
	// BTN CLICK FUNCTIONS -- PAGE 3
	// GENERAL FUNCTIONS
	function setPrayerBox(value){
		$("#prayerForm #prayer").clearFields();
		$("#prayerForm #prayer").val(value);
	}
	function switchImageSource(id){
		var currentSource 	= "";
		var newSource	 	= "";
		currentSource 		= $("#"+id).attr("src");
		newSource			= $("#"+id).attr("longdesc");
		$("#"+id).attr({src: newSource});
		$("#"+id).attr({longdesc: currentSource});
	}
	function switchAndClearImageSource(id, source){
		var currentSource 	= "";
		var newSource	 	= "";
	//	currentSource 		= $("#"+id).attr("src");
	//	newSource			= $("#"+id).attr(source);
		$("#"+id).attr({src: source});
		$("#"+id).attr({longdesc: source});
	}
	function switchPage(currentPageID, destinationPageID){
		$("#"+currentPageID).fadeOut(300);
		setTimeout(function () {showPage(destinationPageID)},300);
	}
	function showPage(pageToShowID){
		$("#"+pageToShowID).fadeIn(300);
	}
	function clearFormElements(ele) {
		$("#prayerForm #name,#prayerForm #region,#prayerForm #city").clearFields();
		$("#prayerForm #country").val('XX');
	    // $(ele).find(':input').each(function() {
	    //     switch(this.type) {
	    //         case 'password':
	    //         case 'select-multiple':
	    //         case 'select-one':
	    // 						$(this).val('XX');
	    // 						break;
	    //         case 'text':
	    //        // case 'textarea':
	    //             $(this).val('');
	    //             break;
	    //         case 'checkbox':
	    //         case 'radio':
	    //             this.checked = false;
	    //     }
	    // });
	}
	// pre-submit callback 
	function showRequest(formData, jqForm, prayerFormOptions){ 
	    // formData is an array; here we use $.param to convert it to a string to display it 
	    // but the form plugin does this for you automatically when it submits the data 
	    // var queryString = $.param(formData); 
		$("#overlay-page-title").html('Prayer Report');
		$("#overlay-page-msg").html('');
	    // jqForm is a jQuery object encapsulating the form element.  To access the 
	    // DOM element for the form do this: 
	    // var formElement = jqForm[0]; 

	    // alert('About to submit: \n\n' + queryString); 

	    // here we could return false to prevent the form from being submitted; 
	    // returning anything other than false will allow the form submit to continue 
	    return true; 
	} 
	// post-submit callback 
	function showResponse(responseText, statusText){ 
		$("#"+IPrayedForID).attr({disabled: 'disabled'});
		$("#"+IPrayedForID).css('cursor', 'default');
	// for normal html responses, the first argument to the success callback 
	    // is the XMLHttpRequest object's responseText property 

	    // if the ajaxForm method was passed an Options Object with the dataType 
	    // property set to 'xml' then the first argument to the success callback 
	    // is the XMLHttpRequest object's responseXML property 

	    // if the ajaxForm method was passed an Options Object with the dataType 
	    // property set to 'json' then the first argument to the success callback 
	    // is the json data object returned by the server 

	//    alert('status: ' + statusText + '\n\nresponseText: \n' + responseText + 
	 //       '\n\nThe output div should have already been updated with the responseText.'); 
	}
	//ALERT FUNCTIONS
	function displayPageOverlay(){
			$("#overlay-page").fadeIn(200,displayOverlayedPage);
	//		$("body").css('overflow','hidden');	//this hides the scroll bar
	}
	function displayOverlayedPage(){
			placeOverlayedPage();	
			$("#overlay-page-window").fadeIn('200')
	}
	function placeOverlayedPage(){
			windowDimArray = new Array();
			divDimArray = new Array();
			windowId = 'overlay-page-window';

			windowDimArray = getWindowDimensions();
			divDimArray = getObjectDimensions(windowId);
			offsetArray = getOffset(windowDimArray, divDimArray);
			setOverlayPageOffset(offsetArray, windowId);
	}
	function hideOverlayedPage(){
			$("#overlay-page-window").fadeOut('100', hidePageOverlayBackground);	
	}
	function hidePageOverlayBackground(){
			$("#overlay-page").fadeOut(200);
		//	$('body').css('overflow','auto');//this shows the scroll bar again
	}
	function getObjectDimensions(object_id){
			var dimensions;
			dimensions = new Array();

			dimensions['x'] = $("#"+object_id).width();
			dimensions['y'] = $("#"+object_id).height(); //  The Height of the "screen" differs depending on browsers. so we can't calculate the screen placement
			return dimensions;	
	}
	function getWindowDimensions(){
			var dimensions;
			windowDimensions = new Array();

			windowDimensions['x'] = $(window).width();
			windowDimensions['y'] = $(window).height(); //  The Height of the "screen" differs depending on browsers. so we can't calculate the screen placement
			return windowDimensions;	
	}
	function getOffset(windowArray, divArray){
			var windowX;
			var windowY;
			var divX;
			var divY;
			var offset = new Array();

			windowX = windowArray['x'];
			windowY = windowArray['y'];
			divX = divArray['x'];
			divY = divArray['y'];
			offset['left'] = ((windowX/2)-(divX/2));
			offset['top'] = ((windowY/2)-(divY/2));
			if(divY >= (windowY/2)){
				$('#overlay-page').css('position', 'absolute');
				offset['top']=30;
				offset['left']=offset['left']/3;
				return offset;

			}else{
				$('#overlay-page').css('position', 'fixed');
				return offset;

			}
	}
	function setOverlayPageOffset(offsetArray, windowId){
			var browser	= $.browser.name;
			var offsetLeft	= "";
			var offsetTop	= "";
			offsetLeft 		= offsetArray['left'];
			offsetTop 		= offsetArray['top'];
			$('#'+windowId).css('left', offsetLeft);
			$('#'+windowId).css('top', offsetTop);
			if(browser	== 'safari'){
				javascript:window.resizeBy(.5,0);//SAFARI FIX -- else the slider will not display the second time
			}	
			checkForPrayerSuccess();					
	}
	function checkForPrayerSuccess(){
		var currentPageID 		= 'page3';
		var destinationPageID 	= 'page1';
		var success;
		var successMsg			= 'If you have another prayer, feel free to post again.';
		
		success = $("#ajax-result-status").html();
	//	alert(success);
		if(success =='TRUE'){
				setPrayerBox(successMsg);
				prayerGenerator = 'COMPUTER';
				emailGenerator = 'COMPUTER';
		}
	}
	function showBanner(){
		$('#prayer-banner').animate( { top:"106px" }, 900 );
		setTimeout(function(){hideBanner()},4000);
	}
	function hideBanner(){
		$('#prayer-banner').animate( { top:"140px" }, 1000 );
	}
	function preloadImages(){
		var cache = [];
    	var args_len = arguments.length;
	    for (var i = args_len; i--;) {
	          var cacheImage = document.createElement('img');
	          cacheImage.src = arguments[i];
	          cache.push(cacheImage);
	        }
  	}
  	preloadImages(
   						'Images/'+scheme+'/Graphics/Utility/btn-over-anonymously.gif', 
   						'Images/'+scheme+'/Graphics/Utility/btn-over-iPrayedForThis.gif',
   						'Images/'+scheme+'/Graphics/Utility/btn-over-semiAnonymously.gif',
   						'Images/'+scheme+'/Graphics/Utility/btn-over-startMyPrayer.gif',
   						'Images/'+scheme+'/Graphics/Utility/btn-over-submitPrayer.gif',
   						'Images/'+scheme+'/Graphics/Utility/btn-clicked-prayedFor.gif'					
   						);
  	setTimeout(function(){showBanner()},2000);
});



