 
$(document).ready(function(){
    
    var tot = 180;
  
    $('#box1').click(function () {
        checkFrase(); 
        tot = 180;
    });
    $('#box2').click(function () {
        checkFrase();
        tot = 165;
    });              
    $('#box3').click(function () {         
        checkFrase();
        tot = 112;
    });
    $('#box4').click(function () {
        checkFrase();
        tot = 180;
    });

    $('#seleziona').submit(function(e) {

      if(!$("#messaggio").val()){
	$('#rimangono').css('color','red');
	$('#rimangono').html('inserire un messaggio');
	e.preventDefault();

	return;
      }
    });

    
    function check()
    {
        var temp = true;
        
        if (!checkFrase())
            temp = false;
        if (!checkRadio())
            temp = false;
        
        if (temp){
            setSubmit(false);
        }
        else{
            setSubmit(true);
        }
    }
            
    
    function setSubmit(status)
    {
//         $("#submit").attr("disabled",status);
//         if (status)
//             $("#submit").attr("src",'/static/img/card/continua_disabled.gif');
//         else
//             $("#submit").attr("src",'/static/img/card/continua.gif');
        
    }
    
    $("#messaggio").keyup(function () {
        check();
    });
    
//     $("#messaggio").mouseout(function () {
//         check();
//     });


    $("input[name='cartolina']").click(function () {
        check();
    });

    function checkFrase()
    {
        testo = $("#messaggio").val ();
        if (testo.length > tot){
          if (!$("#msg-error").length){
                newtesto = testo.substring(0,tot)
                $("#messaggio").val (newtesto);
                //$("#rimangono").html("Frase troppo lunga");
          }
        } else {

	  $('#rimangono').css('color','green');
          $("#rimangono").html(tot - $("#messaggio").val().length +" caratteri a disposizione");
        }

        if ($("#messaggio").val() != '' && $("#messaggio").val().length <= tot)
            return true;
        else
            return false;
        
    }
    
    function checkRadio()
    {
        if ($("input[name='cartolina']").is(":checked"))
            return true;
        else
            return false;
        
    }
    
});