/* FUNCTIONS */

// Set the FCK editor html (content area)
function setEditorValue(instanceName, text)
{
    var oEditor = FCKeditorAPI.GetInstance(instanceName);
    oEditor.SetHTML(text);
}

// On Error
function showError(responseText, statusText){
	alert("Something broke in the CFM! " + responseText + statusText); //something broke in the CFM
}

//Delete Journal 
function fDeleteJournal(jId, jTitle){	
	fConfirm("Deleting this Journal and all Entries. Are you sure?",function(){
		$.ajax({
		  type: 	"post",
		  url: 		"fncDeleteJournal.cfm",
		  data: 	{fldJournalId: jId, fldJournalTitle: jTitle},
		  success: 	dropJournaldiv(jId, jTitle),
		  error: 	function(){alert("error")},
		  complete: function(){$.unblockUI();}
		});
	}); 
}

//Delete Entry
function fDeleteEntry(eId, eTitle){	
	fConfirm("Deleting this Entry. Are you sure?",function(){
		$.ajax({
		  type: 	"post",
		  url: 		"fncDeleteEntry.cfm?date="+Date(),
		  data: 	{fldEntryId: eId, fldEntryTitle: eTitle},
		  success: 	dropEntryRow(eId, eTitle),
		  error: 	showError,
		  complete: function(){$.unblockUI();}
		});
	}); 
	
}

//Delete Comment
function fDeleteComment(cId){	
	fInlineConfirm(cId,function(){
		$.ajax({
		  type: 	"post",
		  url: 		"fncDeleteComment.cfm?date="+Date(),
		  data: 	{fldCommentId: cId},
		  success: 	dropCommentRow(cId),
		  error: 	showError
		});
	}); 
	
}
function fInlineConfirm(Id,fCallback){
	$("#jqConfirm"+Id).fadeIn();
	$("#jqNo"+Id).click(function() { 
		$("#jqConfirm"+Id).fadeOut();	
		return false; 						
	});
	$("#jqYes"+Id).click(fCallback);
}
//Subscribe to Journal
function fSubscribe(eId){
	fAlert("Coming Soon!");
}

// Delete Journal Animate
function dropJournaldiv(jId, jTitle){
	//$("#jqDiv"+jId).animate({opacity: "0"},"slow").slideUp();
	//$("#uiMsg").fadeIn("slow").html("<strong>" + jTitle+ "</strong>" + " has been deleted.").corner("6px");
	location.href="?p=myjournals";
}

// Delete Entry Animate
function dropEntryRow(eId, eTitle){
	$("#jqDiv"+eId).css({"background-color" : "#F0F0F0"}).fadeOut(1500);
	$("#uiMsg").fadeIn("slow").html("<strong>" + eTitle+ "</strong>" + " has been deleted.").corner("6px");}

// Delete Comment Animate
function dropCommentRow(cId){
	$("#jqComment"+cId).animate({opacity: "0"},"slow").slideUp();
}

// Return to My Journals
function showMyJournals()  { 
	location.href="?p=myjournals"; 
} 
// Return to My Journals
function showMyEntries(responseText)  { 
	var JournalId = responseText.split("||")[1];
	location.href="?p=toc&id="+JournalId; 
} 

// Show New Comment
function fShowNewComment(data){
	$.unblockUI();
	var vCommentId = data.COMMENTID;
	var vAuthor = data.AUTHOR;
	var vAvatar = data.AVATAR;
	var vComment = data.COMMENT;
	var vEntryId = data.ENTRYID;
	var vJournalId = data.JOURNALID;
    var pScroll = $('body').attr("scrollHeight");	
	//alert(" author: " + vAuthor + " comment id: " + vCommentId + " avatar: " + vAvatar + " comment: " + vComment);
	//$('div.cjCommentbox:last').after($('div.cjCommentbox:last').clone());	
	//$('div.cjCommentbox:last a.jqAuthor').html(data.AUTHOR);
	//$('div.cjCommentbox:last div.jqAvatar').html(data.AVATAR);	
	//$('div.cjCommentbox:last span.jqDate').html(data.DATEPOSTED);
	//$('div.cjCommentbox:last div.jqComment').html(data.COMMENT);	
	//$('div.cjCommentbox:last').corner("8px").show();
	//$('div.cjCommentbox:last div.jqAvatar').corner("6px");
	//$('div.cjCommentbox:last a.jqDeleteCommentButton').attr("rel", data.COMMENTID);
    //$('html,body').animate({scrollTop: pScroll + 'px'}, 1000, 'swing', function(){
	//	$('div.cjCommentbox:last').pulse({
	//		speed: 500,
	//		opacityRange: [0.4,0.9],
	//		duration: 3000
	//	});
	//});
	setEditorValue("fldCommentContent","");
	// jump to the last page of the comments
	//var pHref = $("span.pageButtonSmall a:last").attr("href");
	location.href = "comments.cfm?id=" + data.JOURNALID +"&entry=" + data.ENTRYID + "&jumpto=last";


}

// Change the Badge
function fChangeBadge(data){
	fSetBlockUIDefaults();
	$.unblockUI();
	if (data.ID != 0){
		$('div.cjBadge img').attr('src',data.IMAGE);
	} else {
		fError("An error occurred while uploading your badge image. Please try again.");
	}
}

// Delete the Badge
function fDeleteBadge(bId){
	fInlineConfirm(bId,function(){
		$.ajax({
		  type: 	"post",
		  url: 		"fncDeleteCJBadge.cfm",
		  data: 	{fldBadgeId: bId},
		  success: 	fReloadProfile,
		  error: 	showError
		});
	}); 
}

function fReloadProfile(){
	document.location = '/cityjournals/?p=profile';	
}

function fAddJournalCommentRating(nCommentId,sRating){
	$.ajax({
		type: 		"post",
		url: 		"fncAddJournalCommentRating.cfm?date="+Date(),
		data: 		{
						CommentId: nCommentId,
						Rating: sRating
					},
		beforeSend:	function(){
						$.blockUI();
					},
		error: 		function(XMLHttpRequest, textStatus, errorThrown){
						fError(errorThrown);
					},
		success: 	function(data){
						var nTotalRating = data.split('||')[1];
						if (nTotalRating == '-9998'){
							fAlert("An error occurred");
						} else if (nTotalRating == '-9999'){
							fAlert("Not allowed.");
						} else {
							$.unblockUI();
							$('div#jqComment'+nCommentId+' span.stexcommentrating').fadeOut('normal').html(nTotalRating).fadeIn('normal');
							$('div#jqComment'+nCommentId+' a.jqSTEXCommentGood').fadeOut('normal');
							$('div#jqComment'+nCommentId+' a.jqSTEXCommentBad').fadeOut('normal');
							if (nTotalRating > -5){
								$('div#jqComment'+nCommentId+'').removeClass('collapsed');
							} else if($('div#jqComment'+nCommentId+' div.content').hasClass('collapsed') != true && nTotalRating <= -5){
								$('div#jqComment'+nCommentId+'').addClass('collapsed');
							}
						}
					}
	});
}

function fBindCommentEvents(){
	// Bind click to jqDeleteButton Class to delete the comment
	$("a.jqDeleteCommentButton").click(function(oEvent){
		fDeleteComment(this.rel);
	});	
	$('a.jqSTEXCommentGood').click(function(){
		fAddJournalCommentRating(this.rel,'Good');
		return false;
	});
	$('a.jqSTEXCommentBad').click(function(){
		fAddJournalCommentRating(this.rel,'Bad');
		return false;
	});
}


/* DOCUMENT READY */
$(document).ready(function() { 

	// Do Journal Specific Corner Elements
	$(".cjBadge").corner("4px");
	$(".cjCommentBox").corner("bl br 6px");	
	$(".jqAvatar").corner("4px");
	
	// Hide comments below threshold
	$(".jqCollapsed").hide();
	
	// Title Field Character Count for New/Edit Journals
	$("#fldTitle").keyup(function(){
		var CharsLeft = 75 - $(this).val().length;
		if(CharsLeft <= 0){
			CharsLeft = "0"
		}
		$(".jqTitleLength").html(CharsLeft + " characters left");
	});
	
	// Description Field Character Count for New/Edit Journals
	$("#fldDescription").keyup(function(){
		var CharsLeft = 500 - $(this).val().length;
		if(CharsLeft <= 0){
			CharsLeft = "0";
			$(this).val($(this).val().substr(0,500));
		}
		$(".jqDescriptionLength").html(CharsLeft + " characters left");
	});	
	
	// Init jq Table Sorter
	if ($("#jqTable").length > 0){
		$("#jqTable").tablesorter({
			headers: {7: {sorter: false}},
			sortList: [[0,0]]
		}); 
	}
   	$('table tr').hover(
        function() {$(this).addClass('highlight');},
        function() {$(this).removeClass('highlight');
    }); 
	

	//Create & Edit Journal
	var oJournalOptions = { 
		target:     	"", 
		url:			"fncSaveJournal.cfm", 
		//beforeSubmit:	validate, 
		success:		showMyJournals,
		resetForm: 		true,
		error:			showError
	};
	// Initiate ajaxSubmit with options and Validate 
	$("#formJournal").validate({										 
		submitHandler: function(form) {
			$.blockUI();
			jQuery(form).ajaxSubmit(oJournalOptions);
			return false; 
		},
		rules: {
			fldTitle: "required",
			fldDescription: "required",
			fldCategory: "required",
			fldKeywords: "required"
		}
	});
	
	//Update FCK instance on submit button click.
	$("#formEntry #btnSubmit").click(function(){
		fUpdateFCKInstance('fldContent');							  
	});
	$("#formComment #btnSubmit").click(function(){
		fUpdateFCKInstance('fldCommentContent');							  
	});
	
	//Create & Edit an Entry
	var JournalId = $('#fldJournalId').fieldValue(); 
	var oEntryOptions = { 
		url:			"fncSaveEntry.cfm?date="+Date(), 
		success:		showMyEntries,
		resetForm: 		true,
		error:			showError
	};
	// Initiate ajaxSubmit with options and Validate 
	$("#formEntry").validate({
		submitHandler: function(form) {
			$.blockUI();			
			$(form).ajaxSubmit(oEntryOptions);
			return false; 
		},
		rules: {
			fldTitle: "required",
			fldContent: "required"
		}
	});
	
	//Create & Edit a Comment
	var EntryId = $('#fldCommentEntryId').fieldValue(); 
	var oCommentOptions = { 
		target:     	"", 
		url:			"fncSaveComment.cfm?date="+Date(), 
		dataType:  		'json',
		//beforeSubmit:	validate, 
		success:		fShowNewComment,
		resetForm: 		true,
		error:			showError
	};
	// Initiate ajaxSubmit with options and Validate 
	$("#formComment").validate({
		submitHandler: function(form) {
			$.blockUI();				
			jQuery(form).ajaxSubmit(oCommentOptions);
			return false; 
		},
		rules: {
		fldCommentContent: {
			required: true,
			minlength: 10
			}
		}
	});
	

	// Update Journal Badage 
	var oBadgeOptions = { 
		url:			"fncSaveCJBadge.cfm?date="+Date(), 
		dataType:		"json",
		success:		fChangeBadge,
		resetForm: 		false,
		iframe:			true,
		error:			showError
	};
	$("#frmBadge").validate({										 
		submitHandler: function(form) {
			fSetBlockUIMessage('<img src="/images/ajax-loader-bar.gif" align="absmiddle"><br><strong style="font-size:12px;">Uploading...</strong><br> Please wait.');
			$.blockUI();
			jQuery(form).ajaxSubmit(oBadgeOptions);
			return false; 
		},
		rules: {
			fldBadgeFile: "required"
		}
	});
	

	/********************** BINDINGS **********************/
	
	// Bind click to jqDeleteButton Class to delete the journal
	$("span.jqDeleteJournalButton a").click(function(oEvent){
		fDeleteJournal(this.rel, this.name);
	});	
	$("a.jqDeleteJournalButton").click(function(oEvent){
		fDeleteJournal(this.rel, this.name);
	});			
	// Bind click to jqDeleteButton Class to delete the Entry
	$(".jqDeleteEntryButton").click(function(oEvent){
		fDeleteEntry(this.rel, this.name);
	});		
	$("a.jqDeleteEntryButton").click(function(oEvent){
		fDeleteEntry(this.rel, this.name);
	});

	// Bind expand/collapse comment
	$("a.jqToggleComment").click(function(){
		$(this).next(".cjCommentbox").slideToggle(600);
	});
	
	// Bind expand/collapse Recent Activity Log
	$("a.jqShowRecentLog").click(function(oEvent){
		$("#jqRecent"+this.rel).slideToggle(600);
	});	
	
	// Bind the delete badge
	$("a.jqDeleteBadge").click(function(oEvent){
		fDeleteBadge(this.rel);
	});		

	// Bind jqSort Buttons
	$('span.jqJournalSort a').click(function(oEvent){
		if ($(this).attr('rel') == ''){
			var sQuerystring = $.query.REMOVE('display');
		} else {
			var sQuerystring = $.query.SET('display', $(this).attr('rel'));
		}
		location.href = sQuerystring;
		return false;
	});	
	
	// Star Ratings
	$('div.jqStarRating.jqEditable a').mouseover(function(){
		var vTotalStars = parseInt($(this).children('img').attr('alt'));
		$('div.jqStarRating.jqEditable img:lt(' + vTotalStars + ')').attr('src','/images/starOn.png');
		$('div.jqStarRating.jqEditable img:gt(' + parseInt(vTotalStars - 1) + ')').attr('src','/images/starOff.png');
	}).mouseout(function(){
		var vSTEXRating = parseFloat($('div.jqStarRating span.jqSTEXStarRatingNumber').html());
		for (var nCount=0; nCount < 5; nCount++){
			var vFraction = (nCount + 1) - vSTEXRating;
			if (vFraction <= 0){
				$('div.jqStarRating.jqEditable img:eq('+nCount+')').attr('src','/images/starOn.png');
			}else{
				if (vFraction <= 0.250){
					$('div.jqStarRating.jqEditable img:eq('+nCount+')').attr('src','/images/star75.png');
				} else if(vFraction <= 0.500){
					$('div.jqStarRating.jqEditable img:eq('+nCount+')').attr('src','/images/star50.png');
				} else if(vFraction <= 0.750){
					$('div.jqStarRating.jqEditable img:eq('+nCount+')').attr('src','/images/star25.png');
				} else {
					$('div.jqStarRating.jqEditable img:eq('+nCount+')').attr('src','/images/starOff.png');
				}
			}
		}
	}).click(function(){
		var nRating = $(this).children('img').attr('alt');
		var nJournalId = $('#txtJournalId').val();
		$.ajax({
			type: 		"post",
			url: 		"fncAddJournalRating.cfm?date="+Date(),
			data: 		{
							JournalId: nJournalId,
							Rating: nRating
						},
			beforeSend:	function(){
							$.blockUI();
						},
			error: 		function(XMLHttpRequest, textStatus, errorThrown){
							fError(errorThrown);
						},
			success: 	function(data){
							var nTotalRating = data.split('||')[1];
							if (nTotalRating == '-9998'){
								fAlert("An error occurred");
							} else if (nTotalRating == '-9999'){
								fAlert("Not allowed.");
							} else {
								$.post("/stex/fncGetStarRating.cfm", { Rating:nTotalRating, Readonly:1},
								function(data){
									$('#stexstarrating').html(data);
									$.unblockUI();
								}, "html");								
							}
						}
		});
	});

	fBindCommentEvents();
}); // document ready




