var myWidth = 0, myHeight = 0, leftPos = 0, topPos = 0;
getSize();

function include(filename)
{
	var head = document.getElementsByTagName('head')[0];
	
	var script = document.createElement('script');
	script.src = filename;
	script.type = 'text/javascript';
	
	head.appendChild(script)
}

function guardarCookie(id,valor)
{
	var validez = 30;
	var caduca = new Date();
	caduca.setTime(caduca.getTime() + (validez*24*60*60*1000));
	
	var contenido = valor;
	document.cookie = escape(id) + "=" + escape(contenido) + "; expires=" + caduca.toString() + "; path=/";
}

function deleteCookie (id)
{
	document.cookie = escape(id) +'='+";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}

function getCookieValue(cookieName)
{
	var exp = new RegExp (escape(cookieName) + "=([^;]+)");
	if (exp.test (document.cookie + ";"))
	{
		exp.exec (document.cookie + ";");
		return unescape(RegExp.$1);
	}
	else return false;
}

function changePrice(idspan,price,aid,actual){
	document.getElementById(idspan).innerHTML = price;
	document.getElementById(document.getElementById(actual).value).style.color = "#2c2c2c";
	document.getElementById(aid).style.color = "rgb(192, 0, 0)";
	document.getElementById(actual).value = aid;
}
function Destacar(idlogo,image,idtitle,tcolor){
	document.getElementById(idlogo).src = image;
	if(idtitle!=null && idtitle!='')
		document.getElementById(idtitle).style.color = tcolor;
}
function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
	d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_showHideLayers() { //v6.0
  var i,p,v,obj,args=MM_showHideLayers.arguments;
  for (i=0; i<(args.length-2); i+=3) if ((obj=MM_findObj(args[i]))!=null) { v=args[i+2];
	if (obj.style) { obj=obj.style; v=(v=='show')?'visible':(v=='hide')?'hidden':v; }
	obj.visibility=v; }
}

//función que despliega y contrae el listado lateral
function desplega(iddesc,forzarDespl,showhide) {
	jQuery(function( $ ){
		var container = $( '#'+iddesc );
		var idactual = document.getElementById('actualdesc').value;
		var actual = $( '#'+idactual );
		if (showhide==1){
		}
		if (iddesc==idactual){
			if (document.getElementById(iddesc).style.display=="none"){
			
				container.slideDown( 1000 );
				if (showhide==1){
					jQuery('#showhide'+idactual).html("<span>"+'<? echo $say_hide;?>'+"</span>");
				}
			} else {
					container.slideUp( 1000 );
					if (showhide==1){
						jQuery('#showhide'+idactual).html("<span>"+'<?=$say_show;?>'+"</span>");
					}
			}
		} else {
			container.slideDown( 1000 );
			actual.slideUp( 1000 );
			if (showhide==1){
				jQuery('#showhide'+iddesc).html("<span>"+'<? echo $say_hide;?>'+"</span>");
				jQuery('#showhide'+idactual).html("<span>"+'<?=$say_show;?>'+"</span>");
			}
		}
	});
	document.getElementById('actualdesc').value = iddesc;
}

//Función que destaca una imágen
function DestacarImagen(id,image) {
	document.getElementById(id).src = image;
}

var popup=null;
// Función que carga un html determinado en el div flotante
function flotante(id,val) {
	var url = "";
	
	if(id=="comprar"){ 
		if(val==undefined)
			url = "http://"+domainName+"/shopping/"; 
		else
			url = "http://"+domainName+"/shopping/"+val; 
	}
	else if(id=="registro"){ 
		if(val==undefined)
			url = "http://"+domainName+"/register/"; 
		else {
			datos = val.split('@#@');
			url = "http://"+domainName+"/register/"+datos[0]+"@@@"+datos[1]+"/";
		}
	}
	else if(id=="contacto"){
		if (val == undefined)
			url = "http://"+domainName+"/contactus/"; 
		else	
			url = "http://"+domainName+"/contactus/"+val+"/";
	}
	else if(id=="confirmation"){
		if (val == undefined)
			url = "http://"+domainName+"/confirmation/"; 
		else	
			{
			url = "http://"+domainName+"/confirmation/"+val;
			}
	}
		else if(id=="forgot"){
		if (val == undefined)
			url = "http://"+domainName+"/forgot_pass/"; 
		else	
			url = "http://"+domainName+"/forgot_pass/"+val+"/";
	}
	else if(id=="login"){ url = "http://"+domainName+"/login/"; }
	else if(id=="guestlist"){
		if (val == undefined)
			url = "http://"+domainName+"/popguestlist/"; 
		else {
			datos = val.split(':::');
			if (datos.length>1) register = 'register/';
			else register = '';
			url = "http://"+domainName+"/popguestlist/"+val+"/"+register; 
		}
	}
	else if(id=="confirm"){ url = "http://"+domainName+"/confirm/"+val+"/"; }
	else if (id=="mailpop") { url= "http://"+domainName+"/mailpop/"+val+"/"; }
	else if(id=="loteria") { url= "http://"+domainName+"/loteria/"+val+"/";  }
	else if(id=="user_profile") { url= "http://"+domainName+"/user_profile/";  }

	if ($('#mies0').val() != undefined)
	{		
		if(url!='') { sendAjax(url,2,'mies0'); }
	}
	else
	{
		if ($('#bt_contenido').val() != undefined)
			if(url!='') { sendAjax(url+"ext/",2,'bt_contenido'); }
		else
			popup = window.open(url,"ventana1","width=920,height=400,toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=yes,copyhistory=no");
	}
}
// función que cierra un overlay
function closeOverlay() {
	if ($('#mies0').val() != undefined)
	{
		$("#mies0").data("overlay").close();
		document.getElementById("mies0").innerHTML = '';
	}
	else
	{
		window.close();
	}
}
// función que carga un overlay
function loadOverlay() {
	if($("#mies0").data("overlay").isOpened())
		$("#mies0").data("overlay").close();
	$("#mies0").data("overlay").load();
}

// función que hace una llamada a un archivo por ajax
function sendAjax(url,actualizar,destino) {
	var xmlhttp=new XMLHttpRequest();
	if(actualizar==1 || actualizar == 0 || actualizar == -1 ||actualizar == -2)
	{
		xmlhttp.onreadystatechange=function()
		{
			if (xmlhttp.readyState==4 && xmlhttp.status==200)
			{
				if (xmlhttp.responseText.charAt(0) != '#')
				{
					datos = xmlhttp.responseText.split('@#@');
					if (!(datos.length > 1)) {
						if ($('#mies0').val() != undefined)
							document.getElementById(destino).innerHTML=xmlhttp.responseText;
					}
					else {
						document.getElementById(destino).innerHTML=datos[1];
					}
					if (actualizar == 1)
					{
						var dat = xmlhttp.responseText.split('#');
						if(dat[0]=='f'){
							$('#error_msg_reg').html(dat[1]);
						}
						else{
							sendAjax('http://'+domainName+'/ajax/login.php?action=repintlogout',4,'log_div');
							if(dat[0]=="close"){
								closeOverlay();
								flotante('confirmation','register/');
							} else {
								if ($('#glid').val())
								{
									ids = $('#glid').val().split(',');
									cant = document.getElementById('quantity'+ids[0]).innerHTML;
									//cant=parseInt($('quantity'+ids[0]).html());
									//closeOverlay();
									addguest(ids[0],cant);
								}
								else
								{
									closeOverlay();
								}
							}
						}
					}
					else
					{
						if (actualizar != -2)
						{
							if ($('#glid').val()!=undefined) {
								sendAjax('http://'+domainName+'/ajax/shopping.php?action=is_logged',10);
								sendAjax('http://'+domainName+'/ajax/facebook.php?action=repintlogin',4,'log_div');
								apuntar($('#glid').val());
							}
							else {
								$('#register_form').hide();
								$('#contentlogin').hide();
								if (actualizar == -1)
								{
									sendAjax('http://'+domainName+'/ajax/shopping.php?action=is_logged',10);
									sendAjax('http://'+domainName+'/ajax/facebook.php?action=repintlogin',4,'log_div');
								}
								else
								{
									sendAjax('http://'+domainName+'/ajax/login.php?action=repintlogout',4,'log_div');
								}
							}
						}
						else
						{
							sendAjax('http://'+domainName+'/ajax/login.php?action=repintlogout',4,'log_div');
							//sendAjax('http://'+domainName+'/ajax/facebook.php?action=repintlogin',4,'facelogin');
							apuntar($('#glid').val());
						}
					}
					if ($('#mies0').val() != undefined)
						$('#log_div').html ('');
				}
				else {
					document.getElementById('error_msg').innerHTML=xmlhttp.responseText;
					if (actualizar == 1) {
						$('#forgot_url').css('color','red');
					}
				}
			}
		}
	}
	else if(actualizar==2)
	{
		xmlhttp.onreadystatechange=function()
		{
			if (xmlhttp.readyState==4 && xmlhttp.status==200)
			{
				document.getElementById(destino).innerHTML=xmlhttp.responseText;
				loadOverlay();
			}
		}
	}
	else if(actualizar==3)
	{
		xmlhttp.onreadystatechange=function()
		{
			if (xmlhttp.readyState==4 && xmlhttp.status==200)
			{
				window.location.href='http://'+domainName+'/'+xmlhttp.responseText;
			}
		}
	}
	else if(actualizar==4)
	{
		xmlhttp.onreadystatechange=function()
		{
			if (xmlhttp.readyState==4 && xmlhttp.status==200)
			{
				document.getElementById(destino).innerHTML=xmlhttp.responseText;
				if(xmlhttp.responseText=='close')
					closeOverlay();
				if(destino == 'partner_zoom')
					$(".scrollablehome").scrollable({ vertical: true, circular: true }).autoscroll({ interval:5000,autoplay:true });
				if(destino=='log_div'){
					sendAjax('http://'+domainName+'/ajax/login.php?action=repintwellcome',4,'hi_div');
				}
				/*else if(destino == 'hi_div') {
					sendAjax('http://'+domainName+'/ajax/login.php?action=repintlogout',4,'log_div');
					alert('entra');
				}*/
			}
		}
	}
	else if (actualizar == 5)
	{
		xmlhttp.onreadystatechange=function()
		{
			if (xmlhttp.readyState==4 && xmlhttp.status==200)
			{
				if(xmlhttp.responseText != 'ok1' && xmlhttp.responseText != '')
					alert (xmlhttp.responseText); //ˇˇˇˇHAY QUE DEPURAR ESTO!!!!!
				else
					if(xmlhttp.responseText != '')
						flotante('comprar');
					else {
						var datos = destino.split(',');
						$('#quantity'+parseInt(datos[0])).html((parseFloat($('#quantity'+parseInt(datos[0])).html()) + parseFloat(datos[1])));
						$('#subtotal'+parseInt(datos[0])).html((parseFloat($('#price'+parseInt(datos[0])).html())*parseFloat($('#quantity'+parseInt(datos[0])).html())));
						$('#total').html((parseFloat(datos[1]) * parseFloat($('#price'+parseInt(datos[0])).html())+parseFloat($('#total').html())));
						$('#tpv_amount').val(parseFloat($('#total').html())*100);
						$('#paypal_amount').val(parseFloat($('#total').html())+parseFloat($('#total').html())*4/100);
						sendAjax('http://'+domainName+'/ajax/shopping.php?action=act_sign&amount='+$('#tpv_amount').val()+'&order='+$('#tpv_order').val()+'&code='+$('#tpv_code').val()+'&currency='+$('#tpv_currency').val()+'&type='+$('#tpv_type').val(),12,'');
					}
			}
		}
	}
	else if (actualizar == 6)
	{
		xmlhttp.onreadystatechange=function()
		{
			if (xmlhttp.readyState==4 && xmlhttp.status==200)
			{
				if(xmlhttp.responseText == 'ok')
				{//alert($('#'+destino).html()+'--'+destino);
					if($('#'+destino).html()!=null)
						document.forms[destino].submit();
					else
						apuntar(destino);
				}
				else
					alert(xmlhttp.responseText);
			}
		}
	}
	else if (actualizar == 7)
	{
		xmlhttp.onreadystatechange=function()
		{
			if (xmlhttp.readyState==4 && xmlhttp.status==200)
			{
				var datos = xmlhttp.responseText.split('@#@');
				if(xmlhttp.responseText=='ok' || datos[0] == 'ok')
					flotante('guestlist',datos[1]);
				else
					if(xmlhttp.responseText!='') {
						//datos[0] = datos[0].replace('@tipo@', 'guestlist')
						//flotante('guestlist',datos[0]);
						alert(datos[0]);
					}
					else {
						var args = destino[0]+'/'+destino[1]+'/';
						//alert(args);
						flotante('comprar',args);
					}
			}
		}
	}
	else if (actualizar == 8)    //function para traducir
	{
		xmlhttp.onreadystatechange=function()
		{
			if (xmlhttp.readyState==4 && xmlhttp.status==200)
			{
				var dat = xmlhttp.responseText.split('@#@');
					$('#'+dat[1]).html(dat[0]);
			}
		}
	}
	else if (actualizar == 9)    //send mail from contact us form
	{
		xmlhttp.onreadystatechange=function()
		{
			if (xmlhttp.readyState==4 && xmlhttp.status==200)
			{
				var datos = xmlhttp.responseText.split('@#@');
				if (datos[0] != 'ok')
				{
					$('#event_error_msg').css('color','red');
					$('#event_error_msg').html(xmlhttp.responseText);
				}
				else
				{
					$('#event_error_msg').html(datos[1]);
					limpiarDatosGroupRequest();
					
					setTimeout(function() {
						$('#event_error_msg').html('');
					}, 5000);
					
					/*if($("#mies0").data("overlay").isOpened())
						closeOverlay();*/	
				}
			}
		}
	}
	else if (actualizar == 10)    //send mail from contact us form
	{
		xmlhttp.onreadystatechange=function()
		{
			if (xmlhttp.readyState==4 && xmlhttp.status==200)
			{
				if(xmlhttp.responseText!='ok')
					flotante ('registro');
			}
		}
	}
	else if (actualizar == 11)    //send mail from contact us form
	{
		xmlhttp.onreadystatechange=function()
		{
			if (xmlhttp.readyState==4 && xmlhttp.status==200)
			{
				var datos=xmlhttp.responseText.split('@#@');
				if(datos[0]=='ok')
				{
					$('#hi_div').html(datos[1]);
					sendAjax('http://'+domainName+'/ajax/login.php?action=repintlogout',4,'log_div');
					closeOverlay();
				}
				else
				{
					closeOverlay();
					flotante('registro');
				}
			}
		}
	}
	else if (actualizar == 12)
	{
		xmlhttp.onreadystatechange=function()
		{
			if (xmlhttp.readyState==4 && xmlhttp.status==200)
			{
				$('#tpv_sign').val(xmlhttp.responseText);
			}
		}
	}
	else if (actualizar == 13)
	{
		xmlhttp.onreadystatechange=function()
		{
			if (xmlhttp.readyState==4 && xmlhttp.status==200)
			{
				alert(xmlhttp.responseText);
			}
		}
	}
	else if (actualizar == 14)
	{
		xmlhttp.onreadystatechange=function()
		{
			if (xmlhttp.readyState==4 && xmlhttp.status==200)
			{
				//para la comprobación del limite de un servicio
				//si ok, hace un huevo de cosas y si caca no hace nada :P
			}
		}
	}
	
	xmlhttp.open("GET",url,true);
	xmlhttp.send();
}

function logfacebook(opc,array)
{
	FB.init({
		appId   : facebook_id,
		session : array,
		status  : true, // check login status
		cookie  : true, // enable cookies to allow the server to access the session
		xfbml   : true // parse XFBML
	});
	
	// whenever the user logs in, we refresh the page
	FB.Event.subscribe('auth.login', function() {
		sendAjax('http://'+domainName+'/ajax/facebook.php?action=log_in',opc,'hi_div');
	});
	FB.Event.subscribe('auth.logout', function() {
		sendAjax('http://'+domainName+'/ajax/facebook.php?action=log_out',4,'hi_div');
	});
		
	if ($.browser.webkit || $.browser.safari) {
		FB.login(
			function(response) {
				if (response.session) {
					if (!response.perms) {
						FB.logout(function(response) {
						});
					}
				}
			}, {perms:'user_birthday,user_location,user_hometown,email,read_friendlists,user_website,user_work_history'});
	} else { 
		FB.login(
			function(response) {
				if (response.session) {
					if (!response.perms) {
						FB.logout(function(response) {
						});
					}
				}
			}, {perms:'user_birthday,user_location,user_hometown,email,read_friendlists,user_website,user_work_history'});
	}
}

// función que valida el login
function validarLogin() {
	var user = $('#email_login').val();
	var pass = $('#pass_login').val();
	
	return 0;
	//sendAjax("",2,'');
	//if(pass!=''){ mensaje_error = ''; }
}

function getSize() {
	if( typeof( window.innerWidth ) == 'number' ) {
	//Non-IE
	var myWidth = window.innerWidth;
	var myHeight = window.innerHeight;
	} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
	//IE 6+ in 'standards compliant mode'
	var myWidth = document.documentElement.clientWidth;
	var myHeight = document.documentElement.clientHeight;
	} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
	//IE 4 compatible
	var myWidth = document.body.clientWidth;
	var myHeight = document.body.clientHeight;
	}
}

function logIn (to)
{
	var email = $('#login_email').val();
	var pass = $('#login_pass').val();
	if (pass != undefined)
	{
		if ($('#remember_me').attr('checked'))
		{
			guardarCookie('usr',email);
			guardarCookie('pass',hex_md5(pass));
		}
		sendAjax('http://'+domainName+'/ajax/login.php?action=log_in&pass='+pass+'&email='+email,to,'hi_div');
	}
	else
		sendAjax('http://'+domainName+'/ajax/login.php?action=remember&email='+email,4,'error_msg');
}

function logout ()
{
	deleteCookie('usr');
	deleteCookie('pass');
	sendAjax('http://'+domainName+'/ajax/login.php?action=log_out',3,'');
}

function forgotpass ()
{
	sendAjax('http://'+domainName+'/ajax/login.php?action=forgot_pass',4,'pass_div');
}

function register(condition)
{
	var email = $('#email').val();
	var reemail = $('#reemail').val();
	var pass = $('#pass').val();
	var repass = $('#repass').val();
	var name = $('#name').val();
	var lastname = $('#lastname').val();
	var day = $('#day').val();
	var month = $('#month').val();
	var year = $('#year').val();
	var sex = $('#sex').val();
	var prefix = $('#prefix').val();
	var mobile = $('#mobile').val();
	var country = $('#country').val();
	var city = $('#city').val();
	var company = $('#company').val();
	var terms = $('#terms').attr('checked');
	var news = $('#news').attr('checked');
	var birth = year+'/'+month+'/'+day;
	var tel = prefix+mobile;

	var lista = new Array();
	lista[0] = email+'@#@email';
	lista[1] = pass+'@#@pass';
	lista[2] = name+'@#@name';
	lista[3] = lastname+'@#@lastname';
	lista[4] = day+'@#@day';
	lista[5] = month+'@#@month';
	lista[6] = year+'@#@year';
	lista[7] = sex+'@#@sex';
	lista[8] = country+'@#@country';
	lista[9] = mobile+'@#@mobile';
	lista[10] = reemail+'@#@reemail';
	lista[11] = repass+'@#@repass';

	if ($('#list').val() != undefined)
		var add = '&list='+$('#list').val()+'&id_usr='+$('#id_usr_list').val();
	else 
		var add = '';
	
	if (validateForm(lista,12))
	{
		if (email == reemail && pass == repass && terms)
		{
			sendAjax('http://'+domainName+'/ajax/login.php?action=register&email='+email+'&pass='+pass+'&name='+name+'&lastname='+lastname+'&birth='+birth+'&sex='+sex+'&tel='+tel+'&country='+country+'&city='+city+'&company='+company+'&news='+news+add+'&condition='+condition,1,'hi_div');
			//$('#register_form').hide();
		}
		else
		{
			if (!terms)
				var msg = 'accept_terms';
		
			if (pass != repass)
			{
				var msg = 'invalid_password';
				correct ('pass','');
				correct ('repass','');
			}
		
			if (email != reemail)
			{
				var msg = 'invalid_email1';
				correct ('email','');
				correct ('reemail','');
			}
			
			setMsg (msg,'red');
		}
	}
}

function modify_userdata(pass_verify)
{
	var name = $('#name').val();
	var lastname = $('#lastname').val();
	var country = $('#country').val();
	var city = $('#city').val();
	var email = $('#email').val();
	var news = $('#news').attr('checked');
	var pass = $('#pass').val();
	var repass = $('#repass').val();
	var day = $('#day').val();
	var month = $('#month').val();
	var year = $('#year').val();	
	var sex = $('#sex').val();
	var tel = $('#mobile').val();
	var company = $('#company').val();	
	var birth = year+'/'+month+'/'+day;
	var lista = new Array();
	lista[0] = name+'@#@name';
	lista[1] = lastname+'@#@lastname';
	lista[2] = country+'@#@country';	
	lista[3] = email+'@#@email';	
	lista[4] = pass+'@#@pass';
	lista[5] = repass+'@#@repass';	
	lista[6] = day+'@#@day';
	lista[7] = month+'@#@month';
	lista[8] = year+'@#@year';
	lista[9] = sex+'@#@sex';
	lista[10] = tel+'@#@mobile';

	var pass_v = hex_md5($('#password_verify').val());
	
	if (validateForm(lista,11))
	{
		if (pass == repass && pass_v == pass_verify)
		{
			sendAjax ('http://'+domainName+'/ajax/login.php?action=modify&email='+email+'&pass='+pass+'&name='+name+'&lastname='+lastname+'&birth='+birth+'&sex='+sex+'&tel='+tel+'&country='+country+'&city='+city+'&company='+company+'&news='+news,1,'hi_div');
		}
		else
		{		
			if (pass != repass)
			{
				var msg = 'invalid_password';
				correct ('pass','');
				correct ('repass','');
			}			
			setMsg (msg,'red');
			if (pass_v != pass_verify)
			{
				var msg = 'insert_psw';
				correct ('password_verify','');
			}			
			setMsg (msg,'red');
		}
	}
}

function validateForm(lista,len)
{
	var result = true;
	var field;
	var cant = 0;
	
	for (i = 0; i < len; i++)
	{
		var datos = lista[i].split ('@#@');
		
		if (datos[1] != 'email' && datos[1] != 'birthday') {
			if (datos[1]!='sex') {
				result = result && (datos[0] != '');
				field = datos[0] != '';
			}
			else {
				result = result && (datos[0] != 0);
				field = datos[0] != 0;
			}
			if (field)
				if (datos[1] == 'sex' || datos[1] == 'day' || datos[1] == 'month' || datos[1] == 'year')
					var tipus = 'select';
				else
					var tipus = '';
				bueno(datos[1],tipus);
		}
		else
		{
			if (datos [1] == 'email') {
				result = result && validateEmail(datos[0]);
				field = validateEmail(datos[0]);
				if(field) {
					$('#'+datos[1]).css('border','none');
				}
			}
			else
				if (datos[1] == 'birthday') {
					result = result && validateBirth(datos[0]);
					field = validateBirth(datos[0]);
					if (field)
						$('#'+datos[1]).css('color','none');
				}
		}
		
		if (!field)
		{
			if (cant==0)
				//setMsg('You must correct the '+datos[1],'red');
				setMsg('must_correct','red');
			cant++;
			if (datos[1] == 'sex' || datos[1] == 'day' || datos[1] == 'month' || datos[1] == 'year')
				var tipus = 'select';
			else
				var tipus = '';
			correct(datos[1],tipus);
		}
	}
	
	return result;
}

function setMsg (msg,color)
{
	if($('#mensaje').val() == undefined) {
		$('#error_msg').css('color',color);
		//$('#error_msg').html(msg);
		traducir(msg, 'error_msg');
	}
	else {
		$('#mensaje').css('color',color);
		//$('#mensaje').html(msg);
		traducir(msg, 'mensaje');
	}
}

function correct (name,tipus)
{
	if (tipus == 'select')
		$('#'+name).css('color','red');
	else
		$('#'+name).css('border','2px solid red');
}
function bueno (name,tipus)
{
	if (tipus == 'select')
		$('#'+name).css('color','#B1B1B1');
	else
		$('#'+name).css('border','');
}

function validateEmail(elementValue)
{  
    var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;  
    return emailPattern.test(elementValue);  
}

function validateBirth(elementValue)
{
    var bithPattern = /^\d{4}(\/)\d{2}\1\d{2}/;
    return bithPattern.test(elementValue);  
}

function loadcompra(id,cant)
{
	if (cant == undefined)
		cant = 1;
	sendAjax('http://'+domainName+'/ajax/shopping.php?action=set_buy&id='+id+'&cant='+cant,5,'');
}

function actcant(suma,id,gl)
{
	if(!(parseFloat($('#quantity'+id).html())== 0 && suma == -1) && gl == undefined)
	{
		if (parseFloat($('#quantity'+id).html()) != 0)
			sendAjax('http://'+domainName+'/ajax/shopping.php?action=set_buy&id='+id+'&cant='+suma+'&add',5,id+','+suma);
		else
			sendAjax('http://'+domainName+'/ajax/shopping.php?action=del_buy&id='+id,5,id+','+suma);

		//sendAjax('http://'+domainName+'/ajax/shopping.php?action=act_sign&amount='+$('#tpv_amount').val()+'&order='+$('#tpv_order').val()+'&code='+$('#tpv_code').val()+'&currency='+$('#tpv_currency').val()+'&type='+$('#tpv_type').val(),12,'');
		
		if(parseFloat($('#total').html()) == 0)
			closeOverlay();
	}
	else
		if (!(parseFloat($('#quantity'+id).html())== 0 && suma==-1) && gl != undefined)
		{
			$('#quantity'+id).html((parseFloat($('#quantity'+id).html()) + suma));
		}
}

function actcant_def(suma,id) {
	var destino = new Array();
	
	destino[0] = 'quantity'+id;
	destino[1] = 'total';
	destino[3] = 'paymethods';
	destino[2] = 'subtotal'+id;
	
	sendAjax_gen('http://'+domainName+'/index_.php?page=book&accion=actbook&id='+id+'&op='+suma+'&total='+$('#total').html(),1,destino);
}

function deleteInst_def(id) {
	actcant_def(-(parseFloat($('#quantity'+id).html())), id);
}

function deleteInst(id)
{
	var ids = id.split('_');
	
	var total = parseFloat($('#total').html());
	var subtotal = parseFloat($('#subtotal'+ids[0]).html());
	$('#total').html((total - subtotal));
	$('#subtotal'+ids[0]).html(0);
	$('#quantity'+ids[0]).html(0);
	$('#tpv_amount').val(parseFloat($('#total').html()));
	$('#paypal_amount').val(parseFloat($('#total').html()));
	if(parseFloat($('#total').html()) == 0 || ids[1]==0)
	{
		sendAjax('http://'+domainName+'/ajax/shopping.php?action=clear',-5,ids[0]);	//He puesto el -5 porque no hay manera de decirle que no actualice (Javi)
		closeOverlay();
	}
}

function confirmLogin (form)
{
	var forlogging = '';
	if($('#idsellticket').val() != undefined)
	{
		if($('#paypal_amount').val() != undefined)
			{
			var precio = $('#paypal_amount').val();
			precio = precio + 2;
			}
		else
			var precio = $('#tpv_amount').val()/100;
		forlogging = '&id='+$('#idsellticket').val()+'&type='+form+'&precio='+precio;
	}
	sendAjax('http://'+domainName+'/ajax/shopping.php?action=is_logged'+forlogging,6,form);
}

function confirmLogin_def(form) {
	sendAjax_gen('http://'+domainName+'/index_.php?page=index&accion=isLogged',2,form);
}

function sendEventForm()
{
	var name = encodeURIComponent($('#name').val());
	var phone = $('#event_phone').val();
	var email = $('#event_email').val();
	var type = encodeURIComponent($('#event_type').val());
	var local = encodeURIComponent($('#event_local').val());
	var date = $('#event_date').val();
	var number = $('#event_people').val();
	var comments = encodeURIComponent($('#event_comments').val());
	
	bueno('name', '');
	bueno('event_phone', '');
	bueno('event_email', '');
	bueno('event_type', 'select');
	bueno('event_local', 'select');
	bueno('event_date', '');
	bueno('event_people', '');
	bueno('event_comments', '');
	
	var send = true;
	if(name == null || name == "")
	{
		correct('name', '');
		send = false;
	}
	if(phone == null || phone == "")
	{
		correct('event_phone', '');
		send = false;
	}
	if(email == null || email == "" || !validateEmail(email))
	{
		correct('event_email', '');
		send = false;
	}
	if(type == null || type == "")
	{
		correct('event_type', 'select');
		send = false;
	}
	if(local == null || local == "")
	{
		correct('event_local', 'select');
		send = false;
	}
	if(date == null || date == "")
	{
		correct('event_date', '');
		send = false;
	}
	if(number == null || number == "")
	{
		correct('event_people', '');
		send = false;
	}
	if(comments == null || comments == "")
	{
		correct('event_comments', '');
		send = false;
	}
	
	sendAjax('http://'+domainName+'/ajax/addselfevent.php?action=send_form&name='+name+'&phone='+phone+'&email='+email+'&type='+type+'&local='+local+'&date='+date+'&number='+number+'&comments='+comments,9,'mensaje_newevent');
}

function limpiarDatosGroupRequest()
{
	$('#name').val("");
	$('#event_phone').val("");
	$('#event_email').val("");
	$("#event_type").attr('selectedIndex', 0);
	$("#event_local").attr('selectedIndex', 0);
	$('#event_date').val("");
	$('#event_people').val("");
	$('#event_comments').val("");
}

function addguest(id,cant)
{
	if (cant == undefined || isNaN(cant)) {
		cant = $('#guest_cant'+id).val();
	}
	
	if ($('#glid').val() != undefined) {
		otro = '&register';	
	} else {
		otro = '';
	}
	//alert(otro);
	var lista = new Array();
	lista[0] = cant;
	lista[1] = id;
	sendAjax('http://'+domainName+'/ajax/addguest.php?action=add&gl='+id+'&cant='+cant+otro,7,lista);
}

function apuntar(lists)
{
	if (lists != '') {
		var insts = lists.split(',');
		var cant = 0;
		for (i=0; i<insts.length;i++)
		{
			if(parseFloat($('#quantity'+insts[i]).html()) != 0)
			{
				cant++;
				var lista = new Array();
				lista[0] = parseFloat($('#quantity'+insts[i]).html());
				lista[1] = insts[i];
				sendAjax('http://'+domainName+'/ajax/addguest.php?action=add&gl='+insts[i]+'&cant='+parseFloat($('#quantity'+insts[i]).html()));
			}
		}
		if (cant!=0)
			flotante('guestlist',lista[1]);
	}
}

function addMassmail(id)
{
	var email = $('#mass_email'+id).val();
	
	sendAjax('http://'+domainName+'/ajax/addmassmail.php?action=add_mail&email='+email,4,'mensaje_massmail'+id);
}

function actcalendar(dia,from,cont,accion)
{
	var data = dia.split("/");
	/*alert('eooooooooo3'+'http://'+domainName+'/index_.php?page='+cont+'&accion='+accion+'&dia='+dia+'&ajax');*/

	sendAjax_gen('http://'+domainName+'/index_.php?page='+cont+'&accion='+accion+'&search='+dia+'&ajax',1,'list_event_homepage');	


	//if (from="_")
	//sendAjax('http://'+domainName+'/includes/boxbody'+from+'_php.php?search='+dia+'&from='+from,4,'calendar');
	//updateBasket('http://'+domainName+'/calendar/calendario1.php?more=same&m='+data[1]+'&year='+data[0]+'&from='+from+'&day='+data[2],'amici');
}
function actcocktail(dia,objeto)
{
	/*alert('eooooooooo3'+'http://'+domainName+'/index_.php?page='+cont+'&accion='+accion+'&dia='+dia+'&ajax');*/
	
	$('.links_fechas_cocktail').each(function(index) {
		$(this).css('color','black');
		$(this).css('font-size','14px');	
		$(this).css('cursor','pointer');			
	});
	$(objeto).css('color','#b48845');
	$(objeto).css('font-size','17px');	
	
	//sendAjax_gen('http://'+domainName+'/index_.php?page=Cocktails&accion=listarEDate&dia='+dia,1,'cocktail_date');	
	sendAjax_gen('http://'+domainName+'/index_.php?page=Cocktails&accion=listarECocktails&dia='+dia,1,'box_invite');	


	//if (from="_")
	//sendAjax('http://'+domainName+'/includes/boxbody'+from+'_php.php?search='+dia+'&from='+from,4,'calendar');
	//updateBasket('http://'+domainName+'/calendar/calendario1.php?more=same&m='+data[1]+'&year='+data[0]+'&from='+from+'&day='+data[2],'amici');
}

function loadcompraevent(idinst)
{
	var datos = $('#combo_ticket'+idinst).val().split("_");
	var id = datos[0];
	var icon = datos[1];
	if(icon == 5)
		addguest(id,$('#guest_cant'+idinst).val());
	else loadcompra(id,$('#guest_cant'+idinst).val());
}

function checklimit(id)
{
	var datos = $('#combo_ticket'+id).val().split("_");
	if(datos[4]!=null) var i = datos[4];
	if(datos[3]=='soldout')
	{
		$('#compra'+id).hide();
		traducir("say_soldout", 'nocompra'+id);
		$('#nocompra'+id).show();
	}
	else if(datos[2]=='passed')
	{
		$('#compra'+id).hide();
		traducir('say_filnalized', 'nocompra'+id);
		$('#nocompra'+id).show();	
	}
	else if(datos[7]!=1)
	{
		$('#compra'+id).hide();
		traducir('not_avaliable', 'nocompra'+id);
		$('#nocompra'+id).show();	
	}
	else
	{
		$('#compra'+id).show();
		$('#nocompra'+id).hide();
		if(datos[1] != '5')
		{
			$('#addorcompra'+i).html("<img id=\"add"+i+"\" onmouseover=\"Destacar('add"+i+"','http://"+domainName+"/images/on_trolley20.png');\" onmouseout=\"Destacar('add"+i+"','http://"+domainName+"/images/off_trolley20.png');\" src=\"http://"+domainName+"/images/off_trolley20.png\" onclick=\"loadcompraevent('"+id+"')\" style=\"cursor:pointer\" >");
		}
		else
			$('#addorcompra'+i).html("<img id=\"add"+i+"\" onmouseover=\"Destacar('add"+i+"','http://"+domainName+"/images/on_add20.png');\" onmouseout=\"Destacar('add"+i+"','http://"+domainName+"/images/off_add20.png');\" src=\"http://"+domainName+"/images/off_add20.png\" onclick=\"loadcompraevent('"+id+"')\" style=\"cursor:pointer\" >");
		
	}
	$('#prev_price'+i).css('display','none');
	if(datos[5]!=null && datos[5]!='')
	{
		$('#prev_price'+i).html(datos[5]+'&euro;');
		$('#prev_price'+i).css('display','block');
	}
	$('#act_price'+i).html(datos[6]+'&euro;');
}

function traducir(palabra,id)
{
	sendAjax('http://'+domainName+'/includes/traducir.php?trad='+palabra+'&id='+id,8);
}
function sendmail()
{
	var problem = $('#problem').val();
	var name = $('#name').val();
	var phone = $('#phone').val();
	var email = $('#email').val();
	var time_call = $('#time_call').val();
	var comments = $('#comments').val();
	
	bueno('phone', '');
	bueno('email', '');
	bueno('name', '');
	
	var lista = new Array();
	lista[0] = email+'@#@email';
	
	var send = true;
	if(name == null || name == "")
	{
		correct('name', '');
		send = false;
	}
	if((phone == null || phone == "") && (email == null || email == ""))
	{
		correct('phone', '');
		correct('email', '');
		send = false;
	}
	if(email != null && email != "")
		send = validateForm(lista, 1);
		
	sendAjax('http://'+domainName+'/includes/contactus_sendmail.php?send='+send+'&name='+name+'&phone='+phone+'&email='+email+'&problem='+problem+'&time_call='+time_call+'&comments='+comments,9);
	
}

function PrintOverlay()
{
	var WindowObject = window.open('', "TrackHistoryData", 
		"width=420,height=225,top=250,left=345,toolbars=no,scrollbars=no,status=no,resizable=no");
	WindowObject.document.write(DocumentContainer.innerHTML);

	WindowObject.document.close();
	WindowObject.focus();
	WindowObject.print();
	WindowObject.close();
}

function cal_form (id)
{
	document.getElementById('calfrom'+id).submit();
}

function showpartner(id, lang)
{
	sendAjax('http://'+domainName+'/includes/partners_zoom.php?partner='+id+'&lang='+lang,4,'partner_zoom');
}

function partner_showinfo(field)
{
	var elem = document.getElementById(field);
	if(elem.style.display == "block")
	{
		$(elem).slideUp(500);
		jQuery('#'+field+'_show').html('<img src="http://'+domainName+'/images/show_arrows.png" style="position: relative;right: 1px;top: 3px;"><span>Show</span>');
	}
	else
	{
		$(elem).slideDown(1000);
		jQuery('#'+field+'_show').html('<img src="http://'+domainName+'/images/hide_arrows.png" style="position: relative;right: 1px;top: 3px;"><span>Hide</span>');
	}
}

function ReinitializeAddThis() //function for AddThis on ajax. Force its load using "<iframe style="display: none;" onload="javascript:ReinitializeAddThis();"></iframe>"
{
	if (window.addthis) {
		window.addthis.ost = 0;
		window.addthis.ready();
	}
}

function loteria_mail(idevent, iduser)
{
	var list_mail = document.getElementById('loteria_mail').value;
	bueno('loteria_mail', '');
	var error = false;
	if (list_mail != null && list_mail != '')
	{	
		var email = list_mail.split(",");
		for(i=0; i < email.length; i++)
		if(!validateEmail(email[i].trim()))
			error = true;
	}	
	else
		error = true;
	
	if(!error)
		sendAjax('http://'+domainName+'/includes/loteria_mail.php?list_mail='+list_mail+'&event='+idevent+'&iduser='+iduser,4,'loteria_error');
	else{
		correct('loteria_mail', '');
		traducir('comma_separate', 'loteria_error');
	}
}

function user_data_select(my_type,lang,desde)
{
	var modify = '';
	if(my_type == "modify")
	{
		my_type = 'my_data';
		modify = '&modify=true';
	}
	if(my_type!=null && my_type!='' && my_type!=undefined)
	{
		document.getElementById('my_data').style.color = (my_type == 'my_data')?'#960':'';
		document.getElementById('my_hist').style.color = (my_type == 'my_hist')?'#960':'';
		document.getElementById('my_events').style.color = (my_type == 'my_events')?'#960':'';
		document.getElementById('my_gl').style.color = (my_type == 'my_gl')?'#960':'';
	}
	sendAjax('http://'+domainName+'/includes/user_data_container.php?my_type='+my_type+'&lang='+lang+'&desde='+desde+modify,4,'user_data_container');
}

function user_resume(url)
{
	sendAjax(url,4,'user_data_container');
}

function validar_onEnter(e, opc)
{
	if(e && e.keyCode == 13)
		logIn(opc);
}
function areUsure(elemid,url, eventurl)
{
	document.getElementById(elemid).innerHTML = '<div style="" id="ask'+elemid+'"></div>'+
												'<div class="" style="" OnMouseOut="Destacar(\'yes'+elemid+'\',\'http://'+domainName+'/images/yes_off.png\');" OnMouseOver="Destacar(\'yes'+elemid+'\',\'http://'+domainName+'/images/yes_on.png\');" onClick="deletegl(\''+elemid+'\', \''+url+'\', \''+eventurl+'\')">'+	
												'<input id="yes'+elemid+'" type="image" src="http://'+domainName+'/images/yes_off.png" value="yes" />'+
												'</div>'+
												'<div class="" style="" OnMouseOut="Destacar(\'no'+elemid+'\',\'http://'+domainName+'/images/no_off.png\');" OnMouseOver="Destacar(\'no'+elemid+'\',\'http://'+domainName+'/images/no_on.png\');" onClick="notsure(\''+elemid+'\', \''+url+'\',\''+eventurl+'\')">'+	
												'<input id="no'+elemid+'" type="image" src="http://'+domainName+'/images/no_off.png" value="no" />'+
												'</div>';			
	traducir('be_sure', 'ask'+elemid);
}
function notsure(elemid,url,eventurl)
{
	document.getElementById(elemid).innerHTML = '<a id="a_'+elemid+'" style="color:#960; font-size: 14px;" href="#" onclick="areUsure(\''+elemid+'\', \''+url+'\',\''+eventurl+'\')"></a>';
	traducir('say_unsubscribe', 'a_'+elemid);
}
function deletegl(elemid,url,eventurl)
{
	document.getElementById(elemid).innerHTML = '<div id="a_'+elemid+'" ></div>'+
												'<div class="" style="width: 35px;" OnMouseOut="Destacar(\'againgl'+elemid+'\',\'http://'+domainName+'/images/joingl_off.png\');" OnMouseOver="Destacar(\'againgl'+elemid+'\',\'http://'+domainName+'/images/joingl_on.png\');">'+	
												'<a href="'+eventurl+'"><img id="againgl'+elemid+'" src="http://'+domainName+'/images/joingl_off.png"/></a>'+
												'</div>';
	sendAjax(url,13);
	traducir('deleted', 'a_'+elemid);	
}

function showCats(id) {
	$('#cats'+id).toggle();
	var show_off ="/images/icons/show_off.gif";
	var show ="/images/icons/show_on.gif";	
	var hide_off = "/images/icons/hide_off.gif";	
	var hide = "/images/icons/hide_on.gif";		
	if($('#cats'+id).css('display')=='none') {
		$('#link_to_show'+id).attr("src",show_off);
		$('#link_to_show'+id).attr("onmouseout",show_off);
		$('#link_to_show'+id).attr("onmouseover",show);		
	} else {
		$('#link_to_show'+id).attr("src",hide_off);		
		$('#link_to_show'+id).attr("onmouseout",hide_off);	
		$('#link_to_show'+id).attr("onmouseover",hide);			
	}
}

function slide(name,eso) {
	$('#'+name).slideToggle(500);
	
	html = $(eso).html();
	if(html.indexOf('show_') != -1) {
		while(html.indexOf('show_') != -1)
			html = html.replace('show_','hide_');
	} else {
		while(html.indexOf('hide_') != -1)
			html = html.replace('hide_','show_');
	}
	
	$(eso).html(html);
}
/***** función que hace una llamada a un archivo por ajax *****/
function sendAjax_gen(url,actualizar,destino)
{
	var xmlhttp=new XMLHttpRequest();
	if(actualizar==1)
	{
		xmlhttp.onreadystatechange=function()
		{
			if (xmlhttp.readyState==4 && xmlhttp.status==200)
			{
				if (!isArray(destino)) {
					print(destino,xmlhttp.responseText);
				} else {
					var res = xmlhttp.responseText.split('@#@');
					for (var i = 0; i<res.length; i++) {
						print(destino[i],res[i]);
					}
				}
			}
		}
	} else if (actualizar==2) {
		xmlhttp.onreadystatechange=function() {
			if (xmlhttp.readyState==4 && xmlhttp.status==200) {
				if(xmlhttp.responseText=="yes")
					$('#'+destino).submit();
				else
					alert(xmlhttp.responseText);
			}
		}
	} else if (actualizar==3) {
		xmlhttp.onreadystatechange=function() {
			if (xmlhttp.readyState==4 && xmlhttp.status==200) {
				//alert(xmlhttp.responseText);
				window.location.reload();
			}
		}
	} else if (actualizar==4) {
		xmlhttp.onreadystatechange=function() {
			if (xmlhttp.readyState==4 && xmlhttp.status==200) {
				//alert(xmlhttp.responseText);
				document.getElementById(destino).innerHTML=xmlhttp.responseText;
				loadOverlay();
			}
		}
	}
	xmlhttp.open("GET",url,true);
	xmlhttp.send();
}

function isArray(testObject) {
    return testObject && !(testObject.propertyIsEnumerable('length')) && typeof testObject === 'object' && typeof testObject.length === 'number';
}

function print(destino,texto) {
	if(destino!="evaluate_js") {
		if (texto != '') {
			//document.getElementById(destino).innerHTML = texto;
			$('#'+destino).html(texto);
			var ob = document.getElementById(destino).getElementsByTagName("script");
			for(var i=0; i<ob.length; i++){
				if(ob[i].text!=null) 
					eval(ob[i].text);
			}
		}
	} else {
		eval(texto);
	}
}

function get_lang(type,section,id,div) {
	if(withhttps!=undefined && withhttps==true)
		sendAjax_gen('https://'+domainName+'/index_.php?page=index&accion=get_lang&obj_id='+id+'&section='+section+'&type='+type,1,div);
	else
		sendAjax_gen('http://'+domainName+'/index_.php?page=index&accion=get_lang&obj_id='+id+'&section='+section+'&type='+type,1,div);
}

function loginFacebook() {
	if ($.browser.webkit || $.browser.safari) {
		FB.login(
			function(response) {
				if (response.session) {
					if (!response.perms) {
						FB.logout(function(response) {
						});
					}
				}
			}, {perms:'user_birthday,user_location,user_hometown,email,read_friendlists,user_website,user_work_history'});
	} else { 
		FB.login(
			function(response) {
				if (response.session) {
					if (!response.perms) {
						FB.logout(function(response) {
						});
					}
				}
			}, {perms:'user_birthday,user_location,user_hometown,email,read_friendlists,user_website,user_work_history'});
	}
}

var MM_contentVersion = 6;
var plugin = (navigator.mimeTypes && navigator.mimeTypes["application/x-shockwave-flash"]) ? navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin : 0;
if ( plugin ) {
		var words = navigator.plugins["Shockwave Flash"].description.split(" ");
		for (var i = 0; i < words.length; ++i)
		{
		if (isNaN(parseInt(words[i])))
		continue;
		var MM_PluginVersion = words[i]; 
		}
	var MM_FlashCanPlay = MM_PluginVersion >= MM_contentVersion;
}
else if (navigator.userAgent && navigator.userAgent.indexOf("MSIE")>=0 
&& (navigator.appVersion.indexOf("Win") != -1)) {
	document.write('<SCR' + 'IPT LANGUAGE=VBScript\> \n'); //FS hide this from IE4.5 Mac by splitting the tag
	document.write('on error resume next \n');
	document.write('MM_FlashCanPlay = ( IsObject(CreateObject("ShockwaveFlash.ShockwaveFlash." & MM_contentVersion)))\n');
	document.write('</SCR' + 'IPT\> \n');
}

if(withhttps!=undefined && withhttps==true)
	url='https://'+domainName+'/index_.php?accion=set_flash&id='+MM_FlashCanPlay;
else
	url='http://'+domainName+'/index_.php?accion=set_flash&id='+MM_FlashCanPlay;
var xmlhttp1=new XMLHttpRequest();
xmlhttp1.open("GET",url,false);
xmlhttp1.send(null);
url='';
