
function start() {
    $("#start_content").dialog({
      height: 625,
      width:  780,
      title:'',
      modal:  true,
      resizable: false,
      draggable: false,
 /*     buttons: {
        Ok: function() {
          $.cookie('trail', '1');
          $(this).dialog('close');
        }
      },
*/
      open: function( event, ui) {

        if (Get_Cookie('loggedinfbc')) {
          $(this).dialog('close');
        }
      }
    });

    $("#start_content").dialog().parents(".ui-dialog").find(".ui-dialog-titlebar").remove();

    $("#presentation_menu").tabs({
      collapsible: true,
      autoHeight: false
    });

}



  $(document).ready( function() {

   $("#presentation_menu").tabs({
      collapsible: true,
      autoHeight: false
    });






    $("#start_button").click(function() { alert("ciao"); $("#start_content").dialog('close'); $.cookie('trail', '1'); } );

    $("#tabs").tabs({
      selected: 3,
      collapsible: true,
      autoHeight: false
    });
    $("#tabs").bind('tabsshow', function(event, ui) {
     checkMapResize();
     refresh_watermarks();
    });
    refresh_watermarks();


    $('#shipping_date').datepicker({
      onClose: function(dateText, inst) { $('#shipping_date').keyup(); refresh_watermarks();  }, // this is neccessary for the values.sync to catch the data
      //$.datepicker.regional['it']
        closeText: 'Chiudi',
        prevText: '&#x3c;Prec',
        nextText: 'Succ&#x3e;',
        currentText: 'Oggi',
        monthNames: ['Gennaio','Febbraio','Marzo','Aprile','Maggio','Giugno', 'Luglio','Agosto','Settembre','Ottobre','Novembre','Dicembre'],
        monthNamesShort: ['Gen','Feb','Mar','Apr','Mag','Giu', 'Lug','Ago','Set','Ott','Nov','Dic'],
        dayNames: ['Domenica','Luned&#236','Marted&#236','Mercoled&#236','Gioved&#236','Venerd&#236','Sabato'],
        dayNamesShort: ['Dom','Lun','Mar','Mer','Gio','Ven','Sab'],
        dayNamesMin: ['Do','Lu','Ma','Me','Gio','Ve','Sa'],
        dateFormat: 'dd/mm/yy', firstDay: 1,
        isRTL: false,
      dateFormat: "yy-mm-dd",
      numberOfMonths: 3,
      minDate: '-21D',
      maxDate:  '+3M'
    });

    $("#shipSearch").autocomplete("equasis.php", {
      cacheLength: 1,
      minChars: 4,
      matchCase: false,
      matchContains: true,
      width: 300,
      max: 20, highlight: false,
      scroll: true,
      scrollHeight: 300,
      // formatResult: function(data, value) { return value.split(".")[0]; },
      formatItem: function(data, i, n, value) { return value.split(".")[0]; }
    }).ajaxSend( function(){ $('#work_img').css("display", "inline");} ).ajaxComplete( function(){ $('#work_img').css("display", "none"); } );

    $("#shipSearch").result(function(event, data, formatted) {
      $("#ship_details").html('');
      $("#ship_name").val('');
      $("#ship_type").val('');
      $("#ship_launch").val('');
      if (data){
        var dati_nave = String(data);
        $("#ship_details").html("Nave: " + dati_nave.split(".")[0] + ", " );
        $("#ship_name").val( dati_nave.split(".")[0]);
        if( dati_nave.split(".")[2] ) {
          $("#ship_details").append( dati_nave.split(".")[2] + " varata nel " + dati_nave.split(".")[3] );
          $("#ship_type").val( dati_nave.split(".")[2]);
          $("#ship_launch").val( dati_nave.split(".")[3]);
        }
      }
      refreshFormData();
    });

    $("#shipSearch").change(function(){
      $("#ship_details").html('');
      $("#ship_name").val('');
      $("#ship_type").val('');
      $("#ship_launch").val('');
      refreshFormData();
    });

    $("#behalf_company").autocomplete("covers.php?a=m", {
      cacheLength: 1,
      minChars: 2,
      matchCase: false,
      matchContains: true,
      width: 300,
      max: 20, highlight: false,
      scroll: true,
      scrollHeight: 300,
      // formatResult: function(data, value) { return value.split(".")[0]; },
      formatItem: function(data, i, n, value) {
          var client_array = eval( "(" + value + ")" );
          return( client_array["behalf_company"] );
        }
    }).ajaxSend( function(){ $('#cust_img').css("display", "inline");} ).ajaxComplete( function(){ $('#cust_img').css("display", "none"); } );

    $("#behalf_company").result(function(event, data, formatted) {
      if (data) {
        var client_array = eval( "(" + data + ")" );
        for( field in client_array) {
          $("#" + field).val( client_array[ field]);
        }
      }
    });


    $("#quaterly_review").jqGrid({
      url:'covers.php?a=c&q=1',
      datatype: "json",
     colNames:['Cert. N.', 'Data', 'Carico', 'Scarico', 'Mezzo', 'Nome', 'Stato', 'Peso', 'Desc. Merci', 'Desc. Imballo', 'Incoterms', 'import', 'Tipo imballo', 'Valore', 'Tasso', 'Premio', 'coverid'],
      colModel:[
        {name:'certificate_number',index:'certificate_number', width:30, align:"center", sorttype:"int"},
        {name:'action_date',index:'action_date', width:70, align:"center"},
        {name:'embankmentPort',index:'embankmentPort', width:70},
        {name:'unloadingPort',index:'unloadingPort', width:70},
        {name:'route_EP_UP_type',index:'route_EP_UP_type', width:40},
        {name:'ship_name',index:'ship_name', width:100, align:"right"},
        {name:'goods_condition',index:'goods_condition', width:60},
        {name:'weight',index:'weight', width:90},
        {name:'goods_description',index:'goods_description', width:230},
        {name:'packaging_description',index:'packaging_description', width:150},
        {name:'incoterms',index:'incoterms', width:35, align:"center"},
        {name:'behalf_role',index:'behalf_role', width:40,align:"left"},
        {name:'packaging_type',index:'packaging_type', width:70},
        {name:'value',index:'value', width:45, align:"right"},
        {name:'rate',index:'rate', width:35, sortable:false},
        {name:'premium',index:'premium', width:40, sortable:false},
        {name:'cover_id',index:'cover_id', width:30, sortable:true}
      ],
      loadComplete: function(){ $("#quaterly_review").jqGrid( 'setGridParam', {datatype:'local'}); },
      onPaging: function(){ $("#quaterly_review").jqGrid( 'setGridParam', {datatype:'json'}); },
      jsonReader: { repeatitems : false, id: "cover_id" }, 
      height:'100%',
      rowNum:80,
      rowList:[80,200,500],
      pager: $('#quaterly_pager'),
      sortname: 'cover_id',
      viewrecords: true,
      sortorder: "desc"
    }).navGrid('#quaterly_pager',{edit:false,add:false,del:false});

    $("#covers").jqGrid({
      url:'covers.php?a=c&q=1',
      datatype: "json",
     colNames:['cover_id', 'Cert. N.', 'Pratica N.','Data', 'Mandante', 'Origine', 'Carico', 'Scarico', 'Destino', 'Incoterms', 'Ruolo', 'Mezzo', 'Nome', 'Descrizione Merce', 'Imballo', 'Valore', 'Tasso', 'Premio', ' '],
      colModel:[
        {name:'cover_id',index:'cover_id', width:0, hidden:true},
        {name:'certificate_number',index:'certificate_number', width:30, align:"center"},
        {name:'contract_number',index:'contract_number', width:70, align:"center"},
        {name:'shipping_date',index:'shipping_date', width:70, align:"center"},
        {name:'behalf_company',index:'behalf_company', width:100},
        {name:'sourceCity',index:'sourceCity', width:70},
        {name:'embankmentPort',index:'embankmentPort', width:70},
        {name:'unloadingPort',index:'unloadingPort', width:70},
        {name:'endDestination ',index:'endDestination ', width:70},
        {name:'incoterms',index:'incoterms', width:35, align:"center"},
        {name:'behalf_role',index:'behalf_role', width:40,align:"left"},
        {name:'route_EP_UP_type',index:'route_EP_UP_type', width:40},
        {name:'ship_name',index:'ship_name', width:100, align:"right"},
        {name:'goods_description',index:'goods_description', width:230},
        {name:'packaging_description',index:'desc_imballo', width:70},
        {name:'value',index:'value', width:45, align:"right"},
        {name:'rate',index:'rate', width:35, sortable:false},
        {name:'premium',index:'premium', width:40, sortable:false},
        {name:'action',index:'action', width:60, sortable:false}
      ],
      jsonReader: { repeatitems : false, id: "cover_id" }, 
      height:'100%',
      rowNum:20,
      //autowidth: true,
      rowList:[10,20,30],
      pager: $('#covers_pager'),
      sortname: 'contract_number',
      viewrecords: true,
      sortorder: "desc",
      loadComplete: function(){
        var ids = $("#covers").getDataIDs();
        for(var i=0;i<ids.length;i++){
          var cl = ids[i];
          var clData = $("#covers").getRowData( cl );
//alert( dump(clData) );
          pop_html = "<a href='http://www.sacebi.com/soluzioni/spedizionieri/?action=view&cover_id=" + clData.cover_id + "'>Certificato</a>";
          $("#covers").setRowData(ids[i],{action:pop_html})
        }
      }

    }).navGrid('#covers_pager',{edit:false,add:false,del:false});

    $("#drafts").jqGrid({
      url:'covers.php?a=d&q=1',
      datatype: "json",
     colNames:['cover_id', 'Pratica N.','Data', 'Mandante', 'Origine', 'Carico', 'Scarico', 'Destino', 'Incoterms', 'Ruolo', 'Mezzo', 'Nome', 'Descrizione Merce', 'Imballo', 'Valore', ' ', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', ''],
      colModel:[
        {name:'cover_id',index:'cover_id', width:0, hidden:true},
        {name:'contract_number',index:'contract_number', width:70, align:"center"},
        {name:'shipping_date',index:'shipping_date', width:60, align:"center"},
        {name:'behalf_company',index:'behalf_company', width:80},
        {name:'sourceCity',index:'sourceCity', width:70},
        {name:'embankmentPort',index:'embankmentPort', width:70},
        {name:'unloadingPort',index:'unloadingPort', width:70},
        {name:'endDestination ',index:'endDestination ', width:70},
        {name:'incoterms',index:'incoterms', width:35, align:"center"},
        {name:'behalf_role',index:'behalf_role', width:40,align:"left"},
        {name:'route_EP_UP_type',index:'route_EP_UP_type', width:40},
        {name:'ship_name',index:'ship_name', width:100, align:"right"},
        {name:'goods_description',index:'goods_description', width:230},
        {name:'packaging_description',index:'desc_imballo', width:70},
        {name:'value',index:'value', width:45, align:"right"},
        {name:'action',index:'action', width:80, sortable:false},

        {name:'notes',index:'notes', width:0, hidden:true},
        {name:'behalf_roadtype',index:'behalf_roadtype', width:0, hidden:true},
        {name:'behalf_roadname',index:'behalf_roadname', width:0, hidden:true},
        {name:'behalf_number',index:'behalf_number', width:0, hidden:true},
        {name:'behalf_postcode',index:'behalf_postcode', width:0, hidden:true},
        {name:'behalf_city',index:'behalf_city', width:0, hidden:true},
        {name:'behalf_country',index:'behalf_country', width:0, hidden:true},
        {name:'behalf_province',index:'behalf_province', width:0, hidden:true},
        {name:'behalf_ssn',index:'behalf_ssn', width:0, hidden:true},
        {name:'behalf_registration',index:'behalf_registration', width:0, hidden:true},
        {name:'goods_type',index:'goods_type', width:0, hidden:true},
        {name:'goods_condition',index:'goods_condition', width:0, hidden:true},
        {name:'weight',index:'weight', width:0, hidden:true},
        {name:'packaging_description',index:'packaging_description', width:0, hidden:true},
        {name:'ship_type',index:'ship_type', width:0, hidden:true},
        {name:'ship_launch',index:'ship_launch', width:0, hidden:true},
        {name:'airwaybill',index:'airwaybill', width:0, hidden:true},

      ],
      jsonReader: { repeatitems : false, id: "cover_id" }, 
      height:'100%',
      rowNum:10,
      //autowidth: true,
      //rowList:[10,20,30],
      pager: $('#drafts_pager'),
      sortname: 'shipping_date',
      viewrecords: true,
      sortorder: "desc",
      loadComplete: function(){
        var ids = $("#drafts").getDataIDs();
        var draftsData = {};
        for(var i=0;i<ids.length;i++){
          var cl = ids[i];
          draftsData[ cl ] = $("#drafts").getRowData( cl );
//alert( dump(draftsData) );
          load_html = "<button type='button' id='load_draft_" + cl + "'>Carica bozza</button>";
          $("#drafts").setRowData(ids[i],{action:load_html})
          $("#load_draft_" + cl).click( function( ) {
            alert("carico la pratica selezionata");
            setFormData( draftsData[ $(this).attr("id").substring(11) ]);
            refreshFormData(); 
            force_complete_map_refresh();
          });
        }
      }

    }).navGrid('#drafts_pager',{edit:false,add:false,del:false});

    $("#templates").jqGrid({
      url:'covers.php?a=t&q=1',
      datatype: "json",
     colNames:['cover_id', 'Pratica N.','Data', 'Mandante', 'Origine', 'Carico', 'Scarico', 'Destino', 'Incoterms', 'Ruolo', 'Mezzo', 'Nome', 'Descrizione Merce', 'Imballo', 'Valore', ' ', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', ''],
      colModel:[
        {name:'cover_id',index:'cover_id', width:0, hidden:true},
        {name:'contract_number',index:'contract_number', width:70, align:"center"},
        {name:'shipping_date',index:'shipping_date', width:60, align:"center"},
        {name:'behalf_company',index:'behalf_company', width:80},
        {name:'sourceCity',index:'sourceCity', width:70},
        {name:'embankmentPort',index:'embankmentPort', width:70},
        {name:'unloadingPort',index:'unloadingPort', width:70},
        {name:'endDestination ',index:'endDestination ', width:70},
        {name:'incoterms',index:'incoterms', width:35, align:"center"},
        {name:'behalf_role',index:'behalf_role', width:40,align:"left"},
        {name:'route_EP_UP_type',index:'route_EP_UP_type', width:40},
        {name:'ship_name',index:'ship_name', width:100, align:"right"},
        {name:'goods_description',index:'goods_description', width:230},
        {name:'packaging_description',index:'desc_imballo', width:70},
        {name:'value',index:'value', width:45, align:"right"},
        {name:'action',index:'action', width:80, sortable:false},

        {name:'notes',index:'notes', width:0, hidden:true},
        {name:'behalf_roadtype',index:'behalf_roadtype', width:0, hidden:true},
        {name:'behalf_roadname',index:'behalf_roadname', width:0, hidden:true},
        {name:'behalf_number',index:'behalf_number', width:0, hidden:true},
        {name:'behalf_postcode',index:'behalf_postcode', width:0, hidden:true},
        {name:'behalf_city',index:'behalf_city', width:0, hidden:true},
        {name:'behalf_country',index:'behalf_country', width:0, hidden:true},
        {name:'behalf_province',index:'behalf_province', width:0, hidden:true},
        {name:'behalf_ssn',index:'behalf_ssn', width:0, hidden:true},
        {name:'behalf_registration',index:'behalf_registration', width:0, hidden:true},
        {name:'goods_type',index:'goods_type', width:0, hidden:true},
        {name:'goods_condition',index:'goods_condition', width:0, hidden:true},
        {name:'weight',index:'weight', width:0, hidden:true},
        {name:'packaging_description',index:'packaging_description', width:0, hidden:true},
        {name:'ship_type',index:'ship_type', width:0, hidden:true},
        {name:'ship_launch',index:'ship_launch', width:0, hidden:true},
        {name:'airwaybill',index:'airwaybill', width:0, hidden:true},

      ],
      jsonReader: { repeatitems : false, id: "cover_id" }, 
      height:'100%',
      rowNum:10,
      //autowidth: true,
      //rowList:[10,20,30],
      pager: $('#templates_pager'),
      sortname: 'shipping_date',
      viewrecords: true,
      sortorder: "desc",
      loadComplete: function(){
        var ids = $("#templates").getDataIDs();
        var templatesData = {};
        for(var i=0;i<ids.length;i++){
          var cl = ids[i];
          templatesData[ cl ] = $("#templates").getRowData( cl );
//alert( dump(templatesData) );
          load_html = "<button type='button' id='load_template_" + cl + "'>Carica modello</button>";
          $("#templates").setRowData(ids[i],{action:load_html})
          $("#load_template_" + cl).click( function( ) {
            alert("carico il modello selezionato");
            setFormData( templatesData[ $(this).attr("id").substring(14) ]);
            refreshFormData(); 
            force_complete_map_refresh();
          });
        }
      }

    }).navGrid('#templates_pager',{edit:false,add:false,del:false});

    $("#reserved").jqGrid({
      url:'covers.php?a=r&q=1',
      datatype: "json",
     colNames:['cover_id', 'Pratica N.','Data', 'Mandante', 'Origine', 'Carico', 'Scarico', 'Destino', 'Incoterms', 'Ruolo', 'Mezzo', 'Nome', 'Descrizione Merce', 'Tipo M.', 'Imballo', 'Valore', 'Tasso', 'Premio', ' ',  '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', ''],
      colModel:[
        {name:'cover_id',index:'cover_id', width:0, hidden:true},
        {name:'contract_number',index:'contract_number', width:70, align:"center"},
        {name:'shipping_date',index:'shipping_date', width:60, align:"center"},
        {name:'behalf_company',index:'behalf_company', width:80},
        {name:'sourceCity',index:'sourceCity', width:70},
        {name:'embankmentPort',index:'embankmentPort', width:70},
        {name:'unloadingPort',index:'unloadingPort', width:70},
        {name:'endDestination ',index:'endDestination ', width:70},
        {name:'incoterms',index:'incoterms', width:35, align:"center"},
        {name:'behalf_role',index:'behalf_role', width:40,align:"left"},
        {name:'route_EP_UP_type',index:'route_EP_UP_type', width:40},
        {name:'ship_name',index:'ship_name', width:100, align:"right"},
        {name:'goods_description',index:'goods_description', width:230},
        {name:'goods_type',index:'goods_type', width:50 },
        {name:'packaging_description',index:'desc_imballo', width:70},
        {name:'value',index:'value', width:45, align:"right"},
        {name:'rate',index:'rate', width:30, sortable:false},
        {name:'premium',index:'premium', width:30, sortable:false},
        {name:'action',index:'action', width:80, sortable:false},

        {name:'notes',index:'notes', width:0, hidden:true},
        {name:'behalf_roadtype',index:'behalf_roadtype', width:0, hidden:true},
        {name:'behalf_roadname',index:'behalf_roadname', width:0, hidden:true},
        {name:'behalf_number',index:'behalf_number', width:0, hidden:true},
        {name:'behalf_postcode',index:'behalf_postcode', width:0, hidden:true},
        {name:'behalf_city',index:'behalf_city', width:0, hidden:true},
        {name:'behalf_country',index:'behalf_country', width:0, hidden:true},
        {name:'behalf_province',index:'behalf_province', width:0, hidden:true},
        {name:'behalf_ssn',index:'behalf_ssn', width:0, hidden:true},
        {name:'behalf_registration',index:'behalf_registration', width:0, hidden:true},
        {name:'goods_type',index:'goods_type', width:0, hidden:true},
        {name:'goods_condition',index:'goods_condition', width:0, hidden:true},
        {name:'weight',index:'weight', width:0, hidden:true},
        {name:'packaging_description',index:'packaging_description', width:0, hidden:true},
        {name:'ship_type',index:'ship_type', width:0, hidden:true},
        {name:'ship_launch',index:'ship_launch', width:0, hidden:true},
        {name:'airwaybill',index:'airwaybill', width:0, hidden:true},

      ],
      jsonReader: { repeatitems : false, id: "cover_id" }, 
      height:'100%',
      rowNum:10,
      //autowidth: true,
      //rowList:[10,20,30],
      pager: $('#reserved_pager'),
      sortname: 'shipping_date',
      viewrecords: true,
      sortorder: "desc",
      loadComplete: function(){
        var ids = $("#reserved").getDataIDs();
        var reservedData = {};
        for(var i=0;i<ids.length;i++){
          var cl = ids[i];
          reservedData[ cl ] = $("#reserved").getRowData( cl );
//alert( dump(reservedData) );
/*
          load_html = "<button type='button' id='load_template_" + cl + "'>Carica modello</button>";
          $("#reserved").setRowData(ids[i],{action:load_html})
          $("#load_template_" + cl).click( function( ) {
            alert("carico il modello selezionato");
            setFormData( reservedData[ $(this).attr("id").substring(14) ]);
            refreshFormData(); 
            force_complete_map_refresh();
          });
*/
        }
      }

    }).navGrid('#reserved_pager',{edit:false,add:false,del:false});



    $("#list_templates").jqGrid({
        onHeaderClick: function( gridstate) {
          jQuery.ajax({
            url: "covers.php?a=t&q=1",
            dataType:"json",
            complete: function(jsondata,stat){
              if(stat=="success") {
                var formData = eval("("+jsondata.responseText+")");
                var newFormData = new Array();
                for( datakey in formData.rows) {
                  newFormData[ formData.rows[ datakey].cover_id ] = formData.rows[ datakey];
                }
                $("#list_templates").data( "formData", newFormData );
//alert( dump( $("#list_templates").data( "formData") ) );
                $("#list_templates")[0].addJSONData(formData);
              }
            }
          });
        },
       
        height: "auto",
        pager: false,
        hiddengrid: true,
        colModel: [
            {name: "menu", width:150, resizable: false, sortable:false, jsonmap:"notes"},
            {name: "id",width:1,hidden:true, key:true, jsonmap:"cover_id"}
        ],
        treeGrid: true,
	caption: "Modelli salvati",
        autowidth: true,
        jsonReader: { repeatitems : false, id: "cover_id" }, 
        treeIcons: {leaf:'ui-icon-document-b'},
        onSelectRow: function(rowid) {
            alert("carico la pratica selezionata");
            setFormData( $("#list_templates").data("formData")[rowid]);
            refreshFormData(); 
            force_complete_map_refresh();
            $("#list_templates").resetSelection();
        }
    });

    $("#list_drafts").jqGrid({
        onHeaderClick: function( gridstate) {
          jQuery.ajax({
            url: "covers.php?a=d&q=1",
            dataType:"json",
            complete: function(jsondata,stat){
              if(stat=="success") {
                var formData = eval("("+jsondata.responseText+")");
                var newFormData = new Array();
                for( datakey in formData.rows) {
                  newFormData[ formData.rows[ datakey].cover_id ] = formData.rows[ datakey];
                }
                $("#list_drafts").data( "formData", newFormData );
                $("#list_drafts")[0].addJSONData(formData);
              }
            }
          });
        },
       
        height: "auto",
        pager: false,
        hiddengrid: true,
        colModel: [
            {name: "menu", width:150, resizable: false, sortable:false, jsonmap:"notes"},
            {name: "id",width:1,hidden:true, key:true, jsonmap:"cover_id"}
        ],
        treeGrid: true,
	caption: "Bozze salvate",
        autowidth: true,
        jsonReader: { repeatitems : false, id: "cover_id" }, 
        treeIcons: {leaf:'ui-icon-document-b'},
        onSelectRow: function(rowid) {
            alert("carico la pratica selezionata");
            setFormData( $("#list_drafts").data("formData")[rowid]);
            refreshFormData(); 
            force_complete_map_refresh();
            $("#list_drafts").resetSelection();
        }
    });


    $('#goods_type').qtip({ content: 'Vengono comunque escluse dall assicurazione le seguenti merci: carte valori, documenti, francobolli, oggetti in materiale preziosom esplosivi, liquidi infiammabili, animali vivim piante vive, fiori freschi, masserizie e/o oggetti usati, merci avariate, argenterie, pellicce, tappeti pregiati, quadri, sculture in genere, oggetti aventi valore d arte, di antiquariato, di collezionismo, o affezione, merci gia avariate, autoveicoli, generi di monopolio, carichi completi di caffe e farmaceutici.',
      show: 'mouseover',
      hide: 'mouseout',
      style: { 
        width: 500,
        padding: 9,
        background: '#E8FFD9',
        color: 'black',
        textAlign: 'left',
        border: {
           width: 7,
           radius: 5,
           color: '#527932'
        },
        tip: 'leftBottom',
        name: 'dark'
      },
      position: {
        corner: {
          target: 'bottomRight',
          tooltip: 'bottomLeft'
        }
      }
    });

    
    initGeoCoder();

    function report_field_not_empty( field_name, field_name_suffix) {
      $("#report_row_" + field_name ).bind( "set.values", function(){
        if( $("#" + field_name + field_name_suffix ).val() == '' || $("#" + field_name + field_name_suffix).val() == null ) {
          $("#report_" + field_name).css("background-color",     "");
        } else {
          $("#report_" + field_name).css("background-color",  "#BEFFB7");
        }
      });
    }

    $("#report").syncFrom("#InsuranceProposal", {SetEvents: true});
    $("#report_row_behalf_company").click( function(){ select_shipping_tab( 1 ); });
    report_field_not_empty( "behalf_company", '' );

    $("#report_row_behalf_role").click(    function(){ select_shipping_tab( 1 ); });
    report_field_not_empty( "behalf_role", '' );

    $("#report_row_value").click(          function(){ select_shipping_tab( 2 ); });
    $("#report_row_value").bind( "set.values", function(){
      if(      $("#value").val() == '') { $("#report_value").css("background-color",     ""); }
      else if( $("#value").val() >  1 ) { $("#report_value").css("background-color","#BEFFB7"); }
      else                              { $("#report_value").css("background-color",  "red"); }
    });
    $("#report_row_goods_type").click(     function(){ select_shipping_tab( 2 ); });
    report_field_not_empty( "goods_type", '' );

    $("#report_row_shipping_date").click(  function(){ select_shipping_tab( 3 ); });
    report_field_not_empty( "shipping_date", '' );

    $("#report_row_route_EP_UP_type").click( function(){ select_shipping_tab( 3 ); });
    $("#report_row_route_EP_UP_type").bind( "set.values", function(){
      $("#report_route_EP_UP_type").css("background-color",  "#BEFFB7"); 
      if( $("#route_EP_UP_type").val() == 'SEA' && ( $("#ship_launch").val() < 1800 || $("#ship_launch").val() =='') ) { $("#report_route_EP_UP_type").css("background-color","red"); }
    });
    $("#report_row_ship_name").click(      function(){ select_shipping_tab( 3 ); });
    report_field_not_empty( "ship_name", '' );


    $("#report_row_incoterms").click(      function(){ select_shipping_tab( 3 ); });
    report_field_not_empty( "incoterms", '' );

    $("#report_row_sourceCity").click(     function(){ select_shipping_tab( 3 ); });
    report_field_not_empty( "sourceCity", "NormalizedCountryCode" );

    $("#report_row_embankmentPort").click( function(){ select_shipping_tab( 3 ); });
    report_field_not_empty( "embankmentPort", "NormalizedCountryCode" );

    $("#report_row_unloadingPort").click(  function(){ select_shipping_tab( 3 ); });
    report_field_not_empty( "unloadingPort", "NormalizedCountryCode" );

    $("#report_row_endDestination").click( function(){ select_shipping_tab( 3 );});
    report_field_not_empty( "endDestination", "NormalizedCountryCode" );

    refreshFormData() ;




    function select_shipping_tab( tab_idx ) {
      if( $("#tabs").tabs("option", "selected") !=  tab_idx ) {
        $("#tabs").tabs("select", tab_idx);
      } 
    }




    $("#route_EP_UP_type").change( function(){ toggle_vehicle_details_field(); refresh_watermarks(); });
    toggle_vehicle_details_field();

    $("#incoterms").change( set_insured_routes );
    $("#behalf_role").change( set_insured_routes );
    set_insured_routes();

    $("#InsuranceProposal").change( get_shipping_quote);

    $("#cover_button").click( request_storage );
    $("#offer_button").click( get_shipping_quote );
    $("#template_button").click( request_storage );
    $("#draft_button").click( request_storage );
    $("#reset_button").click(function() { $('#InsuranceProposal_reset').click(); refreshFormData(); });
    $("#tutorial_button").click(function() { tutorial(); });

       
  });

  $("#accordion").accordion( 'option', 'active', 0) ;


function tutorial() {

  var start_msg = "&Egrave; molto semplice comunicarci una copertura.<br> Proviamo a inserire una spedizione via mare.</p>";
  var description_msg = "Passiamo alla scheda 'Merci' e inseriamo un valore ed una descrizione";
  var embank_msg = "Ci spostiamo sulla mappa e inseriamo il porto di carico";
  var google_msg = "Lasciamo lavorare la mappa!";
  var unload_msg = "poi inseriamo il porto di scarico.";
  var end_msg = "La mappa si aggiorna e mostra il risultato.";

  $("<div id='tutorial_cursor' style='background-color:#E0E0C0'></div>").appendTo("body");

  tutorial_step( 1, start_msg, '', '', '');

  $("#tutorial_cursor").bind("tutorial_step2", function() { tutorial_step( 2, description_msg,  2, 'goods_description', 'Prova Descrizione', " go_type( 'value', '10000'); "); }); 
  $("#tutorial_cursor").bind("tutorial_step3", function() { tutorial_step( 3,      embank_msg,  3,    'embankmentPort',     'Genova italia', ''); }); 
  $("#tutorial_cursor").bind("tutorial_step4", function() { tutorial_step( 4,      google_msg, '',                  '',                  '', "$('#embankmentPort').change();"); }); 
  $("#tutorial_cursor").bind("tutorial_step5", function() { tutorial_step( 5,      unload_msg, '',     'unloadingPort', 'bangkok tailandia', "$('#unloadingPort').change();"); }); 
  $("#tutorial_cursor").bind("tutorial_step6", function() { tutorial_step( 6,         end_msg, '',                  '',                  '', ""); }); 
}

function tutorial_step( step, message, tab, field, content, firing_code) {
  var delay = 0;

  $("#tutorial_cursor").html( message ).dialog({
    bgiframe: true, MODAl: false, position: [ 700 ,100 ],
    buttons: {
      Ok: function() {
        $(this).dialog('destroy');
        if( tab != '' && tab >= 0 && tab <= 20) {  $("#tabs").tabs( 'select', tab); }
        if( field != '' ) {
          delay = delay +  500; setTimeout( " $('#" + field + "').css({ backgroundColor:'yellow', fontWeight:'bolder' }); ", delay);
          delay = delay +  250; setTimeout( " go_type( '" + field + "', '" + content + "'); ", delay);
          delay = delay + content.length*200; setTimeout( " $('#" + field + "').css({ backgroundColor:'', fontWeight:'' }); ", delay);
        }
        if( firing_code != '' ) {
        delay = delay +  250; setTimeout( ""+firing_code+"", delay);
        }
        next_step = step+1;
        delay = delay +  250; setTimeout( " $('#tutorial_cursor').trigger('tutorial_step" + next_step + "'); ", delay);
      }
    }
  });

}

function go_type( field_param, text_param ) {

  type_delay=75+Math.pow(10, Math.floor(Math.random()*3) );
  currentChar=1;
  $('#' + field_param).val(" ");
  refresh_watermarks();
  type( field_param, text_param );

}

function type( field_param_recur, text_param_recur ) {
  $('#' + field_param_recur ).val( text_param_recur.substr(0, currentChar));
  currentChar++;
  if (currentChar>text_param_recur.length) {
    currentChar=1;
    delete currentChar;
    return;
  } else {
    setTimeout("type( '" + field_param_recur + "', '" + text_param_recur + "')", type_delay);
  }
}
    function refresh_watermarks() {

     $.clearwatermarks();
     $.addwatermarks();

     $("#contract_number").watermark({html:'&nbsp;Codice pratica interno',cls:'watermark'});
     $("#behalf_company").watermark({html:'&nbsp;Ragione Sociale',cls:'watermark'});
     $("#behalf_roadname").watermark({html:'&nbsp;Indirizzo',cls:'watermark'});
     $("#behalf_number").watermark({html:'&nbsp;Civico',cls:'watermark'});
     $("#behalf_postcode").watermark({html:'&nbsp;CAP',cls:'watermark'});
     $("#behalf_city").watermark({html:'&nbsp;Citt&agrave;',cls:'watermark'});
     $("#behalf_province").watermark({html:'&nbsp;Prov.',cls:'watermark'});
     $("#behalf_country").watermark({html:'&nbsp;Nazione',cls:'watermark'});

     $("#value").watermark({html:'&nbsp;Valore in Euro',cls:'watermark'});
     $("#weight").watermark({html:'&nbsp;Peso lordo',cls:'watermark'});

     $("#shipping_date").watermark({html:'&nbsp;Data trasporto',cls:'watermark'});

     if( $("#route_EP_UP_type").val() == 'SEA' ) {
       $("#shipSearch").watermark({html:'&nbsp;Nome Nave',cls:'watermark'});
       $("#airwaybill").watermark({remove:true});
     } else if( $("#route_EP_UP_type").val() == 'AIR') {
       $("#airwaybill").watermark({html:'&nbsp;Airway bill',cls:'watermark'});
       $("#shipSearch").watermark({remove:true});
     } else if( $("#route_EP_UP_type").val() == 'LAND') {
       $("#airwaybill").watermark({remove:true});
       $("#shipSearch").watermark({remove:true});
     }

     $("#sourceCity").watermark({html:'&nbsp;Origine merci',cls:'watermark'});
     $("#embankmentPort").watermark({html:'&nbsp;Carico merci',cls:'watermark'});
     $("#unloadingPort").watermark({html:'&nbsp;Scarico merci',cls:'watermark'});
     $("#endDestination").watermark({html:'&nbsp;Destino merci',cls:'watermark'});
    }

    

