var aPopupWindow;
var anotherPopupWindow;
var helpPopupWindow;

var aValueHasChanged = false;

var anyRegExp = /[^\w|\W]/ig;
var alfaRegExp = /[^\w|\s|]/ig;
var numericRegExp = /[^\d]/ig;

var textInputs = new Array();
/*
	ogni elemento dell'array contiene un oggetto con le seguenti proprietà:
	inputObject;
	errorMessage;
*/
	
var dateInputs = new Array();
/*
	ogni elemento dell'array contiene un oggetto con le seguenti proprietà:
	dateArray: array oggetti che compongono la data (anno, mese, giorno)
	timeArray: array oggetti che compongono l'ora (ora, minuto)
	errorMessage: messaggio d'errore
*/

var textareaInputs = new Array();
/*
	ogni elemento dell'array contiene un oggetto con le seguenti proprietà:
	textAreaObject;
	errorMessage;
*/

var selectInputs = new Array();
/*
	ogni elemento dell'array contiene un oggetto con le seguenti proprietà:
	selectObject;
	errorMessage;
*/

function checkLoginForm(f) {
	if (f.username.value.length > 0 && f.password.value.length) {
		return true;
	} else {
		alert('You must enter a USERNAME and a PASSWORD to login');
		focusOn(document.updLogin.username);
		return false;
	}
}

function focusOn(obj) {
	obj.focus();
}

function confirmChange() {
	if (!aValueHasChanged || confirm('It seems data has changed since you have entered this page.\nAre you sure you do NOT want to save?')) {
		ValueChanged(false);
		return true;
	} else {
		return false;
	}
}

function changeCustomer(currentID, customer, businessUnit) {
	if (customer.selectedIndex > 0 && (confirmChange())) {
		newLocation = 'envList.cfm?NewsletterID=' + customer.value;
		if (businessUnit) {
			newLocation += '&BUID=' + businessUnit.value;
		}
		document.location = newLocation;
		if (!businessUnit) {
			window.top.frames.mainFrame.document.location = 'login.cfm?login=1&NewsletterID=' + customer.value;
		}
	} else {
		for (i = 0; i < customer.options.length; i++) {
			if (customer.options[i].value == currentID) {
				customer.options[i].selected = true;
			}
		}
	}
}

function highlight(id) {
	if (confirmChange()) {
		tdList = document.getElementsByTagName('td');
		for (i = 0; i < tdList.length; i++) {
			if (tdList[i].id.indexOf('issue_') != -1) {
				tdList[i].className = 'lineaoff';
			}
		}
		o = document.getElementById('issue_' + id);
		o.className = 'lineaon';
		return true;
	} else {
		return false;
	}
}

function ValueChanged(val) {
	window.top.frames.mainFrame.aValueHasChanged = val;
	window.top.frames.menuFrame.aValueHasChanged = val;
	if (val) {
		notifyUser('You made changes. Remember to save');
	} else {
		notifyUser('');
	}
}

/*
function validateTextInputRegExp(val, contentType) {
	var inputTextRegExp;
	if (val != '') {
		if (contentType == 'any') {
			inputTextRegExp = anyRegExp;
		} else if (contentType == 'onlyalfa') {
			inputTextRegExp = alfaRegExp;
		} else if (contentType == 'numeric') {
			inputTextRegExp = numericRegExp;
		} else {
			return false;
		}
		if (val.search(inputTextRegExp) == -1) {
			alert(1);
			ValueChanged(true);
			return true;
		} else {
			alert(0);
			return false;
		}
	}
}
*/

function notifyUser(str) {
	window.status = str;
	if (str != '' && document.updIssue) {
		document.updIssue.save.disabled = false;
		document.updIssue.save.className = 'save';
		if (document.updIssue.saveScheduleOnly != null) {
			document.updIssue.saveScheduleOnly.disabled = false;
			document.updIssue.saveScheduleOnly.className = 'save';
		}
	}
}

function Validate() {
	var errMsg = '';
	
	for (i = 0; i < textInputs.length; i++) {
		if (textInputs[i].inputObject.value == '' && textInputs[i].inputObject.type != 'file') {
			errMsg += textInputs[i].errorMessage + '\n';
		}
	}
	
	for (i = 0; i < dateInputs.length; i++) {
		errorFound = false;
		if (dateInputs[i].timeArray) {
			tmpDate = new Date(dateInputs[i].dateArray[0].value, dateInputs[i].dateArray[1].value - 1, dateInputs[i].dateArray[2].value, dateInputs[i].timeArray[0].value, dateInputs[i].timeArray[1].value);
			tmpYear = handleYear(tmpDate.getYear());
			if (dateInputs[i].dateArray[2].value != tmpDate.getDate() || dateInputs[i].dateArray[1].value != (tmpDate.getMonth() + 1) || dateInputs[i].dateArray[0].value != tmpYear || dateInputs[i].timeArray[0].value != tmpDate.getHours() || dateInputs[i].timeArray[1].value != tmpDate.getMinutes()) {
				errorFound = true;
			}
		} else {
			tmpDate = new Date(dateInputs[i].dateArray[0].value, dateInputs[i].dateArray[1].value - 1, dateInputs[i].dateArray[2].value);
			tmpYear = handleYear(tmpDate.getYear());
			if (dateInputs[i].dateArray[2].value != tmpDate.getDate() || dateInputs[i].dateArray[1].value != (tmpDate.getMonth() + 1) || dateInputs[i].dateArray[0].value != tmpYear) {
				errorFound = true;
			}
		}
		if (errorFound) {
			errMsg += dateInputs[i].errorMessage + '\n';
		}
	}
	
	for (i = 0; i < textareaInputs.length; i++) {
		if (textareaInputs[i].textAreaObject.value == '') {
			errMsg += textareaInputs[i].errorMessage + '\n';
		}
	}

	for (i = 0; i < selectInputs.length; i++) {
		if (selectInputs[i].selectObject.value == '') {
			errMsg += selectInputs[i].errorMessage + '\n';
		}
	}

	if (errMsg != '') {
		alert('Attention!!\n' + errMsg);
		return false;
	} else {
		return true;
	}
}

function handleYear(yearToHandle) {
	//year is handled in different ways, depending on the browser. checking
	if (yearToHandle < 1000) {
		yearToHandle = yearToHandle + 1900;
	}
	return yearToHandle;
}

function alertUpdated(newsletterID, issueID, isNew, message) {
	ValueChanged(false);
	if (isNew) {
		window.top.frames.menuFrame.document.location = 'envList.cfm?NewsletterID=' + newsletterID + '&IssueID=' + issueID;
	}
	var alertMsg;
	if (message == '') {
		alertMsg = 'Data successfully updated';
	} else {
		alertMsg = 'An error occured:\n' + message;
	}
	alert(alertMsg);
}

function alertUpdatedAdmin(newsletterID, message) {
	ValueChanged(false);
	var alertMsg;
	if (message == '') {
		alertMsg = 'Data successfully updated';
	} else {
		alertMsg = 'An error occured:\n' + message;
	}
	alert(alertMsg);
}

function closePopup() {
	if (window.top.menuFrame.aPopupWindow) {
		window.top.menuFrame.aPopupWindow.close();
		window.top.menuFrame.aPopupWindow = null;
	}

	if (window.top.menuFrame.anotherPopupWindow) {
		window.top.menuFrame.anotherPopupWindow.close();
		window.top.menuFrame.anotherPopupWindow = null;
	}
}

function welcome() {
	var loc = '';
	if (window.top.frames.menuFrame) {
		menuFrameDocument = window.top.frames.menuFrame.document;
		loc = menuFrameDocument.location;
		loc = loc + ' ';
//		if (loc.indexOf('NewsletterID') != -1) {
//			menuFrameDocument.location = 'envList.cfm';
//		}
		if (document.updLogin) { 
			focusOn(document.updLogin.username) 
		}
	}
}

function openImportWindow(mode) {
	window.top.menuFrame.aPopupWindow = window.open('','ImportPopup','width=400,height=400,scrollbars');
	while (!window.top.menuFrame.aPopupWindow) {
		//wait till popup opens
	}
	document.updIssue.Mode.value=mode;
	document.updIssue.target='ImportPopup';
	document.updIssue.action='databaseConfirm.cfm';
}

function confirmImport(displayAlert, mode, importID) {
	if (displayAlert) {
		alert('Users were NOT imported');
	}
	var f = window.opener.document.updIssue;
	f.Mode.value = mode;
	f.ImportID.value = importID;
	f.target = '';
	f.action='updDatabase.cfm';
	f.submit();
	document.location = 'databaseConfirmPleaseWait.cfm?Mode=' + mode;
}

function openCheckAllParametersWindow() {
	window.top.menuFrame.aPopupWindow = window.open('commandsCheckAllParameters.cfm','CheckAllParameters','width=400,height=500,scrollbars');
}

function openCheckMailContentWindow() {
	window.top.menuFrame.aPopupWindow = window.open('commandsCheckMail.cfm','CheckMail','width=600,height=500,scrollbars');
}

function openBodyPreviewWindow(bodyType, textAreaInputName) {
	window.top.menuFrame.aPopupWindow = window.open('contentsPreview.cfm?BodyType=' + bodyType + '&TextAreaInputName=' + textAreaInputName,'PreviewPopup','width=750,height=550,scrollbars');
}

function openUploadPopup() {
	window.top.menuFrame.aPopupWindow = window.open('contentsUpload.cfm','UploadPopup','width=650,height=550,scrollbars');
}

function openProgressBarPopup(importID, InsertUploadedUsersListIn, UserlevelYouAreUploading, UpdateIfMatch, SourceName) {
	window.opener.top.menuFrame.anotherPopupWindow = window.open('databaseConfirmProgressBar.cfm?Reset=1&ImportID=' + importID + '&InsertUploadedUsersListIn=' + InsertUploadedUsersListIn + '&UserlevelYouAreUploading=' + UserlevelYouAreUploading + '&UpdateIfMatch=' + UpdateIfMatch + '&SourceName=' + SourceName,'ProgressBarPopup','width=400,height=400,scrollbars');
}

function openDatabaseDeletionPopup(userLevel) {
	window.top.menuFrame.aPopupWindow = window.open('databaseDeletion.cfm?UserLevel=' + userLevel,'DatabaseDeletionPopup','width=400,height=400,scrollbars');
}

function cleanForm(f) {
	for (i = 0; i < f.elements.length; i++) {
		var type = '' + f.elements[i].type;
		if (type == 'text') {
			f.elements[i].value = '';
		}
		if (type.indexOf('select') > -1) {
			f.elements[i].selectedIndex = 0;
		}
	}
}

function confirmUserDeletion(f,passid,messagestatus) {
	var confirmed = false;
	confirmed = confirm('Are you sure you want to delete this user?');
	if (messagestatus > 0) {
		confirmed = confirm('You have sent an email to this user!\nAre REALLY sure you want to delete its activity history from the database?');
	}
	if (confirmed) {
		f.Mode.value = 'DeleteUser';
		f.PassIDToDelete.value = passid;
		f.submit();
	}
	return false;
}

function openStatsSummaryPopup(statsSummaryType,year) {
	if (confirm('This operation requires much time\nAre you sure you want to continue?')) {
		window.top.menuFrame.aPopupWindow = window.open('statsSummaryPopup.cfm?year=' + year + '&errorType=' + statsSummaryType,'StatsSummaryPopup','width=400,height=400,scrollbars');
	}
}

function confirmBusinessUnitDeletion(f,buid) {
	if (confirm('Are you sure you want to delete this Business Unit?')) {
		f.action.value = 'delBusinessUnit';
		f.BUID.value = buid;
		f.submit();
	}
	return false;
}

function confirmRuleDeletion(f,RuleID) {
	if (confirm('Are you sure you want to delete this Rule?')) {
		f.action.value = 'delRule';
		f.RuleID.value = RuleID;
		f.submit();
	}
	return false;
}

function confirmGroupDeletion(f,GroupID) {
	if (confirm('Are you sure you want to delete this Group?')) {
		f.action.value = 'delGroup';
		f.GroupID.value = GroupID;
		f.submit();
	}
	return false;
}

function confirmAuthUserDeletion(f,UserID) {
	if (confirm('Are you sure you want to delete this User?')) {
		f.action.value = 'delUser';
		f.EditUserID.value = UserID;
		f.submit();
	}
	return false;
}

function confirmDatabaseDeletion(f) {
	if (confirm('Are you really sure you want to delete the whole userlevel ' + f.DeleteUsersDatabaseUserLevel.value + ' from this issue database??')) {
		openDatabaseDeletionPopup(f.DeleteUsersDatabaseUserLevel.value);
	}
	return false;
}

function confirmCustomColumnDeletion(f,ColumnName) {
	if (confirm('Are you sure you want to delete this Custom Column?\nThis operation CANNOT BE UNDONE!')) {
		f.action.value = 'delCustomData';
		f.EditColumn.value = ColumnName;
		f.submit();
	}
	return false;
}

function pause(numberMillis) {
    var now = new Date();
    var exitTime = now.getTime() + numberMillis;
    while (true) {
        now = new Date();
        if (now.getTime() > exitTime)
            return;
    }
}

function checkAllAuthChildElements(f,parentElementID) {
	var elementIndex = -1;
	var i = 0;
	var operation = false;
	
	for (i = 0; i < f.elements.length && elementIndex == -1; i++) {
		if (f.elements[i].name == parentElementID) {
			elementIndex = i;
			operation = f.elements[i].checked;
		}
	}
	for (i = elementIndex + 1; i < f.elements.length && f.elements[i].name.indexOf('BoxElementID_') == -1; i++) {
		if (f.elements[i].name.indexOf('FieldElementID_') != -1) {
			f.elements[i].checked = operation;
		}
	}
}

function openHelp(helpId) {
	window.top.menuFrame.helpPopupWindow = window.open('help.cfm?helpId=' + helpId,'HelpPopup','width=400,height=400,scrollbars');
}

function lightsUp(value, origClassName, elementID) {
	if (value != '') {
		document.getElementById(elementID).className = 'clintcolorlight';
	} else {
		document.getElementById(elementID).className = origClassName;
	}
}

function arrayContains(arr, value) {
	var result = false;
	var i;
	for (i = 0; i < arr.length; i++) {
		if (arr[i].toLowerCase() == value.toLowerCase()) {
			result = true;
		}
	}
	return result;
}

function checkSelection(f) {
	var sheets = new Array();
	var errorMessage = '';
	var sheetCounter = -1;
	var columnCounter = -1;

	for (i = 0; i < f.elements.length && errorMessage == ''; i++) {
		if (f.elements[i].name.indexOf('Sheet_') != -1) {
			sheetCounter++;
			sheets[sheetCounter] = new Array();
			columnCounter = -1;
		} else if (f.elements[i].name.indexOf('Map_') != -1) {
			if (f.elements[i].value != '') {
				if (!arrayContains(sheets[sheetCounter], f.elements[i].value)) {
					columnCounter++;
					sheets[sheetCounter][columnCounter] = f.elements[i].value;
				} else {
					errorMessage = 'You mapped column ' + f.elements[i].value + ' more than once';
				}
			}
		}
	}
	
	for (i = 0; i < sheets.length && errorMessage == ''; i++) {
		if (!arrayContains(sheets[i], 'email')) {
			errorMessage = 'You forgot to map column Email in at least ONE sheet';
		}
	}
	
	if (errorMessage != '') {
		alert(errorMessage);
		return false;
	} else {
		return true;
	}
}