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
	initSifr();
	initPromos();
	initPopLayer();
	initPrint();
	initColumns();
	fixRTE();
	initSMS();
	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 '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;
		default:
			// do nothing
	}
	if ($('body').hasClass('homepage')) {
		initHome();
  }
});

function initVetsource(){
	$iframe = $('#vs-frame').get(0);
	alert($iframe.height)
}

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(){
	$('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);
  			$('.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: text.replace(/'/, '&apos;')
  		};
  		$(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);
		}
	});
}

function initPopLayer(){
	var layer = $('.pop-layer');
	var parent = layer.parent();
	var close = $('.pop-close');
	$('.pop-hover').hover(function(e){
		var clone = $($(this).attr('href')).contents().clone(true);
		close.hide();
		popAction(e, layer, parent, clone, false);
	}, function(e){
		layer.removeAttr('id').hide();
		close.show();
		$('.pop-content').empty();
	});
	$('.pop-trigger, .modal-trigger').click(function(e){
		var clone = $($(this).attr('href')).contents().clone(true);
		var modal = $(this).hasClass('modal-trigger');
		popAction(e, layer, parent, clone, modal);
		return false;
	});
	close.click(function(){
		layer.removeAttr('id').hide();
		$('.pop-shim').remove();
		$('.pop-content').empty();
		return false;
	});
	$('#email-dir').click(function(){
		$('#email-trigger').trigger('click');
	});
}

function popAction(e, layer, parent, clone, modal){
		var left, top;
		$('.pop-content', layer).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();
		}
		if (modal) {
			layer.attr('id', 'pop-layer-emergency');
			left = ((parent.width() - layer.width())/2 + document.documentElement.scrollLeft) + 'px';
			top = (($(window).height() - layer.height())/2 + document.documentElement.scrollTop) + 'px';
			var shim = insertModal(layer, parent);
		}
		layer.css({top: top, left: left}).show();
}

function insertModal(layer, parent){
	return $('<div></div>')
		.attr('class','pop-shim')
		.css({position:'absolute',top:'0',left:'0',height:parent.height(),width:parent.width(),backgroundColor:'#000000',opacity:'0.5'})
		.insertBefore(layer)
		.click(function(){
			$('.pop-close').trigger('click');
		});
}

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);
		$('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");	
	}
}
