
var objlist = new Array();

/*
 * Handles pictures coming into and out of the 
 */
var recentlyAdded;

RecentlyAdded = new Class({
  initialize: function(container, options) {
    this.options = options ? options : {};
    this.maxItems = (this.options.maxItems) ? (this.options.maxItems) : 9;
    this.numItems = (this.options.numItems) ? (this.options.numItems) : 0;
    this.container = $(container);
    
    //Clear the container of any whitespace nodes
    if (!this.container) {
      this.inactive = 1; 
    }
  },
  
  /**
   * Adds a hotlist to the recently added module
   */
  addPix: function(id, pid) {
    if (this.inactive == 1) { return; }
    //If we have hit the maxItems number of items, we have to remove the last pic from the queue
    if (this.numItems >= this.maxItems) {
      //Remove the last non whitespace child
      this.container.removeChild(this.container.getLast());
      this.numItems = this.maxItems;
    } else {
      this.numItems++; 
    }
    //Add the img
    var div = document.createElement('div');
      div = $(div);
      div.addClass('brand_tiny_image');
      div.id = 'ra_' + id;
    
    var img = document.createElement('img');
      //img.setStyle('display', 'none');
      img = $(img);
      img.setStyle('opacity', 0);
      img.src = tinyImages[pid ? pid : id];      
    
    div.appendChild(img);  
      
    new Fx.Style(img, 'opacity', {duration:500}).start(0,1);  
      
    if (this.numItems == 1) {
      this.container.innerHTML = '';
      this.container.appendChild(div);  
    } else {
      if (this.container.firstChild) {
        this.container.insertBefore(div, this.container.firstChild);
      }
    }
  },
  
  changePic: function(bid, pid) {
    var obj = $('ra_' + bid);
    if (obj) {
      obj.innerHTML = ''; 
      this.newPicInDiv(obj, tinyImages[pid]);
    }
  },
  
  newPicInDiv: function(containerDiv, imgUrl) {
    var img = document.createElement('img');
    //img.setStyle('display', 'none');
    img = $(img);
    img.setStyle('opacity', 0);
    img.src = imgUrl;      

    containerDiv.appendChild(img);  

    new Fx.Style(img, 'opacity', {duration:500}).start(0,1);
  },
  
  /**
   * Removes a pix from our queue
   */
  removePix: function(id) {
    if (this.inactive == 1) { return; }
    if ($('ra_'+id)) {
      new Fx.Style($('ra_'+id), 'opacity', {duration: 500, onComplete: function() { this.container.removeChild($('ra_'+id)) }.bind(this)}).start(1,0);
      this.numItems--;
    }
  },
  
  /**
   * changes back to default assuming the presence of tiny_pics with the key 'default'
   */
  changeToDefault: function(id) {
    this.changePic(id, 'default');
  }
  
});

objFade = {};

var BrandController = new Class({

  init: function(options) {
    this.options = options ? options : {};
    
    if (this.options.brandbox) {
      var brand_thumb = this.options.brand_thumb ? this.options.brand_thumb : '.brand_thumb_div';
      var brand_plus = this.options.brand_plus ? this.options.brand_plus : '.brand_thumb_smplus';
      var brand_x = this.options.brand_x ? this.options.brand_x : '.brand_thumb_smx';
      var brandsize = this.options.brand_size ? this.options.brand_size : '.thumb_sm';
    } else {
      var brand_thumb = '.brand_thumb_div';
      var brand_plus = '.brand_thumb_smplus';
      var brand_x = '.brand_thumb_smx';
      var brandsize = 'thumb_sm';
    }

    //Attach mouseover/mouseout event for all the buttons  
    if (brand_thumb) {
      $$(brand_thumb).each(function(e) { 
        //Figure out the id 
        var id = e.id.substr(0, e.id.indexOf('_')); 
        e.addEvent('mouseover', function() { bc.mouseOver(id); });
        e.addEvent('mouseout', function() { bc.mouseOut(id); });
      }); 
    }
       
    if (brand_thumb) {
      $$(brand_plus).each(function(e) { 
        //Figure out the id 
        var id = e.id.substr(0, e.id.indexOf('_')); 
        e.addEvent('mouseover', function() { e.addClass('brand_'+brandsize+'plus_hilite'); }); 
        e.addEvent('mouseout', function() { e.removeClass('brand_'+brandsize+'plus_hilite'); }); 
        e.addEvent('click', function() { bc.addToList(id); }); 
      }); 
    }

    if (brand_x) {
      $$(brand_x).each(function(e) { 
        //Figure out the id 
        var id = e.id.substr(0, e.id.indexOf('_')); 
        e.addEvent('mouseover', function() { e.addClass('brand_'+brandsize+'x_hilite'); }); 
        e.addEvent('mouseout', function() { e.removeClass('brand_'+brandsize+'x_hilite'); }); 
        e.addEvent('click', function() { bc.removeFromList(id); }); 
      }); 
    }
   
  },
 
  
  //We use this function to specify if we're on a brand page (the javascript is slightly different due to the Add/Remove link)
  targetBrand: function(bid) {
    this.target_bid = bid;
  },
  
  mouseOver: function(id) {
    if(objlist[id]) {
      $(id + '_x').setStyle('display', 'inline');
      if (!objFade[id]) {
        $(id + '_added').setStyle('display','inline');
      }
    } else {
      $(id + '_div').addClass('brand_thumb_div_hilite');
    }
  },

  mouseOut: function(id) {
    $(id + '_div').removeClass('brand_thumb_div_hilite');
    if(objlist[id]) {
      $(id + '_x').setStyle('display', 'none');
      if (!objFade[id]) {
        $(id + '_added').setStyle('display','none');
      }
    } 
  },

  addToList: function(bid) {
    if (!loggedIn) {
        var doc = parent ? parent.document : document;
        var loc = 'http://www.hotornot.com/login/?target=' + escape(doc.location);
        doc.location = loc;
        return false;
    }
    var url = WEBROOT + '/ajax/b/?method=AddBrand&brand_id=' + bid;

    var ajax = new Ajax(url, {
      method: 'get',
      onComplete: function(res) { bc.handleAdd(bid, res); }
    });
    
    if (recentlyAdded) {
      //Add to recently added
      recentlyAdded.addPix(bid);
    }
    
    ajax.request(); 
  },

  handleAdd: function(bid,res) {
    if (!bid) return;
    
    if(!res || res == 0 || !this.checkLogin(res, 'add', bid)) {
      //alert('There was an error, please try again.');
      //$(bid + '_plus').setStyle('display', 'inline');
      //return;
       return;
    }
    
    objlist[bid] = 1;
    
    if ($(bid + '_plus')) {
      $(bid + '_plus').setStyle('display', 'none');
    }

    
    if ($(bid + '_div')) {
      //$(bid + '_div').removeClass('brand_thumb_div_hilite');
      //$(bid + '_div').addClass('brand_thumb_div_added');
    }
   
    if ($(bid + '_plus')) {
      $(bid + '_plus').setStyle('display', 'none');
    }
    
    if ($(bid + '_x')) {
      $(bid + '_x').setStyle('display', 'inline');
    }
    
    if ($(bid + '_added')) {
      $(bid + '_added').setStyle('opacity', 0);
      $(bid + '_added').setStyle('display','inline');
      
      //This next section creates the fade-in fade out for the added to hotlist.
      //Prevent a mouse out to cancel the animation too early
      objFade[bid] = 1;
      
      var bid_id = bid;
      
      var fx = new Fx.Style(bid + '_added', 'opacity');
      fx.start(0,0.9).chain( function() { 
         window.setTimeout(function() { 
           new Fx.Style(bid + '_added', 'opacity', { 
             onComplete : function(obj) { 
               var bid = obj.id.substr(0, obj.id.indexOf('_'));
               //Hide it, but set opacity back to one for the mouseovers
               obj.setStyle('display', 'none'); 
               obj.setStyle('opacity', 1); 
               
               //Renable the mouseovers
               objFade[bid_id] = 0; 
             }
           }).start(0.9, 0) }, 1000)
         });
      //fx.start(0, 0.9);
    }
    
    //On the brand page
    if (this.target_bid == bid) {
      $('brand_add_div').style.display = 'none';
      $('brand_remove_div').style.display = 'block';
    }
    
    },

  removeFromList: function(bid) {
    var url = WEBROOT + '/ajax/b/?method=RemoveBrand&brand_id=' + bid;
    
    if ($(bid + '_x')) {
      $(bid + '_x').setStyle('display', 'none');
    }
  
    var ajax = new Ajax(url, {
      method: 'get',
      onComplete: function(res) { bc.handleRemove(bid, res); }
      });
  
    ajax.request(); 
    
    //Add to recently added
    if (recentlyAdded) {
      recentlyAdded.removePix(bid);
    }
    
  },

  handleRemove: function(bid, res) {
    if (!bid) return;
    if(!res || res == 0 || !this.checkLogin(res, 'remove', bid)) {
      //alert('There was an error, please try again.');
      //$(bid + '_x').setStyle('display', 'inline');
      //return;
      return;
    }
    
    objlist[bid] = 0;
    $(bid + '_added').setStyle('display', 'none');
    $(bid + '_div').removeClass('brand_thumb_div_added');
    $(bid + '_x').setStyle('display','none');
    
     //On the brand page
    if (this.target_bid == bid) {
      $('brand_add_div').style.display = 'block';
      $('brand_remove_div').style.display = 'none';
    }
  },

  checkLogin: function(res, action, bid) {
    if(res == -1) {
      //The user isn't logged in (check to see if they were when the page started)
      if (!loggedIn) {
        if (action == 'add') {
        	//First check to see if we're over the max limit
        	var hotlist = CookieTalk.getHotlist();
        	if (!hotlist || hotlist.length < 2) {
          	var flash_response = CookieTalk.addHOTList(bid);
          	return true;
        	} else {
          	//Show the moobox if it's available
          	$('login_link').fireEvent('click');
            return false;	
        	}
      	} else if (action == 'remove') {
        	var flash_response = CookieTalk.removeHOTList(bid);
      	}
      } else {
        var doc = parent ? parent.document : document;
        var loc = 'http://www.hotornot.com/login/?target=' + escape(doc.location);
        doc.location = loc;
        return false;
      }
    }

    return true;
  },

  //-jl
  rateBrandItem: function(biid,rating) {
      if (isNaN(rating)) return false;
      var url = WEBROOT + '/ajax/b/?method=RateBrandItem&branditem_id=' + biid + '&rating=' + rating;
      var ajax = new Ajax(url, {
        method: 'get',
          onComplete: function(res) {
          if (res == 0) {
            alert('Error');
          } else {
            $(biid + '_ratebox').innerHTML = res;
            var myFx = new Fx.Style(biid + '_ratebox', 'opacity').start(0,1);
          }
        }
        });
      
      ajax.request(); 
      return true;
    }

}); 

var HotlistController = BrandController.extend({
  mouseOver: function(id) {
    if(objlist[id]) {
      $(id + '_x').setStyle('display', 'inline');
      //$(id + '_added').setStyle('display', 'inline');
    } else {
      $(id + '_div').addClass('brand_thumb_div_hilite');
    }
  },

  handleRemove: function(bid, res){
    if(!res || res == 0 || !this.checkLogin(res)) {
      //alert('There was an error, please try again.');
      //$(bid + '_x').setStyle('display', 'inline');
      //return;
    }

    objlist[bid] = 0;
    $(bid + '_added').setStyle('display','none');
    var fx = new Fx.Style(bid + '_div', 'opacity');
    fx.chain(function() { $(bid + '_div').setStyle('display','none'); });
    fx.start(1, 0);
  }
});
//Override the default ToolTip behavior to display even if the title is empty
var BrandTips = Tips.extend({
	build: function(el){
		//el.myTitle = el.href ? el.href.replace('http://', '') : (el.rel || false);
		if (el.title){
			var dual = el.title.split('::');
			if (dual.length > 1) {
				//el.myTitle = dual[0].trim();
				el.myText = dual[1].trim();
			} else {
				el.myText = el.title;
			}
			el.removeAttribute('title');
		} else {
			el.myText = false;
		}
		//if (el.myTitle && el.myTitle.length > this.options.maxTitleChars) el.myTitle = el.myTitle.substr(0, this.options.maxTitleChars - 1) + "&hellip;";
		if (el.myText) {
  		el.addEvent('mouseover', function(event){
      	this.start(el);
    		this.locate(event);
    	}.bindWithEvent(this));
    	if (!this.options.fixed) el.addEvent('mousemove', this.locate.bindWithEvent(this));
    	el.addEvent('mouseout', this.end.bindWithEvent(this));
  	}
	}
});
