var Evidente = Class.create({
  debug : false,
  
  initialize: function (debug){
    this.debug = debug || false;
    this.log('Staring ...');
  },
  
  log : function(arg1, arg2){
    if(this.debug)
    {
      if(typeof(arg2) == 'undefined')
      {
        console.debug(arg1);
      }
      else
      {
        console.debug(arg1, arg2);
      }
    }
  }
});

Evidente.Observer = Class.create(Evidente, {
  observers : {
    onLoad  : [],
    onGhost : [] 
  },

  registerOnLoad: function(func){
    this.observers.onLoad[this.observers.onLoad.length] = func;
  },
  
  registerForGhost: function (ghost_){
    this.observers.onGhost[this.observers.onGhost.length] = ghost_;
  },
  
  notify: function (time){
    if(time == 'load')
    {
      if(this.observers.onLoad.size() > 0)
      {
        this.log('Call ...');
        this.observers.onLoad.each(function(item){
          item.notify();
        });
      }
    }
    else if(time=='ghost')
    {
      if(this.observers.onGhost.size() > 0)
      {
        this.log('Call..');
        this.observers.onGhost.each(function(item){
          item.notify();
        });
      }
    }
  }
});

Evidente.Subject = Class.create(Evidente, {
  name  : 'Subject',
  func  : null,
  
  notify: function(){
    this.log('Call to ' + this.name);
  }
}); 

var GhostPlace = Class.create({
  label : '',
  url   : '',
  container : '',
  separator : '',
  isAjax : true,
  ghostPathLinkTemplate : new Template('<a href="#{url}" id="#{id}" onclick="ghost.doPlace(#{index_}); event.returnValue=false; return false;" class="tdazul">#{label}</a>#{separator}'),
  ghostPathTextTemplate : new Template('<em class="tdazul"> #{label}</em>'),
  ghostPathLinkBackTemplate : new Template('<a href="#" onclick="ghost.doPlace(#{index_}); event.returnValue=false; return false;">Regresar</a>'),
  
  toPathString : function (index){
    values = {
      url: this.url, 
      id: 'linkGhost'+index, 
      label: this.label, 
      separator: this.separator,
      index_: index
    };
    if(Object.isNumber(index))
    {
      return this.ghostPathLinkTemplate.evaluate(values);
    }
    else
    {
      return this.ghostPathTextTemplate.evaluate(values);
    }
  },
  
  toBackString : function(index){
    return this.ghostPathLinkBackTemplate.evaluate({index_: index});
  },
  
  doPlace : function(){
    if(this.isAjax)
    {
      new Ajax.Updater(this.container, this.url, {evalScripts:true, requestHeaders:['X-Update', this.container]});
    }
    else
    {
      location.href = this.url;
    }
  },
  
  initialize : function (label, url, container, ajax){
    this.label = label;
    this.url   = url;
    this.container = container;
    if(typeof(ajax) == 'undefined' )
    {
      this.isAjax = true;
    }
    else
    {
      this.isAjax = ajax;
    }
  }
});

var Ghost = Class.create({
  separator : '&nbsp;>&nbsp;',
  
  places : new Hash(),
  
  length : function(){
    return this.places.size();
  },
  
  showGhostPath : function () {
    if($('divGhostContent'))
    {
      $('divGhostContent').innerHTML = '';
      $('divGhostBack').innerHTML    = '';
      places_ = this.places.values(); 
      path    = places_.without(places_.last()); 
      path.each(function(item, index){
        $('divGhostContent').innerHTML += item.toPathString(index);
      });
      if(path.size() >= 1)
      {
        $('divGhostBack').innerHTML = path.last().toBackString(path.size() - 1);
      }
      $('divGhostContent').innerHTML += places_.last().toPathString();
    }
  },
  
  showClose     : function () {},
  
  doPlace : function (index){
    places = this.places.values();
    places[index].doPlace();
    n = this.length() - 1;
    while (n > index)
    {
      this.removeGhostPlace(places[n--]);
    }
    this.showGhostPath();
  }, 
  
  addGhostPlace : function (place){
    place.separator = this.separator;
    this.places.set(place.url, place);
  },
  
  removeGhostPlace : function (place){
    this.places.unset(place.url);
  }
});

Evidente.Ghost = Ghost;

Evidente.refreshBriefcase = function(){
  new Ajax.Updater($('mini-briefcase-content'), '/briefcase/minibriefcase', 
      { asynchronous:true, evalScripts:true, requestHeaders:['X-Update', 'mini-briefcase-content']});
};

var evidente          = new Evidente(false);
var evidente_observer = new Evidente.Observer();
var ghost             = new Evidente.Ghost();
Event.observe(window, 'load', function(){ evidente_observer.notify('load'); evidente_observer.notify('ghost'); });
ghost.addGhostPlace(new GhostPlace('Inicio', '/', 'home_main', false));

var ghostSubject = Class.create(Evidente.Subject, {
  name  : 'Ghost',
  ghost : null,
  
  initialize : function (ghost_){
    this.ghost = ghost_;
  },
  
  notify: function(){
    this.log('Call to ' + this.name);
    this.ghost.showGhostPath();
  }
}); 
evidente_observer.registerForGhost(new ghostSubject(ghost));

var init_basic = Class.create(Evidente.Subject, {
  name : 'Basic',
  notify : function(){
    this.log('Call to ' + this.name);
    Shadowbox.init({
      animate: true,
      animateFade: true,
      flashBgColor: "#EFEFEF",
      fadeDuration: 0.1,
      resizeDuration: 0.2,
      overlayOpacity: 0.3
    });
    if($('ajax_loader'))
    {
      $('ajax_loader').hide();
    }
  }
});

function synchTab(frameName) 
{
  var elList, i;
  // Exit if no frame name was given.
  if (frameName == null)
  {
    return;
  }

  // Check all links.
  elList = document.getElementsByTagName("A");
  for (i = 0; i < elList.length; i++)
  {
    // Check if the link's target matches the frame being loaded.
    if (elList[i].target == frameName) 
    {
      // If the link's URL matches the page being loaded, activate it.
      // Otherwise, make sure the tab is deactivated.
      if (elList[i].href == window.frames[frameName].location.href) 
      {
        elList[i].className += " activeTab";
        elList[i].blur();
      }
      else
     {
        removeName(elList[i], "activeTab");
      }
    }
  }
}

function removeName(el, name) 
{
  var i, curList, newList;
  // Remove the given class name from the element's className property.
  newList = new Array();
  curList = el.className.split(" ");
  for (i = 0; i < curList.length; i++)
  {
    if (curList[i] != name)
    {
      newList.push(curList[i]);
    }
  }
  el.className = newList.join(" ");
}

/*****************************************************/
function showEvento(stock_id, stock_name)
{
  elemento = ($('home_main')) ? ('home_main') : ('containerMain');
  if(typeof(stock_name) == 'undefined')
  {
    stock_name = 'Detalles del Evento';
  }
  ghost.addGhostPlace(new GhostPlace(stock_name, '/ver_evento/' + stock_id, elemento));
  new Ajax.Updater(elemento, '/ver_evento/' + stock_id, 
                   { asynchronous:true, evalScripts:true, requestHeaders:['X-Update', elemento]});
  ghost.showGhostPath();
};
/*****************************************************/

function ajax_loader_fnc(){
  if($('ajax_loader'))
    $('ajax_loader').toggle();
}

Ajax.Responders.register({
  onCreate: function(){
    if($('ajax_loader') && $('ajax_loader').getStyle('display') == 'none')
    {
      $('ajax_loader').show();
      if($('divGhostBack'))
      {
        $('divGhostBack').hide();
      }
    }
  },
  onComplete: function(){
    if($('ajax_loader') && $('ajax_loader').getStyle('display') !== 'none')
    {
      $('ajax_loader').hide();
      if($('divGhostBack'))
      {
        $('divGhostBack').show();
      }
    }
  },
  onFailure : function(){
    alert('Hubo un error en el procesamiento de la petición');
  }
});

window.ajax_loader_fnc = ajax_loader_fnc;

window.showEvento = showEvento;

window.refreshing_ticker = function(){
  new Ajax.Request('/home/ticker', {
    asynchronous:true, 
    onCreate: function(){
      TICKER_REFRESHING = true;
    },
    onSuccess: function(response){
      TICKER_CONTENT = response.responseText;
    }
  });
};

window.tooltipPaso = function (paso) {
  new Ajax.Request('/help/paso' + paso, {
    method : 'get',
    onSuccess: function(response){
	  switch (paso) {
	    case 1: TOOLTIPPASO1 = response.responseText; break;
	    case 2: TOOLTIPPASO2 = response.responseText; break;
	    case 3: TOOLTIPPASO3 = response.responseText; break;
	  }
    }
  });
}