/*
 * File that contains all customizations that we need to do to Confluence's 
 * TinyMce JS plugin 
 * This file has a dependency on the following: 
 * 		blogs.js
 *      jquery.js
 *      wiki.js
 */

if(!ws) var ws = {};
if(!ws.community) ws.community = {};
if(!ws.community.blogs) ws.community.blogs = {};
if(BLOGS == null) var BLOGS = ws.community.blogs;

if(!ws) var ws = {};
if(!ws.community) ws.community = {};
if(!ws.community.wiki) ws.community.wiki = {};
if(WIKI == null) var WIKI = ws.community.wiki;

BLOGS.edit = {};
BLOGS.create = {};
WIKI.edit = {};
WIKI.create = {};

///// Important Note: underscore character in mozilla is 109. In MSIE is 189 ///// 

BLOGS.applyMCEChanges = function(mode, key, tags) {	
	
	if(tags && !ArrayUtils.isArray(tags)) {
		alert("API usage error. Cannot parse argument tags. Expected array argument");
		return;
	}
			if(mode === "create-blogpost") {
		BLOGS.create.applyMCEChanges()
	}
	if(mode === "edit") {
		BLOGS.edit.applyMCEChanges();		
	}
	
	// disable the underscore and hyphen from the labelString bar
	// if the input has labels with underscore remove them
	var jLabelString = jQuery("#labelsString"); 
	
	jLabelString.keydown(function(event) {			
		if(jQuery.browser.mozilla) { 
			return event.keyCode !== 109;		
		}
		else {
			return event.keyCode !== 189;
		}		     					
	});	
	
	// hide suggested labels
	jQuery("#suggestedLabelsSpan").hide();
			
	// insert group blogs	
	if(!StringUtils.isEmpty(key)) {
				
		BLOGS.fetchGroupBlogs(tags, key, 						
			// success			
			function (data) { 
				if(!StringUtils.isEmpty(data)) {
													
					jQuery("#content-title-div").after(data);
					
					var jQgroupsToJoinSelect = jQuery("#groupsToJoinSelect");
					var jQjoinedGroupsSelect = jQuery("#joinedGroupsSelect");
					// after appending attach button event handlers
					jQuery("#groupJoinButton").click(function() {
						
						
						var productLabelMetaArray = jQgroupsToJoinSelect.val();														
						if(productLabelMetaArray) {
																											
							for(var i = 0; i < productLabelMetaArray.length; i++) {					 																
								var labelStr = productLabelMetaArray[i];															
								var index = ArrayUtils.find(BLOGS.meta.productLabels, labelStr);								
								if((index >= 0) && (BLOGS.meta.productTitles.length > index)) {
									var titleStr = BLOGS.meta.productTitles[index];										
									jQjoinedGroupsSelect.append("<option id='" + labelStr + "'  value='" + labelStr + "'>" + titleStr + "</option>");
									jQgroupsToJoinSelect.children("#" + labelStr).remove();	
								}																 								
							}							
						}
						else {
							alert("Select a product to join");
						}
						return false;
					});
					
					jQuery("#groupLeaveButton").click(function() {
						var productLabelMetaArray = jQjoinedGroupsSelect.val();																		
						if(productLabelMetaArray) {
																											
							for(var i = 0; i < productLabelMetaArray.length; i++) {					 																
								var labelStr = productLabelMetaArray[i];																												
								var index = ArrayUtils.find(BLOGS.meta.productLabels, labelStr);
														
								if((index >= 0) && (BLOGS.meta.productTitles.length > index)) {
									var titleStr = BLOGS.meta.productTitles[index];
									jQgroupsToJoinSelect.append("<option id='" + labelStr + "' value='" + labelStr + "'>" + titleStr + "</option>");
									jQjoinedGroupsSelect.children("#" + labelStr).remove();
								}																 								
							}							
						}
						else {
							alert("Select a product to leave");
						}
						return false;
					});
					
					// add event listener to the submit button in order to include all joined groups into the form
					var formId = mode === "edit" ? "editpage" : "createpageform";  					
					jQuery("#" + formId).submit(function () {						
						var jQform = jQuery(this);
						jQjoinedGroupsSelect.children().each(function() {
							var labelStr = jQuery(this).val();
							jQform.append("<input type='hidden' name='productsToJoin' value='" + labelStr + "'/>");							
						});
						return true;
					});									
				}			
			},
			
			// error			
			function (req, textStatus, error) {
				alert("Error!");
			}
		);		
	}	
	// add the pollDaddy link to the MCE editor
	jQuery("#labels_tab").before("<div><strong>Do you want to create a poll or survey?   <a href='http://www.polldaddy.com/'>GoTo PollDaddy</a><strong></div>");	
};

BLOGS.fetchGroupBlogs = function (labels, spaceKey, successCallback, errorCallback) {
		
	if(!labels) {		
		labels = new Array();
	}
	// request constants
	var HTTP_METHOD = "GET";
	var RESPONSE_TYPE = "html";
	var ACTION_URL = "/groupblog/editcreatepostcontrols-html.action";
		
	labels.forEach(function (elem, index, array) {
		array[index] = "selectedLabels=" + elem;
	});
	
	// fetch blog					
	jQuery.ajax({
		type: HTTP_METHOD,
		url : ACTION_URL,
		dataType: RESPONSE_TYPE,
		data: "spaceKey=" + spaceKey + "&" + labels.join("&"),
		success: successCallback,
		error: errorCallback
	});		
};



/**
 * Applies TinyMCE changes to the edit blog post page. It populates the list of 
 * group blogs and pre selects the one's that have already been checked
 */
BLOGS.edit.applyMCEChanges = function() {

	/* FINDING THE LINK TEXT "Remove News" AND REPLACING IT WITH "Remove Blog Post" - DFG */
	jQuery("a").each(function(){
		var dfg = jQuery(this).html();
		
		if (dfg.search("Remove News") != -1) {
			jQuery(this).html("Remove Blog Post");
		}
	});
	

	/* FINDING THE TEXT "Labels" AND REPLACING IT WITH "Tags" - DFG */
	jQuery(".formtitle").each(function(){
		var dfg = jQuery(this).html();
		
		if (dfg.search("Labels: ") !== -1) {
			jQuery(this).html("Tags: ");
		}
	});
		
	/* SUPPRESSING "Minor Change? (No Notifications will be sent" FUNCTIONALITY - DFG */
	jQuery(".minor-edit").css("display","none").html("");
	
	/* FINDING INPUT VALUES "Save" AND REPLACING THEM WITH "Publish Update" - DFG */
	jQuery("input[value='Save']").val("Publish Update");

};

BLOGS.create.applyMCEChanges = function() {
	
	jQuery(".formtitle").each(function(){
		var dfg = jQuery(this).html();
		
		if (dfg.search("Labels: ") !== -1) {
			jQuery(this).html("Tags: ");
		}
	});

	jQuery("#content-title").val("Blog Post Title");
	
	jQuery("input[value='Save']").val("Publish");			
};


WIKI.applyMCEChanges = function(mode) {
	
	if(mode === "create-page") {
		WIKI.create.applyMCEChanges();
	}	
		
	// disable the underscore from the labelString bar
	// if the input has labels with underscore remove them
	var jLabelString = jQuery("#labelsString"); 
	
	jLabelString.keydown(function(event) {			
		if(jQuery.browser.mozilla) { 
			return event.keyCode !== 109;		
		}
		else {
			return event.keyCode !== 189;
		}			
	});	
	
	// hide suggested labels
	jQuery("#suggestedLabelsSpan").hide();
	
	/* FINDING THE TEXT "Labels" AND REPLACING IT WITH "Tags" - DFG */
	jQuery(".formtitle").each(function(){
		var dfg = jQuery(this).html();
		
		if (dfg.search("Labels: ") !== -1) {
			jQuery(this).html("Tags: ");
		}
	});
	
};

WIKI.create.applyMCEChanges = function() {	
	jQuery("#content-title").val("Wiki Page Title");	
};