/*
 * Goweb Sitemanager 5 Framework
 * @author     I&D <dev@goweb.pt>, Pedro Pinto <ppinto@goweb.pt>
 * @copyright  2009 (c) Goweb (http://www.goweb.pt)
 */

Element.childrenWithClassName = function(element, className) {
  return $A($(element).getElementsByTagName('*')).select(
    function(c) { return Element.hasClassName(c, className) });
}

/**
 * http://codeinthehole.com/archives/5-Javascript-cookie-objects-using-Prototype-and-JSON.html
 */
var Cookies = Class.create({
    initialize: function(path, domain) {
        this.path = path || '/';
        this.domain = domain || null;
    },
    // Sets a cookie
    set: function(key, value, days) {
        if (typeof key != 'string') {
            throw "Invalid key";
        }
        if (typeof value != 'string' && typeof value != 'number') {
            throw "Invalid value";
        }
        if (days && typeof days != 'number') {
            throw "Invalid expiration time";
        }
        var setValue = key+'='+escape(new String(value));
        if (days) {
            var date = new Date();
            date.setTime(date.getTime()+(days*24*60*60*1000));
            var setExpiration = "; expires="+date.toGMTString();
        } else var setExpiration = "";
        var setPath = '; path='+escape(this.path);
        var setDomain = (this.domain) ? '; domain='+escape(this.domain) : '';
        var cookieString = setValue+setExpiration+setPath+setDomain;
        document.cookie = cookieString;
    },
    // Returns a cookie value or false
    get: function(key) {
        var keyEquals = key+"=";
        var value = false;
        document.cookie.split(';').invoke('strip').each(function(s){
            if (s.startsWith(keyEquals)) {
                value = unescape(s.substring(keyEquals.length, s.length));
                throw $break;
            }
        });
        return value;
    },
    // Clears a cookie
    clear: function(key) {
        this.set(key,'',-1);
    },
    // Clears all cookies
    clearAll: function() {
        document.cookie.split(';').collect(function(s){
            return s.split('=').first().strip();
        }).each(function(key){
            this.clear(key);
        }.bind(this));
    }
});

function saveCookiePortal(nodeId){
	if (!$(nodeId)) return;
	if (nodeId == 'portal-column-block-list') return;
    var blocks = $(nodeId).childElements();
    var elements = '';
    if (blocks.length > 1){ 
  	  blocks.each(function (block) {
  		  if (block.id){
  			  if (elements.length > 0) elements += ',';
  			  elements += block.id;
  			  $$("#" + block.id + ' > .content').each(function (content) {
  				  if (content.style.display) elements += ':' + content.style.display; 
   			  });
  		  }

  	  });
		h3s = $(nodeId).getElementsByTagName('h2');
		for( var x = 0; x < h3s.length; x++ ){
			if (h3s[x].style.display != 'none') h3s[x].toggle();
		}

    } else {
	    h3s = $(nodeId).getElementsByTagName('h2');
	    for( var x = 0; x < h3s.length; x++ ){
	    	if (h3s[x].style.display == 'none') h3s[x].toggle();
	    }
    }
    if (!portalCookies){
  	  var portalCookies = new Cookies();
    }
    portalCookies.set(nodeId, elements, 10);
}

var Portal = Class.create();
Portal.prototype = {
  initialize: function (options) {
    this.setOptions(options);
    var sortables = $$('.' + this.options.column, '.' + this.options.portal);
    sortables.each(function (sortable) {
      Sortable.create(sortable, { 
        containment: sortables,
        constraint: false,
        tag: 'div',
        only: this.options.block,
        dropOnEmpty: true,
        handle: this.options.handle,
        hoverclass: this.options.hoverclass,
        onUpdate: function (container) {
          if (container.id == this.options.blocklist) {
            return;
          }
          saveCookiePortal(container.id);
        }.bind(this)
      });
    }.bind(this));
    
    var blocks = $$('.' + this.options.block, '.' + this.options.portal);
    blocks.each(
      function (block) {
  		var content = Element.childrenWithClassName(
          block, this.options.content, true
        );
        var toggle = Element.childrenWithClassName(
          block, this.options.toggle, true
        );
        var close_toggle = Element.childrenWithClassName(
                block, 'block-close', true
              );
        var plus_toggle = Element.childrenWithClassName(
                block, 'block-config', true
              );
        for(var i=0; i<toggle.length; i++) {
            Event.observe(
            toggle[i], 'click', 
            function (e) {
            	var node = 0;
            	for( var x = 0; this.parentNode.parentNode.childNodes[x]; x++ ){
            		if (this.parentNode.parentNode.childNodes[x].className == "content"){
            			node = x;
            		}
            	}
            	Effect.toggle(this.parentNode.parentNode.childNodes[node], 'Slide');
            	setTimeout("saveCookiePortal('"+block.parentNode.id+"');",2000);
            	},
            false
          );
        }
        for(var i=0; i<close_toggle.length; i++) {
            Event.observe(
    		close_toggle[i], 'click', 
            function (e) {
            	setTimeout("saveCookiePortal('"+block.parentNode.id+"');",2000);
            	$('portal-column-block-list').appendChild(this.parentNode.parentNode);
            	},
            false
          );
        }
        for(var i=0; i<plus_toggle.length; i++) {
            Event.observe(
            		plus_toggle[i], 'click', 
            function (e) {
            			alert(block.id);
            	//setTimeout("saveCookiePortal('"+block.parentNode.id+"');",2000);
            	//$('portal-column-block-list').appendChild(this.parentNode.parentNode);
            	},
            false
          );
        }
      }.bind(this)
    );
    Event.observe(
    		'portal-column-block-list-bt_close', 'click', 
    		function (e) {
    		    Effect.toggle('portal-column-block-list');
    		    Event.stop(e);
            	},
            false
          );
    Event.observe(
      this.options.blocklistlink, 'click', 
      this.displayBlockList.bindAsEventListener(this), 
      false
    );

    new Draggable(this.options.blocklist, {
        handle: this.options.blocklisthandle
      }
    );
    
  },

  displayBlockList: function (e) {
    Effect.toggle(this.options.blocklist);
    Event.stop(e);
  },

  setOptions: function (options) {
    this.options = {
      portal: 'portal',
      column: 'portal-column',
      block: 'block',
      content: 'content',
      handle: 'handle',
      hoverclass: 'block-hover',
      toggle: 'block-toggle',
      blocklist: 'portal-column-block-list',
      blocklistlink: 'portal-block-list-link',
      blocklisthandle: 'block-list-handle',
      saveurl: ''
    }
    Object.extend(this.options, options || {});
  },

  readCookie: function () {
	var sortables = $$('.portal-column');
	if (!portalCookies){
		var portalCookies = new Cookies();
	}
	sortables.each(function (sortable) {
		keys = portalCookies.get(sortable.id);
		if (keys){
			keyItems = keys.split(',');
			for ( i=0; i < keyItems.length; i++ ){
				key=keyItems[i].split(':');
				if ($(sortable.id) && $(key[0])){
					$(sortable.id).appendChild($(key[0]));
					if (key[1]){
						$$("#" + key[0] + ' > .content').each(function (content) {
							content.style.display = key[1]; 
						});
					} 
				}
			}
		}
	    var blocks = $(sortable.id).childElements();
	    var elements = '';
	    if (blocks.length > 1 && sortable.id != 'portal-column-block-list'){ 
			h3s = $(sortable.id).getElementsByTagName('h2');
			for( var x = 0; x < h3s.length; x++ ){
				if (h3s[x].style.display != 'none') h3s[x].toggle();
			}
	    }
	});
  },

  applySettings: function (settings) {
    for (var container in settings) {
      settings[container].each(function (block) {
        $(container).appendChild($(block));
      });
    }
  }
}