/*
	jQuery RazDog Swiper v1.0
	Copyright (c) 2011 RazDog
*/

$(function(){
	$("body").removeClass("swiper-no-js");
	// Preloader
	$(".swiper").children('.panel').hide().end().prepend(
       '<p class="swiper-loading">Loading...<br /><img src="images/ajax-loader.gif" alt="loading..." /></p>');
});

var swiperCount = 1;

$.fn.swiper = function (options) {

    options = $.extend({
        crossLinking: false,
        externalTriggerSelector: "a.xtrig",
        firstPanelIndex: 1,
        swipeDuration: 1000,
        swipeEaseFunction: "easeInOutExpo",
        panelContainerMargin: 100,
        dragSensitivity: 50,
        panelNames: null
    }, options);

    return this.each(
  function () {

      var swiper = $(this);

      var panelWidth = swiper.find(".panel").width();
      var panelCount = swiper.find(".panel").size();
      var panelContainerWidth = panelWidth * panelCount + options.panelContainerMargin;
      var mouseDownXCoord = 0;
      var mouseDownLeftMargin = 0;
      var startMove = false;
      var previousTick = 0;
      var offset = 0;
      var currentPanelIdx = 1;

      // Surround the collection of panel divs with a container div
      $('.panel', swiper).wrapAll('<div class="panel-container"></div>');
      $('.panel-container', swiper).css({ width: panelContainerWidth });
      $('.panel-container', swiper).css('marginLeft', 0);
      $('.swiper-nav-region img').mousemove(function (e) { return false });

      // Specify the current panel.
      if (options.firstPanelIndex != 1 && options.firstPanelIndex <= panelCount) {
          currentPanelIdx = options.firstPanelIndex;
          offset = -(panelWidth * (currentPanelIdx - 1));
          $('.panel-container', swiper).css({ marginLeft: offset });
      }
      else {
          currentPanelIdx = 1;
      };
      $('.swiper-nav').find('li').removeClass('current').parents('ul')
        .find('li:eq(' + (currentPanelIdx - 1) + ') ').addClass('current');


      // External triggers (anywhere on the page)
      $(options.externalTriggerSelector).each(
    function () {
        // Make sure this only affects the targeted swiper
        if (swiperCount == parseInt($(this).attr("rel").slice(12))) {
            $(this).bind("click",
        function () {
            targetPanel = parseInt($(this).attr("href").slice(1));
            offset = -(panelWidth * (targetPanel - 1));

            // alterPanelHeight(targetPanel - 1);
            currentPanelIdx = targetPanel;

            // Switch the current tab:
            $('.swiper-nav').find('li').removeClass('current').parents('ul')
            .find('li:eq(' + (targetPanel - 1) + ') ').addClass('current');
            // Slide
            $('.panel-container', swiper)
            .animate({ marginLeft: offset }, options.swipeDuration, options.swipeEaseFunction);
            return false;  // Don't change the URL hash unless cross-linking is specified
        });
        };
    });

      // Left arrow click
      $('.swiper-nav-left a').click(
    function () {
        if (currentPanelIdx == 1) {
            offset = -(panelWidth * (panelCount - 1));
            currentPanelIdx = panelCount;
        }
        else {
            currentPanelIdx -= 1;
            offset = -(panelWidth * (currentPanelIdx - 1));
        };

        movePanel(currentPanelIdx, offset);

        if (options.crossLinking) {
            location.hash = currentPanelIdx
        }; // Change the URL hash (cross-linking)
        return false;
    });

      // Right arrow click
      $('.swiper-nav-right a').click(
    function () {
        if (currentPanelIdx == panelCount) {
            offset = 0;
            currentPanelIdx = 1;
        }
        else {
            offset = -(panelWidth * currentPanelIdx);
            currentPanelIdx += 1;
        };

        movePanel(currentPanelIdx, offset);

        if (options.crossLinking) {
            location.hash = currentPanelIdx
        }; // Change the URL hash (cross-linking)

        return false;
    });

      //Swiper click on swipe navigation region handlers
      $('.swiper-nav-region').mousedown(
    function (e) {
        mouseDownXCoord = e.pageX;
        mouseDownLeftMargin = parseInt($('.panel-container', swiper).css('marginLeft'));
        startMove = false;
    });

      $('.swiper-nav-region').mousemove(onMouseMove);

      function onMouseMove(e) {
          if (!startMove) {
              return false;
          }

          var moveLeftMargin = mouseDownLeftMargin - mouseDownXCoord + e.pageX;
          //$('.panel-container', swiper).css('marginLeft', moveLeftMargin);
          $('.panel-container', swiper).animate({ marginLeft: moveLeftMargin }, 1);
      }

      $('.swiper-nav-left, .swiper-nav-right').mousedown(
      function () {
          return false;
      });

      $('.swiper-nav-left, .swiper-nav-right').mouseup(
      function () {
          return false;
      });


      $('.swiper-nav-region').mouseup(swipePanel);

      $('.swiper-nav-region').bind("mouseleave",
    function (e) {
        swipePanel(e);
        offset = 0;
    });

      function swipePanel(e) {
          if (!startMove)
              return false;

          var offsetCorrection = mouseDownXCoord - e.pageX;
          startMove = false;

          if (offsetCorrection < -options.dragSensitivity) {
              if (currentPanelIdx == 1) {
                  offset = -(panelWidth * (panelCount - 1));
                  currentPanelIdx = panelCount;
              }
              else {
                  currentPanelIdx -= 1;
                  offset = -(panelWidth * (currentPanelIdx - 1));
              };
          }
          else if (offsetCorrection > options.dragSensitivity) {
              if (currentPanelIdx == panelCount) {
                  offset = 0;
                  currentPanelIdx = 1;
              }
              else {
                  offset = -(panelWidth * currentPanelIdx);
                  currentPanelIdx += 1;
              };
          }

	  
          movePanel(currentPanelIdx , offset);
      }


      //Global links click handler
      $('.swiper-global-nav a').click(
    function () {
        var panelName = getUrlVarValue(this.href, "PanelViewName");

        var linkPath = getUrlWithoutVars(this.href);
        var documentPath = getUrlWithoutVars(document.location.toString());
        if (linkPath == documentPath) {
            if (prepareToMovePanel(options.panelNames[panelName])) {
                movePanel(currentPanelIdx, offset);
            }
            return false;
        }

        return true;
    });

      function getUrlVars(url) {
          var map = {};
          var parts = url.replace(/[?&]+([^=&]+)=([^&]*)/gi,
            function (m, key, value) {
                map[key] = value;
            });
          return map;
      }

      function getUrlWithoutVars(url) {
          return url.replace(/[?&]+([^=&]+)=([^&]*)/gi, '');
      }

      function getUrlVarValue(url, key) {
          return getUrlVars(url)[key];
      }

      function prepareToMovePanel(destinationIdx) {
          if (destinationIdx == null || currentPanelIdx == destinationIdx + 1) {
              return false;
          }

          offset = -(panelWidth * destinationIdx);
          currentPanelIdx = destinationIdx + 1;
          return true;
      }

      function movePanel(panelIndex, panelOffset) {
          $('.swiper-nav').find('li').removeClass('current').parents('ul')
          .find('li:eq(' + (panelIndex - 1) + ') ').addClass('current');

          var container = $('.panel-container', swiper);
          container.animate({ marginLeft: panelOffset }, options.swipeDuration, options.swipeEaseFunction);
      }

      // Kill the preloader
      $('.panel', swiper).show().end().find("p.swiper-loading").remove();
      swiper.removeClass("preload");

      swiperCount++;
  });
};
