var morefiles=0;
var block_morecall=0;
var tag_top = 0;
var tag_left = 0;
var last_label = 0;

function Setcookie(cookieName,cookieValue,nDays) { 
	var today = new Date(); 
	var expire = new Date(); 
	if (nDays==null || nDays==0) nDays=1; 
	expire.setTime(today.getTime() + 3600000*24*nDays); 
	document.cookie = cookieName+"="+escape(cookieValue) 
	+ ";expires="+expire.toGMTString(); 
} 

function showPopup(url,width,height){
	window.open(url,'Squallstar QR Code','WIDTH='+width+',HEIGHT='+height+',scrollbars=0,resizable=no');
}

function closeKeepAlive() {
	if (/AppleWebKit|MSIE/.test(navigator.userAgent)) {
		new Ajax.Request("/ping/close", { asynchronous:false });
	}
}

function strip_tags(string) {
	 return string.replace(/(<([^>]+)>)/ig,""); 
}

function tagEventsBuilder() {
	$('.tag > .clean').unbind('click');
	$('.tag > .clean').click(function() {
		var text = $(this).next('.fill').html();
		$(this).parent('span.tag').fadeOut('fast');
		$.post('services/removetag/', { tag:text }, function(data) {
			//Nothing to do
		});
	});
	
	$('.tag > .fill').unbind('click');
	$('.tag > .fill').click(function() {
		var text = $(this).html();
		$('input.search').val(text);
		$(this).parent('span.tag').fadeOut('fast');
		$('.whiteloader').fadeIn(200);
		searchWord();
		//val change is triggered by this?
	});
}

function deleteFile(numb) {
	$('#delete-record .danger').attr('onClick', "deleteFileConfirmed("+numb+");return false;");
	$('#delete-record').modal({
		keyboard : true, backdrop: true, show : true
	});
}

function deleteFileConfirmed(numb) {
	$('#delete-record').modal('hide');
	$(".detail > tbody > tr[class='"+numb+"']").fadeOut('fast');
		$.post('services/delete/', { id:numb }, function(data) {
			//Nothing :)
	});
}

function saveLabelTxt(numb) {
	var label = $(".detail > tbody > tr[class='"+numb+"'] input[type=text]").val();
	var xhtml = '<span class="txt">'+label+'</span>';
	$(".detail > tbody > tr[class='"+numb+"'] > td:eq(0)").html(xhtml);
	$.post('services/edit_label/', { id:numb, text:label }, function(data) {
		//Nothing :)
		rowEventBuilder();
		return false;
	});
	return false;

}

function rowEventBuilder() {
	$('.detail > tbody > tr').each(function() {
		var numb = $(this).attr('class');
		$('span.txt', this).unbind('click');
		$('span.txt', this).click(function() {
			var xhtml = '<input type="text" value="'+strip_tags($(this).html())+'" class="xlarge" /> <a href="#" class="btn small" onclick="saveLabelTxt('+numb+');return false;">Salva</a>';
			$(this).parent().html(xhtml);
			$(this).parent().find('input').focus();
		});
	});
}

function searchWord() {
	var text = $('input.search').val();
	$('input.search').blur();
	//addTag(text);
	$.post('services/filter/', { filter:text }, function(data) {
		//$('.whiteloader').fadeOut(200);
		if (data) {
			$('.detail > tbody').html(data);
			rowEventBuilder();
		}else{
			$('.detail > tbody').html('<tr><td colspan="6"><u>Nessun risultato trovato.</u></td></tr>');
		}
	});
}



function addTag(text) {
	if (text!='' && text!=' ' && text!='  ') {
		$('span.tag:eq(6)').remove();
		var xhtml = '<span class="tag" style="display:none"><a href="#" class="clean"></a><a href="#" class="fill">'+text+'</a></span>';
		$('input.search').after(xhtml);
		tagEventsBuilder();
		$('span.tag:first').fadeIn('fast');
	}
}

function searchWordTyped() {
	clearInterval(document._to);
	document._to=setTimeout(function(){searchWord();},600);	
	//$('.whiteloader').fadeIn(200);
}

function showMoreFiles() {
	morefiles++;
	if (!block_morecall) {
		block_morecall=1;
		var tmp_more='morefiles'+morefiles;
		var old_xhtml = $('.more_files').html();
		var loader_xhtml = 'Carico...';
		$('.more_files').html(loader_xhtml).addClass('info');
		$.get('services/get_more_files/', function(data) {
			$('.more_files').fadeOut('fast', function() {
				//Append table content
				$('.more_files').html(old_xhtml).removeClass('info');;
				$('.detail > tbody').append(data);
				rowEventBuilder();
				$('.more_files').fadeIn('fast');
				block_morecall=0;
				rowEventBuilder();
			});
		});
	}
}

function sendFile() {	
	$('.cancel_file').fadeOut(300);
	$('.send_file').removeClass('success').addClass('info').addClass('disabled').html('Caricamento...');
	$('#gogo').submit();
	return true;
}

function hideBanner(which) {
	$('.banner').fadeOut(500);
	Setcookie('banner_'+which,'1',30);	
}

function changeLabel(obj) {
	last_label = obj;
	etich = $('tr[class='+obj+'] span.label').clone();
	$('#change-label .etiquette').html(etich);
	$('#change-label').modal({
		keyboard : true, backdrop: true, show : true
	});
}

function setLabel(el) {
	var color = $(el).attr('data-color');
	etich = $(el).clone();
	etich.css('background-color', '#'+color);
	$('#change-label .etiquette').html(etich);
}

function saveLabel() {
	if (last_label == 0) return;
	var this_label = last_label, obj = $('.etiquette .label');
	$('#change-label').modal('hide');
	$.post('services/set_label/', {row:last_label, label:obj.attr('data-id')}, function(data) {
		obj.attr('onClick', "changeLabel("+obj.attr('data-id')+");return false;");
		$('tr[class='+this_label+'] span.label').replaceWith(obj);
	});
}

function openModal(which) {
	$('#modal-'+which).modal({
		keyboard : true, backdrop: true, show : true
	});
}

$(document).ready(function() {
	rowEventBuilder();
	tagEventsBuilder();
	
	//Tags-Labels
	$('.right_spacer > a').each(function() {
		if (!$(this).hasClass('active')) {
			$(this).hover(
					function () {
						if (!$(this).hasClass('dragging')) {
							$(this).animate({marginLeft:'0px'}, 200);	
						}						
					},
					function () {
						$(this).stop(true, true).animate({marginLeft:'-40px'}, 200);
					}
			);
		}
		
		//Tags dropped into the right father
		/*
		$(this).droppable({
			activeClass: "dragging",
			hoverClass: 'hovering',
			drop: function(event, ui) {
			
			   //New css to reflect new tag
			   var text = $(this).html();
			   if (text != 'Tutti') {
				   var bgcolor = $(this).css('backgroundColor');
				   var tmp = $(this).attr('href').split('=');
				   var id = tmp[1];
			   }else{
				   text = 'Nessuna';
				   var bgcolor = '#AAAAAA';
				   var id = 0;
			   }
			   $(ui.draggable).html(text);
			   $(ui.draggable).css('backgroundColor', bgcolor);
			   
			   //Save new tag
			   var row = $(ui.draggable).parent('td').parent('tr').attr('class');
			   $.post('services/set_label/', {row:row, label:id}, function(data) {
				//Nothing :)
			   });
			}
		});
		*/
	});
});
