/*jslint vars: true, undef: true, browser: true, indent: 2 */
/*global jQuery, $, Modernizr, Placeholder, window, Lectric, helpers */

(function ($) {

  $.fn.lectricCustom = function (method) {

    // public methods
    // to keep the $.fn namespace uncluttered, collect all of the plugin's methods in an object literal and call
    // them by passing the string name of the method to the plugin
    //
    // public methods can be called as
    // element.pluginName('methodName', arg1, arg2, ... argn)
    // where "element" is the element the plugin is attached to, "pluginName" is the name of your plugin and
    // "methodName" is the name of a function available in the "methods" object below; arg1 ... argn are arguments
    // to be passed to the method
    //
    // or, from inside the plugin:
    // methods.methodName(arg1, arg2, ... argn)
    // where "methodName" is the name of a function available in the "methods" object below
    var methods = {

      // this the constructor method that gets called when the object is created
      init : function (options) {

        // the plugin's final properties are the merged default and user-provided properties (if any)
        // this has the advantage of not polluting the defaults, making them re-usable
        this.lectricCustom.settings = $.extend({}, this.lectricCustom.defaults, options);

        // iterate through all the DOM elements we are attaching the plugin to
        return this.each(function () {

          var $element = $(this), // reference to the jQuery version of the current DOM element
            element = this,     // reference to the actual DOM element
            counter = 1;

          $element.lectricCustom.settings.numberOfItems = $element.find($element.lectricCustom.settings.itemClass).size();

          // Are there enough elements in the carousel to slide it
          
          if ($element.lectricCustom.settings.numberOfItems > parseInt($element.lectricCustom.settings.visibleItems, 10)) {
            // Duplicate the amount of elements
            if(!$element.lectricCustom.settings.isAppleDevice) {
            $element.find($element.lectricCustom.settings.itemClass).each(function () {
              if (counter <= parseInt($element.lectricCustom.settings.visibleItems, 10)) {
                $element.append('<div class="' + $(this).attr('class') + '" data-large_img="' + $(this).attr('data-large_img') + '">' + $(this).html() + '</div>');
                counter++;
              }
            });
            }

            var scrubberWidth = 960 / $element.lectricCustom.settings.numberOfItems;
            $("#scrubber").find('.item').css('width', scrubberWidth + 'px');
            // Initialize the slider
            if ($element.lectricCustom.settings.numberOfItems > parseInt($element.lectricCustom.settings.visibleItems, 10)) {
              $element.lectricCustom.settings.slider = new Lectric();
              $(this).lectricCustom.settings.scrubber = new Lectric();
              if(!$element.lectricCustom.settings.isAppleDevice) {
                $element.lectricCustom.settings.slider.init('#slideshow', {next: '.navright', previous: '.navleft', animateEasing: 'linear', animateDuration: 7000, toss: true});
                $(this).lectricCustom.settings.scrubber.init('#scrubber', {reverse: true,  animateDuration: 7000, animateEasing: 'linear'});
              }else{
                $element.lectricCustom.settings.slider.init('#slideshow', {toss: true});
                $(this).lectricCustom.settings.scrubber.init('#scrubber', {toss: true, reverse: true});
              }
              
              
              
              $(this).lectricCustom.settings.scale = $(this).lectricCustom.settings.slider.itemWidth() / $(this).lectricCustom.settings.scrubber.itemWidth();
                            
              if(!$element.lectricCustom.settings.isAppleDevice) {
                $element.lectricCustom.settings.count = $element.lectricCustom.settings.count + 1;
                $element.lectricCustom.settings.slider.to($element.lectricCustom.settings.count);
                $(this).lectricCustom.settings.scrubber.position.x = -$(this).lectricCustom.settings.slider.position.x / $(this).lectricCustom.settings.scale;
                $(this).lectricCustom.settings.scrubber.update({triggerSlide: false});
              }
              var sliderStartPos = $(this).lectricCustom.settings.slider.position.x;
    
              if(!$element.lectricCustom.settings.isAppleDevice) {
                clearInterval($(this).lectricCustom.settings.timer);
                $(this).lectricCustom.settings.timer = setInterval(function () {
                
                  if ($(this).lectricCustom.settings.count >= $(this).lectricCustom.settings.slider.itemCount() - parseInt($(this).lectricCustom.settings.visibleItems, 10)) {
                    $(this).lectricCustom.settings.count = 1;
                    $($(this).lectricCustom.settings.itemsClass).stop();
                    $($(this).lectricCustom.settings.itemsClass).css('left', '0px');
                    $(this).lectricCustom.settings.slider.position.x = 0;
                  } else {
                    $(this).lectricCustom.settings.count = ($(this).lectricCustom.settings.count < $(this).lectricCustom.settings.slider.itemCount() - 1) ? $(this).lectricCustom.settings.count + 1 : 0;
                  }
                  $(this).lectricCustom.settings.slider.to($(this).lectricCustom.settings.count);
                }, 7000);
                }
              $(this).lectricCustom.settings.firstTime = false;
            }

            // Add Hooks to the slider

            // Register the slide hook
            $element.lectricCustom.settings.slider.subscribe('slide', function () {
              //helpers.slide();
              $(this).lectricCustom.settings.scrubber.position.x = -$(this).lectricCustom.settings.slider.position.x / $(this).lectricCustom.settings.scale;
              $(this).lectricCustom.settings.scrubber.update({triggerSlide: false});
            });
            
            $element.lectricCustom.settings.scrubber.subscribe('slide', function () {
              //helpers.slide();
              $(this).lectricCustom.settings.slider.position.x = -$(this).lectricCustom.settings.scrubber.position.x / $(this).lectricCustom.settings.scale;
              $(this).lectricCustom.settings.slider.update({triggerSlide: false});
            });
            
            // If on apple device
            $element.lectricCustom.settings.slider.subscribe('start', function () {
              

            });

            // Register Next Button
            $element.lectricCustom.settings.slider.subscribe('nextButton', function (s, event) {
              clearInterval($element.lectricCustom.settings.timer);
              $element.lectricCustom.settings.timer = null;
              if ($element.lectricCustom.settings.count >= $element.lectricCustom.settings.slider.itemCount() - parseInt($element.lectricCustom.settings.visibleItems, 10)) {
                $element.lectricCustom.settings.count = 1;
                $($element.lectricCustom.settings.itemsClass).stop();
                $($element.lectricCustom.settings.itemsClass).css('left', '0px');
                $element.lectricCustom.settings.slider.position.x = 0;
              } else {
                $element.lectricCustom.settings.count = $element.lectricCustom.settings.count + 1;
              }
              $element.lectricCustom.settings.slider.to($element.lectricCustom.settings.count);

              $element.lectricCustom.settings.arrowClick = true;
            });

              // Register Previous button
            $element.lectricCustom.settings.slider.subscribe('previousButton', function (s, event) {
              clearInterval($element.lectricCustom.settings.timer);
              if ($element.lectricCustom.settings.count === 0) {
                $element.lectricCustom.settings.count = $element.lectricCustom.settings.slider.itemCount() - (parseInt($element.lectricCustom.settings.visibleItems, 10) + 1);
                $($element.lectricCustom.settings.itemsClass).stop();
                var itemWidth = $($element.lectricCustom.settings.itemsClass + ' ' + $element.lectricCustom.settings.itemClass + ":first").width();
                var leftValue = '-' + itemWidth * ($element.lectricCustom.settings.count + 1);
                $($element.lectricCustom.settings.itemsClass).css('left', leftValue + 'px');
                $element.lectricCustom.settings.slider.position.x = leftValue;
                $element.lectricCustom.settings.slider.to($element.lectricCustom.settings.count);
              } else if ($element.lectricCustom.settings.count === 1) {
                $element.lectricCustom.settings.count = 0;
              } else {
                $element.lectricCustom.settings.count = $element.lectricCustom.settings.count - 1;
              }

              $element.lectricCustom.settings.slider.to($element.lectricCustom.settings.count);
              $element.lectricCustom.settings.arrowClick = true;
            });
          } else {
            $element.lectricCustom.settings.isInit = false;
          }
        });

      },

      // Stop the carousel
      stopCarousel: function () {
        if ($(this).lectricCustom.settings.isInit && typeof ($(this).lectricCustom.settings.slider) !== 'undefined' && $(this).lectricCustom.settings.carouselIsOn) {
          $($(this).lectricCustom.settings.itemsClass).stop(true);
          $($(this).lectricCustom.settings.itemsClass).dequeue();
          clearInterval($(this).lectricCustom.settings.timer);
          clearTimeout($(this).lectricCustom.settings.timeout);
          //$(this).lectricCustom.settings.slider.unsubscribe('slide', $(this).lectricCustom.settings.slider);
          var itemWidth = $($(this).lectricCustom.settings.itemsClass + ' ' + $(this).lectricCustom.settings.itemClass + ":first").width();
          var leftValue = 0;
          if ($(this).lectricCustom.settings.count === 0) {
            leftValue = 0;
          } else {
            leftValue = '-' + itemWidth * $(this).lectricCustom.settings.count;
          }
          $(this).lectricCustom.settings.slider.position.x = leftValue;
          $(this).lectricCustom.settings.carouselIsOn = false;
        }
      },

      // Start the carousel
      startCarousel: function () {
        if ($(this).lectricCustom.settings.isInit && typeof ($(this).lectricCustom.settings.slider) !== 'undefined' && !$(this).lectricCustom.settings.carouselIsOn) {
          
          var thisItem = $($(this).lectricCustom.settings.itemsClass + ' ' + $(this).lectricCustom.settings.itemClass + ':nth-child('+$(this).lectricCustom.settings.count+')');
          var thisItemWidth = thisItem.width();          
          var difference = parseInt(thisItemWidth) + parseInt(document.getElementById(thisItem.attr('id')).offsetLeft) + parseInt($('.items').css('left').replace('px',''));
          var speed = 7000 / thisItemWidth;
          var timeout = difference * speed;
          
          $(this).lectricCustom.settings.slider.opts.animateDuration = timeout;
          $(this).lectricCustom.settings.scrubber.opts.animateDuration = timeout;
          $(this).lectricCustom.settings.slider.to($(this).lectricCustom.settings.count);
          if($(this).lectricCustom.settings.scrubber.position.x != -$(this).lectricCustom.settings.slider.position.x / $(this).lectricCustom.settings.scale) {
            $(this).lectricCustom.settings.scrubber.position.x = -$(this).lectricCustom.settings.slider.position.x / $(this).lectricCustom.settings.scale;
            $(this).lectricCustom.settings.scrubber.update({triggerSlide: false});
          }

          $(this).lectricCustom.settings.timeout = setTimeout(function(){
            
            $(this).lectricCustom.settings.slider.opts.animateDuration = 7000;
            $(this).lectricCustom.settings.scrubber.opts.animateDuration = 7000;
              if ($(this).lectricCustom.settings.count >= $(this).lectricCustom.settings.slider.itemCount() - parseInt($(this).lectricCustom.settings.visibleItems, 10)) {
                $(this).lectricCustom.settings.count = 1;
                $($(this).lectricCustom.settings.itemsClass).stop();
                $($(this).lectricCustom.settings.itemsClass).css('left', '0px');
                $(this).lectricCustom.settings.slider.position.x = 0;
              } else {
                $(this).lectricCustom.settings.count = ($(this).lectricCustom.settings.count < $(this).lectricCustom.settings.slider.itemCount() - 1) ? $(this).lectricCustom.settings.count + 1 : 0;
              }
              $(this).lectricCustom.settings.slider.to($(this).lectricCustom.settings.count);
              if($(this).lectricCustom.settings.scrubber.position.x != -$(this).lectricCustom.settings.slider.position.x / $(this).lectricCustom.settings.scale) {
                $(this).lectricCustom.settings.scrubber.position.x = -$(this).lectricCustom.settings.slider.position.x / $(this).lectricCustom.settings.scale;
                $(this).lectricCustom.settings.scrubber.update({triggerSlide: false});
              }

            $(this).lectricCustom.settings.slider.opts.animateDuration = 7000;

            clearInterval($(this).lectricCustom.settings.timer);
            $(this).lectricCustom.settings.timer = setInterval(function () {            
              if ($(this).lectricCustom.settings.count >= $(this).lectricCustom.settings.slider.itemCount() - parseInt($(this).lectricCustom.settings.visibleItems, 10)) {
                $(this).lectricCustom.settings.count = 1;
                $($(this).lectricCustom.settings.itemsClass).stop();
                $($(this).lectricCustom.settings.itemsClass).css('left', '0px');
                $(this).lectricCustom.settings.slider.position.x = 0;

              } else {

                $(this).lectricCustom.settings.count = ($(this).lectricCustom.settings.count < $(this).lectricCustom.settings.slider.itemCount() - 1) ? $(this).lectricCustom.settings.count + 1 : 0;
              }
              $(this).lectricCustom.settings.slider.to($(this).lectricCustom.settings.count);
            }, 7000);
          }, timeout);
          
          
          $(this).lectricCustom.settings.carouselIsOn = true;
        }
      }
    };


    // private methods
    // these methods can be called only from inside the plugin
    //
    // private methods can be called as
    // helpers.methodName(arg1, arg2, ... argn)
    // where "methodName" is the name of a function available in the "helpers" object below; arg1 ... argn are
    // arguments to be passed to the method
    var helpers = {

      // When scroll occur we need to know where we are in the carousel to take care of positioning
      slide: function () {
        if ($(this).lectricCustom.settings.firstTime) {
          clearInterval($(this).lectricCustom.settings.timer);
          $(this).lectricCustom.settings.timer = setInterval(function () {
            if ($(this).lectricCustom.settings.count >= $(this).lectricCustom.settings.slider.itemCount() - parseInt($(this).lectricCustom.settings.visibleItems, 10)) {
              $(this).lectricCustom.settings.count = 1;
              $($(this).lectricCustom.settings.itemsClass).stop();
              $($(this).lectricCustom.settings.itemsClass).css('left', '0px');
              $(this).lectricCustom.settings.slider.position.x = 0;
            } else {
              $(this).lectricCustom.settings.count = ($(this).lectricCustom.settings.count < $(this).lectricCustom.settings.slider.itemCount() - 1) ? $(this).lectricCustom.settings.count + 1 : 0;
            }
            $(this).lectricCustom.settings.slider.to($(this).lectricCustom.settings.count);
          }, 7000);
          $(this).lectricCustom.settings.firstTime = false;
        }
      }
    }; // End of helpers

    // if a method as the given argument exists
    if (methods[method]) {

      // call the respective method
      return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));

      // if an object is given as method OR nothing is given as argument
    } else if (typeof method === 'object' || !method) {

      // call the initialization method
      return methods.init.apply(this, arguments);

      // otherwise
    } else {

      // trigger an error
      $.error('Method "' +  method + '" does not exist in lectricCustom plugin!');

    }

  };

  // plugin's default options
  $.fn.lectricCustom.defaults = {

    visibleItems: 0,
    itemClass: '.item',
    itemsClass: '.items',
    largeImageId: '#bigone',
    largeImageClass: '.bigone',
    numberOfItems: 0,
    carouselIsOn: true,
    slider: '',
    timer: '',
    timeout: '',
    count: 0,
    firstTime: true,
    arrowClick: false,
    isInit: true,
    scrubber: '',
    scale: '',
    isAppleDevice: false
  };

  // this will hold the merged default and user-provided options
  // you will have access to these options like:
  // this.pluginName.settings.propertyName from inside the plugin or
  // element.pluginName.settings.propertyName from outside the plugin, where "element" is the element the
  // plugin is attached to;
  $.fn.lectricCustom.settings = {};

})(jQuery);
