/**
* Update our product page when we select a product variation
* Set up our tab control
*/
$(document).ready(function()
{
    if($('#alternateImageCarousel').length)
    {
    	$('#alternateImageCarousel').jcarousel({
    		scroll: 1
    	});
    }

    $(".variation_option_definition").livequery('change',load_product_variation);
    
    $("#add_to_wishlist_link").click(function(){
    	if($("#option_cancer_color_id").val() != "NULL")
    	{
    		$("#prod_form").attr("action",$("#add_to_wishlist_link").attr("rel")); 
    		$("#prod_form").submit();
    	}
    	else
    	{ return false; }
    });
     
	//Add to the cart is now AJAX...
    $('#add_to_cart').click(function(){
    
    	var option_dropdown_value = $('select.variation_option_definition').val();
		if(option_dropdown_value == 'NULL')
		{
			$('div#choose_option_error').remove();
			html = '<div id="choose_option_error" style="padding: 5px;background-color:#FFFFDD;color: #CC0000; font-size: 10px;clear: left; width: 99%">Please choose an option&nbsp;&nbsp;';
			html +=  '<img src="/img/red-x-icon.jpg" style="cursor: pointer;" onclick="$(\'#choose_option_error\').remove();" alt="close"/></div>';
			$('div#product_right').append(html);
			return false;	
		}
    
    	var prod_id = $('#product_id').val();
    	var var_id = $('#variation_id').val();
    	var qty = $('#quantity').val();
    	
    	/*
    	var custom = '';
    	$('#customization_lo input').each(function(i,e){
			if(!($(this).val() == ''))
				custom =custom +'~'+$(this).val();
		})
		;*/
   
    	$.blockUI();
    	$.post("/product/add_to_cart", { product_id: prod_id, variation_id: var_id, quantity: qty }, update_page_after_cart );
    	
    	return false;
    });
    
	
	/*if($(".variation_option_definition").length > 0){ //have select boxes, disable this until they are used
	$('#quantity, #add_to_cart').attr('disabled','disabled');
	}*/
	/*$("#id").bind('keyup',function(){
		
	}*/
	
	var $tabs = $('#product_tabs').tabs();
	
	//when you click on 'Read More' link in review box in description tab this is whats happening:
	$('#review_read_more_link').click(function(){
		
 		$tabs.tabs('select', '#customerReviews');

		return false;
	});

});

function show_in_stock()
{
    $('#quantity, #add_to_cart').removeAttr('disabled');
	$('#no_stock_message').hide();
	$('#add_to_cart').show();
}

function show_no_stock()
{
	$('#quantity, #add_to_cart').attr('disabled','disabled');
    $('#add_to_cart').hide();
	$('#no_stock_message').show();
}

/**
* Updates product variation fields on the page using Ajax with jquery
*/
function load_product_variation()
{
    $('#sku').html('Loading ...');

	$('#quantity, #add_to_cart').attr('disabled','disabled');

	$('#main_image').attr('src','/img/ajax-loader.gif');
    


    //Currently selected variation_definition_id => variation_option_value
    var selected_options = {};

	try{
		//can't have this as a param as event is first arg GRRR
		for( i in extra_options ){
			selected_options[i] = extra_options[i];
	}
	}catch(e){}

    $(".variation_option_definition").each(function(i){

        selected_options[this.name] = this.value;
    });
    
    //selected_options['swatch'] = 'T120_LIM';

    selected_options['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_options,update_page);
}

function update_page(response)
{
    //Set select boxes
    $('#product_options_template').html( $('variationoptions',response).text() );
    
    //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() );
    var wholesale =  $('variation>wholesale_price',response).text();
    var wholesale_from =  $('variation>wholesale_price_from',response).text();
	$('#main_image img').attr('src',$('variation>image',response).text());
	$('#main_image img').attr('alt',$('variation>image_alt',response).text());
	$('#main_image img').attr('title',$('variation>image_alt',response).text());
	$('#main_image a').attr('href',$('variation>image_full',response).text());
	$('#enlarge_link').attr('href',$('variation>image_full',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; 
    }

    if(sale_price > 0 && sale_price < non_sale_price ){
		$('#price').html(non_sale_price);
		$('#price').css('text-decoration','line-through');
		//$('#price').css('color','darkred');
		$('#sale_pricing').css('color','darkred');
		$('#sale_pricing').html(sale_price);
		$('#sale_pricing').show();
    	$('#sale_pricing').formatCurrency({useHtml:true});
    }
    else{
        $('#price').html(price);
        $('#price').css('text-decoration','none');
		$('#sale_pricing').hide();
    }
      
    $('#price').formatCurrency({useHtml:true});
    
    if(wholesale && wholesale_from)
    {
    	$('#whole_sale_price').html(wholesale_from + ' or more only $' + wholesale + ' each');
    }
        
    if($.trim($('variation>isavailable',response).text()) == '1')
    {
    	show_in_stock();

    	$('div#backOrderEmailForm').hide();
    	$('div#backOrderEmailForm #thanks').hide();
    	$('div#backOrderEmailForm #backOrderEmailErrors').hide();
	    if($('variation>specific_back_order_text',response).text())
	    {
	    	$('#backOrderMessage > p').text($('variation>specific_back_order_text',response).text());
	    	$('#backOrderMessage').show();
	    }
	    else
	    	$('#backOrderMessage').hide();
    }
    else
    {
	    show_no_stock();

    	$('div#backOrderEmailForm').show();
    	$('#backOrderMessage').hide();
	    if($('variation>back_order_text',response).text())
	    {
	    	$('#no_stock_message').text($('variation>back_order_text',response).text());
	    	$('#no_stock_message').css('color','darkred');
	    	$('#no_stock_message').css('font-weight','bold');
	    	$('#no_stock_message').show();
	    }
    }
}

/**
* 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());
    });
}


//called when some click on swatch image
function swapthumb(a_el)
{
    $.getJSON("/json/index/get_image_src/", {sku:$(a_el).find("img").attr('id'), product_id:$('#product_id').val() }, function(data){
        if(data.src_main)
        {
            $('#main_image img').attr( 'src', data.src_main );
            $('#main_image img').attr( 'alt', data.alt_text );
            $('#main_image img').attr( 'title', data.alt_text );

            $('#main_image a').attr( 'href', data.src_big );
            $('#enlarge_link').attr( 'href', data.src_big );
        }
    });
	return false;
}

//GRR this needs to be global, cant pass as a param cause event is  
var extra_options = {};
function swapswatch(a_el)
{
	var swatch_file_name = $(a_el).find("img").attr('id');

	//remove the file extension and last number from file name
	extra_options['swatch'] = swatch_file_name.replace(/(-[0-9]+)?\.[a-z]+$/,'');

	load_product_variation();

	extra_options = {};

	return false;
}


//Update product page after adding item to cart via AJAX with new cart state info 
var timeoutAction;
function update_page_after_cart(html)
{
	$.unblockUI();
    $('#floating_minicart').html(html);
   
    
     //we need to update total and number of items in the cart on top utility menu
   // var subtotal = $('#mini_cart_total').text();
    var items_in_cart = $('#mini_items_in_cart').text();
   // $('#top_nav_total').html(subtotal);
    $('li.cartItems em').html(items_in_cart+' items');
    
    $('div#cart_count').text(items_in_cart +' items');
    $('div#cart_count').css('color','#b85937');
    $('div#cart_count').css('font-weight','bold');
    $('div#to_checkout>a').text('Checkout');
    
    $('div#cart_icon img').attr('src','/img/new_site_buttons/red_cart_icon.png')

    $('div#choose_option_error').remove();

    if($.trim($('#notEnoughQuantity').text())=='1')
    {
    	var quantityToAdd = $.trim($('#quantityToAdd').text());
    	timeoutAction = "$('#floating_minicart').hide();";
    	$.blockUI({message:'<div style="width: 100%; float: left; cursor: default;"><div style="padding: 8px;"><p>Unfortunately, we only have ' + String( quantityToAdd ) + ' items left in stock. They have been added to your cart. Please contact us if you have further questions concerning the availability of this product.</p><br style="clear: both;" /><p style="text-align: center;"><input type="button" onclick="$.unblockUI(); $(\'#floating_minicart\').show(); setTimeout(timeoutAction, 7000);" style="cursor: pointer; background-image: url(/img/new_site_buttons/continue_button.png); width: 82px; height: 30px;" value="" /></p></div></div>'});
    }
    else
	    //hide mini cart after 5 seconds 
    {
    	$('#floating_minicart').show();
	    setTimeout("$('#floating_minicart').hide();", 7000);
    }

    $('.to_checkout_button').show();  	
}

function backOrderEmailSignup()
{
	var variation_id = $('#variation_id').val();
	var backOrderEmail = $.trim($('#backOrderEmail').val());

	if(backOrderEmail)
		$.post("/product/back_order_email_signup", { variation_id: variation_id, backOrderEmail: backOrderEmail }, update_page_after_back_order_email_signup );
	else
	{
		$('div#backOrderEmailForm #thanks').hide(750);
		$('div#backOrderEmailForm #backOrderEmailErrors').show(750);
	}
}

function update_page_after_back_order_email_signup(response)
{
	$('div#backOrderEmailForm #backOrderEmailErrors').hide(750);
	$('div#backOrderEmailForm #thanks').hide();
	$('div#backOrderEmailForm #thanks').show(750);
}

