
(function($) {
  $(document).ready(function(){
    
    /**
     * ##################
     * colorBand plugin
     * ##################
     */
    var colorBandMethods = {
      /**
       * initialize the colorBand
       */
      init: function() {
        $('#colorBandWrapper').colorBand('load', Drupal.settings.aristideColorband.query);
      },
      /**
       * load the colorBand
       */
      load: function(query) {
        $this = $('#colorBandWrapper');
        $('#colorBandWrapper').data('colorBand', 0);
        //$('#contentWrapper').throbber();
        $('#fancybox-loading').show();
        
        // more info: http://stackoverflow.com/questions/5095307/jquery-json-response-always-triggers-a-parseerror
        $.ajax({
          type: "POST",
          url: Drupal.settings.basePath + "ajax/colorband?" + decodeURIComponent(query.replace(/&amp;/g,'&')),
          dataType: "html",
          success: function(data){
            $('#fancybox-loading').hide();
            $data = $(data);
            if($data.length) {
              $this.colorBand('replace', $data);
              $('#colorBandWrapper').data('colorBand', 1);
              //$('#contentWrapper').throbber('destroy');
            }
            else {
              $('#aristide-messages-wrapper').aristideMessages('show', Drupal.t('No fabrics found with the current filter settings.'), 'status');
            }
          },
          error: function(jqXHR, textStatus, errorThrown) {
            $('#fancybox-loading').hide();
            $('#aristide-messages-wrapper').aristideMessages('show', Drupal.t('An error occured while loading the samples.'), 'error');
          }
        });
      },
      /**
       * show the colorBand
       */
      replace: function(newContent) {
        // remove old functionality
        switch(Drupal.settings.platform) {
          case 'desktop':
            $('#colorBand').removeOverscroll();
            break;
          case 'mobile':
            break;
          case 'safari':
            break;
        }
        
        // load new colorband
        $this = $('#colorBandWrapper');
        $this.html(newContent);
        
        // initiate functionality on new colorband
        $this.colorBand('initColors');
        switch(Drupal.settings.platform) {
          case 'desktop':
            $this.colorBand('initDesktop');
            break;
          case 'ie':
            $this.colorBand('initIe');
            break;
          case 'mobile':
            $this.colorBand('initMobile');
            break;
          case 'ios5':
            $this.colorBand('initIos5');
            break;
          case 'safari':
            $this.colorBand('initSafari');
            break;
        }
      },
      /**
       * add desktop functionality
       */
      initDesktop: function() {
        $this = $('#colorBand');
        $this.css('overflow','hidden');
        myOverscroll = $this.overscroll({
          cursor: 'url(' + Drupal.settings.basePath + 'sites/all/themes/aristide/assets/img/cursor-grab-open.gif), move'
        });
        
        cbwHCenter = Math.round(-($this.width() - $(window).width()) / 2);
        cbwWCenter = Math.round(-($this.height() - $(window).height()) / 2);
        
        $this.animate({
            'top': cbwWCenter,
            'left': cbwHCenter
          },
          1000
        );
        
        $(window).resize(function(e){
          $('#colorBand').overscrollCenter();
        });
        
        var config = {    
             over: showCtrls,  
             timeout: 0, // number = milliseconds delay before called
             out: hideCtrls
        };
        $('.color').hoverIntent(config);
        
        function showCtrls() {
            $(this).children('.ctrls').css({'display': 'block', 'opacity': 0});
            $(this).children('.ctrls').stop().animate({'opacity':1, 'filter': ''}, 100);
        }
        
        function hideCtrls() {
            $(this).children('.ctrls').stop().animate({'opacity':0, 'filter': ''}, 100, function() {
              $(this).css({'display': 'none'});
            });
        }
      },
      /**
       * add IE functionality
       */
      initIe: function() {
        $('.color').disableSelect();
        $('.labelHole').disableSelect();
        $('.cbCol').disableSelect();
        $('#colorBand').disableSelect();
        
        $('#colorBandWrapper').colorBand('initDesktop');
      },
      /**
       * add mobile functionality
       */
      initMobile: function() {
        $this = $('#colorBandWrapper');
        myScroll = new iScroll('colorBandWrapper', {
          hScrollbar:     false,
          vScrollbar:     false,
          vScroll:        true, 
          hScroll:        true,
          useTransform:   true, 
          lockDirection:  false,
          bounce:         false,
          momentum:       true
        });
        cbwHCenter = $this.width() / 2;
        cbwWCenter = $this.height() / 2;
        myScroll.scrollTo(cbwHCenter * -1, cbwWCenter * -1, 1000);
        
        
        previousColor = '';
        
        $.fn.hideControls = function () {
          if($(this).hasClass('showCtrls')){
            //window.alert('removing controls');
            $(this).removeClass('showCtrls');
          }
        };
        
        $.fn.showControls = function () {
          if(!$(this).hasClass('showCtrls')){
            //window.alert('adding controls');
            $(this).addClass('showCtrls');
          }
        };
        
        $('#colorBandWrapper .color').click(function(e){
          e.preventDefault();
          
          if($(previousColor).attr('id') != $(this).attr('id')){
            $(previousColor).hideControls();
            
            $(this).showControls();
            previousColor = $('#colorBandWrapper');
          } else {
            if($(this).hasClass('showCtrls')){
              $(this).hideControls();
            } else {
              $(this).showControls();
            }
           
          }
          
          //$(previousColor).delay(2000).hideControls();
        });
      },
      /**
       * add Safari functionality
       */
      initSafari: function() {
        $this = $('#colorBandWrapper');
        $this.css('overflow','hidden');
        myScroll = new iScroll('colorBandWrapper', {
          hScrollbar:     false,
          vScrollbar:     false,
          vScroll:        true, 
          hScroll:        true,
          lockDirection:  false,
          bounce:         false
        })
        cbwHCenter = $this.width() / 2;
        cbwWCenter = $this.height() / 2;
        myScroll.scrollTo(cbwHCenter * -1, cbwWCenter * -1, 3000);
        
        var config = {    
             over: showCtrls,  
             timeout: 0, // number = milliseconds delay before fadeMenu is called
             out: hideCtrls 
        };
        $('#colorBandWrapper .color').hoverIntent(config);
        
        function showCtrls() {
            $(this).children('.ctrls').stop().fadeTo(150, 1);
        }
        
        function hideCtrls() {
            $(this).children('.ctrls').stop().fadeOut(150);
        }
      },
      /**
       * add iOS5 functionality
       */
      initIos5: function() {
        $(window).scrollTo({left:'50%', top:'50%'});    
        
        previousColor = '';
        
        $.fn.hideControls = function () {
          if($(this).hasClass('showCtrls')){
            //window.alert('removing controls');
            $(this).removeClass('showCtrls');
          }
        };
        
        $.fn.showControls = function () {
          if(!$(this).hasClass('showCtrls')){
            //window.alert('adding controls');
            $(this).addClass('showCtrls');
          }
        };
        
        $('#colorBandWrapper .color').click(function(e){
          e.preventDefault();
          
          if($(previousColor).attr('id') != $(this).attr('id')){
            $(previousColor).hideControls();
            
            $(this).showControls();
            previousColor = $(this);
          } else {
            if($(this).hasClass('showCtrls')){
              $(this).hideControls();
            } else {
              $(this).showControls();
            }
           
          }
          
          //$(previousColor).delay(2000).hideControls();
        });
      },
      initColors: function() {
        $this = $('#colorBandWrapper');
        // cache the fabric aid's and element id's in a lookup array
        var fabrics = {};
        $this.find('.color').each(function(e) {
          
          id = $(this).attr('id');
          // if it's a valid ID, process it
          if(id.length && !id.indexOf('n') && id.indexOf('a')) {
            tmp = id.split('a');
            tmp2 = tmp[0].split('n');
            nid = parseInt(tmp2[1]);
            delete tmp, tmp2;
            
            if(!isNaN(nid)) {
              fabrics[nid] = {};
              fabrics[nid]['id'] = id;
            }
          }
        });
        $('#colorBandWrapper').data('fabrics', fabrics);
        
        /**
         * Fabric add button click handler
         */
        $this.find('.lnkPBox').click(function(e) {
          e.preventDefault();
          
          // get the ID from the fabric
          fabric = $(this).parents('.color');
          id = $(fabric).attr('id');
          
          // if it's a valid ID, process it
          if(id.length && !id.indexOf('n') && id.indexOf('a')) {
            tmp = id.split('a');
            aid = parseInt(tmp[1]);
            delete tmp;
            
            if(isNaN(aid)) {
              $('#aristide-messages-wrapper').aristideMessages('show', Drupal.t('The sample could not be added because it is invalid. Please contact the site administrator.'), 'error');
            }
            else {
              if($(this).parents('.color').hasClass('added')) {
                $('#projectBox').projectBox('osRemoveFabric', aid, $(fabric), showFabricControlsAdd);
              }
              else {
                $('#projectBox').projectBox('osAddFabric', aid, $(fabric), showFabricControlsRemove);            
              }
            }
          }
          // it's not a valid ID
          else {
            $('#aristide-messages-wrapper').aristideMessages('show', Drupal.t('The sample could not be added because it is invalid. Please contact the site administrator.'), 'error');
            return;
          }
        });
        
        /**
         * Fabric info button click handler
         */
        fancyboxSettings = $('body').data('fancyboxSettings');
        $this.find(".lnkInfo").each(function(){
          $(this).fancybox(fancyboxSettings);
          $(this).click(function(e){
            e.preventDefault();
          });
        });
        
        /**
         * Fabric controls button click handler
         */
        $this.find('#colorBandWrapper .ctrls a').click(function(e) {
          e.preventDefault();
          $(this).parents('.ctrls').fadeOut(150);
        });

        /**
         * Update the added colors
         */
        // more info: http://stackoverflow.com/questions/5095307/jquery-json-response-always-triggers-a-parseerror
        $.ajax({
          type: "POST",
          url: Drupal.settings.basePath + "json/order/get",
          dataType: "text json",
          success: function(data){
            // if the order session was successfully loaded
            $(data.ordersession).each(function(e) {
              $cbWrapper = $('#colorBandWrapper');
              cbId = $cbWrapper.colorBand('getFabricId', this.nid);
              if(cbId.length) $cbWrapper.colorBand('cbFabricSetAdded', cbId);
            });
            return 1;
          },
          error: function(jqXHR, textStatus, errorThrown) {
            $('#aristide-messages-wrapper').aristideMessages('show', data.message, 'error');
            
            console.log(jqXHR);
            console.log(textStatus);
            console.log(errorThrown);
            return 0;
          }
        });
      },
      /**
       * Get a fabric Id
       * 
       * @param nid
       * 
       * @return
       *   fabric id
       */
      getFabricId: function(nid) {
        fabrics = $('#colorBandWrapper').data('fabrics');
        
        if(fabrics[nid]) {
          return fabrics[nid]['id'];
        }
        else {
          return false;
        }
      },
      /**
       * Set a color band fabric to the added state
       * 
       * @param   id    the fabric html element id
       */
      cbFabricSetAdded: function(id) {
        cbFabric = $('#' + id);
        
        if($(cbFabric).length) {
          cbFabric.addClass('added');
          cbFabric.removeClass('notadded');
        }
      },
      /**
       * Set a color band fabric to the nodadded state
       * 
       * @param   id    the fabric html element id
       */
      cbFabricSetNotAdded: function(id) {
        cbFabric = $('#' + id);
        
        if($(cbFabric).length) {
          cbFabric.removeClass('added');
          cbFabric.addClass('notadded');
        }
      }
    }
    
    /**
     * colorBand plugin
     */
    $.fn.colorBand = function(method) {
      // Method calling logic
      if ( colorBandMethods[method] ) {
        return colorBandMethods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
      } else if ( typeof method === 'object' || ! method ) {
        return colorBandMethods.init.apply( this, arguments );
      } else {
        $.error( 'Method ' +  method + ' does not exist on jQuery.colorBand' );
      }
    }
    
    // init the colorBand plugin
    $('#colorBandWrapper').colorBand();
  });
})(jQuery);


;

