var postTimer = undefined;
var updtTimer = undefined;
var fpData = undefined;
var fpImageUpload = undefined;
var fpImageEnlargement = undefined;
var animateDuration = 500;
var pauseDuration = 1000;
var firstItem = undefined;
var popoverShowTimer = null;
var popoverHideTimer = null;
var popoverDetails = null;
var createPostValidator = new Array(['postTitle',true,'str'],['postTitleModifier',false,'str'],['postMsg',true,'str']);
var createPostChars = new Object({'postTitle':50,'postTitleModifier':50,'postMsg':140,'postComment':140});
var isInitialized = false;
var isPaused = false;
var map = null;
var geocoder = null;
var minX = null;
var maxX = null;
var minY = null;
var maxY = null;
var mapIsDraggable = 0;


function getBounds(map){
	var bounds = map.getBounds();
	var southWest = bounds.getSouthWest();
	var northEast = bounds.getNorthEast();
	var lngSpan = northEast.lng() - southWest.lng();
	var latSpan = northEast.lat() - southWest.lat();
	alert(southWest.lng() + " : " + northEast.lng());
	alert(southWest.lat() + " : " + northEast.lat());
}

function initialize(geoLat, geoLng, dMapDiv, dResultEnabled, dZoom, dIsDraggable) {
  mapIsDraggable = dIsDraggable;
  if (geoLat == null || geoLng == null){
	geoLat = 47.636879;
	geoLng = -122.335854;
  }
  
  if (GBrowserIsCompatible()) {
	map = new GMap2(document.getElementById(dMapDiv));
	map.addControl(new GSmallZoomControl3D());
	var mapCenter = new GLatLng(geoLat, geoLng);
	map.setCenter(mapCenter, dZoom);
	if(dResultEnabled){
		getGeoResults(mapCenter);
	}
	else {
		showFlaggpole(mapCenter);	
	}
	geocoder = new GClientGeocoder();
  }
}

function getSearch(address) {
  if (geocoder) {
	geocoder.getLatLng(
	  address,
	  function(point) {
		if (!point) {
		  alert(address + " not found");
		} else {
			map.clearOverlays();
			showFlaggpole(point);
			map.setCenter(point, map.getZoom());
		}
	  }
	);
  }
}

function getAddress(address) {
  if (geocoder) {
	geocoder.getLatLng(
	  address,
	  function(point) {
		if (!point) {
		  alert(address + " not found");
		} else {
		  getGeoResults(point);
		}
	  }
	);
  }
}

function getGeoResults(point){
	// alert( "point = " + point.lat() + " : " + point.lng());
	var dist = 20;
	$.get("ajax_geo.php",{"lat":point.lat(),"lng":point.lng(),"dist":dist}, function(data, textStatus){
		resetLatLngBounds();
		map.clearOverlays(); // clear overlays
		showAddress(data, textStatus, point);
		// getBounds(map); // AMD: experiment bounds
	},"script");
}

function showAddress(data, textStatus, point) {
	eval(data); // create the new fpGeo JSON object.
	
	// only update new results after initial load.
	if (initialLoad != undefined && initialLoad == false){
		parseGeo(point);
	}
	initialLoad = false;
	
	function addGeoListener(tPoint, html, markerOptions){
		var geoMarker = new GMarker(tPoint, markerOptions );
		GEvent.addListener(geoMarker, "click", function() {
			geoMarker.openInfoWindowHtml(html);
		});
		return geoMarker;
	}
	
	for (var x = 0; x < fpGeo.communities.length ; x++){
		// Create our "blueIcon" marker icon
		var blueIcon = new GIcon();
		blueIcon.image = "http://www.flaggpole.com/images/fp_flagg_blue_angle.png";
		blueIcon.shadow = "http://www.flaggpole.com/images/fp_flagg_shadow_angle.png";
		blueIcon.iconSize = new GSize(26, 32);
		blueIcon.shadowSize = new GSize(40, 32);
		blueIcon.iconAnchor = new GPoint(7, 30);
		blueIcon.infoWindowAnchor = new GPoint(14, 0);
		markerOptions = { icon:blueIcon };
		
		var resultID = fpGeo.communities[x].communityID;
		var resultPermalink= fpGeo.communities[x].communityPermalink;
		var resultName = fpGeo.communities[x].communityName;
		var resultTypeName = fpGeo.communities[x].communityTypeName;
		var resultDescription = fpGeo.communities[x].communityDescription;
		var resultLat = fpGeo.communities[x].communityLatitude;
		var resultLng = fpGeo.communities[x].communityLongitude;
		var distance = fpGeo.communities[x].distance;
		var html = "<div class='communityPop' style='width: 250px;'><h3><a href='" + resultPermalink + "'>" + resultName + "</a> <em>(" + resultTypeName + ")</em></h3>" + resultDescription + "</div>";
		
		map.addOverlay(addGeoListener(new GLatLng(resultLat, resultLng), html, markerOptions));
		
		buildLatLngBounds(Number(resultLat), Number(resultLng));
	}
	
	var marker = new GMarker(point);
	
	if(mapIsDraggable){
		GEvent.addListener(marker, "dragend", function() {
			$("#communityLatitude").attr("value", marker.getLatLng().lat() );
			$("#communityLongitude").attr("value", marker.getLatLng().lng() );
		});
	}
	map.addOverlay(marker);
	buildLatLngBounds(Number(point.lat()), Number(point.lng()));
	
	if(fpGeo.communities.length > 0){
		scaleToMarkers(point, Number(minX), Number(maxX), Number(minY), Number(maxY));
	}
	else {
		map.setCenter(point, map.getZoom());
	}
}

function showFlaggpole(point) {
	var blueIcon = new GIcon();
	blueIcon.image = "http://www.flaggpole.com/images/fp_flagg_blue_angle.png";
	blueIcon.shadow = "http://www.flaggpole.com/images/fp_flagg_shadow_angle.png";
	blueIcon.iconSize = new GSize(26, 32);
	blueIcon.shadowSize = new GSize(40, 32);
	blueIcon.iconAnchor = new GPoint(7, 30);
	blueIcon.infoWindowAnchor = new GPoint(14, 0);
	if(mapIsDraggable){
		markerOptions = { icon:blueIcon, draggable:true };
	}
	else {
		markerOptions = { icon:blueIcon };
	}
		
	var marker = new GMarker(point, markerOptions); // var marker = new GMarker(point);
	
	if($("#communityLatitude").length > 0){
		$("#communityLatitude").attr("value", marker.getLatLng().lat() );
		$("#communityLongitude").attr("value", marker.getLatLng().lng() );

		GEvent.addListener(marker, "dragend", function() {
			$("#communityLatitude").attr("value", marker.getLatLng().lat() );
			$("#communityLongitude").attr("value", marker.getLatLng().lng() );
		});
	}
	
	map.addOverlay(marker);
}

function scaleToMarkers(point, minX, maxX, minY, maxY){
	// alert("minX=" + minX + ", maxX=" + maxX + ", x=" + ((minX + maxX) / 2) + " | minY=" + minY + ", maxY=" + maxY + ", y=" + ((minY + maxY) / 2));
	var center = new GLatLng((minX + maxX) / 2, (minY + maxY) / 2);
	span = new GSize(Math.abs(maxX - minX), Math.abs(maxY - minY));

	slopWid = 0; slopHgt = 0; slopPercentage = .93;
	slopWid = span.width * slopPercentage / 200;
	slopHgt = span.height * slopPercentage / 200;

	var bounds = new GLatLngBounds(new GLatLng(minX-slopHgt, minY-slopWid), new GLatLng(maxX+slopHgt, maxY+slopWid));
	var zoom = map.getBoundsZoomLevel(bounds);
	map.setCenter(center, zoom);
}

// build bound for map
function resetLatLngBounds(){
	minX = null; maxX = null; minY = null; maxY = null;
}

function buildLatLngBounds(rLat, rLng){
	if (minX == null) {
		minX = rLat; maxX = rLat; minY = rLng; maxY = rLng;
	}
	else {
		if (rLat < minX) minX = rLat;
		if (rLat > maxX) maxX = rLat;
		if (rLng < minY) minY = rLng;
		if (rLng > maxY) maxY = rLng;
	}
}

function showImageUpload(data,size){
	eval(data);
	
	if (fpImageUpload.photoPath != undefined) {
		$("#photoUploadLabel").html("<img src='" + fpImageUpload.photoPath + "' border='0' />");
		$("#uploadID").val(fpImageUpload.photoID);
		$("#postImage").val("");
	}
}

function showCharCount(currentElement, eventType, countElement, inputMax){
	if (eventType == "clear"){
		$(countElement).html("");
	}
	else if (eventType == "update"){
		charsLeft = (createPostChars[inputMax] - $(currentElement).val().length);
		$(countElement).html("<em>" + charsLeft + "</em> characters left");
	}
}

function validateAndSubmit(formID){
	var theFormArray = eval(formID + "Validator");
	var hasError = false;
	
	for(var v=0; v < theFormArray.length; v++){	
		if(theFormArray[v][1] && ($("#" + theFormArray[v][0]).val() == "" || $("#" + theFormArray[v][0]).val() == $("label[for=" + theFormArray[v][0] + "]").text()) ){
			hasError = true;
		}
	}
	
	if(! hasError){
		for(var v=0; v < theFormArray.length; v++){
			if($("#" + theFormArray[v][0]).val() == $("label[for=" + theFormArray[v][0] + "]").text()){
				$("#" + theFormArray[v][0]).val("");
			}
		}
		$('#' + formID).submit();
	}
	else {
		alert("Opps, you need to fill out title and description to submit a post.");
		return false;
	}
	
}

function moreTags(target, communityID, popDirection, popWidth){
	$(".popover").css("top","-1000px").css("width", (popWidth+65) + "px");
	$(".popInnerWrapper").html("Additional tags:<br>" + $("#hiddenToggle").html() );
	
	$(".popover").removeClass("popRight").removeClass("popLeft");
	$(".popover").css("top", ($(target).offset().top + $(target).outerHeight() + "px"));
	$(".popover").css("left", ($(target).offset().left - ($(".popover").outerWidth() - $(target).outerWidth() - 16) + "px"));
}

function showComments(postID){
	htmlMsg = "";
	for(var x=0; x < fpComment.comments.length; x++) {
		htmlMsg += "<span class='comment'><img src='images/comment.gif' width='14' height='13' /> <a href='profile.php?uID=" + fpComment.comments[x].commentUserID + "'>" + fpComment.comments[x].commentUserHandle + "</a> says, <span class='commentBody'>\"" + fpComment.comments[x].commentMsg + "\"</span>";
		if (authUserID == fpComment.comments[x].commentUserID) {
			htmlMsg += " <a href='handler_comment.php?fT=delete&cID=" + communityID + "&pID=" + fpComment.postID + "&comID=" + fpComment.comments[x].commentID + "' class='confirm'>Delete</a>";
		}
		htmlMsg += "</span>";
	}
	$("#comments-" + postID).html(htmlMsg);
	
	if ($("#post-" + postID + " .createComment")){
		$("#post-" + postID + " .createComment").show();	
	}
}

function showComment(postID) {
	$("#post-" + postID + " .createComment").show();
}

function getComments(postID){
	$.post("ajax_comments.php", { "postID":postID }, function(data, textStatus){
		if(textStatus == "success"){
			eval(data);
			showComments(postID);
			setConfirm();
		}
		else {
			// some alert message here.	
		}
	},"script");
}

function getEnlargement(target, imageID, popDirection, popWidth){
	clearTimeout(popoverHideTimer);
	$(".postPhoto img").css("cursor","default");
	
	if(imageID != popoverDetails){
		clearTimeout(popoverShowTimer);
		$(".postPhoto img").css("cursor","progress");
		$(".popover").css("top","-1000px");
		popoverDetails = imageID;
		popoverShowTimer = setTimeout(function(){	
			$.post("ajax_image_enlargement.php", { "imageID":imageID }, function(data, textStatus){
				if(textStatus == "success"){
					$(".postPhoto img").css("cursor","default");
					eval(data);		
					showPop(target, popDirection, popWidth);
				}
				else {
					// some alert message here.	
				}
			},"script");
		}, 500);
	}
}


function hidePopover(duration){
	popoverHideTimer = setTimeout(function(){
	   clearTimeout(popoverShowTimer);
	   clearTimeout(popoverHideTimer);
	   popoverDetails = null;
	   $(".popover").css("top","-1000px");
   }, duration);
}

function showPop(target, popDirection, popWidth){
	$(".popover").css("top","-1000px").css("width", (popWidth+65) + "px");
	$(".popInnerWrapper").html("<img src='" + fpImageEnlargement.imagePath + "' width='" + fpImageEnlargement.imageWidth + "' height='" + fpImageEnlargement.imageHeight + "' border='' />");
	
	// no fade for png-24 in ie.
	if(jQuery.browser.msie == false){
		$(".popover").hide();
	}
	
	if (popDirection == "right"){
		$(".popover").removeClass("popRight").addClass("popLeft");
		$(".popover").css("top", ($(target).offset().top - (($(".popover").outerHeight() - $(target).outerHeight()) / 2)) + "px");
		$(".popover").css("left", ($(target).offset().left + $(target).outerWidth() )  + "px");
	}
	else if (popDirection == "left"){
		$(".popover").removeClass("popLeft").addClass("popRight");
		$(".popover").css("top", ($(target).offset().top - (($(".popover").outerHeight() - $(target).outerHeight()) / 2)) + "px");
		$(".popover").css("left", ($(target).offset().left - $(".popover").outerWidth() ) + "px");
	}
		
	// no fade for png-24 in ie.
	if(jQuery.browser.msie == false){
		$(".popover").fadeIn(500);
	}
}

function imagePreview(size){
	if ($("#postImage").val() != ""){
		$.ajaxFileUpload({
			url:'ajax_image_handler.php?sizeXY=' + size, 
			secureuri:false,
			fileElementId:'postImage',
			dataType: 'text',
			success: function (data, status){
				showImageUpload(data,size);
				/*
				if(typeof(data.error) != 'undefined'){
					if(data.error != '')
					{
						alert(data.error);
					}else
					{
						alert(data.error);
					}
				}
				*/
			},
			error: function (data, status, e)
			{
				alert(e);
			}
		});
		return false;
	}
}

function clearNodes(){
	if($(this).html() == "") {
		$(this).remove();	
	}
	else {
		$(this).css('height','auto');	
	}
}

function easeDisplay(){
	$("#results span.pWrapper").each(function(){
		var newHeight = 0;
		$(this).find("div.nodeItem").each(function(){
			newHeight += $(this).height(); // + 1;
		})
		$(this).animate({ height: newHeight}, animateDuration, clearNodes);
	})
}

function buildGeoResultSummary(resultCnt, tlat, tlng){
	var returnHTML = "<div style='float: right;'>";
	if (authUserID != 0) {
		returnHTML += "<a href='communityBuilder.php?lat=" + tlat + "&lng=" + tlng + "' class='btn'><span>Start a flaggpole!</span></a>";
	}
	else {
		returnHTML += "Log In to start a community here.";
	}
	returnHTML += "</div>";
	
	if (resultCnt > 0){
		returnHTML += "Nearby communities... ";
	}
	else {
		returnHTML += "Sorry, no nearby communities found... ";
	}
	
	return returnHTML;
}

function buildGeo(node){
	var returnHTML = "<div class='nodeItem'><div class='community'><img src='images/fp_flagg_blue_angle.png' class='result_icon' width='26' height='30' /><h3><a href='" + node.communityPermalink + "'>" + node.communityName + "</a> ";
	returnHTML += "<em>(" + node.communityTypeName + ") " + node.distance + " mi. away</em></h3>" + node.communityDescription + "</div></div>";
	
	return returnHTML;
}

function buildPost(node){
	var returnHTML = "<div class='nodeItem'><div class='post'><a href='profile.php?uID=" + node.authorID + "' class='userPhoto'>";
	if (node.userImage != "" && node.userImage != "0") {
		returnHTML += "<img src='" + node.userImage + "' width='" + node.userImageWidth + "' height='" + node.userImageHeight + "' />";
	}
	else {
		returnHTML += "<img src='images/headshot.gif' width='48' height='48' />";
	}
	returnHTML += "<div>" + node.authorHandle + "</div></a>";
	if (node.postImage != "" && node.postImage != "0") {
		returnHTML += "<span class='postPhoto'><span><img height='" + node.postImageHeight + "' width='" + node.postImageWidth + "' src='" + node.postImage + "' onMouseOver='javascript: getEnlargement(this, " + node.postImageID + ", \"right\", 300);' onMouseout='javascript: hidePopover(500);' /></span></span>";
	}
	returnHTML += "<span class='tag'>" + node.tagName + "</span>";
	returnHTML += "<h3>" + node.postTitle + " <em>" + node.postTitleModifier + "</em></h3>";
	returnHTML += node.postMsg;
	if (node.authorID == authUserID) {
		returnHTML += " (<a href='javascript: void(0);' onclick='showComment(" + node.postID + ");'>Comment</a> | <!--<a href='#?pID=" + node.postID + "'>Edit</a> |--> <a href='handler_post.php?pID=" + node.postID + "&fT=delete' class='confirm'>Delete</a>)";
	}
	else if (authUserID != 0) {
		returnHTML += " (<!-- <a href='#?pID=" + node.postID + "'>Bookmark</a> | --><a href='javascript: void(0);' onclick='showComment(" + node.postID + ");'>Comment</a>)";
	}
	else {
		returnHTML += " (<a href='index.php'>Log in to comment</a>)";
	}
	returnHTML += " <span class='lifespan'>Posted " + node.postLife + ".</span>";

	returnHTML += "<div class='comments' id='comments-" + node.postID + "'>";
	if(node.postCommentMsg != ""){
		returnHTML += "<span class='comment'><img src='images/comment.gif' width='14' height='13' /> <a href='profile.php?uID=" + node.commentUserID + "'>" + node.commentHandle + "</a> says, <span class='commentBody'>\"" + node.postCommentMsg + "\"</span> &raquo; <a href='javascript: void(0);' onclick='javascript: getComments(\"" + node.postID + "\");'>" + node.commentCount + "</a></span>";
	}
	returnHTML += "</div>";
	
	if(authUserID != 0){
		returnHTML += "<div class='comments'><span class='createComment'><form action='handler_comment.php' method='post' enctype='text/plain' class='commentBody'><input type='hidden' name='fT' value='add' /><input type='hidden' name='cID' value='" + communityID + "' /><input type='hidden' name='pID' value='" + node.postID + "' /><label for='commentMsg-" + node.postID + "'>Write a comment...</label><textarea name='commentMsg' id='commentMsg-" + node.postID + "' wrap='virtual' rows='2' cols='50' ></textarea><br /><span class='showCmtCount cmtCnt_" + node.postID + "'></span><button type='submit'><span class='btn'><span>Comment</span></span></button></form></span></div>";
	}
	else {
		returnHTML += "<div class='comments'></div>";
	}

	returnHTML += "</div></div>";
	
	return returnHTML;
}

function parseGeo(point){
	$("#resultSummary").html(buildGeoResultSummary(fpGeo.communities.length, point.lat(), point.lng() ));	
	$("#emptyMsg").remove();
	$("#loadIndicator").addClass("hide");
	var itemCursor = null; var tempArray = new Array();
		
	if (fpGeo.communities != undefined && fpGeo.communities.length > 0){
		for(var i=0; i < fpGeo.communities.length; i++) {
			var tGeo = fpGeo.communities[i];
			tempArray[tempArray.length] = tGeo.communityID;
			// if the node doesn't exist...
			if($("#community-" + tGeo.communityID).length == 0) {
				if(itemCursor == null){
					// if there are no posts, create the first one.
					if($("#results span:first").length > 0){
						$("#results span:first").before("<span id='community-" + tGeo.communityID + "' class='pWrapper' style='height: 0px;'></span>");
					}
					else {
						$("#results").html("<span id='community-" + tGeo.communityID + "' class='pWrapper' style='height: 0px;'></span>");
					}
				}
				else {
					// alert($(itemCursor));
					$(itemCursor).after("<span id='community-" + tGeo.communityID + "' class='pWrapper' style='height: 0px;'></span>");
				}
				// inject content into the placeholder.
			}
			itemCursor = "#community-" + tGeo.communityID;
			$(itemCursor).html(buildGeo(tGeo));
		}
	}
	else if (fpGeo.communities == undefined){
		$("#emptyMsg").remove();
		$("#results").prepend("<span id='#emptyMsg' style='height: 0px;'><div class='nodeItem'><span class='red'>No posts available.</span></div></span>");
	}
	
	// delete content from display not in the list.
	$("#results span.pWrapper").each(function(){
		var tGeoID = $(this).attr("id");
		var tGeoExists = false;
		for(var a=0; a < tempArray.length; a++){
			if ("community-" + tempArray[a] == tGeoID){
				tGeoExists = true;	
			}
		}
		if(tGeoExists == false){
			var innerHeight = $(this).find("div.nodeItem").height();
			$(this).empty().css('height',innerHeight);
		}
	})
	
	// remove border on first element in the grid.
	$("#results span.pWrapper").removeClass("firstResult");
	if(tempArray.length > 0){
		$("#community-" + tempArray[0]).addClass("firstResult");
	}
	// reveal transition.
	easeDisplay();
}


function parsePost(data, textStatus){
	if(! isPaused){
		eval(data);
		$("#loadIndicator").addClass("hide");
		var itemCursor = null;

		if (fpData.funct == "togglePost"){
			if (fpData.lastUpdate){
				communityTimestamp = fpData.lastUpdate;
			}
			
			var tempArray = new Array();
			if (fpData.posts != undefined && fpData.posts.length > 0){
				
				$("#emptyMsg").remove();
				for(var i=0; i < fpData.posts.length; i++) {
					var tPost = fpData.posts[i]; // .postID;
					tempArray[tempArray.length] = tPost.postID;
					
					if(($("#post-" + tPost.postID).length == 0) || ($("#post-" + tPost.postID).attr("postcommentdate") != tPost.postCommentDate)) {
						if($("#post-" + tPost.postID).length > 0){
							$("#post-" + tPost.postID).html(buildPost(tPost));
							$("#post-" + tPost.postID).attr({"postdate":tPost.postDate,"postcommentdate":tPost.postCommentDate});
						}
						else {
							if(itemCursor == null){
								// if there are no posts, create the first one.
								if($("#results span:first").length > 0){
									$("#results span:first").before("<span id='post-" + tPost.postID + "' class='pWrapper' style='height: 0px;'></span>");
								}
								else {
									$("#results").html("<span id='post-" + tPost.postID + "' class='pWrapper' style='height: 0px;'></span>");
								}
							}
							else {
								$(itemCursor).after("<span id='post-" + tPost.postID + "' class='pWrapper' style='height: 0px;'></span>");
							}
							// inject content into the placeholder.
							$("#post-" + tPost.postID).html(buildPost(tPost));
							$("#post-" + tPost.postID).attr({"postdate":tPost.postDate,"postcommentdate":tPost.postCommentDate});
							setConfirm();
						}
					}
					itemCursor = "#post-" + tPost.postID;
				}
	
				modifyForm();
				$("form.commentBody").unbind('submit');
				$("form.commentBody").submit(function(){
					postComment($(this).find("[name=pID]").val());
					$(this).find("textarea").val("");
					return false;
				});
			}
			else if (fpData.posts == undefined){
				$("#emptyMsg").remove();
				$("#results").prepend("<span id='#emptyMsg' style='height: 0px;'><div class='nodeItem'><span class='red'>No posts available.</span></div></span>");
			}
			
			// delete content from display not in the list.
			$("#results span.pWrapper").each(function(){
				$(this).removeClass("firstResult");
				var tPostID = $(this).attr("id");
				var tPostExists = false;
				for(var a=0; a < tempArray.length; a++){
					if (("post-" + tempArray[a]) == tPostID){
						tPostExists = true;	
					}
				}
				if(tPostExists == false){
					var innerHeight = $(this).find("div.nodeItem").height();
					$(this).empty().css('height',innerHeight);
				}
			})
			
			// remove border on first element in the grid.
			if(tempArray.length > 0){
				$("#post-" + tempArray[0]).addClass("firstResult");
			}
			
			easeDisplay();
			registerComments();
			
			if($("#feedAlertOuter").height() > 0){
				$("#feedAlertContent").hide(); $("#feedAlertOuter").animate({height:0});
			}
		}
		else if (fpData.funct == "ping"){	
			if(fpData.state == "update" && continuousUpdate){
				getPostUpdate();
			}
			else if (fpData.state == "update"){
				if($("#feedAlertOuter").height() == 0){
					$("#feedAlertContent").show(); $("#feedAlertOuter").animate({height:$("#feedAlertInner").height()});
					$("#feedRefresh").unbind('click'); $("#feedRefresh").click(function() {
						getPostUpdate();
					});
					$("#continuous").unbind('click'); $("#continuous").click(function() {
						continuousUpdate = true;
					});
				}
			}
		}
	}
}

function postComment(pID){
	$.post("handler_comment.php", { "commentMsg":$("#commentMsg-" + pID).val(),"cID":communityID,"pID":pID,"fT":"add","clientDatestamp":communityTimestamp,"return":0 }, function(data, textStatus){
		if(textStatus == "success"){
			eval(data);
			getComments(pID);
			if(fpCommentTS.state == "update"){
				getPostUpdate();
			}
			else {
				communityTimestamp = fpCommentTS.lastUpdate;
			}
		}
	});	
}

function getPostUpdate(ping){
	clearInterval(postTimer);
	
	if(!ping){ ping=false; }
	
	var toggleArray = new Array();
	$("ul.tagToggle li").each(function(){
		if ($(this).find("input:checkbox").is(":checked") == true){
			toggleArray[toggleArray.length] = $(this).find("input:checkbox").val();
		}
	})

	var datestamp = "";
	if(ping){ 
		datestamp = communityTimestamp;
	}
	
	// alert("ping:" + ping + ",feedToggle[]:" + toggleArray + ",cID:" + communityID + ",datestamp:" + communityTimestamp);
	$.post("ajax_posts.php", { "feedToggle[]":toggleArray,"cID":communityID,"datestamp":datestamp }, function(data, textStatus){
		parsePost(data, textStatus);
	},"script");
}

function toggleSwatch(){
	clearInterval(postTimer);

	$("ul.tagToggle li:not(.listLabel,.moreTag)").each(function(){
		if ($(this).find("input:checkbox").is(":checked") == true){
			$(this).addClass("active");
		}
		else {
			$(this).removeClass();
		}
	})
	
	$("#loadIndicator").removeClass("hide");
	postTimer = setInterval(getPostUpdate, pauseDuration, false);
}


function setConfirm(){
	$("a.confirm").each(function(){
		$(this).attr({href:"javascript: if(confirm('Are you sure you want to delete this?')){ window.location='" + $(this).attr("href") + "'; };"});
		$(this).removeClass("confirm");
	});
}

function siteEnabled(tempCID){
	$.get("handler_community.php", { "fT":"watch", "cID":tempCID }, function(data, textStatus){
		if(textStatus == "success"){
			$("#jSitContainer").html("<strong class='red' style='line-height: 22px;'>Following</strong> <span class='whatsThis'>(<a href='javascript:void(0);' name='" + communityID +"' id='jSitCancel'>Cancel</a>)</span>");
			$("#jSitCancel").click(function() {
				sitCancel(tempCID);		  
			});
		}
	},"script");
}

function sitCancel(tempCID){
	$.get("handler_community.php", { "fT":"unwatch", "cID":tempCID }, function(data, textStatus){
		if(textStatus == "success"){
			$("#jSitContainer").html("<a href='javascript:void(0);' id='jSit' class='btn' name='" + communityID +"'><span>Follow</span></a>&nbsp;<span class='whatsThis'>(<a href='javascript:void(0);'>What's this?</a>)</span>");
			$("#jSit").click(function() {
				siteEnabled(tempCID);		  
			});
		}
	},"script");
}

function pausePostUpdates(){
	clearInterval(updtTimer);
	isPaused = true;
}

function getTags(comTypeID){
	$(".selectTagLoader").css("display","inline");
	$.post("ajax_tags.php", { "funct":"getTag","comTypeID":comTypeID }, function(data, textStatus){
		parseTags(data, textStatus);
	},"script");
}

function addTag(){
	var newTagName = $("#newTagName").val();
	var newTagNameLabel = $("label[for=newTagName]").text();
	var newTagPrompt = $("#newTagPrompt").val();
	var newTagPromptLabel = $("label[for=newTagPrompt]").text();
	$(".newTagBtn").hide(); $(".newTagLoader").show();
	
	if(newTagName == newTagNameLabel || newTagPrompt == newTagPromptLabel){
		alert("Opps, you need to provide a tag name and prompting question.");
	}
	else {
		$.post("handler_tag.php", { "funct":"add","newTagName":newTagName,"newTagPrompt":newTagPrompt }, function(data, textStatus){
			updateTags(data, textStatus);
		},"script");
	}
}

function updateTags(data, textStatus) {
	eval(data);
	
	if(fpData.funct == "newTag"){
		var tagHTML = "<div class='t_tag'><label><input type='checkbox' checked='checked' value='" + fpData.tagID + "' id='t_" + fpData.tagID + "' name='communityTag[]' class='current' /> " + fpData.tagName + "</label> <span class='grey'>(New tag)</span></div>";
		$(".tagList").append(tagHTML);
		$("#newTagName").val("");
		$("#newTagPrompt").val("");
		$('.newTag_link').show();$('.newTag_form').hide();
		$(".newTagBtn").show(); $(".newTagLoader").hide();
		$(".newTag").removeClass("greyBox");
		fieldPopulate($("#newTagName"),'blur');
		fieldPopulate($("#newTagPrompt"),'blur');
	}
}

function parseTags(data, textStatus){
	eval(data);
	
	// clear unchecked boxes;
	$(".t_tag").each(function(){
		if($(this).find("input[class!=current]").length > 0) { // && $(this).find("input:checkbox").is(":checked") == false){
			$(this).remove();
		}
	});
	// add new tags.
	var tags = fpTagType.tags; var tagHTML = $(".tagList").html();
	for(var a = 0; a < tags.length; a++){
		tagID = tags[a].tagID;
		tagName = tags[a].tagName;
		tagPrompt = tags[a].tagPrompt;
		if($("#t_" + tagID).length == 0){
			tagHTML += "<div class='t_tag'><label><input type='checkbox' name='communityTag[]' id='t_" + tagID + "' value='" + tagID + "' checked='checked' /> " + tagName + "</label></div>";
		}
	}
	$(".tagList").html(tagHTML);
	$(".selectTagLoader").css("display","none");
}

function validateCommunity(){
	var formState = true;
	if($("#communityName").val() == "" || $("#communityName").val() == $("label[for=communityName]").text()){
		formState = false;
		alert("You must provide a community name.");
	}
	else if($("#communityDescription").val() == "" || $("#communityDescription").val() == $("label[for=communityDescription]").text()){
		formState = false;
		alert("You must provide a community description.");
	}
	else if($("#communityTypeID option:selected").val() == ""){
		formState = false;
		alert("You must provide a community type.");
	}
	else if($("input:checked").length < 1){
		formState = false;
		alert("You must add or select one or more tags.");
	}
	return formState;
}

function validateProfile(){
	var formState = true;
	if($("#profilePassword_1").val() == "" || $("#profilePassword_1").val() != $("#profilePassword_2").val()){
		formState = false;
		alert("Your passwords don't match.");
	}
	else if($("#profileName").val() == "" || $("#profileName").val() == $("label[for=profileName]").text()){
		formState = false;
		alert("Your must provide a profile name.");
	}
	else if($("#tosConfirm").is(":checked") == false){
		formState = false;
		alert("You must accept the Terms of Service to continue.");
	}
	return formState;
}

function fieldPopulate(field,e){
	// alert("fieldPopulate: " + field + " | " + e);
	
	tempID = field.attr("id");
	if(e == "focus"){
		field.css("color","#000000");
		if (field.val() == $("label[for=" + tempID + "]").text() && ! $("#" + tempID ).hasClass("traditional")) {
			field.val("");
		}	
	}
	else if(e == "blur"){
		if (field.val() == "" && ! $("#" + tempID ).hasClass("traditional")){
			field.css("color","#999999").val($("label[for=" + tempID + "]").text());
		}
		else if (field.val() == $("label[for=" + tempID + "]").text()){
			field.css("color","#999999");
		}
	}
	else if(e == "load" && ! $("#" + tempID ).hasClass("traditional") && $("#" + tempID ).attr("value") == ""){
		tempLabel = $("label[for=" + tempID + "]").text();
		field.css("color","#999999").val(tempLabel);
	}
}

function modifyForm(){
	if(isInitialized == false){
		$("input[type=text],textarea").unbind();

		$("input[type=text],textarea").each(function(){ 
			fieldPopulate($(this),"load");
		});
		$("input[type=text],textarea").click(function(){ 
			fieldPopulate($(this),"focus");
		});
		$("input[type=text],textarea").focus(function(){ 
			fieldPopulate($(this),"focus");	
		});
		$("input[type=text],textarea").blur(function(){
			fieldPopulate($(this),"blur");
		});
		
		isInitialized = true;
	}
}

function registerComments(){
	$("#results textarea[name=commentMsg]").focus(function(){ 
		fieldPopulate($(this),"focus");
		t = $(this).attr("id");
		commentUpdate = ".cmtCnt_" + t.split("-")[1]
		showCharCount(this, "update", commentUpdate, "postComment"); 
	});	
	
	$("#results textarea[name=commentMsg]").keyup(function(){ 
		t = $(this).attr("id");
		commentUpdate = ".cmtCnt_" + t.split("-")[1]
		showCharCount(this, "update", commentUpdate, "postComment"); 
	});	
	
	$("#results textarea[name=commentMsg]").blur(function(){ 
		t = $(this).attr("id");
		commentUpdate = ".cmtCnt_" + t.split("-")[1]
		showCharCount(this, "clear", commentUpdate, "postComment"); 
	});
}

function registerCreatePost(){
	$("#createPost input[type=text],#createPost textarea[id=postMsg]").focus(function(){ 
		fieldPopulate($(this),"focus");
		showCharCount(this, "update", "#createPost span.showPostCount", $(this).attr("id")); 
	});
	
	$("#createPost input[type=text],#createPost textarea[id=postMsg]").keyup(function(){ 
		showCharCount(this, "update", "#createPost span.showPostCount", $(this).attr("id")); 
	});	
	
	$("#createPost input[type=text],#createPost textarea[id=postMsg]").blur(function(){ 
		showCharCount(this, "clear", "#createPost span.showPostCount", $(this).attr("id")); 
	});	
}



$(document).ready(function(){
	modifyForm();
	
	if($("ul.tagToggle").length > 0){	
		$("ul.tagToggle input:checkbox").click(function() {
			setTimeout(toggleSwatch, 10);
		});
	}

	if($("#results form.commentBody").length > 0){
		$("#results form.commentBody").submit(function(){
			postComment($(this).find("[name=pID]").val());
			$(this).find("textarea").val("");
			return false;
		});
	}
	
	if($("ul.tagToggle").length > 0) {
		updtTimer = setInterval("getPostUpdate(true)", 15000);
	}
	if($("#feedAlertContent").length > 0) {
		$("#feedAlertOuter").animate({height:0});
	}

	if($("#jSit").length > 0){
		$("#jSit").click(function() {
			siteEnabled($(this).attr("name"));
		});
	}
	
	if($("#jSitCancel").length > 0){
		$("#jSitCancel").click(function() {
			sitCancel($(this).attr("name"));
		});
	}
	
	if($("#createPost").length > 0){
		registerCreatePost();
	}
	
	if($("#results textarea[name=commentMsg]").length > 0){
		registerComments();
	}
	
	if($("a.confirm").length > 0){
		setConfirm();
	}

	if($("#results").length > 0){
		easeDisplay();	
	}


	/* community setup */
	if($("#communityTypeID").length > 0) {
		$("#communityTypeID").change(function(){ 
			getTags($("#communityTypeID").val());			  
		});
	}
});
