$.fn.stars = function() {
	$(this).each(function() {
		// Get the value
		var val = parseFloat($(this).html());
		// Make sure that the value is in 0 - 5 range
		val = val > 5 ? 5 : (val < 0 ? 0 : val);
		// Calculate physical size
		var size = 16 * val;
		// Create stars holder
		var stars = $('<span class="stars"><span></span></span>');
		// Adjust yellow stars' width
		stars.find('span').width(size);
		// Replace the numerical value with stars
		$(this).replaceWith(stars);
	});
}

var phoneClicked = false;
var badgeVoteCount = 3;

$(window).load(function(){
	$("#textureFrameOutter").dropShadow({left: 5, top: 5, blur: 1, color: "black"});
});

$(window).unload( function () { GUnload(); } ); // replace onUnload="GUnload()" for gmap api
$(document).ready(function() {
	// $("table.hours th:last").css("border", "none");
	$('table.hours tbody > tr:odd > td').addClass('lunch');
	$('span.rating').stars();
	// check if tabs div exists
	if($('#profileLocation').length > 0){
		if($('#map-location-data').length > 0 ){
			$('#profileLocation').jMapping({ 
				info_window_max_width: 20, 
				default_zoom_level: 15,
			});
		}
		else{
			var geocoder = new GClientGeocoder();
			var address = $("input#drOfficeAddress").val();
			initializeGMap(geocoder, address);
		}
	}
	if($('#tabs').length > 0){
		$("#tabs").tabs({ 
			collapsible: true,
			selected: -1, 
			fx: { opacity: 'toggle' },
			show: function(event, ui) {
				if( $('#tabs-6').is(':visible')){
					$('#map').css('width', 850);
					$('#map').css('height', 350);		
					$('#map').css('margin-right', 'auto');
					$('#map').jMapping({ 
						info_window_max_width: 100, 
						default_zoom_level: 16,
						map_config: function(map){
						      map.setMapType(G_NORMAL_MAP);
						      map.addControl(new GLargeMapControl());
						      map.addControl(new GMapTypeControl()); 
						}
					});
				}
			}
		});	   
		$('.closeTab').click(function() {
			$("#tabs").tabs( 'select', -1 );
		});
	}
	if($('a.badge-vote-button').length > 0){
		$('a.badge-vote-button').cluetip({
		  tracking: false,
		  positionBy: 'relative',
		  activation: 'click',
		  fx: { open: "fadeIn", openSpeed: 500 },
		  closePosition: "title",
		  closeText: "Close",
		  mouseOutClose: true,
		  delayedClose: 8000
		  } );
	}
	$('a.button img').hover(
		function(){
			(this).src = (this).src.replace(/_off/, '_hover');
		},
		function(){
			(this).src = (this).src.replace(/_hover/, '_off');
		}
	);
	$('#phoneToReveal').click( function(){
		var dr_id_value = $('#dr_id').val();
		if (! phoneClicked) {
			$.get("/buscar/dr_phone_number", { dr_id: dr_id_value }, function(data){
				$('#phoneToReveal').html(data);
				phoneClicked = true;
			});
		};
	});
	$('a.deleteReview').click(function(event) {
		event.preventDefault();
		var el = this;
		var href = $(el).attr('href');
		$("#dialog-confirm").dialog({
			resizable: true,
			height:140,
			width: 320,
			modal: true,
			title: 'Deleting Review',
			buttons: {
				'Delete Review': function() {
					$.get(href, {}, function(data, textStatus, xhr) {
						$(this).dialog('close');
						window.location.reload();
					});
				},
				Cancel: function() {
					$(this).dialog('close');
				}
			}
		}); 
	});
	$('#button_badges_info').click(function(event) {
		$("#dialog_badges_info").dialog({
			resizable: false,
			width: 380,
			modal: true,
			autoOpen: true,
			title: 'About Badges',
			buttons: {
				Close: function() {
					$(this).dialog('close');
				}
			}
		});
	});

	$('#button_badges_vote').click(function(event) {
		$("#dialog_badge_vote").dialog({
			resizable: false,
			width: 380,
			modal: true,
			autoOpen: true,
			title: 'Vote For Badges',
			close: function () { drRefreshBadges(); },
			buttons: {
				Close: function() {
					$(this).dialog('close');
				}
			}
		});
	});
			
	// var geocoder = new GClientGeocoder();
	// var address = $("input#drOfficeAddress").val();
	// initializeGMap(geocoder, address);
	
});

function initializeGMap(geocoder, address) {
  if (GBrowserIsCompatible()) {
	var map = new GMap2(document.getElementById("profileLocation"));
	map.setUIToDefault(); 
	if(address){
		showAddress(geocoder, address, map);
	}
  }
}

function showAddress(geocoder, address, map) {
	geocoder.getLatLng(
		address,
		function(point) {
			if (!point) {
				alert(address + " not found");
			} else {
				map.setCenter(point, 16);
				var marker = new GMarker(point);
				map.addOverlay(marker);
				// marker.openInfoWindowHtml('Click to get driving directions');
				var directionsURL = 'http://maps.google.com/maps?' + 'daddr=' + escape(address);
				// GEvent.addListener(map, "click", function(overlay, latlng){
				//	   window.open(directionsURL);
				// });
			}
		}
	);
	
}

function markReviewHelpful(evt, review_id) {
	$.ajax({
		type: "GET",
		url: "/buscar/dr_review_helpful?review_id="+review_id,
		success: function(msg){
			var helpful_el_msg = $("#review_helpful_" + review_id + " > span.message" );
			var helpful_el_count = $("#review_helpful_" + review_id + " > span.helpful_count" );
			var user_msg = "Thank you";
			var current_count_html = helpful_el_count.html();
			if (msg == 'denied') {
				user_msg = 'Your voted has already been counted.';
			}
			else{
				current_count_html = "Helpful(" + msg + ")";
			}
			
			helpful_el_count.hide(1).html(current_count_html).delay(2000).fadeIn('slow');
			helpful_el_msg.html(user_msg).fadeIn('fast').delay(1200).fadeOut('slow');
		}
	});
	
	evt.stopPropagation();
	evt.preventDefault();
}

function drVoteBadge(event, badge_id) {
	var self = this;
	
	$(event.target).css({"border":"2px solid #69cdcf"});

	// $(event.target).removeAttr('onclick');
	$(event.target).unbind();
	
	if(badgeVoteCount > 0){
		$.ajax({
			type: "POST",
			url: "/api/dr/vote_badge?dr_id=" + $('#dr_id').val() + "&badge_id=" + badge_id,
			success: function(msg) {
				 if (! msg.voted) {
					alert("Error: " + msg.message);

					if (msg.fatal) {
						$("#dialog_badge_vote").dialog('close');
						badgeVoteCount = 0;
					}
				   
					return;
				 } else {
					badgeVoteCount--;
					
					$("#badge_votes_remaining").text(badgeVoteCount);
					
					if (badgeVoteCount == 0) {
						// you done run out of votes yo
						$("#dialog_badge_vote").dialog('close');
					}
				}
			}
		});
	}
}

function drRefreshBadges() {
	// update badge votes display 
	$.ajax({
		type: "GET",
		url: '/badge/dr_list?dr_id=' + $('#dr_id').val(),
		success: function (new_badges) {
			$("#dr_badge_list").hide(1);
			$("#dr_badge_list").html(new_badges);
			$("#dr_badge_list").delay(1000).fadeIn("slow");
					
			if (! badgeVoteCount){
				$("#badges_vote").hide();
			}
		}
	});
}