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].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');
		if (printLink != null) {
			if (this.data['UUID'] == null || this.data['UUID'] == '') {
				printLink.style.display = 'none';
			} else {
				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);
		} 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);
			}
		} 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.loadStep1();
			this.initializeAttachmentsSection(true);

			// force going back to home page if user clicks on back button
			// during template creation
			this.setCurrentStepInYUIHistoryMgr(
                            Af.StepsMaker.prototype.TEMPLATE_STEP1);
		}
		hideModalMessageDialog();
	},
	
	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.addAttachment.bindAsEventListener(this);
        }

        this.attachmentListContainer 
            = document.getElementById('attachmentListItems');
        this.sendFileForm 
            = document.getElementById('sendFileForm');
        this.sendFileInput = document.getElementById('sendFileInput');

        // 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() {
		document.getElementsByName("variableMarketplaceFee")[0].value = this.variableMarketplaceFee;
		document.getElementsByName("fixedMarketplaceFee")[0].value = this.fixedMarketplaceFee;
		document.getElementsByName("immediateReturn")[0].value = this.immediateReturn;
		document.getElementsByName("collectShippingAddress")[0].value = this.collectShippingAddress;
		document.getElementsByName("accessKey")[0].value = this.accessKey;
		document.getElementsByName("referenceId")[0].value = this.referenceId;
		document.getElementsByName("recipientEmail")[0].value = this.recipientEmail;
		document.getElementsByName("amount")[0].value = this.amount;
		document.getElementsByName("signature")[0].value = this.signature;
		document.getElementsByName("isDonationWidget")[0].value = this.isDonationWidget;
		document.getElementsByName("description")[0].value = this.description;
		document.getElementsByName("amazonPaymentsAccountId")[0].value = this.amazonPaymentsAccountId;
		document.getElementsByName("ipnUrl")[0].value = this.ipnUrl;
		document.getElementsByName("returnUrl")[0].value = this.returnUrl;
		document.getElementsByName("processImmediate")[0].value = this.processImmediate;
		document.getElementsByName("cobrandingStyle")[0].value = this.cobrandingStyle;
		document.getElementsByName("abandonUrl")[0].value = this.abandonUrl;
	
		
		/*
		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;
		*/
	},

	loadPaymentRequestThroughAmazonStep: function() {
		document.getElementsByName("maxVariableFee")[0].value = this.maxVariableFee;
		document.getElementsByName("maxFixedFee")[0].value = this.maxFixedFee;
		document.getElementsByName("callerAccountId")[0].value = this.callerAccountId;
		document.getElementsByName("recipientPaysFee")[0].value = this.recipientPaysFee;
		document.getElementsByName("collectEmailAddress")[0].value = this.collectEmailAddress;
		document.getElementsByName("callerReference")[0].value = this.callerReference;
		document.getElementsByName("callerKey")[0].value = this.callerKey;
		document.getElementsByName("pipelineName")[0].value = this.pipelineName;
		document.getElementsByName("returnURL")[0].value = this.returnURL;
		document.getElementsByName("awsSignature")[0].value = this.awsSignature;
	},
	
	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 = "I am using Jooners to " +
					"organize this activity. " +
					"Please click on the link above to see what's needed and " +
                    "sign-up!\n\n" +
					"To participate, you don’t need to register or become a " +
                    "member of Jooners.\n\n" +
					"Thanks,\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.emailString.value = this.data['lastEmailString'];
		}
		document.getElementById("copyToClipboardLink").onclick = this.copyToClipboard.bindAsEventListener(this);
		document.getElementById("showPublishableURLHelp").onclick = this.showPublishableURLHelpDialog.bindAsEventListener(this);
		// save on server side if logged in before proceeding
		if (login != null && app != null) {
			document.getElementById("showPublishableURL").style.display = "block";
			if (this.data != null && this.data['UUID'] != null && this.data['UUID'] != '') {
				this.showPublishableURL(this.data['UUID']);
			} else {
				this.saveSilently = true;
				this.goSave("save");
			}
		} else {
			document.getElementById("showPublishableURL").style.display = "none";
		}
	},
	
	loadStepsMakerStep4: function() {
		this.helperNextStepButton = document.getElementById('helperNextStepButton');
		this.rsvpButton = document.getElementById('rsvpButton');
		if (this.data['latestPaymentRequest'] == null || 
				this.data['helperID'] == null) {
			if (this.helperNextStepButton != null) {
				this.helperNextStepButton.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.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);
			}

			sentEmails.innerHTML = 'This list 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";
					}
				} else {
					this.helperEmailElem.value = this.data['helperEmail'];
				}
			}
			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) {
					}
				}
			}
		} 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.askMoreHelpersElem = document.getElementById("askMoreHelpers");
			this.askMoreHelpersElem.style.display = "inline";
			this.askMoreHelpersElem.onclick = this.displayAskMoreHelpersDialog.bindAsEventListener(this);

			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 list 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");

		/*
		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 {
			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><tr><td colspan='2'><span style='font-size:12pt;'><strong>" 
					+ this.listObj.displayName + "</strong></span></td></tr>";
		var items = this.listObj.item;
	
		switch (this.templateType) {
			case HJ.TEMPLATE_TYPE_ORGANIZE_VOLUNTEERS :
				html += "<tr><td align='right'><b>Date:&nbsp;&nbsp;</b></td><td>"+this.listObj.startDT+"</td></tr>";
				html += "<tr><td align='right'><b>Time:&nbsp;&nbsp;</b></td><td>"+this.listObj.fromTime+"</td></tr>";
				html += "<tr><td align='right'><b>Your Responsibility:&nbsp;&nbsp;</b></td>";
				break;
			case HJ.TEMPLATE_TYPE_PRACTICE_CARPOOL :
				html += "<tr><td align='right'><b>From Date:&nbsp;&nbsp;</b></td><td>"+this.listObj.startDT+"</td></tr>";
				html += "<tr><td align='right'><b>To Date:&nbsp;&nbsp;</b></td><td>"+this.listObj.endDT+"</td></tr>";
				html += "<tr><td align='right'><b>Your Responsibility:&nbsp;&nbsp;</b></td>";
				break;
			case HJ.TEMPLATE_TYPE_SNACK_DUTY :
				html += "<tr><td align='right'><b>Your Responsibility:&nbsp;&nbsp;</b></td>";
				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 :
				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 = '';
		
		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("Please enter your email address in Helper Email Address field", 'An Error',
                        300, 100);
				return 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!='' && value !=null
	                        && value != 'Drivers Sign Up Here') {
					    signedUp = true;
					    item.helper = value;
					    var notesElem = document.getElementById('notes_'+i);
					    if (notesElem != null) {
	                        value = notesElem.value;
					        if (notesElem.disabled == false
	                                && value!='' && value !=null
	                                && value != 'Drivers Write Notes Here') {
						        item.notes = value;
					        }
				        }
	                }
				}
			}
			
			
			if (signedUp) {
				if (this.emailAddrWarningShown == undefined || this.emailAddrWarningShown == false) {
					showMessageDialog("Did you double-check the email address on the top of this page? Is it yours?"
							+ "<br /><br />"
							+ "Not your email address = No Jooners' reminders."
							+ "<br /><br />"
							+ "After you confirm your email address, please "
							+ "click SIGN UP (or NEXT) a 2nd time.", "ALERT !!!", 
						350, 150);
					this.emailAddrWarningShown = true;
					return false;
				} else {
					this.emailAddrWarningShown = false;
					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();
	},
	
	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;
		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) {

		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;
		}
		
		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 (!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!='' && !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) {
      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 (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);
      }

	  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) {
      this.implicitListId = response.responseText;
      //alert(this.implicitListId);
      if (this.saveObj.UUID == null) {
         this.saveObj.UUID = response.responseText;      
      }
      
      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) {
         this.saveObj.UUID = response.responseText;
      }
	  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 == this.TEMPLATE_STEP3) {
			this.showPublishableURL(this.saveObj.UUID);
		}
		
		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.", "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 + "\" />";

          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) {
        this.targetHelperElement.value = selectedDisplayText;
        var divNode = this.targetHelperElement.parentNode;
        var nextNode = divNode.nextSibling;
        var UUID = null;
        var helperIdNode = null;

        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.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);
		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 = '';
	   }
	   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;
   },
   
	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;
        }
        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) {
		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.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("=");
				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");
		
		//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();
	}
}
