var spinner				= "<div style='width:640px;height:480px;text-align:center;'><img style='margin-top:150px' src='http://www.siu.it/img/ajax-loader.gif' ></div>";
var help_tag			= "I tag sono etichette che possono essere aggiunte ai contenuti per identificarne meglio il significato e per creare relazioni tra essi.\nIniziando a scrivere in questo campo, verranno proposti una serie di tag già inseriti fra i quali scegliere.";
var help_visibility		= "Impostando la visibilità su pubblico, il contenuto sara visionabile da chiunque, altrimenti esso rimarrà visibile esclusivamente ai soci ed ai revisori.";
var moderation_alert 	= "I files sono stati correttamente caricati. Entro 48 ore verranno verificati dai moderatori e pubblicati se ritenuti idonei.";
var upload_list = [];

// Disable caching of AJAX responses */  
$.ajaxSetup ({
    cache: false
});

function load_uploadify(base_path, client_content_id, MEDIA_SERVLET, token, server_content_id, file_extensions){
	$("#uploadify").uploadify({
		'scriptAccess' 	 : 'always',
		'uploader'       : MEDIA_SERVLET+'uploadify.swf',
		'script'         : MEDIA_SERVLET+'manager?code='+token+'_'+server_content_id,
		'cancelImg'      : base_path+'/img/cancel.png',
		'expressInstall' : base_path+'/files/expressInstall.swf',
		'sizeLimit'      : '1610612736',
		'fileExt'     	 : file_extensions,
		'fileDesc'    	 : 'Mostra soltanto file consentiti',
		'queueID'        : 'fileQueue',
		'fileDataName'	 : 'file',
		'auto'           : true,
		'multi'          : true,
		'scriptData'	 : {
			'token'			:	token,
			'content_id'	:	server_content_id
		},
		'onOpen'		 : function (event, queueID, fileObj) {
			$('#file_pending').html("<span class='ajax_message'>caricamento contenuti...</span>");
        },
		'onError'		 : function (event, queueID, fileObj, error) {
			alert(error.type+" error : "+error.info);
			/*
			if (error.status == 404)
	        	alert('Could not find upload script');
	        else if (error.type === "HTTP")
	            alert(error.type+" error : "+error.status);
	        else if (error.type ==="File Size")
	            alert(fileObj.name+' '+error.type+' Limit: '+Math.round(error.sizeLimit/1024)+'KB');
	        else
	            alert('Unknown error '+error.type+": "+error.text);
	        */
        },
		'onComplete'     : function(event, queueID, fileObj, response, data) {
			var args = response.split("/");
			if(jQuery.trim(args[1])=='true')
				upload_list.push(args[0]);
			else
				alert("Error on upload:"+response);
		},
		'onAllComplete'     : function(event, data) {
			if(upload_list.length > 0){
				$('#file_pending').html("<span class='ajax_message'>caricamento avvenuto con successo...</span>");
				$.ajax({
					type	: 'POST',
				  	url		: base_path+'ajax_create_files/'+client_content_id,
				  	data	: { 'sent_files[]': upload_list },
				  	success	: function(data) {
					  	if(data=='true'){
					  		$('#file_pending').html("<span class='ajax_message'>aggiornamento contenuti...</span>");
					  		$('#file_pending').load(base_path+'ajax_file_list/'+client_content_id+'/'+server_content_id+'/pending');
					  		$.ajax({
								url		: base_path+'ajax_send_mail/'+client_content_id,
							  	success	: function(data) {	alert(moderation_alert);},
								error	: function(XMLHttpRequest, textStatus, errorThrown){alert("ERRORE: "+textStatus);}
							});
					  	}else{
					  		alert('Load was NOT performed: '+data);
					  	}
					},
					error		: function(XMLHttpRequest, textStatus, errorThrown){
					  	alert("ERRORE: "+textStatus);
					}
				});
			}
			upload_list = [];
		}
	});
}

function view_file_window(base_path, file_name, file_id){
	var mask_obj = $('#mask');
	var dialog_obj = $('#dialog');
	
	//Get the 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});
	
	//transition effect		
	$('#mask').fadeIn(1000);	
	$('#mask').fadeTo("slow",0.8);	

	var winW = $(window).width();
	var winH = $(window).height();
	$('#dialog').css('left', winW/2-$('#dialog').width()/2);
	$('#dialog').css('top',  winH/2-$('#dialog').height()/2);

	$('#file_title').html("&nbsp;<b>"+file_name+"</b>");
	$('#file_viewer').html(spinner);
	
	//transition effect
	$('#dialog').fadeIn(2000); 
	
	$('#file_viewer').load(
		base_path+'ajax_view_file/'+file_id,
		function(responseText, textStatus, XMLHttpRequest) {
			
		}
	);	 
}

function view_file_inline(base_path, file_name, file_id){
	$('#file_title').html("&nbsp;<b>"+file_name+"</b>");
	$('#file_viewer').html(spinner);
	$('#file_viewer').load(
		base_path+'ajax_view_file/'+file_id,
		function(responseText, textStatus, XMLHttpRequest) {
			
		}
	);	 
}

function view_search_inline(href,params,divName) {
	$(divName).html(spinner);   
    $(divName).load(href, params, function(){
        var divIntestationLinks = divName+" #intestation a";
        var divPaginationLinks = divName+" #pagination a";
        $(divIntestationLinks+","+divPaginationLinks).click(function() {     
            var thisHref = $(this).attr("href");
            view_search_inline(thisHref,params,divName);
            return false;
        });
    });
}

function toggle_file(base_path, client_content_id, file_type, server_content_id, file_id, range){
	if (confirm('Confermi la modifica?')){
		$('#file_'+file_type).html("<span class='ajax_message'>modifica in corso...</span>");
		$.ajax({
		  url		: base_path+'ajax_toggle_file/'+file_id+'/'+range,
		  success	: function(data) {
		  	if(data=='true'){
		  		if($('#file_hidden')){
		  			$('#file_hidden').html("<span class='ajax_message'>aggiornamento contenuti...</span>");
		  			$('#file_hidden').load(base_path+'ajax_file_list/'+client_content_id+'/'+server_content_id+'/hidden');
		  		}
		  		if($('#file_deployed')){
		  			$('#file_deployed').html("<span class='ajax_message'>aggiornamento contenuti...</span>");
		  			$('#file_deployed').load(base_path+'ajax_file_list/'+client_content_id+'/'+server_content_id+'/deployed');
		  		}
		  	}else{
		  		alert('Load was NOT performed: '+data);
		  	}
		  },
		  error		: function(XMLHttpRequest, textStatus, errorThrown){
		  	alert("ERRORE: "+textStatus);
		  }
		});
	};
	return false;
}

function delete_file(base_path, client_content_id, file_type, server_content_id, file_id){
	if (confirm('Vuoi eliminare l\'elemento selezionato?')){
		$('#file_'+file_type).html("<span class='ajax_message'>eliminazione in corso...</span>");
		$.ajax({
		  url		: base_path+'ajax_delete_file/'+client_content_id+'/'+file_id,
		  success	: function(data) {
		  	if(data=='true'){
		  		$('#file_'+file_type).html("<span class='ajax_message'>aggiornamento contenuti...</span>");
		  		$('#file_'+file_type).load(base_path+'ajax_file_list/'+client_content_id+'/'+server_content_id+'/'+file_type);
		  	}else{
		  		alert('Load was NOT performed: '+data);
		  	}
		  },
		  error		: function(XMLHttpRequest, textStatus, errorThrown){
		  	alert("ERRORE: "+textStatus);
		  }
		});
	};
	return false;
}

function init_interact(base_path, view, client_content_id, MEDIA_SERVLET, token, server_content_id, file_extensions){
	if(view=='load')		load_uploadify(base_path, client_content_id, MEDIA_SERVLET, token, server_content_id,file_extensions);
	if($('#file_pending'))	$('#file_pending').load(base_path+'ajax_file_list/'+client_content_id+'/'+server_content_id+'/pending');
	if($('#file_hidden'))	$('#file_hidden').load(base_path+'ajax_file_list/'+client_content_id+'/'+server_content_id+'/hidden');
	if($('#file_deployed'))	$('#file_deployed').load(base_path+'ajax_file_list/'+client_content_id+'/'+server_content_id+'/deployed');
	$('#close_button').click(function (e) { e.preventDefault(); $('#mask, .window').hide(); });		
	$('#mask').click(function () { $('#mask, .window').hide(); });	
}

function loadContentsManager(base_path){
	if($('#contents_manager'))	$('#contents_manager').load(base_path+'ajax_index');
	if($('#contents_viewer'))	$('#contents_viewer').load(base_path+'ajax_index/show');
}

function createAutocompleteField(base_path, input_field){
 $(document).ready(function(){
	$("#"+input_field).autocomplete(base_path+'ajax_tag_list', {
		multiple: true,
		autoFill: true
	});
  });
}

function createAjaxPagination(){
        $("#pagination a").click(function() {     
            var thisHref = $(this).attr("href");
            loadPiece(thisHref,divName);
            return false;
        }); 
}

function mediatecaIndexSearch(base_path){
	var params = {
		titolo	:	$('#SearchTitolo').val(),
		tipo	:	$('#SearchTipo').val(),
		tags	:	$('#SearchTags').val()
	}
	view_search_inline(base_path+'results',params,'#other_view');  
	$('#main_view').hide();
	$('#other_view').show();
}

function mediatecaIndexView(base_path, file_name, file_id){
	view_file_inline(base_path, file_name, file_id);
	$('#other_view').hide();
	$('#main_view').show();
}

