/**
 * IE && FireBug compatibility to prevent errors in IE
 * debug; should be removed in production
 */
if (typeof console==='undefined')
	console  = {
		log : function () {},
		debug: function () {},
		trace:  function () {},
		dir:   function () {}
	};
	
(function($){
	var updateUpDown = function(sortable){
		$('dl:not(.ui-sortable-helper)', sortable)
			.removeClass('first').removeClass('last')
			.find('.up, .down').removeClass('disabled').end()
			.filter(':first').addClass('first').find('.up').addClass('disabled').end().end()
			.filter(':last').addClass('last').find('.down').addClass('disabled').end().end();
	};
	///**
	var moveUpDown = function(){
		var link = $(this),
			dl = link.parents('dl'),
			prev = dl.prev('dl'),
			next = dl.next('dl');
	
		if(link.is('.up') && prev.length > 0)
			dl.insertBefore(prev);
	
		if(link.is('.down') && next.length > 0)
			dl.insertAfter(next);
	
		// Extra stuff to change up/down buttons appearance. Append later if required
		//updateUpDown(dl.parent());
	    updateCookieWithCurrentModulePositions();
	};
	//*/

    function updateCookieWithCurrentModulePositions() 
    {
        var elements = document.getElementsByTagName("dl");
        var s = "";
        // Build comma-separated list of items
        for(var i=0; i<elements.length; i++)
        {
            // Skip placeholder
            if (elements[i].id == "dl_0")
                continue;
            s+= elements[i].id + ",";
        }
        // Remove trailing comma
        if (s.length > 0)
            s = s.substr(0,s.length-1);
            
        Set_Cookie(nameOfModulePositionsCookie,s,60000);
    }

    function retrieveModulePositionsFromSavedCookie()
    {
        var positions = Get_Cookie(nameOfModulePositionsCookie);
        if (positions == null || positions.length == 0)
            return; // No cookies here
        //alert(positions);
        
        // Split out positions
        var a = positions.split(',');
        
        // Get very first reserved element
        var first = $('#dl_0');
        
        for (var i=0; i<a.length; i++)
        {
            var obj = $('#'+a[i])
            first.before(obj);
        }
    }

	
	var sortableChange = function(e, ui){
		if(ui.sender){
			var w = ui.element.width();
			ui.placeholder.width(w);
			
			ui.helper.css("width",ui.element.children().width());

		}
	};
	
	var sortableUpdate = function(e, ui){
		if(ui.element[0].id == 'trashcan'){
			emptyTrashCan(ui.item);
		} else {
			window.setTimeout ( function () { // timout to prevent weird timing problems in IE. Of cause IE
				updateUpDown(ui.element[0]);
				if(ui.sender) {
					updateUpDown(ui.sender[0]);
				}
			}, 1);
		}
	};
	
	var closeThisOne =  function () {
		 $(arguments[0].target).parents('DL').children('DD').slideToggle('fast');
		 var el = $(arguments[0].target);
		 if (el.text() == '-')
		 	el.text('+');
		else
			el.text('-');
	};
	
	var deleteThisOne = function () {
	 var target = arguments[0].target
	 $(target).parents('DL').slideToggle('fast', function () {
		 ($(target).parents('DL')).appendTo('#header');
	 	 
	 	 $(target).parents('DL').toggle();
	 });

	 
	}
	
	$(document).ready(function(){
		var els = ['#header', '#contentleft', '#contentright', '#contentmiddle'];
		var $els = $(els.toString());
		//$('dt', $els).append('<span class="options"><a class="close" title="Fold in">-</a><a class="delete" title="Close">x</a></span>');
		
		$('a.up, a.down').bind('click', moveUpDown);
		$('a.close').bind('click', closeThisOne);
		$('a.delete').bind('click', deleteThisOne);

		// Bind show/hide links
		$('a.hide').bind('click', hideThisOne);
		$('a.show').bind('click', showThisOne);

        // Hide draggable items before re-arranging them
        document.getElementById("contentleft").style.display = 'none';

        // Load positions from cookies
        retrieveModulePositionsFromSavedCookie();
        
        // Load module visibilites
        retrieveCookieWithModuleVisibility();

        // Show draggable items before re-arranging them
        document.getElementById("contentleft").style.display = '';



//		$('#contentmiddle').corner('10px');
//		$('#contentleft').corner('10px');
//		$('#contentright').corner('10px');

/*	$('DD').corner ('round bottom 10px')
		$els.each(function(){
			updateUpDown(this);
		});
*/
		$('#clickheader').bind('click', function () {
			$('#header').slideToggle('fast');
			var b = $('#clickheader span');
			if (b.text() =='+') 
				b.text('-');
			else
				b.text('+');
			
		}
		);
		
		
		$els.sortable({
			
			items: '> dl',
			handle: 'dtt',  // disabled by specified invalid tag
			cursor: 'move',
			//cursorAt: { top: 2, left: 2 },
			opacity: 0.8,
			helper: 'clone',
			appendTo: 'body',
			//placeholder: 'clone',
			placeholder: 'placeholder',
			connectWith: els,
			
			start: function(e,ui) {
				var w = ui.element[0].clientWidth;
				ui.placeholder.css('height', 50);
				ui.helper.css("width", w);
				
				if (e.target.parentNode.parentNode.id == 'header') {
					ui.helper.css("width", 200);
				}
				
			},
			change: sortableChange,
			update: sortableUpdate
		});
	});
	
	$(window).bind('load',function(){
		setTimeout(function(){
			$('#overlay').fadeOut(function(){
				$('body').css('overflow', 'auto');
			});
		}, 750);
	});
})(jQuery);

// Cookie functions

    var nameOfModulePositionsCookie = "SIP_Reordable_Modules_Positions";
    var nameOfModuleVisibilityCookie = "SIP_Reordable_Modules_Visibility";

	function Get_Cookie(name) { 
	   var start = document.cookie.indexOf(name+"="); 
	   var len = start+name.length+1; 
	   if ((!start) && (name != document.cookie.substring(0,name.length))) return null; 
	   if (start == -1) return null; 
	   var end = document.cookie.indexOf(";",len); 
	   if (end == -1) end = document.cookie.length; 
	   return unescape(document.cookie.substring(len,end)); 
	} 
	// This function has been slightly modified
	function Set_Cookie(name,value,expires,path,domain,secure) { 
		expires = expires * 60*60*24*1000;
		var today = new Date();
		var expires_date = new Date( today.getTime() + (expires) );
	    var cookieString = name + "=" +escape(value) + 
	       ( (expires) ? ";expires=" + expires_date.toGMTString() : "") + 
	       ( (path) ? ";path=" + path : "") + 
	       ( (domain) ? ";domain=" + domain : "") + 
	       ( (secure) ? ";secure" : ""); 
	    document.cookie = cookieString; 
	} 


    function hideThisOne () {
		 $(arguments[0].target).parents('dl').find('div').filter('.cm_body').slideUp('fast');
        window.setTimeout("updateCookieWithModuleVisibility();",500);
    }
    function showThisOne() {
		 $(arguments[0].target).parents('dl').find('div').filter('.cm_body').slideDown('fast');
        window.setTimeout("updateCookieWithModuleVisibility();",500);
    }


    function updateCookieWithModuleVisibility()
    {
        var elements = document.getElementsByTagName("dl");
        var s = "";
        // Build comma-separated list of items
        for(var i=0; i<elements.length; i++)
        {
            // Skip placeholder
            if (elements[i].id == "dl_0")
                continue;
            var visibility = $('#' + elements[i].id).find('div').filter('.cm_body').css('display');
            
            s+= elements[i].id + ";" + visibility + ",";
        }
        // Remove trailing comma
        if (s.length > 0)
            s = s.substr(0,s.length-1);
          
        Set_Cookie(nameOfModuleVisibilityCookie,s,60000);
    }

    function retrieveCookieWithModuleVisibility()
    {
        var positions = Get_Cookie(nameOfModuleVisibilityCookie);
        if (positions == null || positions.length == 0)
            return; // No cookies here
        
        // Split out positions
        var a = positions.split(',');
        
        for (var i=0; i<a.length; i++)
        {
            try {
            var id = a[i].split(';')[0];
            var visibility = a[i].split(';')[1];
            $('#' + id).find('div').filter('.cm_body').css('display',visibility);
            } catch (e){}
        }
    }
