// @Copyright : (c) 2007 - Benjamin Kroll (http://kromes.webkroll.com/license/)

$(document).ready(
	function()
	{
		
		$('#login_tabsave').click(function(){ // login & save tab pos area
			$(this)[0].blur(); // fancy pants
			
			var tabData = '';
			var elemColumn = '';
			var elemCategory = '';
			var elemStatus = '';
			
			$(".menuwrapper").each(function(){ // prep our data strings
			  elemColumn = $(this).parent().attr('id').replace(/col/,"");
			  elemCategory = $(this).attr('id').replace(/menu_/,"");
			  elemStatus = ($(this).children('.menu').css('display') == 'none')? '0' : '1';		  
			  tabData += elemColumn + '.' + elemCategory + '.' + elemStatus + '|';
			});
			
			$.ajax({
					type: "POST",
					url: "savetabs.php",
					data: "tabdata=" + tabData,
					dataType: "json",
					success: function(msg){
						// show confirmation colour
						$('#loginwrapper').animate({backgroundColor: 'green'},100);
						$('#loginwrapper').pause(300);
						$('#loginwrapper').animate({backgroundColor: '#FFF'},2000);
						$('#loginwrapper').pause(300);
						
					},
					error: function(msg){
						$('#loginwrapper').animate({backgroundColor: 'red'},500);
						$('#loginwrapper').pause(300);
						$('#loginwrapper').animate({backgroundColor: '#FFF'},2000);
						alert(msg.responseText);
					}
					
			});
			return false;			
		});
	
		
		$('.menu').hide(); // close all menus without status
		$('.menu.open').show(); // open menus with specific class
		$('.folder.open').css("background-image","url(icons/folder.png)");
		
		// invert all categories
		$('a#all_invert').click(function()
			{
				$(this)[0].blur();
				$('ul.menu').toggle();
				return false;
			}
		);

		// expand all categories
		$('a#all_expand').click(function()
			{
				$(this)[0].blur();
				$('ul.menu').show();
				return false;
			}
		);

		// collapse all categories
		$('a#all_collapse').click(function()
			{
				$(this)[0].blur();
				$('ul.menu').hide();
				return false;
			}
		);
		
		
		// Sortables 
		function sortablesInit(){
			$('#columns td').Sortable(
				{
					accept: 'menuwrapper',
					helperclass: 'sort_placeholder',
					opacity: 0.7,
					handle: 'a.folder',
					tolerance: 'intersect'
				}
			);	
		}
		sortablesInit();
		
		// Toggle Single Portlet
		function singleToggleInit(elem){
			
			var thisToggle = (elem == 'all')? '' : elem;
			
			$('a.folder' + thisToggle).click(function()
				{
					// just for fanciness
					$(this)[0].blur();
					
					if ($(this).css("background-image").indexOf('_add') > 0){
						$(this).css("background-image","url(icons/folder.png)");
					}
					else {
						$(this).css("background-image","url(icons/folder_add.png)");
					}
					$(this).next('ul').toggle('slow');
					return false;
				}
			);
		}
		// Toggle event listeners
		singleToggleInit('all');
		
		// AJAX event listeners
		$("#loading").ajaxStart(function(){
  			$(this).show();
		});
		$("#loading").ajaxStop(function(){
  			$(this).hide();
		});
		
		// Edit in place CATEGORY
		var activeCatEdit = false;
		
		function addEditInPlaceCategories (toggleId) {
			
			var toggleId = (toggleId == 'all')? '.catEditIcon' : '#C_' + toggleId;
			
			$(toggleId).click(function()
				{
					$(this)[0].blur();
								
					if (activeCatEdit == false){
						
						var thisCatNum = $(this).attr('id');
							thisCatNum = thisCatNum.substr(2);
						var thisCatID = '#toggle_' + thisCatNum;
						
						var editInPlace = '<div id="catEditInPlace"><input type="hidden" name="catID" value="' + thisCatNum + '" /><input type="text" id="catTitle" size="10" maxlength="256" value="' + $.trim($(thisCatID).text()) + '" /><br />';

						var buttons = '<div style="text-align:right;"><input type="button" value="delete" class="deleteCatButton" align="left" /><input type="button" value="save" class="saveCatButton" /><input type="button" value="cancel" class="cancelCatButton" /></div></div>';
						
						$(thisCatID).after(editInPlace + buttons);
						activeCatEdit = true;
						$('#catEditInPlace').hide();
						$('#catEditInPlace').slideDown('slow');
					}
					
					$('#catEditInPlace .saveCatButton').click(function(){ 
							$(this)[0].blur();
							catSaveInPlace(this, false);
						});
					$('#catEditInPlace .cancelCatButton').click(function(){ 
							$(this)[0].blur();
							catSaveInPlace(this, true);
						});
					$('#catEditInPlace .deleteCatButton').click(function(){ 
						$(this)[0].blur();
						catDeleteInPlace(this);
					});
					
					return false;
				}
		
			);
			
		}
		
		function catSaveInPlace(obj, cancel) {
			if(!cancel) {

				var catID = $(obj).parent().siblings(0).val();
				var catTitle = $(obj).parent().siblings('#catTitle').val();
				
				 $.ajax({
					type: "POST",
					url: "cat.php",
					data: "id=" + catID + "&title=" + catTitle,
					dataType: "json",
					success: function(msg){
						$('#toggle_' + msg.id).html(msg.title);
						
						// hide editInPlace
						$('#catEditInPlace').animate({backgroundColor: 'green'},100);
						$('#catEditInPlace').pause(300);
						$('#catEditInPlace').animate({backgroundColor: '#2b2c2c'},2000);
						$('#catEditInPlace').pause(300);
						
						$('#catEditInPlace').slideUp("slow",function(){
							$('#catEditInPlace').remove();
							activeCatEdit = false;
						});
					},
					error: function(msg){
						$('#catEditInPlace').animate({backgroundColor: 'red'},500);
						$('#catEditInPlace').pause(300);
						$('#catEditInPlace').animate({backgroundColor: '#2b2c2c'},2000);
						alert(msg.responseText);
					}
					
				 });
			}
			else {
				$('#catEditInPlace').slideUp("slow",function(){
					$('#catEditInPlace').remove();
				});
				activeCatEdit = false;
			}
		}
		// END Edit in place CATEGORY
		addEditInPlaceCategories('all');
		
		// Delete CATEGORY
		function catDeleteInPlace(obj, cancel) {
			var catID = $(obj).parent().siblings(0).val();
				
			if (confirm('By deleting this category you will also delete ALL links within it.\nDo you want to proceed?')){
						
				$.ajax({
						type: "POST",
						url: "delcat.php",
						data: "id=" + catID,
						dataType: "json",
						success: function(msg){
							
							// hide editInPlace
							$('#catEditInPlace').animate({backgroundColor: 'green'},100);
							$('#catEditInPlace').pause(300);
							$('#catEditInPlace').animate({backgroundColor: '#2b2c2c'},2000);
							$('#catEditInPlace').pause(300);
							
							$('#catEditInPlace').slideUp("slow",function(){
								$('#catEditInPlace').remove(); // remove the edit in place box
								$('#menu_' + msg.id).remove(); // remove the actual list item
								activeCatEdit = false;
							});
						},
						error: function(msg){
							var someThing;
							
							$('#editInPlace').animate({backgroundColor: 'red'},500);
							$('#editInPlace').pause(300);
							$('#editInPlace').animate({backgroundColor: '#2b2c2c'},2000);
							alert(msg.responseText);
						}
						
					});
				}
		}		
		// end CATEGORY Delete
		
		
		// Edit in place
		var activeEdit = false;
		
		function addEditInPlaceEvents (toggleId) {
				
				var toggleId = (toggleId == 'all')? '.menu li .editIcon' : '#L_' + toggleId;
				
				$(toggleId).click(function()
				{
					$(this)[0].blur();
								
					if (activeEdit == false){
						var thisLinkID = '#' + $(this).attr('id') + '_link';
						
						var editInPlace = '<div id="editInPlace"><input type="hidden" name="linkID" value="' + $(this).attr('id') + '" /><input type="text" id="linkTitle" size="10" maxlength="256" value="' + $.trim($(thisLinkID).text()) + '" /><br />';
							editInPlace += '<input type="text" id="linkURL" size="10" maxlength="256" value="' + $.trim($(thisLinkID).attr('href')) + '" /><br />';
						var thisFavIcon = ($(thisLinkID).attr('class') == 'fav') ? '' : '_add';
							
						var buttons = '<div style="text-align:right;"><input type="button" value="delete" class="deleteButton" align="left" /><input type="image" src="icons/fav' + thisFavIcon + '.gif" alt="Mark as favorite" title="Mark as favorite" class="favButton" /><input type="button" value="save" class="saveButton" /><input type="button" value="cancel" class="cancelButton" /></div></div>';
						
						$(thisLinkID).after(editInPlace + buttons);
						activeEdit = true;
						$('#editInPlace').hide();
						$('#editInPlace').slideDown('slow');
					}
					
					$('#editInPlace .saveButton').click(function(){ 
							$(this)[0].blur();
							saveInPlace(this, false);
						});
					$('#editInPlace .cancelButton').click(function(){ 
							$(this)[0].blur();
							saveInPlace(this, true);
						});
					$('#editInPlace .favButton').click(function(){ 
							$(this)[0].blur();

							if ($(this).attr("src").indexOf('_add') > 0) {
								$(this).attr("src","icons/fav.gif");
							}
							else {
								$(this).attr("src","icons/fav_add.gif");
							}
						});
					$('#editInPlace .deleteButton').click(function(){ 
						$(this)[0].blur();
						deleteInPlace(this);
					});
					
					return false;
				}
		
			);				
		}
		
		// Add 'Edit in place' event handlers for all list items
		addEditInPlaceEvents ('all');
		
		// Remove selection outline after click on all list item links
		$('.menu li a').click(function(){
			// just for fanciness
			$(this)[0].blur();		
		});

		function saveInPlace(obj, cancel) {
			if(!cancel) {

				var linkID = $(obj).parent().siblings(0).val();
				var linkTitle = $(obj).parent().siblings('#linkTitle').val();
				var linkURL = $(obj).parent().siblings('#linkURL').val();
				var linkFav = ($('#editInPlace .favButton').attr("src").indexOf('_add') > 0)? 0 : 1;
				
				 $.ajax({
					type: "POST",
					url: "link.php",
					data: "id=" + linkID + "&title=" + linkTitle + "&url=" + linkURL + "&fav=" + linkFav,
					dataType: "json",
					success: function(msg){
						var thisLinkID = '#' + msg.id + '_link';
						
						$('#' + msg.id + '_link').attr({href: msg.url});
						$('#' + msg.id + '_link').html(msg.title);
						
						if (msg.fav == 1){
							$(thisLinkID).attr('class','fav');
							$(thisLinkID).css('border-right','10px solid #C00'); // for instant vis. feedback
						} else {
							$(thisLinkID).attr('class','');
							$(thisLinkID).css('border-right','10px solid #FFF'); // for instant vis. feedback
						}
						
						// hide editInPlace
						$('#editInPlace').animate({backgroundColor: 'green'},100);
						$('#editInPlace').pause(300);
						$('#editInPlace').animate({backgroundColor: '#2b2c2c'},2000);
						$('#editInPlace').pause(300);
						
						$('#editInPlace').slideUp("slow",function(){
							$('#editInPlace').remove();
							activeEdit = false;
						});
					},
					error: function(msg){
						$('#editInPlace').animate({backgroundColor: 'red'},500);
						$('#editInPlace').pause(300);
						$('#editInPlace').animate({backgroundColor: '#2b2c2c'},2000);
						alert(msg.responseText);
					}
					
				 });
			}
			else {
				$('#editInPlace').slideUp("slow",function(){
					$('#editInPlace').remove();
				});
				activeEdit = false;
			}
		}
		// end Edit in place

		// Insert new
		
		// *** fancy blur handling
		$('#insert_cat_id').change(function()
			{
				var i_val = $(this).attr('value');
				if (i_val == '0') { 
					//$('#insert_category').css({ display: "none"});
					$('#cat_br').before('<input type="text" id="insert_cat_title" value="Category Title ..." />');
					$('#insert_cat_title')[0].focus();
					
					// focus event handler
					$('#insert_cat_title').click(function()
						{
							var i_val = $(this).val();
							var i_title = (i_val !== undefined)? $.trim(i_val) : i_val;
							if (i_title == 'Category Title ...') { $(this).val(''); }
						}
					);	
					
					// blur event handler
					$('#insert_cat_title').blur(function()
						{
							var i_val = $(this).val();
							var i_title = (i_val !== undefined)? $.trim(i_val) : '';
							if (i_title == '') { $(this).val('Category Title ...'); }
						}
					);		
					
				}
				else {
					$('#insert_cat_title').remove();	
				}
			}
		);
				
		
		$('#insert_title').blur(function()
			{
				var i_val = $(this).val();
				var i_title = (i_val !== undefined)? $.trim(i_val) : '';
				if (i_title == '') { $(this).val('Title ...'); }
			}
		);
		$('#insert_url').blur(function()
			{
				var i_val = $(this).val();
				var i_url = (i_val !== undefined)? $.trim(i_val) : '';
				if (i_url == '') { $(this).val('URL ...'); }	
			}
		);
		
		$('#insert_title').click(function()
			{
				var i_val = $(this).val();
				var i_title = (i_val !== undefined)? $.trim(i_val) : i_val;
				if (i_title == 'Title ...') { $(this).val(''); }
			}
		);
		$('#insert_url').click(function()
			{
				var i_val = $(this).val();
				var i_url = (i_val !== undefined)? $.trim(i_val) : i_val;
				if (i_url == 'URL ...') { $(this).val(''); }
			}
		);
		// *** fancy blur handling END
		
		$('#insertwrapper #insert_submit').click(function()
			{
				$(this)[0].blur();
				if ($('#insert_cat_id').val() !== '') { 
					saveInsert(this, true); 
				}
				else {
					alert('Chose/create a category');	
				}
				return false;
			}
		);
		
		function saveInsert(obj, cancel) {

				var linkCatId = $('#insert_cat_id').val();
				var linkCatTitle = $('#insert_cat_title').val();										  
				var linkTitle = $('#insert_title').val();
				var linkURL = $('#insert_url').val();
				
				 $.ajax({
					type: "POST",
					url: "link.php",
					data: "cat_id=" + linkCatId + "&cat_title=" + linkCatTitle + "&title=" + linkTitle + "&url=" + linkURL,
					dataType: "json",
					success: function(msg){
						
						if (msg.newinsert == 1) {
							var newMenu = '<div class="menuwrapper" id="menu_' + msg.cat_id + '"><img src="icons/application_edit.png" id="C_' + msg.cat_id + '" class="catEditIcon" alt="Edit this category" title="Edit this category" border="0" /><a href="#" class="folder" id="toggle_' + msg.cat_id + '">' + msg.cat_title + '</a><ul class="menu"></ul></div>';
							
							$('#columns td#tcol').after(newMenu); // used to be #columns td#col1
							sortablesInit();
							singleToggleInit('#toggle_' + msg.cat_id);
							$('#insert_cat_id').append('<option value="' + msg.cat_id + '">' + msg.cat_title + '</option>');
							$('#insert_cat_title').remove();
						}
						
						$('#menu_' + msg.cat_id + ' ul').append('<li><img src="icons/application_edit.png" id="L_' + msg.id + '" class="editIcon" alt="Edit this link" title="Edit this link" border="0" /><a href="' + msg.url + '" id="L_' + msg.id + '_link">' + msg.title + '</a></li>\n');
						
						addEditInPlaceEvents(msg.id);
						addEditInPlaceCategories(msg.cat_id);
						
						// trigger input field reset
						$('#insert_title').val('Title ...');
						$('#insert_url').val('URL ...');
						
						$('#insertwrapper').animate({backgroundColor: 'green', color: '#FFFFFF'},100);
						$('#insertwrapper').pause(300);
						$('#insertwrapper').animate({backgroundColor: '#FFFFFF', color: '#000000'},2000);		
					},
					error: function(msg){
						$('#insertwrapper').animate({backgroundColor: 'red', color: '#FFFFFF'},500);
						$('#insertwrapper').pause(300);
						$('#insertwrapper').animate({backgroundColor: '#FFFFFF', color: '#000000'},2000);						
						alert(msg.responseText);
					}
					
				 });
				 
		}
		// end Insert
		
		// Delete entry
		function deleteInPlace(obj, cancel) {
			var linkID = $(obj).parent().siblings(0).val();
			
			$.ajax({
					type: "POST",
					url: "delete.php",
					data: "id=" + linkID,
					dataType: "json",
					success: function(msg){
						
						// hide editInPlace
						$('#editInPlace').animate({backgroundColor: 'green'},100);
						$('#editInPlace').pause(300);
						$('#editInPlace').animate({backgroundColor: '#2b2c2c'},2000);
						$('#editInPlace').pause(300);
						
						$('#editInPlace').slideUp("slow",function(){
							$('#editInPlace').remove(); // remove the edit in place box
							$('#' + msg.id).parent().remove(); // remove the actual list item
							activeEdit = false;
						});
					},
					error: function(msg){
						var someThing;
						
						$('#editInPlace').animate({backgroundColor: 'red'},500);
						$('#editInPlace').pause(300);
						$('#editInPlace').animate({backgroundColor: '#2b2c2c'},2000);
						alert(msg.responseText);
					}
					
				});
		}		
		// end Delete
	}
);