if (!window.console){console={log:function(){}}};

function initSMS() {
	$('#btn-sms' ).click(function(){
		var pop = $('.pop-content');
		var phone = $('#SMSPhoneNumber', pop).val();
		var ipaddress = $('#sms_ip', pop).val();
		var user_agent = $('#sms_agent', pop).val();
		if (!/^(1[\.\s\-]?)?\(?[2-9]\d{2}\)?[\.\s\-]?[2-9]\d{2}[\.\s\-]?\d{4}$/.test(phone)){
			//alert('bad phone');
			$('.error-msg', pop).text('Please use a valid phone number, eg. ###-###-####.');
			return false;
		} else {
			phone = phone.replace(/\D/g, '');
			if (phone.length == 10){
				phone = '1'+phone;
			}
			//alert(targetPhoneNumber);
		}
		var id = $('#hospital-id').val();

		$.post("/tools/sms-info.php", {hospitalId: id, phone: phone, ipaddress: ipaddress, user_agent: user_agent},
		  function(data){
				pop.empty().html(data);
		});
	});
}

function initFixLayout(){
	$('.content img').each(function(){
		if ($(this).css('float') == 'right') {
			$(this).css('margin-left', '10px');
		}
		if ($(this).css('float') == 'left') {
			$(this).css('margin-right', '10px');
		}
	});
	// fix RTE image align
	$('img[align=left]').css('margin-right', '10px');
	$('img[align=right]').css('margin-left', '10px');
	// fix long sidebar
	//alert($('.nav-sidebar').height() +' '+ $('.content').height());
	if ($('body').attr('id') != 'home' && $('.nav-sidebar').height() > $('.content').height()){
		$('.content').css('min-height', ($('.nav-sidebar').height()-40)+'px');		
	}
	if ($('body').attr('id') != 'home' && $('.nav-page').height() > $('.content').height()){
		$('.content').css('min-height', ($('.nav-page').height()-40)+'px');		
	}
	
}

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;
	});
}


// 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(){
	$('.promos div').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(){
	//$('.trans').css('visibility', 'visible');
	$('.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);
		}
	});
}

function initGlobalTabs(){
	var panelOpen = 0;
	$('.nav-tabs a').click(function(){
		var $this = $(this);
		if ($this.hasClass('hybrid-tab')) {
			return true;
		}
		var $panel = $($this.attr('href'));
		if ($panel.hasClass('opened') || $this.parent().hasClass('disabled')) {
			$('.panel-close').trigger('click');
		}
		else {
			$('.global-tabs div.opened').slideUp('normal', function(){
				$(this).removeClass('opened');
			});
			$('.nav-tabs li').removeClass('selected');
			$this.parent().addClass('selected');
			$panel.slideDown('normal', function(){
				$(this).addClass('opened');
			})
		}
		return false;
	});
	$('.panel-close').click(function(){
		$('.global-tabs div.opened').slideUp('normal', function(){
			$(this).removeClass('opened');
			$('.nav-tabs li').removeClass('selected');
			$('.nav-tabs li.disabled').addClass('selected');
		});
		return false;
	})
	$('#trigger-emergency').click(function(){
		$('#tab-emergency a').trigger('click');
	});
	$('form[name=tab-search]').submit(function(){
		if (!/^\d{5}([\-\s]?\d{4})?$/.test($('input[name=map-zip]', this).val())) {
			alert('Please enter a valid 5-digit ZIP code.');
			return false;
		}
	});
		$('input[name=map-zip]').focus(function(){
		if (this.value == '[enter your ZIP code here]'){
			this.value = '';
		}
	}).blur(function(){
		if (this.value == ''){
			this.value = '[enter your ZIP code here]';
		}
	});

}

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;
	});
	
	$('.promos a').click(function(){
		var action = $('span.promo-name', this).text();
		var label = $('meta[name=gapage]').attr('content');
		_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', 'Left Nav', action, label]);
		//alert("['_trackEvent', 'Left Nav', '"+action+"', '"+label+"']");
		return true;
	});
	
	$('#song-download').click(function(){
		_gaq.push(['_trackEvent', 'Download', 'song', 'I will take care of you']);
		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 initPrint(){
	$('#btn-print').click(function(){
		window.print();
		return false;
	});
}

function initButtonLink(){
	$('.btn-link').click(function(){
		document.location.href = $(this).attr('href');
	});
}

function initFaq(){
	$('.faq').faq();
}

function initGallery(){
	//alert('gallery init');
	var img = new Image();
	img.src = '/img/common/icons/icon-slide-over.png';
	img.src = '/img/common/icons/icon-zoom-over.png';

	//var length = $('.gallery-list li').length;
	//$('.gallery-list li:not(:first)').hide();
	$('.gallery-list').each(function(){
		$('li:not(:first)', this).hide();
	});

	$('.gallery-trigger').hover(function(e){
		var src = $('.trigger-icon', this).attr('src');
		$('.trigger-icon', this).attr('src', src.replace(/\.png$/,'-over.png'));
	}, function(e){
		var src = $('.trigger-icon', this).attr('src');
		$('.trigger-icon', this).attr('src', src.replace(/-over\.png$/,'.png'));
	});

	$('.gallery-nav .paging-nav').click(function(){
		//alert('nav clicked');
		var length = $('.pop-content .gallery-list li').length;
		var items = $('.pop-content .gallery-list li');
		var index = items.index($('.pop-modal .gallery-list li:visible'));
		//items.eq(index).hide();
		if ($(this).hasClass('prev')){
			index--;
		}
		else {
			index++;
		}
		if (index == length){
			index = 0;
		}
		else if (index < 0) {
			index = length-1;
		}
		if (index > 0) {
			$('.pop-content .paging-nav.prev').show();
		}
		else {
			$('.pop-content .paging-nav.prev').hide();
		}
		if (index+1 >= length) {
			$('.pop-content .paging-nav.next').hide();
		}
		else {
			$('.pop-content .paging-nav.next').show();
		}

		//items.eq(index).show();
		$('.pop-modal .gallery-nav .count').text(index+1);
		//popGallery(items.eq(index));
		popGallery(index);
		return false;
	});
}

function popGallery(index){
	var items = $('.pop-content .gallery-list li').hide();
	var item = items.eq(index).show();	
	
	var img = new Image();
	img.onload = function(){
		$('a', item).each(function(){
			if ($(this).hasClass('flv-trigger') && !$(this).hasClass('flashed')) {
				$(this).css({display: 'block', height: '355px', width:'480px'})
		  	var config = {
		  		src: '/swf/OSplayer.swf',
		  		height: 330 + 25,
		  		width: 480,
		  		//wmode: 'transparent',
					version: [8, 0, 0]
				};
				var flashvars = {
					movie: $(this).attr('href'),
					autoload: 'on',
					btncolor: '0x6cccccc',
					accentcolor: '0x20b3f7',
					txtcolor: '0xffffff',
					volume: 75,
					previewimage: $('img', this).attr('src')
				};
				$(this).addClass('flashed').flashembed(config, flashvars);
				popResize(index);
			}
		});	
		
	}
	img.src = $('img', item).attr('src');
	$('a', item).click(function(){
		//alert('wrong click');
		return false;
	});
	popResize(index);
}

function popResize(index){
	var layer = $('.pop-modal');
	
	if (typeof index == 'undefined') {
  	index = 0;
  }
	
	if ($('.pop-content .gallery-list li').length > 0) {
		// this is a gallery
		$('.pop-content', layer).css('width', 'auto');
		if (typeof index == 'undefined') {
	  	index = 0;
	  }
		var item = $('.pop-content .gallery-list li').eq(index);
		if (item.find('a.flv-trigger').length > 0) {
			// video
			
			var obj = item.find('a.flv-trigger').children().first();
			obj.height(355);
		}
		else {
			// resize according to image
			var img = $('img', item);
			//console.log($('img', item).height()+' '+$(window).height()*0.75);
			if (img.height() > $(window).height()*0.70){
				img.height($(window).height()*0.75);
			}
			else {
				img.css('height', 'auto');
				// grab the width of the
			}
		}
		
	
	}
	
	var left = (($(window).width() - layer.width())/2) + 'px';
	var top = (($(window).height() - layer.height())/2) + 'px';
	layer.css({top: top, left: left});
}

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
				};

		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').empty();
		return false;
	});
	shim.click(function(){
		close.trigger('click');
	});
	$(window).resize(function(){
		popResize();
	});

	$('#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:1000}).show();
}

function popModal(e, layer, shim, clone, width){
	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);
	}
	if ($('.pop-content ul').hasClass('gallery-list')){
		popGallery(0);
	}
	left = (($(window).width() - layer.width())/2) + 'px';
	top = (($(window).height() - layer.height())/2) + 'px';
	height = $(document).height() > $(window).height() ? $(document).height() : $(window).height();
	shim.css({opacity:'0.5',zIndex:0,height:height}).show();
	layer.css({top: top, left: left, zIndex:1}).show();
	popResize();
}


// 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;
}

// 
// params: key(opt) [string] // return val: [object] keys as properties OR if key specified [string] key value
function getQueryValue(key){
  if (window.location.search.substring(1).length > 0){
		var pairs = window.location.search.substring(1).split(/[&]/);
    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;
  } else {
    return false;
  }
}

jQuery.fn.faq = function(tog) {
	return this.each(function () {
    var dl = $(this).addClass('faq');
 		var dd = $('dd', dl).addClass('faqClosed').hide();
			var dt = $('dt', dl).addClass('faqClosed').click(function(e){
			$(this).toggleClass('faqClosed').toggleClass('faqOpen');
     	$(this).next().toggleClass('faqClosed').toggleClass('faqOpen').slideToggle();
		});
		if(typeof tog == 'number') $('dt:eq('+tog+')').trigger('click');
	});
};


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;
	});

}

