 
var dtPtn , calFormat , userDateFormat; 
var isWorking = false;
var http = getHTTPObject();
var skintype = getObj("skintype")?getObj("skintype").value:'';
var showMenuObj;
var rowCnt=1;
var menuWidth,xMenuPos;
var act=0;
var timeout;

function fillPolicyValues(pcounter,pday,percVal,fixedVal)
{
    getObj('property(DAYS BEFORE)')[pcounter].value=pday;
    getObj('property(PERCENTAGE PENALTY)')[pcounter].value= percVal;
    getObj('property(FIXED COST PENALTY)')[pcounter].value= fixedVal;
}

function ajaxNew(url,params)
{
    //var now1 = Date.now()
	loadAjaxTab2('','lightblue');
	if (!isWorking && http)
	{
		var args = "";
		if(params != undefined)
		{
			args = params;
		}
		try
		{
                        http = getHTTPObject();
			http.open("POST", url, true);
		}
		catch(e)
		{
			http = getHTTPObject();
			http.open("POST", url, true);
		}
		http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;charset=UTF-8');
		http.onreadystatechange = function () {				
		if (http.readyState == 4) {
			txt=http.responseText
		 	if(txt.indexOf("SECURITY::::")>-1)
                    	{	
                        	var errorContent = txt.split("SECURITY::::");
                        	getObj("show").innerHTML = ""
                        	getObj("show").innerHTML = errorContent[1];
				document.getElementById('ajax_load_tab').style.display='none';		
				return;
                    	}
                    if(txt.indexOf("Error::::")>-1)
                    	{	
                        	var errorContent = txt.split("Error::::");
                        	getObj("showError").innerHTML = ""
                        	getObj("showError").innerHTML = errorContent[1];
				document.getElementById('ajax_load_tab').style.display='none';		
				return;
                    	}
			if(txt.indexOf("Your login session has expired")>-1)
			{
				selectone.getJSAlertValue("crm.alert.session.expiry",null,"en_US",
			  													function(mesg) { alert(mesg) })
				window.location.reload();
				return;
			}
			if(getObj("showMenu"))
			{
				if(getObj("showMenu").offsetWidth)
				{
					menuWidth = getObj("showMenu").offsetHeight;
					xMenuPos = findPosX(getObj("showMenu"));
				}
			}
			$("show").innerHTML = txt;
			txt.extractScripts().map(function(script) { return _IW.Ajax.eval(script) });
                        if(getObj("reportSideBar1")!=null){                                       
                                        getObj("reportSideBar1").style.width="0%";
                                        
					getObj("reportSideBarClose").style.display="none";
					getObj("reportSideBarOpen").style.display="none";
					}
			
		
			if(getObj("menuincreate")!=undefined)
			{
				getObj("menuContent").innerHTML = "";
				getObj("menuContent").innerHTML = getObj("menuincreate").innerHTML;
			}
            // TODO SET RECENT ITEMS....
			if(getObj("recentItem")!=undefined)
			{
				if(getObj("sidebar3"))
				{
					getObj("sidebar3").innerHTML = "";
					getObj("sidebar3").innerHTML = getObj("recentItem").innerHTML ;
				}
			}
			/*if(getObj("sidebar3"))
			{
				getObj("sidebarhead3").style.display = 'none';
				getObj("sidebar3").style.display = 'none';
			}
            */
            if(txt.indexOf("#Feature Not Available#")>-1)
        	{	
				document.getElementById('ajax_load_tab').style.display='none';		
				return;
        	}
			itsonview = false;
			dtPtn = (getObj("dtPtn"))?getObj("dtPtn").value:"";
			calFormat = dtPtn;
			rowCnt = 1;
			userDateFormat = dtPtn;
			acLayer = getObj("aclayer");
			
			// --------- Country ~ State dependent value generate Start -------- //

			 /**
			  * Country,State static dependent fields. TODO find the dependent field dynamically
			  */
			/* commented out because of JS error.  To be revisited in another release (as per Paul)
			var countryField=new Array("Country","Primary Country","Secondary Country","Contact Country","Other Country","Location Country");
			var stateField=new Array("State","Primary State","Secondary State","Contact State","Other State","Location State");
			
			var oValues = getObj("fieldvalues") ? getObj("fieldvalues").value : null; 
			var fieldValueSplit = ( oValues != null )? oValues.split("|") : new Array();
			for(field = 0 ; field < fieldValueSplit.length ; field++)
			{
				var eachFieldValues = fieldValueSplit[field].split("=");
				
				_IW.Map.put(eachFieldValues[0], eachFieldValues[1]);
			}
			
			for(iCon = 0 ; iCon < countryField.length; iCon++)
			{
				if(_IW.Map.get(countryField[iCon]) != null)
				{
					var countryName =  _IW.Map.get(countryField[iCon]);
					
					var propStateField = "property(" + stateField[iCon] + ")";
					if(getObj(propStateField))
					{
						_IW.CountryState.selectStateByValue(countryName, propStateField, false);
					}
				}
			}
			
			// --------- Country ~ State dependent value generate End  ---------- //
			*/
			
			init(params);

			/*
			// If a country, state value is not matched ( ie. old data ), add it as a new value.
			for(iCon = 0 ; iCon < countryField.length; iCon++)
			{
				var countryName =  _IW.Map.get(countryField[iCon]);
				var stateName =  _IW.Map.get(stateField[iCon]);

				if(countryName != null)
				{
					var propCountryField = "property(" + countryField[iCon] + ")";
					_IW.CountryState.addDefaultValue(propCountryField,countryName);

				}
				if(stateName != null)
				{
					var propStateField = "property(" + stateField[iCon] + ")";
					_IW.CountryState.addDefaultValue(propStateField,stateName);
				}
			}
			*/
		
			setDisplayNone();
			//showDrillDownPtr(params);
			isWorking = false;
			/*if(url.indexOf("/crm/ShowEntityInfo.do?module=Contacts")>-1)
            {
                emailBounceCheck(getURLParam(url,"id"),'check');
            }
            if(url.indexOf("/crm/ShowEntityInfo.do?")>-1)
            {
               callTagCloud1();
            }
            document.getElementById('ajax_load_tab').style.display='none';	
			}*/
			if(((url.indexOf("/crm/ShowEntityInfo.do?")>-1 && url.indexOf("module=Contacts")>-1)) ||(url.indexOf("/crm/EditCommonModule.do")>-1 && params.indexOf("module=Contacts")>-1))
            {
                if(url.indexOf("/crm/EditCommonModule.do")>-1){
                	if($('subvalue_Email')!= null)
                		 emailBounceCheck(getURLParam(url+"?"+params,"property(id)"),'check',getObj("subvalue_Email").innerHTML);}
                else{
                	if($('subvalue_Email')!= null)
	               		 emailBounceCheck(getURLParam(url,"id"),'check',getObj("subvalue_Email").innerHTML);}
            }
            if((url.indexOf("/crm/ShowEntityInfo.do?")>-1) || (url.indexOf("/crm/EditCommonModule.do")>-1))
            {
               isRelatedListLoaded=false; 
               callTagCloud1();
            }
            /*if(document.getElementById('listview_addinfo'))
    	    {
	    	 var httpobj = getHTTPObject();
		     httpobj.open("POST", "/crm/ShowSelectedCustomViewEnd.do?module="+getObj("module").value, false);                             
		     httpobj.send("module="+getObj("module").value);
             document.getElementById('listview_addinfo').innerHTML="";
             document.getElementById('listview_addinfo').innerHTML=httpobj.responseText;
	        }*/  		
            document.getElementById('ajax_load_tab').style.display='none';	
		if(get_cookie("full_profile")!=null) 
		{
		if(document.getElementById("fullprofile")!=null && document.getElementById("quickprofile")!=null)
                {

			document.getElementById("fullprofile").style.display=get_cookie("full_profile");
			if(get_cookie("full_profile")=="none")
				document.getElementById("quickprofile").style.display="block";
			else
				document.getElementById("quickprofile").style.display="none";
		}
		}
		else
		{
			if(document.getElementById("fullprofile")!=null && document.getElementById("quickprofile")!=null)
			{
				document.getElementById("fullprofile").style.display="none";
				document.getElementById("quickprofile").style.display="block";
			}
		}	
            //var now2 = Date.now();
    
    
			}
		}
		http.send(args);
	}
}


function getURLParam(url,strParamName){
  var strReturn = "";
  var strHref = url;
  if ( strHref.indexOf("?") > -1 ){
    var strQueryString = strHref.substr(strHref.indexOf("?"));
    var aQueryString = strQueryString.split("&");
    for ( var iParam = 0; iParam < aQueryString.length; iParam++ ){
      if (
aQueryString[iParam].indexOf(strParamName + "=") > -1 ){
        var aParam = aQueryString[iParam].split("=");
        strReturn = aParam[1];
        break;
      }
    }
  }
  return strReturn;
}
var base64s =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

function encode(decStr){
       decStr=escape(decStr);  //line add for chinese char
       var bits, dual, i = 0, encOut = '';
       while(decStr.length >= i + 3){
               bits =
                       (decStr.charCodeAt(i++) & 0xff) <<16 |
                       (decStr.charCodeAt(i++) & 0xff) <<8  |
                       decStr.charCodeAt(i++) & 0xff;
               encOut +=
                       base64s.charAt((bits & 0x00fc0000) >>18) +
                       base64s.charAt((bits & 0x0003f000) >>12) +
                       base64s.charAt((bits & 0x00000fc0) >> 6) +
                       base64s.charAt((bits & 0x0000003f));
       }
       if(decStr.length -i > 0 && decStr.length -i < 3){
               dual = Boolean(decStr.length -i -1);
               bits =
                       ((decStr.charCodeAt(i++) & 0xff) <<16) |
                       (dual ? (decStr.charCodeAt(i) & 0xff) <<8 : 0);
               encOut +=
                       base64s.charAt((bits & 0x00fc0000) >>18) +
                       base64s.charAt((bits & 0x0003f000) >>12) +
                       (dual ? base64s.charAt((bits & 0x00000fc0) >>6) : '=') +
                               '=';
       }
       return encOut
}

function decode(encStr) {
       var bits, decOut = '', i = 0;
       for(; i<encStr.length; i += 4){
               bits =
                       (base64s.indexOf(encStr.charAt(i))    & 0xff) <<18 |
                       (base64s.indexOf(encStr.charAt(i +1)) & 0xff) <<12 |
                       (base64s.indexOf(encStr.charAt(i +2)) & 0xff) << 6 |
                       base64s.indexOf(encStr.charAt(i +3)) & 0xff;
               decOut += String.fromCharCode(
                               (bits & 0xff0000) >>16, (bits & 0xff00) >>8, bits & 0xff);
       }
       if(encStr.charCodeAt(i -2) == 61)
       {
               undecOut=decOut.substring(0, decOut.length -2);
       }
       else if(encStr.charCodeAt(i -1) == 61)
       {
               undecOut=decOut.substring(0, decOut.length -1);
       }
       else
       {
               undecOut=decOut;
       }
       return unescape(undecOut);  //line add for chinese char
}

function putInHistory(id,params)
{
    //alert('putInHistory');
    //return;
	var paramValues = params.split("|");
	var action = paramValues[0];
	
	if(paramValues[1].indexOf("Reports") < 0 && paramValues[1].indexOf("Dashboards") < 0 && paramValues[0].indexOf("ShowHomePage") < 0 && paramValues[0].indexOf("Template"))
	{
		Event.observe(""+id+"", "click", function(event) {browserHistory.put(""+encode(params)+"");});
	}
}

/*
Function used to create and clone cached objects
*/
function setGMultiSelect(module,fieldlabel)
{
	var selectedValues="";
	if(getObj("gmultiselect"))
	{
		var tempGroups = getObj("gmultiselect").value;
		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 selectCreateEntityAction(operation, module)
{
	var comboCount = getObj("comboCount").value;        
	module = getObj("module").value;
	if(comboCount > 0)
	{	
		for(var k=1;k<=comboCount;k++)
		{	
			var j = 0;
			if(getObj("comboValue"+k))
			{
				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
 	setInterestGroups(module,"");
	setGMultiSelect(module,"");

	if(module =='Policies')
	{
		if(!validatePolicyModule())
		{
			return false;
		}
	}

	if(module=="Cases")
	{
		var obj1=getObj("property(Case Origin)")
			var selVal=obj1.options[obj1.options.selectedIndex].value
			if(selVal=="Email" && getObj("property(Email)") )
			{
				if(!emptyCheck("property(Email)", 'Email'))
					return false;
			}
	}

	if (module == "Quotes" || module == "SalesOrders" || module == "PurchaseOrders" || module == "Invoices" )
	{
		settotalnoofrows();

		if(validate())
		{
			if(FindDuplicate())
			{
				calcRowTotal();
			}
			else 
			{
				return false;
			}
		}
		else
		{
			return false;
		}
	}
	if(module =="Segments")
	{
		var pattern=getObj("dateFmt").value
		var rowno=getObj("row").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 = getObj("searchfield_"+i);
			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();
				if( ((val=="") && (condition=="is empty")) || ((val=="") && (condition=="is not empty")) )
				{
					bEmptyCondn=true;
					continue;
				}

				if(val_length==0)
				{
					getObj(searchValue+i).focus();
					selectone.getJSAlertValue("crm.alert.not.empty",null,"en_US",
					  function(mesg) { alert(fldLabel + " " + mesg) })
					return false
				}
				else
				{
					var splCharVal = splCharCheck2(val);
					if (! splCharVal )
					{
						selectone.getJSAlertValue("crm.alert.label.special.characters",null,"en_US",function(mesg){ alert(mesg) })        
						getObj(searchValue+i).focus();
						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;
				}
			}	
		}
	
		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;
	
	}
	
    	if (pageValidate())
	{
    		
		if(getObj('property(Probability)'))
		{
			if( getObj('property(Probability)').value >100)
			{
				selectone.getJSAlertValue("crm.create.pbty.check",null,"en_US",
						function(mesg){ alert(mesg) })
					return false
			}
		}
		if(module == "Contacts")
		{
			if(getObj("property(Account Name)") && getObj("property(Vendor Name)") && trimBoth(getObj("property(Account Name)").value) != "" && trimBoth(getObj("property(Vendor Name)").value) != "")
			{
				selectone.getJSAlertValue("crm.alert.contact.org",null,"en_US",
						function(mesg){ alert(mesg) })
					return false;	

			}
		}

		if( document.createEntityForm.elements['property(Portal User)'] != undefined && (document.createEntityForm.elements['property(Portal User)'].checked) )
		{      
			if( document.createEntityForm.elements['property(Email)'] != undefined)
			{
				if( !emptyCheck('property(Email)','Email'))
				{
					return false;
				}
			}
			else
			{
				selectone.getJSAlertValue("crm.alert.portal.email.check",null,"en_US",
						function(mesg){ alert(mesg) })
					return false;
			}                    
		}
                if(module == "Connections")
                {
                		act=1;
                		flag = "true";
                        var entityId =getObj("property(whoName:Contact Name)").value;
                        var contactId =getObj("property(whoName:Relation Contact)").value;
                        var conType= getObj("property(Connection Type)").value;
                        if(operation == "Edit")
                        {	
                           var id = getObj("property(id)").value;
                        }   
                        
                        if(entityId.toUpperCase() == contactId.toUpperCase())
                        {
                        	flag = "false";
                            alert("Relation Contact must be different from Primary Contact");
                            return false;
                        }
                        else
                        {
                        	act=1;
                        	timeout = setTimeout('act=1',3000);
                        	DWRCommonUtil.duplicateConnectionChk
            				(contactId,entityId,conType,operation,id,
            				function(isPresent)
            				{
            					regisPresent=isPresent;
            					if(regisPresent == true)
            					{
            						flag = "false";
            						alert("Already Connections Exists for Same Contacts");
            						return false;    
            					} 
            					else
            					{       
            						act=0;	 
            						submitEntityForm(operation,module);
            					}
            					 

            				});
                        
                    }
                        
                  
                }

                if(module == "Contacts")
                {
                    createContactAction(operation,module);
                }
			else 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;
				if(getObj("property(id)"))
				{                          
					regisid=getObj("property(id)").value;
				}

			DWRCommonUtil.duplicateRegistrationChk
				(pgmid,iterid,contactid,regisid,
				function(isPresent)
				{
				regisPresent=isPresent;
				if(regisPresent == true)
					 {
					alert("Already Registration Exists for Same Iteration & Participant");
					 return false;    
					 } 
					 else
					 {                                
					 submitEntityForm(operation,module);
					 }

				});
			}
			else if(module == "LifeCycles")
			{
			var pgmid=null;
			var iterid=null;
			var contactid=null;
			if(getObj("property(programs:Program Name)")!=null && getObj("property(programs:Program Name)")!="")
			{	
				pgmid=getObj("property(programs:Program Name)").value;
			}
			if(getObj("property(iterations:Iteration Name)")!=null && getObj("property(iterations:Iteration Name)")!="")
			{
				iterid=getObj("property(iterations:Iteration Name)").value;
			}
			contactid=getObj("property(contactName:Contact)").value;
			var lifeid=null;
				if(getObj("property(id)"))
				{                          
					lifeid=getObj("property(id)").value;
				}
			if(pgmid!=null && pgmid!="")
			{if(iterid==null|| iterid==""){
			alert("Iteration Name Cannot be blank");
			return false;
			}}

			
			if(iterid!=null && iterid!="")
			{	
			DWRCommonUtil.duplicateLifeCycleChk
				(pgmid,iterid,contactid,lifeid,
				function(isPresent)
				{
				regisPresent=isPresent;
				if(regisPresent == true)
					 {
					alert("Contact already has this Lifecycle Role & Stage for this Program and Iteration");
					 return false;    
					 } 
					 else
					 {                                
					 submitEntityForm(operation,module);
					 }

				});
			}
			else
			{
				submitEntityForm(operation,module);
			}
			}
		else
		{
			submitEntityForm(operation,module);
		} 

		return false;
	}
	else
	{	
		return false
	}	
}

function submitEntityForm(operation,module)
{ 
if(act==0)
{
act=1;
timeout = setTimeout('act=0',3000);
            	if(operation == 'Create&New')
            	{
		if(window.location.href.indexOf("/crm/Create.do?")>-1  && (getURLParam(window.location.href,"module")=="Contacts") && (getURLParam(window.location.href,"segmentId").length>3))
                {

                    document.createEntityForm.action="/crm/CreateCommonModuleandNew.do?type=savenew&isload=true&module="+module+"&cloneId="+(getURLParam(window.location.href,"cloneID"));
                    document.createEntityForm.submit();
                return false;

                }
		else
		{
			var url = "/crm/CreateCommonModuleandNew.do";
			/*var formData = formData2QueryString(document.createEntityForm);
			var params = "module="+module+"&"+formData;
			ajaxNew(url,params);
            */
           //TODO 
            document.createEntityForm.action=url+"?module="+module;
            document.createEntityForm.submit();
            return false; 
            	}
		}
		else if(operation == 'Edit&New')
		{
			var url = "/crm/CreateCommonModuleandNew.do";
			/*var formData = formData2QueryString(document.createEntityForm);
			var params = "module="+module+"&ActionType=Edit&"+formData;
			ajaxNew(url,params);
            */
            // TODO LATER
            document.createEntityForm.action=url+"?module="+module+"&ActionType=Edit";
            document.createEntityForm.submit();
            return false;
		}
            	else if(operation == 'Create' )
            	{
                if(window.location.href.indexOf("/crm/Create.do?")>-1  && (getURLParam(window.location.href,"module")=="Contacts") && (getURLParam(window.location.href,"segmentId").length>3))
                {
		var actiontype=getURLParam(window.location.href,"actiontype")
                    document.createEntityForm.action="/crm/CreateCommonModule.do?isload=true&actiontype="+actiontype+"&cloneId="+(getURLParam(window.location.href,"cloneID"));
                    document.createEntityForm.submit();
                    return false; 
                }
    
			var formData = formData2QueryString(document.createEntityForm);
			var url = "/crm/CreateCommonModule.do";
			var params = "module="+module+"&"+formData;
			if(getObj("returnAnchor"))
			{
				params = params + "#" + getObj("returnAnchor").value;
			}
			ajaxNew(url,params);
            	}

	    	else if(operation == 'Edit')
	    	{
		if((getURLParam(window.location.href,"module")=="Contacts") && (getURLParam(window.location.href,"segmentIdRW").length>3))
                {
		var actiontype=getURLParam(window.location.href,"actiontype")
                    document.createEntityForm.action="/crm/EditCommonModule.do?isload=true&ActionType=Edit&actiontype="+actiontype+"&segmentIdrw="+(getURLParam(window.location.href,"segmentIdRW"));
                    document.createEntityForm.submit();
                    return false; 
                }

			var formData = formData2QueryString(document.createEntityForm);
			var url = "/crm/EditCommonModule.do";
			var params = "module="+module+"&ActionType=Edit&"+formData;
			ajaxNew(url,params);
   	    	}
	    	else if(operation == 'Clone')
	    	{
			var formData = formData2QueryString(document.createEntityForm);
			var url = "/crm/CloneCommonModule.do";
			var params = "module="+module+"&"+formData;
			ajaxNew(url,params);
  	    	}
	    	else if(operation == 'Clone&New' )
   	    	{
			/*var formData = formData2QueryString(document.createEntityForm);
			var url =  "/crm/CloneCommonModuleandNew.do";
			var params = "module="+module+"&"+formData;
			ajaxNew(url,params);
            */
            // TOTO LATER
            document.createEntityForm.action="/crm/CloneCommonModuleandNew.do?module="+module;
             document.createEntityForm.submit();
            return false;
          	}
	    	else if(operation == 'CreateTemplate' )
   	    	{
		        document.createEntityForm.action="/crm/CommonTemplate.do?template=CaseTemplate&action=save&isload=true";
		        document.createEntityForm.submit();
		        return false;
           	} 
	    	else if(operation == 'EditTemplate' )
   	    	{
		        document.createEntityForm.action="/crm/CommonTemplate.do?template=CaseTemplate&action=update&isload=true";
		        document.createEntityForm.submit();
		        return false;
           	} 
}
                        
                        
}

	
function setInterestGroups(module,fieldlabel)
{
	if(module == "Contacts" || module == "Cases" || module == "Inquiries" || module == "CaseTemplate")
	{
		if(getObj("totalGroups"))
		{
			var totalGroups = getObj("totalGroups").value;
			var selectedValues ='';
			for(var k= 1; k <= totalGroups; k++)
			{
				var groupId = "intGroup_"+k;
				var groupName = getObj(groupId).value;
				var groupSize = parseInt(groupName.substr(groupName.indexOf(":") + 1, groupName.length))
					groupName = groupName.substr(0,groupName.indexOf(":"));
				for(var j=1; j <= groupSize; j++)
				{
					var valuesId = "interest_" + k + j;
					if(getObj(valuesId).checked)
						if (selectedValues == '')
							selectedValues = groupName + "--" + getObj(valuesId).value;
						else
							if(selectedValues.indexOf(groupName+"--")>=0)
								selectedValues = selectedValues + "::" + getObj(valuesId).value;
							else
								selectedValues = selectedValues + "##" + groupName + "--" + getObj(valuesId).value;
				}
			}
			if(module=='Contacts')
			{
				getObj("property(Interests)").value = selectedValues;
			}
			if((module=='Cases' || module=='Inquiries' || module=='CaseTemplate') && fieldlabel != "")
			{
				getObj("property("+fieldlabel+")").value = selectedValues;
			}
			else if((module=='Cases' || module=='Inquiries' || module=='CaseTemplate') && fieldlabel == "")
			{
				getObj("property(Interests)").value = selectedValues;
			}
		}
	}
}

function showCopyMenu()
{
	if(getObj("copy").style.display=="block")
	{
		getObj("copy").style.display="none";
	}
	else
	{
	getObj("copy").style.display="block"
		getObj("copy").style.left=findPosX(getObj("copyAddress"))
		getObj("copy").style.top=findPosY(getObj("copyAddress"))+getObj("copyAddress").offsetHeight
	}
}

function copyMapLocation(addressType)
{
        var module=getObj("module").value; 
	if(module == 'Contacts')
	{
		if (addressType == 'Other to Mailing')
		{
			getObj("property(Mailing Street)").value = getObj("property(Other Street)").value
			getObj("property(Mailing City)").value = getObj("property(Other City)").value
			getObj("property(Mailing State)").value = getObj("property(Other State)").value
			getObj("property(Mailing Zip)").value = getObj("property(Other Zip)").value
			getObj("property(Mailing Country)").value = getObj("property(Other Country)").value
		}
		else if (addressType == 'Mailing to Other')
		{
			getObj("property(Other Street)").value = getObj("property(Mailing Street)").value
			getObj("property(Other City)").value = getObj("property(Mailing City)").value
			getObj("property(Other State)").value = getObj("property(Mailing State)").value
			getObj("property(Other Zip)").value = getObj("property(Mailing Zip)").value
			getObj("property(Other Country)").value = getObj("property(Mailing Country)").value
		}
	}
	else
	{
                if (addressType == 'Shipping to Billing')
                {
                        getObj("property(Billing Street)").value = getObj("property(Shipping Street)").value
                        getObj("property(Billing City)").value = getObj("property(Shipping City)").value
                        getObj("property(Billing State)").value = getObj("property(Shipping State)").value
                        getObj("property(Billing Code)").value = getObj("property(Shipping Code)").value
                        getObj("property(Billing Country)").value = getObj("property(Shipping Country)").value
                }
		else if (addressType == 'Billing to Shipping')
                {
                        getObj("property(Shipping Street)").value = getObj("property(Billing Street)").value
                        getObj("property(Shipping City)").value = getObj("property(Billing City)").value
                        getObj("property(Shipping State)").value = getObj("property(Billing State)").value
                        getObj("property(Shipping Code)").value = getObj("property(Billing Code)").value
                        getObj("property(Shipping Country)").value = getObj("property(Billing Country)").value
                }

	}
	getObj("copy").style.display="none"
	
}

/*function copyAddress()
{
	if (getObj("property(Billing Street)") && getObj("property(Shipping Street)"))
		getObj("property(Shipping Street)").value=getObj("property(Billing Street)").value

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

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

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

	if (getObj("property(Billing Country)") && getObj("property(Shipping Country)"))
		getObj("property(Shipping Country)").value=getObj("property(Billing Country)").value
}
*/

/*function cancelfun()
{
     
      	var module=getObj("module").value; 
      	if(module=='Tasks' || module=='Appointments')
      	{
		var url = "/crm/ShowDetails.do?module=Activities"+"&quickcreate=true";
		ajaxNew(url);
      	}
      	else
      	{
		var url = "/crm/ShowDetails.do?module="+module+"&quickcreate=true";
		ajaxNew(url);
      	}
}
*/

var prodList=getObj("productList")
if(getObj("rowCount"))
{
	rowCnt = getObj("rowCount").value;
}
var listTableStart="<table width='100%' border='0' cellspacing='0' cellpadding='0'>"
var viewTableStart="<table width='100%' border='0' cellspacing='1' cellpadding='1'>"
function settotalnoofrows() {
	var module=getObj("module").value;
	if (module == "Quotes" || module == "SalesOrders" || module == "PurchaseOrders" || module == "Invoices" )
    	{
	        getObj("totalProductCount").value = rowCnt;
	}
}
function getProdListBody() {
        if (browser_ie) {
                var prodListBody=getObj("productList").children[0].children[0]
        } else if (browser_nn4 || browser_nn6) {
                if (getObj("productList").childNodes.item(0).tagName=="TABLE") {
                        var prodListBody=getObj("productList").childNodes.item(0).childNodes.item(0)
                } else {
                        var prodListBody=getObj("productList").childNodes.item(1).childNodes.item(1)
                }
        }
        return prodListBody;
}
function addViewRow()
{
	rowCnt++;
	if(rowCnt%2==0)
	{
		var newRow="<tr id=hrow"+rowCnt+" class='evenBg'>"	
	}
	else
	{
		var newRow="<tr id=hrow"+rowCnt+" class='value'>"
	}	
	newRow += "<td style='padding:3px;' ><div><span id='value_hdnProductName"+rowCnt+"'></span></div></td>"	
	newRow += "<td style='padding:3px;' ><div><span id='value_hdnProductCode"+rowCnt+"'></span></div></td>"	
	newRow += "<td style='padding:3px;' ><div><span id='value_hdnQtyStock"+rowCnt+"'></span></div></td>"	
	newRow += "<td style='padding:3px;' ><div><span id='value_txtQty"+rowCnt+"'></span></div></td>"	
	newRow += "<td style='padding:3px;' ><div><span id='value_hdnUnitPrice"+rowCnt+"'></span></div></td>"	
	newRow += "<td style='padding:3px;' ><div><span id='value_txtListPrice"+rowCnt+"'></span></div></td>"	
	newRow += "<td style='padding:3px;' ><div><span id='value_hdnTotal"+rowCnt+"'></span></div></td>"	
	getObj("productList").innerHTML=viewTableStart+getProdListBody().innerHTML+newRow+"<tr><td colSpan='8' class='tableRowSep'></td></tr></table>"
}


function addRow() {

   rowCnt++;
   if (rowCnt%2==0)
       var newRow="<tr id=hrow"+rowCnt+" class='evenListRow'>"
   else
       var newRow="<tr id=hrow"+rowCnt+" class='oddListRow'>"
         newRow+="<td style='padding:3px;' class='tableData'><input id='txtProduct"+rowCnt+"' name='property(hdnProductName"+rowCnt+")' type='text' size='12' maxlength='120'> <img src='/crm/images/Products_small.gif' title='Product Name Lookup' onclick=\"showLookUp('txtProduct"+rowCnt+"','hdnProductId"+rowCnt+"','','Products','','','','vendorName')\" align='absmiddle' style='cursor:hand;cursor:pointer'></td>"

   newRow+="<td style='padding:3px;' class='tableData'>"
	 +"<input type='text' id='hdnProductCode"+rowCnt+"' name='property(hdnProductCode"+rowCnt+")' size='7' maxlength='120'/>"
         +"</td>"	
   newRow+="<td style='padding:3px;' class='tableData'>"
	 +"<input type='text' id='hdnQtyStock"+rowCnt+"' name='property(hdnQtyStock"+rowCnt+")' size='5' maxlength='9'/>"
         +"</td>"	
   newRow+="<td style='padding:3px;' class='tableData'><input type=text id='txtQty"+rowCnt+"' name='property(txtQty"+rowCnt+")' size='5' maxlength='9' onBlur='calcTotal(this)'></td>"
   newRow+="<td style='padding:3px;' class='tableData'>"
	 +"<input type='text' id='hdnUnitPrice"+rowCnt+"' name='property(hdnUnitPrice"+rowCnt+")' size='7' maxlength='19'/>"
         +"</td>"

   newRow+="<td style='padding:3px;' class='tableData'><input type=text id='txtListPrice"+rowCnt+"' name='property(txtListPrice"+rowCnt+")' size='7' maxlength='19' onBlur='calcTotal(this)'> <img src='/crm/images/PriceBooks_small.gif' title='PriceBook Name Lookup' onclick=\"showLookUp('txtListPrice"+rowCnt+"','hdnPriceBookId"+rowCnt+"','','PriceBooks','','','','hdnProductId"+rowCnt+"')\" align='absmiddle' style='cursor:hand;cursor:pointer'></td>"
   newRow+="<td style='padding:3px;' class='tableData'><input type='text' class='searchFormatText' size='10' id='total"+rowCnt+"' name='property(hdnTotal"+rowCnt+")' ></td>"
   newRow+="<td style='padding:3px;' align='center' width='15' class='tableData'><img id='delRow"+rowCnt+"' align='absmiddle' title='Delete Row' src='/crm/images/del.gif'  onclick='delRow(this.id)' class='pointer'></td>"
   newRow+="<input type='hidden' id='hdnProductId"+rowCnt+"' name='property(hdnProductId"+rowCnt+")'/>"
   newRow+="<input type='hidden' id='hdnPriceBookId"+rowCnt+"' name='hdnPriceBookId"+rowCnt+"'/>"
   newRow+="<input type='hidden' id='hdnRowStatus"+rowCnt+"' name='hdnRowStatus"+rowCnt+"'/>"
   newRow+="</tr>"
     var prodListBody=getProdListBody()
	 if (browser_nn4 || browser_nn6) {
       var product=new Array(rowCnt-1)
       var productcode = new Array(rowCnt-1)
       var qtyinstock = new Array(rowCnt-1)
       var qty=new Array(rowCnt-1)
       var unitprice = new Array(rowCnt-1)	
       var listPrice=new Array(rowCnt-1)
       var productId=new Array(rowCnt-1)
       var total=new Array(rowCnt-1)
       var rowStatus=new Array(rowCnt-1)
         for (var i=1,k=0;i<=rowCnt-1;i++,k++) {
	 product[k]=getObj("txtProduct"+i).value
           qty[k]=getObj("txtQty"+i).value
           listPrice[k]=getObj("txtListPrice"+i).value
	   productcode[k] = getObj("hdnProductCode"+i).value	
	   qtyinstock[k]=getObj("hdnQtyStock"+i).value
	   unitprice[k]=getObj("hdnUnitPrice"+i).value		
           total[k]=getObj("total"+i).value
           productId[k]=getObj("hdnProductId"+i).value
           rowStatus[k]=getObj("hdnRowStatus"+i).value
       }
   }

	//var prodList=getObj("productList")	
	//prodList.innerHTML=listTableStart+prodListBody.innerHTML+newRow+"</table>"	

	getObj("productList").innerHTML=listTableStart+prodListBody.innerHTML+newRow+"<tr><td colSpan='8' class='tableRowSep'></td></tr></table>"
     
	if (browser_nn4 || browser_nn6) {
       for (var i=1,k=0;i<=rowCnt-1;i++,k++) {
           getObj("txtProduct"+i).value=product[k]
	   getObj("hdnProductCode"+i).value=productcode[k]
	   getObj("hdnQtyStock"+i).value=qtyinstock[k]
	   getObj("hdnUnitPrice"+i).value=unitprice[k]		
           getObj("txtQty"+i).value=qty[k]
           getObj("txtListPrice"+i).value=listPrice[k]
           getObj("total"+i).value=total[k]
           getObj("hdnProductId"+i).value=productId[k]
           getObj("hdnRowStatus"+i).value=rowStatus[k]
       }
   }
} 

function delRow(rowId) {

   var rowId=parseInt(rowId.substr(rowId.indexOf("w")+1,rowId.length))
      //removing the corresponding row
	//var child = getProdListBody().childNodes
   var prodListBody=getProdListBody()
	//prodListBody.removeChild(child[rowId])
  getProdListBody().removeChild(getObj("hrow"+rowId))
	
      //assigning new innerHTML after deleting a row
   var newInnerHTML="<tr class='tableHeadBg' height='20' id='tablehead'>"+getObj("tablehead").innerHTML+"</tr>"

	//alert(getObj("tablehead"))
   //newInnerHTML+="<tr id='tableline'>"+getObj("tableline").innerHTML+"</tr>";
	//alert(getObj("tableline"))


      var rowArray=new Array(rowCnt-1);
      if (browser_nn4 || browser_nn6) {
       var product=new Array(rowCnt-1)
	var productcode = new Array(rowCnt-1)
	var qtyinstock = new Array(rowCnt-1)
       var qty=new Array(rowCnt-1)
       var listPrice=new Array(rowCnt-1)
	var unitprice = new Array(rowCnt-1)
       var productId=new Array(rowCnt-1)
       var total=new Array(rowCnt-1)
       var rowStatus=new Array(rowCnt-1)
   }
      for (var i=1,k=0;i<=rowId-1;i++,k++) {
       if (i%2==0) var rowClass="evenListRow"
       else var rowClass="oddListRow"
              rowArray[k]="<tr id='hrow"+i+"' class='"+rowClass+"'>"+getObj("hrow"+i).innerHTML+"</tr><tr id='tableline'><td colSpan='8' class='tableRowSep'></td></tr>"
       newInnerHTML+=rowArray[k]
              if (browser_nn4 || browser_nn6) {
           product[k]=getObj("txtProduct"+i).value
	   productcode[k]=getObj("hdnProductCode"+i).value
	   qtyinstock[k]=getObj("hdnQtyStock"+i).value
           qty[k]=getObj("txtQty"+i).value
	   unitprice[k]=getObj("hdnUnitPrice"+i).value
           listPrice[k]=getObj("txtListPrice"+i).value
           total[k]=getObj("total"+i).value
           productId[k]=getObj("hdnProductId"+i).value
           rowStatus[k]=getObj("hdnRowStatus"+i).value
       }
   }
      for (var i=rowId+1;i<=rowCnt;i++,k++) {
       rowArray[k]=getObj("hrow"+i).innerHTML
       var temp=rowArray[k]
       temp=temp.replace("hrow"+i,"hrow"+(i-1))
       temp=temp.replace("hdnProductName"+i,"hdnProductName"+(i-1))
       temp=temp.replace("hdnProductName"+i,"hdnProductName"+(i-1))
       temp=temp.replace("txtProduct"+i,"txtProduct"+(i-1))
       temp=temp.replace("txtProduct"+i,"txtProduct"+(i-1))
       temp=temp.replace("hdnProductCode"+i,"hdnProductCode"+(i-1))	
       temp=temp.replace("hdnProductCode"+i,"hdnProductCode"+(i-1))	
       temp=temp.replace("hdnQtyStock"+i,"hdnQtyStock"+(i-1))
       temp=temp.replace("hdnQtyStock"+i,"hdnQtyStock"+(i-1))
       temp=temp.replace("txtQty"+i,"txtQty"+(i-1))
       temp=temp.replace("txtQty"+i,"txtQty"+(i-1))
       temp=temp.replace("hdnUnitPrice"+i,"hdnUnitPrice"+(i-1))
       temp=temp.replace("hdnUnitPrice"+i,"hdnUnitPrice"+(i-1))
       temp=temp.replace("txtListPrice"+i,"txtListPrice"+(i-1))
       temp=temp.replace("txtListPrice"+i,"txtListPrice"+(i-1))
       temp=temp.replace("total"+i,"total"+(i-1))
       temp=temp.replace("total"+i,"total"+(i-1))
       temp=temp.replace("delRow"+i,"delRow"+(i-1))
       temp=temp.replace("delRow"+i,"delRow"+(i-1))
       temp=temp.replace("hdnProductId"+i,"hdnProductId"+(i-1))
       temp=temp.replace("hdnProductId"+i,"hdnProductId"+(i-1))
       temp=temp.replace("hdnRowStatus"+i,"hdnRowStatus"+(i-1))
       temp=temp.replace("hdnRowStatus"+i,"hdnRowStatus"+(i-1))
       temp=temp.replace("hdnTotal"+i,"hdnTotal"+(i-1))
       temp=temp.replace("hdnTotal"+i,"hdnTotal"+(i-1))
              if ((i-1)%2==0) var rowClass="evenListRow"
       else var rowClass="oddListRow"
              rowArray[k]="<tr id='hrow"+(i-1)+"' class='"+rowClass+"'>"+temp+"</tr><tr id='tableline'><td colSpan='8' class='tableRowSep'></td></tr>"
       newInnerHTML+=rowArray[k]
              if (browser_nn4 || browser_nn6) {
           product[k]=getObj("txtProduct"+i).value
	   productcode[k]=getObj("hdnProductCode"+i).value
	   qtyinstock[k]=getObj("hdnQtyStock"+i).value
           qty[k]=getObj("txtQty"+i).value
	   unitprice[k]=getObj("hdnUnitPrice"+i).value
           listPrice[k]=getObj("txtListPrice"+i).value
           total[k]=getObj("total"+i).value
           productId[k]=getObj("hdnProductId"+i).value
           rowStatus[k]=getObj("hdnRowStatus"+i).value
       }           }

   var prodListBody=getProdListBody()
   //var prodList=getObj("productList")
   getObj("productList").innerHTML=listTableStart+newInnerHTML+"</table>"

   rowCnt--

   for (var i=1,k=0;i<=rowCnt;i++,k++) {
       if (browser_nn4 || browser_nn6) {
           getObj("txtProduct"+i).value=product[k]
	   getObj("hdnProductCode"+i).value=productcode[k]
	   getObj("hdnQtyStock"+i).value=qtyinstock[k]
           getObj("txtQty"+i).value=qty[k]
	   getObj("hdnUnitPrice"+i).value=unitprice[k]
           getObj("txtListPrice"+i).value=listPrice[k]
           getObj("total"+i).value=total[k]
           getObj("hdnProductId"+i).value=productId[k]
           getObj("hdnRowStatus"+i).value=rowStatus[k]
       }
   }

   calcGrandTotal()
}

function  calcRowTotal()
{
	for(var rowId=1;rowId<=rowCnt;rowId++)
	{

		var qty = getObj("txtQty"+rowId).value;
		var listprice = getObj("txtListPrice"+rowId).value;

		qty = qty.replace(/,+/g, '');
	        listprice = listprice.replace(/,+/g, '');

		var total=(qty*listprice)

		getObj("property(hdnTotal"+rowId+")").value=(total.toString())
	        calcGrandTotal()
	}
}

function calcTotal(currObj) {
        var trObj=currObj.parentNode.parentNode
        var rowId=parseInt(trObj.id.substr(trObj.id.indexOf("w")+1,trObj.id.length))

	var qty = getObj("txtQty"+rowId).value;
        var listprice = getObj("txtListPrice"+rowId).value;

        qty = qty.replace(/,+/g, '');
        listprice = listprice.replace(/,+/g, '');


	var total=(qty*listprice)
        getObj("total"+rowId).value=roundValue(total.toString())
        calcGrandTotal()
}
function calcGrandTotal() {
        var subTotal=0,grandTotal=0;
        for (var i=1;i<=rowCnt;i++) {
                if (getObj("property(hdnTotal"+i+")").value=="")
                        getObj("property(hdnTotal"+i+")").value=0
                if (!isNaN(getObj("property(hdnTotal"+i+")").value))
                        subTotal+=parseFloat(getObj("property(hdnTotal"+i+")").value)
        }
	grandTotal = subTotal;
	var txtTaxVal = getObj("txtTax").value;
	txtTaxVal = txtTaxVal.replace(/,+/g, '');

	var txtAdjust = getObj("txtAdjustment").value;
	txtAdjust=txtAdjust.replace(/,+/g, '');

	var obj1 = document.createEntityForm.elements['property(Tax)'];
	if(obj1 != undefined)
	{
		if(obj1.value != null && obj1.value !=undefined && obj1.value !="" )
		{
			grandTotal += parseFloat(txtTaxVal);
		}
	}	
	var obj2 = document.createEntityForm.elements['property(Adjustment)'];
	if(obj2 !=undefined)
	{
		if(obj2.value != null && obj2.value !=undefined && obj2.value !="" )
		{
			grandTotal += parseFloat(txtAdjust);
		}
	}
        getObj("subTotal").value=roundValue(subTotal.toString())
        getObj("grandTotal").value=roundValue(grandTotal.toString())
}

function roundValue(val) {
        if (val.indexOf(".")<0) {
                val+=".00"
        } else {
                var dec=val.substring(val.indexOf(".")+1,val.length)
                if (dec.length>2)
                        val=val.substring(0,val.indexOf("."))+"."+dec.substring(0,2)
                else if (dec.length==1)
                        val=val+"0"
        }

        return val;
}
function validate() {
	if(!pageValidate())
		return false;
	if(rowCnt == 0)
	{
		selectone.getJSAlertValue("crm.create.product.select",null,"en_US",function(mesg){ alert(mesg) });
		return false;
	}

	for (var i=1;i<=rowCnt;i++) {
		if (!emptyCheck("txtProduct"+i,"Product Name","text")) return false;
		if (!emptyCheck("txtQty"+i,"Qty","text")) return false;
		if (!emptyCheck("txtListPrice"+i,"List Price","text")) return false;
		if (!qtyValidate("hdnQtyStock"+i,"Qty.in stock")) return false;
		if (!numValidate("txtQty"+i,"Qty","any")) return false;
		if (!numConstComp("txtQty"+i,"Qty","GE","1")) return false;
		if (!numValidate("hdnUnitPrice"+i,"Unit Price","any")) return false;
		if (!numValidate("txtListPrice"+i,"List Price","any")) return false;           }
		if (getObj("txtTax").value.replace(/^\s+/g, '').replace(/\s+$/g, '').length>0)
			if (!numValidate("txtTax","Tax","any")) return false;
		if (getObj("txtAdjustment").value.replace(/^\s+/g, '').replace(/\s+$/g, '').length>0)
			if (!adjValidate("txtAdjustment","Adjustment","any")) return false;

		return true;
}

function FindDuplicate()
{
        var product_id = new Array(rowCnt-1);
        var product_name = new Array(rowCnt-1);
        product_id[1] = getObj("hdnProductId"+1).value;
        product_name[1] = getObj("txtProduct"+1).value;
        for (var i=1;i<=rowCnt;i++)
        {
                for(var j=i+1;j<=rowCnt;j++)
                {
                        if(i == 1)
                        {
                                product_id[j] = getObj("hdnProductId"+j).value;
                        }

			if(product_id[i] != "" && product_id[j] != "")
			{

				if(product_id[i] == product_id[j])
                       		{
                                	selectone.getJSAlertValue("crm.alert.product.duplication.check",
                                	getObj("txtProduct"+j).value+";"+i+";"+j,"en_US",function(mesg) { alert(mesg) })
                                	return false;
                       		}
			}	
                	
		}
        }
        return true;
}


function init(params)
{
	dtPtn = (getObj("dtPtn"))?getObj("dtPtn").value:"";
	calFormat = dtPtn;
	rowCnt = 1;
	userDateFormat = dtPtn;
	acLayer = getObj("aclayer");
	userDateFormat = dtPtn;

	if(getObj("module"))
	{
		var module = getObj("module").value;
	}
	else
	{
		return false;
	}

	if(getObj("_DIALOG_LAYER"))
	{
		getObj("_DIALOG_LAYER").innerHTML = "";
	}
	if(getObj("focusid"))
	{
            if(getObj( getObj("focusid").value ))
            {
                getObj( getObj("focusid").value ).focus();
            }
	}
	if(getObj("fieldvalues"))
	{
		if(getObj("operation"))
		{
			var operation = getObj("operation").value
			if(operation != "edit" && module== "Cases")
			{
				getObj("secHeadSolution Information").innerHTML = "";	
				getObj("secContentSolution Information").innerHTML = "";	
				getObj("secHeadComments Information").innerHTML = "";	
				getObj("secContentComments Information").innerHTML = "";	
			}
		}
		var fieldValues = (getObj("fieldvalues").value).split("|");
 		var cnt =0;
		if(getObj("rowCount")){
		  cnt = getObj("rowCount").value;
		}
		if(cnt > 1)
		{
			for(var k=0;k<cnt-1;k++)
			{
				addRow();
			}
 		}
 		for(var j=0;j<fieldValues.length;j++)
		{
			var fieldMaps = fieldValues[j].split("=");
			var fieldName = fieldMaps[0];
			//var uiType = (getObj("uiType_"+fieldName))?getObj("uiType_"+fieldName).value:1;                       
                        var uiType = (getObj("uiType_property("+fieldName+")"))?getObj("uiType_property("+fieldName+")").value:1;
                        var first =fieldValues[j].indexOf("=");
                        var length=fieldValues[j].length;
                        var val =fieldValues[j].substring(first+1,length);                          
			//var val = fieldMaps[1];
			if(val != null && val.indexOf("__") != -1)
			{
				val = val.replace(/__/g,'"');
			}
			if(fieldName == "module")
			{
				if(val == "Leads" || val == "Contacts")
				{ 
					if(getObj("property(leContModSel)"))
					{
						getObj("property(leContModSel)").value=val
					}
				}
				else
				{
					if(getObj("property(modsel)"))
					{
						if(val != "Home")
						{						
							getObj("property(modsel)").value = val;	
						}
					}
				}
			}
			if((fieldName == "module" && val == "Leads") || (fieldName == "leContModSel" && val == "Leads"))
			{
				if(getObj("property(modsel)"))
				{	
					getObj("property(modsel)").disabled = true;	
				}
				if(getObj("property(modname)"))
				{
					getObj("property(modname)").disabled = true;
				}
				if(getObj("modNameImg"))
				{
					getObj("modNameImg").style.visibility = "hidden";	
				}
			}
			if(fieldName == "secmod" && val != null)
			{
				if(getObj("modselId")){ getObj("modselId").innerHTML = "";}
				if(getObj("modnameId")){ getObj("modnameId").innerHTML = "";}
				if(getObj("leContModSelId")){ getObj("leContModSelId").innerHTML = "";}
				if(getObj("leContModNameId")){ getObj("leContModNameId").innerHTML = "";}
			}
			
			if(getObj("property("+fieldName+")"))
			{
				if(getObj("property("+fieldName+")").type == 'checkbox')
				{
					if(val == 'true')
					{
						getObj("property("+fieldName+")").checked = true;
						getObj("property("+fieldName+")").value = "on";
					}	
				}
				else
				{
					if(uiType == "500")
					{
						if(val != null && val != "" && val != "null" && val.indexOf("--")>-1)
						{
							var groupSet = val.split("##");
							for(var k=0;k < groupSet.length; k++)
							{
								var groups = groupSet[k].split("--");
								if(groups.length > 0)
								{
									var groupValues = groups[1].split("::");
									for(var m=0; m < groupValues.length; m++)
									{
										if(getObj(groups[0]+'$'+groupValues[m]))
											getObj(groups[0]+'$'+groupValues[m]).checked = "true";
									}
								}
							}
						}
					}
					getObj("property("+fieldName+")").value = val;
				}
			}
			else if(getObj(fieldName))
			{
				getObj(fieldName).value = val;	
			}
		}
	}
	if(getObj("mapValues"))
	{
		var id = getObj("id").value;
		var whoId, whatId,isWhoId = false,isWhatId = false;
		var ajaxUrl = "/crm/RelatedList.do?action=relatedlist&module="+module+"&id="+id;
		new Ajax.Updater('relatedPageContent',ajaxUrl,{onComplete:function(){setDisplayNone();showDrillDownPtr(params)},asynchronous:true});
		var fieldValues = (getObj("mapValues").value).split("|");
		var cnt = getObj("rowCount").value;
		if(cnt > 1)
		{
			for(var k=0;k<cnt-1;k++)
			{
				addViewRow();
			}
		}
		for(var j=0;j<fieldValues.length;j++)
		{
			var fieldMaps = fieldValues[j].split("::");
			var fieldName = fieldMaps[0];
			var val = fieldMaps[1];
			//var uiType = (getObj("uiType_"+fieldName))?getObj("uiType_"+fieldName).value:1;
			var uiType = (getObj("uiType_property("+fieldName+")"))?getObj("uiType_property("+fieldName+")").value:1;
                        if(fieldName == "modus1")
			{
				if(val != null)
				{
					getObj("labelTD_Who Id").innerHTML = val;
					isWhoId = true	
				}
			}
			if(fieldName == "modus2")
			{
				if(val != null)
				{
					getObj("labelTD_What Id").innerHTML = val;
					isWhatId = true;	
				}
			}
			var valueObj = getObj("value_"+fieldName);
			var obj = getObj(fieldName);
			if(val != null && valueObj && !obj)
			{
				valueObj.innerHTML = val;			
			}
			else if(val != null && obj)
			{
				if(obj.type == 'hidden')
				{
					obj.value = val;
				}
				else
				{
					obj.innerHTML = val;
				}
			}
		}
		if(!isWhoId)
		{
			if(getObj("labelTD_Who Id"))
			{	
				var removeObj = getObj("labelTD_Who Id").parentNode;
				removeObj.parentNode.removeChild(removeObj);
			}
		}
		if(!isWhatId)
		{
			if(getObj("labelTD_What Id"))
			{
				var removeObj = getObj("labelTD_What Id").parentNode;
				removeObj.parentNode.removeChild(removeObj);
			}
		}
		if(params != undefined && params != "")
		{
			location.href = "#ShowEntityInfo|?module="+module+"&id="+id+"";
		}
	}
	if(getObj("dateFields"))
	{
		var dateFields = (getObj("dateFields").value).split("|");
		cals = new Array();
		for(var p=0;p<dateFields.length;p++)
		{
			addCalendar(dateFields[p],dateFields[p],dateFields[p],getObj("dateFields").form.name);
			if(getObj("dtPtn_"+dateFields[p]))
			{
				getObj("dtPtn_"+dateFields[p]).innerHTML = getObj('dtPtn').value;
			}	
		}
	}
	if(getObj('picklistFields'))
	{
		var values = getObj('picklistFields').value;
		var fields = values.split(";");
		for(var i=0;i<fields.length;i++)
		{	
			var label = fields[i];
			var obj = getObj("property("+label+")");
			if(obj)
			{	
				setDependent(obj,true);
			}	
		}	
	}

	if(module== 'Policies')
	{
		handlePolicyEdit();
	}
	fillMultiselectElements();
    
    // viewentityinfo page
    if(getObj('relatedList'))
    {
        var expandrellist = getURLParam(document.location.href,'returnAnchor');
        if("" != expandrellist)
        {
            if(expandrellist.indexOf("#")<0)
            {
            if(getObj('moreinfo_load'))
            	{
           			 toggleRelatedList(expandrellist.toUpperCase(),module);
           		     window.scroll( findPosX(getObj('relatedList')),findPosY(getObj('relatedList')));
           		}     
            }
        }
    }
    if(getObj("operation")){
    	removeFields(operation,'Lifecycle Role/Stage');
    }
}
<!--function to remove any field; operation values are create,edit,clone and fldId is name or id of the field-->
function removeFields(operation,fldId){
	if(getObj(fldId) && operation.toLowerCase() !='edit') 
	{	
		var removeFld = getObj(fldId).parentNode;
		var previousTD = removeFld.previousSibling;
		previousTD.parentNode.removeChild(previousTD);
		removeFld.parentNode.removeChild(removeFld);
	}
}




function fillmultichkBoxVal(fieldName,val)
{
    if(val != null && val != "" && val != "null")
    {
            var groupSet = val.split("##");
            for(var k=0;k < groupSet.length; k++)
            {
                    var groups = groupSet[k].split("--");
                    if(groups.length > 0)
                    {
                            var groupValues = groups[1].split("::");
                            for(var m=0; m < groupValues.length; m++)
                            {
                                    if(getObj(groups[0]+'$'+groupValues[m]))
                                            getObj(groups[0]+'$'+groupValues[m]).checked = "true";
                            }
                    }
            }
    }
	getObj("property("+fieldName+")").value = val;
}	

function fillMultiselectElements()
{
 if(getObj('multiselectpicklist')!=null && getObj('multiselectpicklist').value!="")
	{
    	var mspfields = getObj('multiselectpicklist').value.split("|");
        for(var i=0;i< mspfields.length;i++)
	    {
        	if(mspfields == "")
            {
                break;
            }
            var fieldandvalue =mspfields[i].split(":");
            if(fieldandvalue.length!=2)break;  
            var lfieldlabel =  fieldandvalue[0];    
            var mcombovalue= fieldandvalue[1];
            var valarr = mcombovalue.split(";");
            if(getObj(fieldandvalue[0])!=null)  
	    	{	
         	   	var htmlselectobj =getObj("comboValue"+getObj(fieldandvalue[0]).value);
           		for(var j=0;j< htmlselectobj.length;j++)
	        	{
                	var optionob = htmlselectobj.options[j];
		            htmlselectobj.options[j].selected=false;
        	        for(var k=0;k< valarr.length;k++)
	        	    {
                	    if(optionob.value== valarr[k])
                    	{
                        	optionob.selected=true;
	                    }
    	            }           
        	    }
		    }	
		}
    }
}

/*function setProbability(name)
{
        selectedText = name.substring(name.indexOf(":")+1,name.length)
        name = name.substring(0,name.indexOf(":"))
        if(document.createEntityForm.elements['property(Probability)'] != undefined)
        {
                document.createEntityForm.elements['property(Probability)'].value = name ;
        }
}
*/
/*function validateProductAlias()
{
	var productAlias = document.createEntityForm.elements['property(Product Name Alias)'].value
	var re1=/^[a-z\d\- ]+$/i
	if (!re1.test(productAlias))
	{
		 selectone.getJSAlertValue("crm.alert.label.special.characters",null,"en_US",
															function(mesg) { alert(mesg) })
		document.createEntityForm.elements['property(Product Name Alias)'].focus()
		return false;
	}
	else
	{
		return true;
	}
}
*/
/*function setProductAlias()
{
    
	var productName = document.createEntityForm.elements['property(Product Name)'].value
	if ( productName.indexOf(" ") > 0 )
	{
		productName = productName.replace(" ","-")
	}
	document.createEntityForm.elements['property(Product Name Alias)'].value = productName
	var re1=/^[a-z\d\- ]+$/i
	if (!re1.test(productName))
	{
		 selectone.getJSAlertValue("crm.alert.label.special.characters",null,"en_US",
																function(mesg) { alert(mesg) })
		 return false;
	}
    
    return true;
}
*/

function lookUp(hostName,serverPort,userName)
{
        var obj=getObj("modsel")
        var selMode=obj.options[obj.options.selectedIndex].value
        document.createEntityForm.elements['property(module)'].value=selMode;

        //alert(document.createActivityForm.elements['property(module)'].value);
        switch (selMode)
        {       case "Accounts" : showLookUp('modname','modid',selMode,'Accounts');break;
                case "Potentials" :showLookUp('modname','modid',selMode,'Potentials');break;
                case "Campaigns" :showLookUp('modname','modid',selMode,'Campaigns');break;
                case "Cases" :showLookUp('modname','modid',selMode,'Cases');break;
                case "Products" :showLookUp('modname','modid',selMode,'Products');break;
                case "Vendors" :showLookUp('modname','modid',selMode,'Vendors');break;
                case "Quotes" :showLookUp('modname','modid',selMode,'Quotes');break;
                case "SalesOrders" :showLookUp('modname','modid',selMode,'SalesOrders');break;
               case "PurchaseOrders" :showLookUp('modname','modid',selMode,'PurchaseOrders');break;
                case "Invoices" :showLookUp('modname','modid',selMode,'Invoices');break;
        }
}

function leContModLookUp(hostName,serverPort,userName)
{
        var obj1=getObj("leContModSel")
        var selMode1=obj1.options[obj1.options.selectedIndex].value
        switch (selMode1)
        {       case "Leads" : showLookUp('leContModName','leContModId',selMode1,'Leads');
                        document.createEntityForm.elements['property(module)'].value="Leads"
                        break;
               case "Contacts" :showLookUp('leContModName','leContModId',selMode1,'Contacts');chkContactMod();break;
        }
}

function showTaskType(fldName,searchmodule,hostName,serverPort,username)
{
        var currObj=getObj(fldName)
        openPopUp('subjectWin',currObj,"/crm/Search.do?searchmodule="+searchmodule+"&fldName="+fldName+"&user="+username,"TaskType",150,125,"toolbar=no,statusbar=no,menubar=no,directories=no,resizable=yes,scrollable=no")
}

function chkContactMod()
{
        if(document.createEntityForm.elements['property(modid)'].value=="")
        {
                document.createEntityForm.elements['property(module)'].value="Contacts"
        }
}

function chkModSel()
{
        var obj1=getObj("leContModSel")
        var selMode1=obj1.options[obj1.options.selectedIndex].value
        if(selMode1=="Contacts")
        {
                document.createEntityForm.elements['property(modsel)'].disabled=false
                document.createEntityForm.elements['property(modname)'].disabled=false
                getObj("modNameImg").style.visibility="visible"
        }
        else
        {
                document.createEntityForm.elements['property(modsel)'].disabled=true
                document.createEntityForm.elements['property(modname)'].disabled=true
                getObj("modNameImg").style.visibility="hidden"
        }
}
function chkSetMod()
{
        if(document.createEntityForm.elements['property(bulkCreate)'] == undefined)
        {
                if(document.createEntityForm.elements['property(modid)'].value=="" && document.createEntityForm.elements['property(leContModId)'].value!="" && document.createEntityForm.elements['property(module)'].value!="Leads")
                {
                        document.createEntityForm.elements['property(module)'].value="Contacts"
                }
        }
}
    function callCreateSegCont( segmentId)
    {
	if(getObj("property(cloneId)").value != null)
        {
                var cloneId = getObj("property(cloneId)").value;
                document.createEntityForm.action = "/crm/IWCreateSegCont.do?segmentId="+segmentId + "& cloneId="+cloneId;
                document.createEntityForm.submit();
        }else
        {
                document.createEntityForm.action = "/crm/IWCreateSegCont.do?segmentId="+segmentId;
                document.createEntityForm.submit();
        }
       
       
    }

function formData2QueryString(docForm) 
{
        var strSubmit       = '';
        var formElem;
        var strLastElemName = '';
        
        for (i = 0; i < docForm.elements.length; i++) 
        {
                formElem = docForm.elements[i];
		if(formElem.name != 'fieldname' && formElem.name != 'fieldlabel' && formElem.name != 'fielddatatype' && formElem.name != 'picklistFields')
		{
                	switch (formElem.type) {
                        	// Text, select, hidden, password, textarea elements
                        	case 'text':
				case 'select-one': 
				case 'hidden':
                        	case 'password':
                        	
                        	case 'textarea':
                               		strSubmit += encodeURIComponent(formElem.name) + '=' + encodeURIComponent(formElem.value) + '&';
				break;
				
				case 'checkbox':
					if ( getObj(formElem.name).checked )
					{
						strSubmit += encodeURIComponent(formElem.name) + '=' + encodeURIComponent(formElem.value) + '&';
					}
					else 
					{
					}
				break;

				case 'radio':

					if(formElem.checked)
					{
						strSubmit += encodeURIComponent(formElem.name) + '=' + encodeURIComponent(formElem.value) + '&';
					}
                break;

				}
		}
        }
        return strSubmit;
}
function loadAjaxTab2(str,style)
{
        var divId = document.getElementById('ajax_load_tab');
        divId.style.display = 'block'; 
        divId.style.zIndex = '1000'; 
        divId.style.left = '600px';
        divId.style.top = '350px';
        var imgfile = '/crm/images/loader2.gif';
        divId.innerHTML = '<span><img src="'+imgfile+'" align="absmiddle"></span>&nbsp; Loading ' + str + '...';
	setCenter(divId);
}
function showMenu() {
                if (getObj("subMenu") && getObj("subMenu").style.display=="block")
		{	
                	getObj("subMenu").style.display="none" 
		}
		var iframeIEHack = document.createElement("IFRAME");
		if (browser_ie && !browser_opera) 
		{
			iframeIEHack.id = "menuFrame";
			iframeIEHack.scrolling = "no";
			iframeIEHack.frameBorder = 1;
              	}
		else if(browser_nn6 || browser_nn4)
		{
			iframeIEHack.setAttribute("id","menuFrame");
			iframeIEHack.setAttribute("scrolling","no");
			iframeIEHack.setAttribute("frameBorder",0);
		}    
		iframeIEHack.style.position = "absolute";
		iframeIEHack.style.zIndex = "90";
		iframeIEHack.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(style=0,opacity=0)';
               
	       getObj("menu").style.display="block"
	       getObj("menu").style.zIndex = "98";
		if(getObj("showMenu").offsetWidth != undefined)
		{
			var top= getObj("menu").style.top=findPosY(getObj("showMenu"))+15
			var left= getObj("menu").style.left=findPosX(getObj("showMenu"))+getObj("showMenu").offsetWidth-getObj("menu").offsetWidth
		}
		else
		{
			var top= getObj("menu").style.top=findPosY(getObj("menuTD"))+40;
			var left= getObj("menu").style.left=xMenuPos+menuWidth-getObj("menu").offsetWidth
		}
     
		Dig=document.getElementById('menu');	
	
		iframeIEHack.style.width = Dig.offsetWidth + "px";
		iframeIEHack.style.height = Dig.offsetHeight + "px";
		iframeIEHack.style.top = top + "px";
		iframeIEHack.style.left = left + "px";
	
		document.body.appendChild(iframeIEHack);
	 }
        function hideMenu(ev) {
                if (browser_ie)
			 var obj = window.event.srcElement;
                else if (browser_nn4 || browser_nn6)
			 var obj = ev.target;
                if (obj.id!="showMenu" && obj.id != "showSubMenu" && obj.id != "viewAction" && obj.id!="sendMessageAction" && obj.id != "export"  && obj.id!="allPage" && obj.id!="thisPage" && obj.id!="locateMap" && obj.id != "copyAddress" && obj.id != "btnExport")
		{
                        if (getObj("menu") && getObj("menu").style.display=="block")			    {
				getObj("menu").style.display="none"
			}		
                        if (getObj("subMenu") && getObj("subMenu").style.display=="block")
			{	
                                getObj("subMenu").style.display="none"
			}		
            if (getObj("exportMenu") && getObj("exportMenu").style.display=="block")
			{	
                                getObj("exportMenu").style.display="none"
			}
            if (getObj("viewMenuAction") && getObj("viewMenuAction").style.display=="block")
			{	
            	getObj("viewMenuAction").style.display="none"
			}
            if (getObj("viewSendMessageAction") && getObj("viewSendMessageAction").style.display=="block")
			{	
            	getObj("viewSendMessageAction").style.display="none"
			}
                        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"
			}
		 	if (getObj("copy") && getObj("copy").style.display=="block")
			{	
                                getObj("copy").style.display="none"
			}
			if (document.getElementById("exportAllSubMenu") && document.getElementById("exportAllSubMenu").style.display=="block")
			{	
                                document.getElementById("exportAllSubMenu").style.display="none"
			}
			if (document.getElementById("exportSubMenu") && document.getElementById("exportSubMenu").style.display=="block")
			{	
                                document.getElementById("exportSubMenu").style.display="none"
			}
			
		}			


		iframeIEHack=document.getElementById("menuFrame");
		if(iframeIEHack)
		{
			document.body.removeChild(iframeIEHack);
			iframeIEHack = null;
	 	}
	  }

function pageValidate() {
	var fieldname = getObj("fieldname").value;
	fieldname = fieldname.split(",");
	var fielddatatype = (getObj("fielddatatype").value).split(",");
	var fieldlabel = (getObj("fieldlabel").value).split(",");

    var fielddecimal;
    if(getObj("fielddecimal"))
    {
      fielddecimal = (getObj("fielddecimal").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,",");
		}

		var type=fielddatatype[i].split("~")
			if (type[1]=="M") {
				if (!emptyCheck(fieldname[i],fieldlabel[i]))
					return false;
			}

		switch (type[0]) {
			case "O"  : break;
			case "V"  : break;
			case "C"  : break;
			case "E"  : 
				if (getObj(fieldname[i]) != null 
						&& getObj(fieldname[i]).value.replace(/^\s+/g, '').replace(/\s+$/g, '').length!=0) 
				{
					if (!emailValidate(fieldname[i],fieldlabel[i]))
						return false;
				}
			break;
			case "DT" :
				if (getObj(fieldname[i]) != null 
						&& getObj(fieldname[i]).value.replace(/^\s+/g, '').replace(/\s+$/g, '').length!=0)
				{
					if(typeof(type[3])=="undefined") var currdatechk="OTH";
					else var currdatechk=type[3];

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

                                        if (!monthYrValidate(fieldname[i],fieldlabel[i],currdatechk))
                                                return false

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

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

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

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

function setCenter(obj){
 	obj.style.top=document.body.scrollTop+200;
}

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,sevt)
{

    	if (typeof browser_ie != 'undefined')
    	{
        	sevt=event;
    	}
   /* 
    if (typeof browser_ie == 'undefined')  
    {
        // return false;
    }
    else if(browser_ie)
    {
        selectone.getJSAlertValue("crm.browser.true",null,"en_US",
																		function(mesg) { alert(mesg) })
    }
    else
    {
         selectone.getJSAlertValue("crm.browser.false",null,"en_US",
																		function(mesg) { alert(mesg) })
    }    
    */
       if(sevt.keyCode==13)
         {
            if(browser_ie)
            {
                sevt.returnValue=false;
                getObj(saveButton).fireEvent("onclick", sevt);        
            }
            else
            {
                sevt.returnValue=false;
                getObj(saveButton).click();       
                //return false;
             }
             return false;;
        }
    return true;
}
/*function toggleRelatedList(id)
{
	var listTableObj=getObj(id)
	var toggleImageObj=getObj(id+"img")
	if (listTableObj.style.display=="block")
	{
		listTableObj.style.display="none"
		toggleImageObj.src="/crm/images/expand.gif"
	} else
	{
		listTableObj.style.display="block"
		toggleImageObj.src="/crm/images/collapse.gif"
	}
	set_cookie(id,listTableObj.style.display)
}
*/

// Setting cookies
function set_cookie ( name, value, exp_y, exp_m, exp_d, path, domain, secure )
{
  var cookie_string = name + "=" + escape ( value );
  //delete_cookie(name)
  if ( exp_y )
  {
    var expires = new Date ( exp_y, exp_m, exp_d );
    cookie_string += "; expires=" + expires.toGMTString();
  }
  if ( path )
        cookie_string += "; path=" + escape ( path );
  if ( domain )
        cookie_string += "; domain=" + escape ( domain );
  if ( secure )
        cookie_string += "; secure";
  document.cookie = cookie_string;
}

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

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

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


function selectActionOld(operation, anchor,editmode )
{
    var extraurl="";
    if(getObj('cvid'))
    {
        extraurl = "&cvid="+getObj('cvid').value+ "&cvname="+ getObj('cvname').value;;
        if(getObj('sortcolumn'))
        {
           extraurl = extraurl+"&sortcolumn="+ getObj('sortcolumn').value;    
        }    
    }

   var module= getObj("module").value;
   var id = getObj("id").value; 

	if (document.viewentityform.target == "_blank")
	{
		document.viewentityform.target="_self";
	}
        if(operation == 'Edit')
	{
                document.viewentityform.action="/crm/Edit.do";
		document.viewentityform.submit();
	}
	else if(operation == 'Delete')
	{
		if(window.confirm("Are you sure?"))
                {
			document.viewentityform.action="/crm/MassDelete.do";			
                        document.viewentityform.submit();
		}
		else
		{
			return false;
		}
	}
        else if(operation == 'NewTask')
        {    
                document.viewentityform.action="/crm/Create.do?module=Tasks&actType=Task&returnAnchor=" + anchor+ extraurl;

                
                document.viewentityform.submit();               
	}
        else if(operation == 'NewEvent')
        {       
		document.viewentityform.action="/crm/Create.do?module=Appointments&actType=Event&returnAnchor=" + anchor;
		document.viewentityform.submit();              
	}
	else if(operation == 'Competitor' || operation == 'Competitors')
        {
	        document.viewentityform.action="/crm/potentials/NewCompetitor.do?module=Potentials&title_key=crm.title.create.competitor&returnAnchor=" + anchor;
		document.viewentityform.submit();
	}
        else if(operation == 'Attach')
	{
                document.viewentityform.action="/crm/NewFileAttachment.do?title_key=crm.title.new.attachment&returnAnchor=" + anchor+ extraurl;
		document.viewentityform.submit();
	}
	else if(operation == 'Clone')
        {
	        document.viewentityform.action="/crm/Clone.do";
		document.viewentityform.submit();
	}
	else if(operation == 'Convert')
        {
		document.viewentityform.action="/crm/leads/Convert.do";
		document.viewentityform.submit();
	}
        else if(operation == 'Notes')
        {
	        document.viewentityform.action="/crm/NewNoteAttachment.do?title_key=crm.title.new.note&returnAnchor="+anchor+ extraurl;
		document.viewentityform.submit();
	}
        else if(operation == 'Essays')
        {
	        document.viewentityform.action="/crm/NewEssayAttachment.do?title_key=crm.title.new.essay&returnAnchor=" + anchor;
		document.viewentityform.submit();
	}
        else if(operation == 'AddInfo')
        {
	        document.viewentityform.action="/crm/NewAddInfoAttachment.do?title_key=crm.title.new.addinfo&returnAnchor=" + anchor;
		document.viewentityform.submit();
	}

   else if(operation == 'Sponsors' || operation=='Sponsor')
   {
	        document.viewentityform.action="/crm/NewSponsor.do?title_key=crm.title.new.sponsors&returnAnchor=" + anchor;
		document.viewentityform.submit();
   }
    else if(operation == 'Team' || operation == "Teams")
   {
	        document.viewentityform.action="/crm/NewTeam.do?title_key=crm.title.new.team&returnAnchor=" + anchor;
		document.viewentityform.submit();	
		
   }
   
   else if(operation == 'Pricing' || operation == "Pricings")
   {
	        document.viewentityform.action="/crm/NewPricing.do?title_key=crm.title.new.pricing&returnAnchor=" + anchor;
		document.viewentityform.submit();	
		
   }
   

   else if(operation == 'IterationRequirement')
   {
	        document.viewentityform.action="/crm/NewIterationRequirement.do?title_key=IterationRequirement&returnAnchor=" + anchor+"&editmode="+editmode;
		document.viewentityform.submit();
   }
  else if(operation == 'AddDynamicForms')
  {
	document.viewentityform.action="/crm/AddDynamicForms.do?title_key=AddDynamicForms";
	document.viewentityform.submit();

  }	
   else if(operation == 'Scholarships')
   {
	   if(id == undefined)
	   {
	        document.viewentityform.action="/crm/AssignScholarship.do?title_key=crm.title.new.scholarship&returnAnchor=" + anchor+"&module="+module+"&entityId="+ id;
	   }	
	   else
	   {	   
	        document.viewentityform.action="/crm/AssignScholarship.do?title_key=crm.title.new.scholarship&returnAnchor=" + anchor+"&module="+module+"&entityId="+id+"&id="+id;
	   }
	   document.viewentityform.submit();
   }

   else if(operation == 'Recommenders')
   {
	        document.viewentityform.action="/crm/NewRecommender.do?title_key=crm.title.new.recommenders&returnAnchor=" + anchor;
		document.viewentityform.submit();
   }
    else if(operation == 'Related Contact')
   {
	        document.viewentityform.action="/crm/IWNewContactsRel.do?title_key=Add Related Contact&returnAnchor=" + anchor;
		document.viewentityform.submit();
   }
	else if(operation == 'Duplicate Leads')
        {
                document.viewentityform.action="/crm/leads/DuplicateLeads.do";
                document.viewentityform.submit();
        }
	else if ( operation == "Contact Role" || operation == "Contact Roles")
	{
		document.viewentityform.action="/crm/potentials/ShowContactsRolesMapping.do"+"?returnAnchor="+anchor;
		document.viewentityform.submit();
	}
        else 
	{
         	document.viewentityform.action="/crm/Create.do?module="+operation+"&returnAnchor="+anchor+ extraurl;
		document.viewentityform.submit();
	}
}

function selectActionNew(operation, anchor,primmodule,dispid)
{
	var extraurl="";
    if(getObj('cvid'))
         {
            extraurl = "&cvid="+getObj('cvid').value+ "&cvname="+ getObj('cvname').value;;
            if(getObj('sortcolumn'))
            {
                 extraurl = extraurl+"&sortcolumn="+ getObj('sortcolumn').value;    
            }    
         }

    var isdynamic=false;
    if(getObj('isdynamic').value=='true')
    {
        isdynamic=true;
    } 

    var module= document.getElementById("module").value;
	var mode= document.getElementById("mode").value;
	var id = document.getElementById("id").value; 
	if (document.viewentityform.target == "_blank")
	{
		document.viewentityform.target="_self";
	}
    if(operation == 'Edit')
	{
    
        if(module== 'Campaigns')
        {
            if(mode=='Planned' || mode=='Scheduled' || mode=='Error')
            {
              document.viewentityform.action="/crm/Edit.do?type=Edit&id="+id+"&isload=true";

            } 
            else if(mode=='Completed' || mode=='In Progress')
            {
                document.viewentityform.action="/crm/CreateCampaignWizard.do?type=edit&step=launched&campaignId="+id+"&isload=true";

            }
           	
            document.viewentityform.submit();
            return false;            
        } 
        else if(isdynamic)
        {


          var url = "/crm/Edit.do?module="+module+"&id="+id;
         if(getObj('cvid'))
         {
            url = "/crm/Edit.do?module="+module+"&id="+id+"&cvid="+getObj('cvid').value+ "&cvname="+ getObj('cvname').value;;
            if(getObj('sortcolumn'))
            {
                 url = "/crm/Edit.do?module="+module+"&id="+id+"&cvid="+getObj('cvid').value+"&sortcolumn="+ getObj('sortcolumn').value + "&cvname="+ getObj('cvname').value;    
            }    
         }

		  ajaxNew(url);
        }
        else
        {
          document.viewentityform.action="/crm/Edit.do?module="+module+"&id="+id+"&isload=true";        

          if(getObj('cvid'))
          {
              document.viewentityform.action="/crm/Edit.do?module="+module+"&id="+id+"&isload=true"+"&cvid="+getObj('cvid').value+ "&cvname="+ getObj('cvname').value;;
            if(getObj('sortcolumn'))
            {
                document.viewentityform.action="/crm/Edit.do?module="+module+"&id="+id+"&isload=true"+"&cvid="+getObj('cvid').value+"&sortcolumn="+ getObj('sortcolumn').value+ "&cvname="+ getObj('cvname').value;; ;   
            }         
            

          }

            document.viewentityform.submit();
            return false;
        }
	}
	else if(operation == 'Delete')
	{
		if(window.confirm("Are you sure?"))
                {     
                    if(module=='Venues'){
                        DWRCommonUtil.getlocationStatus
                        (
                        id,
                        function(isPresent)
                        {
                            locationPresent=isPresent;                        
                            if(locationPresent== true)
                            {
                                alert('Unable to perform the operation as the Location used in Event ');
                            }    
                            else 
                            {                        
                                var url="/crm/MassDelete.do?module="+module+"&id="+id;		
                                document.viewentityform.action=url;
                                document.viewentityform.submit();
                            }
                        }
                        );
                     }
                     else if(module=='Discounts'){
                        DWRCommonUtil.getDiscountStatus
                        (
                        id,
                        function(isPresent)
                        {
                            discountPresent=isPresent;                        
                            if(discountPresent== true)
                            {
                                alert('Unable to perform the operation as the Discount has been applied to Invoices');
                            }    
                            else 
                            {                        
                                var url="/crm/MassDelete.do?module="+module+"&id="+id;		
                                document.viewentityform.action=url;
                                document.viewentityform.submit();
                            }
                        }
                        );
                     }
                     else if(module=='Connections'){
                                               
                            var cname= getObj("cname").value;
                	        var rcont= getObj("rcont").value;
                            var url="/crm/DeleteContactRelation.do?module=Connections&id="+id+"&relAccId="+rcont+"&actModule=Contacts&actId="+cname+"&returnAnchor=CONNECTIONSPERSONALITY";
                            document.viewentityform.action=url;
                            document.viewentityform.submit();
                        
                      }
                    else{
                            var url="/crm/MassDelete.do?module="+module+"&id="+id;		
                            document.viewentityform.action=url;
                            document.viewentityform.submit();
                    }
                    return false;
		}
		else
		{
			return false;
		}
	}
        else if(operation == 'NewTask')
	{    
		var url = "/crm/Create.do?module=Tasks&id="+id+"&relmodule="+module+"&returnAnchor=" + anchor+"&primmodule="+primmodule+"&entityid="+dispid;
		ajaxNew(url)
	}
        else if(operation == 'NewEvent')
        {      
	       	var url = "/crm/Create.do?module=Appointments&id="+id+"&relmodule="+module+"&returnAnchor=" + anchor+"&primmodule="+primmodule+"&entityid="+dispid;
		ajaxNew(url)	
	}
	else if(operation == 'Competitor')
        {
	        document.viewentityform.action="/crm/potentials/NewCompetitor.do?module=Potentials&title_key=crm.title.create.competitor&returnAnchor=" + anchor;
		document.viewentityform.submit();
	}
        else if(operation == 'Attach')
	{
		showFileAttach();
                //document.viewentityform.action="/crm/NewFileAttachment.do?title_key=crm.title.new.attachment&returnAnchor=" + anchor;
		//document.viewentityform.submit();
	}
	else if(operation == 'Clone')
        {
    
		var url = "/crm/Clone.do?module="+module+"&id="+id;
        if(isdynamic)
        {
		    ajaxNew(url);
        }
        else
        {
           document.viewentityform.action=url+"&isload=true";
		   document.viewentityform.submit();
        }
	}
	else if(operation == 'Convert')
        {
		document.viewentityform.action="/crm/leads/Convert.do";
		document.viewentityform.submit();
	}
        else if(operation == 'Notes')
        {
	        document.viewentityform.action="/crm/NewNoteAttachment.do?title_key=crm.title.new.note&returnAnchor=" + anchor;
		document.viewentityform.submit();
	}
	else if(operation == 'Duplicate Leads')
        {
                document.viewentityform.action="/crm/leads/DuplicateLeads.do";
                document.viewentityform.submit();
        }
        else if(operation == 'Duplicate Contacts')
        {
                document.viewentityform.action="/crm/contacts/DuplicateContacts.do";
                document.viewentityform.submit();
        }
        else if(operation == 'Duplicate Organizations')
        {
        	document.viewentityform.action = "/crm/FindDuplicateOrganizations.do";
        	document.viewentityform.submit();
        }
	else if ( operation == "Contact Role" )
	{
		document.viewentityform.action="/crm/potentials/ShowContactsRolesMapping.do"+"?returnAnchor="+anchor;
		document.viewentityform.submit();
	}


else if(operation == 'Essays')
        {
	        document.viewentityform.action="/crm/NewEssayAttachment.do?title_key=crm.title.new.essay&returnAnchor=" + anchor;
		document.viewentityform.submit();
	}
        else if(operation == 'AddInfo')
        {
	        document.viewentityform.action="/crm/NewAddInfoAttachment.do?title_key=crm.title.new.addinfo&returnAnchor=" + anchor;
		document.viewentityform.submit();
	}

   else if(operation == 'Sponsors')
   {
	        document.viewentityform.action="/crm/NewSponsor.do?title_key=crm.title.new.sponsors&returnAnchor=" + anchor;
		document.viewentityform.submit();
   }
    else if(operation == 'Team')
   {
	        document.viewentityform.action="/crm/NewTeam.do?title_key=crm.title.new.team&returnAnchor=" + anchor;
		document.viewentityform.submit();	
		
   }
   
   else if(operation == 'Pricing')
   {
	        document.viewentityform.action="/crm/NewPricing.do?title_key=crm.title.new.pricing&returnAnchor=" + anchor;
		document.viewentityform.submit();	
		
   }
   

   else if(operation == 'IterationRequirement')
   {
	        document.viewentityform.action="/crm/NewIterationRequirement.do?title_key=IterationRequirement&returnAnchor=" + anchor+"&editmode="+editmode;// TODO
		document.viewentityform.submit();
   }

   else if(operation == 'Scholarships')
   {
	   if(id == undefined)
	   {
	        document.viewentityform.action="/crm/AssignScholarship.do?title_key=crm.title.new.scholarship&returnAnchor=" + anchor+"&module="+ module+"&entityId="+id;
	   }	
	   else
	   {	   
	        document.viewentityform.action="/crm/AssignScholarship.do?title_key=crm.title.new.scholarship&returnAnchor=" + anchor+"&module="+module+"&entityId="+ id+"&id="+id;// TODO check id variable
	   }
	   document.viewentityform.submit();
   }

   else if(operation == 'Recommenders')
   {
	        document.viewentityform.action="/crm/NewRecommender.do?title_key=crm.title.new.recommenders&returnAnchor=" + anchor;
		document.viewentityform.submit();
   }
	else if(operation == 'Generate Pdf')
   {
	        document.location.href="/crm/GeneratePdf.do?id=" +id;
   }

  else if(operation == 'Mark Spam')
   {
        var httphandle = getHTTPObject();
        var url="/crm/SpamStatus.do?caseID="+document.viewentityform.entityId.value+"&spamStatus=true";
        showInLine('zohobusy_loadpage_vinfo');
        httphandle.open("GET",url,false);
        httphandle.send(null);
        hide('zohobusy_loadpage_vinfo');  
        //alert(httphandle.responseText);
        if(httphandle.responseText.trim() == 'success')
        {
            var spambutton = getObj('spamstatusbutton');
            spambutton.value='Not Spam';
            setTextView("<strong>The case has been marked as spam</strong>");
        }
        else
        {
            alert(httphandle.responseText);
        }
         
   }
   else if(operation == 'Not Spam')
   {
        var httphandle = getHTTPObject();
        var url="/crm/SpamStatus.do?caseID="+document.viewentityform.entityId.value+"&spamStatus=false";
        showInLine('zohobusy_loadpage_vinfo');
        httphandle.open("GET",url,false);
        httphandle.send(null);
         hide('zohobusy_loadpage_vinfo');       
        //alert(httphandle.responseText);
        if(httphandle.responseText.trim() == 'success')
        {
            var spambutton = getObj('spamstatusbutton');
            spambutton.value='Mark Spam';
            setTextView("<string>The case has been unmarked as spam<string>");
        }
        else
        {
            alert(httphandle.responseText);
        }
 
   }


        else 
	{
         	document.viewentityform.action="/crm/Create.do?module="+operation+"&returnAnchor="+anchor+ extraurl;
		document.viewentityform.submit();
	}
    return false;
}

function setTextView(str)
{
    getObj('viewentity_alertdisplay').innerHTML="";
    getObj('viewentity_alertdisplay').innerHTML=str+ "&nbsp;&nbsp;";
    showInLine('viewentity_alertdisplay'); 
    setTimeout("hideViewAlert()",1500);   

}

function hideViewAlert()
{
        Effect.Fade('viewentity_alertdisplay');
}

// function used for merge contacts in Listview
function validateMerge(chk) {
    var checkboxes=getObj(chk);
    var noofrows=checkboxes.length;
	var cnt=0;	
	for (var i=0;i<noofrows;i++) 
	{
		if (checkboxes[i].checked) cnt++
	}
	
	if (cnt==0 || cnt==1) {
            selectone.getJSAlertValue("crm.alert.minlength.merge","Contacts","en_US",function(mesg){ alert(mesg) })


              


		return false
	} else if (cnt>3) {
		selectone.getJSAlertValue("crm.alert.maxlength.merge","Contacts","en_US",function(mesg){ alert(mesg) })
		return false
	}
        else
        {
        document.showcvdetails.action="/crm/contacts/MergeAction.do";
	document.showcvdetails.submit();            
        }
}

// validation function for merging organizations from list view
function validateMergeOrgs(chk)
{
    var checkboxes = getObj(chk);
    var noofrows = checkboxes.length;
	var count = 0;	
	for(var i=0; i < noofrows; i++)
	{
		if(checkboxes[i].checked) 
		{
			count++;
		}
	}
	
    if(count == 2)
    {
	    document.showcvdetails.action="/crm/OrganizationsMerging.do";
    	document.showcvdetails.submit();
    }
    else if(count < 2)
	{
        selectone.getJSAlertValue("crm.merge.orgs.minimum","Organizations","en_US",function(mesg){ alert(mesg) })
		return false;
	}
	else
	{
		selectone.getJSAlertValue("crm.merge.orgs.maximum","Organizations","en_US",function(mesg){ alert(mesg) })
		return false;
	}
}

// function used for showfullprofile of Detailsview
function showprofile(Obj)
{
	if(document.getElementById(Obj).style.display=="none")
	{
		document.getElementById(Obj).style.display="block";
		document.getElementById("quickprofile").style.display="none";
	}
	else
	{
		document.getElementById(Obj).style.display="none";
		document.getElementById("quickprofile").style.display="block";
	}
set_cookie("full_profile",document.getElementById(Obj).style.display)
}
function printAction(xx, module,action)
{
	win=window.open("/crm/PrintEntityInfo.do?module="+module+"&id="+xx+"&action="+action+"&step=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)
{
        var extraurl="";
    if(getObj('cvid'))
    {
        extraurl = "&cvid="+getObj('cvid').value+ "&cvname="+ getObj('cvname').value;;
        if(getObj('sortcolumn'))
        {
           extraurl = extraurl+"&sortcolumn="+ getObj('sortcolumn').value;    
        }    
    }

	var module = getObj("module").value;
	document.viewentityform.action="/crm/Create.do?module=Potentials&accountid="+accountid+"&accountname="+accountname+"&entityid="+contactid+"&entityname="+contactname+"&relmodule=Contacts&returnAnchor="+anchor+ extraurl;
        document.viewentityform.submit();
	/*var url = "/crm/Create.do?module=Potentials&accountid="+accountid+"&accountname="+accountname + "&entityid=" + contactid+ "&entityname="+contactname+"&returnAnchor="+anchor+"&primmodule=Contacts";
    	ajaxNew(url+"&relmodule="+module+"");*/
}



function createOld(module,entityid,entityname,anchor)
{
   
    var viewmodule = getObj('module').value;
    if(viewmodule=='Contacts' && module== 'Registrations' && getObj('regcontactid')!=null && getObj('fullname')!=null)
    {
     var regcontactid =    getObj('regcontactid').value;
    var fullname =    getObj('fullname').value;

         //document.viewentityform.action="/crm/Create.do?module="+module+"&regcontactid="+regcontactid+"&fullname="+fullname+"&returnAnchor="+anchor;
         document.viewentityform.action="/crm/Create.do?module="+module+"&entityid="+entityid+"&entityname="+fullname+"&relmodule="+ viewmodule +"&returnAnchor="+anchor;
document.viewentityform.submit();
        return false;
    }


    if(viewmodule == 'Cases' && module=='Potentials')
    {
            
    }
                document.viewentityform.action="/crm/Create.do?module="+module+"&entityid="+entityid+"&entityname="+entityname+"&relmodule="+ viewmodule +"&returnAnchor="+anchor;
        	document.viewentityform.submit();



if(module == ("Accounts") )
{   
	if(module=='Quotes' || module=='SalesOrders' || module=='Invoices')
	{
		document.viewentityform.action="/crm/FillEntityObject.do?fillUpModule=Accounts&operation=create&module="+module+"&entityid="+entityid+"&entityname="+entityname;
        		document.viewentityform.submit();
	}

   }
   else if(module == ("Quotes"))
   {

	if( module=='SalesOrders' || module=='Invoices')
        {
        	document.viewentityform.action="/crm/FillEntityObject.do?fillUpModule=Quotes&operation=create&module="+module+"&entityid="+entityid+"&entityname="+entityname;
       		document.viewentityform.submit();
        }

   }
   else if(module == ("SalesOrders"))
   {

   	if(module=='Invoices')
        {
        	document.viewentityform.action="/crm/FillEntityObject.do?fillUpModule=SalesOrders&operation=create&module="+module+"&entityid="+entityid+"&entityname="+entityname;
       	 	document.viewentityform.submit();
        }

   }
}

function create(module,entityid,entityname,anchor,primmodule)
{
	var url = "/crm/Create.do?module="+module+"&entityid="+entityid+"&entityname="+entityname+"&returnAnchor="+anchor+"&primmodule="+primmodule;
   	if(module == ("Accounts") )
   	{
		if(module=='Quotes' || module=='SalesOrders' || module=='Invoices')
		{
			url = "/crm/FillEntityObject.do?fillUpModule=Accounts&operation=create&module="+module+"&entityid="+entityid+"&entityname="+entityname+"&primmodule="+primmodule+"&returnAnchor="+anchor ;	
		}
   	}
   	else if(module == ("Quotes"))
   	{
		if( module=='SalesOrders' || module=='Invoices')
        	{
        		url="/crm/FillEntityObject.do?fillUpModule=Quotes&operation=create&module="+module+"&entityid="+entityid+"&entityname="+entityname+"&primmodule="+primmodule+"&returnAnchor="+anchor  ;
        	}	
   	}
   	else if(module == ("SalesOrders"))
   	{
   		if(module=='Invoices')
        	{
        		url="/crm/FillEntityObject.do?fillUpModule=SalesOrders&operation=create&module="+module+"&entityid="+entityid+"&entityname="+entityname+"&primmodule="+primmodule+"&returnAnchor="+anchor ;
        	}
   	}
	ajaxNew(url+"&relmodule="+primmodule+"");
}
function createChildAccount(module,entityid,entityname,anchor)
{
    
        document.viewentityform.action="/crm/Create.do?module="+module+"&accountid="+entityid+"&entityid="+entityid+"&entityname="+entityname+"&accountname="+ entityname+ "&relmodule=Accounts&returnAnchor="+anchor+"&primmodule=Accounts";
        document.viewentityform.submit();
   
    /*
	var url="/crm/Create.do?module="+module+"&accountid="+entityid+"&entityid="+entityid+"&entityname="+entityname+"&accountname="+ entityname+ "&relmodule=Accounts&returnAnchor="+anchor+"&primmodule=Accounts";
	if(module == ("Accounts") )
	{
		if(module=='Quotes' || module=='SalesOrders' || module=='Invoices')
		{
			var url="/crm/FillEntityObject.do?fillUpModule=Accounts&operation=create&module="+module+"&entityid="+entityid+"&entityname="+entityname;
		}
	}
	ajaxNew(url);
    */    
}

function addToPriceBooks(productid)
{
	document.viewentityform.action="/crm/ShowPriceBooksForAdd.do?moduleid="+productid+"&module=PriceBooks";
	document.viewentityform.submit();
}

function addProducts(bookid)
{
      document.viewentityform.action="/crm/ShowPriceBooksForAdd.do?moduleid="+bookid+"&module=Products";
       document.viewentityform.submit();
}


/* function addMultiValue(productid,frommodule,tomodule,anchor)
 {
 	  document.viewentityform.action="/crm/ShowMultiValuesForAdd.do?moduleid="+productid+"&frommodule="+frommodule+"&tomodule="+tomodule+"&returnAnchor=" + anchor;
 	   document.viewentityform.submit();
 }

function editAllValues(moduleid,frommodule,tomodule)
{
      document.viewentityform.action="/crm/ShowMultiValuesForAdd.do?moduleid="+moduleid+"&frommodule="+frommodule+"&tomodule="+tomodule+"&EditAll=true";
       document.viewentityform.submit();
}
*/
function editIterRegReq()
{
    var iterrowcount = getObj('iterregrows').value;
    hide('iterregnew');
    show('iterregsave');
    show('iterregcancel');
        
    for(var i=1;i<= iterrowcount;i++)
    {
        hide('istatusvalue'+i);
        showInLine('istatustext'+i);
        if(getObj('istatusimgyes'+i).style.display=='inline' || getObj('istatusimgyes'+i).style.display=='block')   
      {
            getObj('istatustext'+i).checked=true;
      }
      else
      {
            getObj('istatustext'+i).checked=false;
      }  
    
        hide('icommentsvalue'+i);
        showInLine('icommentstext'+i);
        getObj('icommentstext'+i).value=getObj('icommentsvalue'+i).innerHTML;
    }
    
}
 
function showIterRegReq()
{
    var url = "/crm/SaveRegistrationReq.do";

    var iterrowcount = getObj('iterregrows').value;
    var args="iterrowcount="+ iterrowcount+"&registrationid="+getObj("id").value;
    for(var i=1;i<= iterrowcount;i++)
    {
      args=args+"&ireqiterid"+i+"="+getObj('ireqiterid'+i).innerHTML;    
      args=args+"&istatustext"+i+"="+getObj('istatustext'+i).checked;
      args=args+"&icommentstext"+i+"="+getObj('icommentstext'+i).value;
    }
    
    var httphandle= getHTTPObject();
    showInLine('zohobusy_loadpage_req');
    httphandle.open("POST", url, true);       
    httphandle.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;charset=UTF-8');
    httphandle.onreadystatechange=function()
    {
       if(httphandle.readyState == 4)
       {
		  var str = httphandle.responseText;
		  if(httphandle.status == 200)
          {
              assumeSuccess();  
	      }
          else
          {
             	selectone.getJSAlertValue("crm.alert.error.code",null,"en_US",
																				function(mesg) { alert(mesg + " : "+ httphandle.status) })
          }
        hide('zohobusy_loadpage_req');    
       }
    

    };
    httphandle.send(args);
   
 }

function assumeSuccess()
{
   var iterrowcount = getObj('iterregrows').value;
    show('iterregnew');
    hide('iterregsave'); 
    hide('iterregcancel');   

    for(var i=1;i<= iterrowcount;i++)
    {
       showInLine('icommentsvalue'+i);
       hide('icommentstext'+i)
       getObj('icommentsvalue'+i).innerHTML= getObj('icommentstext'+i).value;        
   
       showInLine('istatusvalue'+i);
       if(getObj('istatustext'+i).checked)
       {
            hide('istatusimgno'+i);   
            show('istatusimgyes'+i);   
       } 
       else
       {
         show('istatusimgno'+i);   
         hide('istatusimgyes'+i);   
       } 
       hide('istatustext'+i);

    }
}
 
function cancelIterRegReq()
{
   var iterrowcount = getObj('iterregrows').value;
    show('iterregnew');
    hide('iterregsave'); 
    hide('iterregcancel');   

    for(var i=1;i<= iterrowcount;i++)
    {
       showInLine('icommentsvalue'+i);
       hide('icommentstext'+i)
       
       showInLine('istatusvalue'+i);
       hide('istatustext'+i);
    }
}  

function editAll(productid)
{
      document.viewentityform.action="/crm/ShowPriceBooksForAdd.do?moduleid="+productid+"&module=PriceBooks&EditAll=true";
       document.viewentityform.submit();
}

function editAllproducts(bookid)
{
      document.viewentityform.action="/crm/ShowPriceBooksForAdd.do?moduleid="+bookid+"&module=Products&EditAll=true";
       document.viewentityform.submit();
}
var PersonalityArray = "";
function setDisplayNone()
{

var module=(getObj("module"))?getObj("module").value:"Home";
if (module == ("Leads"))
   {

	PersonalityArray=new Array('ATTACHMENTSPERSONALITY',
			   'ACTIVITYPERSONALITY', 'ACTIVITYHISTORYPERSONALITY', 'PRODUCTSPERSONALITY','EMAILSPERSONALITY','NOTESPERSONALITY');

   }
   else if (module == ("Accounts"))
   {

		PersonalityArray=new Array('CONTACTSPERSONALITY', 'POTENTIALSPERSONALITY', 'ATTACHMENTSPERSONALITY','NOTESPERSONALITY', 'ACTIVITYPERSONALITY','ACTIVITYHISTORYPERSONALITY', 'PRODUCTSPERSONALITY','SALESORDERSPERSONALITY','QUOTESPERSONALITY','CHILDACCOUNTSPERSONALITY', 'INVOICESPERSONALITY');

   }
   else if (module == ("Contacts"))
   {

		PersonalityArray=new Array('POTENTIALSPERSONALITY','ATTACHMENTSPERSONALITY','NOTESPERSONALITY','ACTIVITYPERSONALITY','ACTIVITYHISTORYPERSONALITY','CASESPERSONALITY','PRODUCTSPERSONALITY','QUOTESPERSONALITY','SALESORDERSPERSONALITY','PURCHASEORDERSPERSONALITY','EMAILSPERSONALITY');

   }
   else if (module == ("Potentials"))
   {

			PersonalityArray=new Array('ATTACHMENTSPERSONALITY','NOTESPERSONALITY','POTSTAGEHISTPERSONALITY','CONTACTSROLESPERSONALITY','ACTIVITYPERSONALITY','ACTIVITYHISTORYPERSONALITY','COMPETITORSPERSONALITY','PRODUCTSPERSONALITY','QUOTESPERSONALITY','SALESORDERSPERSONALITY');

    } 
    else if (module == ("Campaigns"))
    {

		PersonalityArray=new Array('ATTACHMENTSPERSONALITY','LEADSPERSONALITY','POTENTIALSPERSONALITY','ACTIVITYPERSONALITY', 'ACTIVITYHISTORYPERSONALITY');
        
    }
    else if (module == ("Products"))
    {     
               
		PersonalityArray=new Array('PRICEBOOKSPERSONALITY','ACTIVITYPERSONALITY','ACTIVITYHISTORYPERSONALITY','ATTACHMENTSPERSONALITY','CASESPERSONALITY','SOLUTIONSPERSONALITY','CONTACTSPERSONALITY','LEADSPERSONALITY','POTENTIALSPERSONALITY','ACCOUNTSPERSONALITY' );

    }
    else if (module == ("PriceBooks"))
    {     
		
            PersonalityArray=new Array('PRODUCTSPERSONALITY','ATTACHMENTSPERSONALITY');

    }
    else if (module == ("Vendors"))
    {

            PersonalityArray=new Array('PRODUCTSPERSONALITY','PURCHASEORDERSPERSONALITY','CONTACTSPERSONALITY',
					'ACTIVITYPERSONALITY','ACTIVITYHISTORYPERSONALITY','ATTACHMENTSPERSONALITY');

    }
	
    else if (module == ("Cases"))
    {

                PersonalityArray=new Array('ATTACHMENTSPERSONALITY','ACTIVITYPERSONALITY', 'ACTIVITYHISTORYPERSONALITY');

    }
    else if (module == ("Solutions"))
    {

                PersonalityArray=new Array('ATTACHMENTSPERSONALITY');

    }
    else if (module == ("Quotes"))
    {

                PersonalityArray=new Array('ATTACHMENTSPERSONALITY','ACTIVITYPERSONALITY', 'ACTIVITYHISTORYPERSONALITY','SALESORDERSPERSONALITY');

    }
    else if (module == ("SalesOrders"))
    {

                PersonalityArray=new Array('ATTACHMENTSPERSONALITY','ACTIVITYPERSONALITY','ACTIVITYHISTORYPERSONALITY','INVOICESPERSONALITY');

    }
    else if (module == ("Invoices"))
    {

                PersonalityArray=new Array('ATTACHMENTSPERSONALITY','ACTIVITYPERSONALITY','ACTIVITYHISTORYPERSONALITY');

    }
  else if (module == ("Registrations"))
    {

                PersonalityArray=new Array('ATTACHMENTSPERSONALITY','ACTIVITYPERSONALITY','ACTIVITYHISTORYPERSONALITY');

    }
    else if (module == ("PurchaseOrders"))
    {

                PersonalityArray=new Array('ATTACHMENTSPERSONALITY','ACTIVITYPERSONALITY','ACTIVITYHISTORYPERSONALITY');

    }
else if (module == ("Iterations"))
{

		PersonalityArray=new Array('ATTACHMENTSPERSONALITY','ACTIVITYPERSONALITY','ACTIVITYHISTORYPERSONALITY','REGISTRATIONSPERSONALITY','TEAMSPERSONALITY','PRICINGSPERSONALITY','LIFECYCLESPERSONALITY','CASESPERSONALITY');


}


    if(getObj('liststr1')!=undefined)
    {
      var liststr= getObj('liststr1').innerHTML;
        if(liststr ==undefined)// check done for IE
        {  
            PersonalityArray=getObj('liststr1')[0].innerHTML.split(",");
        }
        else
        { 
           PersonalityArray=liststr.split(",");
        }
    }


}

function setDisplayNone_new()
{
    var module=(getObj("module"))?getObj("module").value:"Home";
    if(getObj('liststr1')!=undefined)
    {
      var liststr= getObj('liststr1').innerHTML;
        if(liststr ==undefined)// check done for IE
        {  
            PersonalityArray=getObj('liststr1')[0].innerHTML.split(",");
        }
        else
        { 
           PersonalityArray=liststr.split(",");
        }
    }
}

function setDisplayNone1()
{
	var module=(getObj("module"))?getObj("module").value:"Home";

	if (module == ("Leads"))
	{

		PersonalityArray=new Array('ATTACHMENTSPERSONALITY','ACTIVITYPERSONALITY', 'ACTIVITYHISTORYPERSONALITY', 'PRODUCTSPERSONALITY','EMAILSPERSONALITY','NOTESPERSONALITY');
	}
	else if (module == ("Accounts"))
	{
		PersonalityArray=new Array('CONTACTSPERSONALITY',
			   'POTENTIALSPERSONALITY',
			   'ATTACHMENTSPERSONALITY',
			   'NOTESPERSONALITY',
			   'ACTIVITYPERSONALITY','ACTIVITYHISTORYPERSONALITY', 'PRODUCTSPERSONALITY',
                                   'SALESORDERSPERSONALITY','QUOTESPERSONALITY','CHILDACCOUNTSPERSONALITY',
			   'INVOICESPERSONALITY');
	}
	else if (module == ("Contacts"))
	{
		PersonalityArray=new Array('POTENTIALSPERSONALITY',
			   'ATTACHMENTSPERSONALITY',
			   'NOTESPERSONALITY',
			   'ACTIVITYPERSONALITY','ACTIVITYHISTORYPERSONALITY',
			   'CASESPERSONALITY','PRODUCTSPERSONALITY','QUOTESPERSONALITY',
			   'SALESORDERSPERSONALITY','PURCHASEORDERSPERSONALITY','EMAILSPERSONALITY');
	}
	else if (module == ("Potentials"))
	{
		PersonalityArray=new Array('ATTACHMENTSPERSONALITY',
			   'NOTESPERSONALITY',
     			   'POTSTAGEHISTPERSONALITY','CONTACTSROLESPERSONALITY',
			   'ACTIVITYPERSONALITY','ACTIVITYHISTORYPERSONALITY',
			   'COMPETITORSPERSONALITY','PRODUCTSPERSONALITY',
		  	    'QUOTESPERSONALITY','SALESORDERSPERSONALITY');
	}	 
	else if (module == ("Campaigns"))
	{
		PersonalityArray=new Array('ATTACHMENTSPERSONALITY',
			   'LEADSPERSONALITY',
     			   'POTENTIALSPERSONALITY',
			   'ACTIVITYPERSONALITY', 'ACTIVITYHISTORYPERSONALITY');
	}
	else if (module == ("Products"))
	{     
		PersonalityArray=new Array('PRICEBOOKSPERSONALITY','ACTIVITYPERSONALITY','ACTIVITYHISTORYPERSONALITY',
					   'ATTACHMENTSPERSONALITY','CASESPERSONALITY',
					 'SOLUTIONSPERSONALITY','CONTACTSPERSONALITY',
					'LEADSPERSONALITY','POTENTIALSPERSONALITY',
					'ACCOUNTSPERSONALITY' );

	}
	else if (module == ("PriceBooks"))
	{     
         	PersonalityArray=new Array('PRODUCTSPERSONALITY','ATTACHMENTSPERSONALITY');

	}
	else if (module == ("Vendors"))
	{
	 	PersonalityArray=new Array('PRODUCTSPERSONALITY','PURCHASEORDERSPERSONALITY','CONTACTSPERSONALITY',
					'ACTIVITYPERSONALITY','ACTIVITYHISTORYPERSONALITY','ATTACHMENTSPERSONALITY');

	}
	else if (module == ("Cases"))
	{
                PersonalityArray=new Array('ATTACHMENTSPERSONALITY',
                           'ACTIVITYPERSONALITY', 'ACTIVITYHISTORYPERSONALITY');
	}
	else if (module == ("Solutions"))
	{
               PersonalityArray=new Array('ATTACHMENTSPERSONALITY');
	}
	else if (module == ("Quotes"))
	{
               PersonalityArray=new Array('ATTACHMENTSPERSONALITY','ACTIVITYPERSONALITY', 'ACTIVITYHISTORYPERSONALITY','SALESORDERSPERSONALITY');
	}
	else if (module == ("SalesOrders"))
	{
               PersonalityArray=new Array('ATTACHMENTSPERSONALITY','ACTIVITYPERSONALITY','ACTIVITYHISTORYPERSONALITY','INVOICESPERSONALITY');
	}
	else if (module == ("Invoices"))
	{
               PersonalityArray=new Array('ATTACHMENTSPERSONALITY','ACTIVITYPERSONALITY','ACTIVITYHISTORYPERSONALITY');
	}
	else if (module == ("PurchaseOrders"))
	{
               PersonalityArray=new Array('ATTACHMENTSPERSONALITY','ACTIVITYPERSONALITY','ACTIVITYHISTORYPERSONALITY');
	}

   	/*if(!(module=="Tasks" || module=="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 displayLocateMapMenu(module)
{
	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")
	{
		mapParameter = getObj("value_Street").innerHTML+' '+getObj("value_City").innerHTML+' '+getObj("value_State").innerHTML+' '+getObj("value_Country").innerHTML
		if ( mapParameter.trim() == '' )
		{
			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"
		getObj("dropDownMenu1").style.display="none"
		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"
       	}
}
var pos=0,anchorLeft=0,anchorTop=0,anchorObj;
function showDrillDownPtr(target) 
{
       /*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=false;
	var objAnchor=document.getElementsByTagName("A")
	if(target)
	{
		target = target.substr(target.lastIndexOf("#")+1);
	}
	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;
		getObj("drillDownPtr").style.left= anchorLeft-30;
		//location.href="#"+target;
		new Effect.ScrollTo(target,{duration:1.0})	
		//pos=(parseInt(anchorLeft)>50) ? anchorLeft-50 : pos=0
		//intvl=setInterval("animatePtr()",15)
	}
}

function animatePtr() {
	if (pos<=anchorLeft-22) {
		getObj("drillDownPtr").style.left=pos
		pos++
	} else {
		clearInterval(intvl)
	}
}
function showMail(mid)
{
	showDialog( getObj( mid ).innerHTML, "position=absolute, modal=yes, title=Mail Content, closeOnEscKey=no, top=80, left=250, width=600, height=400 " );
}

function sortViewColumns(columname,targetstring, previous_sort_column )
{
		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 module = getObj("module").value;
		var id = getObj("id").value;
		var url = "/crm/RelatedList.do?id="+id+"&module="+module+"&"+append_sort_column+"="+columname+"&"+append_sort_order+"="+getObj( append_sort_order ).value;
		sortRelatedList(url);
}
function searchMapLocation(addressType)
{
	var mapParameter = '';
	//if(addressType == 'Contact Address' || addressType == 'Other Address' || addressType == 'Primary Address' || addressType == 'Secondary Address')
	{
		var addresstype="value_"+addressType.substring(0,addressType.length-8);
                mapParameter = getObj(addresstype+" Street").innerHTML+' '
                           +getObj(addresstype+" City").innerHTML+' '
                           +getObj(addresstype+" State").innerHTML+' '
                           +getObj(addresstype+" Country").innerHTML
	}
	if ( mapParameter.trim() == '' )
        {
                selectone.getJSAlertValue("crm.alert.not.empty",null,"en_US",
                          function(mesg) { alert(addressType + " " + mesg) })
                return;
        }       
	document.viewentityform.action="http://maps.google.com/maps?q="+mapParameter
	document.viewentityform.target="_blank"
	document.viewentityform.submit()
}

function ajaxTabAction(url)
{
	url = url+"&isload=false";
	ajaxNew(url);
}

function redirectTabAction(url)
{
	document.location.href = url;
}

function tabAction(url,mod)
{
	if(mod != "Home" && mod != "Reports" && mod != "Dashboards" && mod!="Email Templates" && getObj("lftNavDiv") && document.location.href.match("CustomReport.do") != "CustomReport.do")
	{
		ajaxTabAction(url);
	}
	else
	{
		redirectTabAction(url);
	}
	return false;
}

var range = 10;

function doSubmit()
{
	if(document.showcvdetails.searchletter != undefined)
		document.showcvdetails.searchletter.value = "";	
	
	document.showcvdetails.rangeValue.value=getObj("rangeValue").value;
   	document.showcvdetails.action="/crm/ShowSelectedCustomView.do?module="+getObj("module").value;
	document.showcvdetails.method="post";
	document.showcvdetails.submit();
}

function exportAction(obj)
{
 	getObj("exportMenu").style.display="block"
	getObj("exportMenu").style.zIndex = "98";
	getObj("exportMenu").style.top=findPosY(obj)+obj.offsetHeight
      getObj("exportMenu").style.left=findPosX(obj) + obj.offsetWidth - (getObj("exportMenu").offsetWidth+0);
}
function exportSubMenuAction(obj,type)
{
	if(type=="all")
	{
		if(getObj("exportSubMenu"))
		{
			document.getElementById("exportSubMenu").style.display="none"
		}
		var submenu = document.getElementById("exportAllSubMenu");
		submenu.style.display="block"
		submenu.style.zIndex = "90";
		submenu.style.top=findPosY(obj);
		submenu.style.left=findPosX(obj) - submenu.offsetWidth;
	}
	else
	{
		if(getObj("exportAllSubMenu"))
		{
			document.getElementById("exportAllSubMenu").style.display="none"
		}
		var submenu = document.getElementById("exportSubMenu")
		submenu.style.display="block"
		submenu.style.zIndex = "98";
		submenu.style.top=findPosY(obj);
		submenu.style.left=findPosX(obj) - submenu.offsetWidth;
	}
}
function showDropDownMenu(button, divId)
{
	getObj(divId).style.display="block"
	getObj(divId).style.zIndex = "98";
	getObj(divId).style.top=findPosY(button) + button.offsetHeight
    getObj(divId).style.left=findPosX(button) ;
}
function viewActions(obj)
{
	showDropDownMenu(obj, "viewMenuAction");
}
function viewMessageActions(obj)
{
	showDropDownMenu(obj, "viewSendMessageAction");
}
function showOtherInttooltip(obj,Lay)
{
	var tagName = document.getElementById(Lay);
    var leftSide = findPosX(obj);
    var topSide = findPosY(obj);
    var maxW = tagName.style.width;
    var widthM = maxW.substring(0,maxW.length-2);
    var getVal = eval(leftSide) + eval(widthM);
    if(getVal  > document.body.clientWidth ){
        leftSide = eval(leftSide) - eval(widthM);
        tagName.style.left = leftSide+ 'px';
    }
    else
        tagName.style.left= leftSide+ 'px';
    tagName.style.top= topSide + 20 +'px';
    if(tagName.style.display == 'block')
    {
    	tagName.style.display = 'None';
    }
    else
    {
    	tagName.style.display = 'block';
    }
}

// function used to show Listview description tooltip
function showtooltip(obj,Lay)
{
	 var tagName = document.getElementById(Lay);
    var leftSide = findPosX(obj);
    var topSide = findPosY(obj);
    var maxW = tagName.style.width;
    var widthM = maxW.substring(0,maxW.length-2);
    var getVal = eval(leftSide) + eval(widthM);
    if(getVal  > document.body.clientWidth ){
        leftSide = eval(leftSide) - eval(widthM);
        tagName.style.left = leftSide+ 'px';
    }
    else
        tagName.style.left= leftSide+ 'px';
    tagName.style.top= topSide + 20 +'px';
    if(tagName.style.display == 'block')
    {
    	tagName.style.display = 'None';
    }
    else
    {
    	tagName.style.display = 'block';
    }
}
// function used to hide listview description tooltip
function hidetooltip(divId)
{
 var id = document.getElementById(divId);

    id.style.display = 'none';
}
function showAll()
{
	loadAjaxTab4("Loading....");
        if(document.getElementById("advSearchEnable")){
            var advSearchEnableVal = document.getElementById("advSearchEnable").value;
        }
	document.showcvdetails.searchletter.value = "";
	if(getObj("currentOption"))
	{	
	getObj("rangeValue").value = getObj("currentOption").value;
	}
	document.showcvdetails.rangeValue.value=getObj("rangeValue").value;
	var formData = formData2QueryString(document.showcvdetails);
	var module=document.getElementById("module").value
	var url = "/crm/ShowSelectedCustomView.do?module="+module+"&isload=false";
	new Ajax.Updater('show',url,{method:"post",onComplete:function(){
	var from =getObj("fromindex").value;
	var to =getObj("toindex").value;
	getObj("currentOption").value="10";
	if(from!=null && to!=null)
	{
        getObj("rangeValue").value = (to-from)+1;
	getObj("currentOption").value=(to-from)+1;
	}
	
	document.getElementById('ajax_load_tab').style.display="none";
        if( advSearchEnableVal=="true"){      
            callAdvSearch(module)
        }
	},asynchronous:true,postBody:formData});
}

function alphaSearch(alphabet)
{
	loadAjaxTab4("Loading....");
        if(document.getElementById("advSearchEnable")){
            var advSearchEnableVal = document.getElementById("advSearchEnable").value;
        }
	document.showcvdetails.searchletter.value = alphabet;
	document.showcvdetails.searchString.value = "";
	if(getObj("currentOption"))
	{	
	getObj("rangeValue").value = getObj("currentOption").value;
	}
	var formData = formData2QueryString(document.showcvdetails);
	var module=document.getElementById("module").value;
	if ( module == "Iterations" )
	{
		module = "Programs" ;
	}
	var url = "/crm/ShowSelectedCustomView.do?module="+module+"&isload=false";
	new Ajax.Updater('show',url,{method:"post",onComplete:function(){
	
	document.getElementById('ajax_load_tab').style.display="none";
        if( advSearchEnableVal=="true"){      
            callAdvSearch(module)
        }
	},asynchronous:true,postBody:formData});
}



function sortColumnsIW_old(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 location_href = document.location.href;
		var urldetails=location_href.split('/');
        parentId =getObj("entityId").value;

		location_href=urldetails[0]+"//"+urldetails[2]+"/crm/ShowEntityInfo.do?id="+parentId+"&module="+module+"&isload=true";
		document.viewentityform.action=location_href+"#"+targetstring;
                document.viewentityform.submit();
}

function oldsortColumns(columname)
{
		if (columname == "Last Name")
		{
			document.showcvdetails.sortColumnString.value = "First Name";
			columname = "First Name";
		}
		else
			document.showcvdetails.sortColumnString.value = columname;
		if (columname == 'getObj("previous_sort_column")' )
		{
			if (document.showcvdetails.sortOrderString.value == "sort_asc")
				document.showcvdetails.sortOrderString.value = "sort_desc";
			else
				document.showcvdetails.sortOrderString.value = "sort_asc";
		}
		else
			document.showcvdetails.sortOrderString.value = "sort_asc";
		document.showcvdetails.action="/crm/ShowSelectedCustomView.do?module="+getObj("module").value;
		document.showcvdetails.method="post";
                document.showcvdetails.submit();
}
function setCVName(obj,id,search,changeSearchLetter)
{
	var module=document.getElementById("module").value
	if( module == "Iterations" )
	{
		module = "Programs" ;
	}
	document.getElementById("tagsearch").value=trimBoth(document.getElementById("tagsearch").value);
    loadAjaxTab4("Loading...");
    document.showcvdetails.sortColumnString.value=null;
    if(document.getElementById("advSearchEnable")){
        var advSearchEnableVal = document.getElementById("advSearchEnable").value;
    }    

	document.showcvdetails.previousCVID.value=document.showcvdetails.display_cust_view_name.value
	if(getObj("currentOption"))
	{	
	getObj("rangeValue").value = getObj("currentOption").value;
	}

	if (document.all)
	{
		document.showcvdetails.display_cust_view_name.value=obj.options[id].text;
	}
	else if (document.layers)
	{
		document.showcvdetails.display_cust_view_name.value=obj.options[id].innerText;
	}
	else if (document.getElementById)
	{
		document.showcvdetails.display_cust_view_name.value=obj.options[id].text;	
	}
      	if(document.showcvdetails.searchletter != undefined && changeSearchLetter!="true")
		document.showcvdetails.searchletter.value="";
		if(search==null)
		{
			document.showcvdetails.searchString.value="";
		}
	var formData = formData2QueryString(document.showcvdetails);
	var url = "/crm/ShowSelectedCustomView.do?module="+module+"&isload=false";
	new Ajax.Updater('show',url,{method:"post",onComplete:function(){
        
        
	document.getElementById('ajax_load_tab').style.display="none";
        /*{
            var httpobj = getHTTPObject();
		    httpobj.open("POST", "/crm/ShowSelectedCustomViewEnd.do?module="+getObj("module").value, false);                             
		     httpobj.send("module="+getObj("module").value);
             document.getElementById('listview_addinfo').innerHTML="";
             document.getElementById('listview_addinfo').innerHTML=httpobj.responseText;
        }*/
        if( advSearchEnableVal=="true"){      
            callAdvSearch(module)
        }
	var from =getObj("fromindex").value;
	var to =getObj("toindex").value;
	getObj("currentOption").value="10";
	if(from!=null && to!=null && (to-from)>10)
	{
        getObj("rangeValue").value = (to-from)+1;
	getObj("currentOption").value=(to-from)+1;
	}


        
	},asynchronous:true,postBody:formData});

 
}
function selectAll()
{
	if (document.showcvdetails.chk != undefined)
	{

		noofentries = document.showcvdetails.chk.length;
		checkstatus = document.showcvdetails.allcheck.checked;
		if(noofentries == undefined)
		{
			document.showcvdetails.chk.checked = checkstatus;
		}

		for(i=0 ; i < noofentries ; i++)
		{
			document.showcvdetails.chk[i].checked = checkstatus;
		}
	}
}
function toggleCheckBox(state)
{
	noofentries = document.showcvdetails.chk.length;
	if (state==false)
	{
		document.showcvdetails.allcheck.checked=false
	}
	else
	{
		if (noofentries != undefined)
		{
			var unCheckedRecFound=false
			for (i=0 ; i < noofentries ; i++)
        	{
				if (document.showcvdetails.chk[i].checked == false)
				{
					document.showcvdetails.allcheck.checked=false
					unCheckedRecFound=true
					break;
				}
			}
			
			if (unCheckedRecFound==false)
				document.showcvdetails.allcheck.checked=true
		}
	}
} 
function deleteCustomView()
{
	if(window.confirm("Are you sure?"))
	{	
	        document.showcvdetails.action="/crm/DeleteCustomView.do";
		document.showcvdetails.method="post";
	        document.showcvdetails.submit();
	}
}
function editCustomView(custId,display_view_name)
{
	
        document.showcvdetails.action="/crm/EditCustomView.do?custId="+custId+"&display_view_name="+display_view_name;
	document.showcvdetails.method="post";
        document.showcvdetails.submit();
}

function deleteEntity(module,id,customviewname)
{
	if(deleteEvent())
	{
	document.showcvdetails.action="/crm/MassDelete.do?module="+module+"&id="+id+"&customviewname="+customviewname;
	document.showcvdetails.method="post";
	document.showcvdetails.submit();
	}

}

/*function getNoOfSelected()
{
        noofrows = document.showcvdetails.chk.length;
        noofselected = 0
        for(i=0 ; i < noofrows ; i++)
        {
                if (document.showcvdetails.chk[i].checked)
                        noofselected ++;
        }
        return noofselected;
}
*/
/*function createAction()
{
	var module = getObj("module").value;
	ajaxNew("/crm/Create.do?module="+module);
}
*/
/*function massAction(type,actionurl,parameter,module,cvname,cvid,start_index,end_index)
{
	noofrows = document.showcvdetails.chk.length;
	var append_ids = "";
	var moduleStr = document.showcvdetails.module.value;
	if (noofrows == undefined )
	{
		if (document.showcvdetails.chk.checked)	
		{
			append_ids = document.showcvdetails.chk.value;
			document.showcvdetails.idlist.value=append_ids
			document.showcvdetails.action="/crm/"+actionurl+".do?module="+getObj("module").value+parameter;		
			if (type == "massdelete")
			{
				if(moduleStr=="Forecasts")
				{
					if(confirm('<fmt:message key="crm.label.confirm.forecast"/>'))
					{
						document.showcvdetails.method="post";
						document.showcvdetails.submit();
					}
					else
					{
						return false
					}					
				}
				else
				{
                    			Callonclickofbutton2('/crm/DeleteFromCV.do',module,document.showcvdetails.idlist.value,cvname,cvid,start_index,end_index);
                                  
                    			return false;
				}
			}
			else if(type=="bulktask")
			{
				var url = "/crm/"+actionurl+".do?secmod="+getObj("module").value+"&module=Tasks"+parameter+"&idlist="+escape(getObj("idlist").value);
				ajaxNew(url);

			}

			else 
			{
				document.showcvdetails.method="post";		
				document.showcvdetails.submit();
			}
		}
		else 
		{
     	selectone.getJSAlertValue("crm.alert.select.one",null,"en_US",
																function(mesg){ alert(mesg) })
			return false;	
		}
	}
	else if (noofrows != 0)
	{
		if (getNoOfSelected() == 0)
		{
			selectone.getJSAlertValue("crm.alert.select.one",null,"en_US",
																 function(mesg){ alert(mesg) })
			return false;	
		}	
		else 
		{	
			for(i = 0 ; i < noofrows ; i++)
			{
				if (document.showcvdetails.chk[i].checked)
					append_ids= document.showcvdetails.chk[i].value+";"+append_ids;
			}               
			document.showcvdetails.idlist.value=append_ids
			document.showcvdetails.action="/crm/"+actionurl+".do?module="+getObj("module").value+parameter;
                        if(type=="bulktask")
                        {
				var url ="/crm/"+actionurl+".do?secmod="+getObj("module").value+"&module=Tasks"+parameter+"&idlist="+escape(getObj("idlist").value);
				ajaxNew(url);
				return false;
                        }
			else if (type == "massdelete")
			{
				if(moduleStr=="Forecasts")
				{
					if(confirm('<fmt:message key="crm.label.confirm.forecast"/>'))
					{
						document.showcvdetails.method="post";
						document.showcvdetails.submit();
                        
					}
					else
					{
						return false
					}					
				}
				else
				{
                    			Callonclickofbutton2('/crm/DeleteFromCV.do',getObj("module").value,document.showcvdetails.idlist.value,cvname,cvid,start_index,end_index);
                                  
                    			return false;
				}
			}
			else 
			{
					document.showcvdetails.method="post";
					document.showcvdetails.submit();
			}
		}
	}
        else
        {
		return false;
        }
}
*/
function showAttachment(window)
{
	var hh = window.document.getElementById("ATTACHMENTSPERSONALITY");
	if(!hh)
	{
	}
	else
	{
		document.getElementById("ATTACHMENTSPERSONALITY").innerHTML = hh.innerHTML;
		closeDialog();
	}
}
function showFileAttach()
{
	if(http)
	{
		var module = getObj("module").value;
		var id = getObj("id").value;
		var args = "module="+module+"&id="+id;
		var url = "/crm/jsp/FileAttach.jsp";
		http.open("POST", url, true);
		http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;charset=UTF-8');
  		http.onreadystatechange = function() 
		{
			if(http.readyState == 4)
			{
				var item = http.responseText;
				showDialog( item, "position=absolute, modal=yes, title=File Attachment, closeOnEscKey=no,top=200,left=300,width=400, height=250 " );
			}
		}
		http.send(args);	
	}
	return false;	
}
function sortRelatedList(url)
{
	if(http)
	{
		var args = "";
		http.open("POST", url, true);
		http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;charset=UTF-8');
  		http.onreadystatechange = function() 
		{
			if(http.readyState == 4)
			{
				var item = http.responseText;
				getObj("relatedPageContent").innerHTML = "";
				getObj("relatedPageContent").innerHTML = item;
				setDisplayNone();
			}
		}
		http.send(args);	
	}
}
function navigateRelatedList(url,module,id)
{
        var formData = formData2QueryString(document.viewentityform);
	loadAjaxTab2('','lightblue');
	new Ajax.Request(url,{method:"post",onSuccess:function(t)
       {
		document.getElementById('relatedList').innerHTML=t.responseText;
		toggleRelatedList(id,module);
		 document.getElementById('ajax_load_tab').style.display='none';
       },asynchronous:true,postBody:formData
       });
}
function submitForm(navigform,action)
{
	var module=document.getElementById("module").value
   	loadAjaxTab2('','lightblue');
        if(document.getElementById("advSearchEnable")){
            var advSearchEnableVal = document.getElementById("advSearchEnable").value;
        }
   	navigform=document.showcvdetails;
   	navigform.OnSelect.value="true";
	getObj("rangeValue").value = getObj("currentOption").value;
	var formData = formData2QueryString(navigform);
	var url ="/crm/NavigateByRecords.do?isload=false";
	if(action == "next")
	{
		url = url+"&next.x=true";
	}
	else if(action == "previous")
	{
		url = url+"&previous.x=true";
	}
	new Ajax.Request(url,{method:"post",onSuccess:function(t)
       {
		 document.getElementById("show").innerHTML=t.responseText;
		 document.getElementById('ajax_load_tab').style.display='none';
                  if( advSearchEnableVal=="true"){      
                    callAdvSearch(module)
                }
       },asynchronous:true,postBody:formData
       });
}


function navigateTOCV(module,cvid,dcvname,sortcolumn,rownum)
{
    alert("in navigateTOCV-->"+ module + " : " + cvid+" " + dcvname+" "+ sortcolumn+" "+ rownum);

    document.viewentityform.fileName.value='/ShowSelectedCustomView.do?navig=true&mod=true&module='+module+'&display_cust_view_name='+ dcvname + '&cvid='+ cvid+'&sortColumnString='+ sortcolumn+'&sortOrderString=sort_asc';
    alert(document.viewentityform.fileName.value);
    document.viewentityform.fromIndex.value="131";
    document.viewentityform.toIndex.value="140";

 var action="next";
	var url ="/crm/NavigateByRecords.do?isload=true";
	if(action == "next")
	{
		url = url+"&next.x=true";
	}
	else if(action == "previous")
	{
		url = url+"&previous.x=true";
	}
    document.viewentityform.action=url;
    document.viewentityform.submit();

}

function previewSubmitForm(navigform,action)
{
loadAjaxTab4("Loading...");
	navigform.OnSelect.value="true";
	getObj("rangeValue").value = getObj("currentOption").value;
	var formData = formData2QueryString(navigform);
	var url ="/crm/NavigateByRecords.do?ajax=true";
	if(action == "next")
	{
		url = url+"&next.x=true";
	}
	else if(action == "previous")
	{
		url = url+"&previous.x=true";
	}
	if(navigform.name == "ProductLookUpForm")
	{
		document.getElementById('previewQuery').innerHTML="";
		new Ajax.Request(url,{method:"post",onComplete:function(t){
		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});
	}
	else
	{
		navigform.action=url;
		navigform.submit();	
	}

	//ajaxNew(url);
	return false;	
}

/*function submitForm(navigform,action)
{
	navigform.OnSelect.value="true";
	getObj("rangeValue").value = getObj("currentOption").value;
	var formData = formData2QueryString(navigform);
	var url ="/crm/NavigateByRecords.do?ajax=true"+formData;
	if(action == "next")
	{
		url = url+"&next.x=true";
	}
	else if(action == "previous")
	{
		url = url+"&previous.x=true";
	}
	ajaxNew(url);
	return false;	
}*/
function replace(string,text,by)
{
   	// Replaces text with by in string
   	var strLength = string.length, txtLength = text.length;
   	if ((strLength == 0) || (txtLength == 0)) return string;
   	var i = string.indexOf(text);
	if ((!i) && (text != string.substring(0,txtLength))) return string;
   	if (i == -1) return string;
   	var newstr = string.substring(0,i) + by;
   	if (i+txtLength < strLength)
       		newstr += replace(string.substring(i+txtLength,strLength),text,by);

   	return newstr;
} 

//-- integration from zohocrm

function casePgmInterestChk()
{
    var id="";   
    var noofrows = document.createEntityForm.pgmcount.value;    
    for(var i=1;i<=noofrows;i++)
    {
                    if (getObj("pgmckbox_"+i).checked)
                      {   
                            if(id == "")
                            {                           
                                    id=getObj("pgmckbox_"+i).value+":"+getObj("noOfBrochur_"+i).value;
                                    
                            }	
                            else
                            {
                                    id =id+":&&:"+getObj("pgmckbox_"+i).value+":"+getObj("noOfBrochur_"+i).value;
                            }
                        
                      }                     
                      document.createEntityForm.pgmboxvalues.value=id;                    
    }
    
}
function caseGeneralInterestChk()
{
   var id="";
   var parentCol = document.createEntityForm.parentcount.value;    
   for(var p=1 ; p <= parentCol ; p++)
    {       
        var childCol =getObj("subcount_"+p).value       
        for(var j=1;j<=childCol;j++)
        {
                      if (getObj("columnckbox_"+p+j).checked)
                      {                          
                            if(id == "")
                            {                           
                                    id=getObj("columnckbox_"+p+j).value+ ":"+getObj("noOfBrochur_"+p+j).value;
                            }	
                            else
                            {
                                    id =id+":&&:"+getObj("columnckbox_"+p+j).value+":"+getObj("noOfBrochur_"+p+j).value;
                            }
                        
                      }                     
                      document.createEntityForm.columnckboxvalues.value=id;
        }
    }
    
}


/*function clearProgram()
{
getObj("property(Program Name)").value = "" ;
//getObj(" property(programs:Program Name)").value = "" ;
return false;
}
*/
function cancel()
{
	document.createEntityForm.action="/crm/ShowDetails.do?tabGroup=Marketing&module=Campaigns";
	document.createEntityForm.submit();
}

/* function clearItrn()
 {
	if(getObj("property(module)").value!="Iterations")
	getObj("property(Iteration Name)").value = "" ;
        //getObj(" property(iterations:Iteration Name)").value = "" ;
        return false;
 }
*/
function setDependentfielddep(obj ,secId,moduleVal,s,isload)
{
	var name = obj.name;
	var val = "";
	if(getObj("field"+name))
	{
		val = getObj("field"+name).value;
	}
	if(val != null && val != "" && val != "null")
	{
		var fields = val.split("&&&");
		for(var i=0;i<fields.length;i++)
		{	
			var isDependent = false;
			var arr = fields[i].split("|||");
			var label = arr[0];
			var values = arr[1].split(":::");
			if(label.indexOf(")")> -1)
			{
				label = label.replace(/\)/g,"_____");
			}
			if(label.indexOf("(") > -1)
			{
				label = label.replace(/\(/g,"____");
			}
			if(label.indexOf(".")> -1)
			{
				label = label.replace(/\./g,"___");
			}
			var depObj = "";
			if(!secId)
			{				
				depObj = getObj(moduleVal+"_"+label+"___"+s);
			}
			else 
			{				
				depObj = getObj(moduleVal+"_"+label+"_"+secId+"___"+s);
			}
			if(depObj)
			{
					var mapValues = "";
					for (var n=depObj.options.length-1; n >= 0;n--) 
					{	
					 if (depObj.options[n].selected)
					 {	
						if(mapValues == "")
						{
							mapValues = depObj.options[n].value;
						}
						else
						{
							mapValues = mapValues + ";;;"+depObj.options[n].value;
						}
					  } 
				    }
				depObj.value = "";
				var selectValues = "";
				if(secId)
				{
				selectValues = getObj("selectValue"+moduleVal+"_"+label+"_"+secId+"___"+s).value;
				}
				else
				{
					selectValues = getObj("selectValue"+moduleVal+"_"+label+"___"+s).value;
				}
				for(var k=0;k<values.length;k++)
				{
					var list = values[k].split("===");
					var rat = list[0];
					if(rat == "-None-")
					{
						rat = "";
					}
					if(rat == obj.value)
					{
						isDependent = true;
						depObj.length = 0;
						var depvalues = list[1].split(";;;");
						for(var j=depvalues.length-1;j>=0;j--)
						{
							var optionElement = document.createElement("OPTION");
							if(depvalues[j] == "-None-")
							{
								optionElement.value == "";
							}
							else
							{	
								optionElement.value = depvalues[j];
							}
							optionElement.text = depvalues[j];
							if(mapValues != undefined)
							{
								var mapValue = mapValues.split(";;;");
								for(var p=0;p<mapValue.length;p++)
								{
									if(depvalues[j] == mapValue[p])
									{
										optionElement.selected = true;
									}	
								}
							}	
							optionElement.selected = true;
							depObj.options.add(optionElement);
						}	
					}
				  }
							}
			else
  			{
  				continue;
  			}
			if(!isDependent)
			{
				var getValues = selectValues.split(";");
				depObj.length = 0;
				for(var j=0;j<getValues.length;j++)
				{
					var optionElement = document.createElement("OPTION");
					if(getValues[j] == "-None-")
					{
						optionElement.value = "";
					}
					else
					{
						optionElement.value = getValues[j];
					}
					optionElement.text = getValues[j];
					depObj.options.add(optionElement);
				}
			
			}
			if(!isload)
			{
				setDependentfielddep(depObj,secId,moduleVal,s,false);	
			}
			
		}
	}	
	
}	

function setDependent(obj ,isload)
{
	var name = obj.name;
	var val = "";
	var module=getObj("property(module)").value;
	if(getObj("field"+name))
	{
		val = getObj("field"+name).value;
	}
	if(val != null && val != "" && val != "null")
	{
		var fields = val.split("&&&");
		for(var i=0;i<fields.length;i++)
		{	
			var isDependent = false;
			var arr = fields[i].split("|||");
			var label = arr[0];
			var values = arr[1].split(":::");
			if(label.indexOf(")")> -1)
			{
				label = label.replace(/\)/g,"_____");
			}
			if(label.indexOf("(") > -1)
			{
				label = label.replace(/\(/g,"____");
			}
			if(label.indexOf(".")> -1)
			{
				label = label.replace(/\./g,"___");
			}
			var depObj = getObj("property("+label+")");
			if(depObj)
			{
				if(getObj(label))
				{
					var count = getObj(label).value;
					if(count != undefined || count != null)
					{
						depObj = getObj("comboValue"+count);
					}
				}
				var mapValues = "";
				for (var n=depObj.options.length-1; n >= 0;n--) {	
					if (depObj.options[n].selected)
					{	
						if(mapValues == "")
						{
							mapValues = depObj.options[n].value;
						}
						else
						{
							mapValues = mapValues + ";;;"+depObj.options[n].value;
						}
					} 
				}
				depObj.value = "";
				var selectValues = getObj("selectValue"+label).value;
				for(var k=0;k<values.length;k++)
				{
					var list = values[k].split("===");
					var rat = list[0];
					// Not sure what this does but it was preventing dependency fields with -None- selected from having their dependent
					// fields set properly. TODO:
					if(rat == "-None-")
					{
						rat = "";
					}
					// In some cases obj.value will be "" or "-None-" so "" and "-None-" are considered the same.
					if(rat == ((obj.value == "-None-") ? "" : obj.value) || (rat=="Participant" && obj.value=="{0}"))
					{
						isDependent = true;
						depObj.length = 0;
						var depvalues = list[1].split(";;;");
						for(var j=depvalues.length-1;j>=0;j--)
						{
							var optionElement = document.createElement("OPTION");
							if(depvalues[j] == "-None-")
							{
								optionElement.text = "";
								optionElement.value == "";
							}
							else
							{	
								optionElement.text = depvalues[j];
								optionElement.value = depvalues[j];
							}
							if(mapValues != undefined)
							{
								var mapValue = mapValues.split(";;;");
								for(var p=0;p<mapValue.length;p++)
								{
									if(depvalues[j] == mapValue[p])
									{
										optionElement.selected = true;
									}	
								}
							}	
							depObj.options.add(optionElement);
						}	
					}
				}
				if(!isDependent)
				{
					var getValues = selectValues.split(";");
					depObj.length = 0;
					for(var j=0;j<getValues.length;j++)
					{
						var optionElement = document.createElement("OPTION");
						if(getValues[j] == "-None-")
						{
							optionElement.text = "";
							optionElement.value = "";
						}
						else
						{
							optionElement.text = getValues[j];
							optionElement.value = getValues[j];
						}
						depObj.options.add(optionElement);
					}
				
				}
				if(!isload)
				{
					setDependent(depObj,false);	
				}
			}
		}
	}	
	if(module=='Campaigns' && getObj('property(Channel)')!=null && getObj('property(Channel)').value =='Email' )
	{
		getObj("property(Status)").value="Planned";
		getObj("property(Status)").disabled=true;
		getObj("property(Type)").disabled=true;
		getObj("property(Channel)").disabled=true;
	}	
	else if(module=='Campaigns' && getObj('property(Status)')!=null && getObj('property(Status)').value =='Completed')	
	{
		getObj("property(Channel)").disabled=true;
		getObj("property(Type)").disabled=true;
	}
	else if(module=='Campaigns')
	{
		getObj("property(Channel)").disabled=false;
		getObj("property(Type)").disabled=false;
	}
}	

function setDependent1(obj,isload )
{
    //alert('setDependent');
	var isDependent = false;
	var name = obj.name;
        var val = "";
        /*
	if(name == "property(Lifecycle Stage)")
	{            
            getObj("property(Source Group)").selectedIndex = 0
            setDependent(getObj("property(Source Group)") ) ;
	}
	*/
	
	if(( getObj("property(module)").value ) == "Segments" && name == "property(Type)")
	{            
            var img = getObj("property(Type)").value; 
           
            if(img =="Static" )
            {              
                getObj("SegmentContListView").style.display = "block";
                getObj("SegmentQryBuilder").style.display = "none";               
            }
            if(img =="Dynamic" )
            {
                getObj("SegmentQryBuilder").style.display = "block";
                getObj("SegmentContListView").style.display = "none";               
            }
	}
    if(getObj("field"+name)!=null)
    {
      val=getObj("field"+name).value;
    }
	//var val = getObj("field"+name).value;
if(val != null && val != "" && val != "null")
	{
	var fields = val.split(",");
	for(var i=0;i< fields.length;i++)
	{	
		var arr = fields[i].split("|");
		var label = arr[0];
		var values = arr[1].split(":");
		var count = 0;
		var depObj = "";
		var selectValues = "";
		if(getObj(label))
		{	
			count = getObj(label).value;
			depObj = getObj("comboValue"+count);
			selectValues = getObj("selectValue"+count).value;
		}
		else
		{
			depObj = getObj("property("+label+")");
			selectValues = getObj("selectValuefor"+label).value;	
		}	
		for(var k=0;k<values.length;k++)
		{
			var list = values[k].split("=");
			var rat = list[0];
			if(rat == obj.value)
			{
				isDependent = true;
				depObj.length = 0;
				var depvalues = list[1].split(";");
				for(var j=depvalues.length-1;j>=0;j--)
				{
					var optionElement = document.createElement("OPTION");
					optionElement.value = depvalues[j];
					optionElement.text = depvalues[j];
					depObj.options.add(optionElement);
				}	
			}
		}
		if(!isDependent)
		{
			var getValues = selectValues.split(";");
			depObj.length = 0;
			for(var j=0;j<getValues.length;j++)
			{
				var optionElement = document.createElement("OPTION");
				optionElement.value = getValues[j];
				optionElement.text = getValues[j];
				depObj.options.add(optionElement);
			}	
		}
        if(!isload)
		{
			setDependent(depObj,false);	
		}	
	}
}
	
}


function cancelfuncache()
{
     
      	var module=getObj("module").value;
      	var tabGroup=document.getElementById("tabGroup").value;
      	if(module=='Tasks' || module=='Appointments')
      	{
			var url = "/crm/ShowDetails.do?module="+module+"&quickcreate=true&isload=false";
		//ajaxNew(url);
      	}
	else if((getURLParam(window.location.href,"module")=="Contacts") && (getURLParam(window.location.href,"segmentId").length>3))
{
var actiontype=getURLParam(window.location.href,"actiontype");
if(actiontype=="Edit")
{
var url="/crm/Edit.do?module=Segments&id="+(getURLParam(window.location.href,"segmentId"))+"&isload=true&type=save";
}
else if(actiontype=="Clone")
{
var url="/crm/Clone.do?module=Segments&id="+(getURLParam(window.location.href,"segmentId"))+"&cloneId="+(getURLParam(window.location.href,"segmentId"))+"&isload=true&type=save";
}
else
{
var url= "/crm/Create.do?module=Segments&type=insert&segmentId="+(getURLParam(window.location.href,"segmentId"));
}
}
      	else
      	{
		var url = "/crm/ShowDetails.do?tabGroup="+tabGroup+"&module="+module+"&quickcreate=true&isload=true";
		//ajaxNew(url);
      	}
        
	if(module == "Educations" || module=="Experiences" || module == "RelatedAccounts" || module == "Connections" || module == "Recommendations")
	{
		window.history.back();
	}
	else
	{
		document.location.href=url;
	}
}

function cancelfun(module,chkCancelId)
{
      if(module == "Segments")
      {
        if(chkCancelId !=null)
        {      
            document.createEntityForm.action="/crm/IWSegmentCancel.do?chkCancelId="+chkCancelId;
            document.createEntityForm.submit();
        }
        else
        {
	      document.createEntityForm.action="/crm/ShowDetails.do?module="+module+"&quickcreate=true";
	      document.createEntityForm.submit();
        }
       
      }
	 if(module == "Contacts")
      {
        if(chkCancelId !=null)
        {
	window.history.back()      
        }
        else
        {
	      document.createEntityForm.action="/crm/ShowDetails.do?module="+module+"&quickcreate=true";
	      document.createEntityForm.submit();
        }
       
      }

      else if(module=='Tasks' || module=='Appointments')
      {

		  document.createEntityForm.action="/crm/ShowDetails.do?module="+module+"&quickcreate=true";
          document.createEntityForm.submit();
	
      }
      else if(module == "Educations" || module=="Experiences" || module == "RelatedAccounts" || module == "Connections")
	{
		window.history.back();
	}
      else
      {
    	   document.createEntityForm.action="/crm/ShowDetails.do?module="+module+"&quickcreate=true";
	      document.createEntityForm.submit();
      }
}

function validatePercentForSection( sectionFieldsList)
{
	var sectionFields = sectionFieldsList.split("::");

	var totalValue = 0;
	for( i = 0; i< sectionFields.length; i++)
	{
		if(getObj("property("+ sectionFields[i] + ")"))
		{	
			var value = getObj("property("+ sectionFields[i] + ")").value;
			if( value != null && value != "" && value != "null")
			{
				if( value < 0 || value > 100 ) 
				{
					selectone.getJSAlertValue("crm.alert.perc.value.range",null,"en_US",
                          function(mesg) { alert(mesg) })
					return false;
				}
				totalValue = totalValue + parseInt(value) ;
			}
		}	
	}	
	if( totalValue > 100 )
	{
		alert( " Sum of "+ sectionName + " values should be between 0-100 ");
		selectone.getJSAlertValue("crm.alert.section.sum.range",sectionName,"en_US",
                          function(mesg) { alert(mesg) })		
		return false;
	}
	return true;
}


function handlePolicyEdit()
{
 var poption=getObj('poption').value;
 if(poption=="fixed")
 {
     document.createEntityForm.elements['property(Policy Condition Radio)'][1].checked=true;
 }
else
 {
   document.createEntityForm.elements['property(Policy Condition Radio)'][0].checked=true;
 }
var days = getObj('days').value.split(",");
var percvalues=getObj('percvalues').value.split(",");
var fixedvalues=getObj('fixedvalues').value.split(",");

for(var j=0;j<days.length;j++)
     {
         var day = days[j];
         var fixedVal="";
         var percVal="";
         if(poption == "fixed")
         {
             fixedVal = fixedvalues[j];
         }
         else
         {
             percVal = percvalues[j];
         }
         fillPolicyValues(j,day,percVal,fixedVal); 
     }
}

function selectPerformActionNew(operation, module)
{
    return false;
}


function call(sevt)
{
    if (typeof browser_ie != 'undefined')
    {
         sevt=event;
    }

    if(sevt.keyCode==13)
    {
      callTagCloud1();
      return true;
    }
 return true;
}

function callTagCloud1()
{
	var fieldValue = $("txtbox_tagfields") ? $F("txtbox_tagfields") : "";
	if(fieldValue == "" || fieldValue.length == 0)
	{
		return false;
	}

	var test = splCharCheck2(fieldValue)
	if (! test )
	{
		selectone.getJSAlertValue("crm.alert.label.special.characters",null,"en_US",function(mesg){ alert(mesg) })        
		$("txtbox_tagfield").focus();
		return false;
	}
	showInLine('zohobusy_loadpage_vinfo');
 	var moduleId = document.getElementById("id").value; ;
        var module = getObj('module').value;
	var url ="/crm/IWTagCloudAction.do?tagName="+fieldValue+"&moduleId="+moduleId+"&module="+module;

	new Ajax.Request(url,{method:"post",onSuccess:function(t)
       {
		divObj = getObj('tagClouddiv');
     	        divObj.innerHTML=t.responseText;
                hide('zohobusy_loadpage_vinfo');
        	callrefresh();	
       },asynchronous:true
       });
getObj("textbox_First Name").value =  "";
}

function callrefresh()
 {
	var httphandle = getHTTPObject();
	
   	{

	var url ="/crm/jsp/tagclouditem.jsp"
		httphandle.open("GET", url, true);       
		httphandle.onreadystatechange = function()
   		{
			if(httphandle.readyState == 4)
			{
				var str = httphandle.responseText;
		                if(httphandle.status == 200)
        	   		{
	  		              divObj = getObj('sidebar7');
				      divObj.innerHTML="";	
	 	               	      divObj.innerHTML=str;
				}
					        isWorking = false;
       			}
	   	}       
			httphandle.send(null);


	}
}

//-sanjai
function Addtolist_(obj,module)
{
    var checkboxes=getObj('transfer_ck');
    var noofrows=checkboxes.length;
    var append_ids = "";
    var append_list = "";
    if (noofrows == undefined )
    {
        if (checkboxes.checked)	
        {
            append_ids = checkboxes.value;
		var loop = "addtolist_"+checkboxes.value ;
            append_list=getObj(loop).value;
        }
        else 
        {
        	selectone.getJSAlertValue("crm.alert.select.one",null,"en_US",
																		function(mesg){ alert(mesg) })
          return false;	
        }
    }
    
    else if (noofrows != 0)
    {
        if (getNoOfSelectedRel() == 0)
        {
            selectone.getJSAlertValue("crm.alert.select.one",null,"en_US",
																			 function(mesg){ alert(mesg) })
            return false;	
        }	
        else 
        {
            var segcounter=0;
            for(segcounter = 0 ; segcounter < noofrows ; segcounter++)
            {
                if ( checkboxes[segcounter].checked)
                {
                append_ids= checkboxes[segcounter].value+";"+append_ids;
		var loop = "addtolist_"+checkboxes[segcounter].value ;            
                append_list=(getObj(loop).value)+";"+append_list;
                 }
                
            }
 
        }
    }

if (!isWorking && http)
    {
        features="menubar=no,toolbar=no,location=no,status=no,scrollbars=yes,resizable=yes";
        var url ="/crm/jsp/IWAddtoList.jsp?append_ids="+append_ids+"&append_list="+append_list+"&module="+module;
        
        
        openPopUp("ghjhjgk",obj,url,"test",400,140,features)
    }
}

function getNoOfSelectedRel()
{
        var checkboxes=getObj('transfer_ck');    
        var noofrows=checkboxes.length; 
        noofselected = 0
        for(i=0 ; i < noofrows ; i++)
        {
                if (checkboxes[i].checked)
                        noofselected ++;
        }
        return noofselected;
}
function ShowAll(selectedGroup,module)
{
document.location.href="/crm/ShowDetails.do?tabGroup="+selectedGroup+"&module="+module;
}
function importAttendeesList(obj)
{
var checkboxes=getObj('chk');
var importid="";
var noofrows=checkboxes.length;
if(noofrows==undefined)
{

if(checkboxes.checked)
{
importid=checkboxes.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 if(getNoOfSelected()>1)
        {
            selectone.getJSAlertValue("crm.alert.select.one.only",null,"en_US",
																			 function(mesg){ alert(mesg) })
            return false;
	}
	else 
	{
for(i = 0 ; i < noofrows ; i++)
            {
                if (checkboxes[i].checked)
                {
		importid=checkboxes[i].value;
		}
		}

	}	
}
if (!isWorking && http)
    {

	document.getElementById("importAttendees").innerHTML="";
	fnvshobj(obj,'importAttendees');
        var url ="/crm/jsp/IWImportAttendees.jsp?append_ids="+importid;
       	http.open("GET", url, true);
 	http.onreadystatechange = function()
                {
                        if(http.readyState == 4)
                        {
                                var str = http.responseText;
			document.getElementById("importAttendees").innerHTML=str;
                        }
                }
                http.send(null);

        
    }

}	


function Addtolist(obj,module)
{
     var checkboxes=getObj('chk');
if(checkboxes==null)
{
checkboxes=getObj('transfer_ck');
}
    var noofrows=checkboxes.length;
    var append_ids = "";
    var append_list = "";
    if (noofrows == undefined )
    {
    	if (checkboxes.checked)	
        {
                append_ids = checkboxes.value;
		var loop;
		if(module=="Contacts")
   		loop="sendEmailCont_"+checkboxes.value;
		else
             	loop = "addtolist_"+checkboxes.value ;
               append_list=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(var i = 0 ; i < noofrows ; i++)
            {
               if (checkboxes[i].checked)
                {
                append_ids= checkboxes[i].value+";"+append_ids;
		var loop;
		if(module=="Contacts")
                loop = "sendEmailCont_"+checkboxes[i].value ;    
		else
		loop = "addtolist_"+checkboxes[i].value ;            
                append_list=(getObj(loop).value)+";"+append_list;
                 }
                
                
            } 
        }
    }	
    
	if(append_ids!=null )
	{
	  
	DWRCommonUtil.containsContact
	            (
		            append_ids,module,
		            function(isPresent)
		            {
		            	emailPresent=isPresent;
		            	if(emailPresent!= true)
						{
							alert('Unable to perform the operation as the Opportunity does not have Contact');
						}    

else if (!isWorking && http)
    {
	fnvshobj(obj,'AddtoList');
        var url ="/crm/jsp/IWAddtoList.jsp?append_ids="+append_ids+"&append_list="+append_list+"&module="+module+"&skintype="+skintype;
       	http.open("GET", url, true);
 	http.onreadystatechange = function()
                {
                        if(http.readyState == 4)
                        {
						
                                var str = http.responseText;

			document.getElementById("AddtoList").style.top=document.getElementById("idForCV").offsetHeight;
			document.getElementById("AddtoList").innerHTML="<iframe frameborder='0' style='position:absolute;z-index:-1;width:350px;height:140'></iframe><div>"+str+"</div>";

			//grow("AddtoList")
                        }
                }
                http.send(null);

     }
}
);
   
    }
return false
}
function SaveAddtoList()
{
	var appendid=getObj("Property(append_id)").value;
	var segmentid=getObj("segmentid").value;
	var module=getObj("Property(module)").value;
	var segmentname=getObj("Property(text)").value;
	segmentname = trimBoth(segmentname);
	if(segmentid=="" && segmentname=="")
        {
					selectone.getJSAlertValue("crm.alert.target.empty",null,"en_US",
																		function(mesg) { alert(mesg) })
        	return false;
        }
	if (http)
            {		
          	var url ="/crm/SaveAddtoList.do?segmentid="+segmentid+"&appendid="+appendid+"&module="+module+"&segmentname="+segmentname;	
           	http.open("GET", url, true); 	    
		http.onreadystatechange = function()
   		{	
       			if(http.readyState == 4)
       			{
                            var str = http.responseText;	  
 			/*	 if(str.indexOf("ADDERROR::::")>-1)
				{
				
					var length=("ADDERROR::::").length;
                                        var msg = str.substring(str.lastIndexOf("ADDERROR::::")+length);
                                        alert(msg);

 				}*/
				squish("AddtoList")         
       			}	
   		}		  
   		http.send(null);
            }
	
return false;
}
function setoption(obj)
{

	var id = obj.options[obj.selectedIndex].value;
	if( getObj("segmentname").style.display=="block");
	getObj("segmentname").style.display="none";
	if(getObj("segmentname").style.display=="none" && id==1)
	getObj("segmentname").style.display="block";	
	getObj("segmentid").value=id;
}
function showCampaignResults(id)
{
	document.location.href="/crm/CampaignDashboard.do?id="+id+"&tabGroup=Marketing&module=Campaigns";
}

function showFBMesageWindow(toids, skintype)
{
    openPopUp("SendMessage",this,"/crm/SocialMessageForContacts.do?toids="+toids+"&skintype="+skintype,"SendMail",800,500,"menubar=no,toolbar=no,location=no,status=no,scrollbars=yes,resizable=yes");
}

function sendFBMessageContactAction(obj,module,chk,skintype)
{
    // Find the check boxes.
    var checkboxes = getObj(chk);
    
    // No checkboxes at all?
    if (! checkboxes)
    	return;
    
    // If there's only 1, it won't be in an array.
    if (checkboxes.length == undefined)
    	checkboxes = [ checkboxes ];
    
    // Collect the IDs
    var append_ids = "";
    for (i = 0 ; i < checkboxes.length ; i++)
    {
        if (checkboxes[i].checked)
        {
        	if (append_ids.length > 0)
        		append_ids += ",";
        	append_ids += checkboxes[i].value;
        }
    } 

    if (! append_ids)
    {
        selectone.getJSAlertValue("crm.alert.select.one",null,"en_US",function(mesg){ alert(mesg) })
        return false;
    }
    
    showFBMesageWindow(append_ids, skintype);
}

function CreateActionCommon(obj,sortedColumn,module,id,cvname,cvid,start_index,end_index,caseContactId,caseSubject,caseContactName,iterationid, programid,campaignmode,sitestatus,skintype,targetid,parentId,invoiceid,loginname)
{
//	showInLine('zohobusy_loadpage_vinfo');
	var actionName = obj.value ;  
	    features="menubar=no,toolbar=no,location=no,status=no,scrollbars=yes,resizable=yes";
        var tabGroup=document.getElementById("tabGroup").value
    if(actionName=='Clone'){

		var url = "/crm/Clone.do?tabGroup="+tabGroup+"&module="+module+"&id="+id;
		var isdynamic = getObj('isdynamic').value;
        if(isdynamic=='true')
        {
		    ajaxNew(url);
        }
        else
        {
           document.location.href=url+"&isload=true";
        }
	}
     
	if(actionName=="Dashboard")
	{
 		document.location.href="/crm/CampaignDashboard.do?id="+id+"&tabGroup=Marketing&module=Campaigns";
	}
        if(actionName=="EventDashBoard")
	{
            var URL ="/crm/EventDashboard.do";
            URL += "?id="+id+"&tabGroup=Events&module=Events";
             openPopUp("ghjhjgk",obj,URL,"test",700,400,features);
	}
         if(actionName=="DFBPreview")
	{          
            var URL ='/crm/DFBPreview.do?entityId='+id+'&resultView=preview';
            openPopUp("ghjhjgk",obj,URL,"test",800,550,features);
            /*new Ajax.Request(url,{method:"post",onSuccess:function(t)
            {
                showDialog(t.responseText,"position=absolute,title=Preview,top=200,left=200,width=600,modal=yes,closeOnEscKey=no");
            },asynchronous:true});*/
	}

	if(actionName=="EditIterationRequirements")
	{
 		document.location.href="/crm/ShowMultiValuesForAdd.do?moduleid="+id+"&frommodule="+module+"&tomodule=IterationRequirements&EditAll=true&target=CustomView";
	}         
	if(actionName=="AssignScholarships")
	{
 		document.location.href="/crm/AssignScholarship.do?title_key=crm.title.new.essay&returnAnchor=SCHOLARSHIPSPERSONALITY&target=CustomView&id="+id;
	}
 	if(actionName=="Mail Invoice")
	{

	openPopUp("SendMail",this,"/crm/jsp/IWSendMailForContacts.jsp?append_ids="+id+"&module="+module+"&skintype="+skintype,"SendMail",800,500,"menubar=no,toolbar=no,location=no,status=no,scrollbars=yes,resizable=yes");

	}
	if(actionName=="Make Payment")
	{
	document.location.href="/crm/Create.do?module=Payments&entityid="+id+"&relmodule=Invoices&returnAnchor=attachmentspersonality";

	}
	if(actionName=="Make Online Payment")
	{
		window.open("/crm/InitiatePayment.do?invoiceId="+id);
	}
	if(actionName == "Generate Pdf")
	{
	document.location.href="/crm/GeneratePdf.do?module=Invoices&id="+id;

	}	 
	if(actionName=="Print Invoice")
	{
	win=window.open("/crm/PrintEntityInfo.do?module="+module+"&id="+id+"&action=print&step=print","PrintEntityInformation","top=30,left=150,menubar=yes,toolbar=no,location=no,status=yes,scrollbars=yes,resizable=yes,width=750,height=600");

	}	
	if(actionName=="copyregistrant")
	{
	document.location.href="/crm/IWCopyParticipants.do?tabgroup=Programs&module=Registrations&iterationid="+iterationid+"&programid="+programid+"&idlist="+id;		

	
	}	
if(actionName=="TSWTransfers")
	{
 		document.location.href="/crm/IWTransferPolicy.do?iterationid="+iterationid+"&programid="+programid+"&registrationid="+id+"&policyname=&policyid=";
	}
if(actionName=="Preview")
{
	var	option=false;
	var fromModule='';
	var campaignId=''
	if(module=='Campaigns')
	{
		module='Segments';
		if(parentId!=null && parentId!="" && parentId!='null')
		{
			fromModule='FollowupCampaigns';			
		}
		else
		{
			fromModule='Campaigns';
		}
		campaignId=id;
		id=targetid;
		option=true;
	}
	openPopUp("Preview",this,"/crm/ViewPreview.do?module="+module+"&id="+id+"&action="+option+"&campaignId="+campaignId+"&fromModule="+fromModule,"test",600,500,"menubar=no,toolbar=no,location=no,status=no,scrollbars=yes,resizable=yes");
}

        if(actionName=="Edit")
        {
     
            if(module == 'Exclusions')
            {	
             
	            DWRCommonUtil.isEmailOptOut
	        	(
		            id,
		            function(isPresent)
		            {
		            	if(isPresent== true)
						{
							alert('Permission Denied');
							return false;
						} 
						else
						{
							document.location.href="/crm/Edit.do?type=Edit&module="+module+"&id="+id+"&isload=true";
	            			return false;
						}
					}
				
				);
            }
            else if(module == "Segments")
            {	
            	
	            DWRCommonUtil.isEmailOptOutForTargets
	        	(
		            id,
		            function(isPresent)
		            {  
		            	if(isPresent== true)
						{
							alert('Permission Denied');
							return false;
						} 
						else
						{
									
							document.location.href="/crm/Edit.do?type=Edit&tabGroup="+tabGroup+"&module="+module+"&id="+id+"&isload=true";
	            			return false;
						}
					}
				
				);
            }
            else
            {
            	document.location.href="/crm/Edit.do?type=Edit&tabGroup="+tabGroup+"&module="+module+"&id="+id+"&isload=true";
            }
        }
        else if(actionName=="Delete")
        {
             if(module=='Venues'){
                DWRCommonUtil.getlocationStatus
                        (
                        id,
                        function(isPresent)
                        {
                            locationPresent=isPresent;                        
                            if(locationPresent== true)
                            {
                                alert('Unable to perform the operation as the Location used in Event ');
                            }    
                            else 
                            {                        
                                Callonclickofbutton2('/crm/DeleteFromCV.do',module,id,cvname,cvid,start_index,end_index);
                            }
                        }
                        );
             }
             else if(module=='Discounts')
            {
                DWRCommonUtil.getDiscountStatus
                        (
                        id,
                        function(isPresent)
                        {
                            discountPresent=isPresent;                        
                            if(discountPresent== true)
                            {
                                alert('Unable to perform the operation as the Discount has been applied to Invoices');
                            }    
                            else 
                            {                        
                              Callonclickofbutton2('/crm/DeleteFromCV.do',module,id,cvname,cvid,start_index,end_index);
                            }
                        }
                        );
            }
             else if(module=='Campaigns'){
                DWRCommonUtil.hasFollowup
                        (
                        id,
                        function(isPresent)
                        {
                            if(isPresent== true)
                            {
                                alert('Campaigns with Follow up cannot be deleted');
                            }    
                            else 
                            {                        
                                Callonclickofbutton2('/crm/DeleteFromCV.do',module,id,cvname,cvid,start_index,end_index);
                            }
                        }
                        );
             }
            else if(module == 'Exclusions')
            {
	            DWRCommonUtil.isEmailOptOut
	        	(
		            id,
		            function(isPresent)
		            {
		            	if(isPresent== true)
						{
							alert('Permission Denied');
							return false;
						} 
						else
						{
							Callonclickofbutton2('/crm/DeleteFromCV.do',module,id,cvname,cvid,start_index,end_index);
	            			return false;
						}
					}
				
				);
            }
             else{
                Callonclickofbutton2('/crm/DeleteFromCV.do',module,id,cvname,cvid,start_index,end_index);
             }
                //      deleteEntity(module,id,display_cust_view_name)
        }
 else if(actionName=="Not Spam")
        {
             updateSpamStatus('/crm/SpamStatus.do?spamStatus=false',module,id,cvname,cvid,start_index,end_index);
        }
        else if(actionName=="Mark Spam")
        {
             updateSpamStatus('/crm/SpamStatus.do?spamStatus=true',module,id,cvname,cvid,start_index,end_index);
        }
        else if(actionName=="View")
        {
                document.location.href="/crm/ShowEntityInfo.do?module="+module+"&id="+id+"&isload=true";

        }
	else if(actionName=="Send Mail")
	{
	
		DWRCommonUtil.containsEmail
        (
         	id,module,
	        function(isPresent)
	        {
	         	emailPresent=isPresent;
	         	if(emailPresent!= true)
				{
					selectone.getResoureValue("crm.alert.contact.email.empty","Contacts","en_US",function(mesg) { alert(mesg) })
				}    
				else if (!isWorking && http)
			    {
			        //openPopUp("SendMail",this,"/crm/jsp/IWSendMailForContacts.jsp?append_ids="+id+"&module="+module+"&skintype="+skintype,"SendMail",840,700,"menubar=no,toolbar=no,location=no,status=no,scrollbars=yes,resizable=yes");
                    openPopUp("SendMail",this,"/crm/IWSendMailForContacts.do?append_ids="+id+"&module="+module+"&skintype="+skintype,"SendMail",800,500,"menubar=no,toolbar=no,location=no,status=no,scrollbars=yes,resizable=yes");
			    }
	        }
         );
           
		
	}
        
        if(actionName=="NewMessage")
        {
            var URL ="/crm/CreateNewCaseMessage.do";
            URL += "?AddNewMessageCase=true&id="+id+"&caseContactId="+caseContactId+"&caseContactName="+caseContactName+"&caseSubject="+caseSubject;
             openPopUp("ghjhjgk",obj,URL,"test",700,620,features);
        }
        else if(actionName=="reply")
        {
            addReplyLastMsg(obj,id,actionName )

          //  var URL ="/crm/IWCaseRowLevelAction.do";            
           // URL += "?Actiontype=reply&id="+id;
            // openPopUp("ghjhjgk",obj,URL,"test",700,700,features);
        }
        else if(actionName=="replyAll")
        {
            addReplyLastMsg(obj,id,actionName )
            //var URL ="/crm/IWCaseRowLevelAction.do";            
            //URL += "?Actiontype=replyAll&id="+id;
             //openPopUp("ghjhjgk",obj,URL,"test",700,700,features);
        }
       else if(actionName=="Comment")
        {
            var URL ="/crm/jsp/IWAddCaseComment.jsp";
            URL += "?skintype="+skintype+"&id="+id,caseContactId,caseSubject,caseContactName+"&view=listviewpage"; 
            openPopUp("ghjhjgk",obj,URL,"test",705,255,features);
            
        }
        else if(actionName=="addOrEditOpportunity")
        {
                document.location.href="/crm/IWAddOrUpdateCaseOpp.do?relmodule=Cases&entityid="+id+"&caseContactId="+caseContactId; 
		
        }
        else if(actionName=="addOrEditRegistration")
        {
                document.location.href="/crm/IWAddOrUpdateCaseOpp.do?relmodule=LifeCycles&entityid="+id; 
		
        }
        else if(actionName=="addOrEditLifeCycle")
        {
                document.location.href="/crm/IWAddOrUpdateCaseOpp.do?relmodule=Registrations&entityid="+id; 
		
        }
	else if(actionName=="addOrEditInvoice")
	{

	 document.location.href="/crm/IWAddOrUpdateCaseOpp.do?relmodule=Registrations&module=Invoices&entityid="+id; 

	}

       	else if(actionName=="Schedule Later")
       	{
					disableCampaignScheduler(id,obj,sortedColumn,module,cvname,cvid,start_index,end_index);
       	}
	else if(actionName == "Publish" || actionName == "Unpublish")
	{
		document.location.href="/crm/SaveSite.do?tabGroup=Home&module=Sites&siteId="+id+"&actionType="+actionName+"&siteType=ListView";
	}
        else if(actionName=="Action")
        {
            return false;
        }
    else if (actionName == "SendSocialMessage")
    {
    	showFBMesageWindow(id, skintype);
    }

      obj.value ="Action";
}

//addReplyLastMsg method moved from iwcasemessages
function addReplyLastMsg(obj,params,type )
{
	var paramsvalues=params.split('&');
	var caseid=paramsvalues[0];
    DWRCommonUtil.containsEmail(caseid,'Cases',
    function(isPresent)
    {
        emailPresent=isPresent;	            	
        if(emailPresent!= true)
        {	
            selectone.getResoureValue("crm.alert.contact.email.empty","Contacts","en_US",function(mesg) { alert(mesg) })
        }    
        else 
        {

            DWRCommonUtil.getCaseMailboxStatus(caseid,function(isPresent){
            mailboxPresent=isPresent;	            
            if(mailboxPresent == true)
            {		
                    selectone.getJSAlertValue("crm.alert.mailbox.status.disabled",null,"en_US",function(mesg) { alert(mesg) })
                    //alert('Unable to perform the operation as the related MailBox Disabled');
            }
            else
            {
                features="menubar=no,toolbar=no,location=no,status=no,scrollbars=yes,resizable=yes,top=0";
                   var URL ="/crm/IWCaseRowLevelAction.do";     
               if(type=='reply' || type=='Reply')
               {
                    URL += "?Actiontype=reply&id="+params;
               }
               else
               {
                    URL += "?Actiontype=replyAll&id="+params;
               }
               openPopUp("ghjhjgk",obj,URL,"test",710,500,features);
            }
            });

        }
    });
}
//
function checkTemplateStatus(templateId)
{
	var templateStatus=false;
	DWRCommonUtil.getTemplateStatus
        (
              templateId,
              function(isPresent)
              {
                     templatePresent=isPresent;                        
                     if(templatePresent== true)
                     {
			    alert('Unable to perform the operation as the Email Template used in either Event or Communication Plan');
			    return false;
                     }
                     else
                     {
                     		var tstat=false;
					DWRCommonUtil.getCampaignTemplateStatus
				        (
				              templateId,
				              function(isPresent)
				              {
				                     tstat=isPresent;                        
				                     if(tstat== true)
				                     {
							    alert('Unable to perform the operation as the Email Template used in Campaign');
							    return false;
				                     }
						     else if(window.confirm("Are you sure?")) 
						     {
							    document.location.href="/crm/Template.do?step=delEmailTemplate&tabGroup=<%=tabGroup%>&module=Email Templates&emailTemplateId="+templateId;
						     }
						     else
						     {
							     return false;
						     }
					      }
					      
	   			 );
                     
                     
                     
                     }
		     
	      }
	      
	    );
	
}
function checkFolderStatus(folderId)
{
	var templateStatus=false;
	DWRCommonUtil.getTemplateFolderStatus
        (
              folderId,
              function(isPresent)
              {
                     templatePresent=isPresent;                        
                     if(templatePresent== true)
                     {
			    		alert('Unable to perform the operation as the Email Templates in this Folder used in Event or Campaign');
			  			return false;
                     }
                    else if(window.confirm("Are you sure?")) 
					{
						document.location.href="/crm/Template.do?step=delEmailTemplateFolder&tabGroup=<%=tabGroup%>&module=Email Templates&templateFolderId="+folderId;
					}
					else
					{
					    return false;
					}
				}
					      
	   	);
                 
}
function CreateActivitiesAction(obj,type,id,displaycustviewname,module,selectedcvid) 
{
	var actionName = obj.value ; 
	if(actionName=="Edit")
	{
		document.location.href="/crm/Edit.do?module="+type+"&id="+id+"&isload=true";
	}
	else if(actionName=="Clone")
	{	
		document.location.href="/crm/Clone.do?module="+type+"&id="+id+"&isload=true";
	}
	else if(actionName=="Delete")
	{
		deleteEntity(type,id,displaycustviewname)
	}
	else if(actionName=="Close")
	{
		document.location.href="/crm/Edit.do?module="+type+"&id="+id+"&taskstatus=Completed&viewTransfer="+module+"&selectedcvid="+selectedcvid+"&isload=true";
	}
        else if(actionName=="Action")
        {
            return false;
        }

obj.value ="Action";
}
function deleteEvent()
{
	var bool=window.confirm('Are you sure?');
	if(bool)
	{	
		return true;
	}
	else
	{	
		return false;
	}


}
function getNoOfSelected()
{
		var checkboxes=getObj('chk');    
        var noofrows=checkboxes.length; 
        noofselected = 0
        for(i=0 ; i < noofrows ; i++)
        {
                if (checkboxes[i].checked)
                        noofselected ++;
        }
        return noofselected;
}
function triggerSaveAlert()
{
	getObj("valueChanged").value='true';
}
function setListener(docForm,eventName,func) 
{
    var browserName=navigator.appName; 
    var formElem;
    for (i = 0; i < docForm.elements.length; i++) 
    {
        formElem = docForm.elements[i];
             	switch (formElem.type) {
                      	// Text, select, hidden, password, textarea elements
      		            case 'text':
						case 'select-one': 
             	     	case 'password':
                      	case 'textarea':
						case 'checkbox':
						case 'radio':
							if (browserName=="Microsoft Internet Explorer")
							{
	    						formElem.attachEvent( "onchange", triggerSaveAlert);
	    						break;
	  						}	
							else if ( typeof window.addEventListener != "undefined" ) 
							{
	   							 formElem.addEventListener( "change", triggerSaveAlert, false );
	   							 break;
							}
						
	  						  					
		}
	}
}
function CaseintrestChk()
{

if((getObj("property(module)").value  == "Cases" || getObj("property(module)").value  == "Inquiries" ) && name == "property(Type)")
	{
                var noofgrouprows = document.createEntityForm.pgmcount.value;   

                    for(var j=1;j<=noofgrouprows;j++)
                    {             

                        var noofrows = getObj("allpgmNamecount"+j).value;

                        for(var i=1;i<=noofrows;i++)
                        {
                      if (getObj("pgmckbox_"+j+i).checked)
                      {   
                            var brouchField = "noOfBrochur_"+j+i;                            
                            var val=getObj(brouchField).value.replace(/^\s+/g, '').replace(/\s+$/g, '')  
                            var re=/^\d+(,(\d)+)*(\.\d{1,2})*$/	
                            if (isNaN(val)) 
                            {
 														selectone.getJSAlertValue("crm.alert.num.valid",null,"en_US",
																											function(mesg) { alert(mesg) })
                                getObj(brouchField).focus()
                                return false
                            }
                            else if(val.indexOf(".")!=-1 || !re.test(val)) 
                            {
                                selectone.getJSAlertValue("crm.alert.entry.num.whole",null,"en_US",
																                          function(mesg) { alert(mesg) })                   	
                                getObj(brouchField).focus()
                                return false
                            }            
                               
                      }  }       
                    }
}
                    caseGeneralInterestChk()
                    casePgmInterestChk()
return true;
}

/*function casePgmInterestChk()
{
    var id="";   
var noofgrouprows = document.createEntityForm.pgmcount.value; 
for(var j=1;j<=noofgrouprows;j++)
                    {    
 var noofrows = getObj("allpgmNamecount"+j).value;

    for(var i=1;i<=noofrows;i++)
    {
                    if (getObj("pgmckbox_"+j+i).checked)
                      {   
                            if(id == "")
                            {                           
                                    id=getObj("pgmckbox_"+j+i).value+":"+getObj("noOfBrochur_"+j+i).value;
                                    
                            }	
                            else
                            {
                                    id =id+":&&:"+getObj("pgmckbox_"+j+i).value+":"+getObj("noOfBrochur_"+j+i).value;
                            }
                        
                      }                     
                      document.createEntityForm.pgmboxvalues.value=id;                    
    }
}
    
    
}
*/
/*function caseGeneralInterestChk()
{
   var id="";
   var parentCol = document.createEntityForm.parentcount.value;   
 
   for(var p=1 ; p <= parentCol ; p++)
    {       
        var childCol =getObj("subcount_"+p).value       
        
        for(var j=1;j<=childCol;j++)
        {
                      if (getObj("columnckbox_"+p+j).checked)
                      {                          
                            if(id == "")
                            {                           
                                    id=getObj("columnckbox_"+p+j).value;
                            }	
                            else
                            {
                                    id =id+":&&:"+getObj("columnckbox_"+p+j).value;
                            }
                        
                      }                     
                      document.createEntityForm.columnckboxvalues.value=id;
        }
    }
    
   
}
*/

function relatedAction(selectObj)
{
	var selInd=selectObj.selectedIndex;
	var oper=selectObj.options[selInd].text;
	var action=selectObj.value;
	var extraurl="";
        if(getObj('cvid'))
        {
           extraurl = "&cvid="+getObj('cvid').value+ "&cvname="+ getObj('cvname').value;;
           if(getObj('sortcolumn'))
           {
             extraurl = extraurl+"&sortcolumn="+ getObj('sortcolumn').value;    
           }    
        }
        action=action+ extraurl;

	if(oper=='Send Mail')
	{
		openPopUp("SendMail",this,action,"SendMail",800,600,"menubar=no,toolbar=no,location=no,status=no,scrollbars=yes,resizable=yes");
	}
	else if(oper=='Delete')
	{
		var de=window.confirm('Are you sure?');
		if(de)
		{		
				document.location.href=action+'&isload=true';
		}
	}
	else if(oper=='Add Iteration Requirements' ||oper=='Assign Scholarship' || oper=='TSW Transfer' ||oper=='Edit' || oper=='View' || oper=='Close' || oper=='Edit Iteration Requirements' || oper=='Add/Edit Invoice' || oper=='View Attachments')
	{
 		document.location.href=action+'&isload=true';
	}
	else if(oper=='Send Invitation')
        {
            
            var selectedvalue= selectObj.value;
        	DWRCommonUtil.isContactContainsMailId
                        (
                        selectObj.value,
                        function(isPresent)
                        {
                            var status=isPresent;                        
                            if(status == false)
                            {
                             alert('Unable to Perform the operation as the contact does not have Email Address');
                            }    
                            else 
                            {   
					            DWRCommonUtil.getRecommenderStatus
		                        (
		                        selectedvalue,
		                        function(isPresent)
		                        {
		                            var status=isPresent;                        
		                            if(status == true)
		                            {
		                            	var url="/crm/SendEmailForRecommender.do?id="+action;
										features="menubar=no,toolbar=no,location=no,status=no,scrollbars=yes,resizable=yes";
       									openPopUp("ghjhjgk",this,url,"test",800,550,features);
		                            }    
		                            else 
		                            {                        
		                                alert('Recommendation Already Received');
		                            }
		                        }
		                        );
                        
                        
                    }
                }
             );    
        }
	
    else if(oper=='Delivery Status')
        {
            checkMessageStatus(action);
        }
    selectObj.selectedIndex  =0;
}

function formCheck(obj)
{
    if(getObj('formName').value !='')
    {
        var formId = getObj('formName').value
        features="menubar=no,toolbar=no,location=no,status=no,scrollbars=yes,resizable=yes";
        var URL ='/crm/DFBPreview.do?entityId='+formId+'&resultView=preview';
        openPopUp("ghjhjgk",obj,URL,"test",800,550,features);
    }
    else
    {
        alert("Form cannot be blank");
    }
}

function convertToTarget(source,campaignId,action,showUrl)
{
	var targetName=document.getElementById("targetName").value;
	var url;
	var args='';
	if(targetName.trim()=='')
	{
		alert('Enter Target Name');
		return false;
	}
	args="createTarget=true&forContacts="+source+"&campaignId="+campaignId+"&targetName="+targetName;
	if(action!=null)
	{
		if(action!="showall")
			url=showUrl;
		else
			url="showall";
		args=args+"&showUrl="+url;
	}
	var url="/crm/ExportDash.do?"+args;
	new Ajax.Request(url,{method:"get",onSuccess:function(t)
  	{
  		document.getElementById("target").innerHTML="<br>"+t.responseText+"&nbsp;<img src='/crm/javascript/fckeditor/editor/images/smiley/msn/regular_smile.gif' border='0'><br><br>";
    },asynchronous:true});
}

function showTarg()
{
var style = document.getElementById("target").style.display ;

   if(style == 'none')
   {

       document.getElementById("target").style.display = 'block';              
	   
   }
   if(style == 'block')
   {
       document.getElementById("target").style.display = 'none';
       
   }
}
function callAction(module,cvname,cvid,showAll)
{
	
		if(showAll)
		{
	    	callckfn(false);
		}
		else
		{
		if(!callckfn(true)) return false;

		}	
            var programid = getObj("programid").value;               
            var iterationid = getObj("iterationid").value;
            if((!programid=="" && iterationid =="") ||(programid=="" && !iterationid ==""))
            {
                alert("You must select both Program & Iteration fields")
                return false;
            
            }
		document.showcvdetails.filterProgramId.value=programid
		document.showcvdetails.filterIterationId.value=iterationid
	

	if(getObj("currentOption"))
	{
		document.showcvdetails.rangeValue.value = getObj("currentOption").value;
	}
        if (!isWorking && http)
	{
            if(!programid=="" && !iterationid =="")
            {
               
                var args ="module="+module+"&display_cust_view_name="+escape(cvname)+"&cvid="+cvid+"&rangeValue="+escape(getObj("rangeValue").value)+"&regStatushiddenlist="+escape(getObj("regStatushiddenlist").value)+"&isSponsor=&isRecommender=&programid="+ programid+"&iterationid="+iterationid;
                
            }
            else
            {
                
                var args ="module="+module+"&display_cust_view_name="+escape(cvname)+"&cvid="+cvid+"&rangeValue="+escape(getObj("rangeValue").value)+"&regStatushiddenlist="+escape(getObj("regStatushiddenlist").value)+"&isSponsor=&isRecommender=";
            }
	var url ="/crm/IWFilterRegAction.do?"+args+"&showAll="+ showAll;
	
        document.getElementById('zohobusy_filter_search').style.display = 'inline';
	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;
				hide('zohobusy_filter_search');				
			}
			isWorking = false;
		}
	}	
	http.send(null);
	}
return false;
}

function callckfn(doAlert)
{
        noofrows = document.showcvdetails.regid.length;
	var append_ids = "";
	
	if (noofrows == undefined )
	{
		if (document.showcvdetails.regid.checked)	
		{
                append_ids = document.showcvdetails.regid.value;                
                document.showcvdetails.regStatushiddenlist.value=append_ids
		}
		else 
		{
            		if(doAlert)
             		{
    				alert('Select any filter option')
					
			return false;	
              		}
		}
	}
	else if (noofrows != 0)
	{
		if (getNoOfSelectedFilter() == 0)
		{
        		if(doAlert)
        		{
				alert('Select any filter option')
				
			return false;	
        		}
		}	
		else 
		{	
			for(i = 0 ; i < noofrows ; i++)
			{
				if (document.showcvdetails.regid[i].checked)
				append_ids= document.showcvdetails.regid[i].value+";"+append_ids;
			}
			if(doAlert)
			{              
			document.showcvdetails.regStatushiddenlist.value=append_ids	
			}
        	}
	}
        else
        {
		return false;
        }
return true;	
}
function getNoOfSelectedFilter()
{
        noofrows = document.showcvdetails.regid.length;
        noofselected = 0
        for(i=0 ; i < noofrows ; i++)
        {
                if (document.showcvdetails.regid[i].checked)
                        noofselected ++;
        }
        return noofselected;
}
function handleOnChange(selectObj)
{
	 if(getObj("previousvalue").value!="" && getObj("previousvalue").value!=" " && getObj("previousvalue").value!="None")
        {
        hide(getObj("previousvalue").value);
        }
	
	getObj("previousvalue").value=selectObj.value;
    	show(selectObj.value);
    	document.showcvdetails.showall.value='false'
}
function handleShowAll(module,custview,cvid)
{
hide('status');
hide('value1');
show('value2');
document.showcvdetails.showall.value='true';
document.showcvdetails.filterProgramId.value='';
document.showcvdetails.filterIterationId.value='';
document.showcvdetails.regStatushiddenlist.value='';

callAction(module,custview,cvid,true);
}
function handleShowSelected()
{
    show('status');
    show('value1');
    hide('value2');
    document.showcvdetails.showall.value='false';
}
function handleLifeCycleShowAll(cvname,cvid)
{
document.showcvdetails.showall.value='true'
handleForm(cvname,cvid,true);
}

function setDependentOnCreate(obj )
{
	var isDependent = false;
	var name = obj.name;
	/*
	if(name == "property(Lifecycle Stage)")
	{            
            getObj("property(Source Group)").selectedIndex = 0
            setDependentOnCreate(getObj("property(Source Group)") ) ;
	}
	*/
	if(( getObj("property(module)").value ) == "Segments" && name == "property(Type)")
	{            
            var img = getObj("property(Type)").value; 
           
            if(img =="Static" )
            {              
                getObj("SegmentContListView").style.display = "block";
                getObj("SegmentQryBuilder").style.display = "none";               
            }
            if(img =="Dynamic" )
            {
                getObj("SegmentQryBuilder").style.display = "block";
                getObj("SegmentContListView").style.display = "none";               
            }
	}
    var val = "";
	if(getObj("field"+name)!=null)
    {
      val=getObj("field"+name).value;
    }
	if(val != null && val != "" && val != "null")
        {
            var fields = val.split("&&&");
            for(var i=0;i< fields.length;i++)
            {	
                    var arr = fields[i].split("|||");
                    var label = arr[0];
                    var values = arr[1].split(":::");
                    var count = 0;
                    var depObj = "";
                    var selectValues = "";
                    if(getObj(label))
                    {	
                            count = getObj(label).value;
                            depObj = getObj("comboValue"+count);
                            selectValues = getObj("selectValue"+count).value;
                    }
                    else
                    {
                            depObj = getObj("property("+label+")");
                            selectValues = getObj("selectValue"+label).value;	
                    }	
                    for(var k=0;k<values.length;k++)
                    {
                            var list = values[k].split("===");
                            var rat = list[0];
                            if(rat == obj.value)
                            {
                                    isDependent = true;
                                    depObj.length = 0;
                                    var depvalues = list[1].split(";;;");
                                    for(var j=depvalues.length-1;j>=0;j--)
                                    {
                                            var optionElement = document.createElement("OPTION");
                                            if(depvalues[j]=='-None-')
					    depvalues[j]="";
                                            optionElement.value = depvalues[j];
                                            optionElement.text = depvalues[j];
                                            depObj.options.add(optionElement);
                                    }	
                            }
                    }
                    if(!isDependent)
                    {
                            var getValues = selectValues.split(";");
                            depObj.length = 0;
                            for(var j=0;j<getValues.length;j++)
                            {
				    
                                    var optionElement = document.createElement("OPTION");                                    
				    if(getValues[j]=='-None-')
					    getValues[j]="";
                                    optionElement.value = getValues[j];	    
                                    optionElement.text = getValues[j];
                                    depObj.options.add(optionElement);
                            }	
                    }	
            }
	}
if(module=='Campaigns' && getObj('property(Channel)')!=null && getObj('property(Channel)').value =='Email')
{
	getObj("property(Status)").value='Planned';
	getObj("property(Status)").disabled=true;
}	
else if(module=='Campaigns')
{
	getObj("property(Status)").disabled=false;
}
if(module=='Campaigns' && getObj('property(Status)')!=null && getObj('property(Status)').value =='Completed')	
{
	getObj("property(Channel)").disabled=true;
	getObj("property(Type)").disabled=true;
}
else if(module=='Campaigns')
{
	getObj("property(Channel)").disabled=false;
	getObj("property(Type)").disabled=false;
}
}


function processObject(currentid,currvalue,module,cvid,loginname,nextorprevious,sortcolumn,cvname,rownum,pagesizestr)
{
    if(nextorprevious)
    {
        rownum=rownum+1;
    }
    else
    {
        rownum=rownum-1;
    }
    DWRCommonUtil.getNextID_New(currentid,module,cvid,loginname,nextorprevious,rownum,pagesizestr,function(response)
    {
       var responsearray=response;
        if(responsearray==null)
        {
            if(nextorprevious)
            {
                alert("There are no more records in this View");
            }
            else
            {
                alert("No previous record");   
            }
        }
        else
        {
            var id = responsearray[0];
            rownum=responsearray[1];

            var url = "/crm/ShowEntityInfo.do?id="+ id+ "&module="+ module+ "&cvid="+ cvid+"&rownum="+rownum+"&pagesize="+ pagesizestr;
            if(sortcolumn!=null)
            {
                url=url+"&sortcolumn="+ sortcolumn;
            }
            url=url+"&cvname="+ cvname;    
            ajaxNew(url);     
        }           
    });
}

function previousObject(currentid,currvalue,module,cvid,loginname,sortcolumn,cvname,rownum,pagesizestr)
{
    processObject(currentid,currvalue,module,cvid,loginname,false,sortcolumn,cvname,rownum,pagesizestr);
}

function nextObject(currentid,currvalue,module,cvid,loginname,sortcolumn,cvname,rownum,pagesizestr)
{
    processObject(currentid,currvalue,module,cvid,loginname,true,sortcolumn,cvname,rownum,pagesizestr);
}

function firstObject(currentid,currvalue,module,cvid,loginname,sortcolumn,cvname,rownum,pagesizestr)
{
    DWRCommonUtil.getFirstID_new(module,cvid,loginname,rownum,pagesizestr,function(response)
    {
        if(response==null)
        {
           alert("There are no more records in this View");
           
        }
        else
        {
            var id = response[0];
            rownum=response[1];
            var url = "/crm/ShowEntityInfo.do?id="+ id+ "&module="+ module+ "&cvid="+ cvid+"&rownum="+rownum+"&pagesize="+ pagesizestr;
            if(sortcolumn!=null)
            {
                url=url+"&sortcolumn="+ sortcolumn;
            }
            url=url+"&cvname="+ cvname;
            //alert("url-->"+ url);
            if(id== currentid)
            {
                 //alert("SAME ID");
        		alert("No Records");
            }
            else
            {
                ajaxNew(url);     
            }
        }           
    });
}

function lastObject(currentid,currvalue,module,cvid,loginname,sortcolumn,cvname,rownum,pagesizestr)
{
    DWRCommonUtil.getLastID_new(module,cvid,loginname,rownum,pagesizestr,function(response)
    {
        if(response==null)
        {
            alert("No Records");
        }
        var id = response[0];
        var rownum=response[1];
        {
            var url = "/crm/ShowEntityInfo.do?id="+ id+ "&module="+ module+ "&cvid="+ cvid +"&rownum="+rownum+"&pagesize="+ pagesizestr;
            if(sortcolumn!=null)
            {
                url=url+"&sortcolumn="+ sortcolumn;
            }
            url=url+"&cvname="+ cvname;
            //alert("url-->"+ url);
            if(id== currentid)
            {
                 //alert("SAME ID");
		alert("No Records");
            }
            else
            {
                ajaxNew(url);     
            }
        }           
    });
}

var myDuplicate = false;
function isContactDuplicate()
{
    var firstName = "";
    var lastName = "";
    var contactStreet = "";
    var city = "";
    var state = "";
    var zipCode = "";

    if(getObj("property(First Name)"))
    {
        firstName = trim(getObj("property(First Name)").value);
    }
    if(getObj("property(Last Name)"))
    {
        lastName = trim(getObj("property(Last Name)").value);
    }
    if(getObj("property(Contact Street)"))
    {
        contactStreet = trim(getObj("property(Contact Street)").value);
    }
    if(getObj("property(Contact City)"))
    {
        city = trim(getObj("property(Contact City)").value);
    }
    if(getObj("property(Contact State)"))
    {
        state = trim(getObj("property(Contact State)").value);
    }
    if(getObj("property(Contact Postal Code)"))
    {
        zipCode = trim(getObj("property(Contact Postal Code)").value);
    }
    
    DWRCommonUtil.isContactDuplicate(firstName,lastName, city, state, zipCode, contactStreet,
        {callback: function(isDuplicate)
        {
            if(isDuplicate == true)
            {
                myDuplicate = true;
            }
            else
            {
                myDuplicate = false;
            }
        }, async:false});
        return myDuplicate;
}

var studentIdDuplicate = false;
function isStudentIdDuplicate(studentId)
{
    StudentId.isStudentIdDuplicate(studentId,
      { callback: function(status)
      {
        if(status == true)
        {
            studentIdDuplicate = true;
        }
        else
        {
            studentIdDuplicate = false;
        }
      }, async:false});
    return studentIdDuplicate;
}

var anotherContactWithStudentId = false;
function checkForOtherContacts(studentId,currentContactId)
{
    StudentId.anotherContactWithStudentId(studentId,currentContactId,
      { callback: function(status)
      {
        if(status == true)
        {
            anotherContactWithStudentId = true;
        }
        else
        {
            anotherContactWithStudentId = false;
        }
      }, async:false});
    return anotherContactWithStudentId;
}

  function createContactAction(operation,module)
  {
      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 contactId = "";
      if(operation == 'Edit' || operation == 'Edit&New')
      {
          contactId = getObj("property(id)").value;
      }
      
      var msg = Form.serialize(getObj('createEntityForm'));
      var url = "/crm/ContactValidate.do?operation=" + operation + "&contactId=" + contactId;
      
      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
                          submitEntityForm(operation,module);
                      }
              }, 
              onFailure: function (transport) { 
                  alert("Error!");
                  }
      });
  }
  
  function massCreateInvoice()
  {
	  var checkboxes=getObj('chk');
	  // Get the check boxes length
	  var noofrows=checkboxes.length;
	  var append_ids = "";
	   
	  // No check boxes are selected
	  if(noofrows == undefined)
		{
			if (document.showcvdetails.chk.checked)
			{
				var values = (document.showcvdetails.chk.value).split("||&&");
				var append_ids = values[0];
			}
			else
			{
				selectone.getJSAlertValue("crm.alert.select.one",null,"en_US",function(mesg) { alert(mesg) })
				return false;
			}
		}
	  else if (noofrows != 0)
	  {
		  if (getNoOfSelected() == 0)
	      {
			  selectone.getJSAlertValue("crm.alert.select.one",null,"en_US",
					  function(mesg){ alert(mesg) })
	          return false;	
	      }	
	      else 
	      {
	    	  // To get checked Ids and save in to append_ids variable
	    	  if(!window.confirm("By clicking ok you will create/update an invoice and associated PDF for each selected registration"))
	          {
	    		  return false;
	          }
	    	  for(var i = 0 ; i < noofrows ; i++)
	          {
	    		  if (checkboxes[i].checked)
	              {
	    			  append_ids = append_ids+checkboxes[i].value+";";
	              }               
	            } 
	        }
	  }	
	  
	  // post the id values through ajax request
	  if(append_ids.length != 0)
	  {
		  var url = "/crm/MassCreateInvoice.do?module=Invoices&reg_append_ids="+append_ids;
		 
		  new Ajax.Request(url,{method:"post",onSuccess:function(t)
		       {
			  	
				getObj("bulkUpdateSuccess").innerHTML='<table width="100%" ><tr><td align="center" class="widgetalert" ><b>Updated Successfully</b></td></tr></table>';
				setCenter(document.getElementById("bulkUpdateSuccess"));
				show("bulkUpdateSuccess");
				setTimeout(function(){hide("bulkUpdateSuccess")},2000);
		       }
		       });
	  }
	  return false
  }

//This function evaluates javascript code in global scope.  Prototype doesn't do this properly.
// So far, it seems that only safari need this, but it works with the major 3.
_IW.Ajax.eval = function(js)
{
	var script = document.createElement("script");
	script.type = "text/javascript";
	
	if (!!(window.attachEvent && navigator.userAgent.indexOf('Opera') === -1))
		script.text = js;
	else
		script.appendChild(document.createTextNode(js));

	var head = document.getElementsByTagName("head")[0] || document.documentElement;
	head.insertBefore(script, head.firstChild);
	head.removeChild(script);
}