var tick = 0;
var scrollStop;
var isAnimating = false;

function cycleTopImages() {
	  $('#cycle-images .cycle-image:last').fadeOut(3000, function(){
	    $(this).clone().prependTo('#cycle-images').show();
	    $(this).remove();
	  });
}

$(document).ready(function(){
	// Pre-load images
	var preloadedImages = ["/wp-content/themes/twentyten/images/print_hover.png", "/wp-content/themes/twentyten/images/button_search_careers_base.png", 
	                       "/wp-content/themes/twentyten/images/modal_next_hover.png", "/wp-content/themes/twentyten/images/modal_prev_hover.png", 
	                       "/wp-content/themes/twentyten/images/button_find_hover.png", "/wp-content/themes/twentyten/images/homepage_scheduletour_hover.png",
	                       "/wp-content/themes/twentyten/images/button_testimonials_interior_hover.png"];
	
	var imgCount = preloadedImages.length;
	for(i=0; i<imgCount; i++) { 
		  var image_preload = new Image();
		  image_preload.src = preloadedImages[i];
	}
	
	setInterval ( "cycleTopImages()", 5000 ); //be sure to have the interval here greater than the fadeout time


  // Navigation
  $('#primary li a, #logo, .schedule_tour, .scroll-to-section').click(function() { 
    var elementClicked = $(this).attr("href");
    
    var destination = $(elementClicked).offset().top;
    isAnimating = true;
    $("html,body").stop().animate({ 
     scrollTop: destination-111
    },500, 'easeInOutCubic', function(){
    	isAnimating = false;
    	makeCurrentSection(elementClicked);
    });
    return false;
  });
  
  if($("#responseStatus").val()){
	$("#payment-nav").click();  
  }
  
  $('.findbutton .zipcode').click(function(event){
	  event.stopPropagation();
  });

  $('.findbutton .zipcode').bind('keypress', function(e) {
      if(e.keyCode==13){
    	  zipcode = $(this).val();
		  if(validateZipCodeSearch(zipcode)){
			  $(this).removeClass("error");
			  zipCodeSearch(zipcode);
		  }
		  else{
			  $(this).addClass("error");
		  }
	      return false;
      }
  });
  
  
  $('.findbutton').click(function(){
	  var zipcode = $(this).children('.zipcode:first').val();
	  if(validateZipCodeSearch(zipcode)){
		  $(this).children('.zipcode:first').removeClass("error");
		  zipCodeSearch(zipcode);
	  }else{
		  $(this).children('.zipcode:first').addClass("error");
	  }
  });
  
  function validateZipCodeSearch(zipcode){
	  return zipcode.match(/^\d{5}([\-]\d{4})?$/);
  }
  
  function zipCodeSearch(zip_code){
	  $("#locations-nav").click();
	  $("#addressInput").val(zip_code);
	  $("#searchForm").submit();
  }

  
  function makeCurrentSection(section_id){
	  $(".cur").removeClass("cur");
	  $(".cur-nav").removeClass("cur-nav");
	  
	  $(section_id+"-nav").parent().addClass("cur-nav");
	  $(section_id).addClass("cur");
  }
  
  scrollStop = setTimeout(updateScrollInfo, 500);
  
  $(window).scroll(function(){
	  if(isAnimating)
		  return;
      tick++;
      clearTimeout(scrollStop);
      scrollStop = setTimeout(updateScrollInfo, 500);
      if (tick > 10)
      {
        updateScrollInfo();
      }
    });
  
  function updateScrollInfo()
  {
    tick = 0;
    isVisible("#home") ? makeCurrentSection("#home") : null ;
    isVisible("#about-us") ? makeCurrentSection("#about-us") : null ;
    isVisible("#services") ? makeCurrentSection("#services") : null ;
    isVisible("#locations") ? makeCurrentSection("#locations") : null ;
    isVisible("#contact") ? makeCurrentSection("#contact") : null ;
    isVisible("#careers") ? makeCurrentSection("#careers") : null ;
    isVisible("#payment") ? makeCurrentSection("#payment") : null ;
  }
  
  function isVisible(section_id){
     var docViewTop = $(window).scrollTop() - 111;
     var docViewBottom = docViewTop + $(window).height()-60;
     var elemTop = $(section_id).offset().top;
	 var elemBottom = elemTop + $(section_id).height();
	 //Is more than half of the element visible
	 return ((elemBottom >= docViewTop) && (elemTop <= docViewBottom));
  }
  
  $(".locations .location").click(function(){
	  var name = $(this).children('.name').text().replace(/ /g, '').toLowerCase();
	  if(name){ 
		  GEvent.trigger(all_markers[name],"click")		  
	  }
	  
  });
  
  $(".locations .location .details").click(function(){
	  var href = $(this).attr("href");
	  $("#locations #loading").show();
	  $("#single-location-content").load(href+" #content", function(){
		  $("#single-location-content .entry-content").prepend("<a href='#' class='back-to-all-locations'>Back to all locations</a>");
		  $("#locations-side .button_repositioned, #locations-side .locations, #all-locations-content").fadeOut(1000);
		  $("#single-location-side, #single-location-content").fadeIn(2000);
		  $("#locations #loading").hide();
		  var loc = href.replace("/locations/", "");
		  $("#side-calendars .cur-cal").removeClass("cur-cal");
		  $("#side-calendars #"+loc+"-cal-events").addClass("cur-cal");
		  //$('html,body').animate({scrollTop: $('#locations').position().top+111}, 100, 'swing');

		  jQuery('.ppy').popeye({
		        navigation: 'hover',
		        direction: 'left',
		        caption: 'permanent',
		        opacity: 0.8,
		        duration: 120,
		        debug: 0,
		        zindex: 10000,
		        easing: 'swing'
		      });

		  
		  $("#single-location-content .back-to-all-locations").click(function(){
			  $("#single-location-content").html("");
			  $("#single-location-content").hide();
			  $("#single-location-side").fadeOut(1000);
			  $("#locations-side .button_repositioned, #locations-side .locations, #all-locations-content").fadeIn(2000);			  
			  $("#single-location-side .ppy-placeholder").remove();
			  return false;
		  });
	  });
	  
	  return false;
  });

  $("#zoom-text").click(function(){
	  if($(this).hasClass("zoom")){
		  $("p").removeClass("zoom");
		  $(this).removeClass("zoom");
		  $(this).text($(this).text().replace("-", "+"));
	  }else{
		  $("p").addClass("zoom");
		  $(this).addClass("zoom");
		  $(this).text($(this).text().replace("+", "-"));		  
	  }
	  return false;
  });
  
  $("#print-section").hover(
		  function(){
			  $("#print-section img").attr("src", "/wp-content/themes/twentyten/images/print_hover.png")
		  },
		  function(){
			  $("#print-section img").attr("src", "/wp-content/themes/twentyten/images/print_base.png")
		  }
  );
  
  $("#print-section").click(function(){window.print(); return false;});
    
  $("#search-careers").hover(
		  function(){
			  $("#search-careers img").attr("src", "/wp-content/themes/twentyten/images/button_search_careers_hover.png")
		  },
		  function(){
			  $("#search-careers img").attr("src", "/wp-content/themes/twentyten/images/button_search_careers_base.png")
		  }
  );  
  
  $("#payment-form").submit(function(){
	  var total = 0;
	  var comments = "";
	  
	  if($("#roomboard").val().replace("$", ""))
		  total += parseFloat($("#roomboard").val().replace("$", "0"));
	  
	  if($("#copay").val().replace("$", ""))
		  total += parseFloat($("#copay").val().replace("$", "0"));
	  
	  if($("#cable").val().replace("$", ""))
		  total += parseFloat($("#cable").val().replace("$", "0"));
	  
		  if($("#phone").val().replace("$", ""))
		  total += parseFloat($("#phone").val().replace("$", "0"));
	  
	  
	  comments += "Resident: "+$("#resident").val();
	  comments += ", Facility: "+$("#facility").val();	  
	  comments += ", Room/Board: "+$("#roomboard").val();	  
	  comments += ", Copay: "+$("#copay").val();	  
	  comments += ", Cable: "+$("#cable").val();
	  comments += ", Phone: "+$("#phone").val();
	  total = total.toFixed(2);
	  $("#comments").val(comments);
	  $("#chargetotal").val(total);
	  return validatePaymentForm();
  });
  
  $("#contact form").submit(function(){
	  $('#contact form input:not(#contact-phone,.submit), select, textarea').each(function(){
			if(!$(this).val().replace(/\s+/g, '')){
				$(this).addClass('error');
			} else {
				$(this).removeClass('error');
			}
		});
	  
		if(!$('#contact-email').val().match(/^\S+@\S+\.\S+$/)){
			$('#contact-email').addClass('error');
		}
		else {
			$('#contact-email').removeClass('error');
		}

		
		if($('#contact form  input.error, #contact form  select.error, #contact form textarea').length == 0) {
			return true;
		} else {
			$('html,body').animate({scrollTop: $('#contact form .error:first').parent().prev().position().top+111}, 100, 'swing');
			$('.error:first').focus();
			return false;
		}
	  
  });
  
  $("#contact form #select-location").change(function(){
	  var loc = $(this).val().replace(/ /g, '').toLowerCase();
	  $("#contact .form-instructions  .contact-location").removeClass('current');
	  $("#contact .form-instructions  #contact-location-"+loc).addClass('current');
  });
  
  $(".view-testimonials").colorbox({width:"50%", height:"70%", inline:true, href:"#testimonials"});
  $("#side-calendars ul a").click(function(){
	  $.colorbox({width:"50%", height:"70%", inline:true, href:"#all-events #"+$(this).attr("class")});  
	  return false;
  });
  
  $(".cal-events .view-all").click(function(){
	  $.colorbox({width:"50%", height:"70%", inline:true, href:"#side-calendars"});
	  return false;
  });
  
  
  $(".load-modal").click(function(){
	  $.colorbox({width:"80%", height:"80%", href:$(this).attr("href")+" #content"});
	  return false;
  });
  

  $("#testimonials .test-nav").click(function(){
	  if($(this).hasClass("next-active")){
		  $(this).parent().removeClass("cur-testimonial");
		  $(this).parent().next().addClass("cur-testimonial");
	  }
	  if($(this).hasClass("prev-active")){
		  $(this).parent().removeClass("cur-testimonial");
		  $(this).parent().prev().addClass("cur-testimonial");
	  }
	  return false;
  });
  
  $("#testimonials .prev-active img, #testimonials .next-active img").hover(
		  function(){
			  var src = $(this).attr("src").replace("normal","hover");
			  $(this).attr("src", src);
		  },
		  function(){
			  var src = $(this).attr("src").replace("hover","normal");
			  $(this).attr("src", src);
		  }
  );
  
  function validatePaymentForm(){

	  $('#payment-form input:not(#roomboard,#copay,#cable,#phone,.submit,#responseStatus), select').each(function(){
			if(!$(this).val().replace(/\s+/g, '')){
				$(this).addClass('error');
			} else {
				$(this).removeClass('error');
			}
		});
		
		if(!$('#email').val().match(/^\S+@\S+\.\S+$/)){
			$('#email').addClass('error');
		}
		else {
			$('#email').removeClass('error');
		}

		
		if($('#payment-form  input.error, #payment-form  select.error').length == 0) {
			return true;
		} else {
			$('html,body').animate({scrollTop: $('#payment-form .error:first').prev().position().top+111}, 100, 'swing');
			$('.error:first').focus();
			return false;
		}
}
  
});
