
function createLoginXMLDoc()
{
	var loginForm = document.getElementById("loginForm");
	//var username = document.getElementById("username").value;
	//var password = document.getElementById("password").value;
	var username = loginForm.username.value;
	var password = loginForm.password.value;
	var org_id = document.getElementById( 'orgp.o_org_id' ).value;

	//var commandField = document.getElementById("command");
	//commandField.value = "login";
	loginForm.command.value = "login";
					
	var xml = "";
	xml += "<LOGIN>";
	xml +=		"<USERNAME>"+username+"</USERNAME>";
	xml += 		"<PASSWORD>"+password+"</PASSWORD>";
	xml += 		"<ORG_ID>"+org_id+"</ORG_ID>";
	xml +=  "</LOGIN>";
	
	//alert("username: " + username + "\npassword: " + password + "\n" + xml);	
	return xml;
}
//HS016425:overloaded function to create if from the form without disturbingthe existing function 
function sr_createLoginXMLDoc(formname)
{
	var username = formname.username.value;
	var password = formname.password.value;
	var org_id = formname.org_id.value;

	//var commandField = document.getElementById("command");
	//commandField.value = "login";
	formname.command.value = "login";
					
	var xml = "";
	xml += "<LOGIN>";
	xml +=		"<USERNAME>"+username+"</USERNAME>";
	xml += 		"<PASSWORD>"+password+"</PASSWORD>";
	xml += 		"<ORG_ID>"+org_id+"</ORG_ID>";
	xml +=  "</LOGIN>";
	
	//alert("username: " + username + "\npassword: " + password + "\n" + xml);	
	return xml;
}
function createQuestionXMLDoc(){
	var question = document.getElementById("select_question");
	var question_value = question.options[question.selectedIndex].value;
	var answer = questionForm.question_answer.value;
	var xml = "";
	xml += "<QUESTION>"
		+		"<QUES_TEXT>"+question_value+"</QUES_TEXT>"
		+		"<QUES_ID>1</QUES_ID>"
		+		"<ANSWER>"+answer+"</ANSWER>"
		+	"</QUESTION>";
	return xml;
}

function doSecurityQuestions()
{
	//set message
	var questionMsgDiv = Ext.get("questionMessage");
	questionMsgDiv.removeClass("questionMessage");
	xml = createQuestionXMLDoc();
	var field = document.getElementById("xmlQuestionString");
	field.value = xml;
	var form = document.getElementById("questionForm");
	form.submit();
}
		
function doLogin()
{


	clmLoginDialog.disableLoginButton();

	//set message
	var loginMsgDiv = Ext.get("loginMessage");
//	loginMsgDiv.removeClass("loginMessage");
	
	loginMsgDiv.dom.innerHTML = '<span id="id_loginMessage" style="vertical: middle;"><img src="themes/common/images/loading.gif">&nbsp;&nbsp;'+frmwrk_rm.get("Login_processing_login_request")+'</span>';
//	loginMsgDiv.addClass("loginMessage");
	loginMsgDiv.setVisible(true);
	
	
	xml = createLoginXMLDoc();
	
	var field = document.getElementById("xmlString");
	field.value = xml;
	
	var form = document.getElementById("loginForm");
	form.submit();
}
//HS016425: login function for self registered users , 
//since the overload function is not working as expected , I am creating different function
function sr_doLogin(formname)
{
	//set message
	var loginMsgDiv = Ext.get("loginMessage");
//	loginMsgDiv.removeClass("loginMessage");
	loginMsgDiv.dom.innerHTML = '<span id="id_loginMessage" style="vertical: middle;"><img src="themes/common/images/loading.gif">&nbsp;&nbsp;'+frmwrk_rm.get("Login_processing_login_request")+'</span>';
//	loginMsgDiv.addClass("loginMessage");
	loginMsgDiv.setVisible(true);
	
	
	xml = sr_createLoginXMLDoc(formname);
	
	var field = formname("xmlString");
	field.value = xml;
	
	var form = formname;
	form.submit();
}

function getSelfRegScreen()
{
	var form = document.getElementById("getSelfRegForm");
	submitForm(form);
}

function doChooseOrg(){

	var form = document.getElementById("lostPasswordForm");

	var fieldPerID = document.getElementById("person_id");
	
	//get the select form object.
	var orgIDSelect = document.getElementById("orgId");
	
	if(orgIDSelect.options.length == 1)
	{
		//orgIDSelect.selectedIndex = 1;
	}
	
	//get the selected orgID
	var orgId = orgIDSelect.value;
	
	//find the selected person id that is in the selected option node.
	var selIndex = orgIDSelect.selectedIndex;
	var personID = orgIDSelect.options[selIndex].personID;
	
	//assign the person_id to the hidden field .
	fieldPerID.value = personID;
	
	//alert("orgId: " + orgId + "\npersonID: " + personID);	
	//alert(submitForm(form,true));
	submitForm(form);
}

//TODO: fix this so it will handle multiple questions (if we are going to support this)
function doAnswerSecurityQues()
{
	//need to count the number of security questions
	var numSecurityQuestions = 0;
	var questionField = document.getElementById("question1");
	var i=0;
	var answerCount = 0;
	
	while(questionField != null && i<10)
	{
		i++;
		questionField = document.getElementById("question"+i);
	}
	//the logic above counts question1 twice... this needs to be rewritten but for now I'm dropping
	//  the count by 1 for an immediate fix (need in prod asap).  
	numSecurityQuestions = i - 1;
	
	//create the xml for the answers to the questions
	qXML = "";
	for(var i = 1; i <= numSecurityQuestions; i++)
	{
		field = document.getElementById("question"+i);

		if(field.value != "")
		{
			answerCount++;
		}
		
		qXML +=		"<QUESTION>"
		+				"<ANSWER>"+field.value+"</ANSWER>"
		+				"<QUESTION_ID>"+field.quesID+"</QUESTION_ID>"
		+			"</QUESTION>";
	}
	
	fieldQxml = document.getElementById("questionXML");
	fieldQxml.value = qXML;
	
	var form = document.getElementById("lostPasswordForm");
	
	if (answerCount == numSecurityQuestions)
	{
		submitForm(form);
	}
	else
	{
		if (numSecurityQuestions == 1)
		{
			alert("You must answer the security question.");
		}
		else
		{
			alert("You must answer all of the security questions.");
		}
	}
}

function doChangePassword()
{
	if (document.lostPasswordForm.new_password.value == document.lostPasswordForm.confirmNewPass.value)
	{
		document.loginForm.password.value = document.lostPasswordForm.new_password.value;
		submitForm("lostPasswordForm");
	}
	else
	{
		alert("The new passwords do not match, please re-enter your new password.");
		document.lostPasswordForm.confirmNewPass.value = "";
		document.lostPasswordForm.confirmNewPass.focus();
	}
}

function changePasswordSuccess()
{
	clmLoginDialog.setActionButton('lost-password-ChangePassword-success','');
}

/**
 * doLostPassword is called when the Next button is clicked on the first page of the 
 * lost password tab workflow
 */
function doLostPassword()
{
	if (document.lostPasswordForm.username.value != '')
	{
		document.loginForm.username.value = document.lostPasswordForm.username.value;
		submitForm('lostPasswordForm');
	}
	else
	{
		alert("You must enter your username.");
	}
}

function getLostPW(link)
{
	document.getElementById('lostpw').style.visibility = "visible";
	document.getElementById('login').style.visibility = "hidden";
	formatRequest(link);
}

function orgId_Initialize(){
	var org_id = frmwrk_rm.get( 'hostOrgID' );
	var orgs = frmwrk_rm.get( 'orgArray' );
	var htmlResults = '';

	if ( !frmwrk_rm.get( 'hostOrgID' ) || org_id == 'undefined' || org_id == '' ){
		if ( orgs ){
			var selectbox = '<span id="id_organizationLabel">Organization</span></br><select id="orgp.o_org_id" name="orgp.o_org_id" style="width: 95%;" >';
			selectbox += '<option value="0"></option>';
			for ( var x = 0; x < orgs.length; x++ ){
				selectbox += '<option value="' +orgs[x]['id'] + '" ';
				if ( selectedOrgId != 'null' && selectedOrgId.length > 0 && selectedOrgId == orgs[x]['id'] ) selectbox += 'selected';
				selectbox += '>' + orgs[x]['name'] + '</option>';
			}
			selectbox += '</select>';
			htmlResults = selectbox;
		}else{
			htmlResults = "";
		}
	}else{
		var hiddeninput = '<input type="hidden" id="orgp.o_org_id" name="orgp.o_org_id" value="' + org_id + '">';
		htmlResults = hiddeninput;
	}
	
	document.getElementById('orgIdDiv').innerHTML = htmlResults;
	//also set the org id in the reset password form
	if (frmwrk_rm.get( 'showPasswordReset' ) == 'true')
    {
		document.getElementById('lostPassOrgIdDiv').innerHTML = htmlResults;
	}
}

function selfRegister_Initialize(){
	var isSelfRegReq = frmwrk_rm.get( 'isSelfRegReq' );
	
	//TEMPORARY... This needs to be changed becuase it may be possible for a URL
	// to be registered with the self reg flag not set... but for now, we need
	// the link to show up when the URL is not registered (for testing purposes)
	if (( isSelfRegReq && isSelfRegReq == 'true' ) || (!isSelfRegReq)){
		document.getElementById('selfRegDiv').style.visibility = 'visible';
	}else{
		document.getElementById('selfRegDiv').style.visibility = 'hidden';
	}
}

function loginInit()
{
	selfRegister_Initialize();	
	orgId_Initialize();
}

function showSelfReg(){
	clmSelfRegDialog.showDialog();
}

var clmSelfRegDialog = function(){

    var dialog, btnCancel, btnSubmit,btnLogin;

    return {
        showDialog : function(){
            if(!dialog){ // lazy initialize the dialog and only create it once
                dialog = new Ext.LayoutDialog("selfReg-dlg", { 
                        modal:true,
                        animate: true,
                        closable: true,
                        autoTabs: false,
                        alwaysShowTabs: false,
                        fitToFrame: true,
                        width: 495,
                        height: 450,
                        shadow: true,
                        minWidth: 300,
                        minHeight: 500
                });	
                btnCancel = dialog.addButton(frmwrk_rm.get("Login_button_cancel"), dialog.hide, dialog);
                btnSubmit = dialog.addButton(frmwrk_rm.get("Login_button_submit"), this.doSelfReg, dialog);
                btnLogin = dialog.addButton(frmwrk_rm.get("Login_button_login"), this.sr_doLogin, dialog);
                dialog.on("hide", this.showSubmitCancel, dialog);
                btnLogin.hide();
              	getSelfRegScreen();
            }	
            dialog.show();
            
        },
        doSelfReg : function(){
        	submitSelfRegistration(btnSubmit);
        },
        enableButton : function() {
          btnSubmit.enable();
        },
        showSubmitCancel : function(){
          	btnCancel.show();
        	btnSubmit.show();
        	btnLogin.hide();      
        	getSelfRegScreen();
        },
        
        showLoginButton : function(){
        	btnCancel.hide();
        	btnSubmit.hide();
        	btnLogin.show();
        },
        
        sr_doLogin : function(){
        	var form = document.getElementById('selfRegLogin');
        	//alert(form.org_id.value+form.username.value);
        	//form.submit();
        	sr_doLogin(form);
        }
    };
}();
