var numPetsVisible = 0;
var geocoder, map, infoWindow;


jQuery(document).ready(function($) {

	// Initialize the Google Map on Locations template
	if ( $('#google-map').length > 0 ) {
		initializeMap();
		locations_init(); 
	}
	
	
	// Toggle the form help popup if there a help icon
	$('form a.help').click(function() {
		var helpText = $(this).attr('data-help');
		$(this).append('<span>'+helpText+'</span>');
		return false;
	});
	
	$('form a.help').mouseleave(function() {
		$(this).children('span').fadeOut('normal', function() { $(this).remove(); });
	});
	
	
	// Use hidden form labels as placeholder text
	applyPlaceholderTexts();
	

	// Keep top nav item "active" while dropdown is visible
	$('#clinic-bar nav > ul > li').mouseenter(function() {
		$(this).addClass('current_hover');
	});
	
	$('#clinic-bar nav > ul > li').mouseleave(function() {
		$(this).removeClass('current_hover');
	});
	
	
	// Redirect user when select box changes (has PHP fallback as well)
	$('.filters select').change(function() {
		if ( $(this).val() != '' ) {
			window.location = $(this).val();
		}
	});
		
	
	// Open certain links in new window
	$('a[data-link="external"]').live('click', function() {
		$(this).attr('target', '_blank');
	});
	
	
	// Open browser print preview dialog box
	$('#sharing li.print a').click(function() {
		window.print();
	});
	
	
	// Toggle the login form in header
	$('#account li.log-in a').click(function() {
		$('#account #login-form').fadeToggle();
		return false;
	});
	
	
	// Configure the homepage slideshow (Effects: uncover, fade or scrollHorz)
	$('#slideshow ul').cycle({
		fx: 'uncover',
		timeout: 8000,
		speed: 700,
		prev: '#controls a.prev',
		next: '#controls a.next'
	});
		
	
	// Toggle slideshow animation when element is hovered
	$('#slideshow').hover(function() {
		$('#slideshow ul').cycle('pause');
	}, function() {
		$('#slideshow ul').cycle('resume');
	});
	
	
	// Configure iframe for educational programs
	$('ul.educational-programs a').fancybox({
		'type': 'iframe',
		'width': 720,
		'height': 555,
		'autoScale': false,
		'hideOnOverlayClick': false,
		'overlayColor': '#000',
		'overlayOpacity': 0.5
	});
	
	
	// WordPress slideshow gallery (inline)
	$('.post-content ul.gallery').cycle({
		fx: 'fade',
		timeout: 5000
	});
	
	
	// Initialize VideoJs on the <video> element
	$('.post-content video').VideoJS();
	
	
	// Open linked images from post content in Fancybox
	$('.post-content a[href$=".jpg"], .post-content a[href$=".png"], .post-content a[href$=".gif"]').fancybox({
		'overlayColor': '#000',
		'overlayOpacity': '0.5',
		'titlePosition': 'over'
	});


	// Prepare widget for Sick Pet Helper actions
	var ls = $('#ph-species ul.sick-pet-helper li a').click(function() {
		$(".post-content").hide();
		$('#IFrameSickpethelper1').attr('src', $(this).attr('href'));
		$("#IFrameSickpethelper1").show();
		return false;
	});
	

	// Add or remove pet fields on client profile page
	var o = $('#petlist');
	if (o.length) {
		numPetsVisible=document.forms['profileForm'].elements['numvisible'].value;

		// Remove row if button is clicked (mark record for deletion on save, hide row)
		$('#petlist .petinfo .row_delete input').live("click",function() {
			$(this).attr("disabled",true);
			if (window.confirm($('#petlist').attr('data-confirm'))) {
				var idx=$(this).attr("id").substring(7);
				document.forms['profileForm'].elements['pet'+idx+'_deleted'].value=1;
				numPetsVisible--;
				$('#petlist #petinfo_'+idx).fadeOut('fast',function() {
					if (numPetsVisible<=0) $('#nopets').fadeIn('fast');
				});
			}
			else $(this).attr("disabled",false);
		});

		// Add row if add button is clicked (add new fields, increment counter)
		$('input#addpet').click(function() {
			$(this).attr('disable',true);
			var nextNumber = parseInt(document.forms['profileForm'].elements['numpets'].value,10);
			
			$.get('/wp-content/plugins/lifelearn-addons/includes/block-petinfo.php', {
				mode: 'ajax',
				num: nextNumber,
				l_name: $('#petlist').attr('data-label-name'),
				l_type: $('#petlist').attr('data-label-type'),
				l_delete: $('#petlist').attr('data-label-delete'),
				l_types: $('#petlist').attr('data-pet-types')
			}, function(data) {
				$('#petlist').append(data);
				document.forms['profileForm'].elements['numpets'].value=nextNumber+1;
				$('#nopets').fadeOut('fast', function() {
					numPetsVisible++;
					applyPlaceholderTexts();
					$('#petlist #petinfo_'+nextNumber).fadeIn('fast');
				});
			});
		});

	}
	
	
}); // End of document ready



// Configure Google Map for Location template
function initializeMap() {
	var latlng = new google.maps.LatLng(44,-95);
	var mapOptions = {
		zoom: 10,
		center: latlng,
		mapTypeId: google.maps.MapTypeId.ROADMAP
	};
	
	infoWindow = new google.maps.InfoWindow({content:''});
	geocoder = new google.maps.Geocoder();
	map = new google.maps.Map(document.getElementById('google-map'), mapOptions);
	
}


function applyPlaceholderTexts() {
	// Apply a placeholder or value to each input field
	$('#header input[type="text"], #header input[type="password"], form.ll_form input[type="text"], form.ll_form input[type="password"]').each(function() {

		if ($(this).attr("data-ph")!=1) {
			var field_id = $(this).attr('id');
			var field_text = $('form').find('label[for="'+field_id+'"]').text().replace(':', '').replace('* ', '').toLowerCase();
			
			$(this).attr("data-ph",1);

			// don't apply this to reCAPTCHA fields.
			if (field_id) {
				var result = field_id.substring(0,10);
				if (result == "recaptcha_") return false;
			}

			// Check if HTML5 placeholder attr is supported
			if (Modernizr.input.placeholder){
				$(this).attr('placeholder', '').attr('placeholder', field_text);
			} else {
				if ($(this).attr('value')=='') $(this).attr('value', field_text);
				
				$(this).each(function() {
					var default_value = field_text;
					$(this).focus(function() { if (this.value == default_value) {this.value = '';} });
					$(this).blur(function() { if (this.value == '') {this.value = default_value;} });
				});
			}
		}
	});

	$("form.ll_form").submit(function() {

		$(this).find('input[type="text"],input[type="password"]').each(function() {
			var skip=0;
			var field_id = $(this).attr('id');
			var field_text = $('form').find('label[for="'+field_id+'"]').text().replace(':', '').replace('* ', '').toLowerCase();
		
			// don't apply this to reCAPTCHA fields.
			if (field_id) {
				var result = field_id.substring(0,10);
				if (result == "recaptcha_") skip=1;
			}

			// Check if HTML5 placeholder attr is supported
			if ((!Modernizr.input.placeholder)&&(!skip)) {
				if ($(this).attr('value')==field_text) $(this).attr('value','');
			}
		});

		return true;
	});

}
