function highlightTableRow(row, turnOn, bgColor) {

	var numCells = row.cells.length;
	if(turnOn == false)
		bgColor = 'transparent';
	
	for(var i = 0; i < numCells; i++)
		var cell = row.cells[i].style.backgroundColor = bgColor;	

}

function IeSucksUrlDate() {
	return new Date();
}

// type 1 = new and type 2 = extending
function sendToggleFeature(contentId, contentType) {
	
	var params = 'action=togglefeatured&contentType=' + contentType + '&contentId=' + contentId + '&ieSucks=' + IeSucksUrlDate();
	
	
	new Ajax.Request('/rea/admin/ajaxaction', 
	{
		method: 'get',
		parameters: params,
		onSuccess: function(transport)
			{
				var responseXml = transport.responseXML;				
				
				// get base xml element - use to get the three values we need to process
				var xmlBase = responseXml.getElementsByTagName("activation")[0];
				var result = parseInt(xmlBase.getElementsByTagName("result")[0].firstChild.nodeValue);
				var newActiveStatus = parseInt(xmlBase.getElementsByTagName("newActiveStatus")[0].firstChild.nodeValue);					
				var featureImg, successMessage;
				
				if(result == 1) {
					
					var select = document.getElementById('select' + contentId);
					
					if(newActiveStatus == 1) {
						// NEW FEATURE
						featureImg = document.createElement('img');
						featureImg.src = "/images/template/bullet-feature.png";
						featureImg.alt = "Featured";
						featureImg.title = "Featured";
						featureImg.id = "featureIcon" + contentId;
						
						var iconCell = $('iconCell' + contentId);
						iconCell.appendChild(featureImg);
						
						successMessage = "Your content has been featured";
						
						select.options[3] = new Option("Remove Feature", 3);
					}
					else {
						var img = document.getElementById('featureIcon' + contentId);
						img.parentNode.removeChild(img);
						successMessage = "Your content has been unfeatured";
						select.options[3] = new Option("Feature", 3);
					}
					
					createSuccessPop(successMessage, null);
				}
				else {
					// error
					createErrorPop('An error has occurred. Please try again later', null);
				}
			}
	});
}


function sendToggleActive(contentId, contentType) {
	
	var params = 'action=toggleactive&contentType=' + contentType + '&contentId=' + contentId + '&ieSucks=' + IeSucksUrlDate();
	
	resultStatus = new Ajax.Request('/rea/admin/ajaxaction', 
	{
		method: 'get',
		parameters: params,
		onSuccess: function(transport)
			{
				var responseXml = transport.responseXML;
				
				// get base xml element - use to get the three values we need to process
				var xmlBase = responseXml.getElementsByTagName("activation")[0];
				var result = parseInt(xmlBase.getElementsByTagName("result")[0].firstChild.nodeValue);
				var newActiveStatus = parseInt(xmlBase.getElementsByTagName("newActiveStatus")[0].firstChild.nodeValue);					
									
				
				
				if(result == 1)	{
					var newText, altText, imgSrc;
					var successMessage = "Your content has been successfully ";
					
					if(newActiveStatus == 1) {
						newText = "Deactivate";
						altText = "Active";
						imgSrc = "green";
						successMessage += "activated";
					}
					else {
						newText = "Activate";
						altText = "Inactive";
						imgSrc = "red";
						successMessage += "deactivated";
					}

					var select = document.getElementById('select' + contentId);
					select.options[2].text = newText;
					
					// get image
					var activeImage = document.getElementById('activeImage' + contentId);
					activeImage.src = "/images/template/active-" + imgSrc + ".png";
					activeImage.alt = altText;
					activeImage.title = altText;
					
					createSuccessPop(successMessage, null);
				}					
				else {
					// error
					createErrorPop('An error has occurred. Please try again later', null);
				}
			}
	});
}

var inputCount = 0;
function uploadContentImage(formId, isNew, data) {
	
	var headerText, captionValue = "", creditValue = "", inpIndex;
	if(isNew) {
		// new image
		headerText = "Upload Image";
		inputCount++;
		inpIndex = inputCount;
	}
	else {
		// editing image
		headerText = "Edit Image";
		captionValue = data['caption'];
		creditValue = data['credit'];
		inpIndex = data['id'];
	}
	
	var header = document.createElement('h2');
	header.className = 'popLayerHeader';
	header.appendChild(document.createTextNode(headerText)); 

	var inputCaption = document.createElement('input');
	inputCaption.type = 'text';
	inputCaption.name = 'imageCaption' + inpIndex;
	inputCaption.value = captionValue;
	
	var inputCredit = document.createElement('input');
	inputCredit.type = 'text';
	inputCredit.name = 'imageCredit' + inpIndex;
	inputCredit.value = creditValue;
	
	var table = document.createElement('table');
	table.className = "uploadImageTable";
	
	var captionRow = table.insertRow(0);
	captionRow.insertCell(0).appendChild(document.createTextNode('Image Caption:'));
	captionRow.insertCell(1).appendChild(inputCaption);
	
	var creditRow = table.insertRow(1);
	creditRow.insertCell(0).appendChild(document.createTextNode('Image Credit:'));
	creditRow.insertCell(1).appendChild(inputCredit);
	
	if(isNew) {
		var inputFile = document.createElement('input');
		inputFile.type = 'file';
		inputFile.name = 'imageFile' + inpIndex;
		inputFile.size = "45";
		var fileRow = table.insertRow(2);
		fileRow.insertCell(0).appendChild(document.createTextNode('Image File:'));
		fileRow.insertCell(1).appendChild(inputFile);
	}
		
	var saveButton = document.createElement("input");
	saveButton.type = "image";
	saveButton.src = "/images/template/popup-save-button.gif";
	
	var cancelButton = document.createElement("input");
	cancelButton.type = "image";
	cancelButton.src = "/images/template/popup-cancel-button.gif";
	
	var buttonContainer = document.createElement('div');
	buttonContainer.style.margin = "10px 0 0 0";
	buttonContainer.appendChild(saveButton);
	buttonContainer.appendChild(document.createTextNode(" "));
	buttonContainer.appendChild(cancelButton);	
	
	var popLayer = createPopupLayer({width:'500px', className:'popLayerGeneral'});
	popLayer.appendChild(header);
	popLayer.appendChild(table);
	popLayer.appendChild(buttonContainer);
	
	new Draggable('popLayer', {revert: false});
	
	cancelButton.onclick = function () {
		removePopupLayer();
	}
	
	if(isNew) {
		saveButton.onclick = function() {
			// validate there is a file
			if(trim(inputFile.value) == '') {
				// add error
				var errorContainer = document.createElement("div");
				errorContainer.style.margin = "8px 0 0 0";
				errorContainer.style.display = "none";
				
				var errorMessage = "<img style='position: relative; top: 2px;' src='/images/template/ic-x.png' alt='' /> <span style='color: #e42224; font-weight: bold; font-family: Arial, font-size: 12px;'>You must select an image file to upload</span>";
				errorContainer.innerHTML = errorMessage;
				popLayer.appendChild(errorContainer);
				Effect.Appear(errorContainer, {duration:1});
			}
			else {
				var appendUl = false;
				if(document.getElementById('ulImg') != null)
					var ul = document.getElementById('ulImg');
				else {
					var ul = document.createElement('ul');
					ul.style.padding = "0";
					ul.style.margin = "0";
					ul.style.listStyle = "none";
					ul.id = 'ulImg';
					
					appendUl = true;
				}
				
				// good to go
				var form = document.getElementById(formId);
				
				inputCredit.style.display = "none";
				inputCaption.style.display = "none";			
				inputFile.style.display = "none";
				
				var inputIndex = document.createElement('input');
				inputIndex.type = "hidden";
				inputIndex.name = "imgIndexIds[]";
				inputIndex.value = inpIndex;
				
				form.appendChild(inputCredit);
				form.appendChild(inputCaption); 
				form.appendChild(inputFile);
				form.appendChild(inputIndex);
				
				var imgContainer = document.getElementById('uploadImageContainer');
				var imgRow = document.createElement('li');
				imgRow.style.float = "none";
				imgRow.style.width = "100%";
				imgRow.style.display = 'none';
				imgRow.style.marginBottom = "3px;"
				
				var iconDelete = document.createElement('img');
				iconDelete.src = '/images/template/ic-delete-image.png';
				iconDelete.alt = 'Remove this image';
				iconDelete.title = 'Remove this image';
				iconDelete.style.cursor = "pointer";
				iconDelete.style.position = "relative";
				iconDelete.style.top = "3px";			
				
				var imgRowText = document.createElement('span');
				imgRowText.style.color = "#333";
				imgRowText.style.fontWeight = "bold";
				imgRowText.style.fontSize = "11px";
				imgRowText.title = trim(inputFile.value);
				
				var imgDesc = trim(inputFile.value);
				if(imgDesc.length > 30)
					imgDesc = imgDesc.substring(0, 30) + "...";
				
				imgRowText.appendChild(document.createTextNode('\u00a0\u00a0' + imgDesc));
				
				imgRow.appendChild(iconDelete);
				imgRow.appendChild(imgRowText);
							
				ul.appendChild(imgRow);
				if(appendUl)
					imgContainer.appendChild(ul);
				imgContainer.style.display = 'block';				
				
				Effect.Appear(imgRow);
				
				iconDelete.onclick = function() {
					Effect.Fade(iconDelete.parentNode);
					
					form.removeChild(inputCredit);
					form.removeChild(inputCaption);
					form.removeChild(inputFile);
					form.removeChild(inputIndex);
				}
				
				removePopupLayer();
			}		
		}
	}
	else {
		saveButton.onclick = function() {
			
			var form = document.getElementById(formId);
			
			inputCredit.style.display = "none";
			inputCaption.style.display = "none";
			
			var inputIndex = document.createElement('input');
			inputIndex.type = "hidden";
			inputIndex.name = "imgUpdateIds[]";
			inputIndex.value = inpIndex;
			
			form.appendChild(inputCredit);
			form.appendChild(inputCaption); 
			form.appendChild(inputIndex);			
			
			document.getElementById('curImgContainer').style.display = "block";
			removePopupLayer();
		}
	}
}

function createSuccessPop(message, params) {
	if(params == null)
		params = {};
	
	params['className'] = 'popLayerSuccess';
	
	var popup = createPopupLayer(params);
	popup.innerHTML = message;
	setTimeout('removePopupLayer()', 3500);
}

function createErrorPop(message, params) {
	if(params == null)
		params = {};
	
	params['className'] = 'popLayerError';
	
	var popup = createPopupLayer(params);
	popup.innerHTML = message;
	setTimeout('removePopupLayer()', 3500);
}

function createNoticePop(message, params) {
	if(params == null)
		params = {};
	
	params['className'] = 'popLayerNotice';
	
	var popup = createPopupLayer(params);
	popup.innerHTML = message;

}

function createPopupLayer(popProperties) {	
	
	var popContainerHolder = document.createElement('div');
	popContainerHolder.id = 'popLayerHolder';
	
	var popContainer = document.createElement('div');
	if(popProperties['className'] != null)
		popContainer.className = popProperties['className'];
	
	popContainer.id = 'popLayer';
	popContainer.style.marginTop = (getHeightOffset() + 40) + 'px';

	if(popProperties['width'] != null)
		popContainer.style.width = popProperties['width'];
	
	popContainerHolder.appendChild(popContainer);
	document.getElementById('pageContainer').appendChild(popContainerHolder);
	
	return popContainer;
}

function removePopupLayer() {
	if(document.getElementById('popLayerHolder') != null) {
		document.getElementById('pageContainer').removeChild(document.getElementById('popLayerHolder'));
	}
}

function getHeightOffset()
{
	var scrOfY = 0;
	
	if(typeof(window.pageYOffset) == 'number')
		scrOfY = window.pageYOffset;
	else if(document.body && (document.body.scrollLeft || document.body.scrollTop))
		scrOfY = document.body.scrollTop;
	else if(document.documentElement && (document.documentElement.scrollLeft || document.documentElement.scrollTop))
		scrOfY = document.documentElement.scrollTop;
	
	return scrOfY;
}

String.prototype.filterChars = function()
{
	var formatted = trim(this);
	
	// all values following the \u are HEX Unicode values of special Unicode characters
	var AMPERSAND           = new RegExp( '&amp;', 'g' );
	var GREATERTHAN         = new RegExp( '&gt;', 'g' );
	var LESSTHAN            = new RegExp( '&lt;', 'g' );
	var SMART_QUOTE         = new RegExp( '(\u201C|\u201D|&ldquo;|&rdquo;)', 'g' );
	var SMART_APOSTROPHE    = new RegExp( '(\u2018|\u2019|&lsquo;|&rsquo;)', 'g' );
	var NB_SPACE            = new RegExp( '(\u00A0)', 'g' );

	// Make the replacements
	formatted = formatted.replace( AMPERSAND,         '&' );
	formatted = formatted.replace( GREATERTHAN,       '>' );
	formatted = formatted.replace( LESSTHAN,          '<' );
	formatted = formatted.replace( SMART_QUOTE,       '"' );
	formatted = formatted.replace( SMART_APOSTROPHE,  '\'' );
	formatted = formatted.replace( NB_SPACE,          '&nbsp;' );

	return formatted;
}

//Counts characters for a given form field
function characterCounter(textResource, maxCharLimit, displayResource)
{
	var textField = getElementObj(textResource);
	var displayContainer = getElementObj(displayResource);
	
	if(textField != null && displayContainer != null)
	{
		
		var numCharacters = textField.value.length;
		var charactersLeft = (maxCharLimit - numCharacters);
		
		//alert('Num characters left' + charactersLeft);
		if(charactersLeft <= 0)
		{
			charactersLeft = 0;
			textField.value = textField.value.substring(0, maxCharLimit);			
		}
		
		if(charactersLeft <= 50 && charactersLeft >= 25)
			displayContainer.parentNode.style.color = "#d1d32f";
		else
		if(charactersLeft < 25)
			displayContainer.parentNode.style.color = "#bd2432";
		else
			displayContainer.parentNode.style.color = "#000";
		
		displayContainer.innerHTML = charactersLeft;		
	}
}

function getElementObj(elementResource)
{
	var elementObj = null;
	
	if(typeof(elementResource) == 'object')
		elementObj = elementResource;
	else
	{
		if(document.getElementById(elementResource) != null)
			elementObj = document.getElementById(elementResource);
	}
	
	return elementObj;
}

//Removes leading whitespaces
function LTrim( value ) {
	
	var re = /\s*((\S+\s*)*)/;
	return value.replace(re, "$1");
	
}

// Removes ending whitespaces
function RTrim( value ) {
	
	var re = /((\s*\S+)*)\s*/;
	return value.replace(re, "$1");
	
}

// Removes leading and ending whitespaces
function trim( value ) {
	return LTrim(RTrim(value));	
}

function processFormLoading(buttonId, loaderId) {
	var button = $(buttonId);
	var loader = $(loaderId);
	
	if(button != null)
		button.disabled = true;
	if(loader != null)
		loader.style.visibility = "visible";
}

function copyLinkPop(link) {
	
	var cancelButton = document.createElement("input");
	cancelButton.type = "image";
	cancelButton.src = "/images/template/popup-cancel-button.gif";
	
	var buttonContainer = document.createElement('div');
	buttonContainer.style.margin = "10px 0 0 0";
	buttonContainer.appendChild(cancelButton);	
	
	var popLayer = createPopupLayer({width:'500px', className:'popLayerGeneral'});
	popLayer.style.cursor = "default";
	popLayer.appendChild(document.createTextNode(link));
	popLayer.appendChild(buttonContainer);
	
	cancelButton.onclick = function () {
		removePopupLayer();
	}	
}

function deleteContentImage(imageId, contentTypeId) {
	
	if(confirm('Are you sure you want to permanently delete this image?')) {		
		
		var params = 'action=deleteimage&contentTypeId=' + contentTypeId + '&imageId=' + imageId + '&ieSucks=' + IeSucksUrlDate();
		new Ajax.Request('/rea/admin/ajaxaction', 
		{
			method: 'get',
			parameters: params,
			onSuccess: function(transport)
				{
					var imgRow = document.getElementById('imgRow' + imageId);
					Effect.Fade(imgRow);
					createSuccessPop("Successfully deleted image", null);
				}
		});
	}
}

function getIssues(magazineId) {
	
		var params = 'action=getIssues&magazineId=' + magazineId;
		new Ajax.Request('/rea/admin/ajaxaction', 
		{
			method: 'post',
			parameters: params,
			requestHeaders: {Accept: 'application/json'},
			onSuccess: function(transport)
				{
					json = transport.responseText.evalJSON();
					
					var issuesSelect = document.getElementById("issues");
					issuesSelect.innerHTML = "";
					opt = document.createElement("option");
					opt.appendChild(document.createTextNode("Issue"));
					issuesSelect.appendChild(opt);

					for(var c = 0; c < json.length; c++) {
						opt = document.createElement("option");
						opt.appendChild(document.createTextNode(json[c].year + " " + json[c].month));
						opt.setAttribute("value", json[c].magazineIssueId);
						issuesSelect.appendChild(opt);
					}
				}
		});
}

function updateAndSubmit(fieldId, fieldValue, formId) {
	var fieldIds = fieldId.split(",");
	var fieldValues = fieldValue.split(",");
	var numFields = fieldIds.length;

	if(numFields > 0) {
		
		var form = document.getElementById(formId);
		for(var i = 0; i < numFields; i++) {
			document.getElementById(trim(fieldIds[i])).value = fieldValues[i];
		}
		form.submit();
	}
}

function companySearch(input) {
	var select = $('companySelect');
	select.className = "ajaxSearchDrop";
		
	var keywords = trim(input.value);
	
	if(keywords.length >= 1) {
		var params = 'action=companysearch&keywords=' + keywords + '&ieSucks=' + IeSucksUrlDate();
		
		new Ajax.Request('/rea/admin/ajaxaction', 
		{
			method: 'get',
			parameters: params,
			onSuccess: function(transport)
				{
					var responseXml = transport.responseXML;
					
					var companyBase = responseXml.getElementsByTagName("companies")[0];
					var companies = companyBase.getElementsByTagName("company");
					var numCompanies = companies.length;
					
					if(companies != null && numCompanies > 0) {
						
						select.innerHTML = "";
						
						var option = null, company = null;
						for(var i = 0; i < numCompanies; i++) {
							
							company = companies[i];
							
							var companyName = trim(company.getElementsByTagName("name")[0].firstChild.nodeValue);
							var companyId = trim(company.getElementsByTagName("id")[0].firstChild.nodeValue);
							
							option = document.createElement('a');
							option.href = "#";
							option.appendChild(document.createTextNode(companyName));
							option.x = companyName;
							option.y = companyId;
							
							option.onclick = function() {
								var companyNameField = $('companyName');
								var companyIdField = $('companyId');
							
								companyNameField.value = this.x;
								companyIdField.value = this.y;
								
								select.style.display = "none";							
							};
							
							select.appendChild(option);
						}
						
						select.style.display = "block";
					}	
				}
		});
	}	
	else {
		// hide select search
		select.style.display = "none";
	}
}

function userSearch(input, populateIdField) {
	var select = $('userSelect');
	select.className = "userAjaxSearchDrop";
		
	var keywords = trim(input.value);
	
	if(keywords.length >= 1) {
		
		var params = 'action=usersearch&keywords=' + keywords + '&ieSucks=' + IeSucksUrlDate();
		
		new Ajax.Request('/rea/admin/ajaxaction', 
		{
			method: 'get',
			parameters: params,
			onSuccess: function(transport)
				{
					var responseXml = transport.responseXML;
					
					var userBase = responseXml.getElementsByTagName("users")[0];
					var users = userBase.getElementsByTagName("user");
					var numUsers = users.length;
					
					if(users != null && numUsers > 0) {
						
						select.innerHTML = "";
						
						var ul = document.createElement('ul');
						var option = null, user = null;
						for(var i = 0; i < numUsers; i++) {
							
							user = users[i];
							
							var fullName = trim(user.getElementsByTagName("name")[0].firstChild.nodeValue);
							var userId = trim(user.getElementsByTagName("id")[0].firstChild.nodeValue);
							var userImageSrc = trim(user.getElementsByTagName("image")[0].firstChild.nodeValue);
							var userName = trim(user.getElementsByTagName("userName")[0].firstChild.nodeValue);
							
							var userRow = document.createElement('li');
							
							var iconLink = document.createElement('a');
							iconLink.href = "/rea/u/" + userName + "/articles";
							iconLink.target = "_blank";
							iconLink.title = "View profile";
							
							var icon = document.createElement('img');
							icon.src = "/images/template/user_go.png";
							icon.style.paddingRight = "10px";
							icon.style.border = "none";
							icon.title = "View profile";
							
							iconLink.appendChild(icon);
							
							var image = document.createElement('img');
							image.style.width = "30px";
							image.style.height = "30px";
							image.src = userImageSrc;
							image.style.verticalAlign = "middle";
							image.style.border = "none";
							
							
							option = document.createElement('a');
							option.href = "#";
							option.appendChild(image);
							option.appendChild(document.createTextNode(" " + fullName));
							option.x = fullName;
							option.y = userId;
							
							option.onclick = function() {
								var userNameField = $('userName');
								var userIdField = $(populateIdField);
							
								userNameField.value = this.x;
								userIdField.value = this.y;
								
								select.style.display = "none";
								
								// var authorTextField = $('atf');
								// if(authorTextField != null) {
								//	authorTextField.value = this.x;
								// }
								
								return false;
							};
							
							userRow.appendChild(iconLink);
							userRow.appendChild(option);
							
							ul.appendChild(userRow);
						}
						
						select.appendChild(ul);
						select.style.display = "block";
					}	
				}
		});
	}	
	else {
		// hide select search
		select.style.display = "none";
		$(populateIdField).value = 0;
	}
}

function showSearch() {
	var newText;
	var container = $('searchOptions');
	var textContainer = $('searchText');
	textContainer.removeChild(textContainer.childNodes[0]);
	
	if(container.style.display == "none") {
		newText = "Hide Search Options";
		new Effect.SlideDown(container);
	}
	else {
		newText = "Show Search Options";
		new Effect.SlideUp(container);
	}
	
	textContainer.appendChild(document.createTextNode(newText));
}

function processCountryChange(countrySelect) {
	var stateBlock = document.getElementById('stateBlock');
	var regionBlock = document.getElementById('regionBlock');
	
	if(countrySelect.options[countrySelect.options.selectedIndex].value == "US") {
		stateBlock.style.display = "block";
		regionBlock.style.display = "none";
	}
	else {
		stateBlock.style.display = "none";
		regionBlock.style.display = "block";	
	}
}

function changePublishType(sel) {
	window.location = sel.value;
}
