/*
 * sf-Touchscreen v1.2b - Provides touchscreen compatibility for the jQuery Superfish plugin.
 *
 * Developer's note:
 * Built as a part of the Superfish project for Drupal (http://drupal.org/project/superfish)
 * Found any bug? have any cool ideas? contact me right away! http://drupal.org/user/619294/contact
 *
 * jQuery version: 1.3.x or higher.
 *
 * Dual licensed under the MIT and GPL licenses:
 *  http://www.opensource.org/licenses/mit-license.php
 *  http://www.gnu.org/licenses/gpl.html
 */

(function($){
  $.fn.sftouchscreen = function(options){
    options = $.extend({
      mode: 'inactive',
      breakpoint: 768,
      useragent: ''
    }, options);

    function activate(menu){
      // Select hyperlinks from parent menu items.
      menu.find('li > ul').closest('li').children('a').each(function(){
        var item = $(this);
        // No .toggle() here as it's not possible to reset it.
        item.click(function(event){
          // Already clicked? proceed to the URL.
          if (item.hasClass('sf-clicked')){
            window.location = item.attr('href');
          }
          // Prevent it otherwise.
          else {
            event.preventDefault();
            item.addClass('sf-clicked');
          }
        }).closest('li').mouseleave(function(){
          // Reset everything.
          item.removeClass('sf-clicked');
        });
      });
    }
    // Return original object to support chaining.
    return this.each(function(){
      var menu = $(this),
      mode = options.mode;
      // The rest is crystal clear, isn't it? :)
      switch (mode){
        case 'always_active' :
          activate(menu);
        break;
        case 'window_width' :
          if ($(window).width() < options.breakpoint){
            activate(menu);
          }
          var timer;
          $(window).resize(function(){
            clearTimeout(timer);
            timer = setTimeout(function(){
              if ($(window).width() < options.breakpoint){
                activate(menu);
              }
            }, 100);
          });
        break;
        case 'useragent_custom' :
          if (options.useragent != ''){
            var ua = RegExp(options.useragent, 'i');
            if (navigator.userAgent.match(ua)){
              activate(menu);
            }
          }
        break;
        case 'useragent_predefined' :
          if (navigator.userAgent.match(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od|ad)|iris|kindle|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i)){
            activate(menu);
          }
        break;
      }
    });
  };
})(jQuery);