/*
 * piccin.js - Part of piccin.it website
 *
 * Autore: Giovanni Giacobbi <giovanni@giacobbi.net>
 * Copyright (c) 2007 - 2009
 *
 * Tutti i diritti sono riservati.
 *
 */

/* graceful fall-back when firebug is not available
 * @snippet firebug-fallback 20101221 */
if (!window.console || !console.firebug) {
  // from http://getfirebug.com/wiki/index.php/Console_API
  var names = ["log", "debug", "info", "warn", "error", "assert", "clear",
               "dir", "dirxml", "trace", "group", "groupCollapsed", "groupEnd",
               "time", "timeEnd", "profile", "profileEnd", "count", "exception", "table"];

  window.console = { };
  for (var i = 0; i < names.length; i++) {
    window.console[names[i]] = function() { };
  }
}

/* jQuery custom extensions */
(function($) {
  /**
   * Applies IE png hack to selected DOM elements' backgrounds
   */
  $.fn.fixpng = function() {
    if ($.browser.msie) {
      return this.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='scale')";
        }
      });
    }
    return this;
  }
})(jQuery);

/* global site init function */
$(function() {
  /* Get ready to use Thickbox plugin */
  var tb_pathToImage = FrontendPrefix + "images/loadingAnimation.gif";

  /* IE alphapng fix */
  $("ul.wlink li.active a").fixpng();

  /* RDC flash banner */
  if ($("#rdcbanner").hasClass("rdcNoAnim")) {
    $("#rdcbanner").flash({
      swf: FrontendPrefix + "media/banner rdc 241x200 noanim.swf",
      width: 241,
      height: 200
    });
  }
  else {
    $("#rdcbanner").flash({
      swf: FrontendPrefix + "media/banner rdc 241x200.swf",
      width: 241,
      height: 200
    });
  }

  /* better to wrap right-left instead of left-right so the right curved border
   * is visible until the very... end. */
  $("div.body h2").wrapInner("<span class=\"right\"></span>")
                  .wrapInner("<span class=\"left\"></span>")
                  .css("padding-left", "0px");

  $(".listing .book").each(function() {
    var filler = function(e, anchorX, anchorY) {
      var ctor = function() {
        var d = document.createElement("DIV");
        $(d).css({ "position": "absolute", "width": "1px", "height": "1px" });
        return e.appendChild(d);
      };

      $(ctor()).css("background-color", "#fdfdfd")
               .css(anchorX, -1).css(anchorY, -1);
      $(ctor()).css("background-color", "#f4f4f6")
               .css(anchorX, 0).css(anchorY, -1);
      $(ctor()).css("background-color", "#f4f4f6")
               .css(anchorX, -1).css(anchorY, 0);
      $(ctor()).css("background-color", "#b5c9d6")
               .css(anchorX, 0).css(anchorY, 0);
    };

    $(this).css("position", "relative");
    filler(this, "left", "top");
    filler(this, "left", "bottom");
    filler(this, "right", "top");
    filler(this, "right", "bottom");
  });

  $("div.body .content_footer,div.sidebar .block .block_footer").each(function () {
    var ctor = function(e) {
      var d = document.createElement("DIV");
      $(d).css({ "position": "absolute", "width": "3px", "height": "3px" });
      return e.appendChild(d);
    };

    $(this).css("position", "relative");
    $(ctor(this)).css({
      "top": "-1px",
      "left": "-1px",
      "background-image": "url(" + FrontendPrefix + "images/wblock_footer_left.png)"
    });
    $(ctor(this)).css({
      "top": "-1px",
      "right": "-1px",
      "background-image": "url(" + FrontendPrefix + "images/wblock_footer_right.png)"
    });
  });
});

/* admin utility */
function toggleAll(objForm, do_check) {
  for (i = 0; i < objForm.elements.length; i++) {
    if ((objForm.elements[i].type == "checkbox") &&
        (objForm.elements[i].name == "selected[]"))
      objForm.elements[i].checked = do_check;
  }
  return;
}

/* admin utility */
function submitMassOperation(action) {
  var eform = document.forms.massop;
  if (eform) {
    if (action == 'move') {
      eform.action.value = 'promptmassmove';
      eform.dup.value = '0';
    }
    if (action == 'dup') {
      eform.action.value = 'promptmassmove';
      eform.dup.value = '1';
    }
    if (action == 'remove') {
      eform.action.value = 'promptmassremove';
    }

    var cnt = 0;
    eform.submit();
  }
}

/* retarded layout spanner for the home floating boxes */
function resizeLatestNews() {
  var $$ = $(".listing div.book");
  var gap = Math.ceil(parseFloat($$.css("border-left-width")) + parseFloat($$.css("border-right-width")));
  var margin = Math.ceil(parseFloat($$.css("margin-right")));
  var fullWidth = Math.floor($(".latestNews").width() + margin);
  var boxes = Math.floor(fullWidth / 350);
  var singleWidth = Math.floor(fullWidth / boxes);
  if ((singleWidth % 2) == 0)
    singleWidth--;
  var lastWidth = fullWidth - singleWidth * (boxes - 1);
  console.debug("gap=" + gap);
  console.debug("fullWidth=" + fullWidth + ", boxes=" + boxes + ", " +
                "singleWidth=" + singleWidth + ", lastWidth=" + lastWidth);

  $(".listing").css("width", fullWidth + "px");
  $$.css({ "width": (singleWidth - gap - margin) + "px", "clear": "none" });
  for (var j = 0; j < $$.length; j++) {
    if ((j % boxes) == (boxes - 1)) {
      $$.eq(j).css("width", (lastWidth - gap - margin) + "px");
    }
  }
}

$(function() {
  if ($("body").hasClass("home")) {
    resizeLatestNews();
    $(window).resize(resizeLatestNews);
  }

  /* open new windows */
  $(".newWindow").click(function() {
    var url = this.href;
    var posX = (screen.width - 570) / 2;
    var posY = (screen.height - 395) / 2;
    window.open(url, 'cardspopup', 'width=570,height=395,toolbar=no,' +
                'scrollbars=yes,menubar=no,status=no,left=' + posX + ',top=' + posY);
    return false;
  });
});

/* menu bar slider animation */
$(function() {
  var colorNormal = "#ffffff";
  var colorHover = "#006799";

  //console.debug("creating the div");
  var $d = $(document.createElement("DIV"));
  $d.addClass("active");
  $("div.wlink").append($d);
  var $dd = $(document.createElement("DIV"));
  $d.append($dd);
  $dd.fixpng();

  //console.debug("intercepting the active one");
  var $div = $("div.wlink");
  var $a = $("ul.wlink .active a");
  if ($a.length > 0) {
    var activeOffset = Math.round($a.offset().left - $div.offset().left);
    $d.css("left", activeOffset + "px");
    $d.css("opacity", 1);
    $a.css("color", colorHover);
    $("ul.wlink li.active a").get(0).style.filter = "";
    $("ul.wlink .active").removeClass("active");
  }
  else
    $d.css("opacity", 0);

  $("ul.wlink a").mouseover(function() {
    if ($a.length > 0)
      $a.css("color", colorNormal);
    $(this).css("color", colorHover);

    $d.stop();
    var myOffset = Math.round($(this).offset().left - $div.offset().left);
    if ($d.css("opacity") > 0.2) {
      //console.debug("moving the slider to " + myOffset);
      $d.animate({ "left": myOffset + "px", "opacity": 1 }, 500, "linear");
    }
    else {
      //console.debug("spawning slider at " + myOffset);
      $d.css("left", myOffset + "px");
      $d.animate({ "opacity": 1 });
    }
  });

  $("ul.wlink a").mouseout(function() {
    $(this).css("color", colorNormal);

    $d.stop();
    if ($a.length > 0) {
      var activeOffset = Math.round($a.offset().left - $div.offset().left);
      $a.css("color", colorHover);
      $d.animate({ "left": activeOffset + "px" }, 350, "linear");
    }
    else
      $d.animate({ "opacity": 0 });
  });

  /* rifinitura finale: quando lo clicco diventa il nuovo attivo */
  $("ul.wlink a").click(function() {
    $a = $(this);
  });

});



/* chapter attachment */
$(function() {
  $(".attachment_chapter a.chapter").click(function() {
    var $b = $(this).closest(".attachment_chapter");
    $b.find(".chapter_content").toggle();
    return false;
  });
});

