/* policies.js */
$(document).ready(function() {
var policypubliceditor;
var legalRefBeingEdited = null;
// Click a Policy Item - live
$("#tab-policies a.policy, #tab-policies img.add").live("click", function() {
	// Check for Policy in Edit Mode
	if ( $("#edit-policy-item:visible").length > 0 ) {
		if (! confirm("Close this item without saving?")) { return false };
	}
	// left nav highlighting
	$("a.icon", $(this).closest(".pane-navigation")).not($(this)).removeClass("active").removeClass("ui-corner-all").removeClass("ui-widget-content");
	$(this).filter(".policy").addClass("ui-corner-all").addClass("ui-widget-content").addClass("active");
	$("#wrap-policy-item div", "#tab-policies").not(".content-navigation").addClass("visibility-hidden");
		
	// remove editors
	// $.destroyPolicyItemEditors();  
	var unique = $(this).attr("unique");
	$("#current-policy-item").val( unique );
	$.ajax({
		type: "POST",
		url: "/co/acsd50/Board.nsf/LT-GetPolicyItem?open&" + Math.random(),
		data: { id: unique },
		dataType: "html",
		success: function(data) {
			$("#policy-content").html(data);
			// Make sure links launch in new window
			$(".legallinks a").attr("target","_blank");
			// Add Legal Stuff
			$.attachLegalFunctions();
			$.addLegalRemove();
			// put new doc in edit mode
			var isnewdoc = $("[name=isnewdoc]", "#policy-form").val();
			if ( isnewdoc == "1") { $("img.edit", "#wrap-policy-item").trigger("click"); }
			// get files
			$.getPublicFiles( unique, $("[key=publicfiles]", "#wrap-policy-item") );
			// Resize window
			$.windowResize();
			// Attach Button hover info
			$.updateToolTips( $("#tab-policies .content-navigation img") );
			// show document
			$(".pane-content", "#tab-policies").show();
			// annotations
			if ( isExecAnnotations ) { $.addBdAnnotationsPanel( $("#tab-policies"), unique ); }
				
		}
	});
});
// attachLegalFunctions()
$.attachLegalFunctions = function() {	
	// make edit legal sortable
	$("#edit_legal").sortable({ distance: 5 });
	// show legal
	$("#add_legal").show();
}
// Edit Legal Reference
$.editLegalReference = function(el) {
	var parent = $(el);
	var anchor = $(parent).children("a");
	$("#legal-add-form").slideDown(250);
	$("[name=add_legal_title]", "#tab-policies").val( $(parent).text() );
	$("[name=add_legal_url]", "#tab-policies").val( $(anchor).attr("href") );
}
// Add Legal Reference to List
$.addLegalReferenceToList = function(el) {
	var title = $.trim($("[name=add_legal_title]", "#tab-policies").val());
	var url = $.trim($("[name=add_legal_url]", "#tab-policies").val());
	if ( ! title ) { return false; }
	if ( url ) {
		var combined = "<div><a target='_blank' href='" + url + "'>" + title + "</a></div>";
	} else {
		var combined = "<div>" + title + "</div>";
	}
							
	if (legalRefBeingEdited) {
		$(legalRefBeingEdited).replaceWith( combined );
		legalRefBeingEdited = null;
	} else {
		$("#edit_legal").prepend( combined );
		$("div:first a", "#edit_legal").effect("highlight", {  }, 3000);
	}
	$.addLegalRemove();
		
	$("[name=add_legal_title]", "#tab-policies").val('');
	$("[name=add_legal_url]", "#tab-policies").val('');
	$("#add_legal > div").hide();
}
// Cancel Legal Reference to List
$.cancelLegalReferenceToList = function(el) {
	legalRefBeingEdited = null;
	$("[name=add_legal_title]", "#tab-policies").val('');
	$("[name=add_legal_url]", "#tab-policies").val('');
	$("#add_legal > div").hide();
}
// Add Legal Reference
$("#btn-legal-add", "#tab-policies").live( "click", function() {
	$.addLegalReferenceToList();
	return false;
});
// Add Legal Reference
$("#btn-legal-cancel", "#tab-policies").live( "click", function() {
	$.cancelLegalReferenceToList();
	return false;
});
// Add Legal Remove
$.addLegalRemove = function() {
	$(".edit, .remove", "#edit_legal").remove();
	$("div", "#edit_legal").prepend('<img width="14" height="14" style="margin-right: 10px;" class="remove" src="/global.nsf/bin.png">');
	$("div", "#edit_legal").prepend('<img width="14" height="14" style="margin-right: 10px;" class="edit" src="/global.nsf/pencil.png">');
}
// Remove Legal Remove
$.removeLegalRemove = function() {
	$(".remove", "#edit_legal").remove();
	$(".edit", "#edit_legal").remove();
	$("#edit_legal div a").removeAttr("target").removeAttr("style");  // Remove target
}
// Show Legal Add
$("#btn-show-legal-add", "#policy-form").live("click", function() {
	$(this).next().slideDown(250);
	return false;
});
// Live Legal Edit
$(".edit", "#edit_legal").live("click", function() {
	legalRefBeingEdited = $(this).parent();
	$.editLegalReference($(this).parent());
	return false;
});
// Live Legal Remove
$(".remove", "#edit_legal").live("click", function() {
	var parent = $(this).parent();
	var title = $("a", $(parent)).text();
	if (confirm("Remove this reference?\n\n" + title + "\n\n") ) {
		$(this).parent().remove();
	}
	return false;
});
// attachPolicyListFunctions()
$.attachPolicyListFunctions = function() {	
	// If a policy item is current, then open it and expand it's section
	var currentpolicyid = $.trim($("#current-policy-item").val());
	$("#tab-policies .pane-navigation a[unique=" + currentpolicyid + "]:first").trigger("click").parent().prev("h3").find("a").trigger("click");
	
	// expand 1st section if none are open
	if ( $(".ui-state-active", "#policy-accordion").length == 0 ) { $("h3:first", "#policy-accordion").trigger("click"); }
	if ( ! isPublisher ) { return }
	// Policy right-click
	$("a.icon", "#policies").contextMenu('myMenu1', {
		onShowMenu: function(e, menu) {
			$('li', menu).not("#addpacket, #delete, #copyasnew").remove();
			return menu;
		}, 
		bindings: {
			'addpacket': function(t) {
				$.addToPacket( $(t).attr('unique') );
			},
			'delete': function(t) {
				if ( confirm( 'Delete this Policy?\n\n' + $(t).children('a').text() + '\n ') ) { 
					$.deleteByID( $(t).attr('unique') );
					$(t).addClass('being-deleted').hide("pulsate", { times: 5 }, 500);
				}
			},
			'copyasnew': function(t) {
				// not yet
			}
		}
	});
		
}
// getPolicies()
$.getPolicies = function() {	
	$.ajax({
		type: "POST",
		url: "/co/acsd50/Board.nsf/LT-GetPolicies?open&" + Math.random(),
		dataType: "html",
		data: ({status : $("#current-policy-status").val(), book : $("#current-policy-book").val()}),
		success: function(data){
			$("#policies").html(data);
			$("#policy-accordion").accordion({ collapsible: true, autoHeight: false, active: false });
			$.attachPolicyListFunctions();
			// show left nav
			// $("#tab-policies .pane-navigation > div").show();
			// $(".tab-content").fadeTo(250, 1);
		}
	});
}
// getPolicyBooks()
$.getPolicyBooks = function() {	
	$.ajax({
		type: "POST",
		url: "/co/acsd50/Board.nsf/LT-GetPolicyBooks?open&" + Math.random(),
		dataType: "html",
		success: function(data){
			$(".pane-content", "#tab-policies").hide();  // hide policy document being viewed
			$("#policy-books").html(data);
			
			// set select value to current policy book, if any
			if ( ! $("#current-policy-book").val() =="" ) {
				$("#policy-book-select").val( $("#current-policy-book").val() ); 
			}
			$("#current-policy-book").val( $("#policy-book-select").val() );
			$("#wrap-policy-book-select").show();  // select initially hidden, so show it
			$.getPolicies();
			// Policy book selector behavior
			$("#policy-book-select").change( function() {
				$("#current-policy-book").val( $(this).val() );
				$.getPolicies();
			});
		}
	});
}
// Tab Menu
$(".tab-menuitem", "#li-policies").live( "click", function() {
	var key = $(this).attr("key");
	// hide left nav
	// $("#tab-policies .pane-navigation > div").hide();
	// $(".tab-content").fadeTo(250, 0.1);
	switch (key)
	{
		case "active":
			$("#tab-policies .tab-title").html("Active Policies");
			break;
		case "other":
			$("#tab-policies .tab-title").html("Policies Under Consideration");
			break;
		case "retired":
			$("#tab-policies .tab-title").html("Retired Policies");
			break;
	}
	$("#current-policy-status").val( key );
	$.getPolicyBooks();
	
});
// Add Policy Item Editors
$.addPolicyItemEditors = function() {
	$("#edit-policy-item textarea").each( function() {
		var id = $(this).attr("id");
		var instance = CKEDITOR.instances[ id ];
		if ( instance ) { CKEDITOR.remove( instance ); }
	}).ckeditor( 
		function( ) { $.windowResize(); $(".content-navigation img.save", "#wrap-policy-item").removeClass("display-none"); }, 
		{ customConfig : '/co/acsd50/Board.nsf/javascript/ckconfig.js?open&' } 
	);
};
// Close Policy Item
$(".content-navigation img.close", "#tab-policies").live( "click", function() {
	if (! confirm("Close this item without saving?")) { return false };	
	$( "#policy-content").empty();
 	$(".pane-navigation a.icon.active", "#tab-policies").trigger("click");
});
// Edit Policy
$(".content-navigation img.edit", "#tab-policies").live( "click", function() {
	var policyid = $("[name=unique]", "#policy-form").val();
	// show & hide buttons
	$(".content-navigation img.previous", "#tab-policies").addClass("display-none");
	$(".content-navigation img.next", "#tab-policies").addClass("display-none");
	$(".content-navigation img.edit", "#tab-policies").addClass("display-none");
	$(".content-navigation img.print", "#tab-policies").addClass("display-none");
	$(".content-navigation img.close", "#tab-policies").removeClass("display-none");
//	$(".content-navigation img.save", "#tab-policies").removeClass("display-none");
	// show & hide content
	$("#view-policy-item").hide();
	$("#edit-policy-item").show();
	// Legal
	$.attachLegalFunctions();
	$.addLegalRemove();
	// HTML Editors
	$.addPolicyItemEditors();
	// Grab upload controls
	$.updateUploadAreas();
	return false;
		
});
// Save Policy
$(".content-navigation img.save", "#tab-policies").live( "click", function() {
	var lengthpublic = $("[name=policy_public_body]", "#edit-policy-item").val().length;
	if ( lengthpublic > 64000 ) {
		$.quickAlert("Cannot Save", "You have too much information in one field.  Try to trim the amount of information you are saving.  Please contact Support if you need assitance.", 8000);
		return false;
	}
	// get form values
	var book = $("[name=book]", "#policy-form").val();
	var status = $("[name=status]", "#policy-form").val().toLowerCase();
	if ( status != "active" && status != "retired" ) { status = "other"; }  // under consideration detection
	var currentpolicyid = $("[name=unique]", "#policy-form").val();
	$("#current-policy-item").val( currentpolicyid );
	// check required fields
	if ($("[name=book]", "#policy-form").val() == "" || $("[name=section]", "#policy-form").val() == "" || $("[name=title]", "#policy-form").val() == "" ) {
		$.quickAlert("Fields Required", "Book, Section and Title are required to save.", 4000);
		$("[name=book]", "#policy-form").css("background","#ffe");
		$("[name=section]", "#policy-form").css("background","#ffe");
		$("[name=title]", "#policy-form").css("background","#ffe");
		return;
	}
	if ($("[name=retired]", "#policy-form").val() == "" && $("[name=status]", "#policy-form").val() == "Retired") {
		$.quickAlert("Fields Required", "Retired Date is required to save.", 4000);
		$("[name=retired]", "#policy-form").css("background","#ffe");
		return;
	}
	// remove legal button
	$.removeLegalRemove();
	// Legal Field
	$("[name=legal]", "#policy-form").val( $.trim($("[name=edit_legal]", "#policy-form").html()) );
	// hide content area
	$(".pane-content", "#tab-policies").hide();
	// Removed the editor
	// $.destroyPolicyItemEditors();  
	// Serialize form
	var query = $("#policy-form").serialize();
	$.ajax({
		type: "POST",
		url: "/co/acsd50/Board.nsf/LT-SavePolicyItem?open&" + Math.random(),
		dataType: "html",
		data: query,
		success: function(){
			$("#current-policy-book").val( book );
			$("#current-policy-status").val( status );
			$("#li-policies .tab-menuitems [key=" + status + "]").trigger("click");
		}
	});
	return false;
	
});
// initialize
$(".search-box", "#wrap-policies").append("<div id='policy-books'></div>");
});
