$(document).ready(function(){

    // if we're on a page with product images
    if ($('#product_images').length) {
        if($('#product_images').hasClass('skis')) {
            // create the ski images object
            var skiImages = new MO.skiImageZoom();
        }
        else {
            // handle the other product pages
            var productImages = new MO.productImageZoom();
        }
    };

    // create the collection menu
    var pulldown = MO.Pullldown($('#categories'));

    // load up the home logo, and start the animation
    var bgOffset = 0;
    var bgInterval;

    $('#header h1').click(function() {
        window.location = '/';
    });

    $('#header h1').mouseenter(function() {
        bgInterval = setInterval(shiftImage, 50);

        function shiftImage() {
            bgOffset-=150;
            if(Math.abs(bgOffset) >= 2400) {
                bgOffset = 0;
            }
            $('#header h1').css('background-position', bgOffset);
        }
    });

    $('#header h1').mouseleave(function() {
        clearInterval(bgInterval);
        $('#header h1').css('background-position', '0');
    });


    // lightboxes
    $('a[rel*=facebox]').facebox();

    // Image reels
    $("#image_reel .scrollable").imageReel();
    $("#video_scroller .scrollable").imageReel();
    $("#sick_clique .scrollable").imageReel();

    // Footer JS

    //function to convert arrays to act more like objects
    //used in detecting set email strings in array
    function oc(a)
    {
      var o = {};
      for(var i=0;i<a.length;i++)
      {
        o[a[i]]='';
      }
      return o;
    }

    //establish an array for all email errors and success
    var emailArray = ['_Email', 'EMAIL IN USE', 'INVALID EMAIL', 'THANKS, BRO!']

    $('#footer div.dealer .footerInput').blur(function() {
        if( $(this).val() == '' ) {
            $(this).val('_Zip Code');
        }
    });

    $('#footer div.dealer .footerInput').focus(function() {
        if( $(this).val() == '_Zip Code' ) {
            $(this).val('');
        }
    });

    $('#footer div.email .footerInput').focus(function() {
        $(this).css('color', 'white');
        var emailVal = $(this).val();
        if( emailVal in oc(emailArray) ) {
            $(this).val('') 
        }
    });

    $('#footer div.email .footerInput').blur(function() {
        $(this).css('color', 'white');
        if( $(this).val() == '' ) {
            $(this).val('_Email');
        }
    });

    // making sure the footer is always positioned on the
    // bottom even if the content is too small

    var prevDocHeight = 0;
    function setFooter() {
        
//        console.log('---------');
//        console.log('body,html height: ' + $('body,html').height() );
//        console.log('window height: ' + $(window).height() );
//        console.log('document height: ' + $(document).height() );
//        console.log('prevDocHeight: ' + prevDocHeight );
//        console.log('footer height: ' + $('#footer').height() );
//        console.log('footer + body,html ' + parseInt($('#footer').height() + $('body,html').height() ));
//        console.log('body,html - footer ' + Math.abs( $('body,html').height() - $('#footer').height() ));
//        console.log( parseInt($('#footer').height() + $('body,html').height() ) > $(document).height() );
        
        var footer = $('#footer');

        if( $(window).height() > $('body').height() && prevDocHeight < $(document).height() ) {
            $('#footer').css('position', 'absolute');
            $('#footer').css('bottom', '0');
        } else if ( $(window).height() < $('#footer').height() + $('body').height() && prevDocHeight > $(document).height() ) {
            $('#footer').css('position', 'relative');
        }          
    }

    setTimeout(setFooter, 1500);
    $(window).resize(function(){ 
        setFooter();
        prevDocHeight = $(document).height();
    });

    // for the dealer return info on the footer
    // if the user wants to find the nearest brick
    // and mortar stores
    $('#zipFooterSubmit').click(function() {
        var zipcode = $('#zipFooter').val();
        
        $('#footerReturned').animate({ opacity: 0 }, 10);

        var url = '/get_dealers/' + zipcode + '/';
        
        // snag the information and distances
        $.getJSON(url, function(data) {

            if(data.length < 1) {
                // if there are no results for some reason
                $('#footerReturned .footer_dealer_list').html('<li>' + 
                    '<p class="name">Sorry, there were no results</p></li>');
                $('#footerReturned').animate({ opacity: 1 }, 500);
            } else {
                $('#footerReturned .footer_dealer_list').html('');
                $.each(data, function(index, value) {
                    data = value['fields'];

                    // let's add the data to the html
                    $('#footerReturned .footer_dealer_list').append('' + 
                        '<li>' +
                            '<p class="name">' + data['retailer_name'] + '</p>' +
                            '<p class="address1">' + data['address1'] + '</p>' +
                            '<p class="address2">' + data['address2'] + '</p>' +
                            '<p class="address2">' + parseInt(data['dist']) + ' miles</p>' +
                            '<p class="shop_now"><a href="' + data['url'] + '">Shop Now</a></p>' +
                        '</li>');

                    // we have the information, let's display it
                    $('#footerReturned').animate({ opacity: 1 }, 500);
                    
                    // we only need one result from the footer
                    return false;
                });
            }
        });

        return false;
    });


    // for the dealer return info on the home page
    $('.zip_locator .submit').click(function() {
        var zipcode = $('.zip_locator .zip').val();
        $('#homeReturned').animate({ opacity: 0 }, 10);

        var url = '/get_dealers/' + zipcode + '/';
        
        // snag the information and distances
        $.getJSON(url, function(data) {
            if(data.length < 1) {
                // if there are no results for some reason
                $('#homeReturned .footer_dealer_list').html('<li>' + 
                    '<p class="name">Sorry, there were no results</p></li>');
                $('#homeReturned').animate({ opacity: 1 }, 500);
            } else {
                $('#homeReturned .footer_dealer_list').html('');
                $.each(data, function(index, value) {
                    data = value['fields'];

                    // let's add the data to the html
                    $('#homeReturned .footer_dealer_list').append('' + 
                        '<li>' +
                            '<p class="name">' + data['retailer_name'] + '</p>' +
                            '<p class="address1">' + data['address1'] + '</p>' +
                            '<p class="address2">' + data['address2'] + '</p>' +
                            '<p class="address2">' + parseInt(data['dist']) + ' miles</p>' +
                            '<p class="shop_now"><a href="' + data['url'] + '">Shop Now</a></p>' +
                        '</li>');

                    // we have the information, let's display it
                    $('#homeReturned').animate({ opacity: 1 }, 500);
                    
                    // we only need one result from the footer
                    return false;
                });
            }
        });

        return false;
    });

    //clear input fields on focus
    $('#zipFooter, .zip_locator .zip').focus( function() {
        var prevVal = $(this).val();        

        if( $(this).val() == "_ZIP CODE" ) {
            $(this).val('') 
        }

        // if the user hits enter inside the
        // zip code entry input
        $(this).keypress(function(e) {
            if(e.which == 13) {
                $('#zipFooterSubmit').click();
            }
        });
        
        // try to enter something other than numbers...
        // I DARE YOU!
        $(this).keyup(function () { 
            this.value = this.value.replace(/[^0-9\.]/g,'');
            if($(this).val().length > 5) {
                $(this).val(prevVal);
            } else {
                prevVal = $(this).val();
            }            
        });
    });

    $('#home-EMAIL').focus( function() { 
        $(this).css('color', 'white');
        var emailVal = $(this).val();
        if( emailVal in oc(emailArray) ) {
            $(this).val('') 
        }
    });

    $('#home-EMAIL').blur( function() {
        $(this).css('color', 'white');
        if( $(this).val() == '' ) {
            $(this).val('_Email');
        }
    });

    $('.zip_locator .zip').blur( function() { 
        if( $(this).val() == '' ) {
            $(this).val('_ZIP CODE');
        }
    });

    //Scroll page to errors
    if($('.error').length > 0){
        $('html, body').animate( {
            scrollTop: $('.error').offset().top - 15
        }, 800);
    }

    
    // controls the right/left arrows appearing/disappearing on the home page

    // hide everything first
    $('#image_reel .next, #video_scroller .next, #ctas .inner .next, #sick_clique .next, #sick_clique .prev').animate({ opacity: '0' }, 1);
    $('#image_reel .prev, #video_scroller .prev, #ctas .inner .prev, #sick_clique .next, #sick_clique .prev').animate({ opacity: '0' }, 1);

    // classic mouseenter and mouseleave functions
    $('#image_reel, #video_scroller, #ctas .inner, #sick_clique .inner').mouseenter(function(){
        // var item = $('#ctas .inner').find('.item');
        $(this).find('.next').stop(true,true).animate({ opacity: '1' }, 500);
        $(this).find('.prev').stop(true,true).animate({ opacity: '1' }, 500);
    });

    $('#image_reel, #video_scroller, #ctas .inner, #sick_clique .inner').mouseleave(function(){
        $(this).find('.next').stop(true,true).delay(500).animate({ opacity: '0' }, 500);
        $(this).find('.prev').stop(true,true).delay(500).animate({ opacity: '0' }, 500);
    });


    // right/left for featured images
    var next = $('#ctas .next');
    var prev = $('#ctas .prev');
    var currentItem = 0;
    var items = [];

    $('#ctas .items').children('.item').each( function() {
        items.push($(this));
    });
    
    next.click(function(){
        if((currentItem + 1) < items.length) {
            currentItem++;
            $('#ctas .items').animate({
                left: '-' + items[currentItem].position().left
            }, 500);
        }
    });

    prev.click(function(){
        if((currentItem - 1) >= 0) {
            currentItem--;
            $('#ctas .items').animate({
                left: '-' + items[currentItem].position().left
            }, 500);
        }
    });
    
    // make sure that this only applies to the home page
    if( $('.athlete .home_hide_me').length > 0 ) {
        $('.athlete').mouseenter(function(e){
            var hideMe = $(this).children().children('.home_hide_me');

            hideMe.css('display', 'table');
            hideMe.animate({ opacity: 1 }, 250);
        });
        $('.athlete').mouseleave(function(e){
            var hideMe = $(this).children().children('.home_hide_me');
            hideMe.stop(true,true).animate({ opacity: 0 }, 250, function(){
                hideMe.css('display', 'none');
            });
        });
    }

    $('form#mc-embedded-subscribe-form').submit(function() {
        var form = $(this)
        var email = form.find('.mailchimp').val();
        
        $('.success, .error').remove();

        $.ajax({
            url: "http://" + window.location.host + "/mailchimp_signup",
            data: "email_address=" + email,
            dataType: 'json',
            success: function(msg){
                if (msg.error) {

                    if (parseInt(msg.code) == 214) {
                        errorMsg = 'EMAIL IN USE';                        
                    } else {
                        errorMsg = 'INVALID EMAIL';
                    }
                    
                    form.find('.mailchimp').css('color', '#FF0000');
                    form.find('.mailchimp').val(errorMsg);
                    //$('<div class="chimperror">' + errorMsg + '</div>').insertBefore(form);
                    // WTF THERE SHOULD BE ERROR HANDLING HERE. JUST SAYING.
                } else {
                    form.find('.mailchimp').css('color', '#D56350');
                    form.find('.mailchimp').val('THANKS, BRO!');
                    //$('<div class="success">Thanks bro!</div>').insertBefore(form);
                }
            }
         });
            
        return false;
    })


    $('#international_dealers_wrap select').change(function(){
        
        var url = '/get_international_dealers/' + $(this).val() + '/';
        
        // snag the information and distances
        $.getJSON(url, function(data) {

            if(data.length < 1) {
                // if there are no results for some reason
                $('#international_dealers_wrap .results').html('<li>' + 
                    '<p class="name">Sorry, there were no results</p></li>');
                $('#international_dealers_wrap .results').animate({ opacity: 0 }, 500);
            } else {
                $('#international_dealers_wrap .results').html('');
                $.each(data, function(index, value) {
                    data = value['fields'];                    output ='<li>' +
                            '<span class="name">' + data['retailer_name'] + '</span>' +
                            '<span class="address1">' + data['address1'] + '</span>';

                    if (data['address2']) {
                        output += '<span class="address2">' + data['address2'] + '</span>';
                    };

                    if (data['url']) {
                      output += '<span class="shop_now"><a href="' + data['url'] + '">Shop Now</a></span>';
                    };

                    output += '</li>';


                    // let's add the data to the html
                    $('#international_dealers_wrap .results').append(output);

                    // we have the information, let's display it
                    $('#international_dealers_wrap .results').animate({ opacity: 1 }, 500);
                    
                    // we only need one result from the footer
                    // return false;
                });
            }
        });
        
    });



});

