function showError(msg)
{
	$('div#footer div.error').animate(
    {
	    height: 'hide'},
		function()
			{
				$('div#footer div.error span').html(msg);
				
				$('div#footer div.error').animate({ height: 'show' }, 200);					
				$('div#footer div.error').animate({opacity: 1.0}, 3500, function(){ $('div#footer div.error').animate({ height: 'hide' }); } );
				
			}
	);
}

function showNotice(msg, timeout)
{
	if(!timeout) timeout = 3500;	
	
	$('div#footer div.notice').animate(
    {
	    height: 'hide'},
		function()
			{
				$('div#footer div.notice span').html(msg);
				
				$('div#footer div.notice').animate({ height: 'show' }, 200);					
				$('div#footer div.notice').animate({opacity: 1.0}, timeout, function(){ $('div#footer div.notice').animate({ height: 'hide' }); } );
				
			}
	);
}

function showUndoIcon()
{
	$("#undo").show("slow");
	
	if($("#undo").css("display") == "none")
	{	
		showNotice("You can undo the delete with the undo button");	
	}
}


var hexColor;

$(document).ready(function()
{
	// Config for hovers.
	hoverConfig = 
	{
		sensitivity: 3, // number = sensitivity threshold (must be 1 or higher)
	    interval: 50, // number = milliseconds for onMouseOver polling interval
	    timeout: 120,
	    over: feedHover, 
	    out: feedHoverOut
	};
	
	blockHoverConfig = 
	{
		sensitivity: 1, // number = sensitivity threshold (must be 1 or higher)
	    interval: 50, // number = milliseconds for onMouseOver polling interval
	    timeout: 0,
	    over: hoverContentIn, 
	    out: hoverContentOut
	};
	optionsHoverConfig = 
	{
		sensitivity: 3, // number = sensitivity threshold (must be 1 or higher)
	    interval: 20, // number = milliseconds for onMouseOver polling interval
	    timeout: 0,
	    over: showOptions, 
	    out: hideOptions
	};
	socialsHoverConfig = 
	{
		sensitivity: 3, // number = sensitivity threshold (must be 1 or higher)
	    interval: 100, // number = milliseconds for onMouseOver polling interval
	    timeout: 0,
	    over: showSocials, 
	    out: hideSocials
	};	
	// Make sure there is a focus on the google search bar.
	$("#google_search_field").focus();
	
	$('a, button').focus(function(){ this.blur();} );
	$('div.groupWrapper').livequery(function(){ 
		$(this).sortable(
		{
			connectWith: 'div.groupWrapper',
			placeholder: 'ui-state-highlight',
			revert: true,
			handle: 'a.move',
			start: function(){
				var blockHeight = $('.getHeight', this).height();
				$('.ui-state-highlight', this.parentNode.parentNode).css({
					'height': blockHeight+2,
					'margin-bottom': '14px'
				});
			}
			,
    		update: function()
    		{
                // Declare an array for the blockIds.
    		    var blockIds = new Array;
    		    var blockId = false;

                // Get the position (id of the div).
                var position = $(this).attr("id");

                $(this).find('.groupItem').each(function()
                {
                    if(blockId == false)
                    {
                        blockId = $(this).attr("block_id");
                    }

                    blockIds.push($(this).attr("block_id"));
                });

                if(blockId == false) return;

                // Construct the form.
                var frm = "frm_"+blockId;

                // Store the data into the form vars.
                $("#" + frm +' input.todo').val('change_block_order');
                $("#" + frm +' input.block_ids').val(blockIds.join(','));
                $("#" + frm +' input.position').val(position);

                // Process the form.
                processForm(frm, function(data)
                {
                    if(data.error)
                    {
                        showError(data.error);
                    }
                });

                // Clear form vars.
                $("#" + frm +' input.todo').val('');
                $("#" + frm +' input.block_ids').val('');
                $("#" + frm +' input.position').val('');
    		}
		}
	);});

    $('.itemContent ul.blocklinks').livequery(function(){
	$(this).sortable(
    {
    		connectWith: 'div.sortable-links .itemContent ul.blocklinks',
    		placeholder: 'ui-state-highlight',
    		opacity: 0.5,
    		forceHelperSize: true,
    		handle: 'a.handle',
    		over: function()
    		{
    			var targetBlock = $(this.parentNode.parentNode);
    			$('.targetBlock').attr('class', 'groupItem sortable-links');
    			$(targetBlock).attr('class', 'groupItem targetBlock');
    		},
    		stop: function()
    		{
				var targetBlock = $('.targetBlock');
    			
    			// Change the color.
				if ($('body').hasClass('dark')) {
					newColor = targetBlock.find(".itemHeader").css("color");
				}
				else {
					newColor = targetBlock.find(".itemHeader").css("background-color");
				}
    			$(targetBlock).find("span.url").css('color',newColor);
    			
    			if ($('a.move', targetBlock).css('display') == 'none') {
    				$('a.handle', targetBlock).css('display', 'none');
    				$('a.trash', targetBlock).css('display', 'none');
    				$('a.favvyedit', targetBlock).css('display', 'none');
    			}
    			
    			$(targetBlock).attr('class', 'groupItem sortable-links');
    		},
    		update: function()
    		{
    		    // Declare an array for the linkIds.
    		    var linkIds = new Array;

    		    // Something has changed, loop through the elements of this sortable and
    		    // get all id's from the list items.
    		    $(this).find('li .title').each(function()
    		    {
    		        linkIds.push($(this).attr("link_id"));
    		    });

                // Get access to the target block.
                var targetBlock = $(this).parent().parent();

    		    // Get also the block id for these links.
                var blockId = targetBlock.attr("block_id");

                // Construct the id for the form.
                var frm = "frm_"+blockId;

                // Store the data into the form vars.
                $('form input.todo', targetBlock).val('change_link_order');
                $('form input.link_id', targetBlock).val(linkIds.join(','));

                // Process the form.
                processForm(frm, function(data)
                {
                    if(data.error)
                    {
                        showError(data.error);
                    }
                });

                // Clear form vars.
                $('form input.todo', targetBlock).val('');
                $('form input.link_id', targetBlock).val('');
            }
    	}
    )});

    $('a.closeEl').live('click', toggleContent);
	$('div.groupItem').livequery(function(){$(this).hoverIntent(blockHoverConfig)});
	$('a.submit').live('click', addContent);
	$('a.cancel').live('click', cancelEdit);
	$('div.optionsSub').hoverIntent(optionsHoverConfig);
	$('div.share').livequery(function(){	$(this).hoverIntent(socialsHoverConfig);});
	$('a.trash').live('click', deleteContent);
	$('a.edit').live('click', toggleEdit);
	$('input.name').live('click', clearField);
	$('input.url').live('click', clearField);
	$('a.favvyedit').live('click', favvyEdit);
	$('a.move').live('mousedown', getHeight);
	$('a.move').live('mouseup', removeHeight);
	$('a.deleteBlock').live('click', deleteBlock);
	$('a.titleedit').live('click', titleEdit);
	$('a.uploadImages').live('click', uploadImages);
	$('a.colorSelectorHeader').live('click', colorHeader);
	$('a.lessFeeds').live('click', removeItemFromFeed);
	$('a.moreFeeds').live('click', addItemToFeed);
	$('div.rss li').livequery(function(){	$(this).hoverIntent(hoverConfig);});
	$('a.undo').live('click', undo);
	
	//$('div.rss li').hover(feedHover, feedHoverOut);
	
	$('div.rss li .feedHover .feedEntry img').livequery(function(){$(this).bind('load', resizer);});
	
});

/**
 *  @desc	Method to undo a delete of a block / link.
 *  @return html / status
 */
function undo()
{
	// Process the header form.
	todo = $("#header_form").find(".todo");
	todo.val('undo');
	
	// Process the header form.
	processForm("header_form", function(data)
    {
		if(data.count == 0)
		{
			// Hide the undo icon.	
			$("#undo").fadeOut("normal");
		}
		else
		{
			// Keep the undo icon available.
			//$("#undo").fadeIn("normal");
		}
		
		// Perform block undo for a block.
		if(data.type == "block")
		{
			// Check if we have an id where this block should be inserted after.
			if(data.after_id)
			{
				// Construct the target.
				var target = $("#block_" + data.after_id);
				target.after(data.html);
				
				$("#block_" + data.id).slideDown("normal");
			}
			else
			{
				var target = $("#"+data.position);
				target.prepend(data.html);
				$("#block_" + data.id).slideDown("normal");
			}
		}
		
		// Perform link undo
		if(data.type == "link")
		{
			// Check if we have an id where this link should be inserted after.
			if(data.after_id)
			{
				// Construct the target.
				var target = $("#block_" + data.block_id);
				
				// Find the correct link.
				target.find('a').each(function()
				{
					if($(this).attr("link_id") == data.after_id)
					{
						$(this).parent().parent().after(data.html);
			  	    }
				});
			}
			else
			{
				block = $("#block_" + data.block_id);
				blockLinks = block.find('.blocklinks');
				blockLinks.prepend(data.html);
			}
			
			// Show the edit / trash / move icons when the form is 
			// on show.
			if($("#frm_" + data.block_id).css("display") == "block")
			{
				// Construct the target.
				var target = $("#block_" + data.block_id);
				
				// Find the correct link.
				target.find('a').each(function()
				{
					$(this).fadeIn("normal");
				});	
			}
		}
	});
	
	todo.val('');
	
}

function getHeight() {
	$(this.parentNode.parentNode.parentNode).addClass('getHeight');
}

function removeHeight() {
	$(this.parentNode.parentNode.parentNode).removeClass('getHeight');
}

var toggleContent = function(e)
{
    var targetContent = $('div.itemContent', this.parentNode.parentNode.parentNode);
	
	if ( $(this).hasClass('maximize') )  {
		targetContent.animate({ height: 'show' }, 300);
		$('ul#slideshow a', targetContent).animate({ height: 'show' }, 300);
		$(this).removeClass('maximize');
		
		// Get the blockId
		blockId = targetContent.parent().attr("block_id");
		
		// Get the form.
		form = $("#frm_" + blockId);
		todo = form.find(".todo");
		
		if(!form.attr('name')) return;
		
		// Change the todo and process the form field.
		todo.val('expand_block');
		
		// Process the form
		processForm("frm_" + blockId, function(data)
		{
			// Reset the todo
			todo.val('');
			
			// If the data is not ok, show the error.
			if(data != "1")
			{
				showError(data);
			}
		});
	}  
	else 
	{
		targetContent.animate({ height: 'hide' }, 300);
		$('ul#slideshow a', targetContent).animate({ height: 'hide' }, 300);
		$(this).addClass('maximize');
	
		// Get the blockId
		blockId = targetContent.parent().attr("block_id");
		
		// Get the form.
		form = $("#frm_" + blockId);
		todo = form.find(".todo");
		
		if(!form.attr('name')) return;
		
		// Change the todo and process the form field.
		todo.val('collapse_block');
		
		// Process the form
		processForm("frm_" + blockId, function(data)
		{
			// Reset the todo
			todo.val('');
			
			// If the data is not ok, show the error.
			if(data != "1")
			{
				showError(data);
			}
		});
		
	
	}
		
	
	return false;
};


function hoverContentIn()
{
    var targetContent = $('div.itemContent', this);
	var targetCheck = $('div.itemHeaderWrapper div.itemHeader a.closeEl', this);
	if ($('div.itemHeaderWrapper div.itemHeader a.edit').hasClass('done') == false ) {
		if (targetCheck.hasClass("maximize")) {
						targetContent.animate({
							height: 'show'
						}, 300);
			};
	}
	return false;
};

function hoverContentOut(){
	var targetContent = $('div.itemContent', this);
	var targetCheck = $('div.itemHeaderWrapper div.itemHeader a.closeEl', this);
	if ($('div.itemHeaderWrapper div.itemHeader a.edit').hasClass('done') == false) {
		if (targetCheck.hasClass("maximize")) {
			targetContent.animate({
				height: 'hide'
			}, 300);
		}
	}
}

var clearField = function(e){
	var textBtn =  $('a.submit span', this.parentNode.parentNode.parentNode).text();

	if (textBtn == 'save') {

	}
	else {
		$(this).val('');
	}

}

function addContent(){
	var textBtn =  $('a.submit span', this.parentNode.parentNode.parentNode).text();

	if (textBtn == 'save')
	{
	    if ($('label.formLabel', this.parentNode).text() == 'Edit title') {

            // Get the form id.
			formId = $(this).parent().attr("id");

			// Change the todo.
			todo = $(this).parent().find('.todo');

			// Set the todo value.
			todo.val('save_title');

            processForm(formId, function(data)
            {
                if(data.error)
    		    {
    		        showError(data.error);
    		    }
            });

            // Change the todo back to what it was.
            todo.val('');

			var targetBlock = $(this.parentNode.parentNode.parentNode);
			var editTitle = $('input.name', targetBlock).val();
			$('span.title', targetBlock).text(editTitle);
			$('div.cancel', targetBlock).css('display', 'none');
			$('a.submit span', targetBlock).text('add favvy');
			$('label.formLabel', targetBlock).text('Add new favvy');
			$('input.url', targetBlock).attr('readonly', false);
			$('input.url', targetBlock).animate({opacity: 1});
			$('input.url', targetBlock).val('url');
			$('input.name', targetBlock).val('site name');
		}
		else {
			var targetBlock = $(this.parentNode.parentNode.parentNode);
			var blockId = targetBlock.attr("block_id");
			var editName = $('input.name', targetBlock).val();
			var editUrl = $('input.url', targetBlock).val();

			var linkId = $('input.link_id', targetBlock.val());

			var targetEdit = $('li.targetEdit', targetBlock);
			var targetColor = $('span.url', targetBlock).css('color');

			$('a.handle', targetEdit).animate({
				width: 'show'
			});
			$('a.trash', targetEdit).animate({
				width: 'show'
			});
			$(targetEdit).removeClass('targetEdit');
			$('div.cancel', targetBlock).css('display', 'none');
			$('a.submit span', targetBlock).text('add favvy');
			$('label.formLabel', targetBlock).text('Add new favvy');

			// Change the todo.
			var todo = $('form input.todo', targetBlock).val('save_link');

			// Construct the id for the form.
			var form = "frm_" + blockId;

			// Process the form.
			processForm(form, function(data){
				// Clear the todo.
				$('form input.todo', targetBlock).val('');

				// Reset the form.
				$('input.name', targetBlock).val('site name');
				$('input.url', targetBlock).val('url');

				if (data.error) {
					showError(data.error);
				}
				else {
					
					$('a.title', targetEdit).attr('title', data.title);
					$('a.title', targetEdit).html('<li><span class="overflow"><a class="favvyedit icon" title="edit this favvy">&nbsp;&nbsp;</a><a class="trash icon" title="delete this favvy">&nbsp;&nbsp;</a><a class="handle icon" title="arrange this favvy">&nbsp;&nbsp;</a><a class="title" link_id="'+data.id+'" href="'+data.url+'" title="'+data.title+'" target="_blank">'+data.title+'<span class="url" style="color: '+data.color+'; margin-left: 12px;">'+data.url+'</span></a></span></li>');
					//$('a.title', targetEdit).html('' + data.title + '<span class="url" style="color: ' + targetColor + ';  margin-left: 12px;">' + data.url + '</span>');
				}
			});
		}
	}

	else
	{
	    var targetBlock = $(this.parentNode.parentNode.parentNode);
        var blockId = targetBlock.attr("block_id");
		var targetUL = $('.itemContent ul', targetBlock);
		var siteName = $('form input.name', targetBlock).val();
		var siteUrl = $('form input.url', targetBlock).val();
		var targetColor = $('span.url', targetBlock).css('color');
		var todo = $('form input.todo', targetBlock).val('add_link');
        var block = $('form input.block_id', targetBlock.val(blockId));

        // Construct the id for the form.
		var form = "frm_"+blockId;

		// Process the form.
		processForm(form, function(data)
		{
		    // Clear the todo.
		    $('form input.todo', targetBlock).val('');

		    if(data.error)
		    {
		        showError(data.error);
		    }
		    else
		    {
                // Append the link to the block.
                $('<li><span class="overflow"><a class="favvyedit icon" title="edit this favvy" style="display: block"></a><a class="trash icon" title="delete this favvy" style="display: block"><a class="handle icon" title="arrange this favvy" style="display: block"></a><a class="title" target="_blank" href="' + data.url + '" title="' + data.title + '" link_id="' + data.id + '">' + data.title + '<span class="url" style="color: ' + targetColor + '; margin-left: 12px;">' + data.url + '</span></a></span></li>').appendTo(targetUL);
		    }
		});
	}
};


function titleEdit()
{
	var targetBlock = $(this.parentNode.parentNode.parentNode);
	var editTitle = $('span.title', targetBlock).html();
	$('li.targetEdit a.handle', targetBlock).animate({width: 'show'});
	$('li.targetEdit a.trash', targetBlock).animate({width: 'show'});
	$('li.targetEdit', targetBlock).removeClass('targetEdit');

	$('input.url', targetBlock).attr('readonly', true);
	$('input.url', targetBlock).val('');
	$('input.url', targetBlock).animate({opacity: 0.3});

	$('a.submit span', targetBlock).text('save');
	$('label.formLabel', targetBlock).text('Edit title');
	$('div.cancel', targetBlock).css('display', 'block');
	$('input.name', targetBlock).val(editTitle);
}

var favvyEdit = function(e)
{
	var targetBlock = $(this.parentNode.parentNode);
	var targetBlock2 = $(this.parentNode.parentNode.parentNode);
	var targetBlock3 = $(this.parentNode.parentNode.parentNode.parentNode);
	if ($('label.labelForm', targetBlock3).text() != 'Edit title') {
				$('input.url', targetBlock3).attr('readonly', false);
				$('input.url', targetBlock3).animate({opacity: 1});
	}
	if($('a.handle', this.parentNode).css('display') == 'block')
	{
		var editUrl = $('span.url', targetBlock).html();
		var editName = $('a.title', targetBlock).attr('title');
		var editLinkId = $('a.title', targetBlock).attr('link_id');

		$('li.targetEdit a.handle', targetBlock2).animate({
			width: 'show'
		});

		$('li.targetEdit a.trash', targetBlock2).animate({
			width: 'show'
		});

		$('li.targetEdit', targetBlock2).removeClass('targetEdit');
		$(targetBlock).addClass('targetEdit');
		$('a.submit span', targetBlock3).text('save');
		$('label.formLabel', targetBlock3).text('Edit favvys');
		$('div.cancel', targetBlock3).css('display', 'block');
		$('input.url', targetBlock3).val(editUrl);
		$('input.name', targetBlock3).val(editName);
		$('input.link_id', targetBlock3).val(editLinkId);
		$('a.handle', targetBlock).animate({width: 'hide'});
		$('a.trash', targetBlock).animate({width: 'hide'});
	}
}

var deleteContent = function(e)
{
    // Ajax request to remove the link.
    var linkId = ($(this.parentNode.parentNode).find(".title").attr("link_id"));

    // Get access to the main block.
    targetBlock = $(this).parent().parent().parent().parent();

    // Get access to the todo input field.
    todoField = targetBlock.find('.todo');
    linkIdField = targetBlock.find('.link_id');
    blockIdField = targetBlock.find('.block_id');

    // Get the value of the block.
    blockId = blockIdField.val();

    // Change the values of the linkid and the todo field.
    todoField.val('delete_link');
    linkIdField.val(linkId);

    // Construct the id for the form.
    var form = "frm_"+blockId;

    // Process the form.
    processForm(form, function(data)
    {
        // Clear the todo.
        todoField.val('');

        // Clear the linkId
        linkIdField.val('');

        if(data.error)
        {
            showError(data.error);
        }
        else
        {
        	showUndoIcon();
        }
    });

    // We do not have to wait for the ajax request.
    $(this.parentNode).animate(
    {
	    height: 'hide'},
		function(){$(this).remove();}
	);
};

var uploadImages = function(e)
{
    // Get the rel attr.
    url = ($(this).attr("rel"));

    // Ajax request and append the box after the container..
    $.get(url, function(data)
    {
        // Append the html of the popup to the template.
        $("#container").after(data);

        // Show the box.
        showBox();

        // Hide the options again.
        hideOptions();
    });
}


var deleteBlock = function(e)
{
    // Store the id on the blockId field.
    var todo = $(this).parent().parent().parent().find(".todo");

    // Search the form.
    frm = $(this).parent().parent().parent().find("form");

    // delete the block.
    todo.val('delete_block');

    // Process the form.
    processForm(frm.attr("id"), function(data)
    {
        if(data.error)
        {
            showError(data.error);
        }
        else
        {
        	showUndoIcon();
        }
    });

	$(this.parentNode.parentNode.parentNode).animate(
	{
        height: 'hide'
    },
    function()
    {
        $(this).remove();
    });
};

function showOptions() {
		$('div#submenu').animate({
			height: 'show'
		});
}
function hideOptions() {
		$('div#submenu').animate({
			height: 'hide'
		}, 100);
}

function showSocials(){
		$(this).animate({
			height: '44px'
		}, 300);
}

function hideSocials() {
		$(this).animate({
			height: '20px'
		}, 100);
}

function cancelEdit(){
	var targetBlock = (this.parentNode.parentNode.parentNode);
	var targetEdit = $('a.move' , targetBlock);
	if ($('label.labelForm', targetBlock).text() != 'Edit title') {
				$('input.url', targetBlock).attr('readonly', false);
				$('input.url', targetBlock).animate({opacity: 1});
	}
	$('li.targetEdit', targetBlock).removeClass('targetEdit');
	$('div.cancel', targetBlock).css('display', 'none');
	$('a.submit span', targetBlock).text('add favvy');
	$('label.formLabel', targetBlock).text('Add new favvy');
	$('input.name', targetBlock).val('site name');
	$('input.url', targetBlock).val('url');
	$('a.trash', targetBlock).animate({ width: 'show' });
	$('a.handle', targetBlock).animate({ width: 'show' });
}

function toggleEdit()
{
	var targetBlock = (this.parentNode.parentNode.parentNode);
	var targetEdit = $('a.move' , targetBlock);
	var rssCheck = $(targetBlock).attr('class');

	if (targetEdit.css('display') == 'none') {
		$(targetEdit).animate({ height: 'show' });
		$('a.colorSelector', targetBlock).animate({ height: 'show' });
		$('a.uploadImages', targetBlock).animate({ height: 'show' });
		$('a.deleteBlock', targetBlock).animate({ height: 'show' });
		$('a.moreFeeds', targetBlock).animate({ height: 'show' });
		$('a.lessFeeds', targetBlock).animate({ height: 'show' });
		$('a.favvyedit', targetBlock).animate({ width: 'show' });
		$('a.edit', targetBlock).addClass('done');
		$('a.handle', targetBlock).animate({ width: 'show' });
		$('a.trash', targetBlock).animate({ width: 'show' });
		$('a.titleedit', targetBlock).animate({	width: 'show' },
			function(){ 
				if (rssCheck != 'groupItem rss') {
					$('form', targetBlock).animate({ height: 'show'	});
				}
		} );

	} else {
		$(targetEdit).animate({ height: 'hide' });
		$('a.colorSelector', targetBlock).animate({ height: 'hide' });
		$('a.uploadImages', targetBlock).animate({ height: 'hide' });
		$('a.favvyedit', targetBlock).animate({ width: 'hide' });
		$('a.edit', targetBlock).removeClass('done');
		$('form', targetBlock).animate({ height: 'hide' });
		$('a.handle', targetBlock).animate({width: 'hide'});
		$('a.trash', targetBlock).animate({width: 'hide'});
		$('a.deleteBlock', targetBlock).animate({ height: 'hide' });
		$('a.moreFeeds', targetBlock).animate({ height: 'hide' });
		$('a.lessFeeds', targetBlock).animate({ height: 'hide' });		
		$('a.titleedit', targetBlock).animate({ width: 'hide' });
	}
	if ($('label.labelForm', targetBlock).text() != 'Edit title') {
				$('input.url', targetBlock).attr('readonly', false);
				$('input.url', targetBlock).animate({opacity: 1});
	}
	$('li.targetEdit', targetBlock).removeClass('targetEdit');
	$('div.cancel', targetBlock).css('display', 'none');
	$('a.submit span', targetBlock).text('add favvy');
	$('label.formLabel', targetBlock).text('Add new favvy');
	$('input.name', targetBlock).val('site name');
	$('input.url', targetBlock).val('url');

	// Get the color from the block.
	currentColor = $('input.color', targetBlock).val();
	
	$('.colorSelector', targetBlock).ColorPicker({
        color: currentColor,
		onShow: function(colpkr){
			$(colpkr).css('display', 'block');
			return false;
		},
		onHide: function(colpkr){

		    // Get the color from the block.
		    itemHeader = $(targetBlock).find('.itemHeader');
            color = $('span.url', targetBlock).css('color');

            $('.color', targetBlock).val(hexColor);
            $('.todo', targetBlock).val('save_color');
            frm = $('form', targetBlock).attr("id");

            // Process the form.
            processForm(frm, function(data)
            {
                if(data.error)
                {
                    showError(data.error);
                }
            });

            // Clear the todo etc again.
            $('.color', targetBlock).val('');
            $('.color', targetBlock).val('');

			$(colpkr).css('display', 'none');
			return false;
		},
		onChange: function(hsb, hex, rgb){

        if($('body').hasClass('dark')){$('.itemHeader', targetBlock).css('color', '#' + hex);}
		else{$('.itemHeader', targetBlock).css('background-color', '#' + hex);}
		$('ul a span', targetBlock).css('color', '#' + hex);
		hexColor = "#"+hex;
		}
    });

	$('.colorpicker').draggable({
        opacity: 0.8,
		handle: '.colorpicker_move'
	});

	return false;
};

function colorHeader(){
	var targetBlock = (this.parentNode.parentNode.parentNode);
	currentColor = $('input.color', targetBlock).val();
	
	// Reset the targetBlock
	targetBlock = targetBlock.parentNode;
	
	$('.colorSelectorHeader', targetBlock).ColorPicker({
        color: currentColor,
		onShow: function(colpkr){
			$(colpkr).css('display', 'block');
			return false;
		},
		onHide: function(colpkr){

		    // Get the color from the block.
		    itemHeader = $(targetBlock).find('.headerwrapper');
            color = $('.headerwrapper', targetBlock).css('background-color');
            $('.color', targetBlock).val(hexColor);
                        
            // Process the form.
            processForm('header_form', function(data)
            {
                if(data.error)
                {
                    showError(data.error);
                }
            });

            // Clear the todo etc again.
            $('.color', targetBlock).val('');
            $('.color', targetBlock).val('');

			$(colpkr).css('display', 'none');
			return false;
		},
		onChange: function(hsb, hex, rgb){
        $('.headerwrapper', targetBlock).css('background-color', '#' + hex);
		hexColor = "#"+hex;
		}
    });
}

function addItemToFeed()
{
	var targetUL = ($('div.itemContent ul', this.parentNode.parentNode.parentNode));
	// changed to show line at first position so not needed anymore
	//$('li', targetUL).removeClass('last');

	// Loop through the list and show the next list item in the row.
	newLi = targetUL.find("li:hidden:first");
	if(newLi.length == 0)
	{
		showError("There are no more links available for this feed at this time");
		return false;
	}
	
	newLi.slideDown("fast");
	// changed to show line at first position so not needed anymore
	//newLi.addClass("last");
	
	// Enable the hover.
	//$('a.title', newLi).hover(feedHover, feedHoverOut);
	
	// Get access to the parent of the block.
	parent = targetUL.parent().parent();
	
	// Get the block id
	blockId = parent.attr("block_id");
	
	// Change the todo.
	parent.find(".todo").val("add_link");
	
	// Process the form.
	processForm("frm_" + blockId, function(result)
	{
		// Reset the todo
		parent.find("todo").val("");
		
		// check the result and give an error if something is wrong.
		if(result != 1)
		{
			showError("Could not add new links to this feed");
		}
	});
	
	// Old code mabey needed by cap?
	//$('<li class="last"><a class="title" href="">testlinkje!</a></li>').appendTo(targetUL);
	//$('li.last a.title', targetUL).hover(feedHover, feedHoverOut);
}

function removeItemFromFeed(){
	var targetUL = ($('div.itemContent ul', this.parentNode.parentNode.parentNode));
	newLi = targetUL.find("li:visible:last");
	
	if(newLi.length == 0)
	{
		showError("There are no links left for this feed to remove");
		return false;
	}
	
	newLi.slideUp("fast", function()
	{
		targetUL.find("li:visible:first").addClass("first");
	});
	
	// Get access to the parent of the block.
	parent = targetUL.parent().parent();
	
	// Get the block id
	blockId = parent.attr("block_id");
	
	// Change the todo.
	parent.find(".todo").val("remove_link");
	
	// Process the form.
	processForm("frm_" + blockId, function(result)
	{
		// Reset the todo
		parent.find("todo").val("");
		
		// check the result and give an error if something is wrong.
		if(result != 1)
		{
			showError("Could not remove the last link");
		}
	});
	
	//$('li.last:isvisible', targetUL).remove();
	//$('li:last:isvisible', targetUL).addClass('last');
}

function feedHover(e){
	$("a.updated", this).removeClass('updated');
	$('embed', targetHover).attr('wmode', 'transparent');
	
	var targetHover = 	$(".feedHover", this);
	var offSetFeed = $(this.parentNode.parentNode.parentNode).offset();
	if ($(this.parentNode.parentNode.parentNode.parentNode).hasClass('right')) {
		var x = offSetFeed.left - 346;
	}
	else {
		var x = offSetFeed.left + 314;
	}
		
		// Get the id.
		//id = "#"+$(this).attr("extra");
		
		// Get the content of the description + media.
		//content = $(id).html();
		
		//$('body').append('<div id="feedHover"><div class="feedEntry">'+ content +'</div></div>');
		$('embed', targetHover).css('width', function(){
					var iWidth = $(this).css("width");
					var iHeight = $(this).css("height");
					var imageWidth = iWidth.replace("px","");
					var imageHeight = iHeight.replace("px","");
					var widthResult = 312;
					if( imageWidth > widthResult ){
						var resizeFactor = widthResult/imageWidth;
						$(this).css("width", widthResult+'px');
						$(this).css("height", (imageHeight*resizeFactor)+'px');
					}
		});
		var windowDim = getWindowSize();
		var feedHeight = $(targetHover).height();
		
		$('.feedEntry', targetHover).css('max-height', windowDim.Y - 84 );
		
		
		
		var y = e.pageY - 40;
		
				//var feedEntryHeight = $('.feedEntry', targetHover).height();
				//var Max = $('.feedEntry', targetHover).css('max-height');
				//var maxHeight = Max.replace("px","");
				
				//if (feedEntryHeight == maxHeight) {
					//$('.feedEntry', targetHover).jScrollPane();
				//}
		
		var feedHeight = $(targetHover).height();
		if (windowDim.Y < feedHeight + e.clientY - 10 ) {
			var y = e.pageY + (windowDim.Y - (feedHeight + e.pageY))- 30 + (e.pageY - e.clientY);
		}
		
		$(targetHover)
			.css("display", "block")
			.css("top", y + "px")
			.css("left", x + "px")
			//.animate({opacity: 1.0}, 100);
		$('a.title', this ).bind('mousemove', feedMove);	
		}
		
							
function feedHoverOut(){
		var targetHover = $('.feedHover', this);
		//$(targetHover).animate({opacity: 0.0}, 80, function(){$(targetHover).css('display', 'none')});
		$(targetHover).css('display', 'none');
		$('a.title', this ).unbind('mousemove', feedMove);
		$('.feedEntry', targetHover).css('max-height', 'none' );
    }
function feedMove(e){
				
				var targetHover = $('.feedHover', this.parentNode);
				var offSetFeed = $(this.parentNode.parentNode.parentNode.parentNode).offset();
				var windowDim = getWindowSize();
				var feedHeight = $(targetHover).height();
				var y = e.pageY - 40;
				if (windowDim.Y < feedHeight + e.clientY -10 ) {
					var y = e.pageY + (windowDim.Y - (feedHeight + e.pageY))- 30 + (e.pageY - e.clientY);
				}
				if (windowDim.Y < feedHeight) { var y = 10 + (e.pageY - e.clientY) ; }
				if ($(this.parentNode.parentNode.parentNode.parentNode.parentNode).hasClass('right')) {
					var x = offSetFeed.left - 346;
				}
				else {
					var x = offSetFeed.left + 314;
				}
				$(targetHover).css("top", y + "px")
				$(targetHover).css("left", x + "px")
	}			
function resizer(){
	var iWidth = $(this).css("width");
	var iHeight = $(this).css("height");
	var imageWidth = iWidth.replace("px","");
	var imageHeight = iHeight.replace("px","");
	var widthResult = 312;
	if( imageWidth > widthResult ){
		var resizeFactor = widthResult/imageWidth;
		$(this).css("width", widthResult+'px');
		$(this).css("height", (imageHeight*resizeFactor)+'px');
	}			
}
