var jar = new CookieJar({
	expires: 3600, // seconds
	path: '/',
});

var openwindow = function(url) {
  win_cd = window.open(url, 'cd', 'scrollbars=yes,resizable=yes,status=yes,width=450,height=350');
  win_cd.focus();
}

var video = function(url, winw, winh) {
	winw = winw+50; winh = winh+120;
  win_cdvideo = window.open(url, 'cdvideo', 'scrollbars=no,resizable=yes,status=yes,width='+winw+',height='+winh);
  win_cdvideo.focus();
}

/*
var radio = function(url) {
  win_cdradio = window.open(url, 'cdradio', 'scrollbars=no,resizable=no,status=yes,width=620,height=210');
  win_cdradio.focus();
}
*/

var retour = function(url) {
  opener.location.href=url;
}

var formHandler = function(form) {
  var URL = form.site.options[form.site.selectedIndex].value;
  if (URL != "") {
    location.href = URL;
  }
}

var radioselect = function(e) {
  var url = $(e).site.options[$(e).site.selectedIndex].value;
  if (url != "") {
  	radio(url);
  }
}

var page = function(divNum,divMax) {
	c = 0;

	while(c < divMax) {
		c++;

		if(c == divNum) {
			$('page-'+c).show();
		} else {
			$('page-'+c).hide();
		}
	}
}

var setupPairImpair = function(ul) {
	ul.childElements().each(function(li, index) {
		if(((index+1) % 2) > 0) li.addClassName('impair')
		else li.removeClassName('impair');
	});
}

var getTdSortValue = function(td) {
	if(td.select('input[name="sort"]').size() > 0) {
		return td.select('input[name="sort"]')[0].value;
	} else {
		return td.innerHTML.stripTags();
	}
}

var setupTableTri = function(trHead) {
	trHead.select('th').each(function(th, index) {
		th.update('<a href="#">' + th.innerHTML + '</a>');

		Event.observe(th.down('a'), 'click', function(event) {
			link = event.element();
			if(link.tagName != 'A') link = link.up('a');
			link.blur();
			var th = link.up('th');
			
			if(!th.hasClassName('sel')) {
				th.siblings().each(function(th) { th.removeClassName('sel'); });
				th.addClassName('sel');
				
				var table = th.up('table');
				var colIndex = -1;

				trHead.select('th').each(function(thCalc) {
					var colSpan = 1;
					if(thCalc.colSpan != undefined) colSpan = thCalc.colSpan * 1;
					colIndex += colSpan;
					if(thCalc == th) throw $break;
				});
				
				var rowList = table.select('tr').findAll(function(tr) { return (tr.select('td').size() > 0) });
				
				rowList.each(function(tr) {
					var val = getTdSortValue(tr.select('td')[colIndex]);
					if(val != '') tr.show()
					else tr.hide();
				});
				
				var sortedRowList = rowList.clone();
				rowList.each(function(tr) { tr.remove() });
				
				sortedRowList.sort(function(tr1, tr2) {
					var c1 = getTdSortValue(tr1.select('td')[colIndex]);
					var c2 = getTdSortValue(tr2.select('td')[colIndex]);
					if (c1 == c2) return 0;
					if (c1 < c2) return -1;
					return 1;
				});
				
				sortedRowList.each(function(tr) {
					table.down('tbody').insert({ bottom: tr });
				});
			}
		});
	});
}

var updateDevisePrix = function() {
	var deviseId = jar.get('devise');

	if(deviseId) {
		$$('span.devise-prix').each(function(span) {
			if(deviseId == 'cad') {
				span.innerHTML = '';
				span.hide();

			} else {
				var desc = devises.get(deviseId).get('desc');
				var mult = parseFloat(devises.get(deviseId).get('mult'));
				var prix = parseFloat(span.previous('a.btnorder').innerHTML.match(/(\d+[,.]\d+)/)[0].replace(',', '.'));
				var prixDevise = prix * mult;
				span.innerHTML = '~ ' + prixDevise.toFixed(2) + ' ' + desc;
				span.show();
			}
		});
	}
}

var setupDeviseChoix = function() {
	$$('a.btnorder').each(function(link) {
		var deviseLien = new Element('a', { 'class': 'btn-devise', 'href': '#', 'title': ((lng == 'f')? 'Sélectionner une autre devise': 'Select another currency') });
		deviseLien.innerHTML = '&curren;';

		Event.observe(deviseLien, 'click', function(event) {
			deviseLien.blur();
			deviseLien.addClassName('actif');
			
			$('devise-choix').setStyle({
				'left': deviseLien.cumulativeOffset().left + 'px',
				'top': (deviseLien.cumulativeOffset().top + deviseLien.getHeight() - 1) + 'px'
			});

			$('devise-choix').show();
			event.stop();
		});
		
		link.insert({ 'after': deviseLien });
		var devisePrix = new Element('span', { 'class': 'devise-prix' });
		link.insert({ 'after': devisePrix });
	});

	var deviseChoix = new Element('ul', { 'id': 'devise-choix' }).hide();

	Event.observe(document.body, 'click', function(event) {
		var e = event.element().up('#devise-choix') || event.element().up('a.btn-devise');

		if(e == undefined) {
			$('devise-choix').hide();
			$$('a.btn-devise.actif').each(function(e) { e.removeClassName('actif') });
		}
	});

	devises.each(function(pair) {
		var li = new Element('li');
		var link = new Element('a', { 'href': '#devise:' + pair.key });
		link.innerHTML = pair.value.get('desc');
		
		Event.observe(link, 'click', function(event) {
			$('devise-choix').hide();
			$$('a.btn-devise.actif').each(function(e) { e.removeClassName('actif') });
			var deviseId = link.href.match(/#devise\:(.+)$/)[1];
			jar.put('devise', deviseId);
			updateDevisePrix();
			event.stop();
		});
		
		li.insert(link);
		deviseChoix.insert({ 'bottom': li });
	});

	document.body.insert({ 'bottom': deviseChoix });
	updateDevisePrix();
}

var setupCaisse = function() {
	if($('caisse-etape-1')) {
		Event.observe('caisse-etape-1', 'submit', function(event) {
			jar.put('Email', $F('caisse-email'));
			jar.put('Realname', $F('caisse-realname'));
		});

	} else if($('caisse-etape-2')) {
		if(jar.get('Realname')) {
			$('caisse-realname').value = jar.get('Realname');
			$('caisse-realname').up('tr').hide();
		}

		if(jar.get('Email')) {
			$('caisse-email').value = jar.get('Email');
			$('caisse-email').up('tr').hide();
		}
	}
}

var togMiniTab = function(event, containerClass) {
	a = event.element();
	a.blur();
	tabs = a.up('tr');
	noms = new Array();
	nomSel = '';
	
	tabs.childElements().each(function(d) {
		ai = d.down('a');
		ai.className = 'here' + (ai == a? '1': '0');
		nom = d.className.replace('lien-', '')
		noms.push(nom);
		if(ai == a) nomSel = nom;
	});
	
	container = tabs.up('div.' + containerClass);
	
	noms.each(function(s) {
		if(s != nomSel) container.down('div.groupe-' + s).hide();
	});
	
	container.down('div.groupe-' + nomSel).show();
	event.stop();
}

var initSiteDomLoaded = function(event) {
	lng = (baseLngDir == 'fr')? 'f': 'e';

	$$('table.prog').each(setupPairImpair);
	
	$$('tr.table-tri').each(setupTableTri);

	if($('video-zone')) {
		initVideo();
	}

	$$('div.press div.nav-minitab').each(function(e) {
		var tabs = e.down('tr');

		tabs.childElements().each(function(d) {
			var a = d.down('a');
			Event.observe(a, 'click', function(event) { togMiniTab(event, 'press'); });
		});
	});

	Event.observe(document, 'mousemove', function(event) {
		if($('tip') && $('tip').isActif) {
			$('tip').setStyle({
				'left': (Event.pointerX(event) - ($('tip').getWidth() / 2)) + 'px',
				'top': (Event.pointerY(event) - $('tip').getHeight() - 12 ) + 'px'
			});
		}
	});

	if($$('a.btnorder')) {
		setupDeviseChoix();
	}
	
	if($$('body#panier-caisse')) {
		setupCaisse();
	}
}

var initSiteAllLoaded = function(event) {
	isAllLoaded = true;
	initRadio();
}

Event.observe(document, 'dom:loaded', initSiteDomLoaded, false);
Event.observe(window, 'load', initSiteAllLoaded, false);

var isAllLoaded = false;
var tipTimer;
var lng;
