var AppR2 = {};
var $j = jQuery.noConflict();

AppR2.SavedVacation = {
  initialize: function () {
    this.bind_delete();
    this.bind_widget();
    this.bind_view();
  },

  element: function () {
    return $j('#user_saved_vac', top.document);
  },

  update_count: function (count) {
    $j('#user_saved_vac .value', top.document).html(count.toString());
  },

  get_count: function () {
    return parseInt($j('#user_saved_vac .user_messageCount', top.document).html());
  },

  increment_count: function () {
    this.update_count(this.get_count() + 1);
  },

  decrement_count: function () {
    this.update_count(this.get_count() - 1);
  },

  close: function () {
   this.element().qtip("hide");
  },

  open: function () {
   this.element().qtip("show");
  },

  get_host: function () {
    return App.r2.base_url();
  },

  bind_counter: function () {
    var intCookie = YAHOO.util.App.IntCookie.get();
    // Initialize the Saved Vacation dashboard counter if it's not set
    if (intCookie && intCookie.vac && intCookie.vac < 0) {
      AppR2.SavedVacation.update_count(0);
      $j.getJSON(AppR2.SavedVacation.get_host() + '/vacations/saved?format=json&jsoncallback=?',
        AppR2.SavedVacation.process_json);
    }
  },

  bind_widget: function() {
    var updated = YAHOO.util.App.IntCookie.has_updated_vacations();

    AppR2.SavedVacation.element().qtip({
      content: {
        prerender: !updated,
        text: '',
        title: { 'text': ' ', 'button': '&nbsp;' }
      },
      position: {
        target: $j('#secondary #tools #user_saved_vac'),
        corner: { 'target': 'bottomRight', 'tooltip': 'topRight' },
        adjust: {x: -1, y: 0}
      },
      style: {
        tip: false,
        width: 500,
        color: 'black',
        title: { 'background-color': 'transparent' },
        classes: {
          title: 'saved_vacations_title',
          content: 'saved_vacations_content',
          tooltip: 'saved_vacations_modal'
        }
      },
      show: { delay: 1, when: { event: 'click' }},
      hide: { delay: 0, when: { event: 'click' }},
      api: {
        onContentUpdate: AppR2.SavedVacation.bind_delete,
        onRender: AppR2.SavedVacation.classify,
        beforeHide: AppR2.SavedVacation.before_hide,
        beforeShow: AppR2.SavedVacation.before_show,
        beforeContentUpdate: AppR2.SavedVacation.before_content_load
      }
    });
  },

  process_json: function (data) {
    if (!data) return;

	AppR2.SavedVacation.update_count(data.length);
    YAHOO.util.App.IntCookie.update_saved_vacations(data.length);

	var results = AppR2.SavedVacation.create_results(data);
	$j('.saved_vacations_content').html(results);
  },

  before_content_load: function () {
  	$j.getJSON(AppR2.SavedVacation.get_host() + '/vacations/saved?format=json&jsoncallback=?', AppR2.SavedVacation.process_json);
  	return "";
  },

  before_hide: function () {
    $j('.saved_vacations_modal').css('display', 'none');
    $j('#user_saved_vac').css({'background-color': '#1C4865', 'color': '#81C8E8'});
    return true;
  },

  before_show: function () {
    $j('.saved_vacations_modal').css('display', 'inline');
    $j('#user_saved_vac').css({'background-color': '#81C8E8', 'color': 'white'});
    return true;
  },

  classify: function () {
    var tip_parts = AppR2.SavedVacation.element().qtip("api").elements;
    tip_parts.wrapper.addClass('saved_vacations_wrapper');
    tip_parts.contentWrapper.addClass('saved_vacations_content_wrapper');
    tip_parts.button.addClass('close_saved_vacations').css('position', 'absolute');
  },

  bind_delete: function () {
    $j('#saved_vacations a.delete').live('click', function () {
      var name = $j(this).parent().find('a.show').html();
      var escaped = $j('<div />').html(name).text();

      if (confirm("Delete " + escaped + "?")) {
	    $j.getJSON(this.href, AppR2.SavedVacation.process_json);
      }
	  return false;
    });
  },

  bind_view: function () {
    $j('.result .tools a.view_saved').live('click', function () {
      AppR2.SavedVacation.open();
    });
  },

  create_url: function (data) {
    var base = AppR2.SavedVacation.is_excursion(data) ? 'excursions/search' : 'vacations';
    var split_key = data.itinerary_key.split('|');
    if(AppR2.SavedVacation.has_deal(split_key)) {
      return AppR2.SavedVacation.get_host() + '/' + base + '?key=' + split_key[0] + '&deals=Y';
    }
    return AppR2.SavedVacation.get_host() + '/' + base + '?key=' + data.itinerary_key;
  },

  create_item: function (data, list) {
	var message = (typeof data === "string");
    var item = document.createElement('li');
    if (message) { $j(item).html(data); }
    $j(list).append(item);

	if (data.itinerary_key && data.itinerary_title && data.id && data.thumbnail) {
	  var url = AppR2.SavedVacation.create_url(data);
	  var thumb_link = $j('<a />').attr('href', url).addClass('thumb-link');
	  var thumb = $j('<img />').
	    attr('src', data.thumbnail).
	    attr('alt', data.itinerary_title).
	    attr('title', data.itinerary_title).
	    addClass('thumb');
	  thumb_link.append(thumb);
	  $j(item).append(thumb_link);

	  var show = document.createElement('a');
      $j(show).attr('href', url);
      $j(show).html(data.itinerary_title);
      $j(item).append(show);
      $j(show).addClass('show');

      var span = document.createElement('span');
      $j(span).html('&nbsp;');
      $j(item).append(span);

      var remove = document.createElement('a');
      $j(remove).attr('href', AppR2.SavedVacation.get_host() + '/vacations/saved/delete?id=' + data.id + '&format=json&jsoncallback=?');
      $j(remove).html('Remove');
      $j(item).append(remove);
      $j(remove).addClass('delete');
	}
    return item;
  },

  create_results: function (data) {
	  var containerDiv = document.createElement('div');
	  $j(containerDiv).attr('id', 'saved_vacations');

	  var resultsDiv = document.createElement('div');
	  $j(containerDiv).append(resultsDiv);
	  $j(resultsDiv).addClass('results');

	  if (0 < data.length) {
      var lists = _.partition(data, AppR2.SavedVacation.is_excursion).reverse();
	    _.each(lists, function (list) {
	      AppR2.SavedVacation.create_list(list, resultsDiv);
	    });
	  }
	  else {
	    var empty = document.createElement('p');
	    $j(empty).html('You have no saved selections');
	    $j(resultsDiv).append(empty);
	    $j(empty).addClass('empty');
	  }
	  return containerDiv;
  },

  create_list: function (data, results) {
    if (!data || 0 === data.length) return;

    var head = document.createElement('h6');
    head.innerHTML = 'Saved ' + (AppR2.SavedVacation.is_excursion(data[0]) ? 'Excursions' : 'Vacations');
    results.appendChild(head);

    var list = document.createElement('ul');
    _.each(data, function (result) {
      AppR2.SavedVacation.create_item(result, list);
    });
    $j(list).addClass(data[0].type);
    results.appendChild(list);
  },

  is_vacation: function (x) {
    return ('I' === x.type);
  },

  is_excursion: function (x) {
    return ('S' === x.type);
  },

  has_deal: function(split_key) {
    return split_key[1] === '1';
  }
};

$j(function () {
  AppR2.SavedVacation.initialize();
});
