/**
* BLOG
**/

function showBox(field_id)
{
  $(field_id).show();
}
function hideBox(field_id)
{
  $(field_id).hide();
}

/*vent.observe(window, 'load', function() {
  $('tab_blind').hide();
});*/

/**
* FOOTER BAR
**/

function observeBlind(element,tab_id)
{
  var chord         = "blind_chord_" + element;
  var tab_id        = $(tab_id);
  var tab           = $(chord);
  var parent        = $('tab_list');
  var children      = parent.childElements();
  var className     = tab.className;

  // RESET ALL THE CHILD ELEMENTS CLASSES
  var size          = children.length;
  for (var i = 0; i < size; i ++)
  {
    var item = $(children[i]['id']);
    item.className  = "";
  // SET THE CURRENT TAB TO CURRENT
  }
  tab_id.className  = "current";

  if (className == 'down')
  {
    pullBlind(element);
  }
  else if (className == 'up')
  {
    closeBlind(element);
  }
  else
  {
    twitchBlind(element);
  }
}
function show_element(id)
{
  var obj = $(id);
  var type = obj.style.display;

  if(type = 'none')
  {
    //obj.style.height='0px';
    //obj.style.display='';
  }
}

function pullBlind(chord) {
  var blind = $("blind_chord_" + chord);
  Effect.BlindDown('tab_blind', { duration: 0.5 });
  blind.className = "up";
  for (i=1;i<=3;i++)
  {
    var element = $("blind_chord_" + i);
    if(i != chord)
    {
      element.className = "normal";
    }
  }
}

function closeBlind(chord) {
  var blind = $("blind_chord_" + chord);
  Effect.BlindUp('tab_blind', { duration: 0.5 });
  for (i=1;i<=3;i++)
  {
    var element = $("blind_chord_" + i);
    element.className = "down";
  }
}

function twitchBlind(chord) {
  var blind = $("blind_chord_" + chord);
  blind.className = "up";
  for (i=1;i<=3;i++)
  {
    var element = $("blind_chord_" + i);
    if(i != chord)
    {
      element.className = "normal";
    }
  }
}

function selectTab(id) {
  var children  = $('tab_blind').childElements();
  var size      = children.length;
  for (var i = 0; i < size; i ++)
  {
    var item = $(children[i]['id']);
    item.hide();
  }
  var tab_id    = id + '_tab';
  var tab       = $(tab_id);
  tab.show();

}
/**
 *
 * @access public
 * @return void
 **/
function load_id(id)
{
  var obj, type;
  obj = $('q_'+id);
  type = obj.style.display;

  if(type == 'none')
  {
    obj.style.display = '';
  }
  else
  {
    obj.style.display = 'none';
  }
}
/**
* SLIDERS
**/

/*
* function to build a horozontal slider bar with dual sliders
*/
function buildDualSlider(range,ticks,thumb,low,high,con) {

    var Dom = YAHOO.util.Dom;

    // Slider has a range of x pixels
    //var range = 300;
    var range = range;

    // No ticks for this example
    //var tickSize = 0;
    var tickSize = ticks;

    // We'll set a minimum distance the thumbs can be from one another
    //var minThumbDistance = 1;
    var minThumbDistance = thumb;

    // Initial values for the thumbs
    //var initValues = [0,300];
    var initValues = [low,high];

    // Conversion factor from 0-200 pixels to 100-1000
    // Note 20 pixels are subtracted from the range to account for the
    // thumb values calculated from their center point (10 pixels from
    // the center of the left thumb + 10 pixels from the center of the
    // right thumb)
    //var cf = 29900/(range - 20);
    var cf = con /(range - 5);

    // Set up a function to convert the min and max values into something useful
    var convert = function (val) {
        return Math.round(val * cf);
    };

    // Slider set up is done when the DOM is ready
    YAHOO.util.Event.onDOMReady(function () {
        var demo_bg = Dom.get("demo_bg"),
            info    = Dom.get("demo_info"),
            from    = Dom.get("demo_from"),
            to      = Dom.get("demo_to");

        // Create the DualSlider
        var slider = YAHOO.widget.Slider.getHorizDualSlider(demo_bg,
            "demo_min_thumb", "demo_max_thumb",
            range, tickSize, initValues);

        slider.minRange = minThumbDistance;

        // Custom function to update the text fields, the converted value
        // report and the slider's title attribute
        var updateUI = function () {

            from.value = convert(slider.minVal);
            to.value   = convert(slider.maxVal);

            var highlight = Dom.get("demo_highlight");
            var delta = slider.maxVal - slider.minVal;
            var class_name = highlight.className;

            Dom.setStyle(highlight,'width', Math.max(delta,0) + 'px');
            Dom.setStyle(highlight,'left', (slider.minVal + 4) + 'px');
            if(class_name == 'high')
            {
              Dom.setStyle(highlight,'background-position', '-' + (slider.minVal) + 'px 0px');
            }
            else if(class_name == 'inter2')
            {
              Dom.setStyle(highlight,'background-position', '-' + (slider.minVal) + 'px -88px');
            }
            else if(class_name == 'inter')
            {
              Dom.setStyle(highlight,'background-position', '-' + (slider.minVal) + 'px -66px');
            }
            else if(class_name == 'medium')
            {
              Dom.setStyle(highlight,'background-position', '-' + (slider.minVal) + 'px -22px');
            }
            else if(class_name == 'low')
            {
              Dom.setStyle(highlight,'background-position', '-' + (slider.minVal) + 'px -44px');
            }

            filterPrice(convert(slider.minVal), convert(slider.maxVal));


        };

        // Subscribe to the dual thumb slider's change and ready events to
        // report the state.
        slider.subscribe('ready', updateUI);
        slider.subscribe('change', updateUI);

    });
  }


/*
* function to build a horozontal slider bar with ticked values
*
* THIS ONE IS USED ON THE PRODCUT PAGE TO MAKE THE RING SIZE SLIDER
*
*/

function buildTickedSlider(tc,bc,scale,ki,ts,iv) {
    var Event = YAHOO.util.Event,
        Dom   = YAHOO.util.Dom,
        lang  = YAHOO.lang,
        slider,
        bg="slider-bg", thumb="slider-thumb",
        update="ring-size",
        update_object_id="ring-size-id",
        textfield="inject-value";

    // The slider can move 0 pixels up
    // var topConstraint = 0;
    var topConstraint = tc;

    // The slider can move 200 pixels down
    // var bottomConstraint = 200;
    var bottomConstraint = bc;

    // Custom scale factor for converting the pixel offset into a real value
    // var scaleFactor = 1.5;
    var scaleFactor = scale;

    var intial_value = iv;
    var size = product_data['ring_sizes'].length;
    for (var i = 0; i < size; i ++)
    {
      if(product_data['ring_sizes'][i]['object_id'] == iv)
        intial_value = i;
    }

    // The amount the slider moves when the value is changed with the arrow
    // keys
    // var keyIncrement = 20;
    //var keyIncrement = ki;

    // var tickSize = 20;
    var tickSize = ts;

    Event.onDOMReady(function() {

        slider = YAHOO.widget.Slider.getHorizSlider(bg,
                         thumb, topConstraint, bottomConstraint, tickSize);

        slider.getRealValue = function() {
            return Math.round(this.getValue() * scaleFactor);
        }

        slider.subscribe("change", function(offsetFromStart) {

            var fld = Dom.get(update);
            var object_fld = Dom.get(update_object_id);
            var ring_size_display = Dom.get('ring_size_display');

            // use the scale factor to convert the pixel offset into a real
            // value
            var actualValue = product_data['ring_sizes'][slider.getRealValue()]['name'].unescapeHTML();
            var actualObjectId = product_data['ring_sizes'][slider.getRealValue()]['object_id'].unescapeHTML();

            // update the text box with the actual value
            fld.value = actualValue;
            ring_size_display.innerHTML = actualValue;
            object_fld.value = actualObjectId;

            // Update the title attribute on the background.  This helps assistive
            // technology to communicate the state change
            Dom.get(bg).title = actualValue;

            updatePrice();

        });

        slider.subscribe("slideStart", function() {
                YAHOO.log("slideStart fired", "warn");
            });

        slider.subscribe("slideEnd", function() {
                YAHOO.log("slideEnd fired", "warn");
            });

        // set the slider to the initial position.
        var v = parseFloat(intial_value, 10);
        v = (lang.isNumber(v)) ? v : 0;
        slider.setValue(Math.round(v/scaleFactor));

    });
};

/**
* Builds the vertical sliders used on the product view
**/
/*
function buildVerticleSlider(up,down,min,max,tick,slide_bg,slide_thumb,d_val,calc_input,subject,initial) {

    var Event = YAHOO.util.Event;

    // the slider can move up 200 pixels
    var upLimit   = up;

    // and down 0 pixels
    var downLimit = down;

    // Create the Slider instance
    var slider = YAHOO.widget.Slider.getVertSlider(slide_bg, slide_thumb, upLimit, downLimit, tick);

    // Add a little functionality to the instance
    YAHOO.lang.augmentObject(slider, {

        // A custom value range for the slider
        minValue : min,
        maxValue : max,

        // A method to retrieve the calculated value, per the value range
        getCalculatedValue : function () {

            // HERE'S THE MAGIC
            // invert the offset value so "real" values increase as the
            // slider moves up
            var offset = -1 * this.getValue();

            // Convert the offset to a value in our configured range
            var conversionFactor =
                    (this.maxValue - this.minValue) /
                    (this.thumb.topConstraint + this.thumb.bottomConstraint);

            return Math.round(offset * conversionFactor) + this.minValue;
        }
    });

    Event.onDOMReady(function() {
      //set the initial value
      initial_value = 0;
      var size = subject.length;
      for (var i = 0; i < size; i ++)
      {
        if(subject[i]['name'])
        {
          if(parseInt(subject[i]['name']['object_id']) == parseInt(initial))
          {
            initial_value = i;
          }
        }
        else
        {
          if(parseInt(subject[i]['object_id']) == parseInt(initial))
          {
            initial_value = i;
          }
         }
      }
      var offset_calc = ( tick * initial_value ) * -1;
      slider.setValue(Math.round(offset_calc));
    });

    // display the native offset and the calculated while sliding
    var calc_span   = YAHOO.util.Dom.get(d_val);
    var calc_input  = YAHOO.util.Dom.get(calc_input);

    // UPDATES THE UI
    slider.subscribe('change', function (offsetFromStart) {
        var pointer     = this.getCalculatedValue();
        if(subject[pointer]['name']['name'])
          var real_value  = subject[pointer]['name']['name'].unescapeHTML();
        else
          var real_value  = subject[pointer]['name'].unescapeHTML();
        calc_span.innerHTML   = real_value;
        calc_input.value      = real_value;
        updatePrice();
    });
}
*/

function buildHorizontalSlider(up,down,tick,scale,slide_bg,slide_thumb,d_val,calc_input,subject,initial) {
  var Event = YAHOO.util.Event,
        Dom   = YAHOO.util.Dom,
        lang  = YAHOO.lang,
        slider,
        bg=slide_bg, thumb=slide_thumb,
        update=d_val,
        update_object_id=calc_input;

    // The slider can move 0 pixels up
    // var topConstraint = 0;
    var topConstraint = down;

    // The slider can move 200 pixels down
    // var bottomConstraint = 200;
    var bottomConstraint = up;

    // Custom scale factor for converting the pixel offset into a real value
    // var scaleFactor = 1.5;
    var scaleFactor = scale;

    var tickSize = tick;

    Event.onDOMReady(function() {

        slider = YAHOO.widget.Slider.getHorizSlider(bg,
                         thumb, topConstraint, bottomConstraint, tickSize);

        slider.getRealValue = function() {
          return Math.round(this.getValue() * scaleFactor);
        }

        slider.subscribe("change", function(offsetFromStart) {

            var fld = Dom.get(update);
            var object_fld = Dom.get(update_object_id);

            if(subject[slider.getRealValue()]['name']['name'])
              var real_value  = subject[slider.getRealValue()]['name']['name'].unescapeHTML();
            else
              var real_value  = subject[slider.getRealValue()]['name'].unescapeHTML();

            // update the text box with the actual value
            fld.innerHTML = real_value;
            object_fld.value = real_value;

            // Update the title attribute on the background.  This helps assistive
            // technology to communicate the state change
            Dom.get(bg).title = real_value;

            // runs the price calculation on the page
            updatePrice();

        });

        slider.subscribe("slideStart", function() {
                YAHOO.log("slideStart fired", "warn");
            });

        slider.subscribe("slideEnd", function() {
                YAHOO.log("slideEnd fired", "warn");
            });

        var size = subject.length;
        for (var i = 0; i < size; i ++)
        {
          if(subject[i]['name'])
          {
            if(parseInt(subject[i]['name']['object_id']) == parseInt(initial))
            {
              var initial_value = i;
            }
          }
          else
          {
            if(parseInt(subject[i]['object_id']) == parseInt(initial))
            {
              var initial_value = i;
            }
           }
        }

        // set the slider to the initial position.
        var v = parseFloat(initial_value, 10);
        v = (lang.isNumber(v)) ? v : 0;
        slider.setValue(Math.round(v/scaleFactor));

    });
}


/**
* PRODUCT PRICE CALCULATIONS
**/

function updatePrice()
{
  /*
  * product_data is defined in the page as a JSON array
  */

  var price           = 0;
  var price_reduction = 0;
  var price_rrp       = 0;
  var markup_value    = 0;
  var form            = $('update_price');
  var reduction       = product_info['reduction'];
  var rrp_percen      = product_info['rrp'];
  

  if(form['type'])
  {
    var product_type       = form['type'];
    var product_type_value = $F(product_type);
  }

  if(form['ring-size'])
  {
    var ring_size       = form['ring-size'];
    var ring_value      = $F(ring_size);
  }

  if(form['carat'])
  {
    var carat           = form['carat'];
    var carat_value     = $F(carat);
  }

  if(form['band_width'])
  {
    var bandwidth       = form['band_width'];
    var bandwidth_value = $F(bandwidth);
  }

  if(form['clarity'] && form['colour'] && form['diamond_shape'])
  {
    var clarity         = form['clarity'];
    var colour          = form['colour'];
    var diamond_shape   = form['diamond_shape'];
  }

  if(form['material'])
    var material_value  = Form.getInputs(form,'radio','material').find(function(radio) { return radio.checked; }).value;

  if(diamond_shape && clarity && colour)
  {
    var diamond_shape   = $F(diamond_shape);
    var clarity_value   = $F(clarity);
    var colour_value    = $F(colour);
  }

  // Calculate ring cost
  if(product_data['ring_sizes'])
  {
	  var size = product_data['ring_sizes'].length;
    for (var i = 0; i < size; i ++)
    {
	    if (product_data['ring_sizes'][i]['name'] == ring_value)
	    {
	      var ring_price = product_data['ring_sizes'][i]['value'];
	    }
	  }
  }

	// Calculate materials cost
	if(product_data['materials'])
	{
    var size = product_data['materials'].length;
    for (var i = 0; i < size; i ++)
    {
	    if (product_data['materials'][i]['object_id'] == material_value)
	    {
	      var materials_price = product_data['materials'][i]['value'];
        var setting_value = product_data['materials'][i]['setting_value'];

	      // Some UI bits
	      if(image_data['gold_images'] >= 1)
	      {
	        if(product_data['materials'][i]['is_gold'] == 1)
	        {
	          hideDiv('non_gold');
	          showDiv('gold');
	        }
	        else
	        {
	          hideDiv('gold');
	          showDiv('non_gold');
	        }
	      }

	    }
	  }
  }

  // Calculate bandwidth cost
	if(product_data['band_widths'])
	{
    var size = product_data['band_widths'].length;
    for (var i = 0; i < size; i ++)
    {
	    if (product_data['band_widths'][i]['name'] == bandwidth_value)
	    {
	      var bandwidth_price = product_data['band_widths'][i]['value'];
	    }
	  }
  }

  // Calculate the markup
	if(product_data['markups'])
	{
    var size = product_data['markups'].length;
    for (var i = 0; i < size; i ++)
    {
	    if (product_data['markups'][i]['lowsize'] <= carat_value && product_data['markups'][i]['highsize'] >= carat_value)
	    {
	      var markup_value = product_data['markups'][i]['percentage'];
	    }
	  }
  }

  //alert(product_data['rate']);

	// Calculate diamond cost
  if(product_data['diamond_prices'])
  {
    var size = product_data['diamond_prices'].length;
    for (var i = 0; i < size; i ++)
    {
      if(diamond_shape && clarity_value && colour_value)
      {
	      if (product_data['diamond_prices'][i]['shape'] == diamond_shape && product_data['diamond_prices'][i]['clarity'] == clarity_value && product_data['diamond_prices'][i]['colour'] == colour_value && parseFloat(product_data['diamond_prices'][i]['lowsize']) <= parseFloat(carat_value) && parseFloat(product_data['diamond_prices'][i]['highsize']) >= parseFloat(carat_value))
	      {
	        var diamond_price   = product_data['diamond_prices'][i]['price'];
	        diamond_price       = diamond_price * carat_value;
	        markup_cost         = (diamond_price/100) * markup_value;
	        diamond_price       = diamond_price + markup_cost;
	        diamond_price       = diamond_price / product_data['rate'];
	      }
	    }
	    else
	    {
	      if(product_data['diamond_prices'][i]['name'] == carat_value)
	      {
	        var diamond_price = product_data['diamond_prices'][i]['value'];
	      }
	    }
	  }
	}

	var base_price      = 0;
	var material_chunk  = 0;
	var bandwidth_chunk = 0;
	var diamond_chunk   = 0;

  // Calculates the core product price
  if(ring_price)
  {
    base_price = parseInt(ring_price);
  }
  else
  {
    base_price = parseInt(product_data['base_price']);
  }
  // Factors in the material weighting if applicable
  if(materials_price)
  {
    material_chunk = (base_price/100) * parseInt(materials_price);
    material_chunk += parseInt(setting_value);
  }
  // Factors in the band width weighting if applicable (wedding rings)
  if(bandwidth_price)
  {
    bandwidth_chunk = ((base_price + material_chunk)/100) * parseInt(bandwidth_price);
  }
  // Adds the price of the stone if applicable
  if(diamond_price)
  {
    diamond_chunk = parseInt(diamond_price);
  }

  // Add it all together!
  if(product_type_value == 'voucher') // stops the voucher price being rounded to a price marker
  {
    price = base_price + material_chunk + bandwidth_chunk + diamond_chunk;
  }
  else
  {
    price = base_price + material_chunk + bandwidth_chunk + diamond_chunk;
    //price = convertToPriceMarker(base_price + material_chunk + bandwidth_chunk + diamond_chunk);
  }

  // add reduction on final price!
  if(reduction > 0)
  {
    price_reduction = (price - ((price / 100)*reduction));
    price_reduction = price_reduction.toFixed(2);
    price_reduction = addCommas(price_reduction);
  }
  
  price_rrp = price * (1 + (rrp_percen/100));
  price_rrp = price_rrp.toFixed(2);
  $('price_rrp').innerHTML = '<strike>MRP: &pound;'+addCommas(price_rrp)+'</strike>';
  
  price = price.toFixed(2);

  price = addCommas(price);

  if(diamond_shape && clarity_value && colour_value)
  {
    if(diamond_chunk <=0)
    {
      $('price').innerHTML = 'Not&nbsp;Available';
      $('sprice').value = 'ERROR';
      if(reduction > 0)
      {
        $('price_reduction').innerHTML = 'Not&nbsp;Available';
      }
    }
    else
    {
      $('sprice').value = price;
      if(reduction > 0)
      {
        $('price').innerHTML = '<strike>Our Price: <strong>&pound;'+price+'</strong></strike>';
        $('price_reduction').innerHTML = 'Now: &pound;'+price_reduction;
      }
      else
      {
        $('price').innerHTML = '&pound;'+price;
      }
    }
  }
  else
  {
    $('sprice').value = price;
    if(reduction > 0)
    {
      $('price').innerHTML = '<strike>Our Price: <strong>&pound;'+price+'</strong></strike>';
      $('price_reduction').innerHTML = 'Now: &pound;'+price_reduction;
    }
    else
    {
      $('price').innerHTML = 'Our Price: <strong>&pound;'+price+'</strong>';
    }
  }
}

function convertToPriceMarker(price)
{

  var price_marker  = 0;
  var marker        = 0;
  var price         = parseFloat(price);
  var numbers       = new Array();

  numbers[0]        = 1000000000;
  numbers[1]        = 100000000;
  numbers[2]        = 10000000;
  numbers[3]        = 1000000;
  numbers[4]        = 100000;
  numbers[5]        = 10000;
  numbers[6]        = 1000;
  numbers[7]        = 100;

  for(i in numbers)
  {
    if(isNaN(numbers[i]) == false)
    {
      price_marker = price - (Math.floor(price/numbers[i]) * numbers[i]);
    }
  }
  if(price_marker >= 0 && price_marker < 35)
  {
    marker = -price_marker - 5;
  }
  if(price_marker >= 36 && price_marker < 69)
  {
    marker = -price_marker + 45;
  }
  if(price_marker >= 69 && price_marker < 100)
  {
    marker = -price_marker + 95;
  }

  var result = price + marker;

  if(result<0)
  {
    result = price
  }

  return result;

}

function addCommas(nStr)
{
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}

/**
* PRODUCT IMAGE CODE
**/

function hideDiv(id)
{
  if($(id))
    $(id).setStyle({ display: 'none' });
}

function showDiv(id)
{
  if($(id))
    $(id).setStyle({ display: 'block' });
}

function swapImage(src,big,id)
{
  $(id).setAttribute('src', src);
  $(id).setAttribute('jqimg', big);
}

/**
* CATEGORY, PRODUCT DETAILS HOVER
**/

function hideAll()
{
  var items = $$('div.productInfo');
  var size = items.length;
  for (var i = 0; i < size; i ++)
  {
    var item = $(items[i]['id']);
    item.addClassName('hide');
  }
}


/**
* FOOTER BAR
**/

function initBar() {
  if ($('bottom') != null) {
    window.onscroll = setPosition;
    window.onresize = setPosition;

    var clientHeight = document.documentElement.clientHeight;
    if (clientHeight == 0) {
      clientHeight = document.body.clientHeight;
    }

    total = clientHeight - $('bottom').offsetHeight;
    $('bottom').style.top = total + "px";
  }
}

function setPosition(e) {
  var clientHeight = document.documentElement.clientHeight;
  if (clientHeight == 0) {
    clientHeight = document.body.clientHeight;
  }
  scrollOffset = getScrollXY();
  total = clientHeight - scrollOffset[1] - $('bottom').offsetHeight;
  $('bottom').style.top = total + "px";
}

function getScrollXY() {
  var scrOfX = 0, scrOfY = 0;
  if( typeof( window.pageYOffset ) == 'number' ) {
    //Netscape compliant
    scrOfY = window.pageYOffset;
    scrOfX = window.pageXOffset;
  } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
    //DOM compliant
    scrOfY = document.body.scrollTop;
    scrOfX = document.body.scrollLeft;
  } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
    //IE6 standards compliant mode
    scrOfY = document.documentElement.scrollTop;
    scrOfX = document.documentElement.scrollLeft;
  }
  return [ scrOfX, scrOfY ];
}
