// Session Properties
var SESSION = {};

SESSION.homeURL		= 'http://go.uconn.edu/';
SESSION.loginURL 	= 'https://login.uconn.edu/cas/login?service=';
SESSION.logoutURL 	= 'https://login.uconn.edu/cas/logout?url=';

SESSION.isActive = function(){
	return eval($.ajax( { type: "POST", url: "index.php/my/check/", async: false} ).responseText);
};

SESSION.hasEnded = function(){
	if(confirm("You are not logged in or your current session has expired. Please log in to continue customization.")){
		var redirect = SESSION.homeURL;
		if (top.frames.length != 0){
			top.location = redirect;
		}else{
			window.location = redirect;
		}
	}
};




var MODULE = {};

// Debugging Messages
MODULE.debug = false;

MODULE.saveSettings = function(e){

	if(SESSION.isActive()){
		$(this).ajaxSubmit({

			url: 'index.php/preferences/setPreference/' + $(this.parentNode.parentNode).attr("id").replace('portlet_',''),
			type: 'post',
			success: function(){

				if(confirm("The page needs to refesh before the new settings will take effect.\n Press \'OK\' to refresh the page now or \'Cancel\' to refresh the page later.")){

					window.location = 'index.php';

				}
			}

		});
	}else{
		SESSION.hasEnded();
	}

	return false;

};

MODULE.toggleSettings = function(e){
	$(this).parents(".portlet").children(".portlet_settings").slideToggle("normal");
};


MODULE.toggleContent = function(e){
	// Current Portlet
	var portlet = $(this.parentNode.parentNode.parentNode);

	// Current Portlet ID Number
	var id = portlet.attr("id").replace('portlet_','');

	// Get Prefs Object
	var prefs = new _IG_Prefs(id);

	portlet.children(".portlet_content").slideToggle("normal",function(){
		if($(this).css('display') === 'none') var val = 1;
		else var val = 0;

		prefs.set('hide',val);

	});
	return false;
};


// Layout Object
var LAYOUT = {};


LAYOUT.columnNames = ['#column_left','#column_center','#column_right'];

LAYOUT.colString = LAYOUT.columnNames.toString();

LAYOUT.hash = '';

LAYOUT.add = function (portlet,column){

	//var portlet = portlet;

	if(SESSION.isActive()){
		//$.ajax( { type: "POST", url: "index.php/my/check/", async: false} ).responseText)
		$.ajax( {
			   type: 	"POST",
			   url: 	"index.php/layouts/add/",
			   async: 	false,
			   data:	{ 'name': portlet },
			   dataType:'html',
			   success:	function(data){
				   		if(MODULE.debug){ alert(data) };
						$("div#"+column).append(data);
						MODULE.init();
						LAYOUT.save();
			   }
		});

	}else{
		SESSION.hasEnded();
	}
};

LAYOUT.get = function (){
	var x=0;
	LAYOUT.hash = '';
	for(x=0;x<LAYOUT.columnNames.length;x++){
		var current = LAYOUT.columnNames[x];
		$('.portlet', current).not('.ui-sortable-helper, #advertisement').each(function(i){
			if($(this).attr('id')){
				LAYOUT.hash += current.replace('#','') + "[]=" + $(this).attr('id') + "&";
			}
		});


	}
	return LAYOUT.hash;
};


LAYOUT.save = function (){
	$.post('index.php/layouts/save',LAYOUT.get(), function(data){
		if(MODULE.debug) alert(data);
	});
};

LAYOUT.del = function (c){

	// Current Portlet
	var portlet = $(this.parentNode.parentNode.parentNode);

	// Current Portlet ID Number
	var id = portlet.attr("id").replace('portlet_','');

	// Load some objects
	var prefs = new _IG_Prefs(id);


	if(confirm("Are you sure you want to remove this portlet from your page?")){
		portlet.hide("slow", function(){

			// Remove the portlet from the DOM before saving
			$(this).remove();

			// Save the layout
			LAYOUT.save();

			// Delete from the database
			prefs.del();
		});
	}
	return false;
};


LAYOUT.enableSort = function (e){
	var ops = {
		revert:			true,
		fx:				200,
		items: 			"div.portlet",
		connectWith:	LAYOUT.columnNames,
		helperclass: 	'sortHelper',
		placeholder: 	'sortHelper',
		handle: 		'img.handle',
		opacity: 		'.6',
		scroll:			true,
		appendTo: 		'body',
		//tolerance:		'guess',
		intersect: 		'pointer',
		cursor: 		'move',
		start: function(e,ui) {
			ui.helper.css("width", ui.item.width());
			ui.helper.addClass("clone");
		},
		change: function(e, ui){
			if(ui.sender){
				var w = ui.element.width();
				ui.placeholder.width(w);
				ui.helper.css("width",ui.element.children().width());
			}
		},
		stop: function(e, ui){
			LAYOUT.save();
			LAYOUT.sortOBJ.sortable("refresh")
		}
	}
	if(LAYOUT.sortOBJ){ LAYOUT.sortOBJ.sortable('destroy'); }
	LAYOUT.sortOBJ = $(LAYOUT.colString).sortable(ops);
};



/*
	Preference Settings
	*Intended* to be Google IG compatible... for future development
*/

function _IG_Prefs(id){
	this.id = id;
}

// Retrieves the specified userpref as a String value. For a userpref that has a list data type, retrieves the contents of the array as a single string of pipe-delimited values.
_IG_Prefs.prototype.getString = function(userpref){

	return eval( $.ajax( { type: "POST", url: "index.php/preferences/getString/" +userpref, data: "id=" + this.id, async: false} ).responseText );

};

// Retrieves the specified userpref as an Integer value.
_IG_Prefs.prototype.getInt = function(userpref){

};

// Retrieves the specified userpref as a Boolean value.
_IG_Prefs.prototype.getBool = function(userpref){

};

// For a userpref that has a list data type, retrieves the contents as an array.
_IG_Prefs.prototype.getArray = function(userpref){

	return eval( $.ajax( { type: "POST", url: "index.php/preferences/getArray/" +userpref, data: "id=" + this.id, async: false} ).responseText );

};

// Sets the value for the specified userpref. To use this function you must include the setprefs library in your gadget, as described in Setprefs Library. For more discussion of this function and an example, see Saving State.
_IG_Prefs.prototype.set = function(userpref, value){

	$.post('index.php/preferences/set/'+userpref+'/'+value,{ 'id' : this.id }, function(data){
		if(MODULE.debug){
			alert(data);
		}
	});

};

/*
	For a userpref that has a list data type, adds elements to the array. To use this function you must include the setprefs library in your gadget, as described in Setprefs Library. For more discussion of this function, see Using the list Data Type . Example:

	prefs.setArray("mylist", ["Apples","Oranges"]);
*/
_IG_Prefs.prototype.setArray = function(userpref, arr){

	$.post('index.php/preferences/setArray/'+userpref+'/'+arr,{ 'id' : this.id }, function(data)
	{
		if(MODULE.debug){
			alert(data);
		}
	});

};

// For debugging, uses document.writeln() to display all of the available preferences.
_IG_Prefs.prototype.dump = function(){
	// someday...

};

// My addition to delete a preference
_IG_Prefs.prototype.del = function(){

	$.post('index.php/preferences/delete/',{ 'id' : this.id }, function(data){
		if(MODULE.debug){
			alert(data);
		}
	});

};

_IG_Prefs.prototype.setTitle = function(title){
	$("div#portlet_" + this.id + " span.title_text").html(title);
};







MODULE.init = function(){

	// Show & Hide Portlet
	$('a.show_hide').unbind();
	$('a.show_hide').bind('click', MODULE.toggleContent);

	// Close Portlet
	$('a.close').unbind();
	$('a.close').bind('click', LAYOUT.del);

	// Toggle Settings
	$('a.configure,input.button[@name=Cancel]').unbind();
	$('a.configure,input.button[@name=Cancel]').bind('click', MODULE.toggleSettings);

	// Process Settings
	$('form.settings').unbind();
	$('form.settings').bind('submit', MODULE.saveSettings);


	// Make layout sortable
	LAYOUT.enableSort('.portlet_column');

};

$(document).ready(function () {
							
	// AJAX Defaults
	$.ajaxSetup({
		timeout: 10000
	});


	// Initialize the modules
	MODULE.init();


	$(".nav")
	.superfish({
		animation : { opacity:"show" },
		disableHI: false,
		delay: 500
	})
	.find(">li:has(ul)")
		.mouseover(function(){
			$("ul", this).bgIframe({opacity:false});
		})
		.find("a")
			.focus(function(){
				$("ul", $(".nav>li:has(ul)")).bgIframe({opacity:false});
			});

});
