// Moustache May Javascript Document
// insert commonly used functions here
var baseDomain = "http://moustachemay.com/";
var chatTimeDelay = 10000;

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;
	}
}
	
function viewTeam(targ){
	
	if ($("#mainTeamBadge"+targ+" .desc").css("display") != "block"){
		$("#mainTeamBadge"+targ+" .desc").slideDown();
		$("#viewmoreLink"+targ).addClass("active");
		teamOpen=true;
	} else {
		$("#mainTeamBadge"+targ+" .desc").slideUp();
		$("#viewmoreLink"+targ).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(baseDomain + "__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 (body.toLowerCase() == "leave a comment..."){
		err = "No, seriously, leave a comment.";
	}
	if (body.indexOf("http://") > -1){
		err = "Please use the link field to link to things.";	
	}
	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(baseDomain + "_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(baseDomain + "_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>");
						}
					}
				}
			}
		);
}
function turboVote(imgId, fromUserID, toUserID, rating, fromDetail){
	$.post(baseDomain + "_lib/_func/rateimage.php",
			{imgid: imgId, fromUser: fromUserID, toUser: toUserID, therating: rating, func: "rate"}, 
			function(data){
				if (data){ 
					if (data.substring(0,1) != "!"){
						if ($("#theVoteButton"+imgId).hasClass("crowned")){
							$("#theVoteButton"+imgId).removeClass("crowned");
						} else {
							$("#theVoteButton"+imgId).addClass("crowned");
						}
					} else {
						$("#theVoteButton"+imgId).html("ERROR!!");
					}
				}
			}
		);
}

// ------------------------------------------------------------
// add IMAGE favorite
function addimgFavorite(imgID, fromUserID){
	//$("#debug").html(imgID + ", " + fromUserID);
	$.post(baseDomain+"_lib/_func/addfavimage.php",
			{imgid: imgID, fromUser: fromUserID, func: "addfave"}, 
			function(data){
				if (data){ 
					//$("#debug").html(data);
					if (data == "added"){
						$("#favImageIcon"+imgID).addClass("favoriteImage");
						$("#favImageIcon"+imgID).attr("title","Revoke Favorite Status");
						//document.getElementById('favImageIcon').style.backgroundPosition = '0px -63px';
					} else if (data == "removed"){
						$("#favImageIcon"+imgID).removeClass("favoriteImage");
						$("#favImageIcon"+imgID).attr("title","Award Favorite Status");
						//document.getElementById('favImageIcon').style.backgroundPosition = '0px -42px';
					}
							
				}
			}
		);
	return false;
}
// ------------------------------------------------------------
// site closed

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

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

//Gets the current messages from the server
function getChatText() {
	// safety net
	if (!lastMessage || lastMessage == ""){
		lastMessage="check";
	}
	$.get(baseDomain+"_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);
			}
		}
	);
}
// 2011 edition
function getChatTextv2(){
	if (!lastMessage || lastMessage == ""){
		lastMessage="check";
	}
	$.getJSON(baseDomain+"_lib/_func/talkbackv2.php",
		{last: lastMessage},
		function(data){
			if (data){
				clearInterval(mTimer);
				handleReceiveChatv2(data);
				//delete data;
			} else {

				// no data? lets run the get function again in X seconds
				mTimer = setTimeout('getChatTextv2();',chatTimeDelay);
			}
		}
	);
}
//Gets the current staches from the server
function checkStachesMonitor() {
	// safety net
	if (!lastStache || lastStache == 0){
		lastStache="check";
	}
	$.get(baseDomain+"_lib/_func/stachemonitor.php",
		{last: lastStache},
		function(data){
			if (data){
				if (data.substring(0,4) == "NEW:"){
					lastStache = data.substr(4);
					sTimer = setTimeout('checkStachesMonitor();',15000);
				} else {
					clearInterval(sTimer);
					handleReceiveStache(data);
					delete data;
				}
			} else {
				// no data? lets run the get function again in X seconds
				sTimer = setTimeout('checkStachesMonitor();',15000);
			}
		}
	);
}
function createTBBlock(userlink, username, usercomment,id, timestamp){
	
	var messageBlock 	= "";
	usercomment			= stripslashes(usercomment);
	var slashme 		= false;
	var checkcomment 	= usercomment.toLowerCase();
	var theUser 		= "";
	var theAction		= " says:";
	
	if (userlink && userlink != " "){
		theUser = "<a href=\""+userlink+"\">"+stripslashes(username)+"</a>";
	} else {
		theUser = username;
	}

	if (checkcomment.substr(0,4) == "/me "){
		slashme 		= true;
		theUser			= theUser;
		theAction		= " " + usercomment.substr(4);
		messageBlock	= "<div class=\"message actionable\">";
	} else {
		messageBlock	= "<div class=\"message\">";
	}
	
	// create the block
    messageBlock += "    <dl>";
    messageBlock += "     <dt>"+theUser+theAction+"</dt>";
	if (!slashme){
    messageBlock += "     <dd>";
	messageBlock += 		stripslashes(usercomment);
	messageBlock += "		<div class=\"timestamp\">Posted: "+timestamp+"</div>";
	messageBlock += "		</dd>";
	}
    messageBlock += "    </dl>";
	
	messageBlock += "		</div>";
	
	
	return messageBlock;
}
					   
// version 2 (2011) function for handling cht text
   function handleReceiveChatv2(data) {
	  	
		// loop to add new messages
		$.each(data.chats, function(i,item){
					
			// define vars for ease of use
			var msg = stripslashes(item.msg);
			var userlink = item.userlink;
			var username = item.username;
			var date= item.date;
			var id = item.pkID;
			var html = createTBBlock(userlink, username, msg, id, date);
			
			// add to talkback div
			$("#thetalkback").prepend(html);
			$("#tbmsg"+id).slideDown("slow");
			//
			// save the id 
			$("#tbID").val(id);
			lastMessage = id;
			
			// take one off the end
			$("#thetalkback .message:last-child").slideUp();
   		 });
		// fin

		if (data.chats.length){
			var totalchats = $("#thetalkback").children().length;
			var toRemove = data.chats.length;
			var chopInsertion = totalchats - toRemove;
			
			$("#thetalkback .message:gt("+chopInsertion+")").slideUp("slow");
		}
		// reset the controls
		$("#tbBtn").attr("disabled",false);
		mTimer = setTimeout('getChatTextv2();',chatTimeDelay);
}

				
//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);
}*/

//Function for handling the return of a new stache
function handleReceiveStache(data) {
		var pieces = data.split("::");
		lastStache = pieces[1];
		var newStaches = pieces[2];
		/*var gallery_div = document.getElementById('gallery');
		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
		}*/
		//alert(lastStache); 
		$("#gallery").prepend(newStaches);
		sTimer = setTimeout('checkStachesMonitor();',15000);
}



//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
			$.getJSON(baseDomain + "_lib/_func/talkbackv2.php",
				{ last: lastMessage, username: tbName, userlink: tbLink, usercomment: tbComment, avatarCheck: tbUserID},
				function(data){
					handleReceiveChatv2(data);
					delete tbcomment;
					delete tbname;
					delete tblink;
					delete tbUserID;
				}
			);
			$('#tbTalk').val('');
		}
}


//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();
}
function startChatv2(){
	mTimer = setTimeout('getChatTextv2();',chatTimeDelay);	
}
//Function for  checking for staches
function startStacheMonitor() {
	//Set the focus to the Message Box.
	//document.getElementById('tbTalk').focus();
	//Start Recieving Messages.
	mTimer = setTimeout('checkStachesMonitor();',15000);
	//getChatText();
}




// 2009 ADDITIONS! NOW WITH DOCUMENT READY!!
$(document).ready(function() {
	
	// slider page
	// make image viewer super wide (# of images x mask width)
	$(".aboutHeaderMask ul").css("width",$(".aboutHeaderMask ul").children().size() * $(".aboutHeaderMask").width());
	// make main images (click) advance
	$(".aboutHeaderMask ul li img").click(function(){
		var $li = $(this).parents('li');
		var $ul = $(this).parents('ul');
		var num = $ul.children().index($li) + 1;
		var totalChildren = $ul.children().size();
		if (num >= totalChildren){
			num = 0;
		}
		
		slideAbout("aboutHeader", num);
		
		
		return false;
		
	});
	// make thumbs slide the top view
	$(".about-pagination ul li a").click(function(){ 
		var $li = $(this).parents('li');
		var $ul = $(this).parents('ul');
		var num = $ul.children().index($li);
		
		slideAbout("aboutHeader", num);
															 							 
		return false;
	});
	
	
	// sharing stuff
	$("#detail_view a.share").click(function(){
		if ($(this).hasClass("active")){
			$(".sharetools").slideUp();
			$(this).removeClass("active");
		} else {
			$(".sharetools").slideDown();
			$(this).addClass("active");
		}
		return false;
	});
	
	

});


function slideAbout(targ, dest){
	var width = $("."+targ+"Mask").width();
	var xdest = (width * dest) * -1;
	
	$("."+targ+"Mask ul").animate({ 
        marginLeft: xdest+"px"
      }, 600, "swing");
	
	$(".about-pagination ul li a").removeClass("active");
	$(".about-pagination ul li:eq("+dest+") a").addClass("active");
		
	return false;
}


function removeComment(id){
	var ensure = confirm("Woah! This is permanent. Are you sure you wanna do that?")

	var thefunc = "remove";
	var theCommentTarg = id;
	var theUser = $("#c-userid").val();
	var theRequester = $("#c-senderid").val();
	var theImg = $("#c-imgid").val();
	
	if (ensure){
		$.post(baseDomain + "_lib/_func/commentremove.php",
			{func: thefunc, targ: theCommentTarg, user: theUser, sender: theRequester, img: theImg}, 
			function(data){
				if (data){
					
					$("#comment"+id).slideUp();
				}
			});	
	}
}

// add USER favorite
function adduserFavorite(userID, fromUserID, imgID){
	$.post(baseDomain+"_lib/_func/addfavuser.php",
			{userid: userID, fromUser: fromUserID, func: "addfave"}, 
			function(data){
				if (data){ 
					//$("#debug").html(data);
					if (data == "added"){
						$("#favUserIcon"+imgID).addClass("favoriteUser");
						$("#favUserIcon"+imgID).attr("title","Stop Following This User");
						//document.getElementById('favUserIcon').style.backgroundPosition = '0px -17px';
					} else if (data == "removed"){
						$("#favUserIcon"+imgID).removeClass("favoriteUser");
						$("#favUserIcon"+imgID).attr("title","Follow This User");
						//document.getElementById('favUserIcon').style.backgroundPosition = '0px 0px';
					}
					
				}
			}
		);
	return false;
}

