(function($) { 

Drupal.behaviors.mtrvPage = {
  attach: function (context) {
    $('.scrollTo').click(function(){
      $.scrollTo(
        $(this).attr('href'), 500);
        return false;
      });
    }
  };  
    
})(jQuery);;
var Mtrv = Mtrv || {};

(function($){
  
  Mtrv = Mtrv || {};
  Mtrv.search = {
    formClass: '.mtrv-search-form',
    fieldClass: '.mtrv-search-box',
    containsTextClass: 'has-text',
    fieldLabel: Drupal.t("Search by Stock# or Brand"),
    fieldDefaultClass: 'default-label',
    
    // Set up event handlers for each instance of the search box.
    init: function(elem) {
      var currentValue,
          $elem = $(elem),
          $field = $elem.find(Mtrv.search.fieldClass);
      
      // Create clear "x" button.
      $('<span>', {
        'class': 'clear',
        click: Mtrv.search.clearClickCallback
      }).insertAfter($field);
      
      
      // search-box .keyup() event
      $field.bind('keyup', Mtrv.search.fieldKeyupCallback);
      
      
      // Add class if form has text.
      currentValue = $field.val();
      if (currentValue.length > 0) {
        $elem.addClass(Mtrv.search.containsTextClass);
      }
      
      
      // Add default label in the textbox.
      $field.bind('focus', Mtrv.search.fieldFocusCallback);
      $field.bind('blur', Mtrv.search.fieldBlurCallback);
      $field.trigger('blur');
    },
    
    // Response code for clear button's click event
    clearClickCallback: function(e) {
      var $form = $(this).closest(Mtrv.search.formClass);
      $form.removeClass(Mtrv.search.containsTextClass);
      $form.find(Mtrv.search.fieldClass).val('').focus();
    },
    
    fieldKeyupCallback: function(e) {
      switch(e.keyCode) {
        case 9:  // Tab.
        case 13: // Enter.
        case 16: // Shift.
        case 17: // Ctrl.
        case 18: // Alt.
        case 20: // Caps lock.
        case 27: // Esc.
        case 33: // Page up.
        case 34: // Page down.
        case 35: // End.
        case 36: // Home.
        case 37: // Left arrow.
        case 38: // Up arrow.
        case 39: // Right arrow.
        case 40: // Down arrow.
          return true;
        default:
          if (this.value.length > 0) {
            $(this).closest(Mtrv.search.formClass).addClass(Mtrv.search.containsTextClass);
          } else {
            $(this).closest(Mtrv.search.formClass).removeClass(Mtrv.search.containsTextClass);
          }
      }
    },
    fieldFocusCallback: function(e) {
      var $elem = $(e.target);
      if ($elem.val() == Mtrv.search.fieldLabel) {
        $elem.val('').removeClass(Mtrv.search.fieldDefaultClass);
      }
    },
    fieldBlurCallback: function(e) {
      var $elem = $(e.target);
      if ($elem.val() === '' || $elem.val() === Mtrv.search.fieldLabel) {
        $elem.val(Mtrv.search.fieldLabel).addClass(Mtrv.search.fieldDefaultClass);
      }
    }
  };
  
  Drupal.behaviors.mtrvSearchForm = {
    attach: function(context) {
      $(Mtrv.search.formClass, context).once('mtrv-search', function(){
        Mtrv.search.init(this);
      });
    }
  };
})(jQuery);;
var Mtrv = Mtrv || {};

(function($) {
  
  Mtrv = Mtrv || {};
  Mtrv.myFavRv = {
    cookies: {},
    cookiePrefix: 'mtrvRvFavorite',
    container: '#myFavRv',
    trigger: '#toggleDrawer',
    triggerText: 'tickle me',
    triggerClass: 'collapsed',
    triggerImagePath: '/sites/mikethompson.com/modules/custom/mtrv_rv/theme/myFavRv/images/favorite-button.png',
    drawer: '#drawer',
    drawerIsBuilt: false,
    expandedCookieName: 'favoritesExpanded',
    
    // Build the initial markup and bind events. will animate trigger icon if told to do so.
    init: function(options){
      var $container = $(this.container),
      defaults = {
        animate: false
      };
      
      $.extend(defaults, options);
      Mtrv.myFavRv.registerFavorites();
      
      // Build markup. Bind events.
      if (!this.isEmpty(this.cookies)) {
        $('<div />', {
          id: this.drawer.substr(1) // substr(1) removes the leading hash (#)
        }).appendTo($container);
        
        $('<img />', {
          id: this.trigger.substr(1), // substr(1) removes the leading hash (#)
          // text: this.triggerText,
          src: this.triggerImagePath,
          alt: 'open/close drawer',
          'class': this.triggerClass + ' uber', // IE mis-interprets the class property, so we quote it as a string to be safe.
          click: this.triggerCallback
        }).appendTo($container);
        
        this.drawerIsBuilt = true;
        
        // invoke animation, if applicable.
        if (defaults.animate !== false) {
          this.triggerAnimation(200);
        }


        // Auto-expand drawer if cookie is still alive
        if ($.cookie(this.expandedCookieName) !== null) {
          this.expand(0); // instant slidedown
        }
      }
      else {
        // safety net to unset expanded drawer cookie in
        // case it was left open when the last favorite was
        // removed.
        $.cookie(this.expandedCookieName, null, {path:'/'});
      }
    },
    
    triggerCallback: function() {
      if ($(this).hasClass(Mtrv.myFavRv.triggerClass)) {
        Mtrv.myFavRv.expand();
      }
      else {
        Mtrv.myFavRv.collapse();
      }
    },
    
    triggerAnimation: function(delay) {
      // Find the trigger element
      $(this.trigger).show('fast', function() {
        var triggerOffset = $(this).offset();
        $('<div>',{
          id: 'myFavRv-alert',
          css: {
            left: triggerOffset.left - 45,
            top: triggerOffset.top + 100
          }
        }).appendTo('body')
        .animate({
          top:"-=20",
          opacity:"1"
        }, 500) 
        .delay(1000)
        .animate({
          top:"-=50",
          opacity:"0"
        }, 300, function(){
          $(this).remove();
        });
        
      });
    },
    
    // Collapses drawer. Also destroys the expand/collapse preference cookie.
    collapse: function(){
      $(Mtrv.myFavRv.drawer).slideUp();
      $(this.trigger).addClass(Mtrv.myFavRv.triggerClass);
      $.cookie(this.expandedCookieName, null, {path:'/'});
    },
    
    
    // Expands the drawer and sets a cookie to let the
    // application know of it's status. Also updates the
    // trigger class so the appropriate action takes place
    // on the click event. The speed parameter corresponds
    // to the speed of the expand animation. Use 0 to
    // make animation instant.
    expand: function(speed){
      $(Mtrv.myFavRv.drawer).slideDown(speed);
      $(this.trigger).removeClass(Mtrv.myFavRv.triggerClass);
      $.cookie(this.expandedCookieName, true, {path:'/'});
      
      Mtrv.myFavRv.loadFavorites();
    },
    
    
    // Controller for loading un-processed cookies
    loadFavorites: function(){
      var x;
      for (x in this.cookies) {
        if (this.cookies[x].processed === undefined) {
          this.loadFavorite(this.cookies[x].nid);
          this.cookies[x].processed = true;
        }
      }
    },
    
    
    // Spawns new instances of Drupal.ajax to handle the
    // deliver of ajax content.
    loadFavorite: function(nid){
      var settings = {
            effect: 'fade',
            progress: {'type':'throbber'},
            url: '/mtrv/fetch_favorite',
            event: this.cookiePrefix + nid, // These must be unique events
            submit: {'nid': nid}
          },
          base = this.cookiePrefix + nid,
          element = document.getElementById(this.drawer.substr(1)),
          ajax = new Drupal.ajax(base, element, settings);
      
      $(ajax.element).trigger(this.cookiePrefix + nid);
      
      Drupal.ajax[base] = ajax;
    },
    
    
    addFavorite: function(nid){
      if (nid) {
        
        // Determine if the drawer needs to be built
        var needBuild = this.isEmpty(this.cookies) && !this.drawerIsBuilt;
        
        // Add cookie
        $.cookie(Mtrv.myFavRv.cookiePrefix + nid, nid, {path:'/'});
        
        
        // Let application know about new favorite.
        Mtrv.myFavRv.registerFavorites();
        Mtrv.myFavRv.triggerAnimation(0);
        
        // Initialize and load drawer if it is expanded.
        if ($.cookie(Mtrv.myFavRv.expandedCookieName) !== null) {
          Mtrv.myFavRv.loadFavorites();
        }
        else if (needBuild) {
          this.init({animate:true});
        }
        
        // Check if this is the first cookie being added, trigger the init method if so.
      }
    },
    
    
    // Run all necessary tasks to successfully remove a
    // favorited item. This includes removing a browser
    // cookie, unregistering a cookie from the application,
    // deleting base element from Drupal.ajax, unbinding
    // the ajax event from the Drupal.ajax base element,
    // and finally, removing the favorite from the DOM.
    removeFavorite: function(nid){
      if (nid) {
        // Remove cookie
        $.cookie(Mtrv.myFavRv.cookiePrefix + nid, null, {path:'/'});
        
        // Let application know about removed favorite.
        delete Mtrv.myFavRv.cookies[Mtrv.myFavRv.cookiePrefix + nid];
        
        // Remove favorite from Drupal.ajax
        delete Drupal.ajax[this.cookiePrefix + nid];
        
        // Unbinding Drupal.ajax base element event
        $(this.drawer).unbind(this.cookiePrefix + nid);
        
        // Remove from DOM
        $('.nid' + nid, this.drawer).fadeOut('normal', function() {
          $(this).remove();
        })
      }
    },
    
    
    // Filter through the document.cookie string and return
    // an object of cookies
    registerFavorites: function(){
      var registered = Mtrv.myFavRv.cookies,
          fragment = [],
          items = [],
          i = 0;
      if (document.cookie && document.cookie !== '') {
        items = document.cookie.split('; ');
        for (i=0;i<items.length;i++) {
          // Filter RV Favorites from cookies
          if (items[i].indexOf(this.cookiePrefix) !== -1) {
            fragment = items[i].split('=');
            // Only collect unregistered favorites
            if (registered[fragment[0]] === undefined) {
              Mtrv.myFavRv.cookies[fragment[0]] = {
                nid: fragment[1]
              };
            }
            
          }
        }
      }
    },
    
    unRegisterFavorites: function(){},
    
    // Helper method to determine if an object is empty
    isEmpty: function(obj) {
      for(var prop in obj) {
        if(obj.hasOwnProperty(prop)) {
          return false;
        }
      }
      return true;
    }
    
  };
  
  
  
  Drupal.behaviors.mtrvRvMyFavRv = {
    attach: function(context) {
      $(Mtrv.myFavRv.container, context).once('myFavRv', function() {
        Mtrv.myFavRv.init();
      });
    }
  };
  
  
})(jQuery);;

