var conf = {'base_asset_url': "http://%d.bassico.eu/assets" }
var product_config;
var optsFixed = new Array();
var old_sum;
var top_tooltip = 10;
var set;
var g;
jQuery.noConflict();


/******************** Helpers **********************/
function logwrite(text){
//	console.log(text)
}

function modeOfPage(){
	if (json_url != undefined){ return "product_config"}
}

function initLightbox(){
	jQuery('a[@rel*=lightbox]').lightBox();
}

function show_world(world_id, static){
    jQuery('.world_info').hide();
    jQuery('.world-pointer').css('visibility','hidden');
    jQuery('.world-buttons').css('background','none');
    if (world_id){
        jQuery('#world-button-'+world_id).css('background','url("http://st3.bassico.eu/images/pointer.gif") no-repeat center bottom');
        if (!static){
            jQuery('#world_'+world_id).show();
            jQuery('#world-button-'+world_id).css('background','url("http://st2.bassico.eu/images/pointer-info.gif") no-repeat center bottom');
        }
    }
}

function show_language(headline){
    jQuery("#languages-headline").text(headline)
}

function show_country(headline){
    jQuery("#country-headline").text(headline)
}

function bZoomProductImage(t){
	holder = jQuery('#product-image-main-holder')
	jQthis = jQuery(t)
	holder.css('background','white url(' + jQthis.attr('small_url') + ') no-repeat center'); 
	jQuery("#zoom_link").attr("href",jQthis.attr('original_url'))
	holder.css('height', (parseInt(jQthis.attr('small_heigth'))+10) + 'px');
	initLightbox();
}

/* number to decimal formatted euro value */
function formatCurrency(num) {
    num = num.toString().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));
    return (((sign)?'':'-') + num + ',' + cents + ' €<sup>*</sup>');
}

function currencyFormatDiff(num){
	if (num < 0){
		return '' + formatCurrency(num) + ''
	} else if (num == 0) {
		return ''
	}
	else 
	{
		return '+' + formatCurrency(num) + ''
	}
}

// jQuery(document).ajaxSend(function(event, request, settings) {
//   if (typeof(AUTH_TOKEN) == "undefined") return;
//   // settings.data is a serialized string like "foo=bar&baz=boink" (or null)
//   settings.data = settings.data || "";
//   settings.data += (settings.data ? "&" : "") + "authenticity_token=" + encodeURIComponent(AUTH_TOKEN);
// });


function copy_address(){
	      jQuery("[id^=delivery_address]").each(function (i) {
	       	target = jQuery('#' + this.id.replace(/delivery_address/g, "invoice_address"))
			target.val(jQuery(this).val())
	      });
}

jQuery(document).ready(function(){
	
	
	initLightbox();
	jQuery(".roundcorners").corner();
	jQuery("#product-image-thumbs-holder div").bind("click", function(e){ bZoomProductImage(this) })
	
	jQuery("#buy_product_button").bind('click', function(e){
		logwrite('buying stuff')
		logwrite(Object.toJSON(product_config))
		jQuery("#order_form_field").val(Object.toJSON(product_config))
		// alert(jQuery("#order_form_field").val()) 
		jQuery("#order_form").submit()
		// jQuery.post("/cart/add_to_cart?authenticity_token=" + encodeURIComponent(AUTH_TOKEN),
		//   			{'order' : Object.toJSON(product_config), 'authenticity_token' : encodeURIComponent(AUTH_TOKEN)},
		//   			function(data) { window.location = "/cart/list" });
	})
	   	
	jQuery("#config_stack .product_list > li h4").bind('click', function(e){
		productCursor(jQuery(this).parent(), true)
		recalcTotal()
	})
	
	// jQuery("#config_stack .product_list").bind('mouseleave', function(e){
	// })
	// jQuery("#config_stack .product_list").bind('mouseenter', function(e){
	// 	productCursor(jQuery(this).children('.active').filter(':first'), true)
	// })

	show_world(page_world_id, true);

	jQuery("#coun_code").bind("click", function(e){
		country_code = jQuery(this).val()
		zip_code_field = jQuery('#change_shipping_region .zip_code')
		if( country_code == 'de') { zip_code_field.hide() } else { zip_code_field.show() }
	}).click()

	jQuery("#config_stack .product_list > li.active").each(function(obj){
		productCursor(this, true)	
	})
	recalcTotal()

	jQuery("#config_stack li select").bind('change',function(obj){
		recalcTotal()
	})
	
	jQuery("#config_stack li.first_product select").bind('change',function(obj){
		type = jQuery(this).attr('data-type')
		values = jQuery(this.options[this.selectedIndex]).attr('data-skus').split(',')
		jQuery("#config_stack .product_list > li").not('.first_product').filter('.'+type).hide(); 
		values.each(function(value){
			jQuery("#config_stack .product_list > li").not('.first_product').filter('.'+type+value).show(); 

		})
		
		price = 999999999;
		var cheapest
		logwrite('cheapset')
		jQuery("#config_stack .product_list .active").each(function(x){
			cheapest = jQuery(this)
			jQuery(this).filter(':hidden').each(function(x){
				logwrite('find new')
				jQuery(this).parent().children(':visible').each(function(c){
					logwrite('loop')
					if((parseFloat(jQuery(this).attr('data-surcharge')) < price)){
						price = parseFloat(jQuery(this).attr('data-surcharge'))
						cheapest = jQuery(this)
					}
				})
			})
			productCursor(cheapest, false)
		})
		// jQuery("#config_stack > li").each(function(obj){
		// 	count = jQuery(obj).find('.product_list > li:visible').length
		// })
		
	})	
	
})
var price = 999999999;

function productCursor(obj, centered){
	//alert(jQuery(obj).html())
	jQuery(obj).parent().children('li.active').removeClass('active');
	var divOffset = jQuery(obj).parent('.product_list').offset().top;
	var pOffset = jQuery(obj).offset().top;
	var pScroll = pOffset - divOffset;
	
	jQuery(obj).parent('.product_list').animate({scrollTop: '+=' + pScroll + 'px'}, 500);
	jQuery(obj).addClass('active')
}

function recalcTotal(){
	logwrite('recalcing')
	new_price = parseFloat(jQuery("#total_before_config").attr('data-price'))
	old_price = new_price
	logwrite('old ' + old_price)
	product_config = {}
	product_config.sku = jQuery("#config_stack").attr('data-sku')
	product_config.realset = jQuery("#config_stack").attr('data-realset')
	product_config.GroupList = []

	jQuery("#config_stack .product_list > li.active").each(function(x){
		group_id = jQuery(this).parents('.group').attr('data-group-id') || 0
		logwrite('+ gid ' + group_id)
		product_config.GroupList.push({'sku': jQuery(this).attr('data-sku'), 'group-id': group_id, 'options': []})
		s = jQuery(this).attr('data-surcharge') || 0
		new_price += parseFloat(s)
		logwrite('+' + s)
		jQuery(this).find('select').each(function(y){
			s = jQuery(this.options[this.selectedIndex]).attr('data-surcharge')
			type = jQuery(this).attr('data-type')
			value = jQuery(this.options[this.selectedIndex]).attr('data-sku')
			product_config.GroupList[product_config.GroupList.length-1].options.push({'type': type, 'value': value})
			new_price += parseFloat(s)
			logwrite('+ option ' + s)
		})
	})
	jQuery("#total_after_config .price").html(formatCurrency(new_price))
    if(parseFloat(jQuery("#total_before_config").attr('data-price')) != new_price){ 
		jQuery("#total_after_config").css('display', 'block'); 
	};
}




