var fenceMore = 20;

if(jQuery)
{
	$.datepicker.setDefaults({ dateFormat: 'yy-m-d' });
	$(document).ready(function(){
		
	  bindPostCommentHandler();
	  
		$(".close-btn.show_on_start").click(function(){
			
					$.ajax({
				  		url: '/disablemessage',
			  			success: function(data) {
			  				
			  			}
					});
		});
		if($('#inviter').length>0)
		{
			$('#inviter').validate();
		}
		/*photo section code*/
		$('#id_new_album').click(function()
				{
				    if($('#id_new_album').attr('checked'))
				    {
				        $('#id_name').attr('disabled','');
				        $('#album').attr('disabled','disabled');
				    }else
				    {
				        $('#id_name').attr('disabled','disabled');
				        $('#album').attr('disabled','');
				    }
				});
		$('#id_name').click(function(){
		    if(!$('#id_new_album').attr('checked'))
		    {
		        $('#id_name:not(#fsearch #id_name)').attr('disabled','disabled');
		        $('#album').attr('disabled','');
		    }
		})
		if($('#photo_submit').length>0)
		{
			$('#photo_submit').click(function(){

				reg = new RegExp('.png|.jpg|.gif', "gi")
				var valid = true;
				var validCount = 0;
				$('input[type=file]').each(function(i,elem)
						{
							if($('input[type=file]').val().length>0&&$('input[type=file]').val().match(reg)==null)
							{
								valid = false;
							}else if($('input[type=file]').val().length>0)
							{
								validCount = validCount + 1;
							}
						})
				if(!valid)
				{
					alert('Sorry, you are only able to post images');
					return false;
				}else if(validCount == 0)
				{
					alert('Please select at least on photo to upload');
					return false;
				}
				if($('#album').val().length==0 && !$('#id_new_album').attr('checked'))
				{
					alert('Please select an album to upload to');
					return false;
				}

				$(this)
					.hide()
					.after('<img src="/site_media/images/ajax-loader.gif" alt="" />');
				return true;
			});
		}
		if($('.showmore').length>0)
		{
			$('.showmore').click(function(){
				//replace with loading background
				$(this).css({'background': 'url(/site_media/images/ajax-loader.gif) no-repeat center center', 'cursor': 'default'});
				if(window.location.toString().indexOf('/home')>0)
				{
					$.ajax({
				  		url: '/fence/more/'+fenceMore,
			  			success: function(data) 
			  			{
								fenceMore = fenceMore + 20;
								var showMore = $('.showmore');
								showMore.after(data);
								showMore.remove();
								var count = parseInt($('.showmore:last .walllength').html())
								if(count<20)
								{
									$('.showmore').remove();
								}
								
	    					bindPostCommentHandler();
			  			}
					});
				}else if (window.location.toString().indexOf('/blogs/public')>0){
					fenceMore = 10
			$.ajax({
		  		url: '/blogs/public/'+fenceMore,
	  			success: function(data) {
					fenceMore = fenceMore + 10;
					var showMore = $('.showmore');
					showMore.after(data);
					showMore.remove();
					var count = parseInt($('.showmore:last .walllength').html())
					if(count<10){
					$('.showmore').remove();}
	  			}
			});
		} else{
					$.ajax({
				  		url: window.location.toString()+'/more/'+fenceMore,
			  			success: function(data) {
							fenceMore = fenceMore + 20;
							var showMore = $('.showmore');
							showMore.after(data);
							showMore.remove();
							var count = parseInt($('.showmore:last .walllength').html())
							if(count<20){
							$('.showmore').remove();}
			  			}
					});
				}
			})
		}
		if($('#navmsg .msg-tip').text()== "0")
		{
			$('#navmsg .msg-tip').hide();
		}else{
			$('#navmsg .msg-tip').show();
		}
		
		if($('#navfriends .msg-tip').text()== "0")
		{
			$('#navfriends .msg-tip').hide();
		}else{
			$('#navfriends .msg-tip').show();
		}
		
		$('.calendar').datepicker({defaultDate:new Date(1970,1,1),changeYear: true,changeMonth: true,yearRange:'c-70:c+40'});
		$('input').keyup(function(){
			if($(this).val()==' ')
				$(this).val($.trim($(this).val()))
		});		
		$('textarea').keyup(function(){
			if($(this).val()==' ')
				$(this).val($.trim($(this).val()))
		});
		if($('#comment').length>0)
		{
			$('#comment input[type=submit]').click(function(){
				if($('#comment #id_comment').val().length == 0)
				{
					if($('#comment').parent().find('.error-box').length==0)
						$('#comment').before('<div class="error-box">Please enter a comment</div> ')
					return false;
				}
				return true;
			})
		}
		// Delete Wall Posts Function (working)
		if($('.feed-item .user-tools .delete-btn').length>0)
		{
			$('.feed-item .user-tools .delete-btn').click(function(){
				var elemId = $(this).attr('rel');
				if(confirm('Are you sure you want to delete this post?'))
				{
					$('#w'+elemId).hide();
					//window.location = '/fence/'+elemId+'/delete';
					$.ajax({
				  		url: '/fence/'+elemId+'/delete',
						success: function() {
							
							
						}
					})
				}
			})
		}
		
		// Delete Wall Post Comments Function (working)
		if($('.comment .delete-btn').length>0)
		{
			$('.comment .delete-btn').click(function(){
				var elemId = $(this).attr('rel');
				if(confirm('Are you sure you want to delete this comment?'))
				{
					$('#c'+elemId).hide();
					$.ajax({
				  		url: '/fence/comment/'+elemId+'/delete',
						success: function() {
							
							
						}
					})
				}
			})
		}
		
		// Delete Photos from Album
		
			$('.photo .delete-btn').click(function(){
				var albId = $(this).attr('rel');
				var photId = $(this).attr('id');
				if(confirm('Are you sure you want to delete this photo?'))
				{
					window.location = '/photos/album/'+albId+'/'+photId+'/delete';
				}
			})
			
			
		// Delete Album
		
			$('.album-title .delete-btn').click(function(){
				var albId = $(this).attr('rel');
				if(confirm('Are you sure you want to delete this album?'))
				{
					window.location = '/photos/album/'+albId+'/delete';
				}
			})
		
		
		if($('.multiupload').length>0)
		{
			$('.multiupload .btn').click(function(){
				if($('.multiupload input[type=file]').length<6){
					$('.multiupload .last').before('<tr><td><input type="file" name="iupl'+$('.multiupload input').length+'" /></td></tr>');
				}
				return false;
			});
		}
		if($('.albumupload').length>0)
		{
			$('.albumupload .btn').click(function(){
				$('#id_caption').parent().parent().hide();
				if($('.albumupload input[type=file]').length<6){
					$('.albumupload .last').before('<tr><th></th><td><input type="file" name="iupl'+$('.albumupload input[type=file]').length+'" /></td></tr>');
				}
				return false;
			});
		}
		
		$('.albumupload .btn').click(function(){
		//$('.album-load').show();
		});
		
		$('#sidebar-nav a').each(function(i,elem)
				{
					var loc = document.location.toString();
					loc = loc.substring(loc.indexOf('/',8))
					if($(elem).attr('href')==loc)
					{
						$(elem).addClass('selected');
					}
				});
		$('#wall_post input[type="submit"]').click(function(){
			if(checkVideos()){
				$(this)
					.hide()
					.after('<img src="/site_media/images/ajax-loader.gif" alt="" />');
			}else{
				return false;
			}
		})
		
		var comment = getParameterByName('c')
		if(comment.length>0)
		{
			//$.scrollTo('#c'+comment)
		}
		
		
			$('.wall-comments input[type="submit"]').css('opacity', '0.6');
			$('.wall-comments form textarea').TextAreaExpander(13, 200);
			$('.wall-comments form textarea').css('padding','5px');
			$('#wall_post textarea').css('padding','5px');
			
			if($('.wall-comments form textarea').length>0)
		{
			$('.wall-comments form textarea').width('330px')
			$('.wall-comments form textarea').val('Comment on this post...')
			$('.wall-comments form textarea').focus(function()
				{
					if($(this).val()=='Comment on this post...')
					{
						$(this).val('');
					}
					$(this).siblings('input[type="submit"]').css('opacity', '1');
				});
				
			/* dirty 'focusout' function */		
			var subFoc = false;
			$('.wall-comments input[type="submit"]').hover(function(){ subFoc = true; }, function(){ subFoc = false; });
			
			$('.wall-comments form textarea').focusout(function(){
				if(!subFoc){
				if($(this).val()==''){
						$(this).val('Comment on this post...');
						$(this).siblings('input[type="submit"]').css('opacity', '0.6');
				
				}
				}
			});
			
			/* check if field is empty, if empty then do nothing */
			$('.wall-comments input[type="submit"]').click(function(){
				if($(this).siblings('.wall-comments form textarea').val() == '' || $(this).siblings('.wall-comments form textarea').val() == 'Comment on this post...'){
					return false;
				}
			});
			
			
		}
	})
}

/* extra jquery styling */
function wallComms(){
			$('.wall-comments2 input[type="submit"]').css('opacity', '0.6');
			$('.wall-comments2 form textarea').TextAreaExpander(13, 200);
			$('.wall-comments2 form textarea').css('padding','5px');
			$('#wall_post textarea').css('padding','5px');
			
			if($('.wall-comments2 form textarea').length>0)
		{
			$('.wall-comments2 form textarea').width('330px')
			$('.wall-comments2 form textarea').val('Comment on this post...')
			$('.wall-comments2 form textarea').focus(function()
				{
					if($(this).val()=='Comment on this post...')
					{
						$(this).val('');
					}
					$(this).siblings('input[type="submit"]').css('opacity', '1');
				});
				
			/* dirty 'focusout' function */		
			var subFoc = false;
			$('.wall-comments2 input[type="submit"]').hover(function(){ subFoc = true; }, function(){ subFoc = false; });
			
			$('.wall-comments2 form textarea').focusout(function(){
				if(!subFoc){
				if($(this).val()==''){
						$(this).val('Comment on this post...');
						$(this).siblings('input[type="submit"]').css('opacity', '0.6');
				
				}
				}
			});
			
			/* check if field is empty, if empty then do nothing */
			$('.wall-comments2 input[type="submit"]').click(function(){
				if($(this).siblings('.wall-comments2 form textarea').val() == '' || $(this).siblings('.wall-comments2 form textarea').val() == 'Comment on this post...'){
					return false;
				}
			});
			
			
		}
		
		$('.user-msg').linkify();
		$('.comment-box').linkify();
		
		// Delete Wall Posts Function (working)
		if($('.feed-item2 .user-tools .delete-btn').length>0)
		{
			$('.feed-item2 .user-tools .delete-btn').click(function(){
				var elemId = $(this).attr('rel');
				if(confirm('Are you sure you want to delete this post?'))
				{
					$('#w'+elemId).hide();
					//window.location = '/fence/'+elemId+'/delete';
					$.ajax({
				  		url: '/fence/'+elemId+'/delete',
						success: function() {
							
							
						}
					})
				}
			})
		}
		
		// Delete Wall Post Comments Function (not working)
		if($('.wall-comments2 .comment .delete-btn').length>0)
		{
			$('.wall-comments2 .comment .delete-btn').click(function(){
				var elemId = $(this).attr('rel');
				if(confirm('Are you sure you want to delete this comment?'))
				{
					$('#c'+elemId).hide();
					$.ajax({
				  		url: '/fence/comment/'+elemId+'/delete',
						success: function() {
							
							
						}
					})
				}
			})
		}
}

function checkVideos()
{
	if($('#id_content').val().length==0&& $('#photo').val().length==0)
	{
		alert('Please enter a post comment');
		return false;
	}
	if($('#id_content').val().split('youtube.com').length>2)
	{
		alert('Sorry, you are only able to add one video per post');
		return false;
	}
	reg = new RegExp('.png|.jpg|.gif', "gi")
	if($('#photo').val().match(reg)== null&&$('#id_content').val().length==0)
	{
		alert('Sorry, you are only able to post images');
		return false;
	}
	return true;
}
function getParameterByName( name )
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return decodeURIComponent(results[1].replace(/\+/g, " "));
}

function addDelCom(){
	// Delete Wall Post Comments Function (working)
		if($('.wall-comments .recentcomm .delete-btn').length>0)
		{
			$('.wall-comments .recentcomm .delete-btn').click(function(){
				var elemId = $(this).attr('rel');
				if(confirm('Are you sure you want to delete this comment?'))
				{
					$('#c'+elemId).hide();
					$.ajax({
				  		url: '/fence/comment/'+elemId+'/delete',
						success: function() {
							
							
						}
					})
				}
			})
		}
		// Delete Wall Post Comments Function (working)
		if($('.wall-comments2 .recentcomm .delete-btn').length>0)
		{
			$('.wall-comments2 .recentcomm .delete-btn').click(function(){
				var elemId = $(this).attr('rel');
				if(confirm('Are you sure you want to delete this comment?'))
				{
					$('#c'+elemId).hide();
					$.ajax({
				  		url: '/fence/comment/'+elemId+'/delete',
						success: function() {
							
							
						}
					})
				}
			})
		}
}


function bindPostCommentHandler() {
    $('.wall-comments form,.wall-comments2 form').unbind('submit');
    $('.wall-comments form,.wall-comments2 form').submit(function() {
        $.ajax({
            type: "POST",
            data: $(this).serialize(),
            url: $(this).attr('action'),
            cache: false,
            dataType: "html",
            success: function(html, textStatus) {
            	var arr = (this.data.split('&')[4]+"").split('=');
							$('input[name="'+arr[0]+'"][value="'+arr[1]+'"]').parent().before(html);
							$('input[name="'+arr[0]+'"][value="'+arr[1]+'"]').siblings('#id_comment').val('Comment on this post...');
							$('input[name="'+arr[0]+'"][value="'+arr[1]+'"]').siblings('input[type="submit"]').css('opacity', '0.6');
							addDelCom();
							//$('input[name="'+arr[0]+'"][value="'+arr[1]+'"]').parent().hide();
                bindPostCommentHandler();
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
            	var arr = (this.data.split('&')[4]+"").split('=');
							$('input[name="'+arr[0]+'"][value="'+arr[1]+'"]').parent().parent().replaceWith('<div class="error-box">Your comment was unable to be posted at this time.  We apologise for the inconvenience.</div>');
            }
        });
        return false;
    });
    $('form#comment').unbind('submit');
    $('form#comment').submit(function() {
        $.ajax({
            type: "POST",
            data: $(this).serialize(),
            url: $(this).attr('action'),
            cache: false,
            dataType: "html",
            success: function(html, textStatus) {
            	var arr = (this.data.split('&')[4]+"").split('=');
							$('input[name="'+arr[0]+'"][value="'+arr[1]+'"]').parent().before(html);
							$('input[name="'+arr[0]+'"][value="'+arr[1]+'"]').siblings('#id_comment').val('');
							//$('input[name="'+arr[0]+'"][value="'+arr[1]+'"]').parent().hide();
                bindPostCommentHandler();
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
            	var arr = (this.data.split('&')[4]+"").split('=');
							$('input[name="'+arr[0]+'"][value="'+arr[1]+'"]').parent().parent().replaceWith('<div class="error-box">Your comment was unable to be posted at this time.  We apologise for the inconvenience.</div>');
            }
        });
        return false;
    });
}
