$(function(){
	$('.siteDetails').hide();
	$('.getDetails').show();
	$('form#submitLink').css({'float':'left','width':'70%'});
	$('#preview').css({'float':'left','width':'25%','background':'#eee','padding':'4px'});
	$('.hiddenLink').css({'display':'block','border':'1px dashed #09f','padding':'5px'});
	$('.hiddenLink p').before('<h3 class="newLinkSubmitted"><img src="/images/icons/accept.png" class="acceptLink" title="Accept Link" alt="Accept Link" /> <img src="/images/icons/delete.png" class="deleteLink" title="Refuse Link" alt="Refuse Link" /> &nbsp; &nbsp; <img src="/images/icons/new.png" /> New Link Submitted</h3>');
	$('.newLinkSubmitted').css({'color':'#09f'});
	$('.acceptLink').click(function(){
		link = $(this).parent().parent().attr('id');
		item = $(this);
		$.ajax({
			url: '/submitLink.php',
			type: 'GET',
			data: 'action=accept&link='+link+'&sitecode='+sitecode+'&pagename='+pagename,
			timeout: 10000,
			error: function(error){
				alert('Error with Link');
			},
			success: function(php){
				$(item).parent().parent().removeClass('hiddenLink').css('border','none').children('.newLinkSubmitted').hide();
			}
		});
	}).css('cursor','pointer');
	$('.deleteLink').click(function(){
		link = $(this).parent().parent().attr('id');
		item = $(this);
		$.ajax({
			url: '/submitLink.php',
			type: 'GET',
			data: 'action=refuse&link='+link+'&sitecode='+sitecode+'&pagename='+pagename,
			timeout: 10000,
			error: function(error){
				alert('Error with Link');
			},
			success: function(php){
				$(item).parent().parent().hide();
			}
		});
	}).css('cursor','pointer');	
});

function getDetails(link){
	if( link != 'http://' && link != '' ) {
		$.ajax({
			url: '/submitLink.php',
			type: 'GET',
			data: 'action=getDetails&link='+link,
			dataType: 'script',
			timeout: 10000,
			error: function(error){
				alert('Error with Link');
			},
			success: function(php){
				//alert(title);
				if( typeof(title) != 'undefined' ) $('#title').val( title );
				if( typeof(description) != 'undefined' ) {
					$('#description').val( description );
					countChars($('#description'),'#descriptionLabel',255); 
					preview();
					$('.siteDetails').show();
					$('.getDetails').hide();
				}
			}
		});
	} else {
		alert('Invalid URL submitted');
	}
}

function countChars(obj,target, max) {
	chars = $(obj)[0].value.length;
	if( chars > max ) {
		chars = max;
		$(obj)[0].value = $(obj)[0].value.substr(0,max);	
	}
	$(target).html('('+chars+'/'+max+')');
}

function preview() {
	$('#preview').show();
	link = $('#link').val();
	reciprocal = $('#reciprocal').val();
	title = $('#title').val();
	description = $('#description').val();
	$('#preview').html( '<strong>Preview:<\/strong><p><a href="'+link+'" title="'+description+'">'+title+'<\/a><\/p>' ).corner();
	$('#preview strong').css({'display':'block','background':'#09f','padding':'3px','color':'#fff','text-align':'center'}).corner("top");
}
