
/// mixed array_search ( mixed $needle , array $haystack [, bool $strict ] )
function array_search(value, a) {
  for (var i=0; i < a.length; i++) { if(a[i] == value) { return i; } }
  return false;
}


var aLoadImgSrc = '/site/img/aBox-loading.gif'; // where is the loading image? (recommend absolute)

var aImgTypes = new Array('jpg', 'gif', 'png', 'bmp'); // types of images to place in Awesome Box



var aClient = new Object();
/*
 *  aClient.allImgs()
 *    Find all links going to an image with an aImgTypes and return it as an array.
 *    ridefinire nella pagina che usa la lib se il container deve essere differente
 */
aClient.allImgs = function() {
  var a = aClient._allImgs('detail-carousel' /* 'awesomebox'*/ );  
  return a;
}

aClient._allImgs = function(container_id) {

  /*
  di tutte le immagini presenti nel elemeto awesomebox solo quelle che hanno l'attributo
  large
  */
  var imgs = document.getElementsByTagName('img', document.getElementById(container_id) ); //'awesomebox' carousel
  
  var photos = new Array();
  for(i = 0; i < imgs.length; i++) {
    var large = imgs[i].getAttribute('large');
    if ( large ){
      photos.push( imgs[i] );
    }
  }
  
  return photos;
}

/*
 *  aClient.pageWidth() and aClient.pageHeight()
 *    Returns the width and height of the content in the document.
 */
aClient.pageWidth = function() {
  var xScroll;
  if(window.innerHeight && window.scrollMaxY) {
    xScroll = document.body.scrollWidth;
  } else if(document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
    xScroll = document.body.scrollWidth;
  } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
    xScroll = document.body.offsetWidth;
  }
  if(xScroll < $D.getViewportWidth()) {
    pageWidth = $D.getViewportWidth();
  } else {
    pageWidth = xScroll;
  }
  return pageWidth;
};
aClient.pageHeight = function() {
  var yScroll;
  if(window.innerHeight && window.scrollMaxY) {
    yScroll = window.innerHeight + window.scrollMaxY;
  } else if(document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
    yScroll = document.body.scrollHeight;
  } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
    yScroll = document.body.offsetHeight;
  }
  if(yScroll <= $D.getViewportHeight()) {
    pageHeight = $D.getViewportHeight();
  } else {
    pageHeight = yScroll;
  }
  return pageHeight;
};

/*
 *  aClient.xScroll(), aClient.yScroll()
 *    Returns the position of the X and Y scrollbars.
 */
aClient.xScroll = function() {
  var xScroll = window.scrollX || document.documentElement.scrollLeft;
  return xScroll;
}
aClient.yScroll = function() {
  var yScroll = window.scrollY || document.documentElement.scrollTop;
  return yScroll;
}



/*
 *  Helper Variables
 */
var $D = YAHOO.util.Dom;
var $E = YAHOO.util.Event;
var $A = YAHOO.util.Anim;
var $M = YAHOO.util.Motion;
var $S = YAHOO.util.Scroll;
var $Ease = YAHOO.util.Easing;
var $ = $D.get;

/*
 *  AnimMgr
 *    Sets the default frames per second higher so Safari will display animations
 *    at the correct speed. Degrades for slower browsers.
 */
YAHOO.util.AnimMgr.fps = 500;

YAHOO.widget.aEffect = function(el) { this.oEl = YAHOO.util.Dom.get(el); };

/*
 *  YAHOO.widget.aEffect.aShowLoad()
 *    Animation widget for transition period on Awesome Box initialize or between images.
 */
YAHOO.widget.aEffect.prototype.aShowLoad = function() {
  var showLoad = new $A('aLoadImg', {opacity: {to: 1}}, 0.2);
  showLoad.onStart.subscribe(function() {
    $D.setStyle('aLoadImg', 'display', 'block');
    $D.setXY('aLoadImg', [
      ($D.getViewportWidth()/2)-16+aClient.xScroll(),
      ($D.getViewportHeight()/2)-16+aClient.yScroll()
    ]);
    if($D.hasClass('aBoxMeta', 'aOpen')) {
      var hideMeta = new $A('aBoxMeta', {opacity: {to: 0}, height: {to: 0}}, 0.2);
      hideMeta.onStart.subscribe(function() {
        $D.setStyle('aImg', 'opacity', '0');
        $D.setStyle('aImg', 'visibility', 'hidden');
      });
      hideMeta.animate();
    }
  });
  showLoad.animate();
};

/*
 *  YAHOO.widget.aEffect.aShowOverlay
 *    Fades in #aOverlay and #aBox.
 *    Initializes YAHOO.widget.aEffect.aShowLoad()
 */
YAHOO.widget.aEffect.prototype.aShowOverlay = function() {
  selects = document.getElementsByTagName("select");
  for (i = 0; i != selects.length; i++) {
    $D.setStyle(selects[i], 'visibility', 'hidden');
  }

  var fadeOverlay = new $A('aOverlay', {
    opacity: {
      to: 0.25 /*0.85*/
    }
  }, 0.3);
  fadeOverlay.onStart.subscribe(function() {
    $D.setStyle('aOverlay', 'display', 'block');
    $D.setStyle('aOverlay', 'height', aClient.pageHeight()+'px');
  });
  var showBox = new $A('aBox', {opacity: {to: 1}}, 0.3);
  showBox.onStart.subscribe(function() {
    $D.setStyle('aBox', 'display', 'block');
    var showLoad = new YAHOO.widget.aEffect();
    showLoad.aShowLoad();
  });
  showBox.animate();
  fadeOverlay.animate();
};

/*
 *  YAHOO.widget.aEffect.aResizeBox()
 *    Initialized after new image is completed loading. Resizes and moves #aBox, times out
 *    and displays #aBoxMeta information
 */
YAHOO.widget.aEffect.prototype.aResizeBox = function(aPreload) {
  var imgScale = YAHOO.awesomebox.scaleImage(aPreload);

  var moveBox = new $M('aBox', {
    width: {to: (imgScale[0]+20)},
    height: {to: (imgScale[1]+20)},
    points: {to: [
      ($D.getViewportWidth()/2)-(imgScale[0]/2)+aClient.xScroll()-10,
      ($D.getViewportHeight()/2)-(imgScale[1]/2)+aClient.yScroll()-10
      ]
    }
  }, 0.3);
  moveBox.onStart.subscribe(function() {
    $D.setStyle('aBox', 'display', 'block');

    var hideLoad = new $A('aLoadImg', {opacity: {to: 0}}, 0.3);
    var sizeImage = new $A('aImg', {width: {to: imgScale[0]}, height: {to: imgScale[1]}}, 0.3);

    hideLoad.onComplete.subscribe(function() { $D.setStyle('aLoadImg', 'display', 'none'); });
    hideLoad.animate();
    sizeImage.animate();
  });
  moveBox.onComplete.subscribe(function() {
    $D.setStyle('aBox', 'height', imgScale[1]+70+'px');
    $D.setStyle('aBoxMeta', 'width', imgScale[0]+'px');
    $D.addClass('aBoxMeta', 'aOpen');
    $('aImg').setAttribute('width', imgScale[0]);
    $('aImg').setAttribute('height', imgScale[1]);
    $D.setStyle('aImg', 'visibility', 'visible');

    var fadeImg = new $A('aImg', {opacity: {from: 0, to: 1}}, 0.3);

    fadeImg.onComplete.subscribe(function() {
      var showMeta = new $A('aBoxMeta', {opacity: {from: 0, to: 1}, height: {to: 40}}, 0.2);
      showMeta.animate();
    });
    fadeImg.animate();
  });
  if($D.hasClass('aBoxMeta', 'aOpen')) {
    setTimeout(function() {
      $('aImg').setAttribute('src', aPreload.src);
      moveBox.animate();
    }, 300);
  } else {
    $('aImg').setAttribute('src', aPreload.src);
    moveBox.animate();
  }
};

/*
 *  YAHOO.widget.aEffect.aClose
 *    Closes #aBox and #aOverlay. Invoked via pressing 'x', clicking the 'X' image or #aOverlay
 */
YAHOO.widget.aEffect.prototype.aClose = function() {
  var that = $('aImg');
  var hideMeta = new $A('aBoxMeta', {height: {to: 0}, opacity: {to: 0}}, 0.2);
  var fadeBox = new $M('aBox', {opacity: {to: 0}}, 0.3);
  fadeBox.onComplete.subscribe(function() {
    var hideOverlay = new $A('aOverlay', {opacity: {to: 0}}, 0.3);
    hideOverlay.onStart.subscribe(function() {
      selects = document.getElementsByTagName("select");
      for (i = 0; i != selects.length; i++) {
        $D.setStyle(selects[i], 'visibility', 'visible');
      }
      $D.removeClass('aBoxMeta', 'aOpen');
      $D.setStyle('aBox', 'display', 'none');
      $D.setStyle('aImg', 'opacity', '0');
      $D.setStyle('aImg', 'visibility', 'hidden');
      $D.setStyle('aOverlay', 'display', 'none');
      $D.setStyle('aOverlay', 'height', '0px');
      $D.setStyle('aLoadImg', 'display', 'none');
    });
    hideOverlay.animate();
  });
  hideMeta.animate();
  fadeBox.animate();
  $E.removeListener('aNextButton', 'click');
  $E.removeListener('aPrevButton', 'click');
  $E.removeListener(document, 'keypress');
};


/*
 *  YAHOO.awesomebox()
 *    Non-animating functions, initialized on window load completion.
 */
YAHOO.awesomebox = function() {
  return {

    /*
     *  init()
     *    Creates the markup, checks for direct image link, adds event listeners.
     */
    init : function() {


      if(!document.getElementsByTagName){ return; }

      /*
       *  Awesome Box Markup
       *
        <div id="aOverlay" title="Click to Close"></div>
        <div id="aBox">
          <div id="aImgHolder">
            <img id="aImg" />
          </div>
          <div id="aBoxMeta">
            <a class="aButton" href="#next" id="aNextButton"></a>
            <a class="aButton" href="#prev" id="aPrevButton"></a>
            <a class="aButton" href="#close" id="aCloseButton"></a>
            <h1 id="aInfoTitle"></h1>
            <p id="aCount"></p>
            <p id="aInfo"></p>
          </div>
        </div>
        <img src="images/aBox-loading.gif" id="aLoadImg" />
       */

      var aBody = document.getElementsByTagName("body").item(0);

      var aOverlay = document.createElement('div');
      $(aOverlay).setAttribute('id', 'aOverlay');
      $(aOverlay).setAttribute('title', 'Click to Close');
      aBody.appendChild(aOverlay);
      $D.setStyle('aOverlay', 'opacity', '0');

      var aBox = document.createElement('div');
      $(aBox).setAttribute('id', 'aBox');
      aBody.appendChild(aBox);
      $D.setStyle('aBox', 'opacity', '0');
      $D.setXY('aBox', [($D.getViewportWidth()/2)-21, ($D.getViewportHeight()/2)-21])
      $D.setStyle('aBox', 'display', 'none');

      var aImgHolder = document.createElement('div');
      $(aImgHolder).setAttribute('id', 'aImgHolder');
      aBox.appendChild(aImgHolder);

      var aImg = document.createElement('img');
      $(aImg).setAttribute('id', 'aImg');
      aImgHolder.appendChild(aImg);
      $D.setStyle('aImg', 'opacity', '0');
      $D.setStyle('aImg', 'visibility', 'hidden');

      var aBoxMeta = document.createElement('div');
      $(aBoxMeta).setAttribute('id', 'aBoxMeta');
      aBox.appendChild(aBoxMeta);

      var aNextButton = document.createElement('a');
      $(aNextButton).setAttribute('id', 'aNextButton');
      aBoxMeta.appendChild(aNextButton);
      $(aNextButton).setAttribute('href', '#next');
      $D.addClass(aNextButton, 'aButton');

      var aPrevButton = document.createElement('a');
      $(aPrevButton).setAttribute('id', 'aPrevButton');
      aBoxMeta.appendChild(aPrevButton);
      $(aPrevButton).setAttribute('href', '#prev');
      $D.addClass(aPrevButton, 'aButton');

      var aCloseButton = document.createElement('a');
      $(aCloseButton).setAttribute('id', 'aCloseButton');
      aBoxMeta.appendChild(aCloseButton);
      $(aCloseButton).setAttribute('href', '#close');
      $D.addClass(aCloseButton, 'aButton');

      var aInfoTitle = document.createElement('h1');
      $(aInfoTitle).setAttribute('id', 'aInfoTitle');
      aBoxMeta.appendChild(aInfoTitle);

      var aCount = document.createElement('p');
      $(aCount).setAttribute('id', 'aCount');
      aBoxMeta.appendChild(aCount);
      $D.setStyle(aCount, 'opacity', '0');

      var aInfo = document.createElement('p');
      $(aInfo).setAttribute('id', 'aInfo');
      aBoxMeta.appendChild(aInfo);

      var preloadLoading = new Image();
      preloadLoading.src = aLoadImgSrc;

      var aLoadImg = document.createElement('img');
      $(aLoadImg).setAttribute('id', 'aLoadImg');
      aBody.appendChild(aLoadImg);
      $(aLoadImg).setAttribute('src', preloadLoading.src);
      $D.setStyle('aLoadImg', 'opacity', '0');

      /*
       *  Hash Check
       *    Checks the URL on page load for #filename and attempts to load it
      */
      if(window.location.href.indexOf('#') != -1) {
        // generate an ID for the body if it doesn't exist
        if(document.body.id != '' || document.body.id != null) {
          var body = $D.generateId(document.body);
        } else {
          var body = document.body.id;
        }
        var imgArray = aClient.allImgs();
        var loadImg = window.location.href.split('#')[1];
        for(i = 0; i < imgArray.length; i++) {
          var imgUrl = imgArray[i].getAttribute('href');
          // se è stato montato usando un anchor contenitore, altrimenti
          // salta questo passaggio
          if( imgUrl ){
            imgUrl = imgUrl.split('/');
            if(imgUrl[imgUrl.length-1].split('.')[0] == loadImg) {
              $E.onAvailable(body, this.load, $(imgArray[i]), true);
            }
          }
        }
      }

      $E.on(aOverlay, 'click', this.close);
      $E.on(aCloseButton, 'click', this.close);

      $E.on(aClient.allImgs(), 'click', this.load);

    },
    /* handler di debug */
    evtDbg : function(e){
        $E.stopEvent(e);
        alert('clicked');
    },

    /*
     *  load()
     *    Gets information for new image and invokes appropriate actions.
     */
    load : function(e, newImg) {
      //alert( 'loading ');
      var fadeOverlayIn = new YAHOO.widget.aEffect();
      fadeOverlayIn.aShowOverlay();

      // that è la nuova immagine da caricare
      if(newImg) {
        var that = newImg;
      } else {
        var that = this;
      }

      $E.stopEvent(e);

      $E.removeListener(document, 'keypress');

      aPreload = new Image();
      aPreload.onload = function() {
        var resizeBox = new YAHOO.widget.aEffect(that);
        resizeBox.aResizeBox(aPreload);

        //urchinTracker(aPreload.src.split(siteURL)[1]);

        // frecce di navigazione
        if(!that.getAttribute('large' /*'rel'*/)) {
          $D.setStyle('aNextButton', 'visibility', 'hidden');
          $D.setStyle('aPrevButton', 'visibility', 'hidden');
          $D.setStyle('aCount', 'opacity', '0');
        } else {
          $D.setStyle('aCount', 'opacity', '1');
          $E.removeListener('aNextButton', 'click');
          $E.removeListener('aPrevButton', 'click');
        }

        var aInfoTitle = '';
        var aInfo = '';

        if(that.getAttribute('title') != null) {
          var aInfoTitle = that.getAttribute('title');
        }
        if(
          that.getElementsByTagName('img')[0] &&
          that.getElementsByTagName('img')[0].getAttribute('title') != null
        ) {
          var aInfoTitle = that.getElementsByTagName('img')[0].getAttribute('title');
        }
        if(
          that.getElementsByTagName('img')[0] &&
          that.getElementsByTagName('img')[0].getAttribute('alt') != null
        ) {
          var aInfo = that.getElementsByTagName('img')[0].getAttribute('alt');
        } else {
          var aInfo = that.innerHTML;
        }
        if($D.hasClass('aBoxMeta', 'aOpen')) {
          setTimeout(function() {
            $('aInfoTitle').innerHTML = aInfoTitle;
            $('aInfo').innerHTML = aInfo;
          }, 250);
        } else {
          $('aInfoTitle').innerHTML = aInfoTitle;
          $('aInfo').innerHTML = aInfo;
        }

        var urlSplit = that.getAttribute('large'  ).split('/');//'href'
        var filename = urlSplit[urlSplit.length-1].split('.')[0];
        if(window.location.href.indexOf('#') != -1) {
          var url = window.location.href.split('#')[0];
        } else {
          var url = window.location.href;
        }
        window.location = url+'#'+filename;

         
        if(that.getAttribute('large' /*'rel'*/)) {
          YAHOO.awesomebox.loadNeighbors(that);
        }

        $E.addListener(document, 'keypress', function(e) {
          $E.stopEvent(e);
          switch($E.getCharCode(e)) {
            case (120) : YAHOO.awesomebox.close();
            break;
            // case (97) : YAHOO.awesomebox.awesome(); break;
          }
        });
      };
      var src = that.getAttribute( 'large' ); //'href'
      aPreload.src = src;
    },

    /*
     *  loadNeighbors()
     *    Invoked via load(), finds and preloads next and previous image.
     */
    loadNeighbors : function(that) {
      var imgRefs = aClient.allImgs();
      var photoSet = new Array();

     

      for(j = 0; j < imgRefs.length; j++) {
        /// non capisco questo passaggio, perchè solo l'immagine corrente? occorrono tutte le immagini
        ///if(
        ///  imgRefs[j].getAttribute('large' /*'rel'*/) &&
        ///  imgRefs[j].getAttribute('large' /*'rel'*/) == that.getAttribute('large' /*'rel'*/)
        ///) {
          photoSet.push(imgRefs[j]);
        ///}
      }
      
      var key = array_search(that, photoSet);
      if( key !== false ){
          //alert( YAHOO.lang.dump(photoSet) + 'key:'+key );

          setTimeout(function() {
            $('aCount').innerHTML = 'Imagine '+(key+1)+' di '+photoSet.length;
          }, 300);

          if(key != photoSet.length-1) {
            var next = new Image();
            next.src = photoSet[key+1].getAttribute('large' /*'href'*/);
            $D.setStyle('aNextButton', 'visibility', 'visible');
          } else {
            $D.setStyle('aNextButton', 'visibility', 'hidden');
          }
          if(key != 0) {
            var prev = new Image();
            prev.src = photoSet[key-1].getAttribute('large' /*'href'*/);
            $D.setStyle('aPrevButton', 'visibility', 'visible');
          } else {
            $D.setStyle('aPrevButton', 'visibility', 'hidden');
          }

          $E.addListener('aNextButton', 'click', this.load, photoSet[key+1], true);
          $E.addListener('aPrevButton', 'click', this.load, photoSet[key-1], true);

          $E.addListener(document, 'keypress', function(e) {
            $E.stopEvent(e);
            switch($E.getCharCode(e)) {
              // 110 = n, 112 = p
              case (110) :
                if(key != photoSet.length-1) {
                  YAHOO.awesomebox.load('', photoSet[key+1]);
                }
              break;
              case (112) :
                if(key != 0) {
                  YAHOO.awesomebox.load('', photoSet[key-1]);
                }
              break;
            }
          });
      }
    },

    /*
     *  scaleImage()
     * Returns proportional values for height and width of image, scaled if necessary.
     */
    scaleImage : function(aImage) {
      var sHeight = aImage.height;
      var sWidth = aImage.width;
      if(aImage.width > $D.getViewportWidth()) {
        sWidth = $D.getViewportWidth()-20;
        sHeight = aImage.height * (sWidth / aImage.width);
        if(sHeight+100 > ($D.getViewportHeight()-20)) {
          sHeight = $D.getViewportHeight()-120;
          sWidth = aImage.width * (sHeight / aImage.height);
        }
      } else if(aImage.height+100 > $D.getViewportHeight()) {
        sWidth = aImage.width * (($D.getViewportHeight()-120) / aImage.height);
        sHeight = $D.getViewportHeight()-120;
        if(sWidth > ($D.getViewportWidth()-20)) {
          sWidth = aImage.width * (sHeight / aImage.height);
          sHeight = aImage.height * (sWidth / aImage.width);
        }
      }
      var scaleAtts = new Array(Math.floor(sWidth), Math.floor(sHeight));
      return scaleAtts;
    },

    /*
     *  close()
     *    Calls YAHOO.widget.aEffect.aClose() and resets the #filename to #close.
     *    Not the most elegant solution.
     */
    close : function() {
      var aClose = new YAHOO.widget.aEffect();
      aClose.aClose();
      if(window.location.href.indexOf('#') != -1) {
        var url = window.location.href.split('#')[0];
      } else {
        var url = window.location.href;
      }
      window.location = url+'#close';
    }

    /*awesome : function() {
      var aAwesome = new YAHOO.widget.aEffect();
      aAwesome.aAwesome();
    }*/
  }
}();

