/** La Chambre Noire JavaScript Document
* @uses mootools javascript library http://www.mootools.net
* @uses Christophe Beyls' Slimbox http://www.digitalia.be/software/slimbox
* @author http://www.contreforme.ch / s.rossetti
* @copy 2010 see @author
* @version 1.9
* @history 1.9 release
*/
function link_init(){
	$$('a').each(function(el,i){
		if(el.get('rel') == 'external'){
			el.set('target','_blank');
		}
	});
	
	// --- xhr requests ---
	if($$('.book_details','.author_details','.publisher_details').length){
		$$('.book_details','.author_details','.publisher_details').each(function(el,i){
			el.addEvent('click',function(ev){
				var ev = new Event(ev).preventDefault();
				var action = this.className.split(' ');
				var l = $('languages').getElement('li.selected a').get('rel');
				xhr.send('cn_xhr='+action[0]+'&target='+action[1]+'&lng='+l);
			});
		});
	}
	
	if($$('img.popup').length){
		$$('img.popup').addEvent('click',function(ev){
			var src = this.get('src').replace('mini_','');
			Slimbox.open(src,{counterText:'Image {x} '+$('image_of_loc').get('value')+' {y}'});
		});
	}
	
	if($$('a[rel=image_detail]').length){
		$$('a[rel=image_detail]').slimbox({counterText:'Image {x} '+$('image_of_loc').get('value')+' {y}'});
	}
	
	if($('bd_gallery')){
		$('bd_gallery').addEvent('click',function(ev){
			var imgs = [];
			var as = $$('a[rel=image_detail]');
			for(var i=0;i<as.length;i++) imgs[i] = [as[i],null];
			Slimbox.open(imgs,0,{counterText:'Image {x} '+$('image_of_loc').get('value')+' {y}'});
		});
	}
	
	if($('xhr_closer')){
		$('xhr_closer').addEvent('click',function(ev){
			$('xhr_data').slide('out');
		});
	}
}
function xhr_init(){
	scroller = new Fx.Scroll(window);
	xhr = new Request.JSON({
		'method':'post',
		'url':'chambre_noire.xhr.php',
		onSuccess:function(jsn,txt){
			switch(jsn.action){
				case 'book_details':
				case 'author_details':
				case 'publisher_details':
					// --- create a div holder if not present (previous xhr actions || book of the moment) ---
					var div = $('xhr_data') || false;
					if(!div){
						div = new Element('div',{'id':'xhr_data'}).inject($('article'),'top');
					}
					// -- hide it then add content ---
					div.slide('hide');
					div.set('html',jsn.response);
					
					// --- inject closer button ---
					var closer = new Element('a',{
						'id':'xhr_closer',
						'text':$('close_loc').get('value'),
						events:{
							'click':function(ev){
								$('xhr_data').slide('out');
							}
						}
					}).inject(div);
					
					// --- reset links action ---
					link_init();
					cart_action();
					// --- show div ---
					div.slide('in');
					// --- scroll to top ---
					scroller.toTop();
				break;
			}
		}
	});
}
function cart_action(){
	if($('buy_button')){
		$('buy_button').addEvent('click',function(ev){
			var ev = new Event(ev).preventDefault();
			if(usr_books.getLength() > 5){
				alert($('cart_max_books_loc').get('value'));
			}else{
				var itemExists = usr_books.some(function(value, key){
					return value == $('ck_item').get('value')+"#|#"+$('ck_amount').get('value')+"#|#"+$('ck_ref').get('value');
				});
				if(!itemExists){
					usr_books.set('item'+(usr_books.getLength()+1),$('ck_item').get('value')+"#|#"+$('ck_amount').get('value')+"#|#"+$('ck_ref').get('value'));
					update_cart();
					if(!cart_fx.open) cart_fx.toggle();
				}else{
					alert($('item_already_in_cart_loc').get('value'));
				}
			}
		});
	}
}
function update_cart(){
	if(usr_books.getLength()){
		var items = '';
		var refs = [];
		var i = 1;
		cart_total = 0;
		var remove_label = $('cart_remove_item_loc').get('value');
		euro_rate = $('cart_euro_rate').get('value');
		usr_books.each(function(v,j){
			v = v.split('#|#');
			var label = v[0].replace(' / ','</p><p>');
			items +=	'<input type="hidden" name="item_name_'+i+'" value="'+v[0]+'" />'
						+'<input type="hidden" name="amount_'+i+'" value="'+v[1]+'" />'
						+'<div class="cart_item">'
						+'<img src="__layout/cross_white.png" width="16" height="16" alt="'+remove_label+'" title="'+remove_label+'" rel="'+j+'" class="cart_remover" /> '
						+'<div class="label"><p class="title">'+label+'</p></div>'
						+'<div class="price">'+v[1]+' CHF / '+(Math.round((v[1]/euro_rate)*100)/100)+' €</div>'
						+'</div>';
			cart_total += v[1].toInt();
			refs.push(v[2]);
			i++;
		});
		items +=	'<input type="hidden" name="custom" value="'+refs+'" />'
					+'<div id="shipping_costs"></div>'
					+'<div id="cart_total">'
					+'<label>'+$('cart_total_loc').get('value')+' : '+cart_total+' CHF / '+(Math.round((cart_total/euro_rate)*100)/100)+' €<br /><small>1 € = '+euro_rate+' CHF</small></label>'
					+'</div>';
					
		$('cart_items').set('html',items);
		
		$$('img.cart_remover').addEvent('click',function(ev){
			remove_cart_item(this.get('rel'));
		});
		$('region_select').setStyle('display','block');
	}else{
		$('region_select').setStyle('display','none');
		$('cart_items').set('html','<em class="empty_cart">'+$('cart_empty_loc').get('value')+'</em>');
		if(cart_fx.open) (function(){ cart_fx.toggle(); }).delay(1500);
	}
	set_shipping();
}
function remove_cart_item(i){
	usr_books.erase(i);
	update_cart();
}
function cart_init(){
	usr_books = new Hash.Cookie('usr_books');
	cart_action();
	var regions = $('cart_shipping_destinations_loc').get('value').split('/');
	var region_options = '';
	regions.each(function(el,i){
		region_options += '<option>'+el+'</option>';
	});
	cart = new Element('form',{
					   	'name':		'cn_cart_a',
						'id':		'cn_cart',
						'method':	'post',
						'target':	'paypal',	
						'action':	'https://www.paypal.com/cgi-bin/webscr',
						'html':		'<div id="cart_items"><em class="empty_cart">'+$('cart_empty_loc').get('value')+'</em></div>'
									+'<input type="hidden" name="cmd" value="_cart" />'
									+'<input type="hidden" name="notify_url" value="http://www.la-chambre-noire.ch/__interne/pp_feedback.php" />'
									+'<input type="hidden" name="charset" value="utf-8">'
									+'<input type="hidden" name="business" value="declic@lachambrenoire.ch" />'
									+'<input type="hidden" name="upload" value="1" />'
									+'<input type="hidden" name="currency_code" value="CHF" />'
									+'<input type="hidden" id="shipping" name="handling_cart" value="0" />'
									+'<div id="region_select">'
									+'<label>'+$('cart_select_shipping_loc').get('value')+'</label>'
									+'<select id="shipping_select">'
									+'<option>'+$('cart_shipping_choose_loc').get('value')+'</option>'
									+region_options
									+'</select>'
									+'<div><input type="submit" id="paypal_submit" value="'+$('cart_submit_loc').get('value')+'" /></div>'
									+'</div>'
					   }).inject($('content_header'));
	cart_fx = new Fx.Slide(cart).hide();
	new Element('img',{
				'src':'__layout/cart_but.png',
				'width':21,
				'height':19,
				'id':'cart_toggler',
				'events':{
					'click':function(){
						cart_fx.toggle();
					}
				}
			}).inject($('content_header'),'top');
	$('paypal_submit').addEvent('click',function(ev){
		if($('shipping_select').selectedIndex == 0){
			var ev = new Event(ev).preventDefault();
			alert($('cart_shipping_unset_loc').get('value'));
		}else{
			usr_books.empty();
			(function(){
				window.location.reload();
			}).delay(1500);
		}
	});
	$('shipping_select').addEvent('change',function(ev){
		set_shipping();
	});
	update_cart();
}
function set_shipping(){
	if($('shipping_select').selectedIndex > 0 && $('cart_total')){
		//---------- shipping fees ----------//
		//	area		books nb	price	//
		//	CH			1			10.-	//
		//				2-3			13.-	//
		//				4-6			18.-	//
		//	EUR			1			25.-	//
		//				2-3			45.-	//
		//				4-6			60.-	//
		//	other		1			35.-	//
		//				2-3			65.-	//
		//				4-6			100.-	//
		//----------------------------------//
		var v = 0;
		var n = usr_books.getLength();
		switch($('shipping_select').selectedIndex){
			// CH
			case 1:
				if(n<2){
					v = 10;
				}else if(n<4){
					v = 13;
				}else{
					v = 18;
				}
			break;
			// EUR
			case 2:
				if(n<2){
					v = 25;
				}else if(n<4){
					v = 45;
				}else{
					v = 60;
				}
			break;
			// other
			case 3:
				if(n<2){
					v = 35;
				}else if(n<4){
					v = 65;
				}else{
					v = 100;
				}
			break;
		}
		$('shipping').set('value',v);
		cart_total += v;
		$('cart_total').set('html','<label>'+$('cart_total_loc').get('value')+' : '+cart_total+' CHF / '+(Math.round((cart_total/euro_rate)*100)/100)+' €<br /><small>1 € = '+euro_rate+' CHF</small></label>');
		$('shipping_costs').set('html',$('cart_shipping_costs_loc').get('value')+' : '+v+' CHF / '+(Math.round((v/euro_rate)*100)/100)+' €');
	}else if($('shipping_costs')){
		$('shipping_costs').set('html','');
	}
}
function search_init(){
	$('search_reset').addEvent('click',function(ev){
		var ev = new Event(ev).preventDefault();
		$$('input').each(function(el,i){
			if(el.get('type') == 'checkbox'){
				el.checked = false;
			}else if(el.get('type') == 'text'){
				el.value = '';
			}
		});
	});
}
function cn_init(){
	link_init();
	xhr_init();
	if($('sorter_label')){
		$('sort_fields').slide('hide');
		$('sorter_label').addEvent('click',function(ev){
			$('sort_fields').slide('toggle');
		});
	}
	if($$('.book_item').length){
		cart_init();
	}
	if($('cnsearch')){
		search_init();
	}
}
var xhr,scroller,usr_books,cart,cart_fx,cart_total,euro_rate;
window.addEvent('domready',function(){
	cn_init();
});
