function goBlankOnFocus(field, originalValue) {
	if(field.value == originalValue) {
		field.value = "";
		field.style.color = "black";
	}
}

function restoreOnBlur(field, originalValue) {
	if(field.value == '') {
		field.value = originalValue;
		field.style.color = "#777";
	}
}

function initAutocomplete(id, url) {
	$(id).focus(function(){
		$('#ajaxMessage').html("");
	}).blur(function(){
		$('#ajaxMessage').html("Loading data...");
	}).autocomplete(url);
}

function imposeMaxLength(object, maxLength) {
  return (object.value.length <= maxLength);
}

function showResponse(responseText, statusText)  { 
	$("form input").removeAttr("disabled");
	$("form textarea").removeAttr("disabled");
	$("form select").removeAttr("disabled");
	
	responseObject = eval('(' + responseText + ')');
	if(responseObject.msg.length > 0) alert(responseObject.msg);
	
	return responseObject;
}

function prepareForSubmit(ajaxMsg) {
	$('#ajaxMessage').html(ajaxMsg);
	$("form input").attr("disabled", "disabled");
	$("form textarea").attr("disabled", "disabled");
	$("form select").attr("disabled", "disabled");
	
	return true;
}

function hideFlashMessage() {
	$("#flashMessage").fadeOut("slow");
}

function updateFlashMessage(displayValue, displayClass, position) {
	if(position == undefined) position = "inline";

	if(displayValue != "") {
		if(position == "absolute") {
			$("#flashMessage").css("top", $(window).scrollTop() + "px");
		}
		
		$("#flashMessage").css("z-index", "100");
		$("#flashMessage").css("position", position);
		$("#flashMessage").css("width", "100%");
		//$("#flashMessage").css("left", "0");
		//$("#flashMessage").css("right", "0");
		//$("#flashMessage").css("text-align", "center");
		$("#flashMessage").fadeIn("slow");
		$("#flashMessage").html("<center><div class='"+displayClass+"'>"+displayValue+"</div></center>");
	}
	else {
		$("#flashMessage").html("");
	}
}

function redirect(url) {
	location.href = url;
}

function isValidEmail(emailAddress) {
	apos = emailAddress.indexOf("@");
	dotpos = emailAddress.lastIndexOf(".");
	if(apos < 1 || dotpos-apos < 2) {
		return false;
	}
	
	return true;
}

var currentHash = "";
var pageNum = 1;

/** monitors the hash tag to see if there's been any updates */
function checkHashChanges(updateCallBack) {
	if(currentHash != window.location.hash) {
		currentHash = window.location.hash;
		updateCallBack();
	}
}

$(document).ready(function(){
	if(window.location.hash.length > 0) {
		var params = parseHashValues(window.location.hash);
		pageNum = params["page"];
	}
});

/** parses the hash value from the url into a key/value array */
function parseHashValues(hash) {
	var arr = new Array();
	if(hash.indexOf("&") > -1) {
		var keyValues = hash.split("&");
		for(var i = 0; i < keyValues.length; i++) {
			var temp = keyValues[i].split(":");
			if(temp[0].charAt(0) == "#") {
				temp[0] = temp[0].substr(1);
			}
			
			arr[temp[0]] = temp[1];
		}
	}
	
	return arr;
}

function initSearchPage() {
	var hashValues = parseHashValues(currentHash);
	for(key in hashValues) {
		if(key != "searchText" && key != "page" && key != "tab") {
			$("#"+key).val(hashValues[key]);
		}
		else if(key == "page") {
			pageNum = hashValues[key];
		}
	}
}

function removeHashItem(key) {
	var hash = window.location.hash;
	startIndex = hash.indexOf("&"+key);
	if(startIndex > -1) {
		endIndex = hash.indexOf("&", startIndex+1);
		if(endIndex == -1) endIndex = hash.length;
		hash = hash.substr(0, startIndex) + hash.substr(endIndex, hash.length - endIndex);
	}
	
	return hash;
}

/** inititalizes defaults for any search list used on the site */
function initSearchList(replacementId, confirmationMsg, ajaxMsg, updateCallBack) {
	// create hover color effect
	$("div.list-Panel").bind("mouseenter",function(){
		$(this).addClass("list-Panel-Alt");
	}).bind("mouseleave",function(){
		$(this).removeClass("list-Panel-Alt");
	});
	
	// force paging links to update via ajax
	$("#pagingPanel a").click(function(e) {
		var href = $(this).attr("href");
		var startIndex = href.indexOf("page");
		if(startIndex > -1) {
			var endIndex = href.indexOf("/", startIndex);
			startIndex += 5;
			var pageNum = href.substr(startIndex, endIndex - startIndex);
			
			var hash = removeHashItem("page");
	
			window.location.hash = hash + "&page:"+pageNum;
		}
		
		performPageUpdate($(this).attr("href"), replacementId);
		e.preventDefault();
	});
	
	// hijack deletion links and use ajax to delete
	$("div.list-Panel").find("a.deleteItem").click(function(e) {
		e.preventDefault();
		
		var url = $(this).attr("href");
		
		var deleteItem = confirm(confirmationMsg);
		if(deleteItem) {
			$('#ajaxMessage').html(ajaxMsg);
		
			$.ajax({
			   	type: "POST",
			   	url: url,
			   	success: function(response) {
			   		var o = eval('(' + response + ')');
			   		
			   		if(o.error == "") {
			   			currentHash = "";
			   	 		updateCallBack();
			   	 	}
			   	 	
			   	 	updateFlashMessage(o.msg, "infoPanel", "absolute");
			   	 	
			   	 	// hide the flash message after 3 seconds
					setTimeout("hideFlashMessage()", 3000);
			   }
			});
		}
	});
}

/** updates the given replacementId div layer with the contents of url */
function performPageUpdate(url, replacementId, scrollToTop) {
	$.ajax({
		type: "POST",
	   	url: url,
	   	beforeSend: function() { 
	   		if(scrollToTop == null || scrollToTop) {
	   			$('html, body').animate({scrollTop:0}, 'fast');
	   		} 
	   	},
	   	success: function(html) {
	   	 	// update the list div
	   	 	$("#"+replacementId).html(html);
	   	}
	});
}

function initTooltips(tooltipClass, width) {
	// Use the each() method to gain access to each elements attributes
  	$('a.'+tooltipClass).each(function() {
      $(this).qtip( {
         content: {
            // Set the text to an image HTML string with the correct src URL to the loading image you want to use
            text: 'Loading...',
            url: $(this).attr('rel'), // Use the rel attribute of each element for the url to load
            title: {
               text: $(this).text(), // Give the tooltip a title using each elements text
               button: 'Close' // Show a close link in the title
            }
         },
         position: {
            corner: {
               target: 'bottomMiddle', // Position the tooltip above the link
               tooltip: 'topMiddle'
            },
            adjust: {
               screen: true // Keep the tooltip on-screen at all times
            }
         },
         show: 'mouseover',
         hide: 'mouseout',
         style: {
            tip: true, // Apply a speech bubble tip to the tooltip at the designated tooltip corner
            border: {
               width: 0,
               radius: 4
            },
            name: 'light', // Use the default light style
            width: width // Set the tooltip width
         }
      })
   });
}

function initTwitterLink(data) {
	$('#tweet input.basic, #tweet a.basic').click(function (e) {
		e.preventDefault();
		
		var text = escape(data);
		
		$.ajax({
		   type: "POST",
		   url: "/users/tweet/"+text,
		   success: function(html){
		   	 // update the hidden div layer to contain the form information
		   	 $("#tweetFormModal").html(html);
		   	 
		   	 $("#tweetFormModal").css("overflow", "hidden");
		   	 
		   	 // show the modal form
		   	 $('#tweetFormModal').modal();
			 $('#simplemodal-container').css("height", "360px");
			 $('#simplemodal-container').css("width", "560px");
		   }
		});
	});
}

function checkReminders() {
	var prevMsg = $('#ajaxMessage').html();
	$('#ajaxMessage').html("");
		
	$.ajax({
		type: "POST",
	   	url: "/goals/showreminders",
	   	success: function(html) {
	   		if(html.length > 0) {
	   	 		// update the hidden div layer to contain the form information
			   	$("#goalReminder").html(html);
			   	 
			   	$("#goalReminder").css("overflow", "hidden");
			   	 
			   	// show the modal form
			   	$('#goalReminder').modal();
				$('#simplemodal-container').css("height", "360px");
				$('#simplemodal-container').css("width", "560px");
				
				$('#ajaxMessage').html(prevMsg);
			}
	   	}
	});
}