/*
* jQuery.blank
* Carsten Nielsen
*
*   $.blank([])      => true
*   $.blank(" \n  ") => true
*   $.blank(null)    => true
*   $.blank(x.undef) => true
*
*/
jQuery.extend({
  blank : function(object) {
    if ('undefined' == typeof(object)) return true;
    if ('string' == typeof(object)) return '' == jQuery.trim(object);
    if (object instanceof Array) return 0 == object.length;
    return object ? false : true;
  }
});


/*
* Time Helper
* Carsten Nielsen
*
*   $.time.currentDay() => 'Monday'
*   $.time.currentMinutesSinceMidnight() => 203
*
*/
jQuery.extend({
  time : new function() {
    this.dayNames = jQuery(['Sunday', 'Monday', 'Tuesday', 'Wednesday',
    'Thursday', 'Friday', 'Saturday']);

    this.currentDay = function() {
      return this.dayNames[new Date().getDay()];
    }

    this.now = function() {
      return new Date();
    }

    this.currentMinutesSinceMidnight = function() {
      var now = this.now();
      return (now.getHours() * 60) + now.getMinutes();
    }

    this.currentMinutesToMidnight = function() {
      return 1440 - this.currentMinutesSinceMidnight();
    }
  }
});


/*
* Cookie Helper
*
*   $.cookie.set('name', 'Carsten Nielsen')
*   $.cookie.get('name') => 'Carsten Nielsen'
*   $.cookie.destroy('name')
*   $.cookie.get('name') => null
*
*/
jQuery.extend({
  cookie : new function() {
    this.set = function(key, value, days) {
      cookieSet(key, value, days);
    }

    this.get = function(key) {
      return cookieGet(key);
    }

    this.destroy = function(key) {
      cookieSet(key, '', -1);
    }

    function cookieGet(key)
    {
      var key_value = key + '=';
      var cookies = documentCookies();
      for (var i in cookies) {
        var cookie = cookies[i];
        while (' ' == cookie.charAt(0))
          cookie = cookie.substring(1, cookie.length);
        if (0 == cookie.indexOf(key_value))
          return unescape(cookie.substring(key_value.length, cookie.length));
      }
      return null;
    }

    function cookieSet(key, value, days)
    {
      if (days)
        var expires = '; expires=' + daysFromNow(days);
      else
        var expires = '';
      document.cookie = key + '=' + escape(value) + expires + '; path=/';
    }

    function documentCookies()
    {
      return document.cookie.split(';');
    }

    function daysFromNow(days)
    {
      var date = new Date();
      date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
      return date.toGMTString();
    }
  }
});


/*
* Hinted Text Fields
*
*   $('input[title]').hint();
*
*/
jQuery.fn.extend({
  hint : function(style_name_for_blurred_state) {
    var input = jQuery(this);
    var style_name = (style_name_for_blurred_state || 'blurred');
    var title = input.attr('title');
    var wind = jQuery(window);
    var form = jQuery(this.form);

    function remove() {
      if ((input.val() === title) && input.hasClass(style_name))
        input.val('').removeClass(style_name);
    }

    if (title) {
      input.blur(function() {
        if (this.value === '') input.val(title).addClass(style_name);
      }).focus(remove).blur();
      form.submit(remove);
      wind.unload(remove);
    }
  }
});


/*
* LCBO Search
* Carsten Nielsen
*/
var LCBO = {

  load : function()
  {
    $.each(LCBO, function() { if (this.init) this.init() });
  }

};


LCBO.LocationHelper = new function() {

  this.init = function()
  {
    if (!$('.product-inventory-page').length) return;
    $('#location_form').submit(locationFormHasBeenSubmitted);
    $('#location_input').val(getCurrentLocation());
    updateInventory();
  }

  function getCurrentLocation()
  {
    var loc = getCurrentPosition()['location'];
    return loc ? loc : '';
  }

  function locationFormHasBeenSubmitted(event)
  {
    event.preventDefault();
    setLocation($('#location_input').val());
    return false;
  }

  function productInventoryLoadString()
  {
    var pos = getCurrentPosition();
    var product_no = $('.product-definition .product-no').text();
    return '/stores/with/' + $.trim(product_no) + '/near?' +
      $.param({ q : pos['location'] }) + ' .product-inventory-content';
  }

  function updateInventory()
  {
    if ($.blank(getCurrentLocation())) return;
    $('.product-inventory-content').load(productInventoryLoadString(), '', function() {
      LCBO.Stores.init();
      LCBO.TableRows.init();
    });
  }

  function clearInventory()
  {
    $('#product_inventory_content').text('');
  }

  function setLocation(location)
  {
    if ($.blank(location)) {
      $.cookie.destroy('lcbosearch_location');
      clearInventory();
    } else if (locationIsValid(location)) {
      $.cookie.set('lcbosearch_location', location, 365);
      updateInventory();
    } else {
      alert('Sorry, that location won\'t work.');
    }
  }

  function locationIsValid(location)
  {
    if ('string' != typeof(location)) return false;
    var trimmed = location.replace(/\s/, '');
    if (trimmed.length < 3) return false;
    return true;
  }

  function hasCurrentPosition()
  {
    var pos = getCurrentPosition();
    return (!$.blank(pos['lat']) && !$.blank(pos['lon'])) || !$.blank(pos['location']);
  }

  function getCurrentPosition()
  {
    return {
      'lat' : $.cookie.get('lcbosearch_lat'),
      'lon' : $.cookie.get('lcbosearch_lon'),
      'location' : $.cookie.get('lcbosearch_location')
    };
  }

};


LCBO.Pager = new function() {

  this.init = function()
  {
    $('.view-more-button-anchor').click(viewMoreButtonAnchorHasBeenClicked);
  }

  function viewMoreButtonAnchorHasBeenClicked(event)
  {
    event.preventDefault();
    $('.view-more-button-anchor').addClass('processing');
    $.get($(this).attr('href'), function(data) {
      $('.search-results-list').append($(data).find('.search-results-list').contents());
      $('.view-more-button').replaceWith($(data).find('.view-more-button'));
      LCBO.load();
    });
  }

};


LCBO.TableRows = new function() {

  this.init = function()
  {
    $('table tr:nth-child(even)').addClass('even');
  }

};


LCBO.Stores = new function() {

  this.init = function()
  {
    selectCurrentDay();
    setCurrentDayOpenOrClosed();
  }

  function currentDayRow()
  {
    return $('.' + $.time.currentDay().toLowerCase() + '-store-hours');
  }

  function todaysHours()
  {
    var row = currentDayRow();
    var opens = row.find('.msm-time.open-time').attr('title');
    var closes = row.find('.msm-time.close-time').attr('title');
    return {
      'opens' : $.blank(opens) ? null : parseInt(opens),
      'closes' : $.blank(closes) ? null : parseInt(closes)
    };
  }

  function isStoreOpen()
  {
    var today = todaysHours();
    if (!today['opens'] || !today['closes']) return false;
    var now = $.time.currentMinutesSinceMidnight();
    return today['opens'] <= now && today['closes'] > now;
  }

  function minutesUntilClosed()
  {
    if (!isStoreOpen()) return 0;
    var today = todaysHours();
    return today['closes'] - $.time.currentMinutesSinceMidnight();
  }

  function currentOpenCloseStatusHTML()
  {
    if (minutesUntilClosed() == 0) {
      return '<span class="closed">Closed</span>';
    } else if (minutesUntilClosed() <= 45) {
      return '<span class="closing">Closing Soon</span>';
    } else {
      return '<span class="open">Open Now</span>';
    }
  }

  function setCurrentDayOpenOrClosed()
  {
    var row = currentDayRow();
    if (row.hasClass('closed')) return;
    row.find('.open-status').html(currentOpenCloseStatusHTML());
  }

  function selectCurrentDay()
  {
    currentDayRow().addClass('today').show();
  }

};


LCBO.HintedTextFields = new function() {

  this.init = function()
  {
    $('input[title]').hint();
  }

};


$(document).ready(LCBO.load);
