$(function(){
  initGallery();
  clearFormFields({
    clearInputs: true,
    clearTextareas: true,
    passwordFieldText: true,
    addClassFocus: "focus",
    filterClass: "default"
  });
  initFadeGallery();

  initTabs();
  initBubbles();

  initShortConsultationForm();

  initZipConsultationForm();

  initReferralForm();
});

// gallery init
function initGallery() {
  // settings
  var _flag = false;
  var _waitAnimation = false;
  var _autoSlide = true;
  var _easing = 'linear';
  var _activeClass = 'active';
  var _switchTime = 5000;
  var _speed = 650;
  var pauseButton = '.link-pause a';


  $('.G3').each(function(){
    // gallery options
    var _holder = $(this);
    var _prev = _holder.find('a.link-prev');
    var _next = _holder.find('a.link-next');
    var _slidesHolder = _holder.find('.gallery-list');
    var _slider = _slidesHolder.find('>ul');
    var _pagerLinks = _holder.find('.s1 a');
    var _slides = _slider.children();
    var _slidesCount = _slides.length;
    var _slideWidth = _slides.eq(0).outerWidth(true);
    var _visibleCount = Math.round(_slidesHolder.width() / _slideWidth);
    var _currentIndex = 0;
    var _oldIndex = _currentIndex;
    var _animating = false;
    var _direction;
    var _timer;
    var _pauseButton = _holder.find(pauseButton);
    var _pauseClass = "pausedSlides";
    var btnPause = 'stopped';


    // pause buttton
    if(_pauseButton.length) {
      _pauseButton.click(function(){
        if(_holder.hasClass(_pauseClass)) {
          _holder.removeClass(_pauseClass);
          _pauseButton.removeClass(btnPause);
          _autoSlide = true;
          autoSlide();
        } else {
          _pauseButton.addClass(btnPause);
          _holder.addClass(_pauseClass);
          stopAutoSlide();
        }
        return false;
      });
    }

    // autoslide function
    function stopAutoSlide() {
      if(_timer) clearTimeout(_timer);
      _autoSlide = false;
    }

    // slider height
    _holder.css({position:'relative'});
    _slider.css({height:_slides.eq(0).outerHeight(true)});
    _slides.show().css({position:'absolute',top:0,left:_slideWidth});
    _slides.eq(_currentIndex).css({left:0});

    //next slide
    _next.click(function(){
      if (!_flag) {
        nextSlide();
      }
      return false;
    });

    //prev slide
    _prev.click(function(){
      if (!_flag) {
        prevSlide();
      }
      return false;
    });

    // gallery control
    _pagerLinks.each(function(_ind){
      $(this).click(function(){
        if(_animating) return;
        if(_ind != _currentIndex) {
          _oldIndex = _currentIndex;
          _currentIndex = _ind;
          _direction = (_oldIndex < _currentIndex);
          switchSlide();
        }
        return false;
      });
    });
    function prevSlide() {
      if(_animating) return;
      _oldIndex = _currentIndex;
      if(_currentIndex > 0) _currentIndex--;
      else _currentIndex = _slidesCount-1;
      _direction = false;
      switchSlide();
    }
    function nextSlide() {
      if(_animating) return;
      _oldIndex = _currentIndex;
      if(_currentIndex < _slidesCount-1) _currentIndex++;
      else _currentIndex = 0;
      _direction = true;
      switchSlide();
    }

    // gallery animation
    function refreshStatus() {
      _pagerLinks.removeClass(_activeClass).eq(_currentIndex).addClass(_activeClass);
    }
    function switchSlide() {
      if (!_flag) {
        _flag = true;
        if (_waitAnimation)
          _animating = true;
        _slides.eq(_currentIndex).css({
          left: (_direction ? _slideWidth : -_slideWidth)
        }).animate({
          left: 0
        }, {
          duration: _speed,
          queue: false,
          easing: _easing,
          complete: function(){
            _animating = false;
            _flag = false;
          }
        });
        _slides.eq(_oldIndex).animate({
          left: (_direction ? -_slideWidth : _slideWidth)
        }, {
          duration: _speed,
          queue: false,
          easing: _easing,
          complete: function(){
            _flag = false;
          }
        });
        refreshStatus();
        autoSlide();
      }
    }
    function autoSlide() {
      if(!_autoSlide) return;
      if(_timer) clearTimeout(_timer);
      _timer = setTimeout(nextSlide,_switchTime);
    }
    refreshStatus();
    autoSlide();
  });
}

// initFadeGallery
function initFadeGallery(){
  $('div.main-gallery').fadeGallery({
    slideElements:'.gallery .holder >ul >li',
    pagerHold: 'div.switcher',
    pagerLinks:'div.switcher ul li',
    btnNext:'a.next',
    btnPrev:'a.prev',
    pagerGener: true,
    autoRotation:true,
    autoHeight:false,
    pauseOnHover:true,
    btnPlayPause:'a.play-pause',
    switchTime:5000
  });
}
// slideshow plugin
jQuery.fn.fadeGallery = function(_options){
  var _options = jQuery.extend({
    slideElements:'div.slides > div.slide',
    pagerGener: true,
    pagerHold: false,
    pagerLinks:'ul.nav-list li',
    btnNext:'a.btn-next',
    btnPrev:'a.btn-prev',
    btnPlayPause:'a.play-pause',
    btnPlay:'a.play',
    btnPause:'a.pause',
    pausedClass:'paused',
    disabledClass: 'disabled',
    playClass:'playing',
    activeClass:'active',
    currentNum:false,
    allNum:false,
    startSlide:null,
    noCircle:false,
    caption:'ul.caption > li',
    pauseOnHover:true,
    autoRotation:false,
    autoHeight:true,
    onChange:false,
    switchTime:3000,
    duration:650,
    event:'click'
  },_options);

  return this.each(function(){
    // gallery options
    var _this = jQuery(this);
    var _slides = jQuery(_options.slideElements, _this);
    var _btnPrev = jQuery(_options.btnPrev, _this);
    var _btnNext = jQuery(_options.btnNext, _this);
    var _btnPlayPause = jQuery(_options.btnPlayPause, _this);
    var _btnPause = jQuery(_options.btnPause, _this);
    var _btnPlay = jQuery(_options.btnPlay, _this);
    var _pauseOnHover = _options.pauseOnHover;
    var _autoRotation = _options.autoRotation;
    var _activeClass = _options.activeClass;
    var _disabledClass = _options.disabledClass;
    var _pausedClass = _options.pausedClass;
    var _playClass = _options.playClass;
    var _autoHeight = _options.autoHeight;
    var _duration = _options.duration;
    var _switchTime = _options.switchTime;
    var _controlEvent = _options.event;
    var _currentNum = (_options.currentNum ? jQuery(_options.currentNum, _this) : false);
    var _allNum = (_options.allNum ? jQuery(_options.allNum, _this) : false);
    var _startSlide = _options.startSlide;
    var _noCycle = _options.noCircle;
    var _onChange = _options.onChange;
    var _pagerGener = _options.pagerGener;
    var _pagerHold = jQuery(_options.pagerHold,_this);
    var _caption = jQuery(_options.caption,_this);
    var _paging = '';
    if(_pagerGener){
      for(var i=0; i< _slides.length; i++){
        _paging += '<li><a href="#">'+(i+1)+'</a></li>';
      }
      _pagerHold.html('<ul>'+_paging+'</ul>');
    }
    var _pagerLinks = jQuery(_options.pagerLinks, _this);
    // gallery init
    var _hover = false;
    var _prevIndex = 0;
    var _currentIndex = 0;
    var _slideCount = _slides.length;
    var _timer;
    if(_slideCount < 2) return;

    _prevIndex = _slides.index(_slides.filter('.'+_activeClass));
    if(_prevIndex < 0) _prevIndex = _currentIndex = 0;
    else _currentIndex = _prevIndex;
    if(_startSlide != null) {
      if(_startSlide == 'random') _prevIndex = _currentIndex = Math.floor(Math.random()*_slideCount);
      else _prevIndex = _currentIndex = parseInt(_startSlide);
    }
    _slides.hide().eq(_currentIndex).show();
    _caption.hide().eq(_currentIndex).show();
    if(_autoRotation) _this.removeClass(_pausedClass).addClass(_playClass);
    else _this.removeClass(_playClass).addClass(_pausedClass);

    // gallery control
    if(_btnPrev.length) {
      _btnPrev.bind(_controlEvent,function(){
        prevSlide();
        return false;
      });
    }
    if(_btnNext.length) {
      _btnNext.bind(_controlEvent,function(){
        nextSlide();
        return false;
      });
    }
    if(_pagerLinks.length) {
      _pagerLinks.each(function(_ind){
        jQuery(this).bind(_controlEvent,function(){
          if(_currentIndex != _ind) {
            _prevIndex = _currentIndex;
            _currentIndex = _ind;
            switchSlide();
          }
          return false;
        });
      });
    }

    // play pause section
    if(_btnPlayPause.length) {
      _btnPlayPause.bind(_controlEvent,function(){
        if(_this.hasClass(_pausedClass)) {
          _this.removeClass(_pausedClass).addClass(_playClass);
          _autoRotation = true;
          autoSlide();
        } else {
          _autoRotation = false;
          if(_timer) clearTimeout(_timer);
          _this.removeClass(_playClass).addClass(_pausedClass);
        }
        return false;
      });
    }
    if(_btnPlay.length) {
      _btnPlay.bind(_controlEvent,function(){
        _this.removeClass(_pausedClass).addClass(_playClass);
        _autoRotation = true;
        autoSlide();
        return false;
      });
    }
    if(_btnPause.length) {
      _btnPause.bind(_controlEvent,function(){
        _autoRotation = false;
        if(_timer) clearTimeout(_timer);
        _this.removeClass(_playClass).addClass(_pausedClass);
        return false;
      });
    }
    // gallery animation
    function prevSlide() {
      _prevIndex = _currentIndex;
      if(_currentIndex > 0) _currentIndex--;
      else {
        if(_noCycle) return;
        else _currentIndex = _slideCount-1;
      }
      switchSlide();
    }
    function nextSlide() {
      _prevIndex = _currentIndex;
      if(_currentIndex < _slideCount-1) _currentIndex++;
      else {
        if(_noCycle) return;
        else _currentIndex = 0;
      }
      switchSlide();
    }
    function refreshStatus() {
      if(_pagerLinks.length) _pagerLinks.removeClass(_activeClass).eq(_currentIndex).addClass(_activeClass);
      if(_currentNum) _currentNum.text(_currentIndex+1);
      if(_allNum) _allNum.text(_slideCount);
      _slides.eq(_prevIndex).removeClass(_activeClass);
      _slides.eq(_currentIndex).addClass(_activeClass);
      if(_noCycle) {
        if(_btnPrev.length) {
          if(_currentIndex == 0) _btnPrev.addClass(_disabledClass);
          else _btnPrev.removeClass(_disabledClass);
        }
        if(_btnNext.length) {
          if(_currentIndex == _slideCount-1) _btnNext.addClass(_disabledClass);
          else _btnNext.removeClass(_disabledClass);
        }
      }
      if(typeof _onChange === 'function') {
        _onChange(_this, _currentIndex);
      }
    }
    function switchSlide() {
      _slides.eq(_prevIndex).fadeOut(_duration);
      _slides.eq(_currentIndex).fadeIn(_duration);
      _caption.eq(_prevIndex).fadeOut();
      _caption.eq(_currentIndex).fadeIn();
      if(_autoHeight) _slides.eq(_currentIndex).parent().animate({height:_slides.eq(_currentIndex).outerHeight(true)},{duration:_duration,queue:false});
      refreshStatus();
      autoSlide();
    }

    // autoslide function
    function autoSlide() {
      if(!_autoRotation || _hover) return;
      if(_timer) clearTimeout(_timer);
      _timer = setTimeout(nextSlide,_switchTime+_duration);
    }
    if(_pauseOnHover) {
      _this.hover(function(){
        _hover = true;
        if(_timer) clearTimeout(_timer);
      },function(){
        _hover = false;
        autoSlide();
      });
    }
    refreshStatus();
    autoSlide();
  });
};

/* Clear / fill form fields */
function clearFormFields(o){
  if (o.clearInputs == null) o.clearInputs = true;
  if (o.clearTextareas == null) o.clearTextareas = true;
  if (o.passwordFieldText == null) o.passwordFieldText = false;
  if (o.addClassFocus == null) o.addClassFocus = false;
  if (!o.filter) o.filter = "default";
  if(o.clearInputs) {
    var inputs = document.getElementsByTagName("input");
    for (var i = 0; i < inputs.length; i++ ) {
      if((inputs[i].type == "text" || inputs[i].type == "password") && inputs[i].className.indexOf(o.filterClass)) {
        inputs[i].valueHtml = inputs[i].value;
        inputs[i].onfocus = function ()  {
          if(this.valueHtml == this.value) this.value = "";
          if(this.fake) {
            inputsSwap(this, this.previousSibling);
            this.previousSibling.focus();
          }
          if(o.addClassFocus && !this.fake) {
            this.className += " " + o.addClassFocus;
            this.parentNode.className += " parent-" + o.addClassFocus;
          }
          $(this).removeClass('error');
        }
        inputs[i].onblur = function () {
          if(this.value == "") {
            this.value = this.valueHtml;
            if(o.passwordFieldText && this.type == "password") inputsSwap(this, this.nextSibling);
          }
          if(o.addClassFocus) {
            this.className = this.className.replace(o.addClassFocus, "");
            this.parentNode.className = this.parentNode.className.replace("parent-"+o.addClassFocus, "");
          }
        }
        if(o.passwordFieldText && inputs[i].type == "password") {
          var fakeInput = document.createElement("input");
          fakeInput.type = "text";
          fakeInput.value = inputs[i].value;
          fakeInput.className = inputs[i].className;
          fakeInput.fake = true;
          inputs[i].parentNode.insertBefore(fakeInput, inputs[i].nextSibling);
          inputsSwap(inputs[i], null);
        }
      }
    }
  }
  if(o.clearTextareas) {
    var textareas = document.getElementsByTagName("textarea");
    for(var i=0; i<textareas.length; i++) {
      if(textareas[i].className.indexOf(o.filterClass)) {
        textareas[i].valueHtml = textareas[i].value;
        textareas[i].onfocus = function() {
          if(this.value == this.valueHtml) this.value = "";
          if(o.addClassFocus) {
            this.className += " " + o.addClassFocus;
            this.parentNode.className += " parent-" + o.addClassFocus;
          }
        }
        textareas[i].onblur = function() {
          if(this.value == "") this.value = this.valueHtml;
          if(o.addClassFocus) {
            this.className = this.className.replace(o.addClassFocus, "");
            this.parentNode.className = this.parentNode.className.replace("parent-"+o.addClassFocus, "");
          }
        }
      }
    }
  }
  function inputsSwap(el, el2) {
    if(el) el.style.display = "none";
    if(el2) el2.style.display = "inline";
  }
}

function initTabs(){
  var sets = document.getElementsByTagName("div");
  for (var i = 0; i < sets.length; i++)
  {
    if (sets[i].className.indexOf("tabset") != -1)
    {
      var tabs = [];
      var links = sets[i].getElementsByTagName("a");
      for (var j = 0; j < links.length; j++)
      {
        if (links[j].className.indexOf("tab") != -1)
        {
          tabs.push(links[j]);
          links[j].tabs = tabs;
          var c = document.getElementById(links[j].href.substr(links[j].href.indexOf("#") + 1));

          //reset all tabs on start
          if (c) if (links[j].className.indexOf("active") != -1) c.style.display = "block";
          else c.style.display = "none";

          links[j].onmouseover = function ()
          {
            var c = document.getElementById(this.href.substr(this.href.indexOf("#") + 1));
            if (c)
            {
              //reset all tabs before change
              for (var i = 0; i < this.tabs.length; i++)
              {
                var tab = document.getElementById(this.tabs[i].href.substr(this.tabs[i].href.indexOf("#") + 1));
                if (tab)
                {
                  tab.style.display = "none";
                }
                this.tabs[i].className = this.tabs[i].className.replace("active", "");
              }
              this.className += " active";
              c.style.display = "block";
            }
          }
        }
      }
    }
  }
}

function initBubbles() {
  // Store refs to speech bubbles
  var bubble1 = $('.slide-2 .feed1 div');
  var bubble2 = $('.slide-2 .feed2 div');

  // Collect quotation pairs
  var quotes = new Array();

  $('.bubble-quotes li').each(function() {
    var spans = $(this).find('span');
    quotes.push(new Array($(spans[0]).html(), $(spans[1]).html()));
  });

  // Set bubble click action to reveal appropriate quotatations
  $('.bubbles a').click(function(e) {
    $(this).parent().addClass('selected');
    $(this).parent().siblings().removeClass('selected');

    // Determine number of bubble clicked
    var num = parseInt($(this).attr('class').match(/\d+/)[0]);

    // Retrieve quotations from array and reveal
    bubble1.add(bubble2).fadeOut(200, function() {
      bubble1.html(quotes[num-1][0]);
      bubble2.html(quotes[num-1][1]);
    });
    bubble1.add(bubble2).fadeIn(200);
  });
}

function initShortConsultationForm() {
  // Validate complimentary consultation request form
  var reqForm = $('#consultation-form'); // store reference to form for easy access
  var pText = reqForm.find('p');
  var submitNow = false;

  reqForm.submit(function(e) {
    var valid = true; // flag for overall validity

    // Check each required field and make sure it is non-empty
    $.each(['name', 'phone', 'email', 'zip'], function(i, v) {
      var val = $('input[name=' + v + ']').val();

      // If it is empty, mark error
      if (val == '' || val.toLowerCase() == v) {
        valid = false;

        $('input[name=' + v + ']').addClass('error');
      } else {
        $('input[name=' + v + ']').removeClass('error');
      }
    });

    // Cancel submission of invalid forms, mark required text in red
    if (!valid) {
      pText.text('Please fill out the required fields marked in red then re-submit the form.');
      pText.addClass('error');
      e.preventDefault();
      return;
    } else if (submitNow) {
      // Submit now chosen & form checks out, so submit it via AJAX
      e.preventDefault();
      $.post(reqForm.attr('action'),
        reqForm.serialize(),
        function(data) {
          // Inform user that request was submitted
          reqForm.find('.buttons').empty();
          pText.fadeOut(250, function() {
            $(this).removeClass('error').text('Thank you for submitting your request. \
            Our staff will contact you shortly.').fadeIn(250)
          });
        }
      );
    }
  });

  reqForm.find('input[name=submitNow]').click(function(e) {
    submitNow = true;
    reqForm.append($('<input type="hidden" name="submitNow" value="1" />'));
    e.preventDefault();
    reqForm.submit();
  });
}

function initZipConsultationForm() {
  // Consultation zip search
  if ($('#sidebar form input[name=zip]').length) {
    $('#sidebar form input[name=zip]').focus(function(e) {
      if ($(this).val() == 'Enter zip code') {
        $(this).val('');
      }
    });
    $('#sidebar form input[name=zip]').blur(function(e) {
      if (!$(this).val()) {
        $(this).val('Enter zip code');
      }
    });
  }
}

function initReferralForm() {
  // Referral form validation: make sure required fields are filled
  refForm = $('#referrals-form'); // store reference to form for easy access

  // Textarea clearing hack
  refForm.find('textarea').focus(function(e) {
    $(this).attr('class', '');
  });

  refForm.submit(function(e) {
    refValid = true; // flag for overall refValidity

    // Check each required field and make sure it is non-empty
    nameField = refForm.find('input[name=name]');
    if (nameField.val() == '' || nameField.val() == 'Your Name') {
      nameField.addClass('error');
    } else {
      nameField.removeClass('error');
    }

    recipientsField = refForm.find('textarea[name=recipients]');
    if (recipientsField.val() == '' || recipientsField.val() == 'Email') {
      recipientsField.addClass('error');
    } else {
      recipientsField.removeClass('error');
    }


    $.each(['address', 'city', 'state', 'zip', 'email'], function(i, v) {
      val = refForm.find('input[name=' + v + ']').val();

      // If it is empty, mark error
      if (val == '' || val.toLowerCase() == v) {
        refValid = false;

        refForm.find('input[name=' + v + ']').addClass('error');
      } else {
        refForm.find('input[name=' + v + ']').removeClass('error');
      }
    });

    // Cancel submission of invalid form, mark required text in red
    if (!refValid) {
      if (!refForm.find('p.error').length)
        refForm.find('.btn-submit').before($('<p class="error">Please fill out all required fields (in red), then re-submit the form.</p>'));

      e.preventDefault();
    } else {
      // Form is correct, submit by AJAX
      e.preventDefault();
      if (refForm.find('p.error').length) { refForm.find('p.error').empty(); }
      $.post(refForm.attr('action'),
        refForm.serialize(),
        function(data) {
          // Inform user that request was submitted
          var subButton = refForm.find('.btn-submit');
          subButton.fadeOut(250, function() {
            $(this).replaceWith($('<p class="success"><strong>Thank you for submitting \
              your referral!</strong></p>')).fadeIn(250);
          });
        }
      );
    }
  });
}
