/* javascipt con mootools */

var debug = false; // production false
var myRequestMostrarInfoForm = new Request.HTML();
var myRequestEnviarInfoForm = new Request.HTML();

var objContainerFx = new Fx.Slide('containerFx', {
    duration: 1500,
    mode: 'horizontal'
    /*transition: Fx.Transitions.Bounce.easeOut*/
});

var mas_info_div = new Element('div', {
    'class': 'mas_info_div',
    'html': '<a id="mas_info_a" href="info.php" rel="nofollow" title="más información presupuesto precios">Solicite información o presupuesto</a>'
});

var error_div = new Element('div', {
    'class': 'error',
    'html': 'Por favor, rellene correctamente los datos marcados en rojo.'
});
var Enviada_solicitud = new Element('div', {
    'class': 'Enviada_solicitud',
    'html': 'Enviada la solicitud de presupuesto. En breve se pondrá en contacto Moñita con usted. (24/48) horas Muchas gracias.'
});


window.addEvent('domready', function() {

	addMasInfoDebajoDelUltimoParrafo();
	// otros elements que actúan como mas_info
	addEventoToSimilarMas_info('correo_info_foot');
	addEventoToSimilarMas_info('correo_madrid');
	addEventoToSimilarMas_info('correo_salamanca');
	
	addEventoToSimilarMas_info('noti_titular');
	addEventoToSimilarMas_info('noti_princial');
	
});

function addMasInfoDebajoDelUltimoParrafo(  ) {

	if ($defined($('mas_info_a'))) return;
	
	//alert(document.location);
	var url_actual = document.location;
	if ( url_actual.toString().indexOf('index')!=-1 ) return;
	if ( url_actual=='http://www.toldosmonita.com/' ) return;
	
	if ( url_actual.toString().indexOf('nager')!=-1 ) return;
	if ( url_actual.toString().indexOf('descargas')!=-1 ) return;
	if ( url_actual.toString().indexOf('os-ha-conocido')!=-1 ) return;
	if ( url_actual.toString().indexOf('empleo')!=-1 ) return;
	
	var lastElement = null;

	$('content').getElements('[class=parrafo]').each(function(element, index) {
		lastElement = element;
	});

	if (lastElement==null) {
		
		//$('content').grab(mas_info_div);
		/*
		divObjElement = $('content').getElement('[class=obj_cen]');
		if (divObjElement != null) divObjElement.grab(mas_info_div);
		else $('content').grab(mas_info_div);
		*/
		
		divPanel = $('content').getElement('[class=panel]');
		if (divPanel != null) divPanel.grab(mas_info_div,'top');
		else $('content').grab(mas_info_div);
		
	} else {
		lastElement.grab(mas_info_div);
	}
	
	addEventoToMas_info_a();
	
	return;
}

function addEventoToMas_info_a(  ) {
	$('mas_info_a').addEvent('click', function(e) {
		e.stop();

		objContainerFx.slideOut();

		requestMostrarInfoForm();
		
		if (!debug) pageTracker._trackPageview('/info/mostrar/');
	});
}

function addEventoToSimilarMas_info( _id ) {
	
	if ( !$defined($(_id)) ) return;
	
	$(_id).addEvent('click', function(e) {
		e.stop();

		objContainerFx.slideOut();

		requestMostrarInfoForm();
		
		if (!debug) pageTracker._trackPageview('/info/mostrar/');
	});
}

function ocultarContainerFx(){
	// ocultar containerFx por el flash
    $('containerFx').addClass('oculto');
};
function mostrarContainerFx(){
	// ocultar containerFx por el flash
    $('containerFx').removeClass('oculto');
};
function ocultarInfo(){
	// ocultar containerFx por el flash
    $('info').addClass('oculto');
};
function mostrarInfo(){
	// ocultar containerFx por el flash
    $('info').removeClass('oculto');
};


function requestMostrarInfoForm( ) {

	mostrarInfo.delay(1400);
	
	myRequestMostrarInfoForm.onSuccess=function(html) {

		$('info').set('text', '');

		$('info').adopt(html);
		
		if ($defined($('cerrar'))) addEventoToCerrarYVolver('cerrar');
		if ($defined($('volver'))) addEventoToCerrarYVolver('volver');
		
		if ($defined($('infoForm'))) { addEventoToInfoFormInputs(); }
		
	};
	myRequestMostrarInfoForm.onFailure=function(html) {
		$('info').set('text', 'The request failed.');
	};
	
	myRequestMostrarInfoForm.send({url:'info.php', data: 'accion=info.nuevo&ajax=true' });
	
}


function addEventoToCerrarYVolver( _id ) {
	$(_id).addEvent('click', function(e) {
		e.stop();

		ocultarInfo.delay(0);

		objContainerFx.slideIn('horizontal');
		
		if (!debug) pageTracker._trackPageview('/info/cerrar/');
		
	});
}


function addEventoToInfoFormInputs( _id ) {

	$('ajax').set('value','true');
	
	$('nombreCompleto').addEvent('blur', function(e) {
		validateInputText('nombreCompleto',5);
	});
	$('direccion').addEvent('blur', function(e) {
		validateInputText('direccion', 5);
	});
	$('poblacionCli').addEvent('blur', function(e) {
		validateInputText('poblacionCli',4);
	});
	//$('provincia').addEvent('change', function(e) {
	$('provincia').addEvent('blur', function(e) {
		if ( $('lugar').get('value')=='España - Spain')
			validateSelect('provincia');
	});
	$('lugar').addEvent('change', function(e) {
		if ( this.get('value')=='España - Spain' ) showElement('provincia');
		else hideElement('provincia');
	});
	
	$('tlf').addEvent('blur', function(e) {
		validateInputText('tlf', 9);
	});
	// horarioContacto
	$('correo').addEvent('blur', function(e) {
		validateMail('correo');
	});
	// procedenciaCli
	$('yaSoyCliente').addEvent('click', function(e) {
		hideElement('medioMk');
		hideElement('medioMkOtro');
	});
	$('otroCliente').addEvent('click', function(e) {
		showElement('medioMk');
	});
	$('medioMk').addEvent('change', function(e) {
		validateSelect('medioMk');
		if ( this.get('value')=='Otros a definir') showElement('medioMkOtro');
		else hideElement('medioMkOtro');
	});
	$('medioMk').addEvent('blur', function(e) {
		validateSelect('medioMk');
	});
	$('medioMkOtro').addEvent('focus', function(e) {
		if ( $('medioMkOtro').get('value')=='otra procedencia definir') $('medioMkOtro').set('value','');
	});
	$('medioMkOtro').addEvent('blur', function(e) {
		if ( $('medioMk').get('value')=='Otros a definir')
			validateInputText('medioMkOtro',5);
	});
	ProductsByCategoryLN(); // addEvent'categoriaProducto', requestProductsByCategory(...), show,  hide 
	// fkIdProductoDiv
	// fkIdProducto
	// addEventToProducto();
	
	
	$('carpasAlquiler').addEvent('click', function(e) {
		showCarpas();
	});
	$('carpasVenta').addEvent('click', function(e) {
		hideAlquiler();
	});
	// name carpasAlquilerOVenta
	
	$('tipoEvento').addEvent('change', function(e) {
		validateSelect('tipoEvento');
	});
	$('tipoEvento').addEvent('blur', function(e) {
		validateSelect('tipoEvento');
	});
	
	$('duracionEvento').addEvent('change', function(e) {
		validateSelect('duracionEvento');
	});
	$('duracionEvento').addEvent('blur', function(e) {
		validateSelect('duracionEvento');
	});
	
	$('concentracionAsistentes').addEvent('change', function(e) {
		validateSelect('concentracionAsistentes');
	});
	$('concentracionAsistentes').addEvent('blur', function(e) {
		validateSelect('concentracionAsistentes');
	});
	
	$('medidasUnidades').addEvent('blur', function(e) {
		validateInputText('medidasUnidades', 3);
	});
	
	
	$('requiereInstalacion').addEvent('change', function(e) {
		validateSelect('requiereInstalacion');
	});
	$('requiereInstalacion').addEvent('blur', function(e) {
		validateSelect('requiereInstalacion');
	});
	$('month').addEvent('change', function(e) {
		validateFechaEntrega();
	});
	$('month').addEvent('blur', function(e) {
		validateFechaEntrega();
	});
	$('day').addEvent('change', function(e) {
		validateFechaEntrega();
	});
	$('day').addEvent('blur', function(e) {
		validateFechaEntrega();
	});
	
	$('localizacionProvincia').addEvent('change', function(e) {
		if ( $('localizacionPais').get('value')=='España - Spain')
			validateSelect('localizacionProvincia');
	});
	$('localizacionProvincia').addEvent('blur', function(e) {
		if ( $('localizacionPais').get('value')=='España - Spain')
			validateSelect('localizacionProvincia');
	});
	
	$('localizacionPais').addEvent('change', function(e) {
		if ( this.get('value')=='España - Spain' ) showElement('localizacionProvincia');
		else hideElement('localizacionProvincia');
	});
	
	
	
	$('cliTipoParticular').addEvent('click', function(e) {
		hideElement('empresa');
	});
	$('cliTipoEmpresa').addEvent('click', function(e) {
		showElement('empresa');
	});
	
	$('empresa').addEvent('change', function(e) {
		if ( isShowElement('empresa') )
			validateSelect('empresa');
	});
	$('empresa').addEvent('blur', function(e) {
		if ( isShowElement('empresa') )
			validateSelect('empresa');
	});
	
	
	$('infoForm').addEvent('submit', function(e) {
		e.stop();
		
		if (!debug) pageTracker._trackPageview('/info/enviar/');
		
		var result = validarForm( this );
		if ( result==true ) {
			$('message_dbj').set('text', '');
			requestEnviarInfoForm( this );
		} else {
			$('message_dbj').adopt(error_div);
			if (!debug) pageTracker._trackPageview('/info/errorValidacion/');
		}
		return false;
		
	});
	
	return;
}

function showCarpas( ) {
	showElement('carpasAlquilerOVentaDiv');
	showElement('tipoEventoDiv');
	hideElement('medidasUnidadesDiv');
	hideElement('requiereInstalacionDiv');
}
function hideAlquiler( ) {
	hideElement('tipoEventoDiv');
	hideElement('medidasUnidadesDiv');
	hideElement('requiereInstalacionDiv');
}



function ProductsByCategoryLN( ) {
	$('categoriaProducto').addEvent('change', function(e) {
		validateSelect('categoriaProducto');
		if (this.get('value')!=0) { 
			requestProductsByCategory($('infoForm'));
			
			// carpas
			if (this.get('value')==3) {
				showElement('carpasAlquilerOVentaDiv');
				showElement('tipoEventoDiv');
				hideElement('medidasUnidadesDiv');
				hideElement('requiereInstalacionDiv');
			}
			// rotulacion
			if ( this.get('value')==8 || this.get('value')==6) { 
				hideElement('carpasAlquilerOVentaDiv');
				hideElement('tipoEventoDiv');
				showElement('medidasUnidadesDiv');
				showElement('requiereInstalacionDiv');
			}
			// confeccion
			if (this.get('value')==4) { 
				hideElement('carpasAlquilerOVentaDiv');
				hideElement('tipoEventoDiv');
				showElement('medidasUnidadesDiv');
				showElement('requiereInstalacionDiv');
			}
			// cubiertas textiles
			if (this.get('value')==9) { 
				hideElement('carpasAlquilerOVentaDiv');
				hideElement('tipoEventoDiv');
				showElement('medidasUnidadesDiv');
				hideElement('requiereInstalacionDiv');
			}
			// lonas piscinas
			if (this.get('value')==10) { 
				hideElement('carpasAlquilerOVentaDiv');
				hideElement('tipoEventoDiv');
				showElement('medidasUnidadesDiv');
				hideElement('requiereInstalacionDiv');
			}
			// fachada textil
			if (this.get('value')==11) { 
				hideElement('carpasAlquilerOVentaDiv');
				hideElement('tipoEventoDiv');
				showElement('medidasUnidadesDiv');
				hideElement('requiereInstalacionDiv');
			}
			// arquitectura textil
			if (this.get('value')==2) { 
				hideElement('carpasAlquilerOVentaDiv');
				hideElement('tipoEventoDiv');
				showElement('medidasUnidadesDiv');
				hideElement('requiereInstalacionDiv');
			}
			// toldos
			if (this.get('value')==7) { 
				hideElement('carpasAlquilerOVentaDiv');
				hideElement('tipoEventoDiv');
				showElement('medidasUnidadesDiv');
				hideElement('requiereInstalacionDiv');
			}
			
			
		}
		
	});
	return;
}

function addEventToProducto( ) {
	
	if (!$defined($('fkIdProducto'))) return;
	
	$('fkIdProducto').addEvent('blur', function(e) {
		validateSelect('fkIdProducto');
	});
	$('fkIdProducto').addEvent('blur', function(e) {
		validateSelect('fkIdProducto');
	});
	
	return;
}
function validarForm( _form ) {
	
	var error = '';
	
	if ( $('ConsentimientoLOPD').getProperty('checked')!=true ) {
		$('ConsentimientoLOPDError').addClass('errorInput');
		error += 'ConsentimientoLOPD';
	} else {
		if ($('ConsentimientoLOPDError').hasClass('errorInput')) $('ConsentimientoLOPD').removeClass('errorInput');
	}

	error += validateInputText('nombreCompleto', 5);
	error += validateInputText('direccion', 5);
	error += validateInputText('poblacionCli', 4);
	if ( $('lugar').get('value')=='España - Spain' )
		error += validateSelect('provincia'); 
	
	// lugar ~= country
	// horarioContacto : optional
	error += validateInputText('tlf', 9);
	error += validateMail('correo');
	// procedenciaCli
	if ( $('otroCliente').getProperty('checked')==true ) {
		error += validateSelect('medioMk');
				if ( $('medioMk').get('value')=='Otros a definir') {
			if ( $('medioMkOtro').get('value')=='otra procedencia definir') $('medioMkOtro').set('value','');
			error += validateInputText('medioMkOtro',5);
		}
	}
	 
	error += validateSelect('categoriaProducto');
	error += validateSelect('fkIdProducto');
	
	// carpasAlquilerOVenta 
	if (isShowElement('carpasAlquilerOVentaDiv')) {
		if ( $('carpasAlquiler').getProperty('checked')==true ) {
			error += validateSelect('tipoEvento');
			error += validateSelect('duracionEvento');
			error += validateSelect('concentracionAsistentes');
		}
	}
	
	
	if (isShowElement('medidasUnidadesDiv')) error += validateInputText('medidasUnidades', 3);
	
	if (isShowElement('requiereInstalacionDiv')) error += validateSelect('requiereInstalacion');
	
	error += validateFechaEntrega();
	
	
	if ( $('localizacionPais').get('value')=='España - Spain')
			error += validateSelect('localizacionProvincia');
	
	if ( isShowElement('empresa') )
			error += validateSelect('empresa');
	
	
	
	
	
	//alert('error='+error);
	if (error=='') return true;
	
	return false;
	
}
function validateFechaEntrega( ) {
	error_ = '';
	// new Date(year, month, day, hours, minutes, seconds, milliseconds)
	var date = new Date( $('year').get('value'),$('month').get('value'),$('month').get('day'),23,59,59);
	//alert(date);
	//var date = new Date( $('year').get('value'),$('month').get('value'),$('month').get('day'));
	var today = new Date();
	if (date < today) {
		showInputError('month');
		showInputError('day');
		error_ += 'FechaEntrega';
	} else {
		hideInputError('month');
		hideInputError('day');
	}
	return error_;
}

function validateMail( _id ) {
	error_ = '';
	if ( !regIsEmail($(_id).get('value')) ) { 
		showInputError(_id);
		error_ += _id;
	} else {
		hideInputError(_id);
	}
	return error_;
}
function validateSelect( _id ) {
	error_ = '';
	if (!$defined($(_id))) return;
	if ( $(_id).get('value')=='0' || $(_id).get('value')=='-1' ) {
		showInputError(_id);
		error_ += _id;
	} else {
		hideInputError(_id);
	}
	return error_;
}
function validateInputText( _id , _minlength ) {
	error_ = '';
	if (!$defined($(_id))) return;
	if (($(_id).get('value')).length < _minlength) { 
		showInputError(_id);
		error_ += _id;
	} else {
		hideInputError(_id);
	}
	return error_;
}

function showInputError( _id ) {
	if (!$defined($(_id))) return;
	if (!$(_id).hasClass('errorInput')) $(_id).addClass('errorInput');
}
function hideInputError( _id ) {
	if (!$defined($(_id))) return;
	if ($(_id).hasClass('errorInput')) $(_id).removeClass('errorInput');
}
function showElement( _id ) {
	if (!$defined($(_id))) return;
	if ($(_id).hasClass('oculto')) $(_id).removeClass('oculto');
}
function hideElement( _id ) {
	if (!$defined($(_id))) return;
	if (!$(_id).hasClass('oculto')) $(_id).addClass('oculto');
}
function isShowElement( _id ) {
	if (!$defined($(_id))) return false;
	if ($(_id).hasClass('oculto')) return false; 
	else return true;
} 

function requestProductsByCategory( _form ) {
	
	myRequestEnviarInfoForm.onSuccess=function(responseTree, responseElements, responseHTML, responseJavaScript) {
		$('fkIdProductoDiv').set('html', responseHTML);
		
		addEventToProducto();
		//if (!debug) pageTracker._trackPageview('/info/requestProductsByCategory/'+_form.get('categoriaProducto'));
	};
	myRequestEnviarInfoForm.onFailure=function(responseTree, responseElements, responseHTML, responseJavaScript) {
		$('message_dbj').adopt(error_div);
		//if (!debug) pageTracker._trackPageview('/info/requestProductsByCategory/errorOnFailure/'+_form.get('categoriaProducto'));
	};
	
	myRequestEnviarInfoForm.send({data: _form, url: _form.get('action')+'?getProduct=true'});
	return;
}

function requestEnviarInfoForm( _form ) {
	
	$('enviarInfoForm').addClass('oculto');
	$('loading').removeClass('oculto');
	
	myRequestEnviarInfoForm.onSuccess=function(html) {
		
		ocultarInfo.delay(0);
		objContainerFx.slideIn('horizontal');
		
		$('message_dbj').adopt(html);
		
		if (!debug) pageTracker._trackPageview('/info/enviadoOK/');
		
		$('navegacion').grab(Enviada_solicitud, 'bottom');
						
	};
	myRequestEnviarInfoForm.onFailure=function(html) {
		
		//$('message_dbj').getElement('div[class="error"]').set('text', 'The request failed.');
		//$('message_dbj').adopt(html); // No recoge el html en onFailure
		$('message_dbj').adopt(error_div);
		$('enviarInfoForm').removeClass('oculto');
		$('loading').addClass('oculto');
		
		if (!debug) pageTracker._trackPageview('/info/errorOnFailure/');
	};
	
	myRequestEnviarInfoForm.send({data: _form, url: _form.get('action')});
	
}


// Check if string is a valid email address
function regIsEmail(fData) {
	/* http://ntt.cc/2008/05/10/over-10-useful-javascript-regular-expression-functions-to-improve-your-web-applications-efficiency.html */
       //var reg = new RegExp("^[0-9a-zA-Z]+@[0-9a-zA-Z]+[\.]{1}[0-9a-zA-Z]+[\.]?[0-9a-zA-Z]+$");
		var reg = new RegExp("^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,6}$");
       //alert('regIsEmail'+reg.test(fData))
       return reg.test(fData);
}

