/* *********************** */
/*        GLOBAL		   */      
/* *********************** */ 

var global = function() {
	
	return {
	
		init : function (){
			global.initNavigation();
			global.initButtons();
			
			$("#searchForm #firstName").val("First name");
			$("#searchForm #quiltName").val("Quilt name");
			$("#searchForm input.text").addClass("labelized");
			
			$("#searchForm input.text").click(function(){
				
				if ($(this).val() == "First name" || $(this).val() == "Quilt name"){
					$(this).val("");
					$(this).removeClass("labelized");
				}
			});
			
			$("body").addClass("tocBody");
		},
		
		initButtons : function () {
			
			var spanLeft = "<span class='btn-left' />";
			var spanRight = "<span class='btn-right' />";
			
			$('.btn').each(function(){
				
				$(this).prepend(spanLeft);
				$(this).append(spanRight);
				
			});
			
			$("div#searchForm span.btn-submit span").click(function(){
				$("#searchForm input.text").each(function(){
					if ($(this).val() == "First name" || $(this).val() == "Quilt name"){
						$(this).val("");
					}
				});	
			
				if($(this).parents("form")[0].city)
				{
					trackPage('/'+localePath+'/helpingkids/quilt-stories/click-advanced-find');
				}
				else
				{
					trackPage('/'+localePath+'/helpingkids/quilt-stories/click-find-quilt');
				}
			
				$(this).parents("form")[0].submit();	
			});
			
			$('.btn-submit input').remove();
			$('div#footer a').addClass('toc-footer');
		},
				
		initNavigation : function () {	
			if ($("#home").length > 0)
				$("#nav_home").attr("src", "/images/"+localePath+"/helpingkids/home_on.png");
			if ($("#about").length > 0)
				$("#nav_about").attr("src", "/images/"+localePath+"/helpingkids/about_on.png");
			if ($("#help").length > 0)
				$("#nav_help").attr("src", "/images/"+localePath+"/helpingkids/help_on.png");
			if ($("#storyIndex").length > 0 || $("#storyDetail").length > 0 || $("#quiltRegistration").length > 0)
				$("#nav_stories").attr("src", "/images/"+localePath+"/helpingkids/stories_on.png");
			
			$("div.toc-top-header ul img").hover(
				function () {	
					if ($(this).attr("src").indexOf("_on") == -1)
						$(this).attr("src", "/images/"+localePath+"/helpingkids/" + $(this).attr("id").substring(4) + "_over.png");
				}, 
				function () {
					if ($(this).attr("src").indexOf("_on") == -1)
						$(this).attr("src", "/images/"+localePath+"/helpingkids/" + $(this).attr("id").substring(4) + "_off.png");
				}
		    );
		},
		
		resizeAvatar : function () {
			
			var to = setTimeout(function(){
				
				var containerWidth = $("div.quilt-entry-avatar div:first").width();
				
				$("img.quilt-image").each(function () {
					
					var w = this.width;
					var h = this.height;
					var offset;
					
					if (w > h){
						if (w > containerWidth){
							
							$(this).attr("height","210");
							
							w = this.width;
							h = this.height;
							
							if (w > containerWidth){
								offset = (w - containerWidth)/2;
								$(this).css("left","-"+offset+"px");
							}	
							
							$(this).css("top","24px");
						}
					}	
					else {
						if (h > containerWidth){
							
							$(this).attr("width","230");
							
							w = this.width;
							h = this.height;
							
							if (h > containerWidth){
								// add 17px to give preference to the top of the photo,
								// since that's where people's heads tend to be.
								offset = ((h - containerWidth)/2)-17;
								$(this).css("top",offset+"px");
							}	
							
							$(this).css("left","30px");
						}
					}
					
					$(this).css("visibility","visible");
						
				});
			},1000);
		}	
	};
}();


/* *********************** */
/*        HOMEPAGE		   */      
/* *********************** */ 

var home = function() {
	
	return {
	
		init : function (){
		
			var flashvars = {};
			
			flashvars.configPath = "/media/flash/helpingkids/home/xml/en-US/config.xml";
			flashvars.XMLPath = "/"+localePath+"/xml/tocHomeLanding/toc-home.jspx";
			flashvars.StoryUrl = "/"+localePath+"/helpingkids/story/quilt-";
			
			var params = {};
			params.allowScriptAccess="always";
			params.wmode="transparent";
	
			var attributes = {};
			swfobject.embedSWF("/media/flash/helpingkids/home/downyTOC.swf", "flashContent", "700", "425", "9.0.28.0", "/media/flash/expressInstall.swf",  flashvars, params, attributes);
						
		},
		
		expandModule : function (){
			$("div#centerCol").css("width","631px");
		},
		
		contractModule : function (){
			$("div#centerCol").css("width","345px");
		}
	};
}();


/* *********************** */
/*        ABOUT  		   */      
/* *********************** */


var about = function() {
	
	return {
	
		init : function (){
			
			
		}
	};
}();


/* *********************** */
/*        HELP  		   */      
/* *********************** */

var help = function() {
	
	return {
	
		init : function (){
			
			
		}
	};
}();


/* *********************** */
/*        STORY INDEX  	   */      
/* *********************** */

var storyIndex = function() {
	
	return {
	
		init : function (){
			global.resizeAvatar();
		}
	};
}();

/* *********************** */
/*   STORY/COMMENT FORM     */      
/* *********************** */

var tocForm = function() {
	
	// private members
	var type;
	var photoLimit = 6;
	var avatarSelected = false;
	var confirmSubmit = false;
	var underAge = false;
	var count = 1;
	var submitFlag = false;
		
	return {
		
		/* 
		 * FUNCTION: controller
		 * ROLE: Processes and responds to form events, typically user clicks, 
		 * and invokes changes on the model and sets the view.
		 * */
				
		controller : {
		
			init : function () {
		
				if (submitFlag == false){
		
				type = $("#storyDetail").length > 0 ? "comment" : "story"; 
		
				if (tocForm.model.cookieCheck())
					tocForm.view.step1();
				else 
					tocForm.view.underAge();
				}
				else {
					//user has already submitted a comment. 
					// force a page refresh to release the form event bindings. */
					document.location = "/"+localePath+"/helpingkids/story/quilt-"+storyId+".jspx?reload"
				}	
			},
		
			processStep1 : function () {
				
				tocForm.model.validate.fields("reg-step-1");
				tocForm.model.validate.age();
				
				if (underAge == false){
					if ($("div.error").length > 0){
						tocForm.view.formError();
					}
					else {
						tocForm.view.step2();
						tocForm.model.bindSubmission();
						tocForm.model.bindUpload();
						if(type)
						{
							if(type == "story")
							{
								trackPage('/'+localePath+'/helpingkids/quilt-stories/register/start-quilt');
								trackSpotlight('type=downy355;cat=downy109;ord=1');							
							}		
							else
							{
								trackPage('/'+localePath+'/helpingkids/quilt-stories/entry/start-entry');
								trackSpotlight('type=downy355;cat=downy106;ord=1');
							}

						}				
					}
				}	
			},
		
			processStep2 : function (event) {
				
				tocForm.model.validate.fields("reg-step-2");
				tocForm.model.validate.avatar();
				
				if ($("div.error").length > 0){
					tocForm.view.formError();
					return false;
				}	
			},
			
			handleResponse : function (data) {
				
				if (data.success) 
					tocForm.view.comment.submitSucess(data);
				else 
					tocForm.view.comment.submitFailure(data);
			},
			
			removeImage : function (delKey) {
				tocForm.model.removeImage(delKey);
			}	
			
		},
		
		/* 
		 * FUNCTION: model
		 * ROLE: The domain-specific representation of the information 
		 * on which the form operates. The model handles activies such as
		 *   1. form validation
		 *   2. ajax requests
		 *   3. data/object manipulation
		 *   4. event bindings
		 * */
		
		model : {
		
			cookieCheck : function () {
			
				debugger;
			
				downyTOC = getCookie('downyTOC');
				
				if (downyTOC == "underage") 
					return false;
				else 
					return true;
			},
			
			validate : {
				
				fields : function (step){
				
					$("div.error").removeClass("error");
					$("span.err-msg").remove();
										
					$('#'+step+' .required input.text, #'+step+' .required textarea').each(function(){
						if ($.trim($(this).val()) == "")
							$(this).parents("div:first").addClass("error");
					});
					
					$('#'+step+' .required select').each(function(){
						if ($(this).val() == "")
							$(this).parents("div:first").addClass("error");
					});	
					
					$('#'+step+' .required input:checkbox').each(function(){
						if (!$(this).is(":checked"))
							$(this).parents("div:first").addClass("error");
					});	
					
					$('#'+step+' #email').each(function(){
						
						var filter=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i ;
						
						if (!filter.test($(this).val()))
							$(this).parents("div:first").addClass("error");
					});	
				},
				
				age : function (){
					
					if ($("div.error").length == 0){
					
						// check if user is 18
						var currentDate = new Date();
						var nowDay = currentDate.getDate();
						var nowMonth = currentDate.getMonth() + 1;
						var nowYear = currentDate.getFullYear();
						
						var enteredYear = $("#year").val();
						var enteredMonth = $("#month").val();
						var enteredDay = $("#day").val();
						
						//TODO: reverse below conditional
						if ((enteredYear < nowYear - 18) || ((enteredYear == nowYear - 18) && (enteredMonth < nowMonth)) || ((enteredYear == nowYear - 18) && (enteredMonth == nowMonth) && (enteredDay <= nowDay))) {
							// Age check passed
							
						} else {
							// User too young to continue
							underAge = true; 
							setCookie("downyTOC", "underage", 30);
							tocForm.controller.init();
						}
					}	
				},
				
				avatar : function () {
					
					if (avatarSelected == false && type == "story"){
						$("div.choose-file").addClass("error");
					}
				},
				
				checkMaxLength : function (strID) {
					intCount = $("#"+strID).val().length;
				  	intMax = 2000;
				  	strID = "#"+strID+"Counter";
				  	$(strID).text(parseInt(intMax) - parseInt(intCount));
				  	if (intCount < (intMax * .8)) {$(strID).css("color", "#006600"); } //good
				  	if (intCount > (intMax * .8)) { $(strID).css("color", "#FF9933"); } //warning at 80%
				  	if (intCount > (intMax)) { 
				  		$(strID).text(0).css("color", "#990000");
				  		$("textarea.checkMax").val($("textarea.checkMax")[0].value.substring(0,intMax));
				  	}
				}
				
			},
			
			bindUpload : function (){
				
				var formAction = "/" + localePath + "/loadQuiltImage.do";
				if (type == "comment") 
					formAction += "?imgType=comment&imgCount=" + count;
				
				// TODO: ideally these 2 lines of DOM manipulation should go into the view 
				$(".choose-file .btn").empty();
				$(".choose-file .btn").append("<span class='btn-left'/><span class='file-upload' id='upload"+count+"'>Add A Photo</span><span class='btn-right'/>");
				
				$("#upload"+count).upload({
				
					name: 'fileUploaded',
					method: 'post',
					enctype: 'multipart/form-data',
					action: formAction,
					onSubmit: function() {
						//alert ('formAction = ' + formAction);
						
						if (type == "story")
						{
							trackPage('/'+localePath+'/helpingkids/quilt-stories/register/click-upload-start');
							tocForm.view.story.imageLoadStart();
						}
						else
						{
							trackPage('/'+localePath+'/helpingkids/quilt-stories/entry/click-upload-start');
							tocForm.view.comment.imageLoadStart();
						}
					},
					onComplete: function(data) {
						var json = eval("(" + data + ")");								
						if (json.success){
							tocForm.model.loadImage();
							avatarSelected = true;
							if(type)
							{
								if(type && type == "story")
								{
									trackPage('/'+localePath+'/helpingkids/quilt-stories/register/click-upload-complete');
								}
								else
								{
									trackPage('/'+localePath+'/helpingkids/quilt-stories/entry/click-upload-complete');
								}
							}
						}
						else { 
							$('span#uploadProgress').removeClass('loading').addClass('uploadError').html(json.errorDescriptor)
						}	
					}
				});
			},
			
			bindSubmission : function () {
								
				/* 'ajax-ify the comment form' */
				if (type == "comment"){
					
					$('form#tocForm').ajaxForm({
						beforeSubmit: tocForm.controller.processStep2,
						url: '/'+localePath+'/createComment.do?sessionId='+sessionId,
						dataType: 'json',
						type: 'post',
						success: tocForm.controller.handleResponse
					});
					
				    $('form#tocForm2').submit(function() { 
				        $(this).ajaxSubmit(options); 
				        return false; 
				    }); 
				}
				else {
					
					// catch the form submit event
					$("form#tocForm").submit(function(event) { 
						
						// ensure submit is intentional 
						if (confirmSubmit != true){
							event.preventDefault();
							return false;
						}
						else {
							tocForm.controller.processStep2(event);
							
							if ($("div.error").length > 0){
								if (type == "story")
									event.preventDefault();
						}	
						}	
					});
				}	
			},
			
			loadImage : function () {
				
				var n = Math.floor(Math.random() * 1000 + 1);
				var imgSrc = "/" + localePath + "/getQuiltImage.do?imgType=";
				imgSrc += type == "story" ? "story&run=" + n : "comment&imgCount=" + count + "&run=" + n;
				 				
				var img = new Image();				
				$(img).load(function () {
					
					if (type == "story")
						tocForm.view.story.imageLoadEnd(this);
					else 
						tocForm.view.comment.imageLoadEnd(this);
					
					count++;
					
					tocForm.model.bindUpload();
						
				}).attr("src",imgSrc).hide().fadeIn(1000, 
				function () {
					$('span#uploadProgress').removeClass("loading");
				});
			},
			
			removeImage : function (delKey) {
				
				var n = delKey.split("delete-img-")[1];
				$.get("/"+localePath+"/removeImageFromCache.do?imgCount="+n);
				$("#uploaded-photo-"+n).remove();
				$('div#addPhoto span.btn').show();
				$('span#uploadMaxMsg').hide();
			},
			
			flagStory : function (item) {
			
				var id = item.split("item")[1];
				var dataString = 'storyId=' + id;
				$.ajax({  
			    	type: "POST",  
			    	url: "/" + localePath + "/flagStory.do",  
			    	data: dataString,  
			    	success: function() {
			    	    trackPage('/'+localePath+'/helpingkids/click-flag-abuse');
						$("#"+item).html('This story has been flagged for the Administrator');
			    	}  
			    });
			},
			
			flagComment : function (item) {
				
				var id = item.split("comment")[1];
				var dataString = 'commentId=' + id;
				$.ajax({  
			    	type: "POST",  
			    	url: "/" + localePath + "/flagComment.do",  
			    	data: dataString,  
			    	success: function() {  
						$("#"+item).html('This comment has been flagged for the Administrator');
			    	}  
			    });
			}	
		},	
		
		/* 
		 * FUNCTION: view
		 * ROLE: Renders the view, manipulates DOM elements
		 * */
		
		view : {

			step1 : function () {
				$("#commentForm").show();
				$("form#tocForm")[0].reset();
				$("#reg-underAge").hide();
				$("#reg-step-1").show();
				$("#reg-step-2").hide();
				$("#reg-step-3").hide();
			
				$("#btn-next").click(function(){
					tocForm.controller.processStep1();
				});
			},
			
			step2 : function () {
				
				$("#reg-underAge").hide();
				$("#reg-step-1, #step1-copy").hide();
				$("#reg-step-2").show();
				$("#reg-step-3").hide();
				$("#addPhoto").show();
												
				$("span#btnSubmitStory").click(function(){
					
					if(type)
					{
						if (type == "story")
						{
							trackPage('/'+localePath+'/helpingkids/quilt-stories/register/click-submit-quilt');
						}
						else
						{
							trackPage('/'+localePath+'/helpingkids/quilt-stories/entry/click-submit-entry');
						}
					}
					confirmSubmit = true;
					$("form#tocForm").submit();
				});
								
				$("div.avatar-selection input").click(function(){
					avatarSelected = true;
					$('#photo-set').hide();
				});
				
				$("textarea.checkMax").bind("click mouseover keyup change", function(){
					tocForm.model.validate.checkMaxLength(this.id); 
				} );
				
				$("textarea.checkMax").each(function(i){
					if ($("#ctr").length == 0)
						$(this).after("<div id='ctr'>Please type your story in the space above. 2000 characters maximum. <span id='"+this.id+"Counter'>2000</span> characters remaining</div>");
				});
			},
						
			underAge : function () {
				
				$("#reg-underAge").show();
				$("#reg-underAge").addClass("error");
				$("#reg-step-1").hide();
				$("#reg-step-2").hide();
			},
			
			formError : function () {
				
				if ($("span.err-msg").length == 0)
					$(".form-Submit").after("<span class='err-msg'>Please correct the errors above.</span>");
			},	
			
			story : {
				
				imageLoadStart : function () {
					$(".avatar-selection input").attr('checked', false);
					$('#photo-set img').remove();
					$('#photo-set').show();
					$('span#uploadProgress').removeClass("uploadError").empty().addClass("loading");
					$('#photo-set span').remove();
				},
				
				imageLoadEnd : function (img) {
					
					$('#photo-set').append(img);
					
					var w = img.width;
					var h = img.height;
					
					var aspectRatio;
					
					if (w > h){
						aspectRatio = 140/w;
						$(img).css("width","140px");
						$(img).css("height",aspectRatio*h+"px");
					}	
					else { 
						aspectRatio = 140/h;
						$(img).css("height","140px");
						$(img).css("width",aspectRatio*w+"px");
					}
					$('span#uploadProgress').removeClass("loading")
				}
			},
						
			comment : {
				
				imageLoadStart : function () {
				
					$('span#uploadMaxMsg').hide();
					$('span#uploadProgress').removeClass("uploadError").empty().addClass("loading");
				},
				
				imageLoadEnd : function (img) {
					
					$('#photo-set span.uploaded-photo:last').append(img);
					$('#photo-set span.uploaded-photo:last').attr("id","uploaded-photo-"+count);
					
					tocForm.view.comment.imageResize(img);
					
					$(img).after("<span id='delete-img-"+count+"'>REMOVE</span>");
					
					$("#delete-img-"+count).click(function (){
						tocForm.controller.removeImage(this.id);
					});
			
					$('#photo-set span.uploaded-photo:last').show();
				
					// create a new, empty span and append it to the list for future use
					$('#photo-set span.uploaded-photo:last').after("<span class='uploaded-photo' />");
					
					$('span#uploadProgress').removeClass("loading")
					
					if ( $('#photo-set span.uploaded-photo img').length == photoLimit){
					
						// photo upload limit has been reached.
						var to = setTimeout(function(){
							$('div#addPhoto span.btn').hide();
							$('span#uploadMaxMsg').show();	
						},1000)
					}
				},	
				
				imageResize : function (img) {
					
					var w = img.width;
					var h = img.height;
					
					var aspectRatio = 100/h;
					$(img).attr("height","100");
					$(img).attr("width",aspectRatio*w);
					
				},				
				
				submitSucess : function (data) {
					
					$("#reg-step-2 #photo-set .uploaded-photo img").each(function(){
						
						var img = new Image();				
						var imgSrc = this.src;
						
						$(img).load(function () {
							$("#reg-step-3 .comment-images").append(img);
							tocForm.view.comment.imageResize(this);
						}).attr("src",imgSrc);
					})
					if(type)
					{
						if(type=="story")
						{
							trackPage('/'+localePath+'/helpingkids/quilt-stories/register/thank-you');
							trackSpotlight('type=downy355;cat=downy110;ord=1');
						}
						else
						{					
							trackPage('/'+localePath+'/helpingkids/quilt-stories/entry/thank-you');
							trackSpotlight('type=downy355;cat=downy107;ord=1');
						}
					}							
					
					$("form#tocForm")[0].reset();
					$("#reg-underAge").hide();
					$("#reg-step-1").hide();
					$("#reg-step-2").hide();
					$("#reg-step-3").show();
					$("#addPhoto").hide();
					
					$("#reg-step-3 h4").text(data.firstName);
					$("#reg-step-3 span.info").text(data.userType+" on "+data.strDateCreated);
					$("#reg-step-3 div.description").text(data.text);
					$("#reg-step-3 h4").text(data.firstName);
					$("#reg-step-3 h4").text(data.firstName);
					
					submitFlag = true;
				},
			
				submitFailure : function (data) {
					
					$("form#tocForm")[0].reset();
					$("#reg-underAge").hide();
					$("#reg-step-1").hide();
					$("#reg-step-2").hide();
					$("#reg-step-3").show();
					$("#addPhoto").hide();
					
					$("#reg-step-3 h4").text("ERROR: "+ data.errorDescriptor);
					
				}
			}	
		}	
	};
}();


/* ********************************* */
/*      REGISTRATION CONFIRTMATION   */      
/* ********************************* */

var quiltRegistrationConfirmation = function() {
	
	return {
	
		init : function (){

			global.resizeAvatar();
		
		}
	};
}();


/* *********************** */
/*      STORY DETAIL  	   */      
/* *********************** */

var storyDetail = function() {
	
	return {
	
		init : function (){
				
			global.resizeAvatar();
			
			$("#storyDetail .quilt-entry-content .btn").click(function(){
				tocForm.controller.init();
			});
			
			$(".comment-images img").each(function(){
				$(this).load(function () {
					$(this).show();
				}).attr('src', this.id)
			});
			
			if (window.location.href.indexOf("reload") > -1){
				tocForm.controller.init();
				window.location.hash="comment";
			}	
			
			$(".flagStory").click(function(){
				tocForm.model.flagStory(this.id);
				$(this).removeClass("notFlagged");
			});
			
			$(".flagComment").click(function(){
				tocForm.model.flagComment(this.id);
				$(this).removeClass("notFlagged");
			});
		}
	};
}();

/* *********************** */
/*      SEARCH RESULTS 	   */      
/* *********************** */

var searchResults = function() {
	
	return {
	
		init : function (){
		
			$("td.imageCell").click(function () {
			
				trackPage('/'+localePath+'/helpingkids/quilt-stories/results/click-select-story');
				window.location = this.id; 
			});
			
			/* load the thumbnail images via ajax - then resize them */
			$("td.imageCell span img").each(function(){
				$(this).load(function () {
					
					var w = this.width;
					var h = this.height;
					var offset;
					var containerWidth = 60;
					var aspectRatio;
					
					if (w > h){
		
						if (w > containerWidth){
	
							aspectRatio = 55/h;
							
							$(this).attr("height","55");
							$(this).attr("width",aspectRatio*w);
							
							var newW = aspectRatio*w;
							
							if (newW > containerWidth){
								offset = (newW - containerWidth)/2;
								$(this).css("left","-"+offset+"px");
							}	
							$(this).css("top","4px");
						}
					}	
					else {
			
						if (h > containerWidth){
							
							aspectRatio = 55/w;
							
							$(this).attr("width","55");
							$(this).attr("height",aspectRatio*h);
							
							var newH = aspectRatio*h;
							
							if (newH > containerWidth){
								offset = (newH - containerWidth)/2;
								$(this).css("top","-"+offset+"px");
							}	
							$(this).css("left","4px");
						}
					}
										
					$(this).show();
				}).attr('src', this.id)
			});
			
			/*
		
			$("img.customImg").each(function () {
				
				var w = this.width;
				var h = this.height;
				var offset;
				var containerWidth = 60;
				
				if (w > h){
					
					if (w > containerWidth){
						
						$(this).attr("height","50");
						
						w = this.width;
						h = this.height;
						
						if (w > containerWidth){
							offset = (w - containerWidth)/2;
							$(this).css("left","-"+offset+"px");
						}	
						
						$(this).css("top","12px");
					}
				}	
				else {
					if (h > containerWidth){
						
						$(this).attr("width","55");
						
						w = this.width;
						h = this.height;
						
						if (h > containerWidth){
							$(this).css("top","3px");
						}	
						
						$(this).css("left","7px");
					}
				}
				
				$(this).css("visibility","visible");
					
			});
			
			*/
		}
	};
}();

$(document).ready( function() {
	
	global.init();
	
	if ($("#home").length > 0) home.init();
	if ($("#about").length > 0) about.init();
	if ($("#help").length > 0) help.init();
	if ($("#storyIndex").length > 0) storyIndex.init(); 
	if ($("#storyDetail").length > 0) storyDetail.init();
	if ($("#quiltRegistration").length > 0) tocForm.controller.init();
	if ($("#quiltRegistrationConfirmation").length > 0) quiltRegistrationConfirmation.init();
	if ($("#searchResults").length > 0) searchResults.init();
	
});


	





