$(document).ready(function() {
	hideNavElements();
	hideSearchSubmitText();
	clearSearchTerm();
	applyRollovers();
	
	var defaultLogin = 'E-mail address';
	$('#loginEmail').live('focus', function(){
		if ($(this).val() == defaultLogin)	$(this).val('');
	}).bind('blur', function(){
		if ($(this).val() == '')	$(this).val(defaultLogin);
	});
	
	$('#loginPass_placeholder').live('focus', function(){
		$(this).hide();
		$('#loginPass').show();
		$('#loginPass').focus();
	});
	$('#loginPass').live('blur', function(){
		if ($(this).val() == '') {
			$(this).hide();
			$('#loginPass_placeholder').show();
		}
	});
	
	$('#loginForm').live('submit', ajaxLogin);
	$('#logoutLink').live('click', ajaxLogout);
	
	$('#searchTerm, #linkTerm').bind('keyup', function() {
		$.cookie('CakeCookie[searchTerm]', $(this).val(), { expires:this.cookieExpire, domain:'.gemsta.com', path:'/' });
	});
	
	// Homepage and help left column buttons
	$('#leftCol #homepage a').bind('click', function() {
		this.blur();
		
		if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)) {
			this.setHomePage('http://www.gemsta.com');
		}
		else {
			alert('This feature only works in Internet Explorer. Please manually set Gemsta.com to your homepage.');
		}
		
		return false;
	});
	
	$('#leftCol #help').bind('click', function() {
		window.location.href = 'http://search.gemsta.com/help';
	});
	
	$('#resetSearch').bind('click', function() {
		$.cookie('CakeCookie[searchTerm]', '', { expires: -1, domain:'.gemsta.com', path:'/' });
	});
});

function ajaxLogin() {
	var dataString = $('#loginForm').serialize();
	var oldHtml = $('#loginArea').html();
	
	$('#loginArea').html('<div id="loading"><img src="/img/mygemsta-load-login.gif" alt="Loading" /></div>');
	
	$.ajax({
		type: 'POST',
		url: '/signin',
		data: dataString,
		success: function(response) {
			if (response.search('Unauthenticated user: ') < 0 && response.length > 0) {
				window.location.reload();
			}
			else {
				$('#loginArea').html(oldHtml);
				alert('Invalid Login Credentials');
			}
		},
		error: function(response, errtype, e) {
			$('#loginArea').html(oldHtml);
		}
	});
	
	return false;
}

function ajaxLogout() {
	var oldHtml = $('#loggedIn').html();
	
	$('#loggedIn').html('<div id="loading"><img src="/img/mygemsta-load-login.gif" alt="Loading" /></div>');
	
	$.ajax({
		url: '/signout',
		success: function(response) {
			window.location.reload();
		},
		error: function(request, errtype, e) {
			$('#loggedIn').html(oldHtml);
		}		
	});
	
	return false;
}

function ajaxGetName() {
	var oldHtml = $('#loggedIn').html();
	
	$.ajax({
		url: '/getName',
		success: function(response) {
			$('#loggedIn #logout #uName').html(response);
			$('#loginArea').hide();
			$('#loggedIn').show();
			
			$('#loginArea').html(oldHtml);
		}
	});
}

function ajaxSetSession() {
	$.ajax({
		url: '/setUserSession',
		success: ''
	});
}

function hideNavElements()
{
	$('a.mainnavlk').text('');
}

function hideSearchSubmitText()
{
	$('#search_submit').val('');
}

function clearSearchTerm()
{
	$('#search_term').bind("focus", function()
	{
		$(this).val('');
	});
}

function applyRollovers()
{
	$("img.roll").hover(
		function() {
			this.src = this.src.replace("-off","-on");
		},
		function() {
			this.src = this.src.replace("-on","-off");
		}
	);
}

function dump(arr,level) {
	var dumped_text = "";
	if(!level) level = 0;
	
	//The padding given at the beginning of the line.
	var level_padding = "";
	for(var j=0;j<level+1;j++) level_padding += "    ";
	
	if(typeof(arr) == 'object') { //Array/Hashes/Objects 
		for(var item in arr) {
			var value = arr[item];
			
			if(typeof(value) == 'object') { //If it is an array,
				dumped_text += level_padding + "'" + item + "' ...\n";
				dumped_text += dump(value,level+1);
			} else {
				dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
			}
		}
	} else { //Stings/Chars/Numbers etc.
		dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
	}
	return dumped_text;
}

function urlencode (str) {
    str = (str + '').toString();
    str = encodeURIComponent(str).replace(/!/g, '%21').replace(/'/g, '%27').replace(/\(/g, '%28').replace(/\)/g, '%29').replace(/\*/g, '%2A').replace(/%20/g, '+').replace(/&/g, '%26').replace(/"/g, '%22').replace(/\?/g, '%3F');
    return str;
}

function isNumeric(sText) {
   var ValidChars = "0123456789.";
   var IsNumber=true;
   var Char;
   
   for (i = 0; i < sText.length && IsNumber == true; i++) { 
	   Char = sText.charAt(i); 
	   if (ValidChars.indexOf(Char) == -1) {
		   IsNumber = false;
       }
   }
   return IsNumber;
   
}


String.prototype.ucwords = function(){
    return this.replace(/\w+/g, function(a){
        return a.charAt(0).toUpperCase() + a.substr(1).toLowerCase();
    });
};
