$(function(){
  $('a[rel*=external]').live('click',function(){
    window.open(this.href);
    return false;
  });
  /********* FAQ Page JS ************/
  $('.read_more_link').bind('click', function(e){
    e.preventDefault();
    var $this = $(this),
        $more_answer = $this.next('.more_answer');

    $more_answer.slideToggle( 500, function(){

      if( $more_answer.is(':visible') ) {
        $this.text('Read Less');
      } else {
        $this.text('Read More');
      }
    });
  });

  /********** Specs *************/
  $('.order_dropdown.details_link').bind('click', function(e){
    e.preventDefault();
    var $this = $(this),
        $main = $('#main'),
        $footer = $('footer');

    $this.parent().fadeOut();
    $main.slideDown(function(){
      var y = $main.offset().top - 200;
      $('body, html').animate({scrollTop : y}, 400);
      $footer.show();
    });
  });

  /********** Bikes Pages *************/
  $('a.why').bind('click', function(e){
    e.preventDefault();
    var $this = $(this),
        $nextWhy = $this.next('div').children('.further_why');

    $this.toggleClass('active');
    $nextWhy.slideToggle( function(){
      if( $nextWhy.is(':visible') ) {
        $this.text('Close');
      } else {
        $this.text('Info');
      }
    });
  });

  /**************** Order Bikes Page ****************/
  $('a.info_photos').bind('click', function(e){
    e.preventDefault();
    var $this = $(this),
        $nextInfo = $this.next('div.order_more_info');

    $this.toggleClass('active');
    $nextInfo.slideToggle( function(){
      if( $nextInfo.is(':visible') ) {
        $this.text('Close');
      } else {
        $this.text('Info / Photos');
      }
    });
  });

  /* For Other Field if its a Gift */
  $('input#Field6_other').bind('focus', function(){
    $('#Field6_1').attr('checked', 'checked');
    $(this).removeClass('no_valid')
           .parent('.form_row')
           .addClass('active')
           .siblings('.form_row')
           .removeClass('active');
  });

  $('input#Field6_other').bind('blur', function(){
    var $this = $(this);
    if( $this.val() === "" && !($('#Field6_1').attr('checked')) ) {
      $this.addClass('no_valid').removeClass('error_row');
    }
  });

  $('input#Field6_1').change( function(){
    if($(this).is(":checked") ) {
      $('#Field6_other').removeClass('no_valid').focus();
    } else {
      $('#Field6_other').addClass('no_valid').parent('div.error_row').removeClass('error_row');
    }
  });

  $('input#Field6_0').change( function(){
    if($(this).is(":checked") ) {
      $('#Field6_other').addClass('no_valid').parents('div.error_row').removeClass('error_row');
    } else {
      $('#Field6_other').removeClass('no_valid');
    }
  });

  $('#continue_btn').bind('click', function(e) {
    e.preventDefault();
    var $this = $(this);

    if( orderFormValidate('#order_part_1') ) {
      calculateOrderTotal('#order_part_1');
      $('body, html').animate({scrollTop : 0}, 300);

      $('#order_part_1').slideUp(600, function(){
        $('#order_part_2').slideDown(1000);
      });
    }
  });

  /* Click on 'back button' on the second part of the form to take them to the first
  part if they want to review their options and such */
  $('a#back_to_start').click(function(e){
    e.preventDefault();
    var $this = $(this);

    $('#order_part_2').slideUp(1000, function(){
      $('#order_part_1').slideDown(1500);
    });
  });

  $('#order_form_no_2').submit( function() {
    return orderFormValidate('#order_part_2');
  });

  /* Validation for Form based on ID/selector passed in */
  function orderFormValidate( containSelector ) {
    var selects = $(containSelector +' select').not('.no_valid'),
        textBoxes = $(containSelector +' input.text').not('.no_valid'),
        valid = false,
        emailField = $(containSelector + ' #Field24'),
        phoneField = $(containSelector + ' #Field23'),
        checkEmail = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/,
        checkPhone = /^((\+\d{1,3}(-| )?\(?\d\)?(-| )?\d{1,3})|(\(?\d{2,3}\)?))(-| )?(\d{3,4})(-| )?(\d{4})(( x| ext)\d{1,5}){0,1}/;
        //checkPhone = /^(?:(?:\+?1\s*(?:[.-]\s*)?)?(?:\(\s*([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9])\s*\)|([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]))\s*(?:[.-]\s*)?)?([2-9]1[02-9]|[2-9][02-9]1|[2-9][02-9]{2})\s*(?:[.-]\s*)?([0-9]{4})(?:\s*(?:#|x\.?|ext\.?|extension)\s*(\d+))?$/;

    textBoxes.each( function() {
      var $this = $(this);
      if( $this.attr('value') === "" ) {
        $this.parent('.form_row').addClass('error_row');
      } else {
        $this.parent('.form_row').removeClass('error_row');
      }
    });

    selects.each( function() {
      var $this = $(this),
          fieldVal = $this.val(),
          fieldID = $this.attr('id');

      if( fieldVal === "-" ) {
        $this.parent('.form_row').addClass('error_row');
      } else if ( fieldID === "Field30" || fieldID === "Field38" ) {
        /* No state field validation if not US */
        if( fieldVal !== "United States" ) {
          $this.parents('li').find('.state_field').addClass('no_valid').parent('.form_row').removeClass('error_row');
        }
        $this.parent('.form_row').removeClass('error_row');
      } else {
        $this.parent('.form_row').removeClass('error_row');
      }
    });

    if( emailField.length ){
      if( checkEmail.test( emailField.val()) === false ) {
        emailField.parent('.form_row').addClass('error_row');
      } else {
        emailField.parent('.form_row').removeClass('error_row');
      }
    }

    if( phoneField.length ){
      if( checkPhone.test( phoneField.val()) === false ) {
        phoneField.parent('.form_row').addClass('error_row');
      } else {
        phoneField.parent('.form_row').removeClass('error_row');
      }
    }

    if( $('.error_row').length > 0 ) {
      return false;
    } else {
      return true;
    }
  }

  /* Calculates the order total by the data-price attr on the input
  This also adds the selected configuration options to a list */
  function calculateOrderTotal(containSelector) {
    var selectedConfig = $(containSelector + ' input[type="radio"]:checked').next('label').not('.default_val'),
        total = 0,
        $configUL = $('.configuration ul'),
        additionalCosts = $(containSelector + ' input[type="radio"]:checked');

    if( $configUL.children('li').length > 0 ) {
      $configUL.children('li').remove();
    }

    selectedConfig.each( function(){
      var $this  = $(this);
      if( $this.attr('for') !== "Field6_1" ) {
        $configUL.append("<li><span>–</span><div class='config_option'>" + $this.text() + "</div></li>");
      } else {
        $configUL.append("<li><span>–</span><div class='config_option'>Gift - " + $('#Field6_other').val() + "</div></li>");
      }
    });

    additionalCosts.each( function(){
      var $this = $(this),
          priceAdd = $this.data('price');
      if( priceAdd != undefined && priceAdd != NaN ){
        total += parseInt($this.data('price'), 10) ;
      }
    });

    $('.bike_price span').text(total);
  }

  $('.form_row input[type="radio"]:checked').each( function() {
    var $this = $(this);

    $this.parent('.form_row').addClass('active').siblings().removeClass('active');
  });

  /*This changes the style for labels to be black instead of
  greyed out when selected. It also  */
  $('.form_row input').change( function() {
    var $this = $(this);

    $this.parent('.form_row').addClass('active').siblings().removeClass('active');

    /* Show Shipping Info if its Different when the box is checked */
    if( $this.attr('id') === "Field45") {
      if( $this.attr('checked') !== 'checked' ) {
        $('#foli33').fadeIn();
        $('#foli33 .form_row input[type="text"], #foli33 .form_row select').not('#Field34').removeClass('no_valid');
      } else {
        $('#foli33').fadeOut(200);
        $('#foli33 .form_row').removeClass('error_row').children('input[type="text"], #foli33 .form_row select').addClass('no_valid');
      }
    }

  });
  /**************** End Order Bikes Page JS ****************/

  /**** Home Page slideshow Start *****/
  /**** initial setup *****/
  function initialGallerySetup(){
    setupGallery();
    setTimeout( function(){ $('.home_about_budnitz').fadeOut();}, 9500 );

    if( $('#home_slideshow').length > 0 && $('.gallery img').length > 1 ) {
      clearTimeout(slideshow.autoRotate);
      slideshow.autoRotate = setTimeout( function(){ $('.button.next').trigger('click.custom'); } , 9500 );
    }
  }

  $('#home_slideshow img').bind('click', function() {
    clearTimeout(slideshow.autoRotate);
    $('.button.next').trigger('click.custom');
  });

  /* Variable bound to the window to prevent global variable */
  var slideshow = {
    current_image_index : 0
  };
  window.slideshow = slideshow;

  /* Gallery Setup */
  function setupGallery() {
    var $galleryImg = $('.gallery img'),
        $gallery = $('.gallery'),
        windowHt = $(window).height() - 62,
        windowWDTH = $(window).width(),
        wRatio = windowWDTH / windowHt,
        totalWidthImages = 0;

    if ( windowWDTH < '1100' ) {
      windowWDTH = '1100';
    }
    if( $('.order_slideshow').length === 0 ) {
      $('#home_slideshow').height(windowHt);
      $('#slideshow').height(windowHt);
    }

    $galleryImg.each( function() {
      var $this = $(this),
          imgWidth = 1500,
          imgHeight = 1000,
          imgRatio = imgWidth / imgHeight,
          imgReverseRatio = imgHeight / imgWidth;

      var adjH, adjW, left, top = 0;
      if (wRatio > 1){
        adjW = windowWDTH;
        adjH = windowWDTH * imgReverseRatio;
        if (adjH < windowHt){
          adjH = windowHt;
          adjW = windowHt * imgRatio;
        }
      } else {
        adjH = windowHt;
        adjW = windowHt * imgRatio;
        if (adjW < windowWDTH){
          adjW = windowWDTH;
          adjH = windowWDTH * imgReverseRatio;
        }
      }

      totalWidthImages += adjW;

      if ( adjH > windowHt ) {
        top = (windowHt - adjH) /2;
      }

      $this.css({'height' : ~~adjH+'px', 'width' : ~~adjW+'px', 'top' : ~~top});
      $gallery.fadeIn(2e3);
    });

    var newLeft = -1 * slideshow.current_image_index * ( $galleryImg.first().width() ) + ( windowWDTH - $galleryImg.first().width () )/2;

    $gallery.width( totalWidthImages );
    $gallery.css('left', newLeft + 'px');
  }

  /** Click handler for button clicks in the slideshows */
  $('.images_slideshow .button').bind('click, click.custom', function(e) {
    e.preventDefault();
    var user_clicked_button = !e.namespace || !e.namespace === 'custom',
        $button = $(this);

    if ( !user_clicked_button ) {
      slideshow.autoRotate = setTimeout( function(){ $('.button.next').trigger('click.custom'); } , 9500 );
    } else {
      clearTimeout( slideshow.autoRotate );
    }

    $('.images_slideshow').queue(function(){
      var $images_slideshow = $(this);

      var button_direction = $button.hasClass('prev') ? 'back' : 'forward',
          $gallery = $('.gallery'),
          $gallery_img = $('.gallery img'),
          window_width = $(window).width(),
          gallery_left_value = $gallery.css('left') === 'auto' ? 0 : Math.abs(parseInt($gallery.css('left'),10)),
          number_of_images = $gallery_img.length,
          image_width = $gallery_img.first().width(),
          past_image_index = slideshow.current_image_index - 1 === -1 ? number_of_images - 1 : slideshow.current_image_index - 1,
          $past_image = $($gallery_img[past_image_index]),
          last_image_in_view = slideshow.current_image_index === number_of_images - 1,
          first_image_in_view = slideshow.current_image_index === 0,
          diff_in_width = window_width - image_width,
          horz_align_adjust = (window_width - image_width)/2;


      if ( last_image_in_view && button_direction === 'forward') {
        $gallery_img.first().clone().appendTo('.gallery').addClass('last_image');

        $gallery.width($gallery.width() + $gallery_img.first().width());
        $gallery.animate({
          left: '-='+(window_width - diff_in_width) +'px'
        },1000, function(){
          $gallery.css('left', (-1 * horz_align_adjust) + 'px');
          $('.last_image').remove();
          slideshow.current_image_index = 0;
          setupGallery();
          $images_slideshow.dequeue();
        });
      }
      else if (first_image_in_view && button_direction === 'back') {
        $gallery_img.last().clone().prependTo('.gallery').addClass('first_image');
        $gallery.css('left', -(gallery_left_value + image_width) );
        $gallery.animate({
          left: '+='+(window_width - diff_in_width) +'px'
        },1000, function(){
          $gallery.css('left', -($gallery.width() - image_width));
          $('.first_image').remove();
          slideshow.current_image_index = number_of_images - 1;
          setupGallery();
          $images_slideshow.dequeue();
        });

      }
      else {
        $gallery.animate({
          left: button_direction === 'forward' ? ('-='+ (window_width - diff_in_width) +'px') : ('+=' + (window_width - diff_in_width) + 'px')
        },1000, function(){
          slideshow.current_image_index += button_direction === 'forward' ? 1 : -1;
          setupGallery();
          $images_slideshow.dequeue();
        });
      }
    });
  });

  /* After ALL gallery images are loaded, resize 'em. Setup the gallery functionality */
  $('.gallery img').imagesLoaded( initialGallerySetup );

  /* Widnow resize function to check on what the footer should be as well as the images
  in the gallery being resized */
  $(window).resize(function() {
    setupGallery();
    footerPosition();
  });

  window.onorientationchange = function() {
    setupGallery();
    footerPosition();
  }

  /*drop_nav hover state fixes */
  $('#drop_nav li').hover(
    function () {
      $('ul', this).stop(true, true).slideDown(300);
    },
    function () {
      $('ul', this).slideUp(200);
    }
  );

  $('#footer_primary_social .down_arrow').bind('click', function(e){
    e.preventDefault();
    $this = $(this);
    $this.hide();
    $('footer.primary').css('position', 'absolute').stop(true, true).animate( {'height': '220px'}, 200);
    $('#footer_about_budnitz p, #footer_twitter_feed, #footer_blog_feed').fadeIn(200, function() {
      $('footer.primary').removeClass('minimized');
    });
  });

  $('footer.primary').stop(false, true).hover( function(){
    $this = $(this);
    $('#footer_primary_social ul').stop(true, true).fadeOut(300, function(){
      $('#footer_primary_social ul').fadeIn(400);
    });

    $('footer .down_arrow').stop(true, true).fadeOut(300);
    $('footer.primary').css('position', 'absolute').stop(true, true).animate( {'height': '168px'}, 200);
    $('#footer_about_budnitz p, #footer_twitter_feed, #footer_blog_feed').fadeIn(200, function() {
      $this.removeClass('minimized');
    });
  }, function(){
    $this = $(this);
    $('#footer_primary_social ul').stop(true, true).fadeOut(100, function(){
      $('#footer_primary_social ul').fadeIn(200);
    });
    $('#footer_about_budnitz p, #footer_twitter_feed, #footer_blog_feed').stop(false, true).fadeOut(100, function() {
      $this.addClass('minimized');
    });
    $('footer.primary').css('position', 'absolute').animate({'height' : '62px'}, 100, function(){
    });
    $('footer .down_arrow').delay(100).fadeIn(300);
  });

  //Gets latest tweet for The Green Familylifers
  function getTweet() {
    $.getJSON('http://twitter.com/statuses/user_timeline.json?screen_name=familylifers&count=1&callback=?',
      function(data) {
        var text_val = data[0].text;
        $('#footer_twitter_feed p a').text(text_val);
      });
  }
  getTweet();

  /****************** Overall JS for footer positioning of relative vs. absolute (depending on window size) ***************/
  function footerPosition(){
    if( $(window).height() <= 1030 ) {
      $('footer').not('.rel_footer, .primary').css('position', 'relative');
    } else {
      $('footer').not('.rel_footer, .primary').css('position', 'absolute');
    }
  }
  footerPosition();

  /** If the order_now button exists, bind a scroll check to it (throttled) to see if they have scrolled
   high enough for it to be near the image, then make it absolute instead of fixed */

  if( $('a#order_now_btn').length > 0 ) {
    $(window).scroll( _.throttle(function(){
      var scrollPos = $(window).scrollTop(),
      minScrollPos = $('#top_description h1').offset().top - $(window).scrollTop() < $(window).height()/2;

      if( !minScrollPos ) {
        $('a#order_now_btn').css('position', 'absolute').css('top', 'auto');
      } else {
        $('a#order_now_btn').css('position', 'fixed').css('top', '50%');
      }
    }, 50) );
  }

});

