var currentIcon = 0;
var previousIcon = 0;
var repeater;
var wait;

var productId;

var currentPage = 0;
var previousPage;

var currentRegion = '';
var previousRegion = 'prev';

var previousSign;

// Sign Dimensions Hash/Array

var dim = {'d10': [28, 22, 4],
           'd16': [48, 30, 7],
           'd20': [54, 38, 8],
           'd24': [60, 46, 9],
           'd28': [66, 48, 10],
           'd32': [78, 56, 11],
           'd36': [97, 60, 13],
           'd40': [102, 66, 14],
           'd48': [132, 78, 16],
           'd61': [162, 90, 18],
           'd76': [226, 110, 19],
           'd89': [249, 132, 20],
           'd114': [276, 154, 25]
          };

function startVideo(video) {

  $f('video-player', '/flash/flowplayer.swf', {
    clip: {
      url: video,
      autoPlay: true,
      autoBuffering: true
    },
    plugins:  {
      controls:  null
    }
  });

}

$(document).ready(function() {

  // Setup Modal Boxes

  $('.modal').nyroModal({
    galleryCounts: '',
    hideContent : function(elts, settings, callback) {
      elts.contentWrapper.hide();
      callback();
    }, minWidth: 0, minHeight: 0
  });

  // Secure the email address
  $('.secure').amail('[secure1]','{secure2}','NOSPAM');


  // Accordion Nav

  $('#nav .item').not('.active').mouseenter(function() {
    $(this).children('.title-bg').stop(false, true).fadeIn(600);
    $(this).children('.title').stop().animate( {color: '#211F20'}, 600);
    $(this).not('.noexpand').stop().animate({height: '91'}, 600);
  }).mouseleave(function() {
    $(this).children('.title-bg').stop(false, true).fadeOut(600);
    $(this).children('.title').stop().animate( {color: '#ffffff'}, 600);
    $(this).not('.noexpand').stop().animate({height: '26'}, 600);
  });

  // Right Nav

  $('#right-nav .item').mouseenter(function() {
    $(this).stop();
    $(this).animate({paddingTop: '10'}, 600);
  }).mouseleave(function() {
    $(this).stop();
    $(this).animate({paddingTop: '0'}, 600);
  });

  $('body #right-nav #customer').mouseover(function() {
    $(this).stop();
    $(this).animate({height: '61'}, 600);
  });

  $('#right-nav #customer').mouseout(function() {
    $(this).stop();
    $(this).animate({height: '19'}, 600);
  });

  $('#right-nav #login').mouseover(function() {
    $(this).stop();
    $(this).animate({height: '99'}, 600);
  }).mouseout(function() {
    $(this).stop();
    $(this).animate({height: '19'}, 600);
  });


  // Subnav

  $('#nav .child-item.inactive').mouseenter(function() {
    $(this).children('.child-bg').stop(false, true).fadeIn(600);
    $(this).children('.child-title').stop().animate( {color: '#211F20'}, 600);
  }).mouseleave(function() {
    $(this).children('.child-bg').stop(false, true).fadeOut(600);
    $(this).children('.child-title').stop().animate( {color: '#ffffff'}, 600);
  });

  $('#nav .item.parent').click(function() {
    $(this).next().stop(false, true).toggle('blind', {}, 500);
  })


  // Gas Prices

  if($('#billboard').length > 0) {

    var res = {
                'd1024': [-199, 697, 475, 331, 16, 10],
                'd1280': [-271, 842, 583, 404, 20, 16],
                'd1440': [-314, 920, 657, 459, 22, 20],
                'd1900': [-460, 1235, 862, 628, 32, 28]
              };

    var screenWidth = $('#minsize').width();
    var type = screenWidth > 1220 ? 'd1280' : 'd1024';
    if(screenWidth > 1400) { type = 'd1440'; }
    if(screenWidth > 1900) { type = 'd1900'; }

    $('#billboard').css('margin-left', res[type][0]);
    $('#billboard').css('width', res[type][1]);
    $('#billboard').css('height', res[type][2]);
    $('#billboard iframe').css('height', res[type][3]);
    $('#billboard .left').css('font-size', res[type][4]);
    $('#billboard .right').css('font-size', res[type][5]);

    $.jGFeed('http://www.eia.gov/petroleum/gasdiesel/includes/gas_diesel_rss.xml', function(feeds) {
      if(!feeds) {
        return false;
      }

      var prices = feeds.entries[0].content.match(/\d\.\d+\s+\.\.\s+U\.S\./g);
      var unleaded = prices[0].match(/\d\.\d\d/g);
      var diesel = prices[1].match(/\d\.\d\d/g);

      $('#billboard-unleaded .right').html(writePrice(unleaded, 'r'));
      $('#billboard-diesel .right').html(writePrice(diesel, 'g'));

      $('#billboard-power .left, #billboard-millions .left').height($('#billboard-unleaded .left').height());

      if($.browser.msie && parseInt($.browser.version) < 8) {
        $('#billboard-power .left img').height($('#billboard-unleaded .left').height() * 0.6);
        $('#billboard-power .left img').width($('#billboard-unleaded .left').width() * 0.8);
        $('#billboard-millions .left img').height($('#billboard-unleaded .left').height() * 0.8);
        $('#billboard-millions .left img').width($('#billboard-unleaded .left').width() * 0.5);
      }

    }, 1);

    $.getJSON('/ajax/jackpots', function(data) {
  	  $('#billboard-power .right').html(writeJackpot(data['powerball'][0], 'b'));
  	  $('#billboard-millions .right').html(writeJackpot(data['megamillions'][0], 'y'));
    });


  }


  // Default form entry handling

  $('#contact-form textarea').focus(function() {
    if($(this).text() == $(this).attr('default')) {
      $(this).text('');
    }
  });

  if($('#contact-form textarea').text() == '') {
    $('#contact-form textarea').text($('#contact-form textarea').attr('default'));
  }

  $('input.js').focus(function() {
    if($(this).val() == $(this).attr('default')) {
      $(this).val('');
    }
  }).blur(function() {
    if($(this).val() == '') {
      $(this).val($(this).attr('default'));
    }
  });

  $('input.js').each(function() {
    if($(this).val() == '') {
      $(this).val($(this).attr('default'));
    }
  });


  // Tabbed Pages

  if($('#tab-x').length) {
    wait = $.timer(200, function(timer) {
      if($('#tab-x').is(':visible')) {
        $('#content-wrap').css({visibility: 'visible'});
        wait.stop();
      }
    });
  }

  $('#content-menu .item').click(function() {
    currentPage = $('#content-menu .item').index(this);

    if(currentPage == previousPage) {
      return false;
    }

    var menuColor;
    var page = $('#content-menu').attr('class');
    switch(page) {
      case 'fuel':
        menuColor = '#FAAF40';
        break;
      case 'lottery':
        menuColor = '#00ADEE';
        break;
      case 'hotel':
        menuColor = '#EC1C24';
        break;
      case 'time':
        menuColor = '#009345';
        break;
    }

    if(page == 'fuel' || page == 'lottery' || page == 'hotel' || page == 'time') {
      repeater.stop();
      $("#slide-" + (currentIcon)).fadeOut(1000);
      $("#slide-menu-" + (previousPage)).fadeOut(1000);
      $("#slide-menu-" + (currentPage)).fadeIn(1000);
      $("#subtitle-" + (previousPage)).fadeOut(1000);
      $("#subtitle-" + (currentPage)).fadeIn(1000);
      if($.browser.msie && parseInt($.browser.version) < 9) {
        $(".related-" + (previousPage)).hide();
        $(".related-" + (currentPage)).show();
      } else {
        $(".related-" + (previousPage)).fadeOut(1000);
        $(".related-" + (currentPage)).fadeIn(1000);
      }
    }

    var currentMenu = $('#content-menu #menu-' + currentPage);
    var previousMenu = $('#content-menu #menu-' + previousPage);
    var currentTab = $('#content #tab-' + currentPage);
    var previousTab = $('#content #tab-' + previousPage);

    if(previousPage != 0)  {
      previousMenu.css('backgroundImage', "url('../images/page_menu_div.png')");
      $('#content-menu #menu-' + (previousPage + 1)).css('backgroundImage', "url('../images/page_menu_div.png')");
    }
    previousMenu.animate({backgroundColor: '#211F20', color: '#ffffff'}, 600);
    previousTab.fadeOut(600);

    currentMenu.css('backgroundImage', 'none');
    $('#content-menu #menu-' + (currentPage + 1)).css('backgroundImage', 'none');
    currentMenu.animate( {backgroundColor: menuColor, color: '#211F20'}, 600);
    currentTab.fadeIn(600);

    if(!previousPage) {
      $('#tab-x').fadeOut(600);
    }

    previousPage = currentPage;
  });


  // Slideshow

  size = $(".slide").length;
  repeater = $.timer(slideDelay, function(timer) { nextSlide(size); });

  function showSlide(index) {
    previousIcon = currentIcon;
    currentIcon = index;

    if (currentIcon != previousIcon) {
      $("#slide-" + (previousIcon)).fadeOut(1000);
      $("#slide-" + (currentIcon)).fadeIn(1000);
    }
  }

  function nextSlide(size) {
    var index = 0;

    if(currentIcon < size - 1) {
      index = currentIcon + 1;
    } else {
      index = 0;
    }
    showSlide(index);
  }


  // Functions to keep the size of the video & background image correct

  function keepAspect() {
    var height = $('#minsize').height();
    var width = $('#minsize').width();
    var ratio = width/height;

    if(ratio > 1.77777777) {
      $('.slide, .slide-menu').width(width);
      $('.slide, .slide-menu').height(width / 1.7777777);
    } else {
      $('.slide, .slide-menu').width(height * 1.7777777);
      $('.slide, .slide-menu').height(height);
    }

    if($('#tech-dots').length) {
      $('#tech-dots').width(($('#minsize').width() / 2) - 420);
      $('#tech-hdots').width(($('#minsize').width() / 2) - 224);
    }
  }

  keepAspect();

  $.timer(300, function(timer) {
  	keepAspect();
  	timer.stop();
  });

  $(window).resize(function() {
    keepAspect();
  });


  /* Product Pages */
  /* ------------- */

  var prevProduct = 1;

  $('#product-wrap #img-bar img, .indicator').click(function() {
    productId = getNum($(this).attr('id'));

    if(productId != prevProduct) {
      $('#product-images #p-img-' + prevProduct).fadeOut(1000);
      $('#product-images #indicator-' + prevProduct).fadeTo(1000, 0);
      $('#product-wrap #text-' + prevProduct).fadeOut(1000);
      $('#product-images #p-img-' + productId).fadeIn(1000);
      $('#product-images #indicator-' + productId).fadeTo(1000, 1);
      $('#product-wrap #text-' + productId).fadeIn(1000);

      if($('#product-images #p-img-' + productId + ' .subslide').length > 1) {
        subslideRepeat = $.timer(5000, function() {
          if($('#product-images #p-img-' + productId + ' #subslide-0').is(':visible')) {
            $('#product-images #p-img-' + productId + ' #subslide-0').fadeOut(1000);
            $('#product-images #p-img-' + productId + ' #subslide-1').fadeIn(1000);
          } else {
            $('#product-images #p-img-' + productId + ' #subslide-1').fadeOut(1000);
            $('#product-images #p-img-' + productId + ' #subslide-0').fadeIn(1000);
          }
        });
      } else if(typeof(subslideRepeat) != 'undefined') {
        subslideRepeat.stop();
      }
    }

    prevProduct = productId;
  });

  $('#product-wrap .product-dot').click(function(e) {
    var callOut = $(this).attr('data-content');

    if(callOut == 'video') {
      e.preventDefault();

      var videoSrc = $(this).attr('data-src');
      var videoColor = $(this).attr('data-color');
      var closeBut = $(this).attr('data-close');

      $.nyroModalManual({
        bgColor: '#000000',
        url: '#video-player',
        endShowContent : function(elts, settings, callback) {
          $('#nyroModalWrapper').css({background: videoColor, border: 0});
          $('a#closeBut').addClass(closeBut);
          $('#nyroModalContent iframe').attr('src', videoSrc).show();
        },
        hideContent : function(elts, settings, callback) {
          $('#nyroModalContent iframe').attr('src', '');
          elts.contentWrapper.hide();
          callback();
        }
      });
    } else {
      $(this).children('.product-info').html(callOut);
      $('.product-info, .info-arrow').fadeOut();
      $(this).children('.product-info, .info-arrow').fadeIn();
    }
  });

  $('#docs a').mouseenter(function() {
    $(this).children('.bg').stop(false, true).fadeIn(600);
    $(this).children('.title').stop().animate( {color: '#211F20'}, 600);
  }).mouseleave(function() {
    $(this).children('.bg').stop(false, true).fadeOut(600);
    $(this).children('.title').stop().animate( {color: '#ffffff'}, 600);
  });



  /* New Technology  */
  /* --------------- */

  $('#tech-main .link').mouseenter(function() {
    if(!$(this).hasClass('active')) {
      var type = $(this).attr('data-type');
      $('.hover.'+type).stop(false, true).fadeIn();
    }
  }).mouseleave(function() {
    if(!$(this).hasClass('active')) {
      var type = $(this).attr('data-type');
      $('.hover.'+type).stop(false, true).fadeOut();
    }
  });

  $('#tech-main .link').click(function(e) {
    var type = $(this).attr('data-type');
    $(this).addClass('active');

    $('#tech-main .link').not(this).removeClass('active');
    $('.hover.'+type).stop(false, true).fadeOut();
    $('.bw.'+type).stop(false, true).fadeOut();
    $('.bw').not('.bw.'+type).stop(false, true).fadeIn();
    $('.tech-copy').not('.tech-copy.'+type).stop(false, true).fadeOut();
    $('.tech-copy.'+type).stop(false, true).fadeIn();
    $('.center').not('.center.'+type).stop(false, true).fadeOut();
    $('.center.'+type).stop(false, true).fadeIn();

    /*if(type == 'build') {
      e.preventDefault();
      var videoSrc = $(this).attr('data-src');

      $.nyroModalManual({
        bgColor: '#000000',
        url: '#video-player',
        endShowContent : function(elts, settings, callback) {
          $('#nyroModalContent iframe').attr('src', videoSrc).show();
          $('#nyroModalBg').fadeTo(1500, 0.35);
        },
        hideContent : function(elts, settings, callback) {
          $('#nyroModalContent iframe').attr('src', '');
          $('.center.'+type).stop(false, true).fadeOut();
          $('.bw').stop(false, true).fadeOut();
          $('.link.'+type).removeClass('.active');
          elts.contentWrapper.hide();
          callback();
        }
      });
    }*/
  });


  /* Product Photo Galleries */
  /* ----------------------- */

  if($('#gallery-vectormap').length) {

    var us_states = {AL: 'Alabama', AK: 'Alaska', AZ: 'Arizona', AR: 'Arkansas', CA: 'California', CO: 'Colorado', CT: 'Connecticut', DE: 'Delaware', DC: 'District of Columbia', FL: 'Florida', GA: 'Georgia', HI: 'Hawaii', ID: 'Idaho', IL: 'Illinois', IN: 'Indiana', IA: 'Iowa', KS: 'Kansas', KY: 'Kentucky', LA: 'Louisiana', ME: 'Maine', MD: 'Maryland', MA: 'Massachusetts', MI: 'Michigan', MN: 'Minnesota', MO: 'Missouri', MS: 'Mississippi', MT: 'Montana', NE: 'Nebraska', NV: 'Nevada', NH: 'New Hampshire', NJ: 'New Jersey', NM: 'New Mexico', NY: 'New York', NC: 'North Carolina', ND: 'North Dakota', OH: 'Ohio', OK: 'Oklahoma', OR: 'Oregon', PA: 'Pennsylvania', RI: 'Rhode Island', SC: 'South Carolina', SD: 'South Dakota', TN: 'Tennessee', TX: 'Texas', UT: 'Utah', VT: 'Vermont', VA: 'Virginia', WA: 'Washington', WV: 'West Virginia', WI: 'Wisconsin', WY: 'Wyoming'};

    $('#gallery-vectormap').vectorMap({map: 'usa_en', color: '#c9c9ca', backgroundColor: 'transparent', hoverColor: '#FCB040'});

    var stateImgWidth = 0;

    $('#gallery-vectormap').bind('regionClick.jvectormap', function(event, code) {
      var stateName = us_states[code.toUpperCase()];
      var stateImgCount = $('.gallery-photo.'+code).length;
      stateImgWidth = Math.floor((stateImgCount + 1) / 2);

      $('.gallery-state').text(stateName);

      if(stateImgCount > 0) {
        $('#gallery-none').fadeOut(600);

        $('#gallery-state-image').attr('src', '/images/states/'+code+'.png');

        $('.gallery-photo').hide();
        $('.gallery-photo.'+code).show();

        $('.gallery-prev').addClass('inactive');
        $('#photo-slider').width(stateImgWidth * 517).css('left', 0);

        if(stateImgWidth < 3) {
          $('.gallery-next').addClass('inactive');
        } else {
          $('.gallery-next').removeClass('inactive');
        }

        $('#gallery-map').fadeOut(600, function() {
          $('#gallery-left').fadeIn(600, function() {
            $('#gallery-photos').fadeIn(600, function() {
              $('#gallery-children').slideDown();
            });
          });
        });

      } else {
        $('#gallery-none').fadeIn(600);
      }
    });

    $('#gallery-children').click(function(e) {
      e.preventDefault();
      $('#gallery-left').fadeOut(600, function() {
        $('#gallery-photos').fadeOut(600, function() {
          $('#gallery-map').fadeIn(600, function() {
            $('#gallery-children').slideUp();
          });
        });
      });
    });

    $('.gallery-next').click(function() {
      if(getNum($('#photo-slider').css('left')) < (stateImgWidth - 1) * 517) {
        $('#photo-slider').animate({left: '-=517px'}, {}, 300);
        $('.gallery-prev').removeClass('inactive');
      }

      if(getNum($('#photo-slider').css('left')) >= (stateImgWidth - 2) * 517) {
        $('.gallery-next').addClass('inactive');
      }
    });

    $('.gallery-prev').click(function() {
      if(getNum($('#photo-slider').css('left')) > 0) {
        $('#photo-slider').animate({left: '+=517px'}, {}, 300);
        $('.gallery-next').removeClass('inactive');
      }

      if(getNum($('#photo-slider').css('left')) <= 517) {
        $('.gallery-prev').addClass('inactive');
      }
    });

  }


  /* Old Signtracker */
  /* --------------- */

  // Hover over a sign name

  $('.select-sign-wrap').mouseenter(function() {
    var s = $(this).children('.select-sign');
    if(! s.hasClass('active')) {
      s.children('.select-sign-bg').fadeIn(600);
      s.animate( {color: '#211F20'}, 600);
      s.parent().find('.get-directions').fadeIn();
    }
  }).mouseleave(function() {
    var s = $(this).children('.select-sign');
    if(! s.hasClass('active')) {
      s.children('.select-sign-bg').fadeOut(600);
      s.animate( {color: '#ffffff'}, 600);
      s.parent().find('.get-directions').fadeOut();
    }
  });


  // Selecting from the sign list

  $('#sign-list .select-sign').click(function() {
    var id = parseInt($(this).attr('id').replace(/[^0-9]*/, ''));

    if(id != previousSign) {
      // Change status of corresponding map markers
      $('#marker-' + previousSign).removeClass('active');
      $('#marker-' + id).addClass('active');

      // Change status of sign entries
      $('#select-sign-' + previousSign).removeClass('active').animate( {color: '#ffffff'}, 600).children('.select-sign-bg').fadeOut(600);
      $(this).addClass('active');

      // Hide & Show get directions links
      $('#select-sign-' + previousSign).parent().find('.get-directions').fadeOut();
      $(this).parent().find('.get-directions').fadeIn();
    }

    previousSign = id;
  });


  // Sign type check boxes

  $('#type-options .check').click(function() {
    var markerType = $(this).attr('marker');

    if($(this).text() == 'x') {
      $(this).text('');

      // Deactivate & hide all markers for selected type
      $('#map .marker.' + markerType).removeClass('on').hide();
      // Deactivate & hide all list entries for selected type
      $('#sign-list .select-sign.' + markerType).removeClass('on').parent().slideUp();
    } else {
      $(this).text('x');

      // Activate & show all markers for selected type
      $('#map .marker.' + markerType).addClass('on');
      $('#map .marker.' + markerType + currentRegion).show();
      // Activate & show all list entries for selected type
      $('#sign-list .select-sign.' + markerType).addClass('on');
      $('#sign-list .select-sign.' + markerType + currentRegion).parent().slideDown();
    }

    // Reset scroll buttons
    if($('#sign-list .select-sign.on' + currentRegion).size() < 12) {
      $('.scroll').hide();
      $('#sign-list').scrollTop(0);
    } else {
      $('#scroll-down').show();
      $('#sign-list').scrollTop(0);
    }
  });


  // Hover over a Map Region

  $('#map .region').mouseenter(function() {
    id = $(this).attr('id');
    if('.' + id != currentRegion) {
      $('#map-' + id).show();
    }
  }).mouseleave(function(){
    id = $(this).attr('id');
    if('.' + id != currentRegion) {
      $('#map-' + id).hide();
    }
  });


  // Select a Map Region

  $('#map .region').click(function() {
    currentRegion = '.' + $(this).attr('id');

    if(currentRegion != previousRegion) {
      // Deselect current sign/marker when changing region
      $('#select-sign-' + previousSign).removeClass('active').css({color: '#ffffff'}).children('.select-sign-bg').hide();
      $('#select-sign-' + previousSign).parent().find('.get-directions').hide();
      $('#marker-' + previousSign).removeClass('active');
      previousSign = '';

      // Hide "Please select a region text"
      $('#region-select').slideUp();
      // Show sign list
      $('#contents').slideDown();

      // Show activated markers for selected region
      $('#map .marker').hide();
      $('#map .marker.on' + currentRegion).show();

      // Show activated list entried for selected region
      $('#sign-list .select-sign').parent().slideUp();
      $('#sign-list .select-sign.on' + currentRegion).parent().slideDown();

      // Show map for selected region
      $('#map-' + previousRegion.substring(1)).hide();
      $('#map-' + currentRegion.substring(1)).show();

      // Reset scroll buttons
      if($('#sign-list .select-sign.on' + currentRegion).size() < 12) {
        $('.scroll').hide();
        $('#sign-list').scrollTop(0);
      } else {
        $('#scroll-down').show();
        $('#sign-list').scrollTop(0);
      }
    }

    previousRegion = currentRegion;
  });


  // Sign list scroll buttons

  $('#scroll-up').click(function() {
    $('#sign-list').animate({scrollTop : "-=110px"});

    if( $('#sign-list').scrollTop() <= 110 ) {
      $('#scroll-up').hide();
    }
    $('#scroll-down').show();
  });

  $('#scroll-down').click(function() {
    $('#sign-list').animate({scrollTop : "+=110px"});

    if( $('#sign-list').scrollTop() >= (($('#sign-list .select-sign.on' + currentRegion).size() * 22) - 353) ) {
      $('#scroll-down').hide();
    }
    $('#scroll-up').show();
  });


  /* New Signtracker */
  /* --------------- */

  $('.map .marker').click(function() {
    var id = getNum($(this).attr('id'));

    $('#signtracker-list .select-sign').removeClass('selected');
    $('#signtracker-list #select-sign-' + id).addClass('selected');

    var pos = $(this).position();
    showSignInfo(id, pos.left, pos.top);
  });

  $('#signtracker-list .select-sign.enabled').click(function() {
    var id = getNum($(this).attr('id'));

    $('#signtracker-list .select-sign').removeClass('selected');
    $(this).addClass('selected');

    var pos = $('.map #marker-'+id).position();
    showSignInfo(id, pos.left, pos.top);
  });

  $('#info #info-close').click(function() {
    $('#signtracker-list .select-sign').removeClass('selected');
    $('#info, #info-arrow').hide();
  });


  function showSignInfo(id, x, y) {
    var sign = signs[id];

    // Set sign name
    $('#info #name').html(sign.name);

    // Show/Hide image if there is one and set width of info window
    if(sign.image) {
      $('#info').width(526);
      $('#info #info-image').show();
      $('#info #info-image img').attr('src', '/signs/'+id+'/small/'+sign.image);
    } else {
      $('#info #info-image').hide();
      $('#info').width(290);
    }

    // Set the map image according to lat/long
    var url = "http://maps.google.com/maps/api/staticmap?center="+sign.lat+","+sign.long+"&zoom=12&size=290x150&sensor=false&markers=color:green|label:A|"+sign.lat+","+sign.long;
    $('#info #google-map img').attr('src', url);

    $('#info #updated #updated-date').text(sign.updated);

    // Calculate and set the positions of the arrow and info window
    var mapHeight = $('.state-image').height();
    var mapWidth = $('.state-image').width();

    if(y > (mapHeight/2)) {

      $('.map #info-arrow').css({'background-image': 'url("/images/map_info_down.png")', 'left': (x+2) + 'px', 'top': (y-6) + 'px'});

      if(x > (mapWidth/2)) {
        var move = sign.image ? 450 : 200;
        $('.map #info').css({'left': (x-move) + 'px', 'top': (y-248) + 'px'});
      } else {
        $('.map #info').css({'left': (x-200) + 'px', 'top': (y-248) + 'px'});
      }
    } else {

      $('.map #info-arrow').css({'background-image': 'url("/images/map_info_up.png")', 'left': (x+2)  + 'px', 'top': (y+10) + 'px'});

      if(x > (mapWidth/2)) {
        var move = sign.image ? 450 : 200;
        $('.map #info').css({'left': (x-move) + 'px', 'top': (y+21) + 'px'});
      } else {
        $('.map #info').css({'left': (x-200) + 'px', 'top': (y+21) + 'px'});
      }
    }

    // Show the info window
    $('#info, #info-arrow').fadeIn();

  }

  $('.search .search-clear').click(function() {
    var searchField = $(this).siblings('.text');
    searchField.val(searchField.attr('default'));
    $(this).parent().submit();
  });

  $('#city-search form').submit(function() {
    var length = signs.length;
    var city = $('#city-search .text').val();
    city = city == 'city name' ? '' : city;
    var exp =  new RegExp(city, 'i');

    $('#zip-search .text').val($('#zip-search .text').attr('default'));

    for(var x in signs) {
      if(signs.hasOwnProperty(x)) {
        if(exp.test(signs[x].city)) {
          $('#select-sign-' + x).show();
          $('#marker-' + x).show();
        } else {
          $('#select-sign-' + x).hide();
          $('#marker-' + x).hide();
        }
        fleXenv.updateScrollBars(false, false);
      }
    }

    return false;
  });

  $('#zip-search form').submit(function() {
    var length = signs.length;
    var zip = $('#zip-search .text').val();
    zip = zip == 'zip code' ? '' : zip;
    var exp =  new RegExp(zip, 'i');

    $('#city-search .text').val($('#city-search .text').attr('default'));

    for(var x in signs) {
      if(signs.hasOwnProperty(x)) {
        if(exp.test(signs[x].zip)) {
          $('#select-sign-' + x).show();
          $('#marker-' + x).show();
        } else {
          $('#select-sign-' + x).hide();
          $('#marker-' + x).hide();
        }
        fleXenv.updateScrollBars(false, false);
      }
    }

    return false;
  });

  $('#signtracker-content-wrap #down-signs').click(function() {
    var check = $('#down-signs #check');

    $('#zip-search .text').val($('#zip-search .text').attr('default'));
    $('#city-search .text').val($('#city-search .text').attr('default'));

    $('#signtracker-list .select-sign').removeClass('selected');
    $('#info, #info-arrow').hide();

    if(check.text() == '') {
      check.html('&#10004;');
      $('#signtracker-list .select-sign.active').hide();
      $('.map .marker.active').hide();
    } else {
      check.html('');
      $('#signtracker-list .select-sign.active').show();
      $('.map .marker.active').show();
    }
    fleXenv.updateScrollBars(false, false);
  });


  // Fix for weird IE7 javascript layout bug

  if($.browser.msie && parseInt($.browser.version) < 8) {
    $('#minsize').height($('html').height());
    $('#minsize').width($('html').width());
  }

  if($('#blog-content-wrap').length > 0) {
    var dates = $('#blog-dates').length > 0 ? 0 : 20;
    $('#blog-content-wrap').height($('#blog-wrap').height() - 56 + dates);
    $('#blog-content').height($('#blog-wrap').height() - 71 + dates);
  }

  if($.browser.webkit) {
    thewait = $.timer(200, function(timer) {
      if($('#blog-content-wrap').length > 0) {
        var dates = $('#blog-dates').length > 0 ? 0 : 20;
        $('#blog-content-wrap').height($('#blog-wrap').height() - 56 + dates);
        $('#blog-content').height($('#blog-wrap').height() - 71 + dates);
      }
      thewait.stop();
    });
  }

  $(window).resize(function() {

    // Fix for weird IE7 javascript layout bug

    if($.browser.msie && parseInt($.browser.version) < 8) {
      $('#minsize').height($('html').height());
      $('#minsize').width($('html').width());
    }

    if($('#blog-content-wrap').length > 0) {
      var dates = $('#blog-dates').length > 0 ? 0 : 20;
      $('#blog-content-wrap').height($('#blog-wrap').height() - 56 + dates);
      $('#blog-content').height($('#blog-wrap').height() - 71 + dates);
    }

  });


  /* Blog */

  var count = $(this).find('.post-link').length;
  var size = count * 91;
  $('.slider-wrap .slider').width(size);

  var activePost = $('.slider .post-link.active');
  var activePostIndex = $('.slider .post-link').index(activePost)
  var sliderLeft = activePostIndex * 91 * -1 + 182;

  if(count > 5 ) {
    $('.slider-right').show();
  }

  if(activePostIndex > 2 && (count > 5 || sliderLeft < 0)) {
    $('.slider-wrap .slider').css('left', '' + sliderLeft + 'px');
    $('.slider-left').show();
  }

	$('.slider-left').click(function() {
	  if( parseInt($('.slider-wrap .slider').css('left')) >= -91 ) {
	    $(this).hide();
    }
	  if( parseInt($('.slider-wrap .slider').css('left')) >= 0 - $('.slider-wrap .slider').width() - 182 ) {
	    $('.slider-right').show();
    }

	  $('.slider-wrap .slider').animate({left : "+=91px"}, 300, 'easeInOutCubic');
	});

	$('.slider-right').click(function() {
	  if( parseInt($('.slider-wrap .slider').css('left')) <= 0 - $('.slider-wrap .slider').width() + 455) {
	    $(this).hide();
    }
	  if( parseInt($('.slider-wrap .slider').css('left')) <= 0 ) {
	    $(this).siblings('.slider-left').show();
    }

	  $('.slider-wrap .slider').animate({left : "-=91px"}, 300, 'easeInOutCubic');
	});

  $('.video-thumb img').click(function() {
    $('#blog-content .video-title').html($(this).attr('title'));
    $('#video-player iframe').attr('src', $(this).attr('alt'));
  });

  $('.video-thumb .thumb-over').click(function() {
    $('#blog-content .video-title').html($(this).siblings('img').attr('title'));
    $('#video-player iframe').attr('src', $(this).siblings('img').attr('alt'));
  });

  var vcount = $(this).find('.video-thumb').length;
  var vsize = vcount * 102;
  $('.video-slider').width(vsize);

  if(vcount > 4) {
    $('.video-right').show();
  }

	$('.video-left').click(function() {
	  if( parseInt($('.video-slider-wrap .video-slider').css('left')) >= -102 ) {
	    $(this).hide();
    }
	  if( parseInt($('.video-slider-wrap .video-slider').css('left')) >= 0 - $('.video-slider-wrap .video-slider').width() - 202 ) {
	    $('.video-right').show();
    }

	  $('.video-slider-wrap .video-slider').animate({left : "+=102px"}, 300, 'easeInOutCubic');
	});

	$('.video-right').click(function() {
	  if( parseInt($('.video-slider-wrap .video-slider').css('left')) <= 0 - $('.video-slider-wrap .video-slider').width() + 510) {
	    $(this).hide();
    }
	  if( parseInt($('.video-slider-wrap .video-slider').css('left')) <= 0 ) {
	    $(this).siblings('.video-left').show();
    }

	  $('.video-slider-wrap .video-slider').animate({left : "-=102px"}, 300, 'easeInOutCubic');
	});



  /* Build a Sign */
  /* ------------ */


  // Init Form elements

  $('.build-a-sign .form-block.cabinet_color_other').slideUp();
  $('.build-a-sign .other-color').slideUp();
  $('.build-a-sign .product-2-toggle, .build-a-sign .product-3-toggle, .build-a-sign .product-4-toggle').slideUp();

  if($('#label_1_text').length > 0) {
    for(var i = 1; i < 5; i++) {
      refreshLabel(i);
    }
  }


  // These classes can be used anywhere and trigger moving to form steps

	$(".goto-1").click(function() {
	  $('#slider-wrap').animate({scrollLeft : "0px", width : "425px"}, 800, 'easeInOutCubic');
	  $('#bas-content-wrap #content-heading').animate({width : "405px"}, 800, 'easeInOutCubic');
    var title = current_client.title ? current_client.title : 'Build Your Sign';
	  $('#bas-content-wrap #content-heading h1').html(title);
	  $('#no-example-sign').fadeIn();
	  $('.example-sign.active').fadeOut();
	  $('#sign-sample, #digit-sample').fadeOut();
	});

	$(".goto-2").click(function() {
	  $('#slider-wrap').animate({scrollLeft : "423px", width : "425px"}, 800, 'easeInOutCubic');
 	  $('#bas-content-wrap #content-heading').animate({width : "405px"}, 800, 'easeInOutCubic');
    var title = current_client.title ? current_client.title : 'Build Your Sign';
    $('#bas-content-wrap #content-heading h1').html(title);
	  $('#no-example-sign').fadeIn();
	  $('.example-sign').fadeOut();
	  $('#sign-sample, #digit-sample').fadeOut();
	});

	$(".goto-3").click(function() {
	  $('#slider-wrap').animate({scrollLeft : "846px", width : "425px"}, 800, 'easeInOutCubic');
 	  $('#bas-content-wrap #content-heading').animate({width : "405px"}, 800, 'easeInOutCubic');
    var title = current_client.title ? current_client.title : 'Build Your Sign';
    $('#bas-content-wrap #content-heading h1').html(title);
    setStackedSide();
    resetRule();
    $('.example-sign .vrule.main').animate({left: '-25px'});
	  $('#sign-sample, #digit-sample').fadeIn();
	  $('.digit-rule').fadeOut(600, function() { $(this).hide(); });
	  $('.sign-wrap .label-wrap').slideUp(600, function() { $(this).hide(); });
	});

	$(".goto-4").click(function() {
	  $('#slider-wrap').animate({scrollLeft : "1269px", width : "425px"}, 800, 'easeInOutCubic');
	  $('#bas-content-wrap #content-heading').animate({width : "405px"}, 800, 'easeInOutCubic');
    var title = current_client.title ? current_client.title : 'Build Your Sign';
    $('#bas-content-wrap #content-heading h1').html(title);
	  $('.digit-rule').fadeIn(600, function() { $(this).show(); });
	  $('.example-sign .vrule.main').animate({left: '-68px'});
	  showActiveExample();
	  showHideLabels();
	});3

	$(".goto-5").click(function() {
	  $('#slider-wrap').animate({scrollLeft : "1692px", width : "496px"}, 800, 'easeInOutCubic');
	  $('#bas-content-wrap #content-heading').animate({width : "473px"}, 800, 'easeInOutCubic');
	  showActiveExample();
    var submit_title = current_client.submit_title ? current_client.submit_title : 'Finalize+Submit';
    $('#bas-content-wrap #content-heading h1').html(submit_title);
	});


  // Show/Hide input box for Other Cabinet Color in Step 2

  $('select#cabinet_color').change(function() {
    if($(this).val() == 'other') {
      $('.form-block.cabinet_color_other').slideDown();
      $('#cabinet_color_other').addClass('required');
      $('.example-sign .rule-wrap').css('border-color', $('#cabinet_color_other').val());
    } else {
      $('.form-block.cabinet_color_other').slideUp();
      $('#cabinet_color_other').removeClass('required');
      $('.example-sign .rule-wrap').css('border-color', $(this).val());
    }
  });


  $('#cabinet_color_other').keyup(function() {
    if($('select#cabinet_color').val() == 'other') {
      $('.example-sign .rule-wrap').css('border-color', $('#cabinet_color_other').val());
    }
  });


  // Configuration in Step 3

  $('select#configuration').change(function() {
    setStackedSide();

    if($('select#products').val() == '1') {
      $('select#products').val('2');
      $('select#products').parent().children('div').children('span').html('#Of Products: 2');
      $('select#products').trigger('change');
    }

    if(current_client.force_previews && $(this).val() == 'side by side') {
      $('#products_1, #products_3, #products_4, #label_placement_lefthorizontal, #label_placement_leftvertical').removeClass('disabled-false').addClass('disabled-true');
    } else {
      $('#products_1, #products_3, #products_4, #label_placement_lefthorizontal, #label_placement_leftvertical').removeClass('disabled-true').addClass('disabled-false');
    }
  });

  function setStackedSide() {

    if($('select#configuration').val() == 'stacked') {
      $('.example-sign').not('.top').fadeOut();
      $('.example-sign.top').fadeIn();
      $('#no-example-sign').fadeOut();
      $('#no-example-sign .title').text('Your sign will be generated in step 3');
    } else {

      if($('select#products').val() == '2' && $('select#label_placement').val() == 'top') {
        $('.example-sign').not('.side').fadeOut();
        $('.example-sign.side').fadeIn();
        $('#no-example-sign').fadeOut();
        $('#no-example-sign .title').text('Your sign will be generated in step 3');
      } else {
        $('.example-sign').fadeOut();
        $('#no-example-sign .title').text('Preview Not Available');
        $('#no-example-sign').fadeIn();
        $('.sign-wrap .label-wrap').hide();
      }
    }

    if($('select#configuration').val() == 'stacked') {

      switch($('select#label_placement').val()) {
      case 'top':
        $('.example-sign.top').addClass('active');
        $('.example-sign.vertical, .example-sign.horizontal, .example-sign.side').removeClass('active');
        break;
      case 'left - vertical':
        $('.example-sign.vertical').addClass('active');
        refreshLabel(1);
        refreshLabel(2);
        refreshLabel(3);
        refreshLabel(4);
        $('.example-sign.top, .example-sign.horizontal, .example-sign.side').removeClass('active');
        break;
      case 'left - horizontal':
        $('.example-sign.horizontal').addClass('active');
        $('.example-sign.vertical, .example-sign.top, .example-sign.side').removeClass('active');
        break;
      }

    } else {

      if($('select#products').val() == '2' && $('select#label_placement').val() == 'top') {
        $('#preview-unavailable').fadeOut();
        $('.example-sign.side').addClass('active').fadeIn();
        $('.example-sign.vertical, .example-sign.horizontal, .example-sign.top').removeClass('active').fadeOut();
      } else {
        $('.example-sign').removeClass('active').fadeOut();
        $('#preview-unavailable').fadeIn();
      }

    }

    changeSPS();
  }

  function showActiveExample() {
    if($('select#configuration').val() == 'stacked') {
      $('.example-sign.top').fadeOut();
      $('.example-sign.active').fadeIn();
      $('#preview-unavailable').fadeOut();
    } else {
      if($('select#products').val() == '2' && $('select#label_placement').val() == 'top') {
        $('.example-sign.top').fadeOut();
        $('.example-sign.active').fadeIn();
        $('#preview-unavailable').fadeOut();
      } else {
        $('#preview-unavailable').fadeIn();
      }
    }
  }

  function hideActiveExample() {
    if($('select#configuration').val() == 'stacked') {
      $('.example-sign.active').fadeOut();
    } else {
      if($('select#products').val() == '2') {
        $('.example-sign.active').fadeOut();
      } else {
        $('#preview-unavailable').fadeOut();
      }
    }
  }

  function changeSPS() {
    var file = ['1', 'r', '_', '_', '_', 't', 't'];

    var products = $('select#products').val();

    file[0] = products;

    if(products == '1') {
      file[1] = $('select#color_1').val().charAt(0);
      file[2] = file[3] = file[4] = '_';
    }

    if(products == '2') {
      file[1] = $('select#color_1').val().charAt(0);
      file[2] = $('select#color_2').val().charAt(0);
      file[3] = file[4] = '_';
    }

    if(products == '3') {
      file[1] = $('select#color_1').val().charAt(0);
      file[2] = $('select#color_2').val().charAt(0);
      file[3] = $('select#color_3').val().charAt(0);
      file[4] = '_';
    }

    if(products == '4') {
      file[1] = $('select#color_1').val().charAt(0);
      file[2] = $('select#color_2').val().charAt(0);
      file[3] = $('select#color_3').val().charAt(0);
      file[4] = $('select#color_4').val().charAt(0);
    }

    var sign_config = $('select#configuration').val();

    if(sign_config == 'stacked') {
      file[5] = 't';
    } else {
      file[5] = 's';
    }

    var label_pl = $('select#label_placement').val();
    var label_en = $('select#labels').val();

    if(label_en == 'no') {
      file[6] = 'n';
    } else {
      if(label_pl == 'top') {
        file[6] = 't';
      } else {
        file[6] = 's';
      }
    }

    $('#sign-sample .bg').css('background-image', 'url("/images/sps/' + file.join('') + '.jpg")');
  }

  $('select#digit_size').change(function() {
    var digitSize = parseInt($(this).val());
    var width = dim['d' + digitSize][0];
    var height = dim['d' + digitSize][1]; // Now Unused
    var label = dim['d' + digitSize][2];
    var products = parseInt($('#products').val());

    setSignImage();

    var hinches = inchesToFeet(products * digitSize + (products + 1) * 3);

    $('.example-sign.top .vrule.main div').text(hinches);
    $('.example-sign.top .hrule.main').text(inchesToFeet(width));

    $('.example-sign.top .digit-wrap .vrule div').text(digitSize + '"');
    $('.example-sign.top .label-wrap .vrule div').text(label + '"');


    $('.example-sign.horizontal .vrule.main div').text(hinches);
    $('.example-sign.horizontal .hrule.main').text(inchesToFeet(width * 2));

    $('.example-sign.horizontal .label-wrap .vrule div').text(digitSize + '"');


    $('.example-sign.vertical .vrule.main div').text(hinches);
    $('.example-sign.vertical .hrule.main').text(inchesToFeet(Math.ceil(width + (digitSize * 0.75))));

    $('.example-sign.vertical .label-wrap .vrule div').text(digitSize + '"');


    $('.example-sign.side .vrule.main div').text(inchesToFeet(digitSize + 6));
    $('.example-sign.side .hrule.main').text(inchesToFeet(width * 2));

    $('.example-sign.side .label-wrap .vrule div').text(digitSize + '"');

  });



  // Custom drop downs for sign labels in Step 4

	$(".item.drop-down").click(function() {
	  var th = $(this).parent();

	  if($(th).hasClass('expanded')) {
      $(th).animate({height: '25px'});
      $(th).removeClass('expanded');
    } else {
	    $(".form-block.labels").not(th).not(':hidden').animate({height: '25px'});
	    $(".form-block.labels").not(th).not(':hidden').removeClass('expanded');
      $(th).animate({height: '100px'});
      $(th).addClass('expanded');
    }
	});


  // Show other color text input for label colors in Step 4

  $('.radio-buttons input').change(function() {

    if($(this).val() == 'other' && $(this).prop('checked') == true) {
      $(this).parent().parent().hide();
      $(this).parent().parent().parent().children('.other-color').show();
      $('input#' + $(this).attr('name') + '_other').addClass('required');
    }

    if($(this).val() != 'other' && $(this).prop('checked') == true) {
      $('input#' + $(this).attr('name') + '_other').removeClass('required');
    }
  });


  // Hide other color text input for label colors in Step 4

  $('.other-color-cancel').click(function() {
    $(this).parent().hide();
    $(this).parent().parent().children('.radio-buttons').show();
  });


  // Label Placement in step 4

  $('select#label_placement').change(function() {
    if($('select#configuration').val() == 'stacked') {

      $('#preview-unavailable').fadeOut();

      switch($(this).val()) {
      case 'top':
        $('.example-sign.top').addClass('active').fadeIn();
        $('.example-sign.vertical, .example-sign.horizontal, .example-sign.side').removeClass('active').fadeOut();
        break;
      case 'left - vertical':
        $('.example-sign.vertical').addClass('active').fadeIn(400, function() {
          refreshLabel(1);
          refreshLabel(2);
          refreshLabel(3);
          refreshLabel(4);
        });
        $('.example-sign.top, .example-sign.horizontal, .example-sign.side').removeClass('active').fadeOut();
        break;
      case 'left - horizontal':
        $('.example-sign.horizontal').addClass('active').fadeIn();
        $('.example-sign.vertical, .example-sign.top, .example-sign.side').removeClass('active').fadeOut();
        break;
      }

    } else {

      if($('select#products').val() == '2' && $(this).val() == 'top') {
        $('#preview-unavailable').fadeOut();
        $('.example-sign.side').addClass('active').fadeIn();
        $('.example-sign.vertical, .example-sign.horizontal, .example-sign.top').removeClass('active').fadeOut();
      } else {
        $('.example-sign').removeClass('active').fadeOut();
        $('#preview-unavailable').fadeIn();
      }

    }

    changeSPS();
  });


  // Custom Radio button logic for Step 5

  $('.finalize-options .radio').click(function() {
    $('.finalize-options .radio').text('');
    $(this).text('x');
    var name = $(this).attr('title');
    var val = $(this).attr('default');
    $('input[name=' + name + ']').val(val);
  });


  // Custom Check Box logic for Step 5

  $('.finalize-options .check').click(function() {
    var name = $(this).attr('title');

    if($(this).text() == 'x') {
      $(this).text('');
      $('input[name=' + name + ']').val('false');
    } else {
      $(this).text('x');
      $('input[name=' + name + ']').val('true');
    }
  });


  // Sets the right side status bar values when the form is changed

  $('select').not('.jqtransformignore').change(function() {
    if($(this).attr('name') == 'label_placement') {
      $('#bas-status .' + $(this).attr('name')).text($(this).val().substr(0, 8));
    } else {
      $('#bas-status .' + $(this).attr('name')).text($(this).val());
    }
  });

  $('input:radio').not('.jqtransformignore').change(function() {
    if($(this).prop('checked')) {
      $('#bas-status .' + $(this).attr('name')).text($(this).val());
    }
  });


  // Change label Configuration

  $('select#labels').change(function() {
    showHideLabels();
    changeLabelRequired();
    changeSPS();
  });


  // Hide/Show product configuration options depending on the #products they want

  $('select#products').change(function() {
    var count = $(this).val();

    if(count == '1') {
      $('.product-2-toggle, .product-3-toggle, .product-4-toggle').slideUp(400, function() { $(this).hide(); });
    }

    if(count == '2') {
      $('.product-2-toggle').slideDown();
      $('.product-3-toggle, .product-4-toggle').slideUp(400, function() { $(this).hide(); });
    }

    if(count == '3') {
      $('.product-2-toggle, .product-3-toggle').slideDown();
      $('.product-4-toggle').slideUp(400, function() { $(this).hide(); });
    }

    if(count == '4') {
      $('.product-2-toggle, .product-3-toggle, .product-4-toggle').slideDown();
    }

    var ds = parseInt($('#digit_size').val().replace('"', ''));
    var dh = dim['d' + ds][1] - dim['d' + ds][2];
    var pc = parseInt(count);

    $('.example-sign .vrule.main div').text(inchesToFeet(pc * ds + (pc + 1) * 3));
    $('.example-sign.side .vrule.main div').text(inchesToFeet(ds + 6));

    setStackedSide();
    changeLabelRequired();
    changeSPS();
  });


  // Tenths

  $('#tenths').change(function() {
    setDigitImage();
    setSignImage()
  });


  // Change color of LED digits

  $('select.led_color').change(function() {
    setDigitImage();
    changeSPS();
  });


  // Set Digit Image

  function setDigitImage() {
    var tenths = '';

    if($('#tenths').val() == '9/10') {
      var tenths = '_bar';
    }

    for(var i = 1; i < 5; i++) {
      var color = $('#color_' + i).val();
      $('.example-sign .digit-' + i).css('background-image', 'url("/images/digits_' + color + tenths + '.png")');
    }

  }


  // Set Sign Preview Image

  function setSignImage() {
    var tenths = '';

    if($('#tenths').val() == '9/10') {
      var tenths = '_bar';
    }

    var size = $('select#digit_size').val().replace('"', '');

    var color = current_client.color ? current_client.color : 'red';

    $('#digit-sample img').attr('src', '/images/dps/' + size + tenths + '_' + color + '.png');
  }


  // Change color of label text

  $('input.label-color').change(function() {
    var index = $(this).attr('name').substr(6, 1);

    if($(this).prop('checked') && $(this).val() == 'other') {
      var color = $('#label_' + index + '_color_other').val();
    } else if($(this).prop('checked'))  {
      var color = $(this).val();
    }

    $('.example-sign .label-' + index).css('color', color);
    refreshLabel(index);
  });

  $('.label-color-other').keyup(function() {
    var index = $(this).attr('name').substr(6, 1);
    var color = $(this).val();

    if($('input[name=label_' + index + '_color]').filter(':checked').val() == 'other') {
      $('.example-sign .label-' + index).css('color', color);
      refreshLabel(index);
    }
  });


  // Change color of label bg

  $('input.label-background').change(function() {
    var index = $(this).attr('name').substr(6, 1);

    if($(this).prop('checked') && $(this).val() == 'other') {
      var color = $('#label_' + index + '_background_other').val();
    } else if($(this).prop('checked'))  {
      var color = $(this).val();
    }

    $('.example-sign .label-' + index).css({'background-color': color});
    refreshLabel(index);
  });

  $('.label-bg-other').keyup(function() {
    var index = $(this).attr('name').substr(6, 1);
    var color = $(this).val();

    if($('input[name=label_' + index + '_background]').filter(':checked').val() == 'other') {
      $('.example-sign .label-' + index).css({'background-color': color});
      refreshLabel(index);
    }
  });


  // Change label text

  $('.label-text').keyup(function() {
    var index = $(this).attr('name').substr(6, 1);
    refreshLabel(index);
  });


  function refreshLabel(index) {
    try {
      if (quote) {
        var text = quote['label_'+index+'_text'];
      }
    } catch (err) {
      var text = $('#label_'+index+'_text').val().toUpperCase();
    }

    text = text == 'ENTER LABEL TEXT' ? 'LABEL' : text;

    var v_text = '';

    for(var i = 0; i < text.length; i++) {
      v_text = v_text + text.charAt(i) + '<br />';
    }

    $('.example-sign.vertical .label-' + index).html(v_text);
    $('.example-sign.horizontal .label-' + index).html(text);
    $('.example-sign.top .label-' + index).html(text);
    $('.example-sign.side .label-' + index).html(text);

  }


  // Show or Hide labels and label related text & drop downs

  function showHideLabels() {
    var show = $('select#labels').val();
    var digitSize = parseInt($('#digit_size').val());
    var height = dim['d' + digitSize][1];
    var label = dim['d' + digitSize][2];
    var products = parseInt($('#products').val());

    if(show == 'no') {
      $('.toggle-labels').slideUp();
      $('.example-sign.top .vrule.main div').text(inchesToFeet((products * digitSize) + ((products + 1) * 3)));

      if($('select#configuration').val() == 'stacked') {
        if($('select#label_placement').val() != 'top') {
          $('.example-sign').not('.top').fadeOut();
          $('.example-sign.top').fadeIn();
        }
      }
    } else {
      $('.example-sign.top .vrule.main div').text(inchesToFeet(products * height));
      $('.toggle-labels').slideDown();

      if($('select#configuration').val() == 'stacked') {
        if($('select#label_placement').val() != 'top') {
          $('.example-sign').not('.active').fadeOut();
          $('.example-sign.active').fadeIn();
        }
      }
    }

    for(var i = 1; i < 5; i++) {
      if(show != 'no' && $('select#products').val() >= i) {
        $('.label-wrap-' + i).slideDown(600, function() { $(this).show(); });
      } else {
        $('.label-wrap-' + i).slideUp(600, function() { $(this).hide(); });
      }
    }
  }


  // Reset the hight rule when moving back to Step 3

  function resetRule() {
    var digitSize = parseInt($('#digit_size').val());
    var height = dim['d' + digitSize][1];
    var label = dim['d' + digitSize][2];
    var products = parseInt($('#products').val());
    $('.example-sign.top .vrule.main div').text(inchesToFeet((products * digitSize) + ((products + 1) * 3)));
  }


  // Loop through the 4 labels & Add/Remove required field indicators if needed

  function changeLabelRequired() {
    for(var i = 1; i < 5; i++) {
      if($('select#labels').val() != 'no' && $('select#products').val() >= i) {
        $('input#label_' + i + '_text').addClass('required');

        if($('input[name=label_' + i + '_color]').filter(':checked').val() == 'other') {
          $('input#label_' + i + '_color_other').addClass('required');
        }

        if($('input[name=label_' + i + '_background]').filter(':checked').val() == 'other') {
          $('input#label_' + i + '_background_other').addClass('required');
        }
      } else {
        $('input#label_' + i + '_text').removeClass('required');
        $('input#label_' + i + '_color_other').removeClass('required');
        $('input#label_' + i + '_background_other').removeClass('required');
      }
    }
  }


  // Validate & Submit form using AJAX

  $('#bas-form .submit').click(function() {
    $('input, select').removeClass('validation_error');

    var errors = false;
    $('input.required, select.required').each(function() {
      if ($(this).val() == '' || $(this).val() == $(this).attr('default')) {
        errors = true;
        $(this).addClass('validation_error');
      }
    });

    if (errors) {
      alert('Please fill in all required fields highlighted in red.\n There may be some fields you missed in previous steps.');
    } else {

      $('input').not('.required').each(function() {
        if($(this).val() == $(this).attr('default')) {
          $(this).val('');
        }
      });

      $.post("/build-a-sign/save", $("#bas-form").serialize(), function(data) {
        if(data == 'success') {
      	  $('#slider-wrap').animate({scrollLeft : "2184px"}, 800, 'easeInOutCubic');
      	  $('#bas-content-wrap #content-heading h1').html('Quote Submitted');
      	  $('.prev-next').fadeOut('400');
        } else if(data == 'failed') {
          alert('Server Error');
        } else {
          alert('Timeout Error: Please Try Again');
        }
      });

    }
  });

});

function inchesToFeet(inches) {
  return Math.floor(inches/12) + "' " + (inches%12) + '"';
}

function getNum(string) {
  return parseInt(string.match(/\d+/));
}

// Recreates saved sign from quote

function showSign() {

  if(current_client) {
    $('.example-sign').addClass(current_client.add_class);
  }

  for(key in quote) {
    if(key == 'label_placement') {
      $('#bas-status .' + key).text(quote[key].substr(0, 8));
    } else {
      $('#bas-status .' + key).text(quote[key]);
    }
  }

  if(quote.configuration == 'stacked' || (quote.configuration == 'side by side' && quote.label_placement == 'top' && quote.products == '2')) {
    var tenths = '';

    if(quote.tenths == '9/10') {
      tenths = '_bar';
    }

    var digitSize = parseInt(quote.digit_size);
    var products = parseInt(quote.products);

    $('.example-sign .rule-wrap').css('border-color', quote.cabinet_color);

    $('.example-sign .vrule.main').css({left: '-68px'});

    $('.example-sign .digit-wrap .vrule').show();

    for(var i = 1; i <= parseInt(quote.products); i++) {
      $('.example-sign .digit-' + i).css('background-image', 'url("/images/digits_' + quote['color_' + i] + tenths + '.png")');

      $('.product-' + i + '-toggle').show();
      $('.example-sign .label-' + i).css('color', quote['label_' + i + '_color']);
      $('.example-sign .label-' + i).css('background-color', quote['label_' + i + '_background']);

      var text = quote['label_' + i + '_text'].toUpperCase();

      $('.example-sign .label-' + i).text(text);

      if(quote.label_placement == 'left - vertical') {
        var v_text = '';

        for(var j = 0; j < text.length; j++) {
          v_text = v_text + text.charAt(j) + '<br />';
        }

        $('.example-sign .label-' + i).html(v_text);
      }

      if(quote.labels != 'no') {
        $('.label-wrap-' + i).show();
      }
    }

    for(var i = 4; i > products; i--) {
      $('.product-' + i + '-toggle').hide();
    }

    var file = ['1', 'r', '_', '_', '_', 't', 't'];

    file[0] = quote.products;

    if(quote.products == '1') {
      file[1] = quote.color_1.charAt(0);
      file[2] = file[3] = file[4] = '_';
    }

    if(quote.products == '2') {
      file[1] = quote.color_1.charAt(0);
      file[2] = quote.color_2.charAt(0);
      file[3] = file[4] = '_';
    }

    if(quote.products == '3') {
      file[1] = quote.color_1.charAt(0);
      file[2] = quote.color_2.charAt(0);
      file[3] = quote.color_3.charAt(0);
      file[4] = '_';
    }

    if(quote.products == '4') {
      file[1] = quote.color_1.charAt(0);
      file[2] = quote.color_2.charAt(0);
      file[3] = quote.color_3.charAt(0);
      file[3] = quote.color_4.charAt(0);
    }

    if(quote.configuration == 'stacked') {
      file[5] = 't';
    } else {
      file[5] = 's';
    }

    if(quote.labels == 'no') {
      file[6] = 'n';
    } else {
      if(quote.label_placement == 'top') {
        file[6] = 't';
      } else {
        file[6] = 's';
      }
    }

    $('#sign-sample .bg').css('background-image', 'url("/images/sps/' + file.join('') + '.jpg")');

    var color = current_client.color ? current_client.color : 'red';

    $('#digit-sample img').attr('src', '/images/dps/' + digitSize + tenths + '_' + color + '.png');

    var width = dim['d' + digitSize][0];
    var height = dim['d' + digitSize][1];
    var label = dim['d' + digitSize][2];

    var hinches = inchesToFeet(products * digitSize + (products + 1) * 3);

    if(quote.labels == 'no') {
      $('.example-sign.top .vrule.main div').text(hinches);
    } else {
      $('.example-sign.top .vrule.main div').text(inchesToFeet(products * height));
    }

    $('.example-sign.top .hrule.main').text(inchesToFeet(width));

    $('.example-sign.top .digit-wrap .vrule div').text(digitSize + '"');
    $('.example-sign.top .label-wrap .vrule div').text(label + '"');


    $('.example-sign.horizontal .vrule.main div').text(hinches);
    $('.example-sign.horizontal .hrule.main').text(inchesToFeet(width * 2));

    $('.example-sign.horizontal .label-wrap .vrule div').text(digitSize + '"');


    $('.example-sign.vertical .vrule.main div').text(hinches);
    $('.example-sign.vertical .hrule.main').text(inchesToFeet(Math.ceil(width + (digitSize * 0.75))));

    $('.example-sign.vertical .label-wrap .vrule div').text(digitSize + '"');

    $('.example-sign.side .vrule.main div').text(inchesToFeet(digitSize + 6));
    $('.example-sign.side .hrule.main').text(inchesToFeet(width * 2));

    $('.example-sign.side .label-wrap .vrule div').text(label + '"');

    if(quote.configuration == 'stacked') {

      if(quote.label_placement == 'top') {
        $('.example-sign.top').fadeIn();
      }

      if(quote.label_placement == 'left - horizontal') {
        $('.example-sign.horizontal').fadeIn();
      }

      if(quote.label_placement == 'left - vertical') {
        $('.example-sign.vertical').fadeIn();
      }

    } else {
      $('.example-sign.side').fadeIn();
    }

  } else {
    $('#preview-unavailable').show();
  }

}

var client_bp = {
  defaults: {
    application: 'pole sign',
    faces: '2',
    cabinet_color: 'green',
    products: '2',
    color_1: 'green',
    color_2: 'green',
    color_3: 'green',
    color_4: 'green',
    label_placement: 'left - horizontal',
    label_1_background_green: true,
    label_2_background_green: true,
    label_3_background_green: true,
    label_4_background_green: true,
    label_1_text: 'regular',
    label_2_text: 'silver',
    label_3_text: 'ultimate',
    label_4_text: 'diesel',
    company: 'BP'
  },
  disabled: {
    tenths: ['9/10']
  },
  digit_color: 'green',
  add_class: 'bp',
  title: 'Build Your BP Sign',
  submit_title: 'Submit for a Quote',
  force_previews: true,
  color: 'green'
};

function setFormDefaults(client) {

  $.each(client.defaults, function(k, v) {
    var element = $('#'+k);

    if(element.prop('tagName') == 'SELECT') {
      element.children('option[value^="'+v+'"]').attr('selected', 'selected');
    }

    if(element.prop('tagName') == 'INPUT' && element.attr('type') == 'text') {
      element.val(v);
      element.keyup();
    }

    if(element.prop('tagName') == 'INPUT' && element.attr('type') == 'radio') {
      element.attr('checked', 'checked');
    }

    element.change();

  });

  $.each(client.disabled, function(k, v) {
    var element = $('#'+k);

    if(element.prop('tagName') == 'SELECT') {
      for(var i in v) {
        element.children('option[value="'+v[i]+'"]').attr('disabled', 'disabled');
      }
    }

    if(element.prop('tagName') == 'INPUT') {
      element.attr('disabled', 'disabled');
    }

    element.change();

  });

  $('#no-example-sign, #preview-unavailable').css('background', 'url("../images/digits_'+client.digit_color+'.png") #000000')
  $('#content-heading h1').html(current_client.title);
  $('body').addClass('bas-'+client.add_class);
  $('.example-sign').addClass(client.add_class);
  $('.example-sign.horizontal').hide();
  setTimeout(function() { $('#no-example-sign').text('').show() }, 1000);

}

function writePrice(price, kind)
{
  var resp = '';
  var priceStr = price.toString();
  for(var i=0;i<priceStr.length;i++) {
      var str = priceStr.charAt(i);
      if(str == '.')
          str = "p";
      resp = resp + "<img class='dg"+str+"' src='/images/digits/"+kind+str+".png' alt='"+str+"'/>";
  }
  if(priceStr.length == 3)
  resp = resp + "<img src='/images/"+kind+"0.png' alt='0'/>";
  resp = resp + 'gal&nbsp;';
  return resp;
}

function writeJackpot(price, kind)
{
  var resp = '';
  var priceStr = price.toString();
  for(var i=0;i<priceStr.length;i++) {
      var str = priceStr.charAt(i);
      if(str == '.')
          str = "p";
      resp = resp + "<img class='dg"+str+"' src='/images/digits/"+kind+str+".png' alt='"+str+"'/>";
  }
  resp = resp + 'mil&nbsp;';
  return resp;
}
