function changeImage(n) {
		
	img_thumb = $('img#image-' + n);
	img_current = $('#image-current');
	title_current = $('#image-title');

	title = img_thumb.attr('title');

	img_current.attr('src', '/img/ad/' + title);
	img_current.attr('title', title);
	title_current.html(title);

}

function voteAd(opinion, id) {

	var ac = new AjaxConfigurator();

	$.ajax({
	  	url: ac.url + 'votar-anuncio/',
		type: 'POST',
		data: 'opinion=' + opinion + '&id=' + id,
	 	cache: false,
	  	success: function(html) {
			$('span#num-votes').html(html);
			small = $('span#small-num-votes');
			n = parseInt(small.html());
			small.html(n+1);
	  	}
	});
}

function showAllOpinions(id) {

	var ac = new AjaxConfigurator();

	$.ajax({
	  	url: ac.url + 'mostrar-todas-opiniones/',
		type: 'POST',
		data: '&id=' + id,
	  	cache: false,
	  	success: function(html){
	    	$('#fancy_div').html(html);
	  	}
	});

}

function showShareByMail() {

	var ac = new AjaxConfigurator();

	$.ajax({
	  	url: ac.url + 'mostrar-compartir-por-email/',
	  	cache: false,
	  	success: function(html){
	    	$('#fancy_div').html(html);
	  	}
	});

}

function validateShareAdByMail(res) {

	valid = true;

	valid = checkEmail('email', valid);
	valid = checkNotBlank('name', valid);

	verify = $('input[name=verify]:visible').val();

	if(verify == '') {
		$('label[for=verify]:visible').addClass('error');
		valid = false;
	} else {
		if(verify == res) {
			$('label[for=verify]:visible').removeClass('error');
		} else {
			$('label[for=verify]:visible').addClass('error');
			valid = false;
		}
	}

	if(valid) {
		
		$('p[error=error]:visible').html('');
		$('div.button').hide();
		$('div.loading').show();

		// mandamos el correo
		var ac = new AjaxConfigurator();

		$.ajax({
		  	url: ac.url + 'compartir-por-email/',
		 	cache: false,
			type: 'POST',
			data: 	'name=' + $('input[name=name]:visible').val() +
					'&email=' + $('input[name=email]:visible').val() +
					'&message=' + $('textarea[name=message]:visible').val() +
					'&url=' + window.location.pathname,
		  	success: function(html) {
				$.fn.fancybox.close();
				$('div#flash-messages').html(html);
		  	}
		});

	} else {
		$('p[error=error]:visible').html('Porfavor, revisa los campos del formulario marcados en <b>ROJO</b>.');
	}

}

function showAskQuestion(from, title, alias, image1, id_ad, id_user) {

	var ac = new AjaxConfigurator();

	$.ajax({
	  	url: ac.url + 'mostrar-hacer-consulta/',
		type: 'POST',
		data: 	'title=' + title +
				'&from=' + from + 
				'&alias=' + alias + 
				'&image1=' + image1 +
				'&id_user=' + id_user +
				'&id_ad=' + id_ad,
	  	cache: false,
	  	success: function(html){
	    	$('#fancy_div').html(html);
	  	}
	});

}

function validateAskQuestion(res) {

	valid = true;

	valid = checkNotBlank('message', valid);

	verify = $('input[name=verify]:visible').val();

	if(verify == '') {
		$('label[for=verify]:visible').addClass('error');
		valid = false;
	} else {
		if(verify == res) {
			$('label[for=verify]:visible').removeClass('error');
		} else {
			$('label[for=verify]:visible').addClass('error');
			valid = false;
		}
	}

	if(valid) {
		
		$('p[error=error]:visible').html('');
		$('div.button').hide();
		$('div.loading').show();

		// mandamos el correo
		var ac = new AjaxConfigurator();

		$.ajax({
		  	url: ac.url + 'hacer-consulta/',
		 	cache: false,
			type: 'POST',
			data: 	'id_ad=' + $('input[name=ask-question-id-ad]:hidden').val() +
					'&id_user=' + $('input[name=ask-question-id-user]:hidden').val() +
					'&from=' + $('input[name=from]:hidden').val() +
					'&message=' + $('textarea[name=message]:visible').val(),
		  	success: function(html) {
				$.fn.fancybox.close();
				$('div#flash-messages').html(html);
		  	}
		});

	} else {
		$('p[error=error]:visible').html('Porfavor, revisa los campos del formulario marcados en <b>ROJO</b>.');
	}

}

function showCompleteDescription() {

	pShort = $('p#short-description');
	pComplete = $('p#complete-description');
	pShort.hide();
	pComplete.show();

}

function showContractAd(title, alias, image1, id_ad, id_user) {

	var ac = new AjaxConfigurator();

	$.ajax({
	  	url: ac.url + 'mostrar-contratar-anuncio/',
		type: 'POST',
		data: 	'title=' + title +
				'&alias=' + alias + 
				'&image1=' + image1 +
				'&id_user=' + id_user +
				'&id_ad=' + id_ad,
	  	cache: false,
	  	success: function(html){
	    	$('#fancy_div').html(html);
	  	}
	});

}

function initializeRentAd() {
	$('.ad-by-hour').hide();
}


function showHours() {
	$('.ad-by-hour').show();
	$('.link').hide();
}

function calculatePrice() {

	valid = true;

	date_start = $('#date_start').val();
	date_end = $('#date_end').val();

	if(date_start != '' && date_end != '') {

		$('#bill').html('');
		$('#loading').show();

		id_ad = $('input#id_ad:hidden').val();
		hour_start = $('#hour_start option:selected').val();
		hour_end = $('#hour_end option:selected').val();
		extras = '';

		$('.ad-extras input').each(
			function(i) {
				input = $(this);
				if(input.attr('checked')) {
					extras += input.attr('id') + ',';
				}
			}
		);

		secure = $('#secure').attr('checked');

		send_std = $('#can_send_closed_price_standard').attr('checked');
		send_urg = $('#can_send_closed_price_urgent').attr('checked');

		var ac = new AjaxConfigurator();
	
		$.ajax({
		  	url: ac.url + 'calcular-precio/',
		 	cache: false,
			type: 'POST',
			data: 	'date_start=' + date_start +
					'&date_end=' + date_end + 
					'&hour_start=' + hour_start + 
					'&hour_end=' + hour_end +
					'&extras=' + extras +
					'&secure=' + secure +
					'&send_std=' + send_std +
					'&send_urg=' + send_urg +
					'&id_ad=' + id_ad,
		  	success: function(html) {
				$('#loading').hide();
				$('#bill').html(html);
		  	}
		});

	}

}

function validateRentAd(res) {

	valid = true;

	// Selección de fechas
	valid = checkNotBlank('date_start', valid);
	valid = checkNotBlank('date_end', valid);

	if(!valid) {
		setErrorTitle('¡Cuidado!');
		setErrorContent('Debes introducir las fechas de las que quieres disponer del producto. Revisa los campos en <b>rojo</b>.');
		displayError();
		$(location).attr('href','#seccion-1');
		return false;
	} 

	date_start = $('#date_start').val();
	date_end = $('#date_end').val();
	hour_start = $('#hour_start option:selected').val();
	hour_end = $('#hour_end option:selected').val();
	
	if(esMenor(date_start, date_end)) {
		setErrorTitle('¡Cuidado!');
		setErrorContent('La fecha de finalización es anterior a la fecha de inicio. Revisa los campos de fechas.');
		displayError();
		$(location).attr('href','#seccion-1');
		return false;
	}

	if(date_start == date_end) {
		if(hour_end - hour_start <= 0) {
			setErrorTitle('¡Cuidado!');
			setErrorContent('La fecha de finalización es anterior a la fecha de inicio. Revisa los campos de fechas.');
			displayError();
			$(location).attr('href','#seccion-1');
			return false;
		}
	}
	
	if(datepickerHelper.validateDate(date_start, date_end)) {
		setErrorTitle('¡Cuidado!');
		setErrorContent('Un pedido no puede ser realizado en fechas <b>no disponibles<b>.');
		displayError();
		$(location).attr('href','#seccion-1');
		
		return false;
	}
	
	date_start_format = datepickerHelper.correctFormat(date_start);
	date_end_format = datepickerHelper.correctFormat(date_end);
	
	if(checkLimits(date_start_format + ' ' + hour_start + ':00:00', date_end_format + ' ' + hour_end + ':00:00')) {
		setErrorTitle('¡Cuidado!');
		setErrorContent('No estás respetando los <b>límites de reserva</b> de este producto.');
		displayError();
		$(location).attr('href','#seccion-1');
		
		return false;
	}

	// Opciones de pago y envío
	n = $('input[name^=can_pay]:checked').length;
	if(valid && n == 0) {
		setErrorTitle('¡Cuidado!');
		setErrorContent('Debes seleccionar <b>como mínimo una forma de pago</b>.');
		displayError();
		$(location).attr('href','#seccion-2');
		valid = false;
	} // */

	n = $('input[class^=can_send]:checked').length;
	if(valid && n == 0) {
		setErrorTitle('¡Cuidado!');
		setErrorContent('Debes seleccionar <b>como mínimo una forma de envío</b>.');
		displayError();
		$(location).attr('href','#seccion-2');
		valid = false;

	} 

	if(valid) {
						
		// Confirmar pedido
		valid = checkIsChecked('contract_policy', valid);
		valid = checkIsChecked('privacy_policy', valid);

		if(!valid) {

			setErrorTitle('¡Cuidado!');
			setErrorContent('Debes aceptar la política de contratación y de privacidad.');
			displayError();
			$(location).attr('href','#seccion-3');
			return false;

		} 

		verify = $('input[name=verify]').val();
			
		if(verify == '') {
			$('label[for=verify]').addClass('error');
			valid = false;
		} else {
			if(verify == res) {
				$('label[for=verify]').removeClass('error');
			} else {
				$('label[for=verify]').addClass('error');
				valid = false;
			}
		}

		if(!valid) {

			setErrorTitle('¡Cuidado!');
			setErrorContent('No has introducido el código de verificación correctamente.');
			displayError();
			$(location).attr('href','#seccion-3');
			return false;

		} 

		extras = '';

		$('.ad-extras input').each(
			function(i) {
				input = $(this);
				if(input.attr('checked')) {
					extras += input.attr('id') + ',';
				}
			}
		);
		
		$('#extras:hidden').val(extras);
		$('.contract-button').hide();
		$('.loading').show();
		$('form#rent-ad').submit();	
	}

}

function validateReserveAd(res) {

	valid = true;

	// Selección de fechas
	valid = checkNotBlank('date_start', valid);
	valid = checkNotBlank('date_end', valid);

	if(!valid) {
		setErrorTitle('¡Cuidado!');
		setErrorContent('Debes introducir las fechas de las que quieres disponer del producto. Revisa los campos en <b>rojo</b>.');
		displayError();
		$(location).attr('href','#seccion-1');
		return false;
	} 

	date_start = $('#date_start').val();
	date_end = $('#date_end').val();
	hour_start = $('#hour_start option:selected').val();
	hour_end = $('#hour_end option:selected').val();
	
	if(esMenor(date_start, date_end)) {
		setErrorTitle('¡Cuidado!');
		setErrorContent('La fecha de finalización es anterior a la fecha de inicio. Revisa los campos de fechas.');
		displayError();
		$(location).attr('href','#seccion-1');
		return false;
	}

	if(date_start == date_end) {
		if(hour_end - hour_start <= 0) {
			setErrorTitle('¡Cuidado!');
			setErrorContent('La fecha de finalización es anterior a la fecha de inicio. Revisa los campos de fechas.');
			displayError();
			$(location).attr('href','#seccion-1');
			return false;
		}
	}
	
	if(datepickerHelper.validateDate(date_start, date_end)) {
		setErrorTitle('¡Cuidado!');
		setErrorContent('Un pedido no puede ser realizado en fechas <b>no disponibles<b>.');
		displayError();
		$(location).attr('href','#seccion-1');
		
		return false;
	}
	
	date_start_format = datepickerHelper.correctFormat(date_start);
	date_end_format = datepickerHelper.correctFormat(date_end);
	
	if(checkLimits(date_start_format + ' ' + hour_start + ':00:00', date_end_format + ' ' + hour_end + ':00:00')) {
		setErrorTitle('¡Cuidado!');
		setErrorContent('No estás respetando los <b>límites de reserva</b> de este producto.');
		displayError();
		$(location).attr('href','#seccion-1');
		
		return false;
	}

	// Opciones de pago y envío
	n = $('input[name^=can_pay]:checked').length;
	if(valid && n == 0) {
		setErrorTitle('¡Cuidado!');
		setErrorContent('Debes seleccionar <b>como mínimo una forma de pago</b>.');
		displayError();
		$(location).attr('href','#seccion-2');
		valid = false;
	} // */

	n = $('input[class^=can_send]:checked').length;
	if(valid && n == 0) {
		setErrorTitle('¡Cuidado!');
		setErrorContent('Debes seleccionar <b>como mínimo una forma de envío</b>.');
		displayError();
		$(location).attr('href','#seccion-2');
		valid = false;

	} 

	if(valid) {
						
		// Confirmar pedido
		valid = checkIsChecked('contract_policy', valid);
		valid = checkIsChecked('privacy_policy', valid);

		if(!valid) {

			setErrorTitle('¡Cuidado!');
			setErrorContent('Debes aceptar la política de contratación y de privacidad.');
			displayError();
			$(location).attr('href','#seccion-3');
			return false;

		} 

		verify = $('input[name=verify]').val();
			
		if(verify == '') {
			$('label[for=verify]').addClass('error');
			valid = false;
		} else {
			if(verify == res) {
				$('label[for=verify]').removeClass('error');
			} else {
				$('label[for=verify]').addClass('error');
				valid = false;
			}
		}

		if(!valid) {

			setErrorTitle('¡Cuidado!');
			setErrorContent('No has introducido el código de verificación correctamente.');
			displayError();
			$(location).attr('href','#seccion-3');
			return false;

		} 

		extras = '';

		$('.ad-extras input').each(
			function(i) {
				input = $(this);
				if(input.attr('checked')) {
					extras += input.attr('id') + ',';
				}
			}
		);
		
		$('#extras:hidden').val(extras);
		$('.contract-button').hide();
		$('.loading').show();
		$('form#reserve-ad').submit();	
	}

}

errorLimit = false;

function checkLimits(dateTime_start, dateTime_end){
	var ac = new AjaxConfigurator();
	
	$.ajax({
		  url: ac.url + "check-limits/",
		  cache: false,
		  async: false,
		  type: 'POST',
		  data: 'dateTime_start=' + dateTime_start + '&dateTime_end=' + dateTime_end + 
		  		'&id_ad=' + $('#id_ad').val(),
		  success: function(json){
			a = eval(json);
			errorLimit = a.isError;
		}});
	
	return errorLimit;
}

function esMenor(fecha, fecha2)  
{  
    var xMonth=fecha.substring(3, 5);  
    var xDay=fecha.substring(0, 2);  
    var xYear=fecha.substring(6,10);  
    var yMonth=fecha2.substring(3, 5);  
    var yDay=fecha2.substring(0, 2);  
    var yYear=fecha2.substring(6,10);  
    if (xYear> yYear)  
    {  
        return(true)  
    }  
    else  
    {  
      if (xYear == yYear)  
      {   
        if (xMonth> yMonth)  
        {  
            return(true)  
        }  
        else  
        {   
          if (xMonth == yMonth)  
          {  
            if (xDay> yDay)  
              return(true);  
            else  
              return(false);  
          }  
          else  
            return(false);  
        }  
      }  
      else  
        return(false);  
    }  
}


