$(document).ready(function() {
	
	$('#tipafriend-link').bind('click', function(){
		var tipUrl = $(this).attr('href').split('tipUrl=')[1];
		$.ajax({
		  url: tipafriendAjaxUrl,
		  data: {'tipUrl': tipUrl},
		  dataType: 'text',
		  success: function(data){
			  if ($('#tipafriend_popup').length) $('#tipafriend_popup').remove();
			  $('#maincol .content').append(data);
			  $(document).trigger('tipform_loaded');
		  }
		});
		
		return false;
	});
		
	$(document).bind('tipform_loaded', function(){
		$('#tipafriend_close, #tipFormClose').unbind().bind('click', function(){
			$('#tipafriend_popup').hide().remove();
		});
		
		$('#add_recipient').bind('click', function(){
			itemsCount = $('#recipients > div').length;
			if (itemsCount <= 10){
				html = '<div id="recipient-'+itemsCount+'">'+$('#recipient-def0').html().replace(/def0/g, itemsCount)+'</div>';
				$('#recipients').append(html);
			}		
		});
		  
		$('#tipFormSend').bind('click', function(){
			// validation should be applied
			$.ajax({
				url: tipafriendAjaxUrl,
				data: $('#tipafriend_form').serialize(),
				type: 'post',
				success: function(data){
					$('#tipafriend_popup .innercontent').empty().append(data);
					document.location.hash = 'topmenu';
					$(document).trigger('tipform_loaded');
				}
			});
		});
		
		$('#reload_captcha').bind('click',function(){
			var img = $('#captcha_wrapper').find('img:first');
			var src = img.attr('src');
			img.attr('src', src.split('?')[0]+'?r='+new Date().getTime() );
		});
		
		var img = $('#captcha_wrapper').find('img:first');
		if (img.length){
			var src = img.attr('src');		
			img.attr('src', src.split('?')[0]+'?r='+new Date().getTime() );
		}
		
	});
		
});
