	$(document).ready(function(){	
 
		// delete event
		$('#attach').bind("click", parse_link);
		
		function parse_link ()
		{
			if(!isValidURL($('#url').val()))
			{
				alert('Please enter a valid url.');
				return false;
			}
			else
			{
				$('#atc_loading').show();
				$('#atc_url').html($('#url').val());
				$.post("/__fetch.php?url="+escape($('#url').val()), {}, function(response){
					
					//Set Content
					$('#atc_title').html(response.title);
					$('#atc_desc').html(response.description);
					$('#atc_total_images').html(response.total_images);
					
					$('#atc_images').html(' ');
					$.each(response.images, function (a, b)
					{
						$('#atc_images').append('<img src="'+b.img+'" width="100" id="'+(a+1)+'">');
					});
					$('#atc_images img').hide();
					
					//Flip Viewable Content 
					$('#attach_content').fadeIn('slow');
					$('#atc_loading').hide();
					
					//Show first image
					$('img#1').fadeIn();
					$('#cur_image').val(1);
					$('#cur_image_num').html(1);
					
					// next image
					$('#next').unbind('click');
					$('#next').bind("click", function(){
					 
						var total_images = parseInt($('#atc_total_images').html());			 
						if (total_images > 0)
						{
							var index = $('#cur_image').val();
							$('img#'+index).hide();
							if(index < total_images)
							{
								new_index = parseInt(index)+parseInt(1);
							}
							else
							{
								new_index = 1;
							}
							
							$('#cur_image').val(new_index);
							$('#cur_image_num').html(new_index);
							$('img#'+new_index).show();
						}
					});	
					
					// prev image
					$('#prev').unbind('click');
					$('#prev').bind("click", function(){
					 
						var total_images = parseInt($('#atc_total_images').html());				 
						if (total_images > 0)
						{
							var index = $('#cur_image').val();
							$('img#'+index).hide();
							if(index > 1)
							{
								new_index = parseInt(index)-parseInt(1);;
							}
							else
							{
								new_index = total_images;
							}
							
							$('#cur_image').val(new_index);
							$('#cur_image_num').html(new_index);
							$('img#'+new_index).show();
					 	}
					});	
				});
			}
		};	
	});

	function isValidURL(url)
	{
		var RegExp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;
		
		if(RegExp.test(url)){
			return true;
		}else{
			return false;
		}
	}
