
Event.observe( document, 'contentloaded',
	function(){
		if( $('country') && $('country-selector') ){
			$( 'country' ).observe( 'click', show_countries );
			$$('#country-selector li.countries').invoke( 'observe', 'click', change_country );
			$('pais').observe( 'change', change_pais );
			$('cantidad').observe( 'change', update_sum );
		}
		$$( '#etiquetas-selector img.etiqueta-img' ).invoke( 'observe', 'click', choose_etiqueta );
		$$( '#etiquetas-selector input.etiqueta-radio' ).invoke( 'observe', 'click', choose_etiqueta );
		if( $( 'fuente' ) ){
			$( 'fuente' ).observe( 'change', change_font );
		}
	}
);

function update_sum(){
	var prod = parseInt( $('comprar-precio').firstChild.nodeValue );
	var trans = parseFloat( $('transport-price').firstChild.nodeValue );
	var amount = $F('cantidad');
	if( amount > 1 ){
		trans = trans * discount / 100;
	}

$('sum').update( (prod + trans) * amount + ' &euro;' );
}

function round2( a ) {
	return Math.round( a*100 )/100;
	}

function show_countries( evt ){
	var btn = $('country');
	var offset = btn.positionedOffset();
	if( Prototype.Browser.IE && navigator.appVersion.indexOf('MSIE 6') != -1 ){
		$('country-selector').setStyle( {top:'15px',left:'-151px'} );
	}else{
		$('country-selector').setStyle( {top:offset[1]+17+'px',left:offset[0]+'px'} );
	}
	$('country-selector').toggle('show');
	if( $('country-selector').visible() ){
		$('country-arrow').src = '/images/icons/arrow-up.png';
	}else{
		$('country-arrow').src = '/images/icons/arrow-down.gif';
	}
}

function change_country( evt ){
	var li = this;
	var id = li.id.replace(/country-/,'') * 1;
	var params = {
		action: 'get_transport_price',
		country_id: id
	};
	new Ajax.Request( 'comprar.php', {parameters:params, onComplete:country_changed} );
}
function country_changed( t ){
	show_countries();
	$$('#country-selector li.countries').invoke( 'show' );
	$('country-'+t.request.parameters.country_id).hide();
	$('country').firstChild.nodeValue = $('country-'+t.request.parameters.country_id).firstChild.nodeValue;
	var sel = $('pais');
	var opt = $A( sel.options ).detect(
		function( el ){
			if( el.value == t.request.parameters.country_id ){
				return true;
			}else{
				return false;
			}
		}
	);
	sel.selectedIndex = opt.index;
	var data = t.responseText.evalJSON();
	$('transport-price').update(data[0] + ' &euro;' );
	delay = data[1];
	update_sum();
	initializeToday();
}
function change_pais( evt ){
	var params = {
		action: 'get_transport_price',
		country_id: $F('pais')
	};
	new Ajax.Updater( 'transport-price', 'comprar.php', {parameters:params, onComplete:pais_changed} );
}
function pais_changed( t ){
	$$('#country-selector li.countries').invoke( 'show' );
	$('country-'+t.request.parameters.country_id).hide();
	$('country').firstChild.nodeValue = $('country-'+t.request.parameters.country_id).firstChild.nodeValue;
	var data = t.responseText.evalJSON();
	$('transport-price').update(data[0] + ' &euro;' );
	delay = data[1];
	update_sum();
	initializeToday();
}

var textMusicOn = '<a href="javascript: stop_music();"><img src="/images/icons/music_off.gif" title="Parar reproducción" border="0" /></a>';
var textMusicOff = '<a href="javascript: load_music();"><img src="/images/icons/music_on.gif" title="Reproducir música seleccionada" border="0" /></a>';
	
function load_music(){
	doc = document.myform;
	var id = doc.id_musica.selectedIndex;
	id = doc.id_musica.options[id].value;
	//alert( id );
	if( id > 0 ){
		music = '<embed src="/music/'+id+'.mid" width="0" height="0" autostart="true"></embed>';
		if (document.getElementById){
			document.getElementById("div_musica").innerHTML = textMusicOn+music;
		}
		else{
			div_musica.innerHTML = textMusicOn+music;
		}
	}
}
function stop_music(){
	if (document.getElementById){
		document.getElementById("div_musica").innerHTML = textMusicOff;
	}
	else{
		div_musica.innerHTML = textMusicOff;
	}
}

function switch_form( active ){
	var doc = document.myform;
	if( active == 0 ){
		textSwitch = true;
		selectSwitch = false;
	}
	else{
		textSwitch = false;
		selectSwitch = true;
	}
	doc.empresa.disabled = textSwitch;
	doc.nombre.disabled = textSwitch;
	doc.apellidos.disabled = textSwitch;
	doc.direccion1.disabled = textSwitch;
	doc.poblacion.disabled = textSwitch;
	doc.provincia.disabled = textSwitch;
	document.getElementById('pais').disabled = textSwitch;
	doc.codigo_postal.disabled = textSwitch;
	doc.telefono.disabled = textSwitch;
	//doc.carta.disabled = textSwitch;
	doc.id_direccion.disabled = selectSwitch;
}

function set_address(){
	var doc = document.myform;
	var id = doc.id_direccion.selectedIndex;
	id = doc.id_direccion.options[id].value;

	if( id == 0 ){
		doc.use_saved_address[1].checked = true;
		switch_form( 1 );
		return;
	}

	if( addresses[id]['empresa'] ){
		doc.empresa.value = addresses[id]['empresa'];
	}
	doc.nombre.value = addresses[id]['nombre'];
	doc.apellidos.value = addresses[id]['apellidos'];
	doc.direccion1.value = addresses[id]['direccion1'];
	doc.poblacion.value = addresses[id]['poblacion'];
	doc.provincia.value = addresses[id]['provincia'];
	if( typeof addresses[id]['fk_pais_id'] > 0 ){
		var opt = $A( $('pais').options ).detect(
			function( el ){
				if( el.value == addresses[id]['fk_pais_id'] ){
					return true;
				}else{
					return false;
				}
			}
		);
		$('pais').selectedIndex = opt.index;
	}
	doc.telefono.value = addresses[id]['telefono'];
	doc.codigo_postal.value = addresses[id]['codigo_postal'];
	if( letter[id] ){
		var re = new RegExp ('//', 'gi') ;
		var newstr = letter[id].replace(re, "\n") ;
		doc.carta.value = newstr;
	}
	//if( music[id] ){ // Deshabilitado hasta nuevo aviso
		//doc.id_musica.options[music[id]].selected = true;
	//}
	/*if( delivery_date[id] ){
		document.getElementById( 'entrega_fecha' ).checked = true;
		document.getElementById( 'f_entrega' ).value = delivery_date[id];
	}
	else{
		document.getElementById( 'entrega_inmediata' ).checked = true;
	}*/
	doc.use_saved_address[0].checked = true;
	switch_form( 0 );
}

function entregaFecha_selected(){
	document.getElementById( 'entrega_fecha' ).checked = true;
}

function check_form(){
	var doc = document.myform;
	var passed = true;
	//alert( 'Checking form');
	if( doc.use_saved_address[1].checked ){
		//alert( 'Not using saved address' );
		if( doc.nombre.value == ''){
			alert( unescape('Indiquez%20votre%20pr%E9nom') );
			doc.nombre.focus();
			passed = false;
		}
		else if( doc.apellidos.value == ''){
			alert( unescape('Indiquer%20le%20nom') );
			doc.apellidos.focus();
			passed = false;
		}
		else if( doc.direccion1.value == ''){
			alert( unescape('Indiquer%20l%27adresse%20de%20l%27envoi') );
			doc.direccion1.focus();
			passed = false;
		}
		else if( doc.poblacion.value == ''){
			alert( unescape('Indiquer%20%20la%20ville%20de%20l%27envoi') );
			doc.poblacion.focus();
			passed = false;
		}
		else if( doc.provincia.value == ''){
			alert( unescape('Indiquer%20le%20d%E9partement%20%20de%20l%27envoi') );
			doc.provincia.focus();
			passed = false;
		}
		else if( doc.codigo_postal.value == ''){
			alert( unescape('Indiquer%20le%20code%20postal%20du%20destinataire') );
			doc.codigo_postal.focus();
			passed = false;
		}
		else if( doc.telefono.value == ''){
			alert( unescape('Indiquer%20le%20num%E9ro%20de%20t%E9l%E9phone%20du%20destinataire') );
			doc.telefono.focus();
			passed = false;
		}
		else if( document.getElementById( 'entrega_fecha' ).checked && (doc.f_entrega.value == '') ){
			alert( unescape('Manque%20la%20date%20de%20livraison') );
			document.getElementById( 'entrega_fecha' ).focus();
			passed = false;
		}
		else{
			if( doc.carta.value == 'Escriba aquí el texto a añadir' ){
				doc.carta.value = '';
			}
		}
	}

	return passed;
}

function CyJS_Utils_IsEmailValid(checkThisEmail){
	var myEMailIsValid = true;
	var myAtSymbolAt = checkThisEmail.indexOf('@');
	var myLastDotAt = checkThisEmail.lastIndexOf('.');
	var mySpaceAt = checkThisEmail.indexOf(' ');
	var myLength = checkThisEmail.length;

	if (myAtSymbolAt < 1 )
	 {myEMailIsValid = false}

	if (myLastDotAt < myAtSymbolAt)
	 {myEMailIsValid = false}

	if (myLength - myLastDotAt <= 2)
	 {myEMailIsValid = false}

	if (mySpaceAt != -1)
	 {myEMailIsValid = false}

	return myEMailIsValid
}

function textCounter( field, cntfield,maxlimit ){
	if (field.value.length > maxlimit) // if too long...trim it!
		field.value = field.value.substring(0, maxlimit);
	// otherwise, update 'characters left' counter
	else
		cntfield.value = maxlimit - field.value.length;
}

function ver(CatUrl){
     window.open(CatUrl,'ver','width=614,height=415,location=no,toolbar=no,directories=no,menubar=no,resizable=no,scrollbars=no,status=no');
}

// Chequea que la fecha en el campo "Fecha de entrega" sea v&aacute;lida...
// En caso de no serlo la pone en blanco
function checkDeliveryDate(){
	if( document.getElementById('f_entrega').value != '' ){
		var fechaCampo = document.getElementById('f_entrega').value;
		var day = fechaCampo.substring( 0, 2 );
		var month = fechaCampo.substring( 3, 5 );
		month = month - 1;
		var year = fechaCampo.substring( 6, 10 );
		var hour = fechaCampo.substring( 11, 13 );
		var minute = fechaCampo.substring( 14, 16 );
		var fecha = new Date( year, month, day, hour, minute, '00' );
		//alert( checkDateIsValid( fecha, year, month, day ) );
		if( checkDateIsValid( fecha, year, month, day ) == true ){
			document.getElementById('f_entrega').value = '';
		}
	}
}
var active_font = false;
function choose_etiqueta( evt ){
	var el = Event.element( evt );
	if( el.tagName.toLowerCase() == 'img' ){
		var radio = el.previous();
	}else{
		var radio = el;
		el = el.next();
	}
	radio.checked = true;
	var t = el.offsetTop;
	var l = el.offsetLeft;
	var font = $F('fuente');
	active_font = font;
	$(font).setStyle( {top: t+'px', left: l+'px',display:'block'} );
	if( el.hasClassName('align-right') ){
		l += +65;
		$(font).setStyle( {left: l+'px'} );
	}
}
function change_font( evt ){
	if( !active_font ) return;
	var el = $(active_font);
	var t = el.offsetTop;
	var l = el.offsetLeft;
	el.hide();
	var font = $F('fuente');
	active_font = font;
	$(font).setStyle( {top: t+'px', left: l+'px',display:'block'} );
}