//Form options for comments form.
var commentFormOptions = {  
	success:       loadInComment,  // post-submit callback 
    beforeSubmit:  preCommentSubmit,  // pre-submit callback
    url:       '/zw/comments?layout=ajax'
}; 

var submittedCommentForm = undefined;
var commentContent = undefined;
	
$(document).ready(function() {
	
	//Hide anything flagged to be hidden
	$(".jsHide").hide();
	
	//$("input").
	//<img alt="Please wait..." src="/img/loaderpink.gif"/>
	$("input.commentSubmit").live("click", function(){
		$(this).hide().after('<img alt="Please wait..." src="/img/loaderpink.gif" class="commentPleaseWait" />');
		return true;
	});
	
	//Scroll to links
	$("a.scrollTo").click(function() {
		$.scrollTo($($(this).attr('href')),800, {onAfter: function() {
			$("#spotlightSearchField").effect("highlight", {color:"#EB1049"}, 500);
			$("#spotlightSearchField").val('').focus();
		}});
		return false;
	});
	
	$("a.scrollToNearby").click(function() {
		$.scrollTo($($(this).attr('href')),800, {onAfter: function() {
			$(".mini",".spotlightZubsNearby").effect("highlight", {color:"#EB1049"}, 1000);
		}});
		return false;
	});		
	



	//http://simonwillison.net/2006/Jan/20/escape/
    RegExp.escape = function(text)
    {
      if (!arguments.callee.sRE) {
        var specials = [
          '/', '.', '*', '+', '?', '|',
          '(', ')', '[', ']', '{', '}', '\\'
        ];
        arguments.callee.sRE = new RegExp(
          '(\\' + specials.join('|\\') + ')', 'g'
        );
      }
      return text.replace(arguments.callee.sRE, '\\$1');
    }
	
	//Open external links in new window. Hate this!
	$('a').each(function()
	{
		var host = document.location.host;
		var regExpEscapedHost = RegExp.escape(host);
        var outOfHostUrl  =  new RegExp("^(([a-z0-9]*:)?//(?!" + regExpEscapedHost + "(/|$)))", 'i');
        /* 
            ([a-z0-9]*:)?                           optional protocol identifier that may prefix '//'
            //                                      '//' indicates a different host. If it's present then open in a new window unless...
            (?!" + regExpEscapedHost + "(/|$)))"    the // is followed by the current host name. (/|$) ensures that the host name terminates. 
                                                    without (/|$) 'zubworld.com' and 'zubworld' would both match if the current host was 'zubworld'
        */
        var anchor = $(this);
        if( anchor.attr('href') )
        {
			if(anchor.attr('href').match(outOfHostUrl))
			{
				anchor.attr('target', '_blank');
			}
        }
    });

	
	
	
	
	
	
	
	
	//For login form
	$("#Username").focus();

	//Search box
	$("#lnkSearch").click(function(e){
		$("#formGlobalSearch").slideDown(300);
		$("#searchField").focus();
		return false;
	});

	$("#lnkSearchClose").click(function(e){
		$("#formGlobalSearch").slideUp(300);
		return false;
	});

	//Facy box style pop ups.
	$('a[rel*=facybox]').facybox();	

	//Anything that has been classed as lnkLogin will pop-up the login
	$('.lnkLogin,.trophy,.lnkReport').live("click", function(){

		var href = $(this).attr('href');
		
		if(href==undefined) {
			href = $(this).parents('form').attr('action');
		}
		
		if(href.indexOf('?') > 0) {
			href=href+'&layout=disable';
		} else {
			href=href+'?layout=disable';
		}
		
		//Ajax in the login form
		$.facybox({ ajax: href});
		
		//For some reason, we need to focus the username field after the content has been ajaxed in.
		$(document).bind('reveal.facybox', function() { $("#Username").focus(); });
		return false;
		
	});



	/**
	 * Register -> Follow
 	 */
    var followAlls = $('input.fFollowAll');	//there are 2 'follow all' checkboxes
    var followOnes = $('input.fFollow');
    //checked/unchecked all 'follow' checkboxes when a 'follow all' checkbox is checked/unchecked
	followAlls.click(function() 
	{
		var checkedStatus = $(this).attr('checked');
		followAlls.attr('checked', checkedStatus);
		
		followOnes.each(function() 
		{
    		$(this).attr('checked', checkedStatus);
		});
	});


    //uncheck 'follow all' checkboxes when a 'follow one' is unchecked	
	followOnes.click(function()
	{
        followAlls.attr('checked', '');
	});






	/**
	 * User page Tabs
	 */
	$(".userZubsTab").click(function() {
		
		showElement = ltrim($(this).attr('href'),'#');
		
		$(".body", "#wdgtZubsMain").hide();
		$("h3", "#wdgtZubsMain").removeClass('on');
		$(this).parents('h3').addClass('on');
		$("#" + showElement).show();
		return false;
	});

	/**
	 * Share tabs.
	 */
	$("a", "#shareTabs").click(function() {
		
		$("li", "#shareTabs").removeClass('on');
		$(this).parent('li').addClass('on');
		
		$(".shareTab").hide();
		$($(this).attr('href')).show();
		
		return false;
	});

	$("li", "#shareTabs").each(function() {
		if($(this).hasClass('on')) {
			$(".shareTab").hide();
			$($('a',this).attr('href')).show();
		}
	});

	$('#btnSelectLocation').click(function() {
		$.facybox({ ajax: '/zw/content/select-location/'});
		return false;	
	});

	$('a.expandCollapse').live("click", function(){
		var expandID = $(this).attr('href').replace(/#/, '');
		$('#'+expandID).toggle();
		if($(this).text() == '+') {
			$(this).text('-');
			$('input','#'+expandID)[0].focus();
		} else {
			$(this).text('+');
		}
		
		return false;
	});

	//Following/unfollowing
	$("a.lnkFollowZub,a.lnkUnfollowZub").live("click", function() {
		
		$("a.lnkFollowZub,a.lnkUnfollowZub").hide();
		$("img.loader").show();
		
		$.get($(this).attr('href'), { layout: "ajax" }, function(data) {
			
			maps = $('div#wdgtMap');
			$("#bodyContainer").replaceWith(data);
			$('div#wdgtMap').replaceWith(maps);
			
			prepCommentsForm();
		});

		return false;
	});
	
	
	prepCommentsForm();
	
	//The reply link that appears below comments.
	$('a.lnkComment','div.comment').live("click", function() { 
		
		var commentReplyContainer = $(this).parents('div.discussion');
		var commentForm = $("div.commentForm", commentReplyContainer);
		
		if($(this).hasClass('refocus')) {
			$("textarea", commentForm).focus();		
		} else {
			commentForm.show().removeClass('jsCollapsed');
			$("textarea", commentForm).val('').focus();
		}

		
		$(this).addClass('refocus');
		return false;
	});

	//When show earlier link is clicked to reveal other replies.
	$('a.showEarlier','div.replies').live("click", function() {
		var repliesContainer = $(this).parents('div.replies');
		$('p.replyCount',repliesContainer).remove();
		$('div.jsHide',repliesContainer).removeClass('jsHide').show();
		return false;
	});


	//Hide comment forms for discussions with no replies.
	$('textarea','div.commentForm.jsCollapsed').live("click", function() { 
		$(this).parents("div.commentForm").removeClass('jsCollapsed');
		$(this).val('');
	});
	

	$("#btnPostToFacebook").click(function() {
		facebookPublish($("#facebookShareMessage").val());
		return false;
	});
	
	
	
	
	//Ferenc: load more wdgtWall comments
	$('#wdgtWall .lnkShowMore').live("click", function() {
		 //alert($("#wdgtWall").css('height'));
		 $("span.discussionSpinner").show();
		 newcontent = undefined;
		 $.get($(this).attr('href'), function(data, status) {
			  newcontent = data;
			  
			  var first = true;
			  var scrollToElement = undefined;
			  $('#wdgtWall div.discussions div.discussion', data).each(function() {

				  $(this).appendTo('#wdgtWall div.discussions');
				  	
				  if(first) {
					  scrollToElement = this;
					  first = false;
				  }
				  
			  });

			  $('#wdgtWall a.lnkShowMore').replaceWith( $('#wdgtWall a.lnkShowMore', data));
			  
			  //$.scrollTo(scrollToElement, 800, {onAfter: function() {}});
				 prepCommentsForm();
				 $("span.discussionSpinner").hide();

		  });

		  return false;
		  
	});
	
	
	
	//Ferenc: load more  zubActivity
	$('#zubActivity .lnkShowMore').live("click", function() {
		 //alert($("#wdgtWall").css('height'));
		 $("span.activitySpinner").show();
		 newcontent = undefined;
		 $.get($(this).attr('href'), function(data, status) {
			  newcontent = data;
			  
			  var first = true;
			  var scrollToElement = undefined;
			  $('#zubActivity div.discussions div.discussion', data).each(function() {

				  $(this).appendTo('#zubActivity div.discussions');
				  	
				  if(first) {
					  scrollToElement = this;
					  first = false;
				  }
				  
			  });

			  $('#zubActivity a.lnkShowMore').replaceWith( $('#zubActivity a.lnkShowMore', data));
			  
			  //$.scrollTo(scrollToElement, 800, {onAfter: function() {}});
			  $("span.activitySpinner").hide();

		  });

		  return false;
		  
	});
	
	
	
	
	//Ferenc: load more wdgtDiscussions
	$('#wdgtDiscussions .lnkShowMore').live("click", function() {
		//alert($("#wdgtWall").css('height'));
		 $("span.discussionSpinner").show();
		 newcontent = undefined;
		 $.get($(this).attr('href'), function(data, status) {
			  newcontent = data;
			  
			  var first = true;
			  var scrollToElement = undefined;
			  $('#wdgtDiscussions div.discussions div.discussion', data).each(function() {
	
				  $(this).appendTo('#wdgtDiscussions div.discussions');
				  	
				  if(first) {
					  scrollToElement = this;
					  first = false;
				  }
				  
			  });
	
			  $('#wdgtDiscussions a.lnkShowMore').replaceWith( $('#wdgtDiscussions a.lnkShowMore', data));
			  
			  //$.scrollTo(scrollToElement, 800, {onAfter: function() {}});
				 prepCommentsForm();
				 $("span.discussionSpinner").hide();
	
		  });
	
		  return false;
		  
	});

	
	
	
	//Ferenc: load more friends search result
	$('#show_more_friend_results .lnkShowMore').live("click", function() {
		//alert($("#wdgtWall").css('height'));
		 $("span.friendSpinner").show();
		 newcontent = undefined;
		 $.get($(this).attr('href'), function(data, status) {
			  newcontent = data;
			  
			  var first = true;
			  var scrollToElement = undefined;
			  $('div.listPeople.friendsResult div.person', data).each(function() {
	
				  $(this).appendTo('div.listPeople.friendsResult');
				  	
				  if(first) {
					  scrollToElement = this;
					  first = false;
				  }
				  
			  });
	
			  $('#show_more_friend_results a.lnkShowMore').replaceWith( $('#show_more_friend_results a.lnkShowMore', data));
			  
			  //$.scrollTo(scrollToElement, 800, {onAfter: function() {}});
				 prepCommentsForm();
				 $("span.friendSpinner").hide();
	
		  });
	
		  return false;
		  
	});


	
	
	//Ferenc: load more users search result
	$('#show_more_user_results .lnkShowMore').live("click", function() {
		//alert($("#wdgtWall").css('height'));
		 $("span.userSpinner").show();
		 newcontent = undefined;
		 $.get($(this).attr('href'), function(data, status) {
			  newcontent = data;
			  
			  var first = true;
			  var scrollToElement = undefined;
			  $('div.listPeople.usersResult div.person', data).each(function() {
	
				  $(this).appendTo('div.listPeople.usersResult');
				  	
				  if(first) {
					  scrollToElement = this;
					  first = false;
				  }
				  
			  });
	
			  $('#show_more_user_results a.lnkShowMore').replaceWith( $('#show_more_user_results a.lnkShowMore', data));
			  
			  //$.scrollTo(scrollToElement, 800, {onAfter: function() {}});
				 prepCommentsForm();
				 $("span.userSpinner").hide();
	
		  });
	
		  return false;
		  
	});
	
	/*
	//Ferenc: friend request: accept/decline friend requests.
	$('#content div.listPeople div.person div.requestMeta p.decision a').live("click", function() {
		$('#content div.listPeople div.person div.requestMeta p.decision').hide();
		
		$('#content div.head').append('<span class="beFriendSpinner" style="float: right; margin-right:0.3em"><img alt="Please wait..." src="/img/loaderpink.gif"></span>');
		
		$('div#poptarts_default').slideUp('slow', function()
		{
			$(this).remove();
		});
		
		$.get($(this).attr('href'), function(data, status) {
			
			//get the system's flash message
			$('div#poptarts_default', data).each(function() {
				$(this).prependTo($('#bodyContainer')).hide();
				$('div#poptarts_default').slideDown('slow');
			});
			
			//replace the content
			$('div#poptarts_default', data).each(function() {
				$('div#content div.wdgtPerson').replaceWith( $('div#content div.wdgtPerson', data));
				$("span.beFriendSpinner").hide();
			});
				
		});
		
		return false;
	});
	 */

	
	//Ferenc: friend request: accept/decline friend requests.
	$('#content div.listPeople div.person div.requestMeta p.decision a').live("click", function(event) 
	{
		if (event.button != 0) 
		{
		    // wasn't the left button - ignore
		    return true;
		}
		
		$(this).parents("div.requestMeta").replaceWith('<span class="beFriendSpinner" style="float: right; margin-right:0.3em"><img alt="Please wait..." src="/img/loaderpink.gif"></span>');

		$.get($(this).attr('href')+'?ajax=true', function(data, status) 
		{
			
			id = $("div.person",data).attr('id');
			
			$("#" + id).replaceWith($("div.person",data));
			$('.confirmedFriend').css('border', '5px solid #0f0');
			$('.rejectedFriend').css('border', '5px solid #EB1049');
			//get the system's flash message
			/*$('div#poptarts_default', data).each(function() {
				thisDialog.css('border', '5px solid #0f0');
				$("span.beFriendSpinner").hide();
				//thisDialog.replaceWith( this, data );
			});*/

            var decrementFriendsCounter = function()
            {
    			var newLabel = $('a.notification strong');
                var friendCount = parseInt(/^[0-9]*/.exec(newLabel.text())[0]);
    
                if (friendCount - 1 < 1)
                {
                    newLabel.parent().remove();
                } else 
                {
                    newLabel.text(friendCount-1 + ' new');
                }
			}();	
		});

		/*
		 * accepted: style="border: 5px solid #0f0"
		 * */
		
		return false;
		
	});


});//document ready


//pre-submit callback
function preCommentSubmit(formData, jqForm, options) {
    

    submittedCommentForm = jqForm[0];
    
    //Store comment so we can get it back when ajax comes back.
    commentContent = $('textarea', jqForm[0]).val();
    

    //Publish to Facebook if requested.
    if($('input.chkPostToFacebook', jqForm[0]).length==1 && $('input.chkPostToFacebook', jqForm[0])[0].checked) {
    	facebookPublishTemplate(commentContent);
    }
    
    $('button', jqForm[0]).attr("disabled", "true").addClass('disabled');
    return true;
}


//post-submit callback 
function loadInComment(responseText, statusText)  { 

	$('button', submittedCommentForm).attr("disabled", "").removeClass('disabled');
	
	var replies = $(submittedCommentForm).parents('div.replies');
	var parentCommentFormDiv = $(submittedCommentForm).parents('div.commentForm');
	
	if(replies.length == 1) {
		parentCommentFormDiv.before(responseText);
	} else {
		parentCommentFormDiv.after(responseText);
	}

	$(parentCommentFormDiv).addClass('jsCollapsed');
	
	//Reinsert default text.
	//$('textarea',parentCommentFormDiv).val($('label.CommentLabel',parentCommentFormDiv).text());
	prepCommentsForm();
	
}



//Comment form.
function prepCommentsForm() {
	$(".jsHide").hide();
	$('div.commentForm').addClass('jsCollapsed');
	$('textarea', 'div.commentForm').each(function() {
		$(this).val($('label.CommentLabel',$(this).parents('div.commentForm')).text());
	});
	
	$("input.commentSubmit").show();
    //bug fix: If the 'post comment' button is activate with a keyboard action it will retain focus, even if it becomes invisible.
    //We blur the control to prevent this.
	$("input.commentSubmit").blur();	    
	$("img.commentPleaseWait").remove();
	
	//On threaded discussions, hide comment form for replying to a comment when there are no replies yet.
	$('div.replies','div.discussion').each(function() {
		
		if($(this).parents('div.discussions').hasClass('threaded')) {
			if($('div.comment',this).length==0) {
				$('div.commentForm',this).hide();
			}
		}
	});
	
	 // bind form using 'ajaxForm' 
	$('form',"div.commentForm").ajaxForm(commentFormOptions); 

}



function trim(str, chars) {

	chars = chars || "\\s";
	return ltrim(rtrim(str, chars), chars);

}

function ltrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}

function rtrim(str, chars) {
	cchars = chars || "\\s";
	return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}

function trimString(value,length)
{

	if(value==null || trim(value).length<1){
		return "";
	}
	
	if(trim(value).length>0 && trim(value).length < length){
		return trim(value);
	}
	
	if(trim(value).length > length){
		return trim(trim(value).substring(0, length)) + "...";
	}
	
	return value;
}

/*
 * This function is called after the facebook connect button is clicked on the login.
 */
function facebookLoginConnected() {

	$('.body','#wdgtLogin').hide();
	$('#apresFacebook').show();
	
	location.href = '/zw/auth/facebook-auth';
}

function facebookConnect(redirect) {
	location.href = '/zw/auth/facebook-auth?redirect=' + escape(redirect);
}

function facebookRefresh(redirect) {
	location.href = redirect;
}


function facebookPublish(msg, attachment) {
  FB.ensureInit(function () {
    FB.Connect.streamPublish(msg, attachment);
  });
}

function facebookPublishTemplate(msg, attachment) {
	  FB.ensureInit(function () {
	    FB.Connect.streamPublish(msg, attachment);
	    
	    /*
	     * This was deprecated, see http://developers.facebook.com/docs/?u=facebook.jslib.FB.Connect.streamPublish
	     * var attachment = {'media': [{'type':'image',
	                             'src':'http://bit.ly/AJTnf',
	                             'href':'http://bit.ly/hifZk'}]};
	FB.Connect.streamPublish('', attachment);

 FB.Connect.showFeedDialog('153000789819',{"url":location.href},'',msg,null,FB.RequireConnect.promptConnect,null);
	*/
	  });
	}

