/**
 * Javascript zoom tool library
 *
 * LICENSE: This code is licenced to skinflips.com
 *
 * @package    DACH_SHOP
 * @subpackage PHP_WEBSITE 
 * @copyright  2010 Tortoise Design GmbH
 * @license    http://www.skinflips.com
 * @author     Slavisa Miljanovic <slavisa.miljanovic@softserbia.com>
 * @version    $Id: zoomToolLib.js 2328 2010-07-02 10:38:27Z nenadpet $
 * @link       http://www.skinflips.com
 * @since      File available since Release 0
*/


/**
 * object: Javascript zoom tool library 
 *
 * This object contains functions that can be used for zoom effect
 *
 * notice: it needs >> prototype & jquery javascript frameworks
 *
 * @author Slavisa Miljanovic <slavisa.miljanovic@softserbia.com>
 * @param  void
 * @return void
*/
var zoomToolLib = {
  thumbImagesContainerId: 'designs-content-list',  // div >> _content-list.phtml
  thumbImageOffset: null,                          // thumb image offset (top and left position) 
  imgClone: null,                                  // cloned thumb image
  hoverZoomTool: {
    id: 'image-hover-zoom',
    setOn: 'ul.design-item li',
    css: {
      'display': 'block'
    },
    showDuration: 200,
    hideDuration: 200,
    fadeInDuration: 200,
    mouseOutSet: false,
    hideAfter: 0, 
    hideTime: 0,
    imageContainer: {
      id: 'image-hover-zoom-image-container',
      image: {
        thumb: {
          width: '127px',
          height: '100px' 
        },
        full: {
          width: '258px',
          height: '204px' 
        }
      }
    },
    infoContainer: {
      id: 'image-hover-zoom-info-container',
      imageName: {
        id: 'image-hover-zoom-info-container-image-name'
      },
      imageInfo: {
        id: 'image-hover-zoom-info-container-image-info'
      },
      imageDesigner: {
        id: 'image-hover-zoom-info-container-image-designer'
      },
      imageSelect: {
        id: 'image-hover-zoom-info-container-image-select'
      }
    }
  },


  /**
   * function: It initalizes zoomToolLib, triggered when DOM is ready
   * 
   * @author Slavisa Miljanovic <slavisa.miljanovic@softserbia.com>
   * @param  void
   * @return void
  */
  init: function() {
    $j(document).ready(function(){
      zoomToolLib.createZoomToolContainer();  // create hover zoom tool container
      zoomToolLib.setMouseOver();             // set mouse over event
    });
  },


  /**
   * function: Create zoom tool container and insert it into DOM
   * 
   * @author Slavisa Miljanovic <slavisa.miljanovic@softserbia.com>
   * @param  void
   * @return void
  */
  createZoomToolContainer: function() {
    var mainContainer = $j('<div>');                  // create main container
    mainContainer.attr('id', this.hoverZoomTool.id);  // set main container id

    var relativeContainer = $j('<div>');              // create relative container
    relativeContainer.css({'position': 'relative'});  // set position relative
    mainContainer.append(relativeContainer);          // insert relative container into the main container

    var imageContainer = $j('<div>');                                 // create image container
    imageContainer.attr('id', this.hoverZoomTool.imageContainer.id);  // set image container id
    relativeContainer.append(imageContainer);                         // insert image container into the relative container

    var infoContainer = $j('<div>');                                // create info container
    infoContainer.attr('id', this.hoverZoomTool.infoContainer.id);  // set info container id
    relativeContainer.append(infoContainer);                        // insert info container into the relative container

    var imageName = $j('<div>');                                          // create image name container
    imageName.attr('id', this.hoverZoomTool.infoContainer.imageName.id);  // set image name container id
    infoContainer.append(imageName);                                      // insert image name container into the info container

    //var imageInfo = $j('<div>');                                          // create image info container
    //imageInfo.attr('id', this.hoverZoomTool.infoContainer.imageInfo.id);  // set image info container id
    //infoContainer.append(imageInfo);                                      // insert image info container into the info container

    var imageDesigner = $j('<div>');                                              // create image designer container
    imageDesigner.attr('id', this.hoverZoomTool.infoContainer.imageDesigner.id);  // set image designer container id
    infoContainer.append(imageDesigner);                                          // insert image designer container into the info container

    var imageSelect = $j('<div>');                                            // create image select container
    imageSelect.attr('id', this.hoverZoomTool.infoContainer.imageSelect.id);  // set image select container id
    infoContainer.append(imageSelect);                                        // insert image select container into the info container

    // add zoom tool container to body
    $j('body').append(mainContainer);
  },


  /**
   * function: Set zoom tool mouse over event
   * 
   * @author Slavisa Miljanovic <slavisa.miljanovic@softserbia.com>
   * @param  void
   * @return void
  */
  setMouseOver: function() {
    var ul = $j(zoomToolLib.hoverZoomTool.setOn);  // ul list with design-item images

    // no ul list with images
    // console.info('function: setMouseOver >> ul.length == ' + ul.length);
    if (ul.length == 0) {
      return;
    }

    ul.hover(function() {
      // console.time('timing hover');
      // console.debug('function: setMouseOver >> <li> hover >> start');

      // set zoom tool and show it
      zoomToolLib.setZoomTool(this);

      // console.debug('function: setMouseOver >> <li> hover >> end');
      // console.timeEnd('timing hover');
    }, function() {
      // mouse out triggered
    });
    
    this.setMouseOut();  // set mouse out event
  },


  /**
   * function: Set zoom tool mouse out event
   * 
   * @author Slavisa Miljanovic <slavisa.miljanovic@softserbia.com>
   * @param  void
   * @return void
  */
  setMouseOut: function() {
    if (!this.hoverZoomTool.mouseOutSet) { 
      var ul = $j(zoomToolLib.hoverZoomTool.setOn);  // ul list with design-item images
  
      // no ul list with images
      // console.info('function: setMouseOut >> ul.length == ' + ul.length);
      if (ul.length == 0) {
        return;
      }

      var hoverZoomToolId  = '#' + this.hoverZoomTool.id;   // hover zoom tool id
      var hideAfter        = this.hoverZoomTool.hideAfter;  // triger hide after this time

      // hover event for hover zoom tool
      $j(hoverZoomToolId).hover(function() {
        // mouse over triggered
        // console.debug('function: setMouseOut >> ' + hoverZoomToolId + '>> mouse over event empty');

      }, function() {
        // console.debug('function: setMouseOut >> ' + hoverZoomToolId + '>> mouse out event start');

        // hide zoom tool container
        zoomToolLib.hoverZoomTool.hideTime = window.setTimeout(function() { zoomToolLib.hideZoomTool(); }, hideAfter);

        // console.debug('function: setMouseOut >> ' + hoverZoomToolId + '>> mouse out event end');
      });

      this.hoverZoomTool.mouseOutSet = true;
    }
  },


  /**
   * function: Set zoom tool options and effects
   * 
   * @author Slavisa Miljanovic <slavisa.miljanovic@softserbia.com>
   * @param  {Object} object <li> element with thumb image
   * @return void
  */
  setZoomTool: function(object) {
    clearTimeout(zoomToolLib.hoverZoomTool.hideTime);  // clear hide timer

    var hoverZoomToolId  = '#' + this.hoverZoomTool.id;  // hover zoom tool id
    var infoContainerId  = '#' + this.hoverZoomTool.infoContainer.id;   // info container id

    var hoverZoomTool =   $j(hoverZoomToolId);           // hover zoom tool container
    var infoContainer = $j(infoContainerId);    // info container

    ///////////////////////////////////////////////////////////////////////////////////
    // each time, when mouse over is triggered, hide zoom tool container and info
    // container, because of rough transition between two thumb images
    //
    // hide hover zoom tool
    hoverZoomTool.css({ 
      display: 'none'
    });

    // hide info container
    infoContainer.css({
      display: 'none'
    });

    ///////////////////////////////////////////////////////////////////////////////////
    // initialize main variables
    //
    var imageContainerId = '#' + this.hoverZoomTool.imageContainer.id;  // image container id

    var thumbWidth  = parseInt(this.hoverZoomTool.imageContainer.image.thumb.width);   // thumb image width
    var thumbHeight = parseInt(this.hoverZoomTool.imageContainer.image.thumb.height);  // thumb image height

    var fullWidth  = parseInt(this.hoverZoomTool.imageContainer.image.full.width);   // full image width
    var fullHeight = parseInt(this.hoverZoomTool.imageContainer.image.full.height);  // full image height 

    var showDuration = this.hoverZoomTool.showDuration;  // animation show duration

    var fadeInDuration  = this.hoverZoomTool.fadeInDuration;   // fade in duration

    var imageNameId     = '#' + this.hoverZoomTool.infoContainer.imageName.id;      // image name container id
    //var imageInfoId     = '#' + this.hoverZoomTool.infoContainer.imageInfo.id;      // image info link container id
    var imageDesignerId = '#' + this.hoverZoomTool.infoContainer.imageDesigner.id;  // image designer's name container id
    var imageSelectId   = '#' + this.hoverZoomTool.infoContainer.imageSelect.id;    // image select link container id

    var imageContainer = $j(imageContainerId);  // image container
    //
    ///////////////////////////////////////////////////////////////////////////////////

    ///////////////////////////////////////////////////////////////////////////////////
    // begin with options, content and effects
    //
    this.emptyContainers();  // empty all containers every time zoom tool is shown

    var img = $j(object).find('img');  // thumb image, magnified by the zoom tool
    var imgParent = img.parent();      // thumb image parent node
    
    // use first image from img array, there is only one thumb image
    this.thumbImageOffset = this.getThumbImageOffset(img[0]);
    var curtop  = this.thumbImageOffset[0];
    var curleft = this.thumbImageOffset[1];

    this.imgClone = img.clone();
    this.imgClone.prependTo(imageContainer);  // clone image into hover zoom image container
    //
    ///////////////////////////////////////////////////////////////////////////////////

    ///////////////////////////////////////////////////////////////////////////////////
    // fill zoom tool info container 
    //
    // add design name
    // add designer's name
    // add info and select links
    /////////////////////////////////

    // parse seo url
    var params = jsGalleryLib.parseSeoUrl(imgParent[0].href, 'json');

    // image name
    $j(imageNameId).text(jsGalleryLib.designsInfo[params['design-id']]['name']);
    
    /////////////////////////////////
    // info link
    // removed from beta version
    /*
    var infoLink = $j('<a>');
    infoLink.text('info');
    infoLink.attr('href', '#');
    infoLink.click(function() {  // set onclick event
      jsCommonLib.pageUnderConstruction();
      return false;
    });
    $j(imageInfoId).append(infoLink);
    */
    //
    /////////////////////////////////

    // image designer's name
    $j(imageDesignerId).text(jsGalleryLib.designsInfo[params['design-id']]['designer_name']);

    // info link
    var selectLink = $j('<a>');
    selectLink.text('select');
    selectLink.attr('href', imgParent[0].href);
    selectLink.click(function() {  // set onclick event
      zoomToolLib.saveScrollPosition();
    });
    $j(imageSelectId).append(selectLink);

    // set css properties for zoom main container 

    hoverZoomTool.css({
      display: 'block',
      top: (curtop - 1) + 'px',  // -1px because of border thickness 
      left: curleft + 'px',
      width: thumbWidth + 'px',
      height: thumbHeight + 'px'
    });

    // animate hover zoom tool container
    hoverZoomTool.stop().animate({
      top: (curtop - (fullHeight - thumbHeight) / 2) + 'px', 
      left: (curleft - (fullWidth - thumbWidth) / 2) + 'px', 
      width: fullWidth + 'px', 
      height: fullHeight + 'px'
    }, showDuration);

    // animate cloned image
    this.imgClone.stop().animate({
      top: '0px',
      left: '0px',
      width: fullWidth + 'px',
      height: fullHeight + 'px'
    }, showDuration, function() {
      // set onclick event
      zoomToolLib.imgClone.click(function() {
        zoomToolLib.saveScrollPosition();
        window.open(imgParent[0].href, '_self');
      });

      // fade in info container
      infoContainer.fadeIn(fadeInDuration);
    });
  },


  /**
   * function: Hide zoom tool
   * 
   * @author Slavisa Miljanovic <slavisa.miljanovic@softserbia.com>
   * @param  void
   * @return void
  */
  hideZoomTool: function() {
    var hoverZoomToolId  = '#' + this.hoverZoomTool.id;  // hover zoom tool id

    var thumbWidth  = parseInt(this.hoverZoomTool.imageContainer.image.thumb.width);   // thumb image width
    var thumbHeight = parseInt(this.hoverZoomTool.imageContainer.image.thumb.height);  // thumb image height

    var fullWidth  = parseInt(this.hoverZoomTool.imageContainer.image.full.width);   // full image width
    var fullHeight = parseInt(this.hoverZoomTool.imageContainer.image.full.height);  // full image height 

    var hideDuration = this.hoverZoomTool.hideDuration;  // animation hide duration

    var infoContainerId  = '#' + this.hoverZoomTool.infoContainer.id;  // info container id
    var infoContainer    = $j(infoContainerId);                        // info container

    var hoverZoomToolId  = '#' + this.hoverZoomTool.id;  // hover zoom tool id
    var hoverZoomTool    = $j(hoverZoomToolId);          // hover zoom tool container

    var curtop  = this.thumbImageOffset[0];
    var curleft = this.thumbImageOffset[1];

    if (zoomToolLib.imgClone != null) {
      // hide info container
      infoContainer.css({
        display: 'none'
      });

      // hide hover zoom tool container
      hoverZoomTool.stop().animate({
        top: (curtop - 1) + 'px',  // -1px because of border thickness 
        left: curleft + 'px',
        width: thumbWidth + 'px', 
        height: thumbHeight + 'px'
      }, hideDuration);

      // hide cloned image
      zoomToolLib.imgClone.stop().animate({
        top: '0px',
        left: '0px',
        width: thumbWidth + 'px', 
        height: thumbHeight + 'px'
      }, hideDuration, function() {
        // hide hover zoom tool
        hoverZoomTool.css({ 
          display: 'none'
        });
      });
    }
  },


  /**
   * function: Get thumb image offset (top and left position relative to the edge of browser)
   * 
   * @author Slavisa Miljanovic <slavisa.miljanovic@softserbia.com>
   * @param  {Object} thumbImage // thumb image in the list
   * @return It returns curtop and curleft of 'thumbImage'
   * @type   Array
  */
  getThumbImageOffset: function(thumbImage) {
    // console.debug('function: getThumbImageOffset');
    
    var thumbImagesContainerId = '#' + this.thumbImagesContainerId;  // thumb images container id

    var curleft = 0;
    var curtop = 0;

    var nearElement = thumbImage;
    if (nearElement.offsetParent) {
      do {
        curleft += nearElement.offsetLeft;
        curtop += nearElement.offsetTop;
  
      } while (nearElement = nearElement.offsetParent)
    } else if (nearElement.x) {
      curleft += nearElement.x;
      curtop += nearElement.y;
    }

    // fix top for scrolled images
    // document.viewport.getScrollOffsets()[0] - prototype function - left offset
    // document.viewport.getScrollOffsets()[1] - prototype function - top  offset
    curtop = curtop - $j(thumbImagesContainerId).scrollTop() + 1;

    return [curtop, curleft];
  },


  /**
   * function: Empty all containers
   * 
   * @author Slavisa Miljanovic <slavisa.miljanovic@softserbia.com>
   * @param  void
   * @return void
  */
  emptyContainers: function() {
    // console.debug('function: emptyContainers');

    var imageContainerId = '#' + this.hoverZoomTool.imageContainer.id;               // image container id
    var imageNameId      = '#' + this.hoverZoomTool.infoContainer.imageName.id;      // image name container id
    //var imageInfoId      = '#' + this.hoverZoomTool.infoContainer.imageInfo.id;      // image info link container id
    var imageDesignerId  = '#' + this.hoverZoomTool.infoContainer.imageDesigner.id;  // image designer's name container id
    var imageSelectId    = '#' + this.hoverZoomTool.infoContainer.imageSelect.id;    // image select link container id

    $j(imageContainerId).empty();  // empty image container, remove cloned image
    $j(imageNameId).empty();       // empty image name container
    //$j(imageInfoId).empty();       // empty info link container
    $j(imageDesignerId).empty();   // empty image designer container
    $j(imageSelectId).empty();     // empty select link container
  },


  /**
   * function: Save container scroll position
   *    
   * notice: only for designs container
   * 
   * @author Slavisa Miljanovic <slavisa.miljanovic@softserbia.com>
   * @param  void
   * @return void
  */
  saveScrollPosition: function() {
    var thumbImagesContainerId = '#' + this.thumbImagesContainerId;  // thumb images container id
    var scrollPosition = $j(thumbImagesContainerId).scrollTop();
    
    var cookieName = 'designsDivScrollPosition' + jsGalleryLib.getDeviceActiveId(); 

    jsCommonLib.eraseCookie(cookieName);
    jsCommonLib.setCookie(cookieName, scrollPosition, 0.05);  // expire in almost 15 minutes
  }

}
