


/**
* Update our product page when we select a product variation
* Set up our tab control
*/
$(document).ready(function()
{
    $(".variation_option_definition").each(function(i){
        $(this).bind("change",load_product_variation);
    });

    $(".variation_attribute").each(function(i){
        $(this).bind("change",set_attributes);
    });

    $('.tabs').tabs();

});

function show_in_stock()
{
    $('#add_to_cart').css('background-image','url(/img/btn-add-to-cart.gif)');
    $('#quantity, #add_to_cart').removeAttr('disabled');
}

function show_no_stock()
{
    $('#add_to_cart').css('background-image','url(/img/btn-add-to-cart-off.gif)');
    $('#quantity, #add_to_cart').attr('disabled','disabled');
}

function set_attributes()
{
    $('#availability').html('');
    $('#sku').html('Loading ...');
    show_no_stock();

    var selected_attributes = {};
    
    $(".variation_attribute").each(function(i){
    
        // attribute_values[regexThisBit] 
        var match = /\[([\w]+)\]/i.exec(this.name);
        var name = match[1];

        selected_attributes[name] = this.value;
    });

    selected_attributes['id'] = $("#variation_id").val();

    $.get('/product/ajax_set_attributes',selected_attributes,update_page);
}

/**
* Updates product variation fields on the page using Ajax with jquery
*/
function load_product_variation()
{
    $('#sku').html('Loading ...');
    show_no_stock();
    
    //Currently selected variation_definition_id => variation_option_value
    var selected_variations = new Object();

    //Name of the select box we just changed
    var changed_select_name = this.name;

    //Get all the current selected variations above and including the changed one
    //var above_selected_option = true;
    $(".variation_option_definition").each(function(i){

        //if(above_selected_option)
        selected_variations[this.name] = this.value;

        //if(this.name == changed_select_name)
        //above_selected_option = false;
    });

    selected_variations['product_id'] = $("#product_id").val();

	//console.debug(selected_variations);

    //Update all of our selection boxes with the new data
    $.get('/product/ajax_get_product_variation',selected_variations,update_page);
}

function update_page(response)
{
    $('variationoption',response).each(function(i)
    {
        var variation_option_name = $('name',this).text();
        
        if(variation_option_name.substr(0,9) != 'is_custom')
        {
        
            var select_input = $('#option_'+variation_option_name).get(0);

            //Clear all the select options
            select_input.options.length = 0;

            //Repopulate the options
            $('option',this).each(function(select_index){
                                                                 //text                                               //value 
                select_input.options[select_index] = new Option( unescape($('value',this).text().replace(/\+/g," ")) ,$('value',this).text() );
            });

            select_input.selectedIndex = $('selectedindex',this).text();
        }
        else
        {
            //rmcd specific
            console.log('skipping '+variation_option_name+' as its a custom field see the rmcd_options table');
        }
    });

    //Update product page details
    $('#variation_id').attr('value',$('variation>id',response).text());
    //$('#availability').html($('variation>availability',response).text());
    $('#sku').html($('variation>sku',response).text());
    
    var price = parseFloat( $('variation>price',response).text() );
    var sale_price = parseFloat( $('variation>sale_price',response).text() );
    var non_sale_price = parseFloat( $('variation>normal_price',response).text() );
    var retail_price = parseFloat( $('variation>retail_price',response).text() );

    if(sale_price>0)
    {
        var save = (retail_price > 0) ? retail_price - sale_price : non_sale_price - sale_price;

    }else
    {

        var save = (retail_price > 0 && retail_price > price) ? retail_price - price : 0; 
    }

    $('#save_row').show();
    $('#regular_row').show();
    $('#price_total').css('color','#A3562B');

    if( retail_price > 0 && price < retail_price)
    {   
        $('#regular_price').html(retail_price);
        $('#regular_price').formatCurrency({useHtml:true});
    }
    else if( non_sale_price > 0 && sale_price > 0 && sale_price < non_sale_price ){
        $('#regular_price').html(non_sale_price);
    }
    else{
        $('#regular_row').hide();
    }


    if(sale_price > 0 && sale_price < non_sale_price ){
        $('#price_total').css('color','#C50404');
        $('#price').html(sale_price);
    }
    else{
        $('#price').html(price);
    }
      
    if(save > 0){
        $('#you_save').html(save);
    }
    else
    {
        $('#save_row').hide();
    }
   
    $('#price_total').html(price);

    $('#price_total').formatCurrency({useHtml:true});
    $('#regular_price').formatCurrency({useHtml:true});
    $('#price').formatCurrency({useHtml:true});
    $('#you_save').formatCurrency({useHtml:true});
        
        
    if($('variation>isavailable',response).text() == 1)
    show_in_stock();
    else
    show_no_stock();
}

/**
* Updates product rating on the page using DHTML
*/
function rate(product_id,rating)
{

    $.get('/product/ajax_set_product_rating/'+product_id+'/'+rating,function(response){
        $("#current_rating").css("width", $('average_rating',response).text()+'px');
        $("#selected_rating").css("width", $('selected_rating',response).text()+'px');
        $('#number_of_votes').html($('quantity',response).text());
    });
}

/**
 * Formats currency 
 */
(function($) {
	
	$.fn.formatCurrency = function(settings) {
		settings = jQuery.extend({
		    name: "formatCurrency",
		    useHtml: false,
		    symbol: '$',
		    global: true
		}, settings);
		
		return this.each(function() {
		    var num = "0";
		    num = $(this)[settings.useHtml ? 'html' : 'val']();
		    num = num.replace(/\$|\,/g, '');
		    if (isNaN(num))
		        num = "0";
		    sign = (num == (num = Math.abs(num)));
		    num = Math.floor(num * 100 + 0.50000000001);
		    cents = num % 100;
		    num = Math.floor(num / 100).toString();
		    if (cents < 10)
		        cents = "0" + cents;
		    for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++)
		        num = num.substring(0, num.length - (4 * i + 3)) + ',' + num.substring(num.length - (4 * i + 3));
		
		    $(this)[settings.useHtml ? 'html' : 'val'](((sign) ? '' : '-') + settings.symbol + num + '.' + cents);
		});
	};

  // Remove all non numbers from text
  $.fn.toNumber = function(settings) {
		settings = jQuery.extend({
		    name: "toNumber",
		    useHtml: false,
		    global: true
		}, settings);  

    return this.each(function() {
      var method = settings.useHtml ? 'html' : 'val';   
      $(this)[method]($(this)[method]().replace(/[^\d\.]/g, ''));
    });
  };

})(jQuery);
