/*
** News.js
** Copyright Ronningen Design, LLC (http://www.websitesthatdostuff.com)
** Subcontracted to Substratal Code LLC (http://www.substratalcode.com)
** Tampered with by Way Short of Heaven (http://www.wayshortofheaven.com)
**
*/

$(document).ready(function() {
	// Set up the dialog:
   $("#modal").dialog({
		   autoOpen: false,
		   modal: false,
		   height: 446,
		   width: 238,
		   position: [600, 135],
		   close: function(event, ui) { closeDialog() },
		   dialogClass: 'newsModal'
	   });

	// Check the URL for /modal/ and fix the links if necessary:
	if(location.pathname.indexOf("/modal") != -1) {
		$('a[class!="associatedLink"]').attr('target', '_parent');
		var list = $('a[class^="associatedLink"]');
		list.removeAttr('target');

		$.each( list, function( intIndex, obj ){
				var link = $(obj);
				link.attr('href', link.attr('href')+"/modal");
			}
		);
	}


	// Needed for some positioning
	$("#ui-dialog-title-modal").after("<span class='readComments'>Comments on this photo</span>");
	$("#ui-dialog-title-modal").wrap(document.createElement("div")).addClass("phoHeadingWrapper");
	$("#ui-dialog-title-modal").closest("div").addClass("phoHeadingWrapper");

	// Set up close functions:
	$(".modalClose").click(function(){
		$('#modal').dialog('close');
		return false;
	});

	// Add the Back to Photos listener
	$(".backToPhotos").click(function(){
		// Close the dialog:
		$('#modal').dialog('close');
	});

	// Set up the Add Comment button.
	$("#modalAddCommentButton").click(function(){
		// hide the content:
		/*

		$("#modalReadingButtons").hide();
		$("#modalPostingButtons").show();
		$(".readComments").addClass("postAComment");
		$(".postAComment").removeClass("readComments");
		$("#modalLogin").show();
		*/
		$("#modalContent").hide();
		displayLogin();
		return false;
	});

	// Set up the login functions.
	$('.formLogInBtn.loginBtn').click(function() {
		// Get the current clicker's parent:
		var parent = $(this).parent().parent().parent();
		login(parent);

		return false;
	});

	// Set up the Add Comment functions
	$(".makeComment .postButton").click(function(){
		// Get the current clicker's parent:
		var parent = $(this).parent();

		// Check for empty comment body:
		var content = $(parent).find('.addCommentContent');

		if( $.trim(content.val()) == "" ) {
			// Display an error message with the validation engine:
			$.validationEngine.buildPrompt(parent,"Please enter a comment.","error");
			return false;
		}
		submitComment(parent);

		return false;
	});

	// Clear the validation prompts.
	$(".newsModal .addCommentContent").click(function() {
		$.validationEngine.closePrompt('.formError',true);
	});

	// Check for the login and submit:
	$(".loginBox .loginForm").keypress(function(e) {
		if(e.keyCode == 13) {
			// Cancel the normal event: 
			e.preventDefault();
			// Click the submit button:
			var form = $(e.target).closest('form').find('.loginBtn').click();
			return false;
		}
	});

	$("#modalLogin.modalLoginLink").click(function() {
		// Hide the comment box and show the login area:
		$("#modalLogin .addCommentBox").hide();
		$("#modalLogin .loginBox").show();
	});

	// Check the URL for a comment to scroll to:
	var commentID = $.getUrlVar('commentID');

	if(commentID != undefined) {
		// Scroll the body to the comment ID:
		setTimeout( function() {
				$.scrollTo( $('#comment-'+commentID), 800 );
			},
			500
		);
	}

	// Check to see if the user is logged in already:
	displayLogin();
	
	
	// Subscribe Box
	$('#subscribeInner input').focus(function() {
		$(this).css('background-position','0 -17px');
		
		return false;
	});
	
	$('#subscribeInner input').blur(function () {
         if(!$(this).val()) {
         	$(this).css('background-position','0 0');	
         }
    });
	
	/* assign column heights for the dotted borders (index view) */
	$('#news_index #content div.resizeMe').height($('#content').height() - 73);
	
	/* assign column heights for the dotted borders (single view) */
	$('#news #content div.resizeMe').height($('#content').height() -10);
});


/*
** Function to log the user in based on the ID passed in:
**
** param id: the ID of wrapper which holds the form to pull the login information from.
*/
function login(id) {
	var form = id.find("form.loginForm:first");
	var data = form.serialize();

	if(id.find(".formLogInBtn:first").hasClass("loginLoader"))
		return false;

	$.ajax({
		type: "POST",
		url: "/users/login/",
		data: data,
		dataType: "json",
		beforeSend: function() {
			id.find(".formLogInBtn:first").toggleClass("loginLoader");
		},
		complete: function() {
			id.find(".formLogInBtn").toggleClass("loginLoader");
		},
		success: function (response) {
			if (response.success == true) {

				updateLoggedInNotifications(response.data.html);

			} else {
				id.find(".loginError").html(response.data).show().animate({backgroundColor: "#c01a1a", color:"white"}, 500);
			}
		}
	});

}


/*
** Function to submit the comment from a user.
**
** param id: the ID of wrapper which holds the form to pull the login information from.
*/
function submitComment(parent) {
	// Get the data:
	var data = parent.serialize();

	var container = parent.parent().parent().parent();
	// console.log(container);
	$.ajax({
		type: "POST",
		url: "/comments/add/",
		data: data,
		dataType: "json",
		beforeSend: function() {
			$(".commentPost").toggleClass("loginLoader");
		},
		complete: function() {
			$(".commentPost").toggleClass("loginLoader");
		},
		success: function (response) {
			if (response.success == true) {
				// Get the parent content into the Show Comment screen.
				container.find('.commentReviewInnerContent').html( "\"" + container.find('.addCommentContent:first').val() + "\"" );
				// change slikscreen heading
				$(".readComments").addClass("commentSubmitted");
				// Hide the Add Comment screen.
				var addComment = container.find('.addCommentBox:first');
				addComment.hide();

				var commentReview = container.find('.commentReview:first');
				commentReview.show();

				container.find(".addCommentContent:first").val('');

				setTimeout( function() {
						commentReview.fadeOut();
						addComment.show();
					},
					5000
				);
			} else {
				$(".addCommentBox").hide();
				$(".loginBox").show();
				
				// Show the error.
				$(".loginError").html(response.data).show().animate({backgroundColor: "#c01a1a", color:"white"}, 500);
			}
		}
	});
}

/*
** Function to launch the comment dialog.
**
** param @id: the ID of wrapper which holds the form to pull the login information from.
** param @width: the distance from the left side to locate the modal.
** param @title: the title of the modal dialog.
*/
function showDialog(postID, mediaID, width, title){
	$("#modalContent").toggleClass('modalLoading');
	// Clear the content div:
	$("#modalContent").html("");
	// Clear the comment textarea:
	$("textarea.addCommentContent").val("");
	// Clear the title:
	$(".phoHeadingWrapper").hide();

	// Get the offset to position the modal.
	var offset = $("#replacedWrapper").offset();
	$("#modal").dialog('option', 'position', [ width-12, offset.top + 78]);
	// Show the dialog:
	$("#modal").dialog("open");

	$("#modalReadingButtons").show();
	$("#modalPostingButtons").hide();

	// Call the server to get info:
	$.ajax({
		method: "POST",
		url: "/comments/mediaComments/",
		data: "postID="+postID+"&mediaID="+mediaID,
		beforeSend: function(){  }, //show loading just when link is clicked
		complete: function(){ $("#modalContent").toggleClass('modalLoading');}, // stop loader
		success: function(html){
			// Load up the type in the header:
			var phoTitle_heading = {
				typeface: "Helvetica Bold",
				typeColor: "#ffffff",
				typeSize: "16",
				allCaps: "false",
				content: decodeURI(title)
			};
			var params = {
				menu: "false",
				salign: "LEFT",
				wmode: "transparent"
			};
			var attributes = {};

			swfobject.embedSWF("/swf/customType.swf", "ui-dialog-title-modal", "180", "20", "10","/swf/expressInstall.swf", phoTitle_heading, params, attributes);
			
			$(".phoHeadingWrapper").show();

			// Load the type and ID into the Add Comment form.
			$("#modalLogin .media_id").attr('value', mediaID);

			if( html.indexOf('"success":false') != '-1' ) {
				// Show the Login section:
				$("#modalContent").hide();
				displayLogin();
			} else {
				// Display the returned data:
				$("#modalContent").html(html); //show the html inside .content div
				$("#modalContent").show(); //animation
				$("#modalReadingButtons").show();

				$('#modalLogin').css('display', 'none')

				// Check for the URL in the dialog to scroll to section in the #modalContent div.
				var commentID = $.getUrlVar('mediaCommentID');
				if(commentID != undefined) {
					// Scroll the body to the comment ID:
					setTimeout( function() {
							$("#commentStrip").scrollTo( $('#mediaComment-'+commentID), 800 );
						},
						500
					);
				}
			}
		}

	}); //close $.ajax


	 return false;
}


/*
** Function to close the modal dialog in the News area.
** WARNING: Attached to dialog close listener and will be called automatically
** when the .dialog('close') function is called.
*/
function closeDialog(){
	var flash = document.getElementById('replaced');
	flash.hideComments();
	$('body').focus();
	// Hide the Add Comments and Login screens:
	$('#modalLogin').hide();

	$('.loginError').hide();

	// Reset the view to almost all hidden.
	$('#modal .commentReview').hide();
	$('#modal .addCommentBox').show();

	// Show the modal content.
	$('#modal .modalContent').show();

	// Clear the content areas:
	$('#modal .commentReview .commentReviewContent').val('');
	$('#modal .makeComment .addCommentContent').text('');

	// Reset the slikscreen heading:
	$(".readComments").removeClass("commentSubmitted");

	// Close the dialog prompts:
	$.validationEngine.closePrompt('.formError',true);

	return false;
}

/*
** Function to display the login section along with associated buttons.
*/
function displayLogin() {
	// Hide the reading buttons and show the Back button:
	$("#modalReadingButtons").hide();
	$("#modalPostingButtons").show();

	// Check for login status:
	if (document.cookie.length>0)
	{
		// console.log(document.cookie);
		if( document.cookie.indexOf("[User][id]") == -1) {
			// Show the login box:
			$("#modal .addCommentBox").hide();
			$("#modal .loginBox").show();
		} else {
			// Show the add comment box:
			$("#modal .loginBox").hide();
			$("#modal .addCommentBox").show();
		}
	}

	$('#modalLogin').show();
}


/*
** Function to update the logged in notification areas.
**
** param data: the data to put in the notification areas.
*/
function updateLoggedInNotifications(data) {
	$(".loggedInAs").html(data);
	$("#superLoginModalInner").html( data + "<span>&nbsp;/&nbsp;</span>" + $("#superLoginModalInner").html() );

	// Change the Log In link to Log Out.
	$(".logInOutLink").attr('href', '/users/logout').html('Log Out');

	// Update the modals with the right boxes showing:
	updateModals();
}

function updateModals() {
	// Hide the login area:
	$(".loginBox").hide();
	// Show the comment area:
	$(".addCommentBox").show();
}

