window.onload = function(){

	if ($('sparc-cse-input')) {
		var searchbox = $('sparc-cse-input');
		searchbox.value = 'Search';
		searchbox.onfocus = function(){
			if (this._cleared) return
			this.clear();
			this._cleared = true;
		}
		searchbox.onblur = function(){
			if (this.getValue() == '') {
				this.value = 'Search';
				this._cleared = false;
			}
		}
	}
	if ($('lead-link')) {
		$$('#lead-link>a')[0].observe('click', function(){
			$('lead-form').setStyle({top:'-1em'});
		});
		$$('#lead-form>a')[0].observe('click', function(){
			$('lead-form').setStyle({top:'-100em'});
		});
	}
	themestore.init();
};

var themestore = {
	pricing: false,
	options: false,
	subtotal: 0,
	grandtotal: 0,
	optiontotals: [],
	init: function(){
		if ($$('dl.item-detail').length <= 0) {
			return;
		}
		var dl = $$('dl.item-detail')[0];
		this.pricing = pricing;
		this.options = options;
		this.setvalue = $F($$('select.item-quantity')[0]);
		if ($('order-form') && $$('select.item-quantity').length > 0) {
			$('order-form').select('select').each(function(s){
				s.observe('change',themestore.updateCost);
			});
		}
		if ($('store-cart') && $('store-cart').select('select').length > 0) {
			$('store-cart').select('select.item-quantity').each(function(s){
				s.observe('change',function(event){
					Event.element(event).insert({before: '<strong>Pricing updated on cart update.</strong>'});
				});
			});
		}
	},
	updateCost: function(event) {
		var form = Event.element(event).up('form'),
			newquantity = $F($$('select.item-quantity')[0]);
		// newquantity contains index of chosen quantity

		themestore.subtotal = 0 + pricing.blocks[newquantity].cost;
		themestore.grandtotal = themestore.subtotal;

		if (newquantity >= 0) {
			$$('.subtotal')[0].update('$' + parseFloat(themestore.subtotal).toFixed(2));
			new Effect.Highlight($$('.subtotal')[0],{duration: 1.5});
		}
		
		if ($('item-options')) {
			$('item-options').select('select').each(function(option,index){
				var optiontotal = parseFloat(options[index].values[$F(option)].cost_effect_sum);
				option.up('tr').down('td.total-column').update('$' + optiontotal.toFixed(2));
				themestore.subtotal = (themestore.subtotal * 1) + (optiontotal * 1);
				themestore.grandtotal = themestore.subtotal;
				new Effect.Highlight(option.up('tr').down('td.total-column'),{duration: 1.5});
			});
		}
		$('order-form').select('span.total')[0].update('$' + parseFloat(themestore.subtotal).toFixed(2));
		new Effect.Highlight($('order-form').select('span.total')[0],{duration: 1.5});
	}
};
