/*
	jQuery Coda-Slider v2.0 - http://www.ndoherty.biz/coda-slider
	Copyright (c) 2009 Niall Doherty
	This plugin available for use in all personal or commercial projects under both MIT and GPL licenses.
*/

$(function(){
	// Remove the coda-slider-no-js class from the body
	$("body").removeClass("coda-slider-no-js");
	// Preloader
    //dbout
//	$(".coda-slider").children('.panel').hide().end().prepend('<p class="loading">Loading...<br /><img src="images/ajax-loader.gif" alt="loading..." /></p>');
});

var sliderCount = 1;

$.fn.codaSlider = function (settings) {

  settings = $.extend({
    autoHeight: true,
    autoHeightEaseDuration: 1000,
    autoHeightEaseFunction: "easeInOutExpo",
    autoSlide: false,
    autoSlideInterval: 7000,
    autoSlideStopWhenClicked: true,
    crossLinking: false,
    dynamicArrows: true,
    dynamicArrowLeftText: "&#171; left",
    dynamicArrowRightText: "right &#187;",
    dynamicTabs: true,
    dynamicTabsAlign: "center",
    dynamicTabsPosition: "top",
    externalTriggerSelector: "a.xtrig",
    firstPanelToLoad: 1,
    panelTitleSelector: "h2.title",
    slideEaseDuration: 1000,
    slideEaseFunction: "easeInOutExpo",
    dragSensitivity: 100,
    panelNames: null,
  }, settings);

  return this.each(function () {

    // Uncomment the line below to test your preloader
   //  alert("Testing preloader");

    var slider = $(this);

    // If we need arrows
    var panelWidth = slider.find(".panel").width();
    var panelCount = slider.find(".panel").size();
    var panelContainerWidth = panelWidth * panelCount + 100;
    var navClicks = 0; // Used if autoSlideStopWhenClicked = true
    var mouseDownXCoord = 0;

    // Surround the collection of panel divs with a container div (wide enough for all panels to be lined up end-to-end)
    $('.panel', slider).wrapAll('<div class="panel-container"></div>');
    // Specify the width of the container div (wide enough for all panels to be lined up end-to-end)
    $(".panel-container", slider).css({ width: panelContainerWidth });

    // Specify the current panel.
    // If the loaded URL has a hash (cross-linking), we're going to use that hash to give the slider a specific starting position...
    if (settings.firstPanelToLoad != 1 && settings.firstPanelToLoad <= panelCount) {
      var currentPanel = settings.firstPanelToLoad;
      var offset = -(panelWidth * (currentPanel - 1));
      $('.panel-container', slider).css({ marginLeft: offset });
      // Otherwise, we'll just set the current panel to 1...
    } else {
      var currentPanel = 1;
    };
    $('.coda-nav').find('li').removeClass('current').parents('ul').find('li:eq(' + (currentPanel - 1) + ') ').addClass('current');

    selectNavigationPanel(currentPanel);


    // External triggers (anywhere on the page)
    $(settings.externalTriggerSelector).each(function () {

      // Make sure this only affects the targeted slider
      if (sliderCount == parseInt($(this).attr("rel").slice(12))) {
        $(this).bind("click", function () {
          navClicks++;
          targetPanel = parseInt($(this).attr("href").slice(1));
          offset = -(panelWidth * (targetPanel - 1));
          // alterPanelHeight(targetPanel - 1);
          currentPanel = targetPanel;
          // Switch the current tab:
          $('.coda-nav').find('li').removeClass('current').parents('ul').find('li:eq(' + (targetPanel - 1) + ') ').addClass('current');
          // Slide

          $('.panel-container', slider).animate({ marginLeft: offset }, settings.slideEaseDuration, settings.slideEaseFunction);
          return false  // Don't change the URL hash unless cross-linking is specified
        });
      };
    });

    // Specify which tab is initially set to "current". Depends on if the loaded URL had a hash or not (cross-linking).


    // Left arrow click
    $('.coda-nav-left a').click(function () {
      navClicks++;
      if (currentPanel == 1) {
        offset = -(panelWidth * (panelCount - 1));
        currentPanel = panelCount;
      } else {
        currentPanel -= 1;
        offset = -(panelWidth * (currentPanel - 1));
      };
      $('.coda-nav').find('li').removeClass('current').parents('ul').find('li:eq(' + (currentPanel - 1) + ') ').addClass('current');
      $('.panel-container', slider).animate({ marginLeft: offset }, settings.slideEaseDuration, settings.slideEaseFunction);
      if (settings.crossLinking) { location.hash = currentPanel }; // Change the URL hash (cross-linking)
      return false;
    });

    // Right arrow click
    $('.coda-nav-right a').click(function () {
      navClicks++;
      if (currentPanel == panelCount) {
        offset = 0;
        currentPanel = 1;
      } else {
        offset = -(panelWidth * currentPanel);
        currentPanel += 1;
      };
      $('.coda-nav').find('li').removeClass('current').parents('ul').find('li:eq(' + (currentPanel - 1) + ') ').addClass('current');
      $('.panel-container', slider).animate({ marginLeft: offset }, settings.slideEaseDuration, settings.slideEaseFunction);
      if (settings.crossLinking) { location.hash = currentPanel }; // Change the URL hash (cross-linking)
      return false;
    });

    $(".topArea").mousedown(function (e) {
      mouseDownXCoord = e.pageX;
    });

    $(".topArea").mouseup(function (e) {
      

      var aa = mouseDownXCoord - e.pageX;
      if (aa < -settings.dragSensitivity) {
        if (currentPanel == 1) {
          offset = -(panelWidth * (panelCount - 1));
          currentPanel = panelCount;
        } else {
          currentPanel -= 1;
          offset = -(panelWidth * (currentPanel - 1));
        };
      }
      else if (aa > settings.dragSensitivity) {
        if (currentPanel == panelCount) {
          offset = 0;
          currentPanel = 1;
        } else {
          offset = -(panelWidth * currentPanel);
          currentPanel += 1;
        };
      }
      else {
        return;
      }

      navClicks++;
      $('.coda-nav').find('li').removeClass('current').parents('ul').find('li:eq(' + (currentPanel - 1) + ') ').addClass('current');

      selectNavigationPanel( currentPanel);

      var link = $('.coda-global-nav').find('a');
      
      $('.panel-container', slider).animate({ marginLeft: offset }, settings.slideEaseDuration, settings.slideEaseFunction);
      

    });

    $('.coda-global-nav a').click( function() {
        
        var panelName = getUrlVarValue(this.href, "PanelViewName");
        
        
        var linkPath = getUrlWithoutVars(this.href);
        var documentPath = getUrlWithoutVars(document.location.toString());
        var defaspx = documentPath + "Default.aspx";
        if ((linkPath == documentPath) || (linkPath == defaspx))
        {
            if ( prepareToMovePanel(settings.panelNames[panelName]))
            {
                movePanel();
            }
            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 || currentPanel == destinationIdx + 1)
        {
            return false;
        }

        offset = -(panelWidth*destinationIdx);
        currentPanel = destinationIdx + 1;
        selectNavigationPanel(currentPanel);
        return true;
    }


    function selectNavigationPanel(currentPanel)
    {
      if (currentPanel < 3) {    // we have two panels for products  so need to skip one
        $('.coda-global-nav').find('a').removeClass('selected').parents('ul').find('a:eq(' + (currentPanel - 1) + ') ').addClass('selected');
      } else {
        $('.coda-global-nav').find('a').removeClass('selected').parents('ul').find('a:eq(' + (currentPanel - 2) + ') ').addClass('selected');
      }
    }


    function movePanel()
    {
        navClicks++;
        $('.coda-nav').find('li').removeClass('current').parents('ul').find('li:eq(' + (currentPanel - 1) + ') ').addClass('current');

 //       $('.coda-global-nav').find('a').removeClass('selected').parents('ul').find('a:eq(' + (currentPanel - 1) + ') ').addClass('selected');
        
        
 
        
        $('.panel-container', slider).animate({ marginLeft: offset }, settings.slideEaseDuration, settings.slideEaseFunction);

        
    }

    // Kill the preloader
    $('.panel', slider).show().end().find("p.loading").remove();
    slider.removeClass("preload");

    sliderCount++;

  });
};
