	document.onkeydown = function (evt) {
		var keyCode = evt ? (evt.which ? evt.which : evt.keyCode) : event.keyCode;
		var eventTarget = evt ? evt.target : event.srcElement;
		var textField = eventTarget.tagName.toLowerCase() == 'select' || eventTarget.type == 'text' || eventTarget.type == 'password' || eventTarget.type == 'checkbox';
		if (keyCode == 13 && textField) {					
			switch(eventTarget.form.name) {		
				case "mgform":
				case "registrationForm":
				case "reviewForm":
				case "addressForm":
				case "ccForm":
					if(evt)	evt.stop();
					return false;
				default: break;
			}
		}
	};



	function checkQuantity(s)
	{
		// Returns 0 if illegal, 1 if legal but zero, 2 if legal and non-zero
		var result = 1;
		legalChars = ' 0123456789\t\r\n';
		nonZeroChars = '123456789';
		for (var i = 0; i < s.length; i++)
		{
			var c = s.charAt(i);
			if (legalChars.indexOf(c) == -1) return 0;
			if (nonZeroChars.indexOf(c) > -1) result = 2;
		}
		return result;
	}
	function checkAmount(s)
	{
		// Returns 0 if illegal, 1 if legal but zero, 2 if legal and non-zero
		var result = 1;
		legalChars = ' 0123456789\.\t\r\n';
		nonZeroChars = '123456789';
		for (var i = 0; i < s.length; i++)
		{
			var c = s.charAt(i);
			if (legalChars.indexOf(c) == -1) return 0;
			if (nonZeroChars.indexOf(c) > -1) result = 2;
		}
		return result;
	}
	
	function checkContactForm()
	{                               
		if (!document.contactForm.from_name.value) {
			alert('Please enter your name.');
			document.contactForm.from_name.focus();
			return false;
		}
		if (!document.contactForm.from_email.value) {
			alert('Please enter an email address.');
			document.contactForm.from_email.focus();
			return false;
		}
		if (!checkEmail(document.contactForm.from_email.value)){
			document.contactForm.from_email.focus();
			alert('Please enter a valid email address.');
			return false;
		}
		if (!document.contactForm.message.value) {
			alert('Please enter your message or comments.');
			document.contactForm.message.focus();
			return false;
		}
		if (!document.contactForm.captcha.value) {
			alert('Please enter the code as shown on the image.');
			document.contactForm.captcha.focus();
			return false;
		}
		return true;
	}
	
	function validateform()
	{
		// Returns true if this form is valid
		var foundErrors = false;
		var foundQuant = false;
		var isValid = false;
		if (document.mgform) {
			for (var i = 0; i < document.mgform.length; i++)
			{
				var e = document.mgform.elements[i];
				if (e.name.substring(0, 6) == 'quant_')
				{
				quantStatus = checkQuantity(e.value)
				if (quantStatus == 2) foundQuant = true;
				if (quantStatus == 0) foundErrors = true;
				}
				if (e.name.substring(0, 4) == 'amt_')
				{
					quantStatus = checkAmount(e.value)
					if (quantStatus == 2) foundQuant = true;
					if (quantStatus == 0) foundErrors = true;
				}
			}
		}
		isValid = ((foundQuant == true) && (foundErrors == false))
		if (isValid == false) {
			alert('Invalid quantity.  Please enter a quantity of 1 or more.');
			return isValid;
		}
		if (document.mgform.selecteddate && document.mgform.selecteddate.selectedIndex < 1) {
			alert('Please select the date you would like to attend.');
			document.mgform.selecteddate.focus();
			return false;
		}
		return true;
	}
	
	function Show(div, opt)
	{
		var theDiv = document.getElementById(div);
		if (theDiv.style.display == 'none') {
			if (typeof opt != 'undefined' && opt != '')
			  theDiv.style.display = opt;
			else		
			  theDiv.style.display = 'block';
		} else {
			theDiv.style.display = 'none';
		}
	}

	var maximumLength = 150;
	function checkLength(el) {
		var length = el.value.length;
		if (length > maximumLength) {
		alert('Please limit your message to ' + maximumLength
			+ ' characters. There are currently ' + length + '.');
		return false;
		}
		return true;
	}	
	
	function checkInvitationForm() {
		if (!document.invitationForm.from_name.value) {
			alert('Please enter your name.');
			return false;
		}
		if (!document.invitationForm.from_email.value) {
			alert('Please enter your email address.');
			return false;
		}
		if (!document.invitationForm.to_email.value) {
			alert('Please enter a valid email address in the To: field.');
			return false;
		}
		if (!document.invitationForm.subject.value) {
			alert('Please enter a subject for your message.');
			return false;
		}
		if (!document.invitationForm.message.value) {
			alert('Please enter a message.');
			return false;
		}
		if (!checkLength(document.invitationForm.message)) {		
			return false;
		}
		if (!document.invitationForm.captcha.value) {
			alert('Please enter the code as shown on the image.');
			return false;
		}
		var emailStr = document.invitationForm.to_email.value;
		emailStr = emailStr.replace(/\s/g, ',');
		emailStr = emailStr.replace(/(,+)/g, ',');
		document.invitationForm.to_email.value = emailStr;
		emails = emailStr.split(',');
		for (var n = 0; n < emails.length; n++) {
			if (emails[n] && !checkEmail(emails[n])){
				alert(emails[n] + ' is not a valid email address.');
				return false;
			}
		}
		if (emails.length > 10) {
			alert('You can only send this invitations to 10 email addresses at a time.');
			return false;
		}
		return true;
	}

	function setColor(val) {
		var radioSelect = document.customizeForm.radioSelect;
		for (var i = 0; i < radioSelect.length; i++)
		{
			if (radioSelect[i].checked) {
				if (radioSelect[i].value == 'backgroundcolor') {
					document.getElementById('backgroundcolor').style.background = val;
					document.getElementById('regpage').style.background = val;
			                document.getElementById('titleDiv').style.background = val;
					document.customizeForm.background_color.value = val;
				}
				if (radioSelect[i].value == 'boxbackgroundcolor') {
					changeRoundedBackground('order', 'bottom', val);
					changeRoundedBackground('details', 'top', val);
					changeRoundedBackground('details', 'bottom', val);
					changeRoundedBackground('attendees', 'top', val);
					changeRoundedBackground('attendees', 'bottom', val);
					changeRoundedBackground('date', 'bottom', val);
					changeRoundedBackground('host', 'bottom', val);
					changeBackground("roundcontent", val);
					document.getElementById('boxbackgroundcolor').style.background = val;
					document.customizeForm.box_background_color.value = val;
				}
				if (radioSelect[i].value == 'boxheaderbackgroundcolor') {
					changeRoundedBackground('order', 'top', val);
					changeRoundedBackground('date', 'top', val);
					changeRoundedBackground('host', 'top', val);
					changeBackground("roundheader", val);
					changeBackground("roundcontent2", val);
					document.getElementById('boxheaderbackgroundcolor').style.background = val;
					document.customizeForm.box_header_background_color.value = val;
				}
				if (radioSelect[i].value == 'boxbordercolor') {
					changeRoundedBorder('order', val);
					changeRoundedBorder('details', val);
					changeRoundedBorder('attendees', val);
					changeRoundedBorder('date', val);
					changeRoundedBorder('host', val);
					changeBorder("roundheader", val);
					changeBorder("roundcontent", val);
					changeBorder("roundcontent2", val);
					document.getElementById('regpage').style.borderColor = val;
					document.getElementById('boxbordercolor').style.background = val;
					document.customizeForm.box_border_color.value = val;
				}
				if (radioSelect[i].value == 'textcolor') {
					document.getElementById('regpage').style.color = val;
					document.getElementById('titleDiv').style.color = val;
					document.getElementById('textcolor').style.background = val;
					document.customizeForm.text_color.value = val;
				}
				if (radioSelect[i].value == 'linkcolor') {
					var nodes = document.getElementById('regpage').getElementsByTagName('a');
					for (var j = 0; j < nodes.length; j++) {
						nodes[j].style.color = val;
					}
					document.getElementById('linkcolor').style.background = val;
					document.customizeForm.link_color.value = val;
				}
				if (radioSelect[i].value == 'titletextcolor') {
					changeClassColor('title', 'div', val);
					document.getElementById('titletextcolor').style.background = val;
					document.customizeForm.title_text_color.value = val;
				}
				if (radioSelect[i].value == 'boxtextcolor') {
					changeColor('roundcontent', val);
					changeClassColor('tickets', 'td', val);
					changeClassColor('maindetails', 'td', val);
					document.getElementById('boxtextcolor').style.background = val;
					document.customizeForm.box_text_color.value = val;
				}
				if (radioSelect[i].value == 'boxheadertextcolor') {
					changeColor('roundheader', val);
					changeClassColor('tickets2', 'td', val);
					document.getElementById('boxheadertextcolor').style.background = val;
					document.customizeForm.box_header_text_color.value = val;
				}
			}
		}
	}
	
	function setColorFromText(input, val) {
		var regex = /^#[a-fA-F0-9]{6}$/i;
		if (!regex.test( val )) {
			alert("\"" + val + "\" is not a properly formatted color.  Please use the format \"#RRGGBB\" for all colors.");
			input.value = '';
			input.focus();
			return;
		}
		setColor(val);
	}
	
	function setRadio(name) {
		name = name.replace(/_/g, "");
		var radioSelect = document.customizeForm.radioSelect;
		for (var i = 0; i < radioSelect.length; i++)
		{
			if (radioSelect[i].value == name) {
				radioSelect[i].checked = true;
				break;
			}
		}
	}

	function changeBackground( name, color) {
		var nodes = document.getElementsByName(name);
		for (var j = 0; j < nodes.length; j++) {
			nodes[j].style.background = color;
		}
	}

	function changeRoundedBackground( divName, pos, color) {
		if (document.getElementById(divName)) {
			var nodes = document.getElementById(divName).getElementsByTagName('B');
			for (var j = 0; j < nodes.length; j++) {
				if (nodes[j].parentNode.className.indexOf( pos ) > 0) {
					nodes[j].style.background = color;
				}
			}
		}
	}

	function changeBorder( name, color) {
		var nodes = document.getElementsByName(name);
		for (var j = 0; j < nodes.length; j++) {
			nodes[j].style.borderColor = color;
		}
	}
	
	function changeRoundedBorder( divName, color) {
		if (document.getElementById(divName)) {
			var nodes = document.getElementById(divName).getElementsByTagName('B');
			for (var j = 0; j < nodes.length; j++) {
				nodes[j].style.borderColor = color;
			}
		}
	}
	
	function changeColor( name, color) {
		var nodes = document.getElementsByName(name);
		for (var j = 0; j < nodes.length; j++) {
			nodes[j].style.color = color;
		}
	}
	
	function changeClassColor(className, element, color) {
		var elements = document.getElementsByTagName(element);
		for (var i=0; i < elements.length; i++) {
			if (elements[i].className == className || elements[i].id == className ) {
				elements[i].style.color = color;
			}
		}
	}
	
	function Redeem() {
		if (!document.discountForm.discount.value) {
			alert('Please enter a discount code.');
			document.discountForm.discount.focus();
			return false;
		}
		var sUrl = document.location.href.split('?')[0];
		sUrl += '?discount=' + document.discountForm.discount.value;
		document.location.href = sUrl;
		return true;
	}
	
	function ShowRSVP(radio) {
		Hide('RSVPYes');
		Hide('RSVPNo');
		Hide('RSVPUndecided');
		Hide('RSVPInfo');
		Show('RSVP' + radio.id);
		if ((radio.id == 'No' || radio.id == 'Undecided') && document.mgform.invite.value == "")
			Show('RSVPInfo');
	}
	
	function ProcessRSVP(answer, inviteKey) {
		var url = baseUrl + '/inviteaction';
		var pars = '?eid=' + eid + '&r=' + Math.random() + '&i=' + inviteKey;
		pars += '&rsvp=' + answer;
		if ($('full_name'))
			pars += '&name=' + encodeURIComponent($('full_name').value);
		if ($('email'))
			pars += '&email=' + encodeURIComponent($('email').value);
		pars += '&message=' + encodeURIComponent($('rsvp_message_' + answer.toLowerCase()).value);
		window.frames['RSVPFrame'].location.href = url + pars;
		ShowRSVPConfirmation();
		//var myAjax = new Ajax.Request(url, {method: 'get', parameters: pars, onComplete: ShowRSVPConfirmation });
	}
	
	function ShowRSVPConfirmation() {
		$('RSVPDiv').innerHTML = 'Thank you for your reply.';
	}

	function updateCheckout() {
		//==== check with the gTotalRemainingTickets if available ====
		hasQuantity = 0;
		isFree = 0;
		isPaid = 0;
		hasPaid = 0;
		
		//==================================================================
		//== checking remaining quantity if event.capacity() is selected ===
		var sumAllQuantity = 0;
		var currentSelectedQuantity = 0;
		var overRequest = 0;
		var lastCountSelectedTickets = 0;
		
		if (document.mgform) {
			
			for (var i = 0; i < document.mgform.length; i++) {
				var e = document.mgform.elements[i];
				if (e.name.substring(0, 6) == 'quant_') {
					
					//=================================
					//=== reset default quyantity   ===
					if (gShownRemainingTickets == 1)
						affectCell('ticket_table', dicTickeId[e.name], 1,  dicRemainingTicket[e.name]);
					
					//====================================
					//=== a quantity has been selected ===
					if (e[e.selectedIndex].value > 0) {
						hasQuantity = 1;
						ticketQuantity = 0;
						var f = document.mgform.elements[i-1];
						var maxQuantity = dicMaxTicket[e.name]  ;                // remaining tickets quantity 
						var	currentSelectedQuantity = e[e.selectedIndex].value;  // current selected quantity
						//===========================================================================
						//=== Event'sHolder has selected an  "event.capacity()"                   === 
						//=== sum all selected quantity to check if enought tickets are available ===
						//===========================================================================
						if (gTotalRemainingTickets > 0) {
							sumAllQuantity += parseInt(currentSelectedQuantity);
							if (sumAllQuantity > gTotalRemainingTickets) {
								alert('Not enought tickets to satisfy your request !');
								countOverRequest =   gTotalRemainingTickets - lastCountSelectedTickets;
								if (countOverRequest <= maxQuantity) 
									e.selectedIndex = countOverRequest ;
								}
							lastCountSelectedTickets =  sumAllQuantity;
							//if (gShownRemainingTickets == 1 && (gNbrTicketsType > 1 || (gNbrTicketsType == 1 && currentSelectedQuantity > 1))) {
							if (gShownRemainingTickets == 1 && gNbrTicketsType > 1) {
								remainingCurrentTicket = maxQuantity - currentSelectedQuantity;
								affectCell('ticket_table', dicTickeId[e.name], 1,  remainingCurrentTicket + ' tickets');
								}
							}
						//==========================================================================
						//==== End of New Quantity processing                                    === 
						//========================================================================== 
						
						if (f.value.trim() > "0.00") {
							isFree = 0;
							isPaid = 1;
							hasPaid = 1;
							}
						else {
							if (!isPaid)
								isFree = 1;
							}
					}
				}
				
				if (e.name.substring(0, 4) == 'amt_') {
					if (e.value.trim() > "0.00") {
						hasQuantity = 1;
						isFree = 0;
						isPaid = 1;
						hasPaid = 1;
					}
				}
				if (e.name.substring(0, 5) == 'cost_') {
					if (e.value.trim() > "0.00") {
						hasPaid = 1;
					}
				}
			}
			
			//==========================================================
			//=== Make a summary of available Quantity               ===
			//=== event's Holder has selected the "event.capacity()" ===
			//=== check if enought tickets are available             ===
			//==========================================================
			
			if (gTotalRemainingTickets > 0) {
				//===========================================
				//=== reset the disabled Quantity dropdown ==
				for (var i = 0; i < document.mgform.length; i++) {
					var e = document.mgform.elements[i];
					if (e.name.substring(0, 6) == 'quant_') { 
						e.disabled = false;
						}
					}
				//=============================================================================================
				//== No more available tickets, then disable remaining Quantity Dropdown/Remaining Tickets  === 		
				if (sumAllQuantity >= gTotalRemainingTickets) {
					for (var i = 0; i < document.mgform.length; i++) {
						var e = document.mgform.elements[i];
						if (e.name.substring(0, 6) == 'quant_') {
							if (e[e.selectedIndex].value == 0) 
								e.disabled = true;
							if (gShownRemainingTickets == 1)
								affectCell('ticket_table', dicTickeId[e.name], 1,  '0 ticket');
							}
						}
					}
				}	
			
			
		}
		if ((!hasQuantity || isPaid) && !isFree && hasPaid) {
			if ($('freeButton'))
				$('freeButton').style.display = 'none';
			if ($('paidButton'))
				$('paidButton').style.display = 'block';
		} else {
			if ($('freeButton'))   
				$('freeButton').style.display = 'block';
			if ($('paidButton'))   
				$('paidButton').style.display = 'none';
		}
		return true;
	}
	
	function eventbriteCheckout() {
		document.mgform.payment_type.value = 'eventbrite';
		if (validateform())
			document.mgform.submit();
	}
	
	function authnetCheckout() {
		document.mgform.payment_type.value = 'authnet';
		if (validateform())
			document.mgform.submit();
	}
	
	function paypalCheckout() {
		document.mgform.payment_type.value = 'paypal';
		if (validateform())
			document.mgform.submit();
	}
	
	function googleCheckout() {
		document.mgform.payment_type.value = 'google';
		if (validateform())
			document.mgform.submit();
	}
	
	function offlineCheckout() {
		document.mgform.payment_type.value = 'offline';
		if (validateform())
			document.mgform.submit();
	}

	function freeCheckout() {
		document.mgform.payment_type.value = 'free';
		if (validateform())
			document.mgform.submit();
	}
	
	function Checkout() {
		document.mgform.payment_type.value = '';
		if (validateform())
			document.mgform.submit();
	}
	
	function applyDiscount(cmd) {
		
		if(window.location.pathname == '/preview') 
			document.mgform.action = '/preview?eid=' + document.mgform.eid.value;
		else  {
			if (cmd == 'external_body') {
				document.mgform.target = '_self';
				document.mgform.action= 'tickets-external?eid=' + document.mgform.eid.value; 
				}
			else {  	
				document.mgform.action = '/event/' + document.mgform.eid.value;
				}
			}
		document.mgform.submit();
	}
	//==================================================================================
	//====   G L O B A L      F I E L D S     F O R    C U S T O M I Z E   F O R M   ===
	//====  event-new.html     /    event-header.html     /  even-footer.html		 ===  
	//==================================================================================
	
	var global_prfefix_sel = 'show_'            ; // checkbox Name for Header/footer
	var global_prefix_send_sel = 'send_show_'   ; // checkbox Name for Header/footer (Init from Mg.Qdata)			
	var global_prefix_text =  "_text_area"    	; // Header/footer Name  (For Edit process)
	var global_prefix_html =  '_Html'			; // name of Html Field (for Affect InnerHtml))
	var global_prefix_HeaderFooter= 'send_'  	; // Mg.Qdata => original Header / Footer (initialized by Pyhton Module)   
    var global_sel= '' ;
    var global_send_sel='';
    var global_text = '';
    var global_html ='';
    var global_HeaderFooter='';
    
    //==================================================
    //=== init global variables to refer Html Fields  == 
    //==================================================
    function InitCustomizeVar(sel_header_footer)
    {
		global_sel = global_prfefix_sel + sel_header_footer           	; // checkbox Name for Header/footer
		global_send_sel = global_prefix_send_sel + sel_header_footer  	; // checkbox Name for Header/footer			
		global_text = sel_header_footer  + global_prefix_text   		; // Header/footer Name
		global_html = sel_header_footer + global_prefix_html			; // name of Html Field (InnerHtml))
		global_HeaderFooter= global_prefix_HeaderFooter + sel_header_footer		; // Mg.Qdata => original Header / Footer field   
    }	
	// ====================================================================
	// ===  general process to Apply Header or Footer Modification		===
	//=====================================================================
	function ApplyModifHeader(sel_header_footer)
	{
		if (sel_header_footer != "")
			{
	 		InitCustomizeVar(sel_header_footer)	  				;	// Init global variables with Header or Footer
			CopyText(global_text,global_HeaderFooter) 			; // copy textarea to CustomizeForm (Ready to be posted)
			HideDiv('edit_box_' + sel_header_footer)  			; // Hide Div which include the Textarea
			ShowDiv('preview_' + sel_header_footer)         	; // Show Html Preview after Modification 
			//==== Affect to InnerHtml for Preview if Header selected (CheckBox) ====
			document.getElementById(global_send_sel).checked=document.getElementById(global_sel).checked;
			if (document.getElementById(global_sel).checked == true)
				document.getElementById(global_html).innerHTML  =    document.getElementById(global_text).value ;
			else
				document.getElementById(global_html).innerHTML  =  '';
			}
	}
	//=================================================
	//=== prepare for Html Edit  (Header or Footer) ===
	//=================================================
	function EditHeaderFooter(sel_header_footer)
	 {
	 	InitCustomizeVar(sel_header_footer)	  				;	// Init global variables with Header or Footer
	 	HideDiv('preview_'+sel_header_footer)				;	// Hide Html preview
	 	ShowDiv('edit_box_'+sel_header_footer)				;   // Show Box Edit of Html Header/Footer
	 	CopyText(global_HeaderFooter,global_text) 			; // copy Mg.qdata to textarea for Edit
		document.getElementById(global_sel).checked=document.getElementById(global_send_sel).checked;
	 	
	}
	//=====================================================
	//=====  Display Html preview                       ===
	//=====================================================
	function PreparePreview(sel_header_footer)
	{
	 	InitCustomizeVar(sel_header_footer)	  						;	// Init global variables with Header or Footer
		if (document.getElementById(global_send_sel).checked == true)
			document.getElementById(global_html).innerHTML =  document.getElementById(global_HeaderFooter).value ;
		else
			document.getElementById(global_html).innerHTML =  ''	;
	 }

	function updateTracking() {
		var myAjax = new Ajax.Request('/eventclick', {method: 'post', parameters: '?eid='+eid});
	}
	
	//==============================================
	//=== Check numeric field                    ===
	//==============================================   
	function IsNumeric(sText)  {
   		var ValidChars = "0123456789.";
   		var IsNumber = true;
   		var Char;
   		for (i = 0; i < sText.length && IsNumber == true; i++) {
      		Char = sText.charAt(i); 
      		if (ValidChars.indexOf(Char) == -1) {
         		return false;
         		}
      		}
   		return IsNumber;
   		}

   	function affectCell(divTable, rowCount, colCount,  newValue) {
   		var  currenttable = document.getElementById(divTable).rows;
		var y = currenttable[rowCount].cells;
		y[colCount].innerHTML = newValue;    
		}
   		
   		
	