Af.StepsMaker = Class.create();
usedNextStepFromQueryString = false;

//  SAVE ALSO IN AFSRC/ just in case..
Af.StepsMaker.prototype = {
	//Load some variables..
		TEMPLATE_STEP1: '1',
		TEMPLATE_STEP2: '2',
		TEMPLATE_STEP3: '3',
		TEMPLATE_STEP_PAYMENT_REQUEST: 'PaymentRequest',
		TEMPLATE_STEP_PAYMENT_REQUEST_THROUGH_AMAZON: 'PaymentRequestThroughAmazon',
		TEMPLATE_STEP_PAYMENT_ATTEMPT: 'PaymentAttempt',
		TEMPLATE_STEP_PAYMENT_ATTEMPT_THROUGH_AMAZON: 'PaymentAttemptThroughAmazon',

		initialize: function() {
		  // for miniCal functioning
  	  	this.sc = new Array();
  	  	this.date = new Date();
  	  	this.disabledInput = null;
  	  	this.hasAttachments = false;
  	  	this.miniCalendar = null;
		this.miniTableElement = "<div id=\"miniCalContainer\" class=\"miniBox miniCalOneList\"  style=\"z-index:300; position:abolute; \"><div id=\"miniCalTitlePane\" style=\"z-index:100; background-color:#FFFFFF; border:2px solid #489f97; width:185px;\"><h3><a id=\"miniPrevious\" href=\"#\">&lt;</a><span id=\"miniCalHeading\"> December 2007 </span><a id=\"miniNext\" href=\"#\">&gt;</a><span id=\"miniCalHeading\">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a id=\"miniClose\" href=\"#\">X</a></span></h3><table id=\"miniCalTable\" cellspacing=\"0\"></table></div></div>";
		/////////////

		/// Friends Importer
		 this.groupSelectedList = new Array();
		 this.peopleSelectedList = new Array();
		///


		// Exit Step for Unlogged in Users..
		this.listObj = null;
		this.exitStep = 1;
		this.isUpdatedAfterSend = false;
		
		this.attachDiv = "<span class=\"attachCont\"><input type=\"file\" name=\"attachItem\" value=\"\" class=\"dark\"/></span>" +
		"<div class=\"attachDelete\"><a href=\"#\"><span class=\"closeBtn\" title=\"Delete\"></span></a></div>";
        this.ATTACHMENT_ROWS = 10;
		this.emailValidator = new HJ.EmailValidator();
		
		this.selectedStepInitialized = false;
		
		// Jooners' payment fees
		this.maxVariableFee = 1.9;
		this.maxFixedFee = 0.3;
		this.minFee = 5.00;
	},

	loadTemplate: function () {
		this.doLoadTemplate();
	},

		//  Checks selected step and loads the appropriate template
	doLoadTemplate: function () {
		if (this.listObj != null && this.listObj.listDeleted != null && this.listObj.listDeleted == "true") {
			var errorText = document.getElementById("errorText");
			if (errorText != null && errorText.style != null && errorText.style.display != null && errorText.innerHTML != null) {
				errorText.style.display = "block";
				errorText.innerHTML = "The requester has canceled this Sign-Up";
			} else {
				window.alert("This Sign-Up is cancelled");
			}
			return;
		}
		
		showModalMessageDialog("Processing ... please wait",
                        300, 40);
				
		var step = "step" + this.selectedStep;
		this.tl = new Af.TemplateLoader(this.url[step],
                        this.targetContainerId[step], null);
    	this.tl.listener = this;
    	this.tl.loadTemplate();

    	if (app) {
    		app.templateLinkClicked = true;
    	}
	},

	loadEditTemplate:function() {
		this.selectedStep = 1;
		this.loadTemplate();
	},
   
    	loadPublishTemplate:function(evt) {
		if (this.publishTemplateDisplayed || login == null || app == null) {
			// stop multiple dialogs from being shown
			//return false;
		}
		this.publishTemplateDisplayed = true;

	   	// Ignore clicks that occur within timeout interval.
	   	// They are due to event bubbling up through
	   	// element hierarchy.
	    this.timerSet = true;
	    setTimeout(this.onTimeout.bind(this), 10);
	   	this.publishTemplateObj = new HJ.PublishMyList(this);
	   	this.publishTemplateObj.loadTemplate();
	 	return false;
    	
    },

	loadCopyTemplate:function() {
		hideModalMessageDialog();
		if (this.data['templateType'] == 'OrganizeShifts') {
			window.location = basePageURL + "OrganizeShifts.htm?copyFrom="+this.data['UUID'];
			return false;
		}
		if (login == null) {
			window.location = basePageURL + "Signin.htm?template=temp&l=" + this.data['UUID'];
			return false;
		}
		this.data['UUID'] = null;
		this.data['saveSend']=null;
        this.data['name'] = "Copy of " + this.data['name'];
   		this.selectedStep = 1;
   		
   		var items = this.data['item'];
   		if (items != null) {
   			for (var i=0; i<items.length; i++) {
   				items[i].listId = null;
   				items[i].UUID = null;
   				items[i].helper = null;
   				items[i].helperId = null;
   				items[i].helperEmail = null;
   				items[i].notes = null;
   				items[i].helperEventId = null;
   			}
   		}
   		this.loadTemplate();
    },

	//  Reset all Data..  For Cancel..
	cleanUp: function() {
		this.data = new Array;
		this.selectedStep = 1;
		this.loadTemplate();
		if (this.showCancelDialog!=null) {
			this.showCancelDialog.close();
		}
	},

	templateLoaded: function() {
		
		var printLink = document.getElementById('printPlanner');
		this.hideAfterLoad = true;
		if (printLink != null) {
			if (this.data['UUID'] == null || this.data['UUID'] == '') {
				printLink.style.display = 'none';
			} else {
                var showPrint = true;
                if (this.selectedStep == 4 && this.data['helperID']!=null) { // helper is viewing the planner
                    showPrint = false;
                }

                if(showPrint) {
				    printLink.style.display = 'block';
				    printLink.onclick = this.printPlanner.bindAsEventListener(this);

                }
			}
		}

		//  Go to exited Step.
		if (this.exitStep!=1) {
			this.selectedStep = this.exitStep;
			this.loadTemplate();
			//  Reset Unlogged in saved data and flag
			this.exitStep = 1;
			login.returnToObject = null;
			return;
		}
		
		if (this.listObj != null) {
			// initialize payment info
			var paymentRequestAttempt = this.listObj['latestPaymentRequestAttempt'];
			if (paymentRequestAttempt == null) {
				paymentRequestAttempt = this.listObj['latestPaymentRequest'];
			}
			if (paymentRequestAttempt != null) {
				// latestPaymentRequestAttempt has only one element
				paymentRequestAttempt = paymentRequestAttempt[0];
				// Make sure these variables are undefined BEFORE overwriting them with server values
				if (typeof(this.data['collectPayments']) == 'undefined')
					this.data['collectPayments'] = true;

				if (typeof(this.data['suggestedAmount']) == 'undefined')
					this.data['suggestedAmount'] = paymentRequestAttempt['requestedAmount'];

				if (typeof(this.data['payerCanChangeAmount']) == 'undefined'){
					if (paymentRequestAttempt['payerCanChangeAmount'] != null && paymentRequestAttempt['payerCanChangeAmount'] == 'true') {
						this.data['helperCanModifyAmount'] = true;
					} else {
						this.data['helperCanModifyAmount'] = false;
					}
				}

				if (typeof(this.data['payerSeesFees']) == 'undefined'){
					if (paymentRequestAttempt['payerSeesFees'] != null && paymentRequestAttempt['payerSeesFees'] == 'true') {
						this.data['showFeesToHelper'] = true;
					} else {
						this.data['showFeesToHelper'] = false;
					}
			  	}

			}
		}

		if (this.selectedStep == this.TEMPLATE_STEP_PAYMENT_REQUEST_THROUGH_AMAZON) {
			this.loadPaymentRequestThroughAmazonStep();
			hideModalMessageDialog();
			return false;
		}
		if (this.selectedStep == this.TEMPLATE_STEP_PAYMENT_ATTEMPT_THROUGH_AMAZON) {
			this.loadPaymentAttemptThroughAmazonStep();
			hideModalMessageDialog();
			return false;
		}

		if (this.selectedStep==2) {
			//  Nav Buttons
			this.nextButton = document.getElementById('nextButton');
			this.nextButton.onclick = this.goNext.bindAsEventListener(this);

			this.saveDraftButton = document.getElementById('saveDraftButton');
			this.updateButton = document.getElementById('updateButton');
			this.saveDraftButton.onclick = this.goSave.bindAsEventListener(this);
			this.updateButton.onclick = this.goUpdateAfterSend.bindAsEventListener(this);
			if (this.data['saveSend']=='send') {
				this.saveDraftButton.style.display = 'none';
			} else {
				this.updateButton.style.display = "none";
			}

			this.backButton = document.getElementById('backButton');
			this.backButton.onclick = this.goBack.bindAsEventListener(this);

			this.cancelButton = document.getElementById('cancelButton');
			this.cancelButton.onclick = this.goCancel.bindAsEventListener(this);

			this.loadStep2();
			this.initializeAttachmentsSection(true);
			this.setCurrentStepInYUIHistoryMgr(
                            Af.StepsMaker.prototype.TEMPLATE_STEP2);
            this.addIconButton = document.getElementById('customizeIconAddButton');
            if(this.addIconButton)
            {
                this.addIconButton.style.display = 'none';
            }
            this.addIconText = document.getElementById('customizeIconAddText');
            if(this.addIconText)
            {
                this.addIconText.style.display = 'none';
            }

            if(this.implicitIconListId)
                this.loadListIcon(this.implicitIconListId);

            this.loadListAttachment();

		} else if (this.selectedStep==3) {

			//  Nav Buttons
			this.nextButton = document.getElementById('nextButton');
			this.nextButton.onclick = this.goNext.bindAsEventListener(this);

			this.saveDraftButton = document.getElementById('saveDraftButton');
			this.updateButton = document.getElementById('updateButton');
			this.updateButton.style.display = "none";
			
			this.saveDraftButton.onclick = this.goSave.bindAsEventListener(this);
			if (this.data['saveSend']=='send') {
				this.saveDraftButton.style.display = 'none';
			}

			this.backButton = document.getElementById('backButton');
			this.backButton.onclick = this.goBack.bindAsEventListener(this);

			this.cancelButton = document.getElementById('cancelButton');
			this.cancelButton.onclick = this.goCancel.bindAsEventListener(this);

			this.loadStep3();

			this.setCurrentStepInYUIHistoryMgr(
                            Af.StepsMaker.prototype.TEMPLATE_STEP3);

		} else if (this.selectedStep==4) {
			this.loadStepsMakerStep4();
			this.loadStep4();
			this.initializeAttachmentsSection(false);
			
			if (this.data['helperID']!=null) {
				GATrackAction("helper_view_signup_request_for_"+this.templateType);
			} else {
				GATrackAction("organizer_view_signup_request_for_"+this.templateType);
			}

            this.loadListIcon();
            this.loadListAttachment();

		} else if (this.selectedStep==5) {
			GATrackAction("helper_signed_up_for_"+this.templateType);
			this.loadStep5();
		} else if (this.selectedStep==6) {
			this.loadStep6();
		} else if (this.selectedStep == this.TEMPLATE_STEP_PAYMENT_REQUEST) {
			this.nextButton = document.getElementById('nextButton');
			this.nextButton.onclick = this.goNext.bindAsEventListener(this);

			this.backButton = document.getElementById('backButton');
			this.backButton.onclick = this.goBack.bindAsEventListener(this);
			this.loadPaymentRequestStep();
		} else if (this.selectedStep == this.TEMPLATE_STEP_PAYMENT_ATTEMPT) {
			this.backButton  = document.getElementById('backButton');
			this.backButton.onclick = this.goBack.bindAsEventListener(this);
			this.loadPaymentAttemptStep();
		} else {			// Default/Step1 Loader
			// Track start of a template creation with google analytics
			if (this.listObj == null) { // new template is being loaded
				GATrackAction("start_"+this.templateType);		//  Nav Buttons
			}
			this.nextButton = document.getElementById('nextButton');
			this.nextButton.onclick = this.goNext.bindAsEventListener(this);

			this.saveDraftButton = document.getElementById('saveDraftButton');
			this.updateButton = document.getElementById('updateButton');
			this.saveDraftButton.onclick = this.goSave.bindAsEventListener(this);
			this.updateButton.onclick = this.goUpdateAfterSend.bindAsEventListener(this);
			if (this.data['saveSend']=='send') {
				this.saveDraftButton.style.display = 'none';
			} else {
				this.updateButton.style.display = "none";
			}

			this.backButton = document.getElementById('backButton');
			this.backButton.onclick = this.goBack.bindAsEventListener(this);

			this.cancelButton = document.getElementById('cancelButton');
			this.cancelButton.onclick = this.goCancel.bindAsEventListener(this);

			this.customizeIconButton = document.getElementById('customizeIconButton');
            if(this.customizeIconButton) // other templates compatibility
            {

			    this.customizeIconButton.onclick = this.showUploadIconDialog.bindAsEventListener(this);
            }


			this.loadStep1();
			this.initializeAttachmentsSection(true);

            this.loadListIcon();
            this.loadListAttachment();

			// force going back to home page if user clicks on back button
			// during template creation
			this.setCurrentStepInYUIHistoryMgr(
                            Af.StepsMaker.prototype.TEMPLATE_STEP1);
		}
		if (this.hideAfterLoad) {
			hideModalMessageDialog();
		}
		var h = document.getElementById('homePage');

		if(h)
		{
			var homeLink = h.getElementsByTagName('a');
			if(homeLink.length > 0)
				homeLink[0].focus();
		}
	},
	
	initializeAttachmentsSection: function(addDelete) {
		//
		// Handle Attachments at StepsMaker level
		//
        this.uploadResponseIFrame = document.getElementById('uploadResponse');
        this.addAttachmentBlock =
               document.getElementById('addAttachmentBlock');
        if (this.addAttachmentBlock != null) {
        	this.addAttachmentBlock.onclick =
               this.addAttachmentBlockClicked.bindAsEventListener(this);
        }

        // visible elements in the file input that let the user select the 
        // files to attach
        this.sendFileLink
            = document.getElementById('sendFileLink');
        if (this.sendFileLink != null) {
            this.sendFileLink.onclick 
                = this.sendFileClicked.bindAsEventListener(this);
        }
        
		this.addButton = document.getElementById('addAttachButton');
        if (this.addButton != null) {
        	this.addButton.onclick = this.addAttachment.bindAsEventListener(this);
        }

		this.addLink = document.getElementById('addAttachLink');
        if (this.addLink != null) {
        	this.addLink.onclick = this.showUploadAttachmentDialog.bindAsEventListener(this);
        }

        this.attachmentListContainer 
            = document.getElementById('attachmentList');

        // list of attachments
        var listUUID = null;
        if (this.listObj != null) {
            listUUID = this.listObj.UUID;
        } else if (this.implicitListId != null) {
            listUUID = this.implicitListId;
        }
        
        if (this.attachmentListContainer != null) {
            this.attachments = new HJ.Attachments(
                    this.attachmentListContainer, 
                    null,
                    this.ATTACHMENT_ROWS, 
                    listUUID,
                    this.addAttachmentBlock);
            this.attachments.fetchAttachments(addDelete);
        }
	},

	loadStep2:function() {
		this.sideNavBar.className = 'navStep2';
	},
	
	loadPaymentAttemptThroughAmazonStep: function() {
		this.createAmazonPaymentRequestFormElement("variableMarketPlaceFee", this.variableMarketPlaceFee);
		this.createAmazonPaymentRequestFormElement("fixedMarketplaceFee", this.fixedMarketplaceFee);
		this.createAmazonPaymentRequestFormElement("immediateReturn", this.immediateReturn);
		this.createAmazonPaymentRequestFormElement("collectShippingAddress", this.collectShippingAddress);
		this.createAmazonPaymentRequestFormElement("accessKey", this.accessKey);
		this.createAmazonPaymentRequestFormElement("referenceId", this.referenceId);
		this.createAmazonPaymentRequestFormElement("recipientEmail", this.recipientEmail);
		this.createAmazonPaymentRequestFormElement("amount", this.amount);
		this.createAmazonPaymentRequestFormElement("signature", this.signature);
		this.createAmazonPaymentRequestFormElement("isDonationWidget", this.isDonationWidget);
		this.createAmazonPaymentRequestFormElement("description", this.description);
		//this.createAmazonPaymentRequestFormElement("amazonPaymentsAccountId", this.amazonPaymentsAccountId);
		this.createAmazonPaymentRequestFormElement("ipnUrl", this.ipnUrl);
		this.createAmazonPaymentRequestFormElement("returnUrl", this.returnUrl);
		this.createAmazonPaymentRequestFormElement("processImmediate", this.processImmediate);
		this.createAmazonPaymentRequestFormElement("cobrandingStyle", this.cobrandingStyle);
		this.createAmazonPaymentRequestFormElement("abandonUrl", this.abandonUrl);
		this.createAmazonPaymentRequestFormElement("signatureVersion", this.signatureVersion);
		this.createAmazonPaymentRequestFormElement("signatureMethod", this.signatureMethod);
		this.createAmazonPaymentRequestFormElement("variableMarketplaceFee", this.variableMarketplaceFee);
		if( this.paymentUrl != null && this.paymentUrl != "" )
		{
			document.amazonPayForm.action = this.paymentUrl;
		}
	
		
		/*
		var link = document.getElementById("payAtAmazonLink");
		link.href = "https://authorize.payments.amazon.com/cobranded-ui/actions/start?";
		link.href += 
				"callerKey=" + this.callerKey +"&" +
				"callerReference=" + this.callerReference + "&" +
				"pipelineName=" + this.pipelineName +"&" +
				"recipientToken=" + this.recipientToken + "&" +
				"returnURL=" + this.returnURL +"&" +
				"transactionAmount=" + this.transactionAmount + "&" +
				"awsSignature=" + this.awsSignature;
		*/
	},

	createAmazonPaymentRequestFormElement: function(name, value) {
		if(value == null || value == "")
			return;
		var amazonPayForm = document.amazonPayForm;
		var e = document.createElement("input");
		e.setAttribute("type", "hidden");
		e.setAttribute("name", name);
		e.setAttribute("value", value);
		amazonPayForm.appendChild(e);

	},
	loadPaymentRequestThroughAmazonStep: function() {
		this.createAmazonPaymentRequestFormElement("maxVariableFee", this.maxVariableFee);
		this.createAmazonPaymentRequestFormElement("maxFixedFee", this.maxFixedFee);
		this.createAmazonPaymentRequestFormElement("callerAccountId", this.callerAccountId);
		this.createAmazonPaymentRequestFormElement("recipientPaysFee", this.recipientPaysFee);
		this.createAmazonPaymentRequestFormElement("collectEmailAddress", this.collectEmailAddress);
		this.createAmazonPaymentRequestFormElement("callerReference", this.callerReference);
		this.createAmazonPaymentRequestFormElement("callerKey", this.callerKey);
		this.createAmazonPaymentRequestFormElement("pipelineName", this.pipelineName);
		this.createAmazonPaymentRequestFormElement("returnURL", this.returnURL);
		this.createAmazonPaymentRequestFormElement("version", this.version);
		this.createAmazonPaymentRequestFormElement("signature", this.signature);
		this.createAmazonPaymentRequestFormElement("signatureVersion", this.signatureVersion);
		this.createAmazonPaymentRequestFormElement("signatureMethod", this.signatureMethod);
		this.createAmazonPaymentRequestFormElement("maxVariableFee", this.maxVariableFee);
		if( this.paymentUrl != null && this.paymentUrl != "" )
		{
			document.amazonPayForm.action = this.paymentUrl;
		}
	},
	
	loadPaymentRequestStep:function() {
		this.sideNavBar = document.getElementById('sideNavBar');
		
		this.navDivs = this.sideNavBar.getElementsByTagName('div');
		for (var i=0; i<this.navDivs.length; i++) {
			this.navDivs[i].onclick =
                    this.navBarClicked.bindAsEventListener(this);
		}
		
		this.saveDraftButton = document.getElementById('saveDraftButton');
		this.updateButton = document.getElementById('updateButton');
		this.saveDraftButton.onclick = this.goSave.bindAsEventListener(this);
		this.updateButton.onclick = this.goUpdateAfterSend.bindAsEventListener(this);
		if (this.data['saveSend']=='send') {
			this.saveDraftButton.style.display = 'none';
		} else {
			this.updateButton.style.display = "none";
		}
		
		this.collectPaymentElem = document.getElementById('collectPayment');
		this.suggestedAmountElem = document.getElementById('suggestedAmount');
		this.organizerAmountElem = document.getElementById('organizerAmountReceived');
		this.skipPaymentElem = document.getElementById('skipPayment');
		this.helperCanModifyAmountElem = document.getElementById('participantCanModifyAmount');
		this.showFeesToHelperElem = document.getElementById('showFeesToParticipant');
		this.collectPaymentElem.onclick = this.makePaymentsVisible.bind(this);
		this.skipPaymentElem.onclick = this.skipPaymentSetup.bind(this);
		this.suggestedAmountElem.onkeyup = this.calculatePaymentFees.bind(this);
		this.organizerAmountElem.onkeyup = this.calculateRequiredPayment.bind(this);
		this.suggestedAmountElem.onchange = this.setFixedWidthOnAmount.bind(this);
		this.organizerAmountElem.onchange = this.setFixedWidthOnAmount.bind(this);
		
		
		if (this.data['collectPayments'] != null && this.data['collectPayments'] == true) {
			this.collectPaymentElem.checked = true;
			this.makePaymentsVisible();
			
			if (this.data['suggestedAmount'] != null) {
				this.suggestedAmountElem.value = this.data['suggestedAmount'];
			}
			if (this.data['helperCanModifyAmount'] != null & this.data['helperCanModifyAmount'] == true) {
				this.helperCanModifyAmountElem.checked = true;
			}
			if (this.data['showFeesToHelper'] != null & this.data['showFeesToHelper'] == true) {
				this.showFeesToHelperElem.checked = true;
			}
		}
		this.calculatePaymentFees();
		this.setFixedWidthOnAmount();
	},
	
	loadPaymentAttemptStep:function() {
		this.helperEmailElem = document.getElementById('helperEmail');
		if (this.helperEmailElem != null && this.data['helperEmail'] != null && this.data['helperEmail'] != '' ) {
			this.helperEmailElem.value = this.data['helperEmail'];
		}

		if (this.data['name']!=null){
			document.getElementById('plannerName').innerHTML = this.data['name'];
			
		}	
		this.paymentQtyAmountElem = document.getElementById('paymentQty');
		this.unitPaymentAmountElem = document.getElementById('unitPaymentAmount');
	
		this.paymentQtyAmountElem.onkeyup = this.calculateTotalPaymentForHelper.bind(this);
		this.unitPaymentAmountElem.onkeyup = this.calculateTotalPaymentForHelper.bind(this);
	 	
	 	var paymentRequestInfo = this.data['latestPaymentRequest'][0];
	 	
	 	var requestedAmount = parseFloat(paymentRequestInfo.requestedAmount);
	 	requestedAmount = requestedAmount.toFixed(2);
	 	this.unitPaymentAmountElem.value = requestedAmount.toString();
	 	if (paymentRequestInfo.payerCanChangeAmount != 'true') {
	 		this.unitPaymentAmountElem.disabled = true;
	 	}
		// Used in case we are going back and forth to a page
		if (typeof(paymentRequestInfo.quantity) != 'undefined'){
			this.paymentQtyAmountElem.value = paymentRequestInfo.quantity;
		}
	
	 	// handle payerSeesFees later
		if (paymentRequestInfo.payerSeesFees == 'true'){
			document.getElementById('processingFeeTitleDiv').style.visibility = '';
			document.getElementById('processingFeeAmountDiv').style.visibility = '';
		}
	
	 	this.payAtAmazonButton = document.getElementById('payAtAmazonButton');
	 	if (this.payAtAmazonButton != null) {
	 		this.payAtAmazonButton.onclick = this.prepareToPayAtAmazon.bind(this);
	 	}
	 	
	 	var skipPaymentButton = document.getElementById('skipPaymentButton');
	 	if (skipPaymentButton != null) {
	 		skipPaymentButton.onclick = this.skipPayment.bind(this);
	 	}
	
		// Start off by correctly calculating the payment for 1 quantity.
		this.calculateTotalPaymentForHelper();
	},

	loadStep3:function() {
		//  Universal Nav bars - resides in Step 1 and remains
		this.sideNavBar = document.getElementById('sideNavBar');
		this.sideNavBar.className = 'navStep3';
	
		this.navDivs = this.sideNavBar.getElementsByTagName('div');
		for (var i=0; i<this.navDivs.length; i++) {
			this.navDivs[i].onclick =
                    this.navBarClicked.bindAsEventListener(this);
		}

		this.peopleSelectTrigger = document.getElementById("peopleSelector");
	 	this.peopleSelectTrigger.onclick = this.selectPeople.bind(this);

		this.peopleSelectTrigger2 = document.getElementById("peopleSelector2");
	 	this.peopleSelectTrigger2.onclick = this.selectPeople.bind(this);

		this.emailSubject = document.getElementById('emailSubject');
		if (login!=null){
			this.emailSubject.value = this.data.name + " - Please participate!";
		} else {
			this.emailSubject.value = this.data.name + " - Please participate!";
		}
		this.emailMessage = document.getElementById('emailMessage');

		if (this.data['lastEmailNote']!=null) {
			this.emailMessage.value = this.data['lastEmailNote'];
		} else if (this.templateType==HJ.TEMPLATE_TYPE_SIMPLE_LIST) {
			this.emailMessage.value = "I am sending you a Jooners' List that I think you will find useful.\n\n" +
			 "Please view it. A copy is awaiting you at www.jooners.com";
	    } else {

			this.emailMessage.value = "Hello,\n\n" +
					"I would like to invite you to sign up for " + this.data['name'] + ". Please click on the link above to sign up.\n\n" +
					"I am using Jooners to organize this activity. To participate, you do not need to register or become a member of Jooners.\n\n" +
					"Thank you!\n";
			
			if (login != null) {
				this.emailMessage.value += login.userData["fName"];
				this.emailMessage.value += " ";
				this.emailMessage.value += login.userData["lName"];
			}
		}
		
		this.emailString = document.getElementById('emailString');
		if (this.data['lastEmailString']!=null && this.data['lastEmailString']!="" && this.data['lastEmailString']!="undefined") {
			this.emailString.value = this.data['lastEmailString'];
		}
		else
		{
			if(login)
			{
				this.emailString.value = login.userData["email"];
			}
		}
	},
	
	loadStepsMakerStep4: function() {
		this.helperNextStepButton = document.getElementById('helperNextStepButton');
		this.rsvpButton = document.getElementById('rsvpButton');
		this.changesButton = document.getElementById('volunteerChangesButton');
		if (this.data['latestPaymentRequest'] == null || 
				this.data['helperID'] == null) {
			if (this.helperNextStepButton != null) {
				this.helperNextStepButton.parentNode.style.display = 'none';
			}
			this.rsvpButton.style.display = 'block';
		} else {
			// helper is viewing it and a payment request is associated with it
			if (this.helperNextStepButton != null) {
				this.helperNextStepButton.parentNode.style.display = 'block';
			}
			this.rsvpButton.style.display = 'none';
		}
		var sentEmails = document.getElementById('sentEmails');
		this.copyButton = document.getElementById('copyButton');
		var userEmail = HJ.readCookie(HJ.COOKIE_USER_EMAIL_ID);

		if (this.data['helperID']!=null) { // helper is viewing the planner
			var helperEmailDiv = document.getElementById('helperEmailDiv');
			if (helperEmailDiv != null) {
				helperEmailDiv.style.display = 'block';
			}
			if (this.helperNextStepButton != null) {
				this.helperNextStepButton.onclick = this.helperNextStep.bindAsEventListener(this);	
			}
			if (this.rsvpButton != null) {
				this.rsvpButton.onclick = this.goRSVP.bindAsEventListener(this);	
				var buttonText = this.rsvpButton.getElementsByTagName('span')[0];
				buttonText.innerHTML = "Sign-Up";
			}
			if (userEmail != null && userEmail.match("@jooners.com") != null) {
				this.copyButton.style.display = 'inline';
				//this.copyButton.onclick = this.loadCopyTemplate.bind(this);
				this.copyButton.onclick = this.showCopySelection.bind(this);
			}

			sentEmails.innerHTML = 'This sign-up sheet sent by: ' + this.data['sender'];
			this.helperEmailElem = document.getElementById('helperEmail');
			if (this.helperEmailElem != null) {
				if (this.data['helperEmail'] == null) {
					var helperEmailNote = document.getElementById('helperEmailNote');
					if (helperEmailNote != null) {
						helperEmailNote.style.display = "none";
					}
					this.emailWarningMsg = "Please ensure that your email address is entered in the email box at the top of the page and click Sign-Up again";
				} else {
					this.helperEmailElem.value = this.data['helperEmail'];
					this.emailWarningMsg = "Please confirm that your email address is in the email box at the top of the page and click Sign-Up again.";
				}
			}
			var helperPaidAmountDiv = document.getElementById('helperPaidAmountDiv');
			if (helperPaidAmountDiv != null) {
				var helperPaidAmount = this.data['helperPaidAmount'];
				if (helperPaidAmount != null) {
					try {
						helperPaidAmount = parseFloat(helperPaidAmount);
						if (!isNaN(helperPaidAmount) && helperPaidAmount != 0) {
							helperPaidAmountDiv.style.display = "block";
						}
					} catch (e) {
					}
				}
			}

			if(this.changesButton) // not available in certain template yet
			{
				if ( this.data['allowVolunteerChanges'] != null && 
					this.data['allowVolunteerChanges'] == "true") 
				{
					this.changesButton.parentNode.style.display = "inline";	
					// adjust left & rigth div width to fit
					var leftBtnDiv = document.getElementById('tempBtnLeft');
					var w = leftBtnDiv.clientWidth;
					leftBtnDiv.style.width = (w - 120) + "px";

					var rightBtnDiv = document.getElementById('tempBtnRight');

					w = rightBtnDiv.clientWidth;
					rightBtnDiv.style.width = (w + 120) + "px";

					this.changesButton.onclick = this.volunteerChangesCommitment.bindAsEventListener(this);
				}
				else
				{
					this.changesButton.parentNode.style.display = "none";	

				}
			} // this.changesButton

            // 2011-12-10 kee: fixed focus on homepage image problem (intermitent)
            var fblike = document.getElementById('fbLikeBtn');
            if(fblike)
            {
                fblike.focus();
            }
		} else { // organizer is viewing the planner
			var organizerRequestedPaymentDiv = document.getElementById('organizerRequestedPaymentDiv');
			if (organizerRequestedPaymentDiv != null) {
				var paymentRequest = this.listObj['latestPaymentRequest'];
				if (paymentRequest != null) {
					organizerRequestedPaymentDiv.style.display = 'block';
				}
			}
			
			if (this.helperNextStepButton != null) {
				var buttonText = this.helperNextStepButton.getElementsByTagName('span')[0];
				buttonText.innerHTML = "Done";
				this.helperNextStepButton.onclick = this.loadSIHP.bindAsEventListener(this);
			}
			if (this.rsvpButton != null) {
				var buttonText = this.rsvpButton.getElementsByTagName('span')[0];
				buttonText.innerHTML = "Done";
				// this.rsvpButton.onclick = this.loadSIHP.bindAsEventListener(this);
				this.rsvpButton.onclick = this.processDoneInStep4.bindAsEventListener(this);
			}
			
			this.editButton = document.getElementById('editButton');
			this.editButton.style.display = 'inline';
			this.editButton.onclick = this.loadEditTemplate.bind(this);
			
			this.copyButton.style.display = 'inline';
			//this.copyButton.onclick = this.loadCopyTemplate.bind(this);
			this.copyButton.onclick = this.showCopySelection.bind(this);

			this.askMoreHelpersElem = document.getElementById("askMoreHelpers");
			this.askMoreHelpersElem.style.display = "inline";
			this.askMoreHelpersElem.onclick = this.displayAskMoreHelpersDialog.bindAsEventListener(this);
			
			this.contactVolunteersElem = document.getElementById("contactVolunteers");
			if(this.contactVolunteersElem != null)
			{
				this.contactVolunteersElem.style.display = "inline";
				this.contactVolunteersElem.onclick = this.displayContactVolunteersDialog.bindAsEventListener(this);
				var leftBtnDiv = document.getElementById('tempBtnLeft');
				var w = leftBtnDiv.clientWidth;
				leftBtnDiv.style.width = (w + 60) + "px";

				var rightBtnDiv = document.getElementById('tempBtnRight');

				w = rightBtnDiv.clientWidth;
				rightBtnDiv.style.width = (w - 60) + "px";
			}

			this.publicLinkElem = document.getElementById("publicLink");
			if(this.publicLinkElem != null)
			{
				this.publicLinkElem.style.display = "inline";
				this.publicLinkElem.onclick = this.displayPublicLink.bindAsEventListener(this);
				/*
				var leftBtnDiv = document.getElementById('tempBtnLeft');
				var w = leftBtnDiv.clientWidth;
				leftBtnDiv.style.width = (w + 40) + "px";

				var rightBtnDiv = document.getElementById('tempBtnRight');

				w = rightBtnDiv.clientWidth;
				rightBtnDiv.style.width = (w - 40) + "px";
				*/
			}

			this.publish = document.getElementById('publish');
			if (this.publish != null) {
				if(login.userData["email"].search(/jooners.com/i) != -1 ) {
					this.publish.style.display = 'inline';
					this.publish.onclick = this.loadPublishTemplate.bind(this);
				}
			}
			

			if (this.data['lastEmailString'] == null) {
				this.data['lastEmailString'] = "";
			}
			var emails = this.data['lastEmailString'].split(',');
			if (emails.length == 1) {
				emails = emails[0].split(';');
			}
			var displayEmailString = '';
			for (i=0; i<emails.length; i++) {
				displayEmailString += emails[i] + '<br />';
			}
			sentEmails.innerHTML = 'This signup sheet has been sent to:' + '<br />' + displayEmailString + '<br />';
		}
	},

	loadStep5:function() {
		this.emailList = document.getElementById('emailList');

		if (this.data['lastEmailString'] == null) {
			this.data['lastEmailString'] = "";
		}
		var emails = this.data['lastEmailString'].split(',');
		if (emails.length == 1) {
			emails = emails[0].split(';');
		}
		var displayEmailString = '';
		for (i=0; i<emails.length; i++) {
			displayEmailString += emails[i] + '\n';
		}
		this.emailList.innerHTML = displayEmailString;
		this.emailList.setAttribute("readonly", "true");

		// show public link on confirm page
		this.publicLinkElem = document.getElementById("publicLink");
		if(this.publicLinkElem != null)
		{
			var link = window.location.protocol + "//" +
				window.location.host + 
				"/guest?t=help&p=none&l="+ this.data['UUID'];

			this.publicLinkElem.innerHTML = link;
		}
		/*
		document.getElementById('createNewSignUp').onclick =
                this.loadSIHP.bindAsEventListener(this);
		document.getElementById('viewCurrentSignUp').onclick =
                this.loadSIHP.bindAsEventListener(this);
		document.getElementById('goToCalendar').onclick =
                this.loadCalendarTemplate.bindAsEventListener(this);
		document.getElementById('inviteFriends').onclick =
                app.db.inviteFriends.bindAsEventListener(app.db);
        document.getElementById('clickMyJooners').onclick =
    		this.loadSIHP.bindAsEventListener(this);
		 */
    },

	// Recipient Confirmation Page
	loadStep6:function() {
		if (this.templateType==HJ.TEMPLATE_TYPE_SIMPLE_LIST) {
			var rsvpHeader = document.getElementById('rsvpHeader');
			if (rsvpHeader != null) {
				rsvpHeader.innerHTML = "";
			}
			var signupList = document.getElementById('signupList');
			if (signupList != null) {
				signupList.innerHTML = "";
			}

		} else if (this.templateType==HJ.TEMPLATE_TYPE_COLLECT_INFORMATION) {
			var collectInformationSignupInfo = document.getElementById('collectInformationSignupInfo');
			if (collectInformationSignupInfo == null) {
				return false;
			}

			collectInformationSignupInfo.innerHTML = this.collectInformationGenerateSignedUpDetailsHTML(this.listObj.helperEmail);

		} else {
			var signupInfoDiv = document.getElementById('signupInfoDiv');
			if (signupInfoDiv == null) {
				return false;
			}
			signupInfoDiv.innerHTML = this.generateSignedUpDetailsHTML(this.listObj.helperID);
		}
		var helperPaidAmount = this.data['helperPaidAmount'];
		if (helperPaidAmount != null) {
			try {
				helperPaidAmount = parseFloat(helperPaidAmount);
			} catch (e) {
				return false;
			}
			if (isNaN(helperPaidAmount) || helperPaidAmount == 0) {
				helperPaidAmountElem.innerHTML = "(payment unsuccessful)";
				return false;
			}
			
			var helperPaidAmountDiv = document.getElementById("helperPaidAmountDiv");
			var helperPaidAmountElem = document.getElementById("helperPaidAmount");
			if (helperPaidAmountDiv != null) {
				helperPaidAmountDiv.style.display = "block";
				helperPaidAmountElem.innerHTML = "$ "+helperPaidAmount.toFixed(2);
			}
		}
	},

    loadSIHP:function() {
		if (app.homePageUI != null) {
			app.homePageUI.loadNewHomePageTemplate();
		} else {
			window.location = basePageURL;
		}
    },

    generateSignedUpDetailsHTML: function(helperId) {
		var html = "<table>"
        
        html += "<tr><td colspan='2'>&nbsp;</td></tr>";
        html += "<tr><td colspan='2'><span style='font-size:12pt;'><b>" 
					+ this.listObj.displayName + "</b></span></td></tr>";
        html += "<tr><td colspan='2'>&nbsp;</td></tr>";
		var items = this.listObj.item;
	
		switch (this.templateType) {
			case HJ.TEMPLATE_TYPE_ORGANIZE_VOLUNTEERS :
				html += "<tr><td align='left' colspan=\"2\"><b>Date:&nbsp;&nbsp;</b>"+this.listObj.startDT+"</td></tr>";
				html += "<tr><td align='left' colspan=\"2\"><b>Time:&nbsp;&nbsp;</b>"+this.listObj.fromTime+"</td></tr>";
				html += "<tr><td align='left'><b>Your Responsibility:&nbsp;&nbsp;</b></td>";
				break;
			case HJ.TEMPLATE_TYPE_PRACTICE_CARPOOL :
				html += "<tr><td align='left' colspan=\"2\"><b>From Date:&nbsp;&nbsp;</b>"+this.listObj.startDT+"</td></tr>";
				html += "<tr><td align='left' colspan=\"2\"><b>To Date:&nbsp;&nbsp;</b>"+this.listObj.endDT+"</td></tr>";
				html += "<tr><td align='left'><b>Your Responsibility:&nbsp;&nbsp;</b></td>";
				break;
			case HJ.TEMPLATE_TYPE_SNACK_DUTY :
				html += "<tr><td align='left'><b>Your Responsibility:&nbsp;&nbsp;</b></td>";
				break;
			case HJ.TEMPLATE_TYPE_COLLECT_INFORMATION:
				html +="";
				break;
			case HJ.TEMPLATE_TYPE_GENERIC_SIGNUP : // treat generic signup as default
			default:
				html += "<tr><td align='right'><b>Your Responsibility:</b></td>";
		}

		if (helperId == null || helperId == '' || items == null || items.length==0) {
			html += "</tr><tr><td><br /><br /></td></tr></table>";
			return html;
		}

		var firstItemAssignedToHelper = true;
		for (var i=0; i<items.length; i++) {
			if (items[i].helperId != helperId && items[i].helperId != this.data["helperEmail"]) {
				continue;
			}
			if (firstItemAssignedToHelper) {
				firstItemAssignedToHelper = false;
				html+="<td>";
			} else {
				html+="<tr><td>&nbsp;</td><td>";
			}
			switch (this.templateType) {
				case HJ.TEMPLATE_TYPE_ORGANIZE_VOLUNTEERS :
					html += items[i].description;
					break;
				case HJ.TEMPLATE_TYPE_PRACTICE_CARPOOL :
					if (items[i].fromTo=='from') {
						html += "Pick-Up on ";
					} else {
						html += "Drop-off on ";
					}
					html += items[i].day;
					if (items[i].time != null && items[i].time != '') {
						html += " at " + items[i].time;
					}
					break;
				case HJ.TEMPLATE_TYPE_SNACK_DUTY :
					html += items[i].dueDate;
					break;
				case HJ.TEMPLATE_TYPE_GENERIC_SIGNUP :
					html += items[i].description;
					html += '&nbsp;';
					html += 'on ' + items[i].dueDate;
					break;
				case HJ.TEMPLATE_TYPE_COLLECT_INFORMATION:
					html += '';
					break;
				default:
					html += items[i].description;
			}
			html += "</td></tr>";
		}
		html += "</table>";
		return html;
    },
    
	loadIndex:function() {
		window.location = basePageURL + "index.htm";
	},
	loadSignupPage:function() {
		window.location = basePageURL + "Registration.html";
	},

	loadSigninPage:function() {
		window.location = basePageURL + "Signin.htm";
	},

	loadTempLearnPage:function() {
		return window.open('/learnMore.html','_blank','toolbar=yes, location=yes, directories=no, status=no, menubar=yes, scrollbars=yes, resizable=yes, copyhistory=yes, width=800, height=600');
	},

    loadCalendarTemplate: function() {
	    app.setCurrentTab(HJ.DESTINATION_PAGE_OUR_CAL);
	    app.db.displayCurrentTab();
		return false;
  	},

	// Save Step 3 - emails locally
	saveEmailData:function() {
		if (this.emailMessage.value!=null)
			{this.data['lastEmailNote'] = this.emailMessage.value;}
		if (this.emailString.value!=null)
			{this.data['lastEmailString'] = this.emailString.value;}
		if (this.emailSubject.value!=null)
			{this.data['lastEmailSubject'] = this.emailSubject.value;}
 	},

	//  Universal  NavBar comes in at Step1 and remains
	navBarClicked:function(evt) {
		var e = evt.target ? evt.target : evt.srcElement;
		var step = '';
		
		// check reminder day before proceed
		if(this.checkEventReminderDay != null &&
			this.checkEventReminderDay != 'undefined')
		{
			if(!this.checkEventReminderDay())
			{
				return false;
			}
		}

		
		if (e['id'] == 'navStepPaymentRequest') {
			step = this.TEMPLATE_STEP_PAYMENT_REQUEST;
		} else {
			step = e['id'].substr(e['id'].length-1);
		}

		this.sideNavBar.className = "navStep" + step;

		return this.goBack(evt, step);

	 	},

	previewEmail:function() {
		if(this.previewEmailDialog==null || this.previewEmailDialog!=null){
			var handler1 = {
				templateLoaded: function() {
					this.parent.goPreviewEmailLoad();
			},
				parent:this
			}
			this.previewEmailDialog =
                    new Af.HtmlDialog("Preview Email", handler1, null);
			this.previewEmailDialog.width = "850px";
		}
		this.previewEmailDialog.showHTMLTemplate(
                basePageURL + "previewEmail.htm", "MainArea", "Preview Email");
			//this.previewEmailDialog.centerDialog(350, 350);
	},

	goPreviewEmailLoad: function() {
		var emailString = this.emailMessage.value;

		document.getElementById('dialogEmailMessage').innerHTML =
                "<pre>" + emailString + "</pre>";
 	},

 	doInitialRoute: function() {
		if (this.data['helperID']!=null) {
			if (!this.selectedStepInitialized) {
				this.selectedStep = 4;
			}
		}  else if (this.data['saveSend']=='send') {
			// organizer is viewing a sent list
			this.selectedStep = 4;
		}
		this.selectedStepInitialized = true;
	},

//  People selector Dialog
  selectPeople: function() {
	if (login == null) {
		// pass reference to this object so that continue method can be invoked
		login = new HJ.Login(this, "true");
		login.startStep1();
		return false;
	}
		
    this.groupSelectedList = new Array;
    this.peopleSelectedList = new Array;

	 var pgSelector = getPoepleGroupSelector(this);
     pgSelector.setDataList(app.workspace["myGroup"],
      app.workspace["myPeople"],
      this.groupSelectedList,
      this.peopleSelectedList);
     return false;


    },
//  Handler function for peoplegroupselector..
   selectionDone: function (dialog, obj) {

	   var l = this.peopleSelectedList;
	   var groupsPeople = "";

       if (l == null) {
		   l = new Array();
	   }
	   for (var i=0; i<l.length; i++) {
	      var p = l[i];
	      p = findObjById(app.workspace["myPeople"], p.UUID);
	      if (p == null) {
	         continue;
	      }
		  if (groupsPeople == "") {
			groupsPeople +=  p["email"];
		  } else {
			groupsPeople += "," + p["email"];
		  }
	   }

	   var l = this.groupSelectedList;
	   var peopleNames = "";
       if (l == null) {
	       l = new Array();
	   }
	   if (l != null) {
		   for (var i=0; i<l.length; i++) {
		      var g = l[i];
			  g = findObjById(app.workspace["myGroup"], g.UUID);
			  if (g == null) {
			     continue;
			  }
			   var gPeopleList = g["people"];
			   if(gPeopleList != null) {
				   for(pId = 0; pId < gPeopleList.length; pId++ ) {
				        var p = gPeopleList[pId];
					    p = findObjById(app.workspace["myPeople"], p.UUID);
					    if (p == null) {
						  continue;
					    }
						peopleNames += p["email"]+",";
				   }
			   }
		   }
	   }

		var emailString = this.emailString.value;

		if (emailString=='' || emailString==null) {
			emailString='';
		}

		if (emailString=='' || emailString.charAt(emailString.length-1)==','){
			emailString=emailString+peopleNames+groupsPeople;
		} else {
			emailString = emailString + ',' + peopleNames + groupsPeople;
		}
	  	this.emailString.value = emailString;
   },

	helperNextStep:function() {
	   this.goRSVP();
	},
   
	//  override in specific class if there are notes.
	//  see practiceCarpool->goRSVP
	//  TODO:  Generalize this function..
	goRSVP:function() {

		if (this.listObj != null && this.listObj.listDeleted == "true") {
		  	showMessageDialog("The requester has canceled this Sign-Up",
                                "Notice",250,100, null, true);
			return false;
		}
		var items = this.data['item'];
		var signedUp = false;

		var helperEmailElem = document.getElementById('helperEmail');
		var helperEmailVal = null;
		if (helperEmailElem != null) {
			helperEmailVal = helperEmailElem.value;
			if (helperEmailVal != null && helperEmailVal != '') {
				if (!this.emailValidator.validateEmail(helperEmailVal)) {
					showMessageDialog(helperEmailVal, 'Invalid Email Address',
                                    300, 100);
					return false;
				}
				helperEmailVal = this.emailValidator.extractEmailAddress(helperEmailVal);
				//if (helperEmailVal != this.data['helperEmail']) {
				    signedUp = true;
				//}
				this.data['helperEmail'] = helperEmailVal;
			} else {
				// an email address must be provided even if helper is not signing up but wants to pay
                /*
				showMessageDialog("<center>Please enter your email in the email address box. This is required so that Jooners can send you a reminder email.</center>", 'Error',
                        300, 100);
                       */
                        
                this.showEmptyEmailMessage();
				return false;
			}
		}
        
        var itemEntered = false;
        var itemRemoved = false;
		if (items!=null && items.length > 0) {

			for (var i=0; i<items.length; i++) {
				var item = items[i];
				var helperDiv = document.getElementById(item.divName);
				var helperInputs = helperDiv.getElementsByTagName('input');
	
				if (helperInputs[0]!= null) {
	                		var value = helperInputs[0].value;
	                		if (helperInputs[0].disabled == false
	                        		&& value != 'Drivers Sign Up Here') {
					    if(value != null && value != '' && value != 'undefined')
					    {
					        itemEntered = true;
						    item.helperEmail = helperEmailVal;

					    }
					    else
					    {
				 	    	if( item.helperEmail != null && item.helperEmail != '' && item.helperEmail != 'undefined')
						{
							// volunteer remove commitment
							itemRemoved = true;
							item.helperEmail = '';
							item.helperId = '';
						}

					    }
					    item.helper = value;

					    if (this.templateType == HJ.TEMPLATE_TYPE_COLLECT_INFORMATION)
					    {
						    var colData = '';
						    for(var col = 0; col < this.maxColumns; col++)
						    {
						    	var dataElem = document.getElementById('informationField_'+ i + "_" + col);
							colData += dataElem.value
							if(col + 1 < this.maxColumns)
							{
								colData += ";";
							}

						    }

						    item.notes = colData;

					    }
					    else
					    {
						    var notesElem = document.getElementById('notes_'+i);
						    if (notesElem != null) {
							notesvalue = notesElem.value;
							if (notesElem.disabled == false
								&& notesvalue != 'Drivers Write Notes Here') {
								item.notes = notesvalue;
							}
						 }
					   }
	                }
				}
			}

            if(!itemEntered) {
                this.showEnterEmailAgainDialog();
                return false;
            }
			
			if (signedUp) {
				// 2011-06-09 kee: quick mockup to by pass emailAddrWarning
				//this.emailAddrWarningShown = true;
				if (this.emailAddrWarningShown == undefined || this.emailAddrWarningShown == false) {
                    /*
					showMessageDialog("You're almost done. Just one more step before we confirm your commitment to this event"
							+ "<br /><br />"
							+ this.emailWarningMsg, "Request", 
						350, 150);
                        */
                    this.showConfirmEmailDialog();
					//this.emailAddrWarningShown = true;
					return false;
				} else {
					//this.emailAddrWarningShown = true ;
					this.doSave();
					return false;
				}
			}
		}

		if (this.data['latestPaymentRequest'] != null && 
			this.helperNextStepButton != null) {
			this.selectedStep = this.TEMPLATE_STEP_PAYMENT_ATTEMPT;
		} else {
			this.selectedStep = 6;
		}
		this.loadTemplate();
	},

	// validate volunteer email with backend and enable corresponding boxes
	volunteerChangesCommitment:function() {
		this.emailInputDialog = showInputDialog("Please enter your email address ... ",
					"",
					"Change my commitment",
					300, 200, this.volunteerChangesEmailEntered.bind(this));
		return false;

	},
	volunteerChangesEmailEntered: function() {
		hideDialogWin();
		var _email = this.emailInputDialog.textField.value;
		if(_email == null || _email == '' || _email == 'undefined')
		{
			this.emailInputDialog = showInputDialog("Email is empty. Please enter your email address ... ",
					"",
					"Change my commitment",
					300, 200, this.volunteerChangesEmailEntered.bind(this));
			return false;	
		}
		else
		{
			_email = _email.toLowerCase();
			var items = this.data['item'];
			var found = false;
			var focused = false;
			this.prevCommitment = [];
			for (var i = 0; i < items.length; i++)
			{
				if(items[i].helperEmail == null ||
						items[i].helperEmail == "")
					continue;

				if(_email == items[i].helperEmail.toLowerCase())
				{
					var item = items[i];
					found = true;
					this.prevCommitment.push(items[i]);
					
				}
				
			}
			if(!found)
			{
				this.emailInputDialog = showInputDialog("There is no email address on this sign up sheet that matches the email address you entered. Please try again. ",
					"",
					"Change my commitment",
					300, 200, this.volunteerChangesEmailEntered.bind(this));
				return false;	

			}
			else
			{
			   var changeCommitmentDialog = new HJ.ChangeCommitmentDialog(this);
			   changeCommitmentDialog.setMyListUUID(this.data['UUID']);
			   changeCommitmentDialog.setMyItems(this.prevCommitment);
			   changeCommitmentDialog.loadTemplate();
			   //this.emailInputDialog.close();
			   return false;
			}

		}
		
		return false;	
	},

	updateCommitments: function(deleted)
	{
		var len = deleted.length;
		var modified = false;
		for(var i = 0; i < len; i++)
		{
			var items = this.data['item'];
			var ilen = items.length;
			for(var j = 0; j < ilen ; j++)
			{
				var item = items[j];
				if(item.UUID == deleted[i].UUID )
				{

					this.data["helperID"] = item.helperID;
					this.data["helperEmail"] = item.helperEmail;

					var helperDiv = document.getElementById(item.divName);
					var helperInputs = helperDiv.getElementsByTagName('input');
					helperInputs[0].value = "";

					// 2011-10-10 kee: removed notes altogether
					helperInputs[0].removeAttribute('disabled');
					helperInputs[0].style.color = "#000000";
					if (this.templateType == HJ.TEMPLATE_TYPE_COLLECT_INFORMATION) 
					{
						
						for(var h = 0; h < 3 ; h++)
						{
							helperInputs[4 + h].value = "";
							helperInputs[4 + h].removeAttribute('disabled');
							helperInputs[4 + h].style.color = "#000000";
						}

					}
					else
					{
						helperInputs[4].value = "";
						helperInputs[4].removeAttribute('disabled');
						helperInputs[4].style.color = "#000000";
					}


					item.helperEmail = '';
					item.helper = '';
					item.helperId = '';
					item.helperEventId = '';
					item.notes = '';
        				//this.updateMyListItemHelper(null, null, item.UUID);        	
					modified = true;
					break;
				}
			}
		}

		if(modified)
		{
			var xml = "<HELPResult>";
			xml += "<MyList class=\"MyList\" UUID=\"" + this.data["UUID"] + "\">";
			var dl = this.data["item"];

			for (var i=0; i<dl.length; i++) {
				var item = dl[i];
				xml += "<item class=\"MyListItem\" UUID=\"" + item["UUID"] + "\">";

				xml += "<property name=\"lastUpdateDate\" value=\""+item["lastUpdateDate"] + "\" />";

				var helperName = item["helper"];
				if (helperName ==  null || helperName == 'Drivers Sign Up Here') {
					helperName = "";
				} else {
					helperName = xmlEncode(helperName);
				}
				xml += "<property name=\"helper\"" + " value=\"" + helperName + "\" />";

				var notes = item['notes'];
				if (notes == null || notes == 'Drivers Write Notes Here') {
					notes = '';
				} else {
					notes = xmlEncode(notes);
				}
				xml += "<property name=\"notes\"" + " value=\"" + notes + "\" />";

				if(helperName != '')
				{
					var email = item['helperEmail'];
					if (email == null || email == 'undefined') {
						email = '';
					} else {
						email = xmlEncode(email);
					}
					xml += "<property name=\"helperEmail\"" + " value=\"" + email + "\" />";
				}
				else
				{
					xml += "<property name=\"helperEmail\"" + " value=\"\" />";
				}

				var helperId = item['helperId'];
				if (helperId == null || helperId == '' || helperId == 'undefined') {
					helperId = '';
					if (helperName != null && helperName != '') {
						helperId = this.data["helperEmail"];
						item.helperId = helperId;
					}
				}
				xml += "<property name=\"helperId\"" + " value=\"" + helperId + "\" />";

				var helperEventId = item['helperEventId'];
				if (helperEventId == null || helperEventId == 'undefined') {
					helperEventId = '';
				} else {
					helperEventId = xmlEncode(helperEventId);
				}
				xml += "<property name=\"helperEventId\"" + " value=\"" + helperEventId + "\" />";

				xml += "</item>";
			}

			xml += "</MyList>";


			xml += "<idOfUser>" + this.data["idOfUser"] + "</idOfUser>";
			xml += "<idOfHelper>" + this.data["helperID"] + "</idOfHelper>";
			xml += "<helperEmail>" + this.data["helperEmail"] + "</helperEmail>";

			xml += "</HELPResult>";
			this.xml = xml;
			this.saveUrl = svcURL;

			showModalMessageDialog("Processing your request... please wait", 300, 40);
			var req = new Af.DataRequest(this.saveUrl,
				this.updateCommitmentCompleted.bind(this),
			this.requestFailedCommon.bind(this), null,
			this.requestTimedoutCommon.bind(this));
			req.addService("PublicService", "saveHelpResult");
			req.addParameter("isSendReminder", "false");
			req.addParameter("helperID", this.data["helperID"]);
			req.addParameter("helperEmail", this.data["helperEmail"]);
			req.addParameter("listUUID", this.data["UUID"]);

			req.xmlDoc = this.xml;
			ajaxEngine.processRequest(req);
		} // modified

	},

	updateCommitmentCompleted: function(response) {	
		window.location.reload();
		//hideModalMessageDialog();
	},
	
	removeHelper: function(evt) {
		var elem = Event.element(evt);
		var idx = parseInt(elem.name);
		var items = this.data['item'];
		
		items[idx].helper = "";
		items[idx].helperId = null;
		items[idx].helperEmail = null;
		this.data['item'] = items;
		this.doSave("no"); // "no" means do not send reminder
		return false;
	},

	goUpdateAfterSend: function() {
		this.isUpdatedAfterSend = true;
		this.goSave("save");
		return false;
	},

	goSave:function(saveSend) {

		// check reminder day before proceed
		if(this.checkEventReminderDay != null &&
			this.checkEventReminderDay != 'undefined')
		{
			if(!this.checkEventReminderDay())
			{
				return false;
			}
		}
		if (this.selectedStep==1 || this.selectedStep==2 || this.selectedStep==4) {
			this.saveHoldData();
		} else if (this.selectedStep==3) {
			this.saveEmailData();
		}
		else if (this.selectedStep == this.TEMPLATE_STEP_PAYMENT_REQUEST){
			this.processPaymentRequest(false);
		}

		if (saveSend=='send') {
			this.action = 'send'; // useful in case login is necessary
		} else {
			this.action = 'save';
		}

		if (login == null) {

			// duplicated code from Start.js
			showModalMessageDialog("Initializing ... please wait", 240, 40);

			// pass reference to this object so that continue
            // method can be invoked 
	 		login = new HJ.Login(this, "true");
	 		login.startStep1();
	 		return false;

	 		}

		this.saveAfterLogin();
		return false;
	},

	saveAfterLogin:function() {

		if (this.action != null && this.action=='send') {
			this.validateUI();
			// this.saveMyList('send');
		} else {
			this.saveMyList('save');
		}

		if (this.showCancelDialog!=null) {
			this.showCancelDialog.close();
		}

		return false;
	},

	goNext:function(event) {
		if (this.selectedStep==1 || this.selectedStep==2) {
			this.saveHoldData();
		}
		if (this.selectedStep==3) {
			this.goSend();
			if (!event) var event = window.event;
			if (event) {
				YAHOO.util.Event.stopEvent(event);
			}
			return false;
		}
		// check reminder day before proceed
		if(this.checkEventReminderDay != null &&
			this.checkEventReminderDay != 'undefined')
		{
			if(!this.checkEventReminderDay())
			{
				return false;
			}
		}

		
		if (this.selectedStep == this.TEMPLATE_STEP_PAYMENT_REQUEST) {
			this.goBack(event, 3); // 3 is the step after payment request step
			return false;
		} else if (this.selectedStep == 2) {
			this.selectedStep = this.TEMPLATE_STEP_PAYMENT_REQUEST; // payment step is the new step 3
		} else {
			this.selectedStep++;
		}

		this.loadTemplate();
		if (!event) var event = window.event;
		if (event) {
			YAHOO.util.Event.stopEvent(event);
		}
		return false;
	},

	goBack:function(event, backTo) {
		if (this.selectedStep==3) {
			this.saveEmailData();
		}

		if (this.selectedStep==2 || this.selectedStep==1) {
			this.saveHoldData();
		}
		
		if (this.selectedStep == this.TEMPLATE_STEP_PAYMENT_ATTEMPT){
			// save the page data...
			var paymentRequestInfo = this.data['latestPaymentRequest'][0];
			paymentRequestInfo.requestedAmount = document.getElementById('unitPaymentAmount').value;
			paymentRequestInfo.quantity = document.getElementById('paymentQty').value;
			backTo = 4;
		}

		if (backTo == null) {
			if (this.selectedStep == this.TEMPLATE_STEP_PAYMENT_REQUEST) {
				backTo = 2; // the step before payment step
			} else if (this.selectedStep == 3) {
				backTo = this.TEMPLATE_STEP_PAYMENT_REQUEST; // payment step is the new step 3 and shows up before old step 3
			} else {
				backTo = this.selectedStep-1;
			}
		}
		var collectPayment = document.getElementById('collectPayment');

		if (this.selectedStep == this.TEMPLATE_STEP_PAYMENT_REQUEST){
			// Load up the payment's page form to ensure they get saved...
			this.data['collectPayments'] = document.getElementById('collectPayment').checked;
			this.data['suggestedAmount'] = document.getElementById('suggestedAmount').value;
			this.data['helperCanModifyAmount'] = document.getElementById('participantCanModifyAmount').checked;
			this.data['showFeesToHelper'] = document.getElementById('showFeesToParticipant').checked;
		}
		
		if (this.selectedStep == this.TEMPLATE_STEP_PAYMENT_REQUEST &&
			 collectPayment.checked == true && backTo == 3 && this.data['saveSend'] != "send") {	// this piece really isn't maintainable....
			// save mylist and handle creation of amazon payment recipient account
				if (login == null) {	// again, not maintainable
					// pass reference to this object so that continue method can be invoked
					login = new HJ.Login(this, "true");
					login.startStep1();
					return false;
			}
			this.nextStep = backTo;
				
			this.processPaymentRequest(true);
		}
		else {
			this.selectedStep = backTo;
			this.loadTemplate();
		}
		
        if(backTo == 1 || backTo == 2)
        {
            this.loadListIcon();
            this.loadListAttachment();

        }
		if (!event) var event = window.event;
		if (event) {
			YAHOO.util.Event.stopEvent(event);
		}
		return false;
	},

	goCancel:function(event) {
		//this.doCancelConfirmation();
		//this.cleanUp();
		this.loadSIHP();
		if (!event) var event = window.event;
		if (event) {
			YAHOO.util.Event.stopEvent(event);
		}
		return false;
	},

	goSend:function() {
		this.goSave('send');
		return false;

	},

	doCancelConfirmation: function() {
		if(this.showCancelDialog==null){
			var handler1 = {
				templateLoaded: function() {
					this.parent.goCancelConfirmationLoad();
			},
				parent:this
			}
			this.showCancelDialog =
                  new Af.HtmlDialog("Sure you want to cancel?", handler1, null);
			this.showCancelDialog.width = "320px";
		}
		this.showCancelDialog.showHTMLTemplate( basePageURL +
                         "cancelMessage.htm", "MainArea", "cancelConfirmation");
		this.showCancelDialog.centerDialog(350, 350);
	},

	goCancelConfirmationLoad: function() {
		this.save = document.getElementById('save');
		this.save.onclick = this.goSave.bind(this);
		this.dontSave = document.getElementById('dontSave');
		this.dontSave.onclick = this.cleanUp.bind(this);
	},

	validateUI:function() {
		var listFields = this.listFields;
		// Email
		var emailString = this.data['lastEmailString'];

		if (emailString!=null && emailString!='') {
			var emails = this.data['lastEmailString'].split(',');
			if (emails.length == 1) {
				emails = emails[0].split(';');
			}
			
			for (var i=0; i<emails.length; i++) {
				var email = trim(emails[i]);

				if(email == "null")
					continue;
				
				if (email!='' && !this.emailValidator.validateEmail(email)) {
					showMessageDialog(emails[i], 'Invalid Email Address',
                                    300, 100);
					return;
				}
			}
			this.data['lastEmailString'] = this.emailValidator.extractEmailAddressList(this.data['lastEmailString']);

		} else {
			var items = this.data['item'];
			var helperExists = false;
			if (items != null) {
				for (var i=0; i<items.length; i++) {
					if (items[i].helperId != null && items[i].helperId != '') {
						helperExists = true;
						break;
					}
				}
			}
			if (!helperExists) {
				showMessageDialog("Please enter at least one email address to send to.",
                            'No Email Addresses', 300, 100);
				return;
			}
			return false;
		}

		//  Check through the fields
		var flag = false;
		for (var i=0; i<listFields.length; i++) {
			var listField = listFields[i];
			if (this.data[listField]==null || this.data[listField]=='' ||
                            this.data[listField]==undefined) {
				// Disabling this check for now
				// It doesn't seem right to prompt users
				// if they don't fill out optional fields
				// and there is no current mechanism to mark fields
				// as required or optional
				//flag = true;
				flag = flag;
			}
		}
		if (this.data['item']==null) {
			flag = true;
		}

		if (flag) {
			this.verificationConfirmation();
			return;
		}

		//  Anythign but SimpleList. This list might expand as more
        //  shared lists are introduced..
		//  Non Sign-Ups do not need this because originators won't have to
        //  sign-up and sent lists are automatically saved.
		if (this.templateType != 'SimpleList') {
			this.data['lastEmailString'] = emailString;
		}

		this.saveMyList('send');
	},

	verificationConfirmation: function() {
		if(this.verificationDialog==null){
			var handler1 = {
				templateLoaded: function() {
					this.parent.verificationConfirmationLoad();
			},
				parent:this
			}
			this.verificationDialog =
                    new Af.HtmlDialog("Missing Fields", handler1, null);
			this.verificationDialog.width = "320px";
		}
			this.verificationDialog.showHTMLTemplate(
                    basePageURL + "verificationMessage.htm",
                    "MainArea", "cancelConfirmation");
			this.verificationDialog.centerDialog(350, 350);
	},

	verificationConfirmationLoad: function() {
		this.sendAnyway = document.getElementById('sendAnyway');
		//  Not good..  find functions that already exit..
		this.sendAnyway.onclick = this.sendWithError.bind(this);
		this.reCheck = document.getElementById('reCheck');
		this.reCheck.onclick = this.reCheckError.bind(this);
	},


	// No
	sendWithError:function() {
		if (this.verificationDialog!=null) {
			this.verificationDialog.close();
		}
		this.saveMyList('send');
	},
	// Yes
	reCheckError:function() {
		if (this.verificationDialog!=null) {
			this.verificationDialog.close();
		}
	},
	
	updateMyListItemHelper: function (helper, helperId, UUID) {
		//alert(helper + " " + helperId + " " + UUID);
		showModalMessageDialog("Processing ... please wait", 300, 40);
        //do this as a get request since we are only passing a couple of parameters
		var items = this.data['item'];
		var item = null;
		for (var i=0; i<items.length; i++) {
			if (items[i].UUID == UUID) {
				item = items[i];
				break;
			}
		}
		if (item == null) {
			hideModalMessageDialog();
			return false;
		}
		item.helper = helper;
		item.helperId = helperId;
		this.saveMyListItem(item);
	},
	
	saveMyListItem: function(item) {
        req = new Af.DataRequest(svcURL,
                  this.requestMyListItemCompletedCommon.bind(this),
                  this.requestFailedCommon.bind(this), null,
                  this.requestTimedoutCommon.bind(this));
      	req.addService("WorkspaceService", "saveMyListItem");
      	req.addParameter("myListUUID", this.data.UUID);
      	var s = this.getXMLFromItem(item);
		req.xmlDoc = s;
      	ajaxEngine.processRequest(req);
	},

	savePublishedTemplate: function (title, description, UUID, categories, metaTitle, metaDescription, metaKeywords) {
		//alert(helper + " " + helperId + " " + UUID);
		showModalMessageDialog("Processing ... please wait", 300, 40);
        req = new Af.DataRequest(svcURL,
                  this.requestPublishMyListCompletedCommon.bind(this),
                  this.requestFailedCommon.bind(this), null,
                  this.requestTimedoutCommon.bind(this));
        //do this as a get request since we are only passing a couple of parameters
      	req.addService("WorkspaceService", "publishMyList");
		req.addParameter("UUID", UUID);
		//var encodeTitle = xmlEncode(title);
		//req.addParameter("title", encodeTitle);
		//var encodeDesc = xmlEncode(description)
		//req.addParameter("description", encodeDesc);

		var message = "<message>";
		message += "<metaTitle>" + xmlEncode(metaTitle) + "</metaTitle>";
		message += "<metaDescription>" + xmlEncode(metaDescription) + "</metaDescription>";
		message += "<metaKeywords>" + xmlEncode(metaKeywords) + "</metaKeywords>";
		message += "<title>" + xmlEncode(title) + "</title>";
		message += "<description>" + xmlEncode(description) + "</description>";
  	 	message += categories;
	  	message += "</message>";
	  	req.xmlDoc = message;



      	ajaxEngine.processRequest(req);
	},

	saveMyList: function(saveSend, processingPaymentRequest) {
	this.hideAfterLoad = false;
      	showModalMessageDialog("Processing ... please wait", 300, 40);
	  var list = this.data;
	  
	  if (processingPaymentRequest != null && processingPaymentRequest == true) {
		  saveSend = 'save';
	  } else {
		  processingPaymentRequest = false;
	  }
	  list['saveSend'] = saveSend;

	  var items = this.data['item'];
	  var listFields = this.listFields;

	  var req = null;
      if (saveSend == 'saveCopy') {
      	saveSend = 'save';
      	list['saveSend'] = 'save';
        req = new Af.DataRequest(svcURL,
                this.requestMyListSaveCopy.bind(this),
                this.requestFailedCommon.bind(this), null,
                this.requestTimedoutCommon.bind(this));
      } else if (saveSend == 'saveImplicit') {
    	saveSend = 'save';
    	list['saveSend'] = 'save';
        req = new Af.DataRequest(svcURL,
                  this.requestMyListSaveImplicit.bind(this),
                  this.requestFailedCommon.bind(this), null,
                  this.requestTimedoutCommon.bind(this));
      } else if (saveSend == 'saveImplicitIcon') {
    	saveSend = 'save';
    	list['saveSend'] = 'save';
        req = new Af.DataRequest(svcURL,
                  this.uploadIconDialog.requestMyListSaveImplicitIcon.bind(this.uploadIconDialog),
                  this.requestFailedCommon.bind(this), null,
                  this.requestTimedoutCommon.bind(this));
      } else if (saveSend == 'saveImplicitAttachment') {
    	saveSend = 'save';
    	list['saveSend'] = 'save';
        req = new Af.DataRequest(svcURL,
                  this.uploadAttachmentDialog.requestMyListSaveImplicitAttachment.bind(this.uploadAttachmentDialog),
                  this.requestFailedCommon.bind(this), null,
                  this.requestTimedoutCommon.bind(this));
      } else if (processingPaymentRequest) {
      	list['saveSend'] = 'save';
        req = new Af.DataRequest(svcURL,
                  this.myListPaymentRequestCompleted.bind(this),
                  this.myListPaymentRequestFailed.bind(this), null,
                  this.requestTimedoutCommon.bind(this)); 
      } else {
        req = new Af.DataRequest(svcURL,
                  this.requestMyListCompletedCommon.bind(this),
                  this.requestFailedCommon.bind(this), null,
                  this.requestTimedoutCommon.bind(this));
      }

	  var s="<message>";
	  s += "<myListName>" + xmlEncode(list['name']) + "</myListName>";
	  s += "<templateType>" + this.templateType + "</templateType>";
	  s += "<saveSend>" + list['saveSend'] + "</saveSend>";

      req.addService("WorkspaceService", "saveMyList");

      if (list.UUID != null) {
         req.addParameter("UUID", list.UUID);
      } else if (this.implicitListId != null) {
         req.addParameter("UUID", this.implicitListId);
      } else {
      	req.addParameter("UUID", "58d67de8:12e50bb53fb:-7ffc");      
      }

	  this.data['lastEmailString'] = this.emailValidator.extractEmailAddressList(this.data['lastEmailString']);
	  for (var i=0; i<listFields.length; i++) {
	  	var listField = listFields[i];
	  	if (list[listField]!=null && list[listField]!=undefined) {
	  			s += "<"+ listField +">" + xmlEncode(list[listField])
                  + "</"+ listField +">" ;
	  	} else {
	  			s += "<"+ listField +">" + '' + "</"+ listField +">" ;
	  	}
	  }

	  if (items!=null) {
		for (var j=0; j<items.length; j++) {
			var item = items[j];
			s += this.getXMLFromItem(item);
		}
	  }
	  
	  s += "</message>";

	  req.xmlDoc = s;
      this.saveObj = list;
      ajaxEngine.processRequest(req);

   },

   requestMyListSaveCopy: function(response) {
	   hideModalMessageDialog();
  	   GATrackAction("successful_copy_"+copyFromList.templateType+"::"+this.saveObj.name+"_published_template");
  	   GATrackAction("successful_copy_published_template");
	   // refresh the archive
	   app.SIHP.archive.fetchArchive();
	},
   
   requestMyListSaveImplicit: function (response) {
      //alert(this.implicitListId);
      //
      // 2011-08-18 kee: fix attachment failed
      if (this.saveObj.UUID == null) {
	 var resp = response.responseText.split(";");
         this.saveObj.UUID = resp[0];
	 //get item's uuid to avoid creating new item again during send
	 if (resp.length > 1)
	 {
		for(var i = 1 ; i < resp.length; i++)
		{
			var str = resp[i];
			this.data['item'][i-1].UUID = resp[i];
		}
	 }
      }
      
      this.implicitListId = this.saveObj.UUID;
      if (this.uploadResponseIFrame != null) {       
	      // Will work for IE7 and Firefox..  must test on Macs and other browsers..
	      /Firefox[\/\s](\d+\.\d+)/.test(navigator.userAgent) ? 
	      	this.uploadResponseIFrame.onload =
	                    this.uploadResponse.bindAsEventListener(this):
	      	this.uploadResponseIFrame.onreadystatechange =
	                    this.uploadIE.bindAsEventListener(this);	
	      	
	      
	      this.sendFileForm.action= "/rose/upload?MyListId=" + this.implicitListId;
	      this.sendFileForm.submit();
      }
	  hideModalMessageDialog();
   },

   requestMyListCompletedCommon: function(response) {
	   hideModalMessageDialog();

      if (this.saveObj.UUID == null) {
	 var resp = response.responseText.split(";");
         this.saveObj.UUID = resp[0];
	 //get item's uuid to avoid creating new item again during send
	 if (resp.length > 1)
	 {
		for(var i = 1 ; i < resp.length; i++)
		{
			var str = resp[i];
			this.data['item'][i-1].UUID = resp[i];
		}
	 }
      }
	  if (this.saveObj['saveSend'] == 'save'){
		if (this.saveSilently == undefined || !this.saveSilently) {
			showMessageDialog("You've successfully saved your work!",
                        'Saved', 300, 100);
		}
		this.saveSilently = false; // reset the flag

		if (this.selectedStep == 4) {
			this.loadSIHP();
			return false;
		}
      	
      	if (this.isUpdatedAfterSend) {
      		showMessageDialog("This sign-up sheet has been updated. An email has been sent to only those people who's item or time/slot was changed or eliminated", 
      						 "Saved", 300, 100);
      		// go to home page
      		app.db.handleHomeTabClick();
      	}
		return false;

	  } else {
      	//  Change this with confirmation landing page..
      	//   showMessageDialog("You've successfully Sent your work!", 'Sent', 300, 100);
      	this.selectedStep = 5;

      	// Notify google analytics of successful completion
      	GATrackAction("successful_"+this.templateType+"_send");

      	this.loadTemplate();
	  }
   },

   requestMyListItemCompletedCommon: function(response) {
	  hideModalMessageDialog();
	  return false;
   },

   requestPublishMyListCompletedCommon: function(response) {
	  hideModalMessageDialog();
	  return false;
   },

   requestFailedCommon: function(dataRequest, msg) {
	  hideModalMessageDialog();
      hideDialogWin();
      showMessageDialog("We are currently unable to save this record. Please try again.<br/><br/>Error message: " + msg, "Excuse us!", 400, 150);
   },
   
   requestHelpSaveFailed: function(dataRequest, msg) {
	  hideModalMessageDialog();
      hideDialogWin();
      showMessageDialog(msg, "Excuse us!", 400, 150);
   },

   requestTimedoutCommon: function(dataRequest) {
	  hideModalMessageDialog();
      hideDialogWin();
      showMessageDialog("We are currently unable to save this record. Please try again.", "Excuse us!", 400, 150);
   },

	getRepeatNumber:function(dayNumber) {
		//  dayNumber convention 0=Sunday, 1=Monday, etc..
		var n = 0;
		n = n | (1 << dayNumber);
	    return n;
	},

	//  Here to end, copied from Original HELP.js.
    //  All Signup(helper) processing..
	doSave: function(sendReminder) {
      var xml = "<HELPResult>";

      xml += "<MyList class=\"MyList\" UUID=\"" + this.data["UUID"] + "\">";

      var dl = this.data["item"];

      for (var i=0; i<dl.length; i++) {
          var item = dl[i];
          xml += "<item class=\"MyListItem\" UUID=\"" + item["UUID"] + "\">";
          
          xml += "<property name=\"lastUpdateDate\" value=\""+item["lastUpdateDate"] + "\" />";

          var helperName = item["helper"];
          if (helperName ==  null || helperName == 'Drivers Sign Up Here') {
        	  helperName = "";
          } else {
        	  helperName = xmlEncode(helperName);
	      }
		  xml += "<property name=\"helper\"" + " value=\"" + helperName + "\" />";

          var notes = item['notes'];
          if (notes == null || notes == 'Drivers Write Notes Here') {
          	notes = '';
          } else {
          	notes = xmlEncode(notes);
          }
		  xml += "<property name=\"notes\"" + " value=\"" + notes + "\" />";

	  if(helperName != '')
	  {
		  var email = item['helperEmail'];
		  if (email == null || email == 'undefined') {
			email = '';
		  } else {
			email = xmlEncode(email);
		  }
		  xml += "<property name=\"helperEmail\"" + " value=\"" + email + "\" />";
	  }
	  else
	  {
		  xml += "<property name=\"helperEmail\"" + " value=\"\" />";

	  }

          var helperId = item['helperId'];
          if (helperId == null || helperId == '' || helperId == 'undefined') {
          	helperId = '';
          	if (helperName != null && helperName != '') {
          		helperId = this.data["helperEmail"];
          		item.helperId = helperId;
          	}
          }
		  xml += "<property name=\"helperId\"" + " value=\""
                  + helperId + "\" />";

          var helperEventId = item['helperEventId'];
          if (helperEventId == null || helperEventId == 'undefined') {
          	helperEventId = '';
          } else {
          	helperEventId = xmlEncode(helperEventId);
          }
		  xml += "<property name=\"helperEventId\"" + " value=\""
                  + helperEventId + "\" />";

		  xml += "</item>";
      }

      xml += "</MyList>";


      xml += "<idOfUser>" + this.data["idOfUser"] + "</idOfUser>";
      xml += "<idOfHelper>" + this.data["helperID"] + "</idOfHelper>";
      xml += "<helperEmail>" + this.data["helperEmail"] + "</helperEmail>";

      xml += "</HELPResult>";
	  this.xml = xml;
      this.saveUrl = svcURL;
	  this.saveHelperList(sendReminder);
    },
	doSaveHelpResult: function() {
		this.isHelpSaved = true;
		if(!this.reminder.checked) {
			this.openConfirmDialog();
		} else {
			this.doSendReminder();
		}
	},

	openConfirmDialog: function() {
		 if (this.confDialog == null) {
            var handler = {
               templateLoaded: function() {
                  this.parent.confirmDialogLoaded();
               },
				parent:this
            }
            this.confDialog = new Af.HtmlDialog("Thank you for your help!",
                            handler, null);
            this.confDialog.width = "300px";
         }
         this.confDialog.showHTMLTemplate(basePageURL + "ConfirmDialog.htm",
                         "MainArea", "confirmHTMLDailog");
		 this.confDialog.centerDialog(350, 350);
	},
	
	confirmDialogLoaded: function() {
		this.messageText = document.getElementById("messageText");
		this.send = document.getElementById("sendButton");
		this.dontSend = document.getElementById("dontSendButton");
		this.send.onclick = this.doSend.bind(this);
		this.dontSend.onclick = this.doDontSend.bind(this);

		this.messageText.innerHTML =
           "Would you like to have a reminder of your sign-up emailed to you ?";
	},
	
	doSend: function() {
		 this.confDialog.hide();
		 this.doSendReminder();
	},
	
	doDontSend: function() {
		 this.confDialog.hide();
		 this.saveHelperList();	// save only result
                    // so nedd to call method thich is able to save result
	},

	saveHelperList: function(sendReminder) {
		showModalMessageDialog("Processing your request... please wait",
                        300, 40);
		 var req = new Af.DataRequest(this.saveUrl,
			this.requestHelpSaveCompleted.bind(this),
            this.requestHelpSaveFailed.bind(this), null,
            this.requestTimedoutCommon.bind(this));
	   req.addService("PublicService", "saveHelpResult");
	   if (sendReminder == null) {
		   req.addParameter("isSendReminder", "Yes");
	   } else {
		   req.addParameter("isSendReminder", sendReminder);
	   }
	   req.addParameter("helperID", this.data["helperID"]);
	   req.addParameter("helperEmail", this.data["helperEmail"]);
	   req.addParameter("listUUID", this.data["UUID"]);

	   req.xmlDoc = this.xml;
	   ajaxEngine.processRequest(req);
	},

    requestHelpSaveCompleted: function(response) {
		GATrackAction("helper_signed_up_for_"+this.templateType);
		
		this.listObj.helperID = response.responseText;
		if (this.data['latestPaymentRequest'] != null && 
			this.helperNextStepButton != null) {
			this.selectedStep = this.TEMPLATE_STEP_PAYMENT_ATTEMPT;
		} else {
			this.selectedStep = 6;
		}
		
		this.loadTemplate();
    },

	doOpenHomePage: function() {
		window.location.href ="index.htm";
	},

	reminderDialog: function() {
		 if (this.rmndrDialog == null) {
            var handler = {
               templateLoaded: function() {
                  this.parent.confirmRMNDRDialogLoaded();
               },
				parent:this
            }
            this.rmndrDialog = new Af.HtmlDialog("Request", handler, null);
            this.rmndrDialog.width = "350px";
         }
         this.rmndrDialog.showHTMLTemplate(basePageURL +
                      "SignUpRmdrDialog.htm", "MainArea", "confirmHTMLDailog");
		 this.rmndrDialog.centerDialog(350, 350);
	},
	confirmRMNDRDialogLoaded: function() {
		this.messageText = document.getElementById("messageText");
		this.noSignUp = document.getElementById("noSignUp");
		this.returnToSignUp = document.getElementById("returnToSignUp");
		this.noSignUp.onclick = this.noSignUpNow.bind(this);
		this.returnToSignUp.onclick = this.returnToSignUpNow.bind(this);

	},
	noSignUpNow: function() {
		 this.rmndrDialog.hide();
		 //this.doSaveHelpResult();
		 this.doOpenHomePage();
	},
	returnToSignUpNow: function() {
		 this.rmndrDialog.hide();
	},

	continueAfterLoginOrRegistration: function() {
		//  Must load step 1 to get frame..
		//  consequent, saved spot loading takes place in TemplateLoaded
		showModalMessageDialog("Processing your request... please wait",
                300, 40);
		this.exitStep = this.selectedStep;
		this.selectedStep = 1;
        this.loadTemplate();
	},

	loadSavedStep:function(tempStep) {
		this.selectedStep = tempStep;
		this.loadTemplate();
	},


	//////////////////  Template MINI CAL FUNCTIONS //////////////////////
	//
	// input element must have immediate parent Element
	// If MiniCal has calendar image, input element must be sibling of
    // target input element with no other siblings in the parentElement
	// This should be abstracted
	///////////////////////////////////////

	onTimeout:function() {
		this.timerSet = false;
	},

	showMiniCal:function(evt) {
	   	var e = evt.target ? evt.target : evt.srcElement;
	   	var parentDiv = e.parentNode;

	   	if (this.miniCalendar != null) {
            // avoid showing multiple mini calendars at once
	   		return false;
	   	}

	   	// Ignore clicks that occur within timeout interval.
	   	// They are due to event bubbling up through
	   	// element hierarchy.
	    this.timerSet = true;
	    setTimeout(this.onTimeout.bind(this), 10);

	   	//  Creates mini Cal Container
	    this.littleBox = document.createElement('span');
	    this.littleBox.id = "miniCalBox";
	    this.littleBox.className = 'miniCalList';
	    this.mouseClickInMiniCalendar = false;
	    this.littleBox.onclick = this.ignoreClick.bind(this);
	    document.onclick = this.removeMiniCal.bind(this);

		//  creates elements that are needed by the MiniCalendar class.
	    this.littleBox.innerHTML = this.miniTableElement;

	   	parentDiv.appendChild(this.littleBox);
		this.miniClose = document.getElementById("miniClose");
		this.miniClose.onclick = this.removeMiniCal.bind(this);

	  	this.miniCalendar = new HJ.MiniCalendar(true);
	  	this.miniCalendar.listener = this;
	  	this.miniCalendar.render(this.sc, this.date);

	 	// Lock the field so they're not able to edit
        // while the calendar is present
	 	this.selectedInput = parentDiv.getElementsByTagName('input')[0];
	 	this.selectedInput.disabled = 'disabled';
	 	this.selectedDateDiv = parentDiv;
		this.selectedInput.onclick =
                this.removeMiniCal.bindAsEventListener(this);
	 	this.disabledInput = this.selectedInput;
	 	return false;
	},

	selectHelper:function(evt) {
		if (login == null){
			// Only applicable to "organizer view", step 2
			if (this.selectedStep == 2){
				showMessageDialog("To use this feature, you must be logged in first", "Not Logged In", 250, 100, this.goToSignInWithoutDialog.bind(this));
				this.selectHelperDisplayed = true; // fake out the code below
				return false;
			}
			return false;
		}
		
		if (this.selectHelperDisplayed || app == null || login == null) {
			// stop multiple dialogs from being shown
			return false;
		}
		this.selectHelperDisplayed = true;

	   	this.targetHelperElement = evt.target ? evt.target : evt.srcElement;

	   	// Ignore clicks that occur within timeout interval.
	   	// They are due to event bubbling up through
	   	// element hierarchy.
	    this.timerSet = true;
	    setTimeout(this.onTimeout.bind(this), 10);
	   	this.selectHelperObj = new HJ.SelectHelper(this);
	   	this.selectHelperObj.loadTemplate();
	 	return false;
	},
	goToSignInWithoutDialog:function(evt){
		hideDialogWin();
		hideModalMessageDialog();
		login = new HJ.Login(this, "true", false);
		login.startStep1();
	},
    modifyHelper: function(evt, selectedVal, selectedDisplayText, selectedEmail) {
        this.targetHelperElement.value = selectedDisplayText;
        var divNode = this.targetHelperElement.parentNode;
        var nextNode = divNode.nextSibling;
        var UUID = null;
        var helperIdNode = null;
	
	//get item list's index corresponds to this div
	var itemIdx = -1;
	var itemIdNode = divNode.parentNode;
	var itemNodeId = itemIdNode.getAttribute('id');
	var _match = itemNodeId.match(/^(signupDiv|item)_/);
	if(_match != "" && _match != 'undefined' && _match != null) 
	{
		var _idx = parseInt(itemNodeId.replace(/^(signupDiv|item)_/, ''));
		if(_idx != null && _idx >= 0)
		{
			itemIdx = _idx;
			var item = this.data['item'][itemIdx];
			item.helperEmail = selectedEmail;
            item.helper = selectedDisplayText, 
            item.helperId = selectedVal;
		}
		
	}

        while(nextNode != null) {
	        if(nextNode.className == "helperId") {
		        helperIdNode = nextNode.childNodes[0];
		        helperIdNode.value = selectedVal;
	        }
	        if (nextNode.className == "listItemUUID") {
		        UUID = nextNode.childNodes[0].value;
			}
			//don't need helperEventId since we are changing helpers unless later
			//we need it to delete the old one 
		    nextNode = nextNode.nextSibling;
        	
        }
 
 		
		if (this.templateType != HJ.TEMPLATE_TYPE_COLLECT_INFORMATION) {
         

            if (this.data.saveSend=='send' && this.selectedStep == 4) {
                //this.saveMyList('send');
                this.updateMyListItemHelper(selectedDisplayText, helperIdNode.value, UUID);        	
            }
        }
    },

    publishTemplate: function(evt, title, description, UUID, categories, metaTitle, metaDescription, metaKeywords) {
		this.savePublishedTemplate(title, description, UUID, categories, metaTitle, metaDescription, metaKeywords);
    },

	closeSelectHelperDialog: function() {
		this.selectHelperDisplayed = false;
		return false;
	},
	closePublishMyListDialog: function() {
		this.publishMyListDisplayed = false;
		return false;
	},

	ignoreClick:function(evt) {
		// called if the user clicks within mini-calendar element
		return false; // stop event propagation so that removeMiniCal
                      //method is not called.
	},

	removeMiniCal:function(evt) {

	   	if (this.timerSet) {
	   		return false;
	   	}

	   	document.onclick = null;

		this.dateDisabledOff();
		var miniCal = document.getElementById('miniCalBox');

		//  If miniCal already exists, remove
		if (miniCal!=null) {
			miniCal.parentNode.removeChild(miniCal);
		}
	 	this.miniCalendar = null;
	 	return false;
   },

   dateDisabledOff:function() {
	if (this.disabledInput != null) {
		this.disabledInput.disabled = false;
	}
   },

   //  Called from Base Calendar to handle mini calendar event
   dateClicked: function (obj, dt) {
		this.dateDisabledOff();
		this.showDate(dt);
		return this.removeMiniCal();
   },

   showDate:function (dt) {
   	var thisRow = this.currentRow;

   	var displayDate =
            (dt.getMonth()+1) + '/' + dt.getDate() + '/' + dt.getFullYear();
   	this.selectedInput.value = displayDate;

   },
	///////////////  End Template MINI CAL FUnctions  //////////////////////

	showToolTip: function(evt) {
		var e = evt.target ? evt.target : evt.srcElement;

		var tipIndex = e.id;

		var dispMsg = this.toolTipTexts[tipIndex];

		javascript:Tip(dispMsg, SHADOW, true, TITLE, '', PADDING, 9 ,FONTSIZE, '8pt', SHADOWCOLOR, '#dd99aa', BGCOLOR, '#FF9A47', BORDERCOLOR, '#fff', WIDTH, 200, TITLEBGCOLOR, '#ADD57C');
		return;
	},

	eraseDefaultField: function(event) {

		Event.element(event).className = 'dark';
		//this.signupNameFieldElement.className = 'dark';
	},


	processSignupNameFieldKeyPress: function(event) {
		Event.extend(event);
	   	if (event.keyCode == Event.KEY_RETURN) {
	   		var item0 = document.getElementById('item0');
	   		if (item0 == null) {
	   			this.addItem();
	   		}
	   	  	Event.stop(event);
	    }
	},

	processItemFieldKeyPress: function(event) {
		Event.extend(event);
		
	   	if (event.keyCode == Event.KEY_RETURN) {
	   		this.processAddItemEvent(event);
	   	  	Event.stop(event);
	    }

	},
	
	processAddItemEvent: function(event) {
		Event.extend(event);
		
   		var itemNum = null;
   		var target = event.target ? event.target : event.srcElement;

   		if (target != null) {
   			var ancestor = this.getItemDivAncestor(target);
   			if (ancestor != null) {
				itemNum = parseInt(ancestor.id.substring(5));
				this.saveHoldData(); // save data entered in HTML elements
				
				// shift items held in data object by 1
				var itemData = this.data['item'];
				for (var i=itemData.length; i>itemNum; i--) {
					itemData[i] = itemData[i-1];
				}
				this.data['item'][i+1] = new Object();
				this.addItem(null, (itemNum+1)); // template-specific function that adds an item AT position itemNum+1
				return false;
   			}
   		}
   		return false;
	},
	
	addItemElementToDisplay: function(itemDiv, index) {
		var currentElemAtPosition = document.getElementById("item_"+index);
		if (this.listContainer.childNodes.length > 0) { // there are one or more items displayed
			// change id of item elements below the inserted item
			var len = this.listContainer.childNodes.length;
			for (var i=len-1; i>=index; i--){
				var itemElem = document.getElementById("item_"+i);
				itemElem.id = "item_"+(i+1);
			}
		}
		this.listContainer.insertBefore(itemDiv, currentElemAtPosition);

		
		// 2011-05-12 kee: snack duty/recurring event select helper popup issue
		//if (this.templateType != HJ.TEMPLATE_TYPE_SNACK_DUTY) {
		//	this.shiftFocusToTextChild(itemDiv);
		//}

	},
	
	//  Delete row, triggered by circle in the row Div
	deleteItem:function (evt) {
		var e = evt.target ? evt.target : evt.srcElement;
		var deleteDiv = this.getItemDivAncestor(e);
		var index = deleteDiv.id.match(/[\d\.]+/g)[0];
		this.listContainer.removeChild(deleteDiv);		
		
		for(var i = parseInt(index)+1; i<this.itemCount; i++) {			
			var renameDiv = document.getElementById('item_'+i);			
			renameDiv.id = 'item_' + (i-1);	
		}
		this.itemCount--;
		this.itemCount==0 ? this.addItem('first') : null;
	
		return false;
	},

	getItemDivAncestor: function(element) {
   		if (element != null) {
			if (element.id.indexOf('item_') == 0) {
				return element;
			} else {
				return this.getItemDivAncestor(element.parentNode);
			}
   		}
   		return null;
	},
	
	shiftFocusToTextChild: function(element) {
		var node_list = element.getElementsByTagName('input');
		if (node_list != null && node_list.length>0) {
			for (var i=0; i<node_list.length; i++) {
				if (node_list[i].getAttribute('type')=="text") {
					node_list[i].focus();
					break;
				}
			}
		}
	},

	setCurrentStepInYUIHistoryMgr: function(step, calledFromBackButtonPressHandler) {
		try {
			var templateStep = "template"+step;
			if (app) {
				app.setCurrentTabInYUIHistoryMgr(templateStep, true);
			}
		} catch (ex) {
			// noop
		}
	},
	
	timeChanged:function(tdd, newValue, ov) {
      if (tdd == this.fromTime) {
         var newValue = parseInt(newValue);
         var ov = parseInt(ov);
         var tt = parseInt(this.toTime.getValue());
         var tt = newValue + (tt - ov);
         if (tt >= 1440) {
           tt = tt - 1440; // next day
         } else if (tt < 0) {
            tt = 1440 + tt;
         }
       }
   },
   
	getXMLFromItem: function(item) {
	   if (item == null) {
		   return "<item> <uuid> </uuid> </item>";
	   }
	   var s = "";
	   s += "<item>";
	   if(item.UUID != null && item.UUID != "" && item.UUID != undefined) {	
		   s += "<uuid>" + item.UUID + "</uuid>";
	   } else {
		   s += "<uuid> </uuid>";
	   }
	   if (item.helperId == null || item.helperId == '') {
		   item.helper = '';
		   item.helperEmail = '';
	   }
	   for (var i=0; i<this.listItemFields.length; i++) {
		   var listItemField = this.listItemFields[i];
		   s += "<"+ listItemField +">" + xmlEncode(item[listItemField]) +
		   		"</"+ listItemField +">";
	   }
	   s += "</item>";
	   return s;
   },
   
   displayAskMoreHelpersDialog: function() {
	   var askMoreHelpersDialog = new HJ.AskMoreHelpersDialog(this);
	   askMoreHelpersDialog.loadTemplate();
	   return false;
   },

   displayContactVolunteersDialog: function() {
	   var contactVolunteersDialog = new HJ.ContactVolunteersDialog(this);
	   contactVolunteersDialog.setMyListUUID(this.data['UUID']);
	   contactVolunteersDialog.setMyItems(this.data['item']);
	   contactVolunteersDialog.setItemHeader(this.data['col1Name'], this.data['col2Name']);
	   contactVolunteersDialog.setEventName(this.data['name']);
	   contactVolunteersDialog.loadTemplate();
	   return false;
   },

   displayPublicLink: function() {
	   var publicLinkDialog = new HJ.PublicLinkDialog(this);
	   publicLinkDialog.setMyListUUID(this.data['UUID']);
	   publicLinkDialog.loadTemplate();
	   return false;
   },

	addAttachment: function(attch, index) {
		if (index == null) {
			attch = null;
			if (this.data['attach'] != null)
				index = this.data['attach'].length;
			else
				index = 0;
		}
		var attachDiv = document.createElement('div');
		attachDiv.innerHTML = this.attachDiv;
		attachDiv.className = "attachCont";
		attachDiv.id = "attach" + index;
		var attachField = attachDiv.getElementsByTagName('input');
		var attachDelete = attachDiv.getElementsByTagName('a')[0];
		if (attch != null)
			attachField[0].value = attch['attachItem'];
		// attachDelete.id = 'delete' + index;
		// attachDelete.onclick = this.deleteAttachment.bindAsEventListener(this);
		// this.attachmentListContainer.appendChild(attachDiv);
		
		return false;
	},
	
	addAttachmentBlockClicked: function(event) {
       if ((this.listObj == null || this.listObj.UUID == null)
                       && this.implicitListId == null) {
           if (this.data['name'] == null)
               this.data['name'] = "";
           //return;
       }
       this.addAttachmentBlock.style.display = 'none';

       this.attachmentUploadBlock =
               document.getElementById('attachmentUploadBlock');
       this.attachmentUploadBlock.style.display = 'block';

		return false;
	},

	uploadIE:function(event) {
		if(this.uploadResponseIFrame.readyState=="complete"){
			this.uploadResponse(event);
		}
		return false;
	},

	sendFileClicked: function(event) {
        if (this.listObj == null || this.listObj.UUID == null) {
            this.saveMyList('saveImplicit');
        } else {
            this.uploadResponseIFrame.onload =
                    this.uploadResponse.bindAsEventListener(this);
            this.sendFileForm.action= "/rose/upload?MyListId="
                    + this.listObj.UUID;
            this.sendFileForm.submit();
        }
        return false;
	},

    uploadResponse: function(event) {
		
        this.uploadResponseIFrame.contentDocument ?
        this.lastServerAttachmentResponse =
            this.uploadResponseIFrame.contentDocument.documentElement.innerHTML:
        this.lastServerAttachmentResponse =
            this.uploadResponseIFrame.contentWindow.document.
                                        documentElement.innerHTML;
                
        // Veeru: replicating from loadStep1
        //

        this.addAttachmentBlock.style.display = 'none';
        this.attachmentUploadBlock.style.display = 'none';

        this.attachmentListContainer 
            = document.getElementById('attachmentListItems');
        this.attachmentListContainer.style.display = 'block';

        // list of attachments
        var listUUID = null;
        if (this.listObj != null) {
            listUUID = this.listObj.UUID;
        } else if (this.implicitListId != null) { // must hv done 'saveImplicit'
            listUUID = this.implicitListId;
        } else if (this.implicitIconListId != null) { // must hv done 'saveImplicit'
            listUUID = this.implicitIconListId;
        }

        this.attachments = new HJ.Attachments(
            this.attachmentListContainer, 
            null,
            this.ATTACHMENT_ROWS, 
            listUUID,
            this.addAttachmentBlock);
        this.attachments.fetchAttachments(true);

        this.uploadResponseIFrame.onload = null;
        return consumeEvent(event);
	},
	
	deleteAttachment:function(evt) {
		var e = evt.target ? evt.target : evt.srcElement;
		var index = e.parentNode.id.substr(e['id'].length-1);
		var deleteDiv = documentElementById('attach' + index);
		this.attachmentListContainer.removeChild(deleteDiv);
        this.attachmentListContainer.style.display = 'none';
        this.addAttachmentBlock.style.display = 'block';
        this.attachmentUploadBlock.style.display = 'block';
	},
	
	//
	// Payment Request (by Organizer) related methods
	//
	
	calculatePaymentFees: function(evt) {
		var suggestedAmountStr = this.suggestedAmountElem.value;
		var suggestedAmount = 0.0;
		try {
			suggestedAmount = parseFloat(suggestedAmountStr);
		} catch (e) {
			document.getElementById("particpantAmountErrorText").innerHTML = "Invalid Amount";
			return false;
		}
		
		var processingFeesElem = document.getElementById("processingFeesSpan");
		var organizerAmountReceivedElem = document.getElementById('organizerAmountReceived');
		
		// clear any errors on the sister fields
		document.getElementById("organizerAmountErrorText").innerHTML = "";
		
		if (isNaN(suggestedAmount) || suggestedAmount == 0) {
			document.getElementById("particpantAmountErrorText").innerHTML = "Invalid Amount";
			processingFeesElem.innerHTML = "0.00";
			organizerAmountReceivedElem.value = "0.00";
			return false;
		}
		
		//	If the user enters a fee that is on the border of the two amazon fee rates,
		// there is an over-lap of possible recieved values. Because we offer 2-way
		// computation for amounts, we must avoide this boundery dispute
		//
		// For the current amazon model, the overlap occurs between 9.96 and 9.99
		var lBound = 9.96;
		var uBound = 9.99;
		if (suggestedAmount >= lBound && suggestedAmount <= uBound){
			document.getElementById("particpantAmountErrorText").innerHTML = "Values between " + lBound + " and " + uBound + " are not accepted";
			processingFeesElem.innerHTML = "0.00";
			organizerAmountReceivedElem.value = "0.00";
			return false;
		}
		
		if (suggestedAmount < this.minFee){
			document.getElementById("particpantAmountErrorText").innerHTML = "Values must be $" + this.minFee.toFixed(2) + " or more";
			processingFeesElem.innerHTML = "0.00";
			organizerAmountReceivedElem.value = "0.00";
			return false;
		}
		
		document.getElementById("particpantAmountErrorText").innerHTML = "";
		
		// Be sure to drop off excess digits BEFORE doing computations :-)
		suggestedAmount = Math.round(suggestedAmount * 100) / 100;
		var organizerAmount = this.getRecievedValue(suggestedAmount);
		
		// Apply the changes to the UI
		processingFeesElem.innerHTML = (suggestedAmount - organizerAmount).toFixed(2);
		organizerAmountReceivedElem.value = organizerAmount.toFixed(2);
		
		return false;
	},
	calculateRequiredPayment: function(evt) {
		var organizerAmountReceivedElem = document.getElementById('organizerAmountReceived');
		var organizerAmountReceivedStr = this.organizerAmountElem.value;
		var organizerAmountReceived = 0.0;
		
		try {
			organizerAmountReceived = parseFloat(organizerAmountReceivedStr);
		} catch (e) {
			document.getElementById("organizerAmountErrorText").innerHTML = "Invalid Amount";
			return false;
		}
		
		var suggestedAmountElem = document.getElementById("suggestedAmount");
		var processingFeesElem = document.getElementById("processingFeesSpan");
		
		// clear any errors on the sister fields
		document.getElementById("particpantAmountErrorText").innerHTML = "";
		
		if (isNaN(organizerAmountReceived) || organizerAmountReceived == 0) {
			document.getElementById("organizerAmountErrorText").innerHTML = "Invalid Amount";
			processingFeesElem.innerHTML = "0.00";
			suggestedAmountElem.value = "0.00";
			return false;
		}
		// clear out any error message
		document.getElementById("organizerAmountErrorText").innerHTML = "";
		
		// Be sure to drop off excess digits BEFORE doing computations :-)
		organizerAmountReceived = Math.round(organizerAmountReceived * 100) / 100;
		var collectedApprox = this.getApproximateCollectedValue(organizerAmountReceived);
		
		// start at the upper bound of the error and work down;
		collectedApprox += 0.02;
		collectedApprox = Math.ceil(collectedApprox * 100) / 100;
		
		//this loop will only be entered a maxium of 3 times
		var actualRecieved = this.getRecievedValue(collectedApprox); 
		while (organizerAmountReceived < actualRecieved){
			collectedApprox -= 0.01;
			collectedApprox = Math.round(collectedApprox * 100) / 100;
			actualRecieved = this.getRecievedValue(collectedApprox);
		}
		// Because javascript approximations are sooooo off, this must be added to catch boundery errors
		if (organizerAmountReceived > actualRecieved){	
			collectedApprox += 0.01;
			collectedApprox = Math.round(collectedApprox * 100) / 100;
		}
		
		if (collectedApprox < this.minFee){
			document.getElementById("organizerAmountErrorText").innerHTML = "Values must be greater than $" + this.minFee.toFixed(2);
			processingFeesElem.innerHTML = "0.00";
			suggestedAmountElem.value = "0.00";
			return false;
		}
		
		// By now the collectedApprox should be accurate
		suggestedAmountElem.value = collectedApprox.toFixed(2);
		processingFeesElem.innerHTML = (collectedApprox - organizerAmountReceived).toFixed(2);
		return false;
	},
	
	//	The formula for determining amounts:
	//	R(c) = c - A(c) - J(c)
	//	Where:
	//	R(c) = recieved amount
	//	c = collected amount
	//  A(c) = Amazon Commission
	//  J(c) = Jooners commision
	//	
	//  And Where:
	//	A(c) = Ar * C + Af
	//	Ar = Amazon Commission Rate
	//	Af = Amazon Fixed Fee
	//	For c < 10;		Ar = 5%, Af = 0.05
	//  For c >= 10;  	Ar = 2.9%, Af = 0.30
	//
	//	And where: 
	//	J(c) = Jr * Jf
	//  Jr = Jooners Commision Rate
	//  Jf = Jooners Fixed Fee
	// 	For all values of c, Jr = (this.maxVariableFee)%, Jf = this.maxFixedFee
	//
	//	Once rounding has been researched at amazon, we should modify these functions
	// 	as appropriate
	
	// We assume collectedAmnt was rounded BEFORE being passed to this function
	getRecievedValue: function(collectedAmnt, boundryCheck){
		var amazonFee = 0.0;
		var joonersFee = 0.0;
		var boundryCheck = (typeof(boundryCheck) != 'undefined') ? boundryCheck : false;

		if (collectedAmnt >= 10)
			amazonFee = (collectedAmnt * 2.9/100) + 0.30;
		else
			amazonFee = (collectedAmnt * 5/100) + 0.05;
		
		joonersFee = (collectedAmnt * this.maxVariableFee/100) + this.maxFixedFee;
		
		// Round each value to be consistent with Amazon's Payments
		amazonFee = Math.round(amazonFee * 100) / 100;
		joonersFee = Math.round(joonersFee * 100) / 100;
		
		var recievedAmount = collectedAmnt - amazonFee - joonersFee;
		
		// Because JavaScript Math is notorious for addition errors, round again
		recievedAmount = Math.round(recievedAmount * 100) / 100;
		
		// The penny boundry should always error on the low side
		// To guarantee this, compute suggested amount at one penny higher and verify
		// that the values DO NOT match. If they do, reduce then it's a boundry value 
		// and you should reduce the collected amount by 0.01
		// 
		// This effectively translates boundry values -0.01, changing the step curve
		// but ensuring customers will always get AT LEAST the value we quote them
		if (!boundryCheck){
			var altRecievedAmount = this.getRecievedValue(Math.round((collectedAmnt + 0.01)*100)/100, true);
			if (altRecievedAmount == recievedAmount){
				recievedAmount -= 0.01;
				recievedAmount = Math.round(recievedAmount * 100) / 100;
			}
		}
		
		return (recievedAmount);
	},
	
	// Because each commission rate requires rounding, it is not possible
	// to get an exact value for the collected amount. The approximation will
	// have an error of up + or - 0.02 (the number of commission rates)
	// that are rounded.
	//
	// This function assumes recievedAmnt was rounded BEFORE being passed
	getApproximateCollectedValue: function(recievedAmnt){
		var joonersRate = this.maxVariableFee/100;
		var joonersFixed = this.maxFixedFee;
	
		// Use the maxium collected value of 10.00 to determine the maxium recieved amount
		var amzMaxRcvd= this.getRecievedValue(10.00);
		
		var amzRate = 0.0;
		var amzFixed = 0.0;
		if (amzMaxRcvd <= recievedAmnt){
			amzRate = 2.9/100;
			amzFixed = 0.30;
		}
		else{
			amzRate = 5/100;
			amzFixed = 0.05;
		}
		
		//do the approximation
		var collectedAmnt = (recievedAmnt + amzFixed + joonersFixed) / (1 - amzRate - joonersRate);
		return (Math.floor(collectedAmnt * 100) / 100);
	},
	
	setFixedWidthOnAmount: function(evt){
		var organizerAmountReceivedElem = document.getElementById('organizerAmountReceived');
		var suggestedAmountElem = document.getElementById('suggestedAmount');
		var organizerAmount = 0.0;
		var suggestedAmount = 0.0;
		
		try {
			organizerAmount = parseFloat(organizerAmountReceivedElem.value);
			suggestedAmount = parseFloat(suggestedAmountElem.value);
		} catch (e) { 
			// do nothing, already handled in calculations
		}
		
		if (!isNaN(organizerAmount))
			organizerAmountReceivedElem.value = organizerAmount.toFixed(2);
			
		if (!isNaN(suggestedAmount))
			suggestedAmountElem.value = suggestedAmount.toFixed(2);
		
	},
	makePaymentsVisible: function(evt) {
			var paymentForm = document.getElementById("myform");
			var collectPaymentBox = document.getElementById("collectPayment");

			document.getElementById("skipPayment").checked = false;
			if (paymentForm.style.visibility == ""){
				this.data['suggestedAmount'] = document.getElementById('suggestedAmount').value;
				this.data['helperCanModifyAmount'] = document.getElementById('participantCanModifyAmount').checked;
				this.data['showFeesToHelper'] = document.getElementById('showFeesToParticipant').checked;
				paymentForm.style.visibility = "hidden";
			}
			else{
				if (typeof(this.data['suggestedAmount']) != 'undefined')
					document.getElementById('suggestedAmount').value = this.data['suggestedAmount'];
				if (typeof(this.data['participantCanModifyAmount']) != 'undefined')
					document.getElementById('participantCanModifyAmount').checked = this.data['helperCanModifyAmount'];
				if (typeof(this.data['showFeesToParticipant']) != 'undefined')
					document.getElementById('showFeesToParticipant').checked = this.data['showFeesToHelper'];
					
				this.calculatePaymentFees();
				paymentForm.style.visibility = "";
			}
	},

	skipPaymentSetup: function(evt) {
			document.getElementById("myform").style.visibility = "hidden";
			document.getElementById("collectPayment").checked = false;
			this.data["collectPayments"] = false;
			document.getElementById("skipPayment").checked = true;
			this.goNext();
			return true;
	},
	
	processPaymentRequest: function(directSave) {
		var collectPayments = document.getElementById('collectPayment').checked;
		var suggestedAmountStr = this.suggestedAmountElem.value;
		var helperCanModifyAmount = this.helperCanModifyAmountElem.checked;
		var showFeesToHelper = this.showFeesToHelperElem.checked;
		var suggestedAmount = 0.0;
		
		this.setFixedWidthOnAmount();
		
		try {
			suggestedAmount = parseFloat(suggestedAmountStr);
		} catch (e) {
			showMessageDialog("\"" + suggestedAmountStr + "\" is not a valid amount. Please correct.", 'Invalid Participant Amount',
			                300, 100);
			return;
		}
		if (isNaN(suggestedAmount)) {
			showMessageDialog("\"" + suggestedAmountStr + "\" is not a valid amount. Please correct.", 'Invalid Participant Amount',
			                300, 100);
			return;
		}
		if (suggestedAmount < this.minFee) {
			showMessageDialog("\"" + suggestedAmountStr + "\" is not a valid amount. Please correct.", 'Invalid Participant Amount',
			                300, 100);
			return;
		}
		
		// check if the payment request is already made and there are no changes made by the user
		var paymentRequest = this.data['latestPaymentRequest'];
		if (paymentRequest != null) {
			paymentRequest = paymentRequest[0];
			if (paymentRequest != null &&
				paymentRequest.requestedAmount == toString(suggestedAmount) &&
				paymentRequest.payerCanChangeAmount == toString(helperCanModifyAmount) &&
				paymentRequest.payerSeesFees == toString(showFeesToHelper)) {
				this.selectedStep = this.nextStep;
				this.loadTemplate();
				return;
			}
		}
		this.data['collectPayments'] = collectPayments;
		this.data['suggestedAmount'] = suggestedAmount;
		this.data['helperCanModifyAmount'] = helperCanModifyAmount;
		this.data['showFeesToHelper'] = showFeesToHelper;
		this.data['nextStep'] = this.nextStep;
		if (directSave){
			this.data['nextStep'] = this.TEMPLATE_STEP_PAYMENT_REQUEST;
			this.saveMyList('save', true);
		}
	},
	
    myListPaymentRequestCompleted: function(response) {
	   	hideModalMessageDialog();
		var nvPairArray = new Array();
		nvPairArray = response.responseText.split(";;");
		var errorStr = this.valueOf(nvPairArray, "error");
		var listUUID = this.valueOf(nvPairArray, "MyList.UUID");
		if (this.data['UUID'] == null) {
			this.data['UUID'] = listUUID;
		}
		if (errorStr != null) {
			if (errorStr == "UninitializedAmazonPaymentRecipient" ||
				errorStr == "ExpiredAmazonPaymentRecipient") {
				this.maxVariableFee = this.valueOf(nvPairArray, "maxVariableFee");
				this.maxFixedFee = this.valueOf(nvPairArray, "maxFixedFee");
				this.callerAccountId = this.valueOf(nvPairArray, "callerAccountId");
				this.recipientPaysFee = this.valueOf(nvPairArray, "recipientPaysFee");
				this.collectEmailAddress = this.valueOf(nvPairArray, "collectEmailAddress");
				this.callerReference = this.valueOf(nvPairArray, "callerReference");
				this.callerKey = this.valueOf(nvPairArray, "callerKey");
				this.pipelineName = this.valueOf(nvPairArray, "pipelineName");
				this.returnURL = this.valueOf(nvPairArray, "returnURL");
				this.awsSignature = this.valueOf(nvPairArray, "awsSignature");
				this.version = this.valueOf(nvPairArray, "version");
				this.signatureVersion = this.valueOf(nvPairArray, "signatureVersion");
				this.signatureMethod = this.valueOf(nvPairArray, "signatureMethod");
				this.signature = this.valueOf(nvPairArray, "signature");

				this.paymentUrl = this.valueOf(nvPairArray, "paymentUrl");
				this.selectedStep = this.TEMPLATE_STEP_PAYMENT_REQUEST_THROUGH_AMAZON;
			}
		} else {
			this.selectedStep = this.nextStep;
		}
		this.loadTemplate();
	},
	
	valueOf: function(nvPairArray, nameStr) {
		if (nvPairArray == null) {
			return null;
		}
		var nvPair;
		for (i=0; i<nvPairArray.length; i++) {
			nvPair = nvPairArray[i];
			if (nvPair.indexOf(nameStr)==0) {
				var idx = nvPair.indexOf("=");
				//2011-03-11 kee: fixed value error when keys with same prefix
				if(nvPair.substring(0, idx) == nameStr)
					return nvPair.substring(idx+1);
			}
		}
		return null;
	},
	
    myListPaymentRequestFailed: function() {
		// Inserted to make life easier while this payment functionality still fails
		hideModalMessageDialog();
		//alert("got to myListPaymentRequestFailed");
	},
	
	//
	// Payment Attempt related methods
	//
	calculateTotalPaymentForHelper:function(evt) {
		Event.extend(evt);
		var qtyStr = this.paymentQtyAmountElem.value;
		var paymentQtyErrorElem = document.getElementById('paymentQtyErrorSpan');
		var unitPaymentAmountErrorElem = document.getElementById('unitPaymentAmountErrorSpan');
		var totalPaymentAmountElem = document.getElementById('totalPaymentAmount');
		var proccessingFeeAmountElem = document.getElementById('processingFeeAmount');
		
		this.paymentQty = 0;
		
		try {
			this.paymentQty = parseInt(qtyStr);
		} catch (e) {
			paymentQtyErrorElem.innerHTML = "Invalid Quantity";
			totalPaymentAmountElem.innerHTML = "0.00";
			proccessingFeeAmountElem.innerHTML = "0.00";
			return false;
		}
		if (isNaN(this.paymentQty) || this.paymentQty <= 0) {
			paymentQtyErrorElem.innerHTML = "Invalid Quantity";
			totalPaymentAmountElem.innerHTML = "0.00";
			proccessingFeeAmountElem.innerHTML = "0.00";
			return false;
		}		
		paymentQtyErrorElem.innerHTML = "";
		var unitPaymentStr = this.unitPaymentAmountElem.value;
		this.unitPayment = 1.0;
		
		try {
			this.unitPayment = parseFloat(unitPaymentStr);
		} catch (e) {
			unitPaymentAmountErrorElem.innerHTML = "Invalid Amount";
			totalPaymentAmountElem.innerHTML = "0.00";
			proccessingFeeAmountElem.innerHTML = "0.00";
			return false;
		}
		if (isNaN(this.unitPayment) || this.unitPayment < this.minFee ){
			if (!isNaN(this.unitPayment))
				unitPaymentAmountErrorElem.innerHTML = "Amount must be $" + this.minFee.toFixed(2) + " or more";
			else
				unitPaymentAmountErrorElem.innerHTML = "Invalid Amount";
				
			totalPaymentAmountElem.innerHTML = "0.00";
			proccessingFeeAmountElem.innerHTML = "0.00";
			return false;
		}
		// Find the 'processing fee'
		var totalPayment = Math.round(this.unitPayment*this.paymentQty*100) / 100;
		var totalRecieved = this.getRecievedValue(totalPayment);
		var proccessingFee = totalPayment - totalRecieved;
		
		unitPaymentAmountErrorElem.innerHTML = "";
		
		proccessingFeeAmountElem.innerHTML = proccessingFee.toFixed(2);
		totalPaymentAmountElem.innerHTML = totalPayment.toFixed(2);
		return true;
	},
	
	prepareToPayAtAmazon: function() {
		// validate the quantity and amount
		if (!this.calculateTotalPaymentForHelper()) {
			showMessageDialog("Please fix the payment amount before proceeding",
                                "Invalid Amount",250,100, null, true);
			return false;
		}
		
		if (!this.emailValidator.validateEmail(this.helperEmailElem.value)) {
			showMessageDialog(helperEmailVal, 'Invalid Payer Email Address',
                            300, 100);
			return false;
		}
		
		// show a warning dialog to user if they have already made a payment
		var helperPaidAmount = this.data['helperPaidAmount'];
		if (helperPaidAmount != null) {
			try {
				helperPaidAmount = parseFloat(helperPaidAmount);
				if (!isNaN(helperPaidAmount) && helperPaidAmount != 0) {
					if(this.previousPaymentWarningDialog==null) {
						var handler1 = {
							templateLoaded: function() {
								this.parent.handlePreviousPaymentWarningLoad();
						},
							parent:this
						}
						this.previousPaymentWarningDialog =
		                  new Af.HtmlDialog("Sure you want to pay?", handler1, null);
						this.previousPaymentWarningDialog.width = "320px";
					}
					this.previousPaymentWarningDialog.showHTMLTemplate( basePageURL +
			                         "previousPaymentWarningDialog.htm", "bodyContainer", "warningDiv");
					this.previousPaymentWarningDialog.centerDialog(350, 350);
					return false;
				}
			} catch (e) {
			}
		}
		this.doProceedToPayAtAmazon();
		return false;
	},
	
	doProceedToPayAtAmazon: function() {
		
		var paymentRequestInfo = this.data['latestPaymentRequest'][0];
	 /*	window.location = "/amzn-connector?AWSRequestType=StartPaymentAttempt&"+
	 			"paymentRequestId="+paymentRequestInfo.UUID +
	 			"&unitPayment="+this.unitPayment +
	 			"&paymentQty="+this.paymentQty +
	 			"&payerPersonUUID="+this.data['helperID'];
*/
	 	req = new Af.DataRequest(svcURL,
                this.myListPrepareToPayAtAmazonCompleted.bind(this),
                this.myListPrepareToPayAtAmazonFailed.bind(this), null,
                this.requestTimedoutCommon.bind(this));
    	req.addService("PublicService", "prepareToPayAtAmazon");
    	req.addParameter("paymentRequestId", paymentRequestInfo.UUID);
    	req.addParameter("unitPayment", this.unitPayment);
    	req.addParameter("paymentQty", this.paymentQty);
    	req.addParameter("payerEmail", this.emailValidator.extractEmailAddress(this.helperEmailElem.value));
    	ajaxEngine.processRequest(req);
    	
	},
	
	handlePreviousPaymentWarningLoad: function() {
		var payButton = document.getElementById('Pay');
		payButton.onclick = this.doProceedToPayAtAmazon.bind(this);
		var dontPayButton = document.getElementById('DontPay');
		dontPayButton.onclick = this.skipPayment.bind(this);
	},
	
	myListPrepareToPayAtAmazonCompleted: function(response) {
		var nvPairArray = new Array();
		nvPairArray = response.responseText.split(";;");
		var errorStr = this.valueOf(nvPairArray, "error");
		
		// go through name-value pairs and populate the form
		
		this.variableMarketplaceFee = this.valueOf(nvPairArray, "variableMarketplaceFee");
		this.fixedMarketplaceFee = this.valueOf(nvPairArray, "fixedMarketplaceFee");
		this.immediateReturn = this.valueOf(nvPairArray, "immediateReturn");
		this.collectShippingAddress = this.valueOf(nvPairArray, "collectShippingAddress");
		this.accessKey = this.valueOf(nvPairArray, "accessKey");
		this.referenceId = this.valueOf(nvPairArray, "referenceId");
		this.recipientEmail = this.valueOf(nvPairArray, "recipientEmail");
		this.amount = this.valueOf(nvPairArray, "amount");
		this.signature = this.valueOf(nvPairArray, "signature");
		this.isDonationWidget = this.valueOf(nvPairArray, "isDonationWidget");
		this.description = this.valueOf(nvPairArray, "description");
		this.amazonPaymentsAccountId = this.valueOf(nvPairArray, "amazonPaymentsAccountId");
		this.ipnUrl = this.valueOf(nvPairArray, "ipnUrl");
		this.returnUrl = this.valueOf(nvPairArray, "returnUrl");
		this.processImmediate = this.valueOf(nvPairArray, "processImmediate");
		this.cobrandingStyle = this.valueOf(nvPairArray, "cobrandingStyle");
		this.abandonUrl = this.valueOf(nvPairArray, "abandonUrl");
		this.signatureVersion = this.valueOf(nvPairArray, "signatureVersion");
		this.signatureMethod = this.valueOf(nvPairArray, "signatureMethod");
		this.paymentUrl = this.valueOf(nvPairArray, "paymentUrl");
		
		//Cheat here.
		this.loadPaymentAttemptThroughAmazonStep();
		
		document.amazonPayForm.submit();
	},
	
	myListPrepareToPayAtAmazonFailed: function() {
	},
	
	skipPayment: function() {
		this.selectedStep = 6;
		this.loadTemplate();
	},
	
	initializeSelectedStepFromQueryString: function() {
		// usedNextStepFromQueryString is a global variable defined in StepsMaker.js
		if (!usedNextStepFromQueryString) {
			usedNextStepFromQueryString = true;
			this.selectedStep = HJ.requestQueryString.get("nextStep", null);
		}
		if (this.selectedStep == null) {
			this.selectedStep = 1;
			this.selectedStepInitialized = false;
		} else {
			this.selectedStepInitialized = true;
		}
	},
	
	copyToClipboard: function(event) {
		HJ.copyToClipboard(document.getElementById("publishableURL"));
		Event.extend(event);
	   	Event.stop(event); // ignore
	},
	
	showPublishableURLHelpDialog: function(event) {
	  	showMessageDialog("You can imbed the link (URL, web address) of " +
	  			"this sign-up sheet in other electronic media (eNews, website, etc.) " +
	  			"so people can sign-up by clicking on the link there.<br /><br />" +
	  			"You can send the sign-up sheet to both emails and/or use the link " +
	  			"in other electronic media. All participants will be taken to the " +
	  			"same active sign-up page.",
                "What to do with a link to your sign-up page?", 380, 175, null, true);
	  	Event.extend(event);
	  	Event.stop(event); // avoid further propagation of event
	},
	
	showPublishableURL: function(uuid) {
		var publishedURLElem = document.getElementById("publishableURL");
		if (publishedURLElem != null) {
			publishedURLElem.value = window.location.protocol + "//" +
									 window.location.host + 
									 "/guest?t=help&p=none&l="+uuid;
		}
	},
	
	printPlanner: function() {
		var printWindow = window.open("/planner/print?uuid=" + this.data['UUID'],
				 '_print', 
				 'toolbar=no, location=no, directories=no, status=no, menubar=yes, scrollbars=yes, resizable=yes, copyhistory=no, width=700, height=800');
		return false;
	},
	
	processDoneInStep4: function() {
		this.saveSilently = true;
		this.goUpdateAfterSend();
	},

	showCopySelection: function() {
		var copyTemplateDialog = new HJ.CopyTemplateDialog(this);
	   	copyTemplateDialog.loadTemplate();
	   	return false;

	},

	showUploadIconDialog: function(event) {

		showModalMessageDialog("Loading ... please wait",
                        300, 40);

        this.uploadIconDialog = new HJ.UploadIconDialog(this);
        this.uploadIconDialog.loadTemplate();

        return false;    
	},

    loadListIcon: function(listId){

        var t = new Date().getTime(); //append timestamp to skip browser cache
        var listUUID = null;
        if ( listId ) {

            listUUID = listId;
            
        }
        else if (this.listObj != null && this.listObj.useIcon == "true") {
            
            listUUID = this.listObj.UUID;
        }

        var iconElem = document.getElementById("listIcon");
        if(iconElem)
        {
            if(listUUID) {

                this.origIcon = iconElem.src;
                iconElem.src = '/rose/loadIcon?listId=' + listUUID + "&t=" + t;
            }

            iconElem.style.display = "inline";
        }
    },
    showConfirmEmailDialog: function()
    {
        
        var table = document.createElement("table");
        table.setAttribute("width", "100%");
        table.style.width = "100%";
        table.className = "emailDialog";
        var tbody = document.createElement("tbody");
        table.appendChild(tbody);
        var tr = document.createElement("tr");
        tbody.appendChild(tr);
        var td = document.createElement("td");
        td.setAttribute("colspan", "3");
        td.innerHTML = "&nbsp;";
        tr.appendChild(td);
        var tr = document.createElement("tr");
        tbody.appendChild(tr);
        var td = document.createElement("td");
        td.setAttribute("colspan", "3");
        tr.appendChild(td);
        //td.appendChild(document.createTextNode(message));
        td.innerHTML = "<center>Your reminder will be sent to <br/>" + this.data['helperEmail'] + ".</center>";

        tr = document.createElement("tr");
        tbody.appendChild(tr);
        td = document.createElement("td");
        td.setAttribute("colspan", "3");
        td.innerHTML = "&nbsp;";
        tr.appendChild(td);

        tr = document.createElement("tr");
        tbody.appendChild(tr);
        td = document.createElement("td");
        td.style.textAlign = "center";
        tr.appendChild(td);
        /*
        e = document.createElement("button");
        if (okFunc) {
            e.onclick = function(){okFunc()};
        } else {
         e.onclick = hideDialogWin;
        }
        e.className = "ButtonStyle";
        e.innerHTML = "OK";
        td.appendChild(e);
        */
        a = document.createElement("a");
        a.className = "normalOrangeBtn";
        
        //a.setAttribute("class", "tempOrangeBtn");
        //a.setAttribute("className", "tempOrangeBtn");
        a.href = "#";
        a.style.display="block";
        a.style.width = "200px";
        a.style.margin = "5px auto";

        span = document.createElement("span");
        span.innerHTML = "Confirm sign-up";
        a.appendChild(span);
        td.appendChild(a);

        // confirm 
        a.onclick = function(){
            this.confirmEmailDialog.close();
            this.emailAddrWarningShown = true;
            this.goRSVP();
            return false;
        }.bind(this);


        tr = document.createElement("tr");
        tbody.appendChild(tr);
        td = document.createElement("td");
        td.setAttribute("colspan", "3");
        td.setAttribute("align", "center");
        td.style.textAlign = "center";
        td.innerHTML = "<span style=\"padding: 5px;\">or</span>";
        tr.appendChild(td);
             
        tr = document.createElement("tr");
        tbody.appendChild(tr);
        td = document.createElement("td");
        td.style.textAlign = "center";
        tr.appendChild(td);
        /*
        e = document.createElement("button");
        if (okFunc) {
            e.onclick = function(){okFunc()};
        } else {
         e.onclick = hideDialogWin;
        }
        e.className = "ButtonStyle";
        e.innerHTML = "OK";
        td.appendChild(e);
        */
        a = document.createElement("a");
        a.className = "normalOrangeBtn";
        
        //a.setAttribute("class", "tempOrangeBtn");
        //a.setAttribute("className", "tempOrangeBtn");
        a.href = "#";
        a.style.display="block";
        a.style.width = "200px";
        a.style.margin = "5px auto";

        span = document.createElement("span");
        span.innerHTML = "Change contact email";
        a.appendChild(span);
        td.appendChild(a);
        td = document.createElement("td");
        td.style.textAligned = "center";
        tr.appendChild(td);

        a.onclick = function(){
            this.confirmEmailDialog.close();
            /*
            var helperEmail = document.getElementById("helperEmail");
            var as = document.getElementsByTagName('a');
            as[0].focus();
            helperEmail.focus();
            helperEmail.select();
            */

		    this.showEnterEmailAgain();	
            return false;
        }.bind(this);

        tr = document.createElement("tr");
        tbody.appendChild(tr);
        td = document.createElement("td");
        td.setAttribute("colspan", "3");
        td.innerHTML = "&nbsp;";
        tr.appendChild(td);
        if(this.confirmEmailDialog && this.confirmEmailDialog.element) {
        
            p = this.confirmEmailDialog.element.parentNode;
            if(p){

                p.removeChild(this.confirmEmailDialog.element);
                this.confirmEmailDialog = null;
            }

        }
             
        this.confirmEmailDialog = new Af.HtmlDialog("Please confirm", null, table); 
        // 2011-12-15 kee: workaround ajax face HtmlDialog bug in IE 
        //this.confirmEmailDialog.width = "300px;"
        this.confirmEmailDialog.createElement();
        this.confirmEmailDialog.container = "helperEmailDiv";
        this.confirmEmailDialog.centerDialog(300,300);

        // kee: fixed for Ajaxface width problem
        var el = this.confirmEmailDialog.element;
        el.style.width = "300px";
        table = el.firstChild;
        table.style.width = "100%";
        this.confirmEmailDialog.makeVisible();

        window.scrollTo(0, 0);
        var helperEmailElem = document.getElementById("helperEmailDiv");
        
        this.confirmEmailDialog.element.style.left = (helperEmailElem.offsetLeft + 50)+ "px";
        this.confirmEmailDialog.element.style.top = (helperEmailElem.offsetTop + 50) + "px";
	    return false;


    },
    showEmptyEmailMessage: function()
    {
         
        var table = document.createElement("table");
        table.width = "100%";
        table.className = "emailDialog";
        var tbody = document.createElement("tbody");
        table.appendChild(tbody);
        var tr = document.createElement("tr");
        tbody.appendChild(tr);
        var td = document.createElement("td");
        td.setAttribute("colspan", "3");
        td.innerHTML = "&nbsp;";
        tr.appendChild(td);
        var tr = document.createElement("tr");
        tbody.appendChild(tr);
        var td = document.createElement("td");
        td.setAttribute("colspan", "3");
        tr.appendChild(td);
        //td.appendChild(document.createTextNode(message));
        td.innerHTML = "<center>Please enter your email in the email<br/>address box <span style=\"color: red;\">and click the Sign-Up button again</span>. This is required so that Jooners can send you a reminder email.</center>";

        tr = document.createElement("tr");
        tbody.appendChild(tr);
        td = document.createElement("td");
        td.setAttribute("colspan", "3");
        td.innerHTML = "&nbsp;";
        tr.appendChild(td);

        tr = document.createElement("tr");
        tbody.appendChild(tr);
        /*
        td = document.createElement("td");
        td.setAttribute("width", "20%");
        tr.appendChild(td);
        */
        td = document.createElement("td");
        //td.setAttribute("width", "30%");
        //td.style.margin = "5px auto";
        td.style.textAlign = "center";
        tr.appendChild(td);
        /*
        e = document.createElement("button");
        if (okFunc) {
            e.onclick = function(){okFunc()};
        } else {
         e.onclick = hideDialogWin;
        }
        e.className = "ButtonStyle";
        e.innerHTML = "OK";
        td.appendChild(e);
        */
        a = document.createElement("a");
        a.className = "normalOrangeBtn";
        
        //a.setAttribute("class", "tempOrangeBtn");
        //a.setAttribute("className", "tempOrangeBtn");
        a.href = "#";
        a.style.display="block";
        a.style.width = "100px";
        a.style.margin = "5px auto";

        span = document.createElement("span");
        span.innerHTML = "OK";
        a.appendChild(span);
        td.appendChild(a);
        /*
        td = document.createElement("td");
        tr.appendChild(td);
        */

        tr = document.createElement("tr");
        tbody.appendChild(tr);
        td = document.createElement("td");
        td.setAttribute("colspan", "3");
        td.innerHTML = "&nbsp;";
        tr.appendChild(td);
             
        if (this.emptyEmailDialog == 'undefined' || this.emptyEmailDialog == null) {
            this.emptyEmailDialog = new Af.HtmlDialog("Error", null, table); 
            this.emptyEmailDialog.container = "helperEmailDiv";
            this.emptyEmailDialog.width = "300px";
            this.emptyEmailDialog.centerDialog(300,150);
            //this.emptyEmailDialog.createElement();
        }
        a.onclick = function(){
            this.emptyEmailDialog.close();
            return false;
        }.bind(this);

        var helperEmailElem = document.getElementById("helperEmail");
        helperEmailElem.focus();

        window.scrollTo(0, 0);
        this.emptyEmailDialog.makeVisible('helperEmailDiv');
        this.emptyEmailDialog.element.style.left = helperEmailElem.offsetLeft + "px";
        this.emptyEmailDialog.element.style.top = (helperEmailElem.offsetTop + 90) + "px";

	    return false;

    }, 

    showUploadAttachmentDialog: function() {
		showModalMessageDialog("Loading ... please wait",
                        300, 40);

        this.uploadAttachmentDialog = new HJ.UploadAttachmentDialog(this);
        this.uploadAttachmentDialog.loadTemplate();

        return false;    

    },

	loadListAttachment: function(listId) {
        var t = new Date().getTime(); //append timestamp to skip browser cache
        var listUUID = null;
        if ( listId ) {

            listUUID = listId;
            
        }
        else if (this.listObj != null ) {
            
            listUUID = this.listObj.UUID;
        }
        else if (this.implicitAttachmentListId) {
            listUUID = this.implicitAttachmentListId;

        }

        this.attachmentListElem = document.getElementById("attachmentList");
        if(!this.attachmentListElem)
        {
            return;
        }

		this.addLink = document.getElementById('addAttachLink');
        if (this.addLink != null) {
        	this.addLink.onclick = this.showUploadAttachmentDialog.bindAsEventListener(this);
        }

        if(listUUID == null) {
            this.addLink.style.display = "block";
            return;
        }
        
        if (this.attachmentListContainer != null) {
            this.attachments = new HJ.Attachments(
                    this.attachmentListElem, 
                    null,
                    this.ATTACHMENT_ROWS, 
                    listUUID,
                    null);

            this.attachments.fetchAttachments(this.selectedStep!=4);
        }
	}, 

    showEnterEmailAgain : function() {
        var table = document.createElement("table");
        table.width = "100%";
        table.className = "emailDialog";
        var tbody = document.createElement("tbody");
        table.appendChild(tbody);
        var tr = document.createElement("tr");
        tbody.appendChild(tr);
        var td = document.createElement("td");
        td.setAttribute("colspan", "3");
        td.innerHTML = "&nbsp;";
        tr.appendChild(td);
        var tr = document.createElement("tr");
        tbody.appendChild(tr);
        var td = document.createElement("td");
        td.setAttribute("colspan", "3");
        tr.appendChild(td);
        //td.appendChild(document.createTextNode(message));
        td.innerHTML = "<center>Please enter the email you wish to use in the email address box and click the Sign-Up button again.</center>";

        tr = document.createElement("tr");
        tbody.appendChild(tr);
        td = document.createElement("td");
        td.setAttribute("colspan", "3");
        td.innerHTML = "&nbsp;";
        tr.appendChild(td);

        tr = document.createElement("tr");
        tbody.appendChild(tr);
        /*
        td = document.createElement("td");
        td.setAttribute("width", "20%");
        tr.appendChild(td);
        */
        td = document.createElement("td");
        //td.setAttribute("width", "30%");
        //td.style.margin = "5px auto";
        td.style.textAlign = "center";
        tr.appendChild(td);
        /*
        e = document.createElement("button");
        if (okFunc) {
            e.onclick = function(){okFunc()};
        } else {
         e.onclick = hideDialogWin;
        }
        e.className = "ButtonStyle";
        e.innerHTML = "OK";
        td.appendChild(e);
        */
        a = document.createElement("a");
        a.className = "normalOrangeBtn";
        
        //a.setAttribute("class", "tempOrangeBtn");
        //a.setAttribute("className", "tempOrangeBtn");
        a.href = "#";
        a.style.display="block";
        a.style.width = "100px";
        a.style.margin = "5px auto";

        span = document.createElement("span");
        span.innerHTML = "OK";
        a.appendChild(span);
        td.appendChild(a);
        /*
        td = document.createElement("td");
        tr.appendChild(td);
        */

        tr = document.createElement("tr");
        tbody.appendChild(tr);
        td = document.createElement("td");
        td.setAttribute("colspan", "3");
        td.innerHTML = "&nbsp;";
        tr.appendChild(td);
             
        if (this.enterEmailAgainDialog == 'undefined' || this.enterEmailAgainDialog == null) {
            this.enterEmailAgainDialog = new Af.HtmlDialog("Error", null, table); 
            //this.enterEmailAgainDialog.createElement();
            this.enterEmailAgainDialog.container = "helperEmailDiv";
            this.enterEmailAgainDialog.width = "300px";
            this.enterEmailAgainDialog.centerDialog(300,150);
        }
        this.enterEmailAgainDialog.makeVisible('helperEmailDiv');
        a.onclick = function(){
            this.enterEmailAgainDialog.close();
            return false;
        }.bind(this);

        var helperEmailElem = document.getElementById("helperEmail");
        var as = document.getElementsByTagName('a');
        helperEmailElem.focus();
        helperEmailElem.select();
        
        this.enterEmailAgainDialog.element.style.left = (helperEmailElem.offsetLeft + 50)+ "px";
        this.enterEmailAgainDialog.element.style.top = (helperEmailElem.offsetTop + 80) + "px";
	    return false;


    }, 
    
    showEnterEmailAgainDialog : function() {
        var table = document.createElement("table");
        table.width = "100%";
        table.className = "emailDialog";
        var tbody = document.createElement("tbody");
        table.appendChild(tbody);
        var tr = document.createElement("tr");
        tbody.appendChild(tr);
        var td = document.createElement("td");
        td.setAttribute("colspan", "3");
        td.innerHTML = "&nbsp;";
        tr.appendChild(td);
        var tr = document.createElement("tr");
        tbody.appendChild(tr);
        var td = document.createElement("td");
        td.setAttribute("colspan", "3");
        tr.appendChild(td);
        //td.appendChild(document.createTextNode(message));
		if (this.templateType==HJ.TEMPLATE_TYPE_COLLECT_INFORMATION) {
            td.innerHTML = "<center>Please enter your name and any other required information and click on the Sign-Up button again.</center>";
        } else {
            td.innerHTML = "<center>Please enter your name next to the item you want to sign up for and click the Sign-Up button again.</center>";
        }


        tr = document.createElement("tr");
        tbody.appendChild(tr);
        td = document.createElement("td");
        td.setAttribute("colspan", "3");
        td.innerHTML = "&nbsp;";
        tr.appendChild(td);

        tr = document.createElement("tr");
        tbody.appendChild(tr);
        /*
        td = document.createElement("td");
        td.setAttribute("width", "20%");
        tr.appendChild(td);
        */
        td = document.createElement("td");
        //td.setAttribute("width", "30%");
        //td.style.margin = "5px auto";
        td.style.textAlign = "center";
        tr.appendChild(td);
        /*
        e = document.createElement("button");
        if (okFunc) {
            e.onclick = function(){okFunc()};
        } else {
         e.onclick = hideDialogWin;
        }
        e.className = "ButtonStyle";
        e.innerHTML = "OK";
        td.appendChild(e);
        */
        a = document.createElement("a");
        a.className = "normalOrangeBtn";
        
        //a.setAttribute("class", "tempOrangeBtn");
        //a.setAttribute("className", "tempOrangeBtn");
        a.href = "#";
        a.style.display="block";
        a.style.width = "100px";
        a.style.margin = "5px auto";

        span = document.createElement("span");
        span.innerHTML = "OK";
        a.appendChild(span);
        td.appendChild(a);
        /*
        td = document.createElement("td");
        tr.appendChild(td);
        */

        tr = document.createElement("tr");
        tbody.appendChild(tr);
        td = document.createElement("td");
        td.setAttribute("colspan", "3");
        td.innerHTML = "&nbsp;";
        tr.appendChild(td);
             

        var itemsElem = document.getElementById('listItems');
        var inputBoxes =  itemsElem.getElementsByTagName("input");

        for(var i = 0; i< inputBoxes.length; i++) {
            var inputBox = inputBoxes[i];
            if(inputBox.disabled == false && inputBox.type == 'text') {
                inputBox.focus();
                //window.scrollBy(0, -10);
                break;
            }

        }
        if(itemsElem) {
            //calculate header position to scroll to
            var y = itemsElem.offsetTop;

            if(y > 10)
                window.scrollTo(0, y - 10);
        }
        if (this.enterNameDialog == 'undefined' || this.enterNameDialog == null) {
            this.enterNameDialog = new Af.HtmlDialog("Error", null, table); 
            this.enterNameDialog.container = "helperEmailDiv";
            this.enterNameDialog.width = "300px";
            this.enterNameDialog.centerDialog(300,150);
            //this.enterNameDialog.createElement();
        }
        a.onclick = function(){
            this.enterNameDialog.close();
            return false;
        }.bind(this);
        this.enterNameDialog.element.style.left = itemsElem.offsetLeft + "px";
        this.enterNameDialog.element.style.top = itemsElem.offsetTop + "px";
        this.enterNameDialog.makeVisible(itemsElem);
        
	    return false;


    }


}

	

