

var notesEnabled = false;

jQuery.fn.load = function(fn){
  return fn ?
    this.is('img') ?
      this.bind('load readystatechange', function(e){
        if( this.complete || (this.readyState == 'complete' && e.type
== 'readystatechange') )
          fn();
        })
    : this.bind('load', fn)
  : this.trigger('load');

}; 


   //    these scripts are licensed under
   //    Creative Commons Attribuzione-Condividi allo stesso modo 2.5 Italia License
   //    http://creativecommons.org/licenses/by-sa/2.5/it/

var inArray = function(str, arr){
  if(!(typeof str === "undefined") && !(typeof arr === "undefined"))
    if(arr.length > 0)
      for(var i in arr)
        if(arr[i] == str)
          return i;
  return false;
};


var spacer_img = "/spacer.gif";
var chSeq = 0;
var gallery={};

var $ = jQuery;


  var gallery = {
    enabled: false,
    active: 0,
    container: "",
    list: [],
    get: function(data){
// $.log(data);
// $.log((typeof gallery.list[gallery.active][data]));
// $.log(gallery.list[gallery.active][data]);
//       if( ! (typeof gallery.list[gallery.active][data] === 'undefined' ))
	return gallery.list[gallery.active][data];
//       else
// 	$.log(data);
    },
    goto: function(i){

      this.active += i;
      if(i==-1 && $(".gallery a:first").attr("href") == $(gallery.container + " img").attr("src") ){
        // prima, vai all'ultima
        this.active = ( $(".gallery a").size() - 1);
      }
      if(i==1 && $(".gallery a:last").attr("href") == $(gallery.container + " img").attr("src") ){
        // ultima, vai alla prima
        this.active = 0;
      }

      if($(gallery.container).children("img").size())
	$(gallery.container).children("img").remove();
      imgSrc = $(".gallery a").eq( this.active ).attr("href");

//       alert(imgSrc);

//       console.log(gallery.get("nid"));

      
      var notes = new iNotes({ notes: annotations[ gallery.get("nid") ], i: i });

      noteEditor.clear();
      if(notes)
        notes.clearAll();

      var maxH = 500;
      $(gallery.container).height(maxH).append("<div class='loading'>&nbsp;</div>")
	.find(".loading").height( $(gallery.container).height() );
	
      $(gallery.container).image(imgSrc, function(){
	    propH = parseInt($(gallery.container).children("img").height() * $(".gallery-slide").width()/$(gallery.container).children("img").width());

// 	    alert(imgSrc);

	    var $foto = $(gallery.container).children("img");

	    if($foto.width() > $foto.height()){
	      $foto.width('100%').height('100%');
	    }
// 	    else
// 	      $foto.width('100%').height('100%');

	    $foto.hide()
// 	      .width("100%")
// 	      .height("100%")
	    .fadeIn(100, function(){
	      notes.place();

// 	      $(gallery.container).height((propH <= maxH)? propH : maxH);
	      $(".loading").remove();
	      if(noteEditor.enable){
		noteEditor.click_editor();
	      }
	      else{
		notes.bind_notes();
	      }
	    });
      });// img preloader
    }//goto
  };



iNotes = function(settings){

  var def={
    i: 0,
    notes : {},
    id : "",
    containment : ".gallery-slide"
  };


  this.iNotes = $.extend( def , settings );

  this.place = function(){

    if(!notesEnabled) return;

    if(this.iNotes.notes.length < 1)
      return false;

      var post_id = gallery.get("nid");
      if($(".note-" + post_id).size())
        $(".note-" + post_id).remove();

      for(var i in this.iNotes.notes){
        var css = {
            position: "absolute",
            opacity: 0.4,
            width: this.iNotes.notes[i].width,
            height: this.iNotes.notes[i].height,
            top: this.iNotes.notes[i].top,
            left: this.iNotes.notes[i].left
        };

	noteFiller = "<img src='"+(spacer_img)+"' width='"+(this.iNotes.notes[i].width)+"' height='"+(this.iNotes.notes[i].height)+"'>";

        classes = ( "note-" + post_id ) + " notes";
        if(noteEditor.enabled)
          classes += " editable";

        var noteCssId = $(this.iNotes.containment).createContentHelper({ setClass: classes });
        $(noteCssId).attr("rel", ("" + this.iNotes.notes[i].noteIndex)).html(
	  ((noteEditor.enabled)? this.iNotes.notes[i].noteIndex : noteFiller)
	).css(css);//this.iNotes.notes[i].note
      }// for
    };
  this.clear = function(){
    $(".note-" + gallery.get("nid")).remove();
  };
  this.clearAll = function(){
    $(".notes").remove();
  };
  this.bind_notes = function(){
  	  $(".notes")
	  .hover(function(){
// 	    alert("on");
	    var noteContent = "#photonotes_" + gallery.get("nid") + "_"+$(this).attr("rel");
	    var currNote = annotations[gallery.get("nid")][$(this).attr("rel")];
	    $(noteContent).addClass("note-content").css({
	      top: ($(".gallery-slide").offset().top + currNote.top + currNote.height + 5),
	      left: ($(".gallery-slide").offset().left + currNote.left),
	      zIndex: 120
	    }).fadeIn();
	  },function(){
	    $("#photonotes_" + gallery.get("nid") + "_"+$(this).attr("rel")).hide();
	  })
	  .click(function(){
		var noteContent = "#photonotes_" + gallery.get("nid") + "_" + $(this).attr("rel");
		try{
		  if($(noteContent).find("div.linkTo").text())
		    document.location = $(noteContent).find("div.linkTo").text() + "#media-"+ annotations[gallery.get("nid")][$(this).attr("rel")].note;
		}catch(e){ $.log("Oops! " + e.toString());}
		return false;
	  });
  };
};


var noteEditor = {
  enabled: false,
  i: 0,
  id: "",
  note: {},
  start: function(id){
    this.id = "#" + id;
    this.i = ($(this.id).attr("rel") * 1);
    this.note = annotations[($(".gallery span.nid").eq( gallery.active ).text())][this.i];
    if(!($(this.id).hasClass("editing"))){
      this.clear();
//         $(".editing").resizable( "disable" );
//        this.clear();
      this.editElement();
    }
  },
  clear: function(){
    if($(".editing").size()){
      $(".note-options").remove();
      $(".editing").resizable("destroy").draggable("destroy").unbind();
      noteEditor.click_editor();
      $(".editing").removeClass("editing");
    }
  },
  editElement: function(){
//     var chGal2 = $(".gallery-slide").createContentHelper({ tagName:"div", css: {top: this.note.top, left: this.note.left, width:this.note.width, height:this.note.height } });
    if(typeof this.note === "undefined")
      return false;

    var editableNote = $(this.id).css({top: this.note.top, left: this.note.left, width:this.note.width, height:this.note.height }).addClass("editing");
    
    $(editableNote).resizable({
      containment: $(".gallery-slide"),
      //proxy: 'proxy',
      //ghost: true,
//       animate:true,
      handles: 'all',
      knobHandles: true,
      //transparent: true,
      //aspectRatio: true,
      autohide: true,
      minWidth: 10,
      minHeight: 10,
      resize: function(e, ui) {
        $(".note-options").remove();
      },
      stop: function(e, ui) {
        noteEditor.save();
      }
    })
    .draggable({
      cursor: 'move',
      containment: $(".gallery-slide"),
      drag: function(e, ui) {
       $(".note-options").remove();
      },
      stop: function(e, ui) {
         noteEditor.save();
      }
    });
  },
  save: function(){
    var coords = {
      top: ($(".editing").offset().top - $(".gallery-slide").offset().top),
      left:($(".editing").offset().left - $(".gallery-slide").offset().left),
      width:$(this.id).width(),
      height:$(this.id).height()
    }
    var noteData = {
      id: ($(".gallery span.nid").eq( gallery.active ).text()),
      noteIndex: (this.i),
      note:this.note.note,
      op: "save"
    };
    new_note = $.extend(noteData, coords);
    annotations[($(".gallery span.nid").eq( gallery.active ).text())][this.i] = new_note;
    $.post(base_url, new_note);
  },
  click_editor: function(){
    $(".notes").click(function(e){
      $(".gallery-current-image").children("img").click(function(){  noteEditor.clear();  });
      
      noteEditor.start($(this).attr("id"));
      if($(".note-options").size())
	chId = $(".note-options").attr("id");
      else
	chId = $(".gallery-slide").createContentHelper({ setClass: "note-options"});

      if($(".editing").size()){
	$(chId).attr("rel", $(this).attr("rel")).css({
	  position: "absolute", backgroundColor:"green",color: "white", opacity:0.8,
	  top: ($(".editing").offset().top - $(".gallery-slide").offset().top + $(".editing").height()),
	  left:($(".editing").offset().left - $(".gallery-slide").offset().left)
	});
	if($(chId).attr("rel") != $(this).attr("rel") || !$(chId).html().length ){
	  var def = {op: "list"};
	  $(chId).load(base_url, $.extend(def, noteEditor.note), function(){
      // delete item
	  $(".note-options").append("<br /><a href='#' class='delete-note'>X Elimina</a>");
	  $(".delete-note").click(function(){
	    if(confirm("Eliminare la nota ?")){
	      var post_id = $(".gallery span.nid").eq( gallery.active ).text();
	      var I = $(".editing").attr("rel");
	      var opDel = { op: "delete", id: post_id, noteIndex: I  };
	      $.post(base_url, opDel);
	      noteEditor.clear();
	      $(".editable[rel="+I.toString()+"]").remove();

	      var old_annotations = annotations[post_id];
	      var c_notes = jQuery.makeArray( $(".notes.editable"));
	      annotations[post_id] = new Array();
	      var i=0;
	      while( (c_note = c_notes.shift()) ){
		old_annotations[$(c_note).attr("rel")].noteIndex = i;
		annotations[post_id][i] = old_annotations[$(c_note).attr("rel")];
		i++;
	      }
	      gallery.goto(0);
	    }
	    return false;
	  });
      // ! delete item
	  if($("#note-options-select").size())
	    $("#note-options-select").change(function(){
	      var post_id = $(".gallery span.nid").eq( gallery.active ).text();
	      nextI = ($(".note-"+ post_id).size());
	      annotations[post_id][noteEditor.i].note = $(this).find("option").eq(this.selectedIndex).val();
	      if(!annotations[post_id][noteEditor.i].note){
		annotations[post_id][noteEditor.i].note = 'undefined';
	      }
	      noteEditor.save();
	    });
	  }); 
	}
      }
      return this;
    });
  }
};


var is_null = function(v){
  if(typeof v === 'undefined')
    return true;
  return true;
}

/*
// menu
var menu = {
  curr: 0,
  lock: 0,
  start:function(){
    submenu = $.makeArray($("#menu ul:visible li"));
    for(var v in submenu){
      if($(submenu[v]).parent().parent().attr("id") == "menu")
        $(submenu[v]).attr("rel",v).addClass("menu-container").find("ul").addClass("down").attr("rel",v);
    }
    
    $("#logo").hide();
    $("#menu ul li.menu-container > ul").hide();
    $("#menu ul li.menu-container").hover(
      function(){ 
        menu.curr = this; menu.open();
      },
      function(){ 
        menu.curr = 0; menu.close();
      }
    );
    
//     toggleLogo = 
//     $("#menu").hover(function(){
//       $("#logo").css({ zIndex: 16}).show(600);
//     }, function(){
//        $("#logo").queue(function () {
//           $("#logo").dequeue();
//        });
//       $("#logo").animate({opacity: 1}, 500, function(){
// //         toggleLogo();
//         $(this).hide();
//       });
//     });


  },
  open: function(){

    if(this.lock)
      this.closeAll();
    curr = this.curr;


    $(curr).children(".down").addClass("open").css({
      top: ($(curr).parent().parent().offset().top + $(curr).parent().parent().height() + 1), // 1 border
      left: ($(curr).offset().left -25) } // 25 padding-left
    ).show();
  },
  close: function(exceptCurr){
    $.map($.makeArray($("#menu ul li.menu-container > ul")), function(v){
      $(v).removeClass("open").hide();
      $(this).queue(function(){ return;	})
      this.lock=0;
     });
  }
};*/


jQuery.log = function(message) {
  if(window.console) {
     console.debug(message);
  } else {
     alert(message);
  }
};

jQuery.fn.image = function(imSrc, f){
// 	$("<p>caricamento di " + imgSrc +"</p>").appendTo(".entry");
  return this.each(function(){
  
    var imLoader = new Image();
    $(imLoader).attr("src", imSrc);
    elm = this;

    var fxIm = function(e){
//     alert(imSrc);
//  $("<p> -- OK</p>").appendTo(".entry");

      if( ! $.browser.msie ){ // IE7 non gestisce bene le immagini
	$(this).removeAttr("width")
	      .removeAttr("height");
	$(this).width( this.width ).height( this.height );
      }
      
      $(elm).append(imLoader);
      f();
    };
    
 /*if( $.browser.msie ){
      $(this).append(imLoader);
      f();
 }else*/
    $(imLoader).bind("load readystatechange", fxIm);
}); 
}; 


// createContentHelper
$.fn.createContentHelper = function(eopts){

  var chName = "#contentHelper";
  var i = 0;
  var chId = chName + "-" + chSeq.toString();
  chSeq  = chSeq  +1;
  var defaults = {
      tagName: "div",
      setClass: " ",
      css: {},
      reusable: true,
      putOp: "append"
    }
  var opts = $.extend(defaults, eopts);
  html = "<"+(opts.tagName)
+" id='"+(chId.substr(1))
+"' class='ch-content"
+(opts.setClass ? (" "+ (opts.setClass)) : "" ) +"'></"
+(opts.tagName)+">";

  $(this)[(opts.putOp)](html).find(chId.substr(1)).css( opts.css );

  return chId;
}; // createContentHelper


jQuery.fn.rounded_corners = function(){
    return this.each(function() {
        $(this).css({position: 'relative'});
        
        $('<span class="cnrs cnr_nw"></span><span class="cnrs cnr_ne"></span><span class="cnrs cnr_sw"></span><span class="cnrs cnr_se"></span>')
            .css({ // this will only accept numeric border widths
                 marginTop:         '-' + (parseInt($(this).css('border-top-width'))    || 0),
                 marginRight:     '-' + (parseInt($(this).css('border-right-width'))    || 0),
                 marginBottom:     '-' + (parseInt($(this).css('border-bottom-width'))    || 0),
                 marginLeft:     '-' + (parseInt($(this).css('border-left-width'))    || 0)
             })
             .appendTo(this);

        // ie odd values bug fix
        if( $.browser.msie && $.browser.version < 7) {
            $(this).each(function()
            {    
                var h = $(this).height();
                var w = $(this).width();
                
                if(h%2)
                { 
                    $('.cnr_sw', this).css({bottom: '-1px'});
                    $('.cnr_se', this).css({bottom: '-1px'}); 
                }
                
                if(w%2)
                { 
                    $('.cnr_ne', this).css({right: '-1px'});
                    $('.cnr_se', this).css({right: '-1px'}); 
                }
            });
        }
    });
}//rounded_corners


jQuery(function($){

  // init menu
//   menu.start();


  // slide view
  if(typeof enableGallery === "undefined")
    enableGallery = false;

  gallery.enabled = enableGallery;

  if(typeof canEdit === "undefined")
    canEdit = false;

  noteEditor.enabled = canEdit;

  if(gallery.enabled){

    var chGal = $(".gallery-slide").createContentHelper({ tagName: "div", css: {width: ($("#content").width() - 10)}, reusable: false, setClass: "gallery-current-image" });

    gallery.container = chGal;

    if($(".gallery").size()){

      $(".gallery").hide();

      $(".gallery a img").each(function(){
	gallery.list.push({
	"nid": $(this).parent().prev("span.nid").text() ,
	"src": $(this).parent().attr("href") //,
  //       "title": $(this).parent().attr("alt"),
  //       "description":$(this).parent().prev().text(),
	});
      });

	gallery.goto(0);
	// posizionamento gallery-nav
	var galleryNav = $(".gallery-slide").createContentHelper({ putOp: "after",setClass: "gallery-nav" });
	$(galleryNav).css({  zIndex: 10, position:"relative", 
// 	  left: (parseInt(($(".gallery-slide").width() / 2 - ($(galleryNav).width() / 2)) ) + 10),
	  top: "-10px"
	}).html("<span>&nbsp;</span><span>&nbsp;</span>").show();
    
      //   prev next
      $(".gallery-nav span:first-child")
	.click(function(){        return gallery.goto(-1);    });
      $(".gallery-nav span:last-child")
	.click(function(){        return gallery.goto(1);    });
      $(gallery.container)
	.click(function(){   if(!canEdit) return gallery.goto(1);    });

      function bind_keyboard_events(e){
	  gonext = [ 34, 39, 40 ]; // pggiu giu destra 
	  goprev = [ 33, 37, 38 ]; // pgsu su sinistra
	  gohere = false;
	  if(inArray((e.which || e.keyCode), gonext) != false)
	    gohere = 1;
	  if(inArray((e.which || e.keyCode), goprev) != false)
	    gohere = -1;
	  if(gohere != false){
	    gallery.goto(gohere);
	    return false;
	  }
	    return true;
      }

	$(document).keypress(bind_keyboard_events);
    }

      if(noteEditor.enable = canEdit){
	var addNewFx=function(){
	  post_id = $(".gallery span.nid").eq( gallery.active ).text();
	  nextI = ($(".note-"+ post_id).size());
      //       if(is_null(annotations[post_id]))
      // 	annotations[post_id] = new Array();
	  annotations[post_id].push({top: 20, left:20, width: 100, height: 50, id: post_id, noteIndex: nextI });
	  // refresh
	  gallery.goto(0);
	  noteEditor.click_editor();
	};
      // add a note
      //     var editLink = $(".gallery-slide").createContentHelper({ setClass: "add-new-note-link" });
      //     $(editLink).html("<a href='javascript:;'>Aggiungi nota</a>").children("a").click(addNewFx); // click add nota
	  $(gallery.container).dblclick(addNewFx);
    }// noteEditor.enable
    
  }// gallery.enabled



 var fpp = $('body.front #body .post');

  if(fpp.size()){

    fpp.hide().eq(0).show();

    var maxH=0;
    fpp.each(function(i){
      var h = $(this).height();
      if(h > maxH)
        maxH = h;
    });

    fpp.height( maxH );
    
    var o = [];
    for(var i=0; i<fpp.size(); i++){
      
      o.push( [ '<div class="home-nav-item"><a href="javascript:void(0);" class="rounded" rel="',i,'">',(i+1),'</a></div>' ].join('') );
      
    }

    if(o.length > 1){

      $('#body').append("<div id='home-nav'>" + o.join('') + "</div>").find('a').click(function(){
        if( fpp.eq( $(this).attr('rel') ).size() )
          fpp.hide().eq( $(this).attr('rel') ).fadeIn( 400 );
        return false;
      });

    }
    
  }


}); // ready fx

// });


