// JavaScript Document
var SlideList = new Class({
	initialize: function(menu, options) {
		this.setOptions(this.getOptions(), options);

		this.menu = $(menu), this.current = this.menu.getElement('li.current');

        var firstLI;

		this.menu.getElements('li').each(function(item, index){
          if( index == 0 ) firstLI = item;
			item.addEvent('mouseover', function(){ this.moveBg(item); }.bind(this));
			item.addEvent('mouseout', function(){ this.moveBg(this.current); }.bind(this));
			item.addEvent('click', function(event){ this.clickItem(event, item); }.bind(this));
		}.bind(this));

		this.back = new Element('li').addClass('background').adopt(new Element('div').addClass('top')).injectInside(this.menu);
		this.back.fx = this.back.effects(this.options);
		if(!this.current)
        {
          this.current = firstLI;
        }
        this.setCurrent(this.current);
	},
	
	setCurrent: function(el, effect){
      if( !el ) return;
		this.back.setStyles({top: (el.offsetTop)+'px', width: (el.offsetWidth)+'px'});
		(effect) ? this.back.effect('opacity').set(0).start(1) : this.back.setOpacity(1);
		this.current = el;
	},
	
	getOptions: function(){
		return {
			transition: Fx.Transitions.sineInOut,
			duration: 500, wait: false,
			onClick: Class.empty
		};
	},

	clickItem: function(event, item) {
		if(!this.current) this.setCurrent(item, true);
        item.blur();
		this.current = item;
		this.options.onClick(new Event(event), item);
	},

	moveBg: function(to) {
		if(!this.current) return;
		this.back.fx.custom({
			top: [this.back.offsetTop, to.offsetTop],
			width: [this.back.offsetWidth, to.offsetWidth]
		});
	}
});

SlideList.implement(new Options);
// Menu
 window.addEvent('domready', function() {

  var coll_mainnav = $('mainnav'), coll_linesnav = $('linesnav');

  current_url = document.location.href;
  current_url = current_url.replace( /^http:\/\/(www\.)?terraverdeflooring.com/, '' );
  var current_anchor;

  $('main_nav').getElements('a').each( function(anchor) {
    anchor_url = anchor.href.replace( /^http:\/\/(www\.)?terraverdeflooring.com/, '' );

    if( anchor_url == current_url )
    {
      current_anchor = anchor;
    }

  });  

  if( current_anchor )
  {
    current_anchor.getParent().addClass('current');
  }

  new SlideList( $('main_nav'), {transition: Fx.Transitions.Quad.easeOut, duration: 250});

//  new SlideList( coll_linesnav, {transition: Fx.Transitions.backOut, duration: 600});
 });
/**
 * Ecommerce Cost Calculator
 * @description: Tool for Coordinating Calculated Price from Input Quantity Values with Callback HTML Element
 */

var EcommerceCostCalculator = new Class({
  initialize: function( source_el, target_el, fmin_quantity, funit_cost ) {
    this.source = $(source_el);
    this.target = $(target_el);
    this.min_quantity = fmin_quantity;
    this.unit_cost = funit_cost;

    this.source.addEvent( 'focus', function() {
      this.target.old_value = this.target.getText().replace(/[^\.\d]/g, '' );
    }.bind(this) );

    this.source.addEvent( 'keydown', function(event) {
      event = new Event(event);
      this.source.fireEvent( 'beforeupdate' );
      if( event.key == 'enter' ) this.source.blur();
      else
      {
        $clear(this.source.beforeblurPoller);
      }
    }.bind(this) );

    this.source.addEvent( 'beforeupdate', function() {
      this.prevValue = this.value;
    }.bind(this.source) );

    this.source.beforeblur = function() {
      if( this.prevValue != this.value ) { this.fireEvent('updated'); }
      this.blur(); this.focus();
    }.bind(this.source);

    this.source.addEvent( 'keyup', function(event) {
      this.set_cost( this.source.value );
      this.source.beforeblurPoller = this.source.beforeblur.delay(750);
    }.bind(this) );

    this.source.addEvent( 'blur', function() {
      this.set_cost_min( this.source.value );
    }.bind(this) );
  },

  removeChars: function( fvalue, pattern ) {
    return fvalue.replace( new RegExp(pattern, "g"), "" )
  },

  makeOnlyDigits: function( fvalue ) {
    if(!isNaN(fvalue) ) return parseFloat(fvalue);

    return this.removeChars( fvalue, "[^\\d\.]" );
  },

  round: function( num ) {
	var rnum = num;
	var rlength = ( arguments.length > 1 )? arguments[1] : 0; // The number of decimal places to round to
	if (rnum > 8191 && rnum < 10485) {
		rnum = rnum-5000;
		var newnumber = Math.round(rnum*Math.pow(10,rlength))/Math.pow(10,rlength);
		newnumber = newnumber+5000;
	} else {
		var newnumber = Math.round(rnum*Math.pow(10,rlength))/Math.pow(10,rlength);
	}
	return newnumber.toFixed(rlength);
  },

  calc_cost: function( fquantity ) {
    val = fquantity * this.unit_cost;
    return val.toFixed(2);
//    return this.round( fquantity * this.unit_cost, 2 );
  },

  set_cost: function( fquantity ) {
    quantity = this.makeOnlyDigits( fquantity );

    this.target.setText( '$'+this.calc_cost(quantity) );
  },

  set_cost_min: function() {
    quantity = this.makeOnlyDigits( this.source.value );
    quantity = Math.ceil( Math.max( this.min_quantity, quantity ) );

    new_value = this.calc_cost(quantity);
    old_value = this.target.old_value;
    difference = (new_value-old_value).toFixed(2);

    this.target.setText( '$'+new_value );
    this.target.fireEvent( 'updated', difference );
    
    this.target.old_value = this.target.getText().replace(/[^\.\d]/g, '' );
  }

});

var SqftPriceCalculator = EcommerceCostCalculator.extend({
  initialize: function( source_el, target_el, target_boxes_el, fsqft_per_box, funit_cost ) {
    this.parent(source_el, target_el, fsqft_per_box, funit_cost);

    this.targetBoxes = $(target_boxes_el);

    this.targetBoxes.addEvent( 'focus', function() { this.targetBoxes.blur(); }.bind(this) );

    this.sqft_per_box = fsqft_per_box;
    this.source.removeEvents('blur');
    this.source.addEvent( 'blur', function() {
      this.set_cost_min_by_boxes();
    }.bind(this) );
  },

  set_cost_min_by_boxes: function() {
    this.set_num_boxes();
    num_sqft = this.targetBoxes.value * this.sqft_per_box;

    this.source.value = num_sqft;

    this.set_cost_min();

    this.targetBoxes.fireEvent( 'updated' );
  },

  set_cost_by_boxes: function() {
    this.set_num_boxes();

    num_sqft = this.targetBoxes.value * this.sqft_per_box;

    //this.source.value = num_sqft;

    this.parent.set_cost( num_sqft );
  },

  set_num_boxes: function() {
    this.targetBoxes.prevValue = this.targetBoxes.value;
    this.targetBoxes.value = Math.ceil( this.source.value / this.sqft_per_box );
    this.targetBoxes.lastDifference = this.targetBoxes.value - this.targetBoxes.prevValue;
  }
});


// JavaScript Document

var CartAjax = Ajax.extend({
  initialize: function() {
    url = "#";

    options = {};

    if( arguments.length > 1 )
      options = arguments[1];

    this.parent(url, options);
  },

  // Adds the Item
  addItem: function( url, options ) {
    updateData = options['updateData'];

    qs = Object.toQueryString( updateData );
    options['data'] = qs;
    this.setOptions( options );

    this.url = url;

    this.request();
  },

  // Update the Item
  updateItem: function( url, options ) {
    updateData = options['updateData'];

    qs = Object.toQueryString( updateData );
    options['data'] = qs;
    this.setOptions( options );

    this.url = url;

    this.request();
  },

  // Deletes the Item
  deleteItem: function( url, options ) {
    deleteData = options['deleteData'];

    qs = Object.toQueryString( deleteData );
    options['data'] = qs;
    this.setOptions( options );

    this.url = url;

    this.request();
  }
});


// Nav Options for /cart/view

// Extends SlideList Class
var CartSectionsSlidelist = SlideList.extend({
  initialize: function(menu, options) {
    this.parent(menu, options);
    this.menu.getElements('li').each(function(item, index){
          if( index == 0 ) firstLI = item;
			item.addEvent('mouseover', function(){ this.moveBg(item); }.bind(this));
			item.addEvent('mouseout', function(){ this.moveBg(this.current); }.bind(this));
			item.addEvent('click', function(event){ this.clickItem(event, item); this.setActiveSection(event, item); }.bind(this));
	}.bind(this));

    this.ajax = new Ajax( '/includes/etc/cart/ajax.php', { method: 'get', evalScripts:true, onComplete: function() { this.setSectionContent(); }.bind(this) } );

  },

  getSection: function( uri ) {
    this.ajax.cancel();
    var d = new Date();
    this.ajax.send(this.ajax.url, 't='+d.getTime()+'&uri='+uri);
  },

  setSectionContent: function() {
    $('cart_section_cont').removeClass('ajax_loader_bar');
    $('cart_section_cont').setHTML( this.ajax.response.text );
    this.ajax.cancel();
  },

  setActiveSection: function( e, section_handle ) {
    new Event(e).stop();
    
    anc = section_handle.getElement('.handle');
    anc.blur();

    uri = anc.href.replace( /^http:\/\/(www\.)?terraverdeflooring.com/, '' );

    if( this.currentSectionUri == uri ) return;

    $('cart_section_cont').setHTML('');
    $('cart_section_cont').addClass('ajax_loader_bar');
    $('cart_section_cont').setHTML('<br><br>Loading Content...<br><br><br><br><br><br>');

    this.getSection( uri );
    this.currentSectionUri = uri;

   // alert( this.getFragment(anc.href) );
  },

  getFragment: function( url ) {
    pos = url.indexOf("#");

    if( pos < 0 ) return '';

    return url.substr( pos+1, url.length-(pos+1) );
  }
});

window.addEvent('domready', function() {
  current_url = document.location.href;
  current_url = current_url.replace( /^http:\/\/(www\.)?terraverdeflooring.com/, '' );
  var current_anchor;

  $('cart_section_links_nav').getElements('a').each( function(anchor) {
    anchor_url = anchor.href.replace( /^http:\/\/(www\.)?terraverdeflooring.com/, '' );

    if( anchor_url == current_url ) { current_anchor = anchor; }
  });

  if( current_anchor ) { current_anchor.getParent().addClass('current'); }
  new CartSectionsSlidelist( $('cart_section_links_nav'), {transition: Fx.Transitions.Quad.easeOut, duration: 250});

  // Streamlined Cart Re-Poster
  $('tvSubmitButton').addEvent( 'click', function(event) {
    new Event(event).stop();

    url = this.href;
    var RemoteCartSystemData;
    new Ajax( url, {
      method:'get',
      onComplete: function() {
        try {
          if( this.response.text.match(/error/i) ) throw( {'message':this.response.text} );
          RemoteCartSystemData = Json.evaluate( this.response.text );
          RemoteCartSystemForm = new Element( 'form' );
          for( attribute in RemoteCartSystemData.attributes )
            RemoteCartSystemForm[attribute] = RemoteCartSystemData.attributes[attribute];
          RemoteCartSystemForm.setHTML( RemoteCartSystemData.html );
          document.body.appendChild( RemoteCartSystemForm );
          RemoteCartSystemForm.submit();
        } catch( e ) {
          //alert( e.message );
        }
      }
    }).request();
  });

});




