var IE6 = $.browser.msie && $.browser.version.substr(0,1)<7;
var FF2Mac = $.browser.mozilla && $.browser.version.substr(0,1)<3 && navigator.userAgent.toLowerCase().indexOf('mac') != -1;
jQuery(document).ready(function(){
	// global functions
	//alert('hello world');
	initTracking();
	initSifr();
	initPromos();
	initPopLayer();
	initPrint();
	initColumns();
	fixRTE();
	initSMS();
	initShare();
	initSocial();
	if (!IE6){
		$('.trans').css('visibility', 'visible');
		initShadow();
	}	

// page/section specific functions
	switch ($('body').attr('id')){
		case 'landing':
			//initForms();
			initLanding();
			break;
		case 'our-team':
			initOurTeam();
			break;
		case 'services':
			initJumpList();
			break;
		case 'our-hospital':
			initSlideshow();
			break;
		case 'testimonials':
			//initForms();
			initOurTeam();
			//initTestimonials(); // requires forms.js
			break;
		case 'contact-us':
			//initForms();
			//initContactUs(); // requires forms.js
			break;
		case 'offer':
			//initForms();
			//initOffer(); // requires forms.js
			break;
		case 'newmover':
			//initForms();
			//initNewMoverOffer(); // requires forms.js
			break;	
		case 'appt':
			//initForms();
			//initAppt(); // requires forms.js
			break;
		case 'maps-directions':
			initMaps(); // requires additional javascripts (see maps-directions template)
			break;
		case 'news':
			initNews(); // requires tablesorter.js
			break;
		/*case 'seasonal':
			initJumpList();
			initTabs();
			initWeightCalc();
			break;*/
		case 'hills-20percent':
			initWeightCalc();
			break;
		case 'charities':
			//initForms();
			//initCharity(); // requires forms.js
			break;
		case 'facebook-contest':
			//initForms();
			//initFacebookForm(); // requires forms.js
			break;
		case 'appt_google':
			//initForms();
			//initGoogleAppt(); // requires forms.js
			break;
		default:
			// do nothing
	}
	if ($('body').hasClass('homepage')) {
		initHome();
  }
});

function initTracking(){
	$('.nav-primary a').click(function(){
		var action = $(this).text();
		_gaq.push(['_trackEvent', 'Main Nav', action]);
		//alert("_gaq.push(['_trackEvent', 'Main Nav', '"+action+"']);");
		return true;
	});
	
	$('.promo a').click(function(){
		var action = $('img', this).attr('alt');
		var label = document.title
		_gaq.push(['_trackEvent', 'Promo', action, label]);
		//alert("['_trackEvent', 'Promo', '"+action+"', '"+label+"']");
		return true;
	});
	
	$('#flash-replace a').click(function(){
		var label = this.href;
		_gaq.push(['_trackEvent', 'Static PFA', 'Click', label]);
		//alert("['_trackEvent', 'Static PFA', 'Click', '"+label+"']");
		return true;
	});
	
	$('.nav-page a').click(function(){
		var action = $('.nav-page h3').text();
		var label = $(this).text();
		_gaq.push(['_trackEvent', 'Promo', action, label]);
		//alert("['_trackEvent', 'Left Nav', '"+action+"', '"+label+"']");
		return true;
	});
	
	//alert(getQueryValue('utm_campaign'));
	if (getQueryValue('utm_campaign') == 'VCA_Share_Button') {
		switch (getQueryValue('utm_source')) {
			case 'plus.google.com':
				var action = 'Visit-Google+';
				break;
			case 'facebook.com':
				var action = 'Visit-Facebook';
				break;
			case 'twitter.com':
				var action = 'Visit-Twitter';
				break;
		}
		if (typeof(action) != 'undefined') {
			//alert("_gaq.push(['_trackEvent', '"+$('.social-category:first').text()+"', '"+action+"', '"+$('.social-label:first').text()+"'])");
			_gaq.push(['_trackEvent', 'Social - '+$('.social-category:first').text(), action, $('.social-label:first').text()]);
		}
	}
}


/* FUTURE - GA EVENT TRACKING */
// _gaq.push(['_trackEvent', category, action, opt_label, opt_value, opt_noninteraction]);
// _gaq.push(['_trackSocial', network, socialAction, opt_target, opt_pagePath]); 

function googlePlusHandler(response){
	//alert("_gaq.push(['_trackEvent', '"+$('.social-category:first').text()+"', 'Share-Google+', '"+$('.social-label:first').text()+"'])");
	_gaq.push(['_trackEvent', 'Social - '+$('.social-category:first').text(), 'Share-Google+', $('.social-label:first').text()]);
	// google+ button appears to also fire TrackSocial event network=Google, action=+1
	_gaq.push(['_trackSocial', 'Google', '+1', $('.social-label:first').text()]);
}

function twitterTweetHandler(intent_event){
	//alert("_gaq.push(['_trackEvent', '"+$('.social-category:first').text()+"', 'Share-Twitter', '"+$('.social-label:first').text()+"'])");
	_gaq.push(['_trackEvent', 'Social - '+$('.social-category:first').text(), 'Share-Twitter', $('.social-label:first').text()]);
	_gaq.push(['_trackSocial', 'Twitter', 'Tweet', $('.social-label:first').text()]);
}

function facebookLikeHandler(response){
	//alert("_gaq.push(['_trackEvent', '"+$('.social-category:first').text()+"', 'Share-Facebook', '"+$('.social-label:first').text()+"'])");
	_gaq.push(['_trackEvent', 'Social - '+$('.social-category:first').text(), 'Share-Facebook', $('.social-label:first').text()]);
	_gaq.push(['_trackSocial', 'Facebook', 'Like', $('.social-label:first').text()]);
}

function initSocial(){
	// googlePlusHandler callback specified in <g:plusone> markup, see _class/Page::renderSocial
	if ($('.g-plusone').length > 0) {
		window.___gcfg = {
      lang: 'en-US',
			google_analytics: false
    };		
  	$.getScript('https://apis.google.com/js/plusone.js');
  }
	
	if ($('.twitter-share-button').length > 0) {
		$.getScript('http://platform.twitter.com/widgets.js', function(){
			twttr.events.bind('tweet', twitterTweetHandler);
		});
	}
	
	if ($('#fb-root').length > 0) {
  	$.getScript('http://connect.facebook.net/en_US/all.js#xfbml=1', function(){
  		FB.init({
  			status: true,
  			cookie: true,
  			xfbml: true
  		});
  		FB.Event.subscribe('edge.create', facebookLikeHandler);
  		// facebook is by far slowest to load, so don't show social bar until it loads	
				FB.Event.subscribe('xfbml.render', function(){
					//console.log('FB finally loaded');
					if ($('body').attr('id') == 'pet-health-information') {
						var social_bar = $('.social-bar').insertAfter('.content h2').fadeIn();
					}
					else {
						$('.social-bar').fadeIn();
					}
				});
			});
		}
	
}



function initVetsource(){
	$iframe = $('#vs-frame').get(0);
	alert($iframe.height)
}

function initShare(){
	$('.share-tweet, .share-facebook').click(function(){
		window.open(this.href, 'twitter-window', 'status=0,toolbar=0,location=0,menubar=0,scrollobars=1,width=620,height=440');
		return false;
	});
}

function initSMS() {
	$('#SMSBtn' ).click(function(){
		var pop = $('.pop-content');
		var targetPhoneNumber = $('#SMSPhoneNumber', pop).val();
		var thisHospital = VCAhospitalId;
		if (!/^(1[\.\s\-]?)?\(?[2-9]\d{2}\)?[\.\s\-]?[2-9]\d{2}[\.\s\-]?\d{4}$/.test(targetPhoneNumber)){
			//alert('bad phone');
			$('.error-msg', pop).text('Please use a valid phone number, eg. ###-###-####.');
			return false;
		} else {
			targetPhoneNumber = targetPhoneNumber.replace(/\D/g, '');
			if (targetPhoneNumber.length == 10){
				targetPhoneNumber = '1'+targetPhoneNumber;
			}
			//alert(targetPhoneNumber);
		}

		$.post("/tools/SMSComm.php", {hospitalId: thisHospital, targetPhone: targetPhoneNumber},
		  function(data){
				pop.empty().html(data);
		});
	});
}

function initColumns(){
	if (!$('body').hasClass('homepage')) {
  	if ($('.main').height() < $('.nav-sidebar').height()) {
  		$('.content').height($('.nav-sidebar').height());
  	}
  }
}

function initOurTeam(){
	initMoreLess();
	var cssHeight = IE6 ? 'height' : 'min-height';
	$('.pic-list img').each(function(){
	  if (this.complete || this.readyState == 'complete') {
			if ($(this).height() > $(this).parent().height()) {
				$(this).parent().css(cssHeight, $(this).height() + 'px');
			}
		}
	}).load(function(e) {
		if($(this).height()>$(this).parent().height()){
			$(this).parent().css(cssHeight, $(this).height() + 'px');
		}
	});
}

function fixRTE(){
	$('.content img').each(function(){
		if ($(this).css('float') == 'right') {
			$(this).css('margin-left', '10px');
		}
		if ($(this).css('float') == 'left') {
			$(this).css('margin-right', '10px');
		}
	});
	$('img[align=left]').css('margin-right', '10px');
	$('img[align=right]').css('margin-left', '10px');
}

function initTabs(){
	if (location.pathname.indexOf('amazing-pet-care')!=-1){
		$('#promo-amazing, #promo-health').toggleClass('hidden');
	}
	$('.tabs a').click(function(){
		$('#summer-health, #amazing-stories, #promo-amazing, #promo-health').toggleClass('hidden');
		return false;
	});
	if (location.hash.indexOf('amazing-stories')!=-1){
		$('#summer-health, #amazing-stories, #promo-amazing, #promo-health').toggleClass('hidden');
	}
}

function initWeightCalc(){
	$('.flash-trigger').click(function(){

		var layer = $('.pop-layer').css({width:'auto'});
		var parent = layer.parent();
		var target = $($(this).attr('href'));
		var height = parseInt(target.css('height'));
		var width = parseInt(target.css('width'));
		var clone = $('<div id="pop-flash-content"></div>').css({height:height+'px',width:width+'px'});
		var shim = insertModal(layer, parent);
		var config = {
			src: $('a', target).attr('href'),
			height: height,
			width: width,
			wmode: 'transparent',
			bgcolor: '#ffffff',
			version: [8, 0, 0],
			base: '/swf/weight-tool/'
		};
		$('.pop-content', layer).append(clone);
		$(clone).flashembed(config, {});
		var left = ((parent.width() - layer.width())/2 + document.documentElement.scrollLeft) + 'px';
		var top = (($(window).height() - layer.height())/2 + document.documentElement.scrollTop) + 'px';
		layer.css({top: top, left: left}).show();
		return false;
	});
}

function initSlideshow(){
	var list = $('.slideshow ul');
	var i = 0;
	var j =  $('li', list).size();
	$('.prev').click(function(){
		if (i > 0) {
			$('li', list).eq(i).hide();
			i--;
			$('li', list).eq(i).show();
			$('#count').text(i+1);
		}
		return false;
	});
	$('.next').click(function(){
		if (i < j-1) {
			$('li', list).eq(i).hide();
			i++;
			$('li', list).eq(i).show();
			$('#count').text(i+1);
		}
		return false;
	});
	
}

function initNews(){
	$('#news-archive').tablesorter({
		cssHeader:'sort-head',
		cssAsc:'sort-asc',
		cssDesc:'sort-desc'
	});
}


function initHome(){
	if (!FF2Mac) {
  	$('#flash-content').each(function(){
  		var $a = $('a', this);
  		if ($a.attr('rel') !== '') {
  			var config = {
  				src: $a.attr('rel'),
  				height: $(this).height(),
  				width: $(this).width(),
  				wmode: 'opaque',
  				bgcolor: '#394e60',
  				version: [8, 0, 0],
  				onFail: function(){
  					$('#flash-replace, #flash-content img').css('display', 'block');
  				}
  			};
  			var flashvars = {
  				strUrl: $a.attr('href'),
  				strTarget: $a.attr('target'),
  				strLogoPath: $('#vca-logo').attr('src')
  			};
  			$(this).flashembed(config, flashvars);
  			
  		} else  {
				$('#flash-content img').css('display', 'block');
			}
			$('.header img, #flash-replace').css('display', 'none');
  	});
  } else {
		$('#flash-replace, #flash-content img').css('display', 'block');
	}
	if (IE6){
		fixHomeIE();
	}
}

// replace a .sifr dom element with flash movie for lucida sans display
// useful mostly for headings, color comes from css (do not use shorthand colors)
// size of rendered swf comes from a combo of font-size, line-height, padding ... experiment
function initSifr(){
	if (!FF2Mac) {
  	$('.sifr').each(function(){
  		var text = $(this).html();
  		var alt = $('<span>').addClass('hidden').html(text);
  		var config = {
  			src: '/swf/lucida-sans.swf',
  			height: $(this).height(),
  			width: $(this).width(),
  			wmode: 'transparent',
  			version: [8, 0, 0]
  		};
  		var flashvars = {
  			css: '* { color: ' + rgbToHex($(this).css('color')) + '; }',
  			txt: encodeURIComponent(text)
  		};
  		$(this).flashembed(config, flashvars).prepend($('<span>').addClass('replaced').html(text)).css({
  			visibility: 'visible'
  		});
  	});
  } else {
		$('.sifr').css({visibility: 'visible'});
	}
}

// replace a .sifr dom element with flash movie for lucida sans display
// useful mostly for headings, color comes from css (do not use shorthand colors)
// size of rendered swf comes from a combo of font-size, line-height, padding ... experiment
function initPromos(){
	
	$('.promo').each(function(){
		var $a = $('a', this);
		if ($a.attr('rel') !== '') {
			var config = {
				src: $a.attr('rel'),
				height: 68,
				width: 174,
				wmode: 'transparent',
				version: [8, 0, 0]
			};
			var flashvars = {
				strUrl: $a.attr('href'),
				strTarget: $a.attr('target')
			};
			$(this).flashembed(config, flashvars);
		}
	});
}

// creates a drop shadows by sliding a series of absolutely position elements under selected element
// may not work with all elements because of required positioning changes
// WILL NOT WORK ON ABSOLUTELY POSITIONED ELEMENTS (but should be possible with tweaking)
// DOESN'T WORK WITH IE6 (duh) ie6 having a problem with  the height:100% part
function initShadow(){
	$('.shadow').each(function(){
		if (!/relative|absolute/.test($(this).css('position'))){
			$(this).css('position','relative');
		}
		if (!/relative|absolute/.test($(this).children(':first').css('position'))){
			$(this).children(':first').css('position','relative');
		}
		//$(this).add($(this).children(':first')).css('position','relative');
		for (i = 1; i < 5; i++) {
			$('<div style="position:absolute;top:'+i+'px;left:'+i+'px;height:100%;width:100%;background-color:#888;"></div>').css('opacity', '0.'+(5-i)).prependTo(this);
		}
	});
}

var flash_config = {};
var flash_flashvars = {};
function initPopLayer(){
	var modal = $('.pop-modal');
	var shim = $('.pop-shim');
	var layer = $('.pop-layer');
	var parent = layer.parent();
	var close = $('.pop-close');
	$('.hover-trigger').hover(function(e){
		var clone = $($(this).attr('href')).contents().clone(true);
		close.hide();
		popLayer(e, layer, parent, clone, $($(this).attr('href')).css('width'));
	}, function(e){
		close.trigger('click');
	});
	$('.pop-trigger').click(function(e){
		//alert($($(this).attr('href')).css('width'));
		var clone = $($(this).attr('href')).contents().clone(true);
		popLayer(e, layer, parent, clone, $($(this).attr('href')).css('width'));
		return false;
	});
	$('.modal-trigger').click(function(e){
		var clone = $($(this).attr('href')).contents().clone(true);
		popModal(e, modal, shim, clone, $($(this).attr('href')).css('width'));
		return false;
	});
	$('.video-trigger').click(function(e){
		  	flash_config = {
		  		src: '/swf/OSplayer.swf',
		  		height: 480 + 25,
		  		width: 640,
		  		//wmode: 'transparent',
					version: [8, 0, 0]
				};
				flash_flashvars = {
					movie: $(this).attr('href'),
					autoplay: 'on',
					btncolor: '0x6cccccc',
					accentcolor: '0x20b3f7',
					txtcolor: '0xffffff',
					volume: 80
				};
				/*
				 * other flashvars available
				 * autoload: on/off
				 * vTitle: string
				 * showTitle: yes/no
				 * volume: 0/100
				 * mute: on/off
				 * previewimage: string
				 */

		var clone = $('<div style="height:505px" class="pop-video" />');
		popModal(e, modal, shim, clone, 640);
		return false;
	});
	
	close.click(function(){
		layer.hide();
		modal.hide();
		shim.hide();
		$('.pop-content').css('width', 'auto').children().remove();
		return false;
	});
	shim.click(function(){
		close.trigger('click');
	});

	$('#email-dir').click(function(){
		$('#email-trigger').trigger('click');
	});
}

function popLayer(e, layer, parent, clone, width){
	var left, top;
	//var layer = $('.pop-modal');
	$('.pop-content', layer).css('width', width).empty().append(clone);
	if (e.pageX - parent.offset().left < parent.width()/2){
		left = e.pageX - parent.offset().left;
	} else { 
		left = e.pageX - parent.offset().left - layer.width();
	}
	if (e.pageY - parent.offset().top < parent.height()/2) {
		top = e.pageY - parent.offset().top;
	} else {
		top = e.pageY - parent.offset().top - layer.height();
	}
	layer.css({top: top, left: left, zIndex:999}).show();
}

function popModal(e, layer, shim, clone, width){
	//alert(clone.hasClass('pop-video'));
	var left, top;
	var layer = $('.pop-modal');
	$('.pop-content', layer).css('width', width).empty().append(clone);
	if (clone.hasClass('pop-video')) {
		clone.flashembed(flash_config, flash_flashvars);
	}
	left = (($(window).width() - layer.width())/2 + document.documentElement.scrollLeft) + 'px';
	top = (($(window).height() - layer.height())/2 + document.documentElement.scrollTop) + 'px';
	height = $(document).height() > $(window).height() ? $(document).height() : $(window).height();
	shim.css({opacity:'0.5',zIndex:999,height:height}).show();
	layer.css({top: top, left: left, zIndex:1000}).show();
	if ($('.pop-content ul').hasClass('gallery-list')){
		popGallery($('.pop-content ul li:first'));
	}
	$(window).resize(function(){
		popResize();
	}).scroll(function(){
		popResize();
	});
	popResize();
}
 
function popResize(index){
	var layer = $('.pop-modal');
	var item = $('.pop-modal .gallery-list li:visible');
	if ($('img', item).height() > $(window).height()*0.75){
		$('img', item).height($(window).height()*0.75);
	}
	else {
		$('img', item).css('height', 'auto');
	}
	var left = (($(window).width() - layer.width())/2 + document.documentElement.scrollLeft) + 'px';
	var top = (($(window).height() - layer.height())/2 + document.documentElement.scrollTop) + 'px';
	layer.css({top: top, left: left});
}

function initMoreLess(){
	$('.see-more').click(function(){
		var item = $(this).parents('li').get(0);
		$('.more-info', item).show();
		$(this).hide();
		return false;
	});
	$('.see-less').click(function(){
		var item = $(this).parents('li').get(0);
		$('.more-info,', item).hide();
		$('.see-more,', item).show();
		return false;
	});
}

function initJumpList(){
	$('.jump-list').change(function(){
		target = $('option:selected', this).val();
		$('html,body').animate({scrollTop: $('[name='+target+']').offset().top}, 1000);
	});
	$('a[href^=#]').click(function(e){
		target = this.href.substring(this.href.indexOf('#')+1);
		if ($('[name=' + target + ']').length > 0) {
		$('html,body').animate({
			scrollTop: $('[name=' + target + ']').offset().top
		}, 1000);
	}
		return false;
	});

}

function initPrint(){
	$('#print').click(function(){
		window.print();
		return false;
	});
}

/**
 * UTILITY FUNCTIONS
 */

// takes RGB string in format of "rgb(12, 34, 56)" and returns css hex equivalent "#00aa33", returns other formats as is
// used by sIFR to pass css colors as flashvars
function rgbToHex(str){
	if (/^rgb\(/.test(str)){
		var val = '#', hex = "0123456789ABCDEF", rgb = str.replace(/rgb\(|\)/g, '').split(', ');
		for (i=0; i<rgb.length; i++){
			val += String(hex.charAt(Math.floor(rgb[i] / 16))) + String(hex.charAt(rgb[i] - (Math.floor(rgb[i] / 16) * 16)));
		}
		return val;
	} 
	return str;
}

// get querystring parameter value
// returns string if value exists for key, otherwise returns false
function getQueryParam(key){
	var pairs = window.location.search.substring(1).split(/[&]/);
  for (var i=0, j=pairs.length; i<j; i++) {
    var n = pairs[i].split("=");
		if (key == unescape(n[0].replace(/^\s+|\s+$/g,''))){
			return unescape(n[1].replace(/\+/g, ' '));
		} else {
			return false;
		}
  }
}

function getQueryValue(key){
// params: key(opt) [string] // return val: [object] keys as properties OR if key specified [string] key value
  if (window.location.search.substring(1).length > 0){
    return getParams(window.location.search.substring(1).split(/[&]/), key);
  } else {
    return false;
  }
}

function getParams(pairs, key){
// params: pairs(req) [array] of 'key=value' strings, key(opt) [string] // return val: [object] keys as properties OR if key specified [string] key value
    var h = {};
    for (var i=0, j=pairs.length; i<j; i++) {
      var n = pairs[i].split("=");
      if (n.length == 2){
        var k = unescape(n[0].replace(/^\s+|\s+$/g,""));
        var v = unescape(n[1].replace(/\+/g, " "));
        if (key == k) { return v; }
        h[k] = v;
      }
    }
    if (key) { return false; }
    return h;
}

function reverseDisplay (objectId) {
	if 	(document.getElementById(objectId).style.display=="none") {
		jQuery("#"+objectId).slideDown("slow");
	} else {
		jQuery("#"+objectId).slideUp("slow");	
	}
}

