/*
 * brocardi.it
 */

function thdebug(message) {
  if ((typeof(console) != "undefined") && console)
    console.log(message);
}

$(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_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.value == 'Aggiungi un commento')
      this.value = '';
  });
  $("#brocardo_search .form_text").focus(function () {
    if (this.value == 'Es. dura lex sed lex')
      this.value = '';
  });
  $("#articolo_search .form_text").focus(function () {
    if (this.value == 'Es. 15')
      this.value = '';
  });

  // 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')";
      }
    });
  }

});
