$().ready(function() {

  if($('#commenti_form').size() > 0) {
     $("#commenti_form").validate({
       invalidHandler: function(form, validator) {
          var errors = validator.numberOfInvalids();
          if (errors) {
            $("div#error_container").show();
          } else {
            $("div#error_container").hide();
          }
        },
        onfocusout: false,
        onkeyup: false,
        onclick:false,
        meta: "validate",
        errorClass: "invalid",
        errorPlacement: function(error, element) {
          $labelToAppendTo = $('label[for='+element[0].id+']');
          error.appendTo($("div#error_container")).clone().appendTo($labelToAppendTo);
          $('<br />').appendTo($("div#error_container"));
        }
     });
  }
  if($('.lightbox, .lightbox_inside').size() > 0) {
    $('.lightbox, .lightbox_inside').lightBox({
      imageLoading:			main_host+'images/lightbox/lightbox-ico-loading.gif',		// (string) Path and the name of the loading icon
      imageBtnPrev:			main_host+'images/lightbox/lightbox-btn-prev.gif',			// (string) Path and the name of the prev button image
      imageBtnNext:			main_host+'images/lightbox/lightbox-btn-next.gif',			// (string) Path and the name of the next button image
      imageBtnClose:		main_host+'images/lightbox/lightbox-btn-close.gif',		// (string) Path and the name of the close btn
      imageBlank:				main_host+'images/lightbox/lightbox-blank.gif'			// (string) Path and the name of a blank image (one pixel)
      });
  }

  $('.youtubevideo').bind('click', function() {
    url = $(this).attr('href');
    title = $(this).attr('title');
    code_pieces = url.split('=');
    code = code_pieces[1];
    showvideo(title, '&nbsp;');
    var params = { allowScriptAccess: "always" };
    var atts = { id: "youtubeplayer" };
    video_code = $('td:eq(1)', $(this).parent()).html();
    swfobject.embedSWF('http://www.youtube.com/v/'+code+'&enablejsapi=1&playerapiid=ytplayer',
                       "youtubeplayer", "425", "364", "8", null, null, params, atts);
    return false;
  });




  $container_immagini = $('.container_immagini');


  if($container_immagini.size() > 0) {

    $scroller = $('#scroller');
    thumb_height = $('.container_immagini #immagini img:first').height();
    thumb_width = $('.container_immagini #immagini img:first').width();
    var passo = thumb_width*2;
    numero_immagini = $('.container_immagini #immagini img').size();
    lunghezza_contenitore = ((5+thumb_width)*numero_immagini)-5;

    $container_immagini.css({'height':thumb_height+'px'});
    if(lunghezza_contenitore <= ($container_immagini.width()-66)) {
      scroller_width = $container_immagini.width()-66;
    } else {
      $('#prev_img, #next_img').css({'display':'block'});
      scroller_width = $container_immagini.width()-66;
      $('#immagini').css({'position':'relative', 'width':lunghezza_contenitore+'px'});
      /*
      $('#prev_img img').css({'position':'relative', 'top':((thumb_height/2)-8)+'px', 'display':'block', 'left':(($('#prev_img').width()/2)-8)+'px'});
      $('#next_img img').css({'position':'relative', 'top':((thumb_height/2)-8)+'px', 'display':'block', 'left':(($('#next_img').width()/2)-8)+'px'});
      */
      $('#prev_img img').css({'position':'relative', 'top':((thumb_height/2)-8)+'px', 'display':'block', 'left':(($('#prev_img').width()/2)-12)+'px'});
      $('#next_img img').css({'position':'relative', 'top':((thumb_height/2)-8)+'px', 'display':'block', 'left':(($('#next_img').width()/2)-12)+'px'});
      $('#prev_img, #next_img').css({'cursor':'pointer', 'height': thumb_height+'px', 'width':'28px', 'border':'1px solid #fff'});

      $('#prev_img').bind('click', function() {
        posizione_attuale = parseInt($('#immagini').css('left').replace('px', ''));
        log(posizione_attuale);
        if(posizione_attuale == 0 || (-1*posizione_attuale) < passo) {
          new_pos = 0;
        } else {
          new_pos = posizione_attuale + passo;
        }
        $('#immagini').animate({
            left: new_pos+'px'
        }, 500, 'swing' );
      });

      $('#next_img').bind('click', function() {
        max_left = -1*(lunghezza_contenitore - scroller_width);
        posizione_attuale = parseInt($('#immagini').css('left').replace('px', ''));
        log('Posizione attuale :'+posizione_attuale);
        if(posizione_attuale == max_left || (posizione_attuale-passo) <= max_left) {
          new_pos = max_left;
        } else {
          new_pos = posizione_attuale - passo;
        }


        $('#immagini').animate({
            left: new_pos+'px'
        }, 500 , 'swing');

      });

    }

    $scroller.css({'position':'relative',
                   'width':scroller_width+'px',
                   'height':thumb_height,
                   'overflow':'hidden'});


  }

  $container = $('.container_docs');

  if($container.size() > 0) {

    $scroller = $('#scroller_docs');
    thumb_docs_height = $('.container_docs #docs img:first').height();
    thumb_docs_width = $('.container_docs #docs img:first').width();
    var passo_docs = thumb_docs_width*2;
    numero_immagini = $('.container_docs #docs img').size();
    lunghezza_contenitore_docs = ((5+thumb_docs_width)*numero_immagini)-5;

    $container.css({'height':thumb_docs_height+'px'});
    if(lunghezza_contenitore_docs <= ($container.width()-66)) {
      scroller_docs_width = $container.width()-66;
    } else {
      $('#prev_doc, #next_doc').css({'display':'block'});
      scroller_docs_width = $container.width()-66;
      $('#docs').css({'position':'relative', 'width':lunghezza_contenitore_docs+'px'});

      $('#prev_doc img').css({'position':'relative', 'top':((thumb_docs_height/2)-8)+'px', 'display':'block', 'left':(($('#prev_doc').width()/2)-12)+'px'});
      $('#next_doc img').css({'position':'relative', 'top':((thumb_docs_height/2)-8)+'px', 'display':'block', 'left':(($('#next_doc').width()/2)-12)+'px'});
      $('#prev_doc, #next_doc').css({'cursor':'pointer', 'height': thumb_docs_height+'px', 'width':'28px', 'border':'1px solid #fff'});

      $('#prev_doc').bind('click', function() {
        posizione_attuale = parseInt($('#docs').css('left').replace('px', ''));
        log(posizione_attuale);
        if(posizione_attuale == 0 || (-1*posizione_attuale) < passo_docs) {
          new_pos = 0;
        } else {
          new_pos = posizione_attuale + passo_docs;
        }
        $('#docs').animate({
            left: new_pos+'px'
        }, 500, 'swing' );
      });

      $('#next_doc').bind('click', function() {
        max_left = -1*(lunghezza_contenitore_docs - scroller_width);
        posizione_attuale = parseInt($('#docs').css('left').replace('px', ''));
        log('Posizione attuale :'+posizione_attuale);
        if(posizione_attuale == max_left || (posizione_attuale-passo) <= max_left) {
          new_pos = max_left;
        } else {
          new_pos = posizione_attuale - passo_docs;
        }
        $('#docs').animate({
            left: new_pos+'px'
        }, 500 , 'swing');
      });

    }

    $scroller.css({'position':'relative',
                   'width':scroller_docs_width+'px',
                   'height':thumb_docs_height,
                   'overflow':'hidden'});
  }

  $containerv = $('.container_video');

  if($containerv.size() > 0) {

    $scroller = $('#scroller_video');
    thumb_video_height = $('.container_video #videos img:first').height();
    thumb_video_width = $('.container_video #videos img:first').width();
    var passo_video = thumb_video_width*2;
    numero_immagini = $('.container_video #videos img').size();
    lunghezza_contenitore_video = ((5+thumb_video_width)*numero_immagini)-5;

    $containerv.css({'height':thumb_video_height+'px'});
    if(lunghezza_contenitore_video <= ($containerv.width()-66)) {
      scroller_video_width = $containerv.width()-66;
    } else {
      $('#prev_doc, #next_doc').css({'display':'block'});
      scroller_video_width = $containerv.width()-66;
      $('#videos').css({'position':'relative', 'width':lunghezza_contenitore_video+'px'});


      $('#prev_video img').css({'position':'relative', 'top':((thumb_video_height/2)-8)+'px', 'display':'block', 'left':(($('#prev_video').width()/2)-12)+'px'});
      $('#next_video img').css({'position':'relative', 'top':((thumb_video_height/2)-8)+'px', 'display':'block', 'left':(($('#next_video').width()/2)-12)+'px'});
      $('#prev_video, #next_video').css({'cursor':'pointer', 'height': thumb_video_height+'px', 'width':'28px', 'border':'1px solid #fff'});

      $('#prev_video').bind('click', function() {
        posizione_attuale = parseInt($('#videos').css('left').replace('px', ''));
        log(posizione_attuale);
        if(posizione_attuale == 0 || (-1*posizione_attuale) < passo_video) {
          new_pos = 0;
        } else {
          new_pos = posizione_attuale + passo_video;
        }
        $('#videos').animate({
            left: new_pos+'px'
        }, 500, 'swing' );
      });

      $('#next_video').bind('click', function() {
        max_left = -1*(lunghezza_contenitore_video - scroller_video_width);
        posizione_attuale = parseInt($('#docs').css('left').replace('px', ''));
        log('Posizione attuale :'+posizione_attuale);
        if(posizione_attuale == max_left || (posizione_attuale-passo) <= max_left) {
          new_pos = max_left;
        } else {
          new_pos = posizione_attuale - passo_docs;
        }
        $('#videos').animate({
            left: new_pos+'px'
        }, 500 , 'swing');
      });

    }

    $scroller.css({'position':'relative',
                   'width':scroller_video_width+'px',
                   'height':thumb_video_height,
                   'overflow':'hidden'});


  }

  if($('pre').size() > 0) {
    found = false;
    re = new RegExp('^syntax');
    $('pre').each(function() {
      nomeClasse = $(this).attr('class');
      if(nomeClasse.match(re)) {
        found = true;
      }
    });
    if(found) {
      dp.SyntaxHighlighter.ClipboardSwf = 'lib/syntaxhighlight/clipboard.swf';
      dp.SyntaxHighlighter.HighlightAll();
    }
  }

  if($('#recaptcha_div').size() > 0) {
    Recaptcha.create($('#recaptcha_code').val(),
    "recaptcha_div", {
       theme: "custom"
    });
  }

  if($.trim($('#wrongfields').val()) != '') {
    wrong_fields = eval("(" + $('#wrongfields').val()+ ")");
    for(var i = 0; i < wrong_fields.length; i++) {
      $('#'+wrong_fields[i]).addClass('error');
    }
  }


  // gestione commenti

  $('.switch_vis_commento').bind('click', function() {
    id = $(this).parent().attr('id').replace('commento', '');
	  data = 'cmd=NEWS.SWITCHVISIBILITYCOMMENTO&id='+id;
	  $.ajax({
	    type: "POST",
	    url: main_host+"ajax.php",
	    data: data,
	    dataType: "json",
	    success: function(returned_data) { if(parseInt(returned_data.result) == 1) {
	                                         location.href = location.href;
	                                       } else {
	                                       }
	                                     }
	  });

  });

  $('.cancella_commento').bind('click', function() {
    id = $(this).parent().attr('id').replace('commento', '');
	  data = 'cmd=NEWS.DELETECOMMENTO&id='+id;
	  $.ajax({
	    type: "POST",
	    url: main_host+"ajax.php",
	    data: data,
	    dataType: "json",
	    success: function(returned_data) { if(parseInt(returned_data.result) == 1) {
	                                         $('#commento'+id).parent().slideUp('slow').remove();
	                                       } else {
	                                       }
	                                     }
	  });

  });

  $('.edit_commento').bind('click', function() {
    if($('#edit_commento').size() > 0) {
      $('#edit_commento').parent().html($('#mem_commento').html());
    }


    id = $(this).parent().attr('id').replace('commento', '');
    $commento = $('.commento', $(this).parent().parent());

    commento = $.trim($commento.html());

    frm = '<span id="mem_commento" style="display:none">'+commento+'</span>';
    frm += '<form name="edit_commento" id="edit_commento" method="post" action="'+main_host+'ajax.php">';
    frm += '<input type="hidden" name="cmd" value="NEWS.SAVEPCOMMENTO" />';
    frm += '<input type="hidden" id="id_commento" name="id" value="'+id+'" />';
    frm += '<textarea name="commento" id="commento_textarea">'+commento+'</textarea><br />';
    frm += '<input type="submit" value="'+getLang('base', 'SALVA')+'" />';
    frm += '<input type="button" id="cancel_edit" value="'+getLang('base', 'CANCEL')+'" />';
    frm += '</form>';

    $commento.html(frm);

    $('#cancel_edit').bind('click', function() {
      $commento.html($('#mem_commento').html());
    });

    $('#edit_commento').ajaxForm({
      success: function(ret_data) {
        $commento.html(ret_data.commento);
      },
      dataType: 'json'
    });

  });

});


function showvideo(title, contenuto) {
  $('<div id="youtubeplayer">&nbsp;</div>').dialog({
    title: title,
    modal : true,
    overlay: {
      backgroundColor: '#000',
      opacity: 0.5
    },
    width:'425px',
    height:'388px',
    close:function() {
      $(this).dialog('destroy').remove();
    }
  });

}

var ytplayer;
function onYouTubePlayerReady(playerId) {
  ytplayer = document.getElementById("youtubeplayer");
  playVideo();
}
function playVideo() {
  ytplayer.playVideo();
}

