/**
 * Cookie plugin
 * This portion Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * see: http://plugins.jquery.com/project/cookie
**/
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};




/**
 * Begin mobile functionality.
**/
var debug_mode = false;
$(document).ready(function() {
  if($.cookie('debug') == 'enabled') {
    mobile_debug_mode();
  }
  mobile_setup();
});


function mobile_setup()
{
  /* Mobile specific JS */
  if(mobile_detect()) {
    if(mobile_is_disabled()) {
      mobile_disable_modifications();
    }
    else {
      mobile_setup_menu();
      mobile_setup_disable_links();
      mobile_setup_hide_footer();

      if(mobile_detect_opera()) {
        mobile_opera_adjustments();
      }
    }
  }
  
  // Attempt to disable the scrolling location chooser; it doesn't work well on a mobile device
  $(window).load(function() {
    $(window).unbind('scroll');
  })
}


function mobile_setup_menu()
{
  /* Iterate over each menu container */
  var menu_cont = $('#main_menu, #secondary_menu, #tertiary_menu, #storeSubMenu');
  menu_cont.each(function() {
    var option_count = 0;
    
    /* Build a <select><option>...</select> chunk of HTML by iterating through
     * each <li><a>menu</a></li> element in the menu */
    var s = '<select class="quicknav">';
    s += '<option value="">Select from the following...</option>\n';
    $(this).find('ul.links li a, div.storeSubMenuItem a').each(function() {
      option_count++;
      
      // Get menu attributes
      var href = $(this).attr('href');
      var text = $(this).text();
      
      // Attempt to set the <select> to the current page
      var current_url = window.location.toString();
      var selected = '';
      if(current_url.match(href)) {
        selected = 'selected="selected"';
      }

      // Append <option> to the html chunk
      s += '<option value="' + href + '" ' + selected + '>' + text + '</option>\n';
    });
    
    // Close tag
    s += '</select>';
    
    /* Replace the menu list with our HTML chunk only if we had at least 1 menu (we don't want blank selects) */
    if(option_count > 0) {
      // Make this reversible so that we can have a link to disable the changes
      $(this).attr('html', $(this).html());
      $(this).addClass('mobile_replaced_html');
      
      $(this).html(s);
    }
  });
  
  /* Prepend some labels for readability */
  $('#main_menu select').before('<span class="quicknav_label_main">Quick Links:</span>');
  $('#tertiary_menu select').before('<span class="quicknav_label_tertiary">Jump To:</span>');
  $('#storeSubMenu select').before('<span class="quicknav_label_tertiary">Category:</span>');
  
  /* When the <select> changes, we should automatically go to the selected page */
  $('.quicknav').change(function() {
    var url = $(this).find('option:selected').val();
    if(url) window.location = url;
  });
}

function mobile_setup_disable_links()
{
  $('#layContentWrapper').append('<div id="disable_mobile_site"><div class="view_full">View the full version of this page.</div><div class="disable_permanently">Permanently disable mobile site.</div></div>');
  
  $('#disable_mobile_site .view_full').click(function() {
    mobile_disable_modifications();
  });
  $('#disable_mobile_site .disable_permanently').click(function() {
    mobile_permanently_disable_modifications();
  });
}

function mobile_setup_hide_footer()
{
  $('#footer').hide();
}

function mobile_disable_modifications()
{
  // Disable styleheets
  $('link.mobile').attr('disabled', true);
  
  // Reverse HTML changes
  $('.mobile_replaced_html').each(function() {
    if($(this).attr('html')) {
      $(this).html($(this).attr('html'));
    }
  });
  
  // Reverse JS changes
  $('#footer').show();
  
  // Hide these links
  $('#disable_mobile_site').remove();
}

function mobile_permanently_disable_modifications()
{
  mobile_disable_modifications();
  $.cookie('mobile', 'disabled', {expires: 365, path: '/'});
}

function mobile_is_disabled()
{ 
	try {
		return $.cookie('mobile') == 'disabled' ? true : false;
	} catch(e) {
		return false;
	}
}

function mobile_opera_adjustments()
{
  $('img.float_right').remove();
  $('img[align="right"]').remove();
  $('#footer').remove();
}

/* Check whether we're using a mobile device with Javascript functionality
 * The best info I've been able to find for UA strings is:
 *  http://www.zytrax.com/tech/web/mobile_ids.html
 */
function mobile_detect()
{
  if(debug_mode == true) {
    return true;
  }
  
  var ua = navigator.userAgent;
  
  if(mobile_detect_opera()) return true;
  if(ua.match(/iphone/i)) return true;
  if(ua.match(/ipod/i)) return true;
  if(ua.match(/android/i)) return true;
  if(ua.match(/mobile safari/i)) return true;
  if(ua.match(/wm5 pie/i)) return true;
  if(ua.match(/blackberry/i)) return true;
  if(ua.match(/palm/i)) return true;
  if(ua.match(/SonyEricsson/i)) return true;

  return false;
}

function mobile_detect_opera()
{
  var ua = navigator.userAgent;
  
  if(ua.match(/opera mini/i)) return true;
  if(ua.match(/opera mobi/i)) return true;
  if(ua.match(/opera mobile/i)) return true;
}

function mobile_debug_mode()
{
  debug_mode = true;
  $('link.mobile').attr('media', 'screen');
}
