//Normal JavaScript funtions

function FBonConnected(user_id) { 
	$.ajax({
			type: "POST",
			url: "/login.php",
			data: "loginType=Facebook",
		success: function(xml){
			var len = $(xml).find("response").length;
			var responseTag = $(xml).find("response");
			var loginType = $(responseTag).attr("type");
			var loginMessage = $(responseTag).attr("message");
   				
   			if(loginType == "success"){
				window.location = "../index.php";
     		}
   			else {
  				window.location = "../index.php";
  			}
		}
	});
} 
		
function FBonNotConnected() { 
			
}

function installFFToolBar(aEvent)
{
  var params = {
    "LebWinks": { URL: aEvent.target.href,
             IconURL: aEvent.target.getAttribute("iconURL"),
             //Hash: aEvent.target.getAttribute("hash"),
             toString: function () { return this.URL; }
    }
  };
  InstallTrigger.install(params);

  return false;
}

//Will validate that the date was entered in the correct format
function validateDate()
{
	// Regular expression used to check if date is in correct format
	var pattern = /^\d{1,2}(\/)\d{1,2}\1\d{4}$/
	
	if( $("#signUpBirthDate").val().match(pattern) ) {
		$("#signUpFormError").html("");
	}
	else {
		$("#signUpFormError").html("<div class=\"lebWinksMessageError\">Date format is incorrect, please enter format like mm/dd/yyyy</div>");
	}
	
}

//Will Verify the passwords match
function verifyPasswords()
{
	var minLength = 6;
		if ( $("#signUpPassword").val().length < minLength) {
			$("#verifyPasswordResult").html("<div class=\"lebWinksMessageError\">Password is too short. Must be at least "+minLength+" characters</div>");
		}
		else {
			if ( $("#signUpPassword").val() != "" && $("#signUpPassword").val() == $("#vsignUpPassword").val()) {
	     		$("#verifyPasswordResult").html("<div class=\"lebWinksMessageSuccess\">Passwords match</div>");
	   		} else {
	     		$("#verifyPasswordResult").html("<div class=\"lebWinksMessageError\">Passwords do NOT match</div>");
	   		}
	   	}
}

//Will Verify the passwords match
function verifyPasswordsReset()
{
	var minLength = 6;
	if ( $("#newPassword").val().length < minLength) {
		$("#verifyResetPasswordResult").html("<div class=\"lebWinksMessageError\">Password is too short. Must be at least "+minLength+" characters</div>");
	}
	else {
		if ( $("#newPassword").val() != "" && $("#newPassword").val() == $("#vnewPassword").val()) {
     		$("#verifyResetPasswordResult").html("<div class=\"lebWinksMessageSuccess\">Passwords match</div>");
   		} else {
     		$("#verifyResetPasswordResult").html("<div class=\"lebWinksMessageError\">Passwords do NOT match</div>");
   		}
   	}
}

//Will get all of my shared websites. The websites that I am sharing with my friends
	function getMyWebsites()
	{
		$.ajax({
   			type: "POST",
   			url: "/webservice.php",
   			data: "request=<request><action>getMyWebsites</action><content></content></request>",
   			success: function(xml){
   				var websiteDataHeading = "<h3>My Latest Shared Websites</h3>";
   				var type = "";
   				printWebsiteData( $(xml), websiteDataHeading, type );
   			}
 		});
	}

	function printWebsiteData( xml, websiteDataHeading, type ){
		data = "<center>" + websiteDataHeading;
		data = data + "<div id=\"sharedWebsiteData\">";
		
		$(xml).find("friend").each(function()
		{
			
			if(type == "friend"){
				data = data + "<h2><a href=\"#\">";
			}
			data = data + "<strong>" + $(this).attr("friend") + "</strong> ";
			if(type == "friend"){
				data = data + "</a></h2>\n";
			}
			data = data + "<div id=\"friendWebsiteData\">";
			var sharedWebsites = $(this).attr("sharedWebsites");
			data = data + "<div class=\"hidden\" id=\"totalSharedWebsites\">"+sharedWebsites+"</div>";
			data = data + "has shared "+ sharedWebsites +" unique websites with their friends<br /><br />\n"
			
			data = data + "<br /><div id=\"selectedData\"></div><br />";
			
			data = data + "<table id=\"websitesData\" class=\"myData\">\n";
			
			if(type == "everyone")
				data = data + "<thead><th>Website</th><th>Shared By</th><th>Accessed</th><th>Tagged</th><th>Rating</th></thead>\n";
			else
				data = data + "<thead><th>Website</th><th>Accessed</th><th>Tagged</th><th>Rating</th></thead>\n";
		
			$(xml).find("site").each(function()
			{
				var timesAccessed = $(this).attr("timesAccessed");
				var timesTagged = $(this).attr("tagged");
				var rating = $(this).attr("rating");
				if(type == "everyone") {
					data = data + "<tr><td align=\"left\">"+$(this).text()+"</td><td></td><td>" + timesAccessed + "</td><td>" + timesTagged + "</td><td>" + rating + "</td></tr>";
				}
				else {
					data = data + "<tr><td align=\"left\">"+$(this).text()+"</td><td>" + timesAccessed + "</td><td>" + timesTagged + "</td><td>" + rating + "</td></tr>";
				}
			});		
			data = data + "</table>";
			data = data + "</div>";
		});
		
		
		data = data + "</div></center>";
		
		$("#boxContent").html(data);
		

		$(function() {
			$("#websitesData").selectable({
				stop: function(){
					$(".ui-selected", this).each(function(){
						var selectedWebsite=$(this).find("td").eq(0).html();
						var selectedData = "<div id=\"selectedWebsite\" name=\"selectedWebsite\">"+selectedWebsite+"</div><br /><a href=" + selectedWebsite + " target=\"_blank\" class=\"button\" >Go To Site</a>&nbsp;&nbsp;"+
						"<a href=\"#\" class=\"button\" onclick=\"addCommentAction('"+selectedWebsite+"')\">Comment on Site</a>&nbsp;&nbsp;"+
						"<a href=\"#\" class=\"button\" onclick=\"tagWebsite('"+selectedWebsite+"')\">Tag Site</a>&nbsp;&nbsp;"+
						"<select id=\"myWebsiteRating\" class=\"ui-corner-all\">"+
						"<option value=\"1\" >1</option><option value=\"2\" SELECTED>2</option><option value=\"3\" >3</option><option value=\"4\" >4</option><option value=\"5\" >5</option>"+
						"</select>"+
						"<a href=\"#\" class=\"button\" onclick=\"updateWebsiteRating('"+selectedWebsite+"')\">Update Rating</a>&nbsp;&nbsp;"+
						"<a href=\"#\" class=\"button\" onclick=\"blockWebsite('"+selectedWebsite+"')\">Block Site</a>&nbsp;&nbsp;"+
						"<a href=\"#\" class=\"button\" onclick=\"getWebsiteDetails('"+selectedWebsite+"')\">View Details</a>&nbsp;&nbsp;"+
						"<a href=\"#\" class=\"button\" onclick=\"reportSiteInappropriateContent('"+selectedWebsite+"')\">Report Inappropriate Content</a>&nbsp;&nbsp;";
						$("#selectedData").html(selectedData);
					});
				}
			});
		});
		
		return $(xml).find("site").length;
	}

	function addCommentAction(website)
	{
		//$("#actionBox").html("<div id=\"addCommentBox\" align=\"right\"><br>Add a comment to the website "+website+"<br><form id=\"addCommentForm\">comment:<input type=\"text\" size=\"45\" name=\"addCommentText\" id=\"addCommentText\" /><br /><br /></form></div>");

		$("#addCommentBox").dialog({
			title: 'Add Comment', 
   			bgiframe: true,
   			modal: true, 
			overlay: {
				backgroundColor: '#000',
				opacity: 0.5
			},
   			buttons: {
   				'Cancel': function() { 
   					$(this).dialog('close');
   				}, 
   				'Add Comment': function() { 
   					var comment = $("#addCommentText").val();
 					addComment(website, comment);
 					$(this).dialog('close');
 					$("#addCommentText").attr('value', '');
   				} 
   			}, 
    		position: ['150', '200']
		});
		$("#addCommentBox").dialog("open");
	}
	
	function addComment(website, comment)
	{
		$.ajax({
	   		type: "POST",
	   		url: "/webservice.php",
	   		data: "request=<request><action>addComment</action><content><website><![CDATA[" + encodeURIComponent (website) + "]]></website><comment><![CDATA[" + encodeURIComponent (comment) + "]]></comment></content></request>",
	   		success: function(xml){
	   			var len = $(xml).find("response").length;
   				var responseTag = $(xml).find("response");
   				var type = $(responseTag).attr("type");
   				var message = $(responseTag).attr("message");
   				
     			if(type == "success"){
     				displayLebWinksMessage("", message, "lebWinksMessageSuccess");
					location.reload(true);
				}
     			else {
     				displayLebWinksMessage("", message, "lebWinksMessageError");
     			} 
	   		}
	 	});				
	}
	
	function removeComment(commentID)
	{
		$.ajax({
	   		type: "POST",
	   		url: "/webservice.php",
	   		data: "request=<request><action>removeComment</action><content>"+commentID+"</content></request>",
	   		success: function(xml){
	   			var len = $(xml).find("response").length;
   				var responseTag = $(xml).find("response");
   				var type = $(responseTag).attr("type");
   				var message = $(responseTag).attr("message");
   				
     			if(type == "success"){
     				displayLebWinksMessage("", message, "lebWinksMessageSuccess");
     				getMyWebsites();
				}
     			else {
     				displayLebWinksMessage("", message, "lebWinksMessageError");
     			} 
	   		}
	 	});				
	}
	
	function editComment(commentID)
	{
		$.ajax({
	   		type: "POST",
	   		url: "/webservice.php",
	   		data: "request=<request><action>removeComment</action><content>"+commentID+"</content></request>",
	   		success: function(xml){
	   			var len = $(xml).find("response").length;
   				var responseTag = $(xml).find("response");
   				var type = $(responseTag).attr("type");
   				var message = $(responseTag).attr("message");
   				
     			if(type == "success"){
     				displayLebWinksMessage("", message, "lebWinksMessageSuccess");
     				getMyWebsites();
				}
     			else {
     				displayLebWinksMessage("", message, "lebWinksMessageError");
     			} 
	   		}
	 	});				
	}
	
	function tagWebsite(website)
	{
		$.ajax({
	   		type: "POST",
	   		url: "/webservice.php",
	   		data: "request=<request><action>tagSite</action><content><![CDATA[" + encodeURIComponent (website) + "]]></content></request>",
	   		success: function(xml){
	   			var len = $(xml).find("response").length;
   				var responseTag = $(xml).find("response");
   				var type = $(responseTag).attr("type");
   				var message = $(responseTag).attr("message");
   				
     			if(type == "success"){
     				displayLebWinksMessage("", message, "lebWinksMessageSuccess");
     				getMyWebsites();
				}
     			else {
     				displayLebWinksMessage("", message, "lebWinksMessageError");
     			} 
	   		}
	 	});
	}

	function updateWebsiteRating(website)
	{
		var rating = $("#myWebsiteRating :selected").val();
	
		$.ajax({
	   		type: "POST",
	   		url: "/webservice.php",
	   		data: "request=<request><action>updateWebsiteRating</action><content><website><![CDATA[" + encodeURIComponent (website) + "]]></website><rating>"+rating+"</rating></content></request>",
	   		success: function(xml){
	   			var len = $(xml).find("response").length;
   				var responseTag = $(xml).find("response");
   				var type = $(responseTag).attr("type");
   				var message = $(responseTag).attr("message");
   				
     			if(type == "success"){
     				displayLebWinksMessage("", message, "lebWinksMessageSuccess");
     				getMyWebsites();
				}
     			else {
     				displayLebWinksMessage("", message, "lebWinksMessageError");
     			} 
	   		}
	 	});
	}

	function blockWebsite(website)
	{
		$.ajax({
	   		type: "POST",
	   		url: "/webservice.php",
	   		data: "request=<request><action>blockSite</action><content><![CDATA[" + encodeURIComponent (website) + "]]></content></request>",
	   		success: function(xml){
	   			var len = $(xml).find("response").length;
   				var responseTag = $(xml).find("response");
   				var type = $(responseTag).attr("type");
   				var message = $(responseTag).attr("message");
   				
     			if(type == "success"){
     				displayLebWinksMessage("", message, "lebWinksMessageSuccess");
     				getMyWebsites();
				}
     			else {
     				displayLebWinksMessage("", message, "lebWinksMessageError");
     			} 
	   		}
	 	});
	}
	
	function getWebsiteDetails(website)
	{
		$.ajax({
	   		type: "POST",
	   		url: "/webservice.php",
	   		data: "request=<request><action>getWebsiteDetails</action><content><website><![CDATA[" + encodeURIComponent (website) + "]]></website></content></request>",
	   		success: function(xml){
	   			var len = $(xml).find("websiteDetails").length;
   				var responseTag = $(xml).find("websiteDetails");
   				var totalTagged = $(xml).find("websiteDetails").attr("totalTagged");
   				var totalTimesAccessed = $(xml).find("websiteDetails").attr("totalTimesAccessed");
   				var averageRating = $(xml).find("websiteDetails").attr("averageRating");
   				
   				var data = "<div>";
   				data = data + "Liked "+totalTagged+"<br />";
   				data = data + "Times shared "+totalTimesAccessed+"<br />";
   				data = data + "Average Rating "+averageRating+"<br />";
   				
   				data = data + "<h3>Friends</h3>";
   				$(xml).find("friends").each(function()
	   			{
	   				var totalFriends = $(this).attr("totalFriends");
	   				data = data + "There are "+totalFriends+" friends that have shared this website<br />";
	   				data = data + "<table class=\"myData\">\n";
   					data = data + "<tr><th>Friend</th><th>Liked</th><th>Rating</th><th>Times Accessed</th></tr>\n";
	   				
	   				$(xml).find("friend").each(function()
	   				{
	   					var friendName = $(this).text();
   						var tagged = $(this).attr("tagged");
   						var rating = $(this).attr("rating");
   						var timesAccessed = $(this).attr("timesAccessed");
	   					data = data + "<tr><td>"+friendName+"</td><td>"+tagged+"</td><td>"+rating+"</td><td>"+timesAccessed+"</td></tr>";
	   				});		
	   			});
   				
   				data = data + "</table><br /><h3>Comments</h3>";
   				
	    		$(xml).find("comments").each(function()
	   			{
	   				var totalComments = $(this).attr("totalComments");
					data = data + "There are "+totalComments+" comments for this website<br />";
	   				data = data + "<table class=\"myData\">\n";
   					data = data + "<tr><th style=\"display:none;\">Comment ID</th><th>Author</th><th>Timestamp</th><th>Comment</th></tr>\n";
	   				
	   				$(xml).find("comment").each(function()
	   				{
	   					var comment = $(this).text();
	   					var author = $(this).attr("author");
   						var timestamp = $(this).attr("timestamp");
   						var commentID = $(this).attr("commentID");
	   					data = data + "<tr><td style=\"display:none;\">"+commentID+"</td><td>"+author+"</td><td>"+timestamp+"</td><td>"+comment+"</td></tr>";
	   				});		
	   			});
	   			
	   			data = data + "</table>";
	   			data = data + "</div>";
	   			$("#boxContent").html("<center><h1>"+website+"</h1>"+data+"</center>");
	   		}
	 	});
	}
	
	function miniDisplayCommentGetter(weblink, miniDisplayCommentID, actionType)
	{
		
		$.ajax({
	   		type: "POST",
	   		url: "/webservice.php",
	   		data: "request=<request><action>"+actionType+"</action><content><website><![CDATA[" + encodeURIComponent (weblink) + "]]></website></content></request>",
	   		success: function(xml){
	   			
	    		$(xml).find("comments").each(function()
	   			{
	   				var totalComments = $(this).attr("totalComments");
	   				var data = "<div>";
	   				
	   				data = data + "<div class=\"myData\">\n";
   					//data = data + "<tr style=\"display:none;\"><th>Comment ID</th><th style=\"font-size:12px;\">Submitted By</th><th style=\"font-size:12px;\">When</th><th style=\"font-size:12px;\">Comment</th></tr>\n";
	   				
	   				$(xml).find("comment").each(function()
	   				{
	   					var comment = $(this).text();
	   					var author = $(this).attr("author");
   						var timestamp = $(this).attr("timestamp");
   						var commentID = $(this).attr("commentID");
	   					//data = data + "<tr><td style=\"display:none;\">"+commentID+"</td><td style=\"font-size:11px;\">Submitted by "+author+" "+timestamp+"</td><td style=\"display:none;\">"+timestamp+"</td><td style=\"font-size:12px;\">"+comment+"</td></tr>";
	   					data = data + "<div style=\"font-size:11px; margin-bottom:5px; color:#7ca0c3;\">"+author+" "+timestamp+"</div><div style=\"font-size:11px; margin-left:15px; margin-bottom:5px;\">"+comment+"</div>";
	   				});		
	   				data = data + "</div>";
	   				data = data + "</div>";
	   			
	   				$("#"+miniDisplayCommentID).html(data);
	   				
	   			});
	   			
	   		}
	 	});
	}
	
	function reportSiteInappropriateContent(website)
	{
		$.ajax({
	   		type: "POST",
	   		url: "/webservice.php",
	   		data: "request=<request><action>reportSiteInappropriateContent</action><content><![CDATA[" + encodeURIComponent (website) + "]]></content></request>",
	   		success: function(xml){
	   			var len = $(xml).find("response").length;
   				var responseTag = $(xml).find("response");
   				var type = $(responseTag).attr("type");
   				var message = $(responseTag).attr("message");
   				
     			if(type == "success"){
     				displayLebWinksMessage("", message, "lebWinksMessageSuccess");
     				getMyWebsites();
				}
     			else {
     				displayLebWinksMessage("", message, "lebWinksMessageError");
     			} 
	   		}
	 	});
	}

//Gets all the latest visited websites
	function getLatestWebsites(startingNumber)
	{		
		$.ajax({
	   		type: "POST",
	   		url: "/webservice.php",
	   		data: "request=<request><action>getLatestWebsites</action><content>"+startingNumber+"</content></request>",
	   		success: function(xml){
	   			var websiteDataHeading = "<h3>Everyone's Latest Shared Websites</h3>";
	   			var type = "everyone";
   				var currentDisplay = printWebsiteData( $(xml), websiteDataHeading, type );
   				
	   			//var data = "<div>";
	    		//$(xml).find("friend").each(function()
	   			//{
	   				//data = data + "<table class=\"selectable\">\n";
   					//data = data + "<tr><th>Website</th><th>Times Accessed</th><th>Times Tagged</th><th>Rating</th></tr>\n";
	   				
	   				//$(xml).find("site").each(function()
	   				//{
	   					//var timesAccessed = $(this).attr("timesAccessed");
   						//var timesTagged = $(this).attr("tagged");
   						//var rating = $(this).attr("rating");
	   					//data = data + "<tr><td><a href=http://" + $(this).text() + " target=\"_blank\">" + $(this).text() + "</a></td><td>" + timesAccessed + "</td><td>" + timesTagged + "</td><td>" + rating + "</td></tr>";
	   				//});		
	   			//});
	   			
	   			//data = data + "</table>";
	   			//data = data + "</div>";
	   			//$("#boxContent").html("Check out everyone's latest websites shared! "+data);
	   			
	   			//Get the current display number
	   			var defaultSelected = 20;
	   			var currentStart = $("#websiteStartingNumber").text()+1;
	   			var currentEnd = defaultSelected;
	   			var totalSharedWebsites = $("#totalSharedWebsites").text();
	   			for(i=0; i<totalSharedWebsites/defaultSelected; i++)
				{
	   				$("#boxContent").append("<a href=\"#\" id=\"websiteStarter\">"+currentStart+"-"+currentEnd+" </a>");
	   				currentStart = currentEnd + 1;
	   				if(currentStart+defaultSelected < totalSharedWebsites)
	   					currentEnd = currentEnd + defaultSelected;
	   				else
	   					currentEnd = totalSharedWebsites;
	   			}
	   		}
	 	});
	}

//Gets all the most popular websites
	function getMostPopularWebsites()
	{
		$.ajax({
	   		type: "POST",
	   		url: "/webservice.php",
	   		data: "request=<request><action>getMostPopularWebsites</action><content></content></request>",
	   		success: function(xml){
	   			var websiteDataHeading = "<h3>Everyone's Most Popular Shared Websites</h3>";
	   			var type = "";
   				var currentDisplay = printWebsiteData( $(xml), websiteDataHeading, type );
   				
	   			//var data = "<div>";
	    		//$(xml).find("friend").each(function()
	   			//{
	   				//data = data + "<table class=\"selectable\">\n";
   					//data = data + "<tr><th>Website</th><th>Times Accessed</th><th>Times Tagged</th><th>Rating</th></tr>\n";
	   				
	   				//$(xml).find("site").each(function()
	   				//{
	   					//var timesAccessed = $(this).attr("timesAccessed");
   						//var timesTagged = $(this).attr("tagged");
   						//var rating = $(this).attr("rating");
	   					//data = data + "<tr><td><a href=http://" + $(this).text() + " target=\"_blank\">" + $(this).text() + "</a></td><td>" + timesAccessed + "</td><td>" + timesTagged + "</td><td>" + rating + "</td></tr>";
	   				//});		
	   			//});
	   			
	   			//data = data + "</table>";
	   			//data = data + "</div>";
	   			//$("#boxContent").html("Check out everyone's most popular websites shared! "+data);
	   			
	   			var currentStart = $("#websiteStartingNumber").text()+1;
	   			var currentEnd = currentDisplay;
	   			for(i=0; i<5; i++)
				{
	   				$("#boxContent").append("<a href=\"#\" id=\"websiteStarter\">"+currentStart+"-"+currentEnd+" </a>");
	   				currentStart = currentEnd + 1;
	   				currentEnd = currentEnd + currentDisplay;
	   			}
	   		}
	 	});
	}

//Will get LebWinks Terms of Service
	function getTOS(){
		$.ajax({
   			type: "GET",
   			url: "eula_beta.php",
   			success: function(data){
     			$("#actionBox").html("<div class=\"legal\" id=\"tosPage\"><code>" + data + "</code></div>");
     			$("#tosPage").dialog({
	 				title: 'LebWinks Terms of Service', 
	     			bgiframe: true,
	     			width: 900,
	     			height: 700,
					overlay: {
						backgroundColor: '#000',
						opacity: 0.5
					},
	     			buttons: {
	     				'Ok': function() { 
	     					$(this).dialog('close');
	     				}
	     			}
	     		});
   			}
 		});
	}

//Will get LebWinks Privacy Policy
	function getPrivacyPolicy()
	{
		$.ajax({
   			type: "GET",
   			url: "privacy.php",
   			success: function(data){
     			$("#actionBox").html("<div class=\"legal\" id=\"privacyPolicyPage\"><code>" + data + "</code></div>");
     			$("#privacyPolicyPage").dialog({
	 				title: 'LebWinks Privacy Policy', 
	     			bgiframe: true,
	     			width: 900,
	     			height: 700,
					overlay: {
						backgroundColor: '#000',
						opacity: 0.5
					},
	     			buttons: {
	     				'Ok': function() { 
	     					$(this).dialog('close');
	     				}
	     			}
	     		});
   			}
 		});
	}

//Sign Up the User for awesomeness
	function signUpUser()
	{
		if($("#signUpFormModal").dialog("isOpen")){
     	}
     	else{
     		$("#signUpFormModal").dialog({
     			title: 'Sign Up for LebWinks Awesomeness', 
     			draggable: false,
     			resizable: false,
     			modal: true,
     			//width: 500,
				overlay: {
					"backgroundColor": "#000",
					"opacity": ".5"
				},
     			buttons: {
     				'Cancel': function() { 
     					$(this).dialog('close');
     				}, 
     				'Agree and SignUp': function() { 
     					//Verify the user accepted the terms
     					if($("#signUpAgreement").is(':checked')) {
	     					//Get Today's date
	     					var todaysDate=new Date();
	     					var todayYear=todaysDate.getFullYear();
	     					var todayMonth=todaysDate.getMonth();
	     					var todayDay=todaysDate.getDate();
	     					
	     					var splitUserDate = $("#signUpBirthDate").val().split('/');
	     					
	     					/* the minumum age you want to allow in */
							var minAge = 13;     	
	     					var checkDate = new Date((parseInt(splitUserDate[2]) + parseInt(minAge)), splitUserDate[0], splitUserDate[1]);
	     					
	     					if(checkDate>todaysDate){
	     						//You are a minor
	     						$("#signUpFormError").html("<div class=\"lebWinksMessageError\">Sorry dude too young! You aren't 13 :P</div>");
	     					}
	     					else{
	     						//You aren't too young
	     						$.ajax({
		   							type: "POST",
		   							//datatype: "xml";
		   							url: "/webservice.php",
		   							data: "request=<request><action>createUser</action><content><userName>"+$("#signUpUser").val()+"</userName><password>"+$("#signUpPassword").val()+"</password><userEmail>"+$("#signUpEmail").val()+"</userEmail><minor>N</minor></content></request>",
		   						success: function(xml){
									var len = $(xml).find("response").length;
					   				var responseTag = $(xml).find("response");
					   				var loginType = $(responseTag).attr("type");
					   				var loginMessage = $(responseTag).attr("message");
					   								   				
					     			if(loginType == "success"){
					     				displayLebWinksMessage("", message, "lebWinksMessageSuccess");
									}
					     			else {
					     				$("#signUpFormError").html("<div class=\"lebWinksMessageError\">"+loginMessage+"</div>");
					     			}
					   			}
					 			});
	     					
	     					
	     					}
     					}
     					else {
     						$("#signUpFormError").html("<div class=\"lebWinksMessageError\">To use LebWinks you must have read and accepted the Terms of Use and Privacy Policy</div>");
     					}
     					
     				}
     			}, 
     			position: ['150', '200']
     		});
     		$("#signUpFormModal").dialog("open");
     		$('#signUpBirthDate').datepicker({
     			yearRange: "-100:+0",
				changeMonth: true,
				changeYear: true,
				showOn: 'button', 
				buttonImage: 'images/calendar.gif', 
				buttonImageOnly: true
			});
     	}
	}
	
	//Login in the User via AJAX
	function loginUser(loginBox, user, password)
	{
		if($("#loginFormModal").dialog("isOpen")){
     		$("#loginFormModal").dialog("open");
     	}
     	else{
			$("#user").focus();
			
     		$("#loginFormModal").dialog({
     			title: 'Login to LebWinks', 
     			draggable: false,
     			resizable: false,
     			modal: true,
				overlay: {
					"backgroundColor": "#000",
					"opacity": "0.75",
					"-moz-opacity": "0.75"
				},
     			buttons: {
     				'Cancel': function() { 
     					$(this).dialog('close');
     				}, 
     				'Login': function() { 
     						rememberMe = "no";
							if($("#rememberMe").is(':checked'))
								rememberMe = "yes";
     						attemptLogin("1", $("#user").val(), $("#password").val(), rememberMe);
     				}
     			}, 
     			position: ['150', '50']
     		});
     		$("#loginFormModal").dialog("open");
     	}
	}
	
	//Will attempt to perform a login to the LebWinks Server
	function attemptLogin(loginBox, user, password, rememberMe)
	{
		if(rememberMe == "yes")
			loginData = "userEmail="+user+"&password="+password+"&rememberMe=yes";
		else
			loginData = "userEmail="+user+"&password="+password+"&rememberMe=no";
			
		$.ajax({
				type: "POST",
				//datatype: "xml";
				url: "/login.php",
				data: loginData,
			success: function(xml){
				var len = $(xml).find("response").length;
   				var responseTag = $(xml).find("response");
   				var loginType = $(responseTag).attr("type");
   				var loginMessage = $(responseTag).attr("message");
   				
     			if(loginType == "success"){
     				top.location="index.php";
				}
     			else {
     				//$("#loginFormModal").effect("shake", { times:1 });
     				if(loginBox == "1")
     					$("#loginFormError").html("<div class=\"lebWinksMessageError\">"+loginMessage+"</div>");
     				if(loginBox == "2")
     					$("#loginFormError2").html("<div class=\"lebWinksMessageError\">"+loginMessage+"</div>");
     			}
   			}
   		});
	}
	
	//Logout the User via AJAX
	function logoutUser()
	{
		$.ajax({
   			type: "POST",
   			url: "/logout.php",
   			data: "",
   			success: function(xml){
     			top.location="index.php";
   			}
 		});
	}
	
	function getRandomWebsiteFromSelf()
	{
		getRandomWebsiteMain("getRandomWebsiteFromSelf");
	}
	
	function getRandomWebsiteFromFriends()
	{
		getRandomWebsiteMain("getRandomWebsiteFromFriends");
	}
	
	function getRandomWebsite()
	{
		getRandomWebsiteMain("getRandomWebsite");
	}
	
	//get a random website and display it in a new tab
	function getRandomWebsiteMain(actionType)
	{	
		$.ajax({
		   	type: "POST",
		   	url: "/webservice.php",
		   	data: "request=<request><action>"+actionType+"</action><content></content></request>",
		   	success: function(xml){
				var responseTag = $(xml).find("response");
				var loginType = $(responseTag).attr("type");
				var message = $(responseTag).attr("message");
					
	 			if(loginType == "success"){
	 				window.open("http://"+message);
				}
	 			else
	 				displayLebWinksMessage("", message, "lebWinksMessageError");
		   		}
		 });
	}
	
	//View all my friends
	function viewFriends()
	{
		$.ajax({
   			type: "POST",
   			url: "/webservice.php",
   			data: "request=<request><action>getFriends</action><content></content></request>",
   			success: function(xml){
   				var data = "<center><h3>My Friends</h3><table id=\"viewMyFriends\" class=\"myData\">\n";
   				data = data + "<thead><th>UserName</th><th>Email Address</th><th>Accepted Friendship</th><th>Shared Websites</th></thead>";
     			$(xml).find("friend").each(function()
   				{
   					data = data + "<tr><td>" + $(this).attr("friend") + "</td><td>" + $(this).attr("friendEmail") + "</td><td>"+ $(this).attr("friendAccepted") +"</td><td>"+ $(this).attr("sharedWebsites") +" websites</td></tr>\n";
   				});
   				data = data + "</table></center><br /><br />";
   				$("#boxContent").html(data);
   				
   				$(function() {
   					$("#viewMyFriends").selectable();
   				});

   			}
 		});
	}
	
	//Get my Profile Settings
	function getProfileSettings()
	{
		$.ajax({
   			type: "POST",
   			url: "/webservice.php",
   			data: "request=<request><action>getProfileSettings</action><content></content></request>",
   			success: function(xml){
   				
   				var data = "<center><h3>My profile settings</h3>View and Edit your profile information<br /><br /><table class=\"myParagraph\">\n";
     			$(xml).find("user").each(function()
   				{
   					var defaultSelected = $(this).attr("numberOfURLsToDisplay");
   					data = data + 	"<tr><td>User Name</td><td><input type=\"text\" id=\"profileUserName\" class=\"ui-corner-all\" name=\"profileUserName\" value=\"" + $(this).attr("userName") + "\" /></td></tr>"+
   									"<tr><td>User Email</td><td>" + $(this).attr("userEmail") + "</td></tr>"+
   									"<tr><td>Date Registered</td><td>" + $(this).attr("dateRegistered") + "</td></tr>"+
   									"<tr><td>Last Accessed</td><td>" + $(this).attr("lastAccessed") + "</td></tr>"+
   									"<tr><td>Number Of URLs To Display</td><td>"+
   										"<select id=\"profileNumberOfURLsToDisplay\" class=\"ui-corner-all\">";
   					
   					var optionSelected = "";
   					if(defaultSelected == "10")				
   						optionSelected = "<option value=\"10\" SELECTED>10</option> <option value=\"20\" >20</option> <option value=\"30\" >30</option>";
   					if(defaultSelected == "20")				
   						optionSelected = "<option value=\"10\" >10</option> <option value=\"20\" SELECTED>20</option> <option value=\"30\" >30</option>";
   					if(defaultSelected == "30")				
   						optionSelected = "<option value=\"10\" >10</option> <option value=\"20\" >20</option> <option value=\"30\" SELECTED>30</option>";
   					
   					
   								
   					data = data + optionSelected;		
   											
   					data = data +		"</select></td></tr>";
   					if($(this).attr("minor")== "N"){
   						if($(this).attr("allowAdultContent") == "Y")
   							data = data + 	"<tr><td>Allow Adult Content</td><td><input type=\"checkbox\" id=\"profileAllowAdultContent\" name=\"profileAllowAdultContent\" checked=\"yes\"></td></tr>";
   						else
   							data = data + 	"<tr><td>Allow Adult Content</td><td><input type=\"checkbox\" id=\"profileAllowAdultContent\" name=\"profileAllowAdultContent\"></td></tr>";
   					}
   				});
   				data = data + "</table><br /><br />";
   				data = data + "<a class=\"button\" id=\"profileUpdateSettings\" href=\"#\"><img src=\"images/Clear Green Button.png\" alt=\"\" />Update Profile</a><br />";
   				data = data + "<img src=\"images/click_here.png\" alt=\"Click here\"></center>";
   				$("#boxContent").html(data);
   				
   				
   				$("#profileUpdateSettings").hover(function(){
					$("#profileUpdateSettings img")
        			.animate({top:"-10px"}, 200).animate({top:"-4px"}, 200) // first jump
            		.animate({top:"-7px"}, 100).animate({top:"-4px"}, 100) // second jump
            		.animate({top:"-6px"}, 100).animate({top:"-4px"}, 100); // the last jump
    			});
   				
   				
   			}
 		});
	}
	
	//Set my Profile Settings
	function setProfileSettings()
	{
		var allowAdultContent = "N";
		if($("#profileAllowAdultContent").is(':checked'))
			allowAdultContent = "Y";
		
		requestData = "request=<request><action>setProfileSettings</action><content><userName>"+$("#profileUserName").val()+"</userName><numberofURLstoDisplay>"+$("#profileNumberOfURLsToDisplay :selected").val()+"</numberofURLstoDisplay><allowAdultContent>"+allowAdultContent+"</allowAdultContent></content></request>";
		type = "POST";
		
		doAjaxRequest(type, requestData);
	}
	
	//Get my Sharing Settings
	function getSharingSettings()
	{			
		$.ajax({
   			type: "POST",
   			url: "/webservice.php",
   			data: "request=<request><action>getSharingSettings</action><content></content></request>",
   			success: function(xml){
   				var currentSharingSettingWebsites = 1;
   				var currentSharingSettingComments = 1;
   				var data = "<center><h3>My Sharing settings</h3>Configure how you want to share your data<br /><br /><table class=\"myParagraph\">\n";
     			$(xml).find("user").each(function()
   				{
   					currentSharingSettingWebsites = $(this).attr("sharingSettingWebsites");
   					currentSharingSettingComments = $(this).attr("sharingSettingComments");
   					data = data + 	"<tr><td>Sharing Websites with</td><td width=150><input type=\"text\" id=\"sharingSettingWebsitesAmount\" size=\"30\" value=\"" + $(this).attr("sharingSettingWebsites") + "\" style=\"border:0; color:#f6931f; background-color:#e5f6fd; font-weight:bold;\"/></td></tr><td></td><td><div id=\"sharingSettingWebsitesSlider\"></div></td></tr>"+
   									"<tr><td>Sharing Comments with</td><td width=150><input type=\"text\" id=\"sharingSettingCommentsAmount\" size=\"30\" value=\"" + $(this).attr("sharingSettingComments") + "\" style=\"border:0; color:#f6931f; background-color:#e5f6fd; font-weight:bold;\"//></td></tr><td></td><td><div id=\"sharingSettingCommentsSlider\"></div></td></tr>";
   				});
   				data = data + "</table><br /><br />";
   				data = data + "<a class=\"button\" id=\"sharingUpdateSettings\" href=\"#\"><img src=\"images/Clear Green Button.png\" alt=\"\" />Update Profile</a><br />";
   				data = data + "<img src=\"images/click_here.png\" alt=\"Click here\"></center>";
     			
   				$("#boxContent").html(data);
   				
   				
   				$("#sharingUpdateSettings").hover(function(){
					$("#sharingUpdateSettings img")
        			.animate({top:"-10px"}, 200).animate({top:"-4px"}, 200) // first jump
            		.animate({top:"-7px"}, 100).animate({top:"-4px"}, 100) // second jump
            		.animate({top:"-6px"}, 100).animate({top:"-4px"}, 100); // the last jump
    			});
   				
   				
   				$(function() {
					$("#sharingSettingWebsitesSlider").slider({
						min: 1,
						max: 3,
						step: 1,
						value: currentSharingSettingWebsites,
						slide: function(event, ui) {
						        if(ui.value == 1){
									$("#sharingSettingWebsitesAmount").val("friends and everyone WOOT!!");
								}
								else if(ui.value == 2){
									$("#sharingSettingWebsitesAmount").val("just friends :|");
								}
								else if(ui.value == 3){
									$("#sharingSettingWebsitesAmount").val("no one :(");
								}
						}
					});
					if(currentSharingSettingWebsites == 1){
						$("#sharingSettingWebsitesAmount").val("friends and everyone WOOT!!");
					}
					else if(currentSharingSettingWebsites == 2){
						$("#sharingSettingWebsitesAmount").val("just friends :|");
					}
					else if(currentSharingSettingWebsites == 3){
						$("#sharingSettingWebsitesAmount").val("no one :(");
					}
					$("#sharingSettingWebsitesSlider").slider().val(currentSharingSettingWebsites);
				});
   				
   				$(function() {
					$("#sharingSettingCommentsSlider").slider({
						min: 1,
						max: 3,
						step: 1,
						value: currentSharingSettingComments,
						slide: function(event, ui) {
						        if(ui.value == 1){
									$("#sharingSettingCommentsAmount").val("friends and everyone WOOT!!");
								}
								else if(ui.value == 2){
									$("#sharingSettingCommentsAmount").val("just friends :|");
								}
								else if(ui.value == 3){
									$("#sharingSettingCommentsAmount").val("no one :(");
								}
						}
					});
					if(currentSharingSettingComments == 1){
						$("#sharingSettingCommentsAmount").val("friends and everyone WOOT!!");
					}
					else if(currentSharingSettingComments == 2){
						$("#sharingSettingCommentsAmount").val("just friends :|");
					}
					else if(currentSharingSettingComments == 3){
						$("#sharingSettingCommentsAmount").val("no one :(");
					}
				});
   				
   			}
 		});    			
	}
	
	//Set my Sharing Settings
	function setSharingSettings()
	{
		requestData = "request=<request><action>setSharingSettings</action><content><sharingSettingWebsites>"+$("#sharingSettingWebsitesSlider").slider("value")+"</sharingSettingWebsites><sharingSettingComments>"+$("#sharingSettingCommentsSlider").slider("value")+"</sharingSettingComments></content></request>";
		type = "POST";
		
		doAjaxRequest(type, requestData);	
	}
	
	//Will get all the viewed shared websites from my friends
	function viewWebsites()
	{
		$.ajax({
   			type: "POST",
   			url: "/webservice.php",
   			data: "request=<request><action>getWebsiteList</action><content></content></request>",
   			success: function(xml){
   				/*var websiteDataHeading = "<h3>View Friends Shared Websites</h3>";
   				var type = "friend";
   				printWebsiteData( $(xml), websiteDataHeading, type );
   				*/
   				var data = "<div id=\"sharedWebsiteData\">";
     			$(xml).find("friend").each(function()
   				{
   					data = data + "<h2><a href=\"#\"><strong>" + $(this).attr("friend") + "</strong></a></h2>\n";
   					var sharedWebsites = $(this).attr("sharedWebsites");
	   				data = data + "<div><strong>"+$(this).attr("friend")+"</strong> has shared "+ sharedWebsites +" unique websites<br/><br/>\n"
	   				
	   				data = data + "<table>\n";
   					data = data + "<tr><th>Website</th><th>Times Accessed</th><th>Times Tagged</th><th>Rating</th></tr>\n";
   					
   					$(this).find("site").each(function()
   					{
   						var timesAccessed = $(this).attr("timesAccessed");
   						var timesTagged = $(this).attr("tagged");
   						var rating = $(this).attr("rating");
   						data = data + "<tr><td><a href=http://" + $(this).text() + " target=\"_blank\">" + $(this).text() + "</a></td><td>" + timesAccessed + "</td><td>" + timesTagged + "</td><td>" + rating + "</td></tr>";
   					});		
   					data = data + "</table></div>";
   				});
   				
   				data = data + "</div>";
   				$("#boxContent").html(data);
   				
   				//Now that the data has been rendered.... add the accordian's to the box's AWESOME!
   				$(function() {
					$("#sharedWebsiteData").accordion({
						//fillSpace: false,
						collapsible: true,
						autoHeight: false
					});
				});
   					
   							
   			}
 		});
	}
	
	
	
	//Will get all of my most popular shared websites. The websites that I am sharing with my friends
	function getMyMostPopularWebsites()
	{
		$.ajax({
   			type: "POST",
   			url: "/webservice.php",
   			data: "request=<request><action>getMyMostPopularWebsites</action><content></content></request>",
   			success: function(xml){
   				var websiteDataHeading = "<h3>My Most Popular Shared Websites</h3>";
   				var type = "";
   				printWebsiteData( $(xml), websiteDataHeading, type );
   			}
 		});
	}
	
	//Gets the shared website page
	function getShareWebsite()
	{
		var data = "<center><h3>Share a website</h3>Share a website or webpage with others. Just type in the website or webpage you wish to share and your friends will see it. How much easier could it be!<br /><br />\n";
		data = data + "<div id=\"shareWebsiteBox\"><form id=\"shareWebsiteForm\">Website:<input type=\"text\" size=\"40\" name=\"websiteName\" id=\"websiteName\" onkeypress=\"{if (event.keyCode==13)shareWebsite()}\" /><br /></form></div><br /><br />";
		data = data + "<a class=\"button\" id=\"shareWebsiteButton\" ><img src=\"images/Clear Green Button.png\" alt=\"\" />Share Website</a><br />";
		data = data + "<img src=\"images/click_here.png\" alt=\"Click here\"></center>";
			
		$("#boxContent").html(data);
			
			
		$("#shareWebsiteButton").hover(function(){
			$("#shareWebsiteButton img")
			.animate({top:"-10px"}, 200).animate({top:"-4px"}, 200) // first jump
    		.animate({top:"-7px"}, 100).animate({top:"-4px"}, 100) // second jump
    		.animate({top:"-6px"}, 100).animate({top:"-4px"}, 100); // the last jump
		});
	}
	
	//Will share the website
	function shareWebsite()
	{
		$("#slidepanelSharingInfo").slideToggle(200);
		$("#slidepanelSharingInfo").toggleClass("active");
		requestData = "request=<request><action>viewedSite</action><content><![CDATA[" + encodeURIComponent ( $("#websiteName").val() ) + "]]></content></request>";
		type = "POST";
		doAjaxRequest(type, requestData);
		$("#websiteName").attr('value', ''); 
		
		page = "/latestwebsites.php";
		divTag = "boxContent";
		//setTimeout( "getPage(page, divTag);", 4000);
		setTimeout( "location.reload(true);", 4000);
	}	
	
	//Gets the shared website page
	function getShareWebLinkAdvDialog()
	{
		//Get the title
		var title = "";
		
		var data = "Share a website or webpage with others. Just type in the website or webpage you wish to share and your friends will see it. How much easier could it be!<br /><br />\n";
		data = data + "<div id=\"shareWebLinkAdvBox\"><form id=\"shareWebLinkAdvForm\">";
		data = data + "Title:<input type=\"text\" size=\"40\" name=\"weblinkTitleAdv\" id=\"weblinkTitleAdv\"/><br />"; 
		data = data + "Website:<input type=\"text\" size=\"40\" name=\"weblinkNameAdv\" id=\"weblinkNameAdv\" onkeypress=\"{if (event.keyCode==13)shareWebsite()}\" /><br />";
		data = data + "</form></div><br /><br />";
			
		$("#shareWebsiteAdvDialog").html(data);
		$("#shareWebsiteAdvDialog").dialog({
			title: 'Share a WebLink with your friends', 
   			bgiframe: true,
   			modal: true, 
   			width: 500,
			overlay: {
				backgroundColor: '#000',
				opacity: 0.5
			},
   			buttons: {
   				'Cancel': function() { 
   					$(this).dialog('close');
   				}, 
   				'Share WebLink': function() { 
   					
   				} 
   			}
		});
		$("#shareWebsiteAdvDialog").dialog('open');
	}
	
	function getPage($page, $divTag)
	{
		$.ajax({
			type: "GET",
			url: $page,
			cache: false,
			success: function(xml){		
				$("#boxContent").html(xml);
				//$('#boxContent').load('latestwebsites.php');
			},
			error: function (xhr, desc, thrownError) {
			}
		});
	}
	
	//Gets the remove shared website page
	function getRemoveSharedSite()
	{
		var data = "<center><h3>Remove a website</h3>Remove a shared website or webpage. Just type in the website or webpage you wish to remove from your sharing list and your friends will not see it anymore. How much easier could it be! In fact it does get easier because you can type any 3 letters to search your shared websites and it will find it for you!<br /><br />\n";
		data = data + "<div id=\"removeSharedSiteBox\"><form id=\"removeSharedSiteForm\">Website:<input type=\"text\" size=\"40\" name=\"removeWebsiteName\" id=\"removeWebsiteName\" /><br /></form></div><br /><br />";
		data = data + "<a class=\"button\" id=\"removeSharedWebsiteButton\" href=\"#\"><img src=\"images/Clear Green Button.png\" alt=\"\" />Remove Website</a><br />";
		data = data + "<img src=\"images/click_here.png\" alt=\"Click here\"></center>";
			
		$("#boxContent").html(data);
			
		$("#removeSharedWebsiteButton").hover(function(){
			$("#removeSharedWebsiteButton img")
			.animate({top:"-10px"}, 200).animate({top:"-4px"}, 200) // first jump
    		.animate({top:"-7px"}, 100).animate({top:"-4px"}, 100) // second jump
    		.animate({top:"-6px"}, 100).animate({top:"-4px"}, 100); // the last jump
		});
		
		$("#removeWebsiteName").jSuggest({
			minchar: 3,
			url: "/search.php",
			loadingImg: 'images/ajax-loader.gif',
	 		loadingText: 'Loading...',
	 		delay: 2000,
	 		autoChange: false,
			type: "GET",
			data: "websiteSearchQuery",
			autoChange: true
		}); 
	}

	//Will remove the shared website
	function removeSharedWebsite()
	{
		requestData = "request=<request><action>removeViewedSite</action><content><![CDATA[" + encodeURIComponent ( $("#removeWebsiteName").val() ) + "]]></content></request>";
		type = "POST";
		
		doAjaxRequest(type, requestData);
		$("#removeWebsiteName").attr('value', '');
	}
	
	//Will display the addFriend page
	function getAddFriend()
	{
		var data = "<center><h3>Follow an awesome new Friend</h3>Create a new friendship! Just type in the User Name of person you would like to follow<br /><br />\n";
		data = data + "<div id=\"addFriendBox\"><form id=\"addFriendForm\">Friend User Name:<input type=\"text\" size=\"25\" name=\"addFriendName\" id=\"addFriendName\" /><br /></form></div><br /><br />";
		data = data + "<a class=\"button\" id=\"addFriendButton\" href=\"#\"><img src=\"images/Clear Green Button.png\" alt=\"\" />Follow Friend</a><br />";
		data = data + "<img src=\"images/click_here.png\" alt=\"Click here\"></center>";
			
		$("#boxContent").html(data);
			
		$("#addFriendButton").hover(function(){
			$("#addFriendButton img")
			.animate({top:"-10px"}, 200).animate({top:"-4px"}, 200) // first jump
    		.animate({top:"-7px"}, 100).animate({top:"-4px"}, 100) // second jump
    		.animate({top:"-6px"}, 100).animate({top:"-4px"}, 100); // the last jump
		});
		
		$("#addFriendName").jSuggest({
			minchar: 3,
			url: "/search.php",
			loadingImg: 'images/ajax-loader.gif',
	 		loadingText: 'Loading...',
	 		delay: 2000,
	 		autoChange: false,
			type: "GET",
			data: "friendNameSearchQuery",
			autoChange: true
		});
	}
	
	function addFriend()
	{
		requestData = "request=<request><action>addFriend</action><content>"+$("#addFriendName").val()+"</content></request>";
		type = "POST";
		
		doAjaxRequest(type, requestData);
		$("#addFriendName").attr('value', '');
	}
	
	//Display the remove friend page
	function getRemoveFriend()
	{
		var data = "<center><h3>Stop following someone who isn't your friend anymore</h3>Someone is no longer considered your Friend anymore. How sad... For now you must type the friend User Name exactly... A new fix is coming soon<br /><br />\n";
		data = data + "<div id=\"removeFriendBox\"><form id=\"removeFriendForm\">Friend User Name:<input type=\"text\" size=\"25\" name=\"removeFriendName\" id=\"removeFriendName\" /><br /></form></div><br /><br />";
		data = data + "<a class=\"button\" id=\"removeFriendButton\" href=\"#\"><img src=\"images/Clear Green Button.png\" alt=\"\" />Remove Friend</a><br />";
		data = data + "<img src=\"images/click_here.png\" alt=\"Click here\"></center>";
			
		$("#boxContent").html(data);
			
		$("#removeFriendButton").hover(function(){
			$("#removeFriendButton img")
			.animate({top:"-10px"}, 200).animate({top:"-4px"}, 200) // first jump
    		.animate({top:"-7px"}, 100).animate({top:"-4px"}, 100) // second jump
    		.animate({top:"-6px"}, 100).animate({top:"-4px"}, 100); // the last jump
		});
		
		$("#removeFriendName").jSuggest({
			minchar: 3,
			url: "/search.php",
			loadingImg: 'images/ajax-loader.gif',
	 		loadingText: 'Loading...',
	 		delay: 2000,
	 		autoChange: false,
			type: "GET",
			data: "friendNameSearchQuery",
			autoChange: true
		});	
	}
	
	function removeFriend()
	{
		requestData = "request=<request><action>removeFriend</action><content>"+$("#removeFriendName").val()+"</content></request>";
		type = "POST";
		
		doAjaxRequest(type, requestData);
		$("#removeFriendName").attr('value', '');
	}
	
	function resetPassword()
	{
		$("#boxContent").html("<div id=\"passwordReset\" align=\"right\"><br>Please enter the following to reset your password<br><br><br><form id=\"resetPasswordForm\">Old Password:<input type=\"password\" size=\"15\" name=\"oldPassword\" id=\"oldPassword\" /><br /><br />New Password:<input type=\"password\" size=\"15\" name=\"newPassword\" id=\"newPassword\" onKeyUp=\"verifyPasswordsReset()\" /><br>Verify New Password:<input type=\"password\" size=\"15\" name=\"vnewPassword\" id=\"vnewPassword\" onKeyUp=\"verifyPasswordsReset()\" /><div id=\"verifyResetPasswordResult\"></div><br /><br /></form></div>");

		$("#passwordReset").dialog({
			title: 'Password Reset', 
   			bgiframe: true,
   			modal: true, 
			overlay: {
				backgroundColor: '#000',
				opacity: 0.5
			},
   			buttons: {
   				'Cancel': function() { 
   					$(this).dialog('close');
   					getLatestWebsites(0);
   				}, 
   				'Reset Password': function() { 
   					$.ajax({
 						type: "POST",
 						//datatype: "xml";
 						url: "/webservice.php",
 						data: "request=<request><action>resetPassword</action><content><oldPassword><![CDATA[" + $("#oldPassword").val() + "]]></oldPassword><newPassword><![CDATA["+$("#newPassword").val()+"]]></newPassword></content></request>",
 					success: function(xml){
						var len = $(xml).find("response").length;
	   					var responseTag = $(xml).find("response");
	   					var responseType = $(responseTag).attr("type");
	   					var message = $(responseTag).attr("message");
	   				
		     			if(responseType == "success"){
		     				displayLebWinksMessage("", message, "lebWinksMessageSuccess");
						}
		     			else {
		     				displayLebWinksMessage("", message, "lebWinksMessageError");
		     			}
	   				}
	 				});
   				} 
   				
   			}, 
    		position: ['150', '200']
		});
	}
	
	//Simple jQuery ajax handler
	function doAjaxRequest(type, requestData)
	{
		doAjaxRESTRequest(type, "/webservice.php", requestData)
	}
	
	//Simple jQuery ajax handler using REST endpoints
	function doAjaxRESTRequest(type, endpoint, requestData)
	{
		$.ajax({
			type: type,
			url: endpoint,
			data: requestData,
			success: function(xml){				
				var len = $(xml).find("response").length;
				var responseTag = $(xml).find("response");
				var responseType = $(responseTag).attr("type");
				var message = $(responseTag).attr("message");
			
				if(responseType == "success"){
					displayLebWinksMessage("", message, "lebWinksMessageSuccess");
				}
				else {
					displayLebWinksMessage("", message, "lebWinksMessageError");
				} 
			
			},
			error: function (xhr, desc, thrownError) {
				var message = "LebWinks Error!\n xhr.responseText: <" + xhr.responseText + "\nxhr.status: "> + xhr.status + "\ndesc: "+ desc + "\nthrownError: " + thrownError;
				displayLebWinksMessage("", message, "lebWinksMessageError");
			}
		});
	}
	
	function displayLebWinksMessage(titleMessage, message, type)
	{
		if(type == "lebWinksMessageSuccess")
			imageType = "/images/Clear Green Button.png";
		else if("lebWinksMessageInfo")
			imageType = "/images/Get Info Blue Button.png";
		else if("lebWinksMessageWarning")
			imageType = "/images/Yellow Ball.png";
		else if("lebWinksMessageError")
			imageType = "/images/Cancel Red Button.png";
		
		if(titleMessage != ""){
			$.gritter.add({
				title: titleMessage,
				image: imageType,
				text: message,
				sticky: false
			});
		} else {
			$.gritter.add({
				image: imageType,
				text: message,
				sticky: false
			});
		}
	}

	function loginUser2()
	{
		rememberMe = "no";
		if($("#rememberMe2").is(':checked'))
				rememberMe = "yes";
		attemptLogin("2", $("#loginEmailAddress").val(), $("#loginUserPass").val(), rememberMe);
	}
	
	function addMiniComment(weblink, miniCommentID)
	{
		var comment = $("#"+miniCommentID).val();
		addComment(weblink, comment);
	}
	
	function getNotifications(notificationType)
	{
		
		$.ajax({
	   		type: "GET",
	   		url: "/api/notifications/"+notificationType,
	   		data: "",
	   		success: function(xml){
	   			
	    		$(xml).find("notifications").each(function()
	   			{
	   				var totalNotifications = $(this).attr("totalNotifications");
	   				var data = "<div>";
	   				if(totalNotifications > 0) {
	   					if(notificationType == "new")
	   						$("#notificationLink").html("<font color=red>"+totalNotifications+" New Notifications</font>");
	   					else
	   						$("#notificationLink").html("<font>Notifications</font>");
		   				data = data + "<table class=\"myData2\">\n";
	   					data = data + "<tr><th style=\"display:none;\">N ID</th><th style=\"display:none;\">Viewed</th><th>When</th><th>Message</th></tr>\n";
		   				
		   				$(xml).find("notification").each(function()
		   				{
		   					var message = $(this).find("message").text();
		   					var weblinktitle = $(this).find("weblinktitle").text();
		   					var weblink = $(this).find("weblink").text();
		   					message = message.replace("website", "<a href=\"/weblinkdetails.php?weblink="+encodeURIComponent(weblink)+"\" ><font color=#90ee90 style=\"text-decoration: underline;\">website</font></a>");
		   					var viewed = $(this).attr("viewed");
	   						var timestamp = $(this).attr("timestamp");
	   						var notificationID = $(this).attr("notificationID");
	   						var weblink = $(this).find("weblink");
		   					data = data + "<tr><td style=\"display:none;\">"+notificationID+"</td><td style=\"display:none;\">"+viewed+"</td><td>"+timestamp+"</td><td>"+message+"</td></tr>";
		   				});		
		   				data = data + "</table>";
		   				data = data + "</div>";
		   			
		   				$("#notificationBox").html(data);
		   			}
	   				else {
	   					//we have no new notifications
	   					$("#notificationLink").html("Notifications");
	   					$("#notificationBox").html("No notifications. Better start using some more lebwinks");
	   					
	   					//If we tried to new, then get the old notifications.
	   					if(notificationType == "new"){
	   						getNotifications("latest");
	   					}
	   				}
	   			});
	   			
	   		}
	 	});
	}
	
	function displayNotifications() {
		$.gritter.add({
			title: "Notifications",
			image: "/images/Get Info Blue Button.png",
			text: $("#notificationBox").html(),
			sticky: true,
			before_open: function(){
			}
		});
	}
	
	function viewedNotificationIDs() {
		var rows = $("#notificationBox tr:gt(0)");
		var postData = "<request><content><notifications>";
		rows.children("td:nth-child(1)").each(function() {
		    
		    var nid = $(this).html();
		    var viewed = $(this).next().html()
			
			if(viewed == "0") {
				postData = postData+"<notification>"+nid+"</notification>";
			}
		});

		if(postData != "<request><content><notifications>") {
			postData = postData+"</notifications></content></request>";
			doAjaxRESTRequest("POST", "/api/notifications", postData);
		}
	}
	
	function submitSignUpForm()
	{
		document.signupboxform.submit();
	}
	
/********************************** End of Functions *************************************************/	



//JQuery Javascript when document is loaded
$(document).ready(function() {

	getNotifications("new");
	
	$(function() {
		$("#tabs").tabs();
	});
	
	$(function() {
		$("#navAdmin").accordion({
			fillSpace: true,
			collapsible: true,
			autoHeight: false
		});
	});
	
	$(function() {
		$("#navStats").accordion({
			fillSpace: true,
			collapsible: true,
			autoHeight: false
		});
	});
	
	$(function() {
		$("#navProfile").accordion({
			fillSpace: true,
			collapsible: true,
			autoHeight: false
		});
	});
	
	$("#tos").click(function(){
		getTOS();
	});

	$("#privacypolicy").click(function(){
		getPrivacyPolicy();
	});

	$("#loginUser").click(function(){
		loginUser("1", $("#user").val(), $("#password").val());
	});	

	$("#loginUser2").click(function(){
		rememberMe = "no";
		if($("#rememberMe2").is(':checked'))
				rememberMe = "yes";
		attemptLogin("2", $("#loginEmailAddress").val(), $("#loginUserPass").val(), rememberMe);
	});
	
	$("#loginFormBox").click(function(){
		loginUser();
	});	
	
	$("#password").click(function(){
		rememberMe = "no";
		if($("#rememberMe").is(':checked'))
				rememberMe = "yes";
		attemptLogin("1", $("#user").val(), $("#password").val(), rememberMe);
	});	
	
	$('#password').keyup(function(e) {
		//if enter key is pressed while in the password text box then try to login
		if(e.keyCode == 13) {
			rememberMe = "no";
			if($("#rememberMe").is(':checked'))
				rememberMe = "yes";
			attemptLogin("1", $("#user").val(), $("#password").val(), rememberMe);
		}
	});
	
	$("#logout").click(function(){
		logoutUser();
	});	
	
	$("#viewFriends").click(function(){
		viewFriends();
	});	
	
	$("#viewWebsites").click(function(){
		viewWebsites();
	});	
	
	$("#getMyWebsites").click(function(){
		getMyWebsites();
	});	
	
	$("#getMyMostPopularWebsites").click(function(){
		getMyMostPopularWebsites();
	});	
	
	$("#getShareWebsite").click(function(){		
		getShareWebsite();
	});
	
	$("#shareWebsiteButton").live("click", function(){
		shareWebsite();
	});
	
	$("#shareWebsiteAdvButton").live("click", function(){
		getShareWebLinkAdvDialog();
	});
	
	$("#getRemoveSharedSite").click(function(){		
		getRemoveSharedSite();
	});
	
	$("#removeSharedWebsiteButton").live("click", function(){
		removeSharedWebsite();
	});
	
	$("#getAddFriend").click(function(){		
		getAddFriend();
	});
	
	$("#addFriendButton").live("click", function(){
		addFriend();
	});
	
	$("#getRemoveFriend").click(function(){		
		getRemoveFriend();
	});
	
	$("#removeFriendButton").live("click", function(){
		removeFriend();
	});
	
	$("#resetPassword").click(function(){	
 		resetPassword();
	});
	
	$("#getRandomWebsite").click(function(){
		getRandomWebsite();
	});
	
	$("#getRandomWebsiteFromSelf").click(function(){
		getRandomWebsiteFromSelf();
	});	
	
	$("#getRandomWebsiteFromFriends").click(function(){
		getRandomWebsiteFromFriends();
	});
	
	$("#getRandomWebsiteFromEveryone").click(function(){
		getRandomWebsite();
	});
	
	$("#getMostPopularWebsites").click(function(){	
		getMostPopularWebsites();
	});
	
	$("#getLatestWebsites").click(function(){
		var startingNumber = $("#websiteStartingNumber").val();	
		getLatestWebsites(startingNumber);
	});
	
	$("#websiteStarter").live("click", function(){
		
		var startingNumber = $(this).text().split("-");	
		
		getLatestWebsites(startingNumber[0]-1);
	});
	
	$("#getProfileSettings").click(function(){	
		getProfileSettings();
	});
	
	$("#profileUpdateSettings").live("click", function(){
		setProfileSettings();
	});
	
	$("#getSharingSettings").click(function(){	
		getSharingSettings();
	});
	
	$("#sharingUpdateSettings").live("click", function(){	
		setSharingSettings();
	});
	
	$("#profileUpdateSettings").live("click", function(){
		setProfileSettings();
	});
	
	$("#shareWebsiteButton").hover(function(){
		$("#shareWebsiteButton img")
		.animate({top:"-10px"}, 200).animate({top:"-4px"}, 200) // first jump
		.animate({top:"-7px"}, 100).animate({top:"-4px"}, 100) // second jump
		.animate({top:"-6px"}, 100).animate({top:"-4px"}, 100); // the last jump
	});
	
	$(".miniAddComment").click(function(){
		var element = $(this);
		var I = element.attr("id");

		$("#slidepanel"+I).slideToggle(300);
		$(this).toggleClass("active");

		return false;
	});
	
	$(".miniDisplayComment").click(function(){
		var element = $(this);
		var I = element.attr("id");

		$("#slidepanelDisplayComment"+I).slideToggle(200);
		$(this).toggleClass("active");
		if ( $(this).hasClass("active") ) {
			//Box is currently open
			$("#footer").slideToggle(10);
		} else {
			 $("#footer").slideToggle(-10);
		}
		 
		return false;
	});
	
	$("#notificationLink").click(function(){
		//Get the new ones
		displayNotifications();
		
		//Viewed all the new ones
		viewedNotificationIDs();
		
		getNotifications("new");
	});
});




