$().ready(function(){
	
	// this one is to get the pasted text in the status to figure out if there is any links in it
	
	$("#statusUpdateBox").bind('paste', function(e) {
		
        var el = $(this);
        
        // setting timeout to let it populate the paste data
        
        setTimeout(function() {
            
        	var text = $(el).val();
            
            // let's check if pasted text has a link in it.
            
            var regexp = /((ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?)/gi;
            
            var links = text.match(regexp);
            
            if(links != null){
            
            console.log(links);
            
            // use server side function to get the information about the title, description and thumb
            
            $.ajax({
                url: ATTACH_LINK_URL,
                data: ({'data[Link][url][]' : links}),
                dataType: 'html',
                type: 'POST',
                success: function(result){

    				$("#attached_link_preview").html(result);		 		

    			 },
    			 complete: function(){
    				 $(".loading").remove();
    			 },
    			 beforeSend: function(){
    				 $("#statusUpdateBox").before('<div class="loading">Loading</div>');
    			 }
            });
            
            }
    		
        }, 100);
        
        
    });
	
	$("#uploadWallPhotosLink").click(function(){
		
		var link = $(this).attr('href');
		
		$("#options").hide();
		
		$("#wall_photo_upload_box").show();
		
		$("#photo_upload_options_container").show();
		$("#photo_upload_container").hide();
		$("#album_create_container").hide();
		
		
		return false;
		
	});
	
	$("#PhotoUploadWallPhotoForm").submit(function(){
		
		$(this).ajaxSubmit({
			
	        dataType: 'json',

	        type: 'post',
	        
	        beforeSubmit: function(a,f,o) {
		   		o.dataType = 'json';
			},
	        success:function(result){

				if(result.status == 1){
					
					$.jGrowl(result.message);
					
					$("#posts").load(POST_URL + '/all/' + +Math.random());
					
					// hide the photo upload box
					
					$('a.close_options').trigger('click');
					

				}else if(result.status == 0){
					
					$.jGrowl(result.message);
					
				}else{
					
					$.jGrowl('There was an unexpected error. Please try again');
					
				}
			},
			complete: function(){
					 $(".loading").remove();
			},
			beforeSend: function(){
					 $("#PhotoUploadWallPhotoForm").after('<div class="loading">loading</div>');
			}
			
		});
		
		return false;
		
	});
	
	
	$('a.choosePhotoUploadOptionLink').click(function(){
		
		var div_to_display = $(this).attr('href');
		
		$(div_to_display).show();
		$('#photo_upload_options_container').hide();
		$("#PhotoPhoto").show();
		$("#PhotoPhoto").removeAttr('disabled');
		return false;
		
	});
	
	$('a.close_options').click(function(){
		
		$("#album_create_container").hide();
		$("#photo_upload_container").hide();
		$("photo_upload_options_container").show();
		$("#wall_photo_upload_box").hide();
		$("#PhotoPhoto").hide();
		$("#PhotoPhoto").attr('disabled', true);
		$("#options").show();
		
		return false;
		
	});
	
	// ajax get all the posts
	
	$("#posts").load(POST_URL  + '/all/' + +Math.random());
	
	$("#posts").bind("click", function(e){
		
		$target = $(e.target);
		
		if($target.is("a.post_comment_link")){
		
			$target.parent().parent().children(".post_comment_row").html('<textarea name="comment" class="comment"></textarea><input type="submit" value="Comment" class="submit_comment"/> <a href="#" class="close">x</a>'); 
		}
		
		if($target.is('a.comment_reply_link')){
			
			var parent_id = $target.attr("rel");
			
			$target.parent().children('.comment_reply_row').html('<textarea title="'+ parent_id +'" name="comment" class="comment"></textarea><input type="submit" value="Reply" class="submit_comment_reply"/> <a href="#" class="close">x</a>');
			
		}
		
		if($target.is('a.close')){
			$target.parent().html("");
		}
		
		
		if($target.is('a.see_more')){
			$target.parent().hide();
			$target.parent().prev().html(' ');
			$target.parent().parent().next().show();
		}		

		if($target.is("input.submit_comment")){
			
			// ajax submit form
			
			// get the comment data
			
			var post_id = $target.parent().parent().attr("title");
			var comment = $target.parent().children("textarea").val();
			
			
			
			$.ajax({
                url: COMMENT_SAVE_LINK,
                data: ({"data[WallPostComment][wall_post_id]":post_id, "data[WallPostComment][comment]":comment}),
                dataType: 'json',
                type: 'post',
                success: function(result){

    				if(result.status == 1){
    					
    					
    					$target.parent().parent().children(".comments").load(COMMENT_LIST_LINK + post_id);
    					
    					$target.parent().html("");
    					
    					$.jGrowl("Your Comment Has Been Saved !!");
    					
    				}else if(result.status == 0){
    					
    					$.jGrowl("There was an error in saving your comment");
    					
    				}else{
    					
    					$.jGrowl("There was an error in saving your comment");
    					
    				}		 		

    			 },
    			 complete: function(){
    				 $(".loading").remove();
    			 },
    			 beforeSend: function(){
    				 $target.before('<div class="loading">Loading</div>');
    			 }
            });

			
		}
		
		
		if($target.is("input.submit_comment_reply")){
			
			// ajax submit form
			
			// get the comment data
			var post_id = $target.parents(".wall_post").attr("title");
			var parent_id = $target.parent().children("textarea").attr("title");
			var comment = $target.parent().children("textarea").val();
			
			
			
			$.ajax({
                url: COMMENT_SAVE_LINK,
                data: ({"data[WallPostComment][parent_id]":parent_id, "data[WallPostComment][comment]":comment, "data[WallPostComment][wall_post_id]":post_id}),
                dataType: 'json',
                type: 'post',
                success: function(result){

    				if(result.status == 1){
    					
    					
    					$target.parents(".comments").load(COMMENT_LIST_LINK + post_id);
    					
    					$target.parent().html("");
    					
    					$.jGrowl("Your Comment Has Been Saved !!");
    					
    				}else if(result.status == 0){
    					
    					$.jGrowl("There was an error in saving your comment");
    					
    				}else{
    					
    					alert("There was an error in saving your comment");
    					
    				}		 		

    			 },
    			 complete: function(){
    				 $(".loading").remove();
    			 },
    			 beforeSend: function(){
    				 $target.before('<div class="loading">Loading</div>');
    			 }
            });

			
		}
		
		if($target.is("a.follow")){
			location.href = $target.attr('href');
			return true;
		}
		
		if($target.is("img")){
			location.href = $target.parent().attr('href');
			return true;
		}

		if($target.is("a.post_delete_link")){
			
			
			
			$.ajax({
                url: $target.attr('href'),
                type: 'get',
                dataType: 'json',
                success: function(result){

    				if(result.status == 1){
    					
    					$target.parent().parent().fadeOut();
    					
    					$.jGrowl(result.message);
    					
    				}else if(result.status == 0){
    					
    					$.jGrowl(result.message);
    					
    				}else{
    					
    					$.jGrowl("There was an unexpected error");
    					
    				}		 		

    			 },
    			 complete: function(){
    				 $(".loading").remove();
    			 },
    			 beforeSend: function(){
    				 $target.before('<div class="loading">Loading</div>');
    			 }
            });
			
			
		}
		
		if($target.is("a.comment_delete_link")){
			
			var id_to_delete = $target.attr('rel');
			
			$.ajax({
                url: $target.attr('href'),
                type: 'get',
                dataType: 'json',
                success: function(result){

    				if(result.status == 1){
    					
    					$target.parent().parent().fadeOut();
    					
    					for (i=0;i<result.parents.length;i++)
    					{
    						$("." + result.parents[i]).fadeOut().remove();
    					} 
    					
    					
    					$.jGrowl(result.message);
    					
    				}else if(result.status == 0){
    					
    					$.jGrowl(result.message);
    					
    				}else{
    					
    					$.jGrowl("There was an unexpected error");
    					
    				}		 		

    			 },
    			 complete: function(){
    				 $(".loading").remove();
    			 },
    			 beforeSend: function(){
    				 $target.before('<div class="loading">Loading</div>');
    			 }
            });
			
			
		}		
		
		if($target.is("a.liked_by_link")){

			// open a dialog box
			
			$("body").append('<div class="dialog"/>');
			
			$(".dialog").dialog({ 
				
				modal:true, 
				close: function(){ 
							$(this).remove(); 
						}
			});
			
			// start loading
			$.ajax({
				
                url: $target.attr('href'),
                type: 'get',
                dataType: 'html',
                success: function(result){
				
					$(".dialog").html(result);
				
				},
				 complete: function(){
	   				 $(".loading").remove();
	   			 },
	   			 beforeSend: function(){
	   				$(".dialog").html('<div class="loading">Loading</div>');
	   			 }
				
			});
			
			
			// ajax load the list of users who liked this post
			
			// on close remove the contents
		}
		
		if($target.is("a.like_update_link")){
			
			$.ajax({
                url: $target.attr('href'),
                type: 'get',
                dataType: 'json',
                success: function(result){

    				if(result.status == 1){
    					
    					var wall_post_id = $target.parent().parent().parent().attr('title');
    					
    					$target.parent().parent().parent().children(".post_like_row").load(POST_LIKENESS_LINK + wall_post_id);

    					if(result.html != ''){
    						$target.parent().html(result.html);
    					}
    					
    					// add the information about likeness of this post
    					
    					$.jGrowl(result.message);
    					
    				}else if(result.status == 0){
    					
    					$.jGrowl(result.message);
    					
    				}else{
    					
    					$.jGrowl("There was an unexpected error");
    					
    				}		 		

    			 },
    			 complete: function(){
    				 $(".loading").remove();
    			 },
    			 beforeSend: function(){
    				 $target.before('<div class="loading">Loading</div>');
    			 }
            });
		}
		
	    return false;
	});
	
	
	$(".entry_delete_link").click(function(){
		
		var link = $(this).attr("href");
		var id = $(this).attr("id");
		
		var entryId = "#entry_" + id;
		
		$.getJSON(link, function(result){
			
			if(result.status == 1){
				
				$(entryId).fadeOut();
				
			}else if(result.status == 0){
				
				$('#message').addClass('message error-message').show('slow').text(result.message);
				
			}else{
				
				$('#message').addClass('message error-message').show('slow').text('There was an unexpected error. Please try again later');
				
			}		 		

		 });
		
		return false;
		
	});
	
	$("#message").click(function(){
		$(this).hide("slow");
	});
	
	$.validator.setDefaults({
		
		submitHandler: function() { 
		
			var action = $("#statusUpdateForm").attr('action');
			
			$("#statusUpdateForm").ajaxSubmit({
				
		        dataType: 'json',

		        type: 'post',
		        
		        url: action,
		        
		        beforeSubmit: function(a,f,o) {
			   		o.dataType = 'json';
				},
		        success:function(result){

					if(result.status == 1){
						
						$.jGrowl(result.message);
						
						$("#posts").load(POST_URL  + '/all/' + +Math.random());
						
						// hide the photo upload box
						
						$('a.close_options').trigger('click');
						

					}else if(result.status == 0){
						
						$.jGrowl(result.message);
						
					}else{
						
						$.jGrowl('There was an unexpected error. Please try again');
						
					}
				},
				complete: function(){
						 $(".loading").remove();
				},
				beforeSend: function(){
						 $("#statusUpdateForm").after('<div class="loading">loading</div>');
				}
				
			});

          return false; 

      	}
	
	});
     
      
	$("#statusUpdateForm").validate({
  		
		rules: {
			"data[WallPost][post]": "required"
		},

		messages: {
			"data[WallPost][post]": "Please enter something"
		}
	});
	
	
});
