// Global Application JavaScripts
var TOOLTIP_PADDING = 2;

$(document).ready(function() {
	
	$.omnitureTracking = function (hier) {
		if (arguments.length > 0) {
		  var h = '';
		  for (var i = 0; i < arguments.length; i++) {
		    h += '|'+arguments[i];
		  }
		  s.hier1 = 'US|Travel|TravelPlanning'+h;
		}
		s.t();
	};
	
	$.prepareOmnitureText = function (text) {
	  return text.replace(/[^a-zA-Z0-9\s]+/g, '').replace(/\s+/g, '-');
	}
  
  $.toolTipOver = function (target, tooltip) {
    var position = target.offset();
    var top = 0, left = 0;
    
    // an additional 80 pixel offset is hardcoded for the my_link_planner 
    // tooltip, need to change the CSS and this to be more flexible
    if (tooltip.attr('id') == 'my_planner_link')
     left -= 80;
     
    if (tooltip.hasClass('down')) {
      top += position.top + target.height() + TOOLTIP_PADDING;
      left += (position.left - tooltip.width()/2 + target.width()/2 + TOOLTIP_PADDING);
    } else {
      top += position.top - tooltip.height() - TOOLTIP_PADDING;
      left += (position.left - tooltip.width()/2 + target.width()/2 + TOOLTIP_PADDING);             
    }
    tooltip.css({ 'top': top + 'px', 'left': left + 'px' });
    if (!target.hasClass('noanim'))
      tooltip.fadeIn('fast');
  };
  
  $.toolTipOut = function (target, tooltip) {
    if (!target.hasClass('noanim'))
      tooltip.fadeOut('fast');
  }

  jQuery.fn.pluck = function(key) {
    var plucked = [];
    this.each(function() {
      plucked.push(this[key])
    })
    return plucked;
  }

  // Determine if the Planner Entries on the page exist already in the user's collection.
  //  e.g.: $.includesPlannerEntries(TP_PLANNER_ENTRIES, data_on_page);
  $.includesPlannerEntries = function(in_session, on_page) {
    var all_exist = true;
    for (var key in on_page) {
      if (!in_session[key]) {
        all_exist = false;
      }
    }
    
    return all_exist;
  }

  $.postableHandler = function (e) {
    var target = $(this);
    var isAddAll = target.hasClass('addall');
    $.post(this.href, { 'authenticity_token': TP_AUTH_TOKEN }, function(data) {
      if (data) {
        if (isAddAll) {
          TP_PLANNER_ENTRIES = data
          $.setupAddItemButtons();
        } else {
          TP_PLANNER_ENTRIES.push(data);
        } 
        $.disableButton(target);
        $.setupTooltips();
        $.updateMyPlannerTotal();
        // give the user some notification
        $.toolTipOut(target, $('#add'+(isAddAll ? 'all' : '')).hide());
        $.toolTipOver(target, $('#added'+(isAddAll ? 'all' : '')+'-success').fadeIn('fast'));
    	  target.oneTime(1000, "hide", function() {
          $.toolTipOut(target, $('#added'+(isAddAll ? 'all' : '')+'-success').fadeOut('fast'));
        });
      } else {
        $.toolTipOut(target, $('#add'+(isAddAll ? 'all' : '')).hide());
      }
    }, 'json');
    return false;
  };
  $.setupPostables = function () {
    $('a.postable').click($.postableHandler);
  };
  
  $.disableButton = function (button) {
    var isAddAll= button.hasClass('addall')
    if (button == null) return;
    if (isAddAll)
      button.removeClass('addall').addClass('addedall_error')
    else
      button.removeClass('add').addClass('added_error')
    button.removeClass('postable').unbind('click', $.postableHandler)
      .click(function (e) { return false; }).children('img')
      .attr('src', isAddAll ? '/images/btn_added_all.gif' : '/images/btn_added.gif');
  };
  
  $.setupAddItemButtons = function () {
    for (var i = 0; i < TP_PLANNER_ENTRIES.length; i++) {
      var ptype = TP_PLANNER_ENTRIES[i]['planner_entry']['plannable_type'] || 'detail';
      var pid = TP_PLANNER_ENTRIES[i]['planner_entry']['plannable_id'] || 0;
      var button = $('#'+['add', ptype.toLowerCase(), pid.toString()].join('-')+'.add.postable');
      $.disableButton(button);
    }
    $('a.added_error').click(function (e) { return false; });

    if (DESTINATION_PLANNABLES != null) {
      // see if the add all button should be disabled
      if ($.includesPlannerEntries(TP_PLANNER_ENTRIES_LOOKUP, DESTINATION_PLANNABLES)) {
        $.disableButton($('.addall'))
      }
    }
  };
  
  $.setupTooltips = function () {
    $('.tooltip').each(function (index, element) {
      var config = {
           sensitivity: 1,
           interval: 100,
           timeout: 0,
           over: function (e) { $.toolTipOver($(e.target), $(element)); },
           out: function (e) { $.toolTipOut($(e.target), $(element)); }
      };
      var nm = element.className.replace(/\s*?down\s*?/, '').replace(/\s*?tooltip\s*?/, '').replace(' ', '');
      $('a.'+nm).hoverIntent(config);
    });
  };
  
  $.updateMyPlannerTotal = function () {
	var c = TP_PLANNER_ENTRIES.length || 0;
    $('a.my_planner_link').html('MyPlanner ('+c+')');
	$('.items_added_number').html(c);
  };
  
  $.setupAddItemButtons();
  $.setupTooltips();
  $.setupPostables();
  $.updateMyPlannerTotal();
});

/*
// from http://ajaxian.com/archives/jquery-bondage
jQuery.fn.bind = function (bind) {
     return function () {
          console.count("jQuery bind count");
          console.log("jQuery bind %o", this);
          return bind.apply(this, arguments);
      };
}(jQuery.fn.bind);
*/

// mimicking the console or browsers that do not support it
if (!window.console || !console.firebug) {
    var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml", "group", "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"];
    window.console = {};
    for (var i=0; i<names.length; ++i) window.console[names[i]] = function(){}
}

function alert() {
  console.log(arguments[0]);
};

