// $Id: memoryblock.js,v 1.1 2007/08/23 06:56:29 silviogutierrez Exp $

/**
 * Make all blocks collapsible.
 */
$(document).ready(function () {

  $(".block").each(function(i) { //Go through every block being shown.
  	 
  	//Obtain the pointers to all the elements we are going to use.  
    var id = $(this).attr("id");
    var top = $(this).children().eq(0);
    var bottom = $(this).children().eq(1);
    
    var setting = Drupal.settings.memoryblock.blocks[this.id] ? Drupal.settings.memoryblock.blocks[this.id] : Drupal.settings.memoryblock.default_state;
    var status = readCookie(id); //Try to see if the user has a setting for this block already.
    var recentlyOpened;
    
    if (setting == 1 || id == null) { //Abort if block is not collapsible, or has no id.
      return;
    }

    if (status == 'closed' || (status == null && setting == 3)) { //If the setting is closed, or not found, close the block.
      top.attr("class","blockTop"); //Add or change the class of the title for custom theming when closed.
      createCookie(id, 'closed', 1); 
      bottom.hide(); //Hide by default, and ensure the cookie remains with the closed setting.
    }
    else if (status != 'closed' && status == 2) {
      top.attr("class","blockTopOpen") 
      createCookie(id, 'open', 1); 
    }
      top.click(function () {
        recentlyOpened = false;

        if (readCookie(id) == 'closed') {	
          top.attr("class","blockTopOpen"); //Allow custom theming of open block tops.
          recentlyOpened = true; //Make sure the close function below doesn't undo our changes.
          createCookie(id, 'open', 1);
        }		

          bottom.slideToggle('500', function() { //The actual event.

            if (readCookie(id) == 'open' && !recentlyOpened) {
              top.attr("class","blockTop");
              createCookie(id, 'closed', 1);
            }
            //Note that whenever a block is opened, the class of the top is changed first, then the block is opened. 
            //This is to prevent misalignment issues if you chose to make open tops bigger than closed ones.                                 
          });
      });


  }); 
});


/**
 * Common functions.
 */
function createCookie(name,value,days) {
  if (days) {
    var date = new Date();
    date.setTime(date.getTime()+(days*24*60*60*1000));
    var expires = "; expires="+date.toGMTString();
  }
  else {
    var expires = "";
  }

  document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {

  var nameEQ = name + "=";
  var ca = document.cookie.split(';');
  
  for(var i=0;i < ca.length;i++) {
    var c = ca[i];

    while (c.charAt(0)==' ') {
      c = c.substring(1,c.length);
    }

    if (c.indexOf(nameEQ) == 0) {
      return c.substring(nameEQ.length,c.length);
    }

  }
  return null;
}


function eraseCookie(name) {
  createCookie(name,"",-1);
}


