$(document).ready(function()  {
	
  	treeloaded = 0;
	$('#association-dialog').dialog({autoOpen:false, bgiframe:true, modal:true, draggable:false, resizable:false, width:800, height:650});
	showcancelbutton();
	$('#securitytype-span').hide();
	
	$('#setup-dialog').dialog({autoOpen:false, bgiframe:true, modal:true, draggable:false, resizable:false, width:400, height:400});
	$('#setup-dialog').dialog('option', 'buttons', { "Save": 
			function() { 
				
				// take care a few form elements
				$('#setup-data-pane').hide();		
				$('#setup-processing-error').html("").hide();
				// set the HTML, then show the message...
				$('#setup-processing-changes').html( processingChangesHTML() ).show();		
			
				 // sumit the data
				 $.getJSON("/index.cfm/do/manageenrollment.saveUserTypeSetup", {userid:$('#userid').val(), usertypeid:$('#usertypeid').val(), acctusertypeid:$('#acctusertypeid').val(), internalid:$('#internalid').val(), username:$('#username').val(), password:$('#password').val(), email:$('#email').val()},function(data){
				 	// if the result was returned as a success
					if(data.success == 'true'){
						//reload the associations now
						reloadUserAssociationsGrid($('#userid').val());
						// close the dialog window
						$('#setup-dialog').dialog('close');	
					}else{
						// there was an error....display it						
						// there was an error with the data supplied, so swap the data display back around and show the user the message...
						$('#setup-processing-changes').html("").hide();
						$('#setup-processing-error').html(data.returnHTML).show();
						$('#setup-data-pane').show();		
					}
			  });
	 		} 
	 });
	 
	 $('#setup-dialog').bind('dialogclose', function(event, ui) {
  	//alert('closed');
		// dialog back to the default
		$('#setup-data-pane').show();
		$('#setup-processing-changes').html("").hide();
		$('#setup-processing-error').html("").hide();
	});
	 
	$('#delete-dialog').dialog({autoOpen:false, bgiframe:true, modal:true, draggable:false, resizable:false, width:400, height:400});
	$('#delete-dialog').dialog('option', 'buttons', { 
		"Cancel": function() { $(this).dialog("close"); }, 
		"Delete": 
			function() { 	
			
				// take care a few form elements
				$('#delete-data-pane').hide();		
				$('#delete-processing-error').html("").hide();
				// set the HTML, then show the message...
				$('#delete-processing-changes').html( processingChangesHTML() ).show();
				
				 // sumit the data
				 $.getJSON("/index.cfm/do/manageenrollment.deleteAssociation", {userid:$('#userid').val(), usertypeid:$('#usertypeid').val(), acctusertypeid:$('#acctusertypeid').val(), termID:$('#termID').val(), itemString:$('#itemString').val()},function(data){
				 	// if the result was returned as a success
					if(data.success == 'true'){
						//reload the associations now
						reloadUserAssociationsGrid($('#userid').val());
						// close the dialog window
						$('#delete-dialog').dialog('close');	
					}else{
						// there was an error....display it						
						// there was an error with the data supplied, so swap the data display back around and show the user the message...
						$('#delete-processing-changes').html("").hide();
						$('#delete-processing-error').html(data.returnHTML).show();
						$('#delete-data-pane').show();		
					}
			  });
	 		} 
	 });
	 
	 $('#delete-dialog').bind('dialogclose', function(event, ui) {
		// dialog back to the default
		$('#delete-data-pane').show();
		$('#delete-processing-changes').html("").hide();
		$('#delete-processing-error').html("").hide();
	});
	 
	$('#modify-dialog').dialog({autoOpen:false, bgiframe:true, modal:true, draggable:false, resizable:false, width:400, height:320});
	$('#modify-dialog').dialog('option', 'buttons', { 
		"Cancel": function() { $(this).dialog("close"); },
		"Save Changes": 
			function() { 	
			
				// take care a few form elements
				$('#modify-data-pane').hide();		
				$('#modify-processing-error').html("").hide();
				// set the HTML, then show the message...
				$('#modify-processing-changes').html( processingChangesHTML() ).show();
				
				 // sumit the data
				 $.getJSON("/index.cfm/do/manageenrollment.modifyAssociation", {userid:$('#userid').val(), usertypeid:$('#usertypeid').val(), acctusertypeid:$('#acctusertypeid').val(), termID:$('#termID').val(), itemString:$('#itemString').val(),acctSecurityTypeID:$('#acctSecurityTypeID').val(),newtermID:$('#newtermID').val()},function(data){
				 	// if the result was returned as a success
					if(data.success == 'true'){
						//reload the associations now
						reloadUserAssociationsGrid($('#userid').val());
						// close the dialog window
						$('#modify-dialog').dialog('close');	
					}else{
						// there was an error....display it						
						// there was an error with the data supplied, so swap the data display back around and show the user the message...
						$('#modify-processing-changes').html("").hide();
						$('#modify-processing-error').html(data.returnHTML).show();
						$('#modify-data-pane').show();		
					}
			  });
	 		} 
		 });
		 
	$('#modify-dialog').bind('dialogclose', function(event, ui) {
		// dialog back to the default
		$('#modify-data-pane').show();
		$('#modify-processing-changes').html("").hide();
		$('#modify-processing-error').html("").hide();
	});
	
	
	$('#email-login-dialog').dialog({autoOpen:false, bgiframe:true, modal:true, draggable:false, resizable:false, width:700, height:600});
	
	 
	
	// bind the functions to the userAssociation grid
	bindAssociationGridFunctions();
	
	
	
	// when the term is changed....
	$('#term-id').change(function(){
		if($('#term-id').val() > 0) {
			loadtree();
			$('#associations-pane table tbody tr').html("");
			$('#associations-pane').hide();
			$('#tree-pane').show();
			shownextbutton();
		} else {
			$('#tree-pane').hide();
			showcancelbutton();
		}
	});
	
	
	
		
	
		
	$('#association-dialog').bind('dialogclose', function(event, ui) {
  		//alert('closed');
		// dialog back to the default
		$('#term-id').val("");
		$('#tree-pane').html("").hide();
		$('#processing-changes').html("").hide();
		$('#association-dialog').removeData('acctUserTypeID');
		$('#association-dialog').dialog('option', 'buttons', { "Cancel": function() { $(this).dialog("close"); } });
	});
	
});
	
	
	



//Load tree function
function loadtree(){
	$('#association-dialog').block({message: "Loading Term Data ..."});
	// get the tree for the term
	$(function () { 
	
		// TO CREATE AN INSTANCE
		// select the tree container using jQuery
		$("#tree-pane").jstree({
			"json_data" : {
				"ajax" : {
					"url" : "/index.cfm/do/trees.surveyleveltree",
					"data": function(n){
						return {
							id: n.attr ? n.attr("id") : 0,
							level: n.attr ? n.attr("level") : 0,
							termid : $('#term-id').val(),
							rand : Math.floor(Math.random()*11)
						};
					},
					"async" : false 
				}
			},
			"plugins" : ["themes","json_data","checkbox","sort","ui"],
			"checkbox" : {
				"two_state" : true,
				"real_checkboxes" : true, 
				"real_checkboxes_names" : function(n) {
					return [("node" + (n[0].id.replace(/\//g,'_') || Math.ceil(Math.random() * 10000))), 1];
				}
			},
			"ui" : {
				"disable_selecting_children" : true
			},
			"themes" : {
				"theme" : "default",
				"icons" : true
			}
		});
		
	});	

	//Handle changes when the tree is checked
	$('#tree-pane').bind("check_node.jstree", function (event, data) {
		checknode(event, data);
	});		
		
	//Handle changes when the tree is UNCHECKED
	$('#tree-pane').bind("uncheck_node.jstree", function (event, data) {
		unchecknode(event, data);
	});
	
	$('tree-pane').show();
	treeloaded = 1;
	$('#association-dialog').unblock();
}

function checknode(event, data) {
	$('#association-dialog').block({message: "Saving Changes..."});
	$('.ui-dialog-buttonpane').block({message: ""});
	
	$.ajax({
		url:		'/index.cfm/do/manageenrollment.addAssociation'
					+ '?itemString=' + escape(data.rslt.obj.attr("id"))
					+ '&acctusertypeid=' + $('#association-dialog').data('acctUserTypeID')
					+ '&termid=' + $('#term-id').val(),
		async:		true,
		success: function(html){
			//Append the html to the grid
			$('#associations-pane table tbody').append(html);
			$('.association-remove').click(function(){
				var parentrow = $(this).parent().parent();
				parentrow.remove();
				
				// now if there are no more associations....hide the table..
				if ($('#associations-pane table tbody tr').length == 0) {
					$('#association-dialog').block({message: "Saving Changes..."});
					$('#associations-pane').hide();
					$('#tree-pane').show();
					shownextbutton();
					$('#association-dialog').unblock();
				}
				var thisnode = parentrow.attr("id").replace("associate", "node");
				console.log(thisnode);
				var checknode = $('#tree-pane').find("#" + thisnode);
				console.log(checknode);
				checknode.parent().removeClass("jstree-checked");
				checknode.parent().addClass("jstree-unchecked");
				
			});
			$('#association-dialog').unblock();
			$('.ui-dialog-buttonpane').unblock();
		}
	});

}

function unchecknode(event, data) {
	$('#association-dialog').block({message: "Saving Changes..."});
	$('#associate' + data.rslt.obj.attr("id").replace(/\//gi,"_")).remove();
	if($('#associations-pane table tbody tr').length == 0){
		$('#associations-pane').hide();
	}
	$('#association-dialog').unblock();
}

function showsavebutton(){
	//Change the text to 
	$('#association-dialog').dialog('option', 'buttons', {
		"Save Associations": function(){
			
			//Hide all parts
			$('#processing-error').html("").hide();
			$('#tree-pane').hide();
			$('#associations-pane').hide();
			$(".ui-dialog-buttonpane").block({
				message: ''
			});
			
			
			// Block Interface and show saving message
			$('#association-dialog').block({message:"Saving Associations..."});
			
			
			$('#association-acctusertypeid').val($('#association-dialog').data('acctUserTypeID'));
			$('#association-termid').val($('#term-id').val());
			$('#association-userid').val($('#userid').val());
			$('#association-usertypeid').val($('#usertypeid').val());
			
			$('#tree-drill-form').ajaxSubmit({
				dataType: 'json',
				success: function(responseText, statusText){
					//console.log(responseText)
					// once saved...reload the grid on the main page....
					if (responseText.success == 'true') {
						// reload the userAssociationGrid
						reloadUserAssociationsGrid($('#userid').val());
						// now close the window
						$('#association-dialog').dialog('close');
						$('#associations-pane table tbody tr').remove();
						$('#associations-pane').hide();
						$('#association-dialog').unblock();
						$(".ui-dialog-buttonpane").unblock();
					}
					else {
						// there was an error with the data supplied, so swap the data display back around and show the user the message...
						$('#processing-changes').html("").hide();
						$('#processing-error').html(responseText.returnHTML).show();
						$('#associations-pane').show();
						$('#association-dialog').unblock();
						$(".ui-dialog-buttonpane").unblock();
					}
				}
			});
			
		},
		"Back": function(){
			 $('#association-dialog').block({ "Processing": null }); 
			 $('#processing-error').html("").hide();
			 $('#associations-pane').hide();
			 $('#tree-pane').show();
			 $('#term-pane').show();
			 $('#association-dialog').unblock(); 
			 shownextbutton();
		}
	});
}		

function shownextbutton(){
	//Change the text to 
	$('#association-dialog').dialog('option', 'buttons', {
		"Save and Continue": function(){
			 $('#association-dialog').block({ "Processing": null }); 
			 $('#processing-error').html("").hide();
			 $('#term-pane').hide();
			 $('#tree-pane').hide();
			 $('#associations-pane').show();
			 $('#association-dialog').unblock(); 
			 showsavebutton();
		},
		"Cancel": function(){
			$('#processing-error').html("").hide();
			$(this).dialog("close");
		}
		
	});
}	

function showcancelbutton () {
	$('#association-dialog').dialog('option', 'buttons', { "Cancel": function() { $(this).dialog("close"); } });
}

// reloadGridData
function reloadUserAssociationsGrid(userid){
	$.get('/index.cfm/do/manageenrollment.userAssociationsGrid', {userid:userid}, function(html){
		//set the html of the new grid
		$('#user-associations-grid').html(html);
		// b/c the HTML was updated, rebind the functions for the grid
		bindAssociationGridFunctions();
	});
}

// binds the functions to the association grid
function bindAssociationGridFunctions(){
	
	// add the functions to the association link
	$('.add-association-link').click(function(){
		// attach the acctUserTypeID to the dialog data structure...
		$('#association-dialog').data('acctUserTypeID', $(this).attr('id'));
		$('#usertypeid').val($('#' + $(this).attr('id') + '-usertypeid').val());
		$('#term-id').val("");
		$('#association-dialog').dialog('open');
		$('#processing-error').html("").hide();
		$('#term-pane').show();
		$('#associations-pane table tbody tr').html("");
		$('#associations-pane').hide();
	});
		
	// add the functions to the setup link
	$('.setup-level-link').click(function(){
		var acctUserTypeID = $(this).attr('id');
		// attach the acctUserTypeID to the dialog data structure...
		$('#setup-dialog').data('acctUserTypeID', $(this).attr('id'));
		$('#acctusertypeid').val(acctUserTypeID);
		if((typeof($('#' + acctUserTypeID + '-usertypeid').val()) == "undefined")?  false: true) {
			$('#usertypeid').val($('#' + acctUserTypeID + '-usertypeid').val());
		} else {
			$('#usertypeid').val('');
		}
		if((typeof($('#' + acctUserTypeID + '-internalid').val()) == "undefined")?  false: true) {
			$('#internalid').val($('#' + acctUserTypeID + '-internalid').val());
		} else {
			$('#internalid').val('');
		}
		if((typeof($('#' + acctUserTypeID + '-email').val()) == "undefined")?  false: true) {
			$('#email').val($('#' + acctUserTypeID + '-email').val());
		} else {
			$('#email').val('');
		}
		if((typeof($('#' + acctUserTypeID + '-username').val()) == "undefined")?  false: true) {
			$('#username').val($('#' + acctUserTypeID + '-username').val());
		} else {
			$('#username').val('');
		}
		if((typeof($('#' + acctUserTypeID + '-password').val()) == "undefined")?  false: true) {
			$('#password').val($('#' + acctUserTypeID + '-password').val());
		} else {
			$('#password').val('');
		}
		$('#password-field').show().val("");
		// check the auth method, if it is plugin, then we need to hide the username and password fields.
		if($('#' + acctUserTypeID + '-authMethodID').val() != 'UsernameandPassword'){
			$('#username-field').hide().val("");
			$('#password-field').hide().val("");
		}else{
			$('#username-field').show().val("");
			$('#password-field').show().val("");
		}
		
		$('#setup-dialog').dialog('open');
	});	
	
	// add the functions to the delete link
	$('.association-delete-link').click(function(){
		var acctUserTypeID = $(this).attr('id');
		var itemString = $(this).attr('itemString');
		var termID = $(this).attr('termID');
		
		$('#usertypeid').val($('#' + acctUserTypeID + '-usertypeid').val());
		$('#acctusertypeid').val(acctUserTypeID);
		$('#termID').val(termID);
		$('#itemString').val(itemString);
		$('#delete-dialog').dialog('open');
	});
		
	// add the functions to the modify link
	$('.association-modify-link').click(function(){
		var acctUserTypeID = $(this).attr('id');
		var itemString = $(this).attr('itemString');
		var termID = $(this).attr('termID');
		
		$('#usertypeid').val($('#' + acctUserTypeID + '-usertypeid').val());
		$('#acctusertypeid').val(acctUserTypeID);
		$('#termID').val(termID);
		$('#itemString').val(itemString);
		
		//Get the AcctUserType
		$.getJSON("/index.cfm/do/manageenrollment.AcctSecurityType", {userTypeID:$('#usertypeid').val(),itemString:$('#itemString').val(),termID:$('#termID').val()},function(data){
			var acctSecurityTypeID = data.acctSecurityTypeID;
			
			for(var i=0;i<document.getElementById('acctSecurityTypeID').options.length;i++) {
				if(document.getElementById('acctSecurityTypeID').options[i].value == acctSecurityTypeID) {
					document.getElementById('acctSecurityTypeID').options.selectedIndex = i;
				}
			}
		});
		for(var i=0;i<document.getElementById('newtermID').options.length;i++) {
			if(document.getElementById('newtermID').options[i].value == $('#termID').val()) {
				document.getElementById('newtermID').options.selectedIndex = i;
			}
		}
		
		
		$('#modify-dialog').dialog('open');
	});
	
	$('.email-login-link').click(function(){
		
		var acctUserTypeID = $(this).attr('id');
		$('#usertypeid').val($('#' + acctUserTypeID + '-usertypeid').val());
		$('#usertypename').val($('#' + acctUserTypeID + '-usertypename').val());
		$('#email').val($('#' + acctUserTypeID + '-email').val());
		$('#acctusertypeid').val(acctUserTypeID);
		$('#to_email').html($('#' + acctUserTypeID + '-email').val());
		
		
		var iframe_location = $(location).attr('protocol') + '//' + $(location).attr('host') + '/index.cfm/do/Communication.EmailUserLogin/acctUserTypeID/' + acctUserTypeID + '/usertypename/' + $('#' + acctUserTypeID + '-usertypename').val() + '/email/' + $('#' + acctUserTypeID + '-email').val() + '/usertypeid/' + $('#' + acctUserTypeID + '-usertypeid').val();

		
		$('#email-login-dialog').html('<iframe id="email-login-body" width="650" height="1000" marginWidth="0" marginHeight="0" frameBorder="0" scrolling="no" /><div id="loading" style="display:none;" />').dialog('open');
		$("#email-login-body").attr("src",iframe_location);
		
		$('#email-login-dialog').dialog('open');
	});
}

/******* START: General functions *******/

	// returns the ajaxLoaderHTML
	function ajaxLoaderHTML(){
		return '<div align="center" style="margin-top:3em;"><img src="/assets/icons/ajax-loader.gif" border="0" /></div>'
	}
	
	// returns the processingChangesHTML
	function processingChangesHTML(){
		return '<div align="center" style="margin-top:3em;">Processing changes....</div>'
	}
	
	function closeEmailDialog() {
		$('#email-login-dialog').dialog("close");
	}

/******* END: General Functions *******/
