var scrollingInterval = null;
function scrollToTop() {
	if (document.body.scrollTop>110 || document.documentElement.scrollTop>110) 
		window.scrollBy(0,-30);
	else
		window.clearInterval(scrollingInterval);
}
	
(function($) {
	var ph = null;  		// Physicians Object
	var loc = new Array();	// Locations Array
	var current = null;		// Current Physician Object
	var descOpen = false;
	var pageTitle = '';
	jQuery.easing.def = "easeOutSine";
	
	Array.prototype.in_array = function(p_val) {
		for(var i = 0, l = this.length; i < l; i++)
			if(this[i] == p_val) return true;
		return false;
	}
	
	jQuery.fn.fadeIn = function(speed, callback) { 
		return this.animate({opacity: 'show'}, speed, function() { 
			if (jQuery.browser.msie)  
				this.style.removeAttribute('filter');  
			if (jQuery.isFunction(callback)) 
				callback();  
		}); 
	}; 
	 
	jQuery.fn.fadeOut = function(speed, callback) { 
		return this.animate({opacity: 'hide'}, speed, function() { 
			if (jQuery.browser.msie)  
				this.style.removeAttribute('filter');  
			if (jQuery.isFunction(callback)) 
				callback();  
		}); 
	}; 
	 
	jQuery.fn.fadeTo = function(speed,to,callback) { 
		return this.animate({opacity: to}, speed, function() { 
			if (to == 1 && jQuery.browser.msie)  
				this.style.removeAttribute('filter');  
			if (jQuery.isFunction(callback)) 
				callback();  
		}); 
	}; 
	
	function handlePhysicians(data) {
		ph = data.physicians;
		var n = new Array();
		$(ph).each(function(i,p) {
			var front = p.first_name+' '+p.last_name;
			if(!n.in_array(front)) n.push(front);
			var rev = p.last_name+', '+p.first_name;
			if(!n.in_array(rev)) n.push(rev);
		});
		$("#name").attr('autocomplete', 'off').autocompleteArray(n, { onItemSelect:filterPhysicians, width:160, delay:0, minChars:1, matchSubset:1, onFindValue:'', autoFill:false, maxItemsToShow:10 });
	}
	
	function handleLocations(data) {
		$(data.locations).each(function(i,l) {
			loc[l.id] = l;								
		});
	}
	
	function setupDetails() {
		if(!document.getElementById('details')) {
			$('#physicians').before('<div id="details"><h3></h3><div id="details-overlay"><div id="details-content"></div></div></div>');
			$('#details').css({ height:0, paddingTop:0 })
		}
	}
	
	function changePhysician() {
		scrollingInterval=window.setInterval("scrollToTop()",2);
		var found = false;
		var id = $(this).parent().attr('id').substr(1);
		for(var i=0; !found && i<ph.length; i++) {
			if(ph[i].id == id) { current = ph[i]; found = true; }
		}
				
		document.title = current.first_name+' '+current.last_name+' | '+pageTitle;
		pageTracker._trackPageview('/physicians/'+current.url);
		
		if(!descOpen) {
			$('<img src="/images/physicians-close.png" alt="Close" />').appendTo('#details').css({ cursor:'pointer', position:'absolute', top:3, left:3 }).click(closeOverlay);
			$('<ul><li><a class="bio" href=""><span>Bio</span></a></li><li><a class="location" href=""><span>Location</span></a></li><li><a class="education" href=""><span>Education</span></a></li></ul>').prependTo('#details-overlay');
		}
		
		$('.print-image').remove();
		if(current.thumbnail) $('<img class="print-image" src="/images/physicians/'+current.thumbnail+'" alt="'+current.last_name+'" />').prependTo('#details');
		
		var specs = '';
		$(current.specialities).each(function(i,s) { specs += '<br />'+s.name; });
		$('#details').stop().find('h3').each(function() { if(descOpen) $(this).stop().css({ marginLeft:-10, opacity:0 }); else $(this).css({ marginLeft:-330 }); }).html('<strong>'+current.first_name+' '+(current.middle_initial ? current.middle_initial+'. ' : '')+current.last_name+'</strong><br />'+(current.name_suffix ? '<em>'+current.name_suffix+'</em>' : '')+specs);
		
		$('#details-overlay').each(function() { if(descOpen) $('#details-content').hide(); else $(this).css({ right:-280 }).find('#details-content').css({ overflow:'hidden' }); });
		getContent();
		$('#details').css({ background:'#cc91cb url(/styles/images/physicians/'+(current.image ? current.image : '')+') no-repeat' }).each(function() { if(descOpen) $(this).stop().css({ backgroundPosition:'475px 0' }); else $(this).stop().css({ backgroundPosition:'230px 0' }); });
		descOpen = true;
		$('#details').animate({ height:200, paddingTop:10 }, 350, function() {		
			$(this).animate({ marginBottom:0 }, 250).animate({ backgroundPosition: '(230px 0)' }, { duration:300 });
			$(this).find('h3').animate({ marginLeft:0, opacity:1 }, 400);
			$('#details-overlay').animate({ marginBottom:0 }, 200).animate({ right:0 }, 300, function() { $(this).find('#details-content').css({ overflowX:'hidden', overflowY:'auto' }).fadeIn(250); });
		});
		return false;
	}
	
	function getContent() {
		var html =	'<div id="bio"><span>';
		html +=			(current.bio ? current.bio : '<p>There is currently no bio on file for '+current.name+'.</p>');
		html += 	'</span></div>';
		html += 	'<div id="location">';
		$(current.locations).each(function(i,l) {
			var prac = loc[l.id];
			html +=		'<p><strong>'+prac.practice+'</strong><br />'+prac.address_1+'<br />'+(prac.address_2 ? prac.address_2+'<br />' : '')+prac.city+', '+prac.state+' '+prac.zip+(prac.web ? '<br /><a href="http://'+prac.web+'" target="_blank">'+prac.web+'</a>' : '')+'</p>';
		});
		html +=		'</div>';
		html +=		'<div id="education">';
		html +=			(current.education ? current.education : '<p>There is currently no education information on file for '+current.name+'.</p>');
		html +=		'</div>';
		$('#details-content').html(html).find('#bio').siblings().hide().end();
		$('#details-overlay li').removeClass('selected').filter(':first').addClass('selected').end().click(function() {
			addScroll();
			$('#details-overlay li').removeClass('selected');
			$(this).addClass('selected');
			$('#details-content div').hide().filter('#'+$(this).find('span').text().toLowerCase()).show();
			document.title = $(this).find('span').text()+' | '+current.first_name+' '+current.last_name+' | '+pageTitle;
			pageTracker._trackPageview('/physicians/'+current.url+'/'+$(this).find('span').text().toLowerCase());
			return false;
		});
	}
	
	function closeOverlay() {
		removeScroll();
		descOpen = false;
		document.title = pageTitle;	
		$('#details').animate({ height:0, paddingTop:0 }, 300, function() { $(this).find('#details-overlay').css({ right:-240 }).find('#details-content').html('').end().find('ul').remove(); });
	}
	
	function filterPhysicians(el) {
		var list = new Array();
		$(ph).each(function(i,p) {
			$('#p'+p.id).hide();
			if($('#speciality').attr('value') && !hasSpeciality(p)) { return; }
			if($('#practice').attr('value') && !hasPractice(p)) { return; }
			if($('#name').attr('value') && $('#name').attr('value') != 'Enter Name' && !hasName(p)) { return; }
			list.push($('#p'+p.id));
		});
		$(list).each(function(i,d) {
			d.css({ float:'left' }).fadeIn(300);					  
		});
		if(list.length<1) $('#error').html('<p>'+generateError()+'</p>').fadeIn();
		else $('#error').stop().hide().html('');
	}
	
	function hasName(p) {
		var found = 0;
		var name = p.first_name+' '+p.last_name;
		name = name.split(' ');
		var val = $('#name').attr('value');
		val = val.replace(/,/g, '').replace(/^\s*|\s*$/g,'').split(' ');
		$(val).each(function(y) {
			for(var z=0; z<name.length; z++) {
				if(val[y] && name[z].toLowerCase().indexOf(val[y].toLowerCase())==0) { found++; }
			}
		});
		if(found==val.length) { return true; }
		return false;
	}
	
	function hasSpeciality(p) {
		for(var i=0; i<p.specialities.length; i++) {
			if(p.specialities[i].id == $('#speciality').attr('value')) return true;
		}
		return false;	
	}
	
	function hasPractice(p) {
		for(var i=0; i<p.locations.length; i++) {
			if(p.locations[i].practice == $('#practice').attr('value')) return true;
		
		}
		return false;	
	}
	
	function generateError() {
		var errors = new Array();
		if($('#name').attr('value').length>0 && $('#name').attr('value') != 'Enter Name') errors.push('named <strong>'+$('#name').attr('value')+'</strong>');
		if($('#practice').attr('value').length>0) errors.push('that practices at <strong>'+$($('#practice').attr('options')[$('#practice').attr('selectedIndex')]).text()+'</strong>');
		if($('#speciality').attr('value').length>0) errors.push('that specializes in <strong>'+$($('#speciality').attr('options')[$('#speciality').attr('selectedIndex')]).text()+'</strong>');
		var html = 'There are no results for a physician ';
		$(errors).each(function(i,e) { 
			html += e;
			if(i==errors.length-2) html += ' and '; else if(i!=errors.length-1) html += ', ';
		});
		html += '.';
		return html;
	}
	
	function getPageTitle() {
		var t = document.title;
		t = t.split(' | ');
		pageTitle = t[t.length-2]+' | '+t[t.length-1];
		if(t.length>2) setupStageFromMiddle();
	}
	
	function setupStageFromMiddle() {
		descOpen = true;
		$('<img src="/images/physicians-close.png" alt="Close" />').appendTo('#details').css({ cursor:'pointer', position:'absolute', top:3, left:3, opacity:.75 }).click(closeOverlay);
		$('#details-overlay li').removeClass('selected').filter(':first').addClass('selected').end().click(function() {
			$('#details-overlay li').removeClass('selected');
			$(this).addClass('selected');
			$('#details-content div').hide().filter('#'+$(this).find('span').text().toLowerCase()).show();
			document.title = $(this).find('span').text()+' | '+current.first_name+' '+current.last_name+' | '+pageTitle;
			pageTracker._trackPageview('/physicians/'+current.url+'/'+$(this).find('span').text().toLowerCase());
			return false;
		});
	}
	
	function removeScroll() { 
		if($.browser.mozilla) $('#directory #details-content').css({ overflowX:'hidden', overflowY:'hidden' });
	};
	
	function addScroll() {
		$('#directory #details-content').css({ overflowX:'hidden', overflowY:'auto' });
	};
	
		  
	$(document).ready(function() {
		getPageTitle();
		$('#directory form').submit(function() { filterPhysicians(); return false; }).find('input[type=submit]').remove();
		$('.physician a').click(changePhysician);
		$('#directory form select').change(filterPhysicians).keyup(filterPhysicians);
		$('#directory form input').change(filterPhysicians)
			.focus(function() { if($(this).attr('value') == 'Enter Name' || !$(this).attr('value')) $(this).attr('value',''); })
			.blur(function() { if($(this).attr('value') == 'Enter Name' || !$(this).attr('value')) $(this).attr('value','Enter Name'); });
		setupDetails();
		$.getJSON('/ajax-data.php', { action:'physicians' }, handlePhysicians);
		$.getJSON('/ajax-data.php', { action:'locations' }, handleLocations);
	});
})(jQuery);