$('document').ready(function(){
	
	if($.browser.mozilla) {
		$('form div.container input').addClass('moz');
	}
	
	if(window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
		var nameRequest = new XMLHttpRequest();
		var cityRequest = new XMLHttpRequest();
		var provinceRequest = new XMLHttpRequest(); 
	}
	else if(window.ActiveXObject) {
		var nameRequest = new ActiveXObject("Microsoft.XMLHTTP");
		var cityRequest = new ActiveXObject("Microsoft.XMLHTTP");
		var provinceRequest = new ActiveXObject("Microsoft.XMLHTTP");
	} else {
		var nameRequest = null;
		var cityRequest = null;
		var provinceRequest = null;
	}
	
	
	
	// Handler header blue/white band
	
	align();
	
	$(window).resize(function() {
		align();
	});
	
	
	
	// Handle textual search
	
	$('form').submit(function(e) {
		e.preventDefault();
		
		$( "form div.ui input" ).autocomplete("destroy");
		
		initOverlay();
		
		$('#city-col').hide();
		$('#doctor-col').addClass('full');
		$('#doctor-col h2').hide();
		
		var value = $( "form div.ui input" ).val();
		
		_gaq.push(['_trackEvent', 'Search Input', value]);
		
		$.post('home/search', { search:value }, function(data) {
			
			if(data) {
				var result = jQuery.parseJSON(data);
				
				if(result['exact_city'].length > 0) {
					$('#lightbox > h1').text(result['exact_city'].length + ' physician(s) have been found in ' + value);
					
					createDoctorList(result['exact_city']);			
				} else if(result['exact_physician'] != '') {
					$('#lightbox > h1').text('');
					$('#lightbox').addClass('small');
					
					var temp = [result['exact_physician']];
					var img = $("<img src='images/arrow-down.jpg' alt='See' />");
					
					createDoctorList(temp);		
					
					$('#doctor-col ul li').removeClass("over").unbind('mouseenter').unbind('mouseleave').unbind('click').addClass('selected').append(img);
			
					createInfoList($('#doctor-col ul li'), result['exact_physician'], 0);
					
					align();
					
				} else if(result['others'].length > 0) {
					$('#lightbox > h1').text(result['others'].length + ' physician(s) have been found for ' + value);
					
					createDoctorList(result['others'], value);
				} else {
					$('#lightbox > h1').text('No physician has been found');
					$('#doctor-col').hide();
				}
			} 
		});	
	});

	$('form div.ui input').keyup(function(e){
		 var code = (e.keyCode ? e.keyCode : e.which);
		 
		 nameRequest.abort();
		 cityRequest.abort();
		 
		 // if key pressed is enter
		if(code == 13){
			
		}
		// if key pressed is not an arrow
		else if(code < 37 || code > 40) { 
		 	$( "form div.ui input" ).autocomplete("destroy");
			
			var value = $(this).val().toLowerCase();
			var source = new Array();
			var physicians = new Array();
			var cities = new Array();
			
			nameRequest = $.post('home/get_names', { search:value }, function(data) {
			
				if(data) {
					var result = jQuery.parseJSON(data);

					for (var i = 0 ; i < result.length ; i++) {
						var name = result[i].firstname + ' ' + result[i].name;
						
						var decoded = $("<div/>").html(name).text();
					
						physicians.push(decoded);
					}
				} // end if 
				
				cityRequest = $.post('home/get_cities', { search:value }, function(data) {
			
					if(data) 
						cities = jQuery.parseJSON(data);
					
					source = physicians.concat(cities);
					
					if(source.length > 0)
						$( "form div.ui input" ).autocomplete({ source:source, minLength:0 }).autocomplete( "search", "");
					else
						$( "form div.ui input" ).autocomplete("destroy");
					
				}); // end $.post
	
			}); // end $.post
			
		} // end else if
	
    });
	
	
	
	// Handle map search
	
	$('map area').hover(function(){
		var href = $(this).attr('href');
		var province = href.replace('#', '');
		var map = 'images/map-' + province + '.jpg';
		
		$('div.right-col div img').attr('src', map);
	}, function(){
		var map = 'images/map.jpg';
		
		$('div.right-col div img').attr('src', map);
	});
	
	$('map area').click(function(){
		var href = $(this).attr('href');
		var province = href.replace('#', '');
		
		_gaq.push(['_trackEvent', 'Search Map', province]);
		
		$('#doctor-col').removeClass('full');
		$('#doctor-col h2').show();
		
		provinceRequest.abort();
		
		provinceRequest = $.post('home/search_by_province', { province:province }, function(data) {
			
			if(data) {
				
				var result = jQuery.parseJSON(data);
				var counter = 0;
				
				$('#city-col').show();
				$('#doctor-col').show();
				
				initOverlay();
				
				$('#city-col ul').empty();
				
				for (var i in result) {
					var city = result[i];
					var li = $('<li><p>' + i + ' (' + city.length + ')</p></li>').appendTo('#city-col ul');
					
					initCityList(li, city);
	
					for (var j in city) {
						province = city[j].province;
						counter++;
					}
				}
				
				$('#lightbox > h1').text(counter + ' physician(s) have been found in ' + province);

			} else {
				initOverlay();
				
				var temp = province.replace('-', '');
				
				var eq = {	alberta 				: 'Alberta',
							britishcolumbia 		: 'British Columbia',
							manitoba 				: 'Manitoba',
							newbrunswick 			: 'New Brunswick',
							newfoundlandlabrador 	: 'Newfoundland and Labrador',
							northwestterritories 	: 'Northwest Territories',
							novascotia 				: 'Nova Scotia',
							nunavut 				: 'Nunavut',
							ontario 				: 'Ontario',
							princeedwardisland 		: 'Prince Edward Island',
							quebec					: 'Quebec',
							saskatchewan 			: 'Saskatchewan',
							yukon 					: 'Yukon'
							};
				
				$('#lightbox > h1').text('No physician has been found in ' + eq[temp]);
				$('#city-col').hide();
				$('#doctor-col').hide();
			}
		});
	});
});



function align(){
	var bodyWidth = $('body').width();
	var contentWidth = $('header div.mid-col').width();
	var colWidth = (bodyWidth - contentWidth) / 2;
	
	$('header div.left-col').css({ 	width : colWidth,
									display : 'inline'
								});
							
	$('header div.right-col').css({ 	width : colWidth,
										display : 'inline'
								});
	
	
	var lightboxHeight = $('#lightbox').outerHeight();
	
	if ($.browser.msie)
		var y = (document.documentElement.offsetHeight - lightboxHeight) / 2;
	else
		var y = (window.innerHeight - lightboxHeight) / 2;
	
	$('#lightbox').css({ 	top : y		});							
}

function initOverlay() {
	$('#overlay').show();
	$('#city-col').show();
	$('#doctor-col').show();
	
	$('#lightbox').removeClass('small');
	
	$('#overlay').click(function(e){
		if(e.target.attributes['id'] && e.target.attributes['id'].value == $(this).attr('id'))
			$('#overlay').hide();
	});
	
	$('#lightbox > img').click(function(){
		$('#overlay').hide();
	});
	
	align();
	
	$('#doctor-col ul').empty();
	$('#city-col ul').empty();
}

function initCityList(li, city) {
	var img = $("<img src='images/arrow-right.jpg' alt='See' />");
	
	li.bind({
		click: function(){
			$('#city-col ul li').each(function(){
				$(this).removeClass('selected').children('img').remove();
				$(this).bind({
					mouseenter: function(){
						$(this).addClass("over");
					},
					mouseleave: function(){
						$(this).removeClass("over");
					}
				});
			});
			
			$(this).addClass('selected').removeClass("over").unbind('mouseenter').unbind('mouseleave').append(img);
			
			createDoctorList(city);
		},
		mouseenter: function(){
			$(this).addClass("over");
		},
		mouseleave: function(){
			$(this).removeClass("over");
		}
	});
}

function createDoctorList(city, value) {
	$('#doctor-col ul').empty();
	
	for (var i in city) {
		var physician = city[i];
		var li = $('<li><p>' + physician.firstname + ' ' + physician.name +'</p></li>').appendTo('#doctor-col ul');
		
		if(value) {
			var p = li.children('p').first();
			
			var indexes = hasSearchedText(p, value);
						
			if(indexes) 
				highlightSearchedText(p, value, indexes);
		}
		
		initDoctorList(li, physician);
	}
}

function initDoctorList(li, physician) {
	var img = $("<img src='images/arrow-down.jpg' alt='See' />");
	
	li.bind({
		click: function(){
			$('#doctor-col ul li').each(function(){
				$(this).removeClass('selected').children('img').remove();
				$(this).bind({
					mouseenter: function(){
						$(this).addClass("over");
					},
					mouseleave: function(){
						$(this).removeClass("over");
					}
				});
			});
			
			$(this).removeClass("over").unbind('mouseenter').unbind('mouseleave').addClass('selected').append(img);
			
			$('li.info').slideUp(500, function(){ $(this).empty(); });
			
			createInfoList(li, physician);
		},
		mouseenter: function(){
			$(this).addClass("over");
		},
		mouseleave: function(){
			$(this).removeClass("over");
		}
	});
}

function createInfoList(li, physician, value) {
	var obj = $("<li class='info'></li>");
	
	value = (value == 0) ? value : 500;
	
	if(physician.physician_type != '') {
		var decoded = $("<div/>").html(physician.physician_type).text();
		
		$('<p>' + decoded + '</p>').appendTo(obj);
	}
	
	if(physician.clinic != '') {
		var decoded = $("<div/>").html(physician.clinic).text();
		
		$('<p>' + decoded + '</p>').appendTo(obj);
	}
	
	if(physician.address != '') {
		var decoded = $("<div/>").html(physician.address).text();
		
		$('<p>' + decoded + '</p>').appendTo(obj);
	}
	
	if(physician.postalcode != '') {
		$('<p>' + physician.postalcode + '</p>').appendTo(obj);
	}
	
	if(physician.telephone != '') {
		$('<p>Phone : ' + physician.telephone + '</p>').appendTo(obj);
	}
	
	if(physician.tollfree != '') {
		$('<p>Toll free : ' + physician.tollfree + '</p>').appendTo(obj);
	}
	
	if(physician.fax != '') {
		$('<p>Fax : ' + physician.fax + '</p>').appendTo(obj);
	}
	
	if(physician.email != '') {
		$("<p>Email : <a href='mailto:" + physician.email + "'>" + physician.email + "</a></p>").appendTo(obj);
	}
	
	if(physician.website != '') {
		var site = (physician.website.indexOf('http://') == -1) ? 'http://' + physician.website : physician.website;
		
		$("<p><a href='" + site + "'>" + physician.website + "</a></p>").appendTo(obj);
	}
	
	if(physician.additionalinfo1 != '') {
		var decoded = $("<div/>").html(physician.additionalinfo1).text();
		
		$('<p>' + decoded + '</p>').appendTo(obj);
	}
	
	if(physician.additionalinfo2 != '') {
		var decoded = $("<div/>").html(physician.additionalinfo2).text();
		
		$('<p>' + decoded + '</p>').appendTo(obj);
	}
	
	obj.insertAfter(li);
	
	obj.delay(value).slideDown(value);
}

function hasSearchedText(obj, value) {
	var indexes = new Array();
	var strUpper = obj.text();
	var str = strUpper.toLowerCase();
	var counter = 0;
	var searchIndex = 0;
	
	for(var i = 0 ; i < str.length; ++i) {
		searchIndex = str.indexOf(value);
		
		if(searchIndex == -1)
			break;
	
		counter += searchIndex;
	
		indexes.push(counter);
		
		counter += value.length;
		
		str = str.substring(searchIndex + value.length);
	}
	
	if(indexes.length > 0)
		return indexes;
	else
		return false;
}

function highlightSearchedText(obj, value, indexes) {
	var spanOpen = "<span class='selected_text'>";
	var spanClose = "</span>";
	var offset = 0;
	
	for(var i = 0 ; i< indexes.length; ++i) {
		var searchValue =  obj.html().substring(indexes[i] + offset, indexes[i] + offset + value.length);
		var before = obj.html().substring(0, indexes[i] + offset);
		var after = obj.html().substring(indexes[i] + offset + value.length);
		
		obj.html(before + spanOpen + searchValue + spanClose + after);
		
		offset += spanOpen.length + spanClose.length;
	}
}
