window.isMobile = false;

if ( navigator.userAgent.match(/Android/i) ||
 navigator.userAgent.match(/webOS/i) ||
 navigator.userAgent.match(/iPhone/i) ||
 navigator.userAgent.match(/iPod/i) ||
 navigator.userAgent.match(/iPad/i)
 ) {
 window.isMobile = true;
}

var map;
var geocoder;
var browserSupportFlag = new Boolean();
var markersArray = [];
var initialLocation = new google.maps.LatLng(40.58892816969374, -73.84323120117188);  
// Create the marker styles
var image = new google.maps.MarkerImage(
  'map_marker2.png',
  new google.maps.Size(17,35),
  new google.maps.Point(0,0),
  new google.maps.Point(9,35)
);

var shadow = new google.maps.MarkerImage(
  'map_marker_shadow.png',
  new google.maps.Size(39,35),
  new google.maps.Point(0,0),
  new google.maps.Point(9,35)
);

var shape = {
  coord: [16,0,16,1,16,2,15,3,15,4,15,5,15,6,14,7,14,8,14,9,14,10,14,11,14,12,14,13,14,14,14,15,15,16,15,17,15,18,15,19,15,20,15,21,15,22,15,23,15,24,15,25,15,26,15,27,14,28,14,29,14,30,13,31,12,32,11,33,10,34,9,34,9,33,9,32,9,31,9,30,9,29,9,28,9,27,9,26,8,25,8,24,7,23,6,22,6,21,5,20,4,19,3,18,3,17,2,16,1,15,1,14,1,13,0,12,0,11,0,10,0,9,0,8,0,7,0,6,1,5,4,4,7,3,9,2,12,1,15,0,16,0],
  type: 'poly'
};

function initializeHoverScroll(element) {
  $(element).hoverscroll({
    vertical: true,
    height:   450
  });
}
function initializeMap() {
  // Style the map
  var darkStyles = [{
    featureType: "all",
    stylers    : [
      { invert_lightness  : true },
      { saturation        : -97 },
      { gamma             : 0 },
      { lightness         : 6 }
    ]
  }];
  
  // Create a new StyledMapType object, passing it the array of styles,
  // as well as the name to be displayed on the map type control.
  var darkMapType = new google.maps.StyledMapType(darkStyles,
    {name: "elit by Stoli Vendors"});
        
  // Create a map object, and include the MapTypeId to add
  // to the map type control.
  // Center the map on the geolocation.
  var myOptions = {
    zoom: 14,
    disableDefaultUI: true,
    center: initialLocation,
    mapTypeControlOptions: {
      mapTypeIds: [google.maps.MapTypeId.ROADMAP, 'stoli_vendors']
    }
  };
  // Create the map on the id, map.
  map = new google.maps.Map(document.getElementById("map"), myOptions);
  
  // Set up the geocoder.
  geocoder = new google.maps.Geocoder();
  
  //Associate the styled map with the MapTypeId and set it to display.
  map.mapTypes.set('stoli_vendors', darkMapType);
  map.setMapTypeId('stoli_vendors');
  
  // Find the initial location and set it.
  // W3C Geolocation approach.
  if(navigator.geolocation) {
    browserSupportFlag = true;
    navigator.geolocation.getCurrentPosition(function(position) {
      initialLocation = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
      map.setCenter(initialLocation);
    }, function() {
      handleNoGeolocation(browserSupportFlag);
    });
  } else { // The browser does not support Geolocation
    browserSupportFlag = false;
    handleNoGeolocation(browserSupportFlag);
  }

  google.maps.event.addListener(map, 'dragend', searchMap);
  google.maps.event.addListener(map, 'zoom_changed', searchMap);
  
}
function clearMarkers(){
  if (markersArray) {
    for (i in markersArray) {
      markersArray[i].setMap(null);
    }
  }
  google.maps.event.clearListeners(map, 'mouseover');
  google.maps.event.clearListeners(map, 'mouseout');
}

function searchMap() {
  $('#dialog').dialog("close");
  var options = $("#find_stoli").serialize();
  var bounds = { 
                  llat: map.getBounds().getSouthWest().lat().toString(), 
                  glat: map.getBounds().getNorthEast().lat().toString(), 
                  llng: map.getBounds().getSouthWest().lng().toString(),
                  glng: map.getBounds().getNorthEast().lng().toString()
                }
  var query = options + '&' + $.param(bounds);
  $.ajax({
    url: "/vendors/search_by_viewport/",
    data: query,
    success: function(data) {
      clearMarkers();
      $("#find .left ul").html(data);
      // $('.scrollable').scrollbar({arrows: false});
      initializeHoverScroll('#locations');
    }
  });
}
function handleNoGeolocation(errorFlag) {
  return true;
  var d = $("#dialog");
  d.dialog({
    width: 300
  });
  var h = d.find(".header");
  var c = d.find(".content");
  h.removeClass('loading');
  if(errorFlag == true){
    h.find("h1").html("Warning")

    c.html(
      "<p>It appears that Google was unable to locate the address.</p>"
    );
    d.dialog('open');
  }else{
    h.find("h1").html("Warning")

    c.html(
      "<p>It appears your browser is not compatible with Google's Geolocation service.  You will not be able to get the full experience of this page.</p>"
    );
    d.dialog('open');
  }

}

function redirectTo() {
  window.location = "http://google.com";
}

function start_video_player() {
  $('#stoli_elit_video').videoPlayer({
    success: function (playTrigger, domObject) {
      playTrigger.addEventListener('timeupdate', function(e) {
        document.getElementById('current-time').innerHTML = playTrigger.currentTime;
      }, false);
      playTrigger.play();
      $('.mejs-controls').hide();
    }
  });
}

function bindRedGlow() {
  $("#elit_link").mouseenter(function(e) {
    $("#bottle .panel.glow-red").show();
    $("#bottle .panel.glow").hide();
  });
  $("#elit_link").mouseleave(function(e) {
    $("#bottle .panel.glow-red").hide();
    $("#bottle .panel.glow").show();
  });
  bindPoVOpen();
}

function unbindRedGlow() {
  $("#elit_link").unbind('mouseleave');
  $("#elit_link").unbind('mouseenter');
  $("#elit_link").unbind('click');
  $("#elit_link").css('cursor', 'default');
}

function bindPoVOpen() {
  $("#elit_link").css('cursor', '');
  $("#elit_link").click(function(e) {
	var func = funcParse(arguments.callee.toString());
	if (_gaq) _gaq.push(['_trackEvent', 'UI', 'click', 'elit_link']);
    e.preventDefault();
    elitOpen();
    unbindRedGlow();
    return false;
  });
}

function forceLoaded() {
  $("#identify, ").remove();
  $("#background .night, #bottle .panel.glow, #bottle .panel.bottle, #background .logo, .pillar.left, .pillar.right, #news_tab, #account, #footer, .horizon.panel").show();

  bindPoVOpen();
  bindRedGlow();
}

function validBirthDateInputs() {
  if($("#identify input.month_1").val() != "" && $("#identify input.month_2").val() != "" && $("#identify input.day_1").val() != "" && $("#identify input.day_2").val() != "" && $("#identify input.year_1").val() != "" && $("#identify input.year_2").val() != "" && $("#identify input.year_3").val() != "" && $("#identify input.year_4").val() != ""){
    return true;
  }else{
    return false;
  }
}

function validateBirthDate() {
  if ( validBirthDateInputs() ) {
    var year = parseInt($("#identify input.year_1").val() + $("#identify input.year_2").val() + $("#identify input.year_3").val() + $("#identify input.year_4").val());
    var month = parseInt($("#identify input.month_1").val() + $("#identify input.month_2").val());
    var today = new Date;
    var country = $("#identify select.country").val();
    
    if ( country.match(/(United States|Isreal|United Arab Emirates)/i) ) {
      var them = new Date(year + 21, month, 1);
    } else if (country.match(/(Australia|Japan|Norway|Sweden)/i)) {
      var them = new Date(year + 20, month, 1);
    } else if (country.match(/(Canada)/i)) {
      var them = new Date(year + 19, month, 1);
    } else if (country.match(/(Cyprus|Malta)/i)) {
      var them = new Date(year + 17, month, 1);
    } else if (country.match(/(Italy|Luxembourg|Morocco|Portugal)/i)) {
      var them = new Date(year + 16, month, 1);
    } else if (country.match(/(Vietnam)/i)) {
      return true;
    } else {
      var them = new Date(year + 18, month, 1);
    }
    
    if ( (today.getTime() - them.getTime() ) < 0) {
      $("#identify .birthday").addClass("error");
      $("#identify .birthday p").remove();
      $("#identify .birthday").append("<p>You are not of age to enter this site.</p>");
      setTimeout('underageRedirect()', 3000)
      return false;
    } else {
      return true;
    }
  } else {
    $("#identify .birthday p").remove();
    $("#identify .birthday").append("<p class='error'>Please enter your birthdate.</p>");
    return false;
  }
}

function underageRedirect() {
  window.location = "http://www.centurycouncil.org/"
}

function rememberMe() {
  if($("#identify input.remember").is(':checked')){
    $.cookie('remember_me', 'true', { expires: 7 });
    return true;
  }
  else{
    $.cookie('remember_me', null);
    return false;
  }
}

function acceptedTerms() {
  if($("#identify input.terms").is(':checked')){
    return true;
  }else{
    $("#identify .options .option.terms p").remove();
    $("#identify .options .option.terms").append("<p class='error'>You must agree to the terms and conditions to enter this site.</p>");
    return false;
  }
  
}


function openTerms() {
  var d = $("#dialog");
  d.dialog({
    width: 1030,
    position: 'top'
  });
  
  $.ajax({
    url: "/terms",
    success: function(data) {
      d.html(data);
      d.dialog('open');
    }
  });
}

function openPrivacy() {
  var d = $("#dialog");
  d.dialog({
    width: 650,
    position: ['center', 'top']
  });
  
  $.ajax({
    url: "/privacy",
    success: function(data) {
      d.html(data);
      d.dialog('open', {position: 'center'});
    }
  });
}

function runIntro() {
  $("#background .night").show();
  $("#identify").remove();
  $("#nav").hide();
  $("#account .nav").hide();
  $("#loading").delay(250).fadeIn(1000);
  $("#loading .panel.quote1").fadeIn(1000, function() { $(this).delay(2750).fadeOut(500); });
  $("#loading .panel.quote2").delay(4750).fadeIn(1000, function() { $(this).delay(2750).fadeOut(500, function(){$('.nav').fadeIn(3000); }); });
  
  $("#bottle .panel.bottle, .horizon.panel, #bottle .panel.glow, .pillar.left, .pillar.right").delay(8750).fadeIn(5000, function() {
    bindPoVOpen();
    bindRedGlow();
  });
  $("#background .logo").fadeIn(1000);
  $("#news_tab, #account, #footer").delay(1000).fadeIn(1000);
}

function newsTabCollapse() {
  $("#news").animate({
    right: '-300px'
  }, 'slow');
}

function newsTabExpand(){
  $("#news").animate({
    right: '0px'
  }, 'slow');
}

function newsOpen() {
	var func = funcParse(arguments.callee.toString());
	if (_gaq) _gaq.push(['_trackEvent', 'UI', 'click', func]);
  newsTabCollapse();
  rebindCloseToHome();
  closePillars();
  closePoVs();
  //elitClose();
  mapClose();
  hideNav();
  prestineClose();
  $("#find").fadeOut();
  $("#dialog").dialog('close');
  $(".horizon.panel").fadeOut();
  $("#bottle").hide();
  $("#news_reel").fadeIn();
  $("#news_tab").fadeOut();
  $("#background .night").fadeIn(1000);
  $("#background .logo").show();
  $("#background .header .news").fadeIn(1000);
  $("#loading").hide();
  hideMenu();
}

function newsClose() {
  $("#news_tab").fadeIn();
  $("#news_reel").fadeOut();
  $("#background .header .news, #background .header .events").fadeOut(1000);
}

function prestineOpen() {
	var func = funcParse(arguments.callee.toString());
	if (_gaq) _gaq.push(['_trackEvent', 'UI', 'click', func]);
  newsTabCollapse();
  newsClose();
  rebindCloseToHome();
  closePillars();
  closePoVs();
  addThumbListeners();
  elitClose();
  mapClose();
  hideNav();
  $("#find").fadeOut();
  $("#dialog").dialog('close');
  $(".horizon.panel").fadeOut();
  $("#bottle").hide();
  $("#prestine").fadeIn();
  $('.scrollable').scrollbar({arrows: true});
  $("#background .night").fadeIn(1000);
  $("#background .logo").show();
  $("#loading").hide();
  hideMenu();
}

function prestineClose() {
  $("#prestine").fadeOut();
}

function addThumbListeners(){
  $('.thumbs img').each(function(index){
    var id = index + 1;
    $('.thumb' + id).click(function(e){
      $('.thumbs img.selected').removeClass('selected');

      $(this).addClass('selected');
      $('.prestine_left').fadeOut(function(){
        $('.prestine_left img').css('display', 'none');
        $('.prestine_left img.prestine' + id).css('display', 'block');
        $('.prestine_left img').imagesLoaded(function(){
          $('.prestine_left').fadeIn();
        });
      });
    });
  });
}

function mapOpen() {
	var func = funcParse(arguments.callee.toString());
	if (_gaq) _gaq.push(['_trackEvent', 'UI', 'click', func]);
  $("#dialog").dialog('close');
  closePillars();
  //elitClose();
  
  resetPoVBottle();
  $("#bottle .viewport.panel").fadeOut(500);
  $("#pov_silhouette .silhouette.panel").fadeOut(1000);
  $("#elit").fadeOut(1000);
  closePoVs();
  $(".pov_nav div").removeClass('selected');
  newsClose();
  prestineClose();
  bindRedGlow();
  $("#elit .icon").fadeOut('slow');
  $("#bottle .glow-red").hide();
  
  hideNavigation();
  hideNav();
  hideMenu();
  closePoVs();
  newsClose();
  prestineClose();
  $(".horizon.panel").fadeOut();
  $("#bottle").fadeOut();
  $("#background .logo").show();
  $("#loading").hide();
  
  $("#find").fadeIn(function(){$('.scrollable').scrollbar({arrows: false});});
  
  $("#background .header .news").fadeOut(1000);
  
  
  
  google.maps.event.trigger(map, 'resize');
  
  var options = $("#find_stoli").serialize();
  var bounds = { 
                  llat: map.getBounds().getSouthWest().lat().toString(), 
                  glat: map.getBounds().getNorthEast().lat().toString(), 
                  llng: map.getBounds().getSouthWest().lng().toString(),
                  glng: map.getBounds().getNorthEast().lng().toString()
                }
  var query = options + '&' + $.param(bounds);
  $.ajax({
    url: "/vendors/search_by_viewport/",
    data: query,
    success: function(data) {
      $("#find .left ul").html(data);
      // $('.scrollable').scrollbar({arrows: false});
      initializeHoverScroll('#locations');
    }
  });
  
}

function mapClose() {
  //$("#bottle").fadeIn();
  $("#find").fadeOut();
  $("#dialog").dialog('close');
}

function mapDialogOpen(link) {
	var func = funcParse(arguments.callee.toString());
	if (_gaq) _gaq.push(['_trackEvent', 'UI', 'click', func]);
  var d = $("#dialog");
  var h = d.find(".header");
  var c = d.find(".content");
  var v = link.closest("li").attr("id").split("_")[1];
  var venue = link.siblings("h2").html();
  d.dialog({
    width: 300,
    position: {
      my: 'center',
      at: 'center',
      of: "#find .right"
    }
  });
  d.dialog('open');
  
  d.find("h1").addClass("map");
  $(".ui-dialog").addClass("map");
  
  
  h.addClass("header");
  h.find("h1").html(venue)
  
  c.html(
    "<form action='/invite_to_vendor' method='post'><input name='vendor' type='hidden' value='" + v +" '/><div class='input string'><label>From</label><input type='text' class='from' name='from'></div><div class='input string'><label>To</label><input type='text' class='to' name='to'></div><div class='input string'><label>Your Message</label><textarea name='message'>Staying in tonight? You Know Better. Let's meet at " + venue + " for a drink later.</textarea></div><div class='button'><input type='submit' value=''></div></form>"
  );
  
  $("textarea").wysiwyg({
    controls: {},
    formWidth: 250,
    autoSave: true
  });
  
  var f = c.find("form");
  
  f.submit(function(e) {
    $(this).find("input[type='submit']").attr('disabled');
    $.ajax({
      type: 'post',
      url: f.attr('action'),
      data: f.serialize(),
      cache: false,
      success: function() {
        h.html("<h1>Success!</h1>")
        c.html("<p>Thank you! Your message has been sent. You Know Better than to let your friends go thirsty.</p>");
        window.setTimeout(function(){
          $("#dialog").dialog('close');
          $(".ui-dialog").removeClass("map");
        }, 5000);
        $(this).find("input[type='submit']").removeAttr('disabled');
      },
      error: function(jqXHR, textStatus, errorThrown){
        dialogError();
        $(this).find("input[type='submit']").removeAttr('disabled');
      }
    });
    e.preventDefault();
    h.html("<h1>Loading...</h1>")
    c.html("<p>Attempting to Send Message...</p>");
  }); 
}

function loadMapInvite() {
  var d = $("#dialog");
  d.html(data);
}

function dialogError() {
  var d = $("#dialog");
  var h = d.find(".header");
  var c = d.find(".content");
  h.html("<h1>Error!</h1>");
  c.html("<p>There was an error processing your request! An administrator has been notified</p>");
}

function eventsOpen() {
  $("#events").fadeIn();
}

function eventsClose() {
  $("#events").fadeOut();
}

function showNav(activeLeft, activeRight) {
  $("#nav").show();
  var left = $("#nav .left")
  var right = $("#nav .right")
  
  left.removeClass("active");
  right.removeClass("active");
  
  if(activeLeft == true)
    left.addClass("active");

  if(activeRight == true)
    right.addClass("active");

  $("#nav .left, #nav .right").fadeIn();
}

function hideNav() {
  $("#nav .left").fadeOut();
  $("#nav .right").fadeOut();
}

function masteryOpen() {
	var func = funcParse(arguments.callee.toString());
	if (_gaq) _gaq.push(['_trackEvent', 'UI', 'click', func]);
  $("#bottle").fadeIn();
  hideMenu();
  wisdomClose();
  powerClose();
  progressClose();
  unbindRedGlow();
  $(".pillars li").removeClass("selected");
  $(".pillars li.mastery").addClass("selected");
  
  showNav(true, true);

  $("#nav .left, #nav .right").unbind('click');

  
  $("#mastery").fadeIn('slow', function(){
    $("#nav .left").click(function() {
      masteryClose();
      $("#mastery").fadeOut('slow', function(){
        progressOpen();
      });
    });
    $("#nav .right").click(function() {
      masteryClose();
      $("#bottle").fadeOut('slow', function(){
        wisdomOpen();
      });
    });
  });
  $(".horizon.panel").hide();
}

function masteryClose() {
  $(".pillars li").removeClass("selected");
  $("#mastery").fadeOut();
  $("#background .night").fadeIn();
}

function wisdomOpen() {
	var func = funcParse(arguments.callee.toString());
	if (_gaq) _gaq.push(['_trackEvent', 'UI', 'click', func]);
  hideMenu();
  masteryClose();
  powerClose();
  progressClose();
  $("a.rocks").click();
  $(".pillars li").removeClass("selected");
  $(".pillars li.wisdom").addClass("selected");
  
  showNav(true, true);
  
  $("#nav .left, #nav .right").unbind('click');

  $("#bottle").fadeOut();
  $("#wisdom").fadeIn();
  
  $("#drinks .rocks").fadeIn('slow', function(){
    $("#nav .left").click(function() {
      wisdomClose();
      $("#wisdom").fadeOut('slow', function(){
        masteryOpen();
      });
    });
    $("#nav .right").click(function() {
      wisdomClose();
      $("#wisdom").fadeOut('slow', function(){
        elitOpen();
      });
    });
  });

  $(".horizon.panel").hide();
}

function wisdomClose() {
  $(".pillars li").removeClass("selected");
  $("#wisdom").fadeOut();
  $("#drinks .panel").fadeOut();
}

function powerOpen() {
	var func = funcParse(arguments.callee.toString());
	if (_gaq) _gaq.push(['_trackEvent', 'UI', 'click', func]);

  $("#bottle").fadeIn();
  hideMenu();
  masteryClose();
  wisdomClose();
  progressClose();
  unbindRedGlow();
  $(".pillars li").removeClass("selected");
  $(".pillars li.power").addClass("selected");
  
  showNav(true, true);
  
  $("#nav .left, #nav .right").unbind('click');
  
  $("#power").fadeIn('slow', function(){
    $("#nav .left").click(function() {
      powerClose();
      $("#power").fadeOut('slow', function(){
        elitOpen();
      });
    });
    $("#nav .right").click(function() {
      powerClose();
      $("#power").fadeOut('slow', function(){
        progressOpen();
      });
    });
  });
  $(".horizon.panel").fadeIn();
}

function powerClose() {
  $(".pillars li").removeClass("selected");
  $("#power").fadeOut();
}

function progressOpen() {
	var func = funcParse(arguments.callee.toString());
	if (_gaq) _gaq.push(['_trackEvent', 'UI', 'click', func]);
  $("#bottle").fadeIn();
  hideMenu();
  masteryClose();
  wisdomClose();
  powerClose();
  unbindRedGlow();
  $(".pillars li").removeClass("selected");
  $(".pillars li.progress").addClass("selected");
  
  showNav(true, true);
  
  $("#nav .left, #nav .right").unbind('click');
  
  $("#progress").fadeIn('slow', function(){
    $("#nav .left").click(function() {
      progressClose();
      $("#progress").fadeOut('slow', function(){
        powerOpen();
      });
    });
    $("#nav .right").click(function() {
      progressClose();
      $("#progress").fadeOut('slow', function(){
        masteryOpen();
      });
    });
  });
  $(".horizon.panel").fadeIn();
}

function progressClose() {
  $(".pillars li").removeClass("selected");
  $("#progress").fadeOut();
}

function hideNavigation() {
  $("#mastery").fadeOut();
  $("#wisdom").fadeOut();
  $("#power").fadeOut();
  $("#progress").fadeOut();
}

function elitOpen() {
  	var func = funcParse(arguments.callee.toString());
	if (_gaq) _gaq.push(['_trackEvent', 'UI', 'click', func]);
  
  $("#bottle").fadeIn();
  
  
  resetPoVBottle();
  closePoVs();
  
  
  
  
  closePillars();
  unbindRedGlow();
  
  
  $("#bottle .viewport.panel").fadeOut(500);
  $("#pov_silhouette .silhouette.panel").fadeOut(1000);
  $("#bottle .glow.panel").hide();
  $("#bottle .glow-red.panel").hide();
  
  
  
  rebindCloseToHome();

  hideMenu();
  showNav(true, true);
  
  
  
  $("#nav .left, #nav .right").unbind('click');
  
  $("#elit").fadeIn('slow', function(){
    $("#nav .left").click(function() {
      //elitClose();
      
      resetPoVBottle();
      $("#bottle .viewport.panel").fadeOut(500);
      $("#pov_silhouette .silhouette.panel").fadeOut(1000);
      $("#elit").fadeOut(1000);
      closePoVs();
      $(".pov_nav div").removeClass('selected');
      newsClose();
      prestineClose();
      bindRedGlow();
      $("#elit .icon").fadeOut('slow');
      $("#bottle .glow-red").hide();
      
      
      
      closePoVs();
      rebindCloseToHome();
      $("#bottle").fadeOut('slow', function(){
        wisdomOpen();
      });
    });
    
    
    $("#nav .right").click(function() {
      elitClose();
      closePoVs();
      rebindCloseToHome();
      $("#bottle").fadeOut('slow', function(){
        powerOpen();
      });
    });
  });
  $("#elit .icon").fadeIn('slow');

}

function elitClose() {
  resetPoVBottle();
  $("#bottle .viewport.panel").fadeOut(500);
  $("#pov_silhouette .silhouette.panel").fadeOut(1000);
  $("#elit").fadeOut(1000);
  closePoVs();
  $(".pov_nav div").removeClass('selected');
  newsClose();
  prestineClose();
  bindRedGlow();
  $("#elit .icon").fadeOut('slow');
  $("#bottle .glow-red").hide();
  $("#bottle .glow, #bottle").fadeIn();
}

function elitClose2() {
  $("#bottle .bottle.panel img").animate({'height' : '560px', 'bottom' : '0px'}, 'slow', function(){
    
  });
  showMenu();
  $(".horizon.panel").fadeIn();
  $("#bottle .viewport.panel").fadeOut(500);
  $("#pov_silhouette .silhouette.panel").fadeOut(1000);
  $("#elit").fadeOut(1000);
  closePoVs();
  newsClose();
  prestineClose();
  $(".pov_nav div").removeClass('selected');
  bindRedGlow();
  $("#elit .icon").fadeOut('slow');
  $("#bottle .glow-red").hide();
  $("#bottle .glow, #bottle").fadeIn();
}

function resetPoVBottle() {
  $("#bottle .bottle.panel img").animate({'height' : '560px', 'bottom' : '0px'}, 'slow');
}

function bindBackToPoV() {
  // $("#close, #close2").unbind('click');
  // $("#close, #close2").click(function(e) {
  //   e.preventDefault();
  //   elitOpen();
  // });
}

function rebindCloseToHome() {
  //$("#close, #close2").unbind('click');
  //$("#close, #close2").click(function(e) {
  //  e.preventDefault();
  //  $("#background .header .news, #background .header .events").fadeOut(1000);
  //  elitClose();
  //  showMenu();
  //  hideNav();
  //  mapClose();
  //  return false;
  //});
}

function openPoVBottle(position) {
	var func = funcParse(arguments.callee.toString());
	if (_gaq) _gaq.push(['_trackEvent', 'UI', 'click', func]);
  $(".horizon.panel").fadeOut();
  $("#bottle .viewport.panel").fadeIn(500);
  showNav(true, true);
  $("#elit .icon").fadeOut(300);
  $("#pov_silhouette .silhouette.panel").hide();
  bindBackToPoV();
  
  var moveDistance = position + "px"
  $("#bottle .bottle.panel").show();
  $("#bottle .bottle.panel img").animate({'height' : '1655px', 'bottom' : moveDistance}, 'slow');
  
  $("#elit .logo").unbind('click');
  $("#elit .logo").addClass('back');
  $("#elit .logo").click(function(){
    $("#elit .logo").removeClass('back');
    elitOpen();
  });
}

function openPoVSilhouette(transition) {
	var func = funcParse(arguments.callee.toString());
	if (_gaq) _gaq.push(['_trackEvent', 'UI', 'click', func]);
  bindBackToPoV();
  $(".horizon.panel").fadeIn();
  $("#bottle .viewport.panel").fadeOut(500);
  showNav(true, true);
  $('#pov_silhouette img').animate({'height' : '560px'}, 0);
  $("#elit .icon").fadeOut(300);
  if(transition){
    $("#bottle .bottle.panel img").animate({'height' : '560px', 'bottom' : '0px'}, 'slow').delay(0).show(function(){
      $("#pov_silhouette .silhouette.panel").fadeIn(1000);
    });
  } else {
    $("#pov_silhouette .silhouette.panel").fadeIn(1000);
  }
  
  $("#elit .logo").unbind('click');
  $("#elit .logo").addClass('back');
  $("#elit .logo").click(function(){
    $("#elit .logo").removeClass('back');
    elitOpen();
  });
}

function closePoVs() {
  $("#pov_silhouette .silhouette.panel").fadeOut(1000);
  $("#bottle .viewport.panel").fadeOut();
  $(".pov_nav div").removeClass('selected');
  closeCrown();
  closeElement();
  closeCommitment();
  closeMark();
  closeModern();
  resetPoVBottle();
}

function openCrown() {
	var func = funcParse(arguments.callee.toString());
	if (_gaq) _gaq.push(['_trackEvent', 'UI', 'click', func]);
  $(".pov_nav div").removeClass('selected');
  $("#crown_nav").addClass('selected');
  $("#crown .panel.copy").fadeIn(1000, function() {
    $(".pov_nav .next, .pov_nav .prev").unbind('click');
    $(".pov_nav .next").click(function() {
      closeCrown();
      openElement();
    });
    $(".pov_nav .prev").click(function() {
      closeCrown();
      openModern(true);
    });
  });
      
  openPoVBottle(-120);
  
  closeElement();
  closeCommitment();
  closeMark();
  closeModern();
}

function openElement() {
	var func = funcParse(arguments.callee.toString());
	if (_gaq) _gaq.push(['_trackEvent', 'UI', 'click', func]);
  $(".pov_nav div").removeClass('selected');
  $("#element_nav").addClass('selected');
  $("#element .panel.copy").fadeIn(1000);
  
  openPoVBottle(100);
  
  $(".pov_nav .next, .pov_nav .prev").unbind('click');
  $(".pov_nav .next").click(function() {
    closeElement();
    openCommitment();
  });
  $(".pov_nav .prev").click(function() {
    closeElement();
    openCrown();
  });
  
  closeCrown();
  closeCommitment();
  closeMark();
  closeModern();
}

function openCommitment() {
	var func = funcParse(arguments.callee.toString());
	if (_gaq) _gaq.push(['_trackEvent', 'UI', 'click', func]);
  $(".pov_nav div").removeClass('selected');
  $("#commitment_nav").addClass('selected');
  $("#commitment .panel.copy").fadeIn(1000, function() {
    $(".pov_nav .next, .pov_nav .prev").unbind('click');
    $(".pov_nav .next").click(function() {
      closeCommitment();
      openMark();
    });
    $(".pov_nav .prev").click(function() {
      closeCommitment();
      openElement();
    });
  });
  
  openPoVBottle(320);
  
  closeCrown();
  closeElement();
  closeMark();
  closeModern();
}

function openMark() {
  $(".pov_nav div").removeClass('selected');
  $("#mark_nav").addClass('selected');
  $("#mark .panel.copy").fadeIn(1000, function() {
    $(".pov_nav .next, .pov_nav .prev").unbind('click');
    $(".pov_nav .next").click(function() {
      closeMark();
      openModern(true);
    });
    $(".pov_nav .prev").click(function() {
      closeMark();
      openCommitment();
    });
  });
  
  openPoVBottle(480);
  
  closeCrown();
  closeElement();
  closeCommitment();
  closeModern();
}

function openModern(transition) {
  $(".pov_nav div").removeClass('selected');
  $("#modern_nav").addClass('selected');
  $("#modern .panel.copy").fadeIn(1000, function() {
    $(".pov_nav .next, .pov_nav .prev").unbind('click');
    $(".pov_nav .next").click(function() {
      closeModern();
      openCrown();
    });
    $(".pov_nav .prev").click(function() {
      closeModern();
      openMark();
    });
  });
  
  openPoVSilhouette(transition);

  closeCrown();
  closeElement();
  closeCommitment();
  closeMark();
}

function closeCrown() {
  $("#crown .panel.copy").hide();
}

function closeElement() {
  $("#element .panel.copy").hide();
}

function closeCommitment() {
  $("#commitment .panel.copy").hide();
}

function closeMark() {
  $("#mark .panel.copy").hide();
}

function closeModern() {
  $("#modern .panel.copy").hide();
}

function selectNewsItem(t) {
  $("ul#news_items li").removeClass("selected");

  t.addClass("selected");
}

function hideMenu() {
  $(".pillars li p").fadeOut();
  $(".close.panel").fadeIn();
  $("#login, #login_reset, #signup").hide();
  $(".pillar.left, .pillar.right").fadeOut();
}

function closePillars(){
  wisdomClose();
  masteryClose();
  powerClose();
  progressClose();
}

function showMenu() {
  wisdomClose();
  masteryClose();
  powerClose();
  progressClose();
  eventsClose();
  $("#find").hide();
  $(".pillar.left, .pillar.right").fadeIn();
  $(".close.panel").hide();
  $("#news_tab").fadeIn();
  $("#news_reel").hide();
  $("#elite").hide();
  $("#login, #login_reset, #signup").hide();
}

function openLogin() {
  $("#login_reset").hide();
  $("#signup").hide();
  $("#login").show();
}

function openSignup() {
  $("#login").hide();
  $("#login_reset").hide();
  $("#signup").show();
}

function openReset() {
  $("#login").hide();
  $("#login_reset").show();
}


$(document).ready(function() {
  initializeMap();
  initializeHoverScroll('#news_items');
  initializeHoverScroll('#locations');
  
  
  $("#find_stoli input[type='checkbox']").change(searchMap)

  // todo remove the age=false search param force loading of page.
  if (/age=false/.test(window.location.search.substring(1)) || $.cookie('remember_me') == 'true') {
    forceLoaded();
  }
  
  $("#icon1, #crown_nav").click(function() {
    openCrown();
  });
  
  $("#icon2, #element_nav").click(function() {
    openElement();
  });
  
  $("#icon3, #commitment_nav").click(function() {
    openCommitment();
  });
  
  $("#icon4, #mark_nav").click(function() {
    openMark();
  });
  
  $("#icon5, #modern_nav").click(function() {
    openModern(true);
  });

  $("#news_reel tr.item:not(.open)").live('click', function(e) {
    e.preventDefault();
    var t = $(this);
    t.next("tr.data").show();
    t.addClass("open")
  });
  
  $("#news_reel tr.item.open").live('click', function(e) {
    e.preventDefault();
    var t = $(this);
    t.siblings("tr.data:first").hide();
    t.removeClass("open")
  });
  
  $("#map_link").click(function(e) {
    e.preventDefault();
    mapOpen();
    return false;
  });

  $("#dialog").dialog({
    height: 320,
    autoOpen: false
  });

  $(".panel.map .details a.invite").live('click', function(e) {
    e.preventDefault();
    var t = $(this);
    mapDialogOpen(t);
  });

  $("#login_link").click(function(e) {
    e.preventDefault();
    window.location.href = "/events";
    //openLogin();
  });

  $("#signup_link").click(function(e) {
    e.preventDefault();
    openSignup();
  });

  // Deprecated
  $("#reset_login_link").click(function(e) {
    e.preventDefault();
    $("#login_reset").hide();
    $("#login").show();
  });

  $("#reset_link").click(function(e) {
    e.preventDefault();
    openReset();
  });
  
  // Deprecated
  $("#signup_login_link").click(function(e) {
    e.preventDefault();
    $("#signup").hide();
    $("#login").show();
  })
  
  $("#mastery_link").click(function(e) {
    e.preventDefault();
    masteryOpen();
    return false;
  });

  $("#wisdom_link").click(function(e) {
    e.preventDefault();
    wisdomOpen();
    return false;
  });
  
  $("#power_link").click(function(e) {
    e.preventDefault();
    powerOpen();
    return false;
  });
  
  $("#progress_link").click(function(e) {
    e.preventDefault();
    progressOpen();
    return false;
  });

  $("#progress form").submit(function(e) {
    e.preventDefault();
    var t = $(this);
    var d = $("#dialog");
    var b = t.find("input[type='submit']");
    d.dialog({
      width: 300,
      position: {
        my: 'top center',
        at: 'top center',
        of: t
      }
    });
    var h = d.find(".header");
    var c = d.find(".content");
    h.addClass('loading');
    t.submit(function(e) {
      e.preventDefault();
      d.dialog('open');
      h.html("<h1>Loading...</h1>")
      c.html("<p>Attempting to Send Message...</p>");
      b.attr('disabled', true);
      $.ajax({
        type: 'post',
        url: t.attr('action'),
        data: t.serialize(),
        success: function() {
          h.html("<h1>Success!</h1>")
          c.html("<p>Thank you! Your message has been sent. You Know Better than to let your friends go thirsty.</p><a class='another' href='#'>Click Here To Invite Another</a>");
          c.find("a").click(function(){
            t.find("input").each(function(i, e) {
              $(e).val("");
              $(e).css('background-image', $(this).data('bg'));
            });
            d.dialog('close');
          });
          // window.setTimeout(function(){
          //   d.dialog('close');
          // }, 5000);
          h.removeClass('loading');
          b.removeAttr('disabled');
        },
        error: function(jqXHR, textStatus, errorThrown){
          dialogError();
          h.removeClass('loading');
          b.removeAttr('disabled');
        }
      });
    });
  });

  $("a.events_link").click(function(e) {
    e.preventDefault();
    eventsOpen();
    hideMenu();
    return false;
  });

  $("a.news_link").click(function(e) {
    e.preventDefault();
    var t = $(this);
    var news = $("li." + t.attr('news'));
    newsOpen();
    $("#elit").fadeOut(1000);
    news.click();
    $(".selectBox-options, .selectBox-options li").css('background-color', 'gray');
    return false;
  });
  
  $("a#product_link").click(function(e) {
    e.preventDefault();
    var t = $(this);
    var product = $("li." + t.attr('product'));
    prestineOpen();
    product.click();
    $(".selectBox-options, .selectBox-options li").css('background-color', 'gray');
    return false;
  });

  $("a.rocks").click(function(e) {
    e.preventDefault();
    if ($("#drinks .rocks").is(":hidden")) {
      $("#wisdom a").removeClass("selected");
      $("#wisdom a.rocks").addClass("selected");
      $("#drinks .martini").fadeOut();
      $("#wisdom p.martini").hide();
      $("#wisdom p.rocks").show();
      $("#drinks .rocks").fadeIn();
      $(this).closest(".copy.aux").removeClass("martini")
    }
    return false; 
  });

  $("a.martini").click(function(e) {
    e.preventDefault();
    if ($("#drinks .martini").is(":hidden")) {
      $("#wisdom a").removeClass("selected");
      $("#wisdom a.martini").addClass("selected");
      $("#drinks .rocks").fadeOut();
      $("#wisdom p.rocks").hide();
      $("#wisdom p.martini").show();
      $("#drinks .martini").fadeIn();
      $(this).closest(".copy.aux").addClass("martini")
    }
    return false; 
  });

  $("#close, #close2").click(function(e) {
    e.preventDefault();
    $("#background .header .news, #background .header .events").fadeOut(1000);
    elitClose2();
    //showMenu();
    hideNav();
    mapClose();
    return false;
  });

  $("#close, #close2").mouseenter(function(e) {
    $("#close2").css("color", 'red');
  });
  
  $("#close, #close2").mouseleave(function(e) {
    $("#close2").css("color", '#808080');
  });

  $(".pillar ul li").mouseover(function() {
    var t = $(this);
    t.children("p").fadeIn();
    t.addClass("hover");
  });
  
  $(".pillar ul li").mouseleave(function() {
    var t = $(this);
    t.children("p").fadeOut();
    t.removeClass("hover");
  });

  if ($("ul#news_items li.selected").length < 1) {
    $("ul#news_items li").first().addClass("selected");
  }
  
  $("ul#news_items li").live('click', function(e) {
    e.preventDefault();
    var t = $(this);
    var url = t.find("a").attr('href');
    selectNewsItem(t);
    $.ajax({
      url: url,
      success: function(data) {
        //$(".news_right").html(Some Spinner!);
        $(".news_right").html(data);
        $('.scrollable').scrollbar({arrows: false});
      }
    });
  });

  $("ul#news_items li.selected").live('click', function(e) {
    e.preventDefault();
  });
  
  $("#news").animate({
    right: '-300px'
  }, 0);
  
  $("#news_tab").click(function() {
    newsTabExpand();
  });
  
  $("#news").mouseleave(function() {
    newsTabCollapse();
  });
  
  $(".country select").selectBox({menuTransition: 'fade', menuSpeed: 'normal', loopOptions: true});
  $(".filter select").selectBox({menuTransition: 'fade', menuSpeed: 'normal', loopOptions: true});
  
  $("#identify input[type=button]").click(function() {
    validateBirthDate();
    acceptedTerms();
    if(validateBirthDate() && acceptedTerms()) {
      rememberMe();
      runIntro();
    }
  });
  
  $("#news").slides({
    next: 'next',
    prev: 'prev',
    generatePagination: false
  });
  
  $("a.current_location").click(function() {
    if(browserSupportFlag) {
      navigator.geolocation.getCurrentPosition(function(position) {
        currentLocation = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
        
        geocoder.geocode({'latLng': currentLocation}, function(results, status) {
          if (status == google.maps.GeocoderStatus.OK) {
            if (results[1]) {
              $("#find_stoli input.address").val(results[1].formatted_address);
              $("#find_stoli input.address").css('background-image', 'none');
            }
          } else {
            alert("Geocoder failed due to: " + status);
          }
        });
      }, function() {
        handleNoGeolocation(browserSupportFlag);
      });
    } else { // The browser does not support Geolocation
      handleNoGeolocation(browserSupportFlag);
    }
  });
  
  
  $("form#find_stoli").submit(function(e) {
    e.preventDefault();
    var t = $(this);
    var query = t.serialize();
    var address = t.find(".address").val();
    
    var d = $("#dialog");
    d.dialog({
      width: 300,
      position: {
        my: 'center',
        at: 'center',
        of: "#find .right"
      }
    });
    var h = d.find(".header");
    var c = d.find(".content");
    h.addClass('loading');
    // Center to the query location
    $.ajax({
      url: "/address/geocode",
      data: {address: address},
      success: function(data) {
        var new_center = new google.maps.LatLng(data.lat, data.lng);
        map.setCenter(new_center);
        
        // Get results
        var options = $("#find_stoli").serialize();
        var bounds = { 
                        llat: map.getBounds().getSouthWest().lat().toString(), 
                        glat: map.getBounds().getNorthEast().lat().toString(), 
                        llng: map.getBounds().getSouthWest().lng().toString(),
                        glng: map.getBounds().getNorthEast().lng().toString()
                      }
        var query = options + '&' + $.param(bounds);
        $.ajax({
          url: "/vendors/search_by_viewport/",
          data: query,
          success: function(data) {
            $("#find .left ul").html(data);
            initializeHoverScroll('#locations');
            // $('.scrollable').scrollbar({arrows: false});
            if(data.length < 1){
              h.removeClass('loading');
              h.html("<h1>No Results</h1>");
              c.html("<p><a href='http://www.1-877-spirits.com/spirits/stolichnaya-elit-vodka'>Click here</a> to place an order online.</p>");
              d.dialog('open');
            }
          }
        });
        
        
      }
    });
  });
  
  $("#identify .terms a").click(function(e) {
    e.preventDefault();
    openTerms();
  });
  
  $("a.privacy").click(function(e) {
    e.preventDefault();
    openPrivacy();
  });
  
  // form js
  $('input:not([type=submit])').live('focus', function() {
    var t = $(this);
    if(t.attr('type') != 'button' ) {
      $(this).data('bg', $(this).css('background-image'));
      $(this).css('background-image', 'none');
    }
  });

  $('input').live('blur', function() {
    if($(this).val() == "") {
      $(this).css('background-image', $(this).data('bg'));
    }
  });

  $('input:not([type=submit])').each(function() {
    var t = $(this);
    if(t.val() != "" && t.attr('type') != 'button' ) {
      $(this).css('background-image', 'none');
    }
  });

  $("textarea.wysiwyg").wysiwyg({
    controls: {},
    formWidth: 300,
    autoSave: true
  });
  
  
  
  var currentNewsPage = 1;
  
  $(".filter select.filter").change(function() {
    var t = $(this)
    currentNewsPage = 1;
    $.get(t.val(), function(data) {
      $('#news_items').html(data);
    })
  });
  
  
  
  
  var newsEmpty = false;

  function loadMessages(w) {
    currentNewsPage++;

    var a = w.find(".pager li.next.jump a");
    var u = $(".filter select.filter").val();

    u += "?page=" + currentNewsPage;  
    $.get(u, function(data) {
      w.append(data);
    })



    a.html("See More");
  }

  $('#news_reel.window .fixed-listcontainer').scroll(function() {
    if ($(this)[0].scrollHeight - $(this).scrollTop() == $(this).outerHeight()) {
      var w = $("ul#news_items");
      if (!newsEmpty) {
        loadMessages(w);
      }
    }
  })
  
  
  
  $("select.web_updates.filter").live('change', function() {
    
    var url = "/web_updates/" + $(this).val();
    $.ajax({
      url: url,
      success: function(data) {
        $('#prestine.window').html(data);
        $(".filter select").selectBox({menuTransition: 'fade', menuSpeed: 'normal', loopOptions: true});
        addThumbListeners();
        $('#prestine .scrollable').scrollbar({arrows: false});
      }
    });
  })
  

  
  
  $('.age_gate .birthday input').autoFill();
  
});


















(function( $ ){

  $.fn.autoFill = function() {
    var inputs = this;
    
    return this.each(function(index, input) {
      
      var next_input = function(e){
        if ( isNumberKey(e) ) {
          return true;
        } else if ( e.which == 8 || e.which == 9 || e.which == 16 || e.which == 46 || e.which == 13 || (e.which > 36 && e.which < 41)){
          return false;
        } else {
          e.preventDefault();
          return false;
        }
      }
      
      var isNumberKey = function(evt){
        var charCode = (evt.which) ? evt.which : event.keyCode
        if ((charCode > 47 && charCode < 58) || (charCode > 95 && charCode < 106))
          return true;

        return false;
      }
      
      
      
      $(input).keydown(function(e){


			next_input(e);	        


      });

      $(input).keyup(function(e){
        var t = $(this);
        
        var next = t.next("input");

		if(!window.isMobile) {
	        if(next_input(e)){
	          if(next.length > 0 && t.val() != '') {
	            next.focus();
	            next.trigger('click');
	          } else {
	            var nextInput = t.parent().next().children("input, select").first();
	            if(nextInput.length > 0 && t.val() != ''){
	              nextInput.focus();
	              next.trigger('click');
	            } else {
	              t.focusout();
	            }
	          }
	        }else{
	          e.preventDefault();
	        }
		}

      });
      
    })
  };
})( jQuery );


// jQuery.fn.extend({
//     "singleDigits": function() {
//         var inputs = this.keyup(function() {
//             var input = jQuery(this);
//             if (input.val().length > 0) {
//                 inputs.eq(inputs.index(this) + 1).focus();
//             }
//         });
//         return this;
//     }
// });








$('.age_gate .button input[type="button"]').click(function(){
if (_gaq) _gaq.push(['_trackEvent', 'UI', 'click', 'Enter Button']);  
})

 

function log(arg) {
	console.log(arg);
}


log('goo');


function funcParse(str) {
	// chop out function name for output to GA ajax
	var end = str.substr('function '.length);
	end = end.substr(0, end.indexOf('('));  
	return end;
}
















