/*
 * brocardi.it
 */

function thdebug(message) {
  var debug = false;
  if ((typeof(console) != "undefined") && console && debug)
    console.log(message);
}
function wopen(url, name, w, h)
{
  var wleft = (screen.width - w) / 2;
  var wtop = (screen.height - h) / 2;
  // IE5 and other old browsers might allow a window that is
  // partially offscreen or wider than the screen. Fix that.
  // (Newer browsers fix this for us, but let's be thorough.)
  if (wleft < 0) {
    w = screen.width;
    wleft = 0;
  }
  if (wtop < 0) {
    h = screen.height;
    wtop = 0;
  }

  var win = window.open(url,
    name,
    'width=' + w + ', height=' + h + ', ' +
    'left=' + wleft + ', top=' + wtop + ', ' +
    'location=no, menubar=no, ' +
    'status=no, toolbar=no, scrollbars=no, resizable=no');
  return win;

  /*var win = window.open(url,
    name,
    'width=' + w + ', height=' + h + ', ' +
    'left=' + wleft + ', top=' + wtop + ', ' +
    'location=no, menubar=no, ' +
    'status=no, toolbar=no, scrollbars=no, resizable=no');
   Just in case width and height are ignored
  win.resizeTo(w, h);
   Just in case left and top are ignored
  win.moveTo(wleft, wtop);
  win.focus();*/
}


$(function() {
      var bundle_busyWorking = false;
      var bundle_nextQueued = null;
      var bundle_nextQueuedRef = null;
      var bundle_cache = new Array;
      var bundle_timer = null;

  function hidePopup() {
    var $popup = $("#g_bundles_popup");
    if (!$popup.hasClass("popupHover")) {
      $popup.hide();
      $("#g_navbar li a").removeClass("active");
    } 
    
    if (bundle_timer) {
      window.clearTimeout(bundle_timer);
      bundle_timer = null;
    }
  }

  function loadCodice(codice) {
    // hide the screen
    $("#g_bundles_popup div,#g_bundles_popup img").hide();

    $("#cod_" + codice).show();
  }

  function loadBundle(bundle, ref) {
    if (bundle_busyWorking) {
      bundle_nextQueued = bundle;
      bundle_nextQueuedRef = ref;
      return;
    }

    // whatever happens from now on, we are going to hide the screen
    $("#g_bundles_popup div,#g_bundles_popup img").hide();

    if (bundle_cache[bundle]) {
      if (typeof(bundle_cache[bundle]) == "string")
        $("#g_bundles_popup").hide();
      else
        $(bundle_cache[bundle]).show();
      return;
    }

    // lock the ajax mutex
    bundle_busyWorking = true;

    // show the preloading image
    $("#g_bundles_popup img").show();

    $.getJSON("/ws.php?action=bundle:get_tags:" + bundle, function(data) {
      // unlock the ajax mutex (we are done with this request)
      bundle_busyWorking = false;
      var rdiv = "empty";

      if (data.items.length > 0) {
        // render the element
        var html = "<h3 class=\"hidden\">" + bundle + "</h3>\n";
        html += "<ul>\n";
        for (var i = 0; i < data.items.length; i++) {
          html += "<li><a href=\"/tag/" +
                  data.items[i].replace(/_/g, "-") + "/\">" +
                  data.items[i].replace(/_/g, " ") +
                  "</a></li>\n";
        }
        html += "</ul>\n";
        rdiv = document.createElement("div");
        $(rdiv).html(html).css("display", "none");
        $("#g_bundles_popup").append(rdiv);
      }

      // now, if we already have another request waiting,
      // don't even show the previous result and proceed
      bundle_cache[bundle] = rdiv;
      if (typeof(rdiv) == "string")
        $(ref).addClass("single");
      if (bundle_nextQueued) {
        var runParam1 = bundle_nextQueued;
        var runParam2 = bundle_nextQueuedRef;
        bundle_nextQueued = null;
        bundle_nextQueuedRef = null;
        loadBundle(runParam1, runParam2);
      }
      else {
        // otherwise just show the content
        $("#g_bundles_popup img").hide();
        if (typeof(rdiv) == "string") {
          $("#g_bundles_popup").hide();
        }
        else
          $(rdiv).fadeIn("fast");
      }
    });
  }

  $("#g_fonti li a")
    .mouseover(function(e) {
      if (bundle_timer) {
        window.clearTimeout(bundle_timer);
        bundle_timer = null;
      }

      thdebug("Position: ");
      var pos = $(this).offset();
      var cod = $(this).attr("id");
      thdebug("Codice: " + cod);
      $("#g_navbar li a").removeClass("active");
      $(this).addClass("active");
      $("#g_bundles_popup").css("top", pos.top)
                           .css("left", 149)
                           .show();

      loadCodice(cod);
    })
    .mouseout(function() {
      thdebug("Mouse out from fonti");
      // start a timer that will eventually delete the popup
      if (!bundle_timer)
        bundle_timer = window.setTimeout(hidePopup, 500);
    });

  $("#g_argomenti li a")
    .mouseover(function(e) {
      if (bundle_timer) {
        window.clearTimeout(bundle_timer);
        bundle_timer = null;
      }

      thdebug("Position: ");
      var pos = $(this).offset();
      var bundle = $(this).attr("href").replace(/\/tag\/|\//g, "").replace(/-/g, "_");
      $("#g_navbar li a").removeClass("active");
      $(this).addClass("active");
      $("#g_bundles_popup").css("top", pos.top)
                           .css("left", 149)
                           .show();

      loadBundle(bundle, this);
    })
    .mouseout(function() {
      thdebug("Mouse out from argomenti");
      // start a timer that will eventually delete the popup
      if (!bundle_timer)
        bundle_timer = window.setTimeout(hidePopup, 500);
    });
//     .click(function() { return false; });

  $("#g_bundles_popup").hover(function() {
    $(this).addClass("popupHover");
    thdebug("mouse over popup");
  }, function() {
    thdebug("mouse out popup");
    $(this).removeClass("popupHover");
    hidePopup();
  });

  $("#articolo_search .selector a").click(function() {
    var ref = $(this).attr("href").replace(/#/, '');
    thdebug("form click " + ref);
    $("#articolo_search [name=\"codice\"]").val(ref);
    var $txt = $("#articolo_search .form_text");
    if (($txt.val() == '') || ($txt.val() == 'Es. 15'))
      alert("Inserisci il numero dell'articolo nel campo a sinistra");
    else
      $("#articolo_search").submit();
    return false;
  });
  
  /* setta l'altezza minima del body in corrispondenza della navigazione locale */
  var objs = [ $("#g_navbar"), $("#g_sidebar"), $("#g_body") ];
  var pos = [ 0, 0, 0 ];
  var layoutH = 0;
  for (var i in objs) {
    var h = objs[i].height(),
        p = objs[i].offset().top;

    thdebug("acquired h=" + h + ", p=" + p + " for " + objs[i].attr("id"));

    if ((h + p) > layoutH)
      layoutH = h + p;

    pos[i] = p;
  }
  
  layoutH += 100;
  thdebug("setting global layout height to " + layoutH + "px");

  for (var i in objs) {
    if ($.browser.msie && $.browser.version < 7)
      objs[i].css("height", (layoutH - pos[i]) + "px");
    else
      objs[i].css("min-height", (layoutH - pos[i]) + "px");
  }

  /* form che si autopuliscono */
  $("form.comment textarea").focus(function() {
    if ($(this).val() == 'Aggiungi un commento')
      $(this).val('');
  });
  $("#brocardo_search .form_text").focus(function () {
    if ($(this).val() == 'Es. dura lex sed lex')
      $(this).val('');
  });
  $("#articolo_search .form_text").focus(function () {
    if ($(this).val() == 'Es. 15')
      $(this).val('');
  });
  
  /*e si ricompilano se bianchi*/
  $("form.comment textarea").blur(function() {
      if ($(this).val() == ''){
          $(this).val('Aggiungi un commento');
          };
  });
  $("#brocardo_search .form_text").blur(function() {
      if ($(this).val() == ''){
          $(this).val('Es. dura lex sed lex');
          };
  });
  $("#articolo_search .form_text").blur(function() {
      if ($(this).val() == ''){
          $(this).val('Es. 15');
          };
  });

  //advisory sui form
  $("form.comment textarea, form.comment select, form.comment input").focus(function (){
        $('#advisory').show('slow');
        });

  // IE6 png fix
  if ($.browser.msie && $.browser.version < 7) {
    $(".lds_book a.sconto").each(function(w) {
      var results = this.currentStyle.backgroundImage.match(/url\("(.+)"\)/);
      if (results != null) {
        var url = results[1];
        this.style.backgroundImage = 'none';
        this.style.filter = "progid:DXImageTransform.Microsoft." +
                            "AlphaImageLoader(src='" + url + "',sizingMethod='crop')";
      }
    });
  }

});

/* jQuery e jQuerytool codice*/

$(document).ready(function(){
        //nasconde gli elemnti da non visualizzare
        $('#sottoreparti').hide();
        $('#nascondi').hide();
        $('#advisory').hide();

         //validazione form
        $(".comment").validator();

        //tooltip per i libri
        $('.lds_book').tooltip({effect: 'slide', position: "top right", delay: '40', offset: [90, -40], opacity: 0.95, predelay: 650, delay: 150, relative: true});


       //mostra / nasconde i reparti nella libreria
       $('#mostra').click(function() {
          $('#sottoreparti').show('slow');
          $('#nascondi').show();
          $(this).hide();
          return false;
       });

       $('#nascondi').click(function() {
         $('#sottoreparti').hide('fast');
         $('#mostra').show();
         $(this).hide();
         return false;
        });

        //da errore se cerca di usare il "vai all'articolo" senza selezionare un codice
        $('div.selector .form_button').click(function(e){
            if(
                $('#articolo_search_side_pre').is(':checked') ||
                $('#articolo_search_side_cc').is(':checked') ||
                $('#articolo_search_side_cp').is(':checked') ||
                $('#articolo_search_side_cpc').is(':checked') ||
                $('#articolo_search_side_cpp').is(':checked') ||
                $('#articolo_search_side_cost').is(':checked')||
                $('#articolo_search_side_strada').is(':checked')
            ){
                
            }else{
                alert("Seleziona un Codice!");
                e.preventDefault();
            }
        });
        
        /*navigazione a tab per gli articoli*/
        $("ul.tabs").jQueryToolsTabs("div.panes > div.pane", {
                        tabs: 'li'
                        });
});
