
jQuery(document).ready(
   function()
   {  
   		//code line to do something
   }); 

$.ajaxSetup( {
   timeout: 20000,
   error :
	   function (XMLHttpRequest, textStatus, errorThrown) {
	   			//FIX LOGIN
	   			var regExp = new RegExp(".*GO_TO_VS_HOME*", "i")
				var currentUrl = window.location.href;
				if (currentUrl.match(regExp) == null)
	                 showAlertMessage('Errore connessione server. ' + '-' + textStatus + '-' + errorThrown + '-' + XMLHttpRequest.responseText);
	   }
 } ); 


var ajaxLoadingSmall = '<div id="ajaxSmallLoadingDiv" class="ajaxSmallLoading"><img src="/portalWeb/spesachenonpesa/resources/img/ajax/indicator_small.gif" alt=""/></div>';
var ajaxLoading	     = '<div id="ajaxLoading" class="ajaxLoading"><img src="/portalWeb/spesachenonpesa/resources/img/ajax/indicator_medium.gif" alt=""/>  Caricamento in corso...</div>';
var ajaxLoadingPart1	     = '<div id="ajaxLoading" class="ajaxLoading" style="';
var ajaxLoadingPart2	     = '"><img src="/portalWeb/spesachenonpesa/resources/img/ajax/indicator_medium.gif" alt=""/>  Caricamento in corso...</div>';

function getAjaxLoading(styleString) {
	if (styleString == '') {
		return ajaxLoading;
	} else {
		return ajaxLoadingPart1 + styleString + ajaxLoadingPart2;
	}

}


function goToUrl(URL)
{
        document.location.href = URL;
}



/*
*     Funzione per richiamare una action in modo asincrono
*     target: selettore jquery per l'elemento in cui inserire il contenuto della risposta
*     action: nome della action da richiamare (senza suffisso .action)
*     useCase: nome dello useCase della action, a cui si possono aggiungere parametri
*     addizionali semplicemente aggiungendo il carattere '&' e la coppia 'param=value'
*     come ad esempio 'nomeUseCase&param1=valore1&param2=valore2'
*/

function ajaxTrigger (target, action, params, onSuccessFunction) {
	ajaxTrigger(target, action, params, onSuccessFunction, '');
}

function ajaxTrigger (target, action, params, onSuccessFunction, styleString) {
      //clearMessages();
      $.ajax({
            url: action,
            data: "ajax=true&antiCache="+ new Date().getTime() +"&"+ params,
            success: function(msg){
              $(target).html(msg);
			  if (onSuccessFunction != '')
			  	onSuccessFunction();
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                  //$(target).html(printError(errorThrown));
                  $(target).html(XMLHttpRequest.responseText);
            }
      });
      $(target).html(getAjaxLoading(styleString));
}

function ajaxInsertAterElementTrigger (target, action, params, onSuccessFunction, styleString) {
      $.ajax({
            url: action,
            data: "ajax=true&antiCache="+ new Date().getTime() +"&"+ params,
            success: function(msg){
              $(msg).insertAfter(target);
			  if (onSuccessFunction != '')
			  	onSuccessFunction();
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                  //$(target).html(printError(errorThrown));
                  $(target).html(XMLHttpRequest.responseText);
            }
      });
}

function ajaxTriggerNoResponse(action, params, onSuccessFunction) {
      //clearMessages();
      $.ajax({
            url: action,
            data: "ajax=true&antiCache="+ new Date().getTime() +"&"+ params,
            success: function(msg){
			  if (onSuccessFunction != '')
			  	onSuccessFunction();
            }
      });
}

function ajaxTriggerSwf (target, action, params, onSuccessFunction, styleString) {
try{
      $(target).html(getAjaxLoading(styleString));
      $.ajax({
            url: action,
            data: "" + params,
            success: function(msg){
			  if (onSuccessFunction != '')
			  	onSuccessFunction();
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                  //$(target).html(printError(errorThrown));
                  $(target).html(XMLHttpRequest.responseText);
            }
      });
      
} catch(e){}      
}
function blockScreen(message)
{
	var l_message = "Caricamento in corso...";
	if (message != undefined)
		l_message = message;
	//$.blockUI({ message: '<div class="divBlockScreen"><img src="/portalWeb/spesachenonpesa/resources/img/ajax/indicator_medium.gif"/><b>Caricamento in corso...</b></div>' });
	$.blockUI({message: '<img src="/portalWeb/spesachenonpesa/resources/img/ajax/indicator_medium.gif"/><BR><BR><b style="color: #000000">' + l_message + '</b>',
			   css: { 
		            border: 'none', 
		            padding: '15px', 
		            //backgroundColor: '#000', 
		            backgroundColor: '#FFFFFF',
		            '-webkit-border-radius': '10px', 
		            '-moz-border-radius': '10px', 
		            //opacity: .5, 
		            opacity: .8,
		            color: '#fff' 
        		} });
}
function unBlockScreen(){
	$.unblockUI();
}

function showAlertMessage(message){
	var div = $("<div>");
	// By default we're going to hide the DIV until the content is loaded
   	div.hide();
   	div.html(message);
   	div.attr("class","divAlertMessage");
    $("body").prepend(div);
	div.dialog({
			bgiframe: true,
			modal: true,
			buttons: {
				Ok: function() {
					$(this).dialog('close');
				}
			}
		});
}


var selectedProvincia = "";    
var selectedProvinciaDesc = "";  
var selectedComune = ""; 
var selectedComuneDesc = "";
var localizzaSelectDefaultText = "Seleziona Provincia";

var localizzaOptions = { 
	        target:        '#user-box-loc',   // target element(s) to be updated with server response 
	        url : '/portalWeb/portale/pageflow/localizza/setCoop.do',
	        beforeSubmit:  showRequestLocalizza,
	        // pre-submit callback  
	        success:       showResponsetLocalizza
	        //,  // post-submit callback 
	        //dataType:  	   'json'        // 'xml', 'script', or 'json' (expected server response type) 
	       	};
function initLocalizza()
{
//$(document).ready(function() { 				
				//alert($("#provincia").attr("value"));
				$("#provincia").sexyCombo({
								
   								emptyText: localizzaSelectDefaultText, 
   								/*
   								name: "selectProvinciaName", 
   								id: "selectProvincia", 
   								container: "#selectProvinceDiv", 
   								url: "/portalWeb/portale/pageflow/localizza/provinceList.jsp" , 
								*/
								dropDown: true,
								autoFill: true,
								//triggerSelected: true,
								textChangeCallback: function() {
									selectedProvinciaDesc = this.getTextValue();
								},
								changeCallback: function() {
									if (this.getHiddenValue() != "")
									{ 
										selectedProvincia = this.getHiddenValue();
										selectedProvinciaDesc = this.getTextValue();
										$("#nomeProvincia").attr("value",  selectedProvinciaDesc);
										$("#provincia").attr("value",  selectedProvincia);
									}
								},
								initEventsCallback: function() {
 											selectedProvinciaDesc = this.getTextValue();
 											//$("#provincia").attr("value",  '0');
								}
 								});
  		
  			//form
 		   	// bind form using 'ajaxForm' 
	    	//$('#formLocalizzazione').ajaxForm(localizzOptions); 
	    	//alert('dopo ajax form');
	    	// bind to the form's submit event 
		    $('#formLocalizzazione').submit(function() { 
		        //alert('sumbit');
		        // inside event callbacks 'this' is the DOM element so we first 
		        // wrap it in a jQuery object and then invoke ajaxSubmit
		        //alert("submit"); 
		        if (validateFormLocalizzazione())
		        	$(this).ajaxSubmit(localizzaOptions); 
		 
		        // !!! Important !!! 
		        // always return false to prevent standard browser submit and page navigation 
		        return false; 
		    }); 
	    	
//});
}

function initComune()
{
/* NON USATO PER PROBLEMI IN DIALOG
		$("#comune").sexyCombo({
   								emptyText: "Scegli la tua cittą", 
   								dropDown: true,
								autoFill: true,
								//triggerSelected: true,
								textChangeCallback: function() {
								
								},
								changeCallback: function() {
								},
								initEventsCallback: function() {
 											//divLoading.remove();
								}
 								});
*/  		
}

function showRequestLocalizza(formData, jqForm, options) { 
	//alert("showRequestLocalizza" + selectedProvincia);
	//alert(selectedProvinciaDesc);
	
	if ($.trim(selectedProvinciaDesc) == "" && !$("#provincia").attr("value") == '0' ){
		showAlertMessage("Attenzione. Selezionare una provincia per localizzarsi");
		return false;
	}
	if(selectedProvinciaDesc == "Annulla Provincia")
	{
		//alert("annulla");
		$("#provincia").attr("value",  '0');
		$("#nomeProvincia").attr("value" , '');
	} else {
		$("#nomeProvincia").attr("value",  selectedProvinciaDesc);
	}
	
	var queryString = $.param(formData); 
	//alert('About to submit: \n\n' + formData); 
	//alert($("#nomeProvincia").attr("value"));
}
// post-submit callback 
function showResponsetLocalizza(responseText, statusText)  { 
   //alert('response ok')
   initLocalizza();
   //alert('dopo localizza ok')
}
function openComune(provincia) {
    	$('#dialog-comune').dialog({
            autoOpen: false,
            modal: true,
            bgiframe: true,
            //height: 540,
            width: 700,
            draggable: true,
            resizable: true,
            stack: true
        });
        $('#dialog-comune').html('<iframe scrolling="auto" frameborder="0" style="width:100%;height:100%;" src="/portalWeb/portale/pageflow/localizza/comune.jsp?isFromAjaxCall=TRUE"></iframe>').dialog('option', 'title', "Seleziona comune per la provincia di " + provincia ).dialog('open');
}
function closeComuneDialog()
{
    	$('#dialog-comune').dialog('close');
}

//Read a page's GET URL variables and return them as an associative array.
function getUrlVars()
{
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}

function removeURLParam(url, param)
{
 var urlparts= url.split('?');
 if (urlparts.length>=2)
 {
  var prefix= encodeURIComponent(param)+'=';
  var pars= urlparts[1].split(/[&;]/g);
  for (var i=pars.length; i-- > 0;)
   if (pars[i].indexOf(prefix, 0)==0)
    pars.splice(i, 1);
  if (pars.length > 0)
   return urlparts[0]+'?'+pars.join('&');
  else
   return urlparts[0];
 }
 else
  return url;
}

function reloadPage(cooperativa, nomeCooperativa)
{
	//alert("reload");
	blockScreen();
	//openNeon(cooperativa, nomeCooperativa);
	//SEO condition
	var regExp = new RegExp(".*cooperativa-static*", "i")
	var currentUrl = window.location.href;
	if (currentUrl.match(regExp) == null){
		//alert("reload");
		//document.location.reload();
		//document.location.href = "/portalWeb/portale/index.jsp";
		document.location.href = removeURLParam(document.location.href, "cooperativa");
	}
	else
		document.location.href = "/portalWeb/portale/index.jsp";
}

function updateFromNeon(neonWindowObject)
{
    //alert(updateFromNeon);

    // neonWindowObject is the frame containing canali and news, not the browser window
    neonWindow = neonWindowObject;
    
    if (updateNeonWindow)
    {
        updateNeonWindow = false;
        
        // neonWindow.document refers to the active frame of NEON, the window instead should be referred as neonWindow.top.document
        neonWindow.document.location.href = '/portalWeb/neon.portal?startNeon=true';

        // ALTERNATIVE: use the browser window, but this stops STREAMING
        //neonWindow.top.document.location.href = neonWindow.top.document.location.href;
    }
}
function openNeonNewHome(cooperativa, nomeCooperativa)
{
	//NON USER IN NEW HP
	//openNeon('<%=cooperativa.toString()%>', '<%=org.apache.commons.lang.StringEscapeUtils.escapeJavaScript(nomeProvincia)%>');
}
function openLogin()
{
	showAlertMessage("Login da aprire");
}
function openStoreLocator()
{
	manageLink("/StoreLocator/", "URL");
	return false;
}
function openNumeriVerdi() {
   openDettaglioDialog('/portalWeb/resources/jsp/popupDocumento.jsp?oggetto=COOP_CONTATTI', 'Approfondimento', dimX, dimY, true, true, false);
   return false;    	
}
function switchCanale(isFromHPParam, num, nomeCanale, pathCanale) {                
    /*
    $(".episodeBox").each(function() {
        $(this).addClass("inactive");
    });
    */
    $("#news-box ul li").each(function() {
        $(this).removeClass("selected");
    });
	//in canali page
	$(".rightFloatingBox ul li").each(function() {
        $(this).removeClass("selected");
    });
	
    $("#canale-link-"+num).addClass("selected");
    $("#canale-"+num).removeClass("inactive");
    $("#canale-"+num).addClass("active");
    ajaxTrigger('#canale-anticipazioni', '/portalWeb/portale/common/content/anticipazioniCanale.jsp?isFromHP=' + isFromHPParam + '&canale=' + pathCanale ,'','', 'padding-top: 50px; height: 65px');
}
function replaceFontFromEditor()
{
	//remove font fixed with editor
	$(".genericTextBox font").each(function() {
        $(this).removeAttr("face");
    });
}
function changeStyleClass(obj, newStyleClass)
{
    obj.className = newStyleClass;
}


function changeChannel(newURL)
{
    try
    {
        if (navigator.appName == 'Microsoft Internet Explorer')
        {
            // Microsoft Internet Explorer
    
            if (frameElement.width < neonOpenMaximizeWidth)
                maximizeNeon(true);
        }
        else if (navigator.appName == 'Netscape')
        {
            // Firefox
    
            if (window.innerWidth < neonOpenMaximizeWidth)
                maximizeNeon(true);
        }
    }
    catch(er)
    {
    }
    
    if (newURL != '')
    {
        //var WMP = parent.musica.WMP;
        //newURL += '&currentWMPFile=' + WMP.URL + '&currentWMPPosition=' + WMP.controls.currentPosition; 
        
        document.location.href = newURL;
    }
}

var tmpWindow;

function previewAnticipazioni(link)
{
	  //20100603 CR for video player for .flv file
    if (link.indexOf(".flv") > 0)
    {
    		openVideoPlayer(link, 'Video');
    		return true;
    }
    
    if (!tmpWindow || tmpWindow.closed)
    {
        tmpWindow = window.open (link, 'tmpWindow', 'resizable=yes,scrollbars=yes,status=yes,width=720,height=460');
    }
    tmpWindow.focus();
    return true;
}
function openForgotPassword() {
    	titolo = 'Password Dimenticata'; 
    	dimX = 430;
    	dimY = 550;
    	url = '/portalWeb/portale/pageflow/password/begin.do';
    	// We're creating a div element to load the URL contents into
    	div = $("<div>");
    	// By default we're going to hide the DIV until the content is loaded
    	div.hide();
    	$("body").prepend(div);
    	div.dialog({
            autoOpen: false,
            modal: true,
            bgiframe: true,
            height: dimX,
            width: dimY,
            draggable: true,
            resizable: true,
            stack: true
        });       
        div.html('<iframe id="dialogDivPopupFrame" scrolling="auto" frameborder="0" style="width:100%;height:100%;" src="' + url + '"></iframe>').dialog('option', 'title', titolo).dialog('open');
        //return false;
}
/**
 * Apre la dialog dell'oggetto che corrisponde al reference passato in input
 */
function openDialog(reference, title, width, height, modal, draggable) {

    //initDatepicker();

    $("object").each(function() {
        $(this).hide();
    });
    var dialog = $(reference).dialog('option', 'title', title);

    //dialog.bind('dialogclose', function(event, ui) {
    //    dialog.dialog('destroy');
    //});

    if (width)
        dialog.dialog('option', 'width', width);
    if (height)
        dialog.dialog('option', 'height', height);
    if (modal != undefined)
        dialog.dialog('option', 'modal', modal);
    if (draggable != undefined)
        dialog.dialog('option', 'draggable', draggable);

    dialog.dialog('open');
}
function openLavoraConNoi(cooperativa)
{
	var url = "/portalWeb/portlets/LavoraConNoi/tree.jsp";
	if (cooperativa == '7') {// Unicoop Firenze:
		url = "http://www.coopfirenze.it/risorseumane/home.html";
		window.open(url);
		return false;
	}
	if (cooperativa == '9'){ // Unicoop Centro Italia
		url = "http://85.47.153.236/dtlavoraconnoi/";
		window.open(url);
	}
	if (cooperativa == '8'){ // Unicoop Tirreno:
		url = "http://85.47.153.236/dtlavoraconnoi/";
		window.open(url);
		return false;	
	}
	goToUrl(url);
	return false;		
}

function openLoginDialog(contentDialog) {
	//OLD WIH CAS
	//jqDialog.content(contentDialog);
	openTMPLoginDialog();
}

function openTMPLoginDialog() {
    	titolo = 'Login'; 
    	/*dimX = 195;*/
    	/*dimY = 290;*/
    	url = '/portalWeb/portlets/RegistrazioneNascosta/login.jsp';
    	// We're creating a div element to load the URL contents into
    	div = $("<div>");
    	// By default we're going to hide the DIV until the content is loaded
    	div.hide();
    	$("body").prepend(div);
    	div.dialog({
            autoOpen: false,
            modal: true,
            bgiframe: true,
            height: 195,
            width: 290,
            draggable: true,
            resizable: true,
            stack: true
        });       
        div.html('<iframe id="dialogDivPopupFrame" scrolling="auto" frameborder="0" style="width:100%;height:100%;" src="' + url + '"></iframe>').dialog('option', 'title', titolo).dialog('open');
        //return false;
}
//=============================== TMP LOGIN ========================

function openInviaDomandaDialogBox(){
	titolo = 'INVIO DOMANDA';
	url = '/portalWeb/domanderisposte/pageflow/inviadomanda.jsp'
	div = $("<div>");
	div.hide();
	$("body").prepend(div);
   	div.dialog({
           autoOpen: false,
           modal: true,
           bgiframe: true,
           height: 380,
           width: 400,
           draggable: true,
           resizable: true,
           stack: true
       });       
       div.html('<iframe id="dialogDivPopupFrame" scrolling="auto" frameborder="0" style="width:100%;height:100%;" src="' + url + '"></iframe>').dialog('option', 'title', titolo).dialog('open');
} 

function submitLogin() 
{
        //if(isIE) showWaitState();
        //document.loginForm.submit();
        document.getElementById(getNetuiTagName("loginForm")).submit()
}

function submitCancelCreateResource() {
        toggleDialogBoxForDiv("dialogDiv");
}

function toggleDialogBoxForDiv(div, dimX, dimY){
	//nothing
}
   
//END =============================== TMP LOGIN ========================


var firebug = getUrlVars()["firebug"];	
if (firebug != null && firebug != "") {
		document.write('<script type="text/javascript" src="https://getfirebug.com/firebug-lite.js"></script>');
}
