var errors = null;
var passwordFieldShown = false;

$(document).ready(function() {

	if (window['accommodationid'] == null) return;

	$('#reviewsubmissionform').ajaxForm(options);
	
	//The submit button
	$("#submit_review").click(function()
	{
		$('#reviewsubmissionform').ajaxForm(options);
	});

	$('#already_a_member').click(function() {
		return toggleMemberFields();
	});

	$("#forgot_password a").click(function()
	{
		$("#get_password").jqm({
			toTop:true,
			overlay: 50
		});

		$("#get_password").jqmShow();

		$("#get_password input[type=text]").val(
			$("#email").val()
			);

		return false;
	});

	$('#photoupload').change( ajaxFileUpload );

	//convert from caps
	$("#convert_caps").click(function() {
		convertFromCaps();
	});
	
	$('#terms_link').click(function() { 
		window.open('/terms.html?popup=1', 'newWindow', makeOptions()); 
		return false; 
	});
	
	$('#managementResponse').click(function() { 
		window.open('/Management-Response-'+accommodationid+'.html', 'newWindow', makeOptions()); 
		return false; 
	});

	reloadTemporaryUploadedImages();
});

var options = { 
	beforeSubmit:  showRequest,
	success:       showResponse
};

function ajaxFileUpload()
{
	//starting setting some animation when the ajax starts and completes
	$("#loading")
	.ajaxStart(function(){
		$(this).show();
	})
	.ajaxComplete(function(){
		$(this).hide();
	});

	$.ajaxFileUpload
	(
	{
		url: '/HotelPhotoSubmission.html?action=upload&accommodationid=' + accommodationid,
		secureuri: false,
		fileElementId: 'photoupload',
		dataType: 'json',
		success: function (data, status)
		{
			if (data['error_message'])
			{
				showAlertMessage(data.error_message);
				return;
			}

			for(i in data.ids) addImage(i, data.ids[i]);
		},
		error: function (data, status, e)
		{
			showAlertMessage(data.error_message)
		}
	}
	)

	//somehow the onchange event binding. We rebind
	$('#photoupload').change( ajaxFileUpload );

	return true;
}

/**
 * Upon reloading a hotel page, this function
 * re-fetches the previously uploaded images
 */
function reloadTemporaryUploadedImages()
{
	$.getJSON("/HotelPhotoSubmission.html?accommodationid=" + accommodationid,
		function(data){
			$.each(data.ids, function(i,item){
				addImage(i, item);
			});
		});
}

/**
 * This adds temporary images to the review form
 */
function addImage(position, id)
{
	//id == 0, the uploaded photo is not yet in the div
	if($('#tmpphotos').find('img[id='+id+']').length == 0)
	{
		var div = new jQuery('<div />');
		div.addClass('tempimage_wrapper');


		var img = new jQuery('<img />');
		img.attr('src', '/tmp-images/' + accommodationid + '-' + id);
		img.attr('position', position);
		img.addClass('tempimage');
		img.attr('id', id);

		var url = "/HotelPhotoSubmission.html";
		var data = "accommodationid=" + accommodationid + "&action=delete"
					+ "&id=" + id;

		img.click(function() {
			jQuery.getJSON( url, data,
			function() {
				$('img[id='+id+']').parent().fadeOut("fast");
			});
		});

		div.append(img);

		var p = new jQuery('<p />');
		p.addClass('tempimage_comment');
		p.attr('id', 'tempimage_comment_' + id);
		p.html('<em>click to add text...</em>');
		div.append(p);

		p.click(function(){
			 $.blockUI({  
				 message: $('#tempimage_form_' + id),
				 css: {width: '300px', height: '300px'}
			 });
		});

		var hiddenDiv = new jQuery('<div />');
		var info = new jQuery('<p />');
		info.addClass('tempimage_form_info');
		info.attr('id', 'tempimage_form_info_' + id);
		info.html('Please add a description in the box below.');

		hiddenDiv.addClass('tempimage_form')
		hiddenDiv.attr('id', 'tempimage_form_' + id);
		var input = new jQuery('<textarea />');
		input.attr('id', 'tempimage_textarea_' + id);
		input.attr('name', 'tempimage_textarea_' + id);
		input.addClass('tempimage_textarea');

		var cancel = new jQuery('<a />');
		cancel.html('[x] cancel');
		cancel.addClass('tempimage_form_cancel');

		cancel.click(function(){
			 $.unblockUI();
		});

		var submit = new jQuery('<button />');
		submit.html('submit');

		submit.click(function(){
			var comment = '#tempimage_textarea_' + id;
			sendTempImageComment(id, $(comment).val());
		});

		hiddenDiv.append(info);
		hiddenDiv.append(input);
		hiddenDiv.append(cancel);
		hiddenDiv.append('&nbsp;');
		hiddenDiv.append(submit);
		div.append(hiddenDiv);

		$('#tmpphotos').append(div);
	}
}

function sendTempImageComment(_id, _comment)
{
	var url = "/HotelPhotoSubmission.html";
		var data = "accommodationid=" + accommodationid + "&action=acccomment"
					+ "&id=" + _id + "&comment=" + encodeURIComponent(_comment);

	jQuery.getJSON( url, data,
		function(reponse) {
			if (reponse.success)
			{
				$('#tempimage_comment_' + _id + ' em').html(_comment.substring(0, 10 ) + '...');
				$.unblockUI();
			}
			else
			{
				$('#tempimage_form_info_' + _id).html(reponse.error_message);
				$('#tempimage_form_info_' + _id).addClass('error');
			}
		});
}

function toggleMemberFields()
{
	if (!passwordFieldShown)
	{
		$('.form_row_password').fadeIn("slow");
		$('#already_a_member a').html('not a member');
	}
	else
	{
		$('.form_row_password').fadeOut("slow");
		$('#already_a_member a').html('already a member');
	}

	passwordFieldShown = !passwordFieldShown;

	return false;
}

function showRequest(formData, jqForm, options) 
{
	showMessage("Saving your review...");
}

function showResponse(responseText, statusText)
{
	$.unblockUI({});

	response = eval('(' + responseText + ')');
   		
	switch(response['result'])
	{
		case 'success':
			$('.hotels_review_form').hide();
			$('#hotels_review_thx').fadeIn("fast");

			$('#hotels_review_thx').insertAfter($('a[name=reviews_start]'));
			scrollWin();
			break;
		case 'error':
			errors = response.errors;
			
			resetErrors();
			
			for (field in errors)
			{
				for ( error in errors[field])
				{
					$('label[for='+field+']').addClass('error');

					if (field == 'comment' && errors[field]['tooMuchCaps'])
					{
						$("#caps_box").fadeIn("slow");
					}
					if (field == 'whenyear')
					{
						$('label[for=whenmonth]').addClass('error');
					}
				}
			}

			if (response.errors['needpasswordconfirmation'] != null)
			{
				passwordFieldShown = false;
				toggleMemberFields();
				$('label[for=password]').addClass('error');
			}

			if (response['error_message'] != null)
			{
				$('#error_message').html(response['error_message']);
				$('#error_message').fadeIn("slow");
				$('#error_message').addClass('error');
			}

			break;
		default:
			showAlertMessage('Unknown Reponse from Server. Please Try Again.');
			break;
	}
}

function resetErrors()
{
	$('#error_message').fadeOut("slow");
	$('#error_message').html('');

	$('.error').removeClass('error');
	
	if (errors != null)
	{
		for (field in errors)
		{
			for ( error in errors[field])
			{
				//This loops thru all error messages for a given form field
				//nothing to do so far.
			}
		}
	}
}

function convertFromCaps() {

	var text = $("#comment").val();
	var newText = '';

	$.each(text.split('. '), function(i, line) {
		if(i != 0) {
			newText += '. ';
		}
		newText += line.charAt(0).toUpperCase() + line.substr(1).toLowerCase();
	});

	$("#comment").val(newText);
	$("#caps_box").fadeOut("slow");
}

function scrollWin(){
	$('html, body').animate({
		scrollTop: $('a[name=reviews_start]').offset().top
	}, 800);
}