/**
 * (c) Copyright Ashantiplc Limited.
 * All Rights Reserved. Duplication prohibited.
 * Redistribution, Transmission, displayed by any means prohibited.
 * You may not alter or remove any trademark, copyright or other notices.
 * Author: Andrey Anisimov
 */

load('core.ajax.*');
load('core.ui.Event');
load('core.ui.Balloon');
load('core.ui.Calendar');
load('core.ui.Container');
load('core.ui.FileUpload');

load('editor.ui.Balloon');
load('editor.plugins.wizard.MemorialWizard');

load('common.PageMenu');
load('common.util.DateUtils');

function showTip(field, text) {
	if (!defined(window.balloon)) {
		balloon = new editor.ui.Balloon();
	}
	balloon.setOwner(new core.ui.Container(field));
	balloon.setText(text);
	balloon.setPosition(core.ui.Balloon.RIGHT);
	balloon.show();
}

function hideTip() {
	if (defined(window.balloon)) {
		window.balloon.hide();
	}
}

// Registration page. Step #1

function checkContactData(form) {
	var arr = [form.firstName, form.lastName, form.address, form.city, form.state, form.zip];
	for (var id in arr) {
		var field = arr[id];
		if (field.value.length == 0) {
			showTip(field, 'Please fill in this field.');
			return false;
		}
	}
	return true;
}

function checkPersonData(form) {
    if (!checkUsername(form.username) || !checkPassword(form.password, form.repeat) ||
		!checkContactData(form) || !checkPhone(form.phone) || !checkEmail(form.email) ||
		!checkRelation(form.relation, form.other))
	{
		return false;
	}
    return true;
}

function sendRegistrationData(form, reserved) {
    if (!checkPersonData(form)) {
        return false;
    }
	core.ajax.sendRequest('ajax.CheckRegistrationData', onRegistrationResponse, {
		'username' : form.username.value,
		'email' : form.email.value
	});
	return false;
}

function onRegistrationResponse(response) {
	with (document.getElementById('registrationForm')) {
		if ('OK' === response.status) {
			submit();
		} else if (defined(response.message)) {
			if ('username' == response.failee) {
				showTip(username, response.message);
			} else {
				showTip(email, response.message);
			}
		}
	}
}

function checkRelation(field, other) {
	if ('' == field.value) {
		showTip(field, 'Please tell us how did you hear about us?');
		return false;
	} else if (('other' == field.value) && (0 == other.value.length)) {
		showTip(other, 'Please tell us how did you hear about us?');
		return false;
	}
	return true;
}

function checkPhone(field) {
	if (!field.value.match(/^\+?[\d\(][\d\s-]*(\(\d+\))?[\d\s-]*/) || field.value.match(/[a-zA-Z]/)) {
		showTip(field, 'Please enter correct phone number.');
		return false;
	}
	return true;
}

function checkEmail(field) {
	if (!field.value.match(/^[_A-Za-z0-9-]+(\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\.[A-Za-z0-9-]+)+$/)) {
		showTip(field, 'Please enter your email.')
		return false;
	}
	return true;
}

function checkUsername(field) {
	if (!field.value.match(/^[a-z0-9]{3,}$/i)) {
		showTip(field, 'Username shoud contain letters, numbers, <br />and should <b>not</b> be less than 3 characters.')
		return false;
	}
	return true;
}

function checkPassword(field, repeat) {
	if (!field.value.match(/^.{5,}$/i)) {
		showTip(field, 'Please type password with 5 or more characters.')
		return false;
	}
	if (repeat && (repeat.value !== field.value)) {
		showTip(repeat, 'Password did not match.');
		return false;
	}
	return true;
}

// Registration page. Step #2

function checkPersonName(field) {
	if (field.value.length < 5) {
		showTip(field, 'Please enter full person\'s name.')
		return false;
	}
	return true;
}

function updateMemorialUrl() {
	document.getElementById('siteNamePreview').innerHTML = document.getElementById('siteNameField').value;
}

function checkSiteName(field) {
	if (field.value.match(/[^a-z0-9_-]/i)) {
		showTip(field, 'Only letters, numbers and hyphens are accepted.<br />Please do <b>not</b> use spaces.');
		return false;
	} else if (field.value.length < 3) {
		showTip(field, 'Site name should consist 3 or more characters.');
		return false;
	}
	return true;
	
}

function submitPersonName(field) {
	if (checkPersonName(field)) {
		core.ajax.sendRequest('ajax.CheckPersonData', onPersonNameResponse, {
			'personName' : field.value
		})
	}
}

function onPersonNameResponse(response) {
	if ('OK' == response.status) {
		
		var siteName = document.getElementById('siteNameField');
		siteName.value = (response.names.length > 0)
			? response.names[0]
			: document.getElementById('personField').value.replace(/[^a-z0-9-]/i, '');
		
		updateMemorialUrl();
		document.getElementById('siteNameBlock').style.display = 'block';
		document.getElementById('id_button').style.display = 'block';
		document.getElementById('id_submit').value = "Create Website";
	} else if (defined(response.message)) {
		showTip(document.getElementById('personField'), response.message);
	}
}

function sendPersonData(form) {
	if ('block' == document.getElementById('siteNameBlock').style.display) {
		if (checkPersonName(form.personName) && checkSiteName(form.siteName)) 	{
			if (form.siteName.value.length < 3) {
				showTip(field, 'Site name should be more than 3 characters length.');
			} else {
				core.ajax.sendRequest('ajax.CheckPersonData', onSiteNameResponse, {
					'personName' : form.personName.value,
					'siteName' : form.siteName.value
				})
			}
		}
	} else {
		submitPersonName(form.personName);
	}
	return false;
}

function onSiteNameResponse(response) {
	with (document.getElementById('personDataForm')) {
		if ('OK' == response.status) {
			submit();
		} else if (defined(response.message)) {
			var field = (response.failee == 'personName') ? personName : siteName;
			showTip(field, response.message);
		}
	}
}

// Login page


function checkLoginForm(form) {
	/*
	if (!checkUsername(form.username)) {
		return false;
	}*/
	
	if (0 == form.password.value.length) {
		showTip(form.password, 'Please enter your password.');
		return false;
	}
    core.ajax.sendRequest('ajax.CheckLogin', onLoginResponse, {
		'username': form.username.value,
		'password': form.password.value
	});
    return false;
}

function onLoginResponse(response) {
	if ('OK' == response.status) {
		window.location = 'SelectWebsite';
    } else if (defined(response.message)) {
		alert(response.message);
    }
}

function checkMessageData(form) {
	if ('' == form.name.value) {
		showTip(form.name, 'Please enter your name.');
		return false;
	}
	if (!checkEmail(form.email)) {
		return false;
	}
	if ('' == form.message.value) {
		showTip(form.message, 'Please enter your message.');
		return false;
	}
	if (('' != form.phone.value) && !checkPhone(form.phone)) {
		return false;
	}
	return true;
}


// Edit personal data page
function checkDate(field) {
	if (field.value.length > 0 && !field.value.match(/^(\d{2})\/(\d{2})\/(\d{4})$/)) {
		if (field.value == 'MM/DD/YYYY') {
			field.value = '';
			return true;
		}
		showTip(field, 'Please enter date in MM/DD/YYYY format.');
		return false;
	} else if (!common.util.DateUtils.exist(field.value)) {
		showTip(field, 'Please enter correct date.');
		return false;
	}
	return true;
}

function checkSearchData(form) {
	if (form.personName.value == '' && form.content.value == '' && 
		(form.birthDate.value == '' || form.birthDate.value == 'MM/DD/YYYY') &&
		(form.deathDate.value == '' || form.deathDate.value == 'MM/DD/YYYY')) 
	{
		showTip(form.personName, 'Please enter some data to search.');
		return false;
	} else return (checkDate(form.birthDate) && checkDate(form.deathDate));
}

function checkEditPersonalDataForm(form) {
	form.privateFlagValue.value = form.privateFlag.checked ? 'on' : 'off';
	if (!checkPersonName(form.personNameField) || !checkDate(form.birthDateField) ||
		!checkDate(form.deathDateField))
	{
		return false;
	}
	if (common.util.DateUtils.toMilliseconds(form.deathDateField.value) > new Date().getTime()) {
		showTip(form.deathDateField, 'The death date cannot be in future.');
		return false;
	}
	core.ajax.sendRequest('ajax.CheckPersonName', onEditPersonalDataResponse, {
		'personName' : form.personName.value
	})
	return false;
}

function onEditPersonalDataResponse(response) {
	if ('OK' == response.status) {
		document.getElementById('editPersonDataFrom').submit();
	} else {
		showTip(document.getElementById('personNameField'), response.message);
	}
}

function onDateChanged(sender, fieldName) {
	if (sender.value.length > 0) {
		if (checkDate(sender)) {
			document.getElementById(fieldName).value = common.util.DateUtils.client2server(sender.value);
			hideTip();
		}
	} else {
		sender.value = 'MM/DD/YYYY';
		document.getElementById(fieldName).value = '';
	}
}

function showPrompt(sender, show, defaultText) {
	if (show) {
		sender.value = (sender.value == '' ? defaultText : sender.value);
	} else {
		sender.value = (sender.value == defaultText ? '' : sender.value);
	}
	sender.style.color = (sender.value == defaultText) ? 'gray' : 'black';
}

// Edit profile
function checkAdminProfileForm(form) {
	return checkUsername(form.username) && 
		(form.password.value.length > 0 ? checkPassword(form.password, form.repeat) : true);
}

function checkEditProfileForm(form) {
	if ((form.password.value.length > 0) && !checkPassword(form.password, form.repeat)) {
        return false;
    }
	if (!checkEmail(form.email) || !checkContactData(form) || !checkPhone(form.phone))	{
		return false;
	}
	core.ajax.sendRequest('ajax.CheckEditProfileData', onEditProfileResponse, {
		'email' : form.email.value
	});
	return false;
}

function onEditProfileResponse(response) {
	with (document.getElementById('editProfileForm')) {
		if ('OK' == response.status) {
			submit();
		} else {
			showTip(email, response.message);
		}
	}
}

function onRelationChanged(sender, other) {
	if (sender.value == 'other') {
		other.style.visibility = 'visible';
		other.focus();
	} else {
		other.style.visibility = 'hidden';
		other.blur();
	}
}

/**
 * Opens the wizard on the current page.
 *
 * Param:
 * newAccount (bool) [optional] Whether to start wizard for new a/c (false by default).
 */
function startWizard(newAccount) {
	if (newAccount) {
		core.ajax.sendRequest('ajax.Track', function() {}, {
			url : 'javascript:startWizard(true)',
			referer : window.location.href
		});
	}
	var wizard = new editor.plugins.wizard.MemorialWizard();
	wizard.start(newAccount);
}

/**
 * Shows the popup menu on the element.
 *
 * Param:
 * element (HTMLElement) The existing DOM element.
 * id (string) The page identifier.
 * isPrivate (bool) Whether the page is private or public.
 */
function showPageMenu(element, id, isPrivate) {
	var origin = new core.ui.Container(element);
	common.PageMenu.getMenu(id, isPrivate).doPopup(origin,
		origin.getAbsX() + origin.getWidth(),
		origin.getAbsY());

}

// Calendar functions

/**
 * Displays a calendar near the specified element.
 * params is an optional argument which can contain the following options:
 * 
 * startYear (int) 4-digit year number
 * endYear (int) 4-digit year number
 * 
 * defaultYear (int) selected year number (current year by default)
 * defaultMonth (int) selected month (current month by default)
 * defaultDay (int) selected day number (current day by default)
 * 
 * displayField (string|HTMLElement) text element which will receive selected date
 * displayFormat (string) date display format (see Calendar.setFormat)
 * 
 * valueField (string|HTMLElement) hidden element which wil receive a date value in specified format
 * valueFormat (string) date value format (see Calendar.setFormat)
 *
 * Param:
 * element (HTMLElement) calendar's owner element
 * params (object) [optional] calendar params
 */
function showCalendar(element, params) {
	
	if (!defined(window.calendar)) {
		return;
	}
	
	if (calendar.getOrigin() && (calendar.getOrigin().getElement() == element)) {
		if (calendar.isPopup()) {
			calendar.endPopup();
		} else {
			calendar.doPopup(calendar.getOrigin());
		}
		return;
	}
	
	if ('object' !== typeof params)	{
		params = {};
	}
	
	with (core.ui) {
	 
		var displayField, valueField;
		if (params.displayField) {
			displayField = ('string' == typeof params.displayField)
				? document.getElementById(params.displayField)
				: params.displayField;
		}
		
		if (params.valueField) {
			valueField = ('string' == typeof params.valueField)
				? document.getElementById(params.valueField)
				: params.valueField;
		}
		
		calendar.notifyDateSelected.clear();
		calendar.notifyDateSelected.addListener(function(sender, date) {
			if (displayField) {
				displayField.value = params.displayFormat ? calendar.getFormattedDate(params.displayFormat) : date;
			}
			if (valueField) {
				valueField.value = calendar.getFormattedDate(params.valueFormat || Calendar.FORMAT_TIMESTAMP);
			}
			sender.endPopup();
		});
		
		try {
			if (displayField && displayField.value && defined(params.displayFormat)) {
				calendar.setFormattedDate(displayField.value, params.displayFormat);
			} else if (valueField && valueField.value && defined(params.valueFormat)) {
				calendar.setFormattedDate(valueField.value, params.valueFormat);
			} else if (defined(params.defaultYear) || defined(params.defaultMonth) || defined(params.defaultDay)){
				calendar.setDate(params.defaultYear, params.defaultMonth, params.defaultDay);
			}
		} catch (e) {	// InvalidParameterException
			// Invalid date, omitting
			console.error(e.message);
		}
		
		if (defined(params.startYear) || defined(params.endYear)) {
			calendar.setYears(params.startYear, params.endYear);
		}
		
		var origin = new Container(element);
		calendar.doPopup(origin, origin.getAbsX(), origin.getAbsY() + origin.getHeight());
		
	} // with (core.ui)
}

// Pre-create calendar
core.ui.Event.addLoadListener(function() {
	window.calendar = new core.ui.Calendar(null, 0, 0);
	window.calendar.setYears(1900, core.ui.Calendar.currentYear);
	window.calendar.getMonthList().getMenu().setStyleName('SearchComboBoxMenu');
	window.calendar.getYearList().getMenu().setStyleName('SearchComboBoxMenu');
});

