// Moustache May Javascript Document
// insert commonly used functions here
function nl2br(str) {
	str=str.replace(/\\n/g, "<br />");
	//
	return str;
}
function stripslashes(str) {
	str=str.replace(/\\'/g,'');
	str=str.replace(/\\"/g,'"');
	str=str.replace(/\\\\/g,'\\');
	str=str.replace(/\\0/g,'\0');
	//
	return str;
}
//no spam
// USAGE: javascript:doMail('user','domain.com')
function doMail(user,domain) {
	locationstring = "mailto:" + user + "@" + domain;
	window.location = locationstring;
}

function checkEmail(addy) {
	if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(addy)){
		return (true)
	} else {
		return (false)
	}
}
// profile toggle viewTeamInfo
var teamOpen = false;
					
function viewTeamInfo(){
	if (!teamOpen){
		$("#mainTeamBadge .desc").slideDown();
		$("#viewmoreLink").addClass("active");
		teamOpen=true;
	} else {
		$("#mainTeamBadge .desc").slideUp();
		$("#viewmoreLink").removeClass("active");
		teamOpen=false;
	}
}
					
// profile tabs toggler
function ptoggler(ontarg){
	if (ontarg == "info"){
		$("#statsMeat").hide();
		$("#statsNav").removeClass("active");
		$("#extrasMeat").hide();
		$("#extrasNav").removeClass("active");
	} else if (ontarg == "stats"){
		$("#infoMeat").hide();
		$("#infoNav").removeClass("active");
		$("#extrasMeat").hide();
		$("#extrasNav").removeClass("active");
		// load in the stats for this user
		var thisUser = document.getElementById('c-userid').value;
		var statsLoaded = document.getElementById('statsLoaded').value;
		if (statsLoaded == 0){
			$.post("__profile_stats.php",
					{user_id: thisUser}, 
					function(data){
						if (data){
							//
							$("#statsMeat").html(data);
							document.getElementById('statsLoaded').value = '1';
						}
					}
				);
		}
	} else if (ontarg == "extras"){
		$("#infoMeat").hide();
		$("#infoNav").removeClass("active");
		$("#statsMeat").hide();
		$("#statsNav").removeClass("active");
	}
	
	$("#"+ontarg+"Nav").addClass("active");
	$("#"+ontarg+"Meat").show();
	return false;
}

// home tabs toggler
function toggler(ontarg){
	if (ontarg == "talkback"){
		$("#newsMeat").hide();
		$("#commentsMeat").hide();
		$("#newsNav").removeClass("current");
		$("#commentsNav").removeClass("current");
	} else if (ontarg == "comments"){
		$("#newsMeat").hide();
		$("#talkbackMeat").hide();
		$("#newsNav").removeClass("current");
		$("#talkbackNav").removeClass("current");
	} else if (ontarg == "news"){
		$("#commentsMeat").hide();
		$("#talkbackMeat").hide();
		$("#commentsNav").removeClass("current");
		$("#talkbackNav").removeClass("current");
	}
	$("#"+ontarg+"Nav").addClass("current");
	$("#"+ontarg+"Meat").show();
	return false;
}
//---------------------------------------------------------------------------------------
// Send Image Comment
//---------------------------------------------------------------------------------------
function sendComment(bool){
	var err = "";
	var name = document.getElementById("cname").value;
	var link = document.getElementById("clink").value;
	var body = document.getElementById("cbody").value;
	var imgid = document.getElementById("c-imgid").value;
	var userid = document.getElementById("c-userid").value;
	//
	if (link == "Link"){
		link = "";
	}
	if (!body){
		err = "You gotta say something";
	}
	if (link){
		if (link.substring(0,7) != "http://"){
			err = "Invalid Link";
		}
		if (link.length < 8){
			err = "Invalid Link";
		}
	}
	if (!name){
		err = "Enter a name";
	}
	if (name == "Name"){
		err = "Enter a name";
	}
	if (err){
		alert(err + "!");
	} else {
		document.getElementById("comment-btn").disabled=true;
		$.post("_lib/_func/commentadd.php",
				{thename: name, thelink: link, comment: body, func: "add", img_id: imgid, user_id: userid}, 
				function(data){
					if (data){
						commaOne = data.indexOf(",",0);
						commaTwo = data.indexOf(",",commaOne+1);
						//
						latestID = data.substring(0, commaOne);
						commentCount = data.substring(commaOne+1, commaTwo)
						data = data.substring(commaTwo+1);
						//
						if (bool){
							$("#commentMeat").append(data);
						} else {
							$("#commentMeat").prepend(data);
						}
						//$("#talkblock" + latestID).slideDown();
						//
						if (document.getElementById("nocommentsfound")){
							$("#nocommentsfound").remove();
						}
						//
						$("#commentCounter"+imgid).html(commentCount+" Comments");
						//
						document.getElementById("cbody").value = "";
						document.getElementById("cbody").focus();
						document.getElementById("comment-btn").disabled=false;
					}
				}
			);
	}
	
}







// IMAGE RATING
function rateImage(imgId, fromUserID, toUserID, rating, fromDetail){
	$.post("http://www.moustachemay.com/_lib/_func/rateimage.php",
			{imgid: imgId, fromUser: fromUserID, toUser: toUserID, therating: rating, func: "rate"}, 
			function(data){
				if (data){ 
					if (data.substring(0,1) != "!"){
		
						$("#avgRating"+imgId).html("avg: " + data);
						$("#voteBlock"+imgId).html("<li class='rated-"+rating+"'>"+rating+"</li>");
						if (fromDetail == 1){
							$("#voteBlockDetail"+imgId).html("<li class='rated-"+rating+"'>"+rating+"</li>");
						}
					} else {
						//alert("You have already rated this image.");
						newrating = data.substring(1);
						$("#voteBlock"+imgId).html("<li class='rated-"+newrating+"'>"+newrating+"</li>");
						if (fromDetail == 1){
							$("#voteBlockDetail"+imgId).html("<li class='rated-"+newrating+"'>"+newrating+"</li>");
						}
					}
				}
			}
		);
}


// ------------------------------------------------------------
// add IMAGE favorite
function addimgFavorite(imgID, fromUserID){
	$.post("_lib/_func/addfavimage.php",
			{imgid: imgID, fromUser: fromUserID, func: "addfave"}, 
			function(data){
				if (data){ 
					
					if (data == "added"){
						document.getElementById('favImageIcon').style.backgroundPosition = 'bottom';
					} else if (data == "removed"){
						document.getElementById('favImageIcon').style.backgroundPosition = 'top';
					}
							
				}
			}
		);
	return false;
}
// ------------------------------------------------------------
// site closed

function showGallery(){
	$("#thankYou").hide();
	$("#gallery").show();
}

// ------------------------------------------------------------------------------------------------------------------
// CHAT JS
var numofMsgs = 120;
var mTimer;

//Gets the current messages from the server
function getChatText() {
	// safety net
	if (!lastMessage || lastMessage == ""){
		lastMessage="check";
	}
	$.get("http://www.moustachemay.com/_lib/_func/_talkback.php",
		{last: lastMessage},
		function(data){
			if (data){
				clearInterval(mTimer);
				handleReceiveChat(data);
				delete data;
			} else {
				// no data? lets run the get function again in X seconds
				mTimer = setTimeout('getChatText();',10000);
			}
		}
	);
}
function createTBBlock(userlink, username, usercomment,id, timestamp){
	
	var messageBlock = "<div class=\"message\">";
	

    messageBlock += "    <dl>";
    messageBlock += "     <dt>";
	if (userlink && userlink != " "){
		messageBlock += "<a href=\""+userlink+"\">"+stripslashes(username)+"</a> says:</dt>";
	} else {
		messageBlock += username + " says:</dt>";
	}
    messageBlock += "     <dd>";
	messageBlock += 		stripslashes(usercomment);
	messageBlock += "		<div class=\"timestamp\">Posted: "+timestamp+"</div>";
	messageBlock += "		</dd>";
    messageBlock += "    </dl>";
	
	messageBlock += "		</div>";
	
	
	return messageBlock;
}
					   
					   
				
//Function for handling the return of chat text
function handleReceiveChat(data) {
		var chat_div = document.getElementById('thetalkback');
		var xmldoc = data.split("::");
		var n_messages = xmldoc.length - 1;
		if (n_messages > 0){
			for (i = 0; i < n_messages; i++) {
				// 0 = id, 1 = username, 2 = userlink, 3=usercomment
				var mynodes = xmldoc[i].split("|");
				var user_node = mynodes[1];
				var text_node = stripslashes(mynodes[3]);
				var link_node = mynodes[2];
				var time_node = mynodes[4];
				var id_node = mynodes[0];
				var newMsg = createTBBlock(link_node, user_node, text_node, id_node, time_node);
				$("#thetalkback").prepend(newMsg);
				$("#tbmsg"+id_node).slideDown("fast");
				document.getElementById("tbID").value = id_node;
				lastMessage = id_node;
			}
			// remove X number of nodes
			thelist = document.getElementById("thetalkback");
			thelistdt = thelist.getElementsByTagName("div");
			dest = thelistdt.length - n_messages;
			// make sure list is at least X long
			if (thelistdt.length > numofMsgs){
				for (i=dest;i<=thelistdt.length; i++){
					curdt = thelistdt[i];
					$(curdt).remove();
				}
			}
			// fin
		}
		document.getElementById("tbBtn").disabled=false;
		mTimer = setTimeout('getChatText();',10000);
}


//Add a message to the chat server.
function sendChatText() {
		//  ERROR CHECKING
		var err = "";
		var tbName = document.getElementById("tbName").value;
		var tbLink = document.getElementById("tbLink").value;
		var tbComment = document.getElementById("tbTalk").value;
		var tbUserID = document.getElementById("tbUserID").value;
		//
		if (tbLink == "Link" || tbLink == "link"){
			tbLink = " ";
		}
		if ((!tbComment) || (tbComment == "Got something to say?")){
			err = "Please share some wisdom with us.";
		}
		if (tbComment.indexOf("http") != -1){
			err = "Please put your link above the chat box and say 'clame' - it means click my name!";
		}
		if (tbLink && tbLink != " "){
			if (tbLink.substring(0,7) != "http://"){
				err = "Start us off with an http:// please";
			}
			if (tbLink.length < 8){
				err = "That link looks suspect";
			}
		}
		if (!tbName){
			err = "What's yer name?";
		}
		if (tbName == "Name" || tbName == "name"){
			err = "Your name isn't name. I almost bet on it";
		}
		// safety net
		if (!lastMessage || lastMessage == ""){
			lastMessage="check";
		}
		
		if (err){
			alert(err + "!");
		} else {
		
			document.getElementById("tbBtn").disabled=true;
			clearInterval(mTimer);
			// feel free to add more params here
			$.post("http://www.moustachemay.com/_lib/_func/talkback.php",
				{ last: lastMessage, username: tbName, userlink: tbLink, usercomment: tbComment, avatarCheck: tbUserID},
				function(data){
					handleReceiveChat(data);
					delete tbcomment;
					delete tbname;
					delete tblink;
					delete tbUserID;
				}
			);
			document.getElementById('tbTalk').value = '';
		}
}


//When our message has been sent, update our page.
function handleSendChat() {
	//Clear out the existing timer so we don't have
	//multiple timer instances running.
	clearInterval(mTimer);
	getChatText();
}
// this function lets a user hit ENTER for the talkback without refreshing the page
function blockSubmit() {
	sendChatText();
	return false;
}
// this function is called to start off the chat timer, need to make sure this is only called by registered users
//Function for initializating the page.
function startChat() {
	//Set the focus to the Message Box.
	//document.getElementById('tbTalk').focus();
	//Start Recieving Messages.
	mTimer = setTimeout('getChatText();',10000);
	//getChatText();
}