/*
 * jQuery Joyride Plugin 1.0
 * www.ZURB.com/playground
 * Copyright 2011, ZURB
 * Free to use under the MIT license.
 * http://www.opensource.org/licenses/mit-license.php
 * Перевод: команда проекта RUSELLER.COM
*/

(function($) {
  $.fn.joyride = function(options) {

    // +++++++++++++++++++++++++
    //   Значения по умолчанию
    // +++++++++++++++++++++++++
    var settings = {
      'tipLocation': 'bottom', // 'top' или 'bottom' по отношению к родительскому элементу
      'scrollSpeed': 300, // скорость прокуртки страницы в миллисекундах
      'timer': 0, // 0 = без таймера, все остальные значения = время таймера в миллисекундах
      'startTimerOnClick': false, // true или false - при значении true таймер будет запскаться после нажатия на первую ыкнопку
      'nextButton': true, // true или false - управление выводом кнопки "следующий"
      'tipAnimation': 'pop', // 'pop' или 'fade' для каждой подсказки
      'tipAnimationFadeSpeed': 300, // когда tipAnimation = 'fade', данная опция указывает скорость перехода в миллисекундах
      'cookieMonster': false, // true или false - управление использованием куки
      'cookieName': 'JoyRide', // имя используемого куки
      'cookieDomain': false, // присоединение куки к домену, например, '.notableapp.com'
      'tipContainer': 'body', // куда присоединять подсказку, если не используется тип inline
      'inline': false, // true или false, если true, то подсказка будет присоединяться после элемента
      'tipContent': '#joyRideTipContent' // ID элемента <ol> с содержанием подсказок
    };

    //Используем опции
    var options = $.extend(settings, options);
    
    return this.each(function() {
      
      if ($(options.tipContent).length === 0) return;
      
      $(options.tipContent).hide();

      var bodyOffset = $(options.tipContainer).children('*').first().position(),
      tipContent = $(options.tipContent + ' li'),
      count = skipCount = 0,
      prevCount = -1,
      timerIndicatorInstance,
      timerIndicatorTemplate = '<div class="joyride-timer-indicator-wrap"><span class="joyride-timer-indicator"></span></div>',
      tipTemplate = function(tipClass, index, buttonText, self) { return '<div class="joyride-tip-guide ' + tipClass + '" id="joyRidePopup' + index + '"><span class="joyride-nub"></span>' + $(self).html() + buttonText + '<a href="#close" class="joyride-close-tip">X</a>' + timerIndicatorInstance + '</div>'; },
      tipLayout = function(tipClass, index, buttonText, self) {
        if (index == 0 && settings.startTimerOnClick && settings.timer > 0 || settings.timer == 0) {
          timerIndicatorInstance = '';
        } else {
          timerIndicatorInstance = timerIndicatorInstance;
        }
        if (!tipClass) tipClass = '';
        (buttonText != '') ? buttonText = '<a href="#" class="joyride-next-tip small nice radius yellow button">' + buttonText + '</a>': buttonText = '';
        if (settings.inline) {
          $(tipTemplate(tipClass, index, buttonText, self)).insertAfter('#' + $(self).attr('data-id'));
        } else {
          $(options.tipContainer).append(tipTemplate(tipClass, index, buttonText, self));
        }
      };

      if(!settings.cookieMonster || !$.cookie(settings.cookieName)) {
        
      tipContent.each(function(index) {
        var buttonText = $(this).attr('data-text'),
        tipClass = $(this).attr('class'),
        self = this;

        if (settings.nextButton && buttonText == undefined) {
          buttonText = 'Next';
        }
        if (settings.nextButton || !settings.nextButton && settings.startTimerOnClick) {
          if ($(this).attr('class')) {
            tipLayout(tipClass, index, buttonText, self);
          } else {
            tipLayout(false, index, buttonText, self);
          }
        } else if (!settings.nextButton) {
          if ($(this).attr('class')) {
            tipLayout(tipClass, index, '', self);
          } else {
            tipLayout(false, index, '', self);
          }
        }
        $('#joyRidePopup' + index).hide();
      }); 
    }
      
      showNextTip = function() {
        var parentElementID = $(tipContent[count]).attr('data-id'),
        parentElement = $('#' + parentElementID);
        
        if (parentElement.offset() === null) {
          count++;
          skipCount++;
          prevCount++;
          parentElementID = $(tipContent[count]).attr('data-id'),
          parentElement = $('#' + parentElementID);
        }
        var windowHalf = Math.ceil($(window).height() / 2),
        currentTip = $('#joyRidePopup' + count),
        currentTipPosition = parentElement.offset(),
        currentParentHeight = parentElement.height() + 10,
        currentTipHeight = currentTip.height() + 4,
        tipOffset = 0;
        
        if (currentTip.length === 0) return;
        
        if (count < tipContent.length) {
          if (settings.tipAnimation == "pop") {
            $('.joyride-timer-indicator').width(0);
            if (settings.timer > 0) {
              currentTip.show().children('.joyride-timer-indicator-wrap').children('.joyride-timer-indicator').animate({width: '100%'}, settings.timer);
            } else {
              currentTip.show();
            }
          } else if (settings.tipAnimation == "fade") {
            $('.joyride-timer-indicator').width(0);
            if (settings.timer > 0) {
              currentTip.fadeIn(settings.tipAnimationFadeSpeed).children('.joyride-timer-indicator-wrap').children('.joyride-timer-indicator').animate({width: '100%'}, settings.timer);
            } else {
              currentTip.fadeIn(settings.tipAnimationFadeSpeed);
            }
          }
          
          // ++++++++++++++++++++++++
          //   Размещение подсказок
          // ++++++++++++++++++++++++
          
          if (settings.tipLocation == "bottom") {
            currentTip.offset({top: (currentTipPosition.top + currentParentHeight + 14), left: (currentTipPosition.left - bodyOffset.left)});
            currentTip.children('.joyride-nub').addClass('top').removeClass('bottom');
          } else if (settings.tipLocation == "top") {
            if (currentTipHeight >= currentTipPosition.top) {
              currentTip.offset({top: (currentTipPosition.top + currentParentHeight + 10 - bodyOffset.top), left: (currentTipPosition.left - bodyOffset.left)});
              currentTip.children('.joyride-nub').addClass('top').removeClass('bottom');
            } else {
              currentTip.offset({top: ((currentTipPosition.top - 4) - (currentParentHeight + currentTipHeight + bodyOffset.top)), left: (currentTipPosition.left - bodyOffset.left)});
              currentTip.children('.joyride-nub').addClass('bottom').removeClass('top');
            }
          }
          
          // Анимируем прокрутку, когда подсказка удаляется с экрана
          tipOffset = Math.ceil(currentTip.offset().top - windowHalf);
          
          $("html, body").animate({
            scrollTop: tipOffset
          }, settings.scrollSpeed);
          
          if (count > 0) {
            if (skipCount > 0) {
              var hideCount = prevCount - skipCount;
              skipCount = 0;
            } else {
              var hideCount = prevCount;
            }
            if (settings.tipAnimation == "pop") {
              $('#joyRidePopup' + hideCount).hide();
            } else if (settings.tipAnimation == "fade") {
              $('#joyRidePopup' + hideCount).fadeOut(settings.tipAnimationFadeSpeed);
            }
          }
          
        // Скрываем последнюю подсказку
        } else if ((tipContent.length - 1) < count) {
          if (skipCount > 0) {
            var hideCount = prevCount - skipCount;
            skipCount = 0;
          } else {
            var hideCount = prevCount;
          }
          if (settings.cookieMonster == true) {
            $.cookie(settings.cookieName, 'ridden', { expires: 365, domain: settings.cookieDomain });
          } else {
            // Не используем куки
          }
          if (settings.tipAnimation == "pop") {
            $('#joyRidePopup' + hideCount).fadeTo(0, 0);
          } else if (settings.tipAnimation == "fade") {
            $('#joyRidePopup' + hideCount).fadeTo(settings.tipAnimationFadeSpeed, 0);
          }
        }
        count++;
        
        if (prevCount < 0) {
          prevCount = 0;
        } else {
          prevCount++;
        }
      }
      if (!settings.inline) {
      $(window).resize(function() {
        var parentElementID = $(tipContent[prevCount]).attr('data-id'),
        currentTipPosition = $('#' + parentElementID).offset(),
        currentParentHeight = $('#' + parentElementID).height(),
        currentTipHeight = $('#joyRidePopup' + prevCount).height();
        if (settings.tipLocation == "bottom") {
          $('#joyRidePopup' + prevCount).offset({top: (currentTipPosition.top + currentParentHeight + 20), left: currentTipPosition.left});
        } else if (settings.tipLocation == "top") {
          if (currentTipPosition.top <= currentTipHeight) {
            $('#joyRidePopup' + prevCount).offset({top: (currentTipPosition.top + currentParentHeight + 20), left: currentTipPosition.left});
          } else {
            $('#joyRidePopup' + prevCount).offset({top: (currentTipPosition.top - (currentTipHeight + currentParentHeight)), left: currentTipPosition.left});
          }
        }
      });
    }
      
      // +++++++++++++++
      //   Таймер 
      // +++++++++++++++
      
      var interval_id = null,
      showTimerState = false;
      
      if (!settings.startTimerOnClick && settings.timer > 0){
       showNextTip();
       interval_id = setInterval(function() {showNextTip()}, settings.timer);
      } else {
       showNextTip();
      }
      var endTip = function(e, interval_id, cookie, self) {
        e.preventDefault();
        clearInterval(interval_id);
        if (cookie) {
           $.cookie(settings.cookieName, 'ridden', { expires: 365, domain: settings.cookieDomain });
        }
        $(self).parent().hide();
      }
      $('.joyride-close-tip').click(function(e) {
        endTip(e, interval_id, settings.cookieMonster, this);
      });
      
      // Когда нажата кнопка "следующий", показываем следующую подсказку, только когда нет куки
        $('.joyride-next-tip').click(function(e) {
          e.preventDefault();
          if (count >= tipContent.length) {
            endTip(e, interval_id, settings.cookieMonster, this);
          }
          if (settings.timer > 0 && settings.startTimerOnClick) {
            showNextTip();
            clearInterval(interval_id);
            interval_id = setInterval(function() {showNextTip()}, settings.timer);
          } else if (settings.timer > 0 && !settings.startTimerOnClick){
            clearInterval(interval_id);
            interval_id = setInterval(function() {showNextTip()}, settings.timer);
          } else {
            showNextTip();
          }
        });
    }); // each 
  }; // joyride 
  
  
  // +++++++++++++++++++++++++++++
  //   Плагин jQuery Cookie
  // +++++++++++++++++++++++++++++
  
  // Copyright (c) 2010 Klaus Hartl (stilbuero.de)
  // Dual licensed under the MIT and GPL licenses:
  // http://www.opensource.org/licenses/mit-license.php
  // http://www.gnu.org/licenses/gpl.html
  // Перевод: команда проекта RUSELLER.COM
  jQuery.cookie = function (key, value, options) {

      // Ключ и значение заданы, устанавливаем куки...
      if (arguments.length > 1 && String(value) !== "[object Object]") {
          options = jQuery.extend({}, options);

          if (value === null || value === undefined) {
              options.expires = -1;
          }

          if (typeof options.expires === 'number') {
              var days = options.expires, t = options.expires = new Date();
              t.setDate(t.getDate() + days);
          }

          value = String(value);

          return (document.cookie = [
              encodeURIComponent(key), '=',
              options.raw ? value : encodeURIComponent(value),
              options.expires ? '; expires=' + options.expires.toUTCString() : '', // используем атрибут expires, max-age не подддерживается IE
              options.path ? '; path=' + options.path : '',
              options.domain ? '; domain=' + options.domain : '',
              options.secure ? '; secure' : ''
          ].join(''));
      }

      // Ключ и возможные значения заданы, получаем куки...
      options = value || {};
      var result, decode = options.raw ? function (s) { return s; } : decodeURIComponent;
      return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null;
  }; // cookie
})(jQuery);
