var currentFormFields = new Array();

function onLoadNewEventForm(formID) {
	var form = $(formID);
	if (form != null) {
		var formFields = form.getElements();
		formFields.each(function(item) {
			if (item.name != null && item.name != "" && item.name != "action" && (item.tagName == "TEXTAREA" || item.type == "text") ) {
				if (item.hasClassName("plain_field") || item.hasClassName("plain_field_textarea"))
					item.completed = true;
				else
					item.completed = false;
				currentFormFields[item.name] = item;
			}
		});
	}
}

function toggleEnabled(itemsArray) {
	itemsArray.each(function(item) {
		$(item).disabled = !$(item).disabled;
	});
}

function estimateEndTime(prefix) {
	var timePrefix = prefix + "Time";
	var datePrefix = prefix + "Date";
	
	hour = $(timePrefix + "Hour").value;
	if($(timePrefix + "Meridian").value == "PM" && hour != 12)
		hour = parseInt(hour) + 12;
	if($(timePrefix + "Meridian").value == "AM" && hour == 12)
		hour = parseInt(hour) - 12;

	// alert($(datePrefix + "Year").value + ' ' + $(datePrefix + "Month").value  + ' ' + $(datePrefix + "Day").value  + ' ' + hour + ' ' + $(timePrefix + "Minute").value  + ' ' );
	
	var d = new Date(
		$(datePrefix + "Year").value,
		$(datePrefix + "Month").value - 1, 
		$(datePrefix + "Day").value,
		hour,
		$(timePrefix + "Minute").value,
		00);
		
		
	durationInMilis = $(timePrefix + "Duration").value * 60 * 60 * 1000;
	dateInMilis = parseInt(d.getTime()) + durationInMilis;
	timeEstimate = new Date();
	timeEstimate.setTime(dateInMilis);	
	year = timeEstimate.getUTCFullYear();
	minutes = timeEstimate.getMinutes();
	hours = timeEstimate.getHours();
	month = (parseInt(timeEstimate.getMonth())) + 1;
	
	if(minutes < 10)
		minutes = minutes + "0";

	if(hours > 11){
		minutes += " PM - ";
		if(hours > 12)
			hours -= 12;
	} else 
		minutes += " AM  - ";
	if(hours == 0){
		hours = 12;
	}
	
	if(durationInMilis != 0){
		$("estimatedEnd").innerHTML = "End Time: " + hours + ":" + minutes + month + "/" + timeEstimate.getDate() + "/" + timeEstimate.getFullYear();
	} else {
		$("estimatedEnd").innerHTML = "";
	}
}

function changeGrayField(item) {
	item.style.fontFamily = "helvetica";
	item.style.color = "#000000";
	item.style.fontStyle = 'normal';
	item.onfocus ="";
}

function setGrayField(item) {
	item.value = "";
	item.style.fontFamily = "helvetica";
	item.style.color = "#000000";
	item.style.fontStyle = 'normal';
	item.onfocus ="";
}

function setGrayFieldEvent(event) {
	this.value = "";
	this.style.fontFamily = "helvetica";
	this.style.color = "#000000";
	this.style.fontStyle = 'normal';
	this.onfocus ="";
}

function clearGrayField(item, value) {
	if(item.value.length == 0) {
		item.value = value;
		item.style.fontFamily = "helvetica";
		item.style.color = "#CCCCCC";
		item.style.fontStyle = 'italic';
		item.onfocus = setGrayFieldEvent;
		
		if (currentFormFields[item.name] != null)
			currentFormFields[item.name].completed = false;
	} else {
		if (currentFormFields[item.name] != null)
			currentFormFields[item.name].completed = true;
	}
}

function onSubmitEventForm() {
	for (i in currentFormFields) {
		if (currentFormFields[i].completed == false) {
			currentFormFields[i].value = '';
		}
	}
	
	return true;
}

function addAnother(type, itemsAdded) {
	
		var addonWeblinkNewCounter;
		var addonVideoNewCounter;
		var defaultLink;
		var defaultTitle;
		var price;
		
		
		if(type == 'weblink') {
			//addWeblink();
			//addSubTotal(2);
			addonNewCounter = ++weblinkCounter;
			defaultCheck = 2;
			defaultLink = "www.weblink.com/link";
			defaultTitle = "Buy Tickets, Visit Sponsor, etc.";
			$('subTotal').innerHTML = '$'+((itemsAdded * 14).toFixed(2));
		}
		
		if(type == 'video') { 
			//addVideo();
			//addSubTotal(0);
			addonNewCounter = ++videoCounter;
			defaultCheck = 0;
			defaultLink = "www.youtube.com/link";
			defaultTitle = "Event Video";
			$('subTotal').innerHTML = '$'+((itemsAdded * 21).toFixed(2));
		}
		
		var newDiv = document.createElement('div');
		newDiv.setAttribute('id', (type+'addon'+addonNewCounter));
		
		if(type == 'video') {
			// build the objects
			newDiv.innerHTML += '<input type="text" id="'+type+'NewAddonData'+addonNewCounter+'" name="'+type+'NewAddonData'+addonNewCounter+'" value="'+defaultTitle+'" class="gray_field" onKeyUp="updateEventPreview('+addonNewCounter+', \''+type+'NewAddon'+'\');" onFocus="setGrayField(this);" onBlur="clearGrayField(this, \''+defaultTitle+'\');" maxlength="28"> ';
			newDiv.innerHTML += '<input type="text" name="'+type+'NewAddonLink'+addonNewCounter+'" id="'+type+'NewAddonLink'+addonNewCounter+'" value="'+defaultLink+'" class="gray_field" onKeyUp="updateEventPreview('+addonNewCounter+', \''+type+'NewAddon'+'\');" onFocus="setGrayField(this);" onBlur="clearGrayField(this, \''+defaultLink+'\');"> ';
		}
		
		if(type == 'weblink') {
			// build the objects
			newDiv.innerHTML += '<input type="text" id="'+type+'NewAddonData'+addonNewCounter+'" name="'+type+'NewAddonData'+addonNewCounter+'" value="'+defaultTitle+'" class="gray_field" onKeyUp="updateEventPreview('+addonNewCounter+', \''+type+'NewAddon'+'\');" onFocus="setGrayField(this);" onBlur="clearGrayField(this, \''+defaultTitle+'\');" maxlength="28" style="width:175px"> ';
			newDiv.innerHTML += '<input type="text" name="'+type+'NewAddonLink'+addonNewCounter+'" id="'+type+'NewAddonLink'+addonNewCounter+'" value="'+defaultLink+'" class="gray_field" onKeyUp="updateEventPreview('+addonNewCounter+', \''+type+'NewAddon'+'\');" onFocus="setGrayField(this);" onBlur="clearGrayField(this, \''+defaultLink+'\');" style="width:175px"> ';	
			newDiv.innerHTML += '<input type="file" id="weblinkNewAddonFile'+addonNewCounter+'" name="weblinkNewAddonFile'+addonNewCounter+'" > ';
		}
		
		newDiv.innerHTML += '<input type="button" value="Remove" class="removeButton" onclick="removeAnotherItem(\''+addonNewCounter+'\', \''+type+'\')">';
		
		$(type+'addonBase').appendChild(newDiv);
		$(type+'NewAddonLink'+addonNewCounter).completed = false;
		
		if(type == 'video') {
			currentFormFields[type+'NewAddonLink'+videoCounter] = $(type+'NewAddonLink'+videoCounter);
			currentFormFields[type+'NewAddonLink'+videoCounter].completed = false;
			currentFormFields[type+'NewAddonData'+videoCounter] = $(type+'NewAddonData'+videoCounter);
			currentFormFields[type+'NewAddonData'+videoCounter].completed = false;
			
		}
		if(type == 'weblink') {
			currentFormFields[type+'NewAddonLink'+weblinkCounter] = $(type+'NewAddonLink'+weblinkCounter);
			currentFormFields[type+'NewAddonLink'+weblinkCounter].completed = false;
			currentFormFields[type+'NewAddonData'+weblinkCounter] = $(type+'NewAddonData'+weblinkCounter);
			currentFormFields[type+'NewAddonData'+weblinkCounter].completed = false;
		}
		
	}
	
function removeAnother(selector, type, itemsAdded) {
	if(type == 'weblink') {
		//subtractWeblink();
		//addSubTotal(2);
		
		$('subTotal').innerHTML = '$'+((itemsAdded * 14).toFixed(2));
		$(type+'addon'+selector).innerHTML = '';
	}
	
	if(type == 'video') {
		//subtractVideo();
		//addSubTotal(0);
		
		$('subTotal').innerHTML = '$'+((itemsAdded * 21).toFixed(2));
		$(type+'addon'+selector).innerHTML = '';
	}
}

function updateSubtotal(calendar, amount) {
	var total;
	if($('subTotal').innerHTML == '-')
		total = 0;
	else {
		var totalStr = ($('subTotal').innerHTML).substring(1,$('subTotal').innerHTML.length);
		total = parseFloat(totalStr);
	}
	if(total + amount == 0)
		$('subTotal').innerHTML = '-';
	else
		$('subTotal').innerHTML = '$' + (total + amount).toFixed(2);
}

function updateTotal() {
	var total = 0;
	var subTotal;
	priceArray.each(function(item) {
		if(item != undefined) {
			var formElement = $('subTotal');
			if(formElement.innerHTML == '-')
				subTotal = 0;
			else {
				var subTotalStr = (formElement.innerHTML).substring(1,formElement.innerHTML.length);
				subTotal = parseFloat(subTotalStr);
			}
			total += subTotal;
		}
	});
	
	if(total == 0)
		total = '$0';
	else
		total = '$' + total.toFixed(2);
		
	$('totalCost').innerHTML = total;
	
	updateGTotal();
}

function updateGTotal() {
	var total = parseFloat(($('totalCost').innerHTML).substring(1,$('totalCost').innerHTML.length));
	var gtotal = total + addonTotal;
	
	if(gtotal == 0)
		gtotal = '$0';
	else
		gtotal = '$' + gtotal.toFixed(2);
		
	$('gTotalCost').innerHTML = gtotal;
	
}

/*function updateVisitors(calendar, action) {
	// check if the page has been loaded
	if($('dailyVisitorsTotal') != null) {
		if(priceArray[calendar]['visitorsCounted']) {
			var total = parseFloat($('dailyVisitorsTotal').innerHTML);
			if(isNaN(total)) total = 0;
			if(action == "sub") {
				var sum = total - priceArray[calendar]['dailyVisitors'];
				if(sum == 0) sum = '-';
				$('dailyVisitorsTotal').innerHTML = sum;
				priceArray[calendar]['visitorsCounted'] = false;
			}
		} else {
			var total = parseFloat($('dailyVisitorsTotal').innerHTML);
			if(isNaN(total)) total = 0;
			if(action == "add") {
				var sum = total + priceArray[calendar]['dailyVisitors'];
				$('dailyVisitorsTotal').innerHTML = sum;
				priceArray[calendar]['visitorsCounted'] = true;
			}
		}
	} else {
		priceArray[calendar]['visitorsCounted'] = true;
	}
}*/

function clearFeatured(calendar, sender) {
	var formFields = $('upgradeForm').getElements();
	formFields.each(function(item) {
		//alert("looking for FeaturedPlacement"+calendar+'_ and found '+item.name);
		if(item.name.startsWith('FeaturedPlacement' + calendar + '_'))
			if(!item.disabled){
				item.checked = false;
			}
	});
	
	// make sure it's not something previously purchased
	if(sender.disabled == false) {
		$('subTotal').innerHTML = '$' + calendarArray[calendar].premiereCost.toFixed(2);
	//	updateVisitors(calendar, "add");
	}
}

function clearPremiere(calendar, sender) {
	// if the premiere was checked, make sure and reset the subtotal
	if($('PremierePlacement' + calendar).checked)
		$('subTotal').innerHTML = '-';
	// if the featured was checked, 
	if(sender.checked == true) {
		$('FeaturedPlacement' + calendar).checked = true;
		updateSubtotal(calendar, calendarArray[calendar].featuredCost);
	} else {
		updateSubtotal(calendar, -1 * calendarArray[calendar].featuredCost);
	}
	// make sure it's not something previously purchased
	if(sender.disabled == false) { 
		/*if($('subTotal' + calendar).innerHTML == '-')
			updateVisitors(calendar, "sub");
		else
			updateVisitors(calendar, "add");*/
	}
}

function clearBoth(calendar) {
	var formFields = $('upgradeForm').getElements();
	formFields.each(function(item) {
		if(item.name.startsWith('FeaturedPlacement' + calendar + '_'))
			if(item.disabled == false){
				item.checked = false;
			}
	});
	$('subTotal').innerHTML = '-';
	//updateVisitors(calendar, "sub");
}


function selectCalendar(cal) {
	if($('elusSelection' + cal).getStyle("display") == "none") {
		$('elusSelection' + cal).show();
		$('elusSelectionHead' + cal).className = 'gridSelected';
		$('elusSectionCost' + cal).className = 'rightCostColSelected';
	} else {
		$('elusSelection' + cal).hide();
		$('elusSelectionHead' + cal).className = 'plainRow';
		$('elusSectionCost' + cal).className = 'rightCostCol';
	}
}

function whatIsCVS() {
	window.open("../whatIsCVS.php","What Is CVS","menubar=no,width=430,height=260,toolbar=no");
}

function findPos(obj) {
	var curleft = curtop = 0;
	
	if(obj.offsetParent) {
		do { 
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		} while (obj = obj.offsetParent);
	}
	
	return [curleft, curtop];
}

function displayInfoPopup(refElement, params) {
	
	//alert("refElement: "+refElement+" with "+params.content);
	
	if ($('infoPopup').hasClassName('popupShow'))
		closeInfoPopup();
	
	this.classes = new Array();
	
	var pos = findPos(refElement);
	
	//alert("object position "+pos[0]+", "+pos[1]);
	
	var rightEdge = pos[0]+238;
	
	if (rightEdge > document.viewport.getWidth()) { // if the box's right edge is out of the screen, move it left so its visible
		//alert("right edget out of bounds");
		$('infoPopup').style.left = (document.viewport.getWidth()-248)+'px';
		$('infoPopup').style.top = (pos[1]+16) + 'px';
	} else {
		//var parent = refElement.offsetParent;
		//alert(refElement.clientWidth);
		//$('infoPopup').style.left = (refElement.offsetLeft + refElement.clientWidth) + 'px';
		
		//if(navigator.userAgent.indexOf("Firefox")!=-1) {
		//	$('infoPopup').style.left = (pos[0]-145 + refElement.clientWidth) + 'px';
		//	$('infoPopup').style.top = pos[1] + 'px';
		//} else {
		$('infoPopup').style.left = (pos[0]) + 'px';
		$('infoPopup').style.top = pos[1] + 'px';
		//}
	}
	
	$('infoPopup').addClassName('popupShow');
	
	this.classes.push('popupShow');
	
	var topDiv = $(document.createElement('div'));
	var midDiv = $(document.createElement('div'));
	var btmDiv = $(document.createElement('div'));
	
	topDiv.addClassName('backgroundTop');
	midDiv.addClassName('backgroundMiddle');
	btmDiv.addClassName('backgroundBottom');
	
	if(params.classes) {
		for(i = 0; i < params.classes.length; i++) {
			this.classes.push(params.classes[i]);
			$('infoPopup').addClassName(params.classes[i]);			
		}	
	}
	
	if(params.title) {
		midDiv.innerHTML = '<b>' + params.title + '<b><br>';
	}
	
	if(params.content) {
		midDiv.innerHTML += params.content;		
	}
	
	if (params.image) {
		midDiv.innerHTML += '<br>';
		var extraImage = $(document.createElement('img'));
	
		extraImage.id = 'extraImage';
		extraImage.src = params.image;
		extraImage.style.left = '12px';
		extraImage.style.top = '10px';	
		midDiv.appendChild(extraImage);		
	}
	
	var closeImage = $(document.createElement('img'));
	
	closeImage.id = 'closeImage';
	closeImage.addClassName('closeImage');
	closeImage.onclick = function(){closeInfoPopup()};
	closeImage.src = '../imgs/questionBoxClose.png';
	closeImage.style.right = '12px';
	closeImage.style.top = '10px';	
	
	$('infoPopup').appendChild(topDiv);
	$('infoPopup').appendChild(midDiv);
	$('infoPopup').appendChild(btmDiv);
	$('infoPopup').appendChild(closeImage);
}



function closeInfoPopup() {
	for(i = 0; i < this.classes.length; i++) {
		$('infoPopup').removeClassName(this.classes[i]);
	}
	var nodes = $('infoPopup').childNodes.length
	for(i = 0; i < nodes; i++) {
		$('infoPopup').removeChild($('infoPopup').childNodes[0]);
	}
}

function showHideRowsByClassName(tableID, className, show) {
	var rows = $(tableID).getElementsByTagName('tr');
	
	for(i = 0; i < rows.length; i++) {		
		if (rows[i].className == className || rows[i].className == className + " oddRow") {
			if (show) {
				$(rows[i].id).show();
			} else {
				$(rows[i].id).hide();
			}
		}
	}
}

function alternateRowClasses(tableID, className1, className2) {
	var rows = $(tableID).getElementsByTagName('tr');
	var oddRow = false;
	for(i = 0; i < rows.length; i++) {
		if (rows[i].style.display != 'none') {
			oddRow = !oddRow;
			if (oddRow) {
				rows[i].className = rows[i].className.replace(" "+className1, "");
				rows[i].className = rows[i].className+" "+className1;
			}
			else {
				rows[i].className = rows[i].className.replace(className1, "");
			}			
		}
	}
}


/**
*	promotion system start
**/

function unselectAllTabs() {
	$('tabEdit').className = 'tab inactive';
	$('tabDetails').className = 'tab inactive';
	$('tabPromote').className = 'tab inactive';
}

function getEdit(targetDiv, eventid, isLogged) {
	document.location.href = 'edit.php?EventID='+eventid;
	return true;
	//	(ELIMINATED AJAX LOADING)
	showLoading(targetDiv);
	
	unselectAllTabs();
	$('tabEdit').className = 'tab active';
	
	new Ajax.Request('/edit.php', {
		method: 'post',
		parameters: {
			alreadyLogged: isLogged,
			ajaxGetEditPage: true,
			EventID: eventid
		},
		onSuccess: function(transport) {
			$(targetDiv).innerHTML = transport.responseText;
			initializeCalendars(1);
		}
	});
}

function getPromote(targetDiv, eventid, isLogged) {
	document.location.href = 'promote.php?EventID='+eventid;
	return true;
	// (ELIMINATED AJAX LOADING)
	showLoading(targetDiv);
	
	var ajaxTarget = '/promote.php';
	
	unselectAllTabs();
	$('tabPromote').className = 'tab active';
	
	if(isLogged)
		ajaxTarget = '/account/promote.php';
	
	new Ajax.Updater(targetDiv, ajaxTarget, {
		method: 'post',
		parameters: {
			ajaxGetPromotePage: true,
			EventID: eventid
		},
		onSuccess: function(transport) {
			
		}
	});
}

function getDetails(targetDiv, eventid) {
	document.location.href = 'details.php?EventID='+eventid;
	return true;
	//	(ELIMINATED AJAX LOADING)
	showLoading(targetDiv);
	
	unselectAllTabs();
	$('tabDetails').className = 'tab active';
	
	new Ajax.Request('/details.php', {
		method: 'post',
		parameters: {
			ajaxGetDetailsPage: true,
			EventID: eventid,
			evalScripts: true
		},
		onSuccess: function(transport) {	
			$(targetDiv).innerHTML = transport.responseText;
			initializeCalendars(1);
		}
	});
}


function showLoading(targetDiv) {
	$(targetDiv).innerHTML = '<br><br><br><center><h1>Loading...</h1></center>';
}

function changeCalendarType(calID, eventID, type, preview) {
	var ShowOnlyLive = (preview) ? '0' : '1';
	$('calendarPreviewIframe').src = '/preview/index.php?EventID='+eventID+'&CalendarID='+calID+'&Type='+type+'&ShowOnlyLive='+ShowOnlyLive;
}

function removeAll(eventID) {
	if (confirm('Are you sure you want to remove all promotions for this event?')){
		window.location = 'shoppingcart.php?action=removeCartItem&removeall&eventID=' + eventID;
	}
}

/**
*	promotion system end
**/