
/*
  Qry Builder related moveing fn starting
*/ 

// The actual number is 20, but there are 2 TRs for 1 rule in the HTML
var MAX_NUMBER_OF_JOINS = 40;
var MAX_NUMBER_OF_JOINS1 = 20;
var MAX_NUMBER_OF_TARGETS = 5;
var MAX_JOINS_EXCEEDED_ERROR_MESSAGE = "You have exceeded the max no of Joins"
var MAX_TARGETS_EXCEEDED_ERROR_MESSAGE = "You have exceeded the max no of Targets"
var act=0;
var a = 1;
function callclone(id)
{
   var trobj = id;
    var coll = trobj.parentNode.getElementsByTagName("tr");
   
    if(coll.length >= MAX_NUMBER_OF_JOINS)
    {
        alert(MAX_JOINS_EXCEEDED_ERROR_MESSAGE);
        return false;
        
    }
  
     var id_last=0;   
    for(m=0;m< coll.length;m++){
        if(coll[m].id.toString().indexOf("clone")>=0){            
            var escvar =  coll[m].id.toString();           
             var id_last = parseInt(escvar.substr(escvar.indexOf("_") + 1, escvar.length));           
             }
    }    
   
    var tableBodyObj=getObj('tableBodyId');
    var newobj=trobj.cloneNode(true);
    newobj.id = "cloneid_"+(id_last+1);
    
     setId(newobj,id_last+1)
	tableBodyObj.appendChild(newobj);

	
	getObj("row").value=id_last+1;
	getObj("value_"+(id_last+1)).value="";
	if(getObj("datefld_"+(id_last+1)) && getObj("cal"+(id_last+1)))
	{
		getObj("datefld_"+(id_last+1)).value="";
		getObj("cal"+(id_last+1)).value="";
		addCalendar("Calendar"+(id_last+1),"Select Date","datefld_"+(id_last+1),Search.calform)
	}

	if(getObj("datetime_"+(id_last+1)) && getObj("timeval_"+(id_last+1))&& getObj("caal"+(id_last+1)))
	{
		getObj("datetime_"+(id_last+1)).value="";
		getObj("timeval_"+(id_last+1)).value="";
		getObj("caal"+(id_last+1)).value="";
		addCalendar("CalendarDT"+(id_last+1),"Select Date","datetime_"+(id_last+1),Search.calform)
	}
	getObj("logic_"+(id_last+1)).value="";
	getObj("logic_"+(id_last+1)).readOnly=false;
	getObj("endlogic_"+(id_last+1)).value="";
	getObj("endlogic_"+(id_last+1)).readOnly=false;
	getObj("joinid_"+(id_last+1)).disabled=false;
	callRelatedField("relatedmodule_"+(id_last+1));
	Search.changeField("searchfield_"+(id_last+1));
	var joinSeldivObj = newobj.getElementsByTagName("DIV");
	showJoinSelectObj(joinSeldivObj,id_last+1);
}

function callclone1(id)
{
   var trobj = id;
    var coll = trobj.parentNode.getElementsByTagName("tr");
   
    if(coll.length >= MAX_NUMBER_OF_JOINS1)
    {
        alert(MAX_JOINS_EXCEEDED_ERROR_MESSAGE);
        return false;
        
    }
  
     var id_last=0;   
    for(m=0;m< coll.length;m++){
        if(coll[m].id.toString().indexOf("clone")>=0){            
            var escvar =  coll[m].id.toString();           
             var id_last = parseInt(escvar.substr(escvar.indexOf("_") + 1, escvar.length));           
             }
    }    
   
    var tableBodyObj=getObj('tableBodyId');
    var newobj=trobj.cloneNode(true);
    newobj.id = "cloneid_"+(id_last+1);
    
     setId(newobj,id_last+1)


	tableBodyObj.appendChild(newobj);
getObj("row").value=id_last+1;
getObj("value_"+(id_last+1)).value="";
getObj("timeval_"+(id_last+1)).value="";
getObj("logic_"+(id_last+1)).value="";
getObj("endlogic_"+(id_last+1)).value="";
callRelatedField("relatedmodule_"+(id_last+1));
Search.changeField("searchfield_"+(id_last+1));
var joinSeldivObj = newobj.getElementsByTagName("DIV");
showJoinSelectObj(joinSeldivObj,id_last+1);
}


function callclone2(id)
{

   var trobj = id;
    var coll = trobj.parentNode.getElementsByTagName("tr");
   
    if((coll.length-1) >= MAX_NUMBER_OF_TARGETS)
    {
        alert(MAX_TARGETS_EXCEEDED_ERROR_MESSAGE);
        return false;
        
    }
  
     var id_last=0;   
    for(m=0;m< coll.length;m++){
        if(coll[m].id.toString().indexOf("clone")>=0){            
            var escvar =  coll[m].id.toString();           
             var id_last = parseInt(escvar.substr(escvar.indexOf("_") + 1, escvar.length));           
             }
    }    
   
    var tableBodyObj=getObj('tableBodyId');
    var newobj=trobj.cloneNode(true);
    newobj.id = "cloneid_"+(id_last+1);
    
     setIdForCampaign(newobj,id_last+1,true)
	tableBodyObj.appendChild(newobj);

	
	getObj("row").value=id_last+1;

	/*getObj("value_"+(id_last+1)).value="";
	if(getObj("datefld_"+(id_last+1)) && getObj("cal"+(id_last+1)))
	{
		getObj("datefld_"+(id_last+1)).value="";
		getObj("cal"+(id_last+1)).value="";
		addCalendar("Calendar"+(id_last+1),"Select Date","datefld_"+(id_last+1),Search.calform)
	}

	if(getObj("datetime_"+(id_last+1)) && getObj("timeval_"+(id_last+1))&& getObj("caal"+(id_last+1)))
	{
		getObj("datetime_"+(id_last+1)).value="";
		getObj("timeval_"+(id_last+1)).value="";
		getObj("caal"+(id_last+1)).value="";
		addCalendar("CalendarDT"+(id_last+1),"Select Date","datetime_"+(id_last+1),Search.calform)
	}
*/

	getObj("logic_"+(id_last+1)).value="";
	getObj("endlogic_"+(id_last+1)).value="";
	//callRelatedField("relatedmodule_"+(id_last+1));
	//Search.changeField("searchfield_"+(id_last+1));
	var joinSeldivObj = newobj.getElementsByTagName("DIV");
	showJoinSelectObj(joinSeldivObj,id_last+1);
}

// The code in this method is now in findTR, but is slightly different.
// I wish to unify it if possible as smacks 2 much of copy-paste.
function removerow(id)
{ 
     var trobj = id;
     var coll = trobj.parentNode.getElementsByTagName("tr");

    if(coll.length >3)
     {
        trobj.parentNode.removeChild(id);
     }
     else
     {
				selectone.getJSAlertValue("crm.alert.query.condition",null,"en_US",
																	function(mesg) { alert(mesg) })
        return false;
     }
    
     
     
     var t = 1;    
   for(var i=0;i < coll.length; i++)
   {

     if(coll[i].id.toString().indexOf("clone")>=0 && coll[i].id != id){     


             coll[i].id = "cloneid_"+ t;
             newobj = coll[i] ;
            setId(newobj,t);
            var joinSeldivObj = newobj.getElementsByTagName("DIV");
            showJoinSelectObj(joinSeldivObj,t);
            t++;
     }    
   }
getObj("row").value=getObj("row").value-1;

}


function removerowCampaign(id)
{ 
     var trobj = id;
     var coll = trobj.parentNode.getElementsByTagName("tr");

    if(coll.length >2)
     {
        trobj.parentNode.removeChild(id);
     }
     else
     {
				selectone.getJSAlertValue("crm.alert.query.campaign.condition",null,"en_US",
																	function(mesg) { alert(mesg) })
        return false;
     }
    
     
     
     var t = 1;    
   for(var i=0;i < coll.length; i++)
   {

     if(coll[i].id.toString().indexOf("clone")>=0 && coll[i].id != id){     


             coll[i].id = "cloneid_"+ t;
             newobj = coll[i] ;
            setIdForCampaign(newobj,t,false);
            var joinSeldivObj = newobj.getElementsByTagName("DIV");
            showJoinSelectObj(joinSeldivObj,t);
            t++;
     }    
   }
getObj("row").value=getObj("row").value-1;

}

function setId(newobj,id)
{
            var sel = newobj.getElementsByTagName("SELECT");
            var inp = newobj.getElementsByTagName("INPUT");
            var img = newobj.getElementsByTagName("IMG");
            var span = newobj.getElementsByTagName("SPAN");
            var div = newobj.getElementsByTagName("DIV");

            incrId(sel,id);
            incrId(inp,id);
            incrId(img,id);
            incrId(span,id);
            incrId(div,id);
}

function setId1(newobj,id)
{
            var sel = newobj.getElementsByTagName("SELECT");
            var inp = newobj.getElementsByTagName("INPUT");
            var img = newobj.getElementsByTagName("IMG");
            var span = newobj.getElementsByTagName("SPAN");
            var div = newobj.getElementsByTagName("DIV");

            incrId1(sel,id,"SELECT");
            incrId1(inp,id,"INPUT",false);
            incrId1(img,id,"IMG",false);
            //incrId(span,id,"SPAN");
            incrId1(div,id,"DIV",false);
}
function setIdForCampaign(newobj,id,removevalue)
{


         var sel = newobj.getElementsByTagName("SELECT");
         var inp = newobj.getElementsByTagName("INPUT");
         var img = newobj.getElementsByTagName("IMG");
         var span = newobj.getElementsByTagName("SPAN");
         var div = newobj.getElementsByTagName("DIV");


            incrId1(sel,id,"SELECT");
            incrId1(inp,id,"INPUT",removevalue);
            incrId1(img,id,"IMG",removevalue);
            //incrId(span,id,"SPAN");
            incrId1(div,id,"DIV",removevalue);
}

function incrId(el,id_last)
{
    for (var i = el.length - 1; i >= 0; i--)
    {
        var id = el[i].id;

        if (id.indexOf("_") > -1)
        {
            var prefix = id.substr(0, id.lastIndexOf("_") + 1);

            el[i].id = el[i].name = prefix + (id_last);            
        }
        else
        {
        	var prefix=id.substr(0,id.indexOf("l")+1);
        	el[i].id = el[i].name = prefix + (id_last);            
        }
       

    }
}

function incrId1(el,id_last,tagname,removevalue)
{
    for (var i = el.length - 1; i >= 0; i--)
    {
        if(tagname=='DIV')
        {
            if(el[i].title == "Target LookUp")
            {
                el[i].onclick=function(){showLookUp('target_name_'+(id_last),'targetId_'+(id_last),'target_name_'+(id_last),"Segments") };
 
            }
            else if(el[i].title == "Clear Target LookUp")
            {
                // donot think it needed
                el[i].onclick=function(){clearValue('target_name_'+(id_last),'targetId_'+(id_last)) };
            }
        }
        var id = el[i].id;
        if (id.lastIndexOf("_") > -1)
        {
            var prefix = id.substr(0, id.lastIndexOf("_") + 1);
             
            if(prefix=='targetId_' || prefix=='target_name_')
            {
                 el[i].id =  prefix + (id_last);               
                 el[i].name = "property("+prefix + (id_last)+")";            
                 if(removevalue)
                 {
                    el[i].value='';
                 }
            }
        else if(prefix=='joinid_')
            {
                 el[i].id =  prefix + (id_last);               
                 el[i].name = "property("+prefix + (id_last)+")";            
                 if(removevalue)
                 {
                    el[i].value='';
                 }
            }

    else if(prefix=='logic_' || prefix=='endlogic_')
            {
                 el[i].id =  prefix + (id_last);               
                 el[i].name = "property("+prefix + (id_last)+")";            
                 if(removevalue)
                 {
                    el[i].value='';
                 }
            }

            else
            {
                  el[i].id = el[i].name = prefix + (id_last);            
            }
        }
        else
        {
        	var prefix=id.substr(0,id.indexOf("l")+1);
        	el[i].id = el[i].name = prefix + (id_last);            
        }
       

    }
}

var m ;
var row ;

       function movedown(id)
       {
               var trobj=id;
               var coll = trobj.parentNode.getElementsByTagName("tr");
               for(var i=0;i < coll.length; i++)

               {

                       if((coll[i].id)==(trobj.id))
                       {
                                row=coll[i];
                                m=i;

                       }
               }
                if ( coll[m+2] != undefined )
               {               
                 trobj.parentNode.insertBefore(coll[m+2],row);
                 findTRAndSetID(trobj)
               }
               
               
               
               
       }

    function movedown1(id)
       {
               var trobj=id;
               var coll = trobj.parentNode.getElementsByTagName("tr");
               for(var i=0;i < coll.length; i++)

               {

                       if((coll[i].id)==(trobj.id))
                       {
                                row=coll[i];
                                m=i;

                       }
               }
                if ( coll[m+1] != undefined )
               {               
                 trobj.parentNode.insertBefore(coll[m+1],row);
                 findTRAndSetID1(trobj)
               }
               
               
               
               
       }

        function moveup(id)
        {
            var trobj=id;
            var coll = trobj.parentNode.getElementsByTagName("tr");
                for(var i=0;i < coll.length; i++)
                {
                    if((coll[i].id)==(trobj.id))
                    {
                        row=coll[i];
                        m=i;
                    }
                }
           if ( m != 1)
               {
                trobj.parentNode.insertBefore(coll[m],coll[m-2]);
                findTRAndSetID(trobj)
                }
        } 
       
        function moveup1(id)
        {
            var trobj=id;
            var coll = trobj.parentNode.getElementsByTagName("tr");
                for(var i=0;i < coll.length; i++)
                {
                    if((coll[i].id)==(trobj.id))
                    {
                        row=coll[i];
                        m=i;
                    }
                }
           if ( m != 1)
               {
                trobj.parentNode.insertBefore(coll[m],coll[m-1]);
                findTRAndSetID1(trobj)
                }
        } 

        // The code in this method was deom removerow, but is slightly different.
        // I wish to unify it if possible as smacks 2 much of copy-paste.
        
        function findTRAndSetID(trobj)
        {
            var coll = trobj.parentNode.getElementsByTagName("tr");
   
            var t = 1;    
            for(var i=0;i < coll.length; i++)
            {
                if(coll[i].id.toString().indexOf("clone")>=0)
                {
                    coll[i].id = "cloneid_"+ t;
                    newobj = coll[i] ;
                    setId(newobj,t);
                    var joinSeldivObj = newobj.getElementsByTagName("DIV");
                    showJoinSelectObj(joinSeldivObj,t);
                    t++;
                }    
            }
        }
        function findTRAndSetID1(trobj)
        {
            var coll = trobj.parentNode.getElementsByTagName("tr");
   
            var t = 1;    
            for(var i=0;i < coll.length; i++)
            {
                if(coll[i].id.toString().indexOf("clone")>=0)
                {
                    coll[i].id = "cloneid_"+ t;
                    newobj = coll[i] ;
                    setId1(newobj,t);
                    var joinSeldivObj = newobj.getElementsByTagName("DIV");
                    showJoinSelectObj(joinSeldivObj,t);
                    t++;
                }    
            }
        }



function showJoinSelectObj(el,id_last)
{

    for (var i = el.length - 1; i >= 0; i--)
    {
        var id = el[i].id;

        if (id.indexOf("joinSelDiv") > -1)
        {
            
            if(el[i].id=='joinSelDiv_1')
            {                
                document.getElementById(el[i].id).style.display="none";
            }
            else
            {
                document.getElementById(el[i].id).style.display="block";
            }
        }

    }

document.getElementById('joinSelDiv_1').style.display="none";

}
function constructQuery()
{
	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;
		}
	query=query+i;
	if(document.getElementById("endlogic_"+i).value!=null)
		{
	query=query+" "+document.getElementById("endlogic_"+i).value;
		}	
		if(document.getElementById("joinid_"+j)!=null)
		{
			if(document.getElementById("joinid_"+j).value!=null)
			{
				query=query+" "+document.getElementById("joinid_"+j).value;
			}
		}

	}
	query=query+")";
	return query;
}
function validateParanthesis()
{
	var openPar=0;
	var closePar=0;
	var rowno=getObj("row").value;
	for(var i=1;i<=rowno;i++)
	{
	if(document.getElementById("logic_"+i).value!=null)
	{
		var openValue=trimBoth(document.getElementById("logic_"+i).value);
		var openlen =openValue.length;
		var openact=0;
		for(var j=0;j<openlen;j++)
		{
			if(openValue.charAt(j)!=" ")
			{
			openact++;	
			}

		}

		openPar=openPar+openact;
	}
	if(document.getElementById("endlogic_"+i).value!=null)
	{


	var closelen =(document.getElementById("endlogic_"+i).value).length;
	var closeValue=document.getElementById("endlogic_"+i).value;
	var closeact=0;
		for(var k=0;k<closelen;k++)
		{
			if(closeValue.charAt(k)!=" " )
			{
			closeact++;
			}

		}

	closePar=closePar+closeact;

	}	

	}
	if(openPar==closePar)
	{
	return true;
	}
	else
	{ 
	return false;
	}
}

function validateOpenBracket()
{

  var rowno=getObj("row").value;
  for(var i=1;i<=rowno;i++)
  {
	if(document.getElementById("logic_"+i).value!=null)
	{
	var openValue=trimBoth(document.getElementById("logic_"+i).value);
	var openlen =openValue.length;
	
		for(var j=0;j<openlen;j++)
		{
			if(openValue.charAt(j)!=" ")
			{
			if(openValue.charAt(j)!="(" )
			{
				document.getElementById("logic_"+i).focus()	
				return false;
			}
			}

		}
	}
  }
return true;
}
function validateCloseBracket()
{
	var rowno=getObj("row").value;
  	for(var i=1;i<=rowno;i++)
  	{ 

	if(document.getElementById("endlogic_"+i).value!=null)
	{
	var closelen =(document.getElementById("endlogic_"+i).value).length;
	var closeValue=document.getElementById("endlogic_"+i).value;

		for(var k=0;k<closelen;k++)
		{
			if(closeValue.charAt(k)!=" ")
			{
			if(closeValue.charAt(k)!=")" )
			{
				document.getElementById("endlogic_"+i).focus()	
				return false;
			}
			}

		}
	}

 }
return true;
}
function validateColumn()
{
	var rowno=getObj("row").value;
  	for(var i=1;i<=rowno;i++)
  	{ 
		if((getObj("searchfield"+i).value=='None' || getObj("searchfield"+i).value=='none') && rowno > 1)
		{
			getObj("searchfield"+i).focus();
			return false;
		}
	}
	return true;
}
function callPreview(obj)
{
	var rowno=getObj("row").value;
	
	var pattern=getObj("dateFmt").value
	
	var validationSuccess = TargetValidate(obj)
	if (!validationSuccess) return false;
	
	document.getElementById("previewQuery").innerHTML="";
	document.getElementById("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;

	loadAjaxTab4("Loading...");
        var formData="";   
        formData = formData2QueryString(document.createEntityForm);
	var url ="/crm/SegmentQryPreview.do?";

	new Ajax.Request(url,{method:"post",onSuccess:function(t)
       {
	var txt=t.responseText;
	if(txt.indexOf("STACKERROR::::")>-1)
	{
	document.getElementById('ajax_load_tab').style.display='none';
	alert("Invalid query");
	}
	else
	{

		 document.getElementById("previewQuery").innerHTML="<iframe frameborder='0' style='position:absolute;z-index:-1;width:500px;height:400'></iframe><div>" + t.responseText + "</div>";
		 document.getElementById('ajax_load_tab').style.display='none';
	}
       },asynchronous:true,postBody:formData
       }); 
    return false;


}

function callPreview1(obj)
{
	var rowno=getObj("row").value;
	for(var i=1;i<=rowno;i++)
	{
	var objSearchfield=getObj("searchfieldtype_"+i);
		if(objSearchfield.value=="D" || objSearchfield.value=="DT")
		{
		if(!dateValidate("value_"+i,"Date.Date Format is MM/DD/YYYY","OTH"))
		return false;
		}
		
	}
	document.getElementById("previewQuery").innerHTML="";
	document.getElementById("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;


	loadAjaxTab4("Loading...");
        var formData="";   
        formData = formData2QueryString(document.massupdateform);
	var url ="/crm/SegmentQryPreview.do?";

	new Ajax.Request(url,{method:"post",onSuccess:function(t)
       {
	var txt=t.responseText;
	if(txt.indexOf("STACKERROR::::")>-1)
	{
	document.getElementById('ajax_load_tab').style.display='none';
	alert("Invalid query");
	}
	else
	{

		 document.getElementById("previewQuery").innerHTML="<iframe frameborder='0' style='position:absolute;z-index:-1;width:500px;height:400'></iframe><div>" + t.responseText + "</div>";
		 document.getElementById('ajax_load_tab').style.display='none';
	}
       },asynchronous:true,postBody:formData
       }); 
    return false;


}
function handlePrintPreview(obj,id,from,to)
{
        var append= "/crm/SegmentQryPreview.do?id="+id+"&FROM_INDEX="+from+"&TO_INDEX="+to+"&printview=true";
                  features="menubar=no,toolbar=no,location=no,status=no,scrollbars=yes,resizable=yes";
                  openPopUp("PrintView",obj,append,"test",600,500,features)
}
function exportAction1(obj,from,to,id,expage)
{
        if (!isWorking)
    {
        features="menubar=no,toolbar=no,location=no,status=no,scrollbars=yes,resizable=yes";
        var url ="/crm/jsp/IWPreviewSelectColumn.jsp?&FROM_INDEX="+from+"&TO_INDEX="+to+"&module=Segments&viewaction=true&id="+id+"&exportPage="+expage;
        openPopUp("ghjhjgk",obj,url,"test",600,500,features)
    }

}
function showMenu(obj)
{
        getObj("exportSegMenu").style.display="block"
        getObj("exportSegMenu").style.zIndex = "98";
        getObj("exportSegMenu").style.top="75px";
        getObj("exportSegMenu").style.left=getObj("exportSegMenu").offsetWidth;
}
//added by Jai Ganesh for the purpose of Email Bounced exclusion Preview in Edit Mode
function previewEmailBounce(obj,from)
{
	if(from == "fromEdit")
	{
		var formData="";
		formData = formData2QueryString(document.createEntityForm);
		if (!isWorking && http)
		{
			features="menubar=no,toolbar=no,location=no,status=no,scrollbars=yes,resizable=yes";
			var url ="/crm/QryPreview.do?module=Exclusions&previewType=emailBounced&formData="+formData ;
			openPopUp("ghjhjgk",obj,url,"test",600,500,features)
		}
	}
	else if(from == "fromView")
	{
		if (!isWorking && http)
		{
			features="menubar=no,toolbar=no,location=no,status=no,scrollbars=yes,resizable=yes";
			var url ="/crm/QryPreview.do?module=Exclusions&previewType=emailBounced";
			openPopUp("ghjhjgk",obj,url,"test",600,500,features)
		}
	}
    return false;
}

function callQryPreview(obj)
{
   if(getObj("Property(exclusion_1)").value=="" || getObj("Property(exclusion_1)").value=="null")
    {
     selectone.getJSAlertValue("crm.alert.row.create",null,"en_US",
			  function(mesg) { alert(mesg) })
     return false;
    }
    else
    {
        var formData="";
        formData = formData2QueryString(document.createEntityForm);
        if (!isWorking && http)
        {
            features="menubar=no,toolbar=no,location=no,status=no,scrollbars=yes,resizable=yes";
            var url ="/crm/QryPreview.do?module=Exclusions&formData="+formData ;
            openPopUp("ghjhjgk",obj,url,"test",600,500,features)
        }
    }
    return false;
}

	//For Targets Preview
	function previewTarget(obj)
        {
		if(getObj("property(target_1)").value=="" || getObj("property(target_1)").value=="null")
    		{
			     selectone.getJSAlertValue("crm.alert.row.create",null,"en_US",
			  															function(mesg) { alert(mesg) })
		        return false;
    		}
    		else
    		{
                	var formData="";
	                formData = formData2QueryString(document.createEntityForm);
        	        if (!isWorking && http)
                	{
                        	features="menubar=no,toolbar=no,location=no,status=no,scrollbars=yes,resizable=yes";
	                        var url ="/crm/QryPreview.do?module=Targets&formData="+formData;
        	                openPopUp("Targets",obj,url,"test",600,500,features)
                	}
        	}
		return false;
	}

       
/*
  Qry Builder related moveing fn ending 
*/          
function getAjaxHttpObj(){

try{

      if(window.XMLHttpRequest) 
      {
          return new XMLHttpRequest();
      } 
      else if(window.ActiveXObject)
      {
         try 
         {
               return new ActiveXObject("Microsoft.XMLHTTP");
         } catch (e) 
         {
               try {
                    return new ActiveXObject("Msxml2.XMLHTTP");
               } catch (e) {return false;}
         }          
      }
    }catch(e)
    {
			selectone.getJSAlertValue("crm.alert.browser.http.request",null,"en_US",
																function(mesg) { alert(mesg) })    }
}



var startsWith = function(str,prefix)
{
   var preLen=prefix.length;
   var strLen=str.length;
   if(preLen>str.length) return false;
   return(str.substr(0,preLen)==prefix)
}

var endsWith=function(str,suffix)
{
   //alert('inside endsWith  ' + str + ' ' + suffix);
   var sufLen=suffix.length;
   var strLen=str.length;
   if(sufLen>str.length) return false;
   return(str.substr(strLen-sufLen,sufLen)==suffix)
} 

function trim(str)
{
	return(str.replace(/\s+$/,''));
}

function checkwetherTimedOut(response)
{
    if(response.indexOf("New User Registration")>-1)
    {
     // session time out has happened...
     selectone.getJSAlertValue("crm.alert.session.check",null,"en_US",
																function(mesg) { alert(mesg) })
     window.location.reload();
     return true;
    }
    return false;
}

var isWindows=false;

function getHTTPObject() 
{
    	var http_request;
   if (window.XMLHttpRequest) 
   { // Mozilla, Safari, ...
	http_request = new XMLHttpRequest();
	//http_request.overrideMimeType('text/xml');
//	alert("mozilla XMLHttpRequest Object constructed...");
   }
   else if (window.ActiveXObject) 
   { // IE
	http_request = new ActiveXObject("Microsoft.XMLHTTP");
	isWindows=true;
//	alert("IE XML ActivexObject Object constructed...");    
   }
   return http_request;
}

var httphandle = getHTTPObject();


/* for TagCloud*/
function ajaxTagSearch(tagId,tagName,category)
{
        if(tagId != null)
        {
                if (!isWorking && http)
                {
                        var url="/crm/GTag.do?ajaxTagSearch=true&tagName="+tagName+"&searchCategory="+category+"&tagId="+tagId;
                        //var url="/crm/GTag.do?ajaxTagSearch=true&tagId="+tagId+"&tagName="+tagName;
                        document.getElementById('zohobusy_loadpage_search').style.display = 'inline';
                        //showInLine('zohobusy_loadpage_vinfo');
                        http.open("GET", url, true);
                        //http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;charset=UTF-8');
                        http.onreadystatechange = function()
                        {
                                if (http.readyState == 4)
                                {
                                        //alert("Response text "+http.responseText);

                                        txt=http.responseText;
                                        //if(checkwetherTimedOut(txt))
                                        {
                                              //  return;
                                        }
                                        if(txt.indexOf("New User Registration")>-1)
                                        {
                                                // session time out has happened...
                                               // alert('<fmt:message key="crm.alert.session.check"/>');
                                                //window.location.reload();
                                                //return;
                                        }
                                         getObj("show").innerHTML = "";
                                        getObj("show").innerHTML = txt;
                                        hide('zohobusy_loadpage_search');

                                      // dhtmlHistory.add("search["+searchword+"]",txt);


                                        //showDialog( txt, "modal=yes, closeOnEscKey=no" );
					 //showDialog( txt, "position=relative" );

                                        isWorking = false;

                                }
                        }

                        http.send(null);
                }

       }
        else
        {
                selectone.getJSAlertValue("crm.search.letters.check",null,"en_US",
			  																	function(mesg) { alert(mesg) })
                getObj('searchword').focus();
                return false;
        }
       // return false;

}


function CallonclickofbuttonNew(url, getValue,showAfter,hideAfter,fieldLabel,module,subid,uitype,tableName,columnName,entityID,module)
{
	var tagValue="";
	if (httphandle)
	{
	    
		if(uitype==786)
    	     	{

    //zohocrm's code            
    /*    	dateid = getValue.substring( 0, getValue.indexOf( "*" ) );
		        timeid = getValue.substring( getValue.indexOf("*")+1);
			dtime="textbox_"+fieldLabel;
                	htime="textbox_"+fieldLabel+"hour";
                	mtime="textbox_"+fieldLabel+"minute";
                	atime="textbox_"+fieldLabel+"ampm";
			tagValue=trim(document.getElementById(dtime).value) +' '+ trim(document.getElementById(htime).value) + ":" + trim(document.getElementById(mtime).value) + ' ' + trim(document.getElementById(atime).value);
                	subs1="property("+fieldLabel+"subs1)";*/
// cuurent orion code
			dateid = getValue.substring( 0, getValue.indexOf( "*" ) );
			timeid = getValue.substring( getValue.indexOf("*")+1);
			
			if(document.getElementById(dtime).value.length==0)
			{
			//	alert("Enter the Date Time Values correctly");
			}
			else
			{
				dtime="textbox_"+fieldLabel;
				ttime="textbox_"+fieldLabel+"time";
				tagValue=trim(document.getElementById(dtime).value) +' '+ trim(document.getElementById(ttime).value);
				subs1="property("+fieldLabel+"subs1)";
			}
             	}
		else if(uitype==100)
		{
			var j=0;
			for(var i=0;i< getObj("comboValue"+comboCount).length;i++)
			{
				if(getObj("comboValue"+comboCount).options[i].selected==true)
				{
					if(j==0)
                                        {
                                                tagValue  = getObj("comboValue"+comboCount).options[i].value;
                                        }
                                        else
                                        {
                                                tagValue  = tagValue+ ";"+ getObj("comboValue"+comboCount).options[i].value; 
                                        }
					j++;
				}
				else if(j==0)
                                {
                                        tagValue  = "";
                                }
	
			}
		}
		else if(uitype==300 || uitype==301)
        	{
	            tagValue=getObj(globaltextboxpanid).checked;
        	}
		else if(uitype==32)	// This is added for integer custom field 
		{
			var max_intCF_value = 2147483647
			var min_intCF_value = -2147483648	
			tagValue = trim(document.getElementById(getValue).value);
			if( !( (min_intCF_value <= tagValue) && (tagValue<=max_intCF_value) ) )
			{
				callSelectOneMethod(dwrChkVar,"crm.alert.num.integer.range",null,"en_US");       
				return;
			}
		}
		else
		{
                        tagValue = trim(document.getElementById(getValue).value);
		}
		


		var formVRes = formValidate1(fieldLabel,tagValue,uitype);
   		if(!formVRes)
    		{
			if(uitype == 786)
			{
				if(getObj(dateid))
				{
					getObj(dateid).focus();
				}
			}
			else
			{
	        		getObj(getValue).focus();
			}
        		return;
    		}
		
		itsonview=false;
		showInLine('zohobusy_loadpage_vinfo');
		
		var args = "fieldValue="+ encodeURIComponent(tagValue)+ "&module="+module+"&fieldLabel="+encodeURIComponent(fieldLabel)+"&moduleid="+entityID+ "&uitype="+uitype+"&tableName="+tableName+"&columnName="+columnName+ "&module=" +module;

        	if(fieldLabel == "Account Name" && module != 'Accounts')
        	{
	            	actNameDiv = getObj('actName');
        	    	args=args+"&accountID="+actNameDiv.value;
        	}
                if(module == "Contacts" && (fieldLabel == "Current Employer" || fieldLabel == "Most recently attended School" ) )
                {                    
                    if(fieldLabel == "Current Employer")
                    {
						if(tagValue.length==0)
						{
							getObj(hideAfter).innerHTML = ""; 
							hide('zohobusy_loadpage_vinfo');
							return;
						}
                        if(getObj("property(Contact_Employer_Relid)"))
                        {
                            args = args +"&Contact_Employer_Relid="+encodeURIComponent(getObj("property(Contact_Employer_Relid)").value);
                            getObj("property(Contact_Employer_Relid)").value ="";
                        }
                    }
                    else if(fieldLabel == "Most recently attended School")
                    {
                    	if(tagValue.length==0)
						{
							getObj(hideAfter).innerHTML = ""; 
							hide('zohobusy_loadpage_vinfo');
							return;
						}
                        if(getObj("property(Contact_School_Relid)"))
                        {
                           args = args +"&Contact_School_Relid="+encodeURIComponent(getObj("property(Contact_School_Relid)").value);
                           getObj("property(Contact_School_Relid)").value ="";
                        }
                    }                
                }
                if(module == "Contacts" && fieldLabel=="Lifecycle Role/Stage"){
                			var contactlifecycleRel = getObj("contactlifeRel").value;
                			if(!contactlifecycleRel == "")
                			{
		               			args = args+"&contactlifeRel_Id="+contactlifecycleRel;
        		       			getObj("contactlifeRel").value="";
        		       		}
        		       		else{
        		       			hide('zohobusy_loadpage_vinfo');
								return handleCancel('value_Lifecycle Role/Stage','textarea_Lifecycle Role/Stage','Lifecycle Role/Stage');
        		       		}
                	}
                
		
		httphandle.open("POST", url, true);
		httphandle.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;charset=UTF-8');
  		httphandle.onreadystatechange = function() 
        	{
			if (httphandle.readyState == 4) 
                	{
                    		if (httphandle.status == 200) 
                    		{
	                    		var item = httphandle.responseText;
		    			if(item.indexOf("SECURITY::::")>-1)
                    			{
                       	 			var errorContent = item.split("SECURITY::::");
                        			getObj("show").innerHTML = ""
                        			getObj("show").innerHTML = errorContent[1];
                    			}
 	  	
                    			if(checkwetherTimedOut(item))
                    			{	
                        			return;
                    			}

					var isSuccess="";
					var valOrMess="";
					var isRecentItems;
					var modifiedby;
					{
						var saveFieldContent=item.split("AJAX::::");        
						isSuccess=trim(saveFieldContent[1]);
						valOrMess=saveFieldContent[2];
						valOrMess=valOrMess.replace("&","&amp;");
						isRecentItems=trim(saveFieldContent[3]);
						recentContents=trim(saveFieldContent[4]);
						modifiedby=trim(saveFieldContent[5]);
						date=(saveFieldContent[6]);	

						if(uitype==786)
						{
							document.getElementById(subs1).value=date;
						}	
					}
					if(isSuccess == "true")
					{
						//divObj = getObj(showAfter);
                                                divObj = document.getElementById(showAfter);
						valOrMess = valOrMess.replace(/</g,"&lt;");
						valOrMess = valOrMess.replace(/>/g,"&gt;");
						
						if(uitype==25)
						{
							var inner= "";
							if(subid=="subvalue_Email" && module == "Contacts")
							{
								inner=" <a class=\"link\" href=\"javascript:mailTo(this,'Contacts'," + entityID+ ",'" + skintype+"')\" id=\""+subid+"\">"+ valOrMess+"</a>";
            				}
							else
							{
								inner=" <a class=\"link\" href=\"mailto:"+tagValue+"\" id=\""+subid+"\"/>"+ valOrMess+"</a>";
							}				
							divObj.innerHTML="";
							divObj.innerHTML= inner;
						}
						else if(uitype==300 || uitype==301)
						{
							yesID = "yes_"+fieldLabel;
							noID = "no_"+fieldLabel;                                
							if(valOrMess=="true")
							{                                        
								show(yesID);
								hide(noID);
							}
							else
							{                                        
								show(noID);
								hide(yesID);
							}
						}
						else if(uitype==21)
						{
							var inner= "";
							//alert("in update it has a subfield");
							if(tagValue.toLowerCase().indexOf("http")==0)
							{
								inner=" <a class=\"link\" href=\"" + tagValue + "\" target=\"_blank\"  id=\""+subid+"\"/>"+ valOrMess+"</a>";
							}
							else
							{
								inner=" <a class=\"link\" href=\"http://"+tagValue+"\" target=\"_blank\"  id=\""+subid+"\"/>"+ valOrMess+"</a>";
							}
							divObj.innerHTML="";
							divObj.innerHTML= inner;
						}
						else if(uitype==33)
						{
							var inner= "";                        	
							inner="<a class=\"link\" href=\"skype:+"+tagValue+"?call\" id=\""+subid+"\"/>"+ valOrMess+"</a>";
							divObj.innerHTML="";
							divObj.innerHTML= inner;
						}
						else if(uitype==37)
						{
							var inner= "";
							if(tagValue!="")
							{	
								inner="<a class=\"link\" href=\"skype:"+tagValue+"\" id=\""+subid+"\">"+ valOrMess+ " </a><img src=\"/crm/images/skypeBlueSmall.gif\" align=\"absmiddle\" border=\"0\" alt=\"Skype now\" title=\"Skype now\"/>";
							}
							else
							{
								inner="<a class=\"link\" href=\"skype:"+tagValue+"\" id=\""+subid+"\"/>"+ valOrMess+ "</a>";
							}
							divObj.innerHTML="";
							divObj.innerHTML= inner;
						}
						else if(uitype==4)
						{
							var tokens =  valOrMess.split("|||");
							var accountName=tokens[0];
							var accountID=tokens[1];
							var accountValue =  "<a class='link' id='"+subid+"' href=\"javascript:ajaxNew('/crm/ShowEntityInfo.do?module=Accounts&amp;id="+ accountID+ "')\">"+ accountName+ "</a>";
							divObj.innerHTML="";
							divObj.innerHTML= accountValue;
						}
						else if(uitype==22){	
							var tokens = valOrMess.split("|||");
							var lifecycleRoleName = tokens[0];
							var lifecycleId = tokens[1];
							var contactlifeValue = "<a class='link' id='"+subid+"' href=\"javascript:ajaxNew('/crm/ShowEntityInfo.do?module=LifeCycles&amp;id="+ lifecycleId+ "')\">"+lifecycleRoleName+ "</a>";
							divObj.innerHTML="";
							divObj.innerHTML= contactlifeValue;
						}
						else if(uitype==36)
						{
                            divObj=getObj(subid);
							divObj.innerHTML="";
							divObj.innerHTML= valOrMess;
						}
						else if(uitype==34)
						{
                            divObj=getObj(subid);
							divObj.innerHTML="";
							divObj.innerHTML= valOrMess;
						}
						else if(uitype==3)
						{
							if(browser_ie)
							{
								divObj.innerHTML = "";
								divObj.innerHTML = valOrMess;
							}
							else
							{
								divObj.innerHTML="";
								divObj.innerHTML= valOrMess;
							}
						}
						else
						{
							divObj.innerHTML="";
							divObj.innerHTML= valOrMess;
						}

						if(isRecentItems=="true")
						{
							recentDiv = getObj('sidebar2');
							if(recentDiv)
							{	
								recentDiv.innerHTML= "";
								recentDiv.innerHTML= recentContents;
							}	
						}
						if(getObj('modifiedby')!=null)
						{
							getObj('modifiedby').innerHTML="";
							getObj('modifiedby').innerHTML= modifiedby;
						}

					}
                    			else if(isSuccess == "false")
					{
						selectone.getJSAlertValue("crm.alert.error.default",null,"en_US",function(mesg) { alert(mesg + " : " + valOrMess) })
					}
					else if(isSuccess == "contactAlreadyExixts")
					{
						selectone.getJSAlertValue("crm.alert.unique.contact.email.check",null,"en_US",function(mesg){ alert(mesg) })
					}
                                        else if(isSuccess == "studentIdAlreadyExists")
                                        {
                                              alert("Please provide a different Student ID as the current one already exists");
                                        }
					else
					{
						selectone.getJSAlertValue("crm.alert.invalid.response",null,"en_US",function(mesg) { alert(mesg) })
					}
					getObj(hideAfter).innerHTML = "";		
					show(showAfter);
					//alert("showhide called("+showAfter + ","+ hideAfter+")" );

				}
				 else 
				{
					//alert("Not Petfect...");
				}
				
				hide('zohobusy_loadpage_vinfo');
				
				fieldLabelObj = getObj(fieldLabel); 
				
				if(fieldLabelObj)
				{		
					fieldLabelObj.className="label";  
				}
			}
		}
		
		httphandle.send(args);
	}
	else
	{
		alert("http does not exists");
	}
}	
	


function Callonclickofbutton(url, getValue,showAfter,hideAfter,fieldLabel,module,subid,uitype,tableName,columnName,entityID,module)
{
      
	var tagValue="";
	var upd="true";
	 if(module == 'Exclusions')
        {	
              DWRCommonUtil.isEmailOptOut(entityID,function(isPresent)
		            {
		            	if(isPresent== true)
						{
							alert('Permission Denied');
							return false;
						} 
						else
						{
						  CallonclickofbuttonNew(url, getValue,showAfter,hideAfter,fieldLabel,module,subid,uitype,tableName,columnName,entityID,module);
						}
					}
				
			);
       }
      else
       {
       	     CallonclickofbuttonNew(url, getValue,showAfter,hideAfter,fieldLabel,module,subid,uitype,tableName,columnName,entityID,module);
       } 
      
   
   
   
	}

   /*    formValidate(); */
//can be removed once Callonclickofbutton works...
function Callonclickofbutton_old(url, getValue,showAfter,hideAfter,fieldLabel,module,subid,uitype,tableName,columnName,entityID,module)
{
	var tagValue="";
	if (httphandle)
	{
		if(uitype==786)
		{
			dateid = getValue.substring( 0, getValue.indexOf( "*" ) );
			timeid = getValue.substring( getValue.indexOf("*")+1);
			dtime="textbox_"+fieldLabel;
			ttime="textbox_"+fieldLabel+"time";
			tagValue=trim(document.getElementById(dtime).value) +' '+ trim(document.getElementById(ttime).value);
			subs1="property("+fieldLabel+"subs1)";
		}
		else if(uitype==100)
		{
			var j=0;
			for(var i=0;i< getObj("comboValue"+comboCount).length;i++)
			{
				if(getObj("comboValue"+comboCount).options[i].selected==true)
				{
					if(j==0)
					{
						tagValue  = getObj("comboValue"+comboCount).options[i].value;
					}
					else
					{
						tagValue  = tagValue+ ";"+ getObj("comboValue"+comboCount).options[i].value; 
					}
					j++;
				}
				else if(j==0)
				{
					tagValue  = "";
				}
			}
		}
		else if(uitype==300 || uitype==301)
		{
			tagValue=getObj(globaltextboxpanid).checked;
		}
		else
		{
			tagValue = trim(document.getElementById(getValue).value);
		}
		/*
		   if(module=="Cases")
		   {
		   var obj1=getObj("textbox_Case Origin");
		   var selVal=obj1.options[obj1.options.selectedIndex].value
		   if(selVal=="Email" )
		   {
		   var emailValue=  getObj("textbox_Email").value;
		   if (!emptyCheck2("","Email",emailValue))
		   {
		   selectone.getJSAlertValue("crm.alert.not.empty",null,"en_US",
		   function(mesg) { alert(enterEmailLabel + " " + mesg) })
		   return false;
		   }
		   }
		   }
		 */
		/*
		 * vendor obj has removed so this check no need
		 */
		/*		if(fieldLabel == "Account Name" && module == "Contacts")
				{
				if(trimBoth(getObj("textbox_Account Name").value) != "" && trimBoth(getObj("vendorName").value) != "")
				{
				selectone.getJSAlertValue("crm.alert.contact.org",null,"en_US",
				function(mesg) { alert(mesg) })
				return false;
				}
				}
		 */
		if(module == "Campaigns" && fieldLabel == "Start Date")
		{
			if(getObj("value_End Date").innerHTML != "")
			{
				getObj("textbox_End Date").value = getObj("value_End Date").innerHTML
					if (!dateComparison("textbox_End Date","End Date","textbox_Start Date","Start Date","GE"))
						return false
			}		
		}
		
		var formVRes = formValidate1(fieldLabel,tagValue,uitype);
		
		if(!formVRes)
		{
			getObj(getValue).focus();
			return;
		}
		
		itsonview=false;
		showInLine('zohobusy_loadpage_vinfo');

		//url = url+"?fieldValue="+ escape(tagValue)+ "&module="+module+"&fieldLabel="+escape(fieldLabel)+"&moduleid="+entityID+ "&uitype="+uitype+"&tableName="+tableName+"&columnName="+columnName+ "&module=" +module;
		
		var args = "fieldValue="+ encodeURIComponent(tagValue)+ "&module="+module+"&fieldLabel="+escape(fieldLabel)+"&moduleid="+entityID+ "&uitype="+uitype+"&tableName="+tableName+"&columnName="+columnName+ "&module=" +module;
		
		
		if((fieldLabel == "Account Name" || fieldLabel == "Organization") && (module != 'Accounts'&& module !='Leads'))
		{
			actNameDiv = getObj('actName');
			args=args+"&accountID="+actNameDiv.value;
		}

		
		httphandle.open("POST", url, true);
		httphandle.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;charset=UTF-8');
		httphandle.onreadystatechange = function() 
		{
			
			if (httphandle.readyState == 4) 
			{
				if (httphandle.status == 200) 
				{

					var item = httphandle.responseText;

					if(item.indexOf("SECURITY::::")>-1)
					{
						var errorContent = item.split("SECURITY::::");
						getObj("show").innerHTML = ""
							getObj("show").innerHTML = errorContent[1];
					}

					if(checkwetherTimedOut(item))
					{
						return;
					}
					var isSuccess="";
					var valOrMess="";
					var isRecentItems;
					var modifiedby;
					if(false)//old impl
					{
						var xmldoc = httphandle.responseXML;
						var root_node = xmldoc.getElementsByTagName('result').item(0);
						var isSuccess = root_node.getAttribute("success");
						var isEmpty = root_node.getAttribute("isEmpty");
						if(isEmpty== "false")
						{
							var valOrMess = root_node.childNodes.item(0).nodeValue;
						}
						else
						{
							var valOrMess = "";
						}
					}
					else
					{
						var saveFieldContent=item.split("AJAX::::");        
						isSuccess=trim(saveFieldContent[1]);
						valOrMess=saveFieldContent[2];
						valOrMess=valOrMess.replace("&","&amp;");
						isRecentItems=trim(saveFieldContent[3]);
						recentContents=trim(saveFieldContent[4]);
						modifiedby=trim(saveFieldContent[5]);
						date=(saveFieldContent[6]);	

						if(uitype==786)
						{
							document.getElementById(subs1).value=date;
						}	
					}
					if(isSuccess == "true")
					{
						//divObj = getObj(showAfter);
						divObj = document.getElementById(showAfter);
						if(uitype==25)
						{
							var inner= "";
							inner=" <a class=\"link\" href=\"mailto:"+tagValue+"\" id=\""+subid+"\"/>"+ valOrMess+"</a>";
							divObj.innerHTML="";
							divObj.innerHTML= inner;
						}
						else if(uitype==300 || uitype==301)
						{
							yesID = "yes_"+fieldLabel;
							noID = "no_"+fieldLabel;                                
							if(valOrMess=="true")
							{                                        
								show(yesID);
								hide(noID);
							}
							else
							{                                        
								show(noID);
								hide(yesID);
							}
						}
						else if(uitype==21)
						{
							var inner= "";
							//alert("in update it has a subfield");
							if(tagValue.toLowerCase().indexOf("http")==0)
							{
								inner=" <a class=\"link\" href=\"" + tagValue + "\" target=\"_blank\"  id=\""+subid+"\"/>"+ valOrMess+"</a>";
							}
							else
							{
								inner=" <a class=\"link\" href=\"http://"+tagValue+"\" target=\"_blank\"  id=\""+subid+"\"/>"+ valOrMess+"</a>";
							}
							divObj.innerHTML="";
							divObj.innerHTML= inner;
						}
						else if(uitype==33)
						{
							var inner= "";                        	
							inner="<a class=\"link\" href=\"skype:+"+tagValue+"\" id=\""+subid+"\"/>"+ valOrMess+"</a>";
							divObj.innerHTML="";
							divObj.innerHTML= inner;
						}
						else if(uitype==37)
						{
							var inner= "";
							if(tagValue!="")
							{	
								inner="<a class=\"link\" href=\"skype:"+tagValue+"\" id=\""+subid+"\"/>"+ valOrMess+ "<img src=\"/crm/images/skypeBlueSmall.gif\" align=\"absmiddle\" border=\"0\" alt=\"Skype now\" title=\"Skype now\"> </a>";
							}
							else
							{
								inner="<a class=\"link\" href=\"skype:"+tagValue+"\" id=\""+subid+"\"/>"+ valOrMess+ "</a>";
							}
							divObj.innerHTML="";
							divObj.innerHTML= inner;
						}
						else if(uitype==4)
						{
							var spanvarid ='subvalue_'+fieldLabel;
							var tokens =  valOrMess.split("|||");
							var accountName=tokens[0];
							var accountID=tokens[1];
							var accountValue =  "<a class='link' href='/crm/ShowEntityInfo.do?module=Accounts&amp;id="+ accountID+ "&isload=true'><span id='"+spanvarid+"'>"+ accountName+ "</span></a>";
							divObj.innerHTML="";
							divObj.innerHTML= accountValue;
						}
						else if(uitype==36)
						{
							divObj=getObj(subid);
							divObj.innerHTML="";
							divObj.innerHTML= valOrMess;
						}
						else if(uitype==3)
						{
							if(browser_ie)
							{
								divObj.innerHTML = ""
								divObj.innerHTML = "<pre class='value'>"+valOrMess+"</pre>"
							}
							else
							{
								divObj.innerHTML="";
								divObj.innerHTML= valOrMess;
							}
						}
						else
						{
							divObj.innerHTML="";
							divObj.innerHTML= valOrMess.escapeHTML();
						}

						if(isRecentItems=="true")
						{
							recentDiv = getObj('sidebar3');
							recentDiv.innerHTML= "";
							recentDiv.innerHTML= recentContents;
						}
						if(getObj('modifiedby')!=null)
						{
							getObj('modifiedby').innerHTML="";
							getObj('modifiedby').innerHTML= modifiedby;
						}
					}
					else if(isSuccess == "false")
					{
						selectone.getJSAlertValue("crm.alert.error.default",null,"en_US",function(mesg) { alert(mesg + " : " + valOrMess) })
					}
					else if(isSuccess == "contactAlreadyExixts")
					{
						selectone.getJSAlertValue("crm.alert.unique.contact.email.check",null,"en_US",function(mesg){ alert(mesg) })
					}
                                        else if(isSuccess == "studentIdAlreadyExists")
                                        {
                                              alert("Please provide a different Student ID as the current one already exists");
                                        }
					else
					{
						selectone.getJSAlertValue("crm.alert.invalid.response",null,"en_US",function(mesg) { alert(mesg) })
					}

					showHide(showAfter,hideAfter);
					//alert("showhide called("+showAfter + ","+ hideAfter+")" );
				} else 
				{
					//alert("Not Petfect...");
				}
				hide('zohobusy_loadpage_vinfo');
				fieldLabelObj = getObj(fieldLabel); 
				//fieldLabelObj.className="label";  
				if(searchJSP != undefined)
				{
					//set_cookie("previousLocation",window.location.href);
					//window.historyStorage.put("start",getObj('show').innerHTML);
				}
			}
		}
		
		httphandle.send(args);
	}
	else
	{
		selectone.getJSAlertValue("crm.alert.http.exists.check",null,"en_US",function(mesg) { alert(mesg) })
	}
	
}

function replaceAmp(str)
{
	var errorContent=str.split("&amp;");
	var newStr="";
	for(i=0;i<errorContent.length;i++)
	{
		if(i==0)
		{
			newStr=errorContent[i];
		}
		else
		{
			newStr=newStr+ "&" + errorContent[i];
		}
	}
	return newStr;
}

function separate1(textValue)
{
	var trimmed=trim(textValue);
	var start = textValue.indexOf("<PRE");
	var end = textValue.indexOf("</PRE>");
	if(start<0 || end<0)
	{
		return textValue;
	}
	return textValue.substring((start+17),end);
}

function separateSkype(textValue)
{
	var trimmed=trim(textValue);
	var end = textValue.indexOf("<img");
	if(end<0)
	{
		return textValue;
	}
	return textValue.substring(0,end);
}

function separatePhone(textValue)
{
	var trimmed=trim(textValue.trim());
	var phLen = trimmed.length;
	var actVal="";
	if(phLen<0)
	{
		return actVal;
	}
	else
	{
		var re=/^\d+(,(\d)+)*(\.\d{1,2})*$/;
		if(!re.test(trimmed))
		{	
			if(phLen==14)
			{
				// check whether it is in (123) 456-7890 format 1-(, 5-), 6- , 10--
				if(startsWith(trimmed, '(') && trimmed.indexOf('-') && trimmed.indexOf(')') && trimmed.indexOf(" ") )
				{
					actVal=trimmed;
					// Check for 4th, 5th & 9th char
					var fourth = trimmed.indexOf(')');
					var fifth = trimmed.indexOf(" ");
					var ninth = trimmed.indexOf('-');
					if(fourth==4 && fifth==5 && ninth==9)
					{
				 		trimmed=trimmed.replace(' ','')
						trimmed=trimmed.replace('(','');
						trimmed=trimmed.replace(')','');
						trimmed=trimmed.replace('-','');
						if(trimmed.length==10)
						{
							var chkIt = trimmed.replace(' ','').replace('(','').replace(')','').replace('-','');
							if(chkIt.length<10)
							{
								return actVal;				
							}
							return trimmed;
						}
						else
						{
							return actVal;
						}
					}
					else
					{
						return actVal;
					}
				}
				else
				{
					return trimmed;
				}
			}
			else if(phLen==12)
			{
				var chkSpace=trimmed.indexOf(" ");
				if(chkSpace!=-1)
				{
					return trimmed;
				}
				// check whether it is in (12345)-6789 format
				if(startsWith(trimmed, '(') && trimmed.indexOf(')') && trimmed.indexOf('-') ) 
				{
					actVal=trimmed;
					// Check for 6th & 7th char
					var sixth = trimmed.indexOf(')');
					var seventh = trimmed.indexOf('-');

					if(sixth==6 && seventh==7)
					{
						trimmed=trimmed.replace('-','');
						trimmed=trimmed.replace('(','');
						trimmed=trimmed.replace(')','');

						if(trimmed.length==9)
						{
							var chkIt = trimmed.replace('-','').replace('(','').replace(')','');
							if(chkIt.length<9)
							{
								return actVal;				
							}
							return trimmed;
						}
						else
						{
							return actVal;
						}
					}
					else
					{
						return actVal;
					}
				}
				else
				{
					return trimmed;
				}
			}
			else
			{
				return trimmed;
			}
		}
		else
		{
			return	trimmed;
		}
	}
}

function separate(textValue)
{
	var trimmed=trim(textValue);
	var start = textValue.indexOf("<pre");
	var end = textValue.indexOf("</pre>");
	if(start<0 || end<0)
	{
		return textValue;
	}
	return textValue.substring((start+17),end);
}

function setValue(fromID,toID,subid,uitype,fieldlabel,isMandatory)
{
   if(isMandatory)
   {
     fieldLabelObj = getObj(fieldlabel); 
    //fieldLabelObj.className="bodyText mandatory"
    //fieldLabelObj.align="right"
   }
    
   var actualValue =  replaceAmp(document.getElementById(fromID).innerHTML);
   var tagValue = trim(actualValue);
	
   if((fieldlabel=="Account Name" ||fieldlabel=="Organization" ) && uitype==4)
   {
        //alert("Account lookup");
        subobj = getObj(subid);
        divObj = getObj(toID);
        divObj.value = "";
		divObj.value=document.getElementById(subid).innerHTML;
        //divObj.value=subobj.innerHTML;
   }
   else if( uitype==100 )
   {
	for(var i=0;i< getObj("comboValue"+comboCount).length;i++)
	{
		getObj("comboValue"+comboCount).options[i].selected = false;
	}

	var valArr = tagValue.split(";");
	for(var k=0;k<valArr.length;k++)
	{
		for(var i=0;i< getObj("comboValue"+comboCount).length;i++)
		{
			if(getObj("comboValue"+comboCount).options[i].value == valArr[k])
			{
				getObj("comboValue"+comboCount).options[i].selected = true;
			}
		}	
	}		
    }
    else if(uitype==25 || uitype==21 )//mail
    {
           subobj = getObj(subid);
           divObj = getObj(toID);
           divObj.value = "";
           divObj.value=subobj.innerHTML.unescapeHTML();
          
    }
    else if (uitype==36)//currency
    {
           subobj = getObj(subid);
           var newStr=subobj.innerHTML;
             // deformat
           newStr= convertFromCurrency(newStr);
           divObj = getObj(toID);
           divObj.value = "";
           divObj.value = newStr;
    }
    else if(uitype == 34)
    {
    	subobj = getObj(subid);
        var valStr=subobj.innerHTML;
        valStr= covertPercent(valStr.trim());
        divObj = getObj(toID);
        divObj.value = "";
        divObj.value = valStr;
    }
    else if(uitype==3)
    {
           	var baseValue= separate(tagValue);
           	baseValue=separate1(baseValue);
           	if(baseValue!='' && baseValue.trim().length>0 && baseValue!=undefined ){		//Decoding Call for &gt,&lt and &quot
         		HTMLParser.getHTMLEntityDeCode(baseValue,
	        	{
	            	callback:function(response)
    		        	{
							if((response>0)||(response!=null)||(response!='')||(response!=undefined))
							{
								  divObj = getObj(toID);
			                      divObj.value = "";
           						  divObj.value =response;
							}
						}				
				});
			}
			else
			{
				divObj = getObj(toID);
    	        divObj.value = "";
        	    divObj.value = baseValue;
			}
   }
   else if (uitype==33)//Phone field
   {
           subobj = getObj(subid);
		
           divObj = getObj(toID);
           divObj.value = "";

           //divObj.value=(subobj.innerHTML);

           divObj.value=separatePhone(subobj.innerHTML);
    }
	else if(uitype==37) // skypeId field
	{			
           subobj = getObj(subid);
		
           divObj = getObj(toID);
           divObj.value = "";

           divObj.value=separateSkype(subobj.innerHTML);		
	}
	else if(uitype==786)
	{
		dtime="textbox_"+fieldlabel;
		subs1="property("+fieldlabel+"subs1)";	
	
		document.getElementById(dtime).value=document.getElementById(subs1).value;
	}	
   	else
    {
   		divObj = getObj(toID);
        divObj.value = "";
        divObj.value = tagValue.unescapeHTML().trim();
    }
}
function covertPercent(percentVal)
{
	var length = percentVal.length;
	var loop=0;
	var newPercentVal="";
	var previousChar="1";
	for(loop=0;loop<length;loop++)
	{
		if(!isNaN(percentVal.charAt(loop)+""))
		{
			newPercentVal= newPercentVal+ percentVal.charAt(loop);
		}
		else if(percentVal.charAt(loop)== '.' && (!isNaN(previousChar)))
		{
			newPercentVal= newPercentVal+ percentVal.charAt(loop);
	    }
		previousChar=percentVal.charAt(loop);
	}
	return newPercentVal;
}
function convertFromCurrency(currency)
{
	var length = currency.length;
	var i=0;
	var newCurrency="";
	var previousChar="1";
	for(i=0;i<length;i++)
	{
		if(!isNaN(currency.charAt(i)+""))
		{
			newCurrency= newCurrency+ currency.charAt(i);
		}
		else if(currency.charAt(i)== '.' && (!isNaN(previousChar)))
		{
		newCurrency= newCurrency+ currency.charAt(i);
	        }
		else if(currency.charAt(i)== ',' && (!isNaN(previousChar)))
		{
		newCurrency= newCurrency+ currency.charAt(i);
	        }

		previousChar=currency.charAt(i);
	}
	return newCurrency;
}
function showInLine(divId)
{
	
	var id = document.getElementById(divId);
	
	id.style.display = 'inline';
	

}

/*function show(divId)
{
//	alert(document.getElementById(divId).style.cssText);
	var id = document.getElementById(divId);
	id.style.display = 'block';
//	alert(document.getElementById(divId).style.cssText);
//	alert("Inside Show "+id.id);
}
*/

function showHide(showId, hideId)
{
//	alert("Show and Hide id "+showId+hideId);
	show(showId);
	hide(hideId);
}
/*function hide(divId)
{
	var id = document.getElementById(divId);
//	alert(id+" style "+id.style.display);
	id.style.display = 'none';
//	alert("Inside Hide "+id.id);
}
*/


var globalfieldlabel="";
var globalvaluespanid="";
var globalsubvaluespanid="";
var globaltextboxpanid="";
var globaltextareapanid="";
var globaluitype;
var globalismandatory;
var comboCount = 1;
var globalmaxlen="";

function handleEdit()
{

	//alert(globalfieldlabel);
	// alert('In latest handleEdit');
	if(globaluitype==300 || globaluitype==301)
	{
		//alert("In check box handler");
		show(globaltextareapanid) ;
		hide(globalvaluespanid);
		var yesSelected=false;
		if(getObj("yes_"+globalfieldlabel).style.display=="none")
		{
			//alert("Its no.gif");
			yesSelected=false;
		}
		if(getObj("no_"+globalfieldlabel).style.display=="none")
		{
			// alert("Its Yes.gif");
			yesSelected=true;
		}
		checkBox = getObj(globaltextboxpanid);
		checkBox.checked=yesSelected;
	}
	else
	{
		//setValue(globalvaluespanid,globaltextboxpanid,globalsubvaluespanid,globaluitype,globalfieldlabel);
		setValue(globalvaluespanid,globaltextboxpanid,globalsubvaluespanid,globaluitype,globalfieldlabel,globalismandatory);
		show(globaltextareapanid) ;
		if(getObj(globaltextareapanid)!=null)
		{
			getObj(globaltextareapanid).focus();
		}
		if(getObj(globaltextboxpanid)!=null)
		{
			getObj(globaltextboxpanid).focus();
		}
		hide(globalvaluespanid);
	}
	hide('crmspanid');
	itsonview=true;
	//if(dhtmlHistory.currentLocation!="start")
	{
		//window.historyStorage.put("start",getObj('show').innerHTML);
	}
	return false;
}

var mouseOverCalled=false;
function handleMouseOver(uitype,fieldLabel,readonlytype,ismandatory,count,maxlen)
{
	if(readonlytype==true)
	{
		return;
	}
	if( $("SECURITY_EDIT_ALLOWED"))
    {       
            if( $F("SECURITY_EDIT_ALLOWED") == "false")
            {
                    return; //Read only permission check
            }
    }
	if(itsonview)
	{
		return;
	}
	var mouseArea="";
	mouseArea="mouseArea__"+ fieldLabel;
	show("crmspanid");
	globalfieldlabel=fieldLabel;
	globalvaluespanid= "value_"+ fieldLabel;//valuespanid;
	globalsubvaluespanid="subvalue_"+ fieldLabel;//subvaluespanid;
	globaltextareapanid="textarea_"+ fieldLabel;//textareapanid;
	globaluitype=uitype;
	globaltextboxpanid="textbox_"+ fieldLabel;//textboxpanid;
	globalismandatory=ismandatory;
	comboCount = count;
        globalmaxlen = maxlen;
	divObj = getObj('crmspanid');
	crmy = findPosY(document.getElementById(mouseArea));
	crmx = findPosX(document.getElementById(mouseArea));
	//if(isWindows)
        if(browser_ie)
	{
		//document.getElementById('crmspanid').onclick=handleEdit;
        //divObj.onclick=ajaxEdit;
        document.getElementById('crmspanid').onclick=ajaxEdit;
	}
	else
	{
		//document.getElementById('crmspanid').onclick=handleEdit;
	
        divObj.setAttribute('onclick','ajaxEdit();');
	
	}
	document.getElementById('crmspanid').style.left=(crmx+document.getElementById(mouseArea).offsetWidth -document.getElementById('crmspanid').offsetWidth)+"px";
	
	document.getElementById('crmspanid').style.top=crmy+"px";
}

var itsonview=false;

function ajaxEdit()
{
	var spanObj = document.getElementById(globalvaluespanid);
	var subSpanObj = document.getElementById(globalsubvaluespanid);
	var spanValue = spanObj.innerHTML;
	if(subSpanObj)
	{
		spanValue = subSpanObj.innerHTML;
	}

	if(globaluitype==300 || globaluitype==301)
	{
		var objTxt = "<input type='checkbox' id='textbox_"+globalfieldlabel+"' name='property("+globalfieldlabel+")'></input>";
	}
	else if(globaluitype == 3)
	{
		var objTxt = "<textarea id='textbox_"+globalfieldlabel+"' name='property("+globalfieldlabel+")' rows='5' style='width:100%'>"+spanValue+"</textarea>"; 
	}
	else if(globaluitype == 2)
	{
		var objTxt = "<select id='textbox_"+globalfieldlabel+"' name='property("+globalfieldlabel+")'>";
		var mySelObject = jsonSelectValues;
		//var mySelObject = eval('('+getObj('jsonSelectValues').innerHTML+')');
		var selectValues = mySelObject[globalfieldlabel];
		for(var j=0;j<selectValues.length;j++)
		{
			var displayValue = selectValues[j];		
			var rat = selectValues[j];
			rat = rat.replace(/</g,"&lt;")
			rat = rat.replace(/>/g,"&gt;")
			if(rat == '-None-')
			{
				rat = "";
                displayValue="";
			}
                        if(spanValue!=undefined)
                        {
                            if(trimBoth(displayValue) == trimBoth(spanValue))
                            {
                                    objTxt += "<option value='"+rat+"' selected>";
                            }
                            else
                            {
                            objTxt += "<option value='"+rat+"'>";
                            }
                        }
			else
			{
				objTxt += "<option value='"+rat+"'>";
			}	
			objTxt += ""+displayValue+"</option>";
		}
		objTxt += "</select>"
	}
	else if(globaluitype == 100)
	{
		var objTxt = "<select multiple id='comboValue"+comboCount+"' name='comboValue"+comboCount+"'>";
		var mySelObject = jsonSelectValues;
		//var mySelObject = eval('('+getObj('jsonSelectValues').innerHTML+')');
		var selectValues = mySelObject[globalfieldlabel];
		for(var j=0;j<selectValues.length;j++)
		{
			var displayValue = selectValues[j];		
			var rat = selectValues[j];
			rat = rat.replace(/</g,"&lt;")
			rat = rat.replace(/>/g,"&gt;")
			if(rat == '-None-')
			{
				rat = "";
                displayValue="";
			}
			objTxt += '<option value="'+rat+'">';
			objTxt += ""+displayValue+"</option>";
		}
		objTxt += "</select>"
	}
	else if(globaluitype == 786)
	{
		var dateValue = "";
		var dateTimeValues;
		if(spanValue != "")
		{
			if(spanValue.indexOf("&nbsp;")>-1)
			{
				dateTimeValues = spanValue.split("&nbsp;");
			}
			else if(spanValue.indexOf(" ")>-1)
			{
				dateTimeValues = spanValue.split(" ");
			}
			dateValue = dateTimeValues[0];
			var timeValues = dateTimeValues[1].split(":");
		}
		else
		{
			dateTimeValues=new Array();
			dateTimeValues[0]="";
			dateTimeValues[1]="";
		}
	
		var objTxt = "<input type='text' id='textbox_"+globalfieldlabel+"' name='property("+globalfieldlabel+")' value='"+dateValue+"' class='textField' onkeydown=\"handleButton('button__"+globalfieldlabel+"',event)\">";
	
		objTxt += "<img src='/crm/images/cal.gif' align='absmiddle' style='cursor:hand;cursor:pointer' onclick=\"showCal('textbox_"+globalfieldlabel+"')\"><span class='dim'>["+dtPtn+"]</span><br>";
		
        objTxt+= "<input id='textbox_"+ globalfieldlabel+"time' name='property("+globalfieldlabel+"time)' maxlength='120' onkeydown=\"handleButton(\'button__"+ globalfieldlabel+"\',event)\" value='"+dateTimeValues[1]+"' type='text'>";
		
		objTxt += "<input type='hidden' id='property("+globalfieldlabel+"subs1)' value='"+dateValue+"' name='property("+globalfieldlabel+"subs1)'><br><span class='dim'>[hh:mm]</span><br>"; 
		
	}
	else if(globaluitype == 36)
	{
		var objTxt = "<input type='text' id='textbox_"+globalfieldlabel+"' name='property("+globalfieldlabel+")' value='"+spanValue+"' class='textField' onkeydown=\"handleButton('button__"+globalfieldlabel+"',event)\">";
		objTxt += "<img src='/crm/images/calc.gif' align='absmiddle' style='cursor:hand;cursor:pointer' onclick=\"showCalc('property("+globalfieldlabel+")')\">";
	}
	else if(globaluitype == 34)
	{
		var objTxt = "<input type='text' id='textbox_"+globalfieldlabel+"' name='property("+globalfieldlabel+")' value='"+spanValue.trim()+"' class='textField' onkeydown=\"handleButton('button__"+globalfieldlabel+"',event)\">";
	}
	else if(globaluitype == 600)
	{
		var objTxt = "<input type='text' maxlength='7' id='textbox_"+globalfieldlabel+"' name='property("+globalfieldlabel+")' value='"+spanValue+"' class='textField' onkeydown=\"handleButton('button__"+globalfieldlabel+"',event)\">";				
	}
	else if(globaluitype == 24)
	{
		var objTxt = "<input type='text' id='textbox_"+globalfieldlabel+"' name='property("+globalfieldlabel+")' value='"+spanValue+"' class='textField' onkeydown=\"handleButton('button__"+globalfieldlabel+"',event)\">";
		objTxt += "<img src='/crm/images/cal.gif' align='absmiddle' style='cursor:hand;cursor:pointer' onclick=\"showCal('textbox_"+globalfieldlabel+"')\"><span class='dim'>["+dtPtn+"]</span><br>";
	}
	else if(globaluitype == 4)
	{
		var hrefValue = "";
		if(subSpanObj.innerHTML != "")
		{
			hrefValue = subSpanObj.href;
		}
		var accountid = hrefValue.substr(hrefValue.indexOf("id=")+3 , hrefValue.length);
		var objTxt = "<input readonly='true' type='text' id='textbox_"+globalfieldlabel+"' name='property("+globalfieldlabel+")' value='"+spanValue+"' class='textField' onkeydown=\"handleButton('button__"+globalfieldlabel+"',event)\">";
		objTxt += "<img src='/crm/images/lookup.gif' border='0' align='absmiddle' onClick=\"showLookUp('textbox_"+globalfieldlabel+"','actName','"+globalfieldlabel+"','Accounts')\" style='cursor:hand;cursor:pointer'>";
		objTxt += "<input type='hidden' name='property("+globalfieldlabel+")' id='actName' value='"+accountid+"'>";
	}
	else if(globaluitype == 22)
	{
		var hrefValue = "";
		if(subSpanObj.innerHTML != "")
		{
			hrefValue = subSpanObj.href;
		}
		var lifecycleId = hrefValue.substr(hrefValue.indexOf("id=")+3 , hrefValue.length);
		var objTxt = "<input readonly='true' type='text' maxlength= '120' id='textbox_"+globalfieldlabel+"' name='property("+globalfieldlabel+")' value='"+spanValue+"' class='textField' onkeydown=\"handleButton('button__"+globalfieldlabel+"',event)\">";
		objTxt += "<img src='/crm/images/lookup.gif' border='0' align='absmiddle' onClick=\"showLookUp('textbox_"+globalfieldlabel+"','contactlifeRel','"+globalfieldlabel+"','LifeCycles')\" style='cursor:hand;cursor:pointer'>";
		objTxt += "<input type='hidden' name='property("+globalfieldlabel+")' id='contactlifeRel' value='"+lifecycleId+"'>";
	}
	else
	{
		if(globaluitype == 33)
		{
			if(getObj("hiddenValue_"+globalfieldlabel))
			{
				spanValue = getObj("hiddenValue_"+globalfieldlabel).value;
			}
			else if(spanValue.indexOf("<?XML:NAMESPACE PREFIX = SKYPE") > -1)
			{
				return false;
			}
		}
		var objTxt = "<input type='text' id='textbox_"+globalfieldlabel+"' name='property("+globalfieldlabel+")' value='"+spanValue+"' class='textField' width='100%' maxlength='"+globalmaxlen+"' onkeydown=\"handleButton('button__"+globalfieldlabel+"',event)\">";
	}
	var module = getObj("module").value;
	var tableName = getObj("tableName_"+globalfieldlabel).value;
	var columnName = getObj("columnName_"+globalfieldlabel).value;
	var id = getObj("entityId").value;
	var handleSave = "javascript:Callonclickofbutton('/crm/SaveField.do','"+globaltextboxpanid+"','"+globalvaluespanid+"','"+globaltextareapanid+"','"+globalfieldlabel+"','"+module+"','"+globalsubvaluespanid+"','"+globaluitype+"','"+tableName+"','"+columnName+"','"+id+"','"+module+"')";
       
    if(globaluitype==25)
    {
             handleSave= handleSave+";" + "javascript:emailBounceCheck(" +id+",'check',getObj('textbox_"+globalfieldlabel+"').value)";
    }

//	objTxt += "<input type='button' value='Save' class='button' name='button__"+globalfieldlabel+"' onclick=\""+handleSave+"\">";

	objTxt += "<a href=\"javascript:;\" class=\"link\" onclick=\""+handleSave+"\">Save</a>";

	var handleCancel = "handleCancel('"+globalvaluespanid+"','"+globaltextareapanid+"','"+globalfieldlabel+"')";
	objTxt += " or <a class='link' href='javascript:;' onclick=\""+handleCancel+"\">Cancel</a>";
	var divAreaObj = getObj(globaltextareapanid);
	
	if(divAreaObj)
	{
		divAreaObj.innerHTML = objTxt;
	}
	else
	{
		var spanElem = document.createElement("SPAN")
                if(browser_ie)
                {
                    spanElem.id = "textarea_"+globalfieldlabel;
                }
                else
                {			
          	        spanElem.setAttribute("id","textarea_"+globalfieldlabel);
                }        
		        
		var tdObj = document.getElementById("mouseArea__"+globalfieldlabel);
		tdObj.appendChild(spanElem);
		spanElem.innerHTML = objTxt;
	}	
	if(globaluitype == 24 || globaluitype == 25 || globaluitype == 786)
	{
		cals = new Array();
		
		addCalendar(globaltextboxpanid,globaltextboxpanid,globaltextboxpanid,'viewentityform');
	}
	if(globaluitype==300 || globaluitype==301)
	{
		hide(globalvaluespanid);
		var yesSelected=false;
		if(getObj("yes_"+globalfieldlabel).style.display=="none")
		{
			yesSelected=false;
		}
		if(getObj("no_"+globalfieldlabel).style.display=="none")
		{
			yesSelected=true;
		}
		var chkObj = getObj(globaltextboxpanid);
		chkObj.checked=yesSelected;
	}
	else
	{
		hide(globalvaluespanid);
		
		setValue(globalvaluespanid,globaltextboxpanid,globalsubvaluespanid,globaluitype,globalfieldlabel,globalismandatory);
	}
	hide('crmspanid');
	itsonview=true;
	
	if(getObj(globaltextboxpanid))
	{
		getObj(globaltextboxpanid).focus();
	}

	return false;
}


function Callonclickofbutton2(url,module,id,cvname,cvid,start_index,end_index)
{
	if(module == 'Forecasts')
	{
		res = window.confirm('Are you sure ? Your forecast record will be deleted permanently.');
	}
	else
	{
		res = window.confirm('Are you sure ?');
	}
	if(res == false)
	{
		return;
	}
	
	var httphandleDel = getAjaxHttpObj();
	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;
	}
	//url=url+"?module="+ module+ "&display_cust_view_name="+escape(cvname)+"&cvid="+cvid+"&start_index="+ start_index+"&end_index="+ end_index+"&deleteEntityID="+id;
	var args ="module="+ module+ "&display_cust_view_name="+escape(cvname)+"&cvid="+cvid+"&start_index="+ start_index+"&end_index="+ end_index+"&deleteEntityID="+id+''+searchStr;

	var formdata="";
	var advSearchEnableVal="";
	advSearchEnableVal=document.showcvdetails.advSearchEnable.value;
	if(advSearchEnableVal=="true")
	{
		document.showcvdetails.previousCVID.value=document.showcvdetails.display_cust_view_name.value
		formdata = formData2QueryString(document.showcvdetails);
	}
	args+="&"+"advSearchEnableVal="+advSearchEnableVal+"&"+formdata;
	loadAjaxTab4("Loading...");
	httphandleDel.open("POST", url, true);
	httphandleDel.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;charset=UTF-8');

	httphandleDel.onreadystatechange = function() 
	{
		if(httphandleDel.readyState == 4) 
		{
			var str = httphandleDel.responseText;
			if(checkwetherTimedOut(str))
			{
				return;
			}

			if(httphandleDel.status == 200) 
			{
				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 if(str.indexOf("TARGET::::")>-1)
				{
				
					var length=("TARGET::::").length;
                                        var deleteTarget = str.substring(str.lastIndexOf("TARGET::::")+length);
                                        alert(trimBoth(deleteTarget));
					window.location.reload();
				}
				else
				{
					divObj = getObj('idForCV');
					divObj.innerHTML="";
					divObj.innerHTML=str;

					getObj("sidebar3").innerHTML = "";
					getObj("sidebar3").innerHTML = getObj("recentItem").innerHTML ;

					//getObj("dashboardItem").innerHTML = "";
					//getObj("dashboardItem").innerHTML = getObj("dbItem").innerHTML; 
					document.getElementById('ajax_load_tab').style.display='none';
					//hide('zohobusy_loadpage_cv');
				}
				if(searchJSP != undefined)
				{
					//window.historyStorage.put("start",getObj('show').innerHTML);
				}

				if(advSearchEnableVal=="true")
				{
					callAdvSearch(module);
				}

				document.getElementById('ajax_load_tab').style.display='none';
			}
		}
	}
	httphandleDel.send(args);
}

function updateSpamStatus(url,module,id,cvname,cvid,start_index,end_index)
{
    res = window.confirm('Are you sure ?');
	if(res == false)
	{
		return;
	}
	var httphandleDel = getAjaxHttpObj();
	var searchStr='';
	if(document.showcvdetails!=null)
	{
		searchStr="&searchString="+document.showcvdetails.searchString.value+"&sortColumnString="+document.showcvdetails.sortColumnString.value+"&sortOrderString="+document.showcvdetails.sortOrderString.value+"&searchletter="+document.showcvdetails.searchletter.value;
	}
	var args ="module="+ module+ "&display_cust_view_name="+escape(cvname)+"&cvid="+cvid+"&start_index="+ start_index+"&end_index="+ end_index+"&caseID="+id+''+searchStr;

	showCVLoad(module);
  	httphandleDel.open("POST", url, true);
	httphandleDel.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;charset=UTF-8');

	httphandleDel.onreadystatechange = function() 
	{

		if(httphandleDel.readyState == 4) 
		{
			var str = httphandleDel.responseText;

            //showDialog( str, "modal=yes, closeOnEscKey=no" );
			if(checkwetherTimedOut(str))
			{
				return;
			}

			if(httphandleDel.status == 200) 
			{
				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;

//                                   showDialog( str, "modal=yes, closeOnEscKey=no" );

					//getObj("sidebar3").innerHTML = "";
					//getObj("sidebar3").innerHTML = getObj("recentItem").innerHTML ;

					//getObj("dashboardItem").innerHTML = "";
					//getObj("dashboardItem").innerHTML = getObj("dbItem").innerHTML; 

					//hide('zohobusy_loadpage_cv');
                    setCVName(getObj("cvid"),getObj("cvid").options.selectedIndex);
                    
				}
			}
		}
	}
	httphandleDel.send(args);
}

function DeleteTag(tagid,seid,taggerid)
{
showInLine('zohobusy_loadpage_vinfo');

	var httphandle = getHTTPObject();
	if(!isWorking && httphandle)
	{

		var url="IWTagCloudAction.do?delete=true&tagid="+tagid+"&moduleId="+seid;
		httphandle.open("GET", url, true);	
		httphandle.onreadystatechange = function()
                {
                        if(httphandle.readyState == 4)
                        {
                                var str = httphandle.responseText;
                                if(httphandle.status == 200)
                                {
                                      divObj = getObj('tagClouddiv');
                                      divObj.innerHTML=str;
hide('zohobusy_loadpage_vinfo');

                                }
                                isWorking = false;
				callrefresh();

                        }
                }
        }
        httphandle.send(null);
	
}

function Callonclickofbutton3(module,id,cvname,cvid,start_index,end_index)
{
    res = window.confirm('Are you sure ?');
     if(res == false)
	{
		return;
	}
    var comboval= getObj('status_combo').value;
    if(comboval =='-None-')
    {
        return;
    }
	if(module =='Cases' || module == 'Inquiries')
	{
		var form='';
		form=formData2QueryString(document.showcvdetails);
       	var args ="module="+ module+ "&display_cust_view_name="+escape(cvname)+"&cvid="+cvid+"&start_index="+ start_index+"&end_index="+ end_index+"&idlist="+id+"&regstatus="+ comboval+"&status_filter=&showall=true&"+form;
	}

	else if (module=='Attendees')
	{
        var args ="module="+ module+ "&display_cust_view_name="+escape(cvname)+"&cvid="+cvid+"&start_index="+ start_index+"&end_index="+ end_index+"&idlist="+id+"&regstatus="+ comboval+"&status_filter=&showall=true";

	}
	else
	{
        callckfn(false);
		var args ="module="+ module+ "&display_cust_view_name="+escape(cvname)+"&cvid="+cvid+"&start_index="+ start_index+"&end_index="+ end_index+"&idlist="+id+"&regstatus="+ comboval+"&status_filter="+document.showcvdetails.regStatushiddenlist.value+"&showall="+document.showcvdetails.showall.value;
	}
	showCVLoad(module);
	httphandle.open("POST", "/crm/UpdateRegistrationStatus.do", true);
	httphandle.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;charset=UTF-8');

	httphandle.onreadystatechange = function() 
	{

		if(httphandle.readyState == 4) 
		{
			var str = httphandle.responseText;
			if(checkwetherTimedOut(str))
			{
				return;
			}

			if(httphandle.status == 200) 
			{
				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;

					getObj("sidebar3").innerHTML = "";
					getObj("sidebar3").innerHTML = getObj("recentItem").innerHTML ;

					/*getObj("dashboardItem").innerHTML = "";
					getObj("dashboardItem").innerHTML = getObj("dbItem").innerHTML; */

					hide('zohobusy_loadpage_cv');
				}
				if(document.getElementById("advSearchEnable").value=='true')
					callAdvSearch(module);


			}
		}
	}
	httphandle.send(args);
}

function showCVLoad(module)
{
	var cvObject = getObj('zohobusy_loadpage_cv');
	show('zohobusy_loadpage_cv');
	var crmy = findPosY(getObj('cvTable'+" "+module));
	var crmx = findPosX(getObj('cvTable'+" "+module));
	cvObject.style.left=(crmx+150)+"px";
	cvObject.style.top=(crmy+35)+ "px";

}

var sortOrderString = "null";
var temp = "null";
function recordsCount(module,cvid)
{
	loadAjaxTab4("Loading...");
    var formData = formData2QueryString(document.showcvdetails);
	var searchstring = document.getElementById("tagsearch").value;
	var searchletter="";
	if(document.getElementById("searchletter")!=null)
	{
		searchletter =document.getElementById("searchletter").value;
	}
	var url="/crm/RecordsCount.do?module="+module+"&cvId="+cvid+"&searchstring="+searchstring+"&searchletter="+searchletter;
	new Ajax.Request(url,{method:"post",onComplete:function(count){
			document.getElementById('showRecCount').innerHTML=count.responseText;
			document.getElementById('ajax_load_tab').style.display="none";
    },asynchronous:true,postBody:formData,evalScripts:true});
}

//function navigate( url , mod )
function navigate(TOTAL_RECORDS,FORWARD_TO,TO_INDEX,FROM_INDEX,type)
{
	var query = "&ajaxSearch=true";
	var url="/crm/NavigateByRecords.do?totalRecords="+TOTAL_RECORDS+"&fileName="+FORWARD_TO+"&toIndex="+TO_INDEX+"&fromIndex="+FROM_INDEX+"&currentOption=10&"+type+".x=x";

	httpHandle = getHTTPObject();
	httpHandle.open( "POST" , url , true );
	httpHandle.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

	httpHandle.onreadystatechange = function()
	{
		if (httpHandle.readyState == 4)
		{
			var str = httpHandle.responseText;

			if(httpHandle.status == 200 )
			{
				var modObj = getObj( "show" );

  				modObj.innerHTML = "";
				modObj.innerHTML = str;
				document.getElementById('ajax_load_tab').style.display="none";
			}
		}
	}
	loadAjaxTab4("Loading...");
	httpHandle.send(query);
}

		
function segmentPreviewCount(segmentid,frommodule,temporarytable,campaignId,ids,action,finalQuery,rowCount)
{
	var divId = document.getElementById('showRecCount_Segment_Busy');
	divId.style.display = 'inline';
	if(frommodule == undefined || frommodule == 'null' || frommodule=='')
	{
		DWRCommonUtil.getSegmentPreviewCount(segmentid+"",function(response)
		{
			document.getElementById('showRecCount_Segment').innerHTML=response;
			document.getElementById('showRecCount_Segment_Busy').style.display="none";
			return true;					
		}
		);
	}
	else
	{
		DWRCommonUtil.getCampaignPreviewCount(temporarytable,campaignId,ids,finalQuery,function(response)
		{
			document.getElementById('showRecCount_Segment').innerHTML=response;
			document.getElementById('showRecCount_Segment_Busy').style.display="none";
			return true;					
		}
		);
	}
}

function recordsCountSearch(module,searchword)
{
	loadAjaxTab4("Loading...");
	/*
    var formData = formData2QueryString(document.showcvdetails);
	var searchstring = document.getElementById("tagsearch").value;
	var searchletter="";
	if(document.getElementById("searchletter")!=null)
	{
		searchletter =document.getElementById("searchletter").value;
	}
	var url="/crm/RecordsCount.do?module="+module+"&cvId="+cvid+"&searchstring="+searchstring+"&searchletter="+searchletter;
	new Ajax.Request(url,{method:"post",onComplete:function(count){
			document.getElementById('showRecCount').innerHTML=count.responseText;
			document.getElementById('ajax_load_tab').style.display="none";
    },asynchronous:true,postBody:formData,evalScripts:true});
    */
	
	
	
	DWRCommonUtil.getSearchRecordCount(module,searchword,function(response)
	{
		document.getElementById('showRecCount_'+ module).innerHTML=response;
		document.getElementById('ajax_load_tab').style.display="none";
		return true;					
	}
	);
}

function RelatedListrecordsCount(module,personality)
{	
	loadAjaxTab4("Loading...");
	//String registStatusFilterListParam, 


	var entityId=getObj("entityId").value;
	var lifecyclerole="";
	var filterValue;
	var filterOption;
	var chkBoxIds = "";
	var reglist="";
	var isShowAll;


//as now just disabling  this code by changing Iterations to Interations1
//we need to fix this to handle recordcount when filter is being applied
if(module=='Iterations')
{
	if (personality=='REGISTRATIONSPERSONALITY')
	{
		isShowAll = getObj("showall").value
		if( isShowAll == "true")
		{
			filterOption = "ShowAll";
		}
		else
		{
			chkBoxIds = getSelectedChkBoxIdsDup();
	   
			if( ! chkBoxIds ) // no chx box selected
			{
				// return false;
				chkBoxIds=""; 
				filterOption = "";
			}
			else
			{
			filterOption = "RegistStatus";
			}
		}
	}

	if(personality=='LIFECYCLESPERSONALITY')
	{
		getObj("showall").value=showall;
		isShowAll = getObj("showall").value
		if(isShowAll ==true)
		{
			filterOption = "ShowAll";
		}	
		else
		{
			chkBoxIds= getLifeCycleChkBoxIdsDup();
			if( ! chkBoxIds ) // no chx box selected
			{
				chkBoxIds="";
				filterOption = "";
			}
			else
			{
			filterOption = "LifeCycleStatus";
			lifecyclerole= getObj("lrole").value;
			}
		}
	}
	reglist= chkBoxIds;
}

if((module=='Events') && (personality=='ATTENDEESPERSONALITY'))
{
	filterValue= getObj('filter_combo').value;
	if(filterValue=="-None-")
	{
		filterOption="false";
	}
	else
	{
		filterOption="true";
	}
}


DWRCommonUtil.getRecordCount(module,personality, entityId, lifecyclerole,filterOption, reglist,filterValue,function(response)
	{
	//if(response>0)
	{
		var nam="showRecCount1"+personality;
		document.getElementById('ajax_load_tab').style.display="none";
		document.getElementById(nam).style.display = 'block';
		document.getElementById(nam).innerHTML= "";
		document.getElementById(nam).innerHTML= response;
		return true;					
			}
		}
	);

 
}
function sortColumns(columnname,module,cvname,cvid,start_index,end_index,doSort)
{
	// The following code is added to avoid sorting Columns DOB,Email,Company Name in Registration List View 
	if(module=='Registrations')
	{
	if(columnname=='DOB' || columnname=='Email' || columnname=='Organization Name' )
		return;
	}
	if(module =='Accounts'){
		if(columnname=='Organization Owner')
		{
			columnname='Account Owner';
		}
	}
	if ( columnname=='Registrants' )
	{
		return ;
	}
	var tabGroup=document.getElementById("tabGroup").value;
	if(start_index <=end_index)
	{
	var sortObj = getObj('sorted_column');
	if(sortObj!=null)
	{
		var sorted_column = getObj('sorted_column').title;
		var urlSrc=getObj('sorted_column').src;
		var startIndex=urlSrc.indexOf('sort_');
		var endIndex=urlSrc.indexOf('.gif');
		sortOrderString=urlSrc.substring(startIndex,endIndex); 
		//if(sorted_column=='Last Name')sorted_column='Full Name';
		temp= sorted_column;
		if(temp!=null )
		{
			if(temp=='SMCREATORID_FIRSTNAME')
			{
				temp='Created By';
			}
			if(temp=='MODIFIEDBY_FIRSTNAME')
			{
				temp='Modified By';
			}
			if(temp=='SMOWNERID_FIRSTNAME')
			{
				if(module=='Segments')
                                {
                                    temp='Target Owner';
                                }
                                else if(module=='Inquiries')
                                {
                                    temp='Inquiry Owner';
                                }
                                else if(module=='InquiryForms')
                                {
                                    temp='Inquiry Form Owner';
                                }
                                else if(module=='EventForms')
                                {
                                    temp='Event Form Owner';
                                }
				else if(module=='ApplicationForms')
                                {
                                    temp='Application Form Owner';
                                }
                                else if(module=='Venues')
                                {                                    
                                    temp='Location Owner';
                                }
				else if (module=='Activities')
				{
				    temp='Activity Owner';
				}
                                else
                                {
                                    temp=module.substring(0,module.length-1)+ ' Owner';
                                }
			}
		}
	}

	/*if (columnname == "Last Name")
	{
		document.showcvdetails.sortColumnString.value = "First Name";
		columnname = "First Name";
	}
	else*/
		document.showcvdetails.sortColumnString.value = columnname; 


	var sortColumnString = columnname;
	if(temp==columnname)
	{
		if(doSort=='false')
		{
		}
		else if (sortOrderString == "sort_asc")
		{
			sortOrderString = "sort_desc";
			document.showcvdetails.sortOrderString.value = "sort_desc";
		}
		else
		{
			sortOrderString = "sort_asc";
			document.showcvdetails.sortOrderString.value = "sort_asc";
		}
	}
	else
	{
		document.showcvdetails.sortOrderString.value = "sort_asc";
		sortOrderString = "sort_asc";	
	}
	if(getObj("currentOption"))
	{
		document.showcvdetails.rangeValue.value = getObj("currentOption").value;
	}

	var url = '/crm/ShowSelectedCustomView.do';
	var searchstring = document.getElementById("tagsearch").value;
	var searchletter =null;
	if(document.getElementById("searchletter") != null)
	{
		searchletter = document.getElementById("searchletter").value;
	}
	url=url+"?isload=false&tabGroup="+tabGroup+"&module="+ module+ "&display_cust_view_name="+escape(cvname)+"&cvid="+cvid+"&start_index="+ start_index+"&end_index="+ end_index + '&sortColumnString='+escape(sortColumnString)+'&sortOrderString='+escape(sortOrderString)+'&rangeValue='+getObj("rangeValue").value+"&searchString="+searchstring+"&searchletter="+searchletter;
	if(document.getElementById("advSearchEnable")){
            var advSearchEnableVal = document.getElementById("advSearchEnable").value;
        }
	loadAjaxTab4("Loading...");
	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('show');
				divObj.innerHTML="";
				divObj.innerHTML=str;
				document.getElementById('ajax_load_tab').style.display='none';
				 if( advSearchEnableVal=="true"){      
         			   callAdvSearch(module)
			        }
				if(searchJSP != undefined)
				{
					//window.historyStorage.put("start",getObj('show').innerHTML);
					//alert('updated..');
				}
			}
		}
	}
	httphandle.send(null);
	temp = columnname;   
	}
}

function sortColumns5(columname,cvid,viewname,module)
{
	var sortColumnString = columname;
	if(temp==columname)
	{
		if (sortOrderString == "sort_asc")
			sortOrderString = "sort_desc";
		else
			sortOrderString = "sort_asc";
	}
	else
		sortOrderString = "sort_asc";	
	if (!isWorking && http)
	{
		var url="/crm/ShowSelectedCustomView.do?module="
			http.open("GET", url+escape(module)+'&sortColumnString='+escape(sortColumnString)+'&sortOrderString='+escape(sortOrderString)+'&display_cust_view_name='+escape(viewname)+'&cvid='+escape(cvid), true);
		http.onreadystatechange = function () {
			//alert("state=="+http.readyState)
			if (http.readyState == 4) {
				//alert("Response text "+http.responseText);

				txt=http.responseText
					//showDialog( txt, "modal=yes, closeOnEscKey=no" );

					getObj("show").innerHTML = "";
				getObj("show").innerHTML = txt;

				//showDialog( txt, "position=relative" );
				isWorking = false;
			}
		}
		http.send(null);
	}
	temp = columname;
	//document.SubjectNameLookUpForm.submit();
}

// can be removed once handleCancel is wel tested
function handleCancel_old(valuespanid,textareapanid,fieldlabel)
{
	showHide(valuespanid,textareapanid);
	fieldLabelObj = getObj(fieldlabel);
	//fieldLabelObj.className="label";
	itsonview=false;
	return false;
}


function handleCancel(valuespanid,textareapanid,fieldlabel)
{
	getObj(textareapanid).innerHTML = '';
	show(valuespanid);
	fieldLabelObj = getObj(fieldlabel);
	if(fieldLabelObj)
	{
		fieldLabelObj.className="label";
	}
	itsonview=false;
	return false;
}


function patternValidate1(fldName,fldLabel,type,tagValue) {
	// 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
				switch (userDateFormat.toLowerCase()) {

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


						case "dd/mm/yyyy" :
						case "dd.mm.yyyy" :
						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(tagValue)) 
	{
		selectone.getJSAlertValue("crm.alert.entry.valid",null,"en_US",
															function(mesg) { alert(mesg +" "+ fldLabel) })
			// currObj.focus()
			return false
	}
}

function emailValidate1(fldName,fldLabel,tagValue) {
	if(patternValidate1(fldName,fldLabel,"EMAIL",tagValue)==false)
		return false;
	return true;
}

function numValidate1(fldName,fldLabel,format,tagValue,fielddecimal) {
 	//    var val=getObj(fldLabel).value.replace(/^\s+/g, '').replace(/\s+$/g, '')
	var val=tagValue.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 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 (!re.test(val)) 
	{
		//selectone.getJSAlertValue("crm.alert.entry.valid","","en_US",function(mesg) { alert(mesg +' '+ fldLabel) });
		callSelectOneMethod(dwrChkVar,"crm.alert.entry.valid",null,"en_US",fldLabel);
		getObj(fldLabel).focus();
		return false;
	}
	else if (val.indexOf(".")>0 && format == "any" && !re1.test(val))
	{
   		selectone.getJSAlertValue(alertstr,null,"en_US",function(mesg) { alert(mesg) });
        getObj(fldLabel).focus();
        return false;
	} 
	else return true;
}

function numValidate2(fldLabel,format,tagValue) {
	var val=tagValue.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{1,2})*$/;
	}
	if (!re.test(val)) 
	{
		selectone.getJSAlertValue("crm.alert.entry.valid",null,"en_US",function(mesg) { alert(mesg + " " + fldLabel) });
		return false;
	} else return true;
}

function phoneValidate1(fldName,fldLabel,tagValue) 
{
	var val=tagValue.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
	}
}

function formValidate1(currFieldLabel,tagValue,uitype) {
	
	
	var fieldname = (getObj("fieldname").value).split(",");
	var fielddatatype = (getObj("fielddatatype").value).split(",");
    var fielddecimal;
	
    if(getObj("fielddecimal"))
    {
      fielddecimal = (getObj("fielddecimal").value).split(",");
    }
    	
	var fieldlabel = (getObj("fieldlabel").value).split(",");
	
	for (var i=0; i<fieldname.length; i++) 
	{
	
		if(fieldname[i].indexOf("&&&&::") > -1)
		{	

			fieldname[i] = fieldname[i].replace(/&&&&::/g,",");
			fieldlabel[i] = fieldlabel[i].replace(/&&&&::/g,",");
			
		}

		if(currFieldLabel == fieldlabel[i])
		{
		
		}
		else
		{
			continue;
		}
		var type=fielddatatype[i].split("~")
		
			if (type[1]=="M") 
			{
				if (!emptyCheck1(fieldname[i],fieldlabel[i],false,tagValue,uitype))
				{
					return false;
				}
			}
		switch (type[0]) {
			case "O"  : break;
			case "V"  : break;
			case "C"  : break;
			case "E"  : 
				if (tagValue != null 
						&& tagValue.replace(/^\s+/g, '').replace(/\s+$/g, '').length!=0) 
				{
					if (!emailValidate(fieldname[i],fieldlabel[i],tagValue))
						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 "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
								}
					}    
				}
				else if(getObj(fieldname[i]) != null)
				{
					return true;
				}
			break;
			
			case "D"  :    
				if (tagValue != null 
						&& tagValue.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 (tagValue != null 
						&& tagValue.replace(/^\s+/g, '').replace(/\s+$/g, '').length!=0)
				{
					if (!intValidate1(fieldlabel[i],tagValue))
						return false
							if (type[2]) {
								if (!numConstComp(fieldname[i],fieldlabel[i],type[2],type[3]))
									return false
							}
				}
			break;
			case "N"  :
				if (tagValue != null 
						&& tagValue.replace(/^\s+/g, '').replace(/\s+$/g, '').length!=0)
				{
					if (typeof(type[2])=="undefined") var numformat="any"
					else var numformat=type[2]


                        if(fielddecimal!=undefined)
                        {
						if (!numValidate1(fieldname[i],fieldlabel[i],numformat,tagValue,fielddecimal[i]))
							return false
                        }
                        else
                        {
                            		if (!numValidate1(fieldname[i],fieldlabel[i],numformat,tagValue))
							return false
                
                        }
								if (type[3]) 
								{
									if (!numConstComp(fieldname[i],fieldlabel[i],type[3],type[4]))
										return false
								}
				}
			break;
			case "P" :
				if (tagValue != null 
						&& tagValue.replace(/^\s+/g, '').replace(/\s+$/g, '').length!=0)
				{
					if (!phoneValidate1(fieldname[i],fieldlabel[i],tagValue))
						return false
				}
			break;
		}
	}
	
	return true

}

function intValidate1(fldLabel,tagValue) 
{
	var val=tagValue.replace(/^\s+/g, '').replace(/\s+$/g, '')
	if (isNaN(val) || val.indexOf(".")!=-1) 
	{
		selectone.getJSAlertValue("crm.alert.entry.valid",null,"en_US",
															function(mesg) { alert(mesg + " " + fldLabel) })
		getObj(fldLabel).focus()
		return false
	} 
	else return true
}


function emptyCheck2(fldName,fldLabel, fldType,tagValue) {
	var currObj=getObj("textbox_" + fldLabel)



		if(trim(currObj.value).length==0)
		{
			//alert(fldLabel+" cannot be empty")
			//currObj.focus()
			return false;
		}
	return true;



}

function emptyCheck1(fldName,fldLabel, fldType,tagValue,uitype) {
	var currObj=getObj("textbox_" + fldLabel)

        if(uitype == 100)
		{
			currObj=getObj("comboValue"+comboCount);
		}

		if( fldType && currObj.value == "none" ) {

			alert(fldLabel+" cannot be none")

				return false

		}   


	if(trim(currObj.value).length==0)
	{
		selectone.getJSAlertValue("crm.alert.not.none",null,"en_US",
			  function(mesg) { alert(fldLabel + " " + mesg) })
			//currObj.focus()
			return false;
	}
	return true;


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

			currObj.focus()

			return false

	}

	else

		return true

}



function invokeAjaxSecuritySave1()
{
	url="/crm/Security.do";
	var queryStr ="actionName=viewFields&profileId="+getObj('profileslist').value+"&module="+getObj('modlist').value+"&modes=view&bool=sw&ajax";

	httphandle.open("POST", url, true);
	httphandle.onreadystatechange = function()
	{

		if(httphandle.readyState == 4)
		{
			var str = httphandle.responseText;
			if(checkwetherTimedOut(str))
			{
				return;
			}

			if(httphandle.status == 200)
			{
				var divObj1 = getObj('show');
				divObj1.innerHTML="";
				divObj1.innerHTML=str;

				var tableObj = getObj('fieldListTable');
				if(document.myform.edit1==undefined)
				{
					tableObj.width="50%";
				}
				else
				{
					tableObj.width="50%";	
				}





			}


		}
	}

	httphandle.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	httphandle.send(queryStr); 


	//   httphandle.send(queryStr);


}




function invokeAjaxSecuritySave()
{
	var formValues= formDataFormSecurity(document.myform);
	url="/crm/Security.do";
	var queryStr ="actionName=view&module="+getObj('modlist').value+"&profileId="+getObj('profileslist').value+"&modes=view&bool=sw&ajax";
	queryStr=queryStr+"&"+formValues;
	httphandle.open("POST", url, true);
	httphandle.onreadystatechange = function()
	{

		if(httphandle.readyState == 4)
		{
			var str = httphandle.responseText;
			if(checkwetherTimedOut(str))
			{
				return;
			}

			if(httphandle.status == 200)
			{
				if(document.myform.edit1==undefined)
				{
					getObj('edit1').value="Edit"
						getObj('edit1').onclick=invokeAjaxSecurity;

				}
				else
				{
					document.myform.edit1.value="Edit"
						document.myform.edit1.onclick=invokeAjaxSecurity;
				}

				var divObj1 = getObj('show');
				divObj1.innerHTML="";
				divObj1.innerHTML=str;

				var tableObj = getObj('fieldListTable');
				if(document.myform.edit1==undefined)
				{
					tableObj.width="50%";
				}
				else
				{
					tableObj.width="50%";	
				}





				// showDialog(str,"position=relative");
			}


		}
	}

	httphandle.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	httphandle.send(queryStr); 


	//   httphandle.send(queryStr);


}

function formDataFormSecurity(docForm)
{
	var strSubmit = '';
	var formElem;
	var strLastElemName = '';
	fieldcount=getObj('counter').value;


	for(j = 1 ; j <= parseInt(fieldcount) ; j ++)
	{
		var checkname = "checkBoxAjax_"+j;
		if(getObj(checkname).checked==true)
		{
			strSubmit += escape(getObj(checkname).name) +
				'&'
		}
	}

	return strSubmit;
}


function invokeAjaxSecurity()
{
	var i=0;


	if(document.myform.edit1==undefined)
	{
		getObj('edit1').value="Save";
		getObj('edit1').onclick=invokeAjaxSecuritySave;
	}
	else
	{	

		document.myform.edit1.value="Save"
			document.myform.edit1.onclick=invokeAjaxSecuritySave;
	}


	//fieldcount = document.myform.counter.value
	fieldcount=getObj('counter').value; 
	for(j = 1 ; j <= parseInt(fieldcount) ; j ++)
	{
		var checkname = "checkonAjax_"+j
			getObj(checkname).style.display="block"
			//	show(checkname);

			var imagename = "tickAjaximg_"+j
			getObj(imagename).style.display="none"
			//	hide(imagename);
	}
	//document.myform.submit();		
	return true;
}

function handleEnter(url, getValue,showAfter,hideAfter,fieldLabel,module,subid,uitype,tableName,columnName,entityID,module,crmspanid)
{
	if(event.keyCode==13)
	{
		Callonclickofbutton(url, getValue,showAfter,hideAfter,fieldLabel,module,subid,uitype,tableName,columnName,entityID,module);
		hide(crmspanid);
		return false;

	}


}
function showMailDesc(massMailId, mailDesc)
{
	showDialog(mailDesc, "position=absolute,title=Mail Description,top=200,left=200,width=600" );
}


function validatePolicyModule()
{
	if(getObj('property(Policy Condition Radio)')[0].checked==false 
			&& getObj('property(Policy Condition Radio)')[1].checked==false)
	{
		selectone.getJSAlertValue("crm.alert.penalty.sel",null,"en_US",
				function(mesg) { alert(mesg) })
			return false;
	}
	var isPercentage=getObj('property(Policy Condition Radio)')[0].checked;
	var days = getObj('property(DAYS BEFORE)');
	var pers = getObj('property(PERCENTAGE PENALTY)');
	var fixeds = getObj('property(FIXED COST PENALTY)');

	var initval="";
	if(isPercentage)
	{
		initval=pers[0].value;
	}
	else
	{
		initval=fixeds[0].value;
	}

	if(days[0].value=="" && initval=="")
	{
		selectone.getJSAlertValue("crm.alert.term.create.one",null,"en_US",
				function(mesg) { alert(mesg) })
			days[0].focus();
		return false;
	}

	var previousval=-1;
	for(var i=0;i<8;i++)
	{
		var leftval=days[i].value;
		var rightval="";
		if(isPercentage)
		{
			rightval=pers[i].value;
		}
		else
		{
			rightval=fixeds[i].value;
		}

		if(leftval=="" && rightval=="")
		{
			// remaining all values should be empty
			for(var j=i;j<8;j++)
			{
				var lcurr=days[j].value;
				var rcurr="";
				var rightobj;
				if(isPercentage)
				{
					rcurr=pers[j].value;
					rightobj=pers[j];
				}
				else
				{
					rcurr=fixeds[j].value;
					rightobj=fixeds[j];
				}
				if(lcurr!= "")
				{
					selectone.getJSAlertValue("crm.alert.value.empty",null,"en_US",
							function(mesg) { alert(mesg) })
						days[i].focus();
					return false;
				}
				if(rcurr!="")
				{
					selectone.getJSAlertValue("crm.alert.value.empty",null,"en_US",
							function(mesg) { alert(mesg) })
						days[i].focus();
					return false;
				}
			}
		}
		else if (leftval=="")
		{
			selectone.getJSAlertValue("crm.alert.value.empty",null,"en_US",
					function(mesg) { alert(mesg) })
				days[i].focus();
			return false;

		}
		else if(rightval=="")
		{
			if(isPercentage)
			{
				selectone.getJSAlertValue("crm.alert.percentage.penalty.blank",null,"en_US",
						function(mesg) { alert(mesg) })
					pers[i].focus();
				return false;
			}
			else
			{
				selectone.getJSAlertValue("crm.alert.fixed.cost.penalty.blank",null,"en_US",
						function(mesg) { alert(mesg) })
					fixeds[i].focus();
				return false;

			}


		}
		else if(!numValidate2('Days Before','any',leftval))
		{
			days[i].focus();
			return false;
		}
		else 
		{
			// Rana: commenting out validation code 
			// (user can enter number of days in any order)
			/*
			   if(leftval<=previousval)
			   {
			   alert("# of days can be entered in any order");
			   days[i].focus();
			   return false;
			   }
			 */
			previousval=leftval;

			if(isPercentage)
			{
				if(!numValidate2('Percentage Penalty','any',rightval))
				{
					pers[i].focus();
					return false;
				}
				if(rightval>100 || rightval < 0)
				{
					selectone.getJSAlertValue("crm.alert.percentage.penalty.range",null,"en_US",
							function(mesg) { alert(mesg) })
						pers[i].focus();
					return false;
				}
			}
			else
			{
				if(!numValidate2('Fixed Cost Penalty','any',rightval))
				{
					fixeds[i].focus();
					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 handleEnter2(saveButton,event)
{
    if (typeof browser_ie == 'undefined')  
    {
    }
    else if(browser_ie)
    {
    }
    else
    {
    }    

       if(event.keyCode==13)
         {
             getObj(saveButton).fireEvent("onclick", event);
             event.returnValue=false;
                return false;;
        }
    return false;
}
*/

function set_cookie ( 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;
}

function get_cookie ( cookie_name )
{
  var results = document.cookie.match ( cookie_name + '=(.*?)(;|$)' );

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

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();
}


function sortColumnsIW(columname, targetstring, previous_sort_column,module,parentId )
{

    append_sort_column = "sortColumnString_"+targetstring.toUpperCase();
		append_sort_order = "sortOrderString_"+targetstring.toUpperCase();
		
		if (columname == "Last Name")
		{
			getObj( append_sort_column ).value = "First Name";
			columname = "First Name";
		}
		getObj( append_sort_column ).value = columname;
		if (columname == previous_sort_column )
		{
			if (getObj( append_sort_order ).value == "sort_asc")
				getObj( append_sort_order ).value = "sort_desc";
			else
				getObj( append_sort_order ).value = "sort_asc";
		}
		else
			getObj( append_sort_order ).value = "sort_asc";


    var sortparameters = append_sort_column+"="+ columname +"&"+ append_sort_order+"="+getObj( append_sort_order ).value;

    isRelatedListLoaded=false;
    toggleRelatedList(targetstring.toUpperCase(),module,sortparameters);        
}

var isRelatedListLoaded = false;
var currentrelatedlistid;

function refreshRelatedList_new(module)
{
    if(currentrelatedlistid!=undefined)
    {
        isRelatedListLoaded=false;
        toggleRelatedList(currentrelatedlistid,module);        
    }
}

function toggleRelatedList(id,module,sortparameters)
{
 var entityId=getObj("entityId").value;
    if(isRelatedListLoaded == false)
    {
        document.getElementById('moreinfo_load').style.display="block";
        showInLine('moreinfo_load');
        //loadAjaxTab2('','lightblue');
        var httphandle = getHTTPObject();
        var url="/crm/RelatedListAlone.do?module="+module+"&id="+entityId;
        if(sortparameters!=undefined)
        {
                url = url+"&"+sortparameters;
        }
         httphandle.open("GET",url,true);
         httphandle.onreadystatechange = function() 
         {
			 if(httphandle.readyState == 4) 
             {
                   if (httphandle.status == 200) 
                   {
	                    //var item = httphandle.responseText;
                        //alert("done");
                        hide('moreinfo_load');  
                        isRelatedListLoaded=true;
                        getObj('refresh_relatedlist').style.display="inline";
                        getObj("relatedList").innerHTML="";
                        getObj("relatedList").innerHTML=httphandle.responseText;
                        setDisplayNone_new();
                        toggleRelatedList_old(id,module);      
                        
                   }
              }
         }
        httphandle.send(null);
    }
    else
    {
        toggleRelatedList_old(id,module);   
    }    
}


function toggleRelatedList_old(id,module)
{
    var x = PersonalityArray.length;
	for (var i = 0 ; i < x ; i++)
	{
		var listObj=getObj(PersonalityArray[i])
		if(listObj != null)
		{
			if(PersonalityArray[i] == id)
			{
                  //          new Effect.SlideDown(id);
                  currentrelatedlistid=id;  
                  listObj.style.display="block";  
			}
			else
			{
                       listObj.style.display = "none";
			}
		}
	}
	if(module=="Iterations")	
	{
			getObj("registFilterRelList").style.display = "none";	
			getObj("LifeFilterRelList").style.display = "none";
			getObj("registerFilter").checked=false;
			getObj("LifeCycleFilter").checked=false;
       	}
    set_cookie("Relatedlist_"+module,id);
}


function expandRelatedList_new(module)
{
     var id= get_cookie("Relatedlist_"+module);
    if(id==null)
        {
        }
    else
        {
          toggleRelatedList(id,module);
        }
}
function expandRelatedList(module)
{
    var id= get_cookie("Relatedlist_"+module);
    if(id==null)
        {
        }
    else
        {
            showInLine(id);
        }
}
function expandLifeCycleList()
{
    var id= get_cookie("Relatedlist_Iterations");
    if(id==null)
        {
        }
    else
        {
            show(id);
        }
}

function setExpandCollapse()
{
   //if(! (curmodule=="Tasks" || curmodule=="Appointments") )	
   //{

	var x = PersonalityArray.length;
	for (var i = 0 ; i < x ; i++)
	{
		var listObj=getObj(PersonalityArray[i])
		if(listObj != null)
		{
			var toggleImageObj=getObj(PersonalityArray[i]+"img")
			var status = get_cookie(PersonalityArray[i])

			if (status == "none")
			{
				listObj.style.display="none"
				toggleImageObj.src="/crm/images/expand.gif"
			}
			else
			{
				listObj.style.display="block"
				toggleImageObj.src="/crm/images/collapse.gif"
			}
		}
	}
  //}
}
/*function showLocateMapMenu(module)
    {
         if(module=="Contacts")
	 {
	    getObj("dropDownMenu").style.display="block"
            getObj("dropDownMenu").style.left=findPosX(getObj("locateMap"))
            getObj("dropDownMenu").style.top=findPosY(getObj("locateMap"))+getObj("locateMap").offsetHeight
	}
	else if(module=="Accounts" || module=="Quotes" || module=="SalesOrders" || module=="PurchaseOrders" || module=="Invoices" )
	{
            getObj("dropDownMenu1").style.display="block"
            getObj("dropDownMenu1").style.left=findPosX(getObj("locateMap"))
            getObj("dropDownMenu1").style.top=findPosY(getObj("locateMap"))+getObj("locateMap").offsetHeight
        }
	else if( module=="Leads" || module=="Vendors")
	{
		
             if( getObj("value_Street").innerHTML!="" && getObj("value_City").innerHTML!="" && getObj("value_State").innerHTML!="" && getObj("value_Zip Code").innerHTML!="" && getObj("value_Country").innerHTML!="")
                {
                          mapParameter = getObj("value_Street").innerHTML+' '+getObj("value_City").innerHTML+' '+getObj("value_State").innerHTML+' '+getObj("value_Zip Code").innerHTML+' '+getObj("value_Country").innerHTML
                }
                else
                {
                        selectone.getJSAlertValue("crm.locate.mailing",null,"en_US",
			  																					function(mesg) { alert(mesg) })
                                return;
                }
	        document.viewentityform.action="http://maps.google.com/maps?q="+mapParameter
        	document.viewentityform.target="_blank"
	        document.viewentityform.submit()

	}



    }
*/

/*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=="block")
                            getObj("dropDownMenu").style.display="none"
	   
	  		if (getObj("dropDownMenu1") && getObj("dropDownMenu1").style.display=="block")
                            getObj("dropDownMenu1").style.display="none"
       	    }
    }
*/
/*function showDrillDownPtr() 
   {
	if(getObj("module").value=="Iterations")
       	{
        	getObj("registFilterRelList").style.display = "none";
               	getObj("LifeFilterRelList").style.display = "none";
		getObj("registerFilter").checked = false;
		getObj("LifeCycleFilter").checked = false;
       	}

	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)
	}
}
*/

function QCAjaxvalues(moduleName)
   {

  var http = getHTTPObject();

      var divid=document.getElementById('qcformpage');
   var input_nodes=divid.getElementsByTagName("input");
   var valuesNode =input_nodes.length;
   var savetype='qcAjax';
      var count=0;
   var strarray = new Array();
   for(var i=0;i<valuesNode;i++)
   {
       if(input_nodes[i].value != "" && input_nodes[i].type !="button")
       {
           strarray[count++]= input_nodes[i].name+"="+ input_nodes[i].value;
       }
    }
   //to get the textarea fields
   var textarea_nodes = divid.getElementsByTagName("textarea");
   var textarea_length = textarea_nodes.length;

   for(var j=0;j<textarea_length;j++)
   {
       if(trim(textarea_nodes[j].value) != "")
           strarray[count++]= textarea_nodes[j].name+"="+textarea_nodes[j].value;
   }
   //to get the textarea fields
   var select_nodes = divid.getElementsByTagName("select");
   var select_length = select_nodes.length;

   for(j = 0;j < select_length;j++)
   {
       strarray[count++]= select_nodes[j].name+"="+select_nodes[j].options[select_nodes[j].selectedIndex].value;
   }
   var urlstring = strarray.join("&");
        if( http)
        {
                showajax('ajaxload');
      var url = getObj('qcformpage').action;
                alert(url);
                var formData="";
                formData = formData2QueryString(getObj('qcformpage'));
                var args = "module="+moduleName+"&ajax=true&"+formData;
                //alert("formData-->"+ formData);

                http.open("POST", url, true);
                http.onreadystatechange = function()
                {
                        if(http.readyState == 4)
                        {
                                var str = http.responseText;
                                alert(str);
                                hideajax('ajaxload');
                                if(checkwetherTimedOut(str))
                                {
                                        return;
                                }
                                if(http.status == 200)
                                {
                                }
                                isWorking = false;
                        }
                }
                http.send(args);
        }

}
function showajax(Lay){
	if(getObj(Lay)!=undefined)
        {
        document.getElementById(Lay).style.visibility = 'visible';
        }
}
function hideajax(Lay){
        if(getObj(Lay)!=undefined)
        {
        document.getElementById(Lay).style.visibility = 'hidden';
        }
}
function setGMultiSelectForQuickCreate()
{
	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 caseTemplateQCreate()
{
	var templatename=document.getElementById("Template Name");
	var v = templatename.value;
	if(v.length==0)
	{
		alert("Template Name cant be blank")
		return false;
	}
	else
	{
		 templatename=document.getElementById("Subject");
		 v = templatename.value;
		if(v.length==0)
		{
				alert("Template Subject cant be blank")
			return false;
		}
		else
		{
			 templatename=document.getElementById("property(CaseType)");
			 v = templatename.value;
			if(v=="-None-")
			{
				alert("Template Type cant be blank")
				return false;
			}
			else
			{
				 templatename=document.getElementById("property(CaseChannel)");
				 v = templatename.value;
				if(v=="-None-")
				{
					alert("Template Channel cant be blank")
					return false;
				}
				else
				{
					document.createEntityForm.action="/crm/CommonTemplate.do?template=CaseTemplate&action=savefromquick&isload=true";
					document.createEntityForm.submit();
				}
			}
		}
	}	
}
function processQuickCreate(module,cvid,isQuickCreateVar)
{
		var lookUp;
		userDateFormat = getObj("datePattern")?getObj("datePattern").value:"";
		var comboCount = getObj("comboCount").value-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++;
                                }
                                else if(j==0)
                                {
                                        getObj("combo"+k).value  = "";
                                }
                        }
                }
        }
		
		//for uiType 500
		if(getObj("totalGroups"))
		{
			setInterestGroups(module,"");
		}
		setGMultiSelectForQuickCreate();
        if(module=='Campaigns')
        {
        		if(getObj("property(Campaign Name)").value==null || getObj("property(Campaign Name)").value=='')
				{	
					selectone.getJSAlertValue("crm.alert.campaign.name.blank","Campaign Name","en_US",
																		function(mesg) { alert(mesg) })
					return false;
				}
				else if(getObj("property(Email Template)").value==null || getObj("property(Email Template)").value=='')
				{	
					selectone.getJSAlertValue("crm.alert.email.template.blank",null,"en_US",
																		function(mesg) { alert(mesg) })
					return false;
				}
				else if(getObj("property(mail_profile)").value==null ||getObj("property(mail_profile)").value=='')
				{
					selectone.getJSAlertValue("crm.alert.from.blank",null,"en_US",
																		function(mesg) { alert(mesg) })
					return false;
				}
				else if(getObj("property(target_name)")!=null && getObj("property(target_name)").value==null ||getObj("property(target_name)").value=='')
				{
					selectone.getJSAlertValue("crm.alert.target.blank",null,"en_US",
																		function(mesg) { alert(mesg) })
					return false;
				}
				if(getObj('property(schedule)')!=null && getObj('property(schedule)').value=='Select Date & Time')
				{
					//var datePattern=/^\d{1,2}(\/)\d{1,2}\1\d{4}$/
					var startdate=getObj('property(startDate)').value;
					if((getObj('property(startDate)').value=='' || getObj('property(hours)').value=='HH' ||getObj('property(minutes)').value=='MM' ||getObj('property(hours)').value=='null' ||getObj('property(minutes)').value=='null'))
					{
						selectone.getJSAlertValue("crm.alert.date.time.select",null,"en_US",
						  												function(mesg) { alert(mesg) })
						return false;
					}
					else if(!dateValidate("property(startDate)","Start Date & Time","DATE"))                                            
                                        {                        
                                            return false;
                                        }
					else
					{
						act=1;
						var startdate=getObj("property(startDate)").value;
						var hours=getObj("property(hours)").value;
						var mins=getObj("property(minutes)").value;
						var scheduleTime=startdate+" "+hours+":"+mins;
						DWRCommonUtil.compareDateTime(scheduleTime,function(response)
						{
							if(response>0)
							{
								act=0;
								getObj('quickCreateForm').submit();
								return true;					
							}
							else
							{
								alert("Start date & time has to be in the future ");
								return false;
							}
						}
						);
					}
				}	
        }
        if(module=='Scholarships')
        {
        	var totalfunds=eval(getObj("property(Total Funds)").value);
        	var avgfund=eval(getObj("property(Average Award Amount)").value);
        	if(avgfund > totalfunds)
        	{
        		selectone.getJSAlertValue("crm.alert.total.funds.avg.amt",null,"en_US",
																			function(mesg) { alert(mesg) })
        		return false;
        	} 
        }
        if (pageValidate())
        {
               if(module=="Cases")
                {
                     if (!emptyCheck("property(CaseType)","Type","M"))
                    return false
                    if (!emptyCheck("property(CaseChannel)","Channel","M"))
                    return false
                }

                if(module =='Policies')
                {
                    if(!validatePolicyModule())
                        {StudentId
                            return false;
                        }
                }
                
        }
        else
        {
            return false;
        }
        
        if(module=="Contacts")
        {
                lookUp=document.getElementById("lookUp").value
                quickCreateContact(lookUp,module,cvid,isQuickCreateVar);
                return false;
        }
        
        if(module == "Registrations")
        {
            var pgmid=null;
            var iterid=null;
            var contactid=null;
            pgmid=getObj("property(programs:Program Name)").value;
            iterid=getObj("property(iterations:Iteration Name)").value;
            contactid=getObj("property(contactName:Participant)").value;
            var regisid=null;
            DWRCommonUtil.duplicateRegistrationChk
                          (pgmid,iterid,contactid,regisid,
                          function(isPresent)
                          {
                              regisPresent=isPresent;
                              if(regisPresent == true)
                               {
                                   alert("Already Registration Exists for Same Iteration & Participant");
                                   return false;
                               }
                               else
                               {
                                   quickCreateSubmitEntityForm(module,cvid,isQuickCreateVar);
                               }
                          });
        }
        else
        {
            quickCreateSubmitEntityForm(module,cvid,isQuickCreateVar);
        } 
  }


function quickCreateSubmitEntityForm(module,cvid,isQuickCreateVar)
{
   url="/crm/QuickCreateCommonModule.do?module="+module+"&ajax=true&cvid="+cvid;
   if(isQuickCreateVar && false)//TODO HANDLE LATER
     {
         handleNewQuickCreate(module);
         return false;
      }
if(act==0)
{

act=1;
setTimeout("act=0",3000);
getObj('quickCreateForm').submit();       
}
else
{
	return false;
}


}

function handleNewQuickCreate(moduleName)
{
showajax('ajaxload');
var url="/crm/QuickCreateCommonModule.do";
var args = "module="+moduleName+"&ajax=true";    
var http= getHTTPObject();
http.open("POST", url, true);
                http.onreadystatechange = function()
                {
                        if(http.readyState == 4)
                        {
                                var str = http.responseText;
                                alert(str);
                        }
                }
                http.send(args);

}


function formValidate2(currFieldLabel,fieldName,dataType) 
{

    var tagValue= getObj(fieldName).value;
		if (dataType=="M") 
		{
			if (!emptyCheck3(currFieldLabel,getObj(fieldName),tagValue))
			{
            	return false;
			}
		}

		if (dataType=="E") 
		{

				if (tagValue != null 
						&& tagValue.replace(/^\s+/g, '').replace(/\s+$/g, '').length!=0) 
				{
					if (!emailValidate1(fieldName,currFieldLabel,tagValue))
                    {
                        getObj(fieldName).focus();
						return false
                    }
				}
	
       }


    return true;
}
function emptyCheck3(fldLabel,currObj,tagValue) {

		if( currObj.value == "none" ) {
			
			selectone.getJSAlertValue("crm.alert.not.none",null,"en_US",
			  function(mesg) { alert(fldLabel + " " + mesg) })
    currObj.focus();

				return false

		}   


	if(trim(currObj.value).length==0)
	{
		selectone.getJSAlertValue("crm.alert.not.empty",null,"en_US",
			  											function(mesg) { alert(fldLabel + " " + mesg) })		
			currObj.focus()
			return false;
	}
	return true;


	if (currObj.value.replace(/^\s+/g, '').replace(/\s+$/g, '').length==0) {

		selectone.getJSAlertValue("crm.alert.not.empty",null,"en_US",
			  											function(mesg) { alert(fldLabel + " " + mesg) })
			currObj.focus()

			return false

	}

	else

		return true

}


function emptyCheck4(fldLabel,tagValue) {

		if( tagValue == "none" ) {

			selectone.getJSAlertValue("crm.alert.not.none",null,"en_US",
			  											function(mesg) { alert(fldLabel + " " + mesg) })
				return false

		}   

if( tagValue == "<br>" ) {

			selectone.getJSAlertValue("crm.alert.not.none",null,"en_US",
			  											function(mesg) { alert(fldLabel + " " + mesg) })
				return false

		} 

	if(trim(tagValue).length==0)
	{
		selectone.getJSAlertValue("crm.alert.not.empty",null,"en_US",
			  											function(mesg) { alert(fldLabel + " " + mesg) })
			return false;
	}
	return true;


	if (tagValue.replace(/^\s+/g, '').replace(/\s+$/g, '').length==0) {

		selectone.getJSAlertValue("crm.alert.not.empty",null,"en_US",
			  											function(mesg) { alert(fldLabel + " " + mesg) })
			return false

	}

	else

		return true

}
function refreshLifeRelatedList( iterationId,showall)
{
        var filterOption;
        var chkBoxIds = "";
	var lifecyclerole="";

        if (!isWorking && http)
        {
		getObj("showall").value=showall;
		var isShowAll = getObj("showall").value
                if( isShowAll ==true)
                {
			filterOption="";
                }	
		else
		{
                         chkBoxIds= getLifeCycleChkBoxIds();
       
                         lifecyclerole= getObj("lrole").value;     
				 if( ! chkBoxIds ) // no chx box selected
                                {
                                        return false;
                                }
                                filterOption = "LifeCycleStatus";
				getObj("previousvalue").value=lifecyclerole;
		}
  							//alert("Filter option = " + filterOption);                      
                var url ="/crm/RefreshLifeRelatedList.do?module=Iterations&id="+iterationId+"&registStatusFilterList="+escape(chkBoxIds)+"&filterOption="+filterOption+"&lifecyclerole="+lifecyclerole;
	 							http.open("GET", url, true);
	 							//openPopUp("asasdsd",this,url,"test",800,600,"");
                http.onreadystatechange = function()
                {
                        if(http.readyState == 4)
                        {
                                var str = http.responseText;
                                //alert("response from action class" + str);
                                //showDialog(str);
                                divObj = getObj('relatedList');
                                divObj.innerHTML="";
                                divObj.innerHTML=str;
                                hide('zohobusy_filter_search');
                                //alert("------------expanding ------------- ");
                                expandLifeCycleList();
                                getObj('LifeCycleFilter').checked=true;
                                isWorking = false;
                        }
                }
                http.send(null);

        }

        return false;
}
function getLifeCycleChkBoxIds()
{
	var checkObj = getObj("lifecyclechk");
        noofrows = checkObj.length;
	var append_ids = "";
	
	if (noofrows == undefined )
	{
		if (checkObj.checked)	
		{
	               append_ids = checkObj.value;  
		}
		else 
		{
    			alert('Select atleast one filter option')
			return false;	
		}
	}
	else if (noofrows != 0)
	{
		if (getNoOfSelectedLifeFilter() == 0)
		{
			alert('Select atleast one filter option')
			return false;	
		}	
		else 
		{	
			for(i = 0 ; i < noofrows ; i++)
			{
				if (checkObj[i].checked)
				{
				append_ids= checkObj[i].value+";"+append_ids;
				}
			}               
        	}
	}
	return append_ids;
}

// duplication of the above method except alerts...
function getLifeCycleChkBoxIdsDup()
{
	var checkObj = getObj("lifecyclechk");
        noofrows = checkObj.length;
	var append_ids = "";
	
	if (noofrows == undefined )
	{
		if (checkObj.checked)	
		{
	               append_ids = checkObj.value;  
		}
		else 
		{

			return false;	
		}
	}
	else if (noofrows != 0)
	{
		if (getNoOfSelectedLifeFilter() == 0)
		{
			return false;	
		}	
		else 
		{	
			for(i = 0 ; i < noofrows ; i++)
			{
				if (checkObj[i].checked)
				{
				append_ids= checkObj[i].value+";"+append_ids;
				}
			}               
        	}
	}
	return append_ids;
}

function getNoOfSelectedLifeFilter()
{
	  var checkObj = getObj("lifecyclechk");
	  noofrows = checkObj.length;
	  noofselected = 0
	  for(i=0 ; i < noofrows ; i++)
	  {
	  if (checkObj[i].checked)
	  noofselected ++;
	  }
	 return noofselected;
}	
function handleOnChangeRelated(selectObj)
{
	if(getObj("previousvalue").value!="" && getObj("previousvalue").value!="None")
	{
	hide(getObj("previousvalue").value);
	}	
	getObj("previousvalue").value=selectObj.value;	
	if(selectObj.value!="None")
	{
    	  show(selectObj.value);
	  var checkObj = getObj("lifecyclechk");
	  noofrows = checkObj.length;
	  noofselected = 0
	  for(i=0 ; i < noofrows ; i++)
	  {
	  checkObj[i].checked=false;
	  }

	}
}
function handleShowAllLifeCycles( iterationId)
{
 getObj("showall").value='true';
 refreshLifeRelatedList(iterationId,true);
}
function handleShowAllRelated( iterationId)
{
hide('statusPanel');
hide('value1');
show('value2');
getObj("showall").value='true';
refreshRelatedList( iterationId)
}
function handleShowSelectedRelated()
{
    show('statusPanel');
    show('value1');
    hide('value2');
    getObj("showall").value='false';
}


function refreshRelatedList( iterationId)
{
        var filterOption;
        var chkBoxIds = "";

        if (!isWorking && http)
        {
                var isShowAll = getObj("showall").value
                        if( isShowAll == "true")
                        {
                                filterOption = "ShowAll";
                                //getObj('registerFilter'
                        }
                        else
                        {
                                chkBoxIds = getSelectedChkBoxIds();
                                if( ! chkBoxIds ) // no chx box selected
                                {
                                        return false;
                                }
                                filterOption = "RegistStatus";
                                
                        }
  							//alert("Filter option = " + filterOption);                      
                var url ="/crm/RefreshRelatedList.do?module=Iterations&id="+iterationId+"&registStatusFilterList="+escape(chkBoxIds)+"&filterOption="+filterOption;
                document.getElementById('zohobusy_filter_search').style.display = 'inline';
	 							http.open("GET", url, true);
	 							//openPopUp("asasdsd",this,url,"test",800,600,"");
                http.onreadystatechange = function()
                {
                        if(http.readyState == 4)
                        {
                                var str = http.responseText;
                                //alert("response from action class" + str);
                                //showDialog(str);
                                divObj = getObj('relatedList');
                                divObj.innerHTML="";
                                divObj.innerHTML=str;
                                hide('zohobusy_filter_search');
                                //alert("------------expanding ------------- ");
                                expandRelatedList('Iterations');
                                getObj('registerFilter').checked=true;
                                isWorking = false;
                        }
                }
                http.send(null);
        }
        return false;
}
function getSelectedChkBoxIds()
{
	var checkObj = getObj("regid");
        noofrows = checkObj.length; 
	var append_ids = "";
	
	if (noofrows == undefined )
	{
		if (checkObj.checked)	
		{
	               append_ids = checkObj.value;                
		}
		else 
		{
    			alert('Select atleast one filter option')
			return false;	
		}
	}
	else if (noofrows != 0)
	{
		if (getNoOfRegisSelectedFilter() == 0)
		{
			alert('Select atleast one filter option')
			return false;	
		}	
		else 
		{	
			for(i = 0 ; i < noofrows ; i++)
			{
				if (checkObj[i].checked)
				append_ids= checkObj[i].value+";"+append_ids;
			}               
        	}
	}
	return append_ids;
}

//duplication of the above method except alerts..
function getSelectedChkBoxIdsDup()
{
	var checkObj = getObj("regid");
        noofrows = checkObj.length; 
	var append_ids = "";
	
	if (noofrows == undefined )
	{
		if (checkObj.checked)	
		{
	               append_ids = checkObj.value;                
		}
		else 
		{
//    			alert('Select atleast one filter option')
			return false;	
		}
	}
	else if (noofrows != 0)
	{
		if (getNoOfRegisSelectedFilter() == 0)
		{
			//alert('Select atleast one filter option')
			return false;	
		}	
		else 
		{	
			for(i = 0 ; i < noofrows ; i++)
			{
				if (checkObj[i].checked)
				append_ids= checkObj[i].value+";"+append_ids;
			}               
        	}
	}
	return append_ids;
}

function getNoOfRegisSelectedFilter()
{
	var checkObj = getObj("regid");
        noofrows = checkObj.length;
        noofselected = 0
        for(i=0 ; i < noofrows ; i++)
        {
                if (checkObj[i].checked)
                        noofselected ++;
        }
        return noofselected;
}


/*function printAction(xx, module)
{
	window.open("/crm/PrintEntityInfo.do?module="+module+"&id="+xx+"&action=print","PrintEntityInformation","top=30,left=150,menubar=yes,toolbar=no,location=no,status=yes,scrollbars=yes,resizable=yes,width=750,height=600");	
}
*/
/*function createPotentialForContact(contactid,contactname,accountid,accountname, anchor)
{
    document.viewentityform.action="/crm/Create.do?module=Potentials&accountid="+accountid+"&accountname="+accountname + "&contactid=" + contactid+ "&entityname="+contactname+"&entityid="+contactid+"&relmodule=Contacts&returnAnchor="+anchor;
    document.viewentityform.submit();
}
*/
function emailBounceCheck(contactId,actionType,emailid_new)
{
	//var emailId = getObj("textbox_Email").value;
    //var emailId = getObj("subvalue_Email").innerHTML;
    var emailId= emailid_new;
	if(contactId != null & actionType != null)
	{
		if (!isWorking && http)
		{
                        http = getHTTPObject();
			var url ="/crm/IWEmailBounceCheck.do?contactId="+contactId+"&actionType="+actionType+"&emailId="+emailId;
			http.open("GET", url, true);
			http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;charset=UTF-8');
			http.onreadystatechange = function()
			{
				if(http.readyState == 4)
				{
					var str = http.responseText;
					divObj = getObj('EmailBounceError');
					divObj.innerHTML="";
					divObj.innerHTML=str;
					isWorking = false;
				}
			}
			http.send("");
		}
	}
	else
	{
		return false;
	}
}

function togglecontent(divid)
{
   var style = document.getElementById(divid).style.display ;
   if(style == 'none')
   {
        //getObj(divid).style.display = 'block';     
        document.getElementById(divid).style.display= 'block';  
	//getObj("toggleImageObj").src="images/collapse.gif"
   }
   if(style == 'block')
   {
        //getObj(divid).style.display = 'none';
        document.getElementById(divid).style.display= 'none';  
        //document.getElementById("callcollapseid").style.display= 'block'; 
        //getObj("toggleImageObj").src="/crm/images/expand.gif"
   }
}         
function validateQuickCampWizard()
{
	
}
function feedback(obj)
{
document.getElementById("Feedback").innerHTML="";
if (!isWorking && http)
    {
                var url ="/crm/ShowFeedBackPage.do";
                http.open("GET", url, true);
                http.onreadystatechange = function()
                {
                        if(http.readyState == 4)
                        {
                                var str = http.responseText;
document.getElementById("Feedback").innerHTML=str;
grow("Feedback")
                        }
                }
                http.send(null);
        }
return false
}
function mailTo(obj,module,id,skintype)
{
	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",800,600,"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",800,500,"menubar=no,toolbar=no,location=no,status=no,scrollbars=yes,resizable=yes"); 
			    }
	        }
         );
}
function sendMailContactAction(obj,module,chk,skintype)
{
    var checkboxes=getObj(chk);
    var noofrows=checkboxes.length;
    var append_ids = "";
    var append_emails = "";
    var emailPresent=false;
    if (noofrows == undefined )
    {
        if (checkboxes.checked)	
        {
            append_ids = checkboxes.value;   
            if(append_ids!=null)
           	{
	            DWRCommonUtil.containsEmail
	            (
		            append_ids,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)
					    {
					        features="menubar=no,toolbar=no,location=no,status=no,scrollbars=yes,resizable=yes";
					        //var url ="/crm/jsp/IWSendMailForContacts.jsp?append_ids="+append_ids+"&append_emails="+append_emails+"&module="+module+"&skintype="+skintype;
                            var url ="/crm/IWSendMailForContacts.do?append_ids="+append_ids+"&append_emails="+append_emails+"&module="+module+"&skintype="+skintype;
					        openPopUp("ghjhjgk",obj,url,"test",750,500,features);
					    }
		            }
	            );
           	}
            /*var loop = "sendEmailCont_"+checkboxes.value ;                            
            append_emails=getObj(loop).value;*/
        }
        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 (checkboxes[i].checked)
                {
                append_ids= checkboxes[i].value+";"+append_ids;
              /*  var loop = "sendEmailCont_"+checkboxes[i].value ;                
                append_emails=(getObj(loop).value)+";"+append_emails;*/
                 }
                
            } 
          	if(append_ids!=null)
           	{
	            DWRCommonUtil.containsEmail
	            (
		            append_ids,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)
					    {
					        features="menubar=no,toolbar=no,location=no,status=no,scrollbars=yes,resizable=yes";
					        var url ="/crm/jsp/IWSendMailForContacts.jsp?append_ids="+append_ids+"&append_emails="+append_emails+"&module="+module+"&skintype="+skintype;
					        openPopUp("ghjhjgk",obj,url,"test",750,500,features);
					    }
		            }
	            );
          	}
        }
    }
}


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);
    
    //tagName.style.left= leftSide + 150 + 'px';
    tagName.style.top= topSide + 'px';
    tagName.style.display = 'block';
    tagName.style.visibility = "visible";
}
function callAttendeeFilter(module,cvname,cvid,showAll)
{
var filtervalue=getObj("attendeefilter_combo").value;
if(filtervalue=="-None-")
{
return false;
}
else
{
	
        if (!isWorking && http)
	{
               
                var args ="module="+module+"&display_cust_view_name="+escape(cvname)+"&cvid="+cvid+"&rangeValue="+escape(getObj("rangeValue").value)+"&filtervalue="+filtervalue;
                
            }
	
	var url ="/crm/IWFilterRegAction.do?"+args+"&showAll="+ showAll;
	
	http.open("GET", url, true);	
	http.onreadystatechange = function() 
	{
		if(http.readyState == 4) 
		{
			var str = http.responseText;
			if(checkwetherTimedOut(str))
			{
				return;
			}
			if(http.status == 200) 
			{
				divObj = getObj('idForCV');
				divObj.innerHTML="";
				divObj.innerHTML=str;
			}
			isWorking = false;
		}
	}	
	http.send(null);
	}

return false;
}


function sendSMSContactAction(obj,module,chk,skintype)
{
    var checkboxes=getObj(chk);
    var noofrows=checkboxes.length;
    var idnamemobile="";
    var displaychar="";
    if (noofrows == undefined )
    {
        if (checkboxes.checked)	
        {
            var contactid =checkboxes.value;
            var mobilenumber = getObj('sendMobileCont_'+contactid).value;
            var contactname = getObj('sendContactName_'+contactid).innerHTML;
            displaychar=contactname+ "("+ mobilenumber +")";
            idnamemobile = checkboxes.value+":"+mobilenumber+":"+contactname;   
        }
        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 (checkboxes[i].checked)
                {

                     var contactid =checkboxes[i].value;
            var mobilenumber = getObj('sendMobileCont_'+contactid).value;
            var contactname = getObj('sendContactName_'+contactid).innerHTML;
            if(displaychar=="")
            {
             displaychar=contactname+ "("+ mobilenumber +")";
            }
            else
            {
               displaychar= displaychar+","+contactname+ "("+ mobilenumber +")";
            } 
            idnamemobile = idnamemobile+";"+contactid+":"+mobilenumber+":"+contactname;

                }
                
            } 
        }
    }
  document.sendSMS.idnamemobile.value= idnamemobile;      
  getObj('smscontactlist').innerHTML= displaychar; 
  show('qcform1');  
  return;
}

function ajaxAvailableCheck(orgValue,action,type)
{
	if(orgValue != "")
	{
		var url ="/crm/DupCheck.sas?orgValue="+orgValue+"&action="+action+"&type="+type;
		new Ajax.Request(url,{method:"get",onSuccess:function(t)
			{
				var str = t.responseText;

				var message = "You have signed up already!"
				if(type == "orgName")
					message = "Organization Name already exists!";
				if(type == "email")
				{
					getObj('isEmailAvail').value=str;
				}
				else if(type == "orgName")
				{
					getObj('isOrgAvail').value=str;
				}
				if(str == "false")
				{
					getObj('errorMsg').style.display = "block";
					getObj('errorMsg').innerHTML = message;
				}
				if(str == "true")
				{
					if(getObj('isOrgAvail').value == "true" && getObj('isEmailAvail').value == "true")
						getObj('errorMsg').style.display = "none";
					else if(getObj('isOrgAvail').value == "true" && getObj('isEmailAvail').value == "false")
					{
						getObj('errorMsg').style.display = "none";
						if(getObj("j_username").value != "")
						{
							getObj('errorMsg').style.display = "block";
							getObj('errorMsg').innerHTML = "You have signed up already!";
						}
					}
					else if(getObj('isOrgAvail').value == "false" && getObj('isEmailAvail').value == "true")
					{
						getObj('errorMsg').style.display = "none";
						if(getObj('j_organization').value != "")
						{
							getObj('errorMsg').style.display = "block";
							getObj('errorMsg').innerHTML = "Organization Name already exists!";
						}
					}
				}

				if(getObj('isOrgAvail').value == "true" && getObj('isEmailAvail').value == "true")
				{
					getObj('createAccount').disabled = false;
					var licenseType = getObj("licenseType").value;
					getObj('createAccount').className = "buttonok"+licenseType;
				}
				else 
				{
					getObj('createAccount').disabled = true;
					getObj('createAccount').className = "buttonokDisable";
				}
			},asynchronous:true
		});
	}
}

function attachEventLogofilecheck()
{
	var filename=document.getElementById("theLogoFile").value;
	if(filename ==null || filename=="")
	{
		alert("Select a Logo to Attach");
		return false;
	}
	else if(filename!=null)
	{
		var index=filename.lastIndexOf('.');	
		var ext=filename.substring(index,filename.length);
		if(ext==".jpeg" || ext=='.jpg' || ext=='.bmp' || ext=='.png' || ext=='.gif')
		{
			return true;
		}
		else
		{
			alert("The given file extension '"+ext+"' is not allowed");
			return false;
		}
	}
return true;		
}
    
function attachEventLogo()
{
if(attachEventLogofilecheck()){
	var module=getObj("moduleName").value;
	document.getElementById('logoattachment').style.display='none';
       	document.getElementById("campaign_file_attach").style.display="block";
        document.fileAttachForm.encoding="multipart/form-data";
	if(module == "Events")
	{
		var entityId=getObj("entityId").value;
        	document.fileAttachForm.action="/crm/IWEventLogoAttach.do?eventId="+entityId;
	}
	else if(module == "Inquiry Form Config")
	{
		document.fileAttachForm.action="/crm/IWInquiryLogoAttach.do";	
	}
        else if( module == "EventForms" || module == "InquiryForms" || module == "ApplicationForms" )
	{
		var entityId=document.getElementById("encryptedFormID").value;
		document.fileAttachForm.action="/crm/DFBLogoAttach.do?formId="+entityId;
	}
	document.fileAttachForm.submit();	
}}
function cloneTemplateSection(id)
{
   var trobj = id;
    var coll = trobj.parentNode.getElementsByTagName("tr");
   
    if(coll.length >= MAX_NUMBER_OF_JOINS)
    {
        alert(MAX_JOINS_EXCEEDED_ERROR_MESSAGE);
        return false;
        
    }
  
     var id_last=0;   
    for(m=0;m< coll.length;m++){
        if(coll[m].id.toString().indexOf("clone")>=0){            
            var escvar =  coll[m].id.toString();           
             var id_last = parseInt(escvar.substr(escvar.indexOf("_") + 1, escvar.length));           
             }
    }    
   
    var tableBodyObj=getObj('templateBodyId');
    var newobj=trobj.cloneNode(true);
    newobj.id = "cloneid_"+(id_last+1);
    
    setId(newobj,id_last+1)
    tableBodyObj.appendChild(newobj);
    getObj("templaterow").value=id_last+1;
    getObj("days_"+(id_last+1)).value="";
    getObj("emailTemplatehid_"+(id_last+1)).value="";
    getObj("emailTemplate_"+(id_last+1)).value="";
    getObj("type_"+(id_last+1)).value="";


}
function removeTemplaterow(id)
{ 
     var trobj = id;
     var coll = trobj.parentNode.getElementsByTagName("tr");

    if(coll.length >2)
     {
        trobj.parentNode.removeChild(id);
     }
     else
     {
				selectone.getJSAlertValue("crm.alert.query.condition",null,"en_US",
																	function(mesg) { alert(mesg) })
        return false;
     }
var t=1;
	for(var i=0;i < coll.length; i++)
   	{

     	if(coll[i].id.toString().indexOf("clone")>=0 && coll[i].id != id){     


             coll[i].id = "cloneid_"+ t;
             newobj = coll[i] ;
            setId(newobj,t);
            t++;
     }    
   }

	getObj("templaterow").value=(getObj("templaterow").value)-1;

}
function addTemplateimage(obj)
	{
		id=obj.id;
		if (id.indexOf("_") > -1)
		{
			var num = parseInt(id.substr(id.indexOf("_") + 1, id.length));
		}

		var ImageId = "templateIcon_"+num
		var oImage = document.getElementById(ImageId)
			oImage.onclick = function(){showLookUp('emailTemplate_'+num,'emailTemplatehid_'+num,'emailTemplate_'+num,'Email','','type_'+num) }
		
		ImageId = "caseTemplateIcon_"+num
		oImage = document.getElementById(ImageId)
		oImage.onclick = function(){showLookUp('emailTemplate_'+num,'emailTemplatehid_'+num,'emailTemplate_'+num,'Case Template','','type_'+num) }
	}
        
function quickCreateContact(lookUp,module,cvid,isQuickCreateVar)
{
    var emailPattern = /^\w+([a-zA-Z0-9_+'*$%#=?`~{}\^&!\.\-\/])*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/;
    
    if(getObj("property(Email)") && getObj("property(Email)").value != "")
    {
        // validating email address format
        if(!emailPattern.test(getObj("property(Email)").value))
        {
            selectone.getJSAlertValue("crm.alert.email.valid",null,"en_US",
                                      function(mesg) { alert(mesg) });
            return false;
        }
    }
    
    var msg = Form.serialize($('quickCreateForm'));
    var url = "/crm/QuickCreateContactValidate.do";
    new Ajax.Request(url, {
            method: 'post',
            postBody: msg,
            onSuccess: function(transport) {
                    var reply = eval('(' + transport.responseText + ')');
                    if(reply.code == "01")
                    {
                        // student id present in recycle bin
                        if(confirm(reply.msg))
                        {
                            StudentId.restoreContactStudentId(
                            getObj("property(Student ID)").value,null,
                            {callback : function(isPresent)
                            {
                                if(lookUp=="lookUp")
                                {
                                    var searchmodule = document.getElementById("searchModule").value;
                                    var fldName = document.getElementById("fldName").value;
                                    var fldId = document.getElementById("fldId").value;
                                    var fldLabel = document.getElementById("fldLabel").value;
                                    var fromModule = document.getElementById("fromModule").value;
                                    document.location.href = "/crm/QuickCreateCommonModule.do?module="+module+"&searchModule="+searchmodule+
                                                            "&fldName="+fldName+"&fldId="+fldId+"&fromModule="+fromModule+"&fldLabel="+
                                                            fldLabel+"&recycle=Restore&ajax=true&cvid="+cvid;
                                }
                                else
                                {
                                    document.location.href="/crm/ShowDetails.do?tabGroup=Contacts&module=Contacts"
                                }
                            }, async : false
                            });
                        }
                    }
                    else if(reply.code == "02")
                    {
                        // duplicate student id
                        alert(reply.msg);
                    }
                    else if(reply.code == "03")
                    {
                        // email present in recycle bin
                        if(confirm(reply.msg))
                        {
                            DWRCommonUtil.restoreEmailContactChk(
                            getObj("property(Email)").value,null,
                            {callback : function(isPresent)
                            {
                                if(lookUp=="lookUp")
                                {
                                    var searchmodule = document.getElementById("searchModule").value;
                                    var fldName = document.getElementById("fldName").value;
                                    var fldId = document.getElementById("fldId").value;
                                    var fldLabel = document.getElementById("fldLabel").value;
                                    var fromModule = document.getElementById("fromModule").value;
                                    document.location.href = "/crm/QuickCreateCommonModule.do?module="+module+"&searchModule="+searchmodule+
                                                            "&fldName="+fldName+"&fldId="+fldId+"&fromModule="+fromModule+"&fldLabel="+
                                                            fldLabel+"&recycle=Restore&ajax=true&cvid="+cvid;
                                }
                                else
                                {
                                    document.location.href="/crm/ShowDetails.do?tabGroup=Contacts&module=Contacts"
                                }
                            }, async : false
                            });
                        }
                        else
                        {
                            return false;
                        }
                    }
                    else if(reply.code == "04")
                    {
                        // duplicate email ID
                        alert(reply.msg);
                    }
                    else if(reply.code == "05")
                    {
                        //weights-based duplicate contact
                        alert(reply.msg);
                    }
                    else if(reply.code == "06")
                    {
                        // contact is not a duplicate proceed with form submit
                        quickCreateSubmitEntityForm(module,cvid,isQuickCreateVar);
                    }
            }, 
            onFailure: function (transport) { 
                alert("Error!");
                }
    });
}
function TargetValidate(obj)
{
	var rowno=getObj("row").value;
	var pattern=getObj("dateFmt").value

	var arrSearchDataType = new Array('T','N','D','DT');
	var arrSearchCondn = new Array('textcondition_','numcondition_','datecondition_','datetimecondition_');
	var arrSearchValue = new Array('value_','numfld_','datefld_','datetime_');

	for(var i=1;i<=rowno;i++)
	{
		var searchCondn = "";
		var searchValue = "";
		var bEmptyCondn = false;
		var objSearchfield=getObj("searchfieldtype_"+i);
		var strLabel = "";
		if(Search.browser_ie)
		{
			strLabel = document.getElementById("searchfield_"+i).value;
		}
		else
		{
			strLabel = getObj("searchfield_"+i).value;
		}
		var fldLabel=strLabel.substring(strLabel.lastIndexOf(":")+1,strLabel.length);
		// Getting values
		
		for(loop=0;loop<arrSearchDataType.length;loop++)
		{
			if(objSearchfield.value==arrSearchDataType[loop])
			{
				searchCondn=arrSearchCondn[loop];		
				searchValue=arrSearchValue[loop];
			}
		}

		// Empty validation and special charactor validation

		if(searchValue.trim().length>0)
		{
			var val_length = getObj(searchValue+i).value.trim().length;
			var val = getObj(searchValue+i).value.trim();
			var condition = getObj(searchCondn+i).value.trim();
			var startdate = getObj("startdate").value.trim();
			if(getObj("enddate").value!="" && getObj("startdate").value=="")
			{
				alert ('Start Date Should not be Empty');
				return false;
			}
			if(getObj("enddate").value=="" && getObj("startdate").value!="")
			{
				alert ('End Date Should not be Empty');
				return false;
			}
			if(getObj("enddate").value!="" && getObj("startdate").value!="")
			{
				if(!dateValidate("startdate","Date.Date Format is "+pattern,"OTH"))
					return false;
				
			}
			if(getObj("enddate").value!="" && getObj("startdate").value!="")
			{
				if(!dateValidate("enddate","Date.Date Format is "+pattern,"OTH"))
					return false;
			}
			if( ((val=="") && (condition=="is empty")) || ((val=="") && (condition=="is not empty")) )
			{
				bEmptyCondn=true;
				continue;
			}

			if(val_length==0 && getObj("startdate").value=="" && getObj("enddate").value=="" )
			{
				getObj(searchValue+i).focus();
				selectone.getJSAlertValue("crm.alert.not.empty",null,"en_US",
				  function(mesg) { alert(fldLabel + " " + mesg) })
				return false
			}
		}

		// Data type format validation

		if(objSearchfield.value=="D")
		{
			if(!dateValidate("datefld_"+i,"Date.Date Format is "+pattern,"OTH"))
				return false;			
		}		
		if(objSearchfield.value=="DT")
		{
			if(!dateValidate("datetime_"+i,"Date.Date Format is "+pattern,"OTH"))
				return false;
			var len=getObj("timeval_"+i).value.trim().length
			if(len>0)
			{
				if(!timeValidate("timeval_"+i,"Time hh:mm 24 hours format","OTH"))
					return false;
			}
		}
		if(objSearchfield.value=="N")
		{
			var re=/^\-|\d+(,(\d)+)*(\.\d{1,2})*$/	
			if (isNaN(val) || !re.test(val) || val.indexOf("+") != -1) 
			{
				selectone.getJSAlertValue("crm.alert.entry.valid",null,"en_US",function(mesg) { alert(mesg + " " + fldLabel) })
			       	return false;
			}
		}	
	}
	return true;
}
