/***********************************************************************

    Station is a feed builder and API for content.

    Copyright (C) 2011 Kynan Stewart Hughes 

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

************************************************************************/

try { console.log('initialised.'); } catch(e) { console = { log: function() {} } }

station.global_sortable = {};

station.setMenu = function()
{
	//* SET THE MENU TO THE LAST STATE SAVED IN THE COOKIE *//
	// Get the array of open meny items from the cookie
    var a_open = station.getPropertiesFromCookie('menu');

	// if a_open isn't set, make an empty array so we don't
	// get an error when we try to loop over it
    if(!a_open)
    {
        a_open = new Array();
    }

	// Set a flag
	flag = false;	

	// Close all the ULs in the menu
    $('ul.menu-root ul').each(function(){
    
    	//alert($(this).attr("id"));
    		
		$(this).hide();	
		
		// Reopen each item in the array of open menu items,
	    for (j=0;j<a_open.length;j++)
	    {
	        if($(this).attr('id') == a_open[j])
	        {
	        	// Reset the flag to true - it's used
	        	// below for making the admin linkis visible
	        	// on the active menu
	        	flag = true;
				$(this).show();	
	            station.makeSortable($(this).attr('id'),$(this).parent().attr('id'));				
	        } 
	    }	    
	});
	
	// Hide all the admin lists
	$('ul.menu-root li.menu-admin-li ul').each(function(){
    
    	//alert($(this).attr("id"));
		$(this).hide();	
		
	});

	//* SET THE LAST ACTIVE MENU TO ACTIVE *//
	// Get the active item id from the cookie
	var active_li_id = station.getCookie('active_menu');
	
	// Make the last active item active again
	$('ul.menu-root li#'+active_li_id).addClass('active');
	
	//$('ul.menu-root li#'+active_li_id).siblings('menu-admin-li').children('ul').hide();
		
	// If the active menu is open, show the admin links
	if(flag)
	{
		$('ul.menu-root li#'+active_li_id).siblings(".menu-admin-li").children().show();
	}
	else
	{
		$('ul.menu-root li#'+active_li_id).siblings(".menu-admin-li").children().hide();
	}
	
	// IF THERE'S ONLY ONE MENU, OPEN IT - SEE site_template.rsml.php
	if(
		station.current_user_display_groups_count == 1
	)
	{
		//alert("HERE");
		$('ul.menu-root').children('li.menu-container-li').children('ul').show();
		$('ul.menu-root').children('li.menu-admin-li').children().show();
	}
	

	//* OPEN AND CLOSE THE MENU ON CLICK *//
	$('#navigation').click(function (e) {
		if ($(e.target).is('li.menu-container-li span'))
		{
			// Test if _any_ of the children are open
			children_are_open = false;
			
			$(e.target).parent().parent().children().filter('ul').each(function(){
				//alert($(this).css('display'));
				if($(this).css('display')=='block')
				{
					// Set the flag
					children_are_open = true;
				}
			});
			
			
			$(e.target).parent().parent().children().filter('ul').each(function(){
				if(!children_are_open)
				{
					$(this).slideDown('fast', function(){
					
						// Stopped the empty feed bug… somehow
						if($(this).attr('id'))
						{
	                        console.log("adding "+$(this).attr('id')+" to the cookie");
		            		station.addToMenuCookie($(this).attr('id'));				
		            		station.makeSortable($(this).attr('id'),$(this).parent().attr('id'));				
						}
					});
				}
				else
				{
					$(this).slideUp('fast', function(){
	            		station.removeFromMenuCookie($(this).attr('id'));				
	            		station.makeUnsortable($(this).attr('id'));				
					});
					
					if ($(e.target).parent().parent().is('li.top'))
					{
						$(e.target).parent().parent().siblings(".menu-admin-li").children().hide();
					}

				}
			});
			return false;
		}
	});

    // When changing active feeds, close all feeds and then
    // set a new one to active state
	$('#navigation li.menu-container-li.top').click(function (e) {
		
		// Close all the non-active item ULs
		if(!$(this).hasClass("active"))
		{
			$('ul.menu-root ul').each(function(){
				$(this).slideUp('fast', function(){
					// Remove from the cookie
		            station.removeFromMenuCookie($(this).attr('id'));
				});
			});
		}		
			
		// Take the active class off all menu items
		$('#navigation li.menu-container-li.top').each(function (e) {
			//Take off the active class
			$(this).removeClass('active');
			// Hide the admin items
			$(this).siblings(".menu-admin-li").children().hide();
		});
		
		// Make the clicked one acitive
		$(this).addClass('active');
		// Show the admin links
		$(this).siblings(".menu-admin-li").children().show();
		// Set the cookie
		station.setCookie('active_menu', $(this).attr('id'));
	});	
}
	
station.setCookie = function(name, value, expires, path, domain, secure)
{
    var today = new Date();
    today.setTime( today.getTime() );
    
    /*
    if the expires variable is set, make the correct 
    expires time, the current script below will set 
    it for x number of days, to make it for hours, 
    delete * 24, for minutes, delete * 60 * 24
    */
    if ( expires )
    {
    expires = expires * 1000 * 60 * 60 * 24;
    }
    var expires_date = new Date( today.getTime() + (expires) );
    
    document.cookie = name + "=" +escape( value ) + ( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) + ";path=/" + ( ( domain ) ? ";domain=" + domain : "" ) + ( ( secure ) ? ";secure" : "" );
    //alert(document.cookie);
}

station.getCookie = function( check_name )
{
    var a_all_cookies = document.cookie.split( ';' );
    var a_temp_cookie = '';
    var cookie_name = '';
    var cookie_value = '';
    var b_cookie_found = false;
    
    for ( i = 0; i < a_all_cookies.length; i++ )
    {
        a_temp_cookie = a_all_cookies[i].split( '=' );
        cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');
        
        if ( cookie_name == check_name )
        {
            b_cookie_found = true;
            cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
            return cookie_value;
            break;
        }
        a_temp_cookie = null;
        cookie_name = '';
    }
    if ( !b_cookie_found )
    {
        return null;
    }
}

station.addToMenuCookie = function( elm_id )
{
    a_open = station.getPropertiesFromCookie("menu");

    if(a_open)
    {
        a_open.push(elm_id);
    }
    else
    {
        a_open = new Array(elm_id) 
    }

    station.savePropertiesToCookie("menu",a_open)
}

station.removeFromMenuCookie = function( elm_id )
{
    a_open = station.getPropertiesFromCookie("menu");
    
    if(a_open)
    {
        a_open.splice(a_open.indexOf(elm_id), 1);
        station.savePropertiesToCookie("menu",a_open)
        //alert(a_open);
    }
}

station.makeSortable = function( elm_id, container_id )
{
    // Check if this is really a sortable, list of Modules
    // or if it's just a menu item that happens to be a list
    // (like, a list of Containers)
    var patt1=/_feed/;
     
    if(elm_id.match(patt1)){
        return false;
    }
    else
    {
        // First, update the global object of sortable lists
        station.global_sortable[elm_id] = true;
    }

    console.log("making "+elm_id+" of container "+container_id.replace('container-','')+" sortable");

    // At this stage, we're not using the container_id
    var container_id = container_id.replace('container-','');

    $( '#'+elm_id ).sortable();
    //$( '#'+elm_id ).disableSelection();

    // A fix for the helper top issue in FF when the
    // containing element is position:absolute
    var userAgent = navigator.userAgent.toLowerCase();
    if(userAgent.match(/firefox/)) {
        $( '#'+elm_id ).bind( "sortstart", function (event, ui) {
            ui.helper.css('margin-top', $(window).scrollTop() );
        });
        $( '#'+elm_id ).bind( "sortbeforestop", function (event, ui) {
            ui.helper.css('margin-top', 0 );
        });
    }

    // For all sortable lists, connect with all
    // other sortable lists - again
    for(primary_list_element_id in station.global_sortable)
    {
        for(secondary_list_element_id in station.global_sortable)
        {
            if(primary_list_element_id != secondary_list_element_id)
            {
                console.log( 'connect #'+primary_list_element_id+ ' with #' + secondary_list_element_id );
                $( '#'+primary_list_element_id ).sortable( "option", "connectWith", '#'+secondary_list_element_id );
            }
        }
    }

    data = "h=AjaxResetWeights&container_id="+container_id+"&"+$( '#'+elm_id ).sortable('serialize');
    console.log( "setting: "+data );

    // Get the Container's container_id for the backend
    $( '#'+elm_id ).bind( "sortstop", function(event, ui) {

        // At this stage, we're not using the container_id
        var local_container_id = ui.item.parent().parent().attr('id').replace('container-','');
        console.log( "local_container_id: "+local_container_id );
        var local_elm_id = ui.item.parent().attr('id');
        console.log( "local_elm_id: "+local_elm_id );

        data = "h=AjaxResetWeights&container_id="+local_container_id+"&"+$( '#'+local_elm_id ).sortable('serialize');
    console.log( "setting: "+data );

        $.ajax({
           type: "POST",
           url: "/",
           data: data,
           success: function(msg){
             console.log( ": " + msg );
             //console.log( "items re-sorted" );
           }
         });
    });

}

station.makeUnsortable = function( elm_id )
{
    console.log( '#'+elm_id +' disable');
    //$( '#'+elm_id ).sortable('disable');
}

station.savePropertiesToCookie = function( cookie_name, a_values )
{
    var value = null;

    for (var i=0; i < a_values.length; i++)
    {
        if(value)
        {
        	//alert(a_values[i]);
            value += "::::" + a_values[i];
        }
        else
        {
            value = a_values[i];
        }
    }


    station.setCookie( cookie_name, value );
}

station.getPropertiesFromCookie = function( cookie_name )
{
    var ret = null;
    var properties = station.getCookie( cookie_name );

    if(properties)
    {
        obj_properties = new String(properties);
        a_properties = obj_properties.split('::::');
        ret = a_properties;
    }

    return ret;
}

