
var BrowserDetect = {
	init: function () {
		    var agt=navigator.userAgent.toLowerCase();

			var allowIE = false;
			var allowMozilla = false;
			var allowOpera = false;
			var allowGChrome = false;
			var allowSafari = false;
			var allowIE10 = false;
			//alert (" navigator.appVersion = " + navigator.appVersion);
			//alert (" navigator.userAgent = " + navigator.userAgent);

			/*if ( agt.indexOf("firefox/") != -1){  //check for mozilla >= 3.6
				var mozilaIdx = agt.indexOf("firefox/");
					mozilaIdx  += "firefox/".length;
				var mozillaSubStr = agt.substring(mozilaIdx, mozilaIdx +3);
				//alert ("mozillaSubStr = " + mozillaSubStr);
				if (mozillaSubStr >= 3.6) {  allowMozilla = true;}
			}else*/
				allowMozilla=true;
				if (agt.indexOf("msie ") != -1){   //Check for IE >=6.0
				var ieIdx = agt.indexOf("msie ");
					ieIdx += "msie ".length;
				var ieSubstr = agt.substring(ieIdx, ieIdx +3);
				//alert ("ieSubstr  = " + ieSubstr );
				if (ieSubstr >= 7.0) { allowIE = true;}
			}/*else if (agt.indexOf("opera/") != -1){   //Check for opera >=9.0
				var opIdx = agt.indexOf("opera/");
					opIdx += "opera/".length;
				var opSubstr = agt.substring(opIdx, opIdx +3);
				//alert ("opSubstr  = " + opSubstr);
				if (opSubstr >= 9.0) { allowOpera = true;}
			}else if ( (agt.indexOf("safari/") != -1) && (agt.indexOf("chrome/") == -1) ) { //Shafari, Gchrome has safari key word and hence need to suppress
				var sfIdx = agt.indexOf("version/");
					sfIdx += "version/".length;
				var sfSubstr = agt.substring(sfIdx, sfIdx +3);
					//alert ("sfSubstr = " + sfSubstr);
				if (sfSubstr >= 5.0){  allowSafari = true;}
			}*/else if (agt.indexOf("chrome/") != -1) { //Google chrome
				var gIdx = agt.indexOf("chrome/");
					gIdx += "chrome/".length;
				var gSubStr = agt.substring(gIdx, gIdx+3);
					//alert (" gSubStr = "  + gSubStr );
				if (gSubStr >= 8.0) { allowGChrome = true;}
			}
			else {
    				var ie10 =  agt.indexOf("trident");
    				var ie10Rv= agt.indexOf("rv");
    				var allowIE10 = (agt.indexOf("trident")>1 && agt.indexOf("rv:")>1)?true : false;
			}
			//return (allowIE||allowMozilla||allowOpera||allowGChrome||allowSafari||allowIE10);
			return (allowIE||allowMozilla||allowIE10||allowGChrome);
 	  },

   checkBrowser: function () {
		//if(!is_ie6up){
		// alert("MICROSOFT INTERNET EXPLORER 6.0 OR ABOVE IS REQUIRED. PLEASE CHECK THE MINIMUM REQUIREMENT(S) FOR USING THIS APPLICATION.");
		// return false;
		// }
		var acceptedBrowser = BrowserDetect.init();
		//alert (" acceptedBrowser = " + acceptedBrowser);
		if(!acceptedBrowser){
			//alert("FIREFOX 3.6.10 OR MICROSOFT INTERNET EXPLORER 7.0 OR OPERA 9.0 OR SAFARI 5.0 OR GOOGLE CHROME 8.0 ABOVE IS REQUIRED. PLEASE CHECK THE MINIMUM REQUIREMENT(S) FOR USING THIS APPLICATION.");
			alert(" MICROSOFT INTERNET EXPLORER 9.0 AND ABOVE IS REQUIRED. PLEASE CHECK THE MINIMUM REQUIREMENT(S) FOR USING THIS APPLICATION.");
			return false;
		}
    },

   redirectTo:function(docType, pUrl) {
		if (docType=='dgh'){
			window.location=pUrl+"/security/getDGHSignInAction.do";
		}
		/*else if (docType=='ccl'){
			window.location=pUrl+"/security/getCCLSignInAction.do";
		}else if (docType=='tnpl'){
			window.location=pUrl+"/security/getTNPLSignInAction.do";
		}*/
		else{
			window.location=pUrl+"/security/getSignInAction.do";
		}
   }

 }
var AdminController = {

	activateSupplier : function	(/*String*/ formName, /*String*/ csrfToken, /*String*/ methodName,
			/*String*/ supplierId, /*String*/ supplierAuthOrgId, /*String*/ supplierAuthCode, /*String*/ supplierIntenssion){

		eval("document."+formName).supplierId.value = supplierId;
		eval("document."+formName).supplierAuthOrgId.value = supplierAuthOrgId;
		eval("document."+formName).supplierAuthCode.value = supplierAuthCode;
		eval("document."+formName).supplierIntenssion.value = supplierIntenssion;

		Controller.onSubmitWithCsrf(formName, csrfToken, methodName, null, null);
	},
	activateAllSupplier : function	(/*String*/ formName, /*String*/ csrfToken, /*String*/ methodName,/*String*/ supplierDscPresent){
		var allActivatedSupplierInfo=eval("document.supplierListForm").allActivatedSupplierInfo.value;
		var reasonComment =eval("document.supplierListForm").reasonComment.value;
		eval("document."+formName).allSupplierInfo.value = allActivatedSupplierInfo;
		eval("document."+formName).supplierDscPresent.value = supplierDscPresent;
		eval("document."+formName).reasonComment.value = reasonComment;
		Controller.onSubmitWithCsrf(formName, csrfToken, methodName, null, null);
	},
	activate : function(/*String*/ formName, /*String*/ csrfToken,/*String*/ methodName,/*String*/ supplierDscPresent){

		if(AdminController.trim(eval("document."+formName).reasonComment.value)==""){
			alert("Please provide the comment");
			return false;
		}
		if(AdminController.trim(eval("document."+formName).reasonComment.value).length > 100)		{
			alert("Comment cannot contain more than 100 characters");
			return false;
		}
		else{

			eval("document."+formName).newUserSelectedFlag.value = "Y";
			eval("document."+formName).newSupDscPresent.value = supplierDscPresent;
			eval("document."+formName).reject.value = 'false';
			Controller.onSubmitWithCsrf(formName, csrfToken, methodName, null, null);

		}
	},

	mjAuthCodeValidation : function (mjAuthCodeInput, messageDiv, formName, authenticationOrg, csrfToken, userLoginCodePrefix, serverLocation) {
		var onlyNumberPattern = /^[0-9]+$/i;
		var alphaNumericPattern = /^[A-Za-z0-9]+$/;
		var alphaNumericSpecialPattern = /^[A-Za-z0-9()/ -]+$/;
		var orgsList = interestedOrgList.toString();
		var mjAuthCode = AdminController.trim(mjAuthCodeInput);
		var submitFormName = eval("document."+formName).inputFormName.value;
		var codePatternSuccess = false;
		var minAuthCodeLength = 0;
		document.getElementById(messageDiv).innerHTML = "";

		if(serverLocation == 'BHEL'){
			minAuthCodeLength = 8;
		}
		else{
			minAuthCodeLength = 6;
		}

		if(userLoginCodePrefix == 'OTN'){
			if(!alphaNumericSpecialPattern.test(mjAuthCode)) {
				document.getElementById(messageDiv).innerHTML ="Provide proper Login Code without using any special characters";
				document.getElementById(messageDiv).style.color = "#E90404";
				eval("document."+submitFormName).vendorCodeStatus.value = 'N';
				return false;
			}
			else{
				codePatternSuccess = true;
			}
		}
		else{
			if(serverLocation == 'BHEL'){
				if(!onlyNumberPattern.test(mjAuthCode)) {
					document.getElementById(messageDiv).innerHTML ="Provide proper Login Code without using any alphabet and special characters";
					document.getElementById(messageDiv).style.color = "#E90404";
					eval("document."+submitFormName).prefLoginCodeStatus.value = 'N';
					return false;
				}
				else{
					codePatternSuccess = true;
				}
			}
			else{
				if(!alphaNumericSpecialPattern.test(mjAuthCode)) {
					document.getElementById(messageDiv).innerHTML ="Provide proper Login Code without using any special characters";
					document.getElementById(messageDiv).style.color = "#E90404";
					eval("document."+submitFormName).prefLoginCodeStatus.value = 'N';
					return false;
				}
				else{
					codePatternSuccess = true;
				}
			}
		}

		if(codePatternSuccess){
			if((userLoginCodePrefix != 'OTN') && (serverLocation == 'BHEL')){
				mjAuthCode = userLoginCodePrefix + mjAuthCode;
			}

			if (mjAuthCode.length >= minAuthCodeLength && mjAuthCode.length <= 24){
				if(authenticationOrg > 0){
					eval("document."+formName).authenticationOrganization.value = authenticationOrg;
				}
				else{
					if(interestedOrgList.length > 0){
						eval("document."+formName).authenticationOrganization.value = orgsList;
					}
				}

		   		eval("document."+formName).mjAuthCode.value = mjAuthCode;
				eval("document."+formName).authMsgDivName.value = messageDiv;
				eval("document."+formName).userLoginCodePrefix.value = userLoginCodePrefix;
				$("#prefLoginCode").attr("disabled",true);
				Controller.onSubmitWithCsrf(formName, csrfToken, 'chechMJCode', null, AdminController.checkMJAuthCodeValidation);
			}
			else{
				if(mjAuthCode.length < minAuthCodeLength){
					if(serverLocation == 'BHEL'){
						document.getElementById(messageDiv).innerHTML = "Login Code should be 8 - 24 characters in length and can only use numeric values";
					}
					else{
						document.getElementById(messageDiv).innerHTML = "Login Code should be 6 - 24 characters in length and can only use alphabets and numeric values";
					}
				}

				if(userLoginCodePrefix == 'OTN'){
					eval("document."+submitFormName).vendorCodeStatus.value = 'N';
				}
				else{
					eval("document."+submitFormName).prefLoginCodeStatus.value = 'N';
				}

				document.getElementById(messageDiv).style.color = "#E90404";
				return false;
			}
		}
	},

	checkMJAuthCodeValidation : function (data){
		$("#prefLoginCode").attr("disabled",false);
		$("#prefLoginCode").focus();
		if (data.json.mjAuthCodeStatus == 'true'){
			document.getElementById(data.json.authMsgDivName).innerHTML = 'LOGIN CODE : '+data.json.mjAuthCode+' Already Exists.';
			if(data.json.authMsgDivName == 'buyerOrgMsgDiv'){
				document.getElementById(data.json.authMsgDivName).style.color = "#06A409";
				document.getElementById(data.json.authMsgDivName).innerHTML = 'LOGIN CODE : '+data.json.mjAuthCode+' Valid And Exist.';
			}
			else
				{
			document.getElementById(data.json.authMsgDivName).style.color = "#E90404";
				}

			if(data.json.userLoginCodePrefix == 'OTN'){
				document.getElementById(data.json.submitFormName).vendorCodeStatus.value = 'Y';
			}
			else{
				document.getElementById(data.json.submitFormName).prefLoginCodeStatus.value = 'N';
			}
		}
		else if (data.json.mjAuthCodeStatus == 'false'){
			document.getElementById(data.json.authMsgDivName).innerHTML = 'LOGIN CODE : '+data.json.mjAuthCode+' is Available.';
			if(data.json.authMsgDivName == 'buyerOrgMsgDiv'){
				document.getElementById(data.json.authMsgDivName).style.color = "#E90404";
				document.getElementById(data.json.authMsgDivName).innerHTML = 'LOGIN CODE : '+data.json.mjAuthCode+' Does Not Exist. In Case Of Not Enlisted User Please Use Interested Option To Register';
			}
			else{
			document.getElementById(data.json.authMsgDivName).style.color = "#06A409";
			}

			if(data.json.userLoginCodePrefix == 'OTN'){
				document.getElementById(data.json.submitFormName).vendorCodeStatus.value = 'N';
			}
			else{
				document.getElementById(data.json.submitFormName).prefLoginCodeStatus.value = 'Y';
				markMandatory(document.getElementById(data.json.submitFormName).prefLoginCode, false);
			}
		}
	},

	LTrim : function( value )
	{
		var re = /\s*((\S+\s*)*)/;
		return value.replace(re, "$1");

	},

	RTrim : function ( value )
	{
		var re = /((\s*\S+)*)\s*/;
		return value.replace(re, "$1");
	},

	trim : function ( value )
	{
		return AdminController.LTrim(AdminController.RTrim(value));
	},

	reject : function(/*String*/ formName, /*String*/ csrfToken,/*String*/ methodName,/*String*/ supplierDscPresent){
		if(AdminController.trim(eval("document."+formName).reasonComment.value)=="")
		{
			alert("Please provide the comment");
			return false;
		}
		if(AdminController.trim(eval("document."+formName).reasonComment.value).length > 100)
		{
			alert("Comment cannot contain more than 100 characters");
			return false;
		}
		eval("document."+formName).reject.value = 'true';
		eval("document."+formName).newSupDscPresent.value = supplierDscPresent;
		Controller.onSubmitWithCsrf(formName, csrfToken, methodName, null, null);
	},

	printReg : function (/*String*/ formName, /*String*/ csrfToken,/*String*/ methodName,/*String*/ userId){
		eval("document."+formName).userId.value=userId;
		eval("document."+formName).tableName.value="EPS.DRAFTUSER";
		eval("document."+formName).target="_blank";
		Controller.onSubmitWithCsrf(formName, csrfToken, methodName, null, null);
	},

	modifySupplier : function (/*String*/ userId, /*String*/ sellerOrgId, /*String*/ buyerOrganization,
			/*String*/ userAuthentication, /*String*/ formName, /*String*/ csrfToken, /*String*/ methodName, /*String*/ supplierIntenssion)
	{

		var selectId = userId+'|'+sellerOrgId;

		eval("document."+formName).selectId.value = selectId;
		eval("document."+formName).buyerOrganization.value = buyerOrganization;
		eval("document."+formName).userAuthentication.value = userAuthentication;
		eval("document."+formName).supplierIntenssion.value = supplierIntenssion;
		Controller.onSubmitWithCsrf(formName, csrfToken, methodName, null, null);
	},

	checkingAdminAction : function(flagForadminaction,formName, csrfToken, methodName) {
		eval("document."+formName).elements['additionalContact.mobileNo'].value = eval("document."+formName).elements['contact.mobileNo'].value;
		eval("document."+formName).elements['additionalContact.phoneNo'].value = eval("document."+formName).elements['contact.phoneNo'].value;
		eval("document."+formName).elements['additionalContact.contactFax'].value = eval("document."+formName).elements['contact.contactFax'].value;
		eval("document."+formName).elements['additionalContact.address1'].value = eval("document."+formName).elements['contact.address1'].value;
		eval("document."+formName).elements['additionalContact.address2'].value = eval("document."+formName).elements['contact.address2'].value;
		eval("document."+formName).elements['additionalContact.country.id'].value = eval("document."+formName).elements['country.id'].value;
		eval("document."+formName).elements['additionalContact.state.id'].value = eval("document."+formName).elements['state.id'].value;
		eval("document."+formName).elements['additionalContact.city.id'].value = eval("document."+formName).elements['city.id'].value;
		eval("document."+formName).elements['additionalContact.postalCode'].value = eval("document."+formName).elements['contact.postalCode'].value;
		eval("document."+formName).functionPerformed.value=flagForadminaction;
		Controller.onSubmitWithCsrf(formName, csrfToken, methodName, null, null);
	},

	modifyProcCat : function(formName, csrfToken, methodName)
	{
		eval("document."+formName).methodName.value='populateProcurementCategory';
		eval("document."+formName).elements['additionalContact.mobileNo'].value = eval("document."+formName).elements['contact.mobileNo'].value;
		eval("document."+formName).elements['additionalContact.phoneNo'].value = eval("document."+formName).elements['contact.phoneNo'].value;
		eval("document."+formName).elements['additionalContact.contactFax'].value = eval("document."+formName).elements['contact.contactFax'].value;
		eval("document."+formName).elements['additionalContact.address1'].value = eval("document."+formName).elements['contact.address1'].value;
		eval("document."+formName).elements['additionalContact.address2'].value = eval("document."+formName).elements['contact.address2'].value;
		eval("document."+formName).elements['additionalContact.country.id'].value = eval("document."+formName).elements['country.id'].value;
		eval("document."+formName).elements['additionalContact.state.id'].value = eval("document."+formName).elements['state.id'].value;
		eval("document."+formName).elements['additionalContact.city.id'].value = eval("document."+formName).elements['city.id'].value;
		eval("document."+formName).elements['additionalContact.postalCode'].value = eval("document."+formName).elements['contact.postalCode'].value;
		Controller.onSubmitWithCsrf(formName, csrfToken, methodName, null, null);
	},

	submitPrefCat : function(formName, csrfToken, methodName){
		var length = eval("document."+formName).subCat.length;
		var checking=false;
		if(length>1){
			for(var i=0;i<eval("document."+formName).subCat.length;i++){
				if(eval("document."+formName).subCat[i].checked){
					checking=true;
					break;
				}
			}
		}
		else{
			if(eval("document."+formName).subCat.checked==true){
				checking=true;
			}
		}
		if(!checking){
			alert("Select at least one subcategory");
			return false;
		}
		Controller.onSubmitWithCsrf(formName, csrfToken, methodName, null, null);
	},

	myFunctionV2:function(formName,digCertId){
		eval("document."+formName).methodName.value='getCommentHistoryListForDigCertId';
		eval("document."+formName).digCertId.value=digCertId;
		//document.sectionAddForm.submit();
		window.open('', 'addCommentHistory_window', 'top=150, left=110, height=500, width=800, toolbar=no, status=no ,scrollbars=1,resizable=1');
		//document.addCorrigendumForm.target="addCommentHistory_window";
		eval("document."+formName).target="addCommentHistory_window";
		eval("document."+formName).submit();
	},

	myFunction:function(formName,digCertId,rowNum,csrfToken,methodName,rowNumV2,certificateOwnerId) {
	    var myVar =document.getElementsByName('approveStatus')[rowNum].value;
	    var commentFieldValue = document.getElementsByName('commnetBox')[rowNumV2].value;
	    commentFieldValue=$.trim(commentFieldValue);
	    //alert("commentFiledValue="+ commentFieldValue);
	    if (myVar=='D'){
	        var r = confirm( "Post de-association, user will not be able to access this mapping along with associated information/documents. Please confirm ?");
	        if (r == true || r=='true') {
	        	eval("document."+formName).comments.value=commentFieldValue;
	        	javascript:AdminController.changeDigitalCertStatus(formName,digCertId,rowNum,csrfToken,methodName,certificateOwnerId);
	        }else{
	        	return false;
	        }
	    }
	    else
	    {
	    	if(commentFieldValue == "" && (commentFieldValue.length) == 0){
	    		alert("Please enter some valid comments and comments should be within 500 character.");
	    		return false;
	    	}
	    	else if( (commentFieldValue.length) > 0 && (commentFieldValue.length) <=500){
	    		eval("document."+formName).comments.value=commentFieldValue;
	    		javascript:AdminController.changeDigitalCertStatus(formName,digCertId,rowNum,csrfToken,methodName,certificateOwnerId);
	    		return true;
	    	}
	    	else{
	    		alert("Please enter comments within 500 character.");
	    		return false;
	    	}
	    }
	} ,

	changeDigitalCertStatus :function (formName,digCertId,rowNum,csrfToken,methodName,certificateOwnerId){
		var status=document.getElementsByName('approveStatus')[rowNum].value;
		var bOrgName=document.getElementsByName('orgName')[rowNum].value;
		var authCode=document.getElementsByName('authCode')[rowNum].value;
		eval("document."+formName).buyerOrgName.value=bOrgName;
		eval("document."+formName).authenticationCode.value=authCode;
		eval("document."+formName).approvalStatus.value=status;
		eval("document."+formName).userDigitalCertId.value=digCertId;

		eval("document."+formName).certificateOwnerId.value=certificateOwnerId;
		Controller.onSubmitWithCsrf(formName,csrfToken,methodName,null,null);
	},

	updateProfile : function(formName, csrfToken, methodName, exUserId,updateStatus){
		var flagString = "";
		if(updateStatus=='U')flagString = "UPDATE THE EXISTING PROFILE ?";
		else if(updateStatus =='UA')flagString = "UPDATE AND ACTIVATE THE PROFILE ?";
		var submit = confirm("DO YOU WANT TO "+flagString);
	  	if(submit == true) {
	  		eval("document."+formName).exUserId.value=exUserId;
	  		eval("document."+formName).updateStatus.value=updateStatus;
	  		//eval("document."+formName).action="<c:url value='/business/admin.action'/>?methodName="+methodName;
	  		Controller.onSubmitWithCsrf(formName,csrfToken,methodName,null,null);
	 	}
	},

	hideMsgBox :function (divId){
		$("."+divId).hide();
	},
	saveProcGrpUser :function (formName,methodName,selectedUserList,csrfToken){
		var nLength = eval("document."+formName+"."+selectedUserList).options.length;
			for(var nIndex = 0; nIndex < nLength; nIndex++)
			{
				eval("document."+formName+"."+selectedUserList)[nIndex].selected = true;
			}
		Controller.onSubmit(formName,null,methodName,null,null);
	},
	remove :function (formName,userList,selectedUserList)
	{
			   var nLength = eval("document."+formName+"."+selectedUserList).options.length;
				if (nLength >= 0)
				{
					for(var nIndex = --nLength; nIndex >= 0; nIndex--)
					{
						if(eval("document."+formName+"."+selectedUserList).options[nIndex].selected)
						{
							var optionValue = "",optionText= "";
							optionValue = eval("document."+formName+"."+selectedUserList).options[nIndex].value;
							optionText = eval("document."+formName+"."+selectedUserList).options[nIndex].text;
							var optionName = new Option(optionText, optionValue)
							var nlength = eval("document."+formName+"."+userList).length;
				 			eval("document."+formName+"."+userList).options[nlength] = optionName;

							eval("document."+formName+"."+selectedUserList).options[nIndex] = null;
						}
					}
				}
	},
	add :function (formName,userList,selectedUserList)
		{
			var nLength = eval("document."+formName+"."+userList).options.length;
			  if (nLength > 0)
				{
					for(var nIndex = --nLength; nIndex >= 0; nIndex--)
					{
						if(eval("document."+formName+"."+userList).options[nIndex].selected)
						{
							var optionValue = "",optionText= "";
							optionValue = eval("document."+formName+"."+userList).options[nIndex].value;
							optionText = eval("document."+formName+"."+userList).options[nIndex].text;
							var optionName = new Option(optionText, optionValue);
							var nlength = eval("document."+formName+"."+selectedUserList).length;
				 			eval("document."+formName+"."+selectedUserList).options[nlength] = optionName;
							eval("document."+formName+"."+userList).options[nIndex] = null;
						}
					}
				}

		   },
   addHoliday: function (/* String */ tableId) {
		tbody=document.getElementById(tableId);
//			    var index = tbody.rows.length - 2;
	    var index = tbody.rows.length;
	    if (index<0) index=0;
	    if (!AdminController.validateAddHoliday(index)) return;
	    var newRow=tbody.insertRow(tbody.rows.length);
	    var cell0 = newRow.insertCell(0);
	    cell0.setAttribute('class','dataClass');
	    cell0.setAttribute('align','left');
	    cell0.setAttribute('width','25%');
	    cell0.innerHTML = '<input type="text" size="20" name="holidays['+index+'].description"/>';

	    var cell1 = newRow.insertCell(1);
	  	cell1.setAttribute('class','dataClass');
	  	cell1.setAttribute('align','left');
	  	cell1.setAttribute('width','40%');
	  	cell1.innerHTML = '<input type="text" size="22" maxlength="99" readonly="true" id="holidays['+index+'].date" name="holidays['+index+'].date"/><a href="javascript:calendar(\'holidays['+index+'].date\',\'ddMMyyyy\',false,24);"><img src="' + contextRoot + '/image/Calendar.gif" border="0" /></a>';

	  	var cell2 = newRow.insertCell(2);
	  	cell2.setAttribute('width','15%');
	  	cell2.innerHTML='<a href="#" onclick="AdminController.delHoliday(\'' + tableId + '\', this.parentNode.parentNode.rowIndex);">DELETE</a>';

	  	var cell3 = newRow.insertCell(3);
	  	cell3.setAttribute('width','20%');
	},

	validateAddHoliday : function (/*int*/ index) {
		var maxSize = 5 ; /*<c:out value="${_maxRFQAttachSize}"/>;*/
	    if(index == maxSize)
	    {
	    	alert("Maximum "+maxSize+" holidays can be added");
	    	return false;
	    }
	    if (index>0) {
	    	var lastDescription = document.getElementById("holidays["+(index-1)+"].description");
		    if(null!=lastDescription) {
			    if((lastDescription.value=='') || (lastDescription.value==null)) {
			    	alert("Please specify the Description for previous row");
			    	return false;
			    }
			}
		    var lastDate = document.getElementById("holidays["+(index-1)+"].date");
		    if(null!=lastDate) {
			    if((lastDate.value=='') || (lastDate.value==null)) {
			    	alert("Please specify the Date for previous row");
			    	return false;
			    }
			}
	    }
	    return true;
	},
	delHoliday :function(/*String*/ tableId, /*int*/ index) {
		tbody = document.getElementById(tableId);
	  	if (confirm('Delete the holiday?')) tbody.deleteRow(index);
	},
	saveUsers :function (formName,methodName,selectedUserList,csrfToken){
		var nLength = eval("document."+formName+"."+selectedUserList).options.length;
			for(var nIndex = 0; nIndex < nLength; nIndex++)
			{
				eval("document."+formName+"."+selectedUserList)[nIndex].selected = true;
			}
		/*Controller.onSubmit(formName,null,methodName,null,null);*/
			document.selectUsersForm.submit();
	},
	
	validateEmdFeeForm :function(counterIndex) {
		var eleId="";
		var ins=2;
		var cur=2;
		for(var i=0;i<=counterIndex;i++ ){
			eleId="setupMasterList["+i+"].exist1";
			if(document.getElementById(eleId).checked){
				ins=0;
				cur=0;
				$("#insIdsList_"+i).find("input[type='checkbox']").each(function(){
					if ($(this).prop('checked')==true){ 
						ins=1;
				    }
				});
				$("#currIdsList_"+i).find("input[type='checkbox']").each(function(){
					if ($(this).prop('checked')==true){ 
						cur=1;
				    }
				});
				if(!(ins==1 && cur==1)){
					break;
				}
			}		
		}
		if(ins==0){
			alert("Please check Instrument Payment");
		}
		else if(cur==0){
			alert("Please check currency");
		}
		else if(ins==2 && cur==2){
			alert("You have not selected any option");
		}
		else{
			document.initFeeEmdForm.submit();
		}
		
	},
	updateUserRole :function(formName) {
	var roleId = document.getElementById('roleId').value;	
	if(roleId==null || roleId=='')
		{
		alert('Select role to update');
		return false;
		}
	var name = document.getElementById('userNameCode').value;	
		if(confirm('Do you want to update role of '+name+''))
			return true;
		else
			return false;
	}
}


var TemplateController = {

	saveAnswer :function (){
		$("#_msgBox").empty();
		Controller.onSubmit('answerAddForm',null,'saveDocumentSectionAnswer',null,null);
	},
	showQuestionAttr : function(/*int*/ questiontype,/*int*/ index){
		var id = "_"+questiontype+"_"+index;
		//alert("id...xxxxxxxxxxx"+id);
		document.getElementById(id).style.display = "block";
	},
	openQuestionAttrList : function(/*int*/index,crsfToken){
			//alert("index..."+index+"...orgId..."+orgId);

			var url = contextRoot+"/business/template.handle?methodName=getQuestionAttrList&index="+index+"&"+crsfToken;
			//alert("url..."+url);
			window.open(url, 'getQuestionAttrList_window', 'width=460,height=500,scrollbars=yes,resizable=yes');
	},
	openDocumentQuestionAttrList : function(/*int*/ docQuestionIndex,/*int*/ index,/*boolean*/ integrated , /*boolean*/ isRow){
		var url = contextRoot+"/business/template.handle?methodName=getDocumentQuestionAttrList&index="+index+"&questionIndex="+docQuestionIndex+"&integrated="+integrated+"&isRow="+isRow;
		var csrfEle = document.documentQuestionAddForm.OWASP_CSRFTOKEN;
		if(typeof csrfEle!='undefined'){
				var csrf = document.documentQuestionAddForm.OWASP_CSRFTOKEN.value;
				url = url + "&OWASP_CSRFTOKEN="+csrf;
			}
			window.open(url, 'getDocumentQuestionAttrList_window','width=460,height=500,scrollbars=yes,resizable=yes');
},
openQuestionAttrList : function(/*int*/ questionIndex,/*int*/ index,/*boolean*/ integrated , /*boolean*/ isRow){
			//alert("questionIndex..."+questionIndex+"...index..."+index+"....integrated..."+integrated+"...isRow..."+isRow);
			var url = contextRoot+"/business/template.handle?methodName=getQuestionAttrList&index="+index+"&questionIndex="+questionIndex+"&integrated="+integrated+"&isRow="+isRow;
			var csrfEle = document.questionAddForm.OWASP_CSRFTOKEN;
			//alert(csrfEle);
			if(typeof csrfEle!='undefined'){
				/*var csrf = document.questionAddForm.OWASP_CSRFTOKEN.value;*/
				var csrf = $("#OWASP_CSRFTOKEN").val();
				//alert(csrf);
				url = url + "&OWASP_CSRFTOKEN="+csrf;
			}
			window.open(url, 'getQuestionAttrList_window','width=720,height=400,scrollbars=yes,resizable=no,titlebar=no,toolbar=no');
			//window.open(url, 'getQuestionAttrList_window');
	},
	getQuestionGroupByGoToPage : function(csrfToken){
		    	var formNode = $("form[id!='dummyForm']","#_content");
	    	var searchPageNumber = $('input[id="searchPageNumber"]',formNode).get(0);
	    	//log('calling getItem with code='+code);
	    	if (searchPageNumber.value=='') return;
	Controller.loadPage(contextRoot+'/business/template.handle?methodName=getQuestionGroupListByPagination&pageNumber='+searchPageNumber.value+'&'+csrfToken,null,null);
	},
	searchQuestionGroupByCode : function(csrfToken){
		    var formNode = $("form[id!='dummyForm']","#_content");
	    	var code = $('input[name="searchByLotCode"]',formNode).get(0);
	    	if (code.value=='') return;
	Controller.loadPage(contextRoot+'/business/template.handle?methodName=searchQuestionGroupByCode&code='+code.value+'&'+csrfToken,null,null);
	},
	getQuestionGroup : function (csrfToken){
		    	var formNode = $("form[id!='dummyForm']","#_content");
	    	var code = $('input[name="code"]',formNode).get(0);
	    	if (code.value=='') return;
	Controller.loadPage(contextRoot+'/business/template.handle?methodName=initAddQuestionGroup&code='+code.value+'&'+csrfToken,null,null);
	},
	addRow : function(tbodyId){
			var myTbody=document.getElementById(tbodyId);
			var index = myTbody.rows.length ;
			if (index<0) index=0;
			//var table = document.getElementById('quesAttrTab');
			var lastRow = myTbody.rows[index-1];
			var lastRowId = lastRow.id;
			var lastRowIndex = lastRowId.substring(3);
			index = parseInt(lastRowIndex)+1;
			newRow=myTbody.rows[1].cloneNode(true);
			newRow.setAttribute("id","row"+index);
			var tdArr = newRow.getElementsByTagName('td');

			var tdAttValType = tdArr[0];
			var tdAttValTypeArr = tdAttValType.getElementsByTagName('select');
			var tdElementAttValType = tdAttValTypeArr[0];
			tdElementAttValType.setAttribute("id","questionAttributeList["+index+"].attributeValueType.id");
			tdElementAttValType.setAttribute("name","questionAttributeList["+index+"].attributeValueType.id");
			tdElementAttValType.setAttribute("onchange","javascript:TemplateController.changeAttValType("+tbodyId+","+index+");");

			var tdDesc = tdArr[1];
			var tdDescArr = tdDesc.getElementsByTagName('input');
			var tdElementDesc = tdDescArr[0];
			tdElementDesc.setAttribute("id","questionAttributeList["+index+"].description");
			tdElementDesc.setAttribute("name","questionAttributeList["+index+"].description");
			tdElementDesc.value='';

			var tdMinVal = tdArr[2];
			var tdMinValArr = tdMinVal.getElementsByTagName('input');
			var tdElementMinVal = tdMinValArr[0];
			tdElementMinVal.setAttribute("id","questionAttributeList["+index+"].minVal");
			tdElementMinVal.setAttribute("name","questionAttributeList["+index+"].minVal");
			tdElementMinVal.value='0.00';

			var tdMaxVal = tdArr[3];
			var tdMaxValArr = tdMaxVal.getElementsByTagName('input');
			var tdElementMaxVal = tdMaxValArr[0];
			tdElementMaxVal.setAttribute("id","questionAttributeList["+index+"].maxVal");
			tdElementMaxVal.setAttribute("name","questionAttributeList["+index+"].maxVal");
			tdElementMaxVal.value='0.00';

			var tdDfltVal = tdArr[4];
			var tdDfltValArr = tdDfltVal.getElementsByTagName('input');
			var tdElementDfltVal = tdDfltValArr[0];
			tdElementDfltVal.setAttribute("id","questionAttributeList["+index+"].defaultValue");
			tdElementDfltVal.setAttribute("name","questionAttributeList["+index+"].defaultValue");
			tdElementDfltVal.value='';


			var tdOptionVal = tdArr[5];
			var tdOptionValArr = tdOptionVal.getElementsByTagName('input');
			var tdElementOptionVal = tdOptionValArr[0];
			tdElementOptionVal.setAttribute("id","questionAttributeList["+index+"].optionValues");
			tdElementOptionVal.setAttribute("name","questionAttributeList["+index+"].optionValues");
			tdElementOptionVal.value='';

			var tdVisibility = tdArr[6];
			var tdVisibilityArr = tdVisibility.getElementsByTagName('select');
			var tdElementVisibility = tdVisibilityArr[0];
			tdElementVisibility.setAttribute("id","questionAttributeList["+index+"].visibility");
			tdElementVisibility.setAttribute("name","questionAttributeList["+index+"].visibility");

			var tdMand = tdArr[7];
			var tdMandArr = tdMand.getElementsByTagName('select');
			var tdElementMand = tdMandArr[0];
			tdElementMand.setAttribute("id","questionAttributeList["+index+"].mandatory");
			tdElementMand.setAttribute("name","questionAttributeList["+index+"].mandatory");

			var tdEdit = tdArr[8];
			var tdEditArr = tdEdit.getElementsByTagName('select');
			var tdElementEdit = tdEditArr[0];
			tdElementEdit.setAttribute("id","questionAttributeList["+index+"].editable");
			tdElementEdit.setAttribute("name","questionAttributeList["+index+"].editable");

			var tdMaxSize = tdArr[9];
			var tdMaxSizeArr = tdMaxSize.getElementsByTagName('input');
			var tdElementMaxSize = tdMaxSizeArr[0];
			tdElementMaxSize.setAttribute("id","questionAttributeList["+index+"].maxSize");
			tdElementMaxSize.setAttribute("name","questionAttributeList["+index+"].maxSize");
			tdElementMaxSize.value='0';

			var tdDeleteRow = tdArr[10];
			tdElementMaxSize.setAttribute("display","block");
			tdDeleteRow.innerHTML='<a class="pageContentLink" href="javascript:TemplateController.deleteRow('+tbodyId+','+index+');">DELETE ROW</a>';

			myTbody.appendChild(newRow);


	},
	deleteRow :function(/*String*/ tbodyId, /*int*/ index)
	{
		var row = document.getElementById('row'+index);
		if (confirm('Delete The Row?')){
			document.questionAttributeAddForm.deletedQuestionIndex.value = document.questionAttributeAddForm.deletedQuestionIndex.value+","+index ;
			row.parentNode.removeChild(row);
		}

	},
	setDefaultValue :function(/*String*/ tbodyId,/*int*/ index) {
		var myTbody=document.getElementById(tbodyId);
		var rowName = 'row'+index;
		var row = document.getElementById(rowName);
		var tdArr = row.getElementsByTagName('td');
		var tdMinVal = tdArr[2];
		var tdMinValArr = tdMinVal.getElementsByTagName('input');
		var tdElementMinVal = tdMinValArr[0];
		var tdMaxVal = tdArr[3];
		var tdMaxValArr = tdMaxVal.getElementsByTagName('input');
		var tdElementMaxVal = tdMaxValArr[0];
		var tdDfltVal = tdArr[4];
		var tdDfltValArr = tdDfltVal.getElementsByTagName('input');
		var tdElementDfltVal = tdDfltValArr[0];
		var tdOptionVal = tdArr[5];
		var tdOptionValArr = tdOptionVal.getElementsByTagName('input');
		var tdElementOptionVal = tdOptionValArr[0];
		var tdMaxSize = tdArr[9];
		var tdMaxSizeArr = tdMaxSize.getElementsByTagName('input');
		var tdElementMaxSize = tdMaxSizeArr[0];

		tdElementMaxVal.value='0.00';
		tdElementMaxSize.value='0';
		tdElementMinVal.value='0.00';
		tdElementOptionVal.value='';
		tdElementDfltVal.value='';
	},
	changeAttValType :function(/*String*/ tbodyId,/*int*/ index)
	{
		var myTbody=document.getElementById(tbodyId);
		var rowName = 'row'+index;
		var row = document.getElementById(rowName);
		var tdArr = row.getElementsByTagName('td');
		var tdAttValType = tdArr[0];
		var tdAttValTypeArr = tdAttValType.getElementsByTagName('select');
		var attValType = tdAttValTypeArr[0].value;

		var tdDesc = tdArr[1];
		var tdDescArr = tdDesc.getElementsByTagName('input');
		var tdElementDesc = tdDescArr[0];

		var tdMinVal = tdArr[2];
		var tdMinValArr = tdMinVal.getElementsByTagName('input');
		var tdElementMinVal = tdMinValArr[0];

		var tdMaxVal = tdArr[3];
		var tdMaxValArr = tdMaxVal.getElementsByTagName('input');
		var tdElementMaxVal = tdMaxValArr[0];

		var tdDfltVal = tdArr[4];
		var tdDfltValArr = tdDfltVal.getElementsByTagName('input');
		var tdElementDfltVal = tdDfltValArr[0];

		var tdOptionVal = tdArr[5];
		var tdOptionValArr = tdOptionVal.getElementsByTagName('input');
		var tdElementOptionVal = tdOptionValArr[0];

		var tdVisibility = tdArr[6];
		var tdVisibilityArr = tdVisibility.getElementsByTagName('select');
		var tdElementVisibility = tdVisibilityArr[0];

		var tdMand = tdArr[7];
		var tdMandArr = tdMand.getElementsByTagName('select');
		var tdElementMand = tdMandArr[0];

		var tdEdit = tdArr[8];
		var tdEditArr = tdEdit.getElementsByTagName('select');
		var tdElementEdit = tdEditArr[0];

		var tdMaxSize = tdArr[9];
		var tdMaxSizeArr = tdMaxSize.getElementsByTagName('input');
		var tdElementMaxSize = tdMaxSizeArr[0];

		var minValDivIndex = 'minValDiv'+index;
		var maxValDivIndex = 'maxValDiv'+index;
		var optionValDivIndex = 'optionValDiv'+index;
		var maxSizeDivIndex = 'maxSizeDiv'+index;
		var minValCalDivIndex = 'minValCalDiv'+index;
		var maxValCalDivIndex = 'maxValCalDiv'+index;
		var dfltValCalDivIndex = 'dfltValCalDiv'+index;

		var minValDiv = document.getElementById(minValDivIndex);
		var maxValDiv = document.getElementById(maxValDivIndex);
		var optionValDiv = document.getElementById(optionValDivIndex);
		var maxSizeDiv = document.getElementById(maxSizeDivIndex);
		var minValCalDiv = document.getElementById(minValCalDivIndex);
		var maxValCalDiv = document.getElementById(maxValCalDivIndex);
		var dfltValCalDiv = document.getElementById(dfltValCalDivIndex);

		if(attValType==100){
			maxSizeDiv.style.visibility='hidden';
			maxValDiv.style.visibility='visible';
			minValDiv.style.visibility='visible';
			optionValDiv.style.visibility='hidden';
			minValCalDiv.style.visibility='hidden';
			maxValCalDiv.style.visibility='hidden';
			dfltValCalDiv.style.visibility='hidden';
			TemplateController.setDefaultValue(tbodyId,index);
		}else if(attValType==101){
			maxSizeDiv.style.visibility='hidden';
			maxValDiv.style.visibility='visible';
			minValDiv.style.visibility='visible';
			optionValDiv.style.visibility='hidden';
			minValCalDiv.style.visibility='hidden';
			maxValCalDiv.style.visibility='hidden';
			dfltValCalDiv.style.visibility='hidden';
			TemplateController.setDefaultValue(tbodyId,index);
		}else if(attValType==102){
			maxSizeDiv.style.visibility='visible';
			maxValDiv.style.visibility='hidden';
			minValDiv.style.visibility='hidden';
			optionValDiv.style.visibility='hidden';
			minValCalDiv.style.visibility='hidden';
			maxValCalDiv.style.visibility='hidden';
			dfltValCalDiv.style.visibility='hidden';
			TemplateController.setDefaultValue(tbodyId,index);
		}else if(attValType==103){
			maxSizeDiv.style.visibility='visible';
			maxValDiv.style.visibility='hidden';
			minValDiv.style.visibility='hidden';
			optionValDiv.style.visibility='hidden';
			minValCalDiv.style.visibility='hidden';
			maxValCalDiv.style.visibility='hidden';
			dfltValCalDiv.style.visibility='hidden';
			TemplateController.setDefaultValue(tbodyId,index);
		}else if(attValType==104){
			maxSizeDiv.style.visibility='hidden';
			maxValDiv.style.visibility='visible';
			minValDiv.style.visibility='visible';
			optionValDiv.style.visibility='hidden';
			minValCalDiv.style.visibility='visible';
			maxValCalDiv.style.visibility='visible';
			dfltValCalDiv.style.visibility='visible';
			TemplateController.setDefaultValue(tbodyId,index);
		}else if(attValType==105){
			maxSizeDiv.style.visibility='hidden';
			maxValDiv.style.visibility='hidden';
			minValDiv.style.visibility='hidden';
			optionValDiv.style.visibility='visible';
			minValCalDiv.style.visibility='hidden';
			maxValCalDiv.style.visibility='hidden';
			dfltValCalDiv.style.visibility='hidden';
			TemplateController.setDefaultValue(tbodyId,index);
		}
	},
	validateTemplateSearch : function (csrfToken){
			var startDate = document.getElementById("templateCreateDateFrom").value;
			var endDate = document.getElementById("templateCreateDateTo").value;
			if(startDate != ""){
				if(endDate == ""){
				alert("Please specify the Proposal Create Date To correctly");
				return false;
				}
			} else if(endDate != ""){
				if(startDate == ""){
				alert("Please specify the Proposal Create Date From correctly");
				return false;
				}
			}
			if(endDate<startDate){
				alert("To date should be greater than From date ");
				return false;
			}
			return true;
		},
		validateQuestionSearch : function (csrfToken){
/*			var startDate = document.getElementById("templateCreateDateFrom").value;
			var endDate = document.getElementById("templateCreateDateTo").value;
			if(startDate != ""){
				if(endDate == ""){
				alert("Please specify the Proposal Create Date To correctly");
				return false;
				}
			} else if(endDate != ""){
				if(startDate == ""){
				alert("Please specify the Proposal Create Date From correctly");
				return false;
				}
			}
			if(endDate<startDate){
				alert("To date should be greater than From date ");
				return false;
			}
*/			return true;
		},
	search : function search(csrfToken){
			var allow =TemplateController.validateTemplateSearch (csrfToken);
			if(allow){
				SearchController.searchWithForm('templateSearch',['lastId'],'searchResult');
			}
		},
	searchQuestion : function (csrfToken){
			var allow =TemplateController.validateQuestionSearch(csrfToken);
			//alert("hi"+allow);
			if(allow){
				SearchController.searchWithForm('questionSearch',['lastId'],'searchResult');
			}
		},
	viewTemplate : function(templateId, documentType, csrfToken){
		if(null == templateId){
			alert("Please select an Template");
			return;
		}
		Controller.loadPage(contextRoot+'/business/template.handle?methodName=showTemplate&viewMode=true&templateId='+templateId+"&documentType="+documentType+"&"+csrfToken+"&_documentId=109&_subDocumentId=100&_stepId=1",null,null);
	},

	viewQTemplate : function(templateId,csrfToken){
		if(null == templateId){
			alert("Please select an Template");
			return;
		}
		var url= contextRoot+'/business/template.action?tab=y&methodName=showQTemplate&viewMode=true&templateId='+templateId+"&"+csrfToken+"&_documentId=109&_subDocumentId=100&_stepId=1";
		var newWindow = window.open("","viewQuestionnaireDetails_window", 'top=150, left=110, height=500, width=1000, toolbar=no, status=no ,scrollbars=1,resizable=1');
		newWindow.location.href = url;
		/*Controller.loadPage(contextRoot+'/business/template.handle?methodName=showQTemplate&viewMode=true&templateId='+templateId+"&"+csrfToken+"&_documentId=109&_subDocumentId=100&_stepId=1",null,null);*/
	},

	viewRfqDraftQTemplate : function(templateId,csrfToken,rfqDraftQId){
		if(null == templateId){
			alert("Please select an Template");
			return;
		}
		var url= contextRoot+'/business/template.action?tab=y&methodName=showQTemplate&viewMode=true&templateId='+templateId+"&"+csrfToken+"&_documentId=109&_subDocumentId=100&_stepId=1&rfqDraftQId="+rfqDraftQId;
		var newWindow = window.open("","viewQuestionnaireDetails_window", 'top=150, left=110, height=500, width=1000, toolbar=no, status=no ,scrollbars=1,resizable=1');
		newWindow.location.href = url;
		/*Controller.loadPage(contextRoot+'/business/template.handle?methodName=showQTemplate&viewMode=true&templateId='+templateId+"&"+csrfToken+"&_documentId=109&_subDocumentId=100&_stepId=1",null,null);*/
	},

	viewRfqQTemplate : function(templateId,rfqId,rfqItemId,entityId,csrfToken){
		if(null == templateId){
			alert("Please select an Template");
			return;
		}
		var url="";
		if(rfqItemId==0)
			url= contextRoot+'/business/rfq.action?tab=y&methodName=previewRfqConfigTemplate&viewMode=true&templateId='+templateId+"&rfqId="+rfqId+"&entityId="+entityId+"&"+csrfToken+"&_documentId=109&_subDocumentId=100&_stepId=1";
		else
			url= contextRoot+'/business/rfq.action?tab=y&methodName=previewRfqConfigTemplate&viewMode=true&templateId='+templateId+"&rfqId="+rfqId+"&rfqItemId="+rfqItemId+"&entityId="+entityId+"&"+csrfToken+"&_documentId=109&_subDocumentId=100&_stepId=1";
		var newWindow = window.open("","viewQuestionnaireDetails_window", 'top=150, left=110, height=500, width=1000, toolbar=no, status=no ,scrollbars=1,resizable=1');
		newWindow.location.href = url;
		/*Controller.loadPage(contextRoot+'/business/template.handle?methodName=showQTemplate&viewMode=true&templateId='+templateId+"&"+csrfToken+"&_documentId=109&_subDocumentId=100&_stepId=1",null,null);*/
	},

	viewQuestion : function(questionId,csrfToken){
		if(null == questionId){
			alert("Please select an Question");
			return;
		}
		var url= contextRoot+'/business/template.action?tab=y&methodName=getQuestion&viewMode=true&questionId='+questionId+"&"+csrfToken;
		var newWindow = window.open("","viewQuestionDetails_window", 'top=150, left=110, height=500, width=1000, toolbar=no, status=no ,scrollbars=1,resizable=1');
		newWindow.location.href = url;
		/*Controller.loadPage(contextRoot+'/business/template.handle?methodName=getQuestion&viewMode=true&questionId='+questionId+"&"+csrfToken,null,null);*/


	},
	viewSection : function(selectedSectionId,csrfToken){
		if(null == selectedSectionId){
			alert("Please select an Section");
			return;
		}
		var url = contextRoot+"/business/template.handle?methodName=getSection&viewMode=true&selectedSectionId="+selectedSectionId+"&"+csrfToken;
		window.open(url, 'getTemplateSectionList_window', 'width=800,height=500,scrollbars=yes,resizable=yes,menubar=no,directories=no,location=no');
	},
	randomString : function(){
		var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
		var string_length = 11;
		var randomString = '';
		for (var i=0; i<string_length; i++) {
			var rnum = Math.floor(Math.random() * chars.length);
			randomString += chars.substring(rnum,rnum+1);
		}
		return randomString;
	},
	viewDocSectionForAnswer : function(entityId,viewQuestionId,selectedDocSectionId,viewMode,editQuestionScoreFlag,csrfToken,viewScoreFlag,rfqId){
		//alert(entityId+" : "+viewQuestionId+" : "+selectedDocSectionId+" : "+viewMode+" : "+editQuestionScoreFlag+" : "+csrfToken+" : "+viewScoreFlag);
		var randomNumber= TemplateController.randomString();
		if(null == selectedDocSectionId)
		{
			alert("Please select an Section");
			return;
		}
		var url = contextRoot+"/business/template.handle?methodName=getDocSection&viewMode="+viewMode+"&selectedDocSectionId="+selectedDocSectionId+"&entityId="+entityId+"&docId="+viewQuestionId+"&editQuestionScoreFlag="+editQuestionScoreFlag+"&viewScoreFlag="+viewScoreFlag+"&randomNumber="+randomNumber+"&"+csrfToken+"&entityValueId="+rfqId;
		//window.open(url, 'getTemplateSectionListForAnswer_window', 'width=800,height=500,scrollbars=yes,resizable=yes,menubar=no,directories=no,location=no');
		window.open(url, 'getTemplateSectionListForAnswer_window');
	},
	viewDocSection : function(docSectionId,csrfToken,entityId,entityValue){
			if(null == docSectionId)
			{
				alert("Please select an Section");
				return;
			}
			var url = contextRoot+"/business/template.action?methodName=getDocumentSection&viewMode=true&docSectionId="+docSectionId+"&entityId="+entityId+"&entityValue="+entityValue+"&"+csrfToken;
			window.open(url, 'getDocumentConfigTemplateSection_window', 'width=800,height=500,scrollbars=yes,resizable=yes,menubar=no,directories=no,location=no');
	},
	checkIfAllRowsFilledUp : function(lastIndex,msg,csrfToken) {
			var code=null;
			for (var i=lastIndex;i>=0;i--) {
				code =document.getElementById("section.secQuesRelList["+i+"].question.code").value;
				if (code=='') {
					alert(msg);
					return false;
				}
			}
			document.getElementById("buttonValue").value = 'next';
			Controller.onSubmitWithCsrf('questionAddForm',csrfToken,'saveSectionQuestionRelList','next');
	  },
	  checkIfAllDocumentRowsFilledUp : function(lastIndex,msg) {
		var code=null;
		for (var i=lastIndex;i>=0;i--) {
			code =document.getElementById("docSection.docSecQuesRelList["+i+"].docQuestion.code").value;
			if (code=='') {
				alert(msg);
				return false;
			}
		}
		document.getElementById("buttonValue").value = 'next';
		document.documentQuestionAddForm.submit();
	  },
	saveSectionQuestionRelList : function(formName,methodname,buttonName){
		  eval("document."+formName).buttonValue.value=buttonName;
		  Controller.onSubmit(formName,null,methodname,null,null);
	},
	saveSectionQuestionRelListWithCsrf : function(formName,methodname,buttonName,csrfToken){
		eval("document."+formName).buttonValue.value=buttonName;
		Controller.onSubmitWithCsrf(formName,csrfToken,methodname,null,null);
	},
		saveDocumentSectionQuestionRelListWithCsrf : function(formName,methodname,buttonName,csrfToken){
		eval("document."+formName).buttonValue.value=buttonName;
		document.documentQuestionAddForm.submit();
	},
		moreRowForQuesAttr : function(){
			var tabId = "_AttrTab";
			//alert("tabId..."+tabId);
			var tbl = document.getElementById(tabId);
			var row = tbl.insertRow(tbl.rows.length);
			//alert(tbl.rows[0].cells.length);
			for (var i=0; i<tbl.rows[0].cells.length; i++) {
				var rowNo = tbl.rows.length;
				var cell = row.insertCell(i);
				TemplateController.crtQuesAttrCell(cell, rowNo-1,i, 'row');
			 }
		  },
		moreRowForAttr : function(/*int*/ tableIndex){
			var tabId = "_AttrTab_" + tableIndex;
			//alert("tabId..."+tabId);
			var tbl = document.getElementById(tabId);
			var row = tbl.insertRow(tbl.rows.length);
			//alert(tbl.rows[0].cells.length);
			for (var i=0; i<tbl.rows[0].cells.length; i++) {
				var rowNo = tbl.rows.length;
				var cell = row.insertCell(i);
				TemplateController.crtCell(cell, rowNo-1,i, 'row',tableIndex);
			 }
		  },
		  moreDocumentRowForAttr : function(tableIndex){
			 var tabId = "_AttrTab_" + tableIndex;
			var tbl = document.getElementById(tabId);
			var row = tbl.insertRow(tbl.rows.length);
			//alert(tbl.rows[0].cells.length);
			for (var i=0; i<tbl.rows[0].cells.length; i++) {
				var rowNo = tbl.rows.length;
				var cell = row.insertCell(i);
				TemplateController.crtDocumentCell(cell, rowNo-1,i, 'row',tableIndex);
			 }

		  },
		  moreColForQuesAttr : function(){
			  var tabId = "_AttrTab";
			  var tbl = document.getElementById(tabId);
			  for (var i=0; i<tbl.rows.length; i++){
				  var colNo ;
				  if(i==0) colNo = tbl.rows[0].cells.length;
				  var cell = tbl.rows[i].insertCell(tbl.rows[i].cells.length);
				  TemplateController.crtQuesAttrCell(cell,i, colNo, 'col');
			  }
		  },
		  moreColForAttr : function(/*int*/ tableIndex){
			  var tabId = "_AttrTab_" + tableIndex;
			  var tbl = document.getElementById(tabId);
			  for (var i=0; i<tbl.rows.length; i++){
				  var colNo ;
				  if(i==0) colNo = tbl.rows[0].cells.length;
				  var cell = tbl.rows[i].insertCell(tbl.rows[i].cells.length);
				  TemplateController.crtCell(cell,i, colNo, 'col',tableIndex);
			  }
		  },
		  moreDocumentColForAttr : function(/*int*/ tableIndex){
			  var tabId = "_AttrTab_" + tableIndex;
			  var tbl = document.getElementById(tabId);
			  for (var i=0; i<tbl.rows.length; i++){
				  var colNo ;
				  if(i==0) colNo = tbl.rows[0].cells.length;
				  var cell = tbl.rows[i].insertCell(tbl.rows[i].cells.length);
				  TemplateController.crtDocumentCell(cell,i, colNo, 'col',tableIndex);
			  }
		  },
		  deleteLastRowForAttr : function(/*int*/ tableIndex){
			var tabId = "_AttrTab_" + tableIndex;
			var tbl = document.getElementById(tabId);
			var lastRow = tbl.rows.length -1;
			//for (var i=lastRow; i>0; i--) tbl.deleteRow(i);
			if(lastRow!=0)
			tbl.deleteRow(lastRow);
		  },

		  deleteLastColumnForAttr : function(/*int*/ tableIndex){
			 var tabId = "_AttrTab_" + tableIndex;
			 var tbl = document.getElementById(tabId);
			 var lastCol = tbl.rows[0].cells.length - 1;
			 for (var i=0; i<tbl.rows.length; i++)   {
			  // for (var j=lastCol; j>0; j--) tbl.rows[i].deleteCell(j);
				 //alert("lastCol..."+lastCol+"i..."+i);
				 if(lastCol==1 && i==0){
				 }else if(lastCol>1 && i==0){
				  tbl.rows[i].deleteCell(lastCol);
				 }else{
				 }
			  }
		  },
		  deleteLastRow : function(){
			var tabId = "_AttrTab" ;
			var tbl = document.getElementById(tabId);
			var lastRow = tbl.rows.length -1;
			//for (var i=lastRow; i>0; i--) tbl.deleteRow(i);
			if(lastRow!=0)
			tbl.deleteRow(lastRow);
		  },

		  deleteLastColumn : function(){
			 var tabId = "_AttrTab" ;
			 var tbl = document.getElementById(tabId);
			 var lastCol = tbl.rows[0].cells.length - 1;
			 for (var i=0; i<tbl.rows.length; i++)   {
			  // for (var j=lastCol; j>0; j--) tbl.rows[i].deleteCell(j);
				 //alert("lastCol..."+lastCol+"i..."+i);
				 if(lastCol==1 && i==0){
				 }else if(lastCol>1 && i==0){
				  tbl.rows[i].deleteCell(lastCol);
				 }else{
				 }
			  }
		  },
		  crtDocumentCell : function(cell, rowIndex, colIndex ,style , index){
			 //alert("rowIndex..."+rowIndex+"..colIndex.."+colIndex+"..index.."+index);
			  if(rowIndex==0){
				 var rowAttrListIndex = colIndex-1;
				  var str = "<table><tr><td>" +
					 "<input id='docSection.docSecQuesRelList["+index+"].docQuestion.documentQuestionColumnAttribute["+rowAttrListIndex+"].docQuestionAttribute.id' name='docSection.docSecQuesRelList["+index+"].docQuestion.documentQuestionColumnAttribute["+rowAttrListIndex+"].docQuestionAttribute.id' type='hidden' value= '0' /> " +
					"<input id='docSection.docSecQuesRelList["+index+"].docQuestion.documentQuestionColumnAttribute["+rowAttrListIndex+"].docQuestionAttribute.parentQuestionAttribute.id' name='docSection.docSecQuesRelList["+index+"].docQuestion.documentQuestionColumnAttribute["+rowAttrListIndex+"].docQuestionAttribute.parentQuestionAttribute.id' type='hidden' value= '0' /> " +
					 "<input type='text' id='docSection.docSecQuesRelList["+index+"].docQuestion.documentQuestionColumnAttribute["+rowAttrListIndex+"].documentQuestionAttribute.description' name='docSection.docSecQuesRelList["+index+"].docQuestion.documentQuestionColumnAttribute["+rowAttrListIndex+"].description'  /> " +
					 "&nbsp;<a href='javascript:TemplateController.addDocumentQuestionAttr("+index+","+rowAttrListIndex+");' ><img src='../image/icon_add_large.gif' title='ADD ATTRIBUTE' border='0'></a>" +
					 "&nbsp;<a href='javascript:TemplateController.openDocumentQuestionAttrList("+index+","+rowAttrListIndex+",true,false);' ><img src='../image/paperclip.gif' title='ATTACH ATTRIBUTE' border='0'></a></td>"+
					 "</tr></table>";

				 cell.innerHTML = str;
			 }
			 else if(colIndex==0){
				 var columnAttrListIndex = rowIndex-1;
				 var inp = document.createElement('input');
				 inp.setAttribute("name","docSection.docSecQuesRelList["+index+"].docQuestion.documentQuestionRowAttribute["+columnAttrListIndex+"].description");
				 inp.setAttribute("id","docSection.docSecQuesRelList["+index+"].docQuestion.documentQuestionRowAttribute["+columnAttrListIndex+"].description");
				 cell.appendChild(inp);
			 }
			 else{
				 //var rowAttrListIndex = rowIndex-1;
				 //var columnAttrListIndex = colIndex-1;
				 //inp.setAttribute("name","docItemList["+index+"].proposalCsAttributeValueList["+rowAttrListIndex+"].cellList["+columnAttrListIndex+"].attributeVal");
				 //inp.setAttribute("id","docItemList["+index+"].proposalCsAttributeValueList["+rowAttrListIndex+"].cellList["+columnAttrListIndex+"].attributeVal");
				 //inp.setAttribute("value", "");
			 }
		},
		crtCell : function(cell, rowIndex, colIndex ,style , index){
			 //alert("rowIndex..."+rowIndex+"..colIndex.."+colIndex+"..index.."+index);
			  if(rowIndex==0){
				 var rowAttrListIndex = colIndex-1;
				  var str = "<table><tr><td>" +
					 "<input id='section.secQuesRelList["+index+"].question.questionColumnAttribute["+rowAttrListIndex+"].questionAttribute.id' name='section.secQuesRelList["+index+"].question.questionColumnAttribute["+rowAttrListIndex+"].questionAttribute.id' type='hidden' value= '0' /> " +
					 "<input type='text' id='section_secQuesRelList_"+index+"_question_questionColumnAttribute_"+rowAttrListIndex+"_description' name='section.secQuesRelList["+index+"].question.questionColumnAttribute["+rowAttrListIndex+"].description' onkeyup=\"checkSpecialCharacter('section_secQuesRelList_"+index+"_question_questionColumnAttribute_"+rowAttrListIndex+"_description','Column"+parseInt(parseInt(rowAttrListIndex)+1)+" Description of Question"+parseInt(parseInt(index)+1)+"','validationQuestion');\" > " +
					 "&nbsp;" +
					 "<a href='javascript:TemplateController.addQuestionAttr("+index+","+rowAttrListIndex+");' ><img src='../image/icon_add_large.gif' title='ADD ATTRIBUTE' border='0'></a>"+
					 "&nbsp;<a href='javascript:TemplateController.openQuestionAttrList("+index+","+rowAttrListIndex+",true,false);' ><img src='../image/paperclip.gif' title='ATTACH ATTRIBUTE' border='0'></a></td>" +
					 "</tr></table>";
				 cell.innerHTML = str;
			 }
			 else if(colIndex==0){
				 var columnAttrListIndex = rowIndex-1;
				 var str="<input type='text' id='section_secQuesRelList_"+index+"_question_questionRowAttribute_"+columnAttrListIndex+"_description' name='section.secQuesRelList["+index+"].question.questionRowAttribute["+columnAttrListIndex+"].description' onkeyup=\"checkSpecialCharacter('section_secQuesRelList_"+index+"_question_questionRowAttribute_"+columnAttrListIndex+"_description','Row"+parseInt(parseInt(columnAttrListIndex)+1)+" Description of Question"+parseInt(parseInt(index)+1)+"','validationQuestion);\" >";
				 cell.innerHTML = str;
			 }
			 else{
				 //var rowAttrListIndex = rowIndex-1;
				 //var columnAttrListIndex = colIndex-1;
				 //inp.setAttribute("name","docItemList["+index+"].proposalCsAttributeValueList["+rowAttrListIndex+"].cellList["+columnAttrListIndex+"].attributeVal");
				 //inp.setAttribute("id","docItemList["+index+"].proposalCsAttributeValueList["+rowAttrListIndex+"].cellList["+columnAttrListIndex+"].attributeVal");
				 //inp.setAttribute("value", "");
			 }
		},
		crtQuesAttrCell : function(cell, rowIndex, colIndex ,style){
			 //alert("rowIndex..."+rowIndex+"..colIndex.."+colIndex+"..style.."+style);
			  if(rowIndex==0){
				 var rowAttrListIndex = colIndex-1;
				  var str = "<table><tr><td>" +
					 "<input id='questionColumnAttribute["+rowAttrListIndex+"].questionAttribute.id' name='questionColumnAttribute["+rowAttrListIndex+"].questionAttribute.id' type='hidden' value= '0' /> " +
					 "<input type='text' id='questionColumnAttribute_"+rowAttrListIndex+"_description' title='Column Name' class='columnAttribute' name='questionColumnAttribute["+rowAttrListIndex+"].description' onkeyup=\"checkSpecialCharacter('questionColumnAttribute_"+rowAttrListIndex+"_description','Column"+parseInt(parseInt(rowAttrListIndex)+1)+" Description','validationQuestion');\" > " +
					 "&nbsp;" +
					 "<a href='javascript:TemplateController.addQuestionAttr(-1,"+rowAttrListIndex+");' ><img src='../image/icon_add_large.gif' title='ADD ATTRIBUTE' border='0'></a>"+
					 "&nbsp;<a href='javascript:TemplateController.openQuestionAttrList(-1,"+rowAttrListIndex+",false,false);' ><img src='../image/paperclip.gif' title='ATTACH ATTRIBUTE' border='0'></a></td>" +
					 "</tr></table>";
				 cell.innerHTML = str;
			 }
			 else if(colIndex==0){
				 var columnAttrListIndex = rowIndex-1;
				 var str =
					 "<input type='text' id='questionRowAttribute_"+columnAttrListIndex+"_description' title='Row Name' class='rowAttribute1' name='questionRowAttribute["+columnAttrListIndex+"].description' onkeyup=\"checkSpecialCharacter('questionRowAttribute_"+columnAttrListIndex+"_description','Row"+parseInt(parseInt(columnAttrListIndex)+1)+" Description','validationQuestion');\" >";
					cell.innerHTML = str;
			 }
			 else{
			 }
		},
		addQuestionAttr : function(/*int*/ questionIndex,/*int*/ index){
			//alert("questionIndex..."+questionIndex+"...index..."+index);
			var url = contextRoot+"/business/template.handle?methodName=initCreateAttribute&index="+index+"&questionIndex="+questionIndex;
			/*var csrfEle = document.getElementsByName("OWASP_CSRFTOKEN");*/
			var csrfEle = document.questionAddForm.OWASP_CSRFTOKEN;
			//alert("csrfEle.."+csrfEle);
			//alert (" addQuestionAttr :csrfEle  = " + csrfEle);
			if(typeof csrfEle!='undefined'){
				var csrf = $("#OWASP_CSRFTOKEN").val();
				//alert ("csrf..." + csrf);
				url = url + "&OWASP_CSRFTOKEN="+csrf;
				//alert (" addQuestionAttr :url = " + url);
			}
			//alert("url.."+url);
			//window.open(url, 'addQuestionAttr_window','width=700,height=300,scrollbars=yes,resizable=yes,titlebar=no,toolbar=yes');
			window.open(url, 'addQuestionAttr_window','width=950,height=500,scrollbars=yes,resizable=yes');
		},
		addDocumentQuestionAttr : function(/*int*/ documentQuestionIndex,/*int*/ index){
			//alert("questionIndex..."+questionIndex+"...index..."+index);
			var entityId=$("input[name='docSection.entityValue.entityId']").val();
			var entityValue=$("input[name='docSection.entityValue.entityValue']").val();
			//alert("entityId:"+entityId+"entityValue:"+entityValue);
			var url = contextRoot+"/business/template.handle?methodName=initCreateDocumentAttribute&index="+index+"&documentQuestionIndex="+documentQuestionIndex+"&entityId="+entityId+"&entityValue="+entityValue;
			var csrfEle = document.documentQuestionAddForm.OWASP_CSRFTOKEN;
			//alert(document.documentQuestionAddForm.OWASP_CSRFTOKEN.value);
//			alert (" addQuestionAttr :csrfEle  = " + csrfEle);
			if(typeof csrfEle!='undefined'){
				var csrf = document.documentQuestionAddForm.OWASP_CSRFTOKEN.value;
				url = url + "&OWASP_CSRFTOKEN="+csrf;
			//alert (" addQuestionAttr :url = " + csrf);
			}
			window.open(url, 'addDocumentQuestionAttr_window','width=700,height=360');
			//window.open(url, 'addQuestionAttr_window','width=700,height=300');
		},
	retrieveSection : function(formName,csrfToken,methodname,sectionId,templateId){
		eval("document."+formName).sectionId.value=sectionId;
		eval("document."+formName).configTemplateId.value=templateId;
		Controller.onSubmitWithCsrf(formName,csrfToken,methodname,null,null);
	},
	deleteSection : function(formName,csrfToken,methodname,sectionId,templateId){
		eval("document."+formName).sectionId.value=sectionId;
		eval("document."+formName).configTemplateId.value=templateId;
		if (confirm('Delete the Section from the Questionnaire Form?')) Controller.onSubmitWithCsrf(formName,csrfToken,methodname,null,null);
	},
	submitScore : function(){
	document.sectionAddForm.methodName.value = "saveDocSectionQtnScore";
	document.sectionAddForm.submit();
	},

	selectItem : function(id,csrfToken){
		if(null == id)
		{
			alert("Please select an Attribute Master");
			return;
		}
		/*
		document.updateForm.action=contextRoot+"/business/order.action?methodName=getDoc&viewMode=true&id="+id+"&"+csrfToken;
		document.updateForm.submit();
		*/
		Controller.loadPage(contextRoot+'/business/template.handle?methodName=addAttMaster&id='+id+'&'+csrfToken,null,null);
	},

	searchPerticularPage : function (csrfToken){
		var searchPageNumber=document.attrMasterForm.searchPageNumber.value;
		Controller.loadPage(contextRoot+'/business/template.handle?methodName=getAttrMasterListByPagination&pageNumber='+searchPageNumber+'&'+csrfToken,null,null);

		},

	saveTemplate : function(formName,csrfToken,templateStatus,buttonValue){

		/*alert("templateStatus::"+templateStatus);
		alert("buttonValue::"+buttonValue);*/
		if($("#templateStatus").length>0){
			document.getElementById("templateStatus").value=templateStatus;
		}

		document.getElementById("buttonValue").value=buttonValue;

		var defaultSrcValidFlag=true;
		if($("#templateDocumentType").val()=="203"){
			// QUOTATION LOADING ITEM TEMPLATE
			$("select[name$='dfltValSource']").each(function() {
				   // $(this) is a element
					if($(this).val()!="201" && $(this).val()!="0" && $(this).val()!="1"){
						alert("Please select QTN ITEM ATTR for Default Val Source");
						defaultSrcValidFlag=false;
						return;
					}
				});


		}

		if($("#templateDocumentType").val()=="202"){
			// QUOTATION LOADING HEADER TEMPLATE
			$("select[name$='dfltValSource']").each(function() {
				   // $(this) is a element
					if($(this).val()!="200" && $(this).val()!="0" && $(this).val()!="1"){
						alert("Please select QTN HEADER ATTR for Default Val Source");
						defaultSrcValidFlag=false;
						return;
					}
				});


		}

		if(defaultSrcValidFlag==false)	return;


		if(buttonValue == 'FORMULA'){
			var r=confirm("Template,once saved for formula,can not be modified further");
			if (r==true)
			  {
				Controller.onSubmitWithCsrf(formName,csrfToken,'saveTemplate','FORMULA',null);
			  }
			/*else
			  {
			  alert("You pressed Cancel!")
			  }*/
		}
		else if(buttonValue == 'VALIDATION')
		{
			//alert("here");
			var r=confirm("Template,once saved for validation, can not be modified further");
			if(r==true)	Controller.onSubmitWithCsrf(formName,csrfToken,'saveTemplate','VALIDATION',null);

		}
		else if(buttonValue == 'NEWVALIDATION')
		{
			Controller.onSubmitWithCsrf(formName,csrfToken,'saveTemplate','NEWVALIDATION',null);

		}
/*        else if(buttonValue == 'RANKING'){
			alert("RANKING");
			Controller.onSubmitWithCsrf(formName,csrfToken,'saveTemplate','RANKING',null);
			}*/
		else{
			Controller.onSubmitWithCsrf(formName,csrfToken,'saveTemplate','SAVE',null);
		}

	},

	openSequence :function (templateType,countIndex,flag){

		var fieldName='templateBlockMap['+templateType+'].attributeMaster['+countIndex+'].attribute.sequence';
		if(flag){
			document.getElementById(fieldName).value = 0;

			document.getElementById(fieldName).removeAttribute('readOnly');
		}else{
			document.getElementById(fieldName).value = sequence;
			document.getElementById(fieldName).setAttribute('readOnly','readonly');
		}

	},
	displayOrgPcpn : function(csrfToken){
		var url = contextRoot+"/business/template.handle?methodName=getOrgPcnpFlgByOrgId&"+csrfToken;
		window.open(url, 'getOrgPcnpFlgByOrgId_window', 'width=800,height=500,scrollbars=yes,resizable=yes,menubar=no,directories=no,location=no');
	},
	templatePreview : function(templateId,templateStatus,csrfToken){
		Controller.loadPage(contextRoot+'/business/template.handle?methodName=getTemplatePreview&templateId='+templateId+'&templateStatus='+templateStatus+'&'+csrfToken,null,null);
	},

	editTemplate :function(templateId,templateStatus,csrfToken,buttonValue){
	//	if(templateStatus == "D"){
			document.getElementById('buttonValue').value = buttonValue;
			Controller.loadPage(contextRoot+'/business/template.handle?methodName=getAttributeList&templateId='+templateId+'&buttonValue='+buttonValue+'&templateStatus='+templateStatus+'&'+csrfToken,null,null);
		//}
	},


	saveTemplateFormula :function(templateId,csrfToken,buttonValue){
		//	if(templateStatus == "D"){
		alert("templateId:::"+templateId);
		document.getElementById('buttonValue').value = buttonValue;
		//Controller.loadPage(contextRoot+'/business/template.handle?methodName=addFormula&templateId='+templateId+'&buttonValue='+buttonValue+'&'+csrfToken,null,null);
		Controller.onSubmitWithCsrf("templateView",csrfToken,'saveTemplateFormula','SAVE',null);
	//}
	},
	activeTemplate:function(templateId,csrfToken,buttonValue,templateStatus){
		//	if(templateStatus == "D"){
		alert("templateId:::"+templateId);
		alert("buttonValue:::"+buttonValue);
		document.getElementById('templateId').value = templateId;
		document.getElementById('templateStatus').value = templateStatus;
		alert("templateStatus:::"+templateStatus);
		document.getElementById('buttonValue').value = buttonValue;
		alert("buttonValue:::"+buttonValue);
		//Controller.loadPage(contextRoot+'/business/template.handle?methodName=addFormula&templateId='+templateId+'&buttonValue='+buttonValue+'&'+csrfToken,null,null);
		Controller.onSubmitWithCsrf("templateActiveForm",csrfToken,'activeTemplate',null,null);
	//}
	},

	getFormula :function(templateId,csrfToken,buttonValue){
		alert("templateId:::"+templateId);
		Controller.loadPage(contextRoot+'/business/template.handle?methodName=getTemplateFormula&templateId='+templateId+'&'+csrfToken,null,null);
	//	Controller.onSubmitWithCsrf("templateView",csrfToken,'addFormula','SAVE',null);
	//}
	},
	submitConfigTemplate :function(formName /*string*/, csrfToken /*string*/, methodName /*string*/, buttonValue /*string*/){
		var csrf = csrfToken.split("=");
		var csrfTokenName = '"'+csrf[0]+'"';
		var url= document.getElementById("url").value;
		var status= document.getElementById("status").value;
		var isMandatory = document.getElementById("isMandatory").value;
		if(status=='D' || status=='X' )
		  {
			if(parseInt(isMandatory)==1)
				{
					var flag=false;
					$.ajax({
			            "url": url,
			            "async": false,
			            "type": "POST",      
			            "data": { "methodName": "validateFeedbackConfigTemplate", "OWASP_CSRFTOKEN": csrf[1],"button":'VALIDATE'} ,                                                                
			            "success": function( data ) 
			            {
			                  if(data.json.count > 0)
			                  {
			                	  flag=true;  
			                  }   
			            }
						});
					if(flag==true)
					{
						if(confirm('Feedback form is already activated.Click OK to deactivate previous form'))
			      	  	{
							if(confirm('Are you sure you want to activate form !!'))
								{
			      		  $.ajax({
			      	            "url": url,
			      	            "async": false,
			      	            "type": "POST",      
			      	            "data": { "methodName": "validateFeedbackConfigTemplate", "OWASP_CSRFTOKEN": csrf[1],"button":'DELETE'}                                                                
			      		  		});
			      		  Controller.onSubmitWithCsrf(formName,csrfToken,methodName,buttonValue,null);
								}
			      	  	} 
			      	  else
			      		  return;
					}
					else
						Controller.onSubmitWithCsrf(formName,csrfToken,methodName,buttonValue,null);
				}
			else
				Controller.onSubmitWithCsrf(formName,csrfToken,methodName,buttonValue,null);
		   }
		else{
			
			Controller.onSubmitWithCsrf(formName,csrfToken,methodName,buttonValue,null);
		}
	},
	 configTemplateSelection : function()
	 {
		 var val = document.getElementById("invocationPoint").value;
		 if(val == 1)
		 $("#isMandatory").val("1");
		 else
		 $("#isMandatory").val("0"); 
	 }
	/*attachItemListWithSeller : function(entityId, partNumber, selectedSellerId, viewMode, csrfToken){
		//alert(entityId+" : "+partNumber+" : "+selectedSellerId+" : "+viewMode+" : "+csrfToken);

		var url = contextRoot+"/business/rfq.action?methodName=getItemListforSeller&viewMode="+viewMode+"&selectedSellerId="+selectedSellerId+"&entityId="+entityId+"&partNumber="+partNumber+"&"+csrfToken;
		window.open(url, 'getAttachItemListWithSeller_window', 'width=800,height=500,scrollbars=yes,resizable=yes,menubar=no,directories=no,location=no');
	},
*/
}

var OrderController = {
	selectOrder : function(/*String*/ orderCode,/*int*/ orderId,/*String*/inhCode,/*String*/date,/*int*/buyerId) {
		pageScope["order"] = {
			"order.id" : orderId, "order.code":orderCode,
			"order.orderInheritanceCode" : inhCode, "order.createDate" : date,
			"order.orderOrganization.id" : buyerId
		};
		if(sessionScope["_currDocId"] == 106){
			if(sessionScope["_currPrivId"] == 100){
				$("#raiseIr").css("display","inline");
			}
		}
	},
	signOrder : function(/*String*/ formId,/*String*/ token,/*String*/ methodName,/*String*/ pkiEnabled,/*String*/ orderEnabled,/*String*/ button) {

		if (confirm("DO YOU WANT TO PROCEED?"));
	    else return ;
		var code = document.getElementById("code").value;
		var orderDateSign = document.getElementById("orderDateSign").value;
		var signKey = code + '#|#' +orderDateSign;

		var valid = true;
		if(pkiEnabled && orderEnabled){

			valid = valid && signDocument(signKey);

		}
		if (valid){
			eval("document.orderAddForm").button.value = button;
			eval("document.orderAddForm").methodName.value = methodName;
			Controller.onSubmitWithCsrf(formId,token,methodName,button,null);
		}
	},
	checkOtherTermAndCondition: function(isOtherTrmConditnEnable){
		var flag=true;
		var radioValue = $("input[name='checkImpInfoVal']:checked").val();
		var importantInfoMode = $("input[name='importantInfoMode']").val();
		var otherTrmAndConditionMode = $("input[name='otherTrmAndConditionMode']").val();
		var noOrgDocAttachment = $("input[name='noOrgDocAttachment']").val();
		
		if(isOtherTrmConditnEnable && importantInfoMode == 'ADD'){
			var impInfoFileName=$("input[name='importantInfo[0].file']").val();
			var impInfoFileExtension = impInfoFileName.substr((impInfoFileName.lastIndexOf('.') + 1));
			if(radioValue != 'UPLOAD' && radioValue != 'LINK'){
				alert('PLEASE UPLOAD IMPORTANT INFORMATION');
				return;
			}
			if(radioValue == 'UPLOAD' || radioValue == 'LINK'){
				if(radioValue == 'UPLOAD' && impInfoFileExtension != 'pdf' && impInfoFileName!=""){
					alert('ONLY PDF FILE CAN UPLOAD FOR IMPORTANT INFORMATION');
					flag=false;
				}else if(radioValue == 'LINK' && noOrgDocAttachment == 'noOrgDocAttachment'){
					alert('NO ATTACHMENTS FOUND,PLEASE UPLOAD IMPORTANT INFORMATION');
					flag=false;
				}
			}
		}
		if(isOtherTrmConditnEnable && otherTrmAndConditionMode == 'ADD'){
			var trmConditnFileName=$("input[name='otherTrmAndCondition[0].file']").val();
			var trmConditnFileExtension = trmConditnFileName.substr((trmConditnFileName.lastIndexOf('.') + 1));
			if(trmConditnFileExtension != 'pdf' && trmConditnFileName!=""){
				alert('ONLY PDF FILE CAN UPLOAD FOR OTHER TERMS AND CONDITION');
				flag=false;
			}
		}
		
		return flag;
	},	
	selectImportantInfoAttachmentDiv: function (){
		var radioValue = $("input[name='checkImpInfoVal']:checked").val();
		if(radioValue == 'UPLOAD' && document.getElementById("importantInfoByUploadFileDiv").style.display == "none"){
			$("#importantInfoByOrgDocLinkDiv").hide(10);
			$("#importantInfoByUploadFileDiv").show(600);
		}else if(radioValue == 'LINK' && document.getElementById("importantInfoByOrgDocLinkDiv").style.display == "none"){
			$("#importantInfoByUploadFileDiv").hide(10);
			$("#importantInfoByOrgDocLinkDiv").show(600);
		}
	}, 
	signOrderAttachmentFile : function(/*int*/ index){
	var valid = true;
	var fileField='attachments['+index+'].file';
	var elementName='attachments['+index+'].digitalCert.signHash';
	var digitalCertIdElement='attachments['+index+'].digitalCert.id';
	var filePath= document.getElementById(fileField).value;
	//alert("elementName "+elementName);
	valid = signFileAndAssignValue(filePath,elementName);

	//var pubKey = document.getElementById("digitalCert.publicKey").value;
	//document.getElementById(digitalCertIdElement).value=pubKey;
	//encValid = encryptFileAttachment(filePath,fileField,pubKey);
	},
	verifyOrder : function (){
		var code = document.getElementById("code").value;
		var orderDate = document.getElementById("orderDate").value;
	var text = code + '#|#'+orderDate;
	verifyDocument(text);
},
	getRfqsAndQuotationsByOrgId : function (/*String*/startDate,/*String*/endDate,/*String*/rfqCode,csrfToken) {
	    var ordCatId  = 0;
	    if(null != document.getElementById("ordCatId"))ordCatId = document.getElementById("ordCatId").value;
	    var formNode = $("form[id!='dummyForm']");
	 	//$('input[id$=".code"]',formNode).each(function(){this.disabled=true;});
    	Util.clearContent($('#_msgBox'));
    	Util.clearContent($('#rfqList'));
    	Controller.loadPage(contextRoot+
    						"/business/order.handle?methodName=getRfqsAndQuotationsByOrgId&rfqDate.rfqStartDate="+startDate+"&rfqDate.rfqEndDate="+endDate+"&ordCatId="+ordCatId+"&code="+rfqCode+"&"+csrfToken,null,null);
    },
    getUsers : function (/*int*/index,/*int*/orgId) {
	 	var formNode = $("form[id!='dummyForm']");
    	//$('input[id$=".code"]',formNode).each(function(){this.disabled=true;});
    	Controller.loadData(contextRoot+
    						"/business/order.handle?methodName=getUsers&orgId="+orgId,null,
    		function(/*String*/ data) {
    		log("Inside call back::::");
    		//$('input[id$=".code"]',formNode).each(function(){this.disabled=false;});
    		if (data["_errors"]!=null) {
    			Util.showMessage(data);
    			return;
    		}
    		var content = new Array();
			var j=0;
			if(data.userList.length == 0)
			{
				return;
			}
			content[j++]='<select id="orderSellerUsers['+index+'].id" name="orderSellerUsers['+index+'].id">';
			for(var i=0;i<data.userList.length;i++)
			{
				content[j++]='<option value="';
				content[j++]=data.userList[i].id;
				content[j++]='">';
				content[j++]=data.userList[i].userFirstName;
				content[j++]='</option>';
			}
			content[j++]='</select>';
			var seller = document.getElementById("sellerTab");
			seller.rows[2+index].cells[2].innerHTML = content.join('');
	    });
    },
    getItemDetail : function (/*int*/ rowNum) {


    	var codeVal = document.getElementById('docItemList['+rowNum+'].code').value;
    	var csrfTokenName = document.getElementById("csrfTokenName").value;
    	var csrfTokenValue = document.getElementById("csrfTokenValue").value;
    	var csrfToken = csrfTokenName + "=" + csrfTokenValue;
		if(codeVal == "")
		{
			alert("Please specify the Code to get the Description");
			return false;
		}
	 	var formNode = $("form[id!='dummyForm']");
    	$('input[id$=".code"]',formNode).each(function(){this.disabled=true;});
    	Controller.loadData(contextRoot+"/business/item.handle?methodName=getItem&code="+codeVal+"&"+csrfToken,null,
    		function(/*String*/ data) {
    		$('input[id$=".code"]',formNode).each(function(){this.disabled=false;});
    		if (data["_errors"]!=null) {
   			Util.clearContent($('#_msgBox'));
    			Util.showMessage(data);
    			document.getElementById('docItemList['+rowNum+'].code').value='';
    			return;
    		}
    		Util.clearContent($('#_msgBox'));
    		document.getElementById('docItemList['+rowNum+'].bigOrderItemDesc').value=Controller.unescapeHtml(data.item.description);
    });


  },
  openSellers : function(/*int*/index,crsfToken,orgRoleFlagDesc,openSellers,capturePayeeDetails) {
	var url = contextRoot+"/business/order.handle?methodName=getOrderSellers&index="+index+"&"+crsfToken+"&orgRoleFlagDesc="+orgRoleFlagDesc+"&capturePayeeDetails="+capturePayeeDetails;
  	window.open(url, 'orderSeller_window', 'width=460,height=500,scrollbars=yes,resizable=yes');
  },
  findRfqs : function(csrfToken){
    var catId = 0;
    var headerTemplateId = 0;
    if(null != document.getElementById("categoryId"))catId = document.getElementById("categoryId").value;
    if(null != document.getElementById("headerTemplateId"))headerTemplateId = document.getElementById("headerTemplateId").value;
    var url = contextRoot+"/business/order.handle?methodName=getRfqList&categoryId="+catId+"&headerTemplateId="+headerTemplateId+"&"+csrfToken;
  	window.open(url, 'rfqPrint_window', 'width=1150,height=600,scrollbars=yes');
  },
  validate : function() {
  	var valid = false;
	var code = document.orderAddForm.code.value ;
	var description = document.orderAddForm.description.value ;
	var orderValue = document.orderAddForm.orderValue.value ;
	var orderDate = document.orderAddForm.orderDate.value ;
	var groupId = document.orderAddForm.groupId.value ;
	//var suppOrgName = document.orderAddForm.orderSellerUsers[0].organization.organizationName.value ;
	//var suppName = document.orderAddForm.orderSellerUsers[0].userFirstName.value ;
	var suppOrgName = document.getElementById("orderSellerUsers[0].organization.organizationName").value;
	var suppName = document.getElementById("orderSellerUsers[0].userFirstName").value;
	var payeeOrgName = document.getElementById("orderSellerUsers[1].organization.organizationName").value;
	var payeeName = document.getElementById("orderSellerUsers[1].userFirstName").value;
	if(code.length == 0){
		alert("Order Reference Code Required");
		valid = false;
	}else if(description.length == 0){
		alert("Description Required");
		valid = false;
	}else if(orderValue.length == 0){
		alert("Value Required");
		valid = false;
	}else if(!Util.IsNumeric(Util.trim(orderValue))){
		alert("Enter numeric date for Value");
		valid = false;
	}else if(orderDate.length == 0){
		alert("Order Date Required");
		valid = false;
	}else if(!OrderController.isValidOrderDate(orderDate)){
		alert("Invalid Order Date");
		valid = false;
	}else if(groupId == ""){
		alert("Inspection Group Rrequired");
		valid = false;
	}else if(suppOrgName.length == 0){
		alert("Supplier Organization Name Rrequired");
		valid = false;
	}else if(suppName.length == 0){
		alert("Supplier Name Rrequired");
		valid = false;
	}else if(payeeOrgName.length == 0){
		alert("Payee Organization Name Rrequired");
		valid = false;
	}else if(payeeName.length == 0){
		alert("Payee Name Rrequired");
		valid = false;
	}else{
		valid = true;
	}
	return valid;
  },
  isValidOrderDate : function(/*String*/orderdate) {
  	var valid = false;
	var year = orderdate.substring(0,4);
	var month = orderdate.substring(5,7);
	var day = orderdate.substring(8,10);
	var hour = orderdate.substring(11,13);
	var minuit = orderdate.substring(14,16);
	var second = orderdate.substring(17,19);
	//alert("year " + year + " month " + month + " day " + day + " hour " + hour + " minuit " + minuit + " second " + second );
	var today = new Date();
	var mon = month - 1 ;
	//alert(mon);
	var orderdate = new Date(year,month - 1,day,hour,minuit,second);
	today.setHours(0);
	today.setMinutes(0);
	today.setSeconds(0);
	var diff = orderdate.getTime() - today.getTime();
	if(diff > 0 ) valid = true ;
	return valid;
  },
/*  fetchAttribute: function(orderItemId,orderItemCode,srlNo,index){
	document.getElementById("currItem.id").value = orderItemId;
	document.getElementById("currItem.code").value = orderItemCode;
	document.getElementById("currItem.docItmSrlNo").value = srlNo;
	document.orderitemAddForm.button.value = 'attr';
	if(document.getElementById("docItemList["+index+"].delete").checked)
	{
		alert("Attributes of deleted item can not be seen");
		return false;
	}
	var id = document.getElementById("docItemList["+index+"].id").value;
	if(id="")
	{
		alert("id null");
		return false;
	}
	//document.orderitemAddForm.submit();
	return true;
  },
*/
	fetchAttribute : function(orderItemId,orderItemCode,srlNo,index,isDeleteEnabled){
		/*document.getElementById("currItem.id").value = orderItemId;
		document.getElementById("currItem.code").value = orderItemCode;
		document.getElementById("currItem.docItmSrlNo").value = srlNo;
		if(document.getElementById("docItemList["+index+"].delete").checked)
		{
			alert("Attributes of deleted item can not be seen");
			return false;
		}
		var id = document.getElementById("docItemList["+index+"].id").value;
		if(id="")
		{
			alert("id null");
			return false;
		}
		//document.orderitemAddForm.submit();
		return true;*/

		if(isDeleteEnabled=='Y'){
			if(document.getElementById("docItemList["+index+"].deleted").checked){
				alert("Attributes of deleted item can not be seen");
				return false;
			}
		}
		
		var id = document.getElementById("docItemList["+index+"].id").value;
		if(id=""){
			alert("id null");
			return false;
		}
		var orderItem = {
			"currItem.id" : orderItemId, "currItem.code" : orderItemCode, "currItem.docItmSrlNo" : srlNo
		};
		document.orderitemAddForm.buttonValue.value = 'attr';
		Controller.onSubmit('orderitemAddForm',orderItem,'saveDocItemList','attr',null);
	},
	showOrderItemAttachment : function(orderItemId,orderItemCode,srlNo,index){
		if(document.getElementById("docItemList["+index+"].deleted").checked)
		{
			alert("Attributes of deleted item can not be seen");
			return false;
		}
		var id = document.getElementById("docItemList["+index+"].id").value;
		if(id="")
		{
			alert("id null");
			return false;
		}
		var orderItem = {
			"currItem.id" : orderItemId, "currItem.code" : orderItemCode, "currItem.docItmSrlNo" : srlNo
		};
		document.orderitemAddForm.buttonValue.value = 'ordItemAttch';
		Controller.onSubmit('orderitemAddForm',orderItem,'showItemAttachment','ordItemAttch',null);
	},
   validateOrderItemAtachmentAndSave : function(/*String*/ formId,/*Object*/ addlParams,/*String*/ methodName,/*String*/button,/*Function*/ callback){
			var flag=false;
			if(attachmentController.validateFileName('orderAttachmentForm')== false){
				flag=false;
			}else{
				Controller.onSubmitWithCsrf('orderAttachmentForm',addlParams,'saveItemAttachment',null,null);
				flag=true;
			}
			return flag;
		},
  checkIfAllRowsFilledUp : function(lastIndex,msg) {
		var code=null;
		for (var i=lastIndex;i>=0;i--) {
			
			code =document.getElementById("docItemList["+i+"].code").value
			//alert(" code:"+code+" msg:"+msg);
			if (code=='') {
				alert(msg);
				return false;
			}
		}
		document.orderitemAddForm.buttonValue.value = 'next';
		//Controller.onSubmit('orderitemAddForm',null,'saveDocItemList','next',null);
		Controller.onSubmit('orderitemAddForm','saveDocItemList','saveDocItemList','next');
		//return true;
	  },
  checkPOFilledUp:function(lastIndex,isEditable,msg) {
	var code=null;
	//alert("lastIndex>>>>"+lastIndex);
	for (var i=lastIndex;i>=0;i--) {
		code =document.getElementById("docItemList["+i+"].code").value
		if (code=='') {
			alert(msg);
			return false;
		}
	}
	document.orderitemAddForm.buttonValue.value = 'next';
	//Controller.onSubmit('orderitemAddForm',null,'saveDocItemList','next',null);
	if(isEditable==true)
		Controller.onSubmit('orderitemAddForm',null,'nextOrderItem','next');
	else
		Controller.onSubmit('orderitemAddForm',null,'saveDocItemList','next');
	//return true;
  },

  goToOrder : function () {
	document.orderitemAddForm.button.value = 'doc';
	return true;
  },
  doPrev : function() {
	document.orderitemAddForm.button.value = 'prev';
	return true;
  },
  doNext : function() {
	document.orderitemAddForm.button.value = 'next';
	return true;
  },
	loadOrder :function(csrfToken){

		//alert("*****1"+csrfToken);
  		var order = pageScope["order"];
		if (null == order)
	    {
	    	alert("Please select an order");
	    	return ;
	    }
	    order.id = order["order.id"];
	//    alert("*****");
		Controller.loadPage(contextRoot+'/business/order.handle?methodName=getDoc&'+csrfToken,pageScope['order'],null);
	},
	viewOrder : function(id,csrfToken){
		if(null == id)
		{
			alert("Please select an order");
			return;
		}
		/*
		document.updateForm.action=contextRoot+"/business/order.action?methodName=getDoc&viewMode=true&id="+id+"&"+csrfToken;
		document.updateForm.submit();
		*/
		Controller.loadPage(contextRoot+'/business/order.handle?methodName=getDoc&viewMode=true&id='+id+'&'+csrfToken,null,null);
},
	ammend : function(flag,/*boolean*/wfEnabled,tokenName,tokenValue){
	//if(selected==null || selected == '')
	var orderId = document.updateForm.orderId.value;
	if(orderId == null || orderId == '')
    {
        alert("Please select an order");
		return;
   	}
	//document.updateForm.action="<c:url value='/business/order.action'/>?methodName=ammendOrder&orderId="+selected+"&flag="+flag;
	document.updateForm.flag.value = flag;
	document.updateForm.oldOrderId.value = orderId;

	//document.updateForm.submit();
	if(!wfEnabled) Controller.onSubmit('updateForm',{"orderId":orderId,"flag":flag,tokenName:tokenValue},'ammendOrder',null);
	else Controller.loadPage(contextRoot+"/business/work.handle?methodName=initApproval&spec.code=ORDER_CREATION&"+tokenName+"="+tokenValue+"&addlBusinessRefStr=ammendOrder$"+orderId+"$"+flag,null,null);
},
    updateOrRecreateAmendedOrder : function(flag,/*boolean*/wfEnabled,tokenName,tokenValue,selectVal){
	var pOrderId = document.deleteAndCreateAmendOrderForm.pOrderId.value;
	var dOrderId = document.deleteAndCreateAmendOrderForm.dOrderId.value;
	document.deleteAndCreateAmendOrderForm.flag.value = flag;
	if(!wfEnabled) Controller.onSubmit('deleteAndCreateAmendOrderForm',{"pOrderId":pOrderId,"dOrderId":dOrderId,"selectVal":selectVal,"flag":flag,tokenName:tokenValue},'updateOrRecreateAmendedOrder',null);
	else Controller.loadPage(contextRoot+"/business/work.handle?methodName=initApproval&spec.code=ORDER_CREATION&"+tokenName+"="+tokenValue+"&addlBusinessRefStr=ammendOrder$"+pOrderId+"$"+flag,null,null);
},
	cancelPO : function(flag,/*boolean*/wfEnabled,tokenName,tokenValue){
	//if(selected==null || selected == '')
	var orderId = document.cancelForm.orderId.value;
	if(orderId == null || orderId == '')
    {
        alert("Please select an order for cancel");
		return;
   	}
	//document.updateForm.action="<c:url value='/business/order.action'/>?methodName=ammendOrder&orderId="+selected+"&flag="+flag;
	document.cancelForm.flag.value = flag;
	//document.updateForm.submit();
	if(!wfEnabled) Controller.onSubmit('cancelForm',{"orderId":orderId,"flag":flag,tokenName:tokenValue},'cancelOrder',null);
	else Controller.loadPage(contextRoot+"/business/work.handle?methodName=initApproval&spec.code=ORDER_CREATION&"+tokenName+"="+tokenValue+"&addlBusinessRefStr=cancelOrder$"+orderId+"$"+flag,null,null);
},

   respondToOrder : function(/*int*/orderId) {
	document.orderViewForm.action="getOrderResponseAction.do";
	document.orderViewForm.action=contextRoot+"/business/getOrderResponseAction.do?documentIdentity="+orderId;
	document.orderViewForm.target = "_self";
	document.orderViewForm.submit();
},
respondToOrderSpring : function(/*int*/orderId) {
	document.orderViewForm1.action=contextRoot+"/business/order.action?documentIdentity="+orderId;
	document.orderViewForm1.methodName.value = "getOrderResponse";
	document.orderViewForm1.target = "_self";
	document.orderViewForm1.submit();
},
	printOrder : function(/*int*/orgId,/*String*/formulaEnabled,/*String*/flag) {
		document.printOrderForm.orgId.value = orgId;
		document.printOrderForm.formulaEnabled.value = formulaEnabled;
		document.printOrderForm.flag.value = flag;
		document.printOrderForm.target = "_blank";
		document.printOrderForm.submit();
},
	modalwin : function(/*String*/orgType,csrfToken) {
	    var entityId = document.getElementById("id").value;
	    var docCode = document.getElementById("code").value;
	    var docCreateDate = document.getElementById("updateDate").value;
	    var docOwnerId = document.getElementById("createId").value;
	    var url = contextRoot+'/business/clarification.action?popUp=Y&methodName=getClarification&clarType=ORDCLAR_BUYER&entityId='+entityId+'&docCode='+docCode+'&docCreateDate='+docCreateDate+'&'+csrfToken;
	    if(orgType=='SELLER') url = contextRoot+'/business/clarification.action?popUp=Y&methodName=getClarification&clarType=ORDCLAR_SELLER&entityId='+entityId+'&docCode='+docCode+'&docCreateDate='+docCreateDate+'&docOwnerId='+docOwnerId+'&'+csrfToken;
		eval('window.open(url,"","left=510, width=600,height=400,resizable=yes,scrollbars")');
	},
	viewDeliverySchedule : function() {
		Controller.onSubmit('orderitemAddForm',null,'viewDeliverySchedule',null,null);
	},
	manualEntry : function(row_index) {
		$("tr[id^='sellerUser_role_']").each(function(x) {
			var field_id = this.id;
			var arr = field_id.split("_index_");
			var field_index = arr[1];
			var link_field_id = 'btn_index_'+row_index;
			link_field_id = link_field_id.toString();
			var link_text = document.getElementById(link_field_id).innerHTML;
			link_text = link_text.toString();


			if(row_index == field_index){

			var field_information_seller = 'orderSellerUsers['+field_index+'].sellerInformation';
			if(link_text == 'INPUT'){

				field_information_id = document.getElementById(field_information_seller);
				field_information_id.style.display ="block";


			}

			}
		});
		},

		printSupplierOrder : function(/*int*/orgId,/*String*/formulaEnabled,/*String*/flag,orgTypeId) {
			document.printSupplierOrderForm.orgId.value = orgId;
			document.printSupplierOrderForm.flag.value = flag;
			document.printSupplierOrderForm.orgTypeId.value = orgTypeId;
			document.printSupplierOrderForm.formulaEnabled.value = formulaEnabled;
			document.printSupplierOrderForm.target = "_blank";
			document.printSupplierOrderForm.submit();
	},

		addOrderIndentRow:function(/* string */tableId){
			if(confirm('WANT TO ADD MORE ROW ?')){
			/*	var noIndentdataRow = document.getElementById("noIndentdataRow");
				 if(noIndentdataRow.style.display = 'block'){
					 noIndentdataRow.style.display='none'
				 }
				*/
				if(OrderController.validateOrderIndentRow("indentInfo")){
				    tbody=document.getElementById(tableId);
				    var index = tbody.rows.length;
				    var newRow=tbody.insertRow(tbody.rows.length);
				    if((index % 2)==0)
				    	newRow.className='columnClass';
				    else
				    	newRow.className='alternateColumnClass';
				    index = index-1;
				    newRow.id=index;
				    var cell0 = newRow.insertCell(0);
				    cell0.setAttribute('class','dataClass');
				    cell0.innerHTML = '<input type="text" size="20" name="indentInfos['+index+'].code" id="indentInfos['+index+'].code"/>';

				    var cell1 = newRow.insertCell(1);
				    cell1.setAttribute('class','dataClass');
				    cell1.innerHTML = '<input type="text" size="20" readonly="true" name="indentInfos['+index+'].indentDate" id="indentInfos['+index+'].indentDate" style="width:140px;"/><a href="javascript:calendar(\'indentInfos['+index+'].IndentDate\',\'ddMMyyyy\',true,24);"><img src="' + contextRoot + '/image/Calendar.gif" border="0" /></a>';

				    var cell2 = newRow.insertCell(2);
				    cell2.setAttribute('class','dataClass');
				    cell2.innerHTML = '<textarea rows="4" cols="28" name="indentInfos['+index+'].remarks" id="indentInfos['+index+'].remarks" onblur="javascript:ValidationUtil.checkLength(\'indentInfos['+index+'].remarks\',20,5);"></textarea>';

				    var cell3 = newRow.insertCell(3);
				    cell3.setAttribute('class','dataClass');
				    var $clone=$("#unitLocation").clone();
				    var outer='<select id="unitLocation" name="indentInfos['+index+'].unitId">'+$clone.html()+'<\/select>';
				    cell3.innerHTML = outer;

				    var cell4 = newRow.insertCell(4);
				    cell4.innerHTML='<input type="checkbox" name="indentInfos['+index+'].isDeleteIndentRow" id="indentInfos['+index+'].isDeleteIndentRow" value="true"/>';

				    var cell5 = newRow.insertCell(5);
				    cell5.innerHTML = '<input type="hidden" size="20" name="indentInfos['+index+'].id" id="indentInfos['+index+'].id" value="99" />';

				}
			}

		},

		validateOrderIndentRow: function(tableId){
			var flag=true;
			var rowCount = document.getElementById(tableId).rows.length;
			for(i=1;i<rowCount;i++){
				var codeVal= $("input[name='indentInfos["+(i-1)+"].code']").val();
				var IndentDateVal=$("input[name='indentInfos["+(i-1)+"].indentDate']").val();
				var isRowDeleted=$("input[name='indentInfos["+(i-1)+"].isDeleteIndentRow']").is(':checked');

				if(!isRowDeleted){
					if(!codeVal || 0 === codeVal.length || /^\s*$/.test(codeVal)){
						alert('INDENT NO. SHOULD NOT BE LEFT BLANK FOR ROW NO. '+i);
						flag=false;
					}else if(!IndentDateVal || 0 === IndentDateVal || /^\s*$/.test(IndentDateVal)){
						alert('INDENT DATE SHOULD NOT BE LEFT BLANK FOR ROW NO. '+i);
						flag=false;
					}
				}
			}
			return flag;
		},
		
		signOrderBpscl : function(/*String*/ formId,/*String*/ token,/*String*/ methodName,/*String*/ pkiEnabled,/*String*/ orderEnabled,/*String*/ button) {
			
			if (confirm("DO YOU WANT TO PROCEED?"));
		    else return ;
			var code = document.getElementById("code").value;
			var orderDateSign = document.getElementById("orderDateSign").value;
			var signKey = code + '#|#' +orderDateSign;
			var authOrgId = document.getElementById("buyerOrganizationId").value;
			var orderDate= document.getElementById("orderDate").value;
			var currentdate = new Date(); 
			var month = currentdate.getMonth()+1;
			 var day= currentdate.getDate();
			 var hour =currentdate.getHours();
			 var minute =currentdate.getMinutes();
			 var second = currentdate.getSeconds;
			 if (month < 10){ 
			 	month = '0' + month;
			 }
			  if (day < 10){ 
			 	day = '0' + day;
			 }
			  if (hour < 10){ 
			 	hour = '0' + hour;
			 }
			  if (minute < 10){ 
			 	minute = '0' + minute;
			 }
			  if (second < 10){ 
			 	second = '0' + second;
			 }
			 var datetime =  currentdate.getFullYear() + "-"
						     + month  + "-" 
						     + day +" "+  
						     + hour + ":"  
						     + minute + ":" 
						     + second;
/*			var datetime =  currentdate.getFullYear() + "-"
			                + (currentdate.getMonth()+1)  + "-" 
			                + currentdate.getDate() +" "+  
			                + currentdate.getHours() + ":"  
			                + currentdate.getMinutes() + ":" 
			                + currentdate.getSeconds();*/
			if((orderDate<datetime) && (authOrgId ==11)){
				alert("Order date is lesser than present date.");
			}

			var valid = true;
			if(pkiEnabled && orderEnabled){

				valid = valid && signDocument(signKey);

			}
			if (valid){
				
				if(methodName=="submitDoc")
					{
					eval("document.orderAddForm").button.value = button;
					eval("document.orderAddForm").methodName.value = methodName;
					Controller.onSubmitWithCsrf(formId,token,methodName,button,null);
					}
				else
					{
					if(allRTEArray.length>0){
						
						$.each(allRTEArray, function( i, thisObj ){
						  //alert( "Index #" + i + ": " + thisObj);
						  thisObj.disable_design_mode(true);
						});
						
						allRTEArray=new Array();
					}
					Controller.onSubmitWithCsrf(formId,token,methodName,button,null);
					eval("document.orderAddForm").button.value = button;
					eval("document.orderAddForm").methodName.value = methodName;
					eval("document.orderAddForm").action = contextRoot + "/business/order.action";
					
					//document.orderAddForm.submit();
					}
				
			}

		}
}
var InspectionController = {
	selectIR : function(/*String*/ orderCode,/*int*/ orderId,/*String*/inhCode,/*String*/ordCrDate,/*int*/id,/*String*/code,/*String*/date,/*String*/reason,/*int*/groupId,/*String*/irType,/*String*/status,/*String*/ entNo,/*String*/ordDate) {
		pageScope["ir"] = {
			"order.id" : orderId, "order.code":orderCode,
			"order.orderInheritanceCode" : inhCode, "order.createDate" : ordCrDate,
			"code" : code, "inspectionDate":date,"id":id,
			"rejectionReason":reason,"groupId":groupId,
			"status":status,"uniqueEntNo":entNo,"order.orderDate" : ordDate
		};
		pageScope["irForIc"] = {
			"insReq.order.id" : orderId, "insReq.order.code":orderCode,
			"insReq.order.orderInheritanceCode" : inhCode, "insReq.order.createDate" : ordCrDate,
			"insReq.code" : code, "insReq.inspectionDate":date,"insReq.id":id,"insReq.irType":irType,"insReq.uniqueEntNo":entNo
		};
		if(sessionScope["_currPrivId"] == 101){
			$("#editIr").css("display","inline");
			//$("#addIc").css("display","inline");
		}
		if(sessionScope["_currPrivId"] == 107)
		{
			$("#assIr").css("display","inline");
		}
				if(sessionScope["_currPrivId"] == 122)
		{
			$("#forIr").css("display","inline");
		}

		if(sessionScope["_currPrivId"] == 104)
		{
			$("#resIr").css("display","inline");
		}

		if(sessionScope["_currPrivId"] == 123)
		{
			$("#clrIr").css("display","inline");
		}
		//Changed
		if(sessionScope["_currDocId"] == 107 && sessionScope["_currPrivId"] == 100){
			$("#addIc").css("display","inline");
		}
		if(sessionScope["_currPrivId"] == 102)
		{
			$("#viewIr").css("display","inline");
		}

	},
	selectIRItem : function(/*int*/ orderItemId,/*String*/code,/*int*/srlNo,/*int*/itemId) {
		pageScope["irItem"] = {
			"currItem.orderItem.id":orderItemId,"currItem.orderItem.code":code,
			"currItem.orderItem.docItmSrlNo":srlNo,"currItem.id" :itemId
		};
		$("#attr").css("display","inline");
	},
	selectICItem : function(/*int*/ insReqItemId,/*int*/ srlNo,/*int*/ itemId,/*int*/ itmCode) {
		pageScope["icItem"] = {
			"insReqItem.id":insReqItemId,"currItem.srlNo" : srlNo,"currItem.id" :itemId,
			"currItem.code" :itmCode
		};
		$("#attr").css("display","inline");
	},
	selectIC : function(/*int*/id,/*String*/reqCode,/*String*/reqDate,/*String*/code,/*String*/certDate){
		pageScope["ic"] = {"id":id, "insReq.code":reqCode, "insReq.inspectionDate":reqDate,"certCode":code,"certDate":certDate};
		if(sessionScope["_currDocId"] == 107)
		{
			if(sessionScope["_currPrivId"] == 101){
				$("#editIc").css("display","inline");
			}
		}

		if(sessionScope["_currPrivId"] == 106){
				$("#appIc").css("display","inline");
			}
		if(sessionScope["_currPrivId"] == 102)
		{
			$("#viewIc").css("display","inline");
		}

	},
	showIC : function(/*int*/id,/*String*/reqCode,/*String*/reqDate,/*String*/code,/*String*/certDate,/*String*/csrfToken){
		pageScope["ic"] = {"id":id, "insReq.code":reqCode, "insReq.inspectionDate":reqDate,"certCode":code,"certDate":certDate};
		if(sessionScope["_currPrivId"] == 102 || sessionScope["_currPrivId"] == 106)
		{
//			$("#viewIc").css("display","inline");
//			var url = contextRoot+"/business/ic.action?methodName=getDoc&viewMode=true&id="+id+"&certCode="+code+"&certDate="+certDate+"&insReq.code="+reqCode+"&insReq.inspectionDate="+reqDate;
//			window.open(url,"_newWindow",'top=0, left=0, height=500,menubar=yes, width=600,resizable=yes');
			InspectionController.viewIC(id,reqCode,reqDate,code,certDate,csrfToken);
		}
	},
	viewIC : function(id,insReqCode,insReqDate,code,date,csrfToken) {
		var url = contextRoot+"/business/ic.action?methodName=getDoc&viewMode=true&id="+id+"&certCode="+code+"&certDate="+date+"&insReq.code="+insReqCode+"&insReq.inspectionDate="+insReqDate+"&"+csrfToken;
		window.open(url,"_newWindow",'top=0, left=0, height=500,menubar=yes,scrollable=yes,scrollbars=1,width=600,resizable=yes');
	}
	,
	modalwin : function(/*String*/orgType) {
	    var entityId = document.getElementById("id").value;
	    var docCode = document.getElementById("code").value;
	    var docCreateDate = document.getElementById("createDate").value;
	    var docOwnerId = document.getElementById("createId").value;
	    var url = contextRoot+'/business/clarification.action?popUp=Y&methodName=getClarification&clarType=IRCLAR_BUYER&entityId='+entityId+'&docCode='+docCode+'&docCreateDate='+docCreateDate+'&docOwnerId='+docOwnerId;
	    if(orgType=='SELLER') url = contextRoot+'/business/clarification.action?popUp=Y&methodName=getClarification&clarType=IRCLAR_SELLER&entityId='+entityId+'&docCode='+docCode+'&docCreateDate='+docCreateDate;
		eval('window.showModalDialog(url,"","resizable:1,dialogHeight:600,dialogWidth:400")');
	}
	,
	initRevalidation : function() {
	Controller.onSubmit('inspectionCertViewForm',null,'initRevalidation',null,null);
	}
	,
	viewRevalidationHistory : function() {
	Controller.onSubmit('inspectionCertViewForm',null,'viewRevalidationHistory',null,null);
	}
	,
	saveForeclosure : function() {
	Controller.onSubmit('inspectionForm',null,'saveForeclosure',null,null);
	}
	,
	revalidateIC : function() {
	Controller.onSubmit('inspectionCertViewForm',null,'revalidateIC',null,null);
	},
	showPrint : function() {
	document.printIrForm.target = "_blank";
	document.printIrForm.submit();
	},
	showIcPrint : function() {
	document.printIcForm.target = "_blank";
	document.printIcForm.submit();
	}
}
var IndentController = {
	fetchAttribute : function (indentItemId,csrfToken)	{
		document.indentItemForm.selectedIndentItemId.value = indentItemId;
		IndentController.saveDocItemListWithCsrf('indentItemForm','saveDocItemList','attr',csrfToken);
	},
	saveDocItemListWithCsrf : function(formName,methodname,buttonName,csrfToken){
			eval("document."+formName).buttonValue.value = buttonName;
			//document.getElementById("buttonValue").value = buttonName;
			Controller.onSubmitWithCsrf(formName,csrfToken,methodname,null,null);
	},
	addRow : function(tableId){

    tbody=document.getElementById(tableId);
    var index = tbody.rows.length;
    if (index<0) index=0;
    if (index>0) {
	    var lastTerm = document.getElementById("indentSpecialTerm["+(index-1)+"].bigIndentTermLineDescription");
    }

    var prpIndex = document.indentForm.termCount.value ; //note
    prpIndex=prpIndex-1;
    var tab = document.getElementById(tableId);
    var root = tab.getElementsByTagName('tr')[prpIndex].parentNode;//the TBODY
	var clone=tab.getElementsByTagName('tr')[prpIndex].cloneNode(true);//the clone of the first row
	var elems = clone.getElementsByTagName('input');
	elems[0].setAttribute("name", "indentSpecialTerm["+index+"].indentTermSerialNumber");
	elems[0].setAttribute("value", (index+1));
	var elems = clone.getElementsByTagName('select');
	elems[0].setAttribute("name", "indentSpecialTerm["+index+"].indentTermTerm.id");
	elems[0].setAttribute("value","-1");
	var elems = clone.getElementsByTagName('textarea');
	elems[0].setAttribute("name", "indentSpecialTerm["+index+"].bigIndentTermLineDescription");
	elems[0].setAttribute("value","");

	clone.setAttribute('id',"r"+prpIndex);
	root.appendChild(clone);//appends the clone
    document.indentForm.termCount.value = parseFloat(prpIndex)+1;
	},
	deleteRow : function (tableId, ref) {
	var row = document.getElementById("r"+ref.id);
	tbody = document.getElementById(tableId);
	if (tbody.rows.length==2) {
		alert("The first row cannot be removed.");
		return;
	}
  	if (confirm('<fmt:message key="global.field.delete.specialTerm" />')) tbody.deleteRow(ref+1);
	},
    onTermAdd : function() {
    	var clonedRow = $('#termTab tr:last');
    	var noOfRows = $('#termTab tr').length;
    	$('td:first',clonedRow).text(noOfRows);
    	$('[id$=".srlNo"]',clonedRow).attr('value',noOfRows);
    },
    selectIndent : function(/*int*/ id,/*int*/ categoryId) {
		pageScope["indent"] = { "id" : id , "categoryId" : categoryId};
		if(sessionScope["_currPrivId"] == 102)
		{
			$("#viewIndent").css("display","inline");
		}
		if(sessionScope["_currPrivId"] == 101)
		{
			$("#editIndent").css("display","inline");
		}
	},
	selectIndentItem : function(/*int*/ selectedItmId,/*String*/ selectedItmCode,/*int*/selectedItmSrlNo,/*int*/ index) {
		pageScope["indentItem"] = {
			"currItem.id" : selectedItmId, "currItem.code":selectedItmCode,
			"currItem.docItmSrlNo" : selectedItmSrlNo, "index" : index
		};
		log("Page setting done"+pageScope["indentItem"].index);
		$("#attr").css("display","inline");
	},
	toAttribute : function () {
		//log("Page setting displayed::"+document.getElementById('docItemList['+pageScope["indentItem"].index+'].deleted'));
	    if(document.getElementsByName('docItemList['+pageScope["indentItem"].index+'].deleted')[0].checked)
		{
			alert("Please uncheck the delete box before viewing attributes");
			return false;
		}
		Controller.onSubmit(null,pageScope['indentItem'],'saveDocItemList','attr');

	},
	nextItemList : function (/*int*/ lastIndex) {
	    var code=null;
		if (Controller.getBlankRows("].code")>0) {
			alert('Please populate all the rows before proceeding to next page');
			return false;
		}
		Controller.onSubmit(null,null,'saveDocItemList','next');
    },
    getItemDetail : function (/*int*/ rowNum,/*Obj*/code) {
    	var csrfTokenName = document.getElementById("csrfTokenName").value;
    	var csrfTokenValue = document.getElementById("csrfTokenValue").value;
    	var csrfToken = csrfTokenName + "=" + csrfTokenValue;
    	var formNode = $("form[id!='dummyForm']");
    	$('input[id$=".code"]',formNode).each(function(){this.disabled=true;});
    	Controller.loadData(contextRoot+"/business/item.handle?methodName=getItem&code="+code.value+"&"+csrfToken,null,
    		function(/*String*/ data) {
    		$('input[id$=".code"]',formNode).each(function(){this.disabled=false;});
    		if (data["_errors"]!=null) {
    			Util.showMessage(data);
    			document.getElementById("docItemList["+rowNum+"].code").value = "";
    			return;
    		}
    		Util.clearContent($('#_msgBox'));
    		document.getElementById('docItemList['+rowNum+'].bigIndentItemLineDescription').value=Controller.unescapeHtml(data.item.description);
    	});
    }
}
var RfqController = {

		 validateWorkCatForm: function(){
			 var validator=$('#workCatForm').validate({
			        rules: {
			        	"procCatId": {
							required: true,
					        selectCheck: -1
						},
			            "rfqProcurementGroupId": {
							required: true,
					        selectCheck: -1
						},
			            "entityTypeTemplate[0].headerTemplateId": {
							required: true,
					        selectCheck: -1
						},
			            "entityTypeTemplate[1].headerTemplateId": {
							required: true,
					        selectCheck: -1
						},
			            "entityTypeTemplate[0].itemTemplateId": {
							required: true,
					        selectCheck: -1
						},
			            "entityTypeTemplate[1].itemTemplateId": {
							required: true,
					        selectCheck: -1
						}
			        },
				    messages :{
				    	"procCatId" : {
			        		required: "Procurement Category is required",
			        		selectCheck: "Please select Procurement Category"
			        	},
				        "rfqProcurementGroupId": {
				            required: "Procurement Group is required",
				            selectCheck: "Please select Procurement Group"
				        },
				        "entityTypeTemplate[0].headerTemplateId": {
				            required: "Qoutation Header Template is required",
				            selectCheck: "Please select Qoutation Header Template"
				        },
				        "entityTypeTemplate[1].headerTemplateId": {
				            required: "RFQ Header Template is required",
				            selectCheck: "Please select RFQ Header Template"
				        },
				        "entityTypeTemplate[0].itemTemplateId": {
				            required: "Quotation Item Template is required",
				            selectCheck: "Please select Quotation Item Template"
				        },
				        "entityTypeTemplate[1].itemTemplateId": {
				        	required: "Rfq Item Template is required",
				        	selectCheck: "Please select Rfq Item Template"
				        }
				    }
			    });
			    $.validator.addMethod(
			    		"selectCheck",
			    		function(value, element, argument) {
			            	return argument != value;
			        	},
			        	"Please select an Option"
			        );

			if(!($('#workCatForm').valid())){
		    	return false;
		    }else{
				document.getElementById('workCatForm').submit();
			}
		},
		validateBhelWorkCatForm: function(){
			 var validator=$('#workCatForm').validate({
			        rules: {
			        	"procCatId": {
							required: true,
					        selectCheck: -1
						},
			            "rfqProcurementGroupId": {
							required: true,
					        selectCheck: -1
						},
			            "entityTypeTemplate[0].headerTemplateId": {
							required: true,
					        selectCheck: -1
						},
			            "entityTypeTemplate[1].headerTemplateId": {
							required: true,
					        selectCheck: -1
						},
			            "entityTypeTemplate[0].itemTemplateId": {
							required: true,
					        selectCheck: -1
						},
			            "entityTypeTemplate[1].itemTemplateId": {
							required: true,
					        selectCheck: -1
						}
			        },
				    messages :{
				    	"procCatId" : {
			        		required: "RFQ Floated Under The Policy is required",
			        		selectCheck: "Please select RFQ Floated Under The Policy"
			        	},
				        "rfqProcurementGroupId": {
				            required: "Procurement Group is required",
				            selectCheck: "Please select Procurement Group"
				        },
				        "entityTypeTemplate[0].headerTemplateId": {
				            required: "Qoutation Header Template is required",
				            selectCheck: "Please select Qoutation Header Template"
				        },
				        "entityTypeTemplate[1].headerTemplateId": {
				            required: "RFQ Header Template is required",
				            selectCheck: "Please select RFQ Header Template"
				        },
				        "entityTypeTemplate[0].itemTemplateId": {
				            required: "Quotation Item Template is required",
				            selectCheck: "Please select Quotation Item Template"
				        },
				        "entityTypeTemplate[1].itemTemplateId": {
				        	required: "Rfq Item Template is required",
				        	selectCheck: "Please select Rfq Item Template"
				        }
				    }
			    });
			    $.validator.addMethod(
			    		"selectCheck",
			    		function(value, element, argument) {
			            	return argument != value;
			        	},
			        	"Please select an Option"
			        );

			if(!($('#workCatForm').valid())){
		    	return false;
		    }else{
				document.getElementById('workCatForm').submit();
			}
		},

	attachItemListWithSeller : function(entityId, partNumber, selectedSellerId, viewMode, csrfToken){
		//alert(entityId+" : "+partNumber+" : "+selectedSellerId+" : "+viewMode+" : "+csrfToken);

		var url = contextRoot+"/business/rfq.action?methodName=getItemListforSeller&viewMode="+viewMode+"&selectedSellerId="+selectedSellerId+"&entityId="+entityId+"&partNumber="+partNumber+"&"+csrfToken;
		window.open(url, 'getAttachItemListWithSeller_window', 'width=800,height=500,scrollbars=yes,resizable=yes,menubar=no,directories=no,location=no');
	},

 rejectionItemSubmit:function (partNum,csrfToken,formName,methodName){
	document.getElementById('rfqPartNo').value=partNum;
	Controller.onSubmitWithCsrf(formName,csrfToken,methodName,null,null);

	// this.close();
},




	getItemDetail : function (/*int*/ rowNum,/*Obj*/code,/*String*/csrfToken) {
	var formNode = $("form[id!='dummyForm']");
	 	var buyerOrgId = 0;
	 	var nonExistingRfqItemAdd=$("input[name='nonExistingRfqItemAdd']",formNode).val();
    	$('input[id$=".code"]',formNode).each(function(){this.disabled=true;});
    	Controller.loadData(contextRoot+"/business/item.handle?methodName=getItem&code="+code.value+"&"+csrfToken,null,
    		function(/*String*/ data) {
    		$('input[id$=".code"]',formNode).each(function(){this.disabled=false;});
    		if (data["_errors"]!=null) {
    			Util.showMessage(data);
    			document.getElementById('rfqItem['+rowNum+'].code').value='';
    			return;
    		}
    		Util.clearContent($('#_msgBox'));
    		if(data.item.id==0 && nonExistingRfqItemAdd=="false"){
    			alert("Item does not exist");
    			document.getElementById('rfqItem['+rowNum+'].bigRfqItemLineDescription').value="";
    			document.getElementById('rfqItem['+rowNum+'].code').value="";
    			document.getElementById('rfqItem['+rowNum+'].bigRfqItemLineDescription').disabled=true;
    			//$('input[id="code"]',formNode).removeAttr("readonly");
    			//return;
    		}
			if(data.item.id >0 ){
			document.getElementById('rfqItem['+rowNum+'].bigRfqItemLineDescription').disabled=false;
			}
    		if(Controller.unescapeHtml(data.item.description)!=null&& Controller.unescapeHtml(data.item.description)!=""){
    			document.getElementById('rfqItem['+rowNum+'].bigRfqItemLineDescription').value=Controller.unescapeHtml(data.item.description);
    		}
    		//var itemDescription=data.item.description;
    		//alert("$(itemDescription).html().text():"+$(itemDescription).html().text());
    		//alert("itemDescriptionnn:"+$("#rfqItem["+rowNum+"].bigRfqItemLineDescription").length);
    		//$("#rfqItem["+rowNum+"].bigRfqItemLineDescription").value($(itemDescription).html().text());
    		var itemQtn = document.getElementById('rfqItem['+rowNum+'].rfqItemQuantity').value;
    		var totValue = itemQtn * data.item.estimatedValue;
    		document.getElementById('rfqItem['+rowNum+'].rfqItemItem.estimatedValue').value = data.item.estimatedValue;
    		document.getElementById('rfqItem['+rowNum+'].rfqItemPrice').value=totValue;
  			if(document.getElementById('buyerOrgId')){
  				buyerOrgId = document.getElementById('buyerOrgId').value  ;
  			}

  			if(buyerOrgId == 2350){
     		if (data.item.isServiceItemYN == "Y" )
    		{
    			document.getElementById('rfqItem['+rowNum+'].bigRfqItemLineDescription').readOnly=false;
    			document.getElementById('rfqItem['+rowNum+'].bigRfqItemLineDescription').removeAttribute('readonly');

    		} else {
    			document.getElementById('rfqItem['+rowNum+'].bigRfqItemLineDescription').readOnly=true;

    		}
			}
    		var content = new Array();
			var j=0;
			if(data.length == 0)
			{
				return;
			}
			var attachLink = "item.action?popUp=Y&methodName=openItemAttachment&itemId="+data.item.id+"&fileName=";
			for(var i=0;i<data.item.attachments.length;i++)
			{
				content[j++]='<div><input name="rfqItem[';
				content[j++]=rowNum;
				content[j++]='].possibleAttachments[';
				content[j++]=i;
				content[j++]='].selected';
				content[j++]='" type="checkbox" value="true"/>';
				content[j++]='<a target = "_new" href="';
				//content[j++]=data.item.attachments[i].path;
				content[j++]= attachLink+data.item.attachments[i].fileName+"&ext="+data.item.attachments[i].extention+"&"+csrfToken;
				content[j++]='">';
				content[j++]=data.item.attachments[i].label;
				content[j++]='</a>';
				content[j++]='<input name="rfqItem[';
				content[j++]=rowNum;
				content[j++]='].possibleAttachments[';
				content[j++]=i;
				content[j++]='].fileName';
				content[j++]='" type="hidden" value="';
				content[j++]=data.item.attachments[i].fileName;
				content[j++]='"/>';
				content[j++]='</div>';
			}
			var itemTable = document.getElementById('inItemTab'+rowNum);
			var rowCnt  = itemTable.rows.length;
			itemTable.rows[rowCnt-1].cells[1].innerHTML=content.join('');
			
	    });
    },
    getItem : function(/*String*/ csrfToken){
    	var formNode = $("form[id!='dummyForm']","#_content");
    	var code = $('input[id="code"]',formNode).get(0);
    	//log('calling getItem with code='+code);
    	if (code.value=='') return;
    	var isServiceItemYN = document.getElementById("isServiceItemYN").value;
    	Controller.loadData(contextRoot+"/business/item.handle?methodName=getItem&code="+code.value+"&isServiceItemYN="+isServiceItemYN+"&"+csrfToken,null,
    		function(/*Object*/ data) {
    		if (data["_errors"]!=null) {
    			log(data);
    			Util.showMessage(data);
    			return;
    		}else{

    		}
    		if (data.item.id == 0){
    			alert("This item does not exist");
    		}
    		Util.clearContent($('#_msgBox'));
    		$('input[id="code"]',formNode).attr("readonly","readonly");
    		$('#attachmentTab',formNode).css("display","block");
    		$('input[id="id"]',formNode).val(data.item.id);
    		//log($('input[id="id"]',formNode).length);
    		$('textarea[id="description"]',formNode).val(Controller.unescapeHtml(data.item.description));
    		//CKEDITOR.instances.description.setData( data.item.description );
    		$('input[id="estimatedValue"]',formNode).val(data.item.estimatedValue);
    	});
    },
    viewUserContact :function(userId) {
    	var w =600;
    	var h =600;

    	var left = (screen.width/2)-(w/2);
    	var top = (screen.height/2)-(h/2);
    	document.viewUserContactForm.profileIdentity.value = userId;
       	window.open('', 'userContactView_window', 'scrollbars=1, top=0, left=510, height=400, width=500, toolbar=no, status=no');
       	document.viewUserContactForm.target="userContactView_window";
    	document.viewUserContactForm.submit();
    },
	submitPaymentForm : function() {
		document.PaymentInitForm.methodName.value = "getRfqsByPaymentStatus";
		document.PaymentInitForm.submit();
	},
	viewDelegateToUserListContact :function(rfqSellerUserId,rfqId,rfqPartNumber) {
		var urlString = contextRoot+'/business/rfq.action?methodName=getRfqDelegateToUserListContactDetail&rfqId='+rfqId+'&rfqSellerUserId='+rfqSellerUserId+'&rfqPartNumber='+rfqPartNumber;
		window.open(urlString, 'rfqDelegateToUserContactView_window', 'top=0, left=510, height=400, width=700, toolbar=no, status=no,scrollbars=yes');

	},
	deleteRfqSection : function(formName,csrfToken,methodName,entityId,entityValue,docSectionId,docTemplateId){
		eval("document."+formName).entityId.value=entityId;
		eval("document."+formName).entityValue.value=entityValue;
		eval("document."+formName).documentSectionId.value=docSectionId;
		eval("document."+formName).documentConfigTemplateId.value=docTemplateId;
		eval("document."+formName).methodName.value=methodName;
		if(entityId==100){
			if (confirm('Delete the Section from the Rfq?')) eval("document."+formName).submit();
		}
	},retrieveRfqSection : function(formName,csrfToken,methodName,entityId,entityValue,docSectionId,docTemplateId){
		eval("document."+formName).entityId.value=entityId;
		eval("document."+formName).entityValue.value=entityValue;
		eval("document."+formName).documentSectionId.value=docSectionId;
		eval("document."+formName).documentConfigTemplateId.value=docTemplateId;
		eval("document."+formName).methodName.value=methodName;
		eval("document."+formName).submit();
	},
	getCorrigendumItemDetail : function (/*int*/ rowNum,/*Obj*/code,/*String*/csrfToken) {
	 	var formNode = $("form[id!='dummyForm']");
	 	var buyerOrgId = 0;
    	$('input[id$=".code"]',formNode).each(function(){this.disabled=true;});
    	Controller.loadData(contextRoot+"/business/item.handle?methodName=getItem&code="+code.value+"&"+csrfToken,null,
    		function(/*String*/ data) {
    		$('input[id$=".code"]',formNode).each(function(){this.disabled=false;});
    		if (data.item.id==0) {
    			//Util.showMessage(data);
    			alert("Please enter valid Item Code");
    			document.getElementById('domain.rfqItem['+rowNum+'].code').value='';
    			return;
    		}
    		Util.clearContent($('#_msgBox'));
    		document.getElementById('domain.rfqItem['+rowNum+'].bigRfqItemLineDescription').value=data.item.description;
    		var itemQtn = document.getElementById('domain.rfqItem['+rowNum+'].rfqItemQuantity').value;
    		var totValue = itemQtn * data.item.estimatedValue;
    		document.getElementById('domain.rfqItem['+rowNum+'].rfqItemItem.estimatedValue').value = data.item.estimatedValue;
    		document.getElementById('domain.rfqItem['+rowNum+'].rfqItemPrice').value=totValue;
  			if(document.getElementById('buyerOrgId')){
  				buyerOrgId = document.getElementById('buyerOrgId').value
  			}

  			if(buyerOrgId == 2350){
     		if (data.item.isServiceItemYN == "Y" )
    		{
    			document.getElementById('domain.rfqItem['+rowNum+'].bigRfqItemLineDescription').readOnly=false;
    			document.getElementById('domain.rfqItem['+rowNum+'].bigRfqItemLineDescription').removeAttribute('readonly');

    		} else {
    			document.getElementById('domain.rfqItem['+rowNum+'].bigRfqItemLineDescription').readOnly=true;

    		}
			}
    		var content = new Array();
			var j=0;
			if(data.length == 0)
			{
				return;
			}
			var attachLink = "item.action?popUp=Y&methodName=openItemAttachment&itemId="+data.item.id+"&fileName=";
			for(var i=0;i<data.item.attachments.length;i++)
			{
				content[j++]='<div><input name="domain.rfqItem[';
				content[j++]=rowNum;
				content[j++]='].possibleAttachments[';
				content[j++]=i;
				content[j++]='].selected';
				content[j++]='" type="checkbox" value="true"/>';
				content[j++]='<a target = "_new" href="';
				//content[j++]=data.item.attachments[i].path;
				content[j++]= attachLink+data.item.attachments[i].fileName+"&ext="+data.item.attachments[i].extention+"&"+csrfToken;
				content[j++]='">';
				content[j++]=data.item.attachments[i].label;
				content[j++]='</a>';
				content[j++]='<input name="domain.rfqItem[';
				content[j++]=rowNum;
				content[j++]='].possibleAttachments[';
				content[j++]=i;
				content[j++]='].fileName';
				content[j++]='" type="hidden" value="';
				content[j++]=data.item.attachments[i].fileName;
				content[j++]='"/>';
				content[j++]='</div>';
			}
			var itemTable = document.getElementById('inItemTab'+rowNum);
			itemTable.rows[3].cells[1].innerHTML=content.join('');
	    });
    },
    initRfqNoteSheet : function(rfqId,partNo,csrfToken,methodName,formName){
    	if(document.quotationSearchForm.quotationRfqId.value == '')
		{
	    	alert("Please select a rfq");
	    	return;
	    }
		eval("document."+formName).methodName.value=methodName;
		eval("document."+formName).submit();
	},
	attachTermWithSeller : function(rfqId,rfqPartNumber,sellerId,rfqCatId,methodName,viewMode,csrfToken){

		var url = contextRoot+"/business/rfq.handle?methodName="+methodName+"&viewMode="+viewMode+"&selectedSellerId="+sellerId+"&id="+rfqId+"&rfqDate.partNumber="+rfqPartNumber+"&rfqCategory.id="+rfqCatId+"&"+csrfToken;
		window.open(url, 'rfqTermUser_window', 'width=800,height=500,scrollbars=yes,resizable=yes,menubar=no,directories=no,location=no');
	},
	 trialQuotationItemSubmit:function (partNum,formName,methodName){
				document.getElementById('rfqPartNo').value=partNum;
				Controller.onSubmit(formName,methodName,null,null);
				// this.close();
	}
}

var CategoryController = {
selectCat : function(/*int*/ catId) {
	        pageScope["cat"] = { "categoryId":catId };
			$("#catDtl").css("display","inline");
	}
}
var ItemController = {
selectItem : function(/*int*/ itemId,/*String*/code,/*String*/isServiceItemYN) {
	        pageScope["item"] = { "itemId":itemId ,"itemCode":code,"isServiceItemYN":isServiceItemYN};
			$("#itemDtl").css("display","inline");
	},
getLot : function(csrfToken){
	    	var formNode = $("form[id!='dummyForm']","#_content");
    	var code = $('input[id="itemCatCode"]',formNode).get(0);
    	//log('calling getItem with code='+code);
    	if (code.value=='') return;
Controller.loadData(contextRoot+"/business/item.handle?methodName=getLot&itemCatCode="+code.
value+"&"+csrfToken,null,
    		function(/*Object*/ data) {
    		if (data["_errors"]!=null) {
    			log(data);
    			Util.showMessage(data);
    			return;
    		}
    		Util.clearContent($('#_msgBox'));
    		$('input[id="itemCatCode"]',formNode).attr("readonly","readonly");
     		$('input[id="id"]',formNode).val(data.lot.id);
    		$('textarea[id="description"]',formNode).val(data.lot.description);
    	});
},
getUnit : function(csrfToken){
	    var formNode = $("form[id!='dummyForm']","#_content");
    	var code = $('input[id="code"]',formNode).get(0);
    	//log('calling getUnit with code='+code);
    	if (code.value=='') return;
		Controller.loadData(contextRoot+"/business/item.handle?methodName=getUnit&code="+code.value+"&"+csrfToken,null,function(/*Object*/ data) {
			if (data["_errors"]!=null) {
    			log(data);
    			Util.showMessage(data);
    			return;
    		}
    		Util.clearContent($('#_msgBox'));
    		$('input[id="code"]',formNode).attr("readonly","readonly");
     		$('input[id="id"]',formNode).val(data.unit.id);
     		$('textarea[id="description"]',formNode).attr("readonly","readonly");
    		$('textarea[id="description"]',formNode).val(data.unit.description);
    		$('select[id="allowDecimal"]',formNode).attr("disabled","true");
    		$('select[id="allowDecimal"]',formNode).val(data.unit.allowDecimal);
      		$('button[id="submitDoc"]',formNode).hide();
    	});
},
getDescriptionByLotCode : function(rfqItemCount){
		var formNode = $("form[id!='rfqAddForm']","#_content");
    	var code = $('#selectId option:selected',formNode).text();
    	var csrfToken=$("#csrfToken").val();
    	//log('calling getItem with code='+code);
		if($('#selectId option:selected',formNode).val()=="0"){
			$('#selectDescription',formNode).html("");
			return;
		}

		Controller.loadData(contextRoot+"/business/item.handle?methodName=getLotDescriptionByLotCode&itemCatCode="+code+"&"+csrfToken,null,
    		function(/*Object*/ data) {
    		if (data["_errors"]!=null) {
    			log(data);
    			Util.showMessage(data);
    			return;
    		}
    		Util.clearContent($('#_msgBox'));
     		$('#selectDescriptionId',formNode).html("<textarea  name='rfqItemCatList["+rfqItemCount+"].description' rows='3' cols='20'>"+data.lot.description+"</textarea>");
     		$('#lastPurchasedPriceId',formNode).html("<input type='text' name='rfqItemCatList["+rfqItemCount+"].lastPurchasedPrice' value='0.0' />");
    	});
	}

}
var ReceiptController = {
	selectReceiptItem : function(/*int*/ selectedItmId,/*String*/ selectedItmCode,/*int*/selectedItmSrlNo,/*int*/ index) {
		pageScope["receiptItem"] = {
			"currItem.id" : selectedItmId, "currItem.code":selectedItmCode,
			"currItem.docItmSrlNo" : selectedItmSrlNo, "index" : index,
			"currItem.description" : document.getElementById("docItemList["+index+"].description").value,
			"currItem.quantityAdviced" : document.getElementById("docItemList["+index+"].quantityAdviced").value,
			"currItem.quantityReceived" : document.getElementById("docItemList["+index+"].quantityReceived").value,
			"currItem.quantityAccepted" : document.getElementById("docItemList["+index+"].quantityAccepted").value
		};
		log("Page setting done"+pageScope["receiptItem"].index);
		$("#attr").css("display","inline");
	},
	selectReceipt : function (/*int*/ id,/*String*/ orderCode,/*boolean*/ viewMode,csrfToken) {
		pageScope["receipt"] = {"id":id,"order.code":orderCode};
		if (null!=viewMode) Controller.loadPage(contextRoot+'/business/receipt.handle?methodName=getDoc&viewMode=true'+"&"+csrfToken,pageScope['receipt'],null);
	},	
	selectReceiptForView : function(/*int*/ id,/*String*/ orderCode,/*boolean*/ viewMode,csrfToken,orderId){
		pageScope["receipt"] = {"id":id,"order.code":orderCode,"order.id":orderId};
		if (null!=viewMode) Controller.loadPage(contextRoot+'/business/receipt.handle?methodName=getDoc&viewMode=true'+"&"+csrfToken,pageScope['receipt'],null);
	},
	selectDraftReceipt : function (/*int*/ id,/*String*/ receiptCode) {
		pageScope["receipt"] = {"receipt.id":id, "receipt.code":receiptCode };
	},
	onDiscAdd : function (){
		log('onDiscAdd ');
	    var clonedRow = $('#discTab tr:last');
	    $('[id$=".id"]',clonedRow).attr('value','0');
	},
	loadReceipt :function(csrfToken){
  		var receipt = pageScope["receipt"];
		if (null == receipt)
	    {
	    	alert("Please select a receipt");
	    	return ;
	    }
	    receipt.id = receipt["receipt.id"];
		Controller.loadPage(contextRoot+'/business/receipt.handle?methodName=getDoc&'+csrfToken,pageScope['receipt'],null);
	},
	printReceipt : function(receiptId,orgId,orgName){
	   	document.receiptPrintForm.action = "report.action";
	   	document.receiptPrintForm.methodName.value = "showReport";
	   	document.receiptPrintForm.reportName.value = "receiptViewPrint";
	   	document.receiptPrintForm.popUp.value = "Y";
	   	document.receiptPrintForm.receiptId.value = receiptId;
		document.receiptPrintForm.orgId.value = orgId;
		document.receiptPrintForm.orgName.value = orgName;
		document.receiptPrintForm.target="_blank";
	   	document.receiptPrintForm.submit();
	},
	viewReceiptPrint:  function(receiptId){
		var target = 'windowFormTarget';
		window.open('', target, 'scrollbars=yes, menubar=no, height=650, width=900, resizable=yes, toolbar=no, status=no');
		document.receiptPrintForm.setAttribute('target', target);
		document.receiptPrintForm.id.value = receiptId;
		document.receiptPrintForm.submit();		
	},
	viewReceipt : function(id,csrfToken){
		if(null == id)
		{
			alert("Please select an Receipt");
			return;
		}
		Controller.loadPage(contextRoot+'/business/receipt.handle?methodName=getDoc&viewMode=true&id='+id+"&"+csrfToken,null,null);
	},

	/*addBl : function(id,csrfToken){
		if(null == id)
		{
			alert("Please select an Order");
			return;
		}
		alert(id);
		Controller.loadPage(contextRoot+'/business/receipt.handle?methodName=addBl&viewMode=true&id='+id+"&"+csrfToken,null,null);
	},*/

	addBl : function(action){

		var checkedIndex=$("input[name=_radio]").index($("input[name=_radio]:checked"));

			var orderId = $('input:radio[name=_radio]:checked').val();
			//alert(orderId);
			if(orderId == null || orderId == '')
			{
				alert("Please select an order");
				return false;
			}
			pageScope["receipt"] = {"order.id" : orderId}

		},
	addBe : function(action){

		var checkedIndex=$("input[name=_radio]").index($("input[name=_radio]:checked"));

			var blId = $('input:radio[name=_radio]:checked').val();
			//alert(orderId);
			if(blId == null || blId == '')
			{
				alert("Please select a BL");
				return false;
			}
			pageScope["receipt"] = {"bl.id" : blId}

		},
	saveBEFromUpdate : function(tableId, action , csrfToken) {

			tbody=document.getElementById(tableId);
			var index = tbody.rows.length;
			numOfRows = index - 4;
			if(numOfRows > 0 ){

			    for(rowNum = 1; rowNum <= numOfRows; rowNum++) {
			    	var sUrl="";

			    	if (!ReceiptController.validateUpdateBeRow(rowNum)) return;
			    }

			    if(action == "save") {
			    	Controller.onSubmit('updateBeGroupForm',pageScope['beGroup'],'updateBeGroup','save');
				} else if (action == "submit") {
					Controller.onSubmitWithCsrf('updateBeGroupForm',csrfToken,'submitBeDoc',null,null);
				} else if (action == "assignApprovers") {
					Controller.onSubmitWithCsrf('updateBeGroupForm',csrfToken,'updateBeGroup','saveBeRowsAndAssignApprover',null);
				}
			}
			else
				{
					alert("Please add a BE row.");
					return;
				}
		},
		validateUpdateBeRow : function (/*int*/ index) {
			var maxSize = 5 ;

		    if (index>0) {

		    	var lastBeNo = document.getElementById("beGroupUpdate["+(index-1)+"].beNo");
			    if(null!=lastBeNo) {

				    if((lastBeNo.value=='') || (lastBeNo.value==null)) {
				    	alert("Please specify the BE no for row " + index);
				    	return false;
				    }
				}
			    var lastBeDate = document.getElementById("beGroupUpdate["+(index-1)+"].beDate");
			    if(null!=lastBeDate) {
				    if((lastBeDate.value=='') || (lastBeDate.value==null)) {
				    	alert("Please specify the BE date for row " + index);
				    	return false;
				    }
				}

		    	var lastBeNetQty = document.getElementById("beGroupUpdate["+(index-1)+"].beNetQty");

			    if(null!=lastBeNetQty) {

				    if((lastBeNetQty.value=='') || (lastBeNetQty.value==null)) {
				    	alert("Please specify the net quantity for row " + index);
				    	return false;
				    }
					if(!$.isNumeric(lastBeNetQty.value)) {
					    alert("Please enter a numeric net quantity for row " + index);
					    return false;
					}
				}

		    	var lastBeGrossQty = document.getElementById("beGroupUpdate["+(index-1)+"].beGrossQty");

			    if(null!=lastBeGrossQty) {

				    if((lastBeGrossQty.value=='') || (lastBeGrossQty.value==null)) {
				    	alert("Please specify the gross quantity for row " + index);
				    	return false;
				    }
					if(!$.isNumeric(lastBeGrossQty.value)) {
					    alert("Please enter a numeric gross quantity for row " + index);
					    return false;
					}
				}

		    	var lastBeOum = document.getElementById("beGroupUpdate["+(index-1)+"].beUom");

			    if(null!=lastBeOum) {

				    if((lastBeOum.value==0)) {
				    	alert("Please specify the OUM for row " + index);
				    	return false;
				    }
				}

		    	var lastBePlantLocation = document.getElementById("beGroupUpdate["+(index-1)+"].bePlantLocation");

			    if(null!=lastBePlantLocation) {

				    if((lastBePlantLocation.value==0)) {
				    	alert("Please specify the Plant Location for row " + index);
				    	return false;
				    }
				}
		    }
		    return true;
		},
	addDuplicateRowBe : function(count){

		//tbody=document.getElementById(manageAddBlTab);
//	    var index = tbody.rows.length - 2;
		//var index = tbody.rows.length;
		//if (index<0) index=0;
			var referenceNodes = document.getElementById("manageAddBlTab").getElementsByTagName("tr");
		 	var referenceNode = referenceNodes[1];
		    var newNode = referenceNode.cloneNode(true);
		    var index = referenceNodes.length-2;
		    //alert('index'+index);
		    //newNode.getElementsByTagName("input")[0].checked = false;
		    newNode.getElementsByTagName("input")[0].value = "";
		    newNode.getElementsByTagName("input")[0].name = 'beRows['+index+'].beNo';
		    newNode.getElementsByTagName("input")[0].id = 'beRows['+index+'].beNo';

		    newNode.getElementsByTagName("input")[1].value = "";
		    newNode.getElementsByTagName("input")[1].name = 'beRows['+index+'].beDate';
		    newNode.getElementsByTagName("input")[1].id = 'beRows['+index+'].beDate';

		    newNode.getElementsByTagName("input")[2].value = "";
		    newNode.getElementsByTagName("input")[2].name = 'beRows['+index+'].beNetQty';
		    newNode.getElementsByTagName("input")[2].id = 'beRows['+index+'].beNetQty';

		    newNode.getElementsByTagName("input")[3].value = "";
		    newNode.getElementsByTagName("input")[3].name = 'beRows['+index+'].beGrossQty';
		    newNode.getElementsByTagName("input")[3].id = 'beRows['+index+'].beGrossQty';

		    newNode.getElementsByTagName("select")[0].value = "";
		    newNode.getElementsByTagName("select")[0].name = 'beRows['+index+'].beUom';
		    newNode.getElementsByTagName("select")[0].id = 'beRows['+index+'].beUom';

		    newNode.getElementsByTagName("select")[1].value = "";
		    newNode.getElementsByTagName("select")[1].name = 'beRows['+index+'].bePlantLocation';
		    newNode.getElementsByTagName("select")[1].id = 'beRows['+index+'].bePlantLocation';

		   /* var text = '<a href="#" onclick="ReceiptController.delBeRow(\'' + 'manageAddBlTab' + '\', this.parentNode.parentNode.rowIndex);">CANCEL</a>';
		    var element = document.createElement('p');              //this creates an empty node of the type specified
		    element.appendChild(document.createTextNode(text));     //this creates a new text node and inserts it into our empty node
		           //this sets the style in inline CSS (warning, this needs different syntax in IE)
		    newNode.appendChild(element);*/
		    newNode.getElementsByTagName("a")[0].href = "javascript:calendar('beRows["+index+"].beDate','ddMMyyyy',true,24);";;
		    referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
	},

	addDuplicateRowForBe : function(count){

			var referenceNodes = document.getElementById("manageAddBeTab").getElementsByTagName("tr");

			var referenceNode = referenceNodes[1];
			var i = referenceNodes.length-3;
			var newNode = referenceNode.cloneNode(true);
		    newNode.removeAttribute("style");
		    var index = referenceNodes.length-4;

		    newNode.getElementsByTagName("input")[0].name = 'beGroupUpdate['+index+'].beNo';
		    newNode.getElementsByTagName("input")[0].id = 'beGroupUpdate['+index+'].beNo';

		    newNode.getElementsByTagName("input")[1].name = 'beGroupUpdate['+index+'].beDate';
		    newNode.getElementsByTagName("input")[1].id = 'beGroupUpdate['+index+'].beDate';

		    newNode.getElementsByTagName("input")[2].name = 'beGroupUpdate['+index+'].beNetQty';
		    newNode.getElementsByTagName("input")[2].id = 'beGroupUpdate['+index+'].beNetQty';

		    newNode.getElementsByTagName("input")[3].name = 'beGroupUpdate['+index+'].beGrossQty';
		    newNode.getElementsByTagName("input")[3].id = 'beGroupUpdate['+index+'].beGrossQty';

		    newNode.getElementsByTagName("select")[0].name = 'beGroupUpdate['+index+'].beUom';
		    newNode.getElementsByTagName("select")[0].id = 'beGroupUpdate['+index+'].beUom';

		    newNode.getElementsByTagName("select")[1].name = 'beGroupUpdate['+index+'].bePlantLocation';
		    newNode.getElementsByTagName("select")[1].id = 'beGroupUpdate['+index+'].bePlantLocation';

		    newNode.getElementsByTagName("a")[0].href = "javascript:calendar('beGroupUpdate["+index+"].beDate','ddMMyyyy',true,24);";;


		    referenceNode.parentNode.insertBefore(newNode, referenceNodes[i].nextSibling);
	},


	addDuplicateRowForBL : function(){

		//tbody=document.getElementById(manageAddBlTab);
//	    var index = tbody.rows.length - 2;
		//var index = tbody.rows.length;
		//if (index<0) index=0;
			var referenceNodes = document.getElementById("manageAddBlTab").getElementsByTagName("tr");
		 	var referenceNode = referenceNodes[referenceNodes.length - 3];
		    var newNode = referenceNode.cloneNode(true);
		    var index = referenceNodes.length-3;

		    //newNode.getElementsByTagName("input")[0].checked = false;

		    newNode.getElementsByTagName("input")[0].value = "";
		    newNode.getElementsByTagName("input")[0].name = 'blRows['+index+'].invoiceNo';
		    newNode.getElementsByTagName("input")[0].id = 'blRows['+index+'].invoiceNo';

		    newNode.getElementsByTagName("input")[1].value = "";
		    newNode.getElementsByTagName("input")[1].name = 'blRows['+index+'].invoiceDate';
		    newNode.getElementsByTagName("input")[1].id = 'blRows['+index+'].invoiceDate';

		    var cal = "javascript:calendar('blRows["+index+"].invoiceDate','ddMMyyyy',true,24);"
		   // alert(cal);



		    newNode.getElementsByTagName("input")[2].value = "";
		    newNode.getElementsByTagName("input")[2].name = 'blRows['+index+'].blNo';
		    newNode.getElementsByTagName("input")[2].id = 'blRows['+index+'].blNo';

		    newNode.getElementsByTagName("input")[3].value = "";
		    newNode.getElementsByTagName("input")[3].name = 'blRows['+index+'].blDate';
		    newNode.getElementsByTagName("input")[3].id = 'blRows['+index+'].blDate';

		    newNode.getElementsByTagName("input")[4].value = "";
		    newNode.getElementsByTagName("input")[4].name = 'blRows['+index+'].blNetQty';
		    newNode.getElementsByTagName("input")[4].id = 'blRows['+index+'].blNetQty';

		    newNode.getElementsByTagName("input")[5].value = "";
		    newNode.getElementsByTagName("input")[5].name = 'blRows['+index+'].blGrossQty';
		    newNode.getElementsByTagName("input")[5].id = 'blRows['+index+'].blGrossQty';

		    newNode.getElementsByTagName("select")[0].value = "";
		    newNode.getElementsByTagName("select")[0].name = 'blRows['+index+'].blUom';
		    newNode.getElementsByTagName("select")[0].id = 'blRows['+index+'].blUom';

		    //
		    newNode.getElementsByTagName("a")[0].href = cal;
		    newNode.getElementsByTagName("a")[1].href = "javascript:calendar('blRows["+index+"].blDate','ddMMyyyy',true,24);";

		   /* var text = '<a href="#" onclick="ReceiptController.delBeRow(\'' + 'manageAddBlTab' + '\', this.parentNode.parentNode.rowIndex);">CANCEL</a>';
		    var element = document.createElement('p');              //this creates an empty node of the type specified
		    element.appendChild(document.createTextNode(text));     //this creates a new text node and inserts it into our empty node
		           //this sets the style in inline CSS (warning, this needs different syntax in IE)
		    newNode.appendChild(element);*/

		    referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
	},

	addDuplicateRowForUpdateBl : function(){

	//	tbody=document.getElementById(manageAddBlTab);
//	    var index = tbody.rows.length - 2;
		//var index = tbody.rows.length;
		//if (index<0) index=0;
			var referenceNodes = document.getElementById("manageAddBlTab").getElementsByTagName("tr");
		 	//var referenceNode = referenceNodes[referenceNodes.length - 3];
			var referenceNode = referenceNodes[1];
			var i = referenceNodes.length-3;

		    var newNode = referenceNode.cloneNode(true);
		    newNode.removeAttribute("style");
		    var index = referenceNodes.length-4;

		    newNode.getElementsByTagName("input")[0].name = 'blGroupUpdate['+index+'].invoiceNo';
		    newNode.getElementsByTagName("input")[0].id = 'blGroupUpdate['+index+'].invoiceNo';

		    newNode.getElementsByTagName("input")[1].name = 'blGroupUpdate['+index+'].invoiceDate';
		    newNode.getElementsByTagName("input")[1].id = 'blGroupUpdate['+index+'].invoiceDate';

		    newNode.getElementsByTagName("input")[2].name = 'blGroupUpdate['+index+'].blNo';
		    newNode.getElementsByTagName("input")[2].id = 'blGroupUpdate['+index+'].blNo';

		    newNode.getElementsByTagName("input")[3].name = 'blGroupUpdate['+index+'].blDate';
		    newNode.getElementsByTagName("input")[3].id = 'blGroupUpdate['+index+'].blDate';

		    newNode.getElementsByTagName("input")[4].name = 'blGroupUpdate['+index+'].blNetQty';
		    newNode.getElementsByTagName("input")[4].id = 'blGroupUpdate['+index+'].blNetQty';

		    newNode.getElementsByTagName("input")[5].name = 'blGroupUpdate['+index+'].blGrossQty';
		    newNode.getElementsByTagName("input")[5].id = 'blGroupUpdate['+index+'].blGrossQty';

		    newNode.getElementsByTagName("select")[0].name = 'blGroupUpdate['+index+'].blUom';
		    newNode.getElementsByTagName("select")[0].id = 'blGroupUpdate['+index+'].blUom';

		    newNode.getElementsByTagName("a")[0].href = "javascript:calendar('blGroupUpdate["+index+"].invoiceDate','ddMMyyyy',true,24);";;
		    newNode.getElementsByTagName("a")[1].href = "javascript:calendar('blGroupUpdate["+index+"].blDate','ddMMyyyy',true,24);";

		    referenceNode.parentNode.insertBefore(newNode, referenceNodes[i].nextSibling);
	},

	cancelRow : function(rowObject) {
		//alert('cancel');
		var myNode = rowObject.parentNode;
		//if(null!=rowObject){
		//alert('not null');
		//}else{
		//	alert('null');
		//}

		var parentNodeRow = myNode.parentNode;
		var parentTable = parentNodeRow.parentNode;

		parentTable.removeChild(parentNodeRow);

	},





	calculateRejectedItem : function(counterIndex){
		var quantityAdviced = +$("input:text[name='docItemList["+counterIndex+"].quantityAdviced']").val();
		var quantityReceived = +$("input:text[name='docItemList["+counterIndex+"].quantityReceived']").val();
		var quantityAccepted = +$("input:text[name='docItemList["+counterIndex+"].quantityAccepted']").val();
		var quantityRejected = quantityReceived-quantityAccepted;
		if(quantityAccepted > quantityReceived || quantityRejected<0){
			alert("Accepted Item Quantity must be lesser than Received Item Quantity");
			return;
		}
/*		if(quantityReceived > quantityAdviced){
			alert("Received Item Quantity must be lesser than Adviced Item Quantity");
			return;
		}*/
		$("input:text[name='docItemList["+counterIndex+"].quantityRejected']").val(quantityRejected);
	},
	
	displayAcceptedItemDetail : function(counter){
		
		var quantityChallan = $("input:text[name='docItemList["+counter+"].quantityReceived']").val();
		var poBalance = $("input:text[name='docItemList["+counter+"].poBalance']").val();
		var poBal = parseFloat(poBalance);
		var poChallan = parseFloat(quantityChallan);
		var quantityShort = $("input:text[name='docItemList["+counter+"].quantityShort']").val();
		var quantityExcess = $("input:text[name='docItemList["+counter+"].quantityExcess']").val();
		var quantityDamage = $("input:text[name='docItemList["+counter+"].quantityDamage']").val();
		var quantityRejected = $("input:text[name='docItemList["+counter+"].quantityRejected']").val();
		
		if(parseFloat(poBal)<=0)
		{
			alert("PO Balance is less than Zero you can't create GRN.");
			return;
		}
		else if(parseFloat(poChallan)<0)
		{
			alert("CHALLAN QTY must be positive");
			return;
		}
		else if(parseFloat(quantityDamage) > parseFloat(quantityChallan)){
			alert("DAMAGE QTY must be lesser than CHALLAN QTY ");
			return;
		}
		else if(parseFloat(quantityRejected) > parseFloat(quantityChallan)){
			alert("REJECTED QTY must be lesser than CHALLAN QTY ");
			return;
		}
		else if(parseFloat(quantityChallan) > parseFloat(poBalance)){
			alert("CHALLAN QTY must be lesser than PO BALANCE ");
			return;
		}
		else if(parseFloat(quantityShort) > parseFloat(quantityChallan)){
			alert("SHORT QTY must be lesser than CHALLAN QTY ");
			return;
		}
		else if(parseFloat(quantityExcess) > parseFloat(quantityChallan)){
			alert("EXCESS QTY must be lesser than CHALLAN QTY ");
			return;
		}
		else if(parseFloat(quantityShort) > 0 && parseFloat(quantityExcess) > 0)
		{
			alert("Either Short Qty Or Excess Qty");
			return;
		}
		var totalAccepted = parseFloat(quantityChallan)-parseFloat(quantityShort)+parseFloat(quantityExcess)-parseFloat(quantityDamage)-parseFloat(quantityRejected);
		if(parseFloat(totalAccepted)<0)
		{
			totalAccepted=0;
		}
		$("input:text[name='docItemList["+counter+"].quantityAccepted']").val(parseFloat(totalAccepted));
	},
	showAcceptedItemDetails : function(counter){
		//var abc = $("_div_"+counter).css('display');
		var abc = document.getElementById("_div_"+counter).style;
		if(abc.display == 'none'){
			document.getElementById("_div_"+counter).style.display="block";
			$("#_accept_item_"+counter).html("Click to minimize");
		}
		else{
			var quantityAccepted = $("input:text[name='docItemList["+counter+"].quantityAccepted']").val();
			var quantityFresh = $("input:text[name='docItemList["+counter+"].quantityFresh']").val();
			var quantityReplaced = $("input:text[name='docItemList["+counter+"].quantityReplaced']").val();
			var totalAccepted = quantityFresh + quantityReplaced;
/*			if(totalAccepted > quantityAccepted){
				alert("Accepted Item Quantity must be equal to Fresh and Replaced Item Quantity");
				return;
			}
*/			document.getElementById("_div_"+counter).style.display="none";
			$("#_accept_item_"+counter).html("Details");
		}
	},
	hideAcceptedItemDetails : function(counter){
		document.getElementById("_div_"+counter).style.display="none";
		$("#_accept_item_"+counter).html("Details");
	},
	fetchAttribute : function (receiptItemId,csrfToken,srlNo,itemCode,itemQuantityUnit,quantity,description)	{
		var receiptItem = {
				"currItem.id" : receiptItemId
			};
		document.receiptItemAddForm.buttonValue.value = 'attr';
		document.receiptItemAddForm.srlNo.value = srlNo;
		document.receiptItemAddForm.itemCode.value = itemCode;
		document.receiptItemAddForm.itemQuantityUnit.value = itemQuantityUnit;
		document.receiptItemAddForm.itemQuantity.value = quantity;
		document.receiptItemAddForm.itemDescription.value = description;
		Controller.onSubmit('receiptItemAddForm',receiptItem,'saveDocItemList','attr',null);
	},
	editMaterialIssueRow: function (materialId)
	{
		document.materialIssueViewForm.materialId.value = materialId;
		Controller.onSubmit('materialIssueViewForm',pageScope['blGroup'],'addMaterialIssue','edit');
	},

	submitReceipt : function(){
		if ( confirm("Once Activated, the RECEIPT details can not be changed. Do you want to activate?") ){
		Controller.onSubmitWithCsrf("receiptAddForm",'<csrf:token-name/>=<csrf:token-value/>',"submitDoc",null,null);
		}
	},
	getAttachments : function(formName){
		window.open('','Receipt_Attachments', 'top=150, left=110, height=500, width=1000, toolbar=no, status=no ,scrollbars=1,resizable=1');
		//window.open('','Receipt_Attachments', '');
     	//document.receiptAttachmentsForm.target="Receipt_Attachments";
       	//document.receiptAttachmentsForm.submit();
		eval("document."+formName).target="Receipt_Attachments";
		eval("document."+formName).submit();
	},
	deleteReceipt : function (formName) {
		if ( confirm("Once Cancelled, the RECEIPT details will be removed from EPS. Do you want to cancel ?") ){
			Controller.onSubmitWithCsrf("deleteReceiptForm",'<csrf:token-name/>=<csrf:token-value/>',"deleteReceipt",null,null);
		}
	},
	addBlId : function(blId){
		document.getElementById('blId').value=blId;
	},

	addBeId : function(beId){
		document.getElementById('beId').value=beId;
	},


	validateRadioSelection : function (selectedField, message){
		if(null == selectedField || selectedField == '')
		{
			alert(message);
			return false;
		}
	},
	getLineDescription : function(line,index)
	{
		var value=document.getElementsByName("order.docItemList["+index+"].selected");
		var $boxes = $('input[name="order.docItemList['+index+'].selected"]:checked');
		alert($boxes);

		$boxes.each(function (){
			alert(line);
		});
		//document.receiptAddForm.orderItemLine.value = document.receiptAddForm.orderItemLine.value+"#"+line;

		//alert(document.receiptAddForm.orderItemLine.value);
	},
	validateRadioSelection : function (selectedField, message){
		if(null == selectedField || selectedField == '')
		{
			alert(message);
			return false;
		}
		return true;
	},
	changeRow : function (){
		alert("in ch row");
		var trLength= $("#selectionTable tr").length;
		 var i=trLength-1;

		var numberRowLength=$("input[name='maxNumber']").val();
		var value = $("input[name='maxNumber']").val().replace(/^\s\s*/, '').replace(/\s\s*$/, '');
		var intRegex = /^\d+$/;
		if(!intRegex.test(value)) {
			 alert("Field must be numeric");
			 return false;
			  }
		if(parseInt(numberRowLength,10)>=parseInt(trLength,10)){
			while(parseInt(numberRowLength,10)>parseInt(i,10)){
				 $("#selectionTable tr:last").clone().find("select").attr("name","docApprovalUserMap["+i+"]").attr("value","0").end().appendTo("#selectionTable");
				 $("#selectionTable tr:last").find($(".counterClass")).html(i+1);
				 		 i++;
				 		  $("#selectionTable tr:last").find($(".ui-combobox")).html("");
				 		 }
			 }else{
			 	while(parseInt(numberRowLength,10)<parseInt(i,10)){
			 		$("#selectionTable tr:last").remove();
			 		i--;
			 	}
			 }
			 $( ".combobox" ).combobox();
		},
		saveApprovers : function (formId,token,methodName){


		  	Controller.onSubmitWithCsrf(formId,token,methodName,null,null);
		},
addBlRow: function (/* String */ tableId,sUrl) {
		tbody=document.getElementById(tableId);
//				    var index = tbody.rows.length - 2;
	    var index = tbody.rows.length;
	    if (index<0) index=0;
	    if (!ReceiptController.validateAddBlRow(index,sUrl)) return;
	    var newRow=tbody.insertRow(tbody.rows.length);
	    var cell0 = newRow.insertCell(0);
	    cell0.setAttribute('class','dataClass');
	    cell0.setAttribute('align','left');
	    cell0.setAttribute('width','25%');
	    cell0.innerHTML = '<input type="text" size="20" maxlength="50" name="blRows['+index+'].invoiceNo"/>';

	    var cell1 = newRow.insertCell(1);
	  	cell1.setAttribute('class','dataClass');
	  	cell1.setAttribute('align','left');
	  	cell1.setAttribute('width','33%');
	  	cell1.innerHTML = '<input type="text" size="22" maxlength="99" readonly="true" id="blRows['+index+'].invoiceDate" name="blRows['+index+'].invoiceDate"/>&nbsp;<a href="javascript:calendar(\'blRows['+index+'].invoiceDate\',\'ddMMyyyy\',true,24);"><img src="' + contextRoot + '/image/Calendar.gif" border="0" /></a>';

	  	var cell2 = newRow.insertCell(2);
	    cell2.setAttribute('class','dataClass');
	    cell2.setAttribute('align','left');
	    cell2.setAttribute('width','20%');
	    cell2.innerHTML = '<input type="text" size="20" maxlength="50" name="blRows['+index+'].blNo" id="blRows['+index+'].blNo" />';


	    var cell3 = newRow.insertCell(3);
	  	cell3.setAttribute('class','dataClass');
	  	cell3.setAttribute('align','left');
	  	cell3.setAttribute('width','25%');
	  	cell3.innerHTML = '<input type="text" size="22" maxlength="99" readonly="true" id="blRows['+index+'].blDate" name="blRows['+index+'].blDate"/>&nbsp;<a href="javascript:calendar(\'blRows['+index+'].blDate\',\'ddMMyyyy\',true,24);"><img src="' + contextRoot + '/image/Calendar.gif" border="0" /></a>';

	  	var cell4 = newRow.insertCell(4);
	    cell4.setAttribute('class','dataClass');
	    cell4.setAttribute('align','left');
	    cell4.setAttribute('width','25%');
	    cell4.innerHTML = '<input type="text" size="20" maxlength="5" name="blRows['+index+'].blQuantity"/>';


	  	var cell5 = newRow.insertCell(5);
	  	cell5.setAttribute('width','20%');
	  	cell5.innerHTML='<a href="#" onclick="ReceiptController.delBlRow(\'' + tableId + '\', this.parentNode.parentNode.rowIndex);">CANCEL</a>';

	  	var cell6 = newRow.insertCell(6);
	  	cell6.setAttribute('width','20%');


	},
	validateNullBlRow : function(tableId)
	{

		tbody=document.getElementById(tableId);
		var index = tbody.rows.length;
		numOfRows = index - 3;
		if(numOfRows > 0 ){
		    for(rowNum = 1; rowNum <= numOfRows; rowNum++) {
		    	var sUrl="";
		    	if (!ReceiptController.validateAddBlRow(rowNum,sUrl)) return;
		    }
			Controller.onSubmit('addBlRowsForm',pageScope['blRows'],'saveBlRowsForOrderId','dummy');
		}
		else
			{
				alert("Please add a BL row.");
				return;
			}
	},
	validateAddBlRow : function (/*int*/ index,sUrl) {

	    if (index>0) {
	    	var lastinvoiceNo = document.getElementById("blRows["+(index-1)+"].invoiceNo");

		    if(null!=lastinvoiceNo) {

			    if((lastinvoiceNo.value=='') || (lastinvoiceNo.value==null)) {
			    	alert("Please specify the Invoice no for row " + index);
			    	return false;
			    }
			}
		    var lastinvoiceDate = document.getElementById("blRows["+(index-1)+"].invoiceDate");
		    if(null!=lastinvoiceDate) {
			    if((lastinvoiceDate.value=='') || (lastinvoiceDate.value==null)) {
			    	alert("Please specify the Invoice date for row " + index);
			    	return false;
			    }
			}
		    var lastBlNo = document.getElementById("blRows["+(index-1)+"].blNo");
		    if(null!=lastBlNo) {
			    if((lastBlNo.value=='') || (lastBlNo.value==null)) {
			    	alert("Please specify the Bl no for row " + index);
			    	return false;
			    }


			}
		    var lastBlDate = document.getElementById("blRows["+(index-1)+"].blDate");
		    if(null!=lastBlDate) {
			    if((lastBlDate.value=='') || (lastBlDate.value==null)) {
			    	alert("Please specify the Bl date for row " + index);
			    	return false;
			    }
			}
		    var lastBlNetQuantity = document.getElementById("blRows["+(index-1)+"].blNetQty");
		    if(null!=lastBlNetQuantity) {
			    if((lastBlNetQuantity.value=='') || (lastBlNetQuantity.value==null)) {
			    	alert("Please specify the Bl net quantity for row " + index);
			    	return false;
			    }

			   if(!$.isNumeric(lastBlNetQuantity.value))
			    {
			    	alert("Please enter a numeric Bl net quantity for row " + index);
			    	return false;
			    }
			}

		    var lastBlGrossQuantity = document.getElementById("blRows["+(index-1)+"].blGrossQty");
		    if(null!=lastBlGrossQuantity) {
			    if((lastBlGrossQuantity.value=='') || (lastBlGrossQuantity.value==null)) {
			    	alert("Please specify the Bl gross quantity for row " + index);
			    	return false;
			    }

			   if(!$.isNumeric(lastBlGrossQuantity.value))
			    {
			    	alert("Please enter a numeric Bl gross quantity for row " + index);
			    	return false;
			    }
			}

		    var lastBlOUM = document.getElementById("blRows["+(index-1)+"].blUom");
		    if(null!=lastBlOUM) {
			    if(lastBlOUM.value==0) {
			    	alert("Please select OUM for row " + index);
			    	return false;
			    }
		    }
	    }
	    return true;
	},
	saveBLFromUpdate : function(tableId, action , csrfToken)
	{

		tbody=document.getElementById(tableId);
		var index = tbody.rows.length;
		numOfRows = index - 4;

		if(numOfRows > 0 ){
		    for(rowNum = 1; rowNum <= numOfRows; rowNum++) {
		    	var sUrl="";
		    	if (!ReceiptController.validateUpdateBlRow(rowNum,sUrl)) return;
		    }
		    if(action == "save") {
				Controller.onSubmit('updateBlGroupForm',pageScope['blGroup'],'updateBlGroup','save');
			} else if (action == "submit") {
				Controller.onSubmitWithCsrf('updateBlGroupForm',csrfToken,'submitBlDoc',null,null);
			} else if (action == "assignApprovers") {
				Controller.onSubmitWithCsrf('updateBlGroupForm',csrfToken,'updateBlGroup','saveBlRowsAndAssignApprover',null);
			}
		}
		else
			{
				alert("Please add a BL row.");
				return;
			}
	},
	validateUpdateBlRow : function (/*int*/ index,sUrl) {

	    if (index>0) {
	    	var lastinvoiceNo = document.getElementById("blGroupUpdate["+(index-1)+"].invoiceNo");

		    if(null!=lastinvoiceNo) {

			    if((lastinvoiceNo.value=='') || (lastinvoiceNo.value==null)) {
			    	alert("Please specify the Invoice no for row " + index);
			    	return false;
			    }
			}
		    var lastinvoiceDate = document.getElementById("blGroupUpdate["+(index-1)+"].invoiceDate");
		    if(null!=lastinvoiceDate) {
			    if((lastinvoiceDate.value=='') || (lastinvoiceDate.value==null)) {
			    	alert("Please specify the Invoice date for row " + index);
			    	return false;
			    }
			}
		    var lastBlNo = document.getElementById("blGroupUpdate["+(index-1)+"].blNo");
		    if(null!=lastBlNo) {
			    if((lastBlNo.value=='') || (lastBlNo.value==null)) {
			    	alert("Please specify the Bl no for row " + index);
			    	return false;
			    }


			}
		    var lastBlDate = document.getElementById("blGroupUpdate["+(index-1)+"].blDate");
		    if(null!=lastBlDate) {
			    if((lastBlDate.value=='') || (lastBlDate.value==null)) {
			    	alert("Please specify the Bl date for row " + index);
			    	return false;
			    }
			}
		    var lastBlNetQuantity = document.getElementById("blGroupUpdate["+(index-1)+"].blNetQty");
		    if(null!=lastBlNetQuantity) {
			    if((lastBlNetQuantity.value=='') || (lastBlNetQuantity.value==null)) {
			    	alert("Please specify the Bl net quantity for row " + index);
			    	return false;
			    }

			   if(!$.isNumeric(lastBlNetQuantity.value))
			    {
			    	alert("Please enter a numeric Bl net quantity for row " + index);
			    	return false;
			    }
			}

		    var lastBlGrossQuantity = document.getElementById("blGroupUpdate["+(index-1)+"].blGrossQty");
		    if(null!=lastBlGrossQuantity) {
			    if((lastBlGrossQuantity.value=='') || (lastBlGrossQuantity.value==null)) {
			    	alert("Please specify the Bl gross quantity for row " + index);
			    	return false;
			    }

			   if(!$.isNumeric(lastBlGrossQuantity.value))
			    {
			    	alert("Please enter a numeric Bl gross quantity for row " + index);
			    	return false;
			    }
			}

		    var lastBlOUM = document.getElementById("blGroupUpdate["+(index-1)+"].blUom");
		    if(null!=lastBlOUM) {
			    if(lastBlOUM.value==0) {
			    	alert("Please select UOM for row " + index);
			    	return false;
			    }
		    }
	    }
	    return true;
	},

	getAutoBlNo:function(index,sUrl)
	{
		alert("in autoblno");
		$(function(){
		    $("#blRows['"+index+"'].blNo").autocomplete({

			source:function( request, response ) {

					if(request.term.length<2)	return;
					var url=sUrl+"&term="+request.term;
					//alert(url);
					Controller.loadData(url,null,
				    		function( data) {
				    		alert("a2 : "+data.json);
				    		availableTags=data.json;
				    		if (data["_errors"]!=null) {
				    			Util.showMessage(data);
				    			return;
				    		}

				    		response( $.grep( availableTags, function( item ){
				    			if(item=="false")
				    				{
				    				alert("Bl number already exists. Please enter a different number.");
									return item ;
				    				}


							}) );
					});

				}

		    });
		});
	},

	delBlRow :function(/*String*/ tableId, /*int*/ index) {
		tbody = document.getElementById(tableId);
	  	if (confirm('Cancel the Bl row?')) tbody.deleteRow(index);
	},


	addBeRow: function (/* String */ tableId,serverTimeFromDB) {
		tbody=document.getElementById(tableId);
//				    var index = tbody.rows.length - 2;
	    var index = tbody.rows.length;
	    if (index<0) index=0;
	    if (!ReceiptController.validateAddBeRow(index)) return;
	    var newRow=tbody.insertRow(tbody.rows.length);
	    var cell0 = newRow.insertCell(0);
	    cell0.setAttribute('class','dataClass');
	    cell0.setAttribute('align','left');
	    cell0.setAttribute('width','25%');
	    cell0.innerHTML = '';

	    var cell1 = newRow.insertCell(1);
	  	cell1.setAttribute('class','dataClass');
	  	cell1.setAttribute('align','left');
	  	cell1.setAttribute('width','31%');
	  	cell1.innerHTML = '<input type="text" size="22" id="beRows['+index+'].beNo" maxlength="50" name="beRows['+index+'].beNo"/>';

	  	var cell2 = newRow.insertCell(2);
	    cell2.setAttribute('class','dataClass');
	    cell2.setAttribute('align','left');
	    cell2.setAttribute('width','18%');
	    cell2.innerHTML = '<input type="text" size="22" maxlength="99" readonly="true" id="beRows['+index+'].beDate" name="beRows['+index+'].beDate"/>&nbsp;<a href="javascript:calendar(\'beRows['+index+'].beDate\',\'ddMMyyyy\',true,24);"><img src="' + contextRoot + '/image/Calendar.gif" border="0" /></a>'
	    					+'&emsp;&emsp; <a href="#" onclick="ReceiptController.delBeRow(\'' + tableId + '\', this.parentNode.parentNode.rowIndex);">CANCEL</a>';
	    var cell3 = newRow.insertCell(3);
	  	cell3.setAttribute('class','dataClass');
	  	cell3.setAttribute('align','left');
	  	cell3.setAttribute('width','30%');
	  	cell3.innerHTML = '';

	  	var cell4 = newRow.insertCell(4);
	    cell4.setAttribute('class','dataClass');
	    cell4.setAttribute('align','left');
	    cell4.setAttribute('width','30%');
	    cell4.innerHTML = '';


	  	var cell5 = newRow.insertCell(5);
	  	cell5.setAttribute('width','20%');
	  	cell5.innerHTML='';

	  	var cell6 = newRow.insertCell(6);
	  	cell6.setAttribute('width','20%');
	},
	validateNullBeRow : function(tableId)
	{

		var tbody=document.getElementById(tableId);
		var index = tbody.rows.length;
		numOfRows = index - 2;

		if(numOfRows > 0 ){
		    for(rowNum = 1; rowNum <= numOfRows; rowNum++) {
		    	if (!ReceiptController.validateAddBeRow(rowNum)) return;
		    }
			Controller.onSubmit('addBeRowsForm',pageScope['beRows'],'saveBeRowsForBlNo','dummy');
		}
		else
			{
				alert("Please add a BE row.");
				return;
			}
	},
	validateAddBeRow : function (/*int*/ index) {
		var maxSize = 5 ;

	    if (index>0) {
	    	var lastBeNo = document.getElementById("beRows["+(index-1)+"].beNo");

		    if(null!=lastBeNo) {

			    if((lastBeNo.value=='') || (lastBeNo.value==null)) {
			    	alert("Please specify the BE no for row " + index);
			    	return false;
			    }
			}
		    var lastBeDate = document.getElementById("beRows["+(index-1)+"].beDate");
		    if(null!=lastBeDate) {
			    if((lastBeDate.value=='') || (lastBeDate.value==null)) {
			    	alert("Please specify the BE date for row " + index);
			    	return false;
			    }
			}

	    	var lastBeNetQty = document.getElementById("beRows["+(index-1)+"].beNetQty");

		    if(null!=lastBeNetQty) {

			    if((lastBeNetQty.value=='') || (lastBeNetQty.value==null)) {
			    	alert("Please specify the net quantity for row " + index);
			    	return false;
			    }
				if(!$.isNumeric(lastBeNetQty.value)) {
				    alert("Please enter a numeric net quantity for row " + index);
				    return false;
				}
			}

	    	var lastBeGrossQty = document.getElementById("beRows["+(index-1)+"].beGrossQty");

		    if(null!=lastBeGrossQty) {

			    if((lastBeGrossQty.value=='') || (lastBeGrossQty.value==null)) {
			    	alert("Please specify the gross quantity for row " + index);
			    	return false;
			    }
				if(!$.isNumeric(lastBeGrossQty.value)) {
				    alert("Please enter a numeric gross quantity for row " + index);
				    return false;
				}
			}

	    	var lastBeOum = document.getElementById("beRows["+(index-1)+"].beUom");

		    if(null!=lastBeOum) {

			    if((lastBeOum.value==0)) {
			    	alert("Please specify the OUM for row " + index);
			    	return false;
			    }
			}

	    	var lastBePlantLocation = document.getElementById("beRows["+(index-1)+"].bePlantLocation");

		    if(null!=lastBePlantLocation) {

			    if((lastBePlantLocation.value==0)) {
			    	alert("Please specify the Plant Location for row " + index);
			    	return false;
			    }
			}
	    }
	    return true;
	},
	delBeRow :function(/*String*/ tableId, /*int*/ index) {
		tbody = document.getElementById(tableId);
	  	if (confirm('Cancel the BE row?')) tbody.deleteRow(index);
	},

	addBeRowInUpdate: function (/* String */ tableId,/* int */ cIndex) {
		tbody=document.getElementById(tableId);
//				    var index = tbody.rows.length - 2;
		 var index = cIndex+tbody.rows.length+1;
		 var addIndex=10000+index;
	    if (!ReceiptController.validateAddBeRowInUpdate(index)) return;
	    var newRow=tbody.insertRow(tbody.rows.length);
	    var cell0 = newRow.insertCell(0);
	    cell0.setAttribute('class','dataClass');
	    cell0.setAttribute('align','left');
	    cell0.setAttribute('width','25%');
	    cell0.innerHTML = '<input type="hidden" name="beGroupUpdate['+index+'].beId" value="'+addIndex+'"/>';

	    var cell1 = newRow.insertCell(1);
	  	cell1.setAttribute('class','dataClass');
	  	cell1.setAttribute('align','left');
	  	cell1.setAttribute('width','31%');
	  	cell1.innerHTML = '<input type="text" size="22" id="beGroupUpdate['+index+'].beNo" maxlength="50" name="beGroupUpdate['+index+'].beNo"/>';

	  	var cell2 = newRow.insertCell(2);
	    cell2.setAttribute('class','dataClass');
	    cell2.setAttribute('align','left');
	    cell2.setAttribute('width','18%');
	    cell2.innerHTML = '<input type="text" size="22" maxlength="99" readonly="true" id="beGroupUpdate['+index+'].beDate" name="beGroupUpdate['+index+'].beDate"/>&nbsp;<a href="javascript:calendar(\'beGroupUpdate['+index+'].beDate\',\'ddMMyyyy\',true,24);"><img src="' + contextRoot + '/image/Calendar.gif" border="0" /></a>'
	    					+'&emsp;&emsp; <a href="#" onclick="ReceiptController.delBeRowInUpdate(\'' + tableId + '\', this.parentNode.parentNode.rowIndex);">CANCEL</a>';
	    var cell3 = newRow.insertCell(3);
	  	cell3.setAttribute('class','dataClass');
	  	cell3.setAttribute('align','left');
	  	cell3.setAttribute('width','30%');
	  	cell3.innerHTML = '';

	  	var cell4 = newRow.insertCell(4);
	    cell4.setAttribute('class','dataClass');
	    cell4.setAttribute('align','left');
	    cell4.setAttribute('width','30%');
	    cell4.innerHTML = '';


	  	var cell5 = newRow.insertCell(5);
	  	cell5.setAttribute('width','20%');
	  	cell5.innerHTML='';

	  	var cell6 = newRow.insertCell(6);
	  	cell6.setAttribute('width','20%');
	},

	validateAddBeRowInUpdate : function (/*int*/ index) {
		var maxSize = 5 ; /*<c:out value="${_maxRFQAttachSize}"/>;*/
	    /*if(index == maxSize)
	    {
	    	alert("Maximum "+maxSize+" Bl rows can be added");
	    	return false;
	    }*/
	    if (index>0) {
	    	var lastBeNo = document.getElementById("beGroupUpdate["+(index-1)+"].beNo");

	    	//alert(lastinvoiceNo+":::in validateaddBlGroupRowInUpdate after index:::"+(index-1));

		    if(null!=lastBeNo) {

		    	//alert("in validateaddBlGroupRowInUpdate after null check:::"+lastinvoiceNo);
			    if((lastBeNo.value=='') || (lastBeNo.value==null)) {
			    	alert("Please specify the BE no for previous row");
			    	return false;
			    }
			}
		    var lastBeDate = document.getElementById("beGroupUpdate["+(index-1)+"].beDate");
		    if(null!=lastBeDate) {
			    if((lastBeDate.value=='') || (lastBeDate.value==null)) {
			    	alert("Please specify the BE date for previous row");
			    	return false;
			    }
			}

	    }
	    return true;
	},
	delBeRowInUpdate :function(/*String*/ tableId, /*int*/ index) {
		tbody = document.getElementById(tableId);
	  	if (confirm('Cancel the BE row?')) tbody.deleteRow(index);
	},


	addBlGroupRowInUpdate: function (/* String */ tableId,/* int */ cIndex) {
		tbody=document.getElementById(tableId);
//				    var index = tbody.rows.length - 2;
	    var index = cIndex+tbody.rows.length+1;
	    var addIndex=10000+index;
	    /*if (index<0) index=0;
	    else */
	    //alert("index:::"+index);
	    if (!ReceiptController.validateaddBlGroupRowInUpdate(index)) return;
	    var newRow=tbody.insertRow(tbody.rows.length);
	    var cell0 = newRow.insertCell(0);
	    cell0.setAttribute('class','dataClass');
	    cell0.setAttribute('align','left');
	    cell0.setAttribute('width','25%');
	    cell0.innerHTML = '<input type="hidden" name="blGroupUpdate['+index+'].blId" value="'+addIndex+'"/><input type="text" size="20" maxlength="50" name="blGroupUpdate['+index+'].invoiceNo"/>';

	    var cell1 = newRow.insertCell(1);
	  	cell1.setAttribute('class','dataClass');
	  	cell1.setAttribute('align','left');
	  	cell1.setAttribute('width','24%');
	  	cell1.innerHTML = '<input type="text" size="22" maxlength="99" readonly="true" id="blGroupUpdate['+index+'].invoiceDate" name="blGroupUpdate['+index+'].invoiceDate"/>&nbsp;<a href="javascript:calendar(\'blGroupUpdate['+index+'].invoiceDate\',\'ddMMyyyy\',true,24);"><img src="' + contextRoot + '/image/Calendar.gif" border="0" /></a>';

	  	var cell2 = newRow.insertCell(2);
	    cell2.setAttribute('class','dataClass');
	    cell2.setAttribute('align','left');
	    cell2.setAttribute('width','16%');
	    cell2.innerHTML = '<input type="text" size="20" maxlength="50" name="blGroupUpdate['+index+'].blNo"/>';

	    var cell3 = newRow.insertCell(3);
	  	cell3.setAttribute('class','dataClass');
	  	cell3.setAttribute('align','left');
	  	cell3.setAttribute('width','24%');
	  	cell3.innerHTML = '<input type="text" size="22" maxlength="99" readonly="true" id="blGroupUpdate['+index+'].blDate" name="blGroupUpdate['+index+'].blDate"/>&nbsp;<a href="javascript:calendar(\'blGroupUpdate['+index+'].blDate\',\'ddMMyyyy\',true,24);"><img src="' + contextRoot + '/image/Calendar.gif" border="0" /></a>';

	  	var cell4 = newRow.insertCell(4);
	    cell4.setAttribute('class','dataClass');
	    cell4.setAttribute('align','left');
	    cell4.setAttribute('width','20%');
	    cell4.innerHTML = '<input type="text" size="20" name="blGroupUpdate['+index+'].blQuantity"/>';


	  	var cell5 = newRow.insertCell(5);
	  	cell5.setAttribute('width','20%');
	  	cell5.innerHTML='<a href="#" onclick="ReceiptController.delBlGroupRowInUpdate(\'' + tableId + '\', this.parentNode.parentNode.rowIndex);">CANCEL</a>';

	  	var cell6 = newRow.insertCell(6);
	  	cell6.setAttribute('width','20%');
	},
	validateaddBlGroupRowInUpdate : function (/*int*/ index) {
		var maxSize = 5 ; /*<c:out value="${_maxRFQAttachSize}"/>;*/
	    /*if(index == maxSize)
	    {
	    	alert("Maximum "+maxSize+" Bl rows can be added");
	    	return false;
	    }*/
	    if (index>0) {

	    	var lastinvoiceNo = document.getElementById("blGroupUpdate["+(index-1)+"].invoiceNo");

		    if(null!=lastinvoiceNo) {
				//alert("in validateaddBlGroupRowInUpdate after null check");

			    if((lastinvoiceNo.value=='') || (lastinvoiceNo.value==null)) {
			    	alert("Please specify the Invoice no for previous row");
			    	return false;
			    }
			}
		    var lastinvoiceDate = document.getElementById("blGroupUpdate["+(index-1)+"].invoiceDate");
		    if(null!=lastinvoiceDate) {
			    if((lastinvoiceDate.value=='') || (lastinvoiceDate.value==null)) {
			    	alert("Please specify the Invoice date for previous row");
			    	return false;
			    }
			}
		    var lastBlNo = document.getElementById("blGroupUpdate["+(index-1)+"].blNo");
		    if(null!=lastBlNo) {
			    if((lastBlNo.value=='') || (lastBlNo.value==null)) {
			    	alert("Please specify the Bl no for previous row");
			    	return false;
			    }
			}
		    var lastBlDate = document.getElementById("blGroupUpdate["+(index-1)+"].blDate");
		    if(null!=lastBlDate) {
			    if((lastBlDate.value=='') || (lastBlDate.value==null)) {
			    	alert("Please specify the Bl date for previous row");
			    	return false;
			    }
			}
		    var lastBlQuantity = document.getElementById("blGroupUpdate["+(index-1)+"].blQuantity");
		    if(null!=lastBlQuantity) {
			    if((lastBlQuantity.value=='') || (lastBlQuantity.value==null)) {
			    	alert("Please specify the Bl quantity for previous row");
			    	return false;
			    }

			    if(!$.isNumeric(lastBlQuantity.value))
			    {
			    	alert("Please enter a numeric Bl quantity for previous row");
			    	return false;
			    }
			}
	    }
	    return true;
	},
	delBlGroupRowInUpdate :function(/*String*/ tableId, /*int*/ index) {
		tbody = document.getElementById(tableId);
	  	if (confirm('Cancel the Bl row?')) tbody.deleteRow(index);
	},

	addMaterialIssueDetails :function(/*String*/ tableId) {

		tbody=document.getElementById(tableId);
//	    var index = tbody.rows.length - 2;
		var index = tbody.rows.length+1;

		if (!ReceiptController.validateMaterialIssueRow(index)) return;
		var newRow=tbody.insertRow(tbody.rows.length);
		var cell0 = newRow.insertCell(0);
		cell0.setAttribute('class','dataClass');
		cell0.setAttribute('align','left');
		cell0.setAttribute('width','20%');
		cell0.innerHTML = '<input type="text" name="materialIssue['+index+'].code" maxlength="100"/>';

		var cell1 = newRow.insertCell(1);
		cell1.setAttribute('class','dataClass');
		cell1.setAttribute('align','left');
		cell1.innerHTML = '<textarea name="materialIssue['+index+'].description" rows="4" cols="50" id="mDescription['+index+']" onblur="javascript:ValidationUtil.checkLength(\'mDescription['+index+']\',50,10);"></textarea>';

		var cell2 = newRow.insertCell(2);
		cell2.setAttribute('class','dataClass');
		cell2.setAttribute('align','left');
		cell2.setAttribute('width','15%');
		cell2.innerHTML = '<input type="text" name="materialIssue['+index+'].issueQuantity" maxlength="5" />';

		var cell3 = newRow.insertCell(3);
		cell3.setAttribute('class','dataClass');
		cell3.setAttribute('align','left');
		cell3.innerHTML = '<input type="text" name="materialIssue['+index+'].issuedTo" maxlength="200" />';

		var cell4 = newRow.insertCell(4);
		cell4.setAttribute('class','dataClass');
		cell4.setAttribute('align','left');
		cell4.setAttribute('width','15%');
		cell4.innerHTML = '<input type="text" maxlength="99" readonly="true" id="materialIssue['+index+'].issueDatetime" name="materialIssue['+index+'].issueDatetime"/>&nbsp;<a href="javascript:calendar(\'materialIssue['+index+'].issueDatetime\',\'ddMMyyyy\',true,24);"><img src="' + contextRoot + '/image/Calendar.gif" border="0" /></a>';


		var cell5 = newRow.insertCell(5);
		cell5.setAttribute('class','dataClass');
		cell5.setAttribute('align','left');
		cell5.innerHTML='<input type="text" name="materialIssue['+index+'].issueSlipno" maxlength="100" />';

		var cell6 = newRow.insertCell(6);
	  	cell6.innerHTML='<a href="#" onclick="ReceiptController.delMaterialIssueRow(\'' + tableId + '\', this.parentNode.parentNode.rowIndex);">CANCEL</a>';

	},

	delMaterialIssueRow :function(/*String*/ tableId, /*int*/ index) {
		tbody = document.getElementById(tableId);
	  	if (confirm('Cancel the Material details row?')) tbody.deleteRow(index);
	},

	validateMaterialIssueRow : function (/*int*/ index) {
		var maxSize = 5 ;

	    if (index>0) {

	    	var code = document.getElementById("materialIssue["+(index-1)+"].code");
		    if(null!=code) {

			    if((code.value=='') || (code.value==null)) {
			    	alert("Please specify the Material code for previous row");
			    	return false;
			    }
			}
		    var description = document.getElementById("materialIssue["+(index-1)+"].description");
		    if(null!=description) {
			    if((description.value=='') || (description.value==null)) {
			    	alert("Please specify the Material description for previous row");
			    	return false;
			    }
			}
		    var issueQuantity = document.getElementById("materialIssue["+(index-1)+"].issueQuantity");
		    if(null!=issueQuantity) {
			    if((issueQuantity.value=='') || (issueQuantity.value==null)) {
			    	alert("Please specify the Issue Quantity for previous row");
			    	return false;
			    }
			    if(!$.isNumeric(issueQuantity.value))
			    {
			    	alert("Please enter a numeric Issue Quantity for previous row");
			    	return false;
			    }
			}
		    var issuedTo = document.getElementById("materialIssue["+(index-1)+"].issuedTo");
		    if(null!=issuedTo) {
			    if((issuedTo.value=='') || (issuedTo.value==null)) {
			    	alert("Please specify Issued To for previous row");
			    	return false;
			    }
			}
		    var issueDatetime = document.getElementById("materialIssue["+(index-1)+"].issueDatetime");
		    if(null!=issueDatetime) {
			    if((issueDatetime.value=='') || (issueDatetime.value==null)) {
			    	alert("Please specify the Issue Date for previous row");
			    	return false;
			    }

			}
		    var issueSlipno = document.getElementById("materialIssue["+(index-1)+"].issueSlipno");
		    if(null!=issueSlipno) {
			    if((issueSlipno.value=='') || (issueSlipno.value==null)) {
			    	alert("Please specify the Issue Slip Number for previous row");
			    	return false;
			    }

			}
	    }
	    return true;
	},

	validateSaveMaterialIssue : function(addTableId,prevTableId)
	{
		tbody1=document.getElementById(addTableId);
		var index1 = tbody1.rows.length+1;
	    if (index1<0) index1=0;
	    if (!ReceiptController.validateMaterialIssueRow(index1)) return;

	    tbody2=document.getElementById(prevTableId);
		var index2 = tbody2.rows.length/5;
	    if (index2<0) index2=0;
	    if (!ReceiptController.validateMaterialIssueRow(index2)) return;
	    Controller.onSubmit('materialIssueAddForm',pageScope['blGroup'],'addMaterialIssue','save');

	},

	getAutoMaterialSearch :function(id,sUrl)
	{

		$(function(){
		    $("#"+id).autocomplete({

				source:function( request, response ) {

					if(request.term.length<2)	return;
					var url=sUrl+"&term="+request.term;
					//alert(url);
					Controller.loadData(url,null,
				    		function( data) {

				    		availableTags=data.json;
				    		//alert("a2 : "+availableTags);
				    		if (data["_errors"]!=null) {
				    			Util.showMessage(data);
				    			return;
				    		}

				    		response( $.grep( availableTags, function( item ){
				    			//alert("item : "+item);
								return item ;
							}) );
					});

				}

		    });
		});
	},

	getOrderSearchResults :function()
	{
		var searchValue=document.getElementById("orderSearch").value;
		Controller.load('/business/receipt.handle?methodName=getOrderListBySearch&_documentId=103&request=1&code='+searchValue,null,null);

	},

	getBlSearchResultsUpdate :function(methodType)
	{
		var orderSearchValue=document.getElementById("orderSearch").value;
		var blSearchValue=document.getElementById("blSearch").value;

		Controller.load('/business/receipt.handle?methodName=getBlSearchResultsUpdate&_documentId=103&request=1&orderSearchValue='+orderSearchValue+'&blSearchValue='+blSearchValue+'&methodType='+methodType,null,null);

	},

	getBeSearchResultsUpdate :function(methodType)
	{
		var beSearchValue=document.getElementById("beSearch").value;
		var blSearchValue=document.getElementById("blSearch").value;

		Controller.load('/business/receipt.handle?methodName=getBeSearchResultsUpdate&_documentId=103&request=1&beSearchValue='+beSearchValue+'&blSearchValue='+blSearchValue+'&methodType='+methodType,null,null);

	},

	getMaterialSearchResults :function()
	{
		var mCodeSearchValue=document.getElementById("mCodeSearch").value;
		var issuedToSearchValue=document.getElementById("issuedToSearch").value;
		var issueDateSearchValue=document.getElementById("issueDateSearch").value;
		var issueSlNoSearchValue=document.getElementById("issueSlNoSearch").value;

		Controller.load('/business/receipt.handle?methodName=getMaterialSearchResults&_documentId=103&request=1&mCodeSearchValue='+mCodeSearchValue+'&issuedToSearchValue='+issuedToSearchValue
				+'&issueDateSearchValue='+issueDateSearchValue+'&issueSlNoSearchValue='+issueSlNoSearchValue,null,null);

	},

	getAutoOrderSearch :function(id,sUrl)
	{

		$(function(){
		    $("#"+id).autocomplete({

				source:function( request, response ) {

					if(request.term.length<2)	return;
					var url=sUrl+"&term="+request.term;
					//alert(url);
					Controller.loadData(url,null,
				    		function( data) {

				    		availableTags=data.json;
				    		//alert("a2 : "+availableTags);
				    		if (data["_errors"]!=null) {
				    			Util.showMessage(data);
				    			return;
				    		}

				    		response( $.grep( availableTags, function( item ){
				    			//alert("item : "+item);
								return item ;
							}) );
					});

				}

		    });
		});
	},

	getBlSearchResults :function()
	{
		var searchValue=document.getElementById("blSearch").value;
		Controller.load('/business/receipt.handle?methodName=getBlListBySearch&_documentId=103&request=1&code='+searchValue,null,null)

	},

	getOrderPageResults :function(pages,mType)
	{
		var pageValue=document.getElementById("goToPage").value;
		if(pageValue>pages || pageValue<1)
		{
			alert("Please enter a valid page number.");
		}
		else if(mType=="add")
		{
			Controller.load('/business/receipt.handle?methodName=getBlUserOrderList&_documentId=103&request='+pageValue,null,null);
		}
		else if(mType=="update")
		{
			Controller.load('/business/receipt.handle?methodName=getBlUserOrderListForUpdate&_documentId=103&request='+pageValue,null,null);
		}
		else if(mType=="view")
		{
			Controller.load('/business/receipt.handle?methodName=getBlUserOrderListForView&_documentId=103&request='+pageValue,null,null);
		}


	},

	getMaterialIssuePageResults :function(pages)
	{
		var pageValue=document.getElementById("goToPage").value;
		if(pageValue>pages || pageValue<1)
		{
			alert("Please enter a valid page number.");
		}
		else
		{
			Controller.load('/business/receipt.handle?methodName=addMaterialIssue&button=view&_documentId=103&request='+pageValue,null,null);
		}
	},

	getBlPageResults :function(pages,mType)
	{
		var pageValue=document.getElementById("goToPage").value;
		if(pageValue>pages || pageValue<1)
		{
			alert("Please enter a valid page number.");
		}
		else if(mType=="add")
		{
			Controller.load('/business/receipt.handle?methodName=getBlListForBeEntry&_documentId=103&request='+pageValue,null,null);
		}
		else if(mType=="update")
		{
			Controller.load('/business/receipt.handle?methodName=getBlListForBeUpdate&_documentId=103&request='+pageValue,null,null);
		}
		else if(mType=="view")
		{
			Controller.load('/business/receipt.handle?methodName=getBlListForBeView&_documentId=103&request='+pageValue,null,null);
		}


	},

	setBlPageRecordNo :function()
	{
		var noOfRecords=document.getElementById("rowNoSelect").value;

		Controller.load('/business/receipt.handle?methodName=getBlListForBeEntry&_documentId=103&request=1&noOfRecords='+noOfRecords,null,null);

	},

	getAutoBlSearch :function(sUrl)
	{

		$(function(){
		    $("#blSearch").autocomplete({

				source:function( request, response ) {

					if(request.term.length<2)	return;
					var url=sUrl+"&term="+request.term;
					//alert(url);
					Controller.loadData(url,null,
				    		function( data) {
				    		//alert("a2 : "+data.json);
				    		availableTags=data.json;
				    		if (data["_errors"]!=null) {
				    			Util.showMessage(data);
				    			return;
				    		}

				    		response( $.grep( availableTags, function( item ){
								return item ;
							}) );
					});

				}

		    });
		});
	},
	validateAmendReceipt : function (selectedField, message){
		if(null == selectedField || selectedField == '')
		{
			alert(message);
			return false;
		}
		var csrfToken = document.getElementById('csrfToken').value;
		var url = document.getElementById('url').value;
		var orderId = $("input[type=radio]:checked").val();
		var c = false;
        $.ajax({
                  "url": url,
                  "async": false,
                  "type": "POST",      
                  "data": { "methodName": "validateAmendreceipt", "OWASP_CSRFTOKEN": csrfToken,"data": orderId,"button":'VALIDATE'} ,                                                                
                  "success": function( data ) {
                        if(data.json.amendNo > 0){
                        	alert('Receipt Cannot be amended. Another receipt has been generated');
                        	c = false;
                        }
                        else
                        	c = true;
                  }
        });
		return c;
	},
	validateReceiptSelection :function (selectedField, message){
		if(null == selectedField || selectedField == '')
		{
			alert(message);
			return false;
		}
		$("#receiptValidation").hide();
		$("#radioReceipt").remove();
		$("#validatePo").remove();
		$("#validateChallan").remove();
		$("#validateDescription").remove();
		$("#validateComment").remove();
		var csrfToken = document.getElementById('csrfToken').value;
		var url = document.getElementById('url').value;
		var orderId = $("input[type=radio]:checked").val();
		var stat = false;
        $.ajax({
                  "url": url,
                  "async": false,
                  "type": "POST",      
                  "data": { "methodName": "validateDraftreceipt", "OWASP_CSRFTOKEN": csrfToken,"data": orderId,"button":'VALIDATE'} ,                                                                
                  "success": function( data ) {
                        if(data.json.count > 0){
                        	var receiptValue = data.json;
                        	$("#receiptValidation").show();
                        	var challanVal = "'"+ receiptValue.challan+"'";
                        	var radioBtn = $('<td id="radioReceipt"><input type="radio" name="receiptMgm" value="D" onclick="ReceiptController.selectDraftReceipt('+receiptValue.receiptId+','+challanVal+');" /><span style="color:red;">Continue With Existing Draft</span></td>');
                        	var po = $('<td id="validatePo" >'+receiptValue.receiptCode+'</td>');
                        	var challan = $('<td id="validateChallan"><span style="display:block;width:150px;overflow: hidden;white-space: nowrap;text-overflow: ellipsis;">'+receiptValue.challan+'</span></td>');
                        	var description = $('<td id="validateDescription"><span style="display:block;width:150px;overflow: hidden;white-space: nowrap;text-overflow: ellipsis;">'+receiptValue.description+'</span></td>');
                        	var comment = $('<td id="validateComment">Existing Draft Version</td>');
                        	po.appendTo('#draftV');
                        	challan.appendTo('#draftV');
                        	description.appendTo('#draftV');
                        	comment.appendTo('#draftV');
                        	radioBtn.appendTo('#draftV');
                        	stat = false;
                        }
                        else{
                        	stat = true;
                        }
                  }
        });
		return stat;
	},
	loadReceiptBpscl :function(csrfToken){
  		var receipt = pageScope["receipt"];
		if (null == receipt)
	    {
	    	alert("Please select a receipt");
	    	return ;
	    }
		/*var csrfToken = document.getElementById('csrfToken').value;
		var url = document.getElementById('url').value;
		var orderId = $("input[type=radio]:checked").val();
		var c = false;
        $.ajax({
                  "url": url,
                  "async": false,
                  "type": "POST",      
                  "data": { "methodName": "validateAmendreceipt", "OWASP_CSRFTOKEN": csrfToken,"data": orderId,"button":'VALIDATEDRAFT'} ,                                                                
                  "success": function( data ) {
                        if(data.json.amendNo > 0){
                        	alert('Receipt Cannot be amended. Another receipt has been generated');
                        	return ;
                        }
                        
                  }
        });*/
	    receipt.id = receipt["receipt.id"];
		Controller.loadPage(contextRoot+'/business/receipt.handle?methodName=getDoc&'+csrfToken,pageScope['receipt'],null);
	},
	/*deleteDraftReceipt :function(selectedField, message){
		if(null == selectedField || selectedField == '')
		{
			alert(message);
			return false;
		}
		var csrfTokenValue = document.getElementById('csrfToken').value;
		var url = document.getElementById('url').value;
		var orderId = $("input[type=radio]:checked").val();
		
		
        
                        		  $.ajax({
                                      "url": url,
                                      "async": false,
                                      "type": "POST",      
                                      "data": { "methodName": "validateDraftreceipt", "OWASP_CSRFTOKEN": csrfTokenValue,"data": orderId,"button":'DELETE'} ,
                                      "success": function( data ) {  
                                    	  
                                      }
                        		  		});
                        		  return true;
	},*/
	ValidateRadioButton :function(){
		$("#receiptValidation").hide();
		$("#radioReceipt").remove();
		$("#validatePo").remove();
		$("#validateChallan").remove();
		$("#validateDescription").remove();
	},
	receiptMgmSubmit :function(csrfToken,selectedItem,message){
		var button = $('input[name=receiptMgm]:checked').val();
		if(button=='D'){
			var receipt = pageScope["receipt"];
			if (null == receipt)
		    {
		    	alert("Please select a receipt");
		    	return ;
		    }
			else
				{
		    receipt.id = receipt["receipt.id"];
			Controller.loadPage(contextRoot+'/business/receipt.handle?methodName=getDoc&'+csrfToken,pageScope['receipt'],null);
				}
		}
		else if(button=='I'){
			var csrfTokenValue = document.getElementById('csrfToken').value;
			var url = document.getElementById('url').value;
			var orderId = $("input[type=radio]:checked").val();
	                        		  $.ajax({
	                                      "url": url,
	                                      "async": false,
	                                      "type": "POST",      
	                                      "data": { "methodName": "validateDraftreceipt", "OWASP_CSRFTOKEN": csrfTokenValue,"data": orderId,"button":'DELETE'} 
	                                      
	                        		  		});
	        Controller.loadPage(contextRoot+'/business/receipt.handle?methodName=getDoc&'+csrfToken,pageScope['selOrder'],null);               	                 		  
		}
	}
	
}
var attachmentController = {
	addAttachForRfqPrint : function (/*String*/ tableId){
	    tbody=document.getElementById(tableId);
	    var orgId= document.getElementById("hiddenOrgValue").value;
	    var isPrintWithRFQValue = document.getElementById("isPrintWithRFQValue").value;
	    var index = tbody.rows.length - 2;
	    if (index<0) index=0;
	    if (!attachmentController.validateAttach(index)) return;
	    index = index-1;
	    var newRow=tbody.insertRow(tbody.rows.length);
	    
	    var cell0 = newRow.insertCell(0);
	    cell0.setAttribute('class','dataClass');
	    cell0.innerHTML = '<input type="text" size="20" name="attachments['+index+'].label"/>';

	    var cell1 = newRow.insertCell(1);
	  	cell1.setAttribute('class','dataClass');
	  	cell1.innerHTML = '<input type="text" size="20" id="attachments['+index+'].fileName" name="attachments['+index+'].fileName" onblur="javascript:attachmentController.checkFileName('+index+')" /><input type="hidden" name="attachments['+index+'].digitalCert.signHash"/><label style="color :red ; float:left" id="msg['+index+'].fileName" name="msg['+index+'].fileName" ></label>';

	   	var cell2 = newRow.insertCell(2);
	  	cell2.setAttribute('class','dataClass');
	  	cell2.setAttribute('title','Allowable Extensions:'+$("input[name='fileExtension']").val());
	  	cell2.setAttribute('style','word-wrap:break-word');
	  	cell2.innerHTML = '<input type="file" size="20" name="attachments['+index+'].file" onmouseout="javascript:attachmentDetails('+index+');"/>';
	  	
	  	var cell3 = newRow.insertCell(3);
	  	cell3.innerHTML='<a class="pageContentLink" href="javascript:attachmentController.delAttach(attachTab,'+(index+1)+');">DELETE ROW</a>';
	  	
	  	if(isPrintWithRFQValue === 'true'){
	  		var cell4 = newRow.insertCell(4);
	  		cell4.innerHTML='<input type="checkbox" name="attachments['+index+'].isPrintWithRfq" id="attachments['+index+'].isPrintWithRfq" value="Y"/><input type="hidden" name="attachments['+index+'].attachementOrderPrintWithRfq" id="attachments['+index+'].attachementOrderPrintWithRfq" value="'+(index+1)+'"/>'+'<FONT COLOR\="RED"> <B>(Only PDF File)</B></FONT>';
	  	}
	},
	addAttach : function (/*String*/ tableId)
	{
	    //alert("in moreRow");
	    tbody=document.getElementById(tableId);
	    var index = tbody.rows.length - 2;
	    if (index<0) index=0;
	    if (!attachmentController.validateAttach(index)) return;
	    index = index-1;
	    var newRow=tbody.insertRow(tbody.rows.length);
	    var cell0 = newRow.insertCell(0);
	    cell0.setAttribute('class','dataClass');
	    cell0.innerHTML = '<input type="text" size="20" name="attachments['+index+'].label"/>';

	    var cell1 = newRow.insertCell(1);
	  	cell1.setAttribute('class','dataClass');
	  	cell1.innerHTML = '<input type="text" size="20" id="attachments['+index+'].fileName" name="attachments['+index+'].fileName" onblur="javascript:attachmentController.checkFileName('+index+')" /><input type="hidden" name="attachments['+index+'].digitalCert.signHash"/><label style="color :red ; float:left" id="msg['+index+'].fileName" name="msg['+index+'].fileName" ></label>';

	   	var cell2 = newRow.insertCell(2);
	  	cell2.setAttribute('class','dataClass');
	  	cell2.setAttribute('title','Allowable Extensions:'+$("input[name='fileExtension']").val());
	  	cell2.setAttribute('style','word-wrap:break-word');
	  	cell2.innerHTML = '<input type="file" size="20" name="attachments['+index+'].file" onmouseout="javascript:attachmentDetails('+index+');"/>';
	  	var cell3 = newRow.insertCell(3);
	  	cell3.innerHTML='<a class="pageContentLink" href="javascript:attachmentController.delAttach(attachTab,'+(index+1)+');">DELETE ROW</a>';


	},

	addAttachCorrigendum : function (/*String*/ tableId,pkiEnable){
		var isPrintWithRFQValue = document.getElementById("isPrintWithRFQValue").value;
	    tbody=document.getElementById(tableId);
	    var index = tbody.rows.length - 2;
	    if (index<0) index=0;
	    if (!attachmentController.validateAttach(index)) return;
	    	index = index-1;
	    var newRow=tbody.insertRow(tbody.rows.length);
	    var cell0 = newRow.insertCell(0);
	    cell0.setAttribute('class','dataClass');
	    cell0.innerHTML = '<input type="text" size="20" name="domain.attachments['+index+'].label" id="domain.attachments['+index+'].label"/>';

	    var cell1 = newRow.insertCell(1);
	  	cell1.setAttribute('class','dataClass');
	  	cell1.innerHTML = '<input type="text" size="20" name="domain.attachments['+index+'].fileName" id="domain.attachments['+index+'].fileName" onblur="javascript:attachmentController.checkFileName('+index+')"/><input type="hidden" name="domain.attachments['+index+'].digitalCert.signHash" id="domain.attachments['+index+'].digitalCert.signHash"/> <label style="color :red ; float:left" id=msg['+index+'].fileName name=msg['+index+'].fileName></label>';

	   	var cell2 = newRow.insertCell(2);
	  	cell2.setAttribute('class','dataClass');
	  	cell2.setAttribute('title','Allowable Extensions:'+$("input[name='fileExtension']").val());
	  	cell2.setAttribute('style','word-wrap:break-word');
	  	cell2.innerHTML = '<input type="file" size="20" name="domain.attachments['+index+'].file" id="domain.attachments['+index+'].file" onmouseout="javascript:attachmentDetails('+index+');" />';

	  	var documentUploaded = $('input[name=domain\\.documentUploadedFor]:checked').val();
	  	var cell3 = newRow.insertCell(3);
	  	if(documentUploaded == "S"){
	  	cell3.innerHTML='<div id="specific_suppliers['+index+']"><select id="domain.attachments['+index+'].rfqSellerIds" name="domain.attachments['+index+'].rfqSellerIds" multiple="true"></select></div>';
	  	}
	  	
	  	//cell4.innerHTML='';//'<a class="pageContentLink" href="javascript:attachmentController.delAttach(attachTab,'+index+');">DELETE ROW</a>';
	  	
	  	var cell4 = newRow.insertCell(4);
	  	if(isPrintWithRFQValue === 'true'){	  		
	  		cell4.innerHTML='<input type="checkbox" name="domain.attachments['+index+'].isPrintWithRfq" id="domain.attachments['+index+'].isPrintWithRfq" value="Y"/><FONT COLOR\="RED"><B>(Print with RFQ)</B></FONT>';
	  	}
	  	else{
	  		cell4.innerHTML = '';
	  	}
	  	
	  	if(pkiEnable){
	  	    var cell5 = newRow.insertCell(5);
	//	  	cell4.innerHTML = '<input type="button" class="epsSubmit" value="SIGN FILE" onClick="javascript:signCorrigendumAttachmentFile('+index+');"/>';
			cell5.innerHTML = '<a class="pageContentLink" href="javascript:signCorrigendumAttachmentFile('+index+');">SIGN FILE</a>';
	  	}
	  	
	  	

		var suppliersString = $('#specific_suppliers_list').val();
		var record = suppliersString.split(',');
		for(var val in record) {
			var data = record[val].split('#');
			$("#domain\\.attachments\\["+index+"\\]\\.rfqSellerIds").append($("<option>").attr("value", data[0]).text(data[1]));
		}
	},
	addCorrAttach : function (/*String*/ tableId,counterIndex,pkiEnable)
	{
		var tabId = "attachTab"+"_"+counterIndex;
		tbody = document.getElementById(tabId);
	    //tbody=document.getElementById(tableId+rfqItemId);
	    var index = tbody.rows.length - 2;
	    if (index<0) index=0;
	    if (!attachmentController.validateCorrItemAttach(index,counterIndex)) return;
	    var newRow=tbody.insertRow(tbody.rows.length);
	    var cell0 = newRow.insertCell(0);
	    cell0.setAttribute('class','dataClass');
	    cell0.innerHTML = '<input type="text" size="20" name="domain.rfqItem['+counterIndex+'].attachments['+index+'].label" id="attachments['+index+'].label"/>';

	    var cell1 = newRow.insertCell(1);
	  	cell1.setAttribute('class','dataClass');
	  	cell1.innerHTML = '<input type="text" size="20" name="domain.rfqItem['+counterIndex+'].attachments['+index+'].fileName" id="attachments['+index+'].fileName" onblur="javascript:attachmentController.checkFileName('+index+')"/><input type="hidden" name="domain.rfqItem['+counterIndex+'].attachments['+index+'].digitalCert.signHash"/> <label style="color :red ; float:left" id=msg['+index+'].fileName name=msg['+index+'].fileName></label>';

	   	var cell2 = newRow.insertCell(2);
	  	cell2.setAttribute('class','dataClass');
	  	cell2.innerHTML = '<input type="file" size="20" name="domain.rfqItem['+counterIndex+'].attachments['+index+'].file" id="attachments['+index+'].file" onmouseout="javascript:attachmentDetails('+index+');"/>';

	  	var cell3 = newRow.insertCell(3);
	  	//cell3.innerHTML='<a class="pageContentLink" href="javascript:attachmentController.delItemAttach('+index+','+counterIndex+');">DELETE ROW</a>';
		if(pkiEnable === 'true')
	  	{
	  	    var cell4 = newRow.insertCell(4);
	  	    cell4.innerHTML = '<a class="pageContentLink" href="javascript:signCorrigendumAttachmentFile('+index+','+counterIndex+');">SIGN FILE</a>';
	  	}

	},
	validateCorrItemAttach : function (/*int*/ index,/*int*/counterIndex)
	{
		var maxSize = 45 ; /*<c:out value="${_maxRFQAttachSize}"/>;*/
	    if((index -1) == maxSize)
	    {
	    	alert("Please limit no of attachments with in  "+maxSize+" ");
	    	return false;
	    }
	    if (index>0) {
	    	var lastLabel = document.getElementById("domain.rfqItem["+counterIndex+"].attachments["+(index-1)+"].label");
	    	if(null!=lastLabel)
		    {
			    if((lastLabel.value=='') || (lastLabel.value==null))
			    {
			    	alert("Please specify the Label for previous row");
			    	return false;
			    }
			}
	    }
	    return true;
	},


	addItemAttach : function (/*String*/ tableId,/*int*/ counterIndex)
	{
	    var tbody = document.getElementById(tableId);
	    var index = tbody.rows.length - 2;
	    if (index<0) index=0;
	    if (!attachmentController.validateItemAttach(index,counterIndex)) return;
	    var newRow = tbody.insertRow(tbody.rows.length);
	    var cell0 = newRow.insertCell(0);
	    cell0.setAttribute('class','dataClass');
	    cell0.innerHTML = '<input type="text" size="20" name="docItemList['+counterIndex+'].attachments['+index+'].label"/>';

	    var cell1 = newRow.insertCell(1);
	  	cell1.setAttribute('class','dataClass');
	  	cell1.innerHTML = '<input type="text" size="20" name="docItemList['+counterIndex+'].attachments['+index+'].fileName"/><input type="hidden" name="docItemList['+counterIndex+'].attachments['+index+'].digitalCert.signHash"/>';

	   	var cell2 = newRow.insertCell(2);
	  	cell2.setAttribute('class','dataClass');
	  	cell2.innerHTML = '<input type="file" size="40" name="docItemList['+counterIndex+'].attachments['+index+'].file"/>';

	  	var cell3 = newRow.insertCell(3);
	  	cell3.innerHTML='<a class="pageContentLink" href="javascript:attachmentController.delItemAttach('+index+','+counterIndex+');">DELETE ROW</a>';
	},

	addPostActivationAttach : function (/*String*/ tableId)
	{
	    //alert("in moreRow");
	    tbody=document.getElementById(tableId);
	    var index = tbody.rows.length - 2;
	    if (index<0) index=0;
	    if (!attachmentController.validatePostActivationAttach(index)) return;
	    var newRow=tbody.insertRow(tbody.rows.length);
	    var cell0 = newRow.insertCell(0);
	    cell0.setAttribute('class','dataClass');
	    cell0.innerHTML = '<input type="text" size="20" name="postActivationAttachments['+index+'].label"/>';

	    var cell1 = newRow.insertCell(1);
	  	cell1.setAttribute('class','dataClass');
	  	cell1.innerHTML = '<input type="text" size="20" name="postActivationAttachments['+index+'].fileName"/><input type="hidden" name="postActivationAttachments['+index+'].digitalCert.signHash"/>';

	   	var cell2 = newRow.insertCell(2);
	  	cell2.setAttribute('class','dataClass');
	  	cell2.innerHTML = '<input type="file" size="20" name="postActivationAttachments['+index+'].file"/>';

	  	var cell3 = newRow.insertCell(3);
	  	cell3.innerHTML='<a class="pageContentLink" href="javascript:attachmentController.delAttach(attachTab,'+index+');">DELETE ROW</a>';


	},

	addPkiPostActivationAttach : function (/*String*/ tableId)
	{
	    //alert("in moreRow");
	    tbody=document.getElementById(tableId);
	    var index = tbody.rows.length - 2;
	    if (index<0) index=0;
	    if (!attachmentController.validateAttach(index)) return;
		index = index-1;
	    var newRow=tbody.insertRow(tbody.rows.length);
	    var cell0 = newRow.insertCell(0);
	    cell0.setAttribute('class','dataClass');
	    cell0.innerHTML = '<input type="text" size="20" id="postActivationAttachments['+index+'].label" name="postActivationAttachments['+index+'].label"/>';

	    var cell1 = newRow.insertCell(1);
	  	cell1.setAttribute('class','dataClass');
	  	cell1.innerHTML = '<input type="text" size="20" id="postActivationAttachments['+index+'].fileName" name="postActivationAttachments['+index+'].fileName" onblur="javascript:attachmentController.checkFileName('+index+')"/><input type="hidden" id="postActivationAttachments['+index+'].digitalCert.signHash" name="postActivationAttachments['+index+'].digitalCert.signHash"/><label style="color :red ; float:left" id=msg['+index+'].fileName name=msg['+index+'].fileName></label>';

	   	var cell2 = newRow.insertCell(2);
	  	cell2.setAttribute('class','dataClass');
	  	cell2.innerHTML = '<input type="file" size="20" id="postActivationAttachments['+index+'].file" name="postActivationAttachments['+index+'].file" onmouseout="javascript:attachmentController.attachmentDetails('+index+');"/>';

	  	var cell3 = newRow.insertCell(3);

	  	cell3.innerHTML='';//'<a class="pageContentLink" href="javascript:attachmentController.delRfqAttach(attachTab,'+index+');">DELETE ROW</a>';

	  	var cell4 = newRow.insertCell(4);
//	  	cell4.innerHTML = '<input type="button" class="epsSubmit"  value="SIGN FILE" onClick="javascript:signRfqAttachmentFile('+index+');"/>';
		cell4.innerHTML = '<a class="pageContentLink" href="javascript:signPostRfqAttachmentFile('+index+');">SIGN FILE</a> <FONT COLOR\="RED"><B> [Please sign the file before pressing ATTACH/DEATCH button] </B></FONT>';

	},
	
	addPostBidAttach : function (/*String*/ tableId)
	{
	    //alert("in moreRow");
	    tbody=document.getElementById(tableId);
	    var index = tbody.rows.length - 2;
	    if (index<0) index=0;
	    if (!attachmentController.validatePostBidAttach(index)) return;
	    var newRow=tbody.insertRow(tbody.rows.length);
	    var cell0 = newRow.insertCell(0);
	    cell0.setAttribute('class','dataClass');
	    cell0.innerHTML = '<input type="text" size="20" name="postBidAttachments['+index+'].label"/>';

	    var cell1 = newRow.insertCell(1);
	  	cell1.setAttribute('class','dataClass');
	  	cell1.innerHTML = '<input type="text" size="20" name="postBidAttachments['+index+'].fileName"/><input type="hidden" name="postBidAttachments['+index+'].digitalCert.signHash"/>';

	   	var cell2 = newRow.insertCell(2);
	  	cell2.setAttribute('class','dataClass');
	  	cell2.innerHTML = '<input type="file" size="20" name="postBidAttachments['+index+'].file"/>';

	  	var cell3 = newRow.insertCell(3);
	  	cell3.innerHTML='<a class="pageContentLink" href="javascript:attachmentController.delAttach(attachTab,'+index+');">DELETE ROW</a>';


	},
	addPkiComparativeStatementAttach : function (/*String*/ tableId)
	{
	         
	    tbody=document.getElementById(tableId);
	    var index = tbody.rows.length - 2;
	    if (index<0) index=0;
	    if (!attachmentController.validateAttach(index)) return;
		index = index-1;
		
	    var newRow=tbody.insertRow(tbody.rows.length);
	    var cell0 = newRow.insertCell(0);
	    cell0.setAttribute('class','dataClass');
	    cell0.innerHTML = '<input type="text" size="20" id="CSAttachments['+index+'].label" name="CSAttachments['+index+'].label"/><input type="hidden" id="CSAttachments['+index+'].digitalCert.signHash" name="CSAttachments['+index+'].digitalCert.signHash"/>';

	    var cell1 = newRow.insertCell(1);
	  	cell1.setAttribute('class','dataClass');
	  	cell1.innerHTML = '<input type="text" size="20" id="CSAttachments['+index+'].fileName" name="CSAttachments['+index+'].fileName" onblur="javascript:attachmentController.checkFileName('+index+')"/><input type="hidden" id="comaparativeStatementAttachments['+index+'].digitalCert.signHash" name="comaparativeStatementAttachments['+index+'].digitalCert.signHash"/><label style="color :red ; float:left" id=msg['+index+'].fileName name=msg['+index+'].fileName></label>';

	   	var cell2 = newRow.insertCell(2);
	  	cell2.setAttribute('class','dataClass');
	  	cell2.innerHTML = '<input type="file" size="20" id="CSAttachments['+index+'].file" name="CSAttachments['+index+'].file" onchange="javascript:attachmentController.attachmentDetailsForComparativeStatement('+index+');"/>';

	  	var cell4 = newRow.insertCell(3);
		cell4.innerHTML = '<a class="pageContentLink" href="javascript:signComparativeStatementAttachmentFile('+index+');">SIGN FILE</a> <FONT COLOR\="RED"><B> [Please sign the file before pressing ATTACH/DEATCH button] </B></FONT>';

	},

	
	addPkiPostBidAttach : function (/*String*/ tableId)
	{
	    //alert("in moreRow");
	    tbody=document.getElementById(tableId);
	    var index = tbody.rows.length - 2;
	    if (index<0) index=0;
	    if (!attachmentController.validatePostBidAttach(index)) return;
		index = index-1;
	    var newRow=tbody.insertRow(tbody.rows.length);
	    var cell0 = newRow.insertCell(0);
	    cell0.setAttribute('class','dataClass');
	    cell0.innerHTML = '<input type="text" size="20" id="postBidAttachments['+index+'].label" name="postBidAttachments['+index+'].label"/>';

	    var cell1 = newRow.insertCell(1);
	  	cell1.setAttribute('class','dataClass');
	  	cell1.innerHTML = '<input type="text" size="20" id="postBidAttachments['+index+'].fileName" name="postBidAttachments['+index+'].fileName" onblur="javascript:attachmentController.checkFileName('+index+')"/><input type="hidden" id="postBidAttachments['+index+'].digitalCert.signHash" name="postBidAttachments['+index+'].digitalCert.signHash"/><label style="color :red ; float:left" id=msg['+index+'].fileName name=msg['+index+'].fileName></label>';

	   	var cell2 = newRow.insertCell(2);
	  	cell2.setAttribute('class','dataClass');
	  	cell2.innerHTML = '<input type="file" size="20" id="postBidAttachments['+index+'].file" name="postBidAttachments['+index+'].file" onchange="javascript:attachmentController.attachmentDetailsForPostBid('+index+');"/>';

	  	var cell3 = newRow.insertCell(3);

	  	cell3.innerHTML='';//'<a class="pageContentLink" href="javascript:attachmentController.delRfqAttach(attachTab,'+index+');">DELETE ROW</a>';

	  	var cell4 = newRow.insertCell(4);
//	  	cell4.innerHTML = '<input type="button" class="epsSubmit"  value="SIGN FILE" onClick="javascript:signRfqAttachmentFile('+index+');"/>';
		cell4.innerHTML = '<a class="pageContentLink" href="javascript:signPostBidAttachmentFile('+index+');">SIGN FILE</a> <FONT COLOR\="RED"><B> [Please sign the file before pressing ATTACH/DEATCH button] </B></FONT>';

	},



	addClarAttachment : function (/*String*/ tableId, pkiEnable){

		tbody=document.getElementById(tableId);
	    var index = tbody.rows.length - 2;
	    if (index<0) index=0;
	    if (!attachmentController.validateAttach(index)) return;

	    var newRow=tbody.insertRow(tbody.rows.length);
	    var cell0 = newRow.insertCell(0);
	    cell0.setAttribute('class','dataClass');
	    cell0.innerHTML = '<input type="text" size="20" name="attachments['+index+'].label"/>';

	    var cell1 = newRow.insertCell(1);
	  	cell1.setAttribute('class','dataClass');
	  	cell1.innerHTML = '<input type="text" size="20" id="attachments['+index+'].fileName" name="attachments['+index+'].fileName" onblur="javascript:attachmentController.checkFileName('+index+')"/><input type="hidden" name="attachments['+index+'].digitalCert.signHash" name="attachments['+index+'].digitalCert.signHash"/><label style="color :red ; float:left" id=msg['+index+'].fileName name=msg['+index+'].fileName></label>';

	   	var cell2 = newRow.insertCell(2);
	  	cell2.setAttribute('class','dataClass');
	  	cell2.innerHTML = '<input type="file" size="20" id="attachments['+index+'].file" name="attachments['+index+'].file" onmouseout="javascript:attachmentDetails('+index+');"/>';

	  	var cell3 = newRow.insertCell(3);
	  	cell3.innerHTML='';//'<a class="pageContentLink" href="javascript:attachmentController.delAttach(attachTab,'+index+');">DELETE ROW</a>';

	  	if(pkiEnable){
	  		var cell4 = newRow.insertCell(4);
		  	cell4.innerHTML = '<a class="pageContentLink" href="javascript:signClarAttachmentFile('+index+');">SIGN FILE</a> <FONT COLOR\="RED"><B> [Please sign the file before pressing SEND button] </B></FONT>';
	  	}
	},

	addRfqAttach : function (/*String*/ tableId)
	{
	    //alert("in moreRow");
		var isPrintWithRFQValue = 'false';
		if(document.getElementById("isPrintWithRFQValue") != undefined){
			isPrintWithRFQValue = document.getElementById("isPrintWithRFQValue").value;
		}
	    tbody=document.getElementById(tableId);
	    //alert("tbody :"+tbody);
	    var index = tbody.rows.length - 2;
	    if (index<0) index=0;
	    if (!attachmentController.validateAttach(index)) return;
		index = index-1;
	    var newRow=tbody.insertRow(tbody.rows.length);
	    var cell0 = newRow.insertCell(0);
	    cell0.setAttribute('class','dataClass');
	    cell0.innerHTML = '<input type="text" size="20" id="attachments['+index+'].label" name="attachments['+index+'].label"/>';

	    var cell1 = newRow.insertCell(1);
	  	cell1.setAttribute('class','dataClass');
	  	cell1.innerHTML = '<input type="text" size="20" id="attachments['+index+'].fileName" name="attachments['+index+'].fileName" onblur="javascript:attachmentController.checkFileName('+index+')"/><input type="hidden" id="attachments['+index+'].digitalCert.signHash" name="attachments['+index+'].digitalCert.signHash"/><label style="color :red ; float:left" id=msg['+index+'].fileName name=msg['+index+'].fileName></label>';

	   	var cell2 = newRow.insertCell(2);
	  	cell2.setAttribute('class','dataClass');
	  	cell2.innerHTML = '<input type="file" size="20" id="attachments['+index+'].file" name="attachments['+index+'].file" onmouseout="javascript:attachmentController.attachmentDetails('+index+');"/>';
	  	
	  	//'<a class="pageContentLink" href="javascript:attachmentController.delRfqAttach(attachTab,'+index+');">DELETE ROW</a>';
	  	
	  	var cell3 = newRow.insertCell(3);
	  	if(isPrintWithRFQValue === 'true'){	  		
	  		cell3.innerHTML = '<input type="checkbox" name="domain.attachments['+index+'].isPrintWithRfq" id="domain.attachments['+index+'].isPrintWithRfq" value="Y"/><FONT COLOR\="RED"><B>(Print with RFQ)</B></FONT>';
	  	}
	  	else{
	  		cell3.innerHTML = '';
	  	}
	  	
	  	var cell4 = newRow.insertCell(4);
//	  	cell4.innerHTML = '<input type="button" class="epsSubmit"  value="SIGN FILE" onClick="javascript:signRfqAttachmentFile('+index+');"/>';
		cell4.innerHTML = '<a class="pageContentLink" href="javascript:signRfqAttachmentFile('+index+');">SIGN FILE</a> <FONT COLOR\="RED"><B> [Please sign the file before pressing ATTACH/DEATCH button] </B></FONT>';

	},
	addNoticeAttach : function (/*String*/ tableId)
	{
	    tbody=document.getElementById(tableId);
	    //alert("length :"+tbody.rows.length);
	    var index = tbody.rows.length - 1;
	    //alert("After deduction length :"+index);
	    if (index<0) index=0;
	    if (!attachmentController.validateAttach(index)) return;
	    var newRow=tbody.insertRow(tbody.rows.length);
	    

	   // alert("index :"+index);
	    var cell0 = newRow.insertCell(0);
	    cell0.setAttribute('class','dataClass');
	    cell0.innerHTML = '<input type="text" size="100" id="noticeAttachments['+index+'].label" name="noticeAttachments['+index+'].label"/>';

	    var cell1 = newRow.insertCell(1);
	  	cell1.setAttribute('class','dataClass');
	  	cell1.innerHTML = '<input type="text" size="20" id="noticeAttachments['+index+'].fileName" name="noticeAttachments['+index+'].fileName" onblur="javascript:attachmentController.checkHomeNoticeFileName('+index+')"/>';

	   	var cell2 = newRow.insertCell(2);
	  	cell2.setAttribute('class','dataClass');
	  	cell2.innerHTML = '<input type="file" size="20" id="noticeAttachments['+index+'].file" name="noticeAttachments['+index+'].file" onmouseout="javascript:attachmentController.noticeAttachmentDetails('+index+');"/>';
	  	
	  	/*var cell3 = newRow.insertCell(3);
	  	cell3.innerHTML='<input type="checkbox" name="noticeAttachments['+index+'].isDeleteRow" id="noticeAttachments['+index+'].isDeleteRow" value="true"/>';
*/
	},

	supplierSpecificAttach : function (/*String*/ tableId)
	{
	    //alert("in moreRow");
	    tbody=document.getElementById(tableId);
	    var index = tbody.rows.length - 2;
	    if (index<0) index=0;
	    if (!attachmentController.validateAttach(index)) return;
		index = index-1;
	    var newRow=tbody.insertRow(tbody.rows.length);
	    var cell0 = newRow.insertCell(0);
	    cell0.setAttribute('class','dataClass');
	    cell0.innerHTML = '<input type="text" size="20" id="supplierWiseAttachments['+index+'].label" name="supplierWiseAttachments['+index+'].label"/>';

	    var cell1 = newRow.insertCell(1);
	  	cell1.setAttribute('class','dataClass');
	  	cell1.innerHTML = '<input type="text" size="20" id="supplierWiseAttachments['+index+'].fileName" name="supplierWiseAttachments['+index+'].fileName" /><input type="hidden" id="supplierWiseAttachments['+index+'].digitalCert.signHash" name="supplierWiseAttachments['+index+'].digitalCert.signHash"/><label style="color :red ; float:left" id=msg['+index+'].fileName name=msg['+index+'].fileName></label>';

	   	var cell2 = newRow.insertCell(2);
	  	cell2.setAttribute('class','dataClass');
	  	cell2.innerHTML = '<input type="file" size="20" id="supplierWiseAttachments['+index+'].file" name="supplierWiseAttachments['+index+'].file" onmouseout="javascript:attachmentController.supplierSpecificAttachmentDetails('+index+');"/>';

	  	var cell3 = newRow.insertCell(3);
	  	cell3.setAttribute('class','dataClass');
	  	cell3.innerHTML='<select id="supplierWiseAttachments['+index+'].rfqSellerIds" name="supplierWiseAttachments['+index+'].rfqSellerIds" multiple="true"></select>';

	  	var cell4 = newRow.insertCell(4);
	  	cell4.innerHTML='';//'<a class="pageContentLink" href="javascript:attachmentController.delTableAttach(addRfqSupplierSpecificAttachTab,'+index+');">DELETE ROW</a>';

	  	var cell5 = newRow.insertCell(5);
		cell5.innerHTML = '<a class="pageContentLink" href="javascript:signSupplierWiseRfqAttachmentFile('+index+');">SIGN FILE</a> <FONT COLOR\="RED"><B> [Please sign the file before pressing ATTACH/DEATCH button] </B></FONT>';

		var suppliersString = $('#specific_suppliers_list').val();
		var record = suppliersString.split(',');
		for(var val in record) {
			var data = record[val].split('#');
			$("#supplierWiseAttachments\\["+index+"\\]\\.rfqSellerIds").append($("<option>").attr("value", data[0]).text(data[1]));
		}
	},

	addPkiOrderAttach : function (/*String*/ tableId)
	{
	    //alert("in moreRow");
	    tbody=document.getElementById(tableId);
	    var index = tbody.rows.length - 2;
	    if (index<0) index=0;
	    if (!attachmentController.validateAttach(index)) return;
		index = index-1;
	    var newRow=tbody.insertRow(tbody.rows.length);
	    var cell0 = newRow.insertCell(0);
	    cell0.setAttribute('class','dataClass');
	    cell0.innerHTML = '<input type="text" size="20" id="attachments['+index+'].label" name="attachments['+index+'].label"/>';

	    var cell1 = newRow.insertCell(1);
	  	cell1.setAttribute('class','dataClass');
	  	cell1.innerHTML = '<input type="text" size="20" id="attachments['+index+'].fileName" name="attachments['+index+'].fileName" onblur="javascript:attachmentController.checkFileName('+index+')"/><input type="hidden" id="attachments['+index+'].digitalCert.signHash" name="attachments['+index+'].digitalCert.signHash"/><label style="color :red ; float:left" id=msg['+index+'].fileName name=msg['+index+'].fileName></label>';

	   	var cell2 = newRow.insertCell(2);
	  	cell2.setAttribute('class','dataClass');
	  	cell2.innerHTML = '<input type="file" size="20" id="attachments['+index+'].file" name="attachments['+index+'].file" onmouseout="javascript:attachmentController.attachmentDetails('+index+');"/>';

	  	var cell3 = newRow.insertCell(3);
	  	cell3.innerHTML='<a class="pageContentLink" href="javascript:attachmentController.delAttach(attachTab,'+index+');">DELETE ROW</a>';

	  	var cell4 = newRow.insertCell(4);
//	  	cell4.innerHTML = '<input type="button" class="epsSubmit" value="SIGN FILE" onClick="javascript:OrderController.signOrderAttachmentFile('+index+');"/>';
		cell4.innerHTML = '<a class="pageContentLink" href="javascript:OrderController.signOrderAttachmentFile('+index+');">SIGN FILE</a>';

	},

	attachmentDetails : function (/*int*/ index){
		var fileLabel = document.getElementById("attachments["+index+"].label").value;
		var fileName= document.getElementById("attachments["+index+"].fileName").value;
		var fileBrowse= document.getElementById("attachments["+index+"].file").value;
		var requiredfilename = fileBrowse.replace(/^.*[\\\/]/, '');
		var filenameWithOutExtension = requiredfilename.split(".")[0];
		if(fileLabel==''&& fileName==''&&fileBrowse==''){
		}
		if(fileLabel==''&& fileName!=''&&fileBrowse!=''){
		document.getElementById("attachments["+index+"].label").value=fileName;
		document.getElementById("attachments["+index+"].fileName").value=fileName;
		}
		if(fileLabel!=''&& fileName==''&&fileBrowse!=''){
		document.getElementById("attachments["+index+"].fileName").value=fileLabel;
		}
		if(fileLabel==''&& fileName==''&&fileBrowse!=''){
		document.getElementById("attachments["+index+"].label").value=filenameWithOutExtension;
		document.getElementById("attachments["+index+"].fileName").value=filenameWithOutExtension;
		}
	},
	noticeAttachmentDetails : function (/*int*/ index){
		var fileLabel = document.getElementById("noticeAttachments["+index+"].label").value;
		var fileName= document.getElementById("noticeAttachments["+index+"].fileName").value;
		var fileBrowse= document.getElementById("noticeAttachments["+index+"].file").value;
		var requiredfilename = fileBrowse.replace(/^.*[\\\/]/, '');
		var filenameWithOutExtension = requiredfilename.split(".")[0];
		if(fileLabel==''&& fileName==''&&fileBrowse==''){
		}
		if(fileLabel==''&& fileName!=''&&fileBrowse!=''){
		document.getElementById("noticeAttachments["+index+"].label").value=fileName;
		document.getElementById("noticeAttachments["+index+"].fileName").value=fileName;
		}
		if(fileLabel!=''&& fileName==''&&fileBrowse!=''){
		document.getElementById("noticeAttachments["+index+"].fileName").value=fileLabel;
		}
		if(fileLabel==''&& fileName==''&&fileBrowse!=''){
		document.getElementById("noticeAttachments["+index+"].label").value=filenameWithOutExtension;
		document.getElementById("noticeAttachments["+index+"].fileName").value=filenameWithOutExtension;
		}
	},
	attachmentDetailsForPostBid : function (/*int*/ index){
		var fileLabel = document.getElementById("postBidAttachments["+index+"].label").value;
		var fileName= document.getElementById("postBidAttachments["+index+"].fileName").value;
		var fileBrowse= document.getElementById("postBidAttachments["+index+"].file").value;
		var requiredfilename = fileBrowse.replace(/^.*[\\\/]/, '');
		var filenameWithOutExtension = requiredfilename.split(".")[0];
		if(fileLabel==''&& fileName==''&&fileBrowse==''){
		}
		if(fileLabel==''&& fileName!=''&&fileBrowse!=''){
		document.getElementById("postBidAttachments["+index+"].label").value=fileName;
		document.getElementById("postBidAttachments["+index+"].fileName").value=fileName;
		}
		if(fileLabel!=''&& fileName==''&&fileBrowse!=''){
		document.getElementById("postBidAttachments["+index+"].fileName").value=fileLabel;
		}
		if(fileLabel==''&& fileName==''&&fileBrowse!=''){
		document.getElementById("postBidAttachments["+index+"].label").value=filenameWithOutExtension;
		document.getElementById("postBidAttachments["+index+"].fileName").value=filenameWithOutExtension;
		}
	},
	attachmentDetailsForComparativeStatement : function (/*int*/ index){
		var fileLabel = document.getElementById("CSAttachments["+index+"].label").value;
		var fileName= document.getElementById("CSAttachments["+index+"].fileName").value;
		var fileBrowse= document.getElementById("CSAttachments["+index+"].file").value;
		var requiredfilename = fileBrowse.replace(/^.*[\\\/]/, '');
		var filenameWithOutExtension = requiredfilename.split(".")[0];
		if(fileLabel==''&& fileName==''&&fileBrowse==''){
		}
		if(fileLabel==''&& fileName!=''&&fileBrowse!=''){
		document.getElementById("CSAttachments["+index+"].label").value=fileName;
		document.getElementById("CSAttachments["+index+"].fileName").value=fileName;
		}
		if(fileLabel!=''&& fileName==''&&fileBrowse!=''){
		document.getElementById("CSAttachments["+index+"].fileName").value=fileLabel;
		}
		if(fileLabel==''&& fileName==''&&fileBrowse!=''){
		document.getElementById("CSAttachments["+index+"].label").value=filenameWithOutExtension;
		document.getElementById("CSAttachments["+index+"].fileName").value=filenameWithOutExtension;
		}
	},

	supplierSpecificAttachmentDetails : function (/*int*/ index){
		var fileLabel = document.getElementById("supplierWiseAttachments["+index+"].label").value;
		var fileName= document.getElementById("supplierWiseAttachments["+index+"].fileName").value;
		var fileBrowse= document.getElementById("supplierWiseAttachments["+index+"].file").value;
		var requiredfilename = fileBrowse.replace(/^.*[\\\/]/, '');
		var filenameWithOutExtension = requiredfilename.split(".")[0];
		//alert("filenameWithOutExtension>>>"+filenameWithOutExtension);
		//alert("fileName>>>"+fileName);
		//alert("fileBrowse>>>"+fileBrowse);
		if(fileLabel==''&& fileName==''&&fileBrowse==''){
		}
		if(fileLabel==''&& fileName!=''&&fileBrowse!=''){
		document.getElementById("supplierWiseAttachments["+index+"].label").value=fileName;
		document.getElementById("supplierWiseAttachments["+index+"].fileName").value=fileName;
		}
		if(fileLabel!=''&& fileName==''&&fileBrowse!=''){
		document.getElementById("supplierWiseAttachments["+index+"].fileName").value=fileLabel;
		}
		if(fileLabel==''&& fileName==''&&fileBrowse!=''){
		document.getElementById("supplierWiseAttachments["+index+"].label").value=filenameWithOutExtension;
		document.getElementById("supplierWiseAttachments["+index+"].fileName").value=filenameWithOutExtension;
		}
	},


	attachmentRevised : function (/*int*/ index){
		var fileName= document.getElementById("quotationUploadFiles["+index+"].fileName").value;
		var fileBrowse= document.getElementById("quotationUploadFiles["+index+"].file").value;
		var requiredfilename = fileBrowse.replace(/^.*[\\\/]/, '');
		var filenameWithOutExtension = requiredfilename.split(".")[0];
		if(fileName==''&&fileBrowse==''){
		}
		if(fileName!=''&&fileBrowse!=''){
		document.getElementById("quotationUploadFiles["+index+"].fileName").value=fileName;
		}
		if(fileName==''&&fileBrowse!=''){
		document.getElementById("quotationUploadFiles["+index+"].fileName").value=filenameWithOutExtension;
		}
	},

	checkFileName : function(index){
		var requiredfileNameValue= document.getElementById("attachments["+index+"].fileName").value;
		var fileNameValue = requiredfileNameValue.split(".")[0];
		var splChars =  /[^a-zA-Z0-9 _]/; 
		if(splChars.test(fileNameValue)) {
			document.getElementById("attachments["+index+"].fileName").value="";
			document.getElementById("attachments["+index+"].label").value="";
			document.getElementById("msg["+index+"].fileName").innerHTML="Avoid special characters";
			var ctrl = document.getElementById("attachments["+index+"].file");
			ctrl.parentNode.replaceChild(ctrl.cloneNode(true), ctrl);
		    return false;
		}
		else{
			document.getElementById("attachments["+index+"].fileName").value=fileNameValue;
			document.getElementById("msg["+index+"].fileName").innerHTML=" ";
			return true;
		}
	},
	checkHomeNoticeFileName : function(index){
		var requiredfileNameValue= document.getElementById("noticeAttachments["+index+"].fileName").value;
		var fileNameValue = requiredfileNameValue.split(".")[0];
		var splChars =  /[^a-zA-Z0-9 _]/; 
		if(splChars.test(fileNameValue)) {
			document.getElementById("noticeAttachments["+index+"].fileName").value="";
			document.getElementById("noticeAttachments["+index+"].label").value="";
			alert("Avoid special characters");
			var ctrl = document.getElementById("noticeAttachments["+index+"].file");
			ctrl.parentNode.replaceChild(ctrl.cloneNode(true), ctrl);
		    return false;
		}
		else{
			document.getElementById("noticeAttachments["+index+"].fileName").value=fileNameValue;
			document.getElementById("msg["+index+"].fileName").innerHTML=" ";
			return true;
		}
	},
	
	checkFileNameOtherTrmAndCondition : function(index){
		var requiredfileNameValue= document.getElementById("otherTrmAndCondition["+index+"].fileName").value;
		var fileNameValue = requiredfileNameValue.split(".")[0];
		var splChars =  /[^a-zA-Z0-9 _]/;  ///^\w+$/; // /[^a-zA-Z ]/;
		if(splChars.test(fileNameValue)) {
			document.getElementById("otherTrmAndCondition["+index+"].fileName").value="";
			document.getElementById("otherTrmAndCondition["+index+"].label").value="";
			document.getElementById("otherTrmAndConditionMsg["+index+"].fileName").innerHTML="Avoid special characters";
			var ctrl = document.getElementById("otherTrmAndCondition["+index+"].file");
			ctrl.parentNode.replaceChild(ctrl.cloneNode(true), ctrl);
		    return false;
		}
		else{
			document.getElementById("otherTrmAndCondition["+index+"].fileName").value=fileNameValue;
			document.getElementById("otherTrmAndConditionMsg["+index+"].fileName").innerHTML=" ";
			return true;
		}
	},
	checkFileNameImportantInfo : function(index){
		var requiredfileNameValue= document.getElementById("importantInfo["+index+"].fileName").value;
		var fileNameValue = requiredfileNameValue.split(".")[0];
		var splChars =  /[^a-zA-Z0-9 _]/;  ///^\w+$/; // /[^a-zA-Z ]/;
		if(splChars.test(fileNameValue)) {
			document.getElementById("importantInfo["+index+"].fileName").value="";
			document.getElementById("importantInfo["+index+"].label").value="";
			document.getElementById("importantInfoMsg["+index+"].fileName").innerHTML="Avoid special characters";
			var ctrl = document.getElementById("importantInfo["+index+"].file");
			ctrl.parentNode.replaceChild(ctrl.cloneNode(true), ctrl);
		    return false;
		}
		else{
			document.getElementById("importantInfo["+index+"].fileName").value=fileNameValue;
			document.getElementById("importantInfoMsg["+index+"].fileName").innerHTML=" ";
			return true;
		}
	},
	delRfqAttach :function(/*String*/ tableId, /*int*/ index)
	{
		var tabId = "attachTab";
		tbody = document.getElementById(tabId);

	  	if (confirm('Delete The Attachment?')) tbody.deleteRow(index+3);
	},
	delAttach :function(/*String*/ tableId, /*int*/ index)
	{
		var tabId = "attachTab";
		tbody = document.getElementById(tabId);

	  	if (confirm('Delete The Attachment?')) tbody.deleteRow(index+2);
	},
	delTableAttach :function(/*String*/ tabId, /*int*/ index)
	{
		var tabId = "addRfqSupplierSpecificAttachTab";
		tbody = document.getElementById(tabId);

	  	if (confirm('Delete The Attachment? ')) tbody.deleteRow(index+3);
	},
	delItemAttach :function(/*int*/ index , /*int*/ counterIndex)
	{
		var tabId = "attachTab"+"_"+counterIndex;
		tbody = document.getElementById(tabId);
	  	if (confirm('Delete The Attachment?')) tbody.deleteRow(index+2);
	},
	delcomparativeStatementAttach :function(/*int*/ index , /*int*/ counterIndex)
	{
		var tabId = "attach";
		tbody = document.getElementById(tabId);
	  	if (confirm('Delete The Attachment?')) tbody.deleteRow(index+2);
	},
	validateAttach : function (/*int*/ index)
	{
		var maxSize = 45 ; /*<c:out value="${_maxRFQAttachSize}"/>;*/
	    if((index -1 ) == maxSize)
	    {
	    	alert("Please limit no of attachments with in  "+maxSize+" ");
	    	return false;
	    }

	    // Validation Disabledfor adding multiple rows in File Attachment
	    /*if (index>0) {
	    	var lastLabel = document.getElementById("attachments["+(index-1)+"].label");
	    	//alert(lastLabel.value);
		    if(null!=lastLabel)
		    {
			    if((lastLabel.value=='') || (lastLabel.value==null))
			    {
			    	alert("Please specify the Label for previous row");
			    	return false;
			    }
			}
	    }*/

	    return true;
	},
	validateItemAttach : function (/*int*/ index,/*int*/counterIndex)
	{
		var maxSize = 45 ; /*<c:out value="${_maxRFQAttachSize}"/>;*/
	    if((index -1) == maxSize)
	    {
	    	alert("Please limit no of attachments with in  "+maxSize+" ");
	    	return false;
	    }
	    if (index>0) {
	    	var lastLabel = document.getElementById("docItemList["+counterIndex+"].attachments["+(index-1)+"].label");
	    	if(null!=lastLabel)
		    {
			    if((lastLabel.value=='') || (lastLabel.value==null))
			    {
			    	alert("Please specify the Label for previous row");
			    	return false;
			    }
			}
	    }
	    return true;
	},

	validatePostActivationAttach : function (/*int*/ index)
	{
		var maxSize = 45 ; /*<c:out value="${_maxRFQAttachSize}"/>;*/
	    if((index -1) == maxSize)
	    {
	    	alert("Please limit no of attachments with in  "+maxSize+" ");
	    	return false;
	    }
	    if (index>0) {
	    	var lastLabel = document.getElementById("postActivationAttachments["+(index-1)+"].label");
		    if(null!=lastLabel)
		    {
			    if((lastLabel.value=='') || (lastLabel.value==null))
			    {
			    	alert("Please specify the Label for previous row");
			    	return false;
			    }
			}
	    }
	    return true;
	},
	validatePostBidAttach : function (/*int*/ index)
	{
		var maxSize = 45 ; /*<c:out value="${_maxRFQAttachSize}"/>;*/
	    if((index -1) == maxSize)
	    {
	    	alert("Please limit no of attachments with in  "+maxSize+" ");
	    	return false;
	    }
	    if (index>0) {
	    	var lastLabel = document.getElementById("postBidAttachments["+(index-1)+"].label");
		    if(null!=lastLabel)
		    {
			    if((lastLabel.value=='') || (lastLabel.value==null))
			    {
			    	alert("Please specify the Label for previous row");
			    	return false;
			    }
			}
	    }
	    return true;
	},
	addRfiAttach : function (/*String*/ tableId)
	{
	    alert("in moreRow");
	    tbody=document.getElementById(tableId);
	    var index = tbody.rows.length - 2;
	    if (index<0) index=0;
	    if (!attachmentController.validateAttach(index)) return;
	    var newRow=tbody.insertRow(tbody.rows.length);
	    var cell0 = newRow.insertCell(0);
	    cell0.setAttribute('class','dataClass');
	    cell0.innerHTML = '<input type="text" size="20" name="attachments['+index+'].label"/>';

	    var cell1 = newRow.insertCell(1);
	  	cell1.setAttribute('class','dataClass');
	  	cell1.innerHTML = '<input type="text" size="20" name="attachments['+index+'].fileName"/><input type="hidden" name="attachments['+index+'].digitalCert.signHash"/>';

	   	var cell2 = newRow.insertCell(2);
	  	cell2.setAttribute('class','dataClass');
	  	cell2.innerHTML = '<input type="file" size="20" name="attachments['+index+'].file"/>';

	  	var cell3 = newRow.insertCell(3);
	  	cell3.innerHTML='<a class="pageContentLink" href="javascript:attachmentController.delAttach(attachTab,'+index+');">DELETE ROW</a>';

	  	var cell4 = newRow.insertCell(4);
	  //cell4.innerHTML = '<input type="button" class="epsSubmit" value="SIGN FILE" onClick="javascript:signRfqAttachmentFile('+index+');"/>';
	  	cell4.innerHTML = '<a class="pageContentLink" href="javascript:signRfqAttachmentFile('+index+');">SIGN FILE</a>';

	},
	 popupCenter : function(verifyFileHash,verifyFormname)
	 {
	 	$("input[name=attachFileHash]").val(verifyFileHash);
	 	var csrfToken=$("#csrfToken").val();

		var pageURL =contextRoot+ "/security/getVerifyFile.do?tab=y&verifyFormname="+verifyFormname+"&"+csrfToken;

		var title = "selectFile";
		var w = 400;
		var h= 200;
		var left = (screen.width/2)-(w/2);
		var top = (screen.height/2)-(h/2);
		var targetWin = window.open (pageURL, title, 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width='+w+', height='+h+', top='+top+', left='+left);
		//var targetWin = window.open (pageURL, title, '');
	},


	validateFileName : function(formName){
	//$('#'+formName).submit(function() {
	var fileNameList = new Array();
	var breakOut = false;
	$('input[type=text][id*=attachments][id$=fileName],input[type=hidden][id*=attachments][id$=fileName],input[type=text][id*=Attachments][id$=fileName],input[type=text][id*=quotationUploadFiles][id$=fileName],input[type=text][id*=postBidAttachments][id$=fileName],input[type=hidden][id*=postBidAttachments][id$=fileName],input[type=text][id*=postBidAttachments][id$=label],input[type=hidden][id*=postBidAttachments][id$=label],input[type=text][id*=CSAttachments][id$=fileName],input[type=hidden][id*=CSAttachments][id$=fileName],input[type=text][id*=CSAttachments][id$=label],input[type=hidden][id*=CSAttachments][id$=label]').each(function(){
	var thisName=this.name;
    var labelName=thisName.replace('fileName','label');
 	var fileNameValue = $(this).val();
	var alphaNumericUnderScorePattern = /[^a-zA-Z0-9 _-]/;

	var mandatory="Y";
	var mandatoryName=thisName.replace('fileName','mandatory');
	if(document.getElementsByName(mandatoryName)[0]!=null){
		mandatory=document.getElementsByName(mandatoryName)[0].value;
	}

	var availExemption="N";
	var availExemptionName=thisName.replace('fileName','availExemption');
	if(document.getElementsByName(availExemptionName)[0]!=null){
		availExemption=document.getElementsByName(availExemptionName)[0].value;
	}

	var element =  document.getElementById(thisName.replace('fileName','id'));
	if (typeof(element) != 'undefined' && element != null){
		//doing nothing
	}else{
		if(document.getElementsByName(thisName.replace('fileName','file'))[0] != null){
			var myFileVal=document.getElementsByName(thisName.replace('fileName','file'))[0].value;
			var extension =   myFileVal.substr((myFileVal.lastIndexOf('.')));
			fileNameValue = $.trim(fileNameValue).toLowerCase() + extension.toLowerCase();
		}
	}
/*
	if(!$.trim(fileNameValue).length && mandatory=="Y" && availExemption!="Y") {
		alert('file name can not be empty');
		$(this).focus();
		breakOut = true;
		return false;
	}
*/	
	
	//var arrOfStr = fileNameValue.split(".");
	//fileNameValue = arrOfStr[0];

	if($.trim(fileNameValue).length){
		if(jQuery.inArray(fileNameValue.toUpperCase(), fileNameList) == -1){
			if(fileNameValue.indexOf(".") !== -1){
				fileNameList.push($.trim(fileNameValue.toUpperCase()));
			}			
		}else{
			alert('Duplicate file names / label name are not allowed. Note that file name(s) considered are not case-sensitive.');
			fileNameList.length = 0;
			breakOut = true;
			return false;
		}
	}
	//alert("before spcl chsr chk"+fileNameValue);
	if(alphaNumericUnderScorePattern.test(fileNameValue.split('.')[0])) {
		alert('your file name contains special characters');
		$(this).focus();
		breakOut = true;
		return false;
	}
	//check for Label
	//alert("1");
	if(document.getElementsByName(labelName)[0]!=null){
		var labelValue =document.getElementsByName(labelName)[0].value;
		if(alphaNumericUnderScorePattern.test(labelValue.split('.')[0])) {
		alert('your file label contains special characters');
		document.getElementsByName(labelName)[0].value="";
		$(this).focus();
		breakOut = true;
		return false;
		}

	}

	});
	if(breakOut){
		breakOut=false;
		return false;
	}
	//});



	},
	deleteAttach :function(/*String*/tableId)
	{// generic method for deleting attachments
		$('#'+tableId).each(function(){
				  if($(this).find('input[type="text"]').length) {
						    if($('tbody', this).length > 0){
						    	   if (confirm('Delete The Attachment?')) $('tbody tr:last', this).remove();
						    }else {
						    	   if (confirm('Delete The Attachment?'))  $('tr:last', this).remove();
						    }
				  } else {
					  alert("no attachments to be deleted.");//doB();
				  }
		});


	},
	isTheirAnyTextField :function(/*String*/tableId)
	{// generic method for deleting attachments
		var flag=true;
		$('#'+tableId).each(function(){
				  if($(this).find('input[type="text"]').length) {}
				  else {
					  flag=false;
				  }
		});
    return flag;
	}
}
var quotationattAttachmentController = {
	addAttach : function (/*String*/ tableId,isMainTypeAttachmentEnabled)
	{
	    tbody=document.getElementById(tableId);
	    var index = tbody.rows.length - 1;
	    if (index<0) index=0;
	    if (!quotationattAttachmentController.validateAttach(index)) return;
	    var newRow=tbody.insertRow(tbody.rows.length);
	    newRow.setAttribute('id','_'+tableId+"_row_"+index);
	    var colIndex=0;

	    var cell0 = newRow.insertCell(colIndex);
	    cell0.setAttribute('class','dataClass');
	    cell0.innerHTML = '<input type="text" size="20" name="specificAttachments['+index+'].label"/>';
	    colIndex++;

	    var cell1 = newRow.insertCell(colIndex);
	  	cell1.setAttribute('class','dataClass');
	  	cell1.innerHTML = '<input type="text" size="20" id="specificAttachments['+index+'].fileName" name="specificAttachments['+index+'].fileName" onblur="javascript:quotationattAttachmentController.checkFileName('+index+')"/> <label style="color :red ; float:left" id=msg['+index+'].fileName name=msg['+index+'].fileName></label>';
	  	colIndex++;

	  	if(isMainTypeAttachmentEnabled){
		  	 var cell4 = newRow.insertCell(colIndex);
		  	 cell4.setAttribute('class','dataClass');
		  	 cell4.innerHTML = '<select name="specificAttachments['+index+'].type"><option value="Q">SUPPORTIVE DOCUMENT</option><option value="M">MAIN DOCUMENT </option></select>';
			 colIndex++;
		  	}

	  	var cell2 = newRow.insertCell(colIndex);
	  	cell2.setAttribute('class','dataClass');
	  	cell2.setAttribute('title','Allowable Extensions:'+$("input[name='fileExtension']").val());
	  	cell2.setAttribute('style','word-wrap:break-word');
	  	cell2.innerHTML = '<input type="file" size="20" name="specificAttachments['+index+'].file" onmouseout="javascript:quotationattAttachmentController.signAttachmentDetails('+index+');"/>';
	  	colIndex++;

	  	var cell3 = newRow.insertCell(colIndex);
	  	cell3.innerHTML='';//'<a class="pageContentLink" class="pageContentLink" href="javascript:quotationattAttachmentController.delAttach(attachTab,'+index+');">DELETE ROW</a>';
	  	//alert("Row Html = "+rowHtml);
	    //alert("cell0 = "+cell0.innerHTML);
	    //alert("cell1 = "+cell1.innerHTML);
	  	
	},

	addAttachFormat : function (/*String*/ tableId)
	{
	    tbody=document.getElementById(tableId);
	    var index = tbody.rows.length - 1;
	    /*var itemId = document.getElementById(itemID);
	    alert(itemId);
	    alert(Integer.parseInt(itemId));*/
	    if (index<0) index=0;
	    //if (!quotationattAttachmentController.validateAttach(index)) return;
	    var newRow=tbody.insertRow(tbody.rows.length);
	    newRow.setAttribute('id','_'+tableId+"_row_"+index);

	    var colIndex=0;

	    var cell0 = newRow.insertCell(colIndex);
	    cell0.setAttribute('class','dataClass');
	    //cell0.setAttribute('class','dataClass' +$("input[name='quotationUploadedFiles.itemId']").val());
	    //cell0.innerHTML = '<input type="hidden" size="20" name="quotationUploadedFiles['+index+'].itemId" />';
	    colIndex++;

	    var cell1 = newRow.insertCell(colIndex);
	  	cell1.setAttribute('class','dataClass');
	  	//cell1.innerHTML = '<input type="text" size="20" id="quotationUploadedFiles['+index+'].fileName" name="quotationUploadedFiles['+index+'].fileName" onblur="javascript:quotationattAttachmentController.checkFileName('+index+')"/> <label style="color :red ; float:left" id=msg['+index+'].fileName name=msg['+index+'].fileName></label>';
	  	colIndex++;

	  	var cell2 = newRow.insertCell(colIndex);
	  	cell2.setAttribute('class','dataClass');
	  	cell2.setAttribute('style','word-wrap:break-word');
	  	cell2.innerHTML = '<input type="file" size="30" name="quotationUploadedFiles['+index+'].file" /><input type="hidden" name="quotationUploadedFiles['+index+'].digitalCert.signHash"/> ';
	  	colIndex++;

	  	var cell3 = newRow.insertCell(colIndex);
	  	cell3.innerHTML='<a class="pageContentLink" class="pageContentLink" href="javascript:quotationattAttachmentController.delAttach(attachTab,'+index+');">DELETE ROW</a>';
	  	colIndex++;

	  	var cell5 = newRow.insertCell(colIndex);
	   //cell4.innerHTML = '<input type="button" class="epsSubmit" value="SIGN FILE" onClick="javascript:signQuotationAttachmentFile('+index+');"/>';
	  	cell5.innerHTML = '<a class="pageContentLink" href="#" onclick="javascript:signQuoteAttachment('+index+');">SIGN FILE</a>';

	},

	addSignAttach : function (/*String*/ tableId,isMainTypeAttachmentEnabled)
	{

		tbody=document.getElementById(tableId);
	    var index = tbody.rows.length - 1;
	    if (index<0) index=0;
	    if (!quotationattAttachmentController.validateAttach(index)) return;
	    var newRow=tbody.insertRow(tbody.rows.length);
	    newRow.setAttribute('id','_'+tableId+"_row_"+index);
	    var colIndex=0;
	    var cell0 = newRow.insertCell(colIndex);
	    cell0.setAttribute('class','dataClass');
	    cell0.innerHTML = '<input type="text" size="20" name="specificAttachments['+index+'].label" id="specificAttachments['+index+'].label"/>';
	    colIndex++;

	    var cell1 = newRow.insertCell(colIndex);
	  	cell1.setAttribute('class','dataClass');
	  	cell1.innerHTML = '<input type="text" size="20" id="specificAttachments['+index+'].fileName" name="specificAttachments['+index+'].fileName" onblur="javascript:quotationattAttachmentController.checkFileName('+index+')"/><input type="hidden" id="specificAttachments['+index+'].digitalCert.signHash" name="specificAttachments['+index+'].digitalCert.signHash"/><input type="hidden" id="specificAttachments['+index+'].digitalCert.publicKey" name="specificAttachments['+index+'].digitalCert.publicKey"/> <label style="color :red ; float:left" id=msg['+index+'].fileName name=msg['+index+'].fileName></label>';
	  	colIndex++;

	  	if(isMainTypeAttachmentEnabled){
	  	 var cell2 = newRow.insertCell(colIndex);
		 cell2.setAttribute('class','dataClass');
		 cell2.innerHTML = '<select name="specificAttachments['+index+'].type"><option value="Q">SUPPORTIVE DOCUMENT</option><option value="M">MAIN DOCUMENT </option></select>';
		 colIndex++;
	  	}


	   	var cell3 = newRow.insertCell(colIndex);
	  	cell3.setAttribute('class','dataClass');
	  	cell3.setAttribute('title','Allowable Extensions:'+$("input[name='fileExtension']").val());
	  	cell3.setAttribute('style','word-wrap:break-word');
	  	cell3.innerHTML = '<input type="file" id="specificAttachments['+index+'].file" name="specificAttachments['+index+'].file" onmouseout="javascript:quotationattAttachmentController.signAttachmentDetails('+index+');"/>';

	  	colIndex++;
	  	var cell4 = newRow.insertCell(colIndex);
	  	cell4.innerHTML='<a class="pageContentLink" href="javascript:quotationattAttachmentController.delAttach(attachTab,'+index+');">DELETE ROW</a>';

	  	colIndex++;
	  	var cell5 = newRow.insertCell(colIndex);
	//  	cell4.innerHTML = '<input type="button" class="epsSubmit" value="SIGN FILE" onClick="javascript:signQuotationAttachmentFile('+index+');"/>';
	  	cell5.innerHTML = '<a class="pageContentLink" href="#" onclick="javascript:signQuotationAttachmentFile('+index+');">SIGN FILE</a>';



	},
	checkFileName : function(index){
		var requiredfileNameValue= document.getElementById("specificAttachments["+index+"].fileName").value;
		var fileNameValue = requiredfileNameValue.split(".")[0];
		var splChars = /[^a-zA-Z0-9 _]/;
		if(fileNameValue.match(splChars)) {
			document.getElementById("specificAttachments["+index+"].fileName").value="";
			document.getElementById("specificAttachments["+index+"].label").value="";
			document.getElementById("msg["+index+"].fileName").innerHTML="Please avoid Restricted Characters";
			var ctrl = document.getElementById("specificAttachments["+index+"].file");
			ctrl.parentNode.replaceChild(ctrl.cloneNode(true), ctrl);
			return false;
		}
		else{
			document.getElementById("msg["+index+"].fileName").innerHTML="";
			document.getElementById("specificAttachments["+index+"].fileName").value=fileNameValue;

		return true;
		}

	},
	signAttachmentDetails:function (/*int*/ index){
		var fileLabel = document.getElementById("specificAttachments["+index+"].label").value;
		var fileName= document.getElementById("specificAttachments["+index+"].fileName").value;
		var fileBrowse= document.getElementById("specificAttachments["+index+"].file").value;
		var requiredfilename = fileBrowse.replace(/^.*[\\\/]/, '');
		var filenameWithOutExtension = requiredfilename.split(".")[0];
		//alert("fileLabel>>>"+fileLabel);
		//alert("fileName>>>"+fileName);
		//alert("fileBrowse>>>"+fileBrowse);
		if(fileLabel==''&& fileName==''&&fileBrowse==''){
		}
		if(fileLabel==''&& fileName!=''&&fileBrowse!=''){
		document.getElementById("specificAttachments["+index+"].label").value=fileName;
		document.getElementById("specificAttachments["+index+"].fileName").value=fileName;
		}
		if(fileLabel!=''&& fileName==''&&fileBrowse!=''){
		document.getElementById("specificAttachments["+index+"].fileName").value=fileLabel;
		}
		if(fileLabel==''&& fileName==''&&fileBrowse!=''){
		document.getElementById("specificAttachments["+index+"].label").value=filenameWithOutExtension;
		document.getElementById("specificAttachments["+index+"].fileName").value=filenameWithOutExtension;
		}
},
	delAttach :function(/*String*/ tableId, /*int*/ index)
	{
		var tabId = "attachTab";
		tbody = document.getElementById(tabId);
		row=document.getElementById('_'+tabId+"_row_"+index);
	  	if (confirm('Delete The Attachment?')) tbody.removeChild(row);
	},
	validateAttach : function (/*int*/ index)
	{
		var maxSize = 45 ; /*<c:out value="${_maxRFQAttachSize}"/>;*/
	    if((index -1) == maxSize)
	    {
	    	alert("Please limit no of attachments with in  "+maxSize+" ");
	    	return false;
	    }
	    if (index>0) {
	    	var lastLabel = document.getElementById("specificAttachments["+(index-1)+"].label");
		    if(null!=lastLabel)
		    {
			    if((lastLabel.value=='') || (lastLabel.value==null))
			    {
			    	alert("Please specify the Label for previous row");
			    	return false;
			    }
			}
	    }
	    return true;
	}

////
}
var ClarificationController = {
	reply : function() {
		$("#reply").css("display","inline");
		$("#_send").css("display","inline");
		$("#_reply").css("display","none");
		$("#_print").css("display","none");
	},
	viewClarification : function(msgStatus,msgId,clarificationId,parentEntityId,parentPartNo,parentClarType,createId,parentWorkFlowId,parentFlowId,csrfToken) {
	var reply;
	if(msgStatus == 'C')reply = "N";
	else reply = "Y";
	var url = contextRoot+"/business/clarification.action?methodName=viewClarificationMsg&reply="+reply
	+"&id="+msgId+"&clarificationId="+clarificationId
	+"&parentEntityId="+parentEntityId
	+"&parentPartNo="+parentPartNo
	+"&parentClarType="+parentClarType
	+"&createId="+createId
	+"&parentWorkFlowId="+parentWorkFlowId
	+"&parentFlowId="+parentFlowId
	+"&msgStatus="+msgStatus
	+"&"+csrfToken;
	window.open(url, '_self', 'width=800,height=500,scrollbars=yes,resizable=yes,menubar=no,directories=no,location=no');
	},
	viewRfqClarHistory : function(/*String*/ formName,/*String*/ divId){
		$("input[name='rfqId']","#rfqClarHistoryForm").val($("input[name='id']","#rfqViewForm").val());
		SearchController.searchWithForm(formName,['rfqId'],divId);
		$('html,body').animate({
	        scrollTop: $("#clarificationHistoryDiv").offset().top},
	        'slow');
		//event.PreventDefault();
	},
	expandClarification : function(/*int*/ clarificationId){
		var divId = 'clarification['+clarificationId+']';
		document.getElementById(divId).style.display="block";
		var collapseButtonDivId = 'clarificationCollapse['+clarificationId+']';
		var expandButtonDivId = 'clarificationExpand['+clarificationId+']';
		document.getElementById(collapseButtonDivId).style.display="block";
		document.getElementById(expandButtonDivId).style.display="none";
	},
	collapseClarification : function(/*int*/ clarificationId){
		var divId = 'clarification['+clarificationId+']';
		document.getElementById(divId).style.display="none";
		var collapseButtonDivId = 'clarificationCollapse['+clarificationId+']';
		var expandButtonDivId = 'clarificationExpand['+clarificationId+']';
		document.getElementById(collapseButtonDivId).style.display="none";
		document.getElementById(expandButtonDivId).style.display="block";
	}
}

var WFController = {
	showPaymentDetails  : function(rfqId){
		document.paymentDetails.rfqId.value = rfqId;
		document.paymentDetails.submit();
	},
	showPaymentDetailsByRfqId  : function(rfqId){
		document.paymentDetailsByRfqId.rfqId.value = rfqId;
		window.open('', '_paymentDetailsWindow',  'top=150, left=250, height=500, width=1000, toolbar=no, status=no ,scrollbars=1,resizable=1');
		document.paymentDetailsByRfqId.target="_paymentDetailsWindow";
		document.paymentDetailsByRfqId.submit();
	},
	 viewQuotationEvaluationSpringCS : function(/*param,csrfToken*/) {
		qtnEvalExlForm.submit();
	} ,
	viewQuotationPartOneEvaluationSpringCS:function(/*param,csrfToken*/){
		document.qtnPartOneEvalExlForm.submit();
	},

	viewQuotationEvaluationCS:function(rfqPartNumber){
		document.qtnEvalExlForm.partNo.value = rfqPartNumber;
		document.qtnEvalExlForm.partNumber.value = rfqPartNumber;
		document.qtnEvalExlForm.submit();
	},

	showSellerAttachments : function(rfqId,partNo){
		document.sellerAttachments.rfqId.value = rfqId;
		document.sellerAttachments.partNo.value = partNo;
		document.sellerAttachments.submit();
	},
	getUsers : function() {
		Controller.onSubmit(null,null,'getWFTransfers',null);
	},
	selectTransfer : function(/*int*/ id,/*int*/ categoryId,srcUser,dstUser,startDate,endDate)
	{
		pageScope["transfer"] = { "id" : id , "procCatId" : categoryId,"srcUser" : srcUser, "dstUser" : dstUser,
								   "startDate" : startDate, "endDate" : endDate};
		if(sessionScope["_currPrivId"] == 116)
		{
			$("#editTransfer").css("display","inline");
		}
	},
	selectTenderCom : function(id, code, description, createDate, updateDate)
	{
		pageScope["tenderCom"] = { "id" : id , "code" : code,"description" : description,
								   "createDate" : createDate, "updateDate" : updateDate};
		if(sessionScope["_currPrivId"] == 118)
		{
			$("#viewTenderCom").css("display","inline");
		}
	},
	signNoteSheet: function (pkiEnable,formName,csrfToken,buttonValue,status){
		if(attachmentController.validateFileName(formName)==false){return false;}
		var valid =true;

		if(pkiEnable){
			var concatText=$("input[name='entityId']","#"+formName).val()+"#|#"+$("input[name='entityTypeId']","#"+formName).val()+"#|#"+$("input[name='partNumber']","#"+formName).val()+"#|#"+$("input[name='createId']","#"+formName).val();
			valid = valid && signDocument(concatText);
		}
		$("input[name='entityId']","#"+formName).val();
		$("input[name='status']","#"+formName).val(status);
		$("input[name='work.status']","#"+formName).val(status);
		$("input[name='buttonValue']","#"+formName).val(buttonValue);
		if(valid && Controller.alertSignHashFile()){
			document.getElementById("wholeOverlayCSS").style.display="block";
			document.getElementById("cover").style.display="block";
			document.noteSheetForm.submit();
		}
	},
	addWorkAttach : function (/*String*/ tableId,pkiEnable)
	{
	    //alert(pkiEnable);
	    tbody=document.getElementById(tableId);
	    var index = tbody.rows.length - 2;
	    if (index<0) index=0;
	    if (!attachmentController.validateAttach(index)) return;
	    var newRow=tbody.insertRow(tbody.rows.length);
	    var cell0 = newRow.insertCell(0);
	    cell0.setAttribute('class','dataClass');
	    cell0.innerHTML = "<input type='text'  id='attachments["+index+"].label' name='attachments["+index+"].label' />";

	    var cell1 = newRow.insertCell(1);
	  	cell1.setAttribute('class','dataClass');
	  	cell1.innerHTML = "<input type='text' size='20' name='attachments["+index+"].fileName' id='attachments["+index+"].fileName' onblur='javascript:WFController.checkApproveFlowFileName("+index+");'/><input type='hidden' id='attachments["+index+"].digitalCert.signHash' name='attachments["+index+"].digitalCert.signHash'/><label style='color :red ; float:left' id=msg["+index+"].fileName name=msg["+index+"].fileName></label>";

	   	var cell2 = newRow.insertCell(2);
	  	cell2.setAttribute('class','dataClass');
	  	cell2.innerHTML = '<input type="file" size="20" id="attachments['+index+'].file" name="attachments['+index+'].file" onmouseout="javascript:WFController.attachmentDetails('+index+');"/>';

	  	var cell3 = newRow.insertCell(3);
	  	cell3.innerHTML="";//"<a class='pageContentLink' href='javascript:attachmentController.delAttach(attachTab,"+index+");'>DELETE ROW</a>";
	  	if(pkiEnable == 'true'){
		  	var cell4 = newRow.insertCell(4);
		 // 	cell4.innerHTML = '<input type="button"class="epsSubmit"  value="SIGN FILE" onClick="WFController.signWorkAttachmentFile('+index+');"/>';
		 	  	cell4.innerHTML = "<a class='pageContentLink' href='javascript:WFController.signWorkAttachmentFile("+index+");'>SIGN FILE</a>";
	  	}
	},

	signNoteSheetWork : function (pkiEnable,formname,methodName,buttonValue,csrfToken,status,userId){
		var valid = true;
		var rfqStatus = 'X';

		var comment = document.getElementById("work.currentFlow.comment");
		if (comment !== null) {
			if(comment.value == '') {
				alert("Please enter some comments");
				return false;
			}
		}

		var flowId = $("input[name='work.currentFlow.id']").val();

		if(pkiEnable){
			//var concatText = status+'#|#'+document.getElementById("work.currentFlow.comment").value;
			var concatText = flowId+'#|#'+userId;
			var resultHash = signText(concatText);
			document.getElementById("work.currentFlow.digitalCert.signHash").value = resultHash;
			var certStr = getClientCertString();
			document.getElementById("work.currentFlow.digitalCert.publicKey").value = getPublicKeyStrFromCertStr(certStr);
			document.getElementById("work.currentFlow.digitalCert.clientCertString").value = certStr;
			document.getElementById("work.currentFlow.digitalCert.certSerialNo").value = getSrNoFromCertStr(certStr);
			document.getElementById("work.currentFlow.digitalCert.expiryDate").value = getFmtExpiryDateFromCertStr(certStr,'yyyy-MM-dd HH:mm:ss');
			document.getElementById("work.currentFlow.digitalCert.thumbPrint").value = getThumbprintFromCertStr(certStr)
			document.getElementById("work.currentFlow.digitalCert.clientCertSubject").value = getSubjectDNFromCertStr(certStr);

			if(resultHash==null || resultHash=='' ){
				valid = false;
			}
		}

		$("input[name='work.currentFlow.workStatus']").val(status);
		$("input[name='work.currentFlow.status']").val(status);
		$("input[name='buttonValue']","#"+formname).val(buttonValue);

		if(confirm("Do you want to proceed?") && valid  && Controller.alertSignHashFile()){
			eval("document."+formname).action = contextRoot + "/business/work.handle";
			eval("document."+formname).methodName.value = methodName;
			document.getElementById("wholeOverlayCSS").style.display="block";
			document.getElementById("cover").style.display="block";
			Controller.onSubmitWithCsrf(formname,csrfToken,methodName,null,null);
			return valid;
		}else{
			return false;
		}
	},

	signWork : function signWork(pkiEnable,formname,methodName,csrfToken,status,userId){
		var valid = true;
		var rfqStatus = 'X';

		var comment = document.getElementById("currentFlow.comment");
		if (comment !== null) {
			if(comment.value == '') {
				alert("Please enter some comments");
				return false;
			}
		}

		$("input[name='currentFlow.workStatus']").val(status);
		$("input[name='currentFlow.status']").val(status);
		var flowId = $("input[name='currentFlow.id']").val();

		if(pkiEnable){
			for(var i=0;i<document.getElementsByName("currentFlow.workStatus").length;i++){
				if(document.getElementsByName("currentFlow.workStatus").item(i).checked){
				var status = document.getElementsByName("currentFlow.workStatus").item(i).value;
				if(status=='APPROVE')rfqStatus = 'A';
				if(status=='REVIEW')rfqStatus = 'W';
				break;
			}
			}
			//var concatText = status+'#|#'+document.getElementById("currentFlow.comment").value;
			var concatText = flowId+'#|#'+userId;
			var resultHash = signText(concatText);
			document.getElementById("currentFlow.digitalCert.signHash").value = resultHash;
			var certStr = getClientCertString();
			document.getElementById("currentFlow.digitalCert.publicKey").value = getPublicKeyStrFromCertStr(certStr);
			document.getElementById("currentFlow.digitalCert.clientCertString").value = certStr;
			document.getElementById("currentFlow.digitalCert.certSerialNo").value = getSrNoFromCertStr(certStr);
			document.getElementById("currentFlow.digitalCert.expiryDate").value = getFmtExpiryDateFromCertStr(certStr,'yyyy-MM-dd HH:mm:ss');
			document.getElementById("currentFlow.digitalCert.thumbPrint").value = getThumbprintFromCertStr(certStr)
			document.getElementById("currentFlow.digitalCert.clientCertSubject").value = getSubjectDNFromCertStr(certStr);
				var code = document.getElementById("documentCode").value;
				var partCount = document.getElementById("partCount").value;
				var ownerId = document.getElementById("owner.id").value;
				var rfqKey = code + '#|#' + partCount + '#|#' + ownerId + '#|#' + rfqStatus;
				var rfqHash = signText(rfqKey);
				document.getElementById("digitalCert.signHash").value = rfqHash;
			if(resultHash==null || resultHash=='' || rfqHash==null || rfqHash==''){
				valid = false;
			}
		}

		if(confirm("Do you want to proceed?") && valid && Controller.alertSignHashFile()){
			/*document.getElementById("wholeOverlayCSS").style.display="block";
			document.getElementById("cover").style.display="block";*/
			eval("document."+formname).action = contextRoot + "/business/work.action";
			eval("document."+formname).methodName.value = methodName;
			document.getElementById(formname).submit();
			
			return valid;
		}else{
			return false;
		}
	},

	 initApproval : function(){
	  Controller.onSubmit('workCatForm',null,'getWFApprovers',null,null);
	},
	signWorkAttachmentFile :function(index){
		var valid = true;
		var fileField='attachments['+index+'].file';
		var elementName='attachments['+index+'].digitalCert.signHash';
		var filePath= document.getElementById(fileField).value;
		//alert("elementName "+elementName);
		//alert("111"+$("input[name='"+elementName+"']").val());
		//alert($("textarea[name='description']").val());
		valid = signFileAndAssignValue(filePath,elementName);
	},
	signWorkAttachment :function(index){
		var valid = true;
		var fileField='work.attachments['+index+'].file';
		var elementName='work.attachments['+index+'].digitalCert.signHash';
		var filePath= document.getElementById(fileField).value;
		//alert("elementName "+elementName);
		valid = signFileAndAssignValue(filePath,elementName);
	},
	signWorkFlowAttachmentFile :function(index){
		var valid = true;
		var fileField='currentFlow.attachments['+index+'].file';
		var elementName='currentFlow.attachments['+index+'].digitalCert.signHash';
		var filePath= document.getElementById(fileField).value;
		//alert("elementName "+elementName);
		valid = signFileAndAssignValue(filePath,elementName);
	},
	transferWorkTo:function(formName,csrfToken){
		Controller.onSubmitWithCsrf(formName,csrfToken,"updateWorkStatus",null,null);
	},

	transferWorkToV2:function(formName,csrfToken){
		//alert("Check");
		var userId = eval("document."+formName).userId.value;
		if(userId == 0){
			alert("Please select proper user name");
			//return false;
		}else{
			eval("document."+formName).submit();
		}
	},

	addWorkFlowAttach : function (/*String*/ tableId,pkiEnable)
	{
	    //alert("in moreRow");
		tbody=document.getElementById(tableId);
		var index = tbody.rows.length - 2;
	    if (index<0) index=0;
	    if (!attachmentController.validateAttach(index)) return;
	    var newRow=tbody.insertRow(tbody.rows.length);
	    //newRow.setAttribute('id','row_'+index);
	    var cell0 = newRow.insertCell(0);
	    cell0.setAttribute('class','dataClass');
	    cell0.innerHTML = '<input type="text" size="20" name="currentFlow.attachments['+index+'].label" id="attachments['+index+'].label"/>';

	    var cell1 = newRow.insertCell(1);
	  	cell1.setAttribute('class','dataClass');
	  	cell1.innerHTML = '<input type="text" size="20" name="currentFlow.attachments['+index+'].fileName" id="attachments['+index+'].fileName" onblur="javascript:WFController.checkApproveFlowFileName('+index+')"/><input type="hidden" id="currentFlow.attachments['+index+'].digitalCert.signHash" name="currentFlow.attachments['+index+'].digitalCert.signHash"/><label style="color :red ; float:left" id=msg['+index+'].fileName name=msg['+index+'].fileName></label>';

	   	var cell2 = newRow.insertCell(2);
	  	cell2.setAttribute('class','dataClass');
	  	cell2.innerHTML = '<input type="file" size="20" id="attachments['+index+'].file" name="currentFlow.attachments['+index+'].file" onmouseout="javascript:WFController.attachmentDetails('+index+');"/>';

	  	var cell3 = newRow.insertCell(3);
	  	cell3.innerHTML='';
	  	if(pkiEnable=='true'){
		  	var cell4 = newRow.insertCell(4);
//				cell4.innerHTML = '<input type="button" class="epsSubmit" value="SIGN FILE" onClick="WFController.signWorkFlowAttachmentFile('+index+');"/>';
				cell4.innerHTML = '<a class="pageContentLink" href="javascript:WFController.signWorkFlowAttachmentFile('+index+');">SIGN FILE</a>';
	  	}
	},


	delAttach :function(/*String*/tabId,/*int*/listSize)
	{

		tbody = document.getElementById(tabId);
		var length = tbody.rows.length - (2+listSize);
		//alert(tbody.rows.length);

		if(length==0){
			alert("No attachements to be deleted.");
		}
		else{
			if (confirm('Delete The Attachment?')) tbody.deleteRow(tbody.rows.length-1);
		}

	},

	checkApproveFlowFileName : function(index){
		var requiredfileNameValue = document.getElementById("attachments["+index+"].fileName").value;
		var fileNameValue = requiredfileNameValue.split(".")[0];
		var alphaNumericUnderScorePattern = /[^a-zA-Z0-9 _]/; //[^a-zA-Z ]/;
		if(alphaNumericUnderScorePattern.test(fileNameValue) == false) {
			document.getElementById("attachments["+index+"].fileName").value = fileNameValue;
			document.getElementById("msg["+index+"].fileName").innerHTML = "";
			return true;
		}
		else{
			document.getElementById("attachments["+index+"].fileName").value = "";
			document.getElementById("attachments["+index+"].label").value = "";
			document.getElementById("msg["+index+"].fileName").innerHTML = "Avoid special characters";
			var ctrl = document.getElementById("attachments["+index+"].file");
			ctrl.parentNode.replaceChild(ctrl.cloneNode(true), ctrl);
			return false;
		}
	},

	attachmentDetails:function(/*int*/ index){
		var fileLabel = document.getElementById("attachments["+index+"].label").value;
		var fileName= document.getElementById("attachments["+index+"].fileName").value;
		var fileBrowse= document.getElementById("attachments["+index+"].file").value;
		var requiredfilename = fileBrowse.replace(/^.*[\\\/]/, '');
		var filenameWithOutExtension = requiredfilename.split(".")[0];
		//alert("filenameWithOutExtension>>>"+filenameWithOutExtension);
		//alert("fileName>>>"+fileName);
		//alert("fileBrowse>>>"+fileBrowse);
		if(fileLabel==''&& fileName==''&&fileBrowse==''){
		}
		if(fileLabel==''&& fileName!=''&&fileBrowse!=''){
		document.getElementById("attachments["+index+"].label").value=fileName;
		document.getElementById("attachments["+index+"].fileName").value=fileName;
		}
		if(fileLabel!=''&& fileName==''&&fileBrowse!=''){
		document.getElementById("attachments["+index+"].fileName").value=fileLabel;
		}
		if(fileLabel==''&& fileName==''&&fileBrowse!=''){
		document.getElementById("attachments["+index+"].label").value=filenameWithOutExtension;
		document.getElementById("attachments["+index+"].fileName").value=filenameWithOutExtension;
		}
},
	addWorkFlowQualAttach :function  (/*String*/ tableId,pkiEnable){
	    //alert("in moreRow");
	    tbody=document.getElementById(tableId);
	    var index = tbody.rows.length - 2;
	    if (index<0) index=0;
	    if (!attachmentController.validateAttach(index)) return;
	    var newRow=tbody.insertRow(tbody.rows.length);
	    var cell0 = newRow.insertCell(0);
	    cell0.setAttribute('class','dataClass');
	    cell0.innerHTML = '<input type="text" size="20" name="work.currentFlow.attachments['+index+'].label" id="work.currentFlow.attachments['+index+'].label"/>';

	    var cell1 = newRow.insertCell(1);
	  	cell1.setAttribute('class','dataClass');
	  	cell1.innerHTML = '<input type="text" size="20" name="work.currentFlow.attachments['+index+'].fileName" id="work.currentFlow.attachments['+index+'].fileName" onblur="javascript:WFController.currentFlowCheckFileName('+index+')"/><input type="hidden" id="work.currentFlow.attachments['+index+'].digitalCert.signHash" name="work.currentFlow.attachments['+index+'].digitalCert.signHash" /> <label style="color :red ; float:left" id=msg['+index+'].fileName name=msg['+index+'].fileName></label>';

	   	var cell2 = newRow.insertCell(2);
	  	cell2.setAttribute('class','dataClass');
	  	cell2.innerHTML = '<input type="file" size="20" id="work.currentFlow.attachments['+index+'].file" name="work.currentFlow.attachments['+index+'].file" onmouseout="javascript:WFController.currentFlowAttachmentDetails('+index+');"/>';

	  	var cell3 = newRow.insertCell(3);
	  	cell3.innerHTML='';//'<a class="pageContentLink" href="javascript:attachmentController.delAttach(attachTab,'+index+');">DELETE ROW </a>';
	  	if( pkiEnable == true|| pkiEnable == 'true'){
		  	var cell4 = newRow.insertCell(4);
//		  	cell4.innerHTML = '<input type="button" class="epsSubmit" value="SIGN FILE" onClick="WFController.signWorkFlowAttachmentQualFile('+index+');"/>';
			cell4.innerHTML = '<a class="pageContentLink" href="javascript:WFController.signWorkFlowAttachmentQualFile('+index+');">SIGN FILE</a>';
	  	}
	},

	currentFlowCheckFileName : function(index){
		var requiredfileNameValue = document.getElementById("work.currentFlow.attachments["+index+"].fileName").value;
		var fileNameValue = requiredfileNameValue.split(".")[0];
		var alphaNumericUnderScorePattern = /[^a-zA-Z0-9 _]/; //^\w+$/; // /[^a-zA-Z ]/;
		if(alphaNumericUnderScorePattern.test(fileNameValue)) {
			document.getElementById("work.currentFlow.attachments["+index+"].fileName").value = "";
			document.getElementById("work.currentFlow.attachments["+index+"].label").value = "";
			document.getElementById("msg["+index+"].fileName").innerHTML = "Avoid special characters";
			var ctrl = document.getElementById("work.currentFlow.attachments["+index+"].file");
			ctrl.parentNode.replaceChild(ctrl.cloneNode(true), ctrl);
			return false;
		}
		else{
			document.getElementById("work.currentFlow.attachments["+index+"].fileName").value = fileNameValue;
			document.getElementById("msg["+index+"].fileName").innerHTML = "";
			return true;

		}
	},

	currentFlowAttachmentDetails:function(/*int*/ index){
		var fileLabel = document.getElementById("work.currentFlow.attachments["+index+"].label").value;
		var fileName= document.getElementById("work.currentFlow.attachments["+index+"].fileName").value;
		var fileBrowse= document.getElementById("work.currentFlow.attachments["+index+"].file").value;
		var requiredfilename = fileBrowse.replace(/^.*[\\\/]/, '');
		var filenameWithOutExtension = requiredfilename.split(".")[0];
		//alert("filenameWithOutExtension>>>"+filenameWithOutExtension);
		//alert("fileName>>>"+fileName);
		//alert("fileBrowse>>>"+fileBrowse);
		if(fileLabel==''&& fileName==''&&fileBrowse==''){
		}
		if(fileLabel==''&& fileName!=''&&fileBrowse!=''){
		document.getElementById("work.currentFlow.attachments["+index+"].label").value=fileName;
		document.getElementById("work.currentFlow.attachments["+index+"].fileName").value=fileName;
		}
		if(fileLabel!=''&& fileName==''&&fileBrowse!=''){
		document.getElementById("work.currentFlow.attachments["+index+"].fileName").value=fileLabel;
		}
		if(fileLabel==''&& fileName==''&&fileBrowse!=''){
		document.getElementById("work.currentFlow.attachments["+index+"].label").value=filenameWithOutExtension;
		document.getElementById("work.currentFlow.attachments["+index+"].fileName").value=filenameWithOutExtension;
		}
     },
	 signWorkFlowAttachmentQualFile :function (index){
		var valid = true;
		var fileField='work.currentFlow.attachments['+index+'].file';
		var elementName='work.currentFlow.attachments['+index+'].digitalCert.signHash';
		var filePath= document.getElementById(fileField).value;
		//alert("elementName "+elementName);
		//alert($("#textarea[name='description']").val());
		valid = signFileAndAssignValue(filePath,elementName);
	},
	addWorkAttachment : function (/*String*/ tableId,pkiEnable)
	{
	    //alert("tableId"+tableId);
	    tbody=document.getElementById(tableId);
	    var index = tbody.rows.length - 2;
	    //alert("tbody.rows.length"+tbody.rows.length);
	    if (index<0) index=0;
	    if (!attachmentController.validateAttach(index)) return;
	    var newRow=tbody.insertRow(tbody.rows.length);
	    var cell0 = newRow.insertCell(0);
	    cell0.setAttribute('class','dataClass');
	    cell0.innerHTML = '<input type="text" size="20" name="work.attachments['+index+'].label" id="work.attachments['+index+'].label"/>';

	    var cell1 = newRow.insertCell(1);
	  	cell1.setAttribute('class','dataClass');
	  	cell1.innerHTML = '<input type="text" size="20" name="work.attachments['+index+'].fileName" id="work.attachments['+index+'].fileName" onblur="javascript:WFController.checkFileName('+index+')"/><input type="hidden" id="work.attachments['+index+'].digitalCert.signHash" name="work.attachments['+index+'].digitalCert.signHash"/><label style="color :red ; float:left" id=msg['+index+'].fileName name=msg['+index+'].fileName></label>';

	   	var cell2 = newRow.insertCell(2);
	  	cell2.setAttribute('class','dataClass');
	  	cell2.innerHTML = '<input type="file" size="20" id="work.attachments['+index+'].file" name="work.attachments['+index+'].file" onmouseout="javascript:WFController.workAttachmentDetails('+index+');"/>';

	  	var cell3 = newRow.insertCell(3);
	  	cell3.innerHTML='';//'<a class="pageContentLink" href="javascript:attachmentController.delAttach(attachTab,'+index+');">DELETE ROW</a>';
	  	if(pkiEnable == 'true'){
		  	var cell4 = newRow.insertCell(4);
		 // 	cell4.innerHTML = '<input type="button" class="epsSubmit" value="SIGN FILE" onClick="WFController.signWorkAttachment('+index+');"/>';
			cell4.innerHTML = '<a class="pageContentLink" href="javascript:WFController.signWorkAttachment('+index+');">SIGN FILE</a>';
	  	}
	},
	checkFileName : function(index){
		var requiredfileNameValue= document.getElementById("work.attachments["+index+"].fileName").value;
		var fileNameValue = requiredfileNameValue.split(".")[0];
		var splChars =  /[^a-zA-Z0-9 _]/;  ///^\w+$/; // /[^a-zA-Z ]/;
		if(splChars.test(fileNameValue)) {
			document.getElementById("work.attachments["+index+"].fileName").value="";
			document.getElementById("work.attachments["+index+"].label").value="";
			document.getElementById("msg["+index+"].fileName").innerHTML="Avoid special characters";
			var ctrl = document.getElementById("work.attachments["+index+"].file");
			ctrl.parentNode.replaceChild(ctrl.cloneNode(true), ctrl);
		    return false;
		}
		else{
			document.getElementById("work.attachments["+index+"].fileName").value=fileNameValue;
			document.getElementById("msg["+index+"].fileName").innerHTML=" ";
			return true;
		}

	},

	workAttachmentDetails:function(/*int*/ index){
		var fileLabel = document.getElementById("work.attachments["+index+"].label").value;
		var fileName= document.getElementById("work.attachments["+index+"].fileName").value;
		var fileBrowse= document.getElementById("work.attachments["+index+"].file").value;
		var requiredfilename = fileBrowse.replace(/^.*[\\\/]/, '');
		var filenameWithOutExtension = requiredfilename.split(".")[0];
		//alert("filenameWithOutExtension>>>"+filenameWithOutExtension);
		//alert("fileName>>>"+fileName);
		//alert("fileBrowse>>>"+fileBrowse);
		if(fileLabel==''&& fileName==''&&fileBrowse==''){
		}
		if(fileLabel==''&& fileName!=''&&fileBrowse!=''){
		document.getElementById("work.attachments["+index+"].label").value=fileName;
		document.getElementById("work.attachments["+index+"].fileName").value=fileName;
		}
		if(fileLabel!=''&& fileName==''&&fileBrowse!=''){
		document.getElementById("work.attachments["+index+"].fileName").value=fileLabel;
		}
		if(fileLabel==''&& fileName==''&&fileBrowse!=''){
		document.getElementById("work.attachments["+index+"].label").value=filenameWithOutExtension;
		document.getElementById("work.attachments["+index+"].fileName").value=filenameWithOutExtension;
		}
},
	viewDiscussion : function(id){

		//$("input[name='id']","#discussionForm").val(id);
		window.open('', 'formpopup', 'left=510, width=600,height=400,resizable=yes,scrollbars');
		document.discussionForm.target = 'formpopup';
		document.discussionForm.id.value=id;
		document.discussionForm.submit();
	},
	viewDiscussionDetails : function(formName, discussionId){
		window.open('', 'formpopup', 'left=100, width=1000,height=400,resizable=yes,scrollbars');
		eval("document."+formName).target = 'formpopup'
		eval("document."+formName).id.value = discussionId;
		eval("document."+formName).submit();
	},
	viewDiscussionPopDetails : function(formName, discussionId){

		window.open('', 'formpopup', 'left=100, width=1000,height=400,resizable=yes,scrollbars');
		eval("document."+formName).target = 'formpopup';
		eval("document."+formName).id.value = discussionId;
		eval("document."+formName).submit();
	},
	branchFlow :function(){
		document.branchForm.submit();
	},
	getQuotaionList :function(){
		document.quotationForm.submit();
	},
	verifyWorkFlow :function(updateId,flowId,clientCertString,signHash,userDigitalCertId){
		$("input[name='digitalCert.clientCertString']").val(clientCertString);
		$("input[name='digitalCert.signHash']").val(signHash);
		$("input[name='userDigitalCertId']").val(userDigitalCertId);
		var text = flowId+'#|#'+updateId;
		verifyDocument(text);
	},
	viewCorrigendum : function  (rfqId,crsfToken){
		//var urlString = "<c:url value='/business/corrigendum.handle'/>?methodName=viewCorrigendum&rfqId=<c:out value='${command.id}'/>&"+csrfToken
		var url = contextRoot+"/business/corrigendum.handle?methodName=viewCorrigendum&rfqId="+rfqId+"&"+crsfToken;
		alert("url"+url);
		window.open(url, 'viewCorrigendum_window', 'top=150, left=110, height=500, width=800, toolbar=no, status=no ,scrollbars=1,resizable=1');
	},
	discussionFormSubmit : function (pkiEnable)
	{
		var valid=true;

		if(pkiEnable)
		{
			var concatText=$("input[name='id']","#discussionForm").val()+"#|#"+$("input[name='userId']","#discussionForm").val();
			valid = valid && signDocument(concatText);

			$("input[name='digitalCert.publicKey']","#discussionForm").val($("input[name='digitalCert.publicKey']").val());
			$("input[name='digitalCert.clientCertString']","#discussionForm").val($("input[name='digitalCert.clientCertString']").val());
			$("input[name='digitalCert.certSerialNo']","#discussionForm").val($("input[name='digitalCert.certSerialNo']").val());
			$("input[name='digitalCert.expiryDate']","#discussionForm").val($("input[name='digitalCert.expiryDate']").val());
			$("input[name='digitalCert.thumbPrint']","#discussionForm").val($("input[name='digitalCert.thumbPrint']").val());
			$("input[name='digitalCert.clientCertSubject']","#discussionForm").val($("input[name='digitalCert.clientCertSubject']").val());
			$("input[name='digitalCert.signHash']","#discussionForm").val($("input[name='digitalCert.signHash']").val());
			$("input[name='digitalCert.id']","#discussionForm").val($("input[name='digitalCert.id']").val());
			$("input[name='digitalCert.certType']","#discussionForm").val($("input[name='digitalCert.certType']").val());

		}
		if(valid)
		{
			document.discussionForm.submit();
		}
	},
	getQuotationList : function (){
		document.searchForm.submit();
	},
	getWorkflowStatus : function (rfqId,workSpecCode,csrfToken){

	   Controller.loadData(contextRoot+"/business/work.handle?methodName=getWorkflowStatus&rfqId="+rfqId+"&worKSpecCode="+workSpecCode+"&"+csrfToken,null,
        	function(/*Object*/ data) {
		    var WORK_STATUS = data.map['WORK_STATUS'];
    		if(WORK_STATUS != 'APPROVED'){
			alert("YOU CAN'T VIEW THE QUOTATION BEFORE 'VIEW L1 SUPPLIER' APPROVAL");
            }else{
    			document.quotationSearchForm.action="getQuotationListAction.do";
    			document.quotationSearchForm.submit();
            }
    	});
	},
	checkWorkflowStatus : function(rfqId,workSpecCode,csrfToken){
		   Controller.loadData(contextRoot+"/business/work.handle?methodName=getWorkflowStatus&rfqId="+rfqId+"&worKSpecCode="+workSpecCode+"&"+csrfToken,null,
		        	function(/*Object*/ data) {
		    var RA_ENABLED = data.map['RA_ENABLED'];
		    var WORK_STATUS = data.map['WORK_STATUS'];
			if(RA_ENABLED == 'Y'){
					if(WORK_STATUS == 'OPEN'){
						alert("WORKFLOW HAS ALREADY BEEN INITIATED FOR THIS RFQ");
			        }else if(WORK_STATUS == 'APPROVED'){
			        	document.qtnEvalExlForm.L1DetailsDoc.value='Y';
			        	qtnEvalExlForm.submit();
			        }
					else{
			        	document.viewL1SupplierCSForm.submit();
			        }
			}else{
				alert("'L1 SUPPLIER CS' CAN ONLY BE DISPLAYED FOR RA ENABLED RFQ");
			}
    	});
	}


}

var QuotationController = {
	refreshParent : function() {
		if(!window.opener.location)
		window.opener.location = self;
		window.opener.viewConfigTemplateForm.itemCatFlag.value = "true";
		window.opener.viewConfigTemplateForm.methodName.value ="viewDocConfTemplateListDetails";
		window.opener.viewConfigTemplateForm.submit();
		window.close();
		},
	 	backToQuotationList :function(){
			document.quotationSearchForm.action="getQuotationListAction.do";
			document.quotationSearchForm.submit();
	    },
		returnLoadFactor : function(){
			var loadFactor = document.getElementById("loadFactor").value;
			var qItemId = document.getElementById("id").value;
			var loadAttributeId = document.getElementById("loadAttributeId").value;
			//alert("loadAttributeId: "+loadAttributeId);
			//alert("the element:- "+'quotationItemLoadFactor('+qItemId+'_'+loadAttributeId+')');
			opener.document.getElementById('quotationItemLoadFactor('+qItemId+'_'+loadAttributeId+')').value=loadFactor;
			opener.document.getElementById('quotationItemLoadFactor('+qItemId+'_'+loadAttributeId+')').focus();
			window.close();
		},
		decryptQuotation : function(/*String*/ actionName,csrfToken) {
			 itemLength = document.getElementsByName("decryptQuotation").length;
		        var data="";
		        for(i=0;i<itemLength;i++){
		        	if(document.getElementsByName("decryptQuotation").item(i).checked){
		           		quotationId = document.getElementsByName("decryptQuotation").item(i).value;
		           		data = data + quotationId + ",";
		        	}
		    	}
			    if(data!=""){
				    data = data.substring(0,data.length-1);
				    window.open(actionName+"?methodName=getQuotationHeaderByQuotationId&data="+data+"&"+csrfToken+"&auctionEnabled='N'","_blank");
			    }
	},
	decryptQuotationConfirm : function(/*String*/ actionName,csrfToken,auctionEnabled,partNo,isDgh) {
		//confirm("Do you want to enable auction?","Yes","No",QuotationController.decryptQuotation(actionName,csrfToken));
		var buyerOrgId= document.getElementById("organizationId").value;
		var lngOrgId = document.getElementById("lngOrgId").value;
		var ongcOrgId = document.getElementById("ongcOrgId").value;
		var ongcKGD6OrgId = document.getElementById("ongcKGD6OrgId").value;
		
		
		itemLength = document.getElementsByName("decryptQuotation").length;
		var countAll=0;
		var countSelected=0;
		for(i=0;i<itemLength;i++){
			
			countAll++;
        	if(document.getElementsByName("decryptQuotation").item(i).checked){
        		countSelected++;
           		
        	}
    	}
		
		if(auctionEnabled=='N' && partNo==2 && isDgh && (buyerOrgId==ongcOrgId || buyerOrgId==ongcKGD6OrgId) && countAll==countSelected){
			if(confirm("Do you want to enable auction?")){
		       //* itemLength = document.getElementsByName("decryptQuotation").length;
		        var data="";
		        for(i=0;i<itemLength;i++){
		        	if(document.getElementsByName("decryptQuotation").item(i).checked){
		           		quotationId = document.getElementsByName("decryptQuotation").item(i).value;
		           		data = data + quotationId + ",";
		        	}
		    	}
			    if(data!=""){
				    data = data.substring(0,data.length-1); 
				    window.open(actionName+"?methodName=getQuotationHeaderByQuotationId&data="+data+"&"+csrfToken+"&auctionEnabled=Y","_blank");
			    }
			} else{
				 //*itemLength = document.getElementsByName("decryptQuotation").length;
			        var data="";
			        for(i=0;i<itemLength;i++){
			        	if(document.getElementsByName("decryptQuotation").item(i).checked){
			           		quotationId = document.getElementsByName("decryptQuotation").item(i).value;
			           		data = data + quotationId + ",";
			        	}
			    	}
				    if(data!=""){
					    data = data.substring(0,data.length-1);
					    window.open(actionName+"?methodName=getQuotationHeaderByQuotationId&data="+data+"&"+csrfToken+"&auctionEnabled=N","_blank");
				    }
			}
		} else{
			//itemLength = document.getElementsByName("decryptQuotation").length;
	        var data="";
	        for(i=0;i<itemLength;i++){
	        	if(document.getElementsByName("decryptQuotation").item(i).checked){
	           		quotationId = document.getElementsByName("decryptQuotation").item(i).value;
	           		data = data + quotationId + ",";
	        	}
	    	}
		    if(data!=""){
			    data = data.substring(0,data.length-1);
			    window.open(actionName+"?methodName=getQuotationHeaderByQuotationId&data="+data+"&"+csrfToken+"&auctionEnabled=NA","_blank");
		    }
		}
	
},
	viewQuotationComments :function(/*int*/quotationId,/*int*/userId) {
		var urlString = contextRoot+'/business/quotation.action?methodName=viewQuotationComments&popUp=Y&quotationId='+quotationId+'&userId='+userId;
		window.open(urlString, 'userContactView_window', 'top=0, left=400, height=600, width=600, toolbar=no, status=no, scrollbars=yes, resizable=yes');
	},
	addQuotationComment :function(/*int*/ qtnId){
		document.addCommentForm.id.value = qtnId;
		//document.addCommentForm.workId.value = workId;
		//document.addCommentForm.currentFlowId.value = currentFlowId;
		document.addCommentForm.submit();
	},
	auctionTermAcceptance :function(pkiEnable,userID){
		var auctionID = document.getElementById("auctionID").value;
		var concatText = auctionID +'#|#'+userID;
		var valid = true;
		if(pkiEnable){
			var valid = signDocumentAndAsingnValue(concatText, 'digitalCert.signHash');
		}
//		1 signifies term and condition accepted & 0 signifies not accepted
		var termAcceptance = 1;
		if (document.getElementById('termNotAccepted').checked) {
			var termAcceptance = document.getElementById("termNotAccepted").value;
			}
		var termComment = document.getElementById("termComment").value;
		if(confirm("Do you want to proceed?") && valid ){
			document.auctionAcceptanceForm.submit();
		}

	},
	getSelectedAucQuotation :function(){
		var aucQuotationID=$("input[name='quotSelect']:checked").val().split("|")[0];
		var status=$("input[name='quotSelect']:checked").val().split("|")[1];
		//alert(aucQuotationID+"-"+status);
		document.auctionAcceptanceForm.aucQuotation.value=aucQuotationID;
		document.auctionAcceptanceForm.aucStatus.value=status;
		document.auctionAcceptanceForm.submit();
	}
}

var DashBoardController = {

		backToDashBoard :function () {
			document.dashboardForm.methodName.value = "getDashBoard";
			document.dashboardForm.target = "_self";
			document.dashboardForm.submit();
		},
		goBacKToDashBoard :function (actionName,resetDocValue) {
			document.backToNonPkiDashBoardForm.resetDocForNonPki.value=resetDocValue;
			document.backToNonPkiDashBoardForm.action=actionName;
			document.backToNonPkiDashBoardForm.submit();
		},
		viewRfq : function(rfqId,rfqPartNumber, rfqStatus, rfqOwner) {
			//alert('PartNo: '+rfqPartNumber+'  | RfqId: '+rfqId +' | RfqStatus: '+ rfqStatus+'  | RfqOrner: '+ rfqOwner);

			eval(document.viewRfqForm).rfqId.value=rfqId;
			eval(document.viewRfqForm).documentStatus.value = rfqStatus;
			eval(document.viewRfqForm).documentOwner.value = rfqOwner;
			eval(document.viewRfqForm).rfqPartNumber.value = rfqPartNumber;

			document.viewRfqForm.submit();
		},
		changeCurrency : function(rfqId,rfqPartNumber, rfqStatus, rfqOwner , anyCurrDisplayFlag) {
			//alert('PartNo: '+rfqPartNumber+'  | RfqId: '+rfqId +' | RfqStatus: '+ rfqStatus+'  | RfqOrner: '+ rfqOwner);
			//alert(anyCurrDisplayFlag);
			if(confirm(" Do you want to proceed ? ")== true){
				eval(document.viewRfqForm).rfqId.value=rfqId;
				eval(document.viewRfqForm).documentStatus.value = rfqStatus;
				eval(document.viewRfqForm).documentOwner.value = rfqOwner;
				eval(document.viewRfqForm).rfqPartNumber.value = rfqPartNumber;
				eval(document.viewRfqForm).anyCurrDisplayFlag.value = anyCurrDisplayFlag;
				eval(document.viewRfqForm).methodName.value = 'changeCurrency';

				document.viewRfqForm.submit();
			}
		},
		respondToRfq : function(){
			document.dashboardForm.action="getRfqResponseAction.do";
			document.dashboardForm.target = "_self";
			document.dashboardForm.submit();
		},
		viewQuotationList: function(rfqCode,rfqStatus,rfqType,orgId) {
			//alert('rfqCode: '+rfqCode+'  | rfqStatus: '+rfqStatus +' | rfqType: '+ rfqType);

			eval(document.rfqSearchForm).documentCode.value=rfqCode;
			eval(document.rfqSearchForm).documentSearchStatus.value = rfqStatus;
			eval(document.rfqSearchForm).rfqType.value = rfqType;
			eval(document.rfqSearchForm).documentSearchOrganization.value = orgId;

			document.rfqSearchForm.submit();
		},
		viewDecryptionList: function(rfqId,partNo) {
			//alert('::::::: rfqId: '+rfqId + ' | partNo : '+ partNo);

			eval(document.rfqDecryptionForm).quotationRfqStatus.value = 'AAEO';
			eval(document.rfqDecryptionForm).quotationRfqId.value= rfqId;
			eval(document.rfqDecryptionForm).quotationRfqPartIdentifier.value=rfqId+"|"+partNo;

			document.rfqDecryptionForm.submit();
		},
		searchSupplierList : function ( methodName, resultDiv, searchReportType,userStatus){
			//alert("DASHBOARD ..  methodName= "+ methodName+", resultDiv= "+resultDiv+", searchReportType= "+ searchReportType);

			document.userSearchByUserInfoForm.searchReportType.value = searchReportType;
			document.userSearchByUserInfoForm.methodName.value = methodName;
			document.userSearchByUserInfoForm.userStatus.value = userStatus;
			document.userSearchByUserInfoForm.searchRequestFrom.value = 'fromDashboard';
			document.userSearchByUserInfoForm.target = "_self";
			document.userSearchByUserInfoForm.submit();
//			SearchController.searchWithForm('userSearchByUserInfoForm', ['lastId'], resultDiv);
		},
		dscPendingApproval : function(methodName, resultDiv, searchReportType) {
			//alert("DASHBOARD ..  methodName= "+ methodName+", resultDiv= "+resultDiv+", searchReportType= "+ searchReportType);

			document.dscPendingApprovalForm.searchReportType.value = searchReportType;
			document.dscPendingApprovalForm.methodName.value = methodName;
			document.dscPendingApprovalForm.searchRequestFrom.value = 'fromDashboard';
			document.dscPendingApprovalForm.target = "_self";

			SearchController.searchWithForm('dscPendingApprovalForm', ['lastId'], resultDiv);
		},
		issuedPODetails : function (methodName){

			document.purchaseOrderDetailsForm.methodName.value=methodName;
			document.purchaseOrderDetailsForm.target = "_self";
			document.purchaseOrderDetailsForm.submit();
		},
		pendingPODetails : function (methodName){
			//alert("pendingPODetails ..  methodName= "+ methodName);
			document.pendingPurchaseOrderDetailsForm.methodName.value=methodName;
			//document.pendingPurchaseOrderDetailsForm.action.value=action;
			document.pendingPurchaseOrderDetailsForm.target = "_self";
			document.pendingPurchaseOrderDetailsForm.submit();
		},
		getQuotationEval : function (rfqId,partNo,rfqOwnerId){
			//alert(rfqId+" , "+partNo+" , "+rfqOwnerId);
			document.evalForm1.quotationEvaluationRfq.value = rfqId;
			document.evalForm1.quotationEvaluationRfqPart.value = partNo;
			document.evalForm1.quotationRfqPartIdentifier.value=rfqId+"|"+partNo;
			document.evalForm1.partNumber.value = partNo;
			document.evalForm1.quotationEvaluationRfqOwner.value = rfqOwnerId;
			document.evalForm1.quotationRfqOwner.value = rfqOwnerId;
			//alert(document.evalForm1.quotationEvaluationRfq.value );
			document.evalForm1.submit();
		},
		 initiateQualFlow : function (rfqId,partNo,rfqOwnerId){
			document.initQualForm.id.value = rfqId;
			document.initQualForm.partNumber.value = partNo;
			document.initQualForm.quotationRfqOwner.value = rfqOwnerId;
			document.initQualForm.quotationRfqPartIdentifier.value=rfqId+"|"+partNo;
			document.initQualForm.submit();
		},
		loadAndEval : function (rfqId,partNo){
			document.loadAndEvalForm.id.value = rfqId;
			document.loadAndEvalForm.partNumber.value = partNo;
			document.loadAndEvalForm.quotationRfqPartIdentifier.value=rfqId+"|"+partNo;
			document.loadAndEvalForm.submit();
		},
		getQuotationLoad : function (rfqId,partNo,rfqOwnerId){
			document.loadForm1.action="getQuotationLoadAddAction.do";
			document.loadForm1.quotationEvaluationRfq.value = rfqId;
			document.loadForm1.quotationEvaluationRfqPart.value = partNo;
			document.loadForm1.quotationRfqPartIdentifier.value=rfqId+"|"+partNo;
			document.loadForm1.partNumber.value = partNo;
			document.loadForm1.quotationRfqOwner.value = rfqOwnerId;
			document.loadForm1.quotationEvaluationRfqOwner.value = rfqOwnerId;
			document.loadForm1.submit();
		},
		evaluationLoading : function(rfqId,partNo,partCount,rfqOwnerId){
			//alert("rfqId: "+rfqId+" partNo: "+partNo+" partCount: "+partCount);
			document.evaluateLoadingForm.id.value = rfqId;
			document.evaluateLoadingForm.rfqId.value = rfqId;
			document.evaluateLoadingForm.partNumber.value = partNo;
			document.evaluateLoadingForm.partCount.value = partCount;
			document.evaluateLoadingForm.quotationRfqPartIdentifier.value=rfqId+"|"+partNo;
			document.evaluateLoadingForm.quotationRfqOwner.value = rfqOwnerId;
			document.evaluateLoadingForm.submit();
		},
		archiveRfq : function(rfqId,partCount,csrfToken){
			//alert("rfqId: "+rfqId+", partCount: "+partCount+ " , token :"+csrfToken);
			document.rfqArchiveForm.rfqId.value = rfqId;
			document.rfqArchiveForm.partCount.value = partCount;

			if(confirm("Do you want to proceed?")){
				window.scroll(0,0);
				$(".ui-tooltip-content").parents('div').remove();
				Controller.onSubmitWithCsrf('rfqArchiveForm',csrfToken,null,null);

				var parentDiv = document.getElementById("archiveImage_"+rfqId);
				var button = document.getElementById("archiveButton_"+rfqId);
				parentDiv.removeChild(button);

				/*var ss = document.getElementsByClassName('ui-tooltip-content');
				alert(ss.length);
				for (var i = 0; i < len; i++) {
					ss[i].parentNode.removeChild(ss[i]);
				}

				$("#archiveButton_"+rfqId).removeAll();
				$("#archiveButton_"+rfqId).removeAttr("title");
				alert($("#archiveButton_"+rfqId).attr("class"));
				alert($("#archiveButton_"+rfqId).attr("title"));
				$( document ).tooltip({ tooltipClass: "custom-tooltip-styling" } );
				$("#archiveButton_"+rfqId).tooltip({ disabled: true });
				$(".ui-tooltip ui-widget ui-corner-all ui-widget-content custom-tooltip-styling").html("");
				document.getElementById("archiveButton_"+rfqId).disabled=true;
				var btn = document.getElementById("archiveButton_"+rfqId)
				btn.disabled=true;
				btn.setAttribute("title","XXXX");*/

				var elem = document.createElement("img");
				elem.setAttribute("src", "../image/tick.gif");
				elem.setAttribute("title", "Archived");
				//elem.setAttribute("height", "20");
				elem.style.height = '20px';
				elem.style.width = '20px';
				document.getElementById("archiveImage_"+rfqId).appendChild(elem);
				return true;
			}else{
				return false;
			}
		},

		assignAuditor : function(rfqId,partCount,partNumber,actionStatus,csrfToken){

			document.assignToAuditorForm.rfqId.value = rfqId;
			document.assignToAuditorForm.partCount.value = partCount;
			document.assignToAuditorForm.partNumber.value = partNumber;
			document.assignToAuditorForm.actionStatus.value = actionStatus;
			if(confirm("Do you want to proceed?")){
				window.scroll(0,0);
				$(".ui-tooltip-content").parents('div').remove();
				Controller.onSubmitWithCsrf('assignToAuditorForm',csrfToken,null,null);

				var elem = document.createElement("img");
				elem.setAttribute("src", "../image/tick.gif");
				elem.setAttribute("title", "Assigned To Auditor");
				elem.style.height = '20px';
				elem.style.width = '20px';

				/*if(actionStatus == 'assigned'){
                    var parentDiv = document.getElementById("auditorStatusDiv_"+rfqId);
                    var button = document.getElementById("auditorStatusButton_"+rfqId);
                    parentDiv.removeChild(button);
                    parentDiv.style.display = 'none';
                    var parent_new = document.getElementById("deAuditorStatusDiv_"+rfqId);

                    parent_new.innerHTML='<button type="button" id="deAuditorStatusButton_'+rfqId+'" class="epsSubmitNew" title="DeAssign To Auditor"       onclick="javascript:DashBoardController.assignAuditor('+rfqId+','+partCount+',\'deAssigned\',\''+csrfToken+'\');"> Deassign To Auditor</button>';
                    parent_new.style.display = 'block';
				}else if (actionStatus == 'deAssigned'){
                    var parentDiv = document.getElementById("deAuditorStatusDiv_"+rfqId);
                    var button = document.getElementById("deAuditorStatusButton_"+rfqId);
                    parentDiv.removeChild(button);
                    parentDiv.style.display = 'none';
                    var parent_new = document.getElementById("auditorStatusDiv_"+rfqId);

                    parent_new.innerHTML='<button type="button" id="auditorStatusButton_'+rfqId+'" class="epsSubmitNew" title="Assign To Auditor" onclick="javascript:DashBoardController.assignAuditor('+rfqId+','+partCount+',\'assigned\',\''+csrfToken+'\');">Assign To Auditor</button>';
                    parent_new.style.display = 'block';
				}*/
				return true;
			}else{
				return false;
			}
		},
		autoEval :function(rfqId,partNo){
			document.autoEval.rfqIdPartNo.value=rfqId+"|"+partNo;
			document.autoEval.submit();
		}

}

var SecurityController = {

	buttonSelector : function(/*String*/ buttonId, /*String*/ cerFileValidationArea){
		if(buttonId == 'exitOut'){
			document.cerFileUploadForm.submit();
		}

		if(buttonId == 'home'){
			document.cerFileUploadForm.action = contextRoot+"/security/getHomeAction.do";
			document.cerFileUploadForm.submit();
		}

		if(buttonId == 'proceed'){
			//alert("HOME");
			document.cerFileUploadForm.action = contextRoot+"/security/getHomeAction.do";
			document.cerFileUploadForm.submit();
		}

		if(buttonId == 'dashBoard'){
			//alert("DASH BOARD");
			document.cerFileUploadForm.methodName.value = "getDashBoard";
			document.cerFileUploadForm.action = contextRoot + "/business/dashboard.action";
			document.cerFileUploadForm.target = "_self";
			document.cerFileUploadForm.submit();
			/*
			document.cerFileUploadForm.action = contextRoot+"/security/getDashBoardAction.action";
			document.cerFileUploadForm.submit();*/
		}
		
		if(buttonId == 'generateOtp'){
			document.cerFileUploadForm.methodName.value = "generateOTP";
			document.cerFileUploadForm.action = contextRoot + "/business/security.action";
			document.cerFileUploadForm.target = "_self";
			document.cerFileUploadForm.submit();
		}
		
		if(buttonId == 'showRegisterDscDiv'){
			var registerDscDiv = document.getElementById('registerDscDiv');
			var viewDscDetailDiv = document.getElementById('viewDscDetailDiv');
			if (registerDscDiv.style.display == 'none') {
				registerDscDiv.style.display = 'block';
		    }
			if (viewDscDetailDiv.style.display != 'none') {
				viewDscDetailDiv.style.display = 'none';
		    }

			document.digitalCertAddForm.cerFileValidationArea.value = cerFileValidationArea;
		}

		if(buttonId == 'hideRegisterDscDiv'){
			var registerDscDiv = document.getElementById('registerDscDiv');
			if (registerDscDiv.style.display !== 'none') {
				registerDscDiv.style.display = 'none';
		    }
		}

		if(buttonId == 'hideViewDscDetailDiv'){
			var viewDscDetailDiv = document.getElementById('viewDscDetailDiv');
			if (viewDscDetailDiv.style.display !== 'none') {
				viewDscDetailDiv.style.display = 'none';
		    }
		}
	},



	generateDscListReport : function(/*String*/ formName, /*String*/ csrfToken, /*String*/ methodname){

		eval("document."+formName).methodName.value = methodname;
		eval("document."+formName).action = contextRoot + "/business/security.action";
		eval("document."+formName).target = "_self";
		eval("document."+formName).submit();
	},

	signCerFile : function (){
		var valid = true;
		var fileField='digitalCert.cerFile';
		var elementName='digitalCert.cerFileSignHash';
		var filePath= document.getElementById(fileField).value;
		valid = signFileAndAssignValue(filePath,elementName);
	},

	stoteCerFile : function(/*String*/ formName, /*String*/ csrfToken, /*String*/ methodName, /*String*/ cerFileValidationArea) {

		eval("document."+formName).methodName.value = methodName;
		eval("document."+formName).cerFileValidationArea.value = cerFileValidationArea;
		eval("document."+formName).action = contextRoot + "/business/security.action";
		eval("document."+formName).submit();
	},

	selectDigitalCert : function(/*int*/ digitalCertId, /*String*/ cerFileStatus, /*String*/ cerFileValidationArea) {

	    pageScope["digi"] = { "digitalCertId":digitalCertId, "cerFileValidationArea":cerFileValidationArea };

	    //$("#digiDtl").css("display","inline");
		//$("#addCerFile").css("display","inline");
	},

	submitDSC : function(/*String*/ fromName, /*String*/ parameter, /*String*/ methodName){
		var selected = false;
		var radios = document.getElementsByName('radioSelect');
		for (var i = 0; i < radios.length; i++) {
	        if (radios[i].checked) {
	        	selected = true;
	        }
		}

		if(!selected){
			alert("PLEASE SELECT ONE DIGITAL CERTIFICATE TO CONTINUE");
		}
		else{
			Controller.onSubmit(fromName, parameter, methodName, null, null);
		}
	},

	signDoc : function signDoc(/*String*/ formname){
		var selected = false;
		var radios = document.getElementsByName('selectOption');
		for (var i = 0; i < radios.length; i++) {
	        if (radios[i].checked) {
	        	selected = true;
	        }
		}

		if(!selected){
			alert("PLEASE SELECT ONE DIGITAL CERTIFICATE TYPE TO CONTINUE");
			return false;
		}

		var signData = null;
		var encryptionFlag = false;

			if($("input[name='selectOption']:checked").val()=="1"){

				signData = decryptText(null);
				encryptionFlag=true;
			}else{

				signData = signText('dummy');
			}

		if(getClientPublicKeyString() != null||encryptionFlag){
		var clientCertString = getClientCertString();
			//alert('----certSrNo: ' + getSrNoFromCertStr(clientCertString));
            //alert('-----certThumbPrint: ' + getThumbprintFromCertStr(clientCertString));
            //alert('--------clientCertStr: '+clientCertString);
            //alert('--------clientPubKey: '+ getPublicKeyStrFromCertStr(clientCertString));
           // alert('---------ExprDay: '+ getFmtExpiryDateFromCertStr(clientCertString,'yyyy-MM-dd HH:mm:ss'));
            //alert('clientCertSubject: '+ getSubjectDNFromCertStr(clientCertString));
            log('certSrNo: ' + getSrNoFromCertStr(clientCertString));
            log('certThumbPrint: ' + getThumbprintFromCertStr(clientCertString));
            log('clientCertStr: '+clientCertString);
            log('clientPubKey: '+ getPublicKeyStrFromCertStr(clientCertString));
            log('clientExprDay: '+ getExpiryDateFromCertStr(clientCertString));
            log('clientCertSubject: '+ getSubjectDNFromCertStr(clientCertString));
            displayCertInfo(clientCertString);
            $("input[name='digitalCert.certSerialNo']","#"+formname).val(getSrNoFromCertStr(clientCertString));
            $("input[name='digitalCert.thumbPrint']","#"+formname).val(getThumbprintFromCertStr(clientCertString));
            $("input[name='digitalCert.publicKey']","#"+formname).val(getPublicKeyStrFromCertStr(clientCertString));
            $("input[name='digitalCert.expiryDate']","#"+formname).val(getFmtExpiryDateFromCertStr(clientCertString,'yyyy-MM-dd HH:mm:ss'));
            $("input[name='digitalCert.clientCertString']","#"+formname).val(clientCertString);
            $("input[name='digitalCert.clientCertSubject']","#"+formname).val(getSubjectDNFromCertStr(clientCertString));
            $("input[name='digitalCert.certType']","#"+formname).val(getKeyUsageFromCertStr(clientCertString));
           // document.forms[formname].certSerialNo.value = getSrNoFromCertStr(clientCertString);
          //  document.forms[formname].thumbPrint.value = getThumbprintFromCertStr(clientCertString);
          //  document.forms[formname].publicKey.value = getPublicKeyStrFromCertStr(clientCertString);
           // document.forms[formname].expiryDate.value = getFmtExpiryDateFromCertStr(clientCertString,'yyyy-MM-dd HH:mm:ss');
           // document.forms[formname].clientCertString.value = clientCertString;
          //  document.forms[formname].clientCertSubject.value = getSubjectDNFromCertStr(clientCertString);

            Controller.onSubmit(formname,null,'storeDigitalCert',null,null);
         }
	},

	registerSigningDSC : function signDoc(/*String*/ formname){
		var signData = signText('dummy');
		var encryptionFlag = false;

		if(getClientPublicKeyString() != null || encryptionFlag){
			var clientCertString = getClientCertString();

            log('certSrNo: ' + getSrNoFromCertStr(clientCertString));
            log('certThumbPrint: ' + getThumbprintFromCertStr(clientCertString));
            log('clientCertStr: '+clientCertString);
            log('clientPubKey: '+ getPublicKeyStrFromCertStr(clientCertString));
            log('clientExprDay: '+ getExpiryDateFromCertStr(clientCertString));
            log('clientCertSubject: '+ getSubjectDNFromCertStr(clientCertString));

            $("input[name='digitalCert.certSerialNo']","#"+formname).val(getSrNoFromCertStr(clientCertString));
            $("input[name='digitalCert.thumbPrint']","#"+formname).val(getThumbprintFromCertStr(clientCertString));
            $("input[name='digitalCert.publicKey']","#"+formname).val(getPublicKeyStrFromCertStr(clientCertString));
            $("input[name='digitalCert.expiryDate']","#"+formname).val(getFmtExpiryDateFromCertStr(clientCertString,'yyyy-MM-dd HH:mm:ss'));
            $("input[name='digitalCert.clientCertString']","#"+formname).val(clientCertString);
            $("input[name='digitalCert.clientCertSubject']","#"+formname).val(getSubjectDNFromCertStr(clientCertString));
            $("input[name='digitalCert.certType']","#"+formname).val(getKeyUsageFromCertStr(clientCertString));

            eval("document."+formname).action = contextRoot + "/business/admin.action";
            eval("document."+formname).submit();
         }
	},
	getCertificateStatus : function (form,csrfToken){
		var formName = form.name;
		  Controller.loadData(contextRoot+"/business/security.handle?methodName=checkForSupplierEncCertificate&"+csrfToken,null,
	        	function(/*Object*/ data) {
		   		var KEY_ENCRYPTION_STATUS = data.map['KEY_ENCRYPTION_STATUS'];
		   		if(KEY_ENCRYPTION_STATUS != true){
		   			alert('Encryption DSC is either not mapped or expired. kindly map valid encryption DSC.');
		   			return ;
		   		}else{
		   			//document.qtnSubmitForm.submit();
		   			form.submit();
		   		}
		   });
		}

}

var InvoiceController = {
viewPayment : function (invoiceID){
		document.viewInvoiceForm.invoiceId.value = invoiceID;
		document.viewInvoiceForm.methodName.value = "getPayment";
		document.viewInvoiceForm.submit();
	},
addPayment : function(invoiceID){
		document.viewInvoiceForm.invoiceId.value = invoiceID;
		document.viewInvoiceForm.methodName.value = "initAddPayment";
		document.viewInvoiceForm.submit();
	},
viewInvoice : function(id,csrfToken){
		if(null == id)
		{
			alert("Please select an invoice");
			return;
		}
		Controller.loadPage(contextRoot+'/business/invoice.handle?methodName=getDoc&viewMode=true&id='+id+"&"+csrfToken,null,null);
	}
	,
printInvoice : function(invoiceId,orgId,orgName){
	document.invoicePrintForm.action = contextRoot + "/business/report.action";
   	document.invoicePrintForm.methodName.value = "showReport";
   	document.invoicePrintForm.reportName.value = "invoiceDtlViewPrint";
   	document.invoicePrintForm.popUp.value = "Y";
   	document.invoicePrintForm.invoiceId.value = invoiceId;
	document.invoicePrintForm.orgId.value = orgId;
	document.invoicePrintForm.orgName.value = orgName;
	document.invoicePrintForm.target="_blank";
   	document.invoicePrintForm.submit();
},

getInvoice : function getInvoice(invoiceId){
	document.viewInvoiceForm.invoiceId.value = invoiceId;
	document.viewInvoiceForm.submit();
},

viewInvoiceHdr : function(id,csrfToken){
		if(null == id)
		{
			alert("Please select an invoice");
			return;
		}
		Controller.loadPage(contextRoot+'/business/invoice.handle?methodName=getDoc&viewMode=true&hdrView=true&id='+id+"&"+csrfToken,null,null);
	}

}
var IRController = {
	saveAssignment : function(){
	  Controller.onSubmit('inspectionForm',null,'saveAssignment',null,null);
	}

}

var ProposalController = {

		searchInbox : function() {
			document.inboxForm.methodName.value = 'getInboxBySearch';
			document.inboxForm.submit();
		},


		changeRow :  function(){
			var trLength= $("#selectionTable tr").length;
			 var i=trLength-1;

			var numberRowLength=$("input[name='maxNumber']").val();
			var value = $("input[name='maxNumber']").val().replace(/^\s\s*/, '').replace(/\s\s*$/, '');
			var intRegex = /^\d+$/;
			if(!intRegex.test(value)) {
				 alert("Field must be numeric");
				 return false;
				  }
			if(parseInt(numberRowLength,10)>=parseInt(trLength,10)){
				while(parseInt(numberRowLength,10)>parseInt(i,10)){
					 $("#selectionTable tr:last").clone().find("select").attr("name","proposalCommitteeMap["+i+"]").attr("value","0").end().appendTo("#selectionTable");
					 $("#selectionTable tr:last").find($(".counterClass")).html(i+1);
					 		 i++;
					 		 }
				 }else{
				 	while(parseInt(numberRowLength,10)<parseInt(i,10)){
				 		$("#selectionTable tr:last").remove();
				 		i--;
				 	}
				 }
		},
		changeRowForProposalCommittee : function(){
			var trLength= $("#selectionTable tr").length;
			 var i=trLength-1;

			var numberRowLength=$("input[name='maxNumber']").val();
			var value = $("input[name='maxNumber']").val().replace(/^\s\s*/, '').replace(/\s\s*$/, '');
			var intRegex = /^\d+$/;
			if(!intRegex.test(value)) {
				 alert("Field must be numeric");
				 return false;
				  }
			if(parseInt(numberRowLength,10)>=parseInt(trLength,10)){
				while(parseInt(numberRowLength,10)>parseInt(i,10)){
					 $("#selectionTable tr:last").clone().find("select").attr("name","proposalCommitteeUserMap["+i+"]").attr("value","0").end().appendTo("#selectionTable");
					 $("#selectionTable tr:last").find($(".counterClass")).html(i+1);
					 		 i++;
					 		 }
				 }else{
				 	while(parseInt(numberRowLength,10)<parseInt(i,10)){
				 		$("#selectionTable tr:last").remove();
				 		i--;
				 	}
				 }
		},
		initAddPropComm : function(propCommId,formName,divId){
			if(propCommId == 0){
				$("#searchResult").empty();
				$("#proposalCommSearchPrev").css("display","none");
				$("#proposalCommSearchNext").css("display","none");
			}
			$("input[name='id']","#addPropCommForm").val(propCommId);
			SearchController.searchWithForm(formName,['id'],divId);
		},
		initAddPropCommRel : function(formName,divId){
			var priceRangeId = eval("document.proposalCommRelSearch").priceRangeId.value;
			if(priceRangeId==''){
				alert("Please first add Price Range for the Procurement Type");
				return;
			}
			$("input[name='proposalCategory.id']","#addPropCommRelForm").val($("select[name='procurementTypeId']","#proposalCommRelSearch").val());
			$("input[name='priceRange.id']","#addPropCommRelForm").val($("select[name='priceRangeId']","#proposalCommRelSearch").val());
			$("input[name='buUnit.buCode']","#addPropCommRelForm").val($("select[name='buCode']","#proposalCommRelSearch").val());
			SearchController.searchWithForm(formName,['proposalCategory.id','priceRange.id','buUnit.buCode'],divId);
		},
		getPriceRangeList : function(formName,divId){
			$("input[name='procurementTypeId']","#viewPriceRangeForm").val($("select[name='procurementTypeId']","#proposalCommRelSearch").val());
			SearchController.searchWithForm(formName,['procurementTypeId'],divId);
		},
		getPriceRangeListForProposalAdd : function(formName,divId){
			Util.clearContent($('#initialPriceRangeDiv'));
			$("input[name='procurementType.id']","#viewPriceRangeForm").val($("select[name='procurementType.id']","#proposalAddForm").val());
			SearchController.searchWithForm(formName,['procurementType.id'],divId);
		},
		initPriceRangeSave : function(formName,priceRangeId,procTypeId,csrfToken){
			if(procTypeId==0){
				alert("Select any Procurement Type");
				return;
			}
			var w =600;
	    	var h =250;

	    	var left = (screen.width/2)-(w/2);
	    	var top = (screen.height/2)-(h/2);
			window.open(contextRoot+'/business/proposal.handle?methodName=initPriceRangeSave&id='+priceRangeId+'&procurementType.id='+procTypeId+"&"+csrfToken, null, 'top='+top+', left='+left+', height='+h+', width='+w+', toolbar=no, status=no, scrollbars=yes ');
		},
		updateProcurementTypeStatus : function(procurementTypeId,description,status,csrfToken){
			var msg='';
			if(status=='A') msg = "ARE YOU SURE TO ACTIVATE THE PROCUREMENT TYPE "+description;
			else if(status=='X') msg = "ARE YOU SURE TO DEACTIVATE THE PROCUREMENT TYPE "+description;
			var open = confirm(msg);
  			if(open == true){
  				Controller.loadPage(contextRoot+'/business/proposal.handle?methodName=updateProcurementTypeStatus&status='+status+'&id='+procurementTypeId+'&description='+description+'&'+csrfToken,null,null);
  			}
		},
		viewProposal : function(id,csrfToken){
				if(null == id)
				{
					alert("Please select an Proposal");
					return;
				}
				Controller.loadPage(contextRoot+'/business/proposal.handle?methodName=getDoc&viewMode=true&id='+id+"&"+csrfToken,null,null);
		},
		viewProposalForVerify : function(id,csrfToken){
			if(null == id)
			{
				alert("Please select an Proposal");
				return;
			}
			Controller.loadPage(contextRoot+'/business/proposal.handle?methodName=getDoc&viewMode=true&id='+id+'&verify=true&'+csrfToken,null,null);
		},
		viewProposalForRecommend : function(id,csrfToken){
			if(null == id)
			{
				alert("Please select an Proposal");
				return;
			}
			Controller.loadPage(contextRoot+'/business/proposal.handle?methodName=getDoc&viewMode=true&id='+id+'&recommend=true&'+csrfToken,null,null);
		},
		viewProposalForApprove : function(id,workId,flowId,csrfToken){
			if(null == id)
			{
				alert("Please select an Proposal");
				return;
			}
			Controller.loadPage(contextRoot+'/business/proposal.handle?methodName=getDoc&viewMode=true&id='+id+'&work.id='+workId+'&work.currentFlow.id='+flowId+'&approve=true&'+csrfToken,null,null);
		},
		checkIfAllRowsFilledUp : function(lastIndex,msg,csrfToken) {
			var code=null;
			for (var i=lastIndex;i>=0;i--) {
				code =document.getElementById("docItemList["+i+"].heading").value ;
				if (code=='') {
					alert(msg);
					return false;
				}
			}
			document.getElementById("buttonValue").value = 'next';
			//Controller.onSubmit('orderitemAddForm',null,'saveDocItemList','next',null);
			Controller.onSubmitWithCsrf('proposalCSAddForm',csrfToken,'saveDocItemList','next');
			//return true;
		  },
		  saveDocItemList : function(formName,methodname,buttonName){
			  eval("document."+formName).buttonValue.value=buttonName;
			  //document.getElementById("buttonValue").value = buttonName;
			  Controller.onSubmit(formName,null,methodname,null,null);
			},
		  saveDocItemListWithCsrf : function(formName,methodname,buttonName,csrfToken){
			eval("document."+formName).buttonValue.value=buttonName;
			//document.getElementById("buttonValue").value = buttonName;
			Controller.onSubmitWithCsrf(formName,csrfToken,methodname,null,null);
		},
		printProposal : function(){

			document.printProposalForm.target = "_blank";
			document.printProposalForm.submit();
		},
		 moreRowForAttr : function(tableId,csSrlNo){
			  var tbl = document.getElementById(tableId);
			  var row = tbl.insertRow(tbl.rows.length);
			  for (var i=0; i<tbl.rows[0].cells.length; i++) {
				  var rowNo = tbl.rows.length;
				  ProposalController.createCell(row.insertCell(i), rowNo-1,i, 'row',csSrlNo);
			  }

		  },

		  moreColForAttr : function(tableId,csSrlNo){
			  var tbl = document.getElementById(tableId);
			  for (var i=0; i<tbl.rows.length; i++){
				  var colNo ;
				  if(i==0) colNo = tbl.rows[0].cells.length;
				  ProposalController.createCell(tbl.rows[i].insertCell(tbl.rows[i].cells.length),i, colNo, 'col',csSrlNo);
			  }
		  },
		  deleteLastRow : function(tableId){
			var tbl = document.getElementById(tableId);
			var lastRow = tbl.rows.length -1;
			//for (var i=lastRow; i>0; i--) tbl.deleteRow(i);
			if(lastRow!=0)
			tbl.deleteRow(lastRow);
		  },

		  deleteLastColumn : function(tableId){
			 var tbl = document.getElementById(tableId);
			 var lastCol = tbl.rows[0].cells.length - 1;
			 for (var i=0; i<tbl.rows.length; i++)   {
			  // for (var j=lastCol; j>0; j--) tbl.rows[i].deleteCell(j);
				 if(lastCol==0 && i==0){
				 }else{
				  tbl.rows[i].deleteCell(lastCol);
				 }
			  }
		  },
		  createCell : function(cell, rowIndex, colIndex ,style , index){
			 var div = document.createElement('div');
			 var inp = document.createElement('input');
			 if(rowIndex==0){
				 var columnAttrListIndex = colIndex-1;
				 inp.setAttribute("name","docItemList["+index+"].columnAttributeList["+columnAttrListIndex+"].description");
				 inp.setAttribute("id","docItemList["+index+"].columnAttributeList["+columnAttrListIndex+"].description");
				 inp.setAttribute("value", "COLUMN "+colIndex);
			 }
			 else if(colIndex==0){
				 var rowAttrListIndex = rowIndex-1;
				 inp.setAttribute("name","docItemList["+index+"].rowAttributeList["+rowAttrListIndex+"].description");
				 inp.setAttribute("id","docItemList["+index+"].rowAttributeList["+rowAttrListIndex+"].description");
				 inp.setAttribute("value", "ROW "+rowIndex);
			 }
			 else{
				 var rowAttrListIndex = rowIndex-1;
				 var columnAttrListIndex = colIndex-1;
				 inp.setAttribute("name","docItemList["+index+"].proposalCsAttributeValueList["+rowAttrListIndex+"].cellList["+columnAttrListIndex+"].attributeVal");
				 inp.setAttribute("id","docItemList["+index+"].proposalCsAttributeValueList["+rowAttrListIndex+"].cellList["+columnAttrListIndex+"].attributeVal");
				 inp.setAttribute("value", "");
			 }
			 div.appendChild(inp);
			 if(rowIndex==0 || colIndex==0){
				 div.setAttribute("class", "columnClass");
			 }
			 cell.appendChild(div);
			 if((rowIndex%2)==0){
				 cell.setAttribute("class", "columnClass");
				 cell.setAttribute("class", "columnClass");
			 }
			 else{
				 cell.setAttribute("class", "alternateColumnClass");
				 cell.setAttribute("class", "alternateColumnClass");
			 }
		},

		selectProposal : function(/*int*/ proposalId) {
			pageScope["proposal"] = {
				"proposal.id" : proposalId
			};

		},
		loadProposal : function(csrfToken){
	  		var proposal = pageScope["proposal"];
			if (null == proposal)
		    {
		    	alert("Please select an proposal");
		    	return ;
		    }
		    proposal.id = proposal["proposal.id"];
			Controller.loadPage(contextRoot+'/business/proposal.handle?methodName=getDoc&'+csrfToken,pageScope['proposal'],null);
		},
		search : function search(csrfToken){
			var allow =ProposalController.validate (csrfToken);
			if(allow){
				SearchController.searchWithForm('proposalSearch',['lastId'],'searchResult');
			}
		},
		proposalCommRelSearch : function (csrfToken){
			var allow =ProposalController.validateProposalCommRel (csrfToken);
			if(allow){
				$("#addPropCommRel").empty();
				SearchController.searchWithForm('proposalCommRelSearch',['lastId'],'searchResult');
			}
		},
		showPropCommRelUsr : function (csrfToken){
			 $("#propCommRelDiv").fadeToggle("slow", "linear");
		},
		proposalCommSearch : function (csrfToken){
				$("#addPropComm").empty();
				SearchController.searchWithForm('proposalCommSearch',['lastId'],'searchResult');
		},
		validateProposalCommRel : function (csrfToken){
			var procTypeId = document.getElementById("procurementTypeId").value;
			var buCode = document.getElementById("buCode").value;
			if(procTypeId == 0){
				alert("Please specify Procurement Type");
				return false;
			}
			if(buCode == ''){
				alert("Please specify FU/BU");
				return false;
			}
			return true;
		},
		clarification : function (clfType,entityId,docCode,docCreateDate,docOwnerId,proposalWfId,csrfToken) {
			//alert("clfType..."+clfType+"...entityId..."+entityId+"...docCode..."+docCode+"...docCreateDate.."+docCreateDate+"...docOwnerId..."+docOwnerId+"...proposalWfId..."+proposalWfId);
			Controller.loadPage(contextRoot+"/business/clarification.handle?methodName=getClarification&clarType="+clfType+"&entityId="+entityId+"&docCode="+docCode+"&docCreateDate="+docCreateDate+"&docOwnerId="+docOwnerId+"&proposalWorkFlow.id="+proposalWfId+"&"+csrfToken,null,null);
		    //alert("url..."+url);
			//if(orgType=='SELLER') url = "<c:url value='/business/clarification.action?popUp=Y&methodName=getClarification&clarType=RFQ_SELLER&entityId='/><c:out value='${command.id}'/>&docCode=<c:out value='${command.code}'/>&partNo=<c:out value='${command.rfqDate.partNumber}'/>&docCreateDate=<c:out value='${command.updateDate}'/>&docOwnerId=<c:out value='${command.rfqOwnerId}'/>&"+csrfToken;
		    //eval('window.showModalDialog(url,"","resizable:1,dialogHeight:600,dialogWidth:400")');
		},
		clarificationForApproval : function (clfType,entityId,docCode,docCreateDate,docOwnerId,proposalWfId,flowId,commId,csrfToken) {
			//alert("clfType..."+clfType+"...entityId..."+entityId+"...docCode..."+docCode+"...docCreateDate.."+docCreateDate+"...docOwnerId..."+docOwnerId+"...proposalWfId..."+proposalWfId+"...flowId..."+flowId+"..commId.."+commId);
			//alert("url..."+contextRoot+"/business/clarification.handle?methodName=getClarification&clarType="+clfType+"&entityId="+entityId+"&docCode="+docCode+"&docCreateDate="+docCreateDate+"&docOwnerId="+docOwnerId+"&proposalWorkFlow.id="+proposalWfId+"&flow.id="+flowId+"&commId="+commId+"&"+csrfToken);
			Controller.loadPage(contextRoot+"/business/clarification.handle?methodName=getClarification&clarType="+clfType+"&entityId="+entityId+"&docCode="+docCode+"&docCreateDate="+docCreateDate+"&docOwnerId="+docOwnerId+"&proposalWorkFlow.id="+proposalWfId+"&flow.id="+flowId+"&flowId="+flowId+"&commId="+commId+"&"+csrfToken,null,null);


		},
		showExcelReport :function showExcelReport(/*String*/ formId)
		{
		 	document.getElementById(formId).submit();
		},
		validate : function validate (csrfToken){
			var startDate = document.getElementById("proposalCreateDateFrom").value;
			var endDate = document.getElementById("proposalCreateDateTo").value;
			if(startDate != ""){
				if(endDate == ""){
				alert("Please specify the Proposal Create Date To correctly");
				return false;
				}
			} else if(endDate != ""){
				if(startDate == ""){
				alert("Please specify the Proposal Create Date From correctly");
				return false;
				}
			}
			if(endDate<startDate){
				alert("To date should be greater than From date ");
				return false;
			}
			return true;
		},
		showReportView : function showReportView(csrfToken){
			var allow = ProposalController.validate (csrfToken);
			if(allow){
				Controller.onSubmitWithCsrf('proposalReport',csrfToken,'viewProposalReport',null,null);
			}
		},
		doTimer :function (csrfTokenName){
			//alert('called doTimer with Csrf='+csrfToken);
			var csrfToken = csrfTokenName +'='+document.getElementById(csrfTokenName).value;
			if (!timer_is_on){
				timer_is_on=1;
				timedCount(csrfToken);
			}


		 },
		 manageWorkFlow :function (proposalId,status,csrfTokenName){
				//alert("...proposalId..."+proposalId+"...status..."+status+"...csrfTokenName..."+csrfTokenName);
				 if(null == proposalId)
					{
						alert("Please select an Proposal");
						return;
					}
					var stsString = "&approve=true&manageFlowMode=true";
					if(status == 'IV'){
						stsString = "&verify=true&manageFlowMode=true";
					}else if(status == 'IR'){
						stsString = "&recommend=true&manageFlowMode=true";
					}else if(status == 'IA'){
						stsString = "&approve=true&manageFlowMode=true";
					}
					//alert(contextRoot+'/business/proposal.handle?methodName=manageWorkFlow&viewMode=true&id='+proposalId+stsString+csrfTokenName);
					Controller.loadPage(contextRoot+'/business/proposal.handle?methodName=getDoc&viewMode=true&id='+proposalId+stsString+"&"+csrfTokenName,null,null);
			 },
			 manageWorkFlowForApproval :function (proposalId,status,workId,flowId,csrfTokenName){
				 var stsString = "&approve=true&manageFlowMode=true";
				 Controller.loadPage(contextRoot+'/business/proposal.handle?methodName=manageWorkFlow&viewMode=true&id='+proposalId+'&work.id='+workId+'&work.currentFlow.id='+flowId+stsString+"&"+csrfTokenName,null,null);
			 },
			 otherRecipientClar : function otherRecipientClar(){
				 if(document.getElementById("othersEnableSelected").checked==true){
					 document.getElementById("clarDiv").style.visibility="visible";
				 }
				 if(document.getElementById("othersEnableSelected").checked==false){
					 document.getElementById("clarDiv").style.visibility="hidden";
				 }
			 },
			 alertForNotRecommendation: function() {
				 alert("If 'Not recommended' then the proposal would be treated as Dropped proposal and  can't be modified further.");
			 },
			 selectProcComm: function(/*int*/ commTypeId){
				 if(commTypeId == '102'){
					 var ele = document.getElementById("commTypeId_103");
					 if(null!=ele){
						 ele.checked = true;
					 }
				 }
			 }
}
var PaymentController = {
	  viewPayment : function(id,csrfToken){
		if(null == id)
		{
			alert("Please select an payment");
			return;
		}
		Controller.loadPage(contextRoot+'/business/payment.handle?methodName=getDoc&viewMode=true&id='+id+"&"+csrfToken,null,null);
	},
	printPayment : function(paymentId,orgId,orgName){
		document.paymentPrintForm.action = contextRoot + "/business/report.action";
		document.paymentPrintForm.methodName.value = "showReport";
		document.paymentPrintForm.reportName.value = "paymentDtlViewPrint";
		document.paymentPrintForm.popUp.value = "Y";
		document.paymentPrintForm.paymentId.value = paymentId;
		document.paymentPrintForm.orgId.value = orgId;
		document.paymentPrintForm.orgName.value = orgName;
		document.paymentPrintForm.target="_blank";
		document.paymentPrintForm.submit();
  }

}
var DocumentController = {
	saveDocItemList : function(formName,methodname,buttonName){
		eval("document."+formName).buttonValue.value=buttonName;
		Controller.onSubmit(formName,null,methodname,null,null);
	},
	saveDocItemListSru : function(formName,methodname,buttonName){
		var itemSize = document.getElementById("itemList").value;
		for(var i=0;i<itemSize;i++){
			var valid = DocumentController.validateEntry(i);
			if(valid==false)
				return;
		}
		eval("document."+formName).buttonValue.value=buttonName;
		Controller.onSubmit(formName,null,methodname,null,null);
	},
	saveDocItemListForPO :function(formName,isEditable,buttonName){
		//alert("isEditable>>>"+isEditable);
		eval("document."+formName).buttonValue.value=buttonName;
		if(isEditable==true)
			Controller.onSubmit(formName,null,'nextOrderItem',null,null);
		else
			Controller.onSubmit(formName,null,'saveDocItemList',null,null);
	},
	
	validateEntry :function(counter){
		
		var challangrossqty = document.getElementById("docItemList["+counter+"].challangrossqty").value;
		var challannetqty = document.getElementById("docItemList["+counter+"].challannetqty").value;
		var quantityAdviced = document.getElementById("docItemList["+counter+"].quantityAdviced").value;
		var quantityReceived = document.getElementById("docItemList["+counter+"].quantityReceived").value;
		var transportershortage = document.getElementById("docItemList["+counter+"].transportershortage").value;
		var quantityAccepted = document.getElementById("docItemList["+counter+"].quantityAccepted").value;
		var quantityBalance = document.getElementById("docItemList["+counter+"].quantityBalance").value;
		
		var claimOnVendorCode = document.getElementById("docItemList["+counter+"].claimOnVendorCode").value;
		var claimOnVendorName = document.getElementById("docItemList["+counter+"].claimOnVendorName").value;
		var claimOnQuantity = document.getElementById("docItemList["+counter+"].claimOnQuantity").value;
		var claimOnAmount = document.getElementById("docItemList["+counter+"].claimOnAmount").value;
		var remarksOnClaimStatus = document.getElementById("docItemList["+counter+"].remarksOnClaimStatus").value;
		
		if(parseInt(challangrossqty)>parseInt(quantityBalance))
			{
			alert('INVOICE GROSS QUANTITY must be less than or equal to BALANCE QUANTITY');
			return false;
			}
		if(parseInt(challannetqty)>parseInt(challangrossqty))
		{
			alert('INVOICE NET QTY must be less than or equal to INVOICE GROSS QUANTITY');
			return false;
		}
		if(parseInt(quantityAdviced)>parseInt(challannetqty))
		{
			alert('SRU GROSS QUANTITY must be less than or equal to CHALLAN NET QTY');
			return false;
		}
		if(parseInt(quantityReceived)>parseInt(quantityAdviced))
		{
			alert('SRU NET QUANTITY must be less than or equal to SRU GROSS QUANTITY');
			return false;
		}
		
		if(claimOnVendorCode == '' || claimOnVendorName == '' || claimOnQuantity == '' || claimOnAmount == '' || remarksOnClaimStatus == ''){
			alert('Please put NIL in [Claim on Vendor Code, Claim on Vendor Name, Claim on Quantity, Claim on Amount, Remarks on Claim Status] column, if there is no Claim on Vendor/ Transporter');
			return false;
		}
		
		return true;
	}
}


var PreRfqController = {
		selectPreRfq : function(/*int*/ id,/*int*/ categoryId) {
			pageScope["preRfq"] = { "id" : id , "categoryId" : categoryId};
			if(sessionScope["_currPrivId"] == 102)
			{
				$("#viewPreRfq").css("display","inline");
			}
			if(sessionScope["_currPrivId"] == 101)
			{
				$("#editPreRfq").css("display","inline");
			}
		},
		addSupplier : function(){
			var nLength = document.preRfqSellerForm.preRfqSeller.options.length;
			  if (nLength > 0)
				{
					for(var nIndex = --nLength; nIndex >= 0; nIndex--)
					{
						if(document.preRfqSellerForm.preRfqSeller.options[nIndex].selected)
						{
							var optionValue = "",optionText= "", optionId= "";
							optionText = document.preRfqSellerForm.preRfqSeller.options[nIndex].text;
							optionId = document.preRfqSellerForm.preRfqSeller.options[nIndex].id;
							var optionName = new Option(optionText, optionId)
							var nlength = document.preRfqSellerForm.selectedSellerIds.length;
				 			document.preRfqSellerForm.selectedSellerIds.options[nlength] = optionName;
							document.preRfqSellerForm.preRfqSeller.options[nIndex] = null;
						}
					}
				}
		},
		removeSupplier : function ()
			{
					var nLength = document.preRfqSellerForm.selectedSellerIds.options.length;
					if (nLength >= 0)
					{
						for(var nIndex = --nLength; nIndex >= 0; nIndex--)
						{
							if(document.preRfqSellerForm.selectedSellerIds.options[nIndex].selected)
							{
								var optionValue = "",optionText= "" ,optionId= "";
								optionId = document.preRfqSellerForm.selectedSellerIds.options[nIndex].id;
								optionText = document.preRfqSellerForm.selectedSellerIds.options[nIndex].text;
								var optionName = new Option(optionText, optionId)
								var nlength = document.preRfqSellerForm.preRfqSeller.length;
					 			document.preRfqSellerForm.preRfqSeller.options[nlength] = optionName;

								document.preRfqSellerForm.selectedSellerIds.options[nIndex] = null;
							}
						}
					}
			   },
		selectSuppliersAndSubmit : function (/*String*/ formId,/*Object*/ addlParams,/*String*/ methodName,/*String*/button,/*Function*/ callback){
				   var nLength1 = document.preRfqSellerForm.selectedSellerIds.options.length;
				   for(var nIndex1 = 0; nIndex1 < nLength1; nIndex1++)
					{
					   document.preRfqSellerForm.selectedSellerIds.options[nIndex1].selected = true;
					}
				   Controller.onSubmit(formId,addlParams,methodName,button, callback);
			   },
		modalwin : function(/*String*/orgType,csrfToken) {
				    var entityId = document.getElementById("id").value;
				    var docCode = document.getElementById("code").value;
				    var docCreateDate = document.getElementById("createDate").value;
				    var docOwnerId = document.getElementById("owner.id").value;
				    var url = contextRoot+'/business/clarification.action?popUp=Y&methodName=getClarification&clarType=PRERFQCLAR_BUYER&entityId='+entityId+'&docCode='+docCode+'&docCreateDate='+docCreateDate+'&'+csrfToken;
				    if(orgType=='SELLER') url = contextRoot+'/business/clarification.action?popUp=Y&methodName=getClarification&clarType=PRERFQCLAR_SELLER&entityId='+entityId+'&docCode='+docCode+'&docCreateDate='+docCreateDate+'&docOwnerId='+docOwnerId+'&'+csrfToken;
					eval('window.showModalDialog(url,"","resizable:1,dialogHeight:600,dialogWidth:500")');
		},
		addInvitee : function (/*String*/ tableId, /*int*/inviteeCount){
		    //alert("in moreRow");
		    tbody=document.getElementById(tableId);
		    var rowIndex = tbody.rows.length - 2;
		    var index = rowIndex - inviteeCount;
		    if (index<0) index=0;
		    if (!PreRfqController.validateInvitee(index)) return;
		    var newRow=tbody.insertRow(tbody.rows.length);
		    var cell0 = newRow.insertCell(0);
		    cell0.setAttribute('class','dataClass');
		    cell0.innerHTML = '<input type="text" size="20" name="invitees['+index+'].userFirstName"/>';

		    var cell1 = newRow.insertCell(1);
		  	cell1.setAttribute('class','dataClass');
		  	cell1.innerHTML = '<input type="text" size="20" name="invitees['+index+'].userMail"/>';

		   	var cell2 = newRow.insertCell(2);
		  	cell2.setAttribute('class','dataClass');
		  	cell2.innerHTML = '<input type="text" size="30" name="invitees['+index+'].organization.organizationName"/>';

		  	var cell3 = newRow.insertCell(3);
		  	cell3.innerHTML='<a class="pageContentLink" href="javascript:PreRfqController.delInvitee(inviteeTab,'+rowIndex+');">DELETE ROW</a>';


		},
		delInvitee :function(/*String*/ tableId, /*int*/ index)
		{
			var tabId = "inviteeTab";
			tbody = document.getElementById(tabId);
		  	if (confirm('Delete The Invitee?')) tbody.deleteRow(index+2);
		},
		onSubmit : function(/*String*/ formId,/*Object*/ addlParams,/*String*/ methodName,/*String*/button,/*Function*/ callback) {
			/*
			1. Does Ajax Submit from a Form (get or post depends on form.method.
			2. In the callback - reads the contentType, if it is text/json, calls passed handleDataFn (optional parameter).
			3. If contentType is text/html, then reads the status code of response object to decide whether to
				show message or referesh the content alltogether with new content.
			*/
			if (!Util.assertNoServerCall()) return;
			log("formId="+formId);
			var formNode;
			if (formId==null) formNode = $("form[id!='dummyForm']");
			else formNode = $("#"+formId);
			//log("formNode="+formNode[0]);
			var param = formNode.serialize();
			var multiParam = '';
			if (methodName!=null) {
				log("methodName="+methodName);
				param+="&methodName="+methodName;
				multiParam ="methodName="+methodName;
			}
			if (typeof button!='undefined' && button!=null) {
				param+="&button="+button;
				multiParam+="&button="+button;
			}
			if (addlParams!=null) {
				param+="&"+$.param(addlParams);
				multiParam+="&"+addlParams;
			}
			log("action="+formNode.attr("action"));
			log("param="+param);
			if (formNode.attr("enctype")=='multipart/form-data') {

				var newUrl = formNode.attr("action")+"?"+multiParam;
				var options = {
			        url:newUrl,type:formNode.attr("method"),timeout:6000
		    	};
		    	var jqForm = $(formNode,'#_content');
		    	jqForm.ajaxSubmit(options);

			} else {
				if (formNode.attr("method")=='post') $.post(formNode.attr("action"),param,callback);
				else if (formNode.attr("method")=='get') $.get(formNode.attr("action"),param,callback);
			}
		},
		validateInvitee : function (/*int*/ index)
		{
			var maxSize = 15 ;
		    if(index == maxSize)
		    {
		    	alert("Maximum "+maxSize+" invitee can be added");
		    	return false;
		    }
		    if (index>0) {
		    	var lastUserFirstName = document.getElementById("invitees["+(index-1)+"].userFirstName");
			    if(null!=lastUserFirstName)
			    {
				    if((lastUserFirstName.value=='') || (lastUserFirstName.value==null))
				    {
				    	alert("Please specify the Name for previous row");
				    	return false;
				    }
				}
			    var lastUserEmail = document.getElementById("invitees["+(index-1)+"].userMail");
			    if(null!=lastUserEmail)
			    {
				    if((lastUserEmail.value=='') || (lastUserEmail.value==null))
				    {
				    	alert("Please specify the email for previous row");
				    	return false;
				    }
				}
			    var lastUserOrg = document.getElementById("inviteeTab["+(index-1)+"].organization.organizationName");
			    if(null!=lastUserOrg)
			    {
				    if((lastUserOrg.value=='') || (lastUserOrg.value==null))
				    {
				    	alert("Please specify the Organization for previous row");
				    	return false;
				    }
				}

		    }
		    return true;
		}
}

var RfiController = {
	viewSectionSummary:function(){
	$("input[name='methodName']").val("viewDocumentSummeryReport");
	Controller.onSubmit('ModifyRfiDetailForm',null,'viewDocumentSummeryReport',null,null);

	},
	showConfigTemplateList:function(userId){

	$("input[name='userId']").val(userId);
	$("input[name='methodName']").val("showDocumentConfigTemplateList");
	Controller.onSubmit('viewConfigTemplateForm',null,'showDocumentConfigTemplateList',null,null);

	},
	goToRfiResponseList :function(){
	$("input[name='methodName']").val("viewRfiResponseList");
	Controller.onSubmit('ModifyRfiDetailForm',null,'viewRfiResponseList',null,null);
	},
	viewRfiResponse :function(){
	$("input[name='methodName']").val("viewRfiUserSubmission");
	Controller.onSubmit('ModifyRfiDetailForm',null,'viewRfiUserSubmission',null,null);
	},
	finalSubmission :function(csrfToken){
	$("input[name='methodName']").val("finalRfiSubmission");
	Controller.onSubmitWithCsrf('viewConfigTemplateForm',csrfToken,'finalRfiSubmission',null,null);
	},
	getSubmission :function(){
	$("input[name='methodName']").val("addRfiSubmission");
	Controller.onSubmit('rfiSubmissionAddForm',null,'addRfiSubmission',null,null);
	},
	setValue :function(subId,code){

	$("input[name='oldDocumentSubmssionId']").val(subId);
		if($("input[name='selectOption']:checked").val()!="2"){
			$("#tr4").hide();
		}else{

			$("#tr4").show();
		}

		$("input[name='code']").val(code);
	},
	addSubmission:function(){
	$("input[name='methodName']").val("checkRfiSubmission");
	Controller.onSubmit('rfiResponseAddForm',null,'checkRfiSubmission',null,null);
	},
	viewConfigTemplateList:function(){
	$("input[name='methodName']").val("showDocumentConfigTemplateList");
	Controller.onSubmit('rfiResponseAddForm',null,'showDocumentConfigTemplateList',null,null);
	},
	response:function(){
	$("input[name='methodName']").val("addDocumentResponse");
	Controller.onSubmit('rfiResponseAddForm',null,'addDocumentResponse',null,null);
	},
	allowInputForText :function(){
	if($("input[name='responseFlag']:checked").val()=="N"){
		$("textarea[name='responseComment']").removeAttr("readonly");
		$("textarea[name='responseComment']").css("background","white");
	}else{
		$("textarea[name='responseComment']").attr("readonly","true");
		$("textarea[name='responseComment']").css("background","lightGrey");
	}
	},
	addRfiResponse :function(){
	$("input[name='methodName']").val("getDocumentResponse");
	Controller.onSubmit('ModifyRfiDetailForm',null,'getDocumentResponse',null,null);
	},
	backToView : function (rfiResponseFlag){
   	document.BackToRfiViewForm.responseFlag.value = rfiResponseFlag;
   	document.BackToRfiViewForm.submit();
	},
	showSpecAttachment : function  (id, csrfToken){
   		window.open(contextRoot+'/business/rfi.handle?methodName=getSpecificAttachments&itemId='+id+'&'+csrfToken, 'attachment', 'top=0, left=510, height=400, width=500, toolbar=no, status=no, scrollbars=yes ');
   	},
	viewRfiItemAttDesc : function(entityId,tableName,entityValue,documentCode,csrfToken){
		window.open(contextRoot+'/business/rfi.handle?methodName=getDocumentLine&entityId='+entityId+'&entityValue='+entityValue+'&tableName='+tableName+'&documentCode='+documentCode+'&'+csrfToken, 'openline', 'top=0, left=510, height=400, width=500, toolbar=no, status=no, scrollbars=yes ');
	},
	showRfiItemByItemCat : function (counter){
	$("input:hidden[name='rfiItemCatId']").val($("input:hidden[name='rfiItemCatList["+counter+"].id']").val());
	document.rfiViewForm.submit();
	},
	viewUserContact : function(userId) {
    	document.viewUserContactForm.profileIdentity.value = userId;
    	window.open('', 'userContactView_window', 'scrollbars=1, top=0, left=510, height=400, width=500, toolbar=no, status=no');
    	document.viewUserContactForm.target="userContactView_window";
    	document.viewUserContactForm.submit();
    },
	viewRfi : function(id,partNumber,csrfToken,rfqCatId){

			if(null == id)
			{
				alert("Please select an Rfi");
				return;
			}
			//Controller.loadPage(contextRoot+'/business/rfi.handle?methodName=getDoc&viewMode=true&id='+id+"&rfiPartNo="+partNumber+"&"+csrfToken,null,null);
			Controller.loadPage(contextRoot+'/business/rfi.handle?methodName=getDoc&viewMode=true&rfiId='+id+'&rfqCategoryId='+rfqCatId+'&rfiPartNo='+partNumber+'&'+csrfToken,null,null);

	},
	search : function (csrfToken){
			var allow =RfiController.validateSearch(csrfToken);
			if(allow){
				SearchController.searchWithForm('rfiSearch',['lastId'],'searchResult');
			}
	},
	validateSearch : function (csrfToken){
			var startDateFrom = document.getElementById("rfiStartDateFrom").value;
			var startDateTo = document.getElementById("rfiStartDateTo").value;
			var dueDateFrom = document.getElementById("rfiDueDateFrom").value;
			var dueDateTo = document.getElementById("rfiDueDateTo").value;
			if(startDateFrom != ""){
				if(startDateTo == ""){
				alert("Please specify the Rfi Start Date To correctly");
				return false;
				}
			} else if(startDateTo != ""){
				if(startDateFrom == ""){
				alert("Please specify the Rfi Start Date From correctly");
				return false;
				}
			}
			if((startDateTo<startDateFrom) || (dueDateTo<dueDateFrom)){
				alert("To Date should be greater than From Date ");
				return false;
			}
			if(dueDateFrom != ""){
				if(dueDateTo == ""){
				alert("Please specify the Rfi Due Date To correctly");
				return false;
				}
			} else if(dueDateTo != ""){
				if(dueDateFrom == ""){
				alert("Please specify the Rfi Due Date From correctly");
				return false;
				}
			}
			return true;
	},
	fetchAttribute : function (rfiItemId,csrfToken)	{
		document.rfiItemAddForm.selectedRfiItemId.value = rfiItemId;
		RfiController.saveDocItemListWithCsrf('rfiItemAddForm','saveDocItemList','attr',csrfToken);
	},
	getDescOnLoad : function (/*String*/ csrfToken) {
		var itemTable = document.getElementById("itemTab");
		var index = itemTable.rows.length - 2;
		for(var i=0;i<index;i++)
		{
			var code = document.getElementById('docItemList['+i+'].code').value;
			var id = document.getElementById('docItemList['+i+'].id').value;
			if(code == "" ||id!=0)
			{
				return;
			}
			else
			{
				RfiController.getItemDetail(i,document.getElementById('docItemList['+i+'].code'),csrfToken);
			}
		}
	},
	getDescr : function (/*int*/ index) {
		//alert("***");
		if (!RfiController.validate(index)) return;

		var csrfTokenName = document.rfiItemAddForm.csrfTokenName.value;
		var csrfTokenValue = document.rfiItemAddForm.csrfTokenValue.value;
		var csrfToken = csrfTokenName + "=" + csrfTokenValue;
		RfiController.getItemDetail(index,document.getElementById('docItemList['+index+'].code'),csrfToken);
	},
	validate : function (/*int*/ index) {
		var code = document.getElementById('docItemList['+index+'].code').value;
		if(code == "")
		{
			alert("Please specify the Code to get the Description");
			return false;
		}
		return true;
	},
	getItemDetail : function (/*int*/ rowNum,/*Obj*/ code,/*String*/ csrfToken) {
		alert("hello");
	 	var formNode = $("form[id!='dummyForm']");
	 	var buyerOrgId = 0;
    	$('input[id$=".code"]',formNode).each(function(){this.disabled=true;});
    	Controller.loadData(contextRoot+"/business/item.handle?methodName=getItem&code="+code.value+"&"+csrfToken,null,
    		function(/*String*/ data) {
    		$('input[id$=".code"]',formNode).each(function(){this.disabled=false;});
    		if (data["_errors"]!=null) {
    			alert("i am here");
    			Util.showMessage(data);
    			document.getElementById('docItemList['+rowNum+'].code').value='';
    			return;
    		}
    		Util.clearContent($('#_msgBox'));
    		document.getElementById('docItemList['+rowNum+'].bigRfiItemLineDescription').value = Controller.unescapeHtml(data.item.description);
    		//alert(document.getElementById('docItemList['+rowNum+'].bigRfiItemLineDescription').value);
    		var itemQtn = document.getElementById('docItemList['+rowNum+'].rfiItemQuantity').value;

  			if(document.getElementById('buyerOrgId')){
  				buyerOrgId = document.getElementById('buyerOrgId').value
  			}

  			if(buyerOrgId == 2350){
     		if (data.item.isServiceItemYN == "Y" )
    		{
    			document.getElementById('docItemList['+rowNum+'].bigRfiItemLineDescription').readOnly=false;
    			document.getElementById('docItemList['+rowNum+'].bigRfiItemLineDescription').removeAttribute('readonly');

    		} else {
    			document.getElementById('docItemList['+rowNum+'].bigRfiItemLineDescription').readOnly=true;
    		}
			}
    		var content = new Array();
			var j=0;
			if(data.length == 0)
			{
				return;
			}
			var attachLink = "item.action?popUp=Y&methodName=openItemAttachment&itemId="+data.item.id+"&fileName=";
			for(var i=0;i<data.item.attachments.length;i++)
			{
				content[j++]='<div><input name="docItemList[';
				content[j++]=rowNum;
				content[j++]='].possibleAttachments[';
				content[j++]=i;
				content[j++]='].selected';
				content[j++]='" type="checkbox" value="true"/>';
				content[j++]='<a target = "_new" href="';
				//content[j++]=data.item.attachments[i].path;
				content[j++]= attachLink+data.item.attachments[i].fileName+"&ext="+data.item.attachments[i].extention+"&"+csrfToken;
				content[j++]='">';
				content[j++]=data.item.attachments[i].label;
				content[j++]='</a>';
				content[j++]='<input name="docItemList[';
				content[j++]=rowNum;
				content[j++]='].possibleAttachments[';
				content[j++]=i;
				content[j++]='].fileName';
				content[j++]='" type="hidden" value="';
				content[j++]=data.item.attachments[i].fileName;
				content[j++]='"/>';
				content[j++]='</div>';
			}
			var itemTable = document.getElementById('inItemTab'+rowNum);
			itemTable.rows[3].cells[1].innerHTML=content.join('');
	    });
    },
	checkIfAllRowsFilledUp : function(lastIndex,msg,csrfToken) {
		var code=null;
		for (var i=lastIndex;i>=0;i--) {
			code =document.getElementById("docItemList["+i+"].code").value
			if (code=='') {
				alert(msg);
				return false;
			}
		}

		RfiController.saveDocItemListWithCsrf('rfiItemAddForm','saveDocItemList','next',csrfToken);
	},
	saveDocItemListWithCsrf : function(formName,methodname,buttonName,csrfToken){
			eval("document."+formName).buttonValue.value = buttonName;
			//document.getElementById("buttonValue").value = buttonName;
			Controller.onSubmitWithCsrf(formName,csrfToken,methodname,null,null);
	},
	viewDocItemListWithCsrf : function(formName,methodname,buttonName,csrfToken){
			eval("document."+formName).buttonValue.value = buttonName;
			Controller.onSubmitWithCsrf(formName,csrfToken,methodname,null,null);
	},
	submitOnCategorySelection : function() {
	//alert("*******");
		var rfqCategoryId=document.rfiAddForm.rfqCategoryId.value;
	var viewMode=document.rfiAddForm.viewMode.value;
	var csrfToken=document.rfiAddForm.OWASP_CSRFTOKEN.value ;
	Controller.loadPage(contextRoot+'/business/rfi.handle?methodName=getDoc&rfqCategoryId='+rfqCategoryId +'&viewMode='+viewMode+'&OWASP_CSRFTOKEN='+csrfToken,null,null); 	//document.rfiAddForm.submit();
    },


    fillOpenDate : function(){
		var rfiEndDate = document.getElementById('rfiDate.rfiEndDate').value;
		var year = rfiEndDate.substr(0,4);
		var month = rfiEndDate.substr(5,2);
		var day = rfiEndDate.substr(8,2);
		var hour=rfiEndDate.substr(11,2);
		var min=rfiEndDate.substr(14,2);
		var second=rfiEndDate.substr(17,2);
		var rfiEndDateObj = new Date(year,(month-1),day);
		rfiEndDateObj.setHours(hour,min,second,0);
		var rfiOpenDateObj = new Date(rfiEndDateObj.getTime() + 15*60000);
		$("#rfiOpenDate").val(rfiOpenDateObj.getYear()+"-"+(rfiOpenDateObj.getMonth()+1)+"-"+rfiOpenDateObj.getDate()+" "+rfiOpenDateObj.getHours()+":"+rfiOpenDateObj.getMinutes()+":"+rfiOpenDateObj.getSeconds());
	},
	signRfi : function (owner,pkiEnable,docEnable,buyerOrgId,isRfiSigned,corusOrgId,buttonValue,autoCodeEnable){
	if(buyerOrgId==114){
		RfiController.fillOpenDate();
	}

	var valid = true;
	var status = 'A';
	var rfiId = document.getElementById("id").value;
	var code = document.getElementById("code").value;
	var ownerId = document.getElementById("owner.id").value;
	//var status = document.getElementById("rfqStatusCode").value;
	var actionFlag = document.getElementById("actionFlag").value;
	var partCount = document.getElementById("partCount").value;
	var startDate = document.getElementById("rfiDate.rfiStartDate").value;
	var endDate = document.getElementById("rfiDate.rfiEndDate").value;
	var openDate = document.getElementById("rfiDate.rfiOpenDate").value;
	var documentSaleEndDate = "";
	var rfiSigningReqd = false;
	document.rfiAddForm.methodName.value='saveDocAndShowItemList';
	document.rfiAddForm.buttonValue.value=buttonValue;
	//document.getElementById("methodName").value='saveDocAndShowItemList';

	var partNumber ='1';
	if(code == '' && autoCodeEnable!= 'true'){
		alert("Rfi Code is Required");
		valid  = false;
		return valid;
	 }
	 if(startDate==''){
		alert("Rfi Start Date is Required");
		valid  = false;
		return valid;
	 }
	if(endDate==''){
		alert("Rfi End Date is Required");
		valid  = false;
		return valid;
	}
	if(openDate==''){
		alert("Rfi Open Date is Required");
		valid  = false;
		return valid;
	}


	if(rfiId=="0" && docEnable){
	  rfiSigningReqd  = true;
	}else if(rfiId!="0" && isRfiSigned){
	  rfiSigningReqd  = true;
	}

	if(pkiEnable && docEnable && rfiSigningReqd){
		if(ownerId=='0')
			ownerId = owner;
	   	if(actionFlag == '' || actionFlag == 'I')
	   	   var status = 'W';
		var rfiKey = code + '#|#' + rfqPartCount + '#|#' + ownerId + '#|#' + status;
		var rfiDateKey = partNumber + '#|#' + startDate + '#|#' + endDate + '#|#' + openDate;
		//alert("rfqKey:-"+rfqKey);
		valid = valid && signDocument(rfiKey);
		valid = valid && signDocumentAndAsingnValue(rfiDateKey,'rfiDate.digitalCert.signHash');
	}

	if(  valid && RfiController.validateSubmit(corusOrgId)){

		var csrfToken=document.rfiAddForm.OWASP_CSRFTOKEN.value ;
		Controller.onSubmitWithCsrf('rfiAddForm','csrfToken','saveDocAndShowItemList',null,null);
	}

	},

 validateSubmit:function(corusOrgId){
	var flag = document.getElementById("actionFlag").value;
	var orgId=$("input[name='orgId']").val();
	var rfiId= document.getElementById("id").value;

	if(null!=flag)
	{
		if(flag == "A" )
		{
			var open =false;
			if(orgId==corusOrgId){
				open=confirm("Once Activated, the RFP details can not be changed. Do you want to activate?");
			}
			else{
				open=confirm("Once Activated, the RfI details can not be changed. Do you want to activate?");
			}
			if(open == true)
			{
				return true;
			}
			else
			{
				return false;
			}
		}
		else{
			return true;
		}
	}
	else{
		return true;
	}
	},

	moreRow:function(tableId,confirmMessage){
	//alert("v2");
	    tbody=document.getElementById(tableId);
	    var index = tbody.rows.length-1;
	    alert("index"+index);
	    if (index<0) index=0;
	    if (index>0) {
		    var lastTerm = document.getElementById("rfiSpecialTerm["+(index-1)+"].bigRfiTermLineDescription");
	    }
	    var prpIndex = document.rfiAddForm.termCount.value ; //note
	    var tab = document.getElementById('termTable');
		var root=tab.getElementsByTagName('tr')[prpIndex].parentNode;//the TBODY
		var clone=tab.getElementsByTagName('tr')[prpIndex].cloneNode(true);//the clone of the first row
		clone.setAttribute('id',"r"+prpIndex);
		var newIndex=parseInt(prpIndex)+1;


		var elems = clone.getElementsByTagName('input');
		//elems[0].setAttribute("name", "rfiSpecialTerm["+prpIndex+"].rfiTermSerialNumber");
		root.appendChild(clone);
		alert("Length:"+$("#termTable>tr:eq("+newIndex+")").html());
		$("#termTable>tr:eq("+newIndex+")").find("input").removeAttr("name").attr("name", "rfiSpecialTerm["+prpIndex+"].rfiTermSerialNumber");
		//$("#termTable>tr:eq("+newIndex+")").find("input");
		$("#termTable>tr:eq("+newIndex+")").find("input").attr("value", newIndex);
		alert("NAME AFTER:"+$("#termTable>tr:eq("+newIndex+")").find("input").attr("name"));
		var elems = clone.getElementsByTagName('select');
		elems[0].setAttribute("name", "rfiSpecialTerm["+prpIndex+"].rfiTermTerm.id");
		elems[0].setAttribute("value","-1");
		var elems = clone.getElementsByTagName('textarea');
		elems[0].setAttribute("name", "rfiSpecialTerm["+prpIndex+"].bigRfiTermLineDescription");
		elems[0].setAttribute("value",prpIndex);
		var elems = clone.getElementsByTagName('a');
		//elems[0].setAttribute('href',"javascript:deleteRow('termTable',"+prpIndex+");");
		elems[0].setAttribute('href',"#");
		alert("prpindex"+prpIndex);
		elems[0].setAttribute('onClick',"RfiController:deleteRow1('termTable',"+prpIndex+",'"+confirmMessage+"');");
	//	elems[0].setAttribute('onClick',"RfiController:testBaisakhi()");
		//appends the clone
	    document.rfiAddForm.termCount.value = parseFloat(prpIndex)+1;
	},
	deleteRow:function(tableId,rowid,msg){
		alert("reference:::"+rowid);
		//var elem = document.getElementById("r"+ref.id);
		var row = document.getElementById("r"+rowid);
		tbody = document.getElementById(tableId);
		if (tbody.rows.length==2) {
			alert("The first row cannot be removed.");
			return;
		}
	  	if (confirm(msg)) tbody.deleteRow(rowid+1);
	},



	getRfiUserSearch:function(csrfToken){
		Controller.onSubmit('rfiForm',null,'getDocumentUserSearch',null,null);
	},
	getRfiUserSearchResult:function(csrfToken){
		$("input[name='methodName']").val("documentUserSearchResult");
		Controller.onSubmit('rfiForm',null,'documentUserSearchResult',null,null);
	},
	toggleUser:function(buttonValue){
    var arr = $("#"+buttonValue).attr("id").split("-");
    var from = arr[0];
    var to = arr[1];
    $("#" + from + " option:selected").each(function(){
      $("#" + to).append($(this).clone());
      $(this).remove();
    });
  },
	saveRfiUser:function(csrfToken){
		 var sellerIds= $("select[id='mapped'] option").map(function(){
	 			return $(this).val();
	 			}
	 		).get().join(",");
		$("input[name='mappedSellerIds']").val(sellerIds);
		var formNode = $("form[id='rfiForm']","#_content");
			$("input[name='methodName']",formNode).val("saveDocumentUser");
		Controller.onSubmit('rfiForm',null,'saveDocumentUser',null,null);
	},
  viewSelectedTemplate:function(){
		$("input[name='methodName']").val("getDocumentConfigTemplate");
		Controller.onSubmit('rfiForm',null,'getDocumentConfigTemplate',null,null);
	},
	 getRfiConfigTemplateList:function(){
		$("input[name='methodName']").val("getDocumentConfigTemplateList");
		Controller.onSubmit('rfiForm',null,'getDocumentConfigTemplateList',null,null);
	},
	attachTemplate:function(){
		var open = confirm("DO YOU WANT TO ATTACH THE QUESTIONNAIRE TEMPLATE");
  			if(open == true) {
  				$("input[name='methodName']").val("attachDocumentConfigTemplate");
  				$("input[name='buttonValue']").val("ATTACH TEMPLATE AND GOTO R F I")
				Controller.onSubmit('rfiForm',null,'attachDocumentConfigTemplate',null,null);
 		 	}
 		 	else return false;
	},
	downloadExcel:function(formName){
			document.documentItemExcelDownload.submit();
	},getRfiItemCatList:function(){

		$("input[name='methodName']").val("getDocumentItemCatList");
		Controller.onSubmit('rfiForm',null,'getDocumentItemCatList',null,null);
	},uploadExcel:function(formName){
		document.rfiItemUploadForm.submit();
	},saveLotWithDocument:function(){
		Controller.onSubmit('rfiItemCatAddForm',null,'saveDocumentItemCat',null,null);
	},getDescriptionByLotCode : function(rfiItemCount){
		var formNode = $("form[id!='rfiItemCatAddForm']","#_content");
    	var code = $('#selectId option:selected',formNode).text();
    	var csrfToken=$("#csrfToken").val();
    	//log('calling getItem with code='+code);
		if($('#selectId option:selected',formNode).val()=="0"){
			$('#selectDescription',formNode).html("");
			return;
		}

		Controller.loadData(contextRoot+"/business/item.handle?methodName=getLotDescriptionByLotCode&itemCatCode="+code+"&"+csrfToken,null,
    		function(/*Object*/ data) {
    		if (data["_errors"]!=null) {
    			log(data);
    			Util.showMessage(data);
    			return;
    		}
    		Util.clearContent($('#_msgBox'));
     		$('#selectDescriptionId',formNode).html("<textarea  name='rfiItemCatList["+rfiItemCount+"].description' rows='3' cols='20'>"+Controller.unescapeHtml(data.lot.description)+"</textarea>");
     		$('#lastPurchasedPriceId',formNode).html("<input type='text' name='rfiItemCatList["+rfiItemCount+"].lastPurchasedPrice' value='0.0' />");
    	});
	},getRfiConfigTemplate:function(){

		$("input[name='methodName']").val("getAttachDocumentConfigTemplate");
		Controller.onSubmit('rfiForm',null,'getAttachDocumentConfigTemplate',null,null);
	},deleteRfiSection : function(formName,csrfToken,methodName,entityId,entityValue,docSectionId,docTemplateId){
		eval("document."+formName).entityId.value=entityId;
		eval("document."+formName).entityValue.value=entityValue;
		eval("document."+formName).documentSectionId.value=docSectionId;
		eval("document."+formName).documentConfigTemplateId.value=docTemplateId;
		eval("document."+formName).methodName.value=methodName;
		if(entityId==100){
			if (confirm('Delete the Section from the RFI?')) {
				//eval("document."+formName).submit();
					Controller.onSubmit(formName,null,methodName,null,null);
				}
		}
	},retrieveRfiSection : function(formName,csrfToken,methodName,entityId,entityValue,docSectionId,docTemplateId){
		eval("document."+formName).entityId.value=entityId;
		eval("document."+formName).entityValue.value=entityValue;
		eval("document."+formName).documentSectionId.value=docSectionId;
		eval("document."+formName).documentConfigTemplateId.value=docTemplateId;
		eval("document."+formName).methodName.value=methodName;
		Controller.onSubmit(formName,null,methodName,null,null);
	},submitDocumentSection:function(buttonVal){
		$("input[name='methodName']").val("saveDocumentSection");
		$("input[name='buttonValue']").val(buttonVal);
		Controller.onSubmit('documetSectionModifyForm',null,'saveDocumentSection',null,null);
	}, checkIfAllDocumentRowsFilledUp : function(lastIndex,msg) {
		var code=null;
		for (var i=lastIndex;i>=0;i--) {
			code =document.getElementById("docSection.docSecQuesRelList["+i+"].docQuestion.code").value;
			if (code=='') {
				alert(msg);
				return false;
			}
		}
		document.getElementById("buttonValue").value = 'next';
		Controller.onSubmit('documentQuestionAddForm',null,'saveDocumentQuestion',null,null);
	  },saveDocumentSectionQuestionRelListWithCsrf : function(formName,methodname,buttonName,csrfToken){
		eval("document."+formName).buttonValue.value=buttonName;
		Controller.onSubmit(formName,null,methodname,null,null);
	}, goToRfi : function(formName,methodname,modifyType,csrfToken){
		eval("document."+formName).modifyType.value = modifyType;
    	Controller.onSubmitWithCsrf(formName,csrfToken,methodname,null,null);
    },
   modifyRfiDetail: function  (modifyType,formName,csrfToken,methodname){
    	 // eval("document."+formName).modifyType.value = modifyType;
    	 Controller.onSubmitWithCsrf(formName,csrfToken,methodname,null,null);
   		//document.ModifyRfiDetailForm.submit();
	},

    saveRfi:function(buyerOrgId,csrfToken,methodname,formName,buttonValue){
	if(buyerOrgId=='<%=IConstant.ORGANIZATION_ID_CORUS %>'){

			fillOpenDate();
		}
	document.getElementById("buttonValue").value = buttonValue;
	 Controller.onSubmitWithCsrf(formName,csrfToken,methodname,null,null);
	}
  }

var HelpController = {
	openHelpPage : function  (authOrgId, anchorId){
		window.open(contextRoot+'/html/help/organization'+authOrgId+'/help.html#'+anchorId, 'helpPopWinwod', 'top=400, left=400, height=130, width=600, toolbar=no, status=no, scrollbars=no, location=no, resizable=no, menubar=no');
   	},

   	helpPage : function  (authOrgId){
   		window.showModalDialog(contextRoot+'/html/help/organization'+authOrgId+'/help.html', 'helpWindow','dialogHeight: 400px; dialogWidth: 600px; dialogTop: 300px; dialogLeft: 300px; edge: Raised; center: Yes; resizable: Yes; status: Yes; ');
	},

   	openHelpOnClick : function (helpId, anchorId) {
		HelpController.showTip(document.getElementById(helpId), document.getElementById(anchorId).innerHTML);
   	},

	showTip : function (current,text){
		if (document.all||document.getElementById){
			thetitle = text.split('<br>');
				if (thetitle.length>1){
					thetitles = '';
					for (var i=0;i<thetitle.length;i++){
						thetitles+=thetitle[i];
					}
					current.title = thetitles;
					}
				else {
					current.title = text;
				}
			}
	}
}

var ReportController = {
	getReportInputs : function (/*String*/ formName, /*String*/ methodName){
		eval("document."+formName).methodName.value = methodName;
		eval("document."+formName).action = contextRoot + "/business/search.action";
		eval("document."+formName).submit();
	},

	getReportInputDate : function (/*String*/ formId){
		rfqDatePeriod = +document.getElementById(formId).rfqDatePeriod.value;
		document.getElementById(formId).showDatePicker.value = rfqDatePeriod;
	},

	submitForm :function(/*String*/ formId)
		{
			document.getElementById(formId).methodName.value = 'showReportInput';
			document.getElementById(formId).target = "_self";
		 	document.getElementById(formId).submit();
		},

	showReport :function(/*String*/ formId)
		{
			document.getElementById(formId).methodName.value = 'showReport';
			document.getElementById(formId).target = "_new";
		 	document.getElementById(formId).submit();
		},

	generateExcelReport : function(/*String*/ formId)
	{
		document.getElementById(formId).methodName.value = 'reportDownload';
		document.getElementById(formId).target = "_self";
	 	document.getElementById(formId).submit();
	},

	generateExcelReportRfqApprover : function(/*String*/ formId)
	{
		document.getElementById(formId).methodName.value = 'reportDownload';
		document.getElementById(formId).target = "_self";

		var startDate = document.getElementById("startDateRfqApproverReport").value;
		var endDate = document.getElementById("endDateRfqApproverReport").value;

		startDate = startDate + " 00:00:00.0"
		endDate = endDate + " 23:59:59.0"

		document.getElementById("startDateRfqApproverReport").value = startDate;
		document.getElementById("endDateRfqApproverReport").value = endDate;

	 	document.getElementById(formId).submit();
	},

	showReportPDF :function(/*String*/ formId)
		{
			document.getElementById(formId).methodName.value = 'showReport';
			//document.getElementById(formId).target = "_blank";

			if(dateValidation()){
				document.getElementById(formId).target = "_blank";
			}else{
				document.getElementById(formId).target = "_self";
			}

			//window.open('', 'searchResultPopup','top=400, left=400, height=300, width=600, toolbar=no, status=no, scrollbars=yes, location=no, resizable=yes, menubar=yes' );
			document.getElementById(formId).submit();
		},

	showExcelReportDownload :function(/*String*/ formId)
		{
			document.getElementById(formId).methodName.value = 'showExcelReport';
			document.getElementById(formId).target = "_self";
			//window.open('', 'searchResultPopupXls','top=400, left=400, height=300, width=600, toolbar=no, status=no, scrollbars=yes, location=no, resizable=yes, menubar=yes' );
		 	document.getElementById(formId).submit();
		},

	showExcelReport :function(/*String*/ formId)
		{
			document.getElementById(formId).methodName.value = 'showExcelReport';
			document.getElementById(formId).target = "searchResultPopupXls";
			window.open('', 'searchResultPopupXls','top=400, left=400, height=300, width=600, toolbar=no, status=no, scrollbars=yes, location=no, resizable=yes, menubar=yes' );
		 	document.getElementById(formId).submit();
		},
	resetReportForm :function(/*String*/ formId)
	{
		document.getElementById(formId).reset();
	},

	showReportXLS :function(/*String*/ formId, /*String*/ type)
	{
		document.getElementById(formId).methodName.value = 'showReport';
		document.getElementById(formId).reportType.value ='XLS';
	 	document.getElementById(formId).submit();

	},

	generateReport : function(/*String*/ formName, /*String*/ csrfToken, /*String*/ methodname, /*String*/ searchReportType){

		eval("document."+formName).searchReportType.value = searchReportType;
		eval("document."+formName).methodName.value = methodname;
		eval("document."+formName).action = contextRoot + "/business/search.action";
		eval("document."+formName).target = "_self";
		eval("document."+formName).submit();
	},

	doSearch : function(/*String*/ formName, /*String*/ methodName, /*String*/ resultDiv, /*String*/ searchReportType){
		//alert("formName= "+ formName + ", methodName= "+ methodName+", resultDiv= "+resultDiv+", searchReportType= "+ searchReportType);
		$(".msgBox").html("").hide();
		eval("document."+formName).searchReportType.value = searchReportType;
		eval("document."+formName).methodName.value = methodName;
		eval("document."+formName).action = contextRoot + "/business/search.handle";
		eval("document."+formName).target = "_self";
		//$("input[name='methodName']","#"+formName).val(methodName);
		SearchController.searchWithForm(formName, ['lastId'], resultDiv);
	},

	initSearch : function(/*String*/ formName, /*String*/ methodName, /*String*/ csrfToken){
		eval("document."+formName).action = contextRoot + "/business/search.handle";
		eval("document."+formName).methodName.value = methodName;
		Controller.onSubmitWithCsrf(formName, csrfToken, methodName, null, null);
	},

	modifySupplier : function(/*String*/ formName, /*int*/ userId){
		eval("document."+formName).id.value = userId;
		eval("document."+formName).submit();
	},

	modifyBuyer : function(/*String*/ formName, /*int*/ userId){
		eval("document."+formName).id.value = userId;
		eval("document."+formName).profileIdentity.value = userId;
		/*eval("document."+formName).action = contextRoot + "/administration/getUserModifyAction.do";*/
		eval("document."+formName).submit();
	},

	updateUserStatus : function(/*String*/ formName, /*String*/ authCode, /*String*/ authRole, /*String*/ authStatus, /*int*/ userId, /*int*/ buyerOrgId){
		eval("document."+formName).authenticationUserCode.value = authCode;
		eval("document."+formName).authenticationRole.value = authRole;
		eval("document."+formName).authenticationStatus.value = authStatus;
		eval("document."+formName).userIdArray.value = userId;
		eval("document."+formName).userBuyerOrgId.value = buyerOrgId;
		eval("document."+formName).authenticationOrganization.value = buyerOrgId;

		Controller.onSubmitWithCsrf(formName,'<csrf:token-name/>=<csrf:token-value/>',"authenticationUpdateStatus",null,null);
	},
	deAssociateGSTIN : function(/*String*/ formName, /*int*/ userId, /*int*/ supplierOrgId, /*int*/ buyerOrgId){
		eval("document."+formName).supplierOrgId.value = supplierOrgId;
		eval("document."+formName).buyerOrgId.value = buyerOrgId;

		Controller.onSubmitWithCsrf(formName,'<csrf:token-name/>=<csrf:token-value/>',"deAssociateGSTIN",null,null);
	},
	resetPassword : function(/*String*/ formName, /*int*/ userId){
		eval("document."+formName).userBuyerOrgId.value = $('#buyerOrgName').val();
		eval("document."+formName).userIdArray.value = userId;

		Controller.onSubmitWithCsrf(formName,'<csrf:token-name/>=<csrf:token-value/>',"getAuthenticationPasswordReset",null,null);
	},
	changeSellerStatus : function(/*String*/ formName, /*String*/ authCode, /*int*/ userId, /*String*/ buyerOrgName ,  /*int*/ buyerOrgId){

			eval("document."+formName).authenticationUserCode.value = authCode;
			eval("document."+formName).userIdArray.value = userId;
			eval("document."+formName).buyerOrgName.value = buyerOrgName;
			eval("document."+formName).userBuyerOrgId.value = buyerOrgId;
			eval("document."+formName).authenticationOrganization.value = buyerOrgId;



			Controller.onSubmitWithCsrf(formName,'<csrf:token-name/>=<csrf:token-value/>',"updateLockedSeller",null,null);
		},
		
		generatePaymentReport : function(/*String*/ formName, /*String*/ csrfToken, /*String*/ searchReportType){
			if(formName=='paymentMISReportPayment')
			{
				paymentDateF = eval("document."+formName).paymentDateFrom.value;
				paymentDateT = eval("document."+formName).paymentDateTo.value;
				
				if(paymentDateF)
				{
					if(!paymentDateT)
					{alert('Enter PAYMENT DATE TO FIELD');return;}
				}
				if(paymentDateT)
				{
					if(!paymentDateF)
					{alert('Enter PAYMENT DATE FROM FIELD');return;}
				}
			}
			else
			{
				invoiceDateF = eval("document."+formName).invoiceDate.value;
				invoiceDateT = eval("document."+formName).invoiceDateTo.value;
				invoiceCreationDateT = eval("document."+formName).invoiceCreationDateTo.value;
				invoiceCreationDateF = eval("document."+formName).invoiceCreationDateFrom.value;
					if(invoiceDateF)
					{
					if(!invoiceDateT)
						{alert('Enter INVOICE DATE TO FIELD');return;}
					}
					if(invoiceDateT)
					{
					if(!invoiceDateF)
						{alert('Enter INVOICE DATE FROM FIELD');return;}
					}
					if(invoiceCreationDateF)
					{
					if(!invoiceCreationDateT)
						{alert('Enter INVOICE CREATION DATE TO FIELD');return;}
					}
					if(invoiceCreationDateT)
					{
					if(!invoiceCreationDateF)
						{alert('Enter INVOICE CREATION DATE FROM FIELD');return;}
					}
			}

			eval("document."+formName).searchReportType.value = searchReportType;
			eval("document."+formName).submit();
		},
		resetValue :function(/*String*/ formName)
		{
			eval("document."+formName).invoiceNo.value="";
			eval("document."+formName).orderCode.value="";
			eval("document."+formName).referenceNumber.value="";
			
			if(formName=='paymentMISReportPayment')
			{
				eval("document."+formName).paymentDateTo.value="";
				eval("document."+formName).paymentDateFrom.value="";
				eval("document."+formName).supplierCodePayment.value="";
				eval("document."+formName).organizationNamePayment.value="";
				
			}
			else
			{
				eval("document."+formName).invoiceDate.value="";
				eval("document."+formName).invoiceDateTo.value="";
				eval("document."+formName).invoiceCreationDateFrom.value="";
				eval("document."+formName).invoiceCreationDateTo.value="";
				eval("document."+formName).supplierCodeInvoice.value="";
				eval("document."+formName).organizationNameInvoice.value="";
				
				
			}
		},
		generateVendorAndItemList :function(/*String*/ formName, /*String*/ csrfToken, /*String*/ searchReportType)
		{
			var today = new Date();
			var dd = today.getDate();
			var mm = today.getMonth()+1;
			if(mm<10)
			{
				mm = '0'+mm;
			}
			if(dd<10)
			{
				dd = '0'+dd;
			}
			var yyyy = today.getFullYear();
			var dateVal = yyyy+'-'+mm+'-'+dd;
			startDate = eval("document."+formName).rfqStartDateFrom.value;
			endDate = eval("document."+formName).rfqStartDateTo.value;
			if(endDate<startDate){
				alert("RFQ START DATE TO date should be greater than From date ");
				return false;
			}
			if(endDate>dateVal){
				alert("RFQ START DATE TO date should be greater than Current Date ");
				return false;
			}
			eval("document."+formName).searchReportType.value = searchReportType;
			eval("document."+formName).submit();
		},
		resetValueVendor :function(/*String*/ formName)
		{
			eval("document."+formName).rfqStartDateFrom.value='';
			eval("document."+formName).rfqStartDateTo.value='';
		},
		updateUserRole : function(/*String*/ formName, /*int*/ userId){
			eval("document."+formName).id.value = userId;
			eval("document."+formName).submit();
		},
		validateItemHistory : function(/*String*/ formName){
		var today = new Date();
		var dd = today.getDate();
		var mm = today.getMonth()+1;
		if(mm<10)
			{
			mm = '0'+mm;
			}
		if(dd<10)
		{
		dd = '0'+dd;
		}
		var yyyy = today.getFullYear();
		var dateVal = yyyy+'-'+mm+'-'+dd;
		var startDate = eval("document."+formName).publishedDateFrom.value;
		var endDate = eval("document."+formName).publishedDateTo.value;
		var rfqCode = eval("document."+formName).rfqCode.value;
			if(rfqCode==null || rfqCode==''){
				alert('Enter Rfq Code Field');
				return false;
				}
			else if(endDate>dateVal){
				
				alert("RFQ PUBLISHED DATE TO date must be less than CURRENT DATE ");
				return false;
				
			}
			else if(startDate>dateVal){
				alert("RFQ PUBLISHED DATE FROM date must be less than CURRENT DATE ");
				return false;
			}
			else if(endDate<startDate){
				
				alert("RFQ PUBLISHED DATE TO date must be greater than RFQ PUBLISHED DATE FROM");
				return false;
				
			}
			else
			return true;
		},
		resetItemHistory : function (formName /*String*/)
		{
			eval("document."+formName).publishedDateFrom.value='';
			eval("document."+formName).publishedDateTo.value='';
			eval("document."+formName).rfqCode.value='';
		}

}

var NoticeController = {

		loadNotice:function(formName,methodName,csrfToken,buttonValue,noticeStatus){
				if($('.rte1').length>0){
					$('#ifram_desc').removeClass("rte1");

				}
				eval("document."+formName).noticeStatus.value = noticeStatus;
				Controller.loadPage(contextRoot+'/business/admin.handle?methodName='+methodName+'&'+csrfToken+"&buttonValue="+buttonValue+"&noticeStatus="+noticeStatus,null,null);
				//document.buttonNoticeDivForm.submit();
				//Controller.onSubmitWithCsrf(formName, csrfToken, methodName,buttonValue, "searchResult");
			},
		 modifyAndPublishNotice: function(/*Int*/noticeId,/*String*/ formName, /*String*/ methodName,csrfToken,/*String*/button){
			// alert("button:::"+button +"methodName::::"+methodName);

			 	//eval("document."+formName).id.value = noticeId;
				eval("document."+formName).action = contextRoot + "/business/admin.handle";
				//eval("document."+formName).methodName.value = methodName;
				var params=noticeId + '\\' + csrfToken;
				//alert("params:::"+params);
				Controller.loadPage(contextRoot+'/business/admin.handle?methodName='+methodName+'&'+csrfToken+"&buttonValue="+button+"&noticeId="+noticeId,null,null);
				Controller.onSubmitWithCsrf(formName, csrfToken, methodName,button, null);
		 },

		 viewNotice: function(noticeId) {

				var url = contextRoot
						+ "/business/admin.action?methodName=viewNotice&Tab=Y&noticeId="
						+ noticeId;
				document.getElementById("noticeId").value = noticeId;
				var csrfEle = document.signInForm.OWASP_CSRFTOKEN;
				if(typeof csrfEle!='undefined'){
						var csrf = document.signInForm.OWASP_CSRFTOKEN.value;
						url = url + "&OWASP_CSRFTOKEN="+csrf;
					}

				var viewNotice = window.open(url,
							'viewNotice',
							'width=800,height=500,scrollbars=yes,resizable=yes,menubar=no,directories=no,location=no');
			}
      }


