//Utility Functions
// $Id: general.js,v 1.439.2.1 2010/01/29 10:48:49 binliu Exp $

var dwrChkVar ="true";
function parenAnalysis(content)
{
	var open=0;
	var close=0;
	for(var i=1;i<content.length-1;i++)
	{
		var sym=content.substring(i,i+1);
		if(sym=='(')
		{
			open++;
		}
		else if(sym==')')
		{
			close++;
		}
		if(close>open)
		{
			alert("Parenthetical logic not matched properly");
			return false;
		}
	}
	return true;
}
function handleButton(saveButton,sevt)
{
    if (typeof browser_ie != 'undefined')
        {
            sevt=event;
        }

     if(sevt.keyCode==13)
     {
             getObj(saveButton).click();
              return true;
     }
     return true;
}
function callSelectOneMethod(dwrChkVar,key,key2,lang,fldLabel)
{    
    if(dwrChkVar == "true")
    {
         if(key =="crm.alert.not.blank")        
             selectone.getJSAlertValue(key,fldLabel,lang,function(mesg) { alert(mesg) })
        if(key =="crm.alert.entry.valid")
            selectone.getJSAlertValue(key,fldLabel,lang,function(mesg) { alert(mesg) })
        if(key == "crm.alert.entry.num.whole" || key == "crm.alert.capacity.int" || key == "crm.alert.dec.place.max.two" || key == "crm.alert.dec.place.max.three" || key == "crm.alert.dec.place.max.four" || key == "crm.alert.dec.place.max.five")    
            selectone.getJSAlertValue(key,key2,lang,function(mesg) { alert(mesg) }) 
        if(key =="crm.alert.num.integer.range")        
            selectone.getJSAlertValue(key,key2,lang,function(mesg) { alert(mesg) })
    }   
    else
    {
        if(key =="crm.alert.not.blank")
            alert(fldLabel+' cannot be blank');
        if(key =="crm.alert.entry.valid")
            alert('Please enter a valid '+fldLabel);
        if(key == "crm.alert.capacity.int")    
            alert('Enter integer value in Capacity field');
        if(key == "crm.alert.dec.place.max.two")    
            alert('Enter a value with maximum of 2 decimal places');
        if( key == "crm.alert.dec.place.max.three" )
            alert('Enter a value with maximum of 3 decimal places');
        if( key == "crm.alert.dec.place.max.four" )
            alert('Enter a value with maximum of 4 decimal places');
        if( key == "crm.alert.dec.place.max.five")
            alert('Enter a value with maximum of 5 decimal places');
        if(key =="crm.alert.entry.num.whole")  
            alert('Enter only whole numbers');
        
    }
}
function callSelectOne2VarMethod(dwrChkVar,key,key2,lang,fldLabel1,fldLabel2)
{
    if(dwrChkVar == "true")
    {   
        selectone.getJSAlertValue(key,key2,lang, function(mesg) { alert(fldLabel1+" "+mesg+" "+fldLabel2) })        
    }
    else
    {
        if(key =="crm.alert.less.than")
            alert(fldLabel1+' should be less than '+fldLabel2);
        if(key =="crm.alert.less.than.equal.to")
            alert(fldLabel1+' should be less than or equal to '+fldLabel2);
        if(key =="crm.alert.equal.to") 
            alert(fldLabel1+' should be equal to '+fldLabel2);
        if(key =="crm.alert.greater.than")
            alert(fldLabel1+' should be greater than '+fldLabel2);
        if(key =="crm.alert.greater.than.equal.to") 
             alert(fldLabel1+' should be greater than or equal to '+fldLabel2);
        if(key =="crm.alert.not.equal.to") 
             alert(fldLabel1+' should not be equal to '+fldLabel2);     

             
    }
}



	function showLocateMapMenu()
    {
            getObj("copy").style.display="block"
            getObj("copy").style.left=findPosX(getObj("copyAddress"))
            getObj("copy").style.top=findPosY(getObj("copyAddress"))+getObj("copyAddress").offsetHeight
    }
	function hideLocateMapMenu(ev)
    {
            if (browser_ie)
                    currElement=window.event.srcElement
            else if (browser_nn4 || browser_nn6)
                    currElement=ev.target

            if (currElement.id!="copyAddress")
                    if (getObj("copy").style.display=="block")
                            getObj("copy").style.display="none"
    }
   function showDrillDownPtr() 
   {
	var anchorFound;
	var url=document.location.href
	var objAnchor=document.getElementsByTagName("A")
	var target=unescape(url.substr(url.lastIndexOf("#")+1,url.length))
	for (i=0;i<objAnchor.length;i++) {
		if (objAnchor[i].name==target) {
			anchorFound=true
			anchorObj=objAnchor[i]
			anchorLeft=findPosX(objAnchor[i])
			anchorTop=findPosY(objAnchor[i])
			break;
		}
	}
	if (anchorFound==true) {
		getObj("drillDownPtr").style.top=anchorTop-1
		pos=(parseInt(anchorLeft)>50) ? anchorLeft-50 : pos=0
		intvl=setInterval("animatePtr()",15)
	}
}
var pos=0,anchorLeft=0,anchorTop=0,anchorObj;
function animatePtr() {
	if (pos<=anchorLeft-22) {
		getObj("drillDownPtr").style.left=pos
		pos++
	} else {
		clearInterval(intvl)
	}
}
//added for loading img at the time of sending mails
function quickshowPict(oSelect,iter)
{
	var SelectType = oSelect.options[oSelect.selectedIndex].value;
	var ImageId = "lookupIcon_1";
	var oImage = document.getElementById(ImageId)
	var textId="exclusion_1";
	 document.getElementById(textId).value=""
	if(SelectType == 'segment' || SelectType == "Segment")
	{

		oImage.src = 'images/Targets_small.gif'
		oImage.alt = 'Target LookUp';
		oImage.title = 'Target LookUp';
		oImage.onclick = function(){showLookUp('exclusion_1','segmenthid_1','exclusion_1','Segments') }	
	}
else if(SelectType=="Target")
{
oImage.src = 'images/Targets_small.gif'
			oImage.alt = 'Target LookUp';
			oImage.title = 'Target LookUp';
			oImage.onclick = function(){showLookUp('exclusion_1','targethid_1','exclusion_1','Targets') }
}
else
	{
		oImage.src = 'images/Exclusions_small.gif'
		oImage.alt = 'Exclusion LookUp';
		oImage.title = 'Exclusion LookUp';
		oImage.onclick = function(){showLookUp('exclusion_1','exclusionhid_1','exclusion_1','Exclusions') }
	}
}
function CallTagAjaxx(TOTAL_RECORDS,FORWARD_TO,TO_INDEX,FROM_INDEX,type)
{
    var url="/crm/NavigateByRecords.do?totalRecords="+TOTAL_RECORDS+"&fileName="+FORWARD_TO+"&toIndex="+TO_INDEX+"&fromIndex="+FROM_INDEX+"&currentOption=10&"+type+".x=x";
    
    if(getObj("gtagNavig")!=null&&getObj("gtagNavig")!="")
    {
        var gtagNavig = getObj("gtagNavig");
        var gtagNavigVal = gtagNavig.value;
        if(gtagNavigVal=="gtagNavig")
        {
            var http = getHTTPObject();
            http.open("GET",url,true);
            http.onreadystatechange=function()
            {
                  if(http.readyState==4)
                  {
                          var str=http.responseText;	      
                          document.getElementById("show").innerHTML=str;
                  }
            }
            http.send(null);
        }
        else
        {
            document.location.href=url;
        }
    }
    else
    {    
    document.location.href=url;
    }
}

function loadAjaxTab(str,style)
{
        var divId = document.getElementById('ajax_load_tab');
        divId.style.display = 'block'; 
        divId.style.zIndex = '50'; 
        var imgfile = '/crm/images/loader2.gif';
        divId.innerHTML = '<span><img src="'+imgfile+'" align="absmiddle"></span>&nbsp; ' + str + '...';
//	setCenter(divId);
}
// function moved from cloneentity.jsp
function setProbability(name)
{
        selectedText = name.substring(name.indexOf(":")+1,name.length)
        name = name.substring(0,name.indexOf(":"))
	if(document.createEntityForm.elements['property(Probability)'] != undefined)
	{
        document.createEntityForm.elements['property(Probability)'].value = name ;
	}
}
var pos=0,anchorLeft=0,anchorTop=0,anchorObj;
/*function animatePtr() {
	if (pos<=anchorLeft-22) {
		//getObj("drillDownPtr").style.left=pos
		pos++
	} else {
		clearInterval(intvl)
	}
}
*/
function copyAddress()
{
	if (getObj("property(Billing Street)") && getObj("property(Shipping Street)"))
		getObj("property(Shipping Street)").value=getObj("property(Billing Street)").value

	if (getObj("property(Billing City)") && getObj("property(Shipping City)"))
		getObj("property(Shipping City)").value=getObj("property(Billing City)").value

	if (getObj("property(Billing State)") && getObj("property(Shipping State)"))
		getObj("property(Shipping State)").value=getObj("property(Billing State)").value

	if (getObj("property(Billing Code)") && getObj("property(Shipping Code)"))
		getObj("property(Shipping Code)").value=getObj("property(Billing Code)").value

	if (getObj("property(Billing Country)") && getObj("property(Shipping Country)"))
		getObj("property(Shipping Country)").value=getObj("property(Billing Country)").value
}
/*
	Assignment Settings Validation method added
*/
function assignValidation(assignCount)
{
	var flag=true
	for(var zz=0;zz<assignCount;zz++)
	{
	   var assType=document.getElementById("assignType"+(zz+1)).value
	   if(assType=='Rule')
	   {		   
		   var selObj = document.getElementById('assignRule'+(zz+1));
           var selIndex=selObj.selectedIndex
		   var val=selObj.options[selIndex].value
		   if(val=='-')	   
		   {
			document.getElementById('assignType'+(zz+1)).focus();
			alert("Rule 'None' is not allowed")
			flag=false
			return flag
		   }
	   }
	}
	return flag
}
function validateProductAlias()
{
        var productAlias = document.createEntityForm.elements['property(Product Name Alias)'].value
        var re1=/^[a-z\d\- ]+$/i
        if (!re1.test(productAlias))
        {
								selectone.getJSAlertValue("crm.alert.prod.name.spec.char",null,"en_US",
																					function(mesg) { alert(mesg) })
                document.createEntityForm.elements['property(Product Name Alias)'].focus()
                return false;
        }
        else
        {
                return true;
        }
}

function setProductAlias()
{
        var productName = document.createEntityForm.elements['property(Product Name)'].value
        if ( productName.indexOf(" ") > 0 )
        {
                productName = productName.replace(" ","-")
        }
        document.createEntityForm.elements['property(Product Name Alias)'].value = productName
        var re1=/^[a-z\d\- ]+$/i
        if (!re1.test(productName))
        {
					selectone.getJSAlertValue("crm.alert.prod.name.spec.char",null,"en_US",
																					function(mesg) { alert(mesg) })
					return false;
        }
}
// endof  function moved from cloneentity.jsp
//massAction function moved from showcustomviewdetails.jsp
function massAction(type,actionurl,parameter,module,cvname,cvid,start_index,end_index)
{
if(type == "assign_status")
{
        var comboval= getObj('status_combo').value;   
    if(comboval =='-None-')
    {
        return;
    }
}    
	noofrows = document.showcvdetails.chk.length;
   

	var append_ids = "";
	var moduleStr = document.showcvdetails.module.value;
	if (noofrows == undefined )
	{
		if (document.showcvdetails.chk.checked)	
		{
			if ( document.showcvdetails.chk.value =="null" )
			{
				if( module == "Iterations" )
				{
					selectone.getJSAlertValue("crm.alert.iteration.not.selected",null,"en_US",function(mesg) { alert(mesg) })
					document.showcvdetails.chk[i].checked=false;
					document.showcvdetails.allcheck.checked=false;
				}
				return false;
			}
			else
			{
				append_ids = document.showcvdetails.chk.value;
				document.showcvdetails.idlist.value=append_ids;
				document.showcvdetails.action="/crm/"+actionurl+".do?module="+module+parameter;		
			}
            if(type == "assign_status")
                {
                    Callonclickofbutton3(module,document.showcvdetails.idlist.value,cvname,cvid,start_index,end_index);
                    return false;
                }
			if(type=="bulktask")
                        {
                          document.showcvdetails.action="/crm/"+actionurl+".do?secmod="+module+"&module=Tasks"+parameter;
                        }

			if(type == "massdelete")
			{
				if(moduleStr== "Exclusions")
				{
					DWRCommonUtil.isEmailOptOut
	            	(
			            append_ids,
			            function(isPresent)
			            {
			            	if(isPresent== true)
							{
								alert('Permission Denied');
								return false;
							} 
							else
							{
								Callonclickofbutton2('/crm/DeleteFromCV.do',module,document.showcvdetails.idlist.value,cvname,cvid,start_index,end_index);
                    			return false;
							}
						}
					
					);
				}
                                else if(module=='Discounts')
                                {
                                    DWRCommonUtil.getDiscountStatus
                                            (
                                            document.showcvdetails.idlist.value,
                                            function(isPresent)
                                            {
                                                discountPresent=isPresent;                        
                                                if(discountPresent== true)
                                                {
                                                    alert('Unable to perform the operation as the Discount has been applied to Invoices');
                                                }    
                                                else 
                                                {                        
                                                  Callonclickofbutton2('/crm/DeleteFromCV.do',module,document.showcvdetails.idlist.value,cvname,cvid,start_index,end_index);
                                                }
                                            }
                                            );
                                }
                                else if(module=='Venues')
                                {
                                    DWRCommonUtil.getlocationStatus
                                            (
                                            document.showcvdetails.idlist.value,
                                            function(isPresent)
                                            {
                                                locationPresent=isPresent;                        
                                                if(locationPresent== true)
                                                {
                                                    alert('Unable to perform the operation as the Location used in Event ');
                                                }    
                                                else 
                                                {                        
                                                  Callonclickofbutton2('/crm/DeleteFromCV.do',module,document.showcvdetails.idlist.value,cvname,cvid,start_index,end_index);
                                                }
                                            }
                                            );
                                }
				else if(moduleStr=="Forecasts")
				{
					if(confirm('Are you sure? Your forecast record will be deleted permanently.'))
					{
						document.showcvdetails.method="post";
						document.showcvdetails.submit();
					}
					else
					{
						return false
					}					
				}
				else
				{
                    Callonclickofbutton2('/crm/DeleteFromCV.do',module,document.showcvdetails.idlist.value,cvname,cvid,start_index,end_index);
                                  
                    return false;                    
				}
			}
			else 
			{
				document.showcvdetails.method="post";		
				document.showcvdetails.submit();
			}
		}
		else 
		{			
			selectone.getJSAlertValue("crm.alert.select.one",null,"en_US",
			function(mesg){
				alert(mesg)
			}
			)
			
			if(type == "assign_status")
                        {
                            getObj('status_combo').value='-None-';
                        }
			return false;	
		}
	}
	else if (noofrows != 0)
	{
		if (getNoOfSelected() == 0)
		{
			selectone.getJSAlertValue("crm.alert.select.one",null,"en_US",
			  												function(mesg) { alert(mesg) })
			if(type == "assign_status")
                        {
                            getObj('status_combo').value='-None-';
                        }
			return false;	
		}	
		else 
		{	
			for(i = 0 ; i < noofrows ; i++)
			{
				if (document.showcvdetails.chk[i].checked )
				{
					if (document.showcvdetails.chk[i].value =="null")
					{
						if( module == "Iterations" )
						{
							selectone.getJSAlertValue("crm.alert.iteration.not.selected",null,"en_US",function(mesg) { alert(mesg) })
							document.showcvdetails.chk[i].checked=false;
							document.showcvdetails.allcheck.checked=false;
						}
						return false;
					}
					else
					{
						append_ids= document.showcvdetails.chk[i].value+";"+append_ids;
					}
				}
			}              
			document.showcvdetails.idlist.value=append_ids
			document.showcvdetails.action="/crm/"+actionurl+".do?module="+module+parameter;


            if(type == "assign_status")
                {
                    Callonclickofbutton3(module,append_ids,cvname,cvid,start_index,end_index);
                    return false;
                }

                        if(type=="bulktask")
                        {
                          document.showcvdetails.action="/crm/"+actionurl+".do?secmod="+module+"&module=Tasks"+parameter;
                        }
			if (type == "massdelete")
			{
				             if(module=='Venues')
                                {
                                    DWRCommonUtil.getlocationStatus
                                            (
                                            document.showcvdetails.idlist.value,
                                            function(isPresent)
                                            {
                                                locationPresent=isPresent;                        
                                                if(locationPresent== true)
                                                {
                                                    alert('Unable to perform the operation as the Location used in Event ');
                                                }    
                                                else 
                                                {                        
                                                   Callonclickofbutton2('/crm/DeleteFromCV.do',module,document.showcvdetails.idlist.value,cvname,cvid,start_index,end_index);
                                                }
                                            }
                                            );
                                }
                                else if(module=='Discounts')
                                {
                                    DWRCommonUtil.getDiscountStatus
                                            (
                                            document.showcvdetails.idlist.value,
                                            function(isPresent)
                                            {
                                                discountPresent=isPresent;                        
                                                if(discountPresent== true)
                                                {
                                                    alert('Unable to perform the operation as the Discount has been applied to Invoices');
                                                }    
                                                else 
                                                {                        
                                                  Callonclickofbutton2('/crm/DeleteFromCV.do',module,document.showcvdetails.idlist.value,cvname,cvid,start_index,end_index);
                                                }
                                            }
                                            );
                                }
				else if(moduleStr=="Forecasts")
				{
					if(confirm('Are you sure? Your forecast record will be deleted permanently.'))
					{
						document.showcvdetails.method="post";
						document.showcvdetails.submit();
                        
					}
					else
					{
						return false
					}					
				}
				else
				{

                    Callonclickofbutton2('/crm/DeleteFromCV.do',module,document.showcvdetails.idlist.value,cvname,cvid,start_index,end_index);
                                  
                    return false;
                    
				}
			}
			else 
			{
					document.showcvdetails.method="post";
					document.showcvdetails.submit();
			}
		}
	}
        else
        {
		return false;
        }
}
function listMUFields(module,cvname,cvid,start_index, end_index, rangeValue)
{
	var noofrows = document.showcvdetails.chk.length;
	var append_ids = "";
	if(noofrows == undefined)
	{
		if (document.showcvdetails.chk.checked)
		{
			var values = (document.showcvdetails.chk.value).split("||&&");
			if ( document.showcvdetails.chk.value =="null" )
			{
				if( module == "Iterations" )
				{
					selectone.getJSAlertValue("crm.alert.iteration.not.selected",null,"en_US",function(mesg) { alert(mesg) })
					document.showcvdetails.chk[i].checked=false;
					document.showcvdetails.allcheck.checked=false;
				}
				return false;
			}
			else
			{
				var append_ids = values[0];
			}
		}
		else
		{
			selectone.getJSAlertValue("crm.alert.select.one",null,"en_US",function(mesg) { alert(mesg) })
			return false;
		}
	}
	else if(noofrows != 0)
	{
		if (getNoOfSelected() == 0)
		{
			selectone.getJSAlertValue("crm.alert.select.one",null,"en_US",function(mesg) { alert(mesg) })
			return false;
		}
		else
		{
			for(i=0;i<noofrows;i++)
			{
				if (document.showcvdetails.chk[i].checked)
				{
					var values = (document.showcvdetails.chk[i].value).split("||&&");
					var ids = values[0];
					if ( ids == "null" )
					{
						if ( module == "Iterations" )
						{
							selectone.getJSAlertValue("crm.alert.iteration.not.selected",null,"en_US",function(mesg) { alert(mesg) })
							document.showcvdetails.chk[i].checked=false;
							document.showcvdetails.allcheck.checked=false;
						}
						return false;
					}
					else
					{
						append_ids= ids+";"+append_ids;
					}
				}
			}
		}
	}
	var fieldUitype = (getObj("fieldUitype").value).split(",");
	var fieldId = (getObj("fieldId").value).split(",");
	var fieldLabel = (getObj("fieldLabel").value).split(",");
	var displayFieldLabel = (getObj("displayFieldLabel").value).split(",");
	var fieldLen = (getObj("fieldLen").value).split(",");
	var fieldName = (getObj("fieldName").value).split(",");
	var fieldTableName = (getObj("fieldTableName").value).split(",");
	var fieldDatatype = (getObj("fieldDatatype").value).split(",");

	var fldNum = fieldName.length;
	if(fieldName=="null")
	{
	fldNum="0";
	}
	var dumTd1 = "<table border='0' width='100%' class='settingsUI' cellpadding='0' cellspacing='0'><tr class='sidebarHead small searchsmall'><td align='left' style='padding-left:5px;' nowrap>Mass Update</td><td width='6%' align='center'><img src='/crm/images/close.gif' align='absmiddle' style='cursor:hand;cursor:pointer' onClick='hide(\"bulkUpdateFldsList\");if (document.getElementById(\"FreezeLayer\") != null) {document.body.removeChild(document.getElementById(\"FreezeLayer\"));}'></td></tr>";
	var fldsTxt1 = dumTd1 + "<tr><td colspan='2' class='small' align='left' nowrap style='padding:5px;'>Select a field to Update:</td></tr><tr><td class='small' align='center' colspan='2' style='padding-bottom:5px;' ><select class='select' id='muFlds' name='muFlds' onChange='if(this.value == \"None\"){hide(\"bulkUpdate_field\");}else{setMUFld(this.value,\""+append_ids+"\", \""+cvname+"\", \""+cvid+"\",\""+start_index+"\",\""+end_index+"\",\""+rangeValue+"\")}'" + ">";
	fldsTxt1 = fldsTxt1 + "<option value='None' style='font-weight:bold'></option>";
	//alert(fldsTxt1);
	for(var i=0;i<fldNum;i++)
	{
		fldsTxt1 = fldsTxt1 + "<option style='color:black;font-weight:normal' value=" +fieldUitype[i] + "||||" + fieldId[i]+"||||" +encodeURIComponent(fieldLabel[i])+"||||" +fieldLen[i]+"||||" +fieldName[i]+"||||"+fieldTableName[i]+"||||" +fieldDatatype[i]+"> " +displayFieldLabel[i] +"</option>";
	}
	fldsTxt1 = fldsTxt1 + "</select></td></tr><tr><td colspan='2' class='small'>";
//	for(var i=0;i<fldNum;i++)
	{
		fldsTxt1=fldsTxt1+"<div id ='bulkUpdate_field' style=''></div>";
	}
	fldsTxt1 = fldsTxt1 + "</td></tr></table>";
	//alert(fldsTxt1);
	
	getObj("bulkUpdateFldsList").innerHTML=fldsTxt1;
	document.getElementById("bulkUpdateFldsList").style.top=document.getElementById("idForCV").offsetHeight;
	show("bulkUpdateFldsList");
	freezeBackground();
	
}

function setMUFld(argsVal, append_ids, cvname, cvid, start_index, end_index, rangeValue)
{
	//alert("NSP :::INSIDE setMUFld --------" + argsVal);
//	getObj("bulkUpdateFldsList").innerHTML="<b> Bulk Change Value </b>"
//	show("bulkUpdateFldsList");
//	hide("bulkUpdateFldsList");
//Need to handle for uitypes 1,2,21,24,25,32,33,35,36,37,786 Also need to handle maxLen, fieldLevelSecurity
	var uiTypes = new Array("1","2","21","24","25","32","33","35","36","37","300","301","786");
	var valObtained = argsVal.split("||||");
	var muFldUIType	= valObtained[0];
	var fieldId	= valObtained[1];
	var fieldLabel	= valObtained[2];
	var fieldLen = valObtained[3];
	var fieldName = valObtained[4];
	var fieldTableName = valObtained[5];
	var fieldDatatype = valObtained[6];
	var dtPtn=getObj("dtPtn").value;	
	var moduleStr = getObj("module").value;
	var objTxt ="";	
	var dumTd2 = "<table border='0' width='100%' cellpaddin='0' cellspacing='0'><tr><td class='small' nowrap align='left' style='padding:5px;'>"
	if(muFldUIType==2)
	{
		dumTd2 += "Select a new value for the field ";
	}
	else if(muFldUIType==300|| muFldUIType ==301)
	{
		dumTd2 += "Choose a new value for the field ";
	}
	else if(muFldUIType==100 || muFldUIType ==500)
	{
		dumTd2 += "Select one or more values for the field ";
	}
	else
	{
		dumTd2 +="Enter a new value for the field ";
	}
	
	dumTd2 += replaceBySpace(decodeURIComponent(fieldLabel))+"</td></tr><tr><td class='small' align='center' colspan='2' style='padding-bottom:5px;' >";
	objTxt = dumTd2+objTxt;	
	var handleSave = "CallonMassUpdate('/crm/MassUpdateField.do','"+moduleStr+"','"+fieldTableName+"','"+fieldName+"', '"+muFldUIType+"','"+fieldLabel+"','" +fieldDatatype+"','"+append_ids+"','"+cvname+"','"+cvid+"','"+start_index+"','"+end_index+"','"+rangeValue+"')";
	var btnObjTxt = "<input type='button' value='Save' class='button' name='button__"+muFldUIType+"' onclick=\""+handleSave+"\">";
	btnObjTxt +="&nbsp;&nbsp;<input type='button' class='button' value='Cancel' onClick='hide(\"bulkUpdateFldsList\");if (document.getElementById(\"FreezeLayer\") != null) {document.body.removeChild(document.getElementById(\"FreezeLayer\"));}'></td></tr></table>"
	//alert(btnObjTxt);

	if(muFldUIType==1 ||muFldUIType ==21 || muFldUIType==33 ||muFldUIType==35||muFldUIType==37)
	{
		//alert(" INSIDE now && muFldUIType 2 is " +muFldUIType);
		objTxt = objTxt+ "<input type='text' id='txt_"+muFldUIType+"' name='txt_"+muFldUIType+"' class='textField' width='10%' maxlength='"+fieldLen +"' onkeydown=\"handleButton('button__"+muFldUIType+"',event)\"></td></tr><tr><td align='center' class='qcfooter' colspan='2'>";
	}
	else if(muFldUIType==2)
	{
		// Need to get the Allowed Values
		var comboUrl = "/crm/jsp/GetComboValues.jsp" ;
		var comboArgs = "fieldId="+fieldId;	
		if(http)
		{
			getObj("bulkUpdate_field").innerHTML="Loading...";
			//window.open(comboUrl+"?"+ comboArgs);	
			http.open("POST", comboUrl, true);
			http.setRequestHeader('Content-Type','application/x-www-form-urlencoded;charset=UTF-8');
			http.onreadystatechange=function()
			{
				if(http.readyState==4)
				{
					dataStr = http.responseText;
					//alert(dataStr);
					var combovalObt = dataStr.split(",");
					objTxt += "<select id='txt_"+muFldUIType+"' class='importBox' name='txt_"+muFldUIType+"'>";
                                        if(((fieldLabel != "Status" && moduleStr=="Segments")||(moduleStr != "Segments"))&&((fieldLabel != "Status" && moduleStr=="Exclusions")||(moduleStr != "Exclusions")) && ((fieldLabel !="Approval%20Status" && moduleStr == "Campaigns")|| (moduleStr != "Campaigns")) && ((fieldLabel != "Status" && fieldLabel !="Type" && moduleStr=="EventForms") || (moduleStr !="EventForms") ) && ((fieldLabel != "Status" && fieldLabel !="Type" && moduleStr=="InquiryForms") || (moduleStr !="InquiryForms") )  )
                                        {
                                                objTxt +="<option value=''></option>";
                                        }
                                       	for(var i=0;i<combovalObt.length;i++)
					{
						var rat = combovalObt[i];
						rat = rat.replace(/</g,"<")
						rat = rat.replace(/>/g,">")
						objTxt += "<option value='"+rat+"'>"+rat;
					}
					//alert(objTxt);
					objTxt += "</select><p></p></td></tr><tr><td class='qcfooter' align='center' colspan='2'>";
					objTxt += btnObjTxt;
					getObj("bulkUpdate_field").innerHTML=objTxt;
				}
			}
			http.send(comboArgs);
		}
	}
	else if(muFldUIType==100)
	{
	  var comboUrl = "/crm/jsp/GetComboValues.jsp" ;
	  		var comboArgs = "fieldId="+fieldId;	
	  		if(http)
	  		{
	  			getObj("bulkUpdate_field").innerHTML="Loading...";
	  			//window.open(comboUrl+"?"+ comboArgs);	
	  			http.open("POST", comboUrl, true);
	  			http.setRequestHeader('Content-Type','application/x-www-form-urlencoded;charset=UTF-8');
	  			http.onreadystatechange=function()
	  			{
	  				if(http.readyState==4)
	  				{
	  					dataStr = http.responseText;
	  					var combovalObt = dataStr.split(",");
	  					objTxt += "<select id='txt_"+muFldUIType+"' Multiple class='importBox' name='txt_"+muFldUIType+"'>";
	                                          if(((fieldLabel != "Status" && moduleStr=="Segments")||(moduleStr != "Segments"))&&((fieldLabel != "Status" && moduleStr=="Exclusions")||(moduleStr != "Exclusions")) && ((fieldLabel !="Approval%20Status" && moduleStr == "Campaigns")|| (moduleStr != "Campaigns")) && ((fieldLabel != "Status" && fieldLabel !="Type" && moduleStr=="EventForms") || (moduleStr !="EventForms") ) && ((fieldLabel != "Status" && fieldLabel !="Type" && moduleStr=="InquiryForms") || (moduleStr !="InquiryForms") )  )
	                                          {
	                                                  objTxt +="<option value=''></option>";
	                                          }
	                                         	for(var i=0;i<combovalObt.length;i++)
	  					{
	  						var rat = combovalObt[i];
	  						rat = rat.replace(/</g,"<")
	  						rat = rat.replace(/>/g,">")
	  						objTxt += "<option value='"+rat+"'>"+rat;
	  					}
	  					objTxt += "</select><p></p></td></tr><tr><td class='qcfooter' align='center' colspan='2'>";
	  					objTxt += btnObjTxt;
	  					getObj("bulkUpdate_field").innerHTML=objTxt;
	  				}
	  			}
	  			http.send(comboArgs);
		}
		
			
	}
	else if(muFldUIType==500)
	{
		var comboUrl = "/crm/jsp/MassUpdateField.jsp" ;
  		var args = "module="+moduleStr+"&fieldId="+fieldId+"&fieldName="+fieldName+"&fieldLabel="+fieldLabel+"&fieldId="+fieldId+"&uiType="+muFldUIType;	
		http.open("POST", comboUrl, true);
	  	http.setRequestHeader('Content-Type','application/x-www-form-urlencoded;charset=UTF-8');
	  	http.onreadystatechange=function()
	  	{
	  		if(http.readyState==4)
	  		{
				dataStr = http.responseText;
				objTxt+=dataStr;
				objTxt += btnObjTxt;
	  			getObj("bulkUpdate_field").innerHTML=objTxt;
	  		}
		}
		http.send(args);
	}
	else if(muFldUIType==24 || muFldUIType==786)
	{
		objTxt += "<input type='text' id='txt_"+muFldUIType+"' name='txt_"+muFldUIType+"' class='textField' width='10%' maxlength='"+fieldLen +"' onkeydown=\"handleButton('button__"+muFldUIType+"',event)\">";	

		objTxt += "<span class='dim'> ["+dtPtn+"]</span></td></tr><tr>";
		if(muFldUIType==786)
		{
			objTxt += "<tr><td align='right' colspan='2' style='padding-bottom:5px; padding-right:80px;'><input size='6' type='text' class='textField' id='txt_"+muFldUIType+"time' name='txt_"+muFldUIType+"time' onkeydown=\"handleButton('button__"+muFldUIType+"',event)\"><span class='small dim'>&nbsp;[hh:mm]</span>&nbsp;&nbsp;&nbsp;</td></tr><tr><td class='qcfooter' align='center' colspan='2'>"; 
			objTxt += btnObjTxt;
		}
		else
		{
			objTxt +="<tr><td class='qcfooter' align='center' colspan='2'>";
		}
	}
	else if(muFldUIType==25)
	{
		objTxt += "<input type='text' id='txt_"+muFldUIType+"' name='txt_"+muFldUIType+"' class='textField' width='10%' maxlength='"+fieldLen +"' onkeydown=\"handleButton('button__"+muFldUIType+"',event)\"></td></tr><tr><td class='qcfooter' align='center' colspan='2'>";
	}
	else if(muFldUIType==32)
	{
		objTxt += "<input type='text' id='txt_"+muFldUIType+"' name='txt_"+muFldUIType+"' class='textField' width='10%' maxlength='"+fieldLen +"' onkeydown=\"handleButton('button__"+muFldUIType+"',event)\"></td></tr><tr><td class='qcfooter'align='center' colspan='2'>";
	}
	else if(muFldUIType==34)
	{
		objTxt += "<input type='text' id='txt_"+muFldUIType+"' name='txt_"+muFldUIType+"' class='textField' width='10%' maxlength='"+fieldLen +"' onkeydown=\"handleButton('button__"+muFldUIType+"',event)\"></td></tr><tr><td class='qcfooter'align='center' colspan='2'>";
	}
	else if(muFldUIType==36)
	{

		objTxt += "<input type='text' id='txt_"+muFldUIType+"' name='txt_"+muFldUIType+"' class='textField' width='10%' maxlength='"+fieldLen +"' onkeydown=\"handleButton('button__"+muFldUIType+"',event)\">";
//		objTxt += " <img src='/crm/images/calc.gif' align='absmiddle' style='cursor:hand;cursor:pointer' onclick=\"showCalc('txt_"+muFldUIType+")')\">
		objTxt += "</td></tr><tr><td class='qcfooter' align='center' colspan='2'>";
	}
	else if(muFldUIType==300 || muFldUIType==301)
	{
		objTxt += "<input type='checkbox' id='txt_"+muFldUIType+"' name='txt_"+muFldUIType+"'></td></tr><tr><td class='qcfooter' align='center' colspan='2'>";
	}

	if(muFldUIType == 24 || muFldUIType == 786)
	{
		cals = new Array();
		addCalendar('txt_'+muFldUIType, 'txt_'+muFldUIType,'txt_'+muFldUIType,'showcvdetails');
	}
	if(muFldUIType!=2 && muFldUIType!=786 && muFldUIType!=100 && muFldUIType!=500)
	{
		objTxt += btnObjTxt;
	}
	getObj("bulkUpdate_field").innerHTML=objTxt;
	//alert("objTxt-->"+objTxt);
	document.getElementById("bulkUpdate_field").style.top=document.getElementById("idForCV").offsetHeight;
	show("bulkUpdate_field");
	if(muFldUIType!=2 && muFldUIType!=500)
	{
		if(getObj("txt_"+muFldUIType)!=null)
		{
			getObj("txt_"+muFldUIType).focus();
	    }		
	}
	//freezeBackground();
}
function replaceBySpace(str)
{
	var errorContent=str.split("%20");
	var newStr="";
	for(i=0;i<errorContent.length;i++)
	{
		if(i==0)
		{
			newStr=errorContent[i];
		}
		else
		{
			newStr=newStr+ " " + errorContent[i];
		}
	}
	return newStr;
}
function setGMultiSelect()
{
 	var selectedValues="";
	if(getObj("gmultiselect"))
	{
		var tempGroups = getObj("gmultiselect").value;
		if (tempGroups)
		{
			var totalGroups=tempGroups.split("@@@");
			for(var i=0;i<totalGroups.length-1;i++)
			{
				tempGroups=totalGroups[i].split("::");
				var totalGroup_index=tempGroups[0];
				var totalGroupName=tempGroups[1];
	 			var group_object=getObj("property("+totalGroupName+"_temp)").value;
				var totalSubGroups=group_object.split("@@@");
	            for(var j=0;j<totalSubGroups.length-1;j++)
	            {
					tempGroups=totalSubGroups[j].split("::");
					var groupName=tempGroups[0];
					var chk_count=tempGroups[1];
					for(var k=1;k<=chk_count;k++)
					{
						var check_object=getObj("chk"+(i+1)+"_"+(j+1)+"_"+k)
						if(check_object.checked==true)
						{
							if (selectedValues == '')
								selectedValues = groupName + "--" + check_object.value;
							else
								if(selectedValues.indexOf(groupName+"--")>=0)
									selectedValues = selectedValues + "::" + check_object.value;
								else
									selectedValues = selectedValues + "##" + groupName + "--" + check_object.value;
	
	 					}
					}
				}
				getObj("property("+totalGroupName+")").value=selectedValues;
	 			selectedValues='';
			}
		}
	}
}
function CallonMassUpdate(actionUrl, module, tableName, columnName, uiType, fieldLabel, fieldDatatype, append_ids, cvname, cvid, start_index, end_index, rangeValue)
{
	var fldValue = "";
	if(uiType ==1 || uiType==21 || uiType==33 || uiType==34 || uiType==35||uiType==37 || uiType==24 || uiType == 25 || uiType==32 || uiType==36 )
	{
		fldValue = getObj("txt_"+uiType).value.trim();	
	}
	else if(uiType==2)
	{
		fldValue = getObj("txt_"+uiType).value.trim();
	}
	else if(uiType==100)
	{
			var nnnn="txt_"+uiType;
			var len=getObj(nnnn).options.length;
			var str="";
			for(var ii=1;ii<len;ii++)
			{
			     
			     if(getObj(nnnn).options[ii].selected)
			       {
			        //alert(getObj(nnnn).options[ii].value);
			        str=str+getObj(nnnn).options[ii].value+";";
			       } 
			}  
			fldValue =str;
			
	}
	else if(uiType==500)
	{
		setGMultiSelect();
		fldValue=getObj("property("+fieldLabel+")").value;
	}
	else if(uiType ==300 || uiType ==301)
	{
		fldValue = getObj("txt_"+uiType).checked;	
	}
	else if(uiType==786)
	{
		dtime="txt_"+uiType;
               	ttime="txt_"+uiType+"time";
 		fldValue = trim(getObj(dtime).value) + ' ' +trim(getObj(ttime).value);
	}
	
	//alert("Going to send args");
	var doMupFormValid = mupFieldValidate(fieldLabel,fldValue,uiType, fieldDatatype);
		if(!doMupFormValid)
		{
			getObj("txt_"+uiType).focus();
			return false;
		}
	
	var searchStr='';
		if(document.showcvdetails!=null)
		{
            var searchlettervalue ="";
        if(document.showcvdetails.searchletter!=undefined)
        {
            searchlettervalue =document.showcvdetails.searchletter.value;
        }
			searchStr="&searchString="+document.showcvdetails.searchString.value+"&sortColumnString="+document.showcvdetails.sortColumnString.value+"&sortOrderString="+document.showcvdetails.sortOrderString.value+"&searchletter="+ searchlettervalue;
		}
		var args ="module="+ module+"&fieldLabel="+encodeURIComponent(fieldLabel)+"&fieldValue="+encodeURIComponent(fldValue) +"&uiType="+uiType+"&tableName="+tableName+"&columnName="+columnName+"&idlist="+append_ids+"&display_cust_view_name="+cvname+"&cvid="+cvid+"&start_index="+start_index+"&end_index="+end_index+"&rangeValue="+rangeValue+''+searchStr;
		if(document.getElementById("advSearchEnable"))
		{
			var advSearchEnable = document.getElementById("advSearchEnable").value;
			if(advSearchEnable == "true")
			{
				var formData = formData2QueryString(document.showcvdetails);
				args = args + "&"+formData+"&advSearchEnable="+advSearchEnable;
			}
		 }
	loadAjaxTab4("Loading...");
	new Ajax.Request(actionUrl,{method:"post",onSuccess:function(t)
       {
		var str = t.responseText;
		if(str.indexOf("Why does my session expire")>-1 || str.indexOf("Affordable for Medium Business") > -1)
		{
			ResourceUtil.getJSAlertValue("crm.reauth.login.expired",singularModule,loc, function(str){		alert(str); 	});
			document.location.href="/crm/ShowHomePage.do" 
			return;
		}
		if(str.indexOf("SECURITY::::")>-1)
		{
				var errorContent=str.split("SECURITY::::");
				divObj = getObj('ShowCustomViewDetails');
				divObj.innerHTML="";    
				divObj.innerHTML=errorContent[1];
			}    
			else if(str.indexOf("DELETE::::")>-1)  
			{
				var deleteContent=str.split("DELETE::::");
				divObj = getObj('ShowCustomViewDetails');
				divObj.innerHTML="";
				divObj.innerHTML=deleteContent[1];
			}
			else
			{
				divObj = getObj('idForCV');
				divObj.innerHTML="";
				divObj.innerHTML=str;
				deSelectAll();
				if (document.getElementById("FreezeLayer") != null) 
				{
					document.body.removeChild(document.getElementById("FreezeLayer"));
				}
				document.getElementById('ajax_load_tab').style.display='none';
				if( advSearchEnable=="true"){      
		            callAdvSearch(module)
		        }
				getObj("bulkUpdateSuccess").innerHTML='<table width="100%" ><tr><td align="center" class="widgetalert" ><b>Updated Successfully</b></td></tr></table>';
				setCenter(document.getElementById("bulkUpdateSuccess"));
				show("bulkUpdateSuccess");
				setTimeout(function(){hide("bulkUpdateSuccess")},2000);
			}
       },asynchronous:true,postBody:args
       });
	hide("bulkUpdateFldsList");
	
}
function deSelectAll()
{
	if (document.showcvdetails.chk != undefined)
	{
		noofentries = document.showcvdetails.chk.length;
		if(noofentries == undefined)
		{
			document.showcvdetails.chk.checked = false;
		}

		for(i=0 ; i < noofentries ; i++)
		{
			document.showcvdetails.chk[i].checked = false;
		}
	}
}

function mupFieldValidate(fieldLabel, fldValue, uiType, dataType)
{
	fieldLabel =replaceBySpace(fieldLabel); 
	var fieldName="txt_"+uiType;
	//alert("Inside mupFieldValidate fieldName ::: "+fieldName);
	var type=dataType.split("~");
	//alert("mupFieldValidate type is " +type);
	if (type[1]=="M") {
            if (!emptyCheck(fieldName,fieldLabel))
                return false
        }
	switch (type[0]) {
            case "O"  : break;
            case "V"  : break;
            case "C"  : break;
	    case "E"  : 
			if (getObj(fieldName) != null 
				&& getObj(fieldName).value.replace(/^\s+/g, '').replace(/\s+$/g, '').length!=0) 
			{
				if (!emailValidate(fieldName,fieldLabel))
                            		return false
			}
			break;	
            case "DT" :
		  	if (getObj(fieldName) != null 
				&& getObj(fieldName).value.replace(/^\s+/g, '').replace(/\s+$/g, '').length!=0)
			{
				if(typeof(type[3])=="undefined") var currdatechk="OTH"
				else var currdatechk=type[3]

				type[2] = "txt_"+uiType+"time"; // to set proper field name for timefield
				if (!dateTimeValidate(fieldName,type[2],fieldLabel,currdatechk))
					return false
				if (type[4]) 
				{
					if (!dateTimeComparison(fieldName,type[2],fieldLabel,type[5],type[6],type[7],type[4]))
						return false
				}    
			}
                        break;
            case "D"  :    
                    	if (getObj(fieldName) != null 
				&& getObj(fieldName).value.replace(/^\s+/g, '').replace(/\s+$/g, '').length!=0)
			{
                    		if(typeof(type[2])=="undefined") var currdatechk="OTH"
                                        else var currdatechk=type[2]

                    		if (!dateValidate(fieldName,fieldLabel,currdatechk))
                            		return false
                    		if (type[3]) {
                        		if (!dateComparison(fieldName,fieldLabel,type[4],type[5],type[3]))
                                	return false
                          	}    
			}
                        break;
            case "T"  :
                    	if (getObj(fieldName) != null 
					&& getObj(fieldName).value.replace(/^\s+/g, '').replace(/\s+$/g, '').length!=0)
		    	{
                    		if(typeof(type[2])=="undefined") var currtimechk="OTH"
                                        else var currtimechk=type[2]

                    		if (!timeValidate(fieldName,fieldLabel,currtimechk))
                            		return false
                        	if (type[3]) 
				{
                            		if (!timeComparison(fieldName,fieldLabel,type[4],type[5],type[3]))
                                		return false
                           	}
			}
                        break;
            case "I"  :    
                    	if (getObj(fieldName) != null 
				&& getObj(fieldName).value.replace(/^\s+/g, '').replace(/\s+$/g, '').length!=0)
                   	{
                        	if (!intValidate(fieldName,fieldLabel))
                            		return false
                           	if (type[2]) {
                            		if (!numConstComp(fieldName,fieldLabel,type[2],type[3]))
                                		return false
                           	}
                    	}
			break;
            case "N"  :
                    	if (getObj(fieldName) != null 
				&& getObj(fieldName).value.replace(/^\s+/g, '').replace(/\s+$/g, '').length!=0)
                    	{
                        	if (typeof(type[2])=="undefined") var numformat="any"
                        	else var numformat=type[2]
                    
                        	if (!numValidate(fieldName,fieldLabel,numformat))
                        		return false
	                        if (type[3]) 
				{
                	               	if (!numConstComp(fieldName,fieldLabel,type[3],type[4]))
                        			return false
                        	}
                    	}
                    	break;
	     case "P" :
			if(getObj(fieldName) !=null && 
				getObj(fieldName).value.replace(/^\s+/g, '').replace(/\s+$/g, '').length!=0)
                    	{
                        	if (!phoneValidate(fieldName,fieldLabel))
                        		return false
                    	}
                    	break;
        	}

	return true
}

//prabu
function shrink(obj)
{
var tagName = document.getElementById(obj)
if(tagName==null)
{

window.history.back();
}
else
{
new Effect.Shrink(obj);
}
}
function grow(obj)
{
Effect.Grow(obj);
}
function appear(obj)
{
Effect.Appear(obj)
}
function squish(obj)
{
Effect.Squish(obj)
}

function loadAjaxTab3(str,style)
{
        var divId = document.getElementById('ajax_load_tab');
        divId.style.display = "block";
        divId.innerHTML = '<span><img src="/crm/images/loader.gif" align="absmiddle"></span>&nbsp; ' + str + '...';
}
//ending



if (document.all)

	var browser_ie=true

else if (document.layers)

	var browser_nn4=true

else if (document.layers || (!document.all && document.getElementById))

	var browser_nn6=true
if (window.navigator.userAgent.toUpperCase().indexOf("OPERA") >= 0)	
	var browser_opera=true;



function getObj(n,d) {
  var p,i,x; 

  if(!d)

      d=document;

   

  if((p=n.indexOf("?"))>0&&parent.frames.length) {

        if((n.substring(p+1))!="")
        {
            d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);
        }

  }



  if(!(x=d[n])&&d.all)

      x=d.all[n];

 

  for(i=0;!x&&i<d.forms.length;i++)

      x=d.forms[i][n];

 

  for(i=0;!x&&d.layers&&i<d.layers.length;i++)

      x=getObj(n,d.layers[i].document);

 

  if(!x && d.getElementById)

      x=d.getElementById(n);



  return x;

}

	

function getOpenerObj(n) {

    return getObj(n,opener.document)

}



function findPosX(obj) {

	var curleft = 0;

	if (document.getElementById || document.all) {

		while (obj.offsetParent) {

			curleft += obj.offsetLeft

			obj = obj.offsetParent;

		}

	} else if (document.layers) {

		curleft += obj.x;

	}



	return curleft;

}



function findPosY(obj) {

	var curtop = 0;



	if (document.getElementById || document.all) {

		while (obj.offsetParent) {

			curtop += obj.offsetTop

			obj = obj.offsetParent;

		}

	} else if (document.layers) {

		curtop += obj.y;

	}



	return curtop;

}



function clearTextSelection() {

	if (browser_ie) document.selection.empty();

    else if (browser_nn4 || browser_nn6) window.getSelection().removeAllRanges();

}

// Setting cookies
function set_cookie ( name, value, exp_y, exp_m, exp_d, path, domain, secure )
{
  var cookie_string = name + "=" + escape ( value );

  if (exp_y) //delete_cookie(name)
  {
    var expires = new Date ( exp_y, exp_m, exp_d );
    cookie_string += "; expires=" + expires.toGMTString();
  }

  if (path) cookie_string += "; path=" + escape ( path );
  if (domain) cookie_string += "; domain=" + escape ( domain );
  if (secure) cookie_string += "; secure";

  document.cookie = cookie_string;
}

// Retrieving cookies
function get_cookie(cookie_name)
{
  var results = document.cookie.match(cookie_name + '=(.*?)(;|$)');
  if (results) return (unescape(results[1]));
  else return null;
}

// Delete cookies 
function delete_cookie( cookie_name )
{
  var cookie_date = new Date ( );  // current date & time
  cookie_date.setTime ( cookie_date.getTime() - 1 );
  document.cookie = cookie_name += "=; expires=" + cookie_date.toGMTString();
}

//End of Utility Functions


function emptyCheck(fldName,fldLabel, fldType) {
	if(getObj(fldName))
	{
		var currObj=getObj(fldName)
		 
		if( (currObj.value == "none" || currObj.value =="-None-" || currObj.value.replace(/^\s+/g, '').length==0) ) 
			{
				if(getObj('property(module)')!=null)
				{
					var moduleName = getObj('property(module)').value; 
                                        if(moduleName == 'Experiences' && fldLabel=="Organization Name")
                                        {
                                            fldLabel="Company Name";
                                        }
					if(moduleName == 'Cases')
					{
						if(currObj.name=='property(CaseType)')
						{
							selectone.getJSAlertValue("crm.alert.message.type.select",null,"en_US",
									function(mesg) { alert(mesg) })
						}
						else if(currObj.name=='property(CaseChannel)')
						{
							selectone.getJSAlertValue("crm.alert.not.blank",fldLabel,"en_US",
									function(mesg) { alert(mesg) })
						}
						else if(currObj.name=='property(Status)')
						{
							selectone.getJSAlertValue("crm.alert.case.status.select",null,"en_US",
									function(mesg) { alert(mesg) })

						}
						else
						{
							selectone.getJSAlertValue("crm.alert.not.blank",fldLabel,"en_US",
									function(mesg) { alert(mesg) })
						}

					}    
					else 
					{
						selectone.getJSAlertValue("crm.alert.not.blank",fldLabel,"en_US",
								function(mesg) { alert(mesg) })    
						if(getObj("uiType_"+fldName))
                                                {
                                                	var uiTypeFld = parseInt(getObj("uiType_"+fldName).value);
                                                    if( uiTypeFld != 100 && uiTypeFld != 500)
                                                    {
                                                        currObj.focus()	   
                                                    }
                                                }
                                                else
                                                {
                                                    currObj.focus()	   
                                                }    
						return false
					}
				}
				else 
				{
                                    callSelectOneMethod(dwrChkVar,"crm.alert.not.blank",null,"en_US",fldLabel);	
					var isInterestField  = fldLabel.search("Interests");
					if(isInterestField == -1)
					{	
						currObj.focus();
					}
					
				return false
				}

				if(getObj("programWizard"))
				{
					if( ( currObj.name == 'property(Program Name)' || currObj.name == 'property(comboValue1)' || currObj.name == 'property(Program Cost)')  && getObj("programWizard").style.display == 'none')
					{
						getObj("IterationWizard").style.display = "none";
						getObj("programWizard").style.display = 'block';		
					}
				}
				currObj.focus()
					return false

			}   

		if (currObj.value.replace(/^\s+/g, '').replace(/\s+$/g, '').length==0) 
		{
			selectone.getJSAlertValue("crm.alert.not.blank",fldLabel,"en_US",
					function(mesg) { alert(mesg) })    

				if(getObj("programWizard"))
				{
					if( ( currObj.name == 'property(Program Name)' || currObj.name == 'property(comboValue1)' || currObj.name == 'property(Program Cost)')  && getObj("programWizard").style.display == 'none')
					{
						getObj("IterationWizard").style.display = "none";
						getObj("programWizard").style.display = 'block';		
					}
				}
			currObj.focus()

				return false

		}

		else

			return true
	}
	return true;
}



function patternValidate(fldName,fldLabel,type) {
    var currObj=getObj(fldName)


    if (type.toUpperCase()=="EMAIL") //Email ID validation	
                       
    	var re=/^\w+([a-zA-Z0-9_+'*$%#=?`~{}\^&!\.\-\/])*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/
           
    if (type.toUpperCase()=="DATE") {//DATE validation

	    if(userDateFormat==undefined || userDateFormat=="" || userDateFormat=="null")
	    {
		userDateFormat=(getObj("dtPtn"))?getObj("dtPtn").value:"";
	    }
	 switch (userDateFormat.toLowerCase()) {
		
                        case "yyyy/mm/dd" :
                                                var re = /^\d{4}(\/)\d{1,2}\1\d{1,2}$/
                                                break;
			case "yyyy.mm.dd" :	
                                                var re = /^\d{4}(\.)\d{1,2}\1\d{1,2}$/
                                                break;
                        case "yyyy-mm-dd" :
                                                var re = /^\d{4}(\-|)\d{1,2}\1\d{1,2}$/
                                                break;

			case "mm/dd/yyyy" :
                                                var re = /^\d{1,2}(\/)\d{1,2}\1\d{4}$/
                                                break;
			case "mm.dd.yyyy" :
                                                var re = /^\d{1,2}(\.)\d{1,2}\1\d{4}$/
                                                break;
                        case "mm-dd-yyyy" :
                                                var re = /^\d{1,2}(\-)\d{1,2}\1\d{4}$/
                                                break;


                        case "dd/mm/yyyy" :
                                                var re = /^\d{1,2}(\/)\d{1,2}\1\d{4}$/
                                                break;
                        case "dd.mm.yyyy" :
                                                var re = /^\d{1,2}(\.)\d{1,2}\1\d{4}$/
                                                break;
                        case "dd-mm-yyyy" :
                                                var re = /^\d{1,2}(\-)\d{1,2}\1\d{4}$/

                }

    }
    
    if (type.toUpperCase()=="TIME") {//TIME validation
        var re = /^\d{1,2}(\:\d{1,2})*$/
    }
	
    if (!re.test(trimBoth(currObj.value))) {    
        callSelectOneMethod(dwrChkVar,"crm.alert.entry.valid",null,"en_US",fldLabel);
        currObj.focus()
        return false
    }
 }


function emailValidate(fldName,fldLabel) {
	if(patternValidate(fldName,fldLabel,"EMAIL")==false)
            return false;
        return true;
}

function splitDateVal(dateval) {
        var datesep;
        var dateelements = new Array(3);

        if (dateval.indexOf("-")>=0) datesep="-"
        else if (dateval.indexOf(".")>=0) datesep="."
        else if (dateval.indexOf("/")>=0) datesep="/"
        switch (userDateFormat.toLowerCase()) {
		case "yyyy/mm/dd" :
		case "yyyy.mm.dd" :		
                case "yyyy-mm-dd" :
                                                        dateelements[0]=dateval.substr(dateval.lastIndexOf(datesep)+1,dateval.length) //dd
                                                        dateelements[1]=dateval.substring(dateval.indexOf(datesep)+1,dateval.lastIndexOf(datesep)) //mm
                                                        dateelements[2]=dateval.substring(0,dateval.indexOf(datesep)) //yyyyy
                                                        break;
		case "mm/dd/yyyy" :
		case "mm.dd.yyyy" :
                case "mm-dd-yyyy" :
                                                        dateelements[0]=dateval.substring(dateval.indexOf(datesep)+1,dateval.lastIndexOf(datesep))
                                                        dateelements[1]=dateval.substring(0,dateval.indexOf(datesep))
                                                        dateelements[2]=dateval.substr(dateval.lastIndexOf(datesep)+1,dateval.length)
                                                        break;
		case "dd/mm/yyyy" :
		case "dd.mm.yyyy" :
                case "dd-mm-yyyy" :
                                                        dateelements[0]=dateval.substring(0,dateval.indexOf(datesep))
                                                        dateelements[1]=dateval.substring(dateval.indexOf(datesep)+1,dateval.lastIndexOf(datesep))
                                                        dateelements[2]=dateval.substr(dateval.lastIndexOf(datesep)+1,dateval.length)
        }

        return dateelements;
}


function comparingDates(date1,fldLabel1,date2,fldLabel2,type) {

    var ret=true	
    switch (type) {
        case 'L'    :    if (date1>=date2) {//DATE1 VALUE LESS THAN DATE2
                            callSelectOne2VarMethod(dwrChkVar,"crm.alert.less.than",null,"en_US",fldLabel1,fldLabel2)                            
                            ret=false
                        }
                        break;
        case 'LE'    :    if (date1>date2) {//DATE1 VALUE LESS THAN OR EQUAL TO DATE2
                            callSelectOne2VarMethod(dwrChkVar,"crm.alert.less.than.equal.to",null,"en_US",fldLabel1,fldLabel2)                            
                            ret=false
                        }
                        break;
        case 'E'    :    if (date1!=date2) {//DATE1 VALUE EQUAL TO DATE
                            callSelectOne2VarMethod(dwrChkVar,"crm.alert.equal.to",null,"en_US",fldLabel1,fldLabel2)
                            ret=false
                        }
                        break;
        case 'G'    :    if (date1<=date2) {//DATE1 VALUE GREATER THAN DATE2
                            callSelectOne2VarMethod(dwrChkVar,"crm.alert.greater.than",null,"en_US",fldLabel1,fldLabel2)                            
                            ret=false
                        }
                        break;    
        case 'GE'    :    if (date1<date2) {//DATE1 VALUE GREATER THAN OR EQUAL TO DATE2
                            callSelectOne2VarMethod(dwrChkVar,"crm.alert.greater.than.equal.to",null,"en_US",fldLabel1,fldLabel2)       
                            ret=false
                        }
                        break;
    }
    
    if (ret==false) return false
    else return true
}

function dateTimeValidate(dateFldName,timeFldName,fldLabel,type) {

    if(patternValidate(dateFldName,fldLabel,"DATE")==false)
                return false;
    dateval=getObj(dateFldName).value.replace(/^\s+/g, '').replace(/\s+$/g, '')
   
    var dateelements=splitDateVal(dateval)

    dd=dateelements[0]
    mm=dateelements[1]
    yyyy=dateelements[2]
     
    if (dd<1 || dd>31 || mm<1 || mm>12 || yyyy<1 || yyyy<1000) {
        callSelectOneMethod(dwrChkVar,"crm.alert.entry.valid",null,"en_US",fldLabel);
        getObj(dateFldName).focus()
		if (dd<1 || dd>31) selInvalidText(getObj(dateFldName),dd)
		if (mm<1 || mm>12) selInvalidText(getObj(dateFldName),mm)
		if (yyyy<1 || yyyy<1000) selInvalidText(getObj(dateFldName),yyyy)
        return false
    }
    
    if ((mm==2) && (dd>29)) {//checking of no. of days in february month
        callSelectOneMethod(dwrChkVar,"crm.alert.entry.valid",null,"en_US",fldLabel);
        getObj(dateFldName).focus()
		selInvalidText(getObj(dateFldName),dd)
        return false
    }
    
    if ((mm==2) && (dd>28) && ((yyyy%4)!=0)) {//leap year checking
        callSelectOneMethod(dwrChkVar,"crm.alert.entry.valid",null,"en_US",fldLabel);
        getObj(dateFldName).focus()
		selInvalidText(getObj(dateFldName),dd)
        return false
    }

    switch (parseInt(mm)) {
        case 2 :
        case 4 :
        case 6 :
        case 9 :
        case 11 :    if (dd>30) {
                        callSelectOneMethod(dwrChkVar,"crm.alert.entry.valid",null,"en_US",fldLabel);
                        getObj(dateFldName).focus()
						selInvalidText(getObj(dateFldName),dd)
                        return false
                    }    
    }
    
    if (patternValidate(timeFldName,fldLabel,"TIME")==false)
        return false
        
    var timeval=getObj(timeFldName).value.replace(/^\s+/g, '').replace(/\s+$/g, '')

    if (timeval.indexOf(":") < 0 )
    {
	callSelectOneMethod(dwrChkVar,"crm.alert.entry.valid",null,"en_US",fldLabel);
	getObj(timeFldName).focus()
	selInvalidText(getObj(timeFldName),timeval)
	return false	
    }
    var hourval=parseInt(timeval.substring(0,timeval.indexOf(":")))
    var minval=parseInt(timeval.substring(timeval.indexOf(":")+1,timeval.length))
    var currObj=getObj(timeFldName)
    
    if (hourval>23 || minval>59) {
        callSelectOneMethod(dwrChkVar,"crm.alert.entry.valid",null,"en_US",fldLabel);
        currObj.focus()
		if (hourval>23) selInvalidText(getObj(timeFldName),hourval)
		if (minval>59) selInvalidText(getObj(timeFldName),minval)
        return false
    }
    
    var currdate=new Date()
    var chkdate=new Date()
    chkdate.setYear(yyyy)
    chkdate.setMonth(mm-1)
    chkdate.setDate(dd)
    chkdate.setHours(hourval)
    chkdate.setMinutes(minval)

    
    if (type!="OTH") {
        if (!comparingDates(chkdate,fldLabel,currdate,"current date & time",type)) {
            getObj(dateFldName).focus()
            return false
        } else return true;
    } else return true;
}

function dateTimeComparison(dateFldName1,timeFldName1,fldLabel1,dateFldName2,timeFldName2,fldLabel2,type) {
    var dateval1=getObj(dateFldName1).value.replace(/^\s+/g, '').replace(/\s+$/g, '')
    //var dateval2=getObj(dateFldName2).value.replace(/^\s+/g, '').replace(/\s+$/g, '')
    if(getObj(dateFldName2))
    {
        var dateval2=getObj(dateFldName2).value.replace(/^\s+/g, '').replace(/\s+$/g, '')
    }
    else if(getObj(fldLabel2))
    {
        var dateval2=document.getElementById("value_"+fldLabel2).innerHTML.replace(/^\s+/g, '').replace(/\s+$/g, '')
        if(dateval2.indexOf("&nbsp;"))
        {
             dateval2=dateval2.substring(0,dateval2.indexOf("&nbsp;"))
        }
    } 
   
var dateelements1=splitDateVal(dateval1)
        var dateelements2=splitDateVal(dateval2)

        dd1=dateelements1[0]
        mm1=dateelements1[1]
        yyyy1=dateelements1[2]

        dd2=dateelements2[0]
        mm2=dateelements2[1]
        yyyy2=dateelements2[2]
   
    var timeval1=getObj(timeFldName1).value.replace(/^\s+/g, '').replace(/\s+$/g, '')
    //var timeval2=getObj(timeFldName2).value.replace(/^\s+/g, '').replace(/\s+$/g, '')
     if(getObj(timeFldName2))
    {
        var timeval2=getObj(timeFldName2).value.replace(/^\s+/g, '').replace(/\s+$/g, '')        
    }
    else if(getObj(fldLabel2))
    {        
        var timeval2=document.getElementById("value_"+fldLabel2).innerHTML.replace(/^\s+/g, '').replace(/\s+$/g, '')
        if(timeval2.indexOf("&nbsp;"))
        {
             timeval2=timeval2.substring(timeval2.lastIndexOf("&nbsp;")+6,timeval2.length)
             
        }
    } 
    
    var hh1=timeval1.substring(0,timeval1.indexOf(":"))
    var min1=timeval1.substring(timeval1.indexOf(":")+1,timeval1.length)
    
    var hh2=timeval2.substring(0,timeval2.indexOf(":"))
    var min2=timeval2.substring(timeval2.indexOf(":")+1,timeval2.length)
    
    var date1=new Date()
    var date2=new Date()        
    
    date1.setYear(yyyy1)
    date1.setMonth(mm1-1)
    date1.setDate(dd1)
    date1.setHours(hh1)
    date1.setMinutes(min1)
    
    date2.setYear(yyyy2)
    date2.setMonth(mm2-1)
    date2.setDate(dd2)
    date2.setHours(hh2)
    date2.setMinutes(min2)
	
    
    if (type!="OTH") {
        if (!comparingDates(date1,fldLabel1,date2,fldLabel2,type)) {
            getObj(dateFldName1).focus()
            return false
        } else return true;
    } else return true;
}

function dateValidate(fldName,fldLabel,type) {
    if(patternValidate(fldName,fldLabel,"DATE")==false)
        return false;
    dateval=getObj(fldName).value.replace(/^\s+/g, '').replace(/\s+$/g, '')
var dateelements=splitDateVal(dateval)

        var dd=dateelements[0]
        var mm=dateelements[1]
        var yyyy=dateelements[2]
    
    
    if (dd<1 || dd>31 || mm<1 || mm>12 || yyyy<1 || yyyy<1000) {
        callSelectOneMethod(dwrChkVar,"crm.alert.entry.valid",null,"en_US",fldLabel);        
        getObj(fldName).focus()
		if (dd<1 || dd>31) selInvalidText(getObj(fldName),dd)
		if (mm<1 || mm>12) selInvalidText(getObj(fldName),mm)
		if (yyyy<1 || yyyy<1000) selInvalidText(getObj(fldName),yyyy)
        return false
    }
    
    if ((mm==2) && (dd>29)) {//checking of no. of days in february month
        callSelectOneMethod(dwrChkVar,"crm.alert.entry.valid",null,"en_US",fldLabel);  
        getObj(fldName).focus()
		selInvalidText(getObj(fldName),dd)
        return false
    }
    
    if ((mm==2) && (dd>28) && ((yyyy%4)!=0)) {//leap year checking
        callSelectOneMethod(dwrChkVar,"crm.alert.entry.valid",null,"en_US",fldLabel);  
        getObj(fldName).focus()
		selInvalidText(getObj(fldName),dd)
        return false
    }

    switch (parseInt(mm)) {
        case 2 :
        case 4 :
        case 6 :
        case 9 :
        case 11 :    if (dd>30) {
                        callSelectOneMethod(dwrChkVar,"crm.alert.entry.valid",null,"en_US",fldLabel);  
                        getObj(fldName).focus()
						selInvalidText(getObj(fldName),dd)
                        return false
                    }    
    }
    
    var currdate=new Date()
    var chkdate=new Date()
    
    chkdate.setYear(yyyy)
    chkdate.setMonth(mm-1)
    chkdate.setDate(dd)
    
    if (type!="OTH") {
        if (!comparingDates(chkdate,fldLabel,currdate,"current date",type)) {
            getObj(fldName).focus()
            return false
        } else return true;
    } else return true;
}

function dateComparison(fldName1,fldLabel1,fldName2,fldLabel2,type) {
    var dateval1=getObj(fldName1).value.replace(/^\s+/g, '').replace(/\s+$/g, '')
    //var dateval2=getObj(fldName2).value.replace(/^\s+/g, '').replace(/\s+$/g, '')
    if(getObj(fldName2))   
    {	
            var dateval2=getObj(fldName2).value.replace(/^\s+/g, '').replace(/\s+$/g, '')
    }
    else
    {
            var dateval2=getObj("value_"+fldLabel2).innerHTML.replace(/^\s+/g, '').replace(/\s+$/g, '')
            if(dateval2.indexOf("&nbsp;"))
            {
                 dateval2=dateval2.substring(0,dateval2.indexOf("&nbsp;"))
            }
    } 
    
var dateelements1=splitDateVal(dateval1)
        var dateelements2=splitDateVal(dateval2)

        dd1=dateelements1[0]
        mm1=dateelements1[1]
        yyyy1=dateelements1[2]

        dd2=dateelements2[0]
        mm2=dateelements2[1]
        yyyy2=dateelements2[2]
   
    var date1=new Date()
    var date2=new Date()        
    
    date1.setYear(yyyy1)
    date1.setMonth(mm1-1)
    date1.setDate(dd1)        
    
    date2.setYear(yyyy2)
    date2.setMonth(mm2-1)
    date2.setDate(dd2)
    
    if (type!="OTH") {
        if (!comparingDates(date1,fldLabel1,date2,fldLabel2,type)) {
            getObj(fldName1).focus()
            return false
        } else return true;
    } else return true
}

function timeValidate(fldName,fldLabel,type) {
    if (patternValidate(fldName,fldLabel,"TIME")==false)
        return false
        
    var timeval=getObj(fldName).value.replace(/^\s+/g, '').replace(/\s+$/g, '')
    var hourval=parseInt(timeval.substring(0,timeval.indexOf(":")))
    var minval=parseInt(timeval.substring(timeval.indexOf(":")+1,timeval.length))
    var currObj=getObj(fldName)
    if (isNaN(hourval)||isNaN(minval))
    {
    	 callSelectOneMethod(dwrChkVar,"crm.alert.entry.valid",null,"en_US",fldLabel);  
         currObj.focus()
    	return false;
    }
    if (hourval>23 || minval>59) {
        callSelectOneMethod(dwrChkVar,"crm.alert.entry.valid",null,"en_US",fldLabel);  
        currObj.focus()
		if (hourval>23) selInvalidText(getObj(fldName),hourval)
		if (minval>59) selInvalidText(getObj(fldName),minval)
        return false
    }
    
    var currtime=new Date()
    var chktime=new Date()
    
    chktime.setHours(hourval)
    chktime.setMinutes(minval)
    
    if (type!="OTH") {
        if (!comparingDates(chktime,fldLabel,currtime,"current time",type)) {
            getObj(fldName).focus()
            return false
        } else return true;
    } else return true
}

function timeComparison(fldName1,fldLabel1,fldName2,fldLabel2,type) {
    var timeval1=getObj(fldName1).value.replace(/^\s+/g, '').replace(/\s+$/g, '')
    var timeval2=getObj(fldName2).value.replace(/^\s+/g, '').replace(/\s+$/g, '')
    
    var hh1=timeval1.substring(0,timeval1.indexOf(":"))
    var min1=timeval1.substring(timeval1.indexOf(":")+1,timeval1.length)
    
    var hh2=timeval2.substring(0,timeval2.indexOf(":"))
    var min2=timeval2.substring(timeval2.indexOf(":")+1,timeval2.length)

    var time1=new Date()
    var time2=new Date()        
    
    time1.setHours(hh1)
    time1.setMinutes(min1)
    
    time2.setHours(hh2)
    time2.setMinutes(min2)

    if (type!="OTH") {    
        if (!comparingDates(time1,fldLabel1,time2,fldLabel2,type)) {
            getObj(fldName1).focus()
            return false
        } else return true;
    } else return true;
}

function numValidate(fldName,fldLabel,format,fielddecimal) {


	if (getObj(fldName) != null && getObj(fldName).value.replace(/^\s+/g, '').replace(/\s+$/g, '').length!=0)
	{
		var val=getObj(fldName).value.replace(/^\s+/g, '').replace(/\s+$/g, '');
		if (format!="any") {
			var format=format.split(",");
			var restr="/^\\d{1,"+format[0]+"}(\\.\\d{1,"+format[0]+"})$/";
			var re=eval(restr);
		} else {
			//var re=/^\d+(\.\d\d*)*$/
			//var re=/^\d+(,(\d)+)*(\.\d*)$/;
			//var re=/^\d+(,(\d)+)*(\.\d{1,2})*$/ 
			var re=/^\d+(,(\d)+)*(\.)?(\d*)$/;
		}
		var no = val.substr(val.indexOf(".")+1);
		if (!re.test(val)) {
			callSelectOneMethod(dwrChkVar,"crm.alert.entry.valid",null,"en_US",fldLabel);  
			if(getObj("programWizard"))
			{
				if( ( getObj(fldName).name == 'property(Program Name)' || getObj(fldName).name == 'property(comboValue1)' || getObj(fldName).name == 'property(Program Cost)')  && getObj("programWizard").style.display == 'none')
				{
					getObj("IterationWizard").style.display = "none";
					getObj("programWizard").style.display = 'block';		
				}
			}
			getObj(fldName).focus();
			return false;
		}
		else
		{
			var re1=/^\d+(,(\d)+)*(\.\d{1,2})$/;
            var uiType = (getObj("uiType_"+fldLabel))?getObj("uiType_"+fldLabel).value:1;
            
            var alertstr = "crm.alert.dec.place.max.two";
            if(uiType=='60')
            {
                if(fielddecimal!=undefined)
                {
                    var fielddecimali = parseInt(fielddecimal);
                    if(fielddecimali==3)
                    {
                        re1=/^\d+(,(\d)+)*(\.\d{1,3})$/;        
                        alertstr = "crm.alert.dec.place.max.three";
                    }
                    if(fielddecimali==4)
                    {
                        re1=/^\d+(,(\d)+)*(\.\d{1,4})$/;        
                        alertstr = "crm.alert.dec.place.max.four";
                    }
                    if(fielddecimali==5)
                    {
                        re1=/^\d+(,(\d)+)*(\.\d{1,5})$/;        
                        alertstr = "crm.alert.dec.place.max.five";
                    }    
                }              
            }
            
			if(val.indexOf(".")>0 && !re1.test(val))
			{
                                callSelectOneMethod(dwrChkVar,alertstr,null,"en_US",fldLabel);  				
                getObj(fldName).focus();
				return false;
			}
			else
			{
				return true;
			}
		}
	}
	else
	{
		return true;
	}			
}

function qtyValidate(fldName,fldLabel) {
   if (getObj(fldName) != null && getObj(fldName).value.replace(/^\s+/g, '').replace(/\s+$/g, '').length!=0)
   {
   	var val=getObj(fldName).value.replace(/^\s+/g, '').replace(/\s+$/g, '')
   	var re=/^\-|\d+(,(\d)+)*(\.\d{1,2})*$/	
    	if (isNaN(val) || val.indexOf(".")!=-1 || !re.test(val) || val.indexOf("+") != -1) {
        	selectone.getJSAlertValue("crm.alert.entry.valid",null,"en_US",
			  														function(mesg) { alert(mesg + " " + fldLabel) })
        	getObj(fldName).focus()
        	return false
    	} else return true
   }
   else
   {
        return true
   }
}

function phoneValidate(fldName,fldLabel) {
   if (getObj(fldName) != null && getObj(fldName).value.replace(/^\s+/g, '').replace(/\s+$/g, '').length!=0)
   {
   	var val=getObj(fldName).value.replace(/^\s+/g, '').replace(/\s+$/g, '')
   	var re=/^\d+(,(\d)+)*(\.\d{1,2})*$/	
    	if (isNaN(val) || val.indexOf(".")!=-1 || !re.test(val) || val.indexOf("+") != -1) {
        	callSelectOneMethod(dwrChkVar,"crm.alert.entry.valid",null,"en_US",fldLabel);
        	getObj(fldName).focus()
        	return false
    	} else return true
   }
   else
   {
        return true
   }
}


function adjValidate(fldName,fldLabel,format) {
   if (getObj(fldName) != null && getObj(fldName).value.replace(/^\s+/g, '').replace(/\s+$/g, '').length!=0)
   {
   	var val=getObj(fldName).value.replace(/^\s+/g, '').replace(/\s+$/g, '')
   	if (format!="any") {
        	var format=format.split(",")
        	var restr="/^\-|\d{1,"+format[0]+"}(\\.\\d{1,"+format[0]+"})$/"
        	var re=eval(restr)
    	} else {
		var re=/^\-|\d+(,(\d)+)*(\.\d{1,2})*$/ 
    	}
        if (!re.test(val)) {
        	selectone.getJSAlertValue("crm.alert.entry.valid",null,"en_US",
			  														function(mesg) { alert(mesg + " " + fldLabel) })
        	getObj(fldName).focus()
        	return false
    	} else return true
   }
   else
   {
	return true
   }			
}

function intValidate(fldName,fldLabel) 
{
	var max_intCF_value = 2147483647	// This is added for integer range validation
	var min_intCF_value = -2147483648
	if(fldLabel=="Account Number")
	fldLabel="Organization Number";
if (getObj(fldName) != null && getObj(fldName).value.replace(/^\s+/g, '').replace(/\s+$/g, '').length!=0)
   {
   	var val=getObj(fldName).value.replace(/^\s+/g, '').replace(/\s+$/g, '')        
   	var re=/^[\d-]+(,(\d)+)*(\.\d{1,2})*$/	        
        if(fldLabel == "Iteration Capacity")
        {
            if (isNaN(val)) 
            {          
        	callSelectOneMethod(dwrChkVar,"crm.alert.entry.valid",null,"en_US",fldLabel);               	
        	getObj(fldName).focus()
        	return false
            }
            else if(val.indexOf(".")!=-1 || !re.test(val)) 
            {           
        	callSelectOneMethod(dwrChkVar,"crm.alert.entry.num.whole",null,"en_US",fldLabel);                  	
        	getObj(fldName).focus()
        	return false
            }            
            else return true          
        
        }
    	else if (isNaN(val) || val.indexOf(".")!=-1 || !re.test(val)) 
        {
                if(fldLabel == "Capacity")
                {
                    callSelectOneMethod(dwrChkVar,"crm.alert.capacity.int",null,"en_US",fldLabel);                    
                }
                else
                {
                    callSelectOneMethod(dwrChkVar,"crm.alert.entry.valid",null,"en_US",fldLabel);        					
                }        	
        	getObj(fldName).focus()
        	return false
    	} 
		else if( !( (min_intCF_value <= val) && (val<=max_intCF_value) ) )
		{
			callSelectOneMethod(dwrChkVar,"crm.alert.num.integer.range",null,"en_US",fldLabel);       
			getObj(fldName).focus()
			return false
		}
		else return true
   }
   else
   {
        return true
   }
}


function numConstComp(fldName,fldLabel,type,constval) {
   var val=parseFloat(getObj(fldName).value.replace(/^\s+/g, '').replace(/\s+$/g, ''))
    constval=parseFloat(constval)

    var ret=true
    switch (type) {
        case "L"  : if (val>=constval) {

                        callSelectOne2VarMethod(dwrChkVar,"crm.alert.less.than",null,"en_US",fldLabel,constval)
                        ret=false
                    }
                    break;
        case "LE" :    if (val>constval) {
                            callSelectOne2VarMethod(dwrChkVar,"crm.alert.less.than.equal.to",null,"en_US",fldLabel,constval)                                   
                    ret=false
                    }
                    break;
        case "E"  :    if (val!=constval) {
                                 callSelectOne2VarMethod(dwrChkVar,"crm.alert.equal.to",null,"en_US",fldLabel,constval)
                                        ret=false
                                }
                                break;
        case "NE" : if (val==constval) {
                    callSelectOne2VarMethod(dwrChkVar,"crm.alert.not.equal.to",null,"en_US",fldLabel,constval)                    
                            ret=false
                    }
                    break;
        case "G"  :    if (val<=constval) {
                            callSelectOne2VarMethod(dwrChkVar,"crm.alert.greater.than",null,"en_US",fldLabel,constval) 
                                     ret=false
                    }
                    break;
        case "GE" : if (val<constval) {
                        callSelectOne2VarMethod(dwrChkVar,"crm.alert.greater.than.equal.to",null,"en_US",fldLabel,constval)
                            ret=false
                    }
                    break;
    }
    
    if (ret==false) {
        getObj(fldName).focus()
        return false
    } else return true;
}

function selInvalidText(currFld,selText) {
	//seltexting the populated value
	if (browser_ie) {
		if (currFld.createTextRange()) {
			var selRange=currFld.createTextRange()
			selRange.findText(selText)
			selRange.select()
		}
	} else if (browser_nn4 || browser_nn6) {
		currFld.setSelectionRange(currFld.value.indexOf(selText),parseInt(currFld.value.indexOf(selText)+selText.length))
	}
}

function formValidate() {
    for (var i=0; i<fieldname.length; i++) {
        var type=fielddatatype[i].split("~")
        if (type[1]=="M") {
            if (!emptyCheck(fieldname[i],fieldlabel[i]))
                return false
        }
        switch (type[0]) {
            case "O"  : break;
            case "V"  : break;
            case "C"  : break;
            case "FF" :
                        if (getObj(fieldname[i]) != null 
				&& getObj(fieldname[i]).value.replace(/^\s+/g, '').replace(/\s+$/g, '').length!=0) 
			{
				
                                var fileName=getObj(fieldname[i]).value;                                
                                var index=fileName.lastIndexOf('.');
                                var ext = fileName.substring( index, fileName.length );
                                if( ext != ".xls" && ext != ".csv"  && ext != ".html"  && ext != ".htm"  && ext != ".xlt" && ext != ".doc" && ext != ".ppt" && ext != ".pdf" && ext != ".txt" && ext != ".zip" && ext != ".rar" && ext != ".css" && ext != ".jpg" && ext != ".jpeg" && ext != ".png" && ext != ".gif" && ext != ".bmp" && ext != ".eps" && ext != ".tiff" && ext != ".tif"  && ext != ".swf"  && ext != ".avi"  && ext != ".mpg"  && ext != ".mpeg"  && ext != ".mov"  && ext != ".qt"  && ext != ".movie"  && ext != ".rtf"  && ext != ".rm"  && ext != ".wav"  && ext != ".wk1"  && ext != ".wk2"  && ext != ".wk3"  && ext != ".wpd"  && ext != ".ani"  && ext != ".dat" && ext != ".xml" && ext != ".xlw" && ext != ".docx" && ext != ".docm" && ext != ".dotx" && ext != ".dotm" && ext != ".xlsx" && ext != ".xlsm" && ext != ".xltx" && ext != ".xltm" && ext != ".xlsb" && ext != ".xlam" && ext != ".pptx" && ext != ".pptm" && ext != ".potx" && ext != ".potm" && ext != ".ppam" && ext != ".ppsx" && ext != ".ppsm" && ext != ".moov")
                                {
                                    alert( 'The Upload Process has been halted.The given file extension '+ext+ ' is not allowed'  );
                                    return false;
                                }
			}
			break;
	    case "E"  : 
			if (getObj(fieldname[i]) != null 
				&& getObj(fieldname[i]).value.replace(/^\s+/g, '').replace(/\s+$/g, '').length!=0) 
			{
				if (!emailValidate(fieldname[i],fieldlabel[i]))
                            		return false
			}
			break;
            case "DT" :
		  	if (getObj(fieldname[i]) != null 
				&& getObj(fieldname[i]).value.replace(/^\s+/g, '').replace(/\s+$/g, '').length!=0)
			{
				if(typeof(type[3])=="undefined") var currdatechk="OTH"
				else var currdatechk=type[3]

				if (!dateTimeValidate(fieldname[i],type[2],fieldlabel[i],currdatechk))
					return false
				if (type[4]) 
				{
					if (!dateTimeComparison(fieldname[i],type[2],fieldlabel[i],type[5],type[6],type[7],type[4]))
						return false
				}    
			}
                        break;
		
           case "MY" :                        
		  	if (getObj(fieldname[i]) != null 
				&& getObj(fieldname[i]).value.replace(/^\s+/g, '').replace(/\s+$/g, '').length!=0)
			{
                                 if(typeof(type[2])=="undefined") var currdatechk="OTH"
                                        else var currdatechk=type[2]

                    		if (!monthYrValidate(fieldname[i],fieldlabel[i],currdatechk))
                            		return false
                    		  
			}
                        break;
            case "D"  :    
                    	if (getObj(fieldname[i]) != null 
				&& getObj(fieldname[i]).value.replace(/^\s+/g, '').replace(/\s+$/g, '').length!=0)
			{
                    		if(typeof(type[2])=="undefined") var currdatechk="OTH"
                                        else var currdatechk=type[2]

                    		if (!dateValidate(fieldname[i],fieldlabel[i],currdatechk))
                            		return false
                    		if (type[3]) 
                                {                                   
                                    if(getObj(type[4]))
                                    {
                                        if(getObj(type[4]).value!=null && getObj(type[4]).value!=undefined)   
                                        {
                                            if (!dateComparison(fieldname[i],fieldlabel[i],type[4],type[5],type[3]))
                                            return false
                                        }
                                    }
                                    else if(getObj("value_"+type[5]))
                                    {
                                        if(getObj("value_"+type[5]).innerHTML!= null &&  getObj("value_"+type[5]).innerHTML!=undefined)
                                        {
                                            if (!dateComparison(fieldname[i],fieldlabel[i],type[4],type[5],type[3]))
                                            return false
                                        }
                                    }                                   
                          	}    
			}
                        break;
            case "T"  :
                    	if (getObj(fieldname[i]) != null 
					&& getObj(fieldname[i]).value.replace(/^\s+/g, '').replace(/\s+$/g, '').length!=0)
		    	{
                    		if(typeof(type[2])=="undefined") var currtimechk="OTH"
                                        else var currtimechk=type[2]

                    		if (!timeValidate(fieldname[i],fieldlabel[i],currtimechk))
                            		return false
                        	if (type[3]) 
				{
                            		if (!timeComparison(fieldname[i],fieldlabel[i],type[4],type[5],type[3]))
                                		return false
                           	}
			}
                        break;
            case "I"  :    
                    	if (getObj(fieldname[i]) != null 
				&& getObj(fieldname[i]).value.replace(/^\s+/g, '').replace(/\s+$/g, '').length!=0)
                   	{
                        	if (!intValidate(fieldname[i],fieldlabel[i]))
                            		return false
                           	if (type[2]) {
                            		if (!numConstComp(fieldname[i],fieldlabel[i],type[2],type[3]))
                                		return false
                           	}
                    	}
			break;
            case "N"  :
                    	if (getObj(fieldname[i]) != null 
				&& getObj(fieldname[i]).value.replace(/^\s+/g, '').replace(/\s+$/g, '').length!=0)
                    	{
                        	if (typeof(type[2])=="undefined") var numformat="any"
                        	else var numformat=type[2]
                    
                        	if (!numValidate(fieldname[i],fieldlabel[i],numformat))
                        		return false
	                        if (type[3]) 
				{
                	               	if (!numConstComp(fieldname[i],fieldlabel[i],type[3],type[4]))
                        			return false
                        	}
                    	}
                    	break;
	     case "P" :
			if(getObj(fieldname[i]) !=null && 
				getObj(fieldname[i]).value.replace(/^\s+/g, '').replace(/\s+$/g, '').length!=0)
                    	{
                        	if (!phoneValidate(fieldname[i],fieldlabel[i]))
                        		return false
                    	}
                    	break;
        	}
    	}
	return true
}

function clearId(fldName) {

	var currObj=getObj(fldName)	

	currObj.value=""

}

function showCalc(fldName) {
	var currObj=getObj(fldName)
	openPopUp("calcWin",currObj,"/crm/Calc.do?currFld="+fldName,"Calc",170,220,"menubar=no,toolbar=no,location=no,status=no,scrollbars=no,resizable=yes")
}

function clearLookUp(fldName,fldId,fldLabel,searchmodule)
{
    if(getObj("property("+fldName+")"))
    {
    	if(fldName=="Program Name")
    	{
    		if(getObj("property(Iteration Name)"))
    		{
    			getObj("property(Iteration Name)").value="";
    			getObj("property(iterations:Iteration Name)").value="";
    		}
    	}
        getObj("property("+fldName+")").value="";
    }
    else
    {
        if(getObj(fldName) && getObj(fldName).type =='text' )
            getObj(fldName).value="";
    }
    if(getObj("property("+fldId+":"+fldName+")")){
        getObj("property("+fldId+":"+fldName+")").value="";
    }
    else
    {
        if( getObj(fldId+":"+fldName) && getObj(fldId+":"+fldName).type == 'hidden')
            getObj(fldId+":"+fldName).value="";
    }
}

function clearProgAndIterLookUp(fldName,fldId,searchmodule)
{
	if(fldName == 'Iteration' || fldName =='Iteration Name')
	{
		getObj("property("+fldName+")").value="";
		getObj("property("+fldId+":"+fldName+")").value="";
	}
	else if(fldName == 'Program' || fldName == 'Program Name')
	{
		var iterationValue = "";
		if(getObj("property(iterations:Iteration)"))
			iterationValue = getObj("property(iterations:Iteration)").value;
		else if(getObj("property(iterations:Iteration Name)"))
			iterationValue = getObj("property(iterations:Iteration Name)").value;
		if(iterationValue == "" || iterationValue == "null")
		{
			 getObj("property("+fldName+")").value="";
	         getObj("property("+fldId+":"+fldName+")").value="";
		}
		else
		{
			selectone.getJSAlertValue("crm.alert.iter.sel.clr",null,"en_US",
			  												function(mesg) { alert(mesg) }) 
		}
	}
}
function clearRegistrant()
{                            
          getObj("property(Registrant)").value = "" ;
          getObj("property(registrations:Registrant)").value = "" ;                                   
}

function clearItrn()
{                            
 if(getObj("property(module)").value!="Iterations")
  {
        if(getObj("property(module)").value!="Cases")
        {
          getObj("property(Iteration Name)").value = "" ;
          getObj("property(iterations:Iteration Name)").value = "" ;                                   
        }
        else
 	{
         getObj("property(Iteration)").value = "" ;
         getObj("property(iterations:Iteration)").value = "" ;     
         }
   }                             
}
function pressenter(event) 
	{
		if(event.keyCode == 13)
  		{
			searchprogram()
		}
		return true;
	}
	function searchprogram()
	{
    	var searchValue = document.getElementById("tagsearch").value;
    	document.location.href="/crm/ShowDetails.do?module=Programs&searchValue="+searchValue;
	}
function showLookUp(fldName,fldId,fldLabel,searchmodule,productFldId,typeName) 
{
	var currObj=getObj(fldName)

	var fromModule=null
	if(getObj("property(module)")!=null)
	{
		fromModule=getObj("property(module)").value;
	}
	else if(getObj("module")!=null){
		fromModule=getObj("module").value;
	}
	productStr = ""
	if(productFldId == undefined)
	{
		
	}
	else	
	{
		if(getObj(productFldId) != undefined)
		{	
			productId = getObj(productFldId).value;
			productStr = "&productId="+productId;
		}
	}
	if(productFldId != null && !isNaN(productFldId))
	{
		productStr = "&registrationId="+productFldId;
	}
	var winName="Lookup"+fldId;
        //var winName="Lookup";
	//var fldValue=currObj.value.replace(/^\s+/g, '').replace(/\s+$/g, '')

	//need to pass the name of the system in which the server is running so that even when the search is invoked from another system, the url will remain the same

        if(searchmodule=="cprogram")
        {
            var planId=getObj("plans").value;
            if(planId==null ||planId=="")
            {
                    searchmodule="Programs";
            }
            else
            {
                    openPopUp("lookUpWin",currObj,"/crm/Search.do?searchmodule="+searchmodule+"&planId="+planId+"&fldName="+fldName+"&fldId="+fldId+"&fldLabel="+fldLabel+"&fldValue=&user="+productStr,winName,500,400,"menubar=no,toolbar=no,location=no,status=no,scrollbars=yes,resizable=yes")
                    return;
            }
        }
        else if(searchmodule=="Exclusions"|| searchmodule=="Targets")
        {

                var id=getObj("Property(lookupid_1)").value;
                openPopUp("lookUpWin",currObj,"/crm/Search.do?searchmodule="+searchmodule+"&fromModule="+fromModule+"&fldName="+fldName+"&fldId="+fldId+"&fldLabel="+fldLabel+"&Lookupid="+id+"&fldValue=&user="+productStr,winName,500,400,"menubar=no,toolbar=no,location=no,status=no,scrollbars=yes,resizable=yes")
                return
        }
	else if(searchmodule=="Registrations")
         {
		
                var iterId =null; 
		if(getObj("iterations"))
		{
			iterId=getObj("iterations").value;
                	if(iterId==null || iterId=="" )
                	{
                    	selectone.getJSAlertValue("crm.alert.iter.name",null,"en_US",
                                                                                                                                                    function(mesg) { alert(mesg) })
                    	return false;
                	}
                	else
                	{
                    openPopUp("lookUpWin",currObj,"/crm/Search.do?searchmodule="+searchmodule+"&foreignId="+iterId+"&fldName="+fldName+"&fldId="+fldId+"&fldLabel="+fldLabel+"&fldValue=&user="+productStr,winName,500,400,"menubar=no,toolbar=no,location=no,status=no,scrollbars=yes,resizable=yes")
                	}
		}
		else
		{
		 openPopUp("lookUpWin",currObj,"/crm/Search.do?searchmodule="+searchmodule+"&fromModule="+fromModule+"&fldName="+fldName+"&fldId="+fldId+"&fldLabel="+fldLabel+"&fldValue=&user="+productStr,winName,600,400,"menubar=no,toolbar=no,location=no,status=no,scrollbars=yes,resizable=yes")

		}

            }
	else if(searchmodule=="Invoices")
         {
		var regisId=null;
		if( getObj("registrationId"))
		{	
                regisId = getObj("registrationId").value;
                if(regisId==null || regisId=="" )
                {
		    alert("Registrant cannot be blank");
                    return false;
                }
		else
                {
                    openPopUp("lookUpWin",currObj,"/crm/Search.do?searchmodule="+searchmodule+"&foreignId="+regisId+"&fldName="+fldName+"&fldId="+fldId+"&fldLabel="+fldLabel+"&fldValue=&user="+productStr,winName,500,400,"menubar=no,toolbar=no,location=no,status=no,scrollbars=yes,resizable=yes")
                }

		}
		else
		{
		 openPopUp("lookUpWin",currObj,"/crm/Search.do?searchmodule="+searchmodule+"&fromModule="+fromModule+"&fldName="+fldName+"&fldId="+fldId+"&fldLabel="+fldLabel+"&fldValue=&user="+productStr,winName,600,400,"menubar=no,toolbar=no,location=no,status=no,scrollbars=yes,resizable=yes")

		}
         }

        else if(searchmodule=="LifeCycles")
        {
            if(fromModule == 'Registrations' && (getObj("iterations").value==null || getObj("iterations").value==""))
            {
                selectone.getJSAlertValue("crm.alert.iter.name",null,"en_US",
                                  function(mesg) { alert(mesg) })
                return false;
            }
            else if(fromModule == 'Contacts')
            {
            	//get contactId to filter lifecycle role/stage for particular contact.
            	var contactId = null;
            	if(getObj('property(id)') !=null){
            		contactId = getObj('property(id)').value;
            	}
            	else if(getObj('id') !=null){
            		contactId = document.getElementById('id').value;
            	}
            	if(contactId != null){
            		openPopUp("lookUpWin",currObj,"/crm/Search.do?searchmodule="+searchmodule+"&contactId="+contactId+"&fromModule="+fromModule+"&fldName="+fldName+"&fldId="+fldId+"&fldLabel="+fldLabel+"&fldValue=&user="+productStr,winName,500,400,"menubar=no,toolbar=no,location=no,status=no,scrollbars=yes,resizable=yes")
            	}
                return;
            }
            else
            {
                if(fromModule == 'Registrations')
                {
                    openPopUp("lookUpWin",currObj,"/crm/Search.do?searchmodule="+searchmodule+"&foreignId="+getObj("iterations").value+"&fromModule="+fromModule+"&fldName="+fldName+"&fldId="+fldId+"&fldLabel="+fldLabel+"&fldValue=&user="+productStr,winName,500,400,"menubar=no,toolbar=no,location=no,status=no,scrollbars=yes,resizable=yes")
                    return;
                }
                else
                {
                    openPopUp("lookUpWin",currObj,"/crm/Search.do?searchmodule="+searchmodule+"&fromModule="+fromModule+"&fldName="+fldName+"&fldId="+fldId+"&fldLabel="+fldLabel+"&fldValue=&user="+productStr,winName,500,400,"menubar=no,toolbar=no,location=no,status=no,scrollbars=yes,resizable=yes")
                    return;
                }
            }
        }
 
        else if(searchmodule=="coordinator")
         {
         	
         	var iterationId=getObj("iterations").value;
         	if(iterationId==null ||iterationId=="")
         	{
         		selectone.getJSAlertValue("crm.alert.iter.name",null,"en_US",
			  															function(mesg) { alert(mesg) })
         		return false;
         	}
         	else
         	{
         		openPopUp("lookUpWin",currObj,"/crm/Search.do?searchmodule="+searchmodule+"&iterationId="+iterationId+"&fldName="+fldName+"&fldId="+fldId+"&fldLabel="+fldLabel+"&fldValue=&user="+productStr,winName,500,400,"menubar=no,toolbar=no,location=no,status=no,scrollbars=yes,resizable=yes")
         		return;
         	}
         }
                  
         else if(searchmodule=="Iterations")
         {
            if(productFldId!="undefined" && productFldId == "intellispecialcheck")
            {
                var programId = getObj("Destinationprograms").value;
                if(programId==null || programId=="" )
                {
                    selectone.getJSAlertValue("crm.alert.prog.name",null,"en_US",
                                                                                                                                                    function(mesg) { alert(mesg) })
                    return false;
                }
                else
                {
                    openPopUp("lookUpWin",currObj,"/crm/Search.do?searchmodule="+searchmodule+"&foreignId="+programId+"&fldName="+fldName+"&fldId="+fldId+"&fldLabel="+fldLabel+"&fldValue=&user="+productStr,winName,500,400,"menubar=no,toolbar=no,location=no,status=no,scrollbars=yes,resizable=yes")
                }
            }
            else if((productFldId!="undefined" && productFldId == "intellispecialcheckteam")||(fldName=="modname"))
            {
               openPopUp("lookUpWin",currObj,"/crm/Search.do?searchmodule="+searchmodule+"&fldName="+fldName+"&fldId="+fldId+"&fldLabel="+fldLabel+"&fldValue=&user="+productStr,winName,500,400,"menubar=no,toolbar=no,location=no,status=no,scrollbars=yes,resizable=yes")  
            }
            else 
            {
                var programId = getObj("programs").value;

                if(programId==null || programId=="" )
                {
                   selectone.getJSAlertValue("crm.alert.prog.name",null,"en_US",
                                                                                                                                                            function(mesg) { alert(mesg) })
                    return false;
                }
                else
                {
                    openPopUp("lookUpWin",currObj,"/crm/Search.do?searchmodule="+searchmodule+"&foreignId="+programId+"&fldName="+fldName+"&fldId="+fldId+"&fldLabel="+fldLabel+"&fldValue=&user="+productStr,winName,500,400,"menubar=no,toolbar=no,location=no,status=no,scrollbars=yes,resizable=yes")
                }
             }
        }
	
        else if(searchmodule== 'Requirements' && window.location.href.indexOf("crm/NewIterationRequirement.do?")>-1)
        {
            openPopUp("lookUpWin",currObj,"/crm/Search.do?searchmodule="+searchmodule+"&fromModule="+fromModule+"&fldName="+fldName+"&fldId="+fldId+"&fldLabel="+fldLabel+"&fldValue=&user="+productStr+"&iterationid="+getObj('property(id)').value,winName,500,400,"menubar=no,toolbar=no,location=no,status=no,scrollbars=yes,resizable=yes")
        }
        else if((fromModule == "Connections" || fromModule == "Educations" || fromModule == "RelatedAccounts" || fromModule == "Experiences" ) && searchmodule== 'Contacts')
        {
            openPopUp("lookUpWin",currObj,"/crm/Search.do?searchmodule="+searchmodule+"&fromModule="+fromModule+"&fldName="+fldName+"&fldId="+encodeURIComponent(fldId)+"&fldLabel="+fldLabel+"&fldValue=&user="+productStr,"Lookup",600,400,"menubar=no,toolbar=no,location=no,status=no,scrollbars=yes,resizable=yes")
        }
        else if(fromModule == "Iterations" && searchmodule == "Discounts")
        {
            var grandtot = getObj("property(Grand Total)").value;
            if(grandtot == ""){grandtot=0;}
            openPopUp("lookUpWin",currObj,"/crm/Search.do?searchmodule="+searchmodule+"&fromModule="+fromModule+"&fldName="+fldName+"&fldId="+encodeURIComponent(fldId)+"&fldLabel="+fldLabel+"&fldValue=&user="+productStr+"&grandtot="+grandtot,winName,600,400,"menubar=no,toolbar=no,location=no,status=no,scrollbars=yes,resizable=yes")
        }        
        else if(fromModule == "Invoices" && searchmodule == "Discounts")
        {
            var iterId =null; 
            if(getObj("iterations"))
            {
                iterId=getObj("iterations").value;
                if(iterId==null || iterId=="" )
                {
                selectone.getJSAlertValue("crm.alert.iter.name",null,"en_US",
                                                                                                                                            function(mesg) { alert(mesg) })
                return false;
                }
                else
                {                    
                    openPopUp("lookUpWin",currObj,"/crm/Search.do?searchmodule="+searchmodule+"&fromModule="+fromModule+"&foreignId="+iterId+"&fldName="+fldName+"&fldId="+fldId+"&fldLabel="+fldLabel+"&fldValue=&user="+productStr,winName,500,400,"menubar=no,toolbar=no,location=no,status=no,scrollbars=yes,resizable=yes")
                }
            }
        }
        else if(fromModule == "Invoices" && searchmodule == "Additional Item")
        {
            var iterId =null; 
            if(getObj("iterations"))
            {
            	
                iterId=getObj("iterations").value;
            	if(iterId==null || iterId=="" )
                {
                selectone.getJSAlertValue("crm.alert.iter.name",null,"en_US",
                                                                                                                                            function(mesg) { alert(mesg) })
                return false;
                }
                else
                {                    
                    openPopUp("lookUpWin",currObj,"/crm/Search.do?searchmodule="+searchmodule+"&fromModule="+fromModule+"&foreignId="+iterId+"&fldName="+fldName+"&fldId="+fldId+"&fldLabel="+fldLabel+"&fldValue=&user="+productStr,winName,500,400,"menubar=no,toolbar=no,location=no,status=no,scrollbars=yes,resizable=yes")
                }
            }
        }
        else if(fromModule == "Iterations" && searchmodule == "Invoice Template")
        {
        	openPopUp("lookUpWin",currObj,"/crm/Search.do?searchmodule="+searchmodule+"&fromModule="+fromModule+"&foreignId="+iterId+"&fldName="+fldName+"&fldId="+fldId+"&fldLabel="+fldLabel+"&fldValue=&user="+productStr,winName,500,400,"menubar=no,toolbar=no,location=no,status=no,scrollbars=yes,resizable=yes")
        }
        else if(fromModule =="CommunicationPlans" && (searchmodule=="Case Template" || searchmodule=="Email"))
        {
             openPopUp("lookUpWin",currObj,"/crm/Search.do?searchmodule="+searchmodule+"&fromModule="+fromModule+"&fldName="+fldName+"&fldId="+encodeURIComponent(fldId)+"&fldLabel="+fldLabel+"&fldValue=&user="+productStr+"&typeName="+typeName,winName,600,400,"menubar=no,toolbar=no,location=no,status=no,scrollbars=yes,resizable=yes")

        }
        else
        {
            openPopUp("lookUpWin",currObj,"/crm/Search.do?searchmodule="+searchmodule+"&fromModule="+fromModule+"&fldName="+fldName+"&fldId="+encodeURIComponent(fldId)+"&fldLabel="+fldLabel+"&fldValue=&user="+productStr,winName,600,400,"menubar=no,toolbar=no,location=no,status=no,scrollbars=yes,resizable=yes")
        }
}

function openPopUp(winInst,currObj,baseURL,winName,width,height,features) {
	var left=parseInt(findPosX(currObj))
	var top=parseInt(findPosY(currObj))
	
	if (window.navigator.appName!="Opera") top+=parseInt(currObj.offsetHeight)
	else top+=(parseInt(currObj.offsetHeight)*2)+10

	if (browser_ie)	{
		top+=window.screenTop-document.body.scrollTop
		left-=document.body.scrollLeft
		if (top+height+30>window.screen.height) 
			top=findPosY(currObj)+window.screenTop-height-30 //30 is a constant to avoid positioning issue
		if (left+width>window.screen.width) 
			left=findPosX(currObj)+window.screenLeft-width
	} else if (browser_nn4 || browser_nn6) {
		top+=(scrY-pgeY)
		left+=(scrX-pgeX)
		if (top+height+30>window.screen.height) 
			top=findPosY(currObj)+(scrY-pgeY)-height-30
		if (left+width>window.screen.width) 
			left=findPosX(currObj)+(scrX-pgeX)-width
	}
	
	features="width="+width+",height="+height+",top="+top+",left="+left+";"+features
	eval(winInst+'=window.open("'+baseURL+'","'+winName+'","'+features+'")')
}

var scrX=0,scrY=0,pgeX=0,pgeY=0;

if (browser_nn4 || browser_nn6) {
	document.addEventListener("click",popUpListener1,true)
}

function popUpListener1(ev) {
	if (browser_nn4 || browser_nn6) {
		scrX=ev.screenX
		scrY=ev.screenY
		pgeX=ev.pageX
		pgeY=ev.pageY
	}
}

for (var i=0;i<document.forms.length;i++)
	document.forms[i].submitted=true

ScrollEffect = function(){
};

ScrollEffect.lengthcount=0;
ScrollEffect.closelimit=0;
ScrollEffect.limit=0;
ScrollEffect.togglelimit=0;
ScrollEffect.topplelimit=0;


	function just() 
	{
//	ig=document.getElementById('NewUser');
	ig=getObj('NewUser');

	if(ScrollEffect.lengthcount > ScrollEffect.closelimit )
	{
		closet();
		return;
	}
	ig.style.display="block";
	ig.style.height=ScrollEffect.lengthcount+'px';
	ScrollEffect.lengthcount=ScrollEffect.lengthcount+10;
	if(ScrollEffect.lengthcount < ScrollEffect.limit)
	{
		setTimeout("just()", 15);
	}
	else
	{ 
/* 
		document.getElementById('reg').style.display="block";
		document.getElementById('agreement').checked=false;
		document.getElementById('hide').style.display="none";
*/
	
		getObj('reg').style.display="block";
		getObj('agreement').checked=false;
		getObj('hide').style.display="none";
		return;
	}
}


function closet()
{
	//ig=document.getElementById('NewUser');
	//document.getElementById('reg').style.display="none";
	ig=getObj('NewUser');
	getObj('reg').style.display="none";

	ScrollEffect.lengthcount=ScrollEffect.lengthcount-10;
	ig.style.height=ScrollEffect.lengthcount+'px';
	if(ScrollEffect.lengthcount<20)
	{

		ig.style.display="none";
		return;
	}
	else
	{
		setTimeout("closet()", 15);
	}
}




function toggle() 
	{

	  	//bottom_ig=document.getElementById('hide');
	  	bottom_ig=getObj('hide');
	  if(ScrollEffect.lengthcount >= ScrollEffect.togglelimit)
	  	{
	   	topple();
	  	return;
	  	}
         bottom_ig.style.display="block";
    	 ig.style.height=ScrollEffect.lengthcount+'px';
      	   ScrollEffect.lengthcount=ScrollEffect.lengthcount+3;
    	  		if(ScrollEffect.lengthcount < ScrollEffect.togglelimit)
         	   	{
        		 setTimeout("toggle()", 20);
        		}
    			else
    			{  
    		   	//document.getElementById('hide').style.display="block";
    		   	getObj('hide').style.display="block";
    			return;
    			}
	}
	 
 function topple()
 {
  
 //button_ig=document.getElementById('hide');
 button_ig=getObj('hide');
 button_ig.style.display="none";
 ScrollEffect.lengthcount=ScrollEffect.lengthcount-3;
 ig.style.height=ScrollEffect.lengthcount+'px';
 if(ScrollEffect.lengthcount < ScrollEffect.topplelimit)
 {
 return;
 }
 else
 {
 setTimeout("topple()", 30);
 }
 }

 function slideDown(divname)
 {
	if (divname != 'contactdetails' && getObj('contactdetails').style.display == '')
	{
		slideUp('contactdetails');
	}
	else if (divname != 'sendfriend' && getObj('sendfriend').style.display == '')
	{
		slideUp('sendfriend');
		getObj('sent_confirm_message').style.display="none";
	}
	new Effect.SlideDown(divname);	
 }
 function slideUp(divname)
 {
	new Effect.SlideUp(divname);
 }
function trimRight(str)
{
	// remove all spaces on right
	var newstr = str.replace(/[ ]*$/,"");
	return (newstr);
}

function trimBoth(str)
{
	// reomve all spaces on both side
	var newstr = trimRight(trimLeft(str));
	return (newstr);
}
function trimLeft(str)
{
	// remove all spaces on left
	var newstr = str.replace(/[ ]*/, "");
	return (newstr);
}

var splCharArray =  new Array("`","~","!","#","$","^","*","+","=","[","]","{","}","|","\\","\"","\'",":",";","<",">",",","?");

var splCharArray1 = new Array("`","~","!","#","$","^","*","+","=","[","]","{","}","|","\\","\"","\'",":",";","<",">","?");

function splCharCheck(fieldValue)
{
	for(i=0;i<splCharArray.length;i++)
	{
		if(fieldValue.indexOf(splCharArray[i]) >= 0)
		{
			return false
		}
	}
	return true
}

// for pick list special character validation 
function splCharCheck1(fieldValue)
{
	for(i=0;i<splCharArray1.length;i++)
	{
		if(fieldValue.indexOf(splCharArray1[i]) >= 0)
		{
			return false
		}
	}
	return true
}

//For TagCloud Special character validation

var splCharArray2 = new Array("`","~","!","#","$","^","*","+","=","[","]","{","}","|","\\","\"","\'",":",";","<",">",",","?","&","%");

function splCharCheck2(fieldValue)
{
	for(i=0;i<splCharArray2.length;i++)
	{
		if(fieldValue.indexOf(splCharArray2[i]) >= 0)
		{
			return false
		}
	}
	return true
}


function monthYrValidate(fldName,fldLabel,type) {
    
    dateval=getObj(fldName).value.replace(/^\s+/g, '').replace(/\s+$/g, '')

    
var dateelements=splitmonYrVal(dateval)

        
        mm=dateelements[0]
        yyyy=dateelements[1]
            if (isNaN(mm)) 
            {
             callSelectOneMethod(dwrChkVar,"crm.alert.entry.valid",null,"en_US",fldLabel);
        		 getObj(fldName).focus()
        		 return false
            }
            if (isNaN(yyyy)) 
            {                
        	  callSelectOneMethod(dwrChkVar,"crm.alert.entry.valid",null,"en_US",fldLabel);
        		getObj(fldName).focus()
        		return false
            }
    
    if ( mm<1 || mm>12 || yyyy<1 || yyyy<1000) {
        callSelectOneMethod(dwrChkVar,"crm.alert.entry.valid",null,"en_US",fldLabel);
        getObj(fldName).focus()
		
		
        return false
    }
   else
        return true;
    
    
}

function splitmonYrVal(dateval) {
        var datesep;
        var dateelements = new Array(2);

        if (dateval.indexOf("-")>=0) datesep="-"
        else if (dateval.indexOf(".")>=0) datesep="."
        else if (dateval.indexOf("/")>=0) datesep="/"  
		
      dateelements[0]=dateval.substring(0,dateval.indexOf(datesep))                                                       
      dateelements[1]=dateval.substr(dateval.lastIndexOf(datesep)+1,dateval.length)
       
        return dateelements;
}


/*********************************************************************************

** The contents of this file are subject to the vtiger CRM Public License Version 1.0
 * ("License"); You may not use this file except in compliance with the License
 * The Original Code is:  vtiger CRM Open Source
 * The Initial Developer of the Original Code is vtiger.
 * Portions created by vtiger are Copyright (C) vtiger.
 * All Rights Reserved.
 ********************************************************************************/


function compareDates(date1,fldLabel1,date2,fldLabel2,type) {
	var ret=true
	switch (type) {
		case 'L'	:	if (date1>=date2) {//DATE1 VALUE LESS THAN DATE2
							selectone.getJSAlertValue("crm.alert.less.than",null,"en_US",
			  																function(mesg) { alert(fldLabel1 + " " + mesg + " " + fldLabel2) })
							ret=false
						}
						break;
		case 'LE'	:	if (date1>date2) {//DATE1 VALUE LESS THAN OR EQUAL TO DATE2
							selectone.getJSAlertValue("crm.alert.less.than.equal.to",null,"en_US",
			  																function(mesg) { alert(fldLabel1 + " " + mesg + " " + fldLabel2) })
							ret=false
						}
						break;
		case 'E'	:	if (date1!=date2) {//DATE1 VALUE EQUAL TO DATE
							selectone.getJSAlertValue("crm.alert.equal.to",null,"en_US",
			  																function(mesg) { alert(fldLabel1 + " " + mesg + " " + fldLabel2) })
							ret=false
						}
						break;
		case 'G'	:	if (date1<=date2) {//DATE1 VALUE GREATER THAN DATE2
							selectone.getJSAlertValue("crm.alert.greater.than",null,"en_US",
			  																function(mesg) { alert(fldLabel1 + " " + mesg + " " + fldLabel2) })
							ret=false
						}
						break;	
		case 'GE'	:	if (date1<date2) {//DATE1 VALUE GREATER THAN OR EQUAL TO DATE2
							selectone.getJSAlertValue("crm.alert.greater.than.equal.to",null,"en_US",
			  																function(mesg) { alert(fldLabel1 + " " + mesg + " " + fldLabel2) })
							ret=false
						}
						break;
	}
	
	if (ret==false) return false
	else return true
}

function toggleSelect(state,relCheckName) {
	if (getObj(relCheckName)) {
		if (typeof(getObj(relCheckName).length)=="undefined") {
			getObj(relCheckName).checked=state
		} else {
			for (var i=0;i<getObj(relCheckName).length;i++)
				getObj(relCheckName)[i].checked=state
		}
	}
}

function toggleSelectAll(relCheckName,selectAllName) {
	if (typeof(getObj(relCheckName).length)=="undefined") {
		getObj(selectAllName).checked=getObj(relCheckName).checked
	} else {
		var atleastOneFalse=false;
		for (var i=0;i<getObj(relCheckName).length;i++) {
			if (getObj(relCheckName)[i].checked==false) {
				atleastOneFalse=true
				break;
			}
		}
		getObj(selectAllName).checked=!atleastOneFalse
	}
}
//added for show/hide 10July
function expandCont(bn)
{
	var leftTab = document.getElementById(bn);
       	leftTab.style.display = (leftTab.style.display == "block")?"none":"block";
       	img = document.getElementById("img_"+bn);
      	img.src=(img.src.indexOf("images/toggle1.gif")!=-1)?"themes/images/toggle2.gif":"themes/images/toggle1.gif";
      	set_cookie_gen(bn,leftTab.style.display)

}

function setExpandCollapse_gen()
{
	var x = leftpanelistarray.length;
	for (i = 0 ; i < x ; i++)
	{
		var listObj=getObj(leftpanelistarray[i])
		var tgImageObj=getObj("img_"+leftpanelistarray[i])
		var status = get_cookie_gen(leftpanelistarray[i])
		
		if (status == "block") {
			listObj.style.display="block";
			tgImageObj.src="themes/images/toggle2.gif";
		} else if(status == "none") {
			listObj.style.display="none";
			tgImageObj.src="themes/images/toggle1.gif";
		}
	}
}

function toggleDiv(id) {

	var listTableObj=getObj(id)

	if (listTableObj.style.display=="block") 
	{
		listTableObj.style.display="none"
	}else{
		listTableObj.style.display="block"
	}
	//set_cookie(id,listTableObj.style.display)
}

//Setting cookies
function set_cookie_gen ( name, value, exp_y, exp_m, exp_d, path, domain, secure )
{
  var cookie_string = name + "=" + escape ( value );

  if ( exp_y )
  {
    var expires = new Date ( exp_y, exp_m, exp_d );
    cookie_string += "; expires=" + expires.toGMTString();
  }

  if ( path )
        cookie_string += "; path=" + escape ( path );

  if ( domain )
        cookie_string += "; domain=" + escape ( domain );
  
  if ( secure )
        cookie_string += "; secure";
  
  document.cookie = cookie_string;
}

// Retrieving cookies
function get_cookie_gen ( cookie_name )
{
  var results = document.cookie.match ( cookie_name + '=(.*?)(;|$)' );

  if ( results )
    return ( unescape ( results[1] ) );
  else
    return null;
}

// Delete cookies 
function delete_cookie_gen ( cookie_name )
{
  var cookie_date = new Date ( );  // current date & time
  cookie_date.setTime ( cookie_date.getTime() - 1 );
  document.cookie = cookie_name += "=; expires=" + cookie_date.toGMTString();
}
//end added for show/hide 10July

/** This is Javascript Function which is used to toogle between
  * assigntype user and group/team select options while assigning owner to entity.
  */
function toggleAssignType(currType)
{
        if (currType=="U")
        {
                getObj("assign_user").style.display="block"
                getObj("assign_team").style.display="none"
        }
        else
        {
                getObj("assign_user").style.display="none"
                getObj("assign_team").style.display="block"
        }
}
//to display type of address for google map
/*
function showLocateMapMenu()
    {
		if(getObj("dropDownMenu"))
		{
            getObj("dropDownMenu").style.display="block"
            getObj("dropDownMenu").style.left=findPosX(getObj("locateMap"))
            getObj("dropDownMenu").style.top=findPosY(getObj("locateMap"))+getObj("locateMap").offsetHeight
		}
		else if(getObj("dropDownMenu1"))
		{
			getObj("dropDownMenu1").style.display="block"
			getObj("dropDownMenu1").style.left=findPosX(getObj("locateMap"))
			getObj("dropDownMenu1").style.top=findPosY(getObj("locateMap"))+getObj("locateMap").offsetHeight
		}
    }
*/

function hideLocateMapMenu(ev)
    {
            if (browser_ie)
                    currElement=window.event.srcElement
            else if (browser_nn4 || browser_nn6)
                    currElement=ev.target
            if (currElement.id!="locateMap")
				if(getObj("dropDownMenu"))
					getObj("dropDownMenu").style.display="none"
    			else if(getObj("dropDownMenu1"))
					getObj("dropDownMenu1").style.display="none"
	}
/*
* javascript function to display the div tag
* @param divId :: div tag ID
*/
function show(divId)

{

    var id = document.getElementById(divId);
     if(id!=null) 
	{	
    	id.style.display = 'inline';
	}
}

/*
* javascript function to display the div tag
* @param divId :: div tag ID
*/
function showBlock(divId)
{
    var id = document.getElementById(divId);
    id.style.display = 'block';
}


/*
* javascript function to hide the div tag
* @param divId :: div tag ID
*/
function hide(divId)
{

    var id = document.getElementById(divId);

    id.style.display = 'none';

}
function fnhide(divId)
{

    var id = document.getElementById(divId);

    id.style.display = 'none';
}

function fnLoadValues(obj1,obj2,SelTab,unSelTab,moduletype,module){
	
   var oform = document.forms['EditView'];
   oform.action.value='Save';	
   if((moduletype == 'inventory' && validateInventory(module)) ||(moduletype == 'normal') && formValidate())	
   if(formValidate())
   {	
	   var tabName1 = document.getElementById(obj1);

	   var tabName2 = document.getElementById(obj2);

	   var tagName1 = document.getElementById(SelTab);

	   var tagName2 = document.getElementById(unSelTab);

	   if(tabName1.className == "dvtUnSelectedCell")

		   tabName1.className = "dvtSelectedCell";

	   if(tabName2.className == "dvtSelectedCell")

		   tabName2.className = "dvtUnSelectedCell";   
	   tagName1.style.display='block';

	   tagName2.style.display='none';
   }
}

function fnCopy(source,design){

   document.getElementById(source).value=document.getElementById(design).value;

   document.getElementById(source).disabled=true;

}

function fnClear(source){

   document.getElementById(source).value=" ";

   document.getElementById(source).disabled=false;

}

function fnCpy(){

   var tagName=document.getElementById("cpy");

   if(tagName.checked==true){   
       fnCopy("shipaddress","address");

       fnCopy("shippobox","pobox");

       fnCopy("shipcity","city");

       fnCopy("shipcode","code");

       fnCopy("shipstate","state");

       fnCopy("shipcountry","country");

   }

   else{

       fnClear("shipaddress");

       fnClear("shippobox");

       fnClear("shipcity");

       fnClear("shipcode");

       fnClear("shipstate");

       fnClear("shipcountry");

   }

}
function fnDown(obj){
        var tagName = document.getElementById(obj);
        var tabName = document.getElementById("one");
        if(tagName.style.display == 'none'){
                tagName.style.display = 'block';
                tabName.style.display = 'block';
        }
        else{
                tabName.style.display = 'none';
                tagName.style.display = 'none';
        }
}

/*
* javascript function to add field rows
* @param option_values :: List of Field names
*/
var count = 0;
var rowCnt = 1;
function fnAddSrch(option_values,criteria_values){

    var tableName = document.getElementById('adSrc');

    var prev = tableName.rows.length;

    var count = prev;

    var row = tableName.insertRow(prev);

    if(count%2)

        row.className = "dvtCellLabel";

    else

        row.className = "dvtCellInfo";

    var colone = row.insertCell(0);

    var coltwo = row.insertCell(1);

    var colthree = row.insertCell(2);

    colone.innerHTML="<select id='Fields"+count+"' name='Fields"+count+"' class='detailedViewTextBox'>"+option_values+"</select>";

    coltwo.innerHTML="<select id='Condition"+count+"' name='Condition"+count+"' class='detailedViewTextBox'>"+criteria_values+"</select> ";

    colthree.innerHTML="<input type='text' id='Srch_value"+count+"' name='Srch_value"+count+"' class='detailedViewTextBox'>";

}

function totalnoofrows()
{
	var tableName = document.getElementById('adSrc');
	document.basicSearch.search_cnt.value = tableName.rows.length;
}

/*
* javascript function to delete field rows in advance search
* @param void :: void
*/
/*function delRow()
{

    var tableName = document.getElementById('adSrc');

    var prev = tableName.rows.length;

    if(prev > 1)

    document.getElementById('adSrc').deleteRow(prev-1);

}*/

function fnVis(obj){

   var profTag = document.getElementById("prof");

   var moreTag = document.getElementById("more");

   var addrTag = document.getElementById("addr");

  
   if(obj == 'prof'){

       document.getElementById('mnuTab').style.display = 'block';

       document.getElementById('mnuTab1').style.display = 'none';

       document.getElementById('mnuTab2').style.display = 'none';

       profTag.className = 'dvtSelectedCell';

       moreTag.className = 'dvtUnSelectedCell';

       addrTag.className = 'dvtUnSelectedCell';

   }

  
   else if(obj == 'more'){

       document.getElementById('mnuTab1').style.display = 'block';

       document.getElementById('mnuTab').style.display = 'none';

       document.getElementById('mnuTab2').style.display = 'none';

       moreTag.className = 'dvtSelectedCell';

       profTag.className = 'dvtUnSelectedCell';

       addrTag.className = 'dvtUnSelectedCell';

   }

  
   else if(obj == 'addr'){

       document.getElementById('mnuTab2').style.display = 'block';

       document.getElementById('mnuTab').style.display = 'none';

       document.getElementById('mnuTab1').style.display = 'none';

       addrTag.className = 'dvtSelectedCell';

       profTag.className = 'dvtUnSelectedCell';

       moreTag.className = 'dvtUnSelectedCell';

   }

}

function fnvsh(obj,Lay){
    var tagName = document.getElementById(Lay);
    var leftSide = findPosX(obj);
    var topSide = findPosY(obj);
    tagName.style.left= leftSide + 175 + 'px';
    tagName.style.top= topSide + 'px';
    tagName.style.visibility = 'visible';
}

/*function fnvshobj(obj,Lay){
    var tagName = document.getElementById(Lay);
    var leftSide = findPosX(obj);
    var topSide = findPosY(obj);
    var maxW = tagName.style.width;
    var widthM = maxW.substring(0,maxW.length-2);
    var getVal = eval(leftSide) + eval(widthM);
    if(getVal  > document.body.clientWidth ){
        leftSide = eval(leftSide) - eval(widthM);
        tagName.style.left = leftSide + 34 + 'px';
    }
    else
        tagName.style.left= leftSide + 'px';
    tagName.style.top= topSide + 'px';
    tagName.style.display = 'block';
    tagName.style.visibility = "visible";
}
*/
function posLay(obj,Lay){
    var tagName = document.getElementById(Lay);
    var leftSide = findPosX(obj);
    var topSide = findPosY(obj);
    var maxW = tagName.style.width;
    var widthM = maxW.substring(0,maxW.length-2);
    var getVal = eval(leftSide) + eval(widthM);
    if(getVal  > document.body.clientWidth ){
        leftSide = eval(leftSide) - eval(widthM);
        tagName.style.left = leftSide + 'px';
    }
    else
        tagName.style.left= leftSide + 'px';
    tagName.style.top= topSide + 'px';
}

function fninvsh(Lay){

    var tagName = document.getElementById(Lay);
    if(tagName == null)
    {
        window.history.back();
    }else
    {
        tagName.style.visibility = 'hidden';
        tagName.style.display = 'none';
    }
}

function fnvshNrm(Lay){
    var tagName = document.getElementById(Lay);
    tagName.style.visibility = 'visible';
    tagName.style.display = 'block';
}

function cancelForm(frm)
{
	    window.history.back();
}

function trim(s)
{
	var newstr=s.replace(/^\s+|\s+$/g,"");
	return(newstr);
}

function clear_form(form)
{
	for (j = 0; j < form.elements.length; j++)
	{
		if (form.elements[j].type == 'text' || form.elements[j].type == 'select-one')
		{
			form.elements[j].value = '';
		}
	}
}

function ActivateCheckBox()
{
        var map = document.getElementById("saved_map_checkbox");
        var source = document.getElementById("saved_source");

        if(map.checked == true)
        {
                source.disabled = false;
        }
        else
        {
                source.disabled = true;
        }
}

//wipe for Convert Lead  

function fnSlide2(obj,inner)
{
  var buff = document.getElementById(obj).height;
  closeLimit = buff.substring(0,buff.length);
  menu_max = eval(closeLimit);
  var tagName = document.getElementById(inner);
  document.getElementById(obj).style.height=0 + "px"; menu_i=0;
  if (tagName.style.display == 'none')
          fnexpanLay2(obj,inner);
  else
        fncloseLay2(obj,inner);
 }

function fnexpanLay2(obj,inner)
{
    // document.getElementById(obj).style.display = 'run-in';
   var setText = eval(closeLimit) - 1;
   if (menu_i<=eval(closeLimit))
   {
            if (menu_i>setText){document.getElementById(inner).style.display='block';}
       document.getElementById(obj).style.height=menu_i + "px";
           setTimeout(function() { fnexpanLay2(obj,inner); },5);
        menu_i=menu_i+5;
   }
}

 function fncloseLay2(obj,inner)
{
  if (menu_max >= eval(openLimit))
   {
            if (menu_max<eval(closeLimit)){document.getElementById(inner).style.display='none';}
       document.getElementById(obj).style.height=menu_max +"px";
          setTimeout(function() { fncloseLay2(obj,inner); }, 5);
       menu_max = menu_max -5;
   }
}

function addOnloadEvent(fnc){
  if ( typeof window.addEventListener != "undefined" )
    window.addEventListener( "load", fnc, false );
  else if ( typeof window.attachEvent != "undefined" ) {
    window.attachEvent( "onload", fnc );
  }
  else {
    if ( window.onload != null ) {
      var oldOnload = window.onload;
      window.onload = function ( e ) {
        oldOnload( e );
        window[fnc]();
      };
    }
    else
      window.onload = fnc;
  }
}
function InternalMailer(record_id,type) {
        var url;
        switch(type) {
                case 'record_id':
                        url = 'index.php?module=Emails&action=EmailsAjax&internal_mailer=true&type='+type+'&record=&rec_id='+record_id+'&file=EditView';
                break;
                case 'email_addy':
                        url = 'index.php?module=Emails&action=EmailsAjax&internal_mailer=true&type='+type+'&record=&email_addy='+record_id+'&file=EditView';
                break;

        }

        var opts = "menubar=no,toolbar=no,location=no,status=no,resizable=yes,scrollbars=yes";
        openPopUp('xComposeEmail',this,url,'createemailWin',830,662,opts);
}

function fnHide_Event(obj){
        document.getElementById(obj).style.visibility = 'hidden';
}

function OpenCompose(id,mode) 
{
	switch(mode)
	{		
		case 'edit':
			url = 'index.php?module=Emails&action=EmailsAjax&file=EditView&record='+id;
			break;
		case 'create':
			url = 'index.php?module=Emails&action=EmailsAjax&file=EditView';
			break;
		case 'forward':
			url = 'index.php?module=Emails&action=EmailsAjax&file=EditView&record='+id+'&forward=true';
			break;
	}
	openPopUp('xComposeEmail',this,url,'createemailWin',820,689,'menubar=no,toolbar=no,location=no,status=no,resizable=no,scrollbars=yes');
}

//Function added for Mass select in Popup - Philip
function SelectAll(mod,parmod)
{

        x = document.selectall.selected_id.length;
	var y=0;
	if(parmod != 'Calendar')
        {
                var module = window.opener.document.getElementById('return_module').value
                var entity_id = window.opener.document.getElementById('parent_id').value
        }
        idstring = "";
	namestr = "";

        if ( x == undefined)
        {

                if (document.selectall.selected_id.checked)
                {
			idstring = document.selectall.selected_id.value;
			if(parmod == 'Calendar')
                                namestr = document.getElementById('calendarCont'+idstring).innerHTML;
                        y=1;
                }
                else
		{
                        selectone.getJSAlertValue("crm.alert.entity.sel",null,"en_US",
			  																					function(mesg) { alert(mesg) })
                        return false;
                }
        }
        else
        {
                y=0;
                for(i = 0; i < x ; i++)
                {
                        if(document.selectall.selected_id[i].checked)
                        {
                                idstring = document.selectall.selected_id[i].value +";"+idstring;
				if(parmod == 'Calendar')
                                {
                                        idval = document.selectall.selected_id[i].value;
                                        namestr = document.getElementById('calendarCont'+idval).innerHTML+"\n"+namestr;
                                }
                  		y=y+1;
                        }
                }
	}
	if (y != 0)
        {
        	document.selectall.idlist.value=idstring;
        }
        else
        {
                selectone.getJSAlertValue("crm.alert.entity.sel",null,"en_US",
			  																	function(mesg) { alert(mesg) })
                return false;
        }
        if(confirm("Are you sure you want to add the selected "+y+" records ?"))
        {
		if(parmod == 'Calendar')
                {
                        window.opener.document.EditView.contactidlist.value = idstring;
                        window.opener.document.EditView.contactlist.value = namestr;
                }
                else
                {
			opener.document.location.href="index.php?module="+module+"&parentid="+entity_id+"&action=updateRelations&destination_module="+mod+"&idlist="+idstring;
		}
                self.close();
        }
	else
        {
                return false;
        }
}
function ShowEmail(id)
{
       url = 'index.php?module=Emails&action=EmailsAjax&file=DetailView&record='+id;
       openPopUp('xComposeEmail',this,url,'createemailWin',820,695,'menubar=no,toolbar=no,location=no,status=no,resizable=no,scrollbars=yes');
}

var bSaf = (navigator.userAgent.indexOf('Safari') != -1);
var bOpera = (navigator.userAgent.indexOf('Opera') != -1);
var bMoz = (navigator.appName == 'Netscape');
function execJS(node) {
    var st = node.getElementsByTagName('SCRIPT');
    var strExec;
    for(var i=0;i<st.length; i++) {
      if (bSaf) {
        strExec = st[i].innerHTML;
      }
      else if (bOpera) {
        strExec = st[i].text;
      }
      else if (bMoz) {
        strExec = st[i].textContent;
      }
      else {
        strExec = st[i].text;
      }
      try {
        eval(strExec);
      } catch(e) {
        alert(e);
      }
    }
}

//Function added for getting the Tab Selected Values (Standard/Advanced Filters) for Custom View - Ahmed
function fnLoadCvValues(obj1,obj2,SelTab,unSelTab){

   var tabName1 = document.getElementById(obj1);

   var tabName2 = document.getElementById(obj2);

   var tagName1 = document.getElementById(SelTab);

   var tagName2 = document.getElementById(unSelTab);

   if(tabName1.className == "dvtUnSelectedCell")

       tabName1.className = "dvtSelectedCell";

   if(tabName2.className == "dvtSelectedCell")

       tabName2.className = "dvtUnSelectedCell";   
   tagName1.style.display='block';

   tagName2.style.display='none';

}


// Drop Dwon Menu


function fnDropDown(obj,Lay){
    var tagName = document.getElementById(Lay);
    var topPX = 25;
    var is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
    var is_safari = navigator.userAgent.toLowerCase().indexOf('safari') > -1;

    /*var leftSide = findPosX(obj);
    var topSide = findPosY(obj);
    var maxW = tagName.style.width;
    var widthM = maxW.substring(0,maxW.length-2);
    var getVal = eval(leftSide) + eval(widthM);
    if(getVal  > document.body.clientWidth ){
        leftSide = eval(leftSide) - eval(widthM);
        tagName.style.left = leftSide-40  + 'px';
    }
    else
        tagName.style.left= leftSide-40 + 'px';*/
    var topSide = findPosY(obj);
    tagName.style.left=findPosX(document.getElementById(Lay+"left"))+"px";
    if (is_chrome) 
    {
		topPX = 22;
	}
	else if(is_safari)
	{
		topPX = 21;
	}

	tagName.style.top= topSide + topPX +'px';

    if(tagName.style.display == 'block')
    {
    	tagName.style.display = 'None';
    }
    else
    {
	//due to hide Program tab Programs_sub is removed from the Array
         var Layfieldname = new Array('Home_sub','Contacts_sub','Sales_sub','Programs_sub','Inquiries_sub','Events_sub','Marketing_sub','Cases_sub','Analytics_sub');
        for (var i=0; i<Layfieldname.length; i++) 
        {
            var otherDisplay = Layfieldname[i];
            if(otherDisplay !=Lay && $(otherDisplay))
            {
                document.getElementById(otherDisplay).style.display = 'None';
            }

        }
		if(tagName.id!='Home_sub')
		{
    		tagName.style.display = 'block';
		}
    }
 }

function fnShowDrop(obj){
	document.getElementById(obj).style.display = 'block';
}

function fnHideDrop(obj){
	document.getElementById(obj).style.display = 'none';
}

function getCalendarPopup(imageid,fieldid,dateformat)
{
        Calendar.setup ({
                inputField : fieldid, ifFormat : dateformat, showsTime : false, button : imageid, singleClick : true, step : 1
        });
}
function showContactLogDiv(divId)
{
	document.getElementById(divId).style.display = 'block';
}

// Function used for tooltip in Cases Listview Subject column & contactLog
function callContactLog(obj,id)
{
    // Pop down any existing tooltip
    tt_HideInit();

    // Delay the popup until the mouse is stationary over the obj for
    // a determined length of time.  NOTE that the DELAY feature of
    // Tip() does NOT do the same thing.

    // Get the mouse position we're starting at.
    var mx = tt_musX;
    var my = tt_musY;

    // Start polling
    var pe = new PeriodicalExecuter(function() {
        // If we're not in the same place as when we last checked,
        // return and check again on the next pass.
        if (tt_musX != mx || tt_musY != my)
        {
            mx = tt_musX;
            my = tt_musY;
            return;
        }

        // Stop the timer
        pe.stop();

        // Once the tip is shown, we want different mouseout behavior.
        // Only popdown the tip if we're outside of the obj and the tip
        // for a given amount of time.
        obj.onmouseout = function() {
            var pe2 = new PeriodicalExecuter(function() {
                if (! Position.within ($('WzTtDiV'), tt_musX, tt_musY))
                {
                    UnTip();
                    pe2.stop();
                }
            }, 300);        // SEE NOTE BELOW
        }

        showContactLogToolTipNow(obj, id);
    }, 300);                    // SEE NOTE BELOW

    // N O T E  V E R Y  W E L L !!
    // The pe2 timeout SHOULD NOT BE GREATER THAN THE pe timeout.
    // If it is, that opens up the possibility that creating
    // another tooltip could be popped down by a stale pe2.

    // Update the mouseout func so that we can cancel the tooltip timer
    obj.onmouseout = function() {
        pe.stop();
    }
}

function showContactLogToolTipNow(obj,id)
{
    var url ="/crm/ContactLog.do?id="+id+"&module=Contacts";
    if(id.match("MID")=="MID")
    {
        var Mid=(id.split('_'))[1];
        url ="/crm/ContactLog.do?mid="+Mid+"&module=Contacts";
    }

    new Ajax.Request(url, {
        method:"post",
        onSuccess:function(t) {
            var msgTips = t.responseText;
            Tip(msgTips,
	                JUMPVERT, true,
	                JUMPHORZ, false,
	                FOLLOWMOUSE, false,
	                WIDTH, 700,
	                HEIGHT, 300,
	                CLICKCLOSE, false,
	                STICKY, false,
	                BGCOLOR, '#fff9d7',
	                ABOVE, true,
	                DELAY, 0,
	                SHADOW, true,
	                BORDERWIDTH, 2,
	                BORDERCOLOR, '#e2c822');
        },
        evalScripts:true
    });
}

function callSmsLog(obj,smslog)
{
    
    var str = smslog;
    //obj = getObj('CONTACTLOGSPERSONALITYimg');
    obj = getObj('href_'+smslog);
    fnvshobj(obj,'contactlogdiv1')
	tagName = document.getElementById('contactlogdiv1');
    var leftSide = findPosX(obj);
    var topSide = findPosY(obj);
    tagName.style.left = leftSide+'px';
    tagName.style.top= topSide -15 +'px';
    getObj('contactlogdiv1').innerHTML="<table><tr><td align='right'><img onclick='hideContactLog1()' src='/crm/images/close.gif'></img></td></tr><tr><td><pre WRAP='NOWRAP'>"+getObj(smslog).innerHTML+"</pre></td></tr></table>";
    show('contactlogdiv1');
 
}

function hideContactLog1()
{
document.getElementById("contactlogdiv1").style.display="none";
}


function checkMessageStatus(messageid)
{
    //alert("messageid -->"+ messageid);
    if(messageid == "No ACCESS Permission.")
    {
        alert ("Message Not Sent :"+ messageid);
        return;   
    }
    var http = getHTTPObject();
    var url ="/crm/CheckSMSStatus.do?messageid="+messageid;
    //alert(url);
    show('zohobusy_contactlog');
    http.open("GET", url, true);
    http.onreadystatechange = function()
    {
       if(http.readyState == 4)
       {
          document.getElementById('zohobusy_contactlog').style.display='none';  
          if(http.status!=200)
          {
            selectone.getJSAlertValue("crm.alert.status.find.unable",null,"en_US",
			  															function(mesg) { alert(mesg) })
          }
              
          var str = http.responseText;
        
          if(checkwetherTimedOut(str))
          {
               return;
          }
          alert(str);
              
       }
    }
    http.send(null);
 }
function importAttendees(entityid,entityName)
{
	document.location.href="/crm/ImportWizard.do?step=1&module=Attendees&moduleString=Attendees&dataScope=myData&entityid="+entityid+"&entityName="+entityName
/*
	var status=getObj('regisstatus').value;

	if(getObj('theFile').value=="")
	{
	selectone.getJSAlertValue("crm.alert.import.file.blank",null,"en_US",
			  										function(mesg) { alert(mesg) })
	return false;
	}	
	var fileName=getObj("theFile").value;
	var index=fileName.lastIndexOf('.');
	var ext = fileName.substring( index, fileName.length );
	if(ext != ".csv")
	{
	selectone.getJSAlertValue("crm.alert.import.csv",null,"en_US",
			  										function(mesg) { alert(mesg) })
	return false;
	}
		document.forms['exceldo'].action="/crm/ImportAttendees.do?eventId="+eventid+"&status="+status+"&from="+from;
	        document.forms['exceldo'].submit();*/

}
function eventRemainderChk()
{
    var remainderUnReg = getObj("property(Days before reminding unregistered invitees)").value;
    var remainderReg = getObj("property(Days before reminding registered invitees)").value;
    var startdate = getObj("property(Start DateTime)").value;
    var cutoffdate = getObj("property(Registration cut-off date)").value;

    if(remainderUnReg!=""&&remainderUnReg!=null)
    {
        var curObj = getObj("property(Days before reminding unregistered invitees)");
        var fieldlabel="Days before reminding unregistered invitees";
        if(!eventDateDiff(startdate,cutoffdate,remainderUnReg,curObj,fieldlabel))                        
            return false;
    }
    if(remainderReg!=""&&remainderReg!=null)
    {
        var curObj = getObj("property(Days before reminding registered invitees)");
        var fieldlabel="Days before reminding registered invitees";
        if(!eventDateDiff(startdate,cutoffdate,remainderReg,curObj,fieldlabel))                        
        return false;
    }
return true;
}    
function eventDateDiff(strDate1,strDate2,noOfdays,curobj,fieldlabel) 
{        
    var dateDiff = new Date( strDate1 ) - new Date( strDate2 );
    var days = dateDiff / (24*60*60*1000);
    if(noOfdays>days)
    {
    		selectone.getJSAlertValue("crm.alert.date.diff",null,"en_US",
			  function(mesg) { alert(fieldlabel + " " + mesg) })
        curobj.focus();
        return false
    }
return true;
}
 function CreateActionProgram(obj,id,name)
{
	if(obj.value=="Edit")
		document.location.href="/crm/Edit.do?tabGroup=Programs&module=Iterations&id="+id+"&isload=true";
	else if(obj.value=="Clone"){
		document.location.href="/crm/Clone.do?module=Iterations&id="+id+"&isload=true";
	}
	else if(obj.value=="Delete")
	{
		if(window.confirm('Are you sure ?')==true)
		{
			document.location.href="/crm/MassDelete.do?tabGroup=Programs&module=Iterations&id="+id;
		}
	}
	else if(obj.value=="View")
	{
		document.location.href="/crm/ShowEntityInfo.do?id="+id+"&module=Iterations&isload=true";
	}
	else if(obj.value=="CopyIterations")
		{
		document.location.href="/crm/IWCopyIteration.do?tabGroup=Programs&module=Programs&id="+id+"&iterationname="+name;
		}
	
	obj.value ="Action";

}

function createActionIteration()
{
	var tabGroup=document.getElementById("tabGroup").value;
	document.location.href = "/crm/Create.do?tabGroup="+tabGroup+"&module=Iterations" ;
}   
function createAction()
{
	var module=document.getElementById("module").value;
	var tabGroup=document.getElementById("tabGroup").value;
	/*
	if(module=="Programs")
	{ */
	document.location.href="/crm/Create.do?tabGroup="+tabGroup+"&module="+module;
   /*	}
	else
	{ 
	document.showcvdetails.action="/crm/Create.do?module="+module;
	document.showcvdetails.method="post";
	document.showcvdetails.submit();
	}*/
}
function siteTabControl(tabName,siteType,siteId)
{
	if(siteType != "Create")
	{
		if(tabName == "BuilderSec")
		{
			showSiteTab(tabName,siteType,siteId);
		}
	}
	else
	{
		var url="/crm/Edit.do?type="+siteType+"&module=Sites&id="+siteId;
		loadAjaxTab4("Loading...");
		new Ajax.Request(url,{method:"post",onSuccess:function(t)
       		{
			getObj("show").innerHTML = t.responseText;
			showSiteTab(tabName,siteType,siteId);
	 		document.getElementById('ajax_load_tab').style.display='none';
       		},asynchronous:true,evalScripts:true
       		});
	}
}
function showSiteTab(tabName,siteType,siteId)
{
	var profileObj=document.getElementById('ProfileSec');
	var builderObj=document.getElementById('BuilderSec');
	if(tabName == "ProfileSec")
	{
		var url='/crm/Edit.do?module=Sites&id='+siteId;
		new Ajax.Updater('show',url,{method:"get",onComplete:function()
       		{
			profileObj.style.display="block";
			document.getElementById('siteProfileTab').className="dvtSelectedCell";
			builderObj.style.display="none";
			document.getElementById('siteBuilderTab').className="crdvtUnSelectedCell";
	       },asynchronous:true,evalScripts:true
       		});
	}
	else
	{
		if(getObj('valueChanged').value == 'true' && !window.confirm("Do you want to proceed without saving the changes"))
		{
		}
		else
		{
			if(getObj("valueChanged")!=null)
			{
				getObj("valueChanged").value="false";
			}
			if(siteType =='' || siteType==null || siteType=="null" || siteType=="Edit")
			{
				var url="/crm/ViewSite.do?sid="+siteId;
				loadAjaxTab4("Loading...");
				new Ajax.Request(url,{onComplete:function(t){
				
					var resText=t.responseText;
					if(resText != '' && resText !=null && resText != "null")
					{
						resText=replaceAll(resText,'<form', '<Xform');
						resText=replaceAll(resText,'<FORM','<Xform');
						resText=replaceAll(resText,'form>','Yform>')
						resText=replaceAll(resText,'FORM>','Yform>');	
						addHeader(resText);
					}
					profileObj.style.display="none";
					document.getElementById('siteProfileTab').className="crdvtUnSelectedCell";
					builderObj.style.display="block";
					document.getElementById('siteBuilderTab').className="dvtSelectedCell";
					document.getElementById('ajax_load_tab').style.display='none';
				},asynchronous:true,evalScripts:true});
			}
			else
			{
				profileObj.style.display="none";
				document.getElementById('siteProfileTab').className="crdvtUnSelectedCell";
				builderObj.style.display="block";
				document.getElementById('siteBuilderTab').className="dvtSelectedCell";
			}
		}	

	}
}
function saveSite(module,type)
{
	if(getObj("property(Name)").value==null || getObj("property(Name)").value=='' || getObj("property(Name)").value.trim()== "")
	{
		alert("Name cannot be blank");
		return false;
	}
	var re1=/^[a-z\d\s ]+$/i;
	if (!re1.test(getObj("property(Name)").value))
	{
		alert('Special characters are not allowed in Name');
		return false;
	}
	formData = formData2QueryString(document.createEntityForm);
	var url="/crm/CreateCommonModule.do?module="+module;
	loadAjaxTab4("Loading...");
	new Ajax.Request(url,{method:"post",onSuccess:function(t)
       	{
		getObj("show").innerHTML = t.responseText;
		 document.getElementById('ajax_load_tab').style.display='none';
       },asynchronous:true,postBody:formData,evalScripts:true
       });
}

function updateSite(module,type,id)
{
	if(getObj("property(Name)").value==null || getObj("property(Name)").value=='')
	{
		alert("Name cannot be blank");
		return false;
	}
	var re1=/^[a-z\d\s ]+$/i;
	if (!re1.test(getObj("property(Name)").value))
	{
		alert('Special characters are not allowed in Name');
		return false;
	}
	formData = formData2QueryString(document.createEntityForm);
	var url="/crm/UpdateSite.do?type="+type+"&tabGroup=Home&module="+module+"&siteId="+id;
	loadAjaxTab4("Loading...");
	new Ajax.Request(url,{method:"post",onSuccess:function(t)
       	{
		getObj("show").innerHTML = t.responseText;
		 document.getElementById('ajax_load_tab').style.display='none';
       },asynchronous:true,postBody:formData,evalScripts:true
       });
}



function editSection(sectionName,divType)
{
	var currObj=document.getElementById(sectionName);
	document.getElementById('iwFCKEditor').style.top=findPosY(currObj)-40;
	var url ='/crm/jsp/IWFCKEditor.jsp?divId='+sectionName+'&divType='+divType;
	new Ajax.Updater('iwFCKEditor',url,{onComplete:function(){
		if(getObj(sectionName+'_hint'))
		{
			getObj(sectionName).removeChild(getObj(sectionName+'_hint')); 
		}
                if(divType == "Sites")
                {
                    var txtval=document.getElementById(sectionName).innerHTML;
                }
                else
                {
                    var txtval=document.getElementById(sectionName).value;
                }
		
		txtval=replaceAll(txtval,'Yform>','form>');
		txtval=replaceAll(txtval,'<Xform','<form');
		txtval=replaceAll(txtval,'</Xform>','');
		
		document.getElementById("description_fck").value = txtval;
		
		var oFCKeditor = new FCKeditor('description_fck', "100%", 330, "Default");
		oFCKeditor.BasePath = "/crm/javascript/fckeditor/";
		oFCKeditor.Config["CustomConfigurationsPath"] = "/crm/javascript/fckiw.js";
		oFCKeditor.ReplaceTextarea();

		showBlock('iwFCKEditor');
					
	},asynchronous:true,evalScripts:true});		
	freezeBackground();
}
function saveSection(sectionName,divType)
{
	var str=getContent();  
	if((str == '' || str == null || str == 'null') && divType == "Sites")
	{
		addHint(sectionName);
	}
	else
	{
		str = replaceAll(str,'<form', '<Xform');
		str = replaceAll(str,'<FORM','<Xform');
		str = replaceAll(str,'form>','Yform>')
		str = replaceAll(str,'FORM>','Yform>');		
                if(divType == "Sites")
                {
                    document.getElementById(sectionName).innerHTML=str;
                }
                else
                {
                    document.getElementById(sectionName).value=str;
                }
	}
	if (document.getElementById('FreezeLayer') != null) {document.body.removeChild(document.getElementById('FreezeLayer'));}
	hide('iwFCKEditor');
}

function replaceAll(orgStr,findStr,replaceStr)
{
	return(orgStr.replace(new RegExp(findStr,"g"), replaceStr));
}

function closeFCKEditor(sectionName,divType)
{
	var secContent=(document.getElementById(sectionName).innerHTML).trim();
	if((secContent == '' || secContent == null || secContent == 'null') && divType == "Sites")
	{
		addHint(sectionName);
	}
	hide('iwFCKEditor');
	if (document.getElementById('FreezeLayer') != null) {document.body.removeChild(document.getElementById('FreezeLayer'));}
}

function addHint(sectionName)
{
	var headerhint="<span id='header_hint'><i>This area will contain the Header Information.</i></span>";
	var contenthint="<span id='content_hint'><i>This area will display the content of your Site.</i></span>";
	var footerhint="<span id='footer_intel_hint'><i>This area will contain the Footer Information.</i></span>";
	if(sectionName == 'header')
	{	
		getObj(sectionName).innerHTML=headerhint;
	}
	else if(sectionName == 'content')
	{
		getObj(sectionName).innerHTML=contenthint;
	}
	else if(sectionName == 'footer' || sectionName == 'footer_intel')
	{
		document.getElementById('footer_intel').innerHTML=footerhint;
	}
}

function changeBgColor()
{
	document.getElementById('sectionName').value="container";
	var url ='/crm/jsp/IWColorPicker.jsp';
	new Ajax.Updater('iwColorPicker',url,{onComplete:function(){
		changeBgClr('container');show('colorPicker');},asynchronous:true});
}
function changeBgClr(secId)
{
	document.getElementById('divId').value=secId;
	var prevColor=document.getElementById(secId).style.backgroundColor;
	document.getElementById('ColorPreview').style.backgroundColor=prevColor;
//	document.getElementById('PrevColor').style.backgroundColor=prevColor;
	document.getElementById('ColorHex').value="#"+findHexCode(secId);
}
function findHexCode(secId)
{
	var prevColor=document.getElementById(secId).style.backgroundColor;
	if(browser_ie)
	{
		if(prevColor.substring(0,1)=='#')
			prevColor=prevColor.substring(1,prevColor.length);
		return prevColor;
	}
	else
	{
		var RGBStr=prevColor.substring(4,prevColor.length-1);
		var RGBValues=RGBStr.split(",");
		var hexColor=toHEX(RGBValues[0])+toHEX(RGBValues[1])+toHEX(RGBValues[2]);
		return hexColor;
	}
}
function toHEX(colorCode) {
	if (colorCode==null) 
	{
		return "00";
	}
 	colorCode=parseInt(colorCode); 
 	if (colorCode==0 || isNaN(colorCode)) 
	{
		return "00";
	}
 	colorCode=Math.max(0,colorCode); 
 	colorCode=Math.min(colorCode,255); 
 	colorCode=Math.round(colorCode);
	var hexCode="0123456789ABCDEF".charAt((colorCode-colorCode%16)/16)+ "0123456789ABCDEF".charAt(colorCode%16);
 	return hexCode;
}
function setBgColor(colorCode)
{
	var secId=document.getElementById('divId').value;
	document.getElementById('ColorHex').value=colorCode;
	document.getElementById('ColorPreview').style.backgroundColor=colorCode;
	document.getElementById(secId).style.backgroundColor=colorCode;
}

function saveSiteContent(actionType,module,siteId,action)
{
	if(action == "DetailsView")
	{
		document.viewentityform.action="/crm/SaveSite.do?tabGroup=Home&module=Sites&siteId="+siteId+"&actionType="+actionType.value;
		document.viewentityform.submit();
	}
	else
	{
		removeHeader();
		var content=document.getElementById("OuterDiv").innerHTML;
		content=replaceAll(content,'Yform>','form>');
		content=replaceAll(content,'<Xform','<form');
		content=replaceAll(content,'</Xform>','');
		
		document.getElementById("siteString").value="<html><head><title>"+getObj("property(Name)").value+"</title></head><body style='margin:0px;background-color:#"+findHexCode('container')+"'>"+content+"</body></html>";
		document.createEntityForm.action="/crm/SaveSite.do?tabGroup=Home&module=Sites&siteId="+siteId+"&actionType="+actionType.value;
		document.createEntityForm.submit();
	}
}
function removeHeader()
{
	var parentDiv= document.getElementById('container');
	var divArray=new Array('header_head','content_head','footer_head');
	for(var i=0;i<divArray.length;i++)
	{
		var childDiv=document.getElementById(divArray[i])
		if(childDiv != '' && childDiv != 'null' && childDiv != null)
		{
		        parentDiv.removeChild(childDiv);	
		}
	}

	var parentArray=new Array('header','content','footer_intel');
	var childArray=new Array('header_hint','content_hint','footer_intel_hint');
	for(var i=0;i<3;i++)
	{
		var parentObj=document.getElementById(parentArray[i]);
		var childObj=document.getElementById(childArray[i]);
		if(childObj != '' && childObj != 'null' && childObj != null)
		{
			parentObj.removeChild(childObj);
		}
	}
	for(var i=0;i<3;i++)
	{
		document.getElementById(parentArray[i]).className="";
	}

}
function addHeader(resText)
{
	document.getElementById('OuterDiv').innerHTML=resText;
	var headerContent=(document.getElementById('header').innerHTML);
	var bodyContent=(document.getElementById('content').innerHTML);
	var footerContent;
	var footer;
	if(document.getElementById('footer_intel'))
	{
		footerContent = (document.getElementById('footer_intel').innerHTML);
		footer='footer_intel';
	}
	else
	{
		footerContent = (document.getElementById('footer').innerHTML);
		footer='footer';
	}
	var siteContent='<div id="container" style="background-color:#'+findHexCode('container')+';width:90%;padding:50px;"><div style="width:8%;" id="header_head" class="editlink" nowrap="nowrap" onclick="editSection(\'header\',\'Sites\')">Edit Header</div><div id="header" class="siteoutline" style="background-color:#'+findHexCode('header')+'">';
	
	if(headerContent == '' || headerContent == null || headerContent == 'null')
	{
		addHint('header');
	}
	siteContent=siteContent+document.getElementById('header').innerHTML+'</div><br/><div style="width:3%;" id="content_head" class="editlink" nowrap="nowrap" onclick="editSection(\'content\',\'Sites\')">Edit</div><div id="content" class="siteoutline" style="background-color:#'+findHexCode('content')+'">';
	if(bodyContent == '' || bodyContent == null || bodyContent == 'null')
	{
		addHint('content');
	}
	siteContent=siteContent+document.getElementById('content').innerHTML+'</div><br /><div style="width:7%;" id="footer_head" class="editlink" nowrap="nowrap" onclick="editSection(\'footer_intel\',\'Sites\')">Edit Footer</div><div id="footer_intel" class="siteoutline" style="background-color:#'+findHexCode(footer)+'">';
	if(footerContent == '' || footerContent == null || footerContent == 'null')
	{		
		siteContent=siteContent+"<span id='footer_intel_hint'><i>This area will contain the Footer Information.</i></span>";		 	
	}
	siteContent=siteContent+footerContent+'</div></div>';		
	document.getElementById('OuterDiv').innerHTML=siteContent;
}
function loadColorValues()
{
	document.getElementById("colorValues").value=findHexCode("container")+":"+findHexCode("header")+":"+findHexCode("content")+":"+findHexCode("footer_intel");
}
function resetBgColor()
{
	var colorValues=(document.getElementById("colorValues").value).split(":");
	var secArray=new Array("container","header","content","footer_intel");
	for(var i=0;i<4;i++)
	{
		document.getElementById(secArray[i]).style.backgroundColor=colorValues[i];
	}
}
function callSitePreview()
{
	var siteContent=document.getElementById('OuterDiv').innerHTML;

	siteContent=replaceAll(siteContent,'Yform>','form>');
	siteContent=replaceAll(siteContent,'<Xform','<form');
	siteContent=replaceAll(siteContent,'</Xform>','');
	var previewContent='<html><head><title>'+getObj("property(Name)").value+'</title></head><body style="margin:0px;background-color:#'+findHexCode('container')+'">'+siteContent+'<script type="text\/javascript">removeSecHeader();function removeSecHeader() {document.getElementById("header_head").style.display="none";document.getElementById("content_head").style.display="none";document.getElementById("footer_head").style.display="none";var hintArray=new Array("header_hint","content_hint","footer_hint");for(var i=0;i<3;i++){var hintObj=document.getElementById(hintArray[i]);if(hintObj){hintObj.style.display="none";}}var secArray=new Array("header","content","footer");for(var i=0;i<3;i++){document.getElementById(secArray[i]).className="";}}<\/script></body></html>';
	var myWin=window.open('','myWin','menubar=no,toolbar=no,location=no,status=no,scrollbars=yes,resizable=yes,left=30px,top=40px,height=550px,width=800px');
	myWin.document.open();
	myWin.document.write(previewContent);
	myWin.document.close();
}
function createNewPage(siteId)
{
	var currObj=document.getElementById('toolbar');
	document.getElementById('newPage').style.top=findPosY(currObj);
	var url ='/crm/jsp/IWNewPage.jsp?siteId='+siteId;
	
	new Ajax.Updater('newPage',url,{onComplete:function(){  
		show('newPage');
                
	},asynchronous:true,evalScripts:true});	
	freezeBackground();	
}

function handleForm(cvname,cvid,isshowall,filtertype)
{
    var filtertype = filtertype;  
    var module=document.getElementById("module").value;
	document.showcvdetails.showall.value=isshowall;
    if(module == "LifeCycles" )
    {
        var checkeditems= getCheckedItems(document.showcvdetails.lrole.value);
        if(checkeditems=="")
        {
            if(!isshowall)
            {
					document.showcvdetails.showall.value='false';
     					selectone.getJSAlertValue("crm.alert.select.one",null,"en_US",
			  																function(mesg) { alert(mesg) })  
                return;
            }
        }
    }
	//document.showcvdetails.lifeCyclehiddenlist.value=checkeditems
	document.showcvdetails.stageHidden.value=checkeditems;
        if(filtertype!="programfilter")
        {
            var programid = getObj("filterProgramId").value;            
            var iterationid = getObj("filterIterationId").value;            
            if((!programid=="" && iterationid =="")||(programid=="" && !iterationid ==""))
            {
                selectone.getJSAlertValue("crm.alert.prog.iter.sel",null,"en_US",
			  																	function(mesg) { alert(mesg) })
                return false;
            
            }
           
            if(!programid=="" && !iterationid =="")
            {
                var args ="module=LifeCycles&display_cust_view_name="+escape(cvname)+"&cvid="+cvid+"&rangeValue="+escape(getObj("rangeValue").value)+ "&lrole="+ document.showcvdetails.lrole.value+"&stages="+checkeditems+"&showAll="+ document.showcvdetails.showall.value+"&programid="+ programid+"&iterationid="+iterationid+"&filtertype="+filtertype;
            }
            else
            {
                 var args ="module=LifeCycles&display_cust_view_name="+escape(cvname)+"&cvid="+cvid+"&rangeValue="+escape(getObj("rangeValue").value)+ "&lrole="+ document.showcvdetails.lrole.value+"&stages="+checkeditems+"&showAll="+ document.showcvdetails.showall.value+"&filtertype="+filtertype;
            }
            
        }
        else
        {
            var programid = getObj("programid").value;
            
            var iterationid = getObj("iterationid").value;
            
            if(!programid=="" && iterationid =="")
            {
               	selectone.getJSAlertValue("crm.alert.prog.iter.sel",null,"en_US",
			  																	function(mesg) { alert(mesg) })
                return false;
            
            }
            	document.showcvdetails.filterProgramId.value=programid
		document.showcvdetails.filterIterationId.value=iterationid

            var args ="module="+module+"&display_cust_view_name="+escape(cvname)+"&cvid="+cvid+"&rangeValue="+escape(getObj("rangeValue").value)+ "&programid="+ programid+"&iterationid="+iterationid+"&showAll="+ document.showcvdetails.showall.value+"&filtertype="+filtertype;
        }
	var url ="/crm/IWFilterLifeCycleAction.do?"+args;
    		showInLine('zohobusy_lfilter_search');
                    httphandle.open("GET", url, true);	
	httphandle.onreadystatechange = function() 
	{
		if(httphandle.readyState == 4) 
		{
			var str = httphandle.responseText;
			if(checkwetherTimedOut(str))
			{
				return;
			}
			if(httphandle.status == 200) 
			{
				divObj = getObj('idForCV');
				divObj.innerHTML="";
				divObj.innerHTML=str;
				hide('zohobusy_lfilter_search');				
			}
			isWorking = false;
		}
	}	
	httphandle.send(null);
}

//Used to dfb form validation

function sectionSorting()
{
    if(getObj("sectioncountvalue")){
        
        var sseq = parseInt(getObj("sectioncountvalue").value);      
        if( sseq !=null && sseq !="" && sseq !="null" && sseq !=0 ){            
            
            for(var i=1;i<=sseq;i++)
            {    
                getObj("sectionindex_"+i).value = i ;                
            } 
        }
    }  

}


function DFBFormValidate()
{
    var noofpages = document.getElementById("noofpages").value;    
    var totPageEmpty =null;
     var contactsPresence =0;           
    var contactSelectedFields ="null";
var showlabelsPresence =0;
var showlabels =null;
var displaySecType =null;
var displaymodType =null;
var displayshowlabels=null;
    for(var n=1;n<=noofpages;n++)
    {
        var secCount = document.getElementById("sectionId__"+n).value ;   
        if(secCount == 0)
        {
            alert('The Page '+n+' can not be blank')
            return false;
        }
        if(secCount ==0  && totPageEmpty ==null) 
        {
            totPageEmpty =0;            
        }
        else 
        {
            totPageEmpty =1;
            //sectionSorting();
            for(var i=1;i<= secCount;i++)
            {
                var secType = getObj("sectiontype_"+n+"_"+i).value;
               

                if(secType == "Contacts" )
                {
                    contactsPresence = 1;
                    if( contactSelectedFields == "null" )
                    {
                        contactSelectedFields = getObj("selectfieldsdiv_"+n+"_"+i+"_SF").value;
                    }
                    else
                    {
                        contactSelectedFields = contactSelectedFields + "," +getObj("selectfieldsdiv_"+n+"_"+i+"_SF").value;
                    }
                }
               
            }
            
            
            if(contactsPresence != 0)
            {                
               var isMandFields = getObj("Contacts_mandatory").value;
               var mandatoryArr = isMandFields.split(",");
               var showContactLabels =null;
               var showContactLabelsPresence =0;
               for(var i=0;i<mandatoryArr.length;i++)
               {
                    var mandField = mandatoryArr[i];
                    var result = contactSelectedFields.match(mandField);                    
                    if(result == null)
                    {   
                            var showContactLabelsArr = mandField.split(":#:");
                            if(showContactLabels == null)
                                showContactLabels = showContactLabelsArr[2];
                            else
                                showContactLabels = showContactLabels +"\n"+ showContactLabelsArr[2];
                            showContactLabelsPresence =1;                        
                    }
               }
               
               
               
            }
            // non contacts module
            for(var i=1;i<= secCount;i++)
            {
                var secType = getObj("sectiontype_"+n+"_"+i).value;
                if(secType != "Contacts" )
                {
                    var otherModulesSelectedFields = getObj("selectfieldsdiv_"+n+"_"+i+"_SF").value;
                    if(secType == "School" || secType == "Employer" || secType == "OtherAccounts" )
                    {
                        var otherModulesMandFields = getObj("Accounts_mandatory").value;
                    }
                    else if(secType == "Discounts")
                    {
                        var otherModulesMandFields = getObj("Discounts_mandatory").value;
                    }
                    else if(secType == "Cases")
                    {
                        var otherModulesMandFields = getObj("Cases_mandatory").value;
                    }
                    else if(secType == "Attachments")
                    {
                        var otherModulesMandFields = getObj("Attachments_mandatory").value;
                    }
                    else if(secType == "Registrations")
                    {
                        var otherModulesMandFields = "";
                    }
                    else if(secType == "Recommendations")
                    {
                        var otherModulesMandFields = "CrmContactDetails:#:EMAIL:#:Email";
                        otherModulesMandFields  = otherModulesMandFields+",CrmContactDetails:#:FIRSTNAME:#:First Name";
                        otherModulesMandFields  = otherModulesMandFields+",CrmContactDetails:#:LASTNAME:#:Last Name";
                    }
                    else
                    {
                        var otherModulesMandFields = getObj("Contacts_mandatory").value;
                    }
                   var otherModulesMandFieldsArr = otherModulesMandFields.split(",");         
                     
                   var showlabels = null;
                   for(var j=0;j<otherModulesMandFieldsArr.length;j++)
                   {
                        var otherModuleMandField = otherModulesMandFieldsArr[j];
                        var result = otherModulesSelectedFields.match(otherModuleMandField); 
                        if(result == null)
                        {      
                            var showlabelsArr = otherModuleMandField.split(":#:");
                            if(showlabels == null)
                                showlabels = showlabelsArr[2];
                            else
                                showlabels = showlabels +"\n"+ showlabelsArr[2];
                                
                            showlabelsPresence =1;   

                         displaySecType = secType;
                        displaymodType = secType ;
                        if(secType =="School")
                            displaySecType = "Educational History";
                        else if(secType =="Employer")
                            displaySecType ="Employment History";
                        else if(secType =="OtherAccounts")
                            displaySecType ="Other Organizational Relationships";
                            
                            if(showlabels!=null)
                                displayshowlabels = showlabels
                        }
                   }
/*
                   if(showlabelsPresence == 1)
                   {
                        var displaySecType = secType;
                        displaymodType = secType ;
                        if(secType =="School")
                            displaySecType = "Educational History";
                        else if(secType =="Employer")
                            displaySecType ="Employment History";
                        else if(secType =="OtherAccounts")
                            displaySecType ="Other Organizational Relationships";

                       // alert("You must select the following fields from '"+displaySecType+"' Module into '"+secType+"' type of section \n \n"+showlabels);
                       // return false;
                   }
*/

                }               
            }
        }
}
        if(totPageEmpty !=1 ) 
        {
            
            alert('The Form must contain one Section with Contact Fields in any Page');
            return false;
            
        }
        if(contactsPresence == 0)
            {
                alert('The Form must contain one Section  with Contact Fields');
                return false;
            }
            if(showContactLabelsPresence == 1)
               {                       
                    alert("You must select the following fields  from Contacts Module into Contacts type of section\n \n"+showContactLabels);
                    return false;
               }
               if(showlabelsPresence == 1)
                   {
                        
                        alert("You must select the following fields from '"+displaySecType+"' Module into '"+displaymodType+"' type of section \n \n"+displayshowlabels);
                        return false;
                   }
        
       return true;
}
function getContent()
{
   var oEditor = FCKeditorAPI.GetInstance('description_fck') ;
   return( oEditor.GetXHTML( true ) ) ;
}
function setContent(message)
{
   var oEditor = FCKeditorAPI.GetInstance('description_fck') ;
   oEditor.SetHTML( message )
}
function insertContent(message)
{
	var oEditor=FCKeditorAPI.GetInstance('description_fck');
	oEditor.InsertHtml(message);
}

function setContentFooter(message)
{
   var oEditor = FCKeditorAPI.GetInstance('invoiceFooter') ;
   oEditor.SetHTML( message )
}
function getContentFooter()
{
	var oEditor = FCKeditorAPI.GetInstance('invoiceFooter') ;
	return( oEditor.GetXHTML( true ) ) ;
}
function setContentHeader(message)
{
   var oEditor = FCKeditorAPI.GetInstance('invoiceHeader') ;
   oEditor.SetHTML( message )
}
function getContentHeader()
{
	var oEditor = FCKeditorAPI.GetInstance('invoiceHeader') ;
	return( oEditor.GetXHTML( true ) ) ;
}

function dfbFormAccValidation()
{
       if(getObj("empModuleValidationList"))
       {            
            var empModValidList = document.getElementById("empModuleValidationList").value;
            if(empModValidList!=null && empModValidList!="" && empModValidList!="null"  )
            {
                var empModValidListArr = empModValidList.split(":##:")
                for(var i=0;i< empModValidListArr.length;i++)
                {                    
                    var currObj=getObj(empModValidListArr[i])
                    if( !(currObj.value == "none" || currObj.value =="-None-" || currObj.value.replace(/^\s+/g, '').length==0) ) 
                    {
                       var empModuleAccName = document.getElementById("empModuleAccName").value;
                       if((getObj(empModuleAccName).value.replace(/^\s+/g, '').length==0) ) 
                       {
                            var fieldLabel = empModuleAccName.substring(empModuleAccName.indexOf("_")+1);
                            alert(fieldLabel+' cannot be blank');
                            return false;                 
                       }
                    }
                }
            }
       }
       if(getObj("schoolModuleValidationList"))
       {            
            var schoolModValidList = document.getElementById("schoolModuleValidationList").value;
            if(schoolModValidList!=null && schoolModValidList!="" && schoolModValidList!="null"  )
            {
                var schoolModValidListArr = schoolModValidList.split(":##:")
                for(var i=0;i< schoolModValidListArr.length;i++)
                {                    
                    var currObj=getObj(schoolModValidListArr[i])
                    if( !(currObj.value == "none" || currObj.value =="-None-" || currObj.value.replace(/^\s+/g, '').length==0) ) 
                    {
                       var schoolModuleAccName = document.getElementById("schoolModuleAccName").value;
                       if((getObj(schoolModuleAccName).value.replace(/^\s+/g, '').length==0) ) 
                       {
                            var fieldLabel = schoolModuleAccName.substring(schoolModuleAccName.indexOf("_")+1);
                            alert(fieldLabel+' cannot be blank');
                            return false;                 
                       }
                    }
                }
            }
       }
       return true;
}
function clearIteration()
{
if(getObj("property(NewIteration Name)"))
{
getObj("property(NewIteration Name)").value="";
}
if(getObj("iterationid"))
{
getObj("iterationid").value="";
}

}
function clearFilterLookUp(fldName,fldId)
{
	if(getObj(fldName)){
        getObj(fldName).value="";
    }
    if(getObj(fldId)){
        getObj(fldId).value="";
    }


}

//added this method for quick links
function callQuickLinkActions(actionName,id,module,skintype,anchor,loginname,invoiceid)
{
	DWRCommonUtil.hasAccess(module,function(hasAccess)
	{
		if(hasAccess==true)
		{
			doQuickLinkActions(actionName,id,module,skintype,anchor,loginname,invoiceid);
		}
	}
	);
}
function doQuickLinkActions(actionName,id,module,skintype,anchor,loginname,invoiceid)
{
     var entityName ="";   
     if(document.getElementById("module_entityName")){
        var entityName = document.getElementById("module_entityName").value;
      }  

    if(actionName == "SENDMAIL")
    {
        DWRCommonUtil.containsEmail
        (
            id,module,
            function(isPresent)
            {
                emailPresent=isPresent;
                if(emailPresent!= true)
                {
                    selectone.getResoureValue("crm.alert.contact.email.empty","Contacts","en_US",function(mesg) { alert(mesg) })
                }    
                else if (!isWorking && http)
                {
                    //openPopUp("SendMail",this,"/crm/jsp/IWSendMailForContacts.jsp?append_ids="+id+"&module="+module+"&skintype="+skintype,"SendMail",840,700,"menubar=no,toolbar=no,location=no,status=no,scrollbars=yes,resizable=yes");
                    openPopUp("SendMail",this,"/crm/IWSendMailForContacts.do?append_ids="+id+"&module="+module+"&skintype="+skintype,"SendMail",750,500,"menubar=no,toolbar=no,location=no,status=no,scrollbars=yes,resizable=yes");
                }
            }
         );
    }
    else if(actionName == 'MAKECREDITPAYMENT'){
		window.open("/crm/InitiatePayment.do?invoiceId="+id);
    }
    else if(actionName == 'MAKEONLINEPAYMENT'){
    	   	openPopUp("shen",this,"/crm/MakeOnlinePayment.do?append_ids="+id+"&module="+module+"&invoiceid="+invoiceid+"&skintype="+skintype,"shen",550,350,"menubar=no,toolbar=no,location=no,status=no,scrollbars=yes,resizable=yes");
           }
    else if(actionName == "ADDTASK")
    {
        selectActionOld('NewTask',anchor);
    }
    else if(actionName == "ADDAPPOINTMENT")
    {
        selectActionOld('Appointments',anchor);
    }
    else if(actionName == "ADDATTACHMENT")
    {
        selectActionOld('Attach',anchor);
    }
    else if(actionName == "ADDNOTE")
    {
        selectActionOld('Notes',anchor);
    }
    else if(actionName == "ADDOPPORTUNITY")
    {        
        var mod = document.getElementById("module_quickLink").value;
        if(mod == "Contacts")
            createPotentialForContact( id,entityName,'','', anchor)
        else
        {            
            createOld('Potentials',id,entityName,anchor)            
        }
    }
    else if(actionName == "ADDEDITINVOICE")	
    {	
	document.location.href="/crm/IWAddOrUpdateCaseOpp.do?relmodule=Registrations&module=Invoices&entityid="+id; 

    }

    else if(actionName == "ADDITERATION")
    {
	createOld('Iterations',id,entityName,anchor);	 
    }
    else if(actionName == "ADDREGISTRATION")
    {
	createOld('Registrations',id,entityName,anchor);	 
    }
    else if(actionName == "ADDRECOMMENDATIONS")
    {
		createOld('Recommendations',id,entityName,anchor);	 
    }
    else if(actionName == "ADDLIFECYCLE")
    {
	createOld('LifeCycles',id,entityName,anchor);	 
    }
    else if(actionName == "ADDPAYMENT")
    {
	createOld('Payments',id,entityName,anchor);	 
    }
    else if(actionName == "ADDCASE")
    {
        createOld('Cases',id,entityName,anchor)        
    }
    else if(actionName == "ADDLIFECYCLE")
    {
        createOld('LifeCycles',id,entityName,anchor)        
    }
    else if(actionName == "ADDATTENDEE")
    {        
        createOld('Attendees',id,entityName,anchor)
    }
    else if(actionName == "ADDEXCLUSION")
    {        
        createOld('Exclusions',id,entityName,anchor)
    }
    else if(actionName == "ADDCONNECTION")
    {        
        createOld('Connections',id,entityName,anchor)
    }
    else if(actionName == "ADDEDUCATION")
    {        
        createOld('Educations',id,entityName,anchor)
    }
    else if(actionName == "ADDEXPERIENCE")
    {        
        createOld('Experiences',id,entityName,anchor)
    }
    else if(actionName == "ADDRELATEDACC")
    {        
        createOld('RelatedAccounts',id,entityName,anchor)
    }
    else if(actionName == "ADDREQUIREMENT")
    {        
        createOld('Requirements',id,entityName,anchor)
    }
    else
    {
        return false;
    }
}
//added the following methods for Advanced level Search

function advSearchView()
{    
   document.getElementById("advSearchEnable").value="true"; 
   setCVName(getObj("cvid"),getObj("cvid").options.selectedIndex,"","true")
   
}
function setAdvSearchText(count)
{
    var selVal = document.getElementById("advSearch_select_"+count).value;
    if(selVal == "Is empty" || selVal == "Is not empty" || selVal=="true" || selVal=="false")
    {
        document.getElementById("advSearch_text_"+count).disabled =true;
        document.getElementById("advSearch_text_"+count).value="";
        if(document.getElementById("advSearch_DT_"+count))
        {
            document.getElementById("advSearch_DT_"+count).value="";
        }
    }
    else
    {
        document.getElementById("advSearch_text_"+count).disabled =false;
    }   
}
function callCancelAdvSearch()
{
    
    for(var i=1;i<=document.getElementById("advSearchCnt").value;i++)
    {
        document.getElementById("advSearch_text_"+i).value ="";
        if(document.getElementById("advSearch_DT_"+i))
        {
            document.getElementById("advSearch_DT_"+i).value="";
        }
    }
    document.getElementById("advSearchEnable").value="false";
    setCVName(getObj("cvid"),getObj("cvid").options.selectedIndex,"","true")

    
}

function callClearAdvSearch()
{
	for(var loop=1;loop<=document.getElementById("advSearchCnt").value;loop++)
	{
		document.getElementById("advSearch_text_"+loop).value="";
		if(document.getElementById("advSearch_DT_"+loop))
		{
			document.getElementById("advSearch_DT_"+loop).value="";
		}
	}
}

function callAdvSearch(module)
{

     
    if(document.getElementById("advancedSearch_showpickId"))
    {
         if(document.getElementById("advancedSearch_showpickId").style.display == "block" || document.getElementById("advancedSearch_showpickId").style.display == "table-row" )   
         {
         	document.getElementById("module").value=module
            callCancelAdvSearch()
            return false;
         }
    }


    if (browser_ie)
    {
        if(document.getElementById("advancedSearch_showpickId"))
        {
            if(document.getElementById("advancedSearch_showpickId").style.display == "none")        
                document.getElementById("advancedSearch_showpickId").style.display="block";
            else
                document.getElementById("advancedSearch_showpickId").style.display="none";        
        }
        if(document.getElementById("advancedSearch_showtextId"))
        {
            if(document.getElementById("advancedSearch_showtextId").style.display == "none")        
                document.getElementById("advancedSearch_showtextId").style.display="block";
            else
                document.getElementById("advancedSearch_showtextId").style.display="none";        
        }
        if(document.getElementById("advancedSearch_showbuttonId"))
        {
            if(document.getElementById("advancedSearch_showbuttonId").style.display == "none")        
                document.getElementById("advancedSearch_showbuttonId").style.display="block";
            else
                document.getElementById("advancedSearch_showbuttonId").style.display="none";        
        }
    }
    else
    {        
        if(document.getElementById("advancedSearch_showpickId"))
        {        
            if(document.getElementById("advancedSearch_showpickId").style.display == "none")             
                document.getElementById("advancedSearch_showpickId").style.display="table-row";
            else                
                document.getElementById("advancedSearch_showpickId").style.display = "none";       
        }
        if(document.getElementById("advancedSearch_showtextId"))
        {
            if(document.getElementById("advancedSearch_showtextId").style.display == "none")        
                document.getElementById("advancedSearch_showtextId").style.display="table-row";
            else
                document.getElementById("advancedSearch_showtextId").style.display="none";        
        }
        if(document.getElementById("advancedSearch_showbuttonId"))
        {
            if(document.getElementById("advancedSearch_showbuttonId").style.display =="none")        
                document.getElementById("advancedSearch_showbuttonId").style.display="table-row";
            else
                document.getElementById("advancedSearch_showbuttonId").style.display="none";        
        }
    }
    
    if(document.getElementById("advSearchCnt"))
    {
        for(var i=1;i<=document.getElementById("advSearchCnt").value;i++)
        {
            var selVal = document.getElementById("advSearch_select_"+i).value;
    	    if(selVal == "Is empty" || selVal == "Is not empty" || selVal=="true" || selVal=="false")
            {
                document.getElementById("advSearch_text_"+i).disabled =true;
                document.getElementById("advSearch_text_"+i).value="";
                if(document.getElementById("advSearch_DT_"+i))
                {
                    document.getElementById("advSearch_DT_"+i).value="";
                }
            }
        }
    }
   



}
function sendInvoiceMail(id,module)
{
openPopUp("SendMail",this,"/crm/jsp/IWSendMailForContacts.jsp?append_ids="+id+"&module="+module+"&skintype="+skintype,"SendMail",750,500,"menubar=no,toolbar=no,location=no,status=no,scrollbars=yes,resizable=yes");
}
function showRegisFilter()
{
	if( getObj("registFilterRelList").style.display == "none")
	{
		Effect.SlideDown("registFilterRelList");
		getObj('registerFilter').checked=true;
	}
	else
	{
		Effect.SlideUp("registFilterRelList");
		getObj('registerFilter').checked=false;
	}
}
function showLifeFilter()
{
	if( getObj("LifeFilterRelList").style.display == "none")
	{
		Effect.SlideDown("LifeFilterRelList");
		getObj('LifeCycleFilter').checked=true;
	}
	else
	{
		Effect.SlideUp("LifeFilterRelList");
		getObj('LifeCycleFilter').checked=false;
	}
}

function CVPrintAction(obj,url)
{
    var formData = formData2QueryString(document.showcvdetails);
    
    new Ajax.Request(url,{method:"post",onSuccess:function(t)
    {   
       var features="width=600,height=550,menubar=no,toolbar=no,location=no,status=no,scrollbars=yes,resizable=yes";
       var win=window.open("","preview",features);
       win.document.body.innerHTML=t.responseText;      
    },asynchronous:true,postBody:formData});

/* 
   if(document.getElementById("advSearchEnable")){
        var advSearchEnableVal = document.getElementById("advSearchEnable").value;
        url = url +"&advSearchEnable="+advSearchEnableVal;
    } 
openPopUp('printView',obj,url,'sheet',1000,700,'toolbar=no,statusbar=no,menubar=no,directories=no,resizable=yes,scrollable=yes,scrollbars=yes');
*/
}
function CVExportAction(url)
{
    document.showcvdetails.action=url;
    document.showcvdetails.submit();
}
function hideExperienceToDate()
{
    if(getObj("property(Current Employer)"))
    {
        if(getObj("property(Current Employer)").checked)
        {
            if(getObj("property(To Date)"))
            {
                getObj("property(To Date)").disabled =true;    
                getObj("calender_property(To Date)").style.display ="none" ;
                getObj("property(To Date)").value="";
            }
        }
        else
        {
            if(getObj("property(To Date)"))
            {
                getObj("property(To Date)").disabled =false;
                getObj("calender_property(To Date)").style.display ="block" ;
            }
        }
    }
}

function DFBMulPageSubmitForm(){
    if(DFBPrevNextValidation('submit')){
       var returnDFBSubmit = document.dfbForm.onsubmit();
       if(returnDFBSubmit == false){
       		alert('Mandatory Fields cannot be blank in any Pages');
       		return false;
       }
       else{
       		return true;
       }
    }else{
        return false;
    }
}
function DFBPrevNextValidation(option)
{
DFBsetInterestGroups();
var currentPage = parseInt(getObj("currentPage").value);

var pagevalidationFieldName = getObj("pageSecDivid_"+currentPage+"_pagevalidationFieldName").value;
var pagevalidationFieldLabel = getObj("pageSecDivid_"+currentPage+"_pagevalidationFieldLabel").value;
var pagevalidationDataType = getObj("pageSecDivid_"+currentPage+"_pagevalidationDataType").value;


    var newValidationFieldName ="";
    var newValidationFieldLabel ="";
    var newValidationDataType ="";
    var oldfieldname = pagevalidationFieldName.split(",");
    var oldfieldlabel = pagevalidationFieldLabel.split(",");
    var oldfielddatatype = pagevalidationDataType.split(",");
    
    var secIds = "";
    
    for (var i=0; i< oldfieldname.length; i++) 
    {    
         var field_module = oldfieldname[i].substr(0,oldfieldname[i].indexOf("_"));  
         var field_label = oldfieldlabel[i];
          //If the field label is 'Interests' change fieldlabel = 'Interests'
         var isInterestField  = oldfieldname[i].search("_Interests___");
         if(isInterestField != -1){
         	field_label='Interests';
         }
         var data_type = oldfielddatatype[i];
        if(newValidationFieldName == "")
        {
        	 
        	newValidationFieldName = field_module+"_"+field_label+"___1"; 
            newValidationFieldLabel =field_label;
            newValidationDataType =data_type;
        }
        else
        {
        	 
        	newValidationFieldName = newValidationFieldName +","+ field_module+"_"+field_label+"___1";
            newValidationFieldLabel =newValidationFieldLabel +","+field_label;
            newValidationDataType =newValidationDataType +","+data_type;
        }
         if(field_module != "Contacts" )
         {
            var totSecCount = 1;
            if(getObj("addResponseCount_"+field_module))
            totSecCount = parseInt(getObj("addResponseCount_"+field_module).value);
            if(totSecCount>1)
            {
                 for (var j=2; j<= totSecCount; j++) 
                {             
                	newValidationFieldName = newValidationFieldName +","+ field_module+"_"+field_label+"___"+j;
                    newValidationFieldLabel =newValidationFieldLabel +","+field_label;
                    newValidationDataType =newValidationDataType +","+data_type;             
                 }
            }
         }
     }
     fieldname = newValidationFieldName.split(",");
     fieldlabel = newValidationFieldLabel.split(",");
     fielddatatype = newValidationDataType.split(",");
     DFBAssigncomboval()
   if ( formValidate() )
    {   
        document.getElementById("doServerSidevalidation").value ="false";
        if(option =="submit"){
            return DFBnonContactsModuleVallidatiion();
        }else{        
            if(DFBMulPagenonContactsModuleVallidatiion(currentPage))
            {              
                DFBPrevNextForm(option);
                return true;
            }
            else
            {
                return false;
            }
        }
    }
    else
    {
        return false;
    }
    
    DFBPrevNextForm(option);
    return true;

}
// Dynamic Form Methods
function DFBSubmitForm()
{
    var newValidationFieldName ="";
    var newValidationFieldLabel ="";
    var newValidationDataType ="";
    var newValidationSectionId ="";
    var secIds = "";
    var oldsectionid;
    
    if(document.getElementById('validationSectionId') != null)
    {
    	secIds = document.getElementById('validationSectionId').value;
    	oldsectionid = secIds.split(",");
    }
    
    var oldfieldname = validationFieldName.split(",");
    var oldfieldlabel = validationFieldLabel.split(",");
    var oldfielddatatype = validationDataType.split(",");
    
    var flag = 0;
    for (var i=0; i< oldfieldname.length; i++) 
    {     
    	var section_id;
    	if(oldsectionid)
    	{
    		section_id = oldsectionid[i];
    	}
    	
         var field_module = oldfieldname[i].substr(0,oldfieldname[i].indexOf("_"));  
         var field_label = oldfieldlabel[i];
         var isInterestField  = oldfieldname[i].search("_Interests_");
         if(isInterestField != -1){
         	field_label='Interests';
         }
         var data_type = oldfielddatatype[i];
        
        if(newValidationFieldName == "")
        {
        	if(section_id)
        	{ 
        	newValidationFieldName = field_module+"_"+field_label+"_"+section_id+"___1";   
        	newValidationSectionId =section_id;
        	}else
        	{
        		newValidationFieldName = field_module+"_"+field_label+"___1"; 
        	}
        	newValidationFieldLabel =field_label;
            newValidationDataType =data_type;
             
        }
        else
        {
        	if(section_id)
        	{
        		newValidationFieldName = newValidationFieldName +","+ field_module+"_"+field_label+"_"+section_id+"___1";    
        		newValidationSectionId =newValidationSectionId +","+section_id;
        	}else
        	{
        		newValidationFieldName = newValidationFieldName +","+ field_module+"_"+field_label+"___1";
        	}
             newValidationFieldLabel =newValidationFieldLabel +","+field_label;
             newValidationDataType =newValidationDataType +","+data_type;
        }
         if(field_module != "Contacts" )
         {
            var totSecCount = 1;
            if(getObj("addResponseCount_"+field_module))
            totSecCount = parseInt(getObj("addResponseCount_"+field_module).value);
            if(totSecCount>1)
            {
                 for (var j=2; j<= totSecCount; j++) 
                {    
                	 if(section_id)
                 	{
                		 newValidationFieldName = newValidationFieldName +","+ field_module+"_"+field_label+"_"+section_id+"___"+j;         
                		 newValidationSectionId =newValidationSectionId +","+section_id;
                 	}else
                 	{
                 		newValidationFieldName = newValidationFieldName +","+ field_module+"_"+field_label+"___"+j;
                 	}
                    newValidationFieldLabel =newValidationFieldLabel +","+field_label;
                    newValidationDataType =newValidationDataType +","+data_type;
          
                 }
            }
         }
     }

     DFBAssigncomboval()

	fieldname = newValidationFieldName.split(",");
 	fieldlabel = newValidationFieldLabel.split(",");
 	fielddatatype = newValidationDataType.split(",");
 	sectionid = newValidationSectionId.split(",");
 	if ( formValidate() )
 	{   
    	document.getElementById("doServerSidevalidation").value ="false";
    	if( DFBnonContactsModuleVallidatiion() )
    	{
        	return true;
    	}
        else
	    {
    	    return false;
    	}
 	}
    else
	{
    	return false;
 	}

     return true;
}

function setGMultiSelectforForm()
{
	 
 		var selectedValues="";
		if(getObj("gmultiselect"))
		{
			var tempGroups = getObj("gmultiselect").value;
			if (tempGroups)
			{
				var totalGroups=tempGroups.split("@@@");
				for(var i=0;i<totalGroups.length-1;i++)
				{
					tempGroups=totalGroups[i].split("::");
					var totalGroup_index=tempGroups[0];
					var totalGroupName=tempGroups[1];
					var sectionType=tempGroups[2];
					var sectionId=tempGroups[3];
					var section=tempGroups[4];
					
		 			var group_object=getObj("property("+totalGroupName+"_temp)").value;
					var totalSubGroups=group_object.split("@@@");
		            for(var j=0;j<totalSubGroups.length-1;j++)
		            {
						tempGroups=totalSubGroups[j].split("::");
						var groupName=tempGroups[0];
						var chk_count=tempGroups[1];
						for(var k=1;k<=chk_count;k++)
						{
							var check_object=getObj("chk"+(i+1)+"_"+(j+1)+"_"+k)
							if(check_object.checked==true)
							{
								if (selectedValues == '')
									selectedValues = groupName + "--" + check_object.value;
								else
									if(selectedValues.indexOf(groupName+"--")>=0)
										selectedValues = selectedValues + "::" + check_object.value;
									else
										selectedValues = selectedValues + "##" + groupName + "--" + check_object.value;
		
		 					}
						}
					}
		            if(getObj(sectionType+"_"+totalGroupName+"_"+sectionId+"___"+section))
		            {
	            		getObj(sectionType+"_"+totalGroupName+"_"+sectionId+"___"+section).value=selectedValues;
	 	            }
		            else
		            {
	 	            	getObj(sectionType+"_"+totalGroupName+"___"+section).value=selectedValues;
		            }
	 	           	selectedValues='';
				}
			}
		}
		return true;
     
    
}

function DFBsetInterestGroups()
{
 var sectionCountTotal = 1;
    if(getObj("sectionCountTotal")){
        sectionCountTotal = getObj("sectionCountTotal").value;
    }
    
   
    for(var i=1;i<=sectionCountTotal;i++)
    {
    	if(getObj("sectionType_secId_"+i))
        {
    		var sectionId = getObj("sectionType_secId_"+i).value;
        }
    	
    	var sectionType = getObj("sectionType_"+i).value;
        var addResponseCount = 1 ;
                
        if(sectionType != 'Contacts'){
        	if(getObj("addResponseCount_"+sectionType))
		    	 addResponseCount = parseInt(getObj("addResponseCount_"+sectionType).value);
		 }
        
        for(var j=1;j<= addResponseCount;j++)
        { 
       if(getObj("sectionType_secId_"+i))
       {
        var totalGroups = 'totalGroups_'+sectionType+'_Interests_'+sectionId+'___'+j;
       }
       else
       {
    	   var totalGroups = 'totalGroups_'+sectionType+'_Interests___'+j;
       }
		if(getObj(totalGroups))
		{
			var totGroup = document.getElementById(totalGroups).value;
			var selectedValues ='';
			for(var k= 1; k <= totGroup; k++)
			{
				if(getObj("sectionType_secId_"+i))
			       {
						var groupId = "intGroup_"+sectionType+'_Interests_'+sectionId+'___'+j+'_'+k;
			       }else
			       {
			    	   var groupId = "intGroup_"+sectionType+'_Interests___'+j+'_'+k;
			       }
				var groupName = getObj(groupId).value;
				var groupSize = parseInt(groupName.substr(groupName.indexOf(":") + 1, groupName.length))
					groupName = groupName.substr(0,groupName.indexOf(":"));
				for(var m=1; m <= groupSize; m++)
				{
					if(getObj("sectionType_secId_"+i))
				       {
						var valuesId = "interest_"+k+m+"_"+sectionType+"_Interests_"+sectionId+"___"+j;
				       }else
				       {
				    	   var valuesId = "interest_"+k+m+"_"+sectionType+"_Interests___"+j;
				       }
					if(getObj(valuesId).checked)
						if (selectedValues == '')
							selectedValues = groupName + "--" + getObj(valuesId).value;
						else
							if(selectedValues.indexOf(groupName+"--")>=0)
								selectedValues = selectedValues + "::" + getObj(valuesId).value;
							else
								selectedValues = selectedValues + "##" + groupName + "--" + getObj(valuesId).value;
				}
			}
			if(getObj("sectionType_secId_"+i))
		       {
			getObj(sectionType+'_Interests'+'_'+sectionId+'___'+j).value = selectedValues;
		       }else
		       {
			getObj(sectionType+'_Interests___'+j).value = selectedValues;
		       }
		  }        
        }
	}
} 
function DFBcallFormCacel(url,gotop)
{
    if(url!=null && url!="" && url !="null")
    {
      if(url.indexOf("http://") < 0 && url.indexOf("https://") < 0)
        {
    	  	url = "http://" + url;
        }
      if (gotop)
      {
    	  top.location.href = url; 	
      }
      else
      {
    	  document.location.href = url;
      }
    }
    else
    {
    window.self.close();
    }
}
function ChangeDFBcomboIds()
{
    var sectionCountTotal = 1;
    if(getObj("sectionCountTotal")){
        sectionCountTotal = getObj("sectionCountTotal").value;
    }
    for(var i=1;i<=sectionCountTotal;i++)
    {
        var sectionType = getObj("sectionType_"+i).value;
        var addResponseCount = 1 ;
	   if(sectionType != "Contacts" && getObj("addResponseCount_"+sectionType))
    	    addResponseCount = parseInt(getObj("addResponseCount_"+sectionType).value);
    	    
        for(var k=1;k<= addResponseCount;k++)
        {
            if(document.getElementById(sectionType+"_comboFields___"+k))
            {
                document.getElementById(sectionType+"_comboFields___"+k).name=sectionType+"_comboFields_"+i+"___"+k;
                document.getElementById(sectionType+"_comboFields___"+k).id=sectionType+"_comboFields_"+i+"___"+k;
            }
        }
    }
}
function DFBAssigncomboval()
{
    var sectionCountTotal = 1;
    if(getObj("sectionCountTotal")){
        sectionCountTotal = getObj("sectionCountTotal").value;
    }
    for(var i=1;i<=sectionCountTotal;i++)
    {
        var sectionType = getObj("sectionType_"+i).value;
        var addResponseCount = 1 ;
        
		if(sectionType != "Contacts" && getObj("addResponseCount_"+sectionType))
			addResponseCount = parseInt(getObj("addResponseCount_"+sectionType).value);
	    
        for(var k=1;k<= addResponseCount;k++)
        {
            if(document.getElementById(sectionType+"_comboFields_"+i+"___"+k))
            {
		            var comboFields =  document.getElementById(sectionType+"_comboFields_"+i+"___"+k).value;
			}
            if(comboFields!=null && comboFields!="" && comboFields!="null" && comboFields!=undefined)
            {
                var comboFieldsArr = comboFields.split(":##:")
                for(var m=0;m< comboFieldsArr.length;m++)
                {   
                    var fieldname =comboFieldsArr[m]

                    if(getObj("comboValue_"+fieldname))
                    {
                        DFBSetComboValues(fieldname);
                    }                    
                }
            }
            
        }
    }
}
function DFBSetComboValues(fieldname)
{
    var j = 0;
    var combo ="";
    //alert("FieldName is "+getObj("comboValue_"+fieldname).value)
    if(getObj("comboValue_"+fieldname))
    {    
        for(var i=0;i< getObj(fieldname).length;i++)
        {            
            if(getObj(fieldname).options[i].selected==true)
            {         
                if(j==0)
                {	
                    combo  = getObj(fieldname).options[i].value;                                   
                }
                else
                {
                    combo  = combo + ";"+ getObj(fieldname).options[i].value;                                    
                }                
                j++;
            }            				
        }
        getObj("comboValue_"+fieldname).value = combo ;
    }
    //alert("final is "+getObj("comboValue_"+fieldname).value)
}


function DFBnonContactsModuleVallidatiion()
{
    var sectionCountTotal = getObj("sectionCountTotal").value;
    for(var i=1;i<=sectionCountTotal;i++)
    {
        var sectionType = getObj("sectionType_"+i).value;
        if(sectionType!= "Contacts" )
        {           
            var addResponseCount = 1 ;
            if(getObj("addResponseCount_"+sectionType))
            addResponseCount = parseInt(getObj("addResponseCount_"+sectionType).value);
            for(var k=1;k<= addResponseCount;k++)
            {
                var manFields =  getObj(sectionType+"_mandFields___"+k).value;
                var nonMandFields =  getObj(sectionType+"_nonMandFields___"+k).value;
                if(nonMandFields!=null && nonMandFields!="" && nonMandFields!="null" && nonMandFields!=undefined)
                {
                
                    var nonMandFieldsArr = nonMandFields.split(":##:")
                    for(var j=0;j< nonMandFieldsArr.length;j++)
                    {   
                        if(getObj(nonMandFieldsArr[j])){
                        var currObj=getObj(nonMandFieldsArr[j])
                        if( !(currObj.value == "none" || currObj.value =="-None-" || currObj.value.replace(/^\s+/g, '').length==0) ) 
                        {
                            if(getObj(manFields))
                             {
                           if((getObj(manFields).value.replace(/^\s+/g, '').length==0) ) 
                           {
                                var fieldLabel = manFields.substring(manFields.indexOf("_")+1,manFields.lastIndexOf("___")+0);
                                var subFieldLabel = fieldLabel.substring(0,fieldLabel.indexOf("_"));
                                alert(subFieldLabel+' cannot be blank');
                                getObj(manFields).focus();
                                return false;                 
                           }}
                        }}
                    }
                }//end of nonMandFields if loop
            }//end of addResponseCount for loop
        }//end of sectiontype if loop
    }//end of sectiontotalcount for loop
return true;
}
function DFBEnableSubmitButtons()
{
    if(getObj("submitButtonId"))
    getObj("submitButtonId").disabled = false;
    if(getObj("saveandprevButtonId"))
    getObj("saveandprevButtonId").disabled = false;
    if(getObj("saveandnextButtonId"))
    getObj("saveandnextButtonId").disabled = false;
    
}
function DFBCallingAddSections(secId,secType,seccanDuplicate)
{
var newCount = parseInt(getObj('addResponseCount_'+secType).value)+1 ;
var lastSecCount = parseInt(getObj('addResponseCount_'+secType).value);
if(newCount>=10)
{
return;
}
getObj('addResponseCount_'+secType).value  = newCount;
var secDivObj = document.getElementById(secId+"_"+secType+"___1");
var newdivObj=document.createElement("DIV");
newdivObj.id = secId+"_"+secType+"___"+newCount;
newdivObj.innerHTML=secDivObj.innerHTML;
var temp = newdivObj.innerHTML.replace(/___1/g,'___'+newCount);
newdivObj.innerHTML=temp;

var lastsecDivObj = document.getElementById(secId+"_"+secType+"___"+lastSecCount);

lastsecDivObj.parentNode.insertBefore(newdivObj,lastsecDivObj.nextSibling);
var brObj = document.createElement("BR");
var trObj=document.createElement("TR");
trObj.id = "removeResponse___"+newCount;
trObj.align = "right";
var tdObj1 = document.createElement("TD");
var myLink = document.createElement("A");
var arglist = secId+"_"+secType+"___"+newCount;
myLink.setAttribute('href', 'javascript:DFBRemoveResponse('+secId+',"'+secType+'","___'+newCount+'"  )');
myLink.setAttribute('title', 'Remove this section'); 
myLink.setAttribute("style", 'font-family:Arial, Helvetica, sans-serif;font-size:11px;font-weight: normal;color:#000; text-decoration: underline;'); 
myLink.appendChild(document.createTextNode('Remove Response')); 
tdObj1.appendChild(myLink);
trObj.appendChild(tdObj1);
(getObj("addResponseId___"+newCount)).parentNode.appendChild(trObj);            
(getObj("addResponseId___"+newCount)).parentNode.removeChild(getObj("addResponseId___"+newCount));
    var manFields =  getObj(secType+"_mandFields___"+newCount).value;
    var nonMandFields =  getObj(secType+"_nonMandFields___"+newCount).value;
        if(nonMandFields!=null && nonMandFields!="" && nonMandFields!="null" && nonMandFields!=undefined)
        {
            var nonMandFieldsArr = nonMandFields.split(":##:")
            for(var j=0;j< nonMandFieldsArr.length;j++)
            {   
                 if(getObj(nonMandFieldsArr[j])){
                var currObj=getObj(nonMandFieldsArr[j])
                currObj.value="";}
            }   
        }
        if(manFields!=null && manFields!="" && manFields!="null" && manFields!=undefined)
        {
            var manFieldsArr = manFields.split(":##:")
            for(var k=0;k< manFieldsArr.length;k++)
            {   
                 if(getObj(manFieldsArr[k])){
                var currObjk=getObj(manFieldsArr[k])
                currObjk.value="";}
            }   
        }
}
function DFBRemoveResponse(secid,type,count)
{
    count  = parseInt(count.substring(count.indexOf("___")+3))
    var arglist = secid+"_"+type+"___"+count;
    var secDivObj = document.getElementById(arglist);
    secDivObj.parentNode.removeChild(secDivObj);
    var newCount = parseInt(getObj('addResponseCount_'+type).value) ;
    for(var k=count+1;k<=newCount;k++)
    {
        var divid = secid+"_"+type+"___"+k;
        var replacevar = "___"+k;
        var temp = getObj(divid).innerHTML.replace(/___[0-9]*/g,'___'+(k-1));
        getObj(divid).innerHTML=temp;
        getObj(divid).id = secid+"_"+type+"___"+(k-1);
    }
    getObj('addResponseCount_'+type).value  = newCount-1;
}
function setDependentOnEdit(obj,load )
{
	var isDependent = false;
	var name = obj.name;
	var val = "";
	/*
	if(name == "property(Lifecycle Stage)")
	{            
		getObj("property(Source Group)").selectedIndex = 0;
		setDependent(getObj("property(Source Group)") ) ;
	}
	*/
	if(getObj("field"+name)!=null)
	{
		val=getObj("field"+name).value;
	}
	if(val != null && val != "" && val != "null")
	{
		var fields = val.split("&&&");
		for(var i=0;i<fields.length;i++)
		{	
			var isDependent = false;
			var arr = fields[i].split("|||");
			var label = arr[0];
			var values = arr[1].split(":::");
			if(label.indexOf(")")> -1)
			{
				label = label.replace(/\)/g,"_____");
			}
			if(label.indexOf("(") > -1)
			{
				label = label.replace(/\(/g,"____");
			}
			if(label.indexOf(".")> -1)
			{
				label = label.replace(/\./g,"___");
			}
			var depObj = getObj("property("+label+")");
			if(depObj)
			{
				if(getObj(label))
				{
					var count = getObj(label).value;
					depObj = getObj("comboValue"+count);
				}
				var mapValues = "";
				for (var n=depObj.options.length-1; n >= 0;n--) {	
					if (depObj.options[n].selected)
					{	
						if(mapValues == "")
						{
							mapValues = depObj.options[n].value;
						}
						else
						{
							mapValues = mapValues + ";;;"+depObj.options[n].value;
						}
					} 
				}
				depObj.value = "";
				var selectValues = getObj("selectValue"+label).value;
				for(var k=0;k<values.length;k++)
				{
					var list = values[k].split("===");
					var rat = list[0];
					/*
					if(rat == "-None-")
					{
						rat = "";
					}
					*/
					if(rat == obj.value)
					{
						isDependent = true;
						depObj.length = 0;
						var depvalues = list[1].split(";;;");
						for(var j=depvalues.length-1;j>=0;j--)
						{
							var optionElement = document.createElement("OPTION");
							if(depvalues[j]=='-None-')
                                                            depvalues[j]="";	
							optionElement.value = depvalues[j];
							optionElement.text = depvalues[j];
							if(mapValues != undefined)
							{
								var mapValue = mapValues.split(";;;");
								for(var p=0;p<mapValue.length;p++)
								{
									if(depvalues[j] == mapValue[p])
									{
										optionElement.selected = true;
									}	
								}
							}	
							depObj.options.add(optionElement);
						}	
					}
				}
				if(!isDependent)
				{
					var getValues = selectValues.split(";");
					depObj.length = 0;
					for(var j=0;j<getValues.length;j++)
					{
						var optionElement = document.createElement("OPTION");
						if(getValues[j]=='-None-')
                                                    getValues[j]="";						
                                                optionElement.value = getValues[j];						
						optionElement.text = getValues[j];
						depObj.options.add(optionElement);
					}
				
				}
			}
		}
	}
	if(module=='Campaigns' && getObj('property(Channel)')!=null && getObj('property(Channel)').value =='Email' && load==true)
	{
		getObj("property(Status)").value="Planned";
		getObj("property(Status)").disabled=true;
		getObj("property(Type)").disabled=true;
		getObj("property(Channel)").disabled=true;
	}
	else if(module=='Campaigns' && getObj('property(Channel)')!=null && getObj('property(Channel)').value =='Email')
	{
		getObj("property(Status)").value="Planned";
		getObj("property(Status)").disabled=true;
	}
	else if(module=='Campaigns' && getObj('property(Channel)')!=null && getObj('property(Channel)').value !='Email')
	{
		getObj("property(Status)").disabled=false;
	}
	else if(module=='Campaigns' && getObj('property(Status)')!=null && getObj('property(Status)').value =='Completed')	
	{
		getObj("property(Channel)").disabled=true;
		getObj("property(Type)").disabled=true;
	}
	else if(module=='Campaigns')
	{
		getObj("property(Channel)").disabled=false;
		getObj("property(Type)").disabled=false;
	}	
}

function saveTrack(module,type,todisplay)
{

	if (!emptyCheck("property(Plan Name)","Plan Name"))
        return false
	formData = formData2QueryString(document.createEntityForm);
	var url="/crm/CreateCommonModule.do?module="+module+"&ActionType="+type;
	if( type=="Edit")
	{
	url="/crm/EditCommonModule.do?module="+module+"&ActionType="+type+"&todisplay="+todisplay;
	}
	if( type=="Clone")
	{
	url="/crm/CloneCommonModule.do?module="+module+"&ActionType="+type;
	}
	loadAjaxTab4("Loading...");
	new Ajax.Request(url,{method:"post",onSuccess:function(t)
       	{
		getObj("show").innerHTML = t.responseText;
		 document.getElementById('ajax_load_tab').style.display='none';
       },asynchronous:true,postBody:formData,evalScripts:true
       });

}
function showConditionTab(tabName,type,trackId)
{
				if(tabName=="TemplateSec")
				{
				document.getElementById('trackProfile').style.display="none";
				document.getElementById('trackProfileTab').className="crdvtUnSelectedCell";
				document.getElementById('trackCriteria').style.display="none";
				document.getElementById('trackCriteriaTab').className="crdvtUnSelectedCell";
				document.getElementById('trackCondition').style.display="block";
				document.getElementById('trackConditionTab').className="dvtSelectedCell";
				}
				else if(tabName=="ProfileSec")
				{
				document.getElementById('trackProfile').style.display="block";
				document.getElementById('trackProfileTab').className="dvtSelectedCell";
				document.getElementById('trackCriteria').style.display="none";
				document.getElementById('trackCriteriaTab').className="crdvtUnSelectedCell";
				document.getElementById('trackCondition').style.display="none";
				document.getElementById('trackConditionTab').className="crdvtUnSelectedCell";


				}
				else if(tabName=="CriteriaSec")
				{
				if(getObj('valueChanged').value == 'true' && !window.confirm("Do you want to proceed without saving the changes"))
				{
				}
				else
				{

				document.getElementById('trackProfile').style.display="none";
				document.getElementById('trackProfileTab').className="crdvtUnSelectedCell";
				document.getElementById('trackCriteria').style.display="block";
				document.getElementById('trackCriteriaTab').className="dvtSelectedCell";
				document.getElementById('trackCondition').style.display="none";
				document.getElementById('trackConditionTab').className="crdvtUnSelectedCell";
				}
				}
}
//check for allowing only integer values in the days field
function integerValidation(value) 
{
if (value!= null || value.equals("null") && value.replace(/^\s+/g, '').replace(/\s+$/g, '').length!=0)
   {
   		var val=value.replace(/^\s+/g, '').replace(/\s+$/g, '')        
   		var re=/^\d+(,(\d)+)*(\.\d{1,2})*$/	        
        if (isNaN(val)) 
        {          
   	    	return false
        }
        else if(val.indexOf(".")!=-1 || !re.test(val)) 
        {           
      		return false
        }  
        else
        {
        	return true
        }          
   } 
   else 
   {
   		return true
   }
}
function saveTemplate(actionType,module,id,action)
{
 
	var rowno=document.getElementById("templaterow").value;
	var tabGroup=document.getElementById("tabGroup").value
	for(var i=1;i<=rowno;i++)
	{
		var noofdays = document.getElementById("days_"+i).value;
		if(noofdays==null || noofdays=="" || noofdays.trim().length==0)
		{
			alert("Days cannot be blank");
			document.getElementById("days_"+i).focus();
			return false;
		}
		// checking whether the day field accepting a day in exponential form or not
		if (!integerValidation(noofdays))
		{
			alert("Please Enter a valid day");
			document.getElementById("days_"+i).focus();
			return false;
		}
		var email_template = document.getElementById("emailTemplate_"+i).value;
		if(email_template==null || email_template=="")
		{
			alert("Email Template cannot be blank");
			document.getElementById("emailTemplate_"+i).focus;
			return false;
		}
	}
	for(var i=1;i<=rowno;i++)
	{
		var dateObj="days_"+i;
		var value =parseInt(document.getElementById(dateObj).value,10);
		for(var j=i+1;j<=rowno;j++)
		{
			var newDataObj=parseInt(document.getElementById("days_"+j).value,10);
			if(value==newDataObj)
			{
				alert("Day "+ value+" already entered");
				document.getElementById("days_"+j).focus();
				return false;
			}
		}
	}
	document.createEntityForm.action="/crm/SaveTrack.do?tabGroup="+tabGroup+"&module=CommunicationPlans&id="+id+"&isload=true";
	document.createEntityForm.method="post";
	document.createEntityForm.submit();
}

function createRule(trackid)
{
	var url ="/crm/jsp/NewRule.jsp?trackid="+trackid+"&module=CommunicationPlans&skintype="+skintype;
	new Ajax.Request(url,{method:"post",onSuccess:function(t)
    {      
        showDialog(t.responseText,"modal=yes, closeOnEscKey=no,position=absolute,top=200,left=50,width=900");
    },asynchronous:true,evalScripts:true});
}

// added here for Contact Org Relations
function CancelContactOrgRelation()
{
        var fldName = getObj("fldName").value ;        
        var fldNameObj=getOpenerObj(fldName)
        var fldId = getObj("fldId").value ; 
        var fldIdObj=getOpenerObj(fldId)
        fldNameObj.value="";
        fldIdObj.value="";
        window.self.close();
}
function CreateContactOrgRelation()
{
    var comboCount =  getObj("comboCount").value;
        comboCount = comboCount-1;
	if(comboCount > 0)
	{	
		for(var k=1;k<=comboCount;k++)
		{	
			var j = 0;
			for(var i=0;i< getObj("comboValue"+k).length;i++)
			{
				if(getObj("comboValue"+k).options[i].selected==true)
				{
					if(j==0)
					{	
						getObj("combo"+k).value  = getObj("comboValue"+k).options[i].value;
					}
					else
					{
						getObj("combo"+k).value  = getObj("combo"+k).value + ";"+ getObj("comboValue"+k).options[i].value;
					}
					j++;
				}						
			}
		}
	}
    if(pageValidate()) 
    {
        var fldName = getObj("fldName").value ;        
        var fldNameObj=getOpenerObj(fldName)
        var tdVal = "";
        var hiddenLabelval = getObj("hiddenLabelid").value;
        var hiddenLabelArr = hiddenLabelval.split(":##:");
        for(var i=0;i<hiddenLabelArr.length;i++)
        {
            var hdnFieldLabel = hiddenLabelArr[i];

            if(getObj(hdnFieldLabel))
            var hdnFieldLabelVal = getObj(hdnFieldLabel).value;
            else if(getObj("property("+hdnFieldLabel+")"))
             hdnFieldLabelVal = getObj("property("+hdnFieldLabel+")").value;

            var mergeVal = hdnFieldLabel+":##:"+hdnFieldLabelVal;
            if(tdVal == ""){tdVal = mergeVal;}
            else{
            tdVal = tdVal+":&::&:"+mergeVal;}
        }
        var Contact_Org_Relid = "Contact_School_Relid";
        if(fldName == "Current Employer"|| fldName == "textbox_Current Employer")
        {
            Contact_Org_Relid = "Contact_Employer_Relid";
        }
        if(getOpenerObj("property("+Contact_Org_Relid+")"))
        {
            getOpenerObj("property("+Contact_Org_Relid+")").value = tdVal;
        }
/*
        else
        {
            var hiddenbox = document.createElement('input');
            hiddenbox.type = 'hidden';
            hiddenbox.name = 'property('+Contact_Org_Relid+')';
            hiddenbox.id = 'property('+Contact_Org_Relid+')';
            hiddenbox.value = tdVal;

            var cell  = document.createElement('td');
            cell.appendChild(hiddenbox);
            fldNameObj.parentNode.appendChild(cell);
        }
*/
        var fldName1 = getObj("fldName").value ;        
        var fldNameObj1=getOpenerObj(fldName1)
        var fldId1 = getObj("fldId").value ; 
        var fldIdObj1=getOpenerObj(fldId1);
        fldNameObj1.value=getObj("fldLabelValue").value ;
        fldIdObj1.value=getObj("fldIdValue").value ; 
        window.self.close()
    }
    else
    {
        return false;
    }    
}
//added for form sections drag
function dragFormSections()
{
    //var pagecountvalue  =getObj("pagecountvalue").value;   
    var pagecountvalue = document.getElementById("noofpages").value;
    for(var p=1;p<=pagecountvalue;p++)
    {

        Sortable.create("pageDiv__"+p , {tag:'div',constraint:false, onUpdate:function(element)
        {
            var sectionSequence = Sortable.sequence(element);
            document.getElementById("dragSectionSequence__"+p).value = sectionSequence;
            var sseq = document.getElementById("dragSectionSequence__"+p).value;
            var sq = sseq.split(",");
            for(var i=0;i< sq.length;i++)
            {            
                document.getElementById("sectionindex_"+p+"_"+sq[i]).value=(i+1);
            }
        }});
    }
 
}
function attendeesFilter(id)
{
 var filterval= getObj('filter_combo').value;
if(filterval=="-None-")
{
return false;
}
if (!isWorking && http)
        {
                var url ="/crm/RefreshRelatedList.do?module=Events&id="+id+"&filterOption=true&filterValue="+filterval;
	 	http.open("GET", url, true);
	        http.onreadystatechange = function()
                {
                        if(http.readyState == 4)
                        {
                                var str = http.responseText;
                                divObj = getObj('relatedList');
                                divObj.innerHTML="";
                                divObj.innerHTML=str;
                                expandRelatedList('Events');
                                isWorking = false;
                                var options = getObj('filter_combo').options;
                                if(filterval=='All')
                                {
                                }
                                else
                                {
                                	for (var i = 0; i < options.length; i++) 
                                	{
                                		if (options[i].value== filterval)
                            			{		
                            				options[i].selected=true;
                            				break;
                            			}
                                	}
                                }
                                toggleRelatedList('ATTENDEESPERSONALITY','Events');
                        }
                }
                http.send(null);
        }

}
function changeStatus(id)
{
var append_ids="";
if(document.viewentityform.atten_ck ==null)
{
	getObj('status_combo').value='-None-';
	return false;
}
var noofrows = document.viewentityform.atten_ck.length;
	if (noofrows == undefined )
	{
		if (document.viewentityform.atten_ck !=null && document.viewentityform.atten_ck.checked)	
		{
			append_ids = document.viewentityform.atten_ck.value;
		}
	else
	{
		alert('Select atleast one record')
		getObj('status_combo').value='-None-';
		return false;
	}
}
else if (noofrows != 0)
	{
		if (getNoOfChecked("Attendees") == 0)
		{
			alert('Select atleast one record')
                            getObj('status_combo').value='-None-';
			return false;	
		}	
		else 
		{	
			for(i = 0 ; i < noofrows ; i++)
			{
				if (document.viewentityform.atten_ck[i].checked)
					append_ids= document.viewentityform.atten_ck[i].value+";"+append_ids;
			}
		}              
		}
var res = window.confirm('Are you sure ?');
     if(res == false)
	{
		return false;
	}
    var comboval= getObj('status_combo').value;
   
    if(comboval =='-None-')
    {
        return false;
    }
if (!isWorking && http)
        {
                var url ="/crm/RefreshRelatedList.do?module=Events&id="+id+"&idlist="+append_ids+"&regstatus="+ comboval;
	 	http.open("GET", url, true);
	        http.onreadystatechange = function()
                {
                        if(http.readyState == 4)
                        {
                                var str = http.responseText;
                                divObj = getObj('relatedList');
                                divObj.innerHTML="";
                                divObj.innerHTML=str;
                                expandRelatedList('Events');
                                isWorking = false;
                        }
                }
                http.send(null);
        }

}
function getNoOfChecked(module)
{
        var checkboxes="";
	if(module=="Targets")
       checkboxes=getObj('deletetar_ck');
	else if(module=="Exclusions")
	checkboxes=getObj('deleteex_ck');
	else if(module=="Attendees")
	checkboxes=getObj('atten_ck');
	var noofrows=checkboxes.length; 
        noofselected = 0
        for(i=0 ; i < noofrows ; i++)
        {
                if (checkboxes[i].checked)
		{
                        noofselected ++;
		}
        }
        return noofselected;
}
function saveCriteria(trackid,action)
{
	var rulename = (getObj("property(Rule Name)").value).trim();
	
	if (rulename=='')
	{
		selectone.getJSAlertValue("crm.alert.not.blank","Rule Name","en_US",function(mesg) { alert(mesg) })  
				getObj("property(Rule Name)").focus();
                return false
	}
	var rowno=getObj("row").value;
	var pattern=getObj("dateFmt").value

	for(var i=1;i<=rowno;i++)
	{
		var objSearchfield=getObj("searchfieldtype_"+i);
		var sSearchFieldLabel = getObj("searchfieldtype_"+i);
		var sFieldLabel ;
		if(Search.browser_ie)
		{
			sFieldLabel = document.getElementById("searchfield_"+i).value;
		}
		else
		{
			sFieldLabel = getObj("searchfield_"+i).value;
		}
	
		sFieldLabel = sFieldLabel.substring(sFieldLabel.lastIndexOf(":")+1,sFieldLabel.length);
		var sCondition = "";
		if(objSearchfield.value=="D")
		{
			sCondition=getObj("datecondition_"+i).value;
			
			if(sCondition !="is empty" && sCondition !="is not empty") 
			{
				if(!dateValidate("datefld_"+i,"Date.Date Format is "+pattern,"OTH"))
					return false;
			}
		}
		else if(objSearchfield.value=="DT")
		{
			sCondition=getObj("datetimecondition_"+i).value;
			if(sCondition !="is empty" && sCondition !="is not empty") 
			{
				var len=getObj("timeval_"+i).value.trim().length
				if(len>0)
				{
					if(!dateValidate("datetime_"+i,"Date.Date Format is "+pattern,"OTH"))
						return false;
					else if(!timeValidate("timeval_"+i,"hh:mm 24 hours format","OTH"))
						return false
				}
				else
				{
					if(!dateValidate("datetime_"+i,"Date.Date Format is "+pattern,"OTH"))
						return false;
				}
			}
		}
		else if(objSearchfield.value=="N")
		{
			sCondition=getObj("numcondition_"+i).value;
			if(sCondition !="is empty" && sCondition !="is not empty") 
			{
				var sVal = getObj("numfld_"+i).value.trim();
 				var len = sVal.length;
 				if(len>0)
				{
					var re=/^\-|\d+(,(\d)+)*(\.\d{1,2})*$/
					
					if (isNaN(sVal) || !re.test(sVal) || sVal.indexOf("+") != -1) 
					{
						getObj("numfld_"+i).focus();
						selectone.getJSAlertValue("crm.alert.entry.valid",null,"en_US",function(mesg) { alert(mesg + " " + fldLabel) })
					       	return false;
					}
				}
				else
				{
					getObj("numfld_"+i).focus();
					selectone.getJSAlertValue("crm.alert.not.blank",sFieldLabel,"en_US",function(mesg) { alert(mesg) })              
			                return false
				}
			}
		
		}
		else if(objSearchfield.value=="T")
		{
			sCondition=getObj("textcondition_"+i).value;
			if(sCondition !="is empty" && sCondition !="is not empty") 
			{
				var sVal = getObj("value_"+i).value.trim();
				var len = sVal.length;
				if(len>0)
				{
					var test = splCharCheck2(sVal)
					if (! test )
					{
						selectone.getJSAlertValue("crm.alert.label.special.characters",null,"en_US",function(mesg){ alert(mesg) })        
						getObj("value_"+i).focus();
						return false;
					}
				}
				else
				{
					getObj("value_"+i).focus();
					selectone.getJSAlertValue("crm.alert.not.blank",sFieldLabel,"en_US",function(mesg) { alert(mesg) })              
			                return false
				}
			}
		
		}

	}


	if(!validateOpenBracket())
	{
	alert("open Braces only allowed in left side ");
return false;
	}
	if(!validateCloseBracket())
	{
	alert("Closed Braces only allowed in right side ");
return false;
	}

	if(!validateParanthesis())
	{
	alert("Parenthetical logic not matched properly");
	return false;
	}

	var query=constructQuery();
	document.getElementById("finalQuery").value=query;
	var formData = formData2QueryString(document.criteriaForm);
var url="/crm/SaveTrackRule.do?trackid="+trackid+"&action="+action;
	if (!isWorking && httphandle)
	{
	httphandle.open("POST", url, true);
	httphandle.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;charset=UTF-8');
		httphandle.onreadystatechange = function() 
		{
			if(httphandle.readyState == 4) 
			{
				var str = httphandle.responseText;
				getObj('trackCriteria').innerHTML=str;
				
				closeDialog()
				if(checkwetherTimedOut(str))
				{	                            
					return;
				}

				
			}
		}




httphandle.send(formData);
}

}

function ruleAction(obj,ruleid,trackid)
{
	var action=obj.value;
	var url="/crm/EditRule.do?action="+action+"&module=CommunicationPlans&id="+ruleid+"&trackid="+trackid+"&skintype="+skintype;
	if(action=='Edit')
	{
	new Ajax.Request(url,{method:"post",onSuccess:function(t)
    	{        
        showDialog(t.responseText,"modal=yes, closeOnEscKey=no,position=absolute,top=200,left=50,width=900");
    	},asynchronous:true,evalScripts:true});


	}
	else if(action=="Delete")
	{
	if(window.confirm('Are you sure ?'))
	{

	if (!isWorking && httphandle)
	{
		httphandle.open("GET", url, true);
		httphandle.onreadystatechange = function() 
		{
			if(httphandle.readyState == 4) 
			{
				var str = httphandle.responseText;
				
				getObj('trackCriteria').innerHTML=str;
				if(checkwetherTimedOut(str))
				{	                            
					return;
				}

				
			}
		}




		httphandle.send(null);
		}
	}


	}	
	obj.value ="Action";


}

function DFBloadDefaultPageContent()
{
    var olddivobj = document.getElementById("defaultContentId");
    var divobj = document.getElementById("pageContentDivId_1");

    var oldContent = olddivobj.innerHTML;
    divobj.innerHTML= oldContent;
}
function DFBshowFormPages(id)
{
    var totPage = parseInt(getObj("noofpages").value);    
    if(totPage>1)
    {
        for (var j=1; j<= totPage; j++) 
        {     
        
            document.getElementById("pg_"+j).className="FormTabUnSel";
            
            if(j == id)
            {
                getObj("pageContentDivId_"+j).style.display="block";
            }
            else
            {
                getObj("pageContentDivId_"+j).style.display="none";
            }
        }
    }
    getObj("pg_"+id).className="FormTabSel";
}

function DFBrenamePage(pageNum)
{
	var link = $('pgLink_' + pageNum);
	var name = prompt("Please enter the new page name", link.innerHTML);
	if (name && name != "")
	{
		link.innerHTML = name;
	    $("pageName__" + pageNum).value = name;
	}
}

function _DFBpageHTML(pgNum, pageName)
{
	return "<table border='0' cellpadding='0' cellspacing='0'>" +
	"<tr>" +
	"<td align='left' title='Page "+pgNum+"' width='200px'>" +
	  "<a id='pgLink_"+pgNum+"' onclick='DFBshowFormPages("+pgNum+")' class='FormLinkSmall' style='cursor: pointer;'>"+pageName+"</a>" +
	"</td>" + 
//	"<td align='right' width='1px'>" +
//	  "<img src='images/editLink.gif' border='0' align='absmiddle' alt='Edit' title='Edit' style='cursor: pointer;' onclick='DFBrenamePage("+pgNum+");'>" +
//	"</td>" +
	"<td align='right' width='20px'>" +
	  "<img src='/crm/images/del.gif' border='0' align='absmiddle' alt='Delete' title='Delete' style='cursor: pointer;' onClick='DFBdeletePage("+pgNum+");'></td>" +
	"</tr>" +
	"</table>";
}

function DFBaddFormPages()
{
    var totPage = parseInt(getObj("noofpages").value);
    totPage++
    var pageName = "Page "+totPage;
    var newdivObj=document.createElement("DIV");
    newdivObj.id = "pg_"+totPage;    
    newdivObj.className="FormTabSel";    
    newdivObj.setAttribute("style", "height:25px");    
    newdivObj.innerHTML = _DFBpageHTML(totPage, pageName);
    getObj("pagemenu").appendChild(newdivObj);

    var newContentdivObj=document.createElement("DIV");
    newContentdivObj.id = "pageContentDivId_"+totPage;
    newContentdivObj.style.padding="5px";
    var defaultContentobj = document.getElementById("defaultContentId");
    var defaultContent = defaultContentobj.innerHTML;
    defaultContent = replaceAll(defaultContent,'__1', '__'+totPage);
    newContentdivObj.innerHTML= defaultContent;
    getObj("pageContentMenu").appendChild(newContentdivObj);
    
    getObj("pageName__" + totPage).value = pageName;

    getObj("noofpages").value = totPage;
    document.getElementById("pageid__"+totPage).value=totPage;    
    DFBshowFormPages(totPage);
}
function DFBdeletePage(pageno)
{
    
    var totalpage=getObj("noofpages").value;
    if(totalpage==1)
    {
        alert("The Form must contain one page");
        return false;
    }

    var res = window.confirm('Are you sure ?');
    if(res == false){
        return;
    }
    
    var pno=parseInt(pageno);
    DFBshowFormPages(pno);
    
    var pgobj = document.getElementById("pg_"+pageno);
    var pageDivobj = document.getElementById("pagemenu");
    pageDivobj.removeChild(pgobj);
    
    var pgContent=document.getElementById("pageContentDivId_"+pageno);
    var pgContentDiv=document.getElementById("pageContentMenu");
    pgContentDiv.removeChild(pgContent);

    for(var i=(pno+1);i<=totalpage;i++)
    {
        var changeObj=document.getElementById("pg_"+i);
        var j=i-1;
        var pageName = "Page "+j;
        changeObj.innerHTML = _DFBpageHTML(i-1, pageName);
        getObj("pageid__"+i).value=(getObj("pageid__"+i).value)-1
        var temp = getObj("pageContentDivId_"+i).innerHTML.replace(/_[0-9]+_/g,'_'+(i-1)+'_');
        getObj("pageContentDivId_"+i).innerHTML=temp;
        getObj("pageName__"+i).value=pageName;
        temp=getObj("pageContentDivId_"+i).innerHTML.replace(/__[0-9]+/g,'__'+(i-1));
        getObj("pageContentDivId_"+i).innerHTML=temp;
        getObj("pg_"+i).id="pg_"+(i-1);
        getObj("pageContentDivId_"+i).id="pageContentDivId_"+(i-1);        
    }

    getObj("noofpages").value=(getObj("noofpages").value)-1
    
    if(getObj("pg_"+pno))
    {
        document.getElementById("pg_"+pno).className="FormTabSel";
        getObj("pageContentDivId_"+pno).style.display="block";
    }
    else
    {
        document.getElementById("pg_"+(pno-1)).className="FormTabSel";
        getObj("pageContentDivId_"+(pno-1)).style.display="block";
    }

}

function DFBcreateSection(theButton,pageId,sId,mode) 
{
var pageIdValue = parseInt(document.getElementById(pageId).value);
var secIdVal = parseInt(document.getElementById("sectionId__"+pageIdValue).value);
    var formData = formData2QueryString(document.createEntityForm);
    if(mode == "createmode"){
        var url = "/crm/DFBCreateEditSection.do?mode="+mode+"&pageId="+pageIdValue+"&secCount="+secIdVal+"&module_c="+module;
        var title="Create Section";
        }
    else{
	sId = theButton.id;
	sId = parseInt(sId.substring(sId.lastIndexOf("_")+1));
        var dataSectiontype ="fieldSections";
        if(getObj("dataSectiontype_"+pageIdValue+"_"+sId))
        {
            dataSectiontype = getObj("dataSectiontype_"+pageIdValue+"_"+sId).value;
        }
        var url = "/crm/DFBCreateEditSection.do?mode="+mode+"&pageId="+pageIdValue+"&secCount="+sId+"&dataSectiontype="+dataSectiontype;
        var title="Edit Section";
        }
       
    new Ajax.Request(url,{method:"post",onSuccess:function(t)
    {        
        showDialog(t.responseText,"modal=yes, closeOnEscKey=no,position=absolute,title="+title+",top=200,left=200,width=600");
        if(document.getElementById("secname")){
         document.getElementById("secname").focus();}         
    },asynchronous:true,evalScripts:true,postBody:formData});
   
}

function DFBcreateDataSection(theButton,pageId,sId,mode) 
{

var pageIdValue = parseInt(document.getElementById(pageId).value);
var secIdVal = parseInt(document.getElementById("sectionId__"+pageIdValue).value);
    var formData = formData2QueryString(document.createEntityForm);
    if(mode == "createmode"){
        var url = "/crm/DFBCreateEditSection.do?mode="+mode+"&pageId="+pageIdValue+"&secCount="+secIdVal+"&dataSectiontype=dataSection";
        var title="Create Section";
        }
    else{
        var url = "/crm/DFBCreateEditSection.do?mode="+mode+"&pageId="+pageIdValue+"&secCount="+sId+"&dataSectiontype=dataSection";
        var title="Edit Section";
        }
       
    new Ajax.Request(url,{method:"post",onSuccess:function(t)
    {        
        showDialog(t.responseText,"modal=yes, closeOnEscKey=no,position=absolute,title="+title+",top=200,left=200,width=600");
        if(document.getElementById("secname")){
         document.getElementById("secname").focus();}         
    },asynchronous:true,evalScripts:true,postBody:formData});
   
}
function DFBdeleteOption(id, value) {

        var fieldValArr = value.split(":#:");
        var fieldValue = fieldValArr[0]+":#:"+fieldValArr[1]+":#:"+fieldValArr[2]+":#:"+fieldValArr[3]+":#:"+fieldValArr[4]+":#:"+fieldValArr[5] ;

	// Delete option with given value from given selector
	var selector = document.getElementById(id);
	var options = selector.options;
	for (var i = 0; i < options.length; i++) {
		if (options[i].value.indexOf(fieldValue)>-1) {		
			options[i] = null;
			break;
		}
	}
}
function DFBdataListValidation(mode,pageId,seccount)
{

    var dataListModule = getObj("dataListModule").value ;  
      
    var mode = getObj("mode").value;
     
    var noofpages = document.getElementById("noofpages").value;
    
    for(var n=1;n<=noofpages;n++)
    {
        var totSecCount = document.getElementById("sectionId__"+n).value ;
        if(totSecCount!=0)
        {
            for(var i=1;i<=totSecCount;i++)
            {
                var secType = getObj("sectiontype_"+n+"_"+i).value ;     
                if(dataListModule == secType)
                {
                    var secFields = getObj("selectfieldsdiv_"+n+"_"+i+"_SF").value ;
                    var selectfieldsvalArr = secFields.split(",");                
                    for(var j=0;j< selectfieldsvalArr.length;j++)
                    {
                        var oldFieldValues = selectfieldsvalArr[j] ;    
                        if(mode == "createmode"){
                            DFBdeleteOption("availList", oldFieldValues)
                            DFBdeleteOption("selectedColumns", oldFieldValues)
                        }
                        else
                        {
                            if(pageId!=n || seccount!=i)
                            {
                                DFBdeleteOption("availList", oldFieldValues)
                                DFBdeleteOption("selectedColumns", oldFieldValues)
                            }
                            else
                            {
                                //DFBdeleteOption("availList", oldFieldValues)
                                DFBdeleteOption("selectedColumns", oldFieldValues)
                                var fieldValArr = oldFieldValues.split(":#:");
                                var dfbfieldlabel = fieldValArr[8] ;
                                if(dfbfieldlabel !=undefined){
                                    var newColObj=document.createElement("OPTION");
                                    newColObj.value=oldFieldValues;

                                    if (browser_ie) newColObj.innerText=dfbfieldlabel;
                                    else if (browser_nn4 || browser_nn6) newColObj.text=dfbfieldlabel;
                                    getObj("selectedColumns").appendChild(newColObj);
                                }
                            }

                        }
                    }
                }            
            }
        }
    
    }
    
    //var totSecCount = getObj("sectioncountvalue").value ;
    
}
function dfbScripts()
{
 var noofpages = document.getElementById("noofpages").value;
    
    for(var n=1;n<=noofpages;n++)
    {
        var totSecCount = document.getElementById("sectionId__"+n).value ;
        if(totSecCount!=0)
        {
           for(var j=1;j<=totSecCount;j++)
         {
             var secType = getObj("sectiontype_"+n+"_"+j).value ;    
             if((secType != "Contacts") && (secType != "Registrations"))
             {
             // Delete option with given value from given selector
             var selector = document.getElementById("dataListType");
             var options = selector.options;
             for (var i = 0; i < options.length; i++) {
                     if (options[i].value.indexOf(secType)>-1) {
                             options[i] = null;
                            // break;
                     }
             }
             }

         }
         
        }
    }

}
function DFBchangeDataListColumns(module,mode,pageId,seccount)
{
    DFBchangeNoofRowsObj(module,mode,seccount);
    var url = "/crm/jsp/DFBAddDatalist.jsp?selModuleValue="+module;    
    new Ajax.Updater('dataListColumns',url,{method:"post",onComplete:function(){
    DFBdataListValidation(mode,pageId,seccount);
    },asynchronous:true,evalScripts:true});
}
function DFBchangeNoofRowsObj(module,mode,secCount)
{
    if(module == "Contacts" || module == "Discounts" || module == "Cases" || module == "Recommendations" || module == "Registrations")
    {
        document.getElementById("noOfRowsDivId").style.display="none";
    }    
    else
    {
        if (browser_ie)
        {
            document.getElementById("noOfRowsDivId").style.display="block";
        }
        else
        {
            document.getElementById("noOfRowsDivId").style.display="table-row";
        }        
    }  
}
function DFBshowEditField(fieldId)
{
    var itemObj=getObj("fldLblDiv_availFields_"+fieldId);
    currFieldObj = itemObj;

    var obj = currFieldObj.id;
    var id = getObj(obj).parentNode.id ;
    var parentDivId = getObj(obj).parentNode.parentNode.id ;
    if(parentDivId.indexOf("selectfieldsdiv_")> -1)
    {
        crmy = findPosY(itemObj);
        crmx = findPosX(itemObj);
        var spanObj = getObj('crmfieldid');
        spanObj.style.display='inline';
        spanObj.style.left=(crmx+itemObj.offsetWidth - spanObj.offsetWidth)+"px";
        spanObj.style.top=crmy+3+"px";        
    } 	
}

function DFBdeleteSection(theButton,pageId,secCount,mode)
{
    var pageIdVal = document.getElementById(pageId).value;
    
    var res = window.confirm('Are you sure ?');
    if(res == false){
    	return;
    }
	secCount = theButton.id;
	secCount = parseInt(secCount.substring(secCount.lastIndexOf("_")+1));
    var secDivobj = document.getElementById("sectionDiv_"+pageIdVal+"_"+secCount);   
 
    var pageDivobj = document.getElementById("pageDiv__"+pageIdVal);
    pageDivobj.removeChild(secDivobj);
   
    var kcountVal = document.getElementById("sectionId__"+pageIdVal).value ;//getObj("sectioncountvalue").value;        
   for(var k=secCount+1;k<=kcountVal;k++)
    {
        getObj("sectionDiv_"+pageIdVal+"_"+k).id = "sectionDiv_"+pageIdVal+"_"+(k-1);
        
        getObj("secNameDisDiv_"+pageIdVal+"_"+k).id = "secNameDisDiv_"+pageIdVal+"_"+(k-1);
        
        getObj("sectionName_"+pageIdVal+"_"+k).id = getObj("sectionName_"+pageIdVal+"_"+k).name = "sectionName_"+pageIdVal+"_"+(k-1);       
        
        getObj("sectionMsg_"+pageIdVal+"_"+k).id = getObj("sectionMsg_"+pageIdVal+"_"+k).name = "sectionMsg_"+pageIdVal+"_"+(k-1);     
  
        getObj("sectionDuplicate_"+pageIdVal+"_"+k).id = getObj("sectionDuplicate_"+pageIdVal+"_"+k).name = "sectionDuplicate_"+pageIdVal+"_"+(k-1);    
        
        getObj("dataSectiontype_"+pageIdVal+"_"+k).id = getObj("dataSectiontype_"+pageIdVal+"_"+k).name = "dataSectiontype_"+pageIdVal+"_"+(k-1);   
       
        getObj("sectiontype_"+pageIdVal+"_"+k).id = getObj("sectiontype_"+pageIdVal+"_"+k).name = "sectiontype_"+pageIdVal+"_"+(k-1);
        getObj("sectionindex_"+pageIdVal+"_"+k).id =  getObj("sectionindex_"+pageIdVal+"_"+k).name = "sectionindex_"+pageIdVal+"_"+(k-1); 
        
        getObj("selectfieldsdiv_"+pageIdVal+"_"+k).id = "selectfieldsdiv_"+pageIdVal+"_"+(k-1);
        
        getObj("selectfieldsdiv_"+pageIdVal+"_"+k+"_SF").id =  getObj("selectfieldsdiv_"+pageIdVal+"_"+k+"_SF").name = "selectfieldsdiv_"+pageIdVal+"_"+(k-1)+"_SF";
         
        if (browser_ie)
        {
            getObj("editlink_"+pageIdVal+"_"+k).onclick = function(){ DFBcreateSection(this,"pageid__"+pageIdVal,(k-1),'editmode') } ;
            getObj("deletelink_"+pageIdVal+"_"+k).onclick = function(){ DFBdeleteSection(this,"pageid__"+pageIdVal,(k-1),'deletemode') } ;
        }
        else
        {
                var tempp = "pageid__"+pageIdVal;
             getObj("editlink_"+pageIdVal+"_"+k).setAttribute("onclick","DFBcreateSection(this,'"+tempp+"',"+(k-1)+",'editmode');")
             getObj("deletelink_"+pageIdVal+"_"+k).setAttribute("onclick","DFBdeleteSection(this,'"+tempp+"',"+(k-1)+",'deletemode');")        
        }
         
        getObj("editlink_"+pageIdVal+"_"+k).id = "editlink_"+pageIdVal+"_"+(k-1);
        getObj("deletelink_"+pageIdVal+"_"+k).id = "deletelink_"+pageIdVal+"_"+(k-1);
        
        
    }  
    document.getElementById("sectionId__"+pageIdVal).value = ((document.getElementById("sectionId__"+pageIdVal).value)-1);      
    if(kcountVal == 1)
    {
        if(document.getElementById("createSectionButtonDiv__"+pageIdVal).style.display == "block")
        {            
            document.getElementById("createSectionEmptyMsgDiv__"+pageIdVal).style.display = "block";
            document.getElementById("createSectionButtonDiv__"+pageIdVal).style.display = "none";
        }
    }
   // sectionSorting();
    //dragFormSections();
}

function DFBCallSectionOrders(theButton,pageId,sId,mode)
{
	var pageIdValue = document.getElementById(pageId).value;
	var secIdVal = parseInt(document.getElementById("sectionId__"+pageIdValue).value);
    if(secIdVal>1){
    	var formData = formData2QueryString(document.createEntityForm);
    	var url = "/crm/DFBChangeSectionOrders.do?mode="+mode+"&pageId="+pageIdValue+"&secCount="+secIdVal;
    	var title="Change Section Orders";
    	new Ajax.Request(url,{method:"post",onSuccess:function(t)
    	{        
        	showDialog(t.responseText,"modal=yes, closeOnEscKey=no,position=absolute,title="+title+",top=200,left=200,width=300");        
	    },asynchronous:true,evalScripts:true,postBody:formData});
    }
    else{
        alert('More than one sections can be reordered')
        return false;
    }
}


function DFBChangeSectionOrder(obj,mode,pageId,seccount)
{

    var selectedColumnsObj=getObj("selectedColumns")
    var valueofOpt="";
    var currpos=selectedColumnsObj.length;
    if (currpos>0) 
    {   
        var temp ="";
        var j=1;
        for (i=0;i<selectedColumnsObj.length;i++) 
        {       
        
            var v = selectedColumnsObj.options[i].value;
            var secDivObj = document.getElementById("sectionDiv_"+pageId+"_"+v); 
            // To change section index
            document.getElementById('sectionindex_'+pageId+'_'+v).value = j;
            
            var temp = secDivObj.innerHTML.replace(/_[0-9]+_[0-9]+/g,'_'+(pageId)+'_'+j);
            var tempDivid = "TempsectionDiv_"+pageId+"_"+j;
            document.getElementById("tempContent").innerHTML = document.getElementById("tempContent").innerHTML+"<div id='"+tempDivid+"' style='position: relative; z-index: 0; left: 0px; top: 0px; opacity: 0.999999;'>"+temp+"</div>";
        j++;    
        }
    }

var str=document.getElementById("tempContent").innerHTML;
str = replaceAll(str,'TempsectionDiv', 'sectionDiv');
    
    document.getElementById("pageDiv__"+pageId).innerHTML = str;
    document.getElementById("tempContent").innerHTML="";
    
    for(var k=1;k<=seccount;k++)
    {
     
         if (browser_ie)
        {  
            var ltemp = k;
            document.getElementById("editlink_"+pageId+"_"+ltemp).onclick = function(){ DFBcreateSection(this,"pageid__"+pageId,ltemp,'editmode'); } ;
            document.getElementById("deletelink_"+pageId+"_"+ltemp).onclick = function(){ DFBdeleteSection(this,"pageid__"+pageId,ltemp,'deletemode'); } ;
        }
        else
        {
             var tempp = "pageid__"+pageId;
             var ltemp = k;
             document.getElementById("editlink_"+pageId+"_"+ltemp).setAttribute("onclick","DFBcreateSection(this,'"+tempp+"',"+(ltemp)+",'editmode');")
             document.getElementById("deletelink_"+pageId+"_"+ltemp).setAttribute("onclick","DFBdeleteSection(this,'"+tempp+"',"+(ltemp)+",'deletemode');")        
        }
    }
   
  closeDialog();
   return false; 
}  

function editDFBField(mode)
{
    var obj = currFieldObj.id;
    var id = getObj(obj).parentNode.id ;
    var parentDivId = getObj(obj).parentNode.parentNode.id ;
    var pageIdval =parentDivId.substring(parentDivId.indexOf("_")+1,parentDivId.lastIndexOf("_")+0);
    var secCount = parentDivId.substring(parentDivId.lastIndexOf("_")+1);               
    if(mode == "deleteField")
    {
        if(parentDivId.indexOf("availFields_")> -1)
        {
            alert('You are not allowed to delete this field')
            return false;
        }
        else
        {
            if(parentDivId.indexOf("selectfieldsdiv_")> -1)
            {
                var removeDivObj = getObj("selectfieldsdiv_"+pageIdval+"_"+secCount);
                removeDivObj.removeChild(document.getElementById(id));
               
               var removedElement = id.substring(id.indexOf("_")+1);
               var selectfieldsIDList = getObj("selectfieldsdiv_"+pageIdval+"_"+secCount+"_SF").value;
                var secIDListArr = selectfieldsIDList.split(",");
                var newList="";
                for(var i=0;i< secIDListArr.length;i++)
                {
                    if(secIDListArr[i] != removedElement)
                    {
                        if(newList =="")
                        {
                            newList=secIDListArr[i];
                        }
                        else
                        {
                        newList=newList+","+secIDListArr[i];
                        }
                    }
                }               
               getObj("selectfieldsdiv_"+pageIdval+"_"+secCount+"_SF").value = newList;
               
            }
            else
            {
                return false;
            }
        }
    }else
    {
        var changeHdnVal ="false";
        if(parentDivId.indexOf("selectfieldsdiv_")> -1)
        {
            changeHdnVal ="true";
        }
        var formData = "mode="+mode+"&fieldValues="+id+"&changeHdnVal="+changeHdnVal+"&pageId="+pageIdval+"&secCount="+secCount ;
        var url = "/crm/DFBCreateEditFields.do";        
        new Ajax.Request(url,{method:"post",onSuccess:function(t)
        {
            showDialog(t.responseText,"modal=yes, closeOnEscKey=no,position=absolute,title=Edit Field Properties,top=200,left=400,width=400");
            if(document.getElementById("fieldName")){
             document.getElementById("fieldName").focus();}
        },asynchronous:true,postBody:formData});

    }
}
function DFBShowSecPageDiv(pageno)
{
    var pageSize = document.getElementById("pageSizes").value;
    for(var i=1;i<=pageSize;i++)
    {
        if( i == pageno)
        {
                document.getElementById("pageSecDivid_"+i).style.display ="block";
                document.getElementById("pageLinkClassId_"+i).className="selectedPage";
                document.getElementById("pageLinkAClassId_"+i).className="selectedPage";

        }else{
            document.getElementById("pageSecDivid_"+i).style.display ="none";
            document.getElementById("pageLinkClassId_"+i).className="unselectedPage";
            document.getElementById("pageLinkAClassId_"+i).className="unselectedPage";
        }
    }
document.getElementById("currentPage").value = pageno;

 
}
function DFBSaveandPrevForm()
{
    getObj("nextPage").value = (parseInt(getObj("currentPage").value))-1 ;
}
function DFBSaveandNextForm()
{
    getObj("nextPage").value = (parseInt(getObj("currentPage").value)) +1 ;
}
function DFBcallPageNavigAction(pageno)
{
	pageno = parseInt(pageno)
	getObj("nextPage").value = pageno ;
	if(window.confirm('Do you want to save the changes?')==true)
	{
    	getObj("saveSecureFormValues").value = "saveValues" ;
	    DFBsetInterestGroups();
    	if(document.dfbForm.onsubmit())
    	{
        	document.dfbForm.submit();     
    	}
	}
	else
	{
   		getObj("saveSecureFormValues").value = "dontSaveValues" ;
	    document.dfbForm.submit();        
	}
	return true;      
}
function DFBcallPageNavigActionN(pageno)
{	
	pageno = parseInt(pageno)
	getObj("nextPage").value = pageno ;
	if(window.confirm('Do you want to save the changes ?')==true)
	{
    	getObj("saveSecureFormValues").value = "saveValues" ;
        if(document.dfbForm.onsubmit())
    	{
        	document.dfbForm.submit();     
        }
	}
	else
	{
   		getObj("saveSecureFormValues").value = "dontSaveValues" ;
	    document.dfbForm.submit();     
   
	}
	return true; 
}
function dfbCallRequirementPage(pageNo)
{
	pageNo = parseInt(pageNo)
	getObj("nextPage").value = pageNo ;
	if(window.confirm('Do you want to save the changes ?')==true)
	{
    	getObj("saveSecureFormValues").value = "saveValues" ;
        if(document.dfbForm.onsubmit())
    	{
        	document.dfbForm.submit();     
    	}
	}
	else
	{
   		getObj("saveSecureFormValues").value = "dontSaveValues" ;
	    document.dfbForm.submit();        
	}
	return true; 
}
function DFBPreNextButtonEnable(pageno)
{
pageno = parseInt(pageno)
var prevPage =pageno-1;
    if(prevPage >0 )
    {
        getObj("saveandprevButtonDivId").style.display="block";
    }else
    {
    getObj("saveandprevButtonDivId").style.display="none";
    }
    
    var pageSizes = parseInt(getObj("pageSizes").value);
   
    if(pageno == pageSizes)
    {
        getObj("saveandprevButtonDivId").style.display="block";
        getObj("saveandnextButtonDivId").style.display="none";
        if(getObj("submitButtonDivId"))
        getObj("submitButtonDivId").style.display="block";
    }
    else{
        getObj("saveandnextButtonDivId").style.display="block";
        if(getObj("submitButtonDivId"))
        getObj("submitButtonDivId").style.display="none";
    }
}
function DFBPrevNextForm(option)
{
    var currentPage = parseInt(getObj("currentPage").value);
    if(option == "prev"){
    var nextPage =currentPage-1;
    }else{
    var nextPage =currentPage+1;
    }
    if(nextPage >1 )
    {
        getObj("saveandprevButtonDivId").style.display="block";
    }else
    {
    getObj("saveandprevButtonDivId").style.display="none";
    }
    
    var pageSizes = parseInt(getObj("pageSizes").value);
   
    if(nextPage == pageSizes)
    {
        getObj("saveandprevButtonDivId").style.display="block";
        getObj("saveandnextButtonDivId").style.display="none";
        if(getObj("submitButtonDivId"))
        getObj("submitButtonDivId").style.display="block";
    }else
    {
    getObj("saveandnextButtonDivId").style.display="block";
    if(getObj("submitButtonDivId"))
    getObj("submitButtonDivId").style.display="none";
    }
    
    getObj("currentPage").value = nextPage;
    DFBShowSecPageDiv(nextPage);    
    
}
function DFBcallPreviewAction(currObj,validationMode)
{  
  
    if(validationMode == "validationMode")
    {
        if(!DFBFormValidate())
        {
            return false;
        }
    }
    
    //sectionSorting();
    var operation = "create";
    var imageid =null;
    if(getObj("operation")){operation =getObj("operation").value; }
    if(getObj("property(id)")){imageid =getObj("property(id)").value ;}
    
    var formData = formData2QueryString(document.createEntityForm);
    var url ='/crm/DFBPreview.do?resultView=preview';
    if(imageid!=null && imageid!="" && imageid!="null")
    {
        url = url+"&imageid="+imageid;
    }
   new Ajax.Request(url,{method:"post",onSuccess:function(t)
    {   
       var features="width=600,height=550,menubar=no,toolbar=no,location=no,status=no,scrollbars=yes,resizable=yes";
       var win=window.open("","preview",features);
       win.document.body.innerHTML=t.responseText;      
       DFBmakeScriptExecute(win.document);
    },asynchronous:true,postBody:formData,evalScripts:true});
}

function resetQryBuilder()
{
	if (document.getElementById('FreezeLayer') != null) {document.body.removeChild(document.getElementById('FreezeLayer'));}
	var rowCount=document.getElementById("row").value;
	if(rowCount>=2)
	{
		for(var i=2;i<=rowCount;i++)
		{
			document.getElementById("tableBodyId").removeChild(document.getElementById('cloneid_'+i));
		}
	}
	document.getElementById('searchfieldtype_1').value='T';
	document.getElementById("row").value="1";
	document.getElementById('relatedmodule_1').selectedIndex='0';
	document.getElementById('textcondition_1').selectedIndex='0';
	document.getElementById('datecondition_1').selectedIndex='0';
	document.getElementById('numcondition_1').selectedIndex='0';
	document.getElementById('datetimecondition_1').selectedIndex='0';
	document.getElementById('value_1').value="";
	document.getElementById('numfld_1').value="";
	document.getElementById('datefld_1').value="";
	document.getElementById('datetime_1').value="";
	document.getElementById('timeval_1').value="";
	document.getElementById('logic_1').value="";
	document.getElementById('endlogic_1').value="";
	callRelatedField('relatedmodule_1');
	setTimeout("Search.changeField('searchfield_1')","2000");


}
function showConditionalSec(obj,module)
{
	var topVal=findPosY(obj);
	var leftVal=findPosX(obj)-600;
	var url ="/crm/jsp/IWConditionalSec.jsp?module="+module+"&isConditionalSec=true";
	loadAjaxTab4("Loading...");
	new Ajax.Request(url,{method:"post",onSuccess:function(t)
	{      
        	showDialog(t.responseText,"modal=yes, closeOnEscKey=no,position=absolute,top="+topVal+",left="+leftVal+",width=725");
		document.getElementById('ajax_load_tab').style.display='none';
	},asynchronous:true,evalScripts:true});
}	
function saveConditionalQuery()
{
	var rowno=getObj("row").value;
	var pattern=getObj("dateFmt").value
	for(var i=1;i<=rowno;i++)
	{
		
		var objSearchfield=getObj("searchfieldtype_"+i);
		var sFieldCondn = "";
		var fldLabel = "";
		if(objSearchfield.value=="DT" || objSearchfield.value=="D")
		{
			if(objSearchfield.value=="D")
			{
				sFieldCondn = "datecondition_";
			}
			else if(objSearchfield.value=="DT")
			{
				sFieldCondn = "datetimecondition_";
			}
	
			if (browser_ie)
			{
				fldLabel=getObj(sFieldCondn+i).options[getObj(sFieldCondn+i).options.selectedIndex].innerText
			}
			else if (browser_nn4 || browser_nn6)
			{
				fldLabel=getObj(sFieldCondn+i).options[getObj(sFieldCondn+i).options.selectedIndex].text
			}	
			if(objSearchfield.value=="D")
			{
				if(fldLabel!= "is empty" && fldLabel!= "is not empty")
				{
					if(!dateValidate("datefld_"+i,"Date. Date Format is "+pattern,"OTH"))
						return false;
				}
			}
			else if(objSearchfield.value=="DT")
			{
				if(fldLabel!= "is empty" && fldLabel!= "is not empty")
				{
					var len=trimBoth(getObj("timeval_"+i).value).length;
					if(len>0)
					{
						if(!dateValidate("datetime_"+i,"Date. Date Format is "+pattern,"OTH"))
							return false;
						else if(!timeValidate("timeval_"+i,"Time hh:mm 24 hours format","OTH"))
							return false
					}
					else
					{
						if(!dateValidate("datetime_"+i,"Date. Date Format is "+pattern,"OTH"))
							return false;
					}
				}
			}
		}		
	}
	//document.getElementById("previewQuery").innerHTML="";
	//document.gtElementById("previewQuery").style.display="block";
	if(!validateOpenBracket())
	{
	alert("open Braces only allowed in left side ");
return false;
	}
	if(!validateCloseBracket())
	{
	alert("Closed Braces only allowed in right side ");
return false;
	}

	if(!validateParanthesis())
	{
	alert("Parenthetical logic not matched properly");
	return false;
	}
	var query=constructQuery();
	document.getElementById("finalQuery").value=query;
	var formData = formData2QueryString(document.criteriaForm);
	
	var url="/crm/SaveConditionalQuery.do";
        new Ajax.Request(url,{method:"post",onSuccess:function(t)
       	{
		var str = t.responseText;
		insertContent(str);
		closeDialog();
       	},asynchronous:true,postBody:formData
       	});	
}
function DFBmakeScriptExecute(doc)
{ 
    var scriptTags = doc.body.getElementsByTagName("SCRIPT");
    var len = scriptTags.length;
    for (var i = 0; i <len; i++) {
    var scriptTag = doc.createElement("SCRIPT");
    scriptTag.type = "text/javascript";
    scriptTag.language = "javascript";
    if (scriptTags[i].src != "") { scriptTag.src =
    scriptTags[i].src;}
    scriptTag.text = scriptTags[i].text;
    if (typeof doc.getElementsByTagName("HEAD")[0] ==
    "undefined") {
    doc.createElement("HEAD").appendChild(scriptTag)
    } else {

    doc.getElementsByTagName("HEAD")[0].appendChild(scriptTag);
    }
    }
}
function DFBMulPagenonContactsModuleVallidatiion(option)
{
var pagevalidationSecTypes = getObj("pageSecDivid_"+option+"_validationSecType").value;
if(pagevalidationSecTypes!=""){
var secTypeArr = pagevalidationSecTypes.split(";")
    for(var i=0;i<secTypeArr.length;i++)
    {
        var sectionType =secTypeArr[i];
        if(sectionType!="" && sectionType!= "Contacts" && sectionType!="Recommendations")
        {
            var addResponseCount = 1 ;

            if(getObj("addResponseCount_"+sectionType))
            addResponseCount = parseInt(getObj("addResponseCount_"+sectionType).value);
            for(var k=1;k<= addResponseCount;k++)
            {
                var manFields =  getObj(sectionType+"_mandFields___"+k).value;
                var nonMandFields =  getObj(sectionType+"_nonMandFields___"+k).value;
                if(nonMandFields!=null && nonMandFields!="" && nonMandFields!="null" && nonMandFields!=undefined)
                {
                
                    var nonMandFieldsArr = nonMandFields.split(":##:")
                    for(var j=0;j< nonMandFieldsArr.length;j++)
                    {   
                        if(getObj(nonMandFieldsArr[j])){
                        var currObj=getObj(nonMandFieldsArr[j])
                        
                        if( !(currObj.value == "none" || currObj.value =="-None-" || currObj.value.replace(/^\s+/g, '').length==0) ) 
                        {
                             if(getObj(manFields))
                             {
                           if((getObj(manFields).value.replace(/^\s+/g, '').length==0) ) 
                           {
                                var fieldLabel = manFields.substring(manFields.indexOf("_")+1,manFields.lastIndexOf("___")+0);
                                var subFieldLabel = fieldLabel.substring(0,fieldLabel.indexOf("_"));
                                alert(subFieldLabel+' cannot be blank');
                                getObj(manFields).focus();
                                return false;                 
                           }}
                        }}
                    }
                }//end of nonMandFields if loop
            }//end of addResponseCount for loop
        }//end of sectiontype if loop
    }//end of sectiontotalcount for loop
}
return true;

}
function constructCVCriteria()
{
	var query="(";
	var rowno=getObj("row").value;
	for(var i=1;i<=rowno;i++)
	{
		var j=i+1;
		if(document.getElementById("logic_"+i).value!=null)
		{
			query=query+" "+document.getElementById("logic_"+i).value.trim();
		}
		query=query+i;
		if(document.getElementById("endlogic_"+i).value!=null)
		{
			query=query+" "+document.getElementById("endlogic_"+i).value.trim();
		}	
		if(j<=rowno && getObj("match"+j)!=null)
		{
			if(getObj("match"+j).value!=null)
			{
				query=query+" "+getObj("match"+j).value;
			}
		}
	}
	query=query+")";
	return query;
}
function addAnotherDisLine()
{
    showLookUp('DiscountCode_DiscountID_lookup','DiscountCode','DiscountCode','Discounts')
    return false;
}
function addLineItemADD()
{
    showLookUp('LineItem_LineItemID_lookup','Item','Item','Additional Item')
    return false;
}
function getDiscountCodeBody() {
        if (browser_ie) {
                var prodListBody=getObj("DiscountCode_Discounts").children[0].children[0]
        } else if (browser_nn4 || browser_nn6) {
                if (getObj("DiscountCode_Discounts").childNodes.item(0).tagName=="TABLE") {
                        var prodListBody=getObj("DiscountCode_Discounts").childNodes.item(0).childNodes.item(0)
                } else {
                        var prodListBody=getObj("DiscountCode_Discounts").childNodes.item(1).childNodes.item(1)
                }
        }
        return prodListBody;
        
}
function DiscountCodedelRow(id)
{

    var rowId=parseInt(id.substr(21));
    getDiscountCodeBody().removeChild(getObj("DC__hrow__"+rowId))

    var totdistrowCnt = parseInt(getObj("tot_discount__codes").value );


    var newInnerHTML="<tr class='dynamicsegqbhead'  id='discounts_tablehead'>"+getObj("discounts_tablehead").innerHTML+"</tr>";

    var rowArray=new Array(totdistrowCnt-1);
    if (browser_nn4 || browser_nn6) 
    {
        var discount=new Array(totdistrowCnt-1)
        var discountId=new Array(totdistrowCnt-1)
        var desc=new Array(totdistrowCnt-1)
        var amt=new Array(totdistrowCnt-1)
        var pgmprice=new Array(totdistrowCnt-1)
        var amtType=new Array(totdistrowCnt-1)
    }
    for (var i=1,k=0;i<=rowId-1;i++,k++) {
        if (i%2==0) var rowClass="evenListRow";
        else var rowClass="oddListRow";
        rowArray[k]="<tr id='DC__hrow__"+i+"' class='"+rowClass+"'>"+getObj("DC__hrow__"+i).innerHTML+"</tr><tr id='tableline'><td colSpan='8' class='tableRowSep'></td></tr>";
        newInnerHTML+=rowArray[k];
        if (browser_nn4 || browser_nn6) 
        {
            discount[k]=getObj("DiscountCode_Discount__"+i).value
            discountId[k]=getObj("DiscountCode_DiscountID_lookup__"+i).value
            desc[k]=getObj("DiscountCode_Description__"+i).value
            amt[k]=getObj("DiscountCode_Amount__"+i).value
           pgmprice[k]=getObj("DiscountCode_PgmPrice__"+i).value
           amtType[k]=getObj("DiscountCode_hdnAmtType__"+i).value
        }
    }


    for (var i=rowId+1;i<=totdistrowCnt;i++,k++) 
    {
        rowArray[k]=getObj("DC__hrow__"+i).innerHTML;
        var temp=rowArray[k];
        temp = replaceAll(temp,'__'+i, '__'+(i-1));

        if ((i-1)%2==0) var rowClass="evenListRow";
        else var rowClass="oddListRow";
        rowArray[k]="<tr id='DC__hrow__"+(i-1)+"' class='"+rowClass+"'>"+temp+"</tr><tr id='tableline'><td colSpan='8' class='tableRowSep'></td></tr>";
        newInnerHTML+=rowArray[k];
        if (browser_nn4 || browser_nn6) {
            discount[k]=getObj("DiscountCode_Discount__"+i).value
            discountId[k]=getObj("DiscountCode_DiscountID_lookup__"+i).value
            desc[k]=getObj("DiscountCode_Description__"+i).value
            amt[k]=getObj("DiscountCode_Amount__"+i).value
            pgmprice[k]=getObj("DiscountCode_PgmPrice__"+i).value
            amtType[k]=getObj("DiscountCode_hdnAmtType__"+i).value
        }           
    }

    var prodListBody=getDiscountCodeBody();
    var listTableStart="<table width='100%' border='0' cellspacing='0' cellpadding='0' class='formBorder' style='bgcolor:#f9f9f9;'>"
    getObj("DiscountCode_Discounts").innerHTML=listTableStart+newInnerHTML+"</table>";

    totdistrowCnt--; 

    for (var i=1,k=0;i<=totdistrowCnt;i++,k++) 
    {
            if (browser_nn4 || browser_nn6) {
                getObj("DiscountCode_Discount__"+i).value=discount[k]
               getObj("DiscountCode_DiscountID_lookup__"+i).value=discountId[k]
               getObj("DiscountCode_Description__"+i).value=desc[k]
               getObj("DiscountCode_Amount__"+i).value=amt[k]
               getObj("DiscountCode_PgmPrice__"+i).value=pgmprice[k]
               getObj("DiscountCode_hdnAmtType__"+i).value=amtType[k]
            }
    }

    getObj("tot_discount__codes").value = (parseInt(getObj("tot_discount__codes").value )-1);

}
function LineItemdelRow(id)
{
	 var rowId=parseInt(id.substr(17));
     getLineItemBody().removeChild(getObj("invoice_paymentA_discount"+rowId))

    var totdistrowCnt = parseInt(getObj("tot_Invoice_Addinfo").value );

    var newInnerHTML="<tr class='dynamicsegqbhead'  id='invoice_paymentaddinfo_discount'>"+getObj("invoice_paymentaddinfo_discount").innerHTML+"</tr>";

    var rowArray=new Array(totdistrowCnt-1);
    if (browser_nn4 || browser_nn6) 
    {
        var lineitem=new Array(totdistrowCnt-1)
        var lineitemId=new Array(totdistrowCnt-1)
        var desc=new Array(totdistrowCnt-1)
        var cost=new Array(totdistrowCnt-1)
        var qt=new Array(totdistrowCnt-1)
        var total=new Array(totdistrowCnt-1)
    }
    for (var i=1,k=0;i<=rowId-1;i++,k++) {
    	if (i%2==0) var rowClass="evenListRow";
        else var rowClass="oddListRow";
        rowArray[k]="<tr id='invoice_paymentA_discount"+i+"' class='"+rowClass+"'>"+getObj("invoice_paymentA_discount"+i).innerHTML+"</tr><tr id='tableline'><td colSpan='8' class='tableRowSep'></td></tr>";
        newInnerHTML+=rowArray[k];
        if (browser_nn4 || browser_nn6) 
        {
        	lineitem[k]=getObj("invoice_Addinfo_Lineitem__"+i).value
            lineitemId[k]=getObj("LineItem_LineItemID_lookup__"+i).value
            desc[k]=getObj("invoice_Addinfo_Description__"+i).value
            cost[k]=getObj("invoice_Addinfo_cost__"+i).value 
            qt[k]=getObj("invoice_Addinfo_txtQty__"+i).value
            total[k]=getObj("invoice_Addinfo_total__"+i).value
           
        }
    }


    for (var i=rowId+1;i<=totdistrowCnt;i++,k++) 
    {
    	rowArray[k]=getObj("invoice_paymentA_discount"+i).innerHTML;
        var temp=rowArray[k];
        temp = replaceAll(temp,'__'+i, '__'+(i-1));

        if ((i-1)%2==0) var rowClass="evenListRow";
        else var rowClass="oddListRow";
        rowArray[k]="<tr id='invoice_paymentA_discount"+(i-1)+"' class='"+rowClass+"'>"+temp+"</tr><tr id='tableline'><td colSpan='8' class='tableRowSep'></td></tr>";
        newInnerHTML+=rowArray[k];
        if (browser_nn4 || browser_nn6) {
        	lineitem[k]=getObj("invoice_Addinfo_Lineitem__"+i).value
            lineitemId[k]=getObj("LineItem_LineItemID_lookup__"+i).value
            desc[k]=getObj("invoice_Addinfo_Description__"+i).value
            cost[k]=getObj("invoice_Addinfo_cost__"+i).value
            qt[k]=getObj("invoice_Addinfo_txtQty__"+i).value
            total[k]=getObj("invoice_Addinfo_total__"+i).value
        }           
    }

    var prodListBody=getLineItemBody();
    var listTableStart="<table width='100%' border='0' cellspacing='0' cellpadding='0' class='formBorder' style='bgcolor:#f9f9f9;'>"
    getObj("invoice_paymentaddinfo_discountmaindiv").innerHTML=listTableStart+newInnerHTML+"</table>";

    totdistrowCnt--; 

    for (var i=1,k=0;i<=totdistrowCnt;i++,k++) 
    {
            if (browser_nn4 || browser_nn6) {
            	getObj("invoice_Addinfo_Lineitem__"+i).value=lineitem[k]
            	   	getObj("LineItem_LineItemID_lookup__"+i).value=lineitemId[k]
            	    getObj("invoice_Addinfo_Description__"+i).value=desc[k]
            	    getObj("invoice_Addinfo_cost__"+i).value=cost[k]
            	    getObj("invoice_Addinfo_txtQty__"+i).value=qt[k]
            	    getObj("invoice_Addinfo_total__"+i).value=total[k]
            }
    }

    
    getObj("tot_Invoice_Addinfo").value = (parseInt(getObj("tot_Invoice_Addinfo").value )-1);
      calcAdjusTotal();
   
}
function DeleteInvoiceDiscountCode()
{
	
getObj("invoice_paymentinfo_discountmaindiv").innerHTML = "";

//    getObj("invoice_payment_trid").parentNode.removeChild(getObj("invoice_payment_discount"));
//    getObj("invoice_payment_trid").parentNode.removeChild(getObj("invoice_payment_disc_blanrow"));
 
    getObj("tot_Invoice_Discount").value =0;    
    getObj("invoice_Discount_DiscountID").value ="";    
    if(getObj("invoice_Discount_cost")){getObj("invoice_Discount_cost").value = 0;}
    if(getObj("invoice_Discount_total")){getObj("invoice_Discount_total").value = 0;}


        var subtotal = parseFloat(getObj("subTotal").innerHTML);        
         var newtotal = 0 ;
         if(getObj("tot_Invoice_Adjusment")!=null)
        {           
            var totadjusrowCnt = parseInt(getObj("tot_Invoice_Adjusment").value );
            for(var k=1;k<=totadjusrowCnt;k++)
            {   
                var adjusval = getObj("invoice_adjusment_total__"+k).value;                
                newtotal = parseFloat(newtotal)-parseFloat(adjusval) ; 
             }
        }  
         var fftotal = 0;
         if(getObj("tot_Invoice_Addinfo")!=null)
         {           
         	 
             var totadjusrowCnt = parseInt(getObj("tot_Invoice_Addinfo").value );
             for(var k=1;k<=totadjusrowCnt;k++)
             {                                
                 var adjusval = getObj("invoice_Addinfo_total__"+k).value;                            
                 fftotal = parseFloat(fftotal)+parseFloat(adjusval) ;                             
             }
         }
        getObj("hdnGrandTotal").value =getObj("grandTotal").innerHTML= parseFloat(subtotal)-  parseFloat(newtotal)+parseFloat(fftotal);
        if(getObj("hdnBalanceDue")!=null)
        {
                getObj("hdnBalanceDue").value=getObj("hdnGrandTotal").value
        }
        if(getObj("remainingamount")!=null)
        {
            getObj("remainingamount").innerHTML = parseFloat(getObj("hdnGrandTotal").value)-parseFloat(getObj("payment").innerHTML)
        }

    getObj("invoice_payment_discountdivid").style.display="block";
}
function addinvoiceDiscount()
{   
    showLookUp('invoice_Discount_DiscountID','DiscountCode','DiscountCode','Discounts')
    return false;
}
function addinvoiceAddinfo()
{   
    showLookUp('invoice_Addinfo_LineitemID','Item','Item','Additional Item')
    return false;
}
function calcAdjusmentTotal(currObjId) {
        
        var rowId=parseInt(currObjId.substr(currObjId.indexOf("__")+2))
        
 	var qty = getObj("invoice_adjusment_txtQty__"+rowId).value;
	var n=qty.indexOf(".");	
	if(n==-1){
        var listprice = getObj("invoice_adjusment_txtListPrice__"+rowId).value;
        qty = qty.replace(/,+/g, '');
        listprice = listprice.replace(/,+/g, '');
	var total=(qty*listprice)
        getObj("invoice_adjusment_total__"+rowId).value=(total.toString())
        calcAdjusTotal()
	}
}
function calcAddTotal(currObjId)
{
	var rowId=parseInt(currObjId.substr(currObjId.indexOf("__")+2))
    var qty = getObj("invoice_Addinfo_txtQty__"+rowId).value;
	var n=qty.indexOf(".");	
	if(n==-1){
		var listprice = getObj("invoice_Addinfo_cost__"+rowId).value;
		qty = qty.replace(/,+/g, '');
		listprice = listprice.replace(/,+/g, '');
	var total=(qty*listprice)
	getObj("invoice_Addinfo_total__"+rowId).value=(total.toString())
		 calcAdjusTotal()
	
}}
function getInvoicePaymentInfoBody() {
        if (browser_ie) {
                var prodListBody=getObj("invoice_paymentdetails_maindiv").children[0].children[0]
        } else if (browser_nn4 || browser_nn6) {
                if (getObj("invoice_paymentdetails_maindiv").childNodes.item(0).tagName=="TABLE") {
                        var prodListBody=getObj("invoice_paymentdetails_maindiv").childNodes.item(0).childNodes.item(0)
                } else {
                        var prodListBody=getObj("invoice_paymentdetails_maindiv").childNodes.item(1).childNodes.item(1)
                }
        }
        return prodListBody;
        
}
function addinvoiceAdjusment()
{
    var tot_Invoice_Adjusment = getObj("tot_Invoice_Adjusment").value;       
    var adjusrowCnt = parseInt(tot_Invoice_Adjusment)+1 ;
    
    var newRow="<tr id=invoice_payment_adjusment__"+adjusrowCnt+">";
    newRow+="<td class='tableData' width='25%'><input id='invoice_adjusment_item__"+adjusrowCnt+"' name='property(invoice_adjusment_item__"+adjusrowCnt+")' type='text' size='12' maxlength='120' class='detailedViewTextBox' > </td>"
    newRow+="<td class='tableData' width='30%'><input type=text id='invoice_adjusment_Desc__"+adjusrowCnt+"' name='property(invoice_adjusment_Desc__"+adjusrowCnt+")'   value=''   class='detailedViewTextBox'></td>";
    newRow+="<td class='tableData' width='10%'><input type=text id='invoice_adjusment_txtQty__"+adjusrowCnt+"' name='property(invoice_adjusment_txtQty__"+adjusrowCnt+")' size='7' maxlength='9' readonly class='detailedViewTextBoxDisabled' value='1'></td>";
    newRow+="<td class='tableData' width='15%' align='right'><input type=text id='invoice_adjusment_txtListPrice__"+adjusrowCnt+"' name='property(invoice_adjusment_txtListPrice__"+adjusrowCnt+")' size='10' maxlength='19' onBlur='calcAdjusmentTotal(this.id)' class='detailedViewTextBox' style='width:90%;text-align:right;padding-right:5px;'></td>";
    newRow+="<td class='tableData' width='15%' align='right'><input type=text id='invoice_adjusment_total__"+adjusrowCnt+"' name='property(invoice_adjusment_total__"+adjusrowCnt+")' readonly value='' class='detailedViewTextBoxDisabled' style='text-align:right;padding-right:5px;'></td>";
    newRow+="<td class='tableData' width='5%'><img id='adjusment_delRow__"+adjusrowCnt+"' align='absmiddle' title='Delete Row' src='/crm/images/del.gif'  onclick='DeleteInvoiceAdjusments(this.id)' class='pointer'></td>";
    newRow+="</tr>";

    var prodListBody=getInvoicePaymentInfoBody();


    var totadjusrowCnt = getObj("tot_Invoice_Adjusment").value;    
    if (browser_nn4 || browser_nn6) 
    {
        if(totadjusrowCnt > 0)
        {
            var item=new Array(totadjusrowCnt-1)                        
            var desc=new Array(totadjusrowCnt-1)
            var qty=new Array(totadjusrowCnt-1)
            var cost=new Array(totadjusrowCnt-1)
            var total=new Array(totadjusrowCnt-1)
            for (var i=1,k=0;i<=totadjusrowCnt;i++,k++)
            {
                item[k]=getObj("invoice_adjusment_item__"+i).value
                desc[k]=getObj("invoice_adjusment_Desc__"+i).value
                qty[k]=getObj("invoice_adjusment_txtQty__"+i).value
                cost[k]=getObj("invoice_adjusment_txtListPrice__"+i).value
                total[k]=getObj("invoice_adjusment_total__"+i).value
            }
        }
    }

    var listTableStart="<table width='100%' border='0' cellspacing='0' cellpadding='0' class='formBorder' style='bgcolor:#f9f9f9;'>"                    
    getObj("invoice_paymentdetails_maindiv").innerHTML=listTableStart+prodListBody.innerHTML+newRow+"<tr><td colSpan='8' class='tableRowSep'></td></tr></table>"

    if (browser_nn4 || browser_nn6) 
    {
        if(totadjusrowCnt > 0)
        {
            for (var i=1,k=0;i<=totadjusrowCnt;i++,k++) 
            {
                getObj("invoice_adjusment_item__"+i).value=item[k]
                getObj("invoice_adjusment_Desc__"+i).value=desc[k]
                getObj("invoice_adjusment_txtQty__"+i).value=qty[k]
                getObj("invoice_adjusment_txtListPrice__"+i).value=cost[k]
                getObj("invoice_adjusment_total__"+i).value=total[k]
            }   
        }
    }

    getObj("tot_Invoice_Adjusment").value = parseInt(tot_Invoice_Adjusment)+1 ;
}

function DeleteInvoiceAdjusments(id)
{
    var rowId = parseInt(id.substr(18));    
    getObj("invoice_payment_adjusment__"+rowId).parentNode.removeChild(getObj("invoice_payment_adjusment__"+rowId));

    var prodListBody=getInvoicePaymentInfoBody();

    var totadjusrowCnt = parseInt(getObj("tot_Invoice_Adjusment").value );
    var newInnerHTML="<tr class='dynamicsegqbhead'  id='invoice_payment_trid'>"+getObj("invoice_payment_trid").innerHTML+"</tr>";
        newInnerHTML+="<tr><td colspan=6><div id ='invoice_payment_pricedetailsdivId'>"+document.getElementById("invoice_payment_pricedetailsdivId").innerHTML+"</div></td></tr>";
    var rowArray=new Array(totadjusrowCnt-1);
    if (browser_nn4 || browser_nn6) 
    {
        var item=new Array(totadjusrowCnt-1)
        var desc=new Array(totadjusrowCnt-1)
        var qty=new Array(totadjusrowCnt-1)
        var cost=new Array(totadjusrowCnt-1)
        var total=new Array(totadjusrowCnt-1)
    }
    for (var i=1,k=0;i<=rowId-1;i++,k++) {
        if (i%2==0) var rowClass="evenListRow";
        else var rowClass="oddListRow";
        rowArray[k]="<tr id='invoice_payment_adjusment__"+i+"' class='"+rowClass+"'>"+getObj("invoice_payment_adjusment__"+i).innerHTML+"</tr><tr id='tableline'><td colSpan='8' class='tableRowSep'></td></tr>";
        newInnerHTML+=rowArray[k];
        if (browser_nn4 || browser_nn6) 
        {
            item[k]=getObj("invoice_adjusment_item__"+i).value
            desc[k]=getObj("invoice_adjusment_Desc__"+i).value
            qty[k]=getObj("invoice_adjusment_txtQty__"+i).value
            cost[k]=getObj("invoice_adjusment_txtListPrice__"+i).value
           total[k]=getObj("invoice_adjusment_total__"+i).value
        }
    }

     for (var i=rowId+1;i<=totadjusrowCnt;i++,k++) 
    {
        rowArray[k]=getObj("invoice_payment_adjusment__"+i).innerHTML;
        var temp=rowArray[k];
        temp = replaceAll(temp,'__'+i, '__'+(i-1));

        if ((i-1)%2==0) var rowClass="evenListRow";
        else var rowClass="oddListRow";
        rowArray[k]="<tr id='invoice_payment_adjusment__"+(i-1)+"' class='"+rowClass+"'>"+temp+"</tr><tr id='tableline'><td colSpan='8' class='tableRowSep'></td></tr>";
        newInnerHTML+=rowArray[k];
        if (browser_nn4 || browser_nn6) {
            item[k]=getObj("invoice_adjusment_item__"+i).value
            desc[k]=getObj("invoice_adjusment_Desc__"+i).value
            qty[k]=getObj("invoice_adjusment_txtQty__"+i).value
            cost[k]=getObj("invoice_adjusment_txtListPrice__"+i).value
            total[k]=getObj("invoice_adjusment_total__"+i).value
        }           
    }
    
    var listTableStart="<table width='100%' border='0' cellspacing='0' cellpadding='0' class='formBorder' style='bgcolor:#f9f9f9;'>"
    getObj("invoice_paymentdetails_maindiv").innerHTML=listTableStart+newInnerHTML+"</table>";

    totadjusrowCnt--; 

    for (var i=1,k=0;i<=totadjusrowCnt;i++,k++) 
    {
            if (browser_nn4 || browser_nn6) {
               getObj("invoice_adjusment_item__"+i).value=item[k]
               getObj("invoice_adjusment_Desc__"+i).value=desc[k]
               getObj("invoice_adjusment_txtQty__"+i).value=qty[k]
               getObj("invoice_adjusment_txtListPrice__"+i).value=cost[k]
               getObj("invoice_adjusment_total__"+i).value=total[k]
            }
    }


    var totadjusrowCnt = parseInt(getObj("tot_Invoice_Adjusment").value );
    getObj("tot_Invoice_Adjusment").value =totadjusrowCnt -1 ;

    calcAdjusTotal();
}
function calcAdjusTotal(id)
{
	
    var newtotal = parseFloat(getObj("subTotal").innerHTML) ;

    var totadjusrowCnt = parseInt(getObj("tot_Invoice_Adjusment").value );
    var totaddinforowCnt =  parseInt(getObj("tot_Invoice_Addinfo").value);
   
    for(var k=1;k<=totadjusrowCnt;k++)
    {   
        var adjusval = getObj("invoice_adjusment_total__"+k).value;                
        newtotal = parseFloat(newtotal)+parseFloat(adjusval) ; 
    }
    if(getObj("invoice_Discount_total")!=null)
    {        
        newtotal = parseFloat(newtotal) - parseFloat(getObj("invoice_Discount_cost").value)
    }
    if(totaddinforowCnt>0)
    {
    for(var k=1;k<=totaddinforowCnt;k++)
    {   
        var addval = getObj("invoice_Addinfo_total__"+k).value;
        newtotal = parseFloat(newtotal)+parseFloat(addval) ;
            }}
        getObj("hdnGrandTotal").value =getObj("grandTotal").innerHTML= parseFloat(newtotal);
        if(getObj("hdnBalanceDue")!=null)
        {
                getObj("hdnBalanceDue").value=getObj("hdnGrandTotal").value
        }
        if(getObj("remainingamount")!=null)
        {
            getObj("remainingamount").innerHTML = parseFloat(getObj("hdnGrandTotal").value)-parseFloat(getObj("payment").innerHTML)
        }
}

function discountLookupSetValue(val,id,desc,doubleVal,type,fldName,fldId,pgmpriceTotal) 
{
    val=unescape(val); 
    desc=unescape(desc);
    desc = replaceAll(desc,"'","&#39");
    var lookUpModule=getOpenerObj("module").value    
    var rowId=fldName.substr(32);
    var dicountval = parseFloat(doubleVal);    
    var hdnAmtType = type;
    if(type == "percentage")
    {
        dicountval = parseFloat(pgmpriceTotal) * (dicountval/100)        
        pgmpriceTotal = parseFloat(pgmpriceTotal)-parseFloat(dicountval);
    }else
    {
        pgmpriceTotal = parseFloat(pgmpriceTotal)-parseFloat(doubleVal);
    }

    if(lookUpModule == "Iterations" )
    {
       var discountrowCnt = parseInt(getOpenerObj("tot_discount__codes").value );
       discountrowCnt = discountrowCnt+1;
        
       var totdistrowCnt = discountrowCnt ;
        
       if (totdistrowCnt%2==0)
           var newRow="<tr id=DC__hrow__"+totdistrowCnt+" class='evenListRow'>"
       else
           var newRow="<tr id=DC__hrow__"+totdistrowCnt+" class='oddListRow'>"

        newRow+="<td style='padding:3px;' class='tableData'><input id='DiscountCode_Discount__"+discountrowCnt+"' name='property(DiscountCode_Discount__"+discountrowCnt+")' type='text' size='12' maxlength='120' class='detailedViewTextBoxDisabled' readonly value='"+val+"' style='width:70%' > <input id='DiscountCode_DiscountID_lookup__"+discountrowCnt+"' name='property(DiscountCode_DiscountID_lookup__"+discountrowCnt+")' type='hidden' value='"+id+"' > </td>"
        newRow+="<td style='padding:3px;' class='tableData'><input type=text id='DiscountCode_Description__"+discountrowCnt+"' name='property(DiscountCode_Description__"+discountrowCnt+")'  readonly value='"+desc+"'   class='detailedViewTextBoxDisabled'></td>"
        newRow+="<td style='padding:3px;' class='tableData'><input type=text id='DiscountCode_Amount__"+discountrowCnt+"' name='property(DiscountCode_Amount__"+discountrowCnt+")'  readonly value='"+parseFloat(doubleVal)+"'   class='detailedViewTextBoxDisabled' style='width:70%;text-align:right;padding-right:5px;'></td>"
        newRow+="<td style='padding:3px;' class='tableData'><input type=text id='DiscountCode_PgmPrice__"+discountrowCnt+"' name='property(DiscountCode_PgmPrice__"+discountrowCnt+")' readonly  class='detailedViewTextBoxDisabled' value='"+parseFloat(pgmpriceTotal)+"' style='width:70%;text-align:right;padding-right:5px;'> <input type=hidden id='DiscountCode_hdnAmtType__"+discountrowCnt+"' name='property(DiscountCode_hdnAmtType__"+discountrowCnt+")' value='"+hdnAmtType+"' ></td>"   
        newRow+="<td style='padding:3px;' class='tableData'><img id='DiscountCode_delRow__"+discountrowCnt+"' align='absmiddle' title='Delete Row' src='/crm/images/del.gif'  onclick='DiscountCodedelRow(this.id)' class='pointer'></td>"
        newRow+="</tr>"
   
        var prodListBody=getDiscountCodeLookupBody()
        if (browser_nn4 || browser_nn6) 
        {
            var discount=new Array(totdistrowCnt-1)
            var discountId=new Array(totdistrowCnt-1)
            var desc=new Array(totdistrowCnt-1)
            var amt=new Array(totdistrowCnt-1)
            var pgmprice=new Array(totdistrowCnt-1)
            for (var i=1,k=0;i<=rowCnt-1;i++,k++)
            {
                discount[k]=getOpenerObj("DiscountCode_Discount__"+i).value
                discountId[k]=getOpenerObj("DiscountCode_DiscountID_lookup__"+i).value
                desc[k]=getOpenerObj("DiscountCode_Description__"+i).value
                amt[k]=getOpenerObj("DiscountCode_Amount__"+i).value
                pgmprice[k]=getOpenerObj("DiscountCode_PgmPrice__"+i).value
           }
        }
        var listTableStart="<table width='100%' border='0' cellspacing='0' cellpadding='0' class='formBorder' style='bgcolor:#f9f9f9;'>"
        getOpenerObj("DiscountCode_Discounts").innerHTML=listTableStart+prodListBody.innerHTML+newRow+"<tr><td colSpan='8' class='tableRowSep'></td></tr></table>"
        if (browser_nn4 || browser_nn6) 
        {
            for (var i=1,k=0;i<=rowCnt-1;i++,k++) 
            {
               getOpenerObj("DiscountCode_Discount__"+i).value=discount[k]
               getOpenerObj("DiscountCode_DiscountID_lookup__"+i).value=discountId[k]
               getOpenerObj("DiscountCode_Description__"+i).value=desc[k]
               getOpenerObj("DiscountCode_Amount__"+i).value=amt[k]
               getOpenerObj("DiscountCode_PgmPrice__"+i).value=pgmprice[k]
           }
        }
        getOpenerObj("tot_discount__codes").value = discountrowCnt;
    }
                if(lookUpModule == "Invoices" )
                {
                    var newRow = "<tr id=invoice_payment_discount>";
                    newRow+="<td class='tableData' width='25%'><input id='invoice_Discount' name='property(invoice_Discount)' type='text' size='12' maxlength='120' class='detailedViewTextBoxDisabled' readonly value='' style='width:90%'></td>";
                    newRow+="<td class='tableData' width='30%'><input type=text id='invoice_Discount_Description' name='property(invoice_Discount_Description)'  readonly value=''   class='detailedViewTextBoxDisabled'></td>";
                    newRow+="<td class='tableData' width='10%'><input type=text id='invoice_Discount_qty' name='property(invoice_Discount_qty)'  readonly value='1'   class='detailedViewTextBoxDisabled'></td>";
                    newRow+="<td class='tableData' width='15%' align='right'><input type=text id='invoice_Discount_cost' name='property(invoice_Discount_cost)'  readonly value='' style='text-align:right;padding-right:5px;' class='detailedViewTextBoxDisabled'></td>";
                    newRow+="<td class='tableData' width='15%' align='right'><input type=text id='invoice_Discount_total' name='property(invoice_Discount_total)'  readonly value='' style='text-align:right;padding-right:5px;' class='detailedViewTotalTextBox'></td>";
                    newRow+="<td class='tableData' width='5%'><img id='DiscountCode_delRow' align='absmiddle' title='Delete Row' src='/crm/images/del.gif'  onclick='DeleteInvoiceDiscountCode(this.id)' class='pointer'></td>";
                    newRow+="</tr>"
                    var listTableStart="<table width='100%' border='0' cellspacing='0' cellpadding='0' class='formBorder' style='bgcolor:#f9f9f9;'>"
                    
                    getOpenerObj("invoice_paymentinfo_discountmaindiv").innerHTML=listTableStart+newRow+"<tr id=invoice_payment_disc_blanrow><td colSpan='8' class='tableRowSep'></td></tr></table>"
                    
                    getOpenerObj("tot_Invoice_Discount").value = 1;
                    getOpenerObj("invoice_payment_discountdivid").style.display="none";
                    
                    getOpenerObj("invoice_Discount").value = val
                    getOpenerObj("invoice_Discount_DiscountID").value = id
                    getOpenerObj("invoice_Discount_Description").value = desc

                    var subtotal = parseFloat(getOpenerObj("subTotal").innerHTML);
                    var dicountval = parseFloat(doubleVal);    
                    if(type == "percentage")
                    {
                        dicountval = (subtotal*(dicountval/100))            
                    }

                    getOpenerObj("invoice_Discount_cost").value = parseFloat(dicountval)
                    getOpenerObj("invoice_Discount_total").value = - (parseFloat(dicountval))       


                     var newtotal = 0 ;
                     if(getOpenerObj("tot_Invoice_Adjusment")!=null)
                    {           
                        var totadjusrowCnt = parseInt(getOpenerObj("tot_Invoice_Adjusment").value );
                        for(var k=1;k<=totadjusrowCnt;k++)
                        {                                
                            var adjusval = getOpenerObj("invoice_adjusment_total__"+k).value;                            
                            newtotal = parseFloat(newtotal)+parseFloat(adjusval) ;                             
                        }
                    }
                     var fftotal=parseFloat(subtotal)- (parseFloat(dicountval) - parseFloat(newtotal));
                     if(getOpenerObj("tot_Invoice_Addinfo")!=null)
                     {           
                     	 
                         var totadjusrowCnt = parseInt(getOpenerObj("tot_Invoice_Addinfo").value );
                         for(var k=1;k<=totadjusrowCnt;k++)
                         {                                
                             var adjusval = getOpenerObj("invoice_Addinfo_total__"+k).value;                            
                             fftotal = parseFloat(fftotal)+parseFloat(adjusval) ;                             
                         }
                     }
                    
                    getOpenerObj("hdnGrandTotal").value =getOpenerObj("grandTotal").innerHTML= parseFloat(fftotal);//parseFloat(subtotal)- (parseFloat(dicountval) - parseFloat(newtotal));
                    if(getOpenerObj("hdnBalanceDue")!=null)
                    {
                            getOpenerObj("hdnBalanceDue").value=getOpenerObj("hdnGrandTotal").value
                    }
                    if(getOpenerObj("remainingamount")!=null)
                    {
                        getOpenerObj("remainingamount").innerHTML = parseFloat(getOpenerObj("hdnGrandTotal").value)-parseFloat(getOpenerObj("payment").innerHTML)
                    }
                }
    window.self.close()
}

function lineitemLookupSetValue(val,id,desc,doubleVal,fldName,fldId,pgmpriceTotal) 
{
	var dis = parseInt(getOpenerObj("tot_Invoice_Addinfo").value);
	
	dis = dis + 1;
	
	var totdis = dis;
	if(totdis%2==0)
	var newRow = "<tr id=invoice_paymentA_discount"+totdis+" class='evenListRow'>"
	else
	var newRow = "<tr id=invoice_paymentA_discount"+totdis+" class='oddListRow'>"	
	
    newRow+="<td class='tableData' width='25%'><input id='invoice_Addinfo_Lineitem__"+dis+"' name='property(invoice_Addinfo_Lineitem__"+dis+")' type='text' size='12' maxlength='120' class='detailedViewTextBoxDisabled' readonly value='"+(unescape(val))+"' style='width:90%'><input id='LineItem_LineItemID_lookup__"+dis+"' name='property(LineItem_LineItemID_lookup__"+dis+")' type='hidden' value='"+id+"' ></td>";
    newRow+="<td class='tableData' width='30%'><input type=text id='invoice_Addinfo_Description__"+dis+"' name='property(invoice_Addinfo_Description__"+dis+")'  readonly value='"+desc+"'   class='detailedViewTextBoxDisabled'></td>";
    newRow+="<td class='tableData' width='10%'><input type=text id='invoice_Addinfo_txtQty__"+dis+"' name='property(invoice_Addinfo_txtQty__"+dis+")' size='7' value='1' maxlength='9' onBlur='calcAddTotal(this.id)' class='detailedViewTextBoxDisabled' ></td>";
    newRow+="<td class='tableData' width='15%' align='right'><input type=text id='invoice_Addinfo_cost__"+dis+"' name='property(invoice_Addinfo_cost__"+dis+")'  readonly value='"+parseFloat(doubleVal)+"'    class='detailedViewTextBoxDisabled' style='text-align:right;padding-right:5px;'></td>";
    newRow+="<td class='tableData' width='15%' align='right'><input type=text id='invoice_Addinfo_total__"+dis+"' name='property(invoice_Addinfo_total__"+dis+")' readonly  value='"+parseFloat(doubleVal)+"' class='detailedViewTextBoxDisabled' style='text-align:right;padding-right:5px;'></td>";
    newRow+="<td class='tableData' width='5%'><img id='LineItem_delRow__"+dis+"' align='absmiddle' title='Delete Row' src='/crm/images/del.gif'  onclick='LineItemdelRow(this.id)' class='pointer'></td>";
    newRow+="</tr>"
    	 var prodListBody=getDiscountCodeALookupBody()
    	 if (browser_nn4 || browser_nn6) 
         {
        	
             var lineitem=new Array(totdis-1)
             var lineitemId=new Array(totdis-1)
             var desc=new Array(totdis-1)
             var cost=new Array(totdis-1)
             var qt=new Array(totdis-1)
             var total=new Array(totdis-1)
             for (var i=1,k=0;i<=rowCnt-1;i++,k++)
             {
            	
                 lineitem[k]=getOpenerObj("invoice_Addinfo_Lineitem__"+i).value
                 lineitemId[k]=getOpenerObj("LineItem_LineItemID_lookup__"+i).value
                 desc[k]=getOpenerObj("invoice_Addinfo_Description__"+i).value
                 cost[k]=getOpenerObj("invoice_Addinfo_cost__"+i).value
                 qt[k]=getOpenerObj("invoice_Addinfo_txtQty__"+i).value
                 alert("qty=="+getOpenerObj("invoice_Addinfo_txtQty__"+i).value)
                 total[k]=getOpenerObj("invoice_Addinfo_total__"+i).value
                 
            }
             
        	 
         }
    var listTableStart="<table width='100%' border='0' cellspacing='0' cellpadding='0' class='formBorder' style='bgcolor:#f9f9f9;'>"
    
    getOpenerObj("invoice_paymentaddinfo_discountmaindiv").innerHTML=listTableStart+prodListBody.innerHTML+newRow+"<tr><td colSpan='8' class='tableRowSep'></td></tr></table>"
    if (browser_nn4 || browser_nn6) 
    {
    	
        for (var i=1,k=0;i<=rowCnt-1;i++,k++) 
        {
        	getOpenerObj("invoice_Addinfo_Lineitem__"+i).value=lineitem[k]
        	getOpenerObj("LineItem_LineItemID_lookup__"+i).value=lineitemId[k]
            getOpenerObj("invoice_Addinfo_Description__"+i).value=desc[k]
            getOpenerObj("invoice_Addinfo_cost__"+i).value=cost[k]
            getOpenerObj("invoice_Addinfo_txtQty__"+i).value=qt[k]
            getOpenerObj("invoice_Addinfo_total__"+i).value=total[k]
    }
    }
    getOpenerObj("tot_Invoice_Addinfo").value = dis;
     window.self.close()
    var newtotal = 0;
    var subtotal = parseFloat(getOpenerObj("subTotal").innerHTML);
    if(getOpenerObj("tot_Invoice_Adjusment")!=null)
    {           
        var totadjusrowCnt = parseInt(getOpenerObj("tot_Invoice_Adjusment").value );
        for(var k=1;k<=totadjusrowCnt;k++)
        {                                
            var adjusval = getOpenerObj("invoice_adjusment_total__"+k).value;                            
            newtotal = parseFloat(newtotal)+parseFloat(adjusval) ;                             
        }
    }
     var fftotal = parseFloat(newtotal)+parseFloat(subtotal);
     if(getOpenerObj("invoice_Discount_total")!=null)
     {        
    	 fftotal = parseFloat(fftotal) - parseFloat(getOpenerObj("invoice_Discount_cost").value)
      }
                 if(getOpenerObj("tot_Invoice_Addinfo")!=null)
                     {           
                     	 
                         var totadjusrowCnt = parseInt(getOpenerObj("tot_Invoice_Addinfo").value );
                         for(var k=1;k<=totadjusrowCnt;k++)
                         {                                
                             var adjusval = getOpenerObj("invoice_Addinfo_total__"+k).value;                            
                             fftotal = parseFloat(fftotal)+parseFloat(adjusval) ;                             
                         }
                     }
                    
                    getOpenerObj("hdnGrandTotal").value =getOpenerObj("grandTotal").innerHTML= parseFloat(fftotal);
                    if(getOpenerObj("hdnBalanceDue")!=null)
                    {
                            getOpenerObj("hdnBalanceDue").value=getOpenerObj("hdnGrandTotal").value
                    }
                    if(getOpenerObj("remainingamount")!=null)
                    {
                        getOpenerObj("remainingamount").innerHTML = parseFloat(getOpenerObj("hdnGrandTotal").value)-parseFloat(getOpenerObj("payment").innerHTML)
                    }
                   
      	}




function getInvoicePaymentInfoLookupBody() {
        if (browser_ie) {
                var prodListBody=getOpenerObj("invoice_paymentdetails_maindiv").children[0].children[0]
        } else if (browser_nn4 || browser_nn6) {
                if (getOpenerObj("invoice_paymentdetails_maindiv").childNodes.item(0).tagName=="TABLE") {
                        var prodListBody=getOpenerObj("invoice_paymentdetails_maindiv").childNodes.item(0).childNodes.item(0)
                } else {
                        var prodListBody=getOpenerObj("invoice_paymentdetails_maindiv").childNodes.item(1).childNodes.item(1)
                }
        }
        return prodListBody;
        
}


function getDiscountCodeLookupBody() {
        if (browser_ie) {
                var prodListBody=getOpenerObj("DiscountCode_Discounts").children[0].children[0]
        } else if (browser_nn4 || browser_nn6) {
                if (getOpenerObj("DiscountCode_Discounts").childNodes.item(0).tagName=="TABLE") {
                        var prodListBody=getOpenerObj("DiscountCode_Discounts").childNodes.item(0).childNodes.item(0)
                } else {
                        var prodListBody=getOpenerObj("DiscountCode_Discounts").childNodes.item(1).childNodes.item(1)
                }
        }
        return prodListBody;
        
}
function getLineItemBody() {
    if (browser_ie) {
            var prodListBody=getObj("invoice_paymentaddinfo_discountmaindiv").children[0].children[0]
    } else if (browser_nn4 || browser_nn6) {
            if (getObj("invoice_paymentaddinfo_discountmaindiv").childNodes.item(0).tagName=="TABLE") {
                    var prodListBody=getObj("invoice_paymentaddinfo_discountmaindiv").childNodes.item(0).childNodes.item(0)
            } else {
                    var prodListBody=getObj("invoice_paymentaddinfo_discountmaindiv").childNodes.item(1).childNodes.item(1)
            }
    }
    return prodListBody;
    
}
function getDiscountCodeALookupBody() {
    if (browser_ie) {
            var prodListBody=getOpenerObj("invoice_paymentaddinfo_discountmaindiv").children[0].children[0]
    } else if (browser_nn4 || browser_nn6) {
            if (getOpenerObj("invoice_paymentaddinfo_discountmaindiv").childNodes.item(0).tagName=="TABLE") {
                    var prodListBody=getOpenerObj("invoice_paymentaddinfo_discountmaindiv").childNodes.item(0).childNodes.item(0)
            } else {
                    var prodListBody=getOpenerObj("invoice_paymentaddinfo_discountmaindiv").childNodes.item(1).childNodes.item(1)
            }
    }
    return prodListBody;
    
}

function DFAddValidatorForRequirementsUpload(uploadFieldId)
{
	var uploadField = document.getElementById(uploadFieldId);

	_IW.FormValidator.insertValidator(uploadFieldId, 
		function() {
			if (uploadField.files.length)
				return true;
			if (eval(uploadFieldId + "_nFiles"))
				return true;
			return false;
		}, 
		function() {
			alert("You must upload a file");
			uploadField.focus();
	});
}
function assignMe(rule,index)
{
 	if(rule.value=="User")
	{
		document.getElementById('assignTo'+index).style.display='block';
		document.getElementById('assign'+index).style.display='block';
		document.getElementById('rule'+index).style.display='none';
		document.getElementById('assRule'+index).style.display='none';
	}
	else
	{
		document.getElementById('assignTo'+index).style.display='none';
		document.getElementById('assign'+index).style.display='none';
		document.getElementById('rule'+index).style.display='block';
		document.getElementById('assRule'+index).style.display='block';
	}
}
