var jmCart = new Hash.Cookie('jmCart', {'autoSave':false});
var jmCheck = new Hash.Cookie('jmCheck');
var jmUser = Cookie.read('si') || Cookie.write('si', 'JackBauer', {'duration': 14});

window.addEvent('domready',function(){
	cartSet = new Fx.Elements($$('#Count, #modal'));
	cartMorph = new Fx.Elements($$('#cart, #cart1'));

	new Hash.Cookie('jmCart').each(function(value, key){ 
		value.title ? addSong(key, value.title, value.album, value.price) :	addAlb(key, value.album, value.price) 
	});
	updateTotal(0,1);
	
	var bodySize = $('body').getSize();
	$('modal').setStyles({'opacity':0.01, 'width':bodySize.x, 'height':bodySize.y });
	$('cart2').set('morph', { link:'cancel', duration: 'long' });
	$$('.hideCart').addEvent('click', hideCart);
	$('viewCart').addEvent('click', showCart);
	if(jmCheck.get('total'))$$('#cart, #viewCart').setStyle('display','block');
})

function addAlbum(){
	//var key = window.location.search.split('a=')[1].split('&')[0];//this should really be a regex. Is in php as $a
	var key = $('albTitle').get('key')*19;
	if(jmCart.has(key)){ alert("You already have this album in your cart."); return; }
	
	var eid, overlap =[[],[]], total=0; 
	$$('tr.tr').each(function(el){ 
		if(jmCart.has(eid = el.get('id'))){ overlap[0].push(eid); overlap[1].push('\n'+el.getElement('.td_1').get('text').trim()); }; 
	})
	if(overlap[0][0]){
		var addalb = window.confirm("You already have the folowing songs from this album in your cart:"+overlap[1]+"\nDo you want to add the album instead?");
		if(!addalb)return;
		overlap[0].each(function(songKey){ 
			total -= jmCart.get(songKey)['price'];
			removeRow(songKey)	
		})
		jmCheck.erase(key);
	}
	
	price =$('albPrice').get('text').substr(1).toFloat().round(2);
	total += price;
	addAlb(key, $('albTitle').get('text').trim(), price);
	
	updateTotal(total);
	$$('#cart, #viewCart').setStyle('display','block');
}

function addSongs(){
	var albKey = $('albTitle').get('key')*19;
	//var albKey = window.location.search.split('a=')[1].split('&')[0];//this should really be a regex. Is in php as $a
	if(jmCart.has(albKey)){ alert("You already have the entire album in your cart."); return; }
	
	var price, total = 0;
	$$('tr.tr').each(function(el){
		var key = el.get('id'), selected = el.getLast().getLast().get('checked'), exists = jmCart.has(key), album = $('albTitle').get('text');
		if(exists && !selected)	{
			price = jmCart.get(key)['price'];
			total -= price
			removeRow(key, price)
		}
		else if (selected && !exists) {
			price = el.getElement('.td_4').get('text').trim().substr(1).toFloat();
			total += price
			addSong(key, el.getElement('.td_1').get('text').trim(), album, price, albKey);
		}
	});
	updateTotal(total);
	checkPrice(total, albKey);
	$$('#cart, #viewCart').setStyle('display','block');
}

function addAlb(key, album, price){ 
	jmCart.set(key, {'album':album, 'price':price});
	new Element('tr', {'id':'cart_'+key, 'class':'tr_1' }).adopt(
		new Element('td', {'class':'albNo'}),
		new Element('td', {'text':album, 'colspan':'2' }),
		new Element('td', {'class':'remove', 'events':{ 'click': function(){ 
			removeRow(key); updateTotal(price*-1)	}	}	} 	),
		new Element('td', {'text':'$'+price})
	).inject('cartAlbums', 'after');
}

function addSong(key, title, album, price, albKey){ 
	jmCart.set(key,  {'title':title, 'album':album, 'price':price});
	new Element('tr', {'id':'cart_'+key, 'class':'tr_1' }).adopt(
		new Element('td', {'class':'songNo'}),
		new Element('td', {'text':title }),
		new Element('td', {'text':album }),
		new Element('td', {'class':'remove', 'events':{ 'click': function(){ 
			removeRow(key); updateTotal(price*-1); checkPrice(price*-1, albKey);	
		}	}	} 	),
		new Element('td', {'text':'$'+price})
	).inject('cartSongs', 'after');
	if($(key))$(key).getLast().getLast().set('checked', true);
	
}

function removeRow(key){
	console.log('remove key: '+key)
	jmCart.erase(key);
	$('cart_'+key).destroy();
	if($(key))$(key).getLast().getLast().set('checked', false);
}

function checkPrice(price, key){
	var albTotal = jmCheck.get(key) + price;
	jmCheck.set(key, albTotal);
	if( albTotal > $('albPrice').get('text').substr(1).toFloat()){ 
		var addalb = window.confirm("The cost of the entire album is less than the cost of the individual songs you have chosen, would you like to add the entire album instead?");
		if(!addalb)return;
		addAlbum();
		//finish this correctly!
	}
}

function updateTotal(price, load){ 
	var total = (jmCheck.get('total')+price).round(2);
	jmCheck.set('total', total);
	$('Total').set('text', total);
	
	var snl = $$('td.songNo').length, anl = $$('td.albNo').length, counter=0;
	$$('td.albNo','td.songNo').each(function(el){el.set('text',++counter)});
	$('sCount1').set('text', snl);
	$('aCount1').set('text', anl);
	$('sPlural').setStyle('display', (snl == 1 ? 'none':''));
	$('aPlural').setStyle('display', (anl == 1 ? 'none':''));
	$('cartAlbums').setStyle('display', anl ? '' : 'none');
	$('cartSongs').setStyle('display', snl ? '' : 'none');
	
	var minimized = $('modal').getStyle('display')=='none';
	if(total && minimized && !load) showCart();
	else if(!total && !minimized){ hideCart(); $$('#cart, #viewCart, #modal').setStyle('display','none')};//
	
	jmCart.save()
}

function next(to){
	var divSize = 600;	
	$('cart2').morph({ 'left': -to*divSize })
	if(to == 2){
		$('errResponse').set({'display':'none'}); 
		$('keys').set('value', jmCart.getKeys() );
		new Request({
			url:'axmd.php',
			data: $('loginForm'),
			onComplete:function(response){
				if (response.substr(0,2) == "ok"){
					$('successResponse').set('html', response.substring(2)).set('class','successResponsePlus');
					next(3);
				} else {
					$('errResponse').set({'html':response, styles:{'display':'block'}});
					next(1);
		}	}	}).send();
}	}


function hideCart(){
	cartSet.set({
		'0':{'display':'block'},
		'1':{'display':'none'}
	})
	cartMorph.start({
		'0':{ 'left': 0, 'bottom': [75, 25] },
		'1':{ 'width': 134, 'height':40 }
	})
	$('cart2').setStyle('left', 0)
}

function showCart(){
	if(!$('Total').get('text').toFloat())return;
	var cartH = $('cart2').getSize().y;
	cartSet.set({
		'0':{'display':'none'},
		'1':{'display':'block'}
	})
	cartMorph.start({
		'0':{ 'left': 50, 'bottom': [25, 75] },
		'1':{ 'width': 600, 'height': (cartH > 265 ? cartH + 100 : 350) }
	})
}
function placeOrderBtn(){
	$$('#placeOrder .closeCartBtn').toggleClass('n');
	//$('placeOrder').removeProperty('onclick').addEvent('click', completeSale)
	//$('placeOrder').removeEvent()
	//var aInp = new Element('img',{'src':'images/checkout2.gif', 'styles':{'height':'100px', 'border':'5px solid maroon'}, 'events':{'click':completeSale}}).inject($('placeOrder'));
	//aInp.replaces($('placeOrder'));
}

function completeSale(){
	var keys = jmCart.getKeys();
	for(var i=0; i<keys.length; i++){ 
		if($(keys[i]))$(keys[i]).setStyle('background-color','#fde')
		console.log(keys[i])
		removeRow(keys[i]) 
	}
	updateTotal(-1*jmCheck.get('total'), 1);
}

/*## Think this is not used ##*/
function clearCart(){
	$('d6').empty().set('html', '<table id="cartAlbums"><tr><td>Album</td><td>Price</td><td></td></tr></table><table id="cartSongs"><tr><td>Title</td><td>Album</td><td>Price</td><td></td></tr></table>')
}


 //window.addEvent('load',completeSale);