jQuery.extend(jQuery.validator.messages, {
 nif:"NIF",
 passw:'La contraseña debe tener entre 6 y 12 caracteres, y al menos un dígito, una minúscula y una mayúscula. No se permiten otros caracteres.'
});


errorCIFNIF='El formato de NIF no es correcto. ej: 12345678Z ó B12345678';
errorNIFLetra='La letra del NIF no se corresponde con su numero.';
errorCIFLetra='La letra del NIF no se corresponde con su numero.';
errorCIFGen='El NIF introducido no es correcto.';

flagAddProduct = false;

jQuery.validator.addMethod("passw", function(value, element) { 
	passwOk=false;										 
											 
	condPassw1=value.search(/^(.{6,12})?$/);
	condPassw2=value.search(/[0-9]+/);
	condPassw3=value.search(/[a-z]+/);
	condPassw4=value.search(/[A-z]+/);
	

	if(condPassw1!=-1&condPassw2!=-1&condPassw3!=-1&condPassw4!=-1){
		passwOk=true;		
	}
	return this.optional(element) || passwOk; 
}, jQuery.validator.messages.passw);

jQuery.validator.addMethod("nif", function(value, element) { 
	nifOK=true;
	nifError=errorCIFNIF;
	nif=value;
	
		if(nif.search(/^(X|\d{1})\d{7}[A-Za-z]{1}$/)!=-1){ //DNI
			var primeraLetra=nif.substring(0,1).toUpperCase();
			if(primeraLetra=="X"){
				nif="0"+nif.substring(1,9);
			}
			numero=nif.substring(0,8).replace(/^0+/, ""); //quito posibles ceros de delante paar que no haya lios con el octal
			letra=nif.substring(8,9).toUpperCase();	
			letrasNIF='TRWAGMYFPDXBNJZSQVHLCKET';
			posLetraOK = numero % 23;
			letraCorrecta = letrasNIF.substring(posLetraOK,posLetraOK+1);
			if(letra!=letraCorrecta) {
				nifError=errorNIFLetra;
				nifOK=false;
			}else{ nifOK=true;}
		}else if(nif.search(/^[A-Za-z]{1}\d{8}$/)!=-1){
			cif=nif;
			//CIF
			   /* Correspondencia de las letras del CIF:
				 A - Sociedades Anónimas
				 B - Sociedades de responsabilidad limitada
				 C - Sociedades colectivas
				 D - Sociedades comanditarias
				 E - Comunidades de bienes
				 F - Sociedades cooperativas
				 G - Asociaciones y otros tipos no definidos
				 H - Comunidades de propietarios
				 P - Corporaciones locales
				 Q - Organismos autónomos
				 S - Organos de la administración
				 K, L y M - seguramente para compatibilidad con formatos antiguos
				 X - Extranjeros, que en lugar del D.N.I. tienen el N.I.E.
			*/
			var letrasCIF='ABCDEFGHPQSKLMX';
			// La primera ha de ser una letra válida...
			var primeraLetra=cif.substring(0,1).toUpperCase();
			if( letrasCIF.indexOf(primeraLetra) == -1) {
			   nifError=errorCIFLetra;
			   nifOK=false;
			}
	
			// CIF 'normal'...
			else {
				//A58818501 --> x5881850x --> 8 + 1 + 5
				var suma=parseInt(cif.substring(2,3)) + parseInt(cif.substring(4,5)) + parseInt(cif.substring(6,7));
				for(var n=1; n<=4; n++) {
					suma+= ((2* parseInt(cif.substring(2*n-1,2*n)))%10) + Math.floor((2*parseInt(cif.substring(2*n-1,2*n)))/10);
				}
				control=10-(suma % 10);
				// Organismos públicos
				if(primeraLetra=="P" || primeraLetra=="S") {
				   if(cif.substring(8,9)==String.fromCharCode(64+control)) return '';
				   nifError=errorCIFGen;
				   nifOK=false;
				}
				// Resto de CIFs
				else {
					if(control==10)
						control=0;
					if(cif.substring(8,9)==""+control) return '';
					 nifError=errorCIFGen;
					 nifOK=false;
				}
			}
		}else{
			nifOK=false;
			nifError=errorCIFNIF;
		}

	jQuery.validator.messages.nif=nifError;
							  
 	return this.optional(element) || nifOK; 
}, jQuery.validator.messages.nif);

var userAgent = navigator.userAgent.toLowerCase();
jQuery.browser = {
    version: (userAgent.match( /.+(?:rv|it|ra|ie|me)[\/: ]([\d.]+)/ ) || [])[1],
    chrome: /chrome/.test( userAgent ),
    safari: /webkit/.test( userAgent ) && !/chrome/.test( userAgent ),
    opera: /opera/.test( userAgent ),
    msie: /msie/.test( userAgent ) && !/opera/.test( userAgent ),
    mozilla: /mozilla/.test( userAgent ) && !/(compatible|webkit)/.test( userAgent )
};


$(document).ready(function () {

    var changePeriodElements = $('select[id^=periodicidad]');
    changePeriodElements.change(function(){
            var elem = $(this);
            var idproducto = elem.attr('id').replace('periodicidad','');
            var antivirusName = $('input[id=FiltroAntivirus/AntispamAvanzado_'+idproducto+']').attr('name');
            var label = $('label[for='+antivirusName+']');
            
            if (elem.val() == 12){
                //Periodicidad anual
                var precio = $('span', label).text();
                $('span',label).remove();
                label.append('<del>'+precio+'</del>');
                label.append('<strong style="color:#b1005d;"> AHORA GRATIS!!!</strong>');
            }else{
                //Periodicidad mensual
                var precio = $('del', label).text();
                $('del',label).remove();
                $('strong',label).remove();
                label.append('<span>'+precio+'</span>');
            }
    });



	
	divProductInfoBottom=$('<div id="product_info_bottom"></div>');
	$('#product_info').append(divProductInfoBottom);



	helpDivs=$('.pop_int').parent(); 
	$('body').append(helpDivs);//move help divs to the end of code to avoid problems with relative/absolute coordinate
	
	oblfield=$('.oblfield');
	$('#general_content').append(oblfield);
	
	buttonsA=$('.but a').parent();
	buttonsInput=$('.but input').parent();
	
	spanAuxA=$('<span />');
	spanAuxInput=$('<span />');
	
	if($.browser.safari){
		$('input',buttonsInput).css('padding','4px 15px 5px 5px');
		spanAuxInput.css('left','2px');
	}
	
	if($.browser.msie){
		if($.browser.version<8){
			spanAuxA.css('top','5px');
			spanAuxInput.css('top','5px');
		}else{
			spanAuxInput.css('top','1px');
		}
	}
	
	if($.browser.chrome){
		spanAuxInput.css('top','1px');
		spanAuxInput.css('left','2px');
	}
	
	
	buttonsA.prepend(spanAuxA);
	buttonsInput.prepend(spanAuxInput);
	
	divClientFormBottom=$('<div id="client_form_bottom"></div>');
	$('#client_form').append(divClientFormBottom);
	
	divStepContentBottom=$('<div id="step_content_bottom"></div>');
	$('#step_content').append(divStepContentBottom);
	
	divProductTop=$('<div class="product_top"></div>');
	divProductBottom=$('<div class="product_bottom"></div>');
	$('.product').prepend(divProductBottom).append(divProductTop);
	
	
	//inicializacion whois privado
	selectWhoisPrivado=$("[id*='datoasociado_adicional0']");
	selectLength=$("[id*='duracion']");
	
	//inicializacion codigo promocion cat
	inputCodigoPromocion=$("[id*='codigoPromoCat']");

	selectWhoisPrivado.change(function(){
		idSelectWP=$(this).attr('id');							   	
		firstD=idSelectWP.indexOf('d');
		numProd=$(this).attr('id').substr(0,firstD);
		
		compareWhoisLength(numProd);
	})
	
	selectLength.change(function(){
		idSelectLength=$(this).attr('id');							   	
		numProd=$(this).attr('id').substr(8,idSelectLength.length-1);
		
		inputCodigoPromocion=$("[id*='codigoPromoCat"+numProd+"']");
		idCodPromo = inputCodigoPromocion.attr('id');
		if(idCodPromo != undefined){
			//establecer duración según promoción
			numCat =idCodPromo.substr(14,idCodPromo.length-1);
			if (numCat == numProd){
				codeCat = document.getElementById(inputCodigoPromocion.attr('id')).value;
				if (codeCat != "" ){
					d=$('#'+numProd+'datoasociado_adicional0')[0];
					if(d.value>1){
						d.selectedIndex=0;
					}
					d=$('#duracion'+numProd)[0];
					if(d.value > 1){
						d.selectedIndex=0;
					}
				}
			}
		}
		compareWhoisLength(numProd);
	})
	
	inputCodigoPromocion.change(function(){
		//establecer duración segun promoción
		idCodPromo=$(this).attr('id');
		numProd=idCodPromo.substr(14,idCodPromo.length-1);
		d=$('#'+numProd+'datoasociado_adicional0')[0];
		d.selectedIndex=0;
		d=$('#duracion'+numProd)[0];
		d.selectedIndex=0;
		compareWhoisLength(numProd);
	})

	//inicializacion VPS
	ampliacionesPlesk=$("[id*='AmpliacionesPlesk']");
	for(i=0;i<ampliacionesPlesk.length;i++){
		indice=$(ampliacionesPlesk[i]).attr('id').substr(18,$(ampliacionesPlesk[i]).attr('id').length);
		$(ampliacionesPlesk[i]).attr('indice',indice);
		$('#PleskPowerPack_'+indice).parent().attr('id','pppp'+indice)
		
		if($(ampliacionesPlesk[i]).attr('value')==0){
			$('#PleskPowerPack_'+indice).parent().hide();
		}
		
		$(ampliacionesPlesk[i]).change(function(){	  
				pleskPP=$('#pppp'+$(this).attr('indice'));
							
				if($(this).attr('value')>0){ pleskPP.show();
				}else{ pleskPP.hide(); }			  
		})
	}
	
	
	//form de clientes		
	if($('#fc').length==1){ /*mejorarrrr*/
		$('#fc').hide();
		$('#fc_link').click(function(){
			if($('#fc').css("display")=='none'){
				$('#fc').show('slow'); /* fuck fuck fuck ie7 */
				$('#fc .but').show();
			}else{
				$('#fc').hide('slow');
				$('#fc .but').hide();
			}
			return false;
		})
		
		$('#client_data').validate({
			rules: {
				user: {
					required: true,
					email: true
				},
				pass: {
					required: true 
					/*passw:true*/
					/*minlength: 5*/
				}
			},
			messages: {
				user: {
					required: "Introduce tu email",
					email: "Introduce una direccion de email válida"
				},
				pass: {
					required: "Introduce tu contraseña"
					/*minlength: "Tu contraseña debe tener al menos 5 caracteres"*/
				}
			},
			/*necesario saber mejor que error está bien o mal para jugar con su id o lo que sea y no ñapear con la posicion
			(el script quita el texto del error pero display=none por eso queda el hueco que hay que ñapear
			*/
			showErrors: function(errorMap, errorList) {
          		this.defaultShowErrors();
				if(errorList[0]){
					$('#info_'+errorList[0]['element'].name).css("display","none");
				}
         	 },
			success: function(label){
				$('#info_'+label[0].htmlFor).css("display","block");
				$('#info_'+label[0].htmlFor).css("position","relative");
				$('#info_'+label[0].htmlFor).css("left","-11px");
			}
		})
		
	}
	
	setTimeout(function(){$('.notif').fadeOut(3000);},5000);
	//setTimeout(function(){$('.error_generico').fadeOut(3000);},5000);
	
	if($('.error_generico').length==1){
		$('#fc').show('slow'); //ojo solo con error de password!
	}
	
	if($('#promoEntry').length==1){
		
		var conditions=', las condiciones de la promoción';
		
		radiosEntry=$("#promoEntry input.entryok[type=radio][checked]");
		
		if(radiosEntry.length>0){
			$('#promoentry').show();
			$('.conditionstext').text(conditions);
		}else{
			$('#promoentry').hide();
			$('.conditionstext').text('');
		}
		
		radiosGen=$("#promoEntry input[type=radio]");
		
		radiosGen.click(function(){
			var conditions=', las condiciones de la promoción';					 
								 
			radiosEntry=$("#promoEntry input.entryok[type=radio][checked]");					 
			if(radiosEntry.length>0){
				$('#promoentry').show();
				$('.conditionstext').text(conditions);
			}else{
				$('#promoentry').hide();
				$('#condicionespromoentry_pop').hide();
				$('.conditionstext').text('');
			}			
		})

	}
		
	//productos del carrito
	if($('#step0').length==1){ /*mejorarrrr*/
		$('.product_int').hide();
		if(posiciones.length>0){
			for(i=0;i<posiciones.length;i++){
				$($('.product_int')[posiciones[i]]).show();
				$($('.product_int')[posiciones[i]]).parent(".product").children("h2").attr("class","close");
			}		
		}else{
			
			if($('.product_int').length>0){
				$($('.product_int')[0]).show();
				$($('.product_int')[0]).parent(".product").children("h2").attr("class","close");
			}
		}
	}

	$('#omit .product_int .product_int').hide(); //checkout
	
	$('.product_name').css("cursor","pointer");
	$('.product_name').click(function(){
		$(this).parent().toggleClass("close");
		product=$(this).parent().parent();
		producId=product.attr("id");
		productInt=$('#'+producId+'_int');
		if($(this).parent().attr("class")=="close"){
			productInt.show('slow');
		}else{
			productInt.hide('slow');
		}
		return false;
	})
	
	ie6=false;
	if($.browser.msie && $.browser.version <= 6){
		ie6=true;
	}

	if(ie6){
		ie6Css=$('<link href="/piensa/css/ie6.css" rel="stylesheet" type="text/css" media="screen" />');
		$('head').prepend(ie6Css);
	}

	
	//aperttura de popups:
	//
	// whois '_blank', 
	paramsHelp='height=510,width=750';
	paramsWhois='width=670,height=460,resizable=yes,scrollbars=yes';
	paramsForg='width=650,height=150,scrollbars=yes';
	
	$('.shoppingcart_help').click(function(){openPop(this.href,'help',paramsHelp); return false;})
	$('.checkout_help').click(function(){openPop(this.href,'help',paramsHelp); return false;})
	$('.clientdata_help').click(function(){openPop(this.href,'help',paramsHelp); return false;})
	$('.payment_help').click(function(){openPop(this.href,'help',paramsHelp); return false;})
	$('.confirm_help').click(function(){openPop(this.href,'help',paramsHelp); return false;})
	$('.end_help').click(function(){openPop(this.href,'help',paramsHelp); return false;})
	
	$('.whois').click(function(){ openPop(this.href,'_blank',paramsWhois);return false;})
	$('.passforg').click(function(){openPop(this.href,'forgot',paramsForg); return false;})
	
	
	/*selectPais=$('select[id*=tens]');
	alert(selectPais.attr('id')); */
	
	
	zIndexPop=100;
	//links de "popup"

	$('.pop').hide();
	$('.pop').draggable();/*{containment: 'parent'}*/
	$('.pop h4').css("cursor","pointer");
	$('.pop').click(function(e){$(this).css("z-index",zIndexPop); zIndexPop++; })
						
	$('.poplink').click(function(e){ 
		invPaint=false;
		if($(this).attr("class").indexOf("inv")>0){
			invPaint=true;
		}
		
		helpWindowId=$(this).attr('id').substring(0,$(this).attr('id').length-4); // de xxx_link a xxx para sabr la id, mejor con #nombre_ventana?
		helpWindow=$('#'+helpWindowId);
		
		helpWindowWidth=helpWindow.css("width").substring(0,helpWindow.css("width").length-2);
		
		helpWindow.css("z-index",zIndexPop);
		zIndexPop++;
	
		x=e.pageX;
		y=e.pageY;
		
		if(invPaint){ x=x-helpWindowWidth;} 
		
	
		helpWindow.css("top",y);
		helpWindow.css("left",x);
		helpWindow.show('slow');
		
		return false;
	})
	
	//cerrar pop up
	$('.pop_close').click(function(){						 
			helpWindowId=$(this).attr('id').substring(0,$(this).attr('id').length-5); //de xxx_popclose a xxx_pop, mejor con un this.parent?
			helpWindow=$('#'+helpWindowId);
			helpWindow.hide('slow');
			return false;
	})
	
	//hosting asociado desde parking-
	
	$("input[name='idservicio']").click(function(){
		if ( flagAddProduct == false ){
		   flagAddProduct = true;
		   valueProd=$(this).attr('value');
		   indexProd=$(this).parents('.product').attr('id').substr(7,$(this).parents('.product').attr('id').length);
		   $("#formulariocarrito")[0].action="add-product.php?idProduct="+valueProd+"&index="+indexProd;
		   $("#formulariocarrito")[0].submit();
		}else{
		   //
		}
		return false;
	})
	
	//hosting opcional desde tienda
	$("select[name*='hosting']").change(function(){
		valueProd=$(this).attr('value');
		indexProd=$(this).parents('.product').attr('id').substr(7,$(this).parents('.product').attr('id').length);
		$("#formulariocarrito")[0].action="add-product.php?idProduct="+valueProd;//+"&index="+indexProd;
		$("#formulariocarrito")[0].submit();
		return false;			 
	})

	
	if($('#step1').length==1){ /*mejorarrrr selecion de capas segun checkbox, similar a tarjetas, hacer funcion propia*/  
	
		if(errorDatos){	location.href='#datos';}
		
		checkParticular=$('.check_part');
		checkCompany=$('.check_comp');
		
		formParticular=$('#particular');
		formCompany=$('#company');
		
		checkParticular.click(function(){
			checkParticular.attr('checked','checked');
			formParticular.show();
			formCompany.hide();
			
		})
		checkCompany.click(function(){
			checkCompany.attr('checked','checked');
			formParticular.hide();
			formCompany.show();
		})
		
		if(whatCheck=='block'){ 
			checkParticular.attr('checked','checked');
			formParticular.show();
			formCompany.hide();
		}else{
			checkCompany.attr('checked','checked');
			formParticular.hide();
			formCompany.show();
		}
	}
	
	if($('#step2').length==1){ /*mejorarrrr*/
		
	
		capaTpv=$('#texto_tpv');
		capaTrans=$('#texto_trans');
		//capaIngreso=docId('texto_ingreso');
	
		checkTpv=$('#check_tpv');
		checkTrans=$('#check_trans');
		//checkIngreso=docId('check_ingreso');

		checkTpv.click(function(){
			checkTpv.attr('checked','checked');
			capaTpv.show();
			capaTrans.hide();
			
		})
		checkTrans.click(function(){
			checkTrans.attr('checked','checked');
			capaTpv.hide();
			capaTrans.show();
		})
		
		if(checkTrans.attr('checked')!='checked'&&checkTpv.attr('checked')!='checked'){ //ningun ckeck seleccionado
			checkTpv.attr('checked','checked');
			capaTpv.show();
			capaTrans.hide();
		}
	
	}
	
	
	$('#particular').submit(function(){
		docId('reEmailpart').value=docId('emailpart').value;					 
	})
	
	$('#company').submit(function(){
		docId('reEmailcomp').value=docId('emailcomp').value;					 
	})
	
	//pasar a jquery
	if($('#question').length==1){
		nQuestion=$('#question')[0];
		txtnQuestion=nQuestion.value;
		nQuestion.onfocus= function(){ if(this.value==txtnQuestion) this.value='';	}
	}
	if($('#email_question').length==1){
		nEmailQuestion=$('#email_question')[0];
		txtnEmailQuestion=nEmailQuestion.value;
		nEmailQuestion.onfocus= function(){	if(this.value==txtnEmailQuestion) this.value='';}
	}
	
	if($('#online_at').length==1){
		nodo0=$('#online_at')[0];
		firstBut=$('#first_but');
		
		$('#sendform2').hide();
		
		//pruebica
		//$('#search_results').hide();
		
		firstBut.click(function(){	
			if(validateForm()){
				$('#sendform1').hide();
				$('#sendform2').show();
				return false;
			}
		})
		
		nodo0.onsubmit=function(){
			if($('#sendform1')[0].style.display=='none'){
				if($('#captcha')[0].value!=''){
					//$(this).submit();
					alert('seguimos');
				}else{
					alert('Por favor, introduce el código de la imagen para enviar tu consulta');
					return false;
				}
			}else{
				$('#sendform1').hide();
				$('#sendform2').show();
				return false;
			}
		}
	}
	

	if($('#num_prod_cart').length==1){
		if(num_products>0){
			$('#text_cart').text('Carrito');
			$('#link_cart').attr({href:'/shopping-cart.php',title:'Carrito'});
			$('#num_prod_cart').text('('+num_products+')');
		}
	}
	
	$('.changeToPro').click(function(){	
		id=$(this).attr('id'); 
		position=id.substr(11,id.length);
		
		$('#Cambio'+position).attr('value', 188);
		validaCarrito();
	})
	
	
	error=$('div.error');
	errorGen=$('div.error_generico');
	
	errorAuxLT=$('<div class="errorLT"></div>');
	errorAuxRT=$('<div class="errorRT"></div>');
	errorAuxLB=$('<div class="errorLB"></div>');
	errorAuxRB=$('<div class="errorRB"></div>');
	
	errorAux2LT=errorAuxLT.clone();
	errorAux2RT=errorAuxRT.clone();
	errorAux2LB=errorAuxLB.clone();
	errorAux2RB=errorAuxRB.clone();;
	

	error.prepend(errorAux2LT).prepend(errorAux2RT).prepend(errorAux2LB).prepend(errorAux2RB);
	errorGen.prepend(errorAuxLT).prepend(errorAuxRT).prepend(errorAuxLB).prepend(errorAuxRB);
	
	
	notif=$('.notif');
	

	
	notifAux2LT=$('<div class="notifLT"></div>');
	notifAux2RT=$('<div class="notifRT"></div>');
	notifAux2LB=$('<div class="notifLB"></div>');
	notifAux2RB=$('<div class="notifRB"></div>');	

	notif.prepend(notifAux2LT).prepend(notifAux2RT).prepend(notifAux2LB).prepend(notifAux2RB);

	
	aviso=$('.aviso_generico');
	

	
	avisoAux2LT=$('<div class="avisoLT"></div>');
	avisoAux2RT=$('<div class="avisoRT"></div>');
	avisoAux2LB=$('<div class="avisoLB"></div>');
	avisoAux2RB=$('<div class="avisoRB"></div>');	

	aviso.prepend(avisoAux2LT).prepend(avisoAux2RT).prepend(avisoAux2LB).prepend(avisoAux2RB);
})
		
function compareWhoisLength(numProd){
	lengthReg=$('#duracion'+numProd)[0];
	wp=$('#'+numProd+'datoasociado_adicional0')[0];
	
	if( parseInt(wp.value) > parseInt(lengthReg.value)){
		alert('La duración del Whois Privado no debe superar la del registro');
		wp.selectedIndex=lengthReg.value-1;
	}
}


function openPop(url,namewindow,params){
	window.open(url,namewindow,params);
	return false;
}
		
function docId(id){
	return document.getElementById(id);	
}	
		
//pasar a jquery
function submitForm(){
	if(validateForm()){
		document.online_at1.submit();
	}
}
function validateForm() {
	  var err="Se produjeron los siguientes errores:";
	
	  if(document.online_at1.question.value==''){
		  err += "\n - Debe introducir una consulta.";
		}
	if(!validateEmail(document.online_at1.email_question.value)) {
		err += "\n - Introduzca un email de destinatario válido.";
	}

	if(err != "Se produjeron los siguientes errores:") {
		alert (err);
		return false;
	}
	else {
		return true;
	}
}

function validateEmail(email) {
	if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,4})+$/.test(email)){
		return (true)
	}
}

function reloadCaptcha() {
	alert('cambiamos captcha');
/*	var ran_unrounded=Math.random()*10;
	var ran_number=Math.floor(ran_unrounded);
	var estilo = new Array(10);
   estilo[0]=0; estilo[1]=1;  estilo[2]=2;  estilo[3]=4;  estilo[4]=6;
   estilo[5]=19; estilo[6]=28; estilo[7]=29; estilo[8]=41; estilo[9]=42;
   
	docId("img_captcha").src="genimg.asp?Command=CreateImage&TextStyle="+estilo[ran_number]+"&ImageWidth=100&imageHeight=33&CodeLength=5&CodeType=0";*/
}

//payment, se usa?

function tpvCheck(){
	idCliente=docId('idcliente').value;
	idApp=1; /*contratacion*/
	idUn=1; /*ES*/
	url='tarjetas.php?=idCliente='+idCliente+'&IdUn='+idUn+'&IdApplication='+idApp;
	
	var peticion = false;
    try{
    peticion=new XMLHttpRequest();
   }catch (trymicrosoft) {
   try{
    peticion=new ActiveXObject("Msxml2.XMLHTTP");
   }catch (othermicrosoft) {
   try{
    peticion=new ActiveXObject("Microsoft.XMLHTTP");
   }catch (failed) {
    peticion=false;
   } 
   }
 }


 peticion.open("GET", url);
 peticion.onreadystatechange = function() { 
  if (peticion.readyState == 4) {
   xmlTpv = peticion.responseXML;
 	 manageXmlTpv(xmlTpv);
  }
 } 
 peticion.send(null);

}

function createErrorParagraph(text){
	pError=document.createElement('p');
	pErrorText=document.createTextNode(text);
	pError.appendChild(pErrorText);
	pError.className='error';
	tpvCards.appendChild(pError);
}

function manageXmlTpv(xml){
	tpvCards=docId('tpvcards');
	tpvCardsChildLength=tpvCards.childNodes.length;
	for(j=0;j<tpvCardsChildLength;j++){
		tpvCards.removeChild(tpvCards.childNodes[0]);
	}
		
	estado=xml.getElementsByTagName('estado')[0].firstChild.nodeValue;
	
	if(estado==-1){ //error
		createErrorParagraph('Ha ocurrido un error tratando de obtener la información de tarjetas disponibles');
	}else{ //caso normal
		cards=xml.getElementsByTagName('tarjeta');
		numCards=cards.length;
		if(numCards<1){
			
			createErrorParagraph('En este momento no hay tarjetas disponibles para efectuar el pago');
		}else{
			
			pOk=document.createElement('p');
			for(k=0;k<numCards;k++){
				cardId=cards[k].getElementsByTagName('id')[0].firstChild.nodeValue;
				cardName=cards[k].getElementsByTagName('nombre')[0].firstChild.nodeValue;
			
				auxInput=document.createElement('input');
				auxInput.id='TiendaVirtual'+cardId;
				auxInput.name='TiendaVirtual';
				auxInput.value=cardId;
				auxInput.type='radio';
				if(idCard=1){auxInput.checked=true}
				
				auxImg=document.createElement('img');
				auxImg.src='show-credit-card.php?id='+cardId;
				auxImg.title=cardName;
				
				auxLabel=document.createElement('label');
				auxLabel.htmlFor='TiendaVirtual'+cardId;
				auxLabel.appendChild(auxImg);
				
				pOk.appendChild(auxInput);
				pOk.appendChild(auxLabel);
			}
			
			tpvCards.appendChild(pOk);
		}
	}
	//alert(xml);	
}

function comprar(){
	if($("#idcompra")[0]){
		$("#formulariocarrito")[0].submit();
	}else{
		this.location.href="/index.php";
	}
}

function enviar(){
	$("#formulariocarrito")[0].action="checkout.php";
	$("#formulariocarrito")[0].submit();
}

function confirmEmpty(){
	if(confirm('¿Seguro que deseas vaciar tu carrito?')){
		return true;
	}else{
		return false;
	}	
}

function confirmDel(pos){
	 if (flagAddProduct == false){
	 	if(confirm('¿Seguro que deseas eliminar este producto?')){
	 	   flagAddProduct = true;
		   $("#formulariocarrito")[0].action="del-product.php?pos=" + pos;
		   $("#formulariocarrito")[0].submit();
		}else{
		   return false;
  	        }
	}else{
		return false;
        }
}

function desconectar(){ //carrito, checkout
	$("#formulariocarrito")[0].action="logout.php";
   	$("#formulariocarrito")[0].submit();
}

function anadir(posicion){
	$("#formulariocarrito")[0].action="checkout.php?posicion="+posicion+"&oculto=1";
	$("#formulariocarrito")[0].submit();
}

function comprobar(posicion){
	 if (flagAddProduct == false){
	    flagAddProduct = true;
	    dom=$('#dominio'+posicion)[0].value;
	    $("#formulariocarrito")[0].action="add-product.php?index="+posicion;
	    $("#formulariocarrito")[0].submit();
	 }else{
	    return false;
         }
}

function siguiente(){ //checkout
	$("#formulariocarrito")[0].action="client-data.php";
	$("#formulariocarrito")[0].submit();
}

function volver(){ //checkout
	$("#formulariocarrito")[0].action="shopping-cart.php";
	$("#formulariocarrito")[0].submit();
}


function validaCarrito(){ //checkout
	$("#formulariocarrito")[0].action="change-product.php";
	$("#formulariocarrito")[0].submit();
}



function cancel(){ 
	if(confirm('¿Seguro que deseas cancelar todo el proceso de contratación?')){
		location.href='sale-cancel.php';
	}
}

function printFrame(fr){
	eval('window.'+fr+'.focus();');
	eval('window.'+fr+'.print();');
}

function checkEs(typ){
	if($('#pais_'+typ).val()==724){
		$('#provincia_div_'+typ).show();
	}else{
		$('#provincia_div_'+typ).hide();
		$('#provincia_'+typ)[0].selectedIndex=0;
	}
}

function changeProduct(){ //checkout
	$("#formulariocarrito")[0].action="change-product.php";
	$("#formulariocarrito")[0].submit();
}

function limpiarContenido($objeto){
	 var valor  = $objeto.value;
	 var cadena1 = "www.dominio.com";
	 var cadena2 = "dominio.com";
	 if (valor == cadena1 || valor == cadena2){
	    $objeto.value = "";
	 }else{
	    //
	 }
}

function rellenarCombo($indice){
    //{{{  
    if ($flagEmail == true){
	var $url = $('#ssl_dom' + $indice);
//	if ( $url.is("input") ){
	    // Nada es el certificado
	    $url = $url.val();
//	}else{
//	    $url = $('#SSL_Dominio' + $indice + ' label');
//	    $url = $url.html();
//	}
	$url = $url.replace("www.", "");
	$url = $url.replace("shop.", "");
	$url = $url.replace("secure.", "");
	$url = $url.toLowerCase();
	
	var $combo = $('#ssl_email' + $indice);
	var $options = "<option selected value=\"eleccion\">Seleccione su email</option>";
	$options    += "<option value=\"postmaster@" + $url + "\">postmaster@" + $url + "</option>";
	$options    += "<option value=\"webmaster@" + $url + "\">webmaster@" + $url + "</option>";
	$options    += "<option value=\"root@" + $url + "\">root@" + $url + "</option>";
	$options    += "<option value=\"hostmaster@" + $url + "\">hostmaster@" + $url + "</option>";
	$options    += "<option value=\"admin@" + $url + "\">admin@" + $url + "</option>";
	$options    += "<option value=\"administrator@" + $url + "\">administrator@" + $url + "</option>";
	$options    += "<option value=\"personalizar\">personalizar</option>";

	$combo.html($options);
    }else{
	//
    }
    
    $flagEmail = true;
    //}}}
}

function parsearEmail($objeto, $indice){
    //{{{  
    $objeto = $($objeto)
    var $valor = $objeto.val();
    var $mail  = $("#ssl_email_input" + $indice);
    var $capa  = $("#ssl_email_input_capa" + $indice);

    if ( $valor == "personalizar" ){
    	$capa.removeClass('nv');
	    $capa.addClass('ok');
    	$valor = "";
    }else if( $valor == "eleccion" ){
	    $capa.removeClass('ok');
    	$capa.addClass('nv');
    	$valor = "";
    }else{
    	$capa.removeClass('definition-form');
	    $capa.addClass('nv');
    }
    $mail.val($valor);
    $flagEmail = true;
    //}}}
}

var $flagEmail = true;

function comprobarDomWB(pos,selec){
    //$adicionales  = $('#carac_'+pos+" .servicios_adicionales");
    //$ampliaciones = $('#carac_'+pos+" .ampliaciones");

	if (selec == "1"){
		docId('MostrarDomWB'+pos).style.display='block';
		docId('MostrarDomWB'+pos).style.display='inline';
		
		docId('bannerWB'+pos).style.display='block';
		docId('bannerWB'+pos).style.display='inline';
        //$adicionales.show();
        //$ampliaciones.show();
        //$('#carac_'+pos+' .ampliaciones input[type=text]').removeAttr('disabled');
        //$('#carac_'+pos+' .servicios_adicionales input[type=checkbox]').removeAttr('disabled');
	}else{
		docId('MostrarDomWB'+pos).style.display='none';
		docId('bannerWB'+pos).style.display='none';
		
        //$adicionales.hide();
        //$ampliaciones.hide();
        //$('#carac_'+pos+' .ampliaciones input[type=text]').attr('disabled','disabled');        
        //$('#carac_'+pos+' .servicios_adicionales input[type=checkbox]').attr('disabled','disabled');        
	}
}

