//################################################################################
//#			NAME: 		functionLoader
//#			CALLED BY:	Page Layout Manager (Post Form) [WebGUI Template]
//#			PURPOSE:	A single function that launches all necessary functions
//#						to run the form. Keeps the form page a little cleaner.
//################################################################################
function functionLoader(titleVal) {
	parseFields(1);
	parseFields(2);
	parseFields(3);
	parseFields(4);
	parseFields(5);
	populateMe(titleVal);
	attachValidation();
	validateForm();
	backgroundImages(document.getElementById('themeName').value,'miniLayout',320);
}


//################################################################################
//#			NAME: 		updateFields
//#			CALLED BY:	functionLoader, validateForm
//#			PURPOSE:	Obtains the values of a given layout, top, left and width
//#						and concatenates them into a single value, and assigns 
//#						them to a user defined variable. Secondly, it feeds these
//#						values to the miniLayout function.
//################################################################################
function updateFields(positionVal) {
	var topVal = document.getElementById('top' + positionVal).value;
	var leftVal = document.getElementById('left' + positionVal).value;
	var widthVal = document.getElementById('width' + positionVal).value;	
	
	var combineEm = topVal + "," + leftVal + "," + widthVal;
	
	document.getElementById("userDefined" + positionVal + "_formId").value = combineEm;
	miniLayout(positionVal,topVal,leftVal,widthVal);
}


//################################################################################
//#			NAME: 		parseFields
//#			CALLED BY:	functionLoader
//#			PURPOSE:	Grabs the concatenated top, left and width values and
//#						splits them up again to populate the input boxes when the
//#						page is loaded.
//################################################################################
function parseFields(userField) {
	var valArray = document.getElementById("userDefined" + userField + "_value").value.split(",");
	var elementArray = new Array(document.getElementById('top' + userField),document.getElementById('left' + userField),document.getElementById('width' + userField));
	for(i=0;i<valArray.length;i++) {
		elementArray[i].value = valArray[i];	
	}
	
}


//################################################################################
//#			NAME: 		populateMe
//#			CALLED BY: 	functionLoader
//#			PURPOSE:	Two WebGUI navigation assets create two javascript arrays
//#						that contain all of the names of user created themes, and
//#						then the names of themes to not be displayed. The function
//#						takes the values from the arrays and uses them to populate
//#						a dropdown box
//################################################################################
function populateMe(noTitle) {
	var themeNames = new Array("Theme ManagerLayout","exampleLayout","marsLayout","patrimonyLayout","meet_obama_spLayout","geography_spLayout","women_courage_spLayout","continual_promise09_spLayout","climate_change_spLayout","hemisphere_spLayout","baseballLayout","global_financial_spLayout","disease_surveillance_spLayout","destination_education_spLayout","hispanic_arts_spLayout","proteccion_oceanosLayout","Baseball_spLayout","usconstitutionLayout","declaracionuniversalLayout","declaracionuniversalspLayout","h1n1Layout","bicicletasparaelmundoLayout","thecabinet_spLayout","americanindiansbusinessspLayout");		//Supplies the populated themeNames array
	var usedLayouts = new Array("obamaLayout","identityLayout","patrimonyLayout","meet_obama_spLayout","geography_spLayout","women_courage_spLayout","continual_promise09_spLayout","climate_change_spLayout","hemisphere_spLayout","baseballLayout","global_financial_spLayout","disease_surveillance_spLayout","destination_education_spLayout","hispanic_arts_spLayout","proteccion_oceanosLayout","Baseball_spLayout","declaracionuniversalLayout","usconstitutionLayout","declaracionuniversalspLayout","h1n1Layout","bicicletasparaelmundoLayout","thecabinet_spLayout","americanindiansbusinessspLayout");		//Supplies the populated usedLayouts array
	var themeName = document.getElementById('themeName').options;
	
	if(noTitle != 'Thread') {
		themeName[themeName.length] = new Option(noTitle, noTitle);
		themeName[themeName.length] = new Option("", "");
	}
	
	for (i=1;i<themeNames.length; i++) {
		if(noTitle != themeNames[i]) {
			for(x=0;x<usedLayouts.length;x++) {
				if(usedLayouts[x] == themeNames[i]) {
					repeatedLayout = 1;
					break;				
				}
				else
					repeatedLayout = 0;
			}
			if(!repeatedLayout) 
				themeName[themeName.length] = new Option(themeNames[i],themeNames[i]);	
		}
	}
}


//################################################################################
//#			NAME: 		miniLayout
//#			CALLED BY:	updateFields
//#			PURPOSE:	Positions boxes on a mock layout that is 1/3rd the scale
//#						of an actual america.gov layout
//################################################################################
function miniLayout(miniVal,topVal,leftVal,widthVal) {
	var miniVal = document.getElementById("mini" + miniVal);
	if((topVal != '') && (leftVal != '') && (widthVal != '')) {
		miniVal.style.top = Math.round(topVal / 3) + "px";
		miniVal.style.left = Math.round(leftVal / 3) + "px";
		miniVal.style.width = Math.round(widthVal / 3) + "px";
		miniVal.style.display = "block";
	}
	else {
		miniVal.style.top = "0px";
		miniVal.style.left = "0px";
		miniVal.style.width = "0px";
		miniVal.style.display = "none";
	}
}


//################################################################################
//#			NAME: 		validateForm
//#			CALLED BY: 	attachValidation, functionLoader
//#			PURPOSE:	Primarily this is to validate that each layout has all 3
//#						necessary values, left, top and width when the submit
//#						button is pressed. Error notifications are displayed in 
//#						red. This is also called to initially place the boxes
//#						in the mini layout.
//################################################################################
function validateForm() {
	var numOf = 5;
	var valid = true;
	var errorVal = document.getElementById('errorConsole');
	errorVal.innerHTML = '';
	
	for(i=1;i<=numOf;i++) {
		var topVal = document.getElementById('top' + i).value;
		var leftVal = document.getElementById('left' + i).value;
		var widthVal = document.getElementById('width' + i).value;
		var labelVal = document.getElementById('label' + i);
		
		if((topVal == '') || (leftVal == '') || (widthVal == '')) {
			if((topVal == '') && (leftVal == '') && (widthVal == '')) {
				//No values were entered, so don't do anything
			}
			else
			{	
				errorVal.style.color = 'red';
				errorVal.innerHTML = errorVal.innerHTML + "<div style='padding:5px 15px'>You must enter left, top and width values for layout " + i + "</div>"
				labelVal.style.color = 'red';
				valid = false;
			}
		}
		else {
			labelVal.style.color = 'black';
			updateFields(i);
			continue;
		}
		
	}
	//alert(valid);
	return valid;
}
	

//################################################################################
//#			NAME: 		attachValidation
//#			CALLED BY: 	functionLoader
//#			PURPOSE:	Attachs an onsubmit event to fire off the validateForm
//#						function
//################################################################################
function attachValidation() {
	var attachForm = document.getElementById('layoutManagerPost');	
	attachForm = attachForm.getElementsByTagName('form');
	attachForm[0].onsubmit = function () { return validateForm(); };
}


//################################################################################
//#			NAME: 		backgroundImages
//#			CALLED BY: 	Page Layout Manager (Thread), functionLoader()
//#			PURPOSE:	Places the correct background image for the layout. This 
//#						function is AssetProxied into the updatefields.js Snippet
//#						because it is actually a Collaboratoin System template,
//#						so its MIME type isn't text/javascript
//################################################################################
function backgroundImages(themeName,elementId,bckImgWidth) {
	//var themeName = themeName;
	var counter = 23;
	var themeArray = new Array(23);
	var imgHeight;
			
	for(i=0;i<counter;i++)
		themeArray[i] = new Array(2);
			
	
	themeArray[1-1][0] = "americanindiansbusinessspLayout";			//Theme Name	
	themeArray[1-1][1] = "/esp/uploads/mq/NG/mqNG5kCsIpY7jqvUWMZ4TA/AmericanIndians2.jpg";		//Background Image
	
	themeArray[2-1][0] = "thecabinet_spLayout";			//Theme Name	
	themeArray[2-1][1] = "/esp/uploads/G3/yD/G3yDfEwtrOQm2CGilUueQg/TheCabinet2_sp.jpg";		//Background Image
	
	themeArray[3-1][0] = "bicicletasparaelmundoLayout";			//Theme Name	
	themeArray[3-1][1] = "/esp/uploads/0S/fd/0Sfdvw1umQNYee58tS1sZw/BikesfortheWorld2.jpg";		//Background Image
	
	themeArray[4-1][0] = "h1n1Layout";			//Theme Name	
	themeArray[4-1][1] = "/esp/uploads/Cg/jF/CgjF1_UVdJq7Udc9kOvAPA/swineflu-bkgd1.jpg";		//Background Image
	
	themeArray[5-1][0] = "usconstitutionLayout";			//Theme Name	
	themeArray[5-1][1] = "/esp/uploads/aw/SO/awSOKeCSDd9ERHU0sqo7WQ/Constitution3_sp.jpg";		//Background Image
	
	themeArray[6-1][0] = "declaracionuniversalspLayout";			//Theme Name	
	themeArray[6-1][1] = "/esp/uploads/5L/8Q/5L8QP56Pmnrr_OQ3aCeakQ/UN_declaration2-.jpg";		//Background Image
	
	themeArray[7-1][0] = "declaracionuniversalLayout";			//Theme Name	
	themeArray[7-1][1] = "/esp/uploads/x7/B-/x7B-19fNLpX3i_nn5ipPwQ/UN_declaration_558x234-.jpg";		//Background Image
	
	themeArray[8-1][0] = "global_financial_spLayout";			//Theme Name	
	themeArray[8-1][1] = "/esp/uploads/za/mH/zamHqMFtGalIGDUPJC8I-Q/GlobalFinance_SP_bkg.jpg";		//Background Image
	
	themeArray[9-1][0] = "hemisphere_spLayout";			//Theme Name	
	themeArray[9-1][1] = "/esp/uploads/1b/S-/1bS-pcHaigKTfd5h5wIl3A/Seguridad_SP.jpg";		//Background Image
	
	themeArray[10-1][0] = "Baseball_spLayout";			//Theme Name	
	themeArray[10-1][1] = "/esp/uploads/ec/ga/ecgakluNBxl85m8H0U5K5A/Baseball_bkg_SP_slice.jpg";		//Background Image
	
	themeArray[11-1][0] = "proteccion_oceanosLayout";			//Theme Name	
	themeArray[11-1][1] = "/esp/uploads/jb/Zh/jbZhhcn4fRzQ7GV-pd5JrA/ocean-protecting2.jpg";		//Background Image
	
	themeArray[12-1][0] = "baseballLayout";			//Theme Name	
	themeArray[12-1][1] = "/esp/uploads/sL/WH/sLWHw6WiMjIIh5utfSvloA/Baseball_bkg_SP_slice.jpg";		//Background Image
	
	themeArray[13-1][0] = "geography_spLayout";			//Theme Name	
	themeArray[13-1][1] = "/esp/uploads/gB/ME/gBMERJlBxYAy5K3viijsfA/Geography_SP_Bkg.jpg";		//Background Image
	
	themeArray[14-1][0] = "climate_change_spLayout";			//Theme Name	
	themeArray[14-1][1] = "/esp/uploads/dW/gN/dWgNhLExyrzwGV9LVkQJEg/SP_climate_bkgd.jpg";		//Background Image
	
	themeArray[15-1][0] = "hispanic_arts_spLayout";			//Theme Name	
	themeArray[15-1][1] = "/esp/uploads/t8/pm/t8pml6Zm_ZrYW863n7detw/Arts_layout_SP.jpg";		//Background Image
	
	themeArray[16-1][0] = "destination_education_spLayout";			//Theme Name	
	themeArray[16-1][1] = "/esp/uploads/VP/aB/VPaBqdDyyzDxk2jmxR_67Q/Spanish-EducationExchange.jpg";		//Background Image
	
	themeArray[17-1][0] = "disease_surveillance_spLayout";			//Theme Name	
	themeArray[17-1][1] = "/esp/uploads/PH/jJ/PHjJQuVMTjXVBXDnL6Fzng/campaign-disease_bkgd.jpg";		//Background Image
	
	themeArray[18-1][0] = "women_courage_spLayout";			//Theme Name	
	themeArray[18-1][1] = "/esp/uploads/fV/fB/fVfBtYUoEHQaXHuuoEdZCQ/SP_women_courage_bkgd.jpg";		//Background Image
	
	themeArray[19-1][0] = "continual_promise09_spLayout";			//Theme Name	
	themeArray[19-1][1] = "/esp/uploads/vs/WV/vsWV-BlYbPJ2EgfodM6dAg/Spanish-Promesa2009-bkgd.jpg";		//Background Image
	
	themeArray[20-1][0] = "meet_obama_spLayout";			//Theme Name	
	themeArray[20-1][1] = "/esp/uploads/mk/MF/mkMFTvyVsYZ0UyRUm7_rvw/SP_obama_bkgd.jpg";		//Background Image
	
	themeArray[21-1][0] = "patrimonyLayout";			//Theme Name	
	themeArray[21-1][1] = "/esp/uploads/dT/yx/dTyx7DgWI4d0euBscyxxFA/Spanish-Patrimonio1-bkgd.jpg";		//Background Image
	
	themeArray[22-1][0] = "marsLayout";			//Theme Name	
	themeArray[22-1][1] = "/esp/uploads/29/Yt/29YtsO9z4fkV_WYmUw9rIw/campaign-mars-bkgd2.jpg";		//Background Image
	
	themeArray[23-1][0] = "exampleLayout";			//Theme Name	
	themeArray[23-1][1] = "/esp/uploads/yo/6-/yo6-g4tok1ePkgHRcjzdLw/25.png";		//Background Image
	
	
	
	for(i=0;i<counter;i++)		
		if(themeName == themeArray[i][0]) {			
			var bckImg = document.getElementById(elementId);
			var ifImage = bckImg.getElementsByTagName('img');
			if(ifImage.length > 0)
				bckImg.removeChild(ifImage[0])
			var newImg = document.createElement('img');
			newImg.setAttribute('src',themeArray[i][1]);
			newImg.setAttribute('style','z-index:0;position:relative;top:0px;left:0px;');
			newImg.setAttribute('width',bckImgWidth);
			//imgHeight = (bckImgWidth < 500) ? '33%' : '100%';	
			newImg.setAttribute('height','*');			
			bckImg.appendChild(newImg);
		}
}


//################################################################################
//#			NAME: 		expandParent
//#			CALLED BY: 	Page Layout Manager (Thread)
//#			PURPOSE:	Resizes the containing element to allow all of the
//#						absolutely positioned items to not overflow
//################################################################################
function expandParent(parentEl) {
	var parentEl = document.getElementById(parentEl);
	var childEl = parentEl.getElementsByTagName('div');  
	var childImg = parentEl.getElementsByTagName('img');
	var dynaCells = new Array();
	var counter = 1;
	var finalVal = 0;
	var isProduction = 0;
	
	for(i=0;i<childEl.length;i++) {
		if(childEl[i].id.indexOf('dyna') != -1) isProduction = 1;
		if(childEl[i].className.indexOf('Layout') != -1) parentEl = childEl[i];
	}
			
	
	if(isProduction) {
		counter = 0;
		for(i=0;i<childEl.length;i++) {
			dynaCells[counter] = childEl[i].offsetTop + childEl[i].offsetHeight;
			counter++
		}
		counter = 1;
		
		for(i=0;i<dynaCells.length;i++) {
			if(i==dynaCells.length-1)
				counter = 0;
			
			if(dynaCells[i] >= dynaCells[counter]) {
				if(dynaCells[i] > finalVal)
					finalVal = dynaCells[i]
				
				//alert(i + "- " + dynaCells[i] + " vs." + dynaCells[counter] + " = " + finalVal);
			}
		}	

	}
	else {
		for(i=0;i<childEl.length;i++) {
			if(i==childEl.length - 1)
				counter = 0;
	
			if(childEl[i].offsetTop + childEl[i].offsetHeight > childEl[counter].offsetTop + childEl[counter].offsetHeight)
				finalVal = childEl[i].offsetTop + childEl[i].offsetHeight;
				
			counter++;			
		}
	}


	if(!isProduction)
		for(i=0;i<childImg.length;i++) {
			if(i==childImg.length -1)
				counter = 0;
				
			if(childImg[i].offsetHeight > finalVal) {
				finalVal = childImg[i].offsetHeight;		
				
			}
		}

	parentEl.setAttribute("style", "min-height:" + (finalVal + 16) + "px;height:auto !important;height:" + (finalVal + 16) + "px");
	parentEl.style.height = finalVal + 16 + "px";
}


//################################################################################
//#			NAME: 		macroLayout
//#			CALLED BY: 	Page Layout Manager (Thread)
//#			PURPOSE:	Positions the layout squares based on the info provided
//#						via the Post Form
//################################################################################
function macroLayout(posValues,itemId) {
	var itemId = document.getElementById(itemId);
	if(posValues != '') {
		var posArray = posValues.split(",");
		itemId.style.top = posArray[0] + "px";
		itemId.style.left = posArray[1] + "px";
		itemId.style.width = posArray[2] + "px";
		itemId.style.display = "block";	
	}	
}


//################################################################################
//#			NAME: 		initializeDelete
//#			CALLED BY: 	Page Layout Manager (Thread)
//#			PURPOSE:	Takes the 'confirmDelete' box from the template, clones it
//#						removes the original and then attaches the clone to the 
//#						body of the document. This allows the box to be centered
//#						on the page no matter what layout is used. It also creates
//#						the dropshadow div.
//################################################################################
function intializeDelete() {
	var newDiv = document.createElement('div');
	var confirmDelete = document.getElementById('confirmDelete');
	var confirmClone = confirmDelete.cloneNode(true);
	
	newDiv.setAttribute('id','overlay');
	newDiv.setAttribute('style','display:none');		
	document.body.appendChild(newDiv);	
	
	confirmDelete.parentNode.removeChild(confirmDelete);
	document.body.appendChild(confirmClone);
}



//################################################################################
//#			NAME: 		confirmDelete
//#			CALLED BY: 	Page Layout Manager (Thread)
//#			PURPOSE:	Handles the appearance of the confirmDelete box and its
//#						dropshadow
//################################################################################
function confirmDelete(titleVal) {
	var confirmDelete = document.getElementById('confirmDelete');
	var deleteMessage = document.getElementById('deleteMessage');
	var overlayDiv = document.getElementById('overlay');
	deleteMessage.innerHTML = "Are you sure you wish to delete " + titleVal + "?";
	
	overlayDiv.style.display = "block";
	confirmDelete.style.display = "block";
	
	overlayDiv.style.width = confirmDelete.offsetWidth + "px";
	overlayDiv.style.height = confirmDelete.offsetHeight + "px";
			
	confirmDelete.style.left = ((document.body.clientWidth / 2) - (confirmDelete.offsetWidth / 2)) + "px";
	confirmDelete.style.top = ((document.body.clientHeight / 2) - confirmDelete.offsetHeight) + "px";
	overlayDiv.style.left = eval(x=confirmDelete.style.left.split('p')[0]) + 5 + "px";
	overlayDiv.style.top = eval(x=confirmDelete.style.top.split('p')[0]) + 5 + "px";

}


function addLayoutLink() {
	var usedLayouts = new Array("obamaLayout","identityLayout","patrimonyLayout","meet_obama_spLayout","geography_spLayout","women_courage_spLayout","continual_promise09_spLayout","climate_change_spLayout","hemisphere_spLayout","baseballLayout","global_financial_spLayout","disease_surveillance_spLayout","destination_education_spLayout","hispanic_arts_spLayout","proteccion_oceanosLayout","Baseball_spLayout","declaracionuniversalLayout","usconstitutionLayout","declaracionuniversalspLayout","h1n1Layout","bicicletasparaelmundoLayout","thecabinet_spLayout","americanindiansbusinessspLayout");		//Supplies the populated usedLayouts array
	var themeNames = new Array("Theme ManagerLayout","exampleLayout","marsLayout","patrimonyLayout","meet_obama_spLayout","geography_spLayout","women_courage_spLayout","continual_promise09_spLayout","climate_change_spLayout","hemisphere_spLayout","baseballLayout","global_financial_spLayout","disease_surveillance_spLayout","destination_education_spLayout","hispanic_arts_spLayout","proteccion_oceanosLayout","Baseball_spLayout","usconstitutionLayout","declaracionuniversalLayout","declaracionuniversalspLayout","h1n1Layout","bicicletasparaelmundoLayout","thecabinet_spLayout","americanindiansbusinessspLayout");		//Supplies the populated themeNames array
	
	var isUsed = 0;	
	
	for(i=1;i<themeNames.length;i++) {
		for(x=0;x<usedLayouts.length;x++)
			if(themeNames[i] == usedLayouts[x])	{	
				document.getElementById(usedLayouts[x] + 'Id').innerHTML = "<a href='/esp/page-layout-manager/page-layout-manager/" + usedLayouts[x].toLowerCase() +"?func=edit'  class='editLayout' target='_blank'>Edit Layout</a>";	
				isUsed = 1;
			}
		if(!isUsed)	
			document.getElementById(themeNames[i] + 'Id').innerHTML = "<a href='/esp/page-layout-manager/page-layout-manager.html?func=add;class=WebGUI::Asset::Post::Thread' class='addLayout'>Add a Layout</a>";
			
		isUsed = 0;			
	}	
}









