/*
 * Author: Colin Mollenhour 2009
 */

/* Used for main menu hover */
function delegateHover(event,selector,callback){
	/* IE will have event.srcElement == null on some mouseout events */
	if( ! event.target || ! (related = event.relatedTarget)) return;
	var current = event.element();
	do{
		if( current.match(selector) && related != current && ! related.childOf(current))
		{
			callback.call(current,event);
			return;
		}
	}while( current != this && (current = $(current.parentNode)) && current != document );
}

/* main menu hover - extremely convoluted code to make dropdown menus more forgiving of sloppy mouse movement */
function trier_init(menu,childmenu){
  var changeDelay = 500;  // delay when a submenu is active before swapping to another submenu
  var clearDelay = 400;   // delay when leaving the submenu area before hiding it

  menu = $(menu);
  childmenu = $(childmenu);
  var active_parent = menu.down('.active');
  //var active_child = childmenu.down('.active');
  //var current = active_child;
  var current = active_child = null;
  var last_active = [active_parent,active_child];

  function activate(parent,child,skipreset){
    if(parent) parent.addClassName('active');
    if(child) child.show();
    if( ! skipreset) last_active = [parent,child];
    current = child;
  }
  function deactivate(parent,child){
    if(parent) parent.removeClassName('active');
    if(child) child.hide();
    current = null;
  }
  var timeout = null;
  var timeout2 = null;

  menu
  .observe('mouseover',delegateHover.bindAsEventListener(menu,'td',function(){
    clearTimeout(timeout2);
    clearTimeout(timeout);
    timeout2 = setTimeout(function(){
      var new_current = $(this.id+'-child');
      if(new_current && current && current == new_current){ return; }
      if(current) deactivate.apply(null,last_active);
      if(new_current != active_child) deactivate(active_parent,active_child);
      if(new_current) activate(this,new_current);
    }.bind(this),current ? changeDelay:0);
  }))
  .observe('mouseout', delegateHover.bindAsEventListener(menu,'td',function(){
    timeout = setTimeout(function(){
      if(current && current != active_child)
        deactivate.apply(null,last_active);
      if(active_child)
        activate(active_parent,active_child,true);
    },current ? clearDelay:0);
  }));

  childmenu
  .observe('mouseover',delegateHover.bindAsEventListener(menu,'div',function(){
    clearTimeout(timeout2);
    clearTimeout(timeout);
  }))
  .observe('mouseout',delegateHover.bindAsEventListener(menu,'div',function(){
    clearTimeout(timeout);
    timeout = setTimeout(function(){
      if(current && current != active_child)
        deactivate.apply(null,last_active);
      if(active_child)
        activate(active_parent,active_child,true);
    },current ? clearDelay:0);
  }));
}


/* Open an info popup */
function generalInfoPopup(url) {
  window.open(url,"general_info","dependent=1,height=650,width=790,resizable=0,scrollbars=1,status=0");
}

/* Use a fade effect to toggle a thumbnail with an alternate image */
Effect.ToggleThumb = {

  fadeDuration: 0.3,
  appearDuration: 0.1,

  toggle: function(el,src){
    el = $(el);
    var img = el.down('img.thumb');
    if(!el.altImageCreated){
      var altImage = document.createElement('img');
      altImage.onload = Effect.ToggleThumb.altLoaded.bind(img);
      img.observe('ToggleThumb:ShowAlt',Effect.ToggleThumb.showAlt);
      altImage.src = src;
      img.altSrc = src;
      el.altImageCreated = true;
    }
    if(img.effect){
      img.effect.cancel();
      img.effect = null;
      img.setStyle({opacity:1.0});
    }else{
      img.effect = new Effect.Fade(img,{
        duration:Effect.ToggleThumb.fadeDuration,
        to:0.1,
        afterFinish: function(effect){
          effect.element.effect = null;
          effect.element.isFaded = true;
          effect.element.fire('ToggleThumb:ShowAlt');
        }
      });
    }
  },

  altLoaded: function(){
    this.isSrcLoaded = true;
    this.fire('ToggleThumb:ShowAlt');
  },

  showAlt: function(event){
    if(this.isSrcLoaded && this.isFaded){
      var tmpSrc = this.src;
      this.src = this.altSrc;
      this.altSrc = tmpSrc;
      new Effect.Appear(this,{
        duration:Effect.ToggleThumb.appearDuration
      });
      this.isFaded = false;
    }
  }
}

/* Used for Date of Birth select boxes in member club */
Varien.DOBSelect = Class.create();
Varien.DOBSelect.prototype = {
    initialize: function(selector, required, format) {
        var el        = $$(selector)[0];
        this.day      = Element.select($(el), '.dob-day')[0];
        this.month    = Element.select($(el), '.dob-month')[0];
        this.year     = Element.select($(el), '.dob-year')[0];
        this.dob      = Element.select($(el), 'input')[0];
        this.required = required;
        this.format   = format || '%m/%d/%y';

        this.dob.validate = this.validate.bind(this);
    },

    validate: function() {
        var error = false;

        if (this.day.value=='' && this.month.value=='' && this.year.value=='') {
            if (this.required) {
                error = 'This date is a required value.';
            } else {
                this.dob.value = '';
            }
        } else if (this.day.value=='' || this.month.value=='' || this.year.value=='') {
            error = 'Please enter a valid full date.';
        } else {
            var date = new Date();
            if (this.day.value<1 || this.day.value>31) {
                error = 'Please enter a valid day (1-31).';
            } else if (this.month.value<1 || this.month.value>12) {
                error = 'Please enter a valid month (1-12).';
            } else if (this.year.value<1900 || this.year.value>date.getFullYear()) {
                error = 'Please enter a valid year (1900-'+date.getFullYear()+').';
            } else {
                var testDOB = this.month.value + '/' + this.day.value + '/'+ this.year.value;
                var test = new Date(testDOB);
                if (isNaN(test))
                    error = 'Please enter a valid date.';
                else
					this.dob.value = this.format.replace(/(%m|%b)/i, this.month.value).replace(/(%d|%e)/i, this.day.value).replace(/%y/i, this.year.value);
            }
        }

        if (error !== false) {
            try {
                Validation.methods['validate-dobselect'].error = Translator.translate(error);
            }
            catch (e) {
                Validation.methods['validate-dobselect'].error = error;
            }
            return false;
        }

        return true;
    }
}

Validation.addAllThese([
    ['validate-dobselect', 'Please select a valid date', function(v,elm) {
        return elm.validate();
    }]
]);


if(typeof Product=='undefined') {
    var Product = {};
}


Product.Variation = Class.create();
Product.Variation.prototype = {
  initialize: function(active,galleries,template){
    this.galleries = galleries;
    this.active = this.galleries[active];
    this.template = new Template(template);
    this._show(this.active);
  },
  showVariation: function(value){
    var variation = this.galleries[value];
    if(this.active){
      this._hide(this.active);
    }
    this._show(variation);
    this.active = variation;
  },
  _show: function(value){
    var more_views = '';
    $A(value.gallery).each(function(image){
      more_views += this.template.evaluate(image);
    }.bind(this));
    $('more-views').innerHTML = more_views;
    changeImage(value.gallery[0].image);
    $('product_id').value = value.product_id;
    $('ask-link').href = $('ask-link').href.replace(/(\d+)$/,value.product_id);
    $('product_config_'+value.product_id).show().select('select').each(function(el){
      el.disabled = false;
    });
  },
  _hide: function(value){
    $('product_config_'+value.product_id).hide().select('select').each(function(el){
      el.disabled = true;
    });
    $('more-views').innerHTML = '';
  }
}


/*
 * Prototype port of jQuery Hover Zoom 0.2 by Pierre Bertet
 */

// Hover Zoom
Product.HoverZoom = function( element, options ) {
  element = $(element);
  options = Object.extend({
    preload: false,
    previewCursor: "simple",
    cursorOpacity: 0.5,
    customPreviewElement: function(){ return new Element('div',{className:'hoverzoom-preview'}); },
    loadingClass: "hoverzoom-loading",
    customInsert: function(preview, link){ link.appendChild(preview); },
    onMouseEnter: function(){},
    onMouseLeave: function(){},
    getPreviewSource: function(element){ return element.readAttribute('href'); }
  }, options || {});

  var useCursor = (!!options.previewCursor && (options.previewCursor == "simple" || options.previewCursor == "mask"));
  var thumb = element.down('img');
  var preview = $(options.customPreviewElement());
  var source;
  var preload;
  var cursor = null;
  var isLoaded = false;
  var hover = false;

  var nWidthRatio, nHeightRatio,
    nPreviewWidth, nPreviewHeight,
    nImgWidth, nImgHeight,
    nThumbWidth, nThumbHeight,
    nCursorWidth, nCursorHeight,
    nThumbPosX, nThumbPosY,
    nMouseX, nMouseY = 0;

  // Insert Preview Element
  options.customInsert( preview, element );

  // Hide Preview Element
  preview.addClassName(options.loadingClass).hide();

  // Prevent default click event
  //element.observe('click', function(e) { e.stop() });

  // Init image loading
  element.initLoading = function() {
    // Insert preview cursor
    if( ! cursor){
      // Style cursor
      cursor = new Element('div',{
        className: "hoverzoom-cursor",
        position: "absolute",
        top: 0,
        left: 0,
        display: "none"
      });
      cursor.setOpacity(options.cursorOpacity);
      element.insert(cursor);
    }
    source = options.getPreviewSource(element);
    isLoaded = false;
    preload = $(document.createElement('img'));
    preload.style.display = 'none';
    preload.src = source;
    document.body.appendChild(preload);

    // Image load event
    function onLoadHandler() {
      // Apply background to preview element
      preview.setStyle({background: "url(" + source + ") no-repeat"});
      preview.removeClassName(options.loadingClass);

      // Preview element
      nPreviewWidth = preview.getWidth();
      nPreviewHeight = preview.getHeight();

      // Big image
      nImgWidth = preload.getWidth();
      nImgHeight = preload.getHeight();

      // Ratio
      nWidthRatio = nImgWidth / nThumbWidth;
      nHeightRatio = nImgHeight / nThumbHeight;

      // Remove loaded image
      if(preload && preload.parentNode) preload.remove();
      preload = null;

      nCursorWidth = Math.floor(nPreviewWidth/nWidthRatio);
      nCursorHeight = Math.floor(nPreviewHeight/nHeightRatio);

      // "simple"
      if (options.previewCursor == "simple") {
        cursor.setStyle({
          width: (nCursorWidth-2)+'px',
          height: (nCursorHeight-2)+'px',
          position: "absolute"
        });

      // "mask"
      } else if (options.previewCursor == "mask") {
        cursor.setStyle({
          width: nThumbWidth+'px',
          height: nThumbHeight+'px',
          background: "url("+ thumb.readAttribute("src") +") no-repeat",
          position: "absolute"
        });
      }

      if (hover) {
        cursor.show();
      }
      isLoaded = true;
    }
    if(thumb.src == source && thumb.complete)
      onLoadHandler();
    else
      preload.onload = onLoadHandler;
  } //end initLoading

  // Preload ?
  if (options.preload) element.initLoading();

  function initHover(){
    // Thumb
    nThumbWidth = thumb.getWidth();
    nThumbHeight = thumb.getHeight();

    // Set display:block to thumb
    thumb.setStyle({display:"block"});

    // Style link to fit thumb dimensions
    element.setStyle({
      position: "relative",
      display: "block",
      width: nThumbWidth + "px",
      overflow: "hidden"
    })

    .observe('mouseover', function() {
      hover = true;
      thumb.addClassName("hover");
      Element.addClassName(document.body,'hide-select');

      // Get thumb offset
      nThumbPosX = thumb.cumulativeOffset().left;
      nThumbPosY = thumb.cumulativeOffset().top;

      // Show cursor ?
      if (useCursor && cursor && source == options.getPreviewSource(element)) {
        cursor.show();
      } else {
        element.initLoading(); // Load image
      }
      preview.show();
      element.observe("mousemove", onMouseMove);
    })

    .observe('mouseout', function() {
      element.stopObserving("mousemove", onMouseMove);
      hover = false;
      thumb.removeClassName("hover");
      Element.removeClassName(document.body,'hide-select');

      if (useCursor && cursor) cursor.hide();
      preview.hide();
    });

  } // end function init
  initHover();

  // On "mousemove" event
  function onMouseMove(e) {
    if( ! isLoaded) return;

    // Mouse position
    nMouseX = e.pageX || nMouseX;
    nMouseY = e.pageY || nMouseY;

    // Preview position
    var nPreviewPosX = -( ( (nMouseX - nThumbPosX) * nWidthRatio ) - nPreviewWidth/2 );
    var nPreviewPosY = -( ( (nMouseY - nThumbPosY) * nHeightRatio ) - nPreviewHeight/2 );

    var nCursorPosX = e.pageX - nThumbPosX - nCursorWidth/2;
    var nCursorPosY = e.pageY - nThumbPosY - nCursorHeight/2;

    // X limit
    if ( nPreviewPosX > 0 ) { // left
      nPreviewPosX = nCursorPosX = 0;

    } else if ( nPreviewPosX <= ( nPreviewWidth - nImgWidth ) ) { // right
      nPreviewPosX = -nImgWidth + nPreviewWidth;
      nCursorPosX = Math.floor(nThumbWidth - nCursorWidth);
    }

    // Y limit
    if ( nPreviewPosY > 0 ) { // top
      nPreviewPosY = nCursorPosY = 0;

    } else if ( nPreviewPosY <= ( nPreviewHeight - nImgHeight ) ) { // bottom
      nPreviewPosY = -nImgHeight + nPreviewHeight;
      nCursorPosY = Math.ceil(nThumbHeight - nCursorHeight);
    }

    // Set preview position
    preview.setStyle({backgroundPosition: nPreviewPosX+"px "+nPreviewPosY+"px"});

    // Set cursor position ( "simple" )
    if (options.previewCursor == "simple") {
      cursor.setStyle({
        left: nCursorPosX + "px",
        top: nCursorPosY + "px"
      });

    // Set cursor clip ( "mask" )
    } else if (options.previewCursor == "mask") {
      cursor.setStyle({
        clip: "rect("+ nCursorPosY + "px " + (nCursorPosX + nCursorWidth) + "px " + (nCursorPosY + nCursorHeight) + "px " + nCursorPosX + "px)"
      });
    }
  } //end onMouseMove

}



/**** CREATE SLIDER FOR CHECKOUT CART ****/
function createSlider(itemId,options){
  options = Object.extend({
    onSlide: function(value) {
      var spending = $('points-spending-'+itemId);
      spending.innerHTML = spending.innerHTML.replace(/\d+/,Math.floor(value));
    }
  },options);
  if(options.step){
    var val = options.range.start;
    var vals = [];
    while(val <= options.range.end) {
      vals.push(val)
      val += options.step;
    }
    options.values = vals;
  }
  var slider = new Control.Slider('points-handle-'+itemId,'points-slider-'+itemId, options);
  slider.options.onChange = function(value) {
    if(value == this.options.sliderValue) return;
    this.setDisabled();
    this.track.setOpacity(0.5);
    this.activeHandle.setOpacity(0.5);
    var params = {
      rule_id: this.options.ruleId,
      item_id: this.options.itemId,
      points: Math.floor(value)
    };
    window.location.href = this.options.callbackUrl+'?'+Object.toQueryString(params);
  }.bind(slider);
}



