/* ---------------------------------------------------------------------
Global JavaScript & jQuery

Target Browsers: All
Authors: John Heimkes IV, Anthony Ticknor, Dan Piscitiello, Angela Norlen
------------------------------------------------------------------------ */

var NERD = NERD || {};

$(function() {

    // Initialize!
    NERD.HasJS.init();
    NERD.ExternalLinks.init();
    NERD.AutoReplace.init();
    NERD.FeaturedCarousel.init();
    NERD.LanguageSwitcher.init();
    showGallery.init();
    productTabs.init();
    NERD.MachineType.init();
    MapRegion.init();

    $('.wysiwig table > tbody > tr:nth-child(2n)').addClass('even');
    $('.wysiwig table > tbody > tr:nth-child(2n) td[rowspan]').addClass('exception');

});

/* ---------------------------------------------------------------------
HasJS
Author: Nerdery Boilerplate

Replaces "no-js" class with "has-js" on the body if JavaScript
is present. This allows you to style both the JavaScript enhanced
and non JavaScript experiences.
------------------------------------------------------------------------ */

NERD.HasJS = {
    init: function() {
        $('body').removeClass('no-js');
        $('body').addClass('has-js');
    }
};

/* ---------------------------------------------------------------------
ExternalLinks
Author: Nerdery Boilerplate

Launches links with a rel="external" in a new window
------------------------------------------------------------------------ */

NERD.ExternalLinks = {
    init: function() {
        $('a[rel=external]').attr('target', '_blank');
    }
};

/* ---------------------------------------------------------------------
AutoReplace
Author: Nerdery Boilerplate

Mimics HTML5 placeholder behavior

Additionally, adds and removes 'placeholder-text' class, used as a styling
hook for when placeholder text is visible or not visible

Additionally, prevents forms from being
submitted if the default text remains in input field - which we may
or may not want to leave in place, depending on usage in site
------------------------------------------------------------------------ */
NERD.AutoReplace = {
    $fields: undefined,

    init: function() {
        var $fields = $('[placeholder]');

        if ($fields.length !== 0) {
            var self = this;
            self.$fields = $fields.addClass('placeholder-text');
            self.bind();
        }
    },

    bind: function() {
        var self = this;

        self.$fields.each(
            function() {
                var me = $(this);
                var requiredNote =  me.siblings('.required-field');
                var defaultText = me.attr('placeholder');
                me.attr('placeholder', '').val(defaultText);

                me.focus(
                    function() {
                        if (me.val() === defaultText) {
                            me.val('').removeClass('placeholder-text');
                            if (me.parents('li').children('.required-field').length !== 0) {
                                $(me).siblings('.form-error-message').remove();
                            }
                        }
                    }
                );

                me.blur(
                    function() {
                        if (me.val() === '') {
                            me.val(defaultText).addClass('placeholder-text');
                        }
                    }
                );

                me.parents('form').submit(
                    function() {
                        if (me.is('.required') && (me.val() === defaultText || me.val() === "")) {

                           if(me.siblings('.form-error-message').length == 0) {
                               $('<div class="form-error-message">' + ctx.formError +'</div>').insertAfter(requiredNote);
                           }

                            return false;
                        }
                    }
                );
            }
        );
    }
};

/* ---------------------------------------------------------------------
showGallery
Author: Angela Norlen
------------------------------------------------------------------------ */

var showGallery = {
  galleryUrl : undefined,

  init: function() {
      if($('#gallery-selection').length !== 0) {
          var self = this;
          galleryUrl = 'select-gallery'
          self.grabSelectedGallery();
      }
  },

  grabSelectedGallery: function() {

      $('#gallery-selection').bind('change' , function(e) {
         galleryUrl = $(this).val();
      });

      $('.btn-homepage-callout').bind('click', function(e) {
          if (galleryUrl == 'select-gallery') {
			$("#gal-error").remove();
              $('<div class="error" id="gal-error">' + ctx.galleryError +'</div>').insertBefore('#gallery-selection');
          } else {
          $('#home-content-block3 .error').remove();
              window.top.location = ctx.siteUrl + ctx.langID + galleryUrl;
          }

      });
  }
}

/* ---------------------------------------------------------------------
Featured Product Variations
Author: Angela Norlen

Product Tab Switching
------------------------------------------------------------------------ */

var productTabs = {
	init: function() {
	    var variation = $('.product-variations');

	    if(variation.length !==0) {
	     	variation.hide();
    		$('.product-variations.first').show();

    		$('.nav-variations li a').click(function() {

    			var tabId = $(this).attr('href');
    			var tabIdName = tabId.replace('#' ,'');
    			variation.hide();
    			$('#' + tabIdName).fadeIn();

    			$('.nav-variations li').removeClass('active');
    			$(this).parent('li').addClass('active');

    			return false;
    		});
	    }

	}
}

/* ---------------------------------------------------------------------
Featured Carousel
Author: Anthony Ticknor & Dan Piscietello

Description
------------------------------------------------------------------------ */

NERD.FeaturedCarousel = {

    $slideshow: undefined,
    numSlides: undefined,
    slides: undefined,
    currentSlide: 1,
    play: undefined,

    init: function() {
        var $slideshow = $('#featured-carousel');
        if ($slideshow.length !== 0) {
            var self = this;
            self.$slideshow = $slideshow;
            self.slides = $slideshow.children('.slide');
            self.numSlides = self.slides.length;
            self.setupSlides();
            self.setupControls();
            self.playCarousel();
            self.bind();
        }
    },

    bind: function() {
        var self = this;
        $('.slideshow-prev').click(function() {
            self.togglePlayPause('stop');
            self.prevSlide();
        });
        $('.slideshow-next').click(function() {
            self.togglePlayPause('stop');
            self.nextSlide();
        });
        $('.slideshow-switch').click(function() {
            self.togglePlayPause();
        });
    },

    setupSlides: function() {
        var self = this;
        self.slides.each(
            function() {
                var me = $(this);
                me.css(
                    {
                        'position' : 'absolute',
                        'display' : 'block',
                        'top' : '0',
                        'left' : (me.index() * self.$slideshow.width()) + 'px'
                    }
                );
                var slidePara = me.find('.slide-paragraph');
                var slideText = slidePara.text();
                var slideParaHeight = slidePara.text('W').height();
                slidePara.text('');
                var slideTextArray = slideText.split(' ');

                var temp = '';
                var scratch = '';
                var count = 0;

                for (i = 0; i < slideTextArray.length; i++) {
                    slidePara.append(slideTextArray[i]+' ');

                    if (slidePara.height() > slideParaHeight) {
                        slideParaHeight = slidePara.height();

                        for(j = count; j < i; j++) {
                            scratch += slideTextArray[j] + ' ';
                        }

                        temp += '<span class="slide-text-break">' + scratch + '</span>';
                        scratch = "";
                        count = i;
                    }

                    if (i === slideTextArray.length - 1) {
                        for (k = count; k < i + 1; k++) {
                            scratch += slideTextArray[k] + ' ';
                        }

                        temp += '<span class="slide-text-break">' + scratch + '</span>';
                        slidePara.html($(temp));
                    }
                }
            }
        );
    },

    setupControls: function() {
        var self = this;
        self.slides.first().before('<a class="slideshow-prev"></a><a class="slideshow-next"></a><a class="slideshow-switch play"></a>');
    },

    prevSlide: function() {
        var self = this;
        if (self.currentSlide === 1) {
            self.slides.animate(
                {
                    left: '-=' + self.$slideshow.width() * (self.numSlides - 1)
                }
            );
            self.currentSlide = self.numSlides;
        } else {
            self.slides.animate(
                {
                    left: '+=' + self.$slideshow.width()
                }
            );
            self.currentSlide--;
        }
    },

    nextSlide: function() {
        var self = this;
        if (self.currentSlide === self.numSlides) {
            self.slides.animate(
                {
                    left: '+=' + self.$slideshow.width() * (self.numSlides - 1)
                }
            );
            self.currentSlide = 1;
        } else {
            self.slides.animate(
                {
                    left: '-=' + self.$slideshow.width()
                }
            );
            self.currentSlide++;
        }
    },

    pauseCarousel: function() {
        var self = this;
        clearInterval(self.play);
    },

    playCarousel: function() {
        var self = this;
        self.play = window.setInterval(function() {self.nextSlide();}, 5000);
    },

    togglePlayPause: function(override) {
        var controlButton = $('.slideshow-switch');
        if (controlButton.hasClass('play') || override === 'stop') {
            controlButton.removeClass('play');
            controlButton.addClass('pause');
            this.pauseCarousel();
        } else {
            controlButton.removeClass('pause');
            controlButton.addClass('play');
            this.playCarousel();
        }
    }

};

/* ---------------------------------------------------------------------
Language Switcher
Author: Josh Anderson

By Default, the langauge switcher is a list of links.
This JS hides the go button and makes the language switcher happen instantly. (BAM!)
------------------------------------------------------------------------ */

NERD.LanguageSwitcher = {

    container: undefined,

    init: function() {
        if ($('.language-switcher').length) {
            var self = this;
            self.container = $('.language-switcher');
            self.container.after('<form method="post" id="lang-form"><select id="lang-switcher" name="language"></select></form>');
            self.container.find('li').each(function() {
                var optionValue = $(this).find('a').attr('href');
                var optionClass = $(this).find('a').attr('class');
                var link = $(this).text();
                $('#lang-form select').append('<option value="' + optionValue + '" class="' + optionClass + '">' + link + '</option>');
            });
            $('option.' + ctx.langID).attr('selected', 'selected');
            self.container.remove();
            self.bind();
        }
    },

    bind: function() {
        var self = this;
        $('#lang-switcher').change(function() {
            window.location = $(this).val();
        });
    }

}

/* ---------------------------------------------------------------------
MachineType
Author: Anthony Ticknor

Replaces "no-js" class with "has-js" on the body if JavaScript
is present. This allows you to style both the JavaScript enhanced
and non JavaScript experiences.
------------------------------------------------------------------------ */

NERD.MachineType = {

    $machineTypeSelect: undefined,

    init: function() {
        var $machineTypeSelect = $('#machine-type');
        if ($machineTypeSelect.length !== 0) {
            var self = this;
            self.$machineTypeSelect = $machineTypeSelect;
            self.bind();
        }
    },

    bind: function() {
        var self = this;
        self.$machineTypeSelect.change(function() {
            window.location = $(this).val();
        });
    }
};


/* ---------------------------------------------------------------------
MapRegion
Author: Adrienne L. Travis

This is functionality for the Dealer Locator. It handles form
initialization, clearing of unused inputs, and selecting of map regions/
checkboxes.
------------------------------------------------------------------------ */

var MapRegion = {

regionmap : undefined,
checklist : undefined,
allinputs : undefined,

init : function() {
        if(jQuery("#dealer-block").length > 0) {
            var self = this;
            self.regionmap = jQuery("#dealer-map");
            self.checklist = jQuery("#region-list");
            self.allinputs = jQuery("#dealer-form input").add(jQuery("#dealer-form select"));
            self.bind(); //object has been initialized, call bind
            }
    }, // end init

bind : function() {
        var self = this;
        // initialize form if it's got querystring values
        self.formEvents.formInitialize(self.allinputs,self.mapEvents.processSelection);
        // process map click
        self.regionmap.find('li').click(function(e) {
            self.mapEvents.processSelection(e.currentTarget,'mapclick');
            });
        // process region checkbox click
        self.checklist.find('input').click(function(e) {
            self.mapEvents.processSelection(e.currentTarget,'formclick');
            });
        // other form events
        self.allinputs.filter('#find').change(function() {
            self.formEvents.clearSome('regionsearch',self.allinputs);
            });
        self.allinputs.filter('.regionsearch').change(function() {
            self.formEvents.clearSome('addrsearch',self.allinputs);
            });
        self.allinputs.filter('.btn-search').click(function() {
            self.formEvents.submitDisable(self.allinputs);
            });
    }, // end bind

mapEvents : {

    processSelection : function(me,clicktype) {
        var incomingme = undefined;
        var mapme = undefined;
        var checkme = undefined;
        var genericid = '';
        // get our initial object
        if(typeof(me) == 'object') {
            incomingme = jQuery(me);
            }
        else if(typeof(me) == 'string') {
            incomingme = jQuery("#"+me);
            }
        // process objects by type
        if(clicktype == 'mapclick') {
            genericid = incomingme.attr("title");
            mapme = incomingme;
            checkme = jQuery("#region-"+genericid).find("input");
            }
        else if(clicktype == 'formclick') {
            genericid = incomingme.attr("value");
            checkme = incomingme;
            mapme = jQuery("#map-"+genericid);
            }
        // make sure both checkbox and map region are selected/unselected appropriately
        if(mapme) {
            if(mapme.hasClass("selected")) {
                mapme.removeClass("selected");
                checkme.removeAttr("checked");
                }
            else {
                mapme.addClass("selected");
                checkme.attr("checked","checked");
                }
            }
        } // end processSelection

    }, // end mapEvents

formEvents : {

    clearSome : function(clearClass,mySelections) {
        mySelections.filter("#is-region").val("Select");    // always reset the hidden input, it'll get cleared again if necessary
        mySelections.filter("#radius").val("50");           // also always reset the radius, it'll get cleared again if necessary
        if(clearClass) {
            var clearme = mySelections.filter("."+clearClass);
            clearme.removeAttr("checked");
            clearme.not(":checkbox").not(":submit").val(""); // don't clear the VALUES of checkboxes or submits!
            }
        if(clearClass == "regionsearch") {      // if we're clearing regionsearch fields, we also need to clear the map regions
            jQuery(".map-region").removeClass("selected");
            }
        }, // end clearSome

    submitDisable : function(mySelections) {
        mySelections.filter( function() { return $(this).val() == ''; } ).attr("disabled","disabled");
        }, // end submitDisable

    formInitialize : function(mySelections,myMapEvents) {
        var myquerystring = window.location.search.substring(1);
        mySelections.filter(":checkbox").each(function(index) {
            var myval = jQuery(this).val();
            var myid = jQuery(this).attr("id");
            if(myquerystring.indexOf(myval) > -1) {
                myMapEvents(myid,'formclick');
                }
            });
        } // end formInitialize

    } // end formEvents

};
