$.noConflict();

var exday = 1, hasFocus = false;;

jQuery(document).ready(function($) 
{
	var channel_id 	= $('#channel_id').val();
	var total_posts = $('a.totalPosts').attr('id');

	/**
	 * Attach Asset
	 * 
	 * This is triggered when user clicks on attachment link.
	 */
	$('div.attach > a').live('click', function()
	{
		// underline current selection
		$('div.attach a').css('text-decoration', 'none');	
		$(this).css('text-decoration', 'underline').blur();
		
		if ($(this).hasClass('photo'))
		{
			$('div.attachment').show();
			$('div.attachment > span').hide();
			
			$('#attachment').val('photo');
			$('div.attachment > span.photo').show();
		}
		
		if ($(this).hasClass('album'))
		{
			$('div.attachment').show();
			$('div.attachment > span').hide();
			
			$('#attachment').val('album');
			$('div.attachment > span.album').show();
		}

		if ($(this).hasClass('video'))
		{
			$('div.attachment').show();
			$('div.attachment > span').hide();
			
			$('#attachment').val('video');
			$('div.attachment > span.video').show();
		}

		if ($(this).hasClass('blog'))
		{
			$('div.attachment').show();
			$('div.attachment > span').hide();
			
			$('#attachment').val('blog');
			$('div.attachment > span.blog').show();
		}

		// void
		return false;
	});

	/**
	 * Cancel Attachment
	 * 
	 * This is triggered when user clicks on cancel image.
	 */
	$('div.attachment a.cancel').live('click', function()
	{	
		// reset all attachments
		resetAttachments();
		
		// void
		return false;
	});

	/**
	 * Reset Attachment
	 * 
	 * This function resets the attachment inputs.
	 */
	function resetAttachments()
	{
		// hide attachment inputs
		$('div.attachment').hide();
		$('div.attachment > span').hide();
		
		// reset containers
		$('#attachment').val('');
		$('#attachment_id').val('');
		
		// reset album input
		$('#select_album').show();		
		$('span.album img.preview').remove();
		
		// reset file input
		$('#upload_photo').val('');

		// display default texts
		$('div.attachment > span > input').each(function(index, element)
		{
			var text = $(this).attr('default');
			$(this).val(text);
		});

		// remove underline on current selection
		$('div.attach a').css('text-decoration', 'none');	
	}

	function isYoutube(content)
	{
		var result = content.search(/(v\/|v=)([\-\w]+)/);
		if (result != -1) return true;
		return false;
	}
	
	$('input.channel').keyup(function(e){
		if(e.which != 13){
			return;
		}
		$(e.target).next('.postComment').click();
		return true;
	});
	
	/**
	 * Post Asset
	 * 
	 * This is triggered when user clicks on 'post' button.
	 */
	$('#doPost').live('click', function(e)
	{
		if(hasFocus && '' == $('#attachment_id').val()){ return false; }
		var input 		= $('#status_update');
		var status 		= input.val();
		var attachment	= $('#attachment').val();
		var content 	= '';

		// check if status update = default text
		if (input.val() == input.attr('default'))
		{
			if (language == 'de') 
			{
				show_modal('Bitte gib eine Nachricht ein.');
			}
			else
			{
				show_modal('Please enter a status message.');
			}
			
			return false;
		}
		
		// validate attachments
		switch (attachment)
		{
			case 'photo':
			content = $('#upload_photo').val();
			break;
			
			case 'video':
			content = $('#select_video').val();
			
			// check if youtube link is valid
			if (isYoutube(content) == false)
			{
				if (language == 'de') 
				{
					show_modal('Das ist kein gültiger YouTube link.');
				}
				else
				{
					show_modal('This is not a valid YouTube link.');
				}
				return false;
			}
			break;
			
			default:
			content = $('#attachment_id').val();
		}
				
		// check if attachment = default text
		if (attachment && content == $('#select_' + attachment).attr('default'))
		{
			if (language == 'de') 
			{
				show_modal('Bitte wähle einen Anhang.');
			}
			else
			{
				show_modal('The attachment is missing.');
			}
			return false;
		}
		// check for empty attachment value
		else if (attachment && content == '')
		{
			if (language == 'de') 
			{
				show_modal('Bitte wähle einen gültigen Anhang.');
			}
			else
			{
				show_modal('Please choose a valid attachment.');
			}
			return false;
		}
		
		// go to the uploader...		
		if (attachment == 'photo') 
		{
			$("#upload_form").submit();
			return false;
		}		

		$.ajax({
			url: 'channel_ajax.php',
			data: {
				channel_id: channel_id,
				task: 'updateStatus',
				posts: total_posts,
				status: status,
				attachment: attachment,
				content: content,
				day: exday
			},
			success: function(data)
			{
				updatePosts(data);
				resetAttachments();
			}
		})
		
		// void
		return false;	
	});
	
	/**
	 * Trigger Comment
	 * 
	 * Opens the comment text input field.
	 */
	$('a.comment').live('click', function()
	{
		var div = $(this).closest('div.post').find('div.comment');
		var post_id = $(this).attr('data-id');

		if (div.is(':hidden')) {
			div.show();
		}
		
		if (post_id) {
			$('#commentbox' + post_id).show();
		}

		return false;
	});

	/**
	 * Add Comment
	 * 
	 * Adds a comment to a post.
	 */
	$('input.postComment').live('click', function()
	{
		var parent_id = $(this).closest('div.post').attr('id');	
		var input 	= $(this).prev('input.channel');
		var content = input.val();
		
		// check for valid user input
		if (input.val() == input.attr('default'))
		{
			if (language == 'de') 
			{
				show_modal('Bitte gib ein Kommentar ein.');
			}
			else
			{
				show_modal('Please enter your comment.');
			}
			return false;
		}
		
		$.ajax({
			url: 'channel_ajax.php',
			data: {
				task: 'comment',
				posts: total_posts,
				parent_id: parent_id,
				content: content,
				channel_id: channel_id,
				day: exday
			},
			success: function(data)
			{
				updatePosts(data);
			}
		})
		
		// void
		return false;	
	});
	
	/**
	 * Delete Post
	 * 
	 * Deletes a post or comment from this user.
	 */
	$('a.deletePost, a.deleteComment').live('click', function()
	{
		if ($(this).hasClass('deleteComment'))
		{
			// delete comment
			var post_id = $(this).closest('div.comment').attr('id');
		}
		else
		{
			// delete post
			var post_id = $(this).closest('div.post').attr('id');
		}

		$.ajax({
			url: 'channel_ajax.php',
			data: {
				task: 'deletePost',
				posts: total_posts,
				post_id: post_id,
				channel_id: channel_id,
				day: exday
			},
			success: function(data)
			{
				updatePosts(data);
			}
		})
		
		// void
		return false;	
	});	

	/**
	 * Like it
	 * 
	 * Likes a post.
	 */		
	$('a.like').live('click', function()
	{
		var parent_id = $(this).closest('div.post').attr('id');
		$.ajax({
			url: 'channel_ajax.php',
			data: {
				task: 'like',
				posts: total_posts,
				parent_id: parent_id,
				channel_id: channel_id,
				day: exday
			},
			success: function(data)
			{
				updatePosts(data);
			}
		})
		
		// void
		return false;	
	});

	/**
	 * Show Photo
	 * 
	 * Shows modal dialog with full size image.
	 */	
	$('a.photo').live('click', function()
	{
		var href = $(this).attr('href');
		$('<img />').attr('src', href).load(function()
		{
			var image = '<img src="' + href + '" />';
			show_modal(image, 'modal_image');		
		});
    
		return false;
	});	
	
	/**
	 * Show a facebook photo in a lightbox
	 */
	$('a.fb-link').live('click', function(){
		var $this = $(this), $img = $this.find('img');
		// check if the image is a fb image
		if($img && $img.attr('src').test(/^http:\/\/photos.*?fbcdn.net/i)){
			// suffix _s is for a small image, _n for normal. replace _s with _n
			var href = $img.attr('src').replace(/_s(\.\w{3,4})$/i, '_n$1');
			$('<img />').attr('src', href).load(function()
			{
				var image = '<img src="' + href + '" />';
				show_modal(image, 'modal_image');		
			});
			return false;
		}
		return false;
	});
	
	$('#modal_image').live('click', close_modal);
	
	/**
	 * Upload Photo
	 * 
	 * Handles the photo upload.
	 */		
	$("#upload_form").submit(function(data)
	{
		if(hasFocus){ return false; }
		var input 			= $('#status_update');
		var status 			= input.val();
		
		var submitForm		= $(this);
		var frameName 		= ("upload" + (new Date()).getTime());
		var uploadFrame 	= $('<iframe name="' + frameName + '" />');

		// show AJAX loader image
		$('#loader').show();

		uploadFrame.css("display", "none");
		uploadFrame.load(function(data)
		{
			// submit complete
			setTimeout(function()
			{
				// get file name
				var content = uploadFrame.contents().find('#result').html();
				
				if (content)
				{
					$.ajax({
						url: 'channel_ajax.php',
						data: {
							channel_id: channel_id,
							task: 'updateStatus',
							posts: total_posts,
							status: status,
							attachment: 'photo',
							content: content,
							day: exday
						},
						success: function(data)
						{
							$('#loader').hide();
							updatePosts(data);
							resetAttachments();
						}
					})
				}
				else
				{
					// upload failed
					$('#loader').hide();

					if (language == 'de') 
					{
						show_modal('Bildupload fehlgeschlagen. Bitte überprüfe deine Datei.');
					}
					else
					{
						show_modal('Image upload failed. Please check your file.');
					}
					return false;
				}			

				//remove hidden upload frame
				uploadFrame.remove();
			}, 1000);
		});
		
		$("body:first").append(uploadFrame);
		
		//setup complete
		submitForm.attr("target", frameName);

		return true;
	});	
	
	/**
	 * Load More
	 * 
	 * Load older posts.
	 */		
	$('a.loadMore').live('click', function()
	{
		$.ajax({
			url: 'channel_ajax.php',
			data: {
				task: 'loadMore',
				posts: total_posts,
				channel_id: channel_id,
				day: exday
			},
			success: function(data)
			{
				updatePosts(data);

				// filter results
				if (typeof window.filter_posts == 'function') {
					filter_posts();
				}
			}
		});
		
		// void
		return false;	
	});
	
	/**
	 * Update Post
	 * 
	 * Reloads the updated posts.
	 */	
	function updatePosts(response)
	{
		$('#posts').replaceWith(response);
		total_posts = $('a.totalPosts').attr('id');
		setDefaultLabels();
	}

	// --------------------------------------------------------------------------	

	/**
	 * Select Album
	 * 
	 * jQuery autocomplete to select a user's media album
	 */	
	$('#select_album').autocomplete(
	{
		source: function(request, response)
		{
			$.ajax({
				url: 'channel_ajax.php',
				dataType: 'json',
				data: {
					task: 'searchAlbums',
					term: request.term,
					limit: 5
				},
				success: function(data)
				{
					response($.map(data, function(item)
					{
						return {
							id: item.id,
							label: item.label,
							value: item.value,
							thumbnail: item.thumbnail
						}
					}))
				}
			})
			
			// reset attachment_id
			$('#attachment_id').val('');
		},
		select: function(event, ui) 
		{
			// store attachment_id
			$('#attachment_id').val(ui.item.id);

			// display thumbnail
			$(this).after(ui.item.thumbnail);
			$(this).hide();			

			// void
			return false;
		}
	});
	
	/**
	 * Select Blog
	 * 
	 * jQuery autocomplete to select a user's media album
	 */	
	$('#select_blog').autocomplete(
	{
		source: function(request, response)
		{
			$.ajax({
				url: 'channel_ajax.php',
				dataType: 'json',
				data: {
					task: 'searchBlogs',
					term: request.term,
					limit: 5
				},
				success: function(data)
				{
					response($.map(data, function(item)
					{
						return {
							id: item.id,
							label: item.label,
							value: item.value
						}
					}))
				}
			})
			
			// reset attachment_id
			$('#attachment_id').val('');
		},
		select: function(event, ui) 
		{
			// store attachment_id
			$('#attachment_id').val(ui.item.id);

			// display thumbnail
			$(this).val(ui.item.label);

			// void
			return false;
		}
	});	
	
	// --------------------------------------------------------------------------		
	
	/**
	 * Text Inputs
	 * 
	 * The functions below handle the text input 
	 * values upon page load or on focus and blur
	 */

	var input = '';
	 
	setDefaultLabels();

	function setDefaultLabels() 
	{
		$('input.channel').each(function(index, element)
		{
			var text = $(this).attr('default');
			$(this).val(text);
		});

		$('textarea.channel').each(function(index, element)
		{
			$(this).val('');
		});
	}

	// clear default or select text on focus
	$('input.channel').live('focus', function()
	{
		hasFocus = true;
		input = this.value;
		if (this.value == $(this).attr('default')) 
		{
			this.value = '';
		}
		else
		{
		    this.select();
		}
	});
	
	// reset to former input on blur
	$('input.channel').live('blur', function()
	{
		hasFocus = false;
		if ( ! this.value) this.value = input;
	});
	
	// --------------------------------------------------------------------------	
	
	/**
	 * Show Modal Dialog
	 * 
	 * Shows modal dialog just like the thickbox one.
	 */
	function show_modal(content, div)
	{
		// set default modal
		if (div == null) div = 'modal_error';
		
		// get screen height and width
		var maskHeight = $(document).height();
		var maskWidth = $(window).width();
	
		//Set height and width to mask to fill up the whole screen
		$('#mask').css({'top':0,'left':0,'width':maskWidth,'height':maskHeight});
		
		// fade in mask
		$('#mask').fadeTo("slow", 0.2);
	
		// get window height and width
		var winH = $(window).height();
		var winW = $(window).width();

		// insert message
		$('#' + div + ' p.message').html(content);

		// get modal
		var modal = $("#" + div);
		
		// if modal contains image
		if (div == 'modal_error')
		{
			var height = modal.height();
			var width = modal.width();
		}
		else
		{
			var height = $(content).attr('height');
			var width = $(content).attr('width');
		}

		// center modal window
		modal.css('top', winH / 2 - height / 2 + $(document).scrollTop() - 20);
		modal.css('left', winW / 2 - width / 2);

		// fade in modal
		modal.fadeIn(500);

		$(document).bind('scroll.modal', function()
		{
			var winH = $(window).height();
			modal.css('top', winH / 2 - modal.height() / 2 + $(document).scrollTop() - 20);
		});
		
		$(window).bind('resize.modal', function()
		{
			var winW = $(window).width();
			var winH = $(window).height();
			
			modal.css('left', winW / 2 - modal.width() / 2);
			modal.css('top', winH / 2 - modal.height() / 2 + $(document).scrollTop() - 20);
		});		
	}
	
	// close modal when close button is clicked
	$('div.modal .close').live('click', close_modal);		
	
	// close modal when mask is clicked
	$('#mask').live('click', close_modal);	
	
	function close_modal()
	{
		$('#mask').hide();
		$('div.modal').hide();
		$(document).unbind('scroll.modal');
		$(window).unbind('resize.modal');
		return false;	
	}
});
