var dayNames = ['Domenica',
                'Luned&igrave;',
                'Marted&igrave;',
                'Mercoled&igrave;',
                'Gioved&igrave;',
                'Venerd&igrave;',
                'Sabato'];
var dayNamesShort = ['Dom','Lun','Mar','Mer','Gio','Ven','Sab'];            
var dayNamesMin = ['Do','Lu','Ma','Me','Gi','Ve','Sa'];
var monthNames = ['Gennaio','Febbraio','Marzo','Aprile','Maggio','Giugno','Luglio','Agosto','Settembre','Ottobre','Novembre','Dicembre'];
var monthNamesShort = ['Gen','Feb','Mar','Apr','Mag','Giu','Lug','Ago','Set','Ott','Nov','Dic'];
var datePicker = {
                dateFormat: 'dd-mm-yy',
                dayNames: dayNames,
                dayNamesShort: dayNamesShort,
                dayNamesMin: dayNamesMin,
                monthNames: monthNames,
                monthNamesShort: monthNamesShort,
                firstDay: 1
            };
var areaName = ["Arezzo", "Grosseto", "Perugia", "Siena", "Terni"];

Cufon.replace('h1');
Cufon.replace('h2');
Cufon.replace('h3');
Cufon.replace('h4'); 

var ie6errorMsg = "Il tuo browser &egrave; obsoleto. Scarica la versione aggiornata dal sito Microsoft " +
                    '<a href="http://www.microsoft.com/italy/windows/internet-explorer/download-ie.aspx">Download</a> ' + 
                    '<span style="padding-left:10px">Oppure passa a Firefox</span> <a href="http://www.mozilla-europe.org/it/firefox/">Download</a>'
                    ;

var errorBoxTpl =   '<div id="error-box" class="error-bar">' +
                    '<span id="error-box-close"><img alt="Close" src="/assets/img/ico-close.gif" /></span>' +
                    '<div id="error-text"></div>' +
                    '</div>';
                    


function appendError(errorText) {
    $("#error-text").append('<p>' + errorText + '</p>');
}

function showErrors() {
    
    $('body').prepend(errorBoxTpl);
    
    $('#error-box').css("display", "block");
    $('#error-box').animate({top:$(window).scrollTop()+"px" },{queue: false, duration: 350}); 
    $(window).scroll(function()
    {
      $('#error-box').animate({top:$(window).scrollTop()+"px" },{queue: false, duration: 350});
    });

    $('#error-box #error-box-close').click(function()
    {
      $('#error-box').animate({ top:"+=15px",opacity:0 }, "fast");
    });    
}

function errorIE6() {
    showErrors();
    appendError(ie6errorMsg); 
}

jQuery.AgroMenu = function(id){
    
    if (jQuery.browser.msie)
        if (parseInt(jQuery.browser.version) < 8)  
        	$(id + ' li').css('z-index','11');
    
    $(id + ' li').hover(function(e){
        
        $(this).css('background-color','#f0f0f0');
        
        var elem = $(this).find('ul:first');
        
        if (elem != null) {
            $(elem).css('z-index','10');
             
            var height = $(elem).css("height");
            
            var width = $(this).find('a:first').width();
            var padding = 12;
            
            var temp_item = ('<span class="temp_item" style="display:none; font-size: 0.70em; font-weight:bold">'+ $(elem).find('a:first').html() +'</span>');
            $(temp_item).appendTo('body');
            var newwidth = $('span.temp_item').width() + 12;
            $('span.temp_item').remove();
                      
            if (height != null)
                $(elem).css({
                    'top' :  '-' + ($(elem).height() - 5) + 'px',
                    'left' : width + 12 + 5,
                    'width' : newwidth + 'px'
                }); 
  
           $(elem).stop(true,true).fadeIn(250);           
        }
     
    },
    function(){
        $(this).css('background-color','#ffffff');
        
        $(this).find('ul:first').stop(true,true).fadeOut(150);
    });

}

jQuery.extend({
    random: function(X) {
        return Math.floor(X * (Math.random() % 1));
    },
    randomBetween: function(MinV, MaxV) {
      return MinV + jQuery.random(MaxV - MinV + 1);
    }
});

  
    
$(document).ready(function(){

    if (jQuery.browser.msie) {
        if (parseInt(jQuery.browser.version) < 7)   {
            errorIE6();
        }
    }
    
    
    $.AgroMenu(".menu-bottom-sub");
    
    

    var options = { 
    //target:        '#output1',  
 	    dataType:  'json',
 	    beforeSubmit: function(formData, jqForm, options) {
 		    $('#form-login').find('span.error').remove();
 	    },
        success: function(response, statusText)  { 

           
            
            if (response.success) {
			   $('#form-login').find(".form-login").remove();
                	        
                $.get("/agrotecnici/areariservata/1", function(data, textStatus) {
                    
                    unmask($('#form-login'));
                                        
                    setTimeout(function() {
                         
                        $('#form-login').replaceWith(data);
                        $('.riservata-box').fadeIn(200);
                        fix_icons('.riservata-box'); 
                    }, maskTime+100);

                }, "html"); 
                
                //location.reload(true);
            }

            unmask($('#form-login').find('.mask'));  
            
            
		    function error(str) {
			    return '<span class="error" style="color: red;"> (' + str + ')</span>';
		    }
		    
		    if (response.validation) {
			    if (response.validation.login)
				    $('#lbl-login').after(error("Campo richiesto"));	   
			    if (response.validation.pwd)
				    $('#lbl-password').after(error("Campo richiesto"));
		    }	
		    if (response.errors) {
			    if (response.errors.login)
				    $('#lbl-login').after(error("Utente errato"));   		
			    if (response.errors.password)
				    $('#lbl-password').after(error("Password errata"));
		    }
	    } 
 				
        // other available options: 
        //url:       url         // override for form's 'action' attribute 
        //type:      type        // 'get' or 'post', override for form's 'method' attribute 
        //dataType:  'json'       // 'xml', 'script', or 'json' (expected server response type) 
        //clearForm: true        // clear all form fields after successful submit 
        //resetForm: true        // reset the form after successful submit 
 
        // $.ajax options can be used here too, for example: 
        //timeout:   3000 
    }; 
 
    // bind form using 'ajaxForm' 
    $('#form-login').ajaxForm(options);
    
    
    $('A[rel="external"]').click( function() {
        window.open( $(this).attr('href') );
        return false;
    });         
    
});

var maskTime = 800;

function mask(container, mask) {
    $(mask).height($(container).height()+10);
    $(mask).width($(container).width());                                    
    $(mask).fadeIn(maskTime);    
}
function unmask(mask) {
    $(mask).fadeOut(maskTime);
}

function maskSubmit(form) {
    
    mask($(form), $(form).find('.mask'));
    
    setTimeout(function() { 
        $(form).submit();
    }, maskTime); 

    return false; 
}

function confirm(text, callback, attrs) {
    
    var dialog = ('<div id="dialog">'+text+'</div>'); 
 
    $(dialog).dialog({
                    autoOpen: true,
                    dialogClass: "alert",
                    modal: true,
                    show: "slide",
                    hide: "explode",
                    buttons: {
                        "Conferma": function() { 
                            $(this).dialog("close");
                            
                            $('#dialog').remove();
                            
                            if (callback != null) {
                                callback(attrs);
                            }
                             
                            return true;  
                        }, 
                        "Annulla": function() { 
                            $(this).dialog("close");

                            $('#dialog').remove();
                            return false;
                        } 
                    }
                });

    return false;

}

function test(args) {
    alert(args);
}

function messageError(msgText) {
    return message(msgText, "alert", "error");    
}

function messageInfo(msgText) {
    return message(msgText, "info", "highlight");
}

function message(msgText, icon, state) {
    
    $.tpl("message",['<div class="ui-widget msgBox" style="display:none; margin-bottom:1px">',
                            '<div class="ui-state-{state:s} ui-corner-all">',
                                '<span class="ui-icon ui-icon-{icon:s}" style="float: left; margin-right: .3em;"></span>',
                                '<a href="#" class="ui-icon ui-icon-close" style="float: right; margin-left: .3em;"></a>',
                                '{text:s}',
                            '</div>',
                        '</div>']);  
                        
    var box = $.tpl('message', {
            state: state,
            text: msgText,              
            icon: icon
        }, true);
                                                    

                
      $(box).prependTo("#content").fadeIn();
 
      $("#content").find(".msgBox a.ui-icon-close").click(function() {
          $(this).parent().parent().hide("explode",null,500,function(){
             $(this).remove();
         
          }); 
         return false;                                             
     }); 

     return false;
}

$(function(){
    $('ul.icons li, .action-icons a, a.icon').hover(
        function() { $(this).addClass('ui-state-hover'); }, 
        function() { $(this).removeClass('ui-state-hover'); }
    );
});

function fix_icons(e) {
    $(e).find('ul.icons li, .action-icons a, a.icon').hover(
        function() { $(this).addClass('ui-state-hover'); }, 
        function() { $(this).removeClass('ui-state-hover'); }
    );        
}

$(function(){
    $("a[rel^='submit']").bind("click", function(e){
        var a = $(this).attr("rel").split(";");
        
        if (a[2] != null && a[2] == "mask") {
            maskSubmit($(this).closest("form")); 
            return false;
        }
        
        if (a[1] != null && a[1] != "")
            $("#"+a[1]).submit();
        else    
            $(this).closest("form").submit();
        return false;  
    });
});


String.prototype.defaultIfEmpty=function(def) {
    return (this) ? (this == "" ? def : this) : def;
}
