/**
 * @author bplamondon
 */
var increment = 0;
var divNum = 0;

function addOrUpdateDivs() {
	var buttonValue = document.getElementById('prevWorkButton').value;
	
	var valid = validatePreviousWork();
	if (valid) {
		if (buttonValue == 'Add Position') {
			createPreviousWorkDiv();	
		}
		else if (buttonValue == 'Update Position'){
			updatePreviousWorkDiv(divNum);	
		}
	} 
}

function createPreviousWorkDiv() {
	increment += 1;
	
	// Get the div containing the code you want to add.
	var startingPoint = document.getElementById('previousWork');
	var previousWorkDiv = document.createElement('span');
	previousWorkDiv.id = "previousWorkDiv" + increment;
	previousWorkDiv.style.display = 'none';
	
	// Add the paragraph container.
	var paragraph = document.createElement('p');
	paragraph.id = "prevWorkPara" + increment;
	paragraph.style.display = 'none';
    // IE hack - don't delete.
	paragraph.innerHTML = paragraph.innerHTML;
	
	// Get the values required from the input text fields.
	var employer = document.getElementById('employer').value;
	var jobTitle = document.getElementById('jobTitle').value;
	var responsibilities = document.getElementById('responsibilities').value;
	var startDate = document.getElementById('startDate').value;
	var endDate = document.getElementById('endDate').value;
	var jobCity = document.getElementById('jobCity').value;
	var jobProvince = document.getElementById('jobProvince');
	var jobProvIndex = jobProvince.selectedIndex;
	var jobProvText = jobProvince.options[jobProvIndex].text;
	var contactName = document.getElementById('contactName').value;
	var contactPhone = document.getElementById('contactPhone').value;
	var reasonForLeaving = document.getElementById('reasonForLeaving').value;
		
	// To make sure the input is inserted in the right spot by endDate.
	var divNumLastLessThan = dateCompareForInsert(endDate);
	
	// Attach the new div.	
	if (divNumLastLessThan!=null) {
		startingPoint.insertBefore(paragraph, document.getElementById('prevWorkPara' + divNumLastLessThan));
	} else {
		startingPoint.appendChild(paragraph);
	}	
	
	// Add links and text formating
	paragraph.appendChild(document.createTextNode(' ('));
	paragraph.innerHTML = paragraph.innerHTML + '<a href="#prevWorkAnchor" onclick="deletePreviousWorkDiv(\'' + paragraph.id + '\');">delete</a>';
	paragraph.appendChild(document.createTextNode(', '));
	paragraph.innerHTML = paragraph.innerHTML + '<a href="#prevWorkAnchor" onclick="modifyPreviousWorkDiv(\'' + paragraph.id + '\');">modify</a>';
	paragraph.appendChild(document.createTextNode(')'));
	paragraph.appendChild(document.createElement('br'));
    
    // Add a input for employer and the employer data to that input.	
	var employerInput = document.createElement('input')
	employerInput.id = 'employerInput' + increment;
	employerInput.name = 'employerInput' + increment;
	employerInput.type = 'text';
	employerInput.setAttribute('value', employer);
	employerInput.readonly = true;
	employerInput.size = employer.length;
	employerInput.className = 'prevWorkInputs';
	paragraph.appendChild(employerInput);
	
	// Add a input for job title and the data to that input.
	var jobTitleInput = document.createElement('input')
	jobTitleInput.id = 'jobTitleInput' + increment;
	jobTitleInput.name = 'jobTitleInput' + increment;
	jobTitleInput.type = 'text';
	jobTitleInput.setAttribute('value', jobTitle);
	jobTitleInput.readonly = true;
	jobTitleInput.size = jobTitle.length;
	jobTitleInput.className = 'prevWorkInputs';
	paragraph.appendChild(jobTitleInput);
	
	paragraph.appendChild(document.createElement('br')); // Text formatting
	
	//Add a input for responsibilities and the data to that input.
	var responsibilitiesInput = document.createElement('textarea')
	responsibilitiesInput.id = 'responsibilitiesInput' + increment;	
	responsibilitiesInput.name = 'responsibilitiesInput' + increment;
	responsibilitiesInput.cols = '61';

	// figure out how many repeats of 60 there are and insert \r\n after each iteration; plus one for padding
	var tmp = [];
	var lineCount = 1;

	for (var j = 0, i = 0, imax = responsibilities.length; i < imax; ++i, j++) {
		tmp.push(responsibilities.charAt(i));

		if (j > 0 && (j % (parseInt(responsibilitiesInput.cols) - 3)) == 0) {
			tmp.push( "\r\n" );
			lineCount++;
			j = 0;
		}

		if (responsibilities.charAt(i) == '\r' || responsibilities.charAt(i) == '\n')
		{
			if (responsibilities.charAt(i) == '\r' && responsibilities.charAt(i+1) == '\n') {
				i++
			};

			lineCount++;
			j = 0;
		}
	}
	
	responsibilitiesInput.rows = '' + (lineCount != 0 ? lineCount : '3');
	responsibilitiesInput.value = tmp.join(''); //innerHTML = tmp.join('');

	responsibilitiesInput.readonly = true;
	responsibilitiesInput.className = 'prevWorkInputs';

	paragraph.appendChild(responsibilitiesInput);
	
	paragraph.appendChild(document.createElement('br')); // Text formatting
	
	//Add a input for start date and the data to that input.
	var startDateInput = document.createElement('input')
	startDateInput.id = 'startDateInput' + increment;	
	startDateInput.name = 'startDateInput' + increment;
//	startDateObject = new Date(Date.parse(startDate));
//	startDateText = startDateObject.formatDate('F j, Y');
	startDateInput.type = 'text';
	startDateInput.setAttribute('value', startDate);
	startDateInput.readonly = true;
	startDateInput.size = startDate.length;
	startDateInput.className = 'prevWorkInputs';
	paragraph.appendChild(startDateInput);
	
	paragraph.appendChild(document.createTextNode(' to ')); // Text formatting
	
	//Add a input for end date and the data to that input.
	var endDateInput = document.createElement('input')
	endDateInput.id = 'endDateInput' + increment;
	if (document.getElementById('toPresent').checked) {
		endDate = "Present";
	}
	endDateInput.name = 'endDateInput' + increment;
	endDateInput.type = 'text';
	endDateInput.setAttribute('value', endDate);
	endDateInput.readonly = true;
	endDateInput.size = endDate.length;
	endDateInput.className = 'prevWorkInputs';
	paragraph.appendChild(endDateInput);
	
	var somediv = document.createElement( 'small' );
		somediv.innerHTML = "(mm/dd/yyyy)";
	paragraph.appendChild(somediv);
	
	paragraph.appendChild(document.createElement('br')); // Text formatting
	
	//Add a input for the city of the position and the data to that input.
	var jobCityInput = document.createElement('input')
	jobCityInput.id = 'jobCityInput' + increment;
	jobCityInput.name = 'jobCityInput' + increment;
	jobCityInput.type = 'text';
	jobCityInput.setAttribute('value', jobCity);
	jobCityInput.readonly = true;
	jobCityInput.size = jobCity.length;
	jobCityInput.className = 'prevWorkInputs';
	paragraph.appendChild(jobCityInput);
	
	paragraph.appendChild(document.createTextNode(', ')); // Text formatting
	
	//Add a input for the province of the position and the data to that input.
	var jobProvTextInput = document.createElement('input')
	jobProvTextInput.id = 'jobProvinceInput' + increment;
	jobProvTextInput.name = 'jobProvinceInput' + increment;
	jobProvTextInput.type = 'text';
	jobProvTextInput.setAttribute('value', jobProvText);
	jobProvTextInput.readonly = true;
	jobProvTextInput.size = jobProvText.length;
	jobProvTextInput.className = 'prevWorkInputs';
	paragraph.appendChild(jobProvTextInput);
	
	paragraph.appendChild(document.createElement('br')); // Text formatting
	
	//Add a input for contact name and the data to that input.
	if (contactName != "") {
		var contactNameInput = document.createElement('input')
		contactNameInput.id = 'contactNameInput' + increment;
		contactNameInput.name = 'contactNameInput' + increment;
		contactNameInput.type = 'text';
		contactNameInput.setAttribute('value', contactName);
		contactNameInput.readonly = true;
		contactNameInput.size = contactName.length;
		contactNameInput.className = 'prevWorkInputs';
		paragraph.appendChild(contactNameInput);
		paragraph.appendChild(document.createTextNode(' ')); // Text formatting
	}	
	    
	//Add a input for contact phone and the data to that input.
	if (contactPhone != "") {        
		var contactPhoneInput = document.createElement('input');        
		contactPhoneInput.id = 'contactPhoneInput' + increment;        
		contactPhoneInput.name = 'contactPhoneInput' + increment;        
		contactPhoneInput.type = 'text';        
		contactPhoneInput.setAttribute('value', contactPhone);        
		contactPhoneInput.readonly = true;        
		contactPhoneInput.size = contactPhone.length;        
		contactPhoneInput.className = 'prevWorkInputs';        
		//contactPhoneInput.appendChild(document.createTextNode(contactPhone));
        contactPhoneInput.setAttribute('value', contactPhone);        
		paragraph.appendChild(contactPhoneInput);       
	}
		
	//Add a input for reason for leaving and the data to that input.
	if (reasonForLeaving != "") {
        paragraph.appendChild(document.createElement('br')); // Text formatting
		var reasonForLeavingInput = document.createElement('input')
		reasonForLeavingInput.id = 'reasonForLeavingInput' + increment;
		reasonForLeavingInput.name = 'reasonForLeavingInput' + increment;
		reasonForLeavingInput.type = 'text';
		reasonForLeavingInput.setAttribute('value', reasonForLeaving);
		reasonForLeavingInput.readonly = true;
		reasonForLeavingInput.size = reasonForLeaving.length;
		reasonForLeavingInput.className = 'prevWorkInputs';
		//reasonForLeavingInput.appendChild(document.createTextNode(reasonForLeaving));
        reasonForLeavingInput.setAttribute('value', reasonForLeaving)
		paragraph.appendChild(reasonForLeavingInput);
	}
		
		
	showText(paragraph);
	var counter = document.getElementById('counter');
	counter.value = increment;
		
	// Reset the input buttons.	
	clearInputs();
}

function clearInputs() {
	document.getElementById('employer').value = "";
	document.getElementById('jobTitle').value = "";
	document.getElementById('responsibilities').value = "";
	document.getElementById('startDate').value = "";
	document.getElementById('endDate').value = "";
	document.getElementById('jobCity').value = "";
	document.getElementById('jobProvince').selectedIndex = "0";
	document.getElementById('contactName').value = "";
	document.getElementById('contactPhone').value = "";
    document.getElementById('reasonForLeaving').value = "";
	
	var button = document.getElementById('endDateButtonRB');
	var toPresentCheckbox = document.getElementById('toPresent');
	toPresentCheckbox.checked = false;
	button.style.display = "inline";
}

function updatePreviousWorkDiv(divNumber) {

	var button = document.getElementById('prevWorkButton');
	button.value = 'Add Position';
	
	deletePreviousWorkDiv('prevWorkPara' + divNumber);
	createPreviousWorkDiv();	
	
}

function validatePreviousWork() {
	var isValid = true;
	
	// Make sure all fields aren't empty
	if (document.getElementById('employer').value == "") {
		isValid = false;
		document.getElementById('nullEmployerError').style.display = "block";
	} else {
		document.getElementById('nullEmployerError').style.display = "none";
	}
	
	if (document.getElementById('jobTitle').value == "") {
		isValid = false;
		document.getElementById('nullJobTitleError').style.display = "block";
	} else {
		document.getElementById('nullJobTitleError').style.display = "none";
	}
	
	if (document.getElementById('responsibilities').value == "") {
		isValid = false;
		document.getElementById('nullResponsibilitiesError').style.display = "block";
	} else {
		document.getElementById('nullResponsibilitiesError').style.display = "none";
	}
	
	if (document.getElementById('jobCity').value == "") {
		isValid = false;
		document.getElementById('nullJobCityError').style.display = "block";
	} else {
		document.getElementById('nullJobCityError').style.display = "none";
	}
	
	if (document.getElementById('startDate').value == "") {
		isValid = false;
		document.getElementById('nullStartDateError').style.display = "block";
	} else {
		document.getElementById('nullStartDateError').style.display = "none";
	}
	
	if (document.getElementById('endDate').value == "" && !document.getElementById('toPresent').checked) {
		isValid = false;
		document.getElementById('nullEndDateError').style.display = "block";
	} else {
		document.getElementById('nullEndDateError').style.display = "none";
	}
	
	// Make sure date formats are accurate
	if (!validateDate(document.getElementById('startDate'))) {
		isValid = false;
	}
	if (!document.getElementById('toPresent').checked) {
		if (!validateDate(document.getElementById('endDate'))) {
			isValid = false;
		}
	}
	
	// Make sure start date is before end date.
	var checkbox = document.getElementById('toPresent');
	if (!checkbox.checked) {
		if (Date.parse(document.getElementById('startDate').value) > Date.parse(document.getElementById('endDate').value)) {
			isValid = false;
			document.getElementById('startDateGTEndDate').style.display = "block";
		} else {
			document.getElementById('startDateGTEndDate').style.display = "none";
		}
	} else {
		var d = new Date();
		if (Date.parse(document.getElementById('startDate').value) > d.getTime()) {
			isValid = false;
			document.getElementById('startDateGTEndDate').style.display = "block";
		} else {
			document.getElementById('startDateGTEndDate').style.display = "none";
		}
	}
	
	// Make sure phone format is correct
	if (document.getElementById('contactPhone').value != "") {
		if (!validatePhone(document.getElementById('contactPhone'))) {
			isValid = false;
			document.getElementById('phoneError').style.display = "block";
		} else {
			document.getElementById('phoneError').style.display = "none";
		}
	}
	
	return isValid;
}

function validateDate(input) {
	var validformat = /^\d{2}\/\d{2}\/\d{4}$/; 
	var returnval = false;
	 
	if (validformat.test(input.value)) { //Detailed check for valid date ranges
		var monthfield = input.value.split("/")[0];
		var dayfield = input.value.split("/")[1];
		var yearfield = input.value.split("/")[2];
		var dayobj = new Date(yearfield, monthfield-1, dayfield);
		if ((dayobj.getMonth()+1 != monthfield) || (dayobj.getDate() != dayfield) || (dayobj.getFullYear() != yearfield))
			alert("Invalid Day, Month, or Year range detected. Please correct and submit again.")
		else
			returnval = true;
	}
	if (returnval == false) 
		input.select();
		
	return returnval
}

function validatePhone(input) {
	var validformat = /^[1-9]\d{2}\-\d{3}\-\d{4}$/;
	var returnVal = true;
	
	if (!validformat.test(input.value)) {
		returnVal = false;
	}
	
	return returnVal;
}

function deletePreviousWorkDiv(divId) {
	var button = document.getElementById('prevWorkButton');
	// if button is not update, delete.
	if (button.value == 'Add Position') {
		var previousWorkDiv = document.getElementById('previousWork');
		var previousWorkDivDel	= document.getElementById(divId);
		previousWorkDiv.removeChild(previousWorkDivDel);
	} else {
		alert('You can not delete a record while updating a record.  Please finish updating the record.');
	}
}

function modifyPreviousWorkDiv(divId) {	
	// Get the increment number used for this div.
	var previousWorkDiv	= document.getElementById(divId);
	var prevString = "PrevWorkPara";
	var divNumber = previousWorkDiv.id.substr(prevString.length); 
	divNum = divNumber;
	
	var startDateValue = document.getElementById('startDateInput' + divNum).value;
	var endDateValue = document.getElementById('endDateInput' + divNum).value;
//	var startDate = new Date();
//	startDate.setTime(Date.parse(startDateValue));

	// Add values back for editing.
	document.getElementById('employer').value = document.getElementById('employerInput' + divNum).value;
	document.getElementById('jobTitle').value = document.getElementById('jobTitleInput' + divNum).value;
	document.getElementById('responsibilities').value = document.getElementById('responsibilitiesInput' + divNum).value;
	document.getElementById('startDate').value = startDateValue;
	if (endDateValue == "" || endDateValue == "Present") {	
		document.getElementById('endDate').value = "";
		var button = document.getElementById('endDateButtonRB');
		var checkbox = document.getElementById('toPresent');
		checkbox.checked = true;
		button.style.display = "none";
		
	} else {
//		var endDate = new Date();
//		endDate.setTime(Date.parse(endDateValue));	
		document.getElementById('endDate').value = endDateValue;
	}
	document.getElementById('jobCity').value = document.getElementById('jobCityInput' + divNum).value;
	if (document.getElementById('contactNameInput' + divNum)) {
		document.getElementById('contactName').value = document.getElementById('contactNameInput' + divNum).value;
	}
	if (document.getElementById('contactPhoneInput' + divNum)) {
		document.getElementById('contactPhone').value = document.getElementById('contactPhoneInput' + divNum).value;
	}
	
	var button = document.getElementById('prevWorkButton');
	button.value = 'Update Position';
}

function dateCompareForInsert(endDate) {
	var highestLowerValue = null;
	var highestLowerValueId = null;
	// Loop over divs
	for (i=1; i<increment; i++) {
		// Skip any deleted divs.
		if (document.getElementById('endDateInput' + i) != null) {
			// Get date from the div to compare to.
			var endDateCompare = document.getElementById('endDateInput' + i).value;
			if (endDateCompare == 'Present' || '') {
				var today = new Date();
				endDateCompare = today.getTime();
			} else {
				endDateCompare = Date.parse(endDateCompare)
			}
			if (Date.parse(endDate) <  endDateCompare) {
				// If there are no divs and its lower then set the values.
				if (highestLowerValue == null) {
					highestLowerValue = endDateCompare;
					highestLowerValueId = i;
				} else { // Compare to current store values and set if needed.
					if(Date.parse(endDateCompare) < Date.parse(highestLowerValue)) {
						highestLowerValue = endDateCompare;
						highestLowerValueId = i;
					}
				}
			}
		}
	}
	
	return highestLowerValueId;  // return the value of the lowest date above the one being added.
}

function toPresentChecked() {
	var button = document.getElementById('endDateButtonRB');
	var toPresentCheckbox = document.getElementById('toPresent');
	if (toPresentCheckbox.checked) {
		button.style.display = "none";
	} else {
		button.style.display = "inline";
	}
}
