//JavaScript Document

var ipad = (navigator.appVersion.indexOf("iPad")==-1) ? false : true;//iPad
var iphone = (navigator.appVersion.indexOf("iPhone")==-1) ? false : true;//iPhone
// If the user agent string contains "android" then it's Android. If it doesn't but it's not another browser, not an iOS device and we're in
// a mobile and touch OS then we can be 99% certain that it's Android.
var android = (navigator.appVersion.indexOf("Android") == -1) ? false : true;

String.prototype.string_create_urls = function () {
	var v = this.replace(/<br>/gi,"  <br>  ").replace(/<\/a>/gi,"  </a>").replace(/[^\"\S]+?(ftp|http|https|file):\/\/[\S]+(\b|$)|[^\"\S]+([\w\.\@])+((.com)|(.tv))+(\b|$)/gim,'<a href="$&" class="my_link" target="_blank">$&</a>');
	v = v.replace(/(href)+[\=]+[\"\s]+([\w\.\@]+((.com)|(.tv))+(\b|$))/gim,'href="http://$2');
	return v;
};
String.prototype.anchorEntities = function () {
	return this.replace(/<a/g,'<a target="_blank"');
};
String.prototype.styleEntities = function () {
	var ua = navigator.userAgent.toLowerCase();
	var ua_index = ua.indexOf('msie');
	if(ua.indexOf('msie') != -1)
	{
		var styleStartIndexCaps = this.indexOf("<STYLE");
		var styleEndIndexCaps = this.indexOf("</STYLE");
		var styleFormatCaps = this.substring(styleStartIndexCaps,styleEndIndexCaps+8);
		if(styleStartIndexCaps!= -1 && styleEndIndexCaps!= -1)
		{
			return this.replace(styleFormatCaps,'');
		}
		else
		{
			return this;
		}
	}
	else
	{
		var styleStartIndex = this.indexOf("<style");
		var styleEndIndex = this.indexOf("</style");
		var styleFormat = this.substring(styleStartIndex,styleEndIndex+8);
		if(styleStartIndex!= -1 && styleEndIndex!= -1)
		{
			return this.replace(styleFormat,'');
		}
		else
		{
			return this;
		}
	}

};
String.prototype.fontEntities = function () { 
	return this.replace(/(<font face)+[\=]+[\"]+[\w\,\-\s]+[\"]/gim,'<font face="Arial,Helvetica,sans-serif"').replace(/(<font style)+[\=]+[\"]+[\w\-\:\s\;]+[\"]/gim,'<font style="font-size:13px;"');
}
var counter=0;
function closealerts(id)
{
	if(id=='watchvedio')
	{
		$('watchvedio').hide();
	}
	else if(id=='invitefriends')
	{
		$('invitefriends').hide();
	}
	else if(id=='starttopic')
	{
		$('starttopic').hide();
	}
	else if(id=='moreideadiv')
	{
		$('moreideadiv').hide();
		$('hide-div').hide();
		$('moreideas-div').show();

	}else{
		$(id).hide();
	}
}

function getSelUserGroupIds(userId) {
	$("selGroupsUserId").value = userId;
	var url = $("getGroupIdsByUserIdURL").value+"&userId="+userId;

	sendMemberRequest(url, checkValidGroupsForUser); 
}

function hideGroups() {
	if($('period-menu').style.display=='block'){
		$('period-menu').style.display='none';
		var userGroupRef = document.getElementsByName('userGroupsRef');
		for (i=0; i<userGroupRef.length; i++) {
			userGroupRef[i].className ="flight-menu";
		}
	}
}

function checkValidGroupsForUser(resp){
	$('group-contents').value = resp.responseText;
	var groupContents = $('group-contents').value;
	var allGroupsArr = document.getElementsByName('allGroups');
	var groupsArr = groupContents.split(",");	
	var userId = $("selGroupsUserId").value;
	var pathToImages = '/collaborize/site/common/images/common-images/';
	//Compare both the userid groups with the total groups available for this site.
	for (i=0; i<allGroupsArr.length; i++) {

		for (j=0;j<groupsArr.length;j++) {
			var allGroupsVal = allGroupsArr[i].id.split("_");	
			if(allGroupsVal[1] == groupsArr[j]) {
				allGroupsArr[i].src=pathToImages+'checkbox_checked.gif';
				//$(allGroupsArr[i]).checked = true;
				break;
			} else {
				//$(allGroupsArr[i]).checked = false;
				allGroupsArr[i].src=pathToImages+'checkbox_unchecked.gif';
			}
		}
	}
}

function showmenubar(ele)
{
	var myPos = new Array();
	var myPos = new Array();
	myPos = findPos(ele);
	var fx = myPos[0];
	var fy = myPos[1];
	var ua = navigator.userAgent.toLowerCase();
	var ua_index = ua.indexOf('msie');
	var ua_version = ua.charAt(ua_index+5);
	if(ua.indexOf('msie') != -1 && ua_version == 7)
	{
		$('period-menu').style.top = fy+25+'px';
		$('period-menu').style.left = fx-118+'px';
	}
	else if(ua.indexOf('msie') != -1 && ua_version == 8)
	{
		$('period-menu').style.top = fy+19+'px';
		$('period-menu').style.left = fx-120+'px';
	}
	else if(BrowserDetect.browser=="Firefox")
	{
		$('period-menu').style.top = fy+19+'px';
		$('period-menu').style.left = fx-120+'px';
	}
	else
	{
		$('period-menu').style.top = fy+19+'px';
		$('period-menu').style.left = fx-119+'px';

	}
}

function updateGroups(checkBoxObj,groupId){

	var pathToImages = '/collaborize/site/common/images/common-images/';
	var url = "";

	if(checkBoxObj.src.indexOf('checkbox_unchecked')>=0)
	{
		url = $('addUserToGroup').value;
		checkBoxObj.src=pathToImages+'checkbox_checked.gif';
	}
	else if(checkBoxObj.src.indexOf('checkbox_checked')>=0){
		url = $('deleteUserFromGroup').value;
		checkBoxObj.src=pathToImages+'checkbox_unchecked.gif';
	}
	url += "&userId="+$("selGroupsUserId").value+"&groupId="+groupId;

	loadDivContent('',url,testFn);
}

function testFn(){

}

function showmorealerts(id)
{
	if(id=='moreideadiv')
	{
		$('moreideadiv').show();
		$('hide-div').show();
		$('moreideas-div').hide();
	}
}
function expandall(ele)
{
	var android = (navigator.appVersion.indexOf("Android") == -1) ? false : true;
	var HideDiv = $$('.topicdesc');
	// to set the width and height of textarea in ipad :::fix
	if(ipad || iphone || android){
		var textArea = document.getElementsByTagName('textarea');
		for(var i=0;i<textArea.length;i++){
			textArea[i].style.width = "100%";
			textArea[i].style.height = "100px";	
			textArea[i].style.marginTop = "5px";		
		}
	}
	if(ele.innerHTML==$('resExpandAll').value)
	{
		for(var i=0; i<HideDiv.length; i++)
		{
			HideDiv[i].show();
			ele.innerHTML=$('resCollapseAll').value;
		}
	} else if(ele.innerHTML==$('resExpand').value) 
	{
		for(var i=0; i<HideDiv.length; i++)
		{
			HideDiv[i].show();
			ele.innerHTML=$('resCollapse').value;
		}
	}
	else if(ele.innerHTML==$('resCollapseAll').value)
	{
		for(var i=0; i<HideDiv.length; i++)
		{
			HideDiv[i].hide();
			ele.innerHTML=$('resExpandAll').value;	
		}
	}else 
	{
		for(var i=0; i<HideDiv.length; i++)
		{
			HideDiv[i].hide();
			ele.innerHTML=$('resExpand').value;	
		}
	}
}
function retrieveComments(url,type){

	try{

		//alert(type);
		if(type=="pro"){
			loadDivContent('proDiv',url+"&type=Pro");
		}else if(type=="con"){
			loadDivContent('proDiv',url+"&type=Con");
		}else{
			loadDivContent('proDiv',url);
		}
	}catch(e){
		alert(e);
	}
}
function searchActiveUser(div,url){

	var search=$('searchUser').value.strip();
	$('userSearchString').value =url+'&search='+search;
	$('searchresults-tab').style.display="block";
	chageusertab(div,url+'&search='+search);
}
function inviteUsers(div,url){
	var msg = $('resInvitations').value;
	if($("invitations").value.strip() == msg) {
		$('invite_errorlist').innerHTML = $('resinvite_errormsg').value;
		$('invite_errorlist').show();
	} else {
		var note = trim (document.getElementById("note").value);
		url = url+"&note="+escape(note)+"&ids="+$("invitations").value.strip();

		sendRequest(url, inviteUserResponseHandler);
	}
}

function removeghosttext()
{
	document.getElementById('ghost-text').innerHTML = '';
	document.getElementById('ghost-text').focus();
}
function insertghosttext()
{
	if(document.getElementById('ghost-text').innerHTML=="")
	{
		document.getElementById('ghost-text').innerHTML="Describe the change(s) you've made.";
	}
}

function resendInvitation(div,url){

	loadDivContent('',url);
	counter=counter+1;

	$("invite_status").innerHTML = counter+''+ $('resinvite_status').value +'!';
	$("invite_status").show();

}
function browseFile(div,url){
	var android = (navigator.appVersion.indexOf("Android") == -1) ? false : true;
	var fileName=$('fileName').value;
	var fName = document.getElementById('emailFilename').value;
	if(fileName.search(/.csv/)!=-1 || fName != ""){
		if(ipad || iphone || android){
			$("note").value = $("formattedNote").value;
		} else {
			$("note").value = instance7.e.body.innerHTML;
		}
		document.importForm.submit();
	}else if($('invitations').value!=$('resInvitations').value && $('invitations').value!=''){	
		if(ipad || iphone || android){
			$("note").value = $("formattedNote").value;
		} else {
			$("note").value = instance7.e.body.innerHTML;
		}
		document.importForm.submit();
	}else {
		/**Author :spenumatsa
		@bug: DS-4188 : As an Account Owner, when sending invites using the batch csv process, there are times when the send invitations button is clickable multiple times which may cause a system problem or duplicate emails to be sent.
		 */
		enablebrowseFileSubmitButton('sendInviteUserSubmitButton');
		var sHTML;
		sHTML = '<a id="importlink" href="javascript:openwindow();"> ';
		sHTML+='Click here';
		sHTML+='</a>&nbsp;';
		$('invalidFile').innerHTML=$('resinvalidFile').value+"<br/>"+sHTML+$('resinemailfile').value;
		document.getElementById('invalidFile').style.display="block";
	}
}
function openwindow()
{
	var Contextpath = $('pagecontext').value+'/FAQ/Export Contacts to CSV-1.pdf';
	window.open(Contextpath,'welcome','width=1000,height=650,scrollbars=yes,menubar=yes,status=yes');
}
function enablebrowseFileSubmitButton(id){
	$(id).href="javascript:sendinvitationuser();";
	$(id).className="button small primary vote"; 
}
function inviteUserResponseHandler(resp) {
	$("invite_errorlist").innerHTML = resp.responseText;
	$("invite_errorlist").show();
	var msg = $('resInvitations').value;
	var note = $('resNote').value;
	$("invitations").value = msg;
	$("note").value = note;
}

function chageusertab(id,url){

	try{
		var Tabs = new Array();
		Tabs[0] = "active-tab";
		Tabs[1] = "activation-tab";
		Tabs[2] = "approval-tab";
		Tabs[3] = "blocked-tab";
		Tabs[4] = "searchresults-tab";

		for(var i=0;i<Tabs.length;i++)
		{

			$(Tabs[i]).className='';
			$(id).addClassName('current');
			if(id=='searchresults-tab'){
				$('searchresults-tab').style.visibility='visible';
			}

		}
		//submitForm('manageuserdiv', document.activeMembersSearch);
		loadDivContent('manageuserdiv',url);
	}catch(e){
		alert(e);
	}
}

function chageProfileTab(id,url){

	try{
		var Tabs = new Array();
		Tabs[0] = "mytopics-tab";
		Tabs[1] = "participation-tab";
		Tabs[2] = "watchlist-tab";
		Tabs[3] = "inbox-tab";
		Tabs[4] = "settings-tab";
		Tabs[5] = "myprofile-tab";
		for(var i=0;i<Tabs.length;i++)
		{
			$(Tabs[i]).className='';
			$(id).addClassName('current');

		}
		loadDivContent('manageprofile',url,callbackProfile);
	}catch(e){
		alert(e);
	}
}

var currentstartDate;
var currentendDate;

function callbackProfile(resp){
	//alert("kkk");
	try{
		var pageView=$('pageView').value;

		// alert("pageView +"+pageView);

		if($(pageView+'count') != null){
			var mytopicsCount=$(pageView+'count').value;

			var mywatchedCount=$(pageView+'count').value;
		}

		if(pageView=='mytopics' && mytopicsCount>0){

			//$('mytopics').addClassName('current');
			// $('mytopics').innerHTML='( '+mytopicsCount+' )';
			// $('mywatched').innerHTML='';
			// $('myparticipation').innerHTML='';

		}
		if(pageView=='myparticipation'){
			getDefaultdates();

			refreshParticipation('site');		 
			// $('myparticipation').addClassName('current');
			// $('myparticipation').innerHTML='( '+myparticipationCount+' )';
			// $('mywatched').innerHTML='';
			// $('mytopics').innerHTML='';
		}
		if(pageView=='mywatchlist' && mywatchedCount>0){
			parent.document.getElementById('mywatchedCount').innerHTML=$("res_WatchedCount").value+'('+mywatchedCount+')';
			// $('mywatched').addClassName('current');
			// $('mywatched').innerHTML='( '+mywatchedCount+' )';
			// $('mytopics').innerHTML='';
			// $('myparticipation').innerHTML='';
		}

	}catch(e){
		//alert('in call back : '+e);
	}
}

/*
* @author gkottala
* @feature : 4141 Report in participation tab in profile
* Show from date and toDate in date fields as default dates.    
*/

function getDefaultdates(){

	var today = new Date();
	// alert("today ::"+today);
	var dd = today.getDate();
	var mm = today.getMonth()+1;// January is 0!
	var yyyy = today.getFullYear();
	if(dd<10){dd='0'+dd}
	if(mm<10){mm='0'+mm} 

	var nextmonth = new Date(today.getFullYear(), today.getMonth()  ,today.getDate()-30);
	var ndd = nextmonth.getDate();
	var nmm = nextmonth.getMonth()+1;// January is 0!
	var nyyyy = nextmonth.getFullYear();
	if(ndd<10){ndd='0'+ndd}
	if(nmm<10){nmm='0'+nmm}  
	document.getElementById("fromDate").value=nmm+'-'+ndd+'-'+nyyyy;
	document.getElementById("toDate").value=mm+'-'+dd+'-'+yyyy;
	// alert("From Date: "+document.getElementById("fromDate").value);
	// alert("To Date: "+document.getElementById("fromDate").value);
	var repstartDate=nyyyy+'-'+nmm+'-'+ndd;
	var rependDate=yyyy+'-'+mm+'-'+dd;
	var startDate=nmm+'-'+ndd+'-'+nyyyy;
	var endDate=mm+'-'+dd+'-'+yyyy;
	document.getElementById("dates").innerHTML="<strong>"+startDate+" to "+endDate+"</strong> ("+days_between(startDate,endDate)+" days)";
	rependDate=rependDate+' 23:59:59';

}

function refreshParticipation(type){

	document.getElementById("login-message-alert").style.display="none";
	var startDate=document.getElementById("fromDate").value;
	var endDate = document.getElementById("toDate").value;
	var startDateVal = startDate.split("-");
	var curr_smonth = startDateVal[0];
	var curr_sdate = startDateVal[1];
	var curr_syear = startDateVal[2];
	currentstartDate = curr_syear + "-" + curr_smonth + "-" + curr_sdate;
	var endDateVal = endDate.split("-");
	var curr_emonth = endDateVal[0];
	var curr_edate = endDateVal[1];
	var curr_eyear = endDateVal[2];

	currentendDate = curr_eyear + "-" + curr_emonth + "-" + curr_edate;
	document.getElementById("dates").innerHTML="<strong>"+startDate+"  "+$('res_to').value+" "+endDate+"</strong> ("+days_between(startDate,endDate)+"  "+$('res_days').value+")";
	currentendDate = currentendDate+' 23:59:59';
	if(currentstartDate>currentendDate){
		document.getElementById("login-message-alert").style.display="block";
		document.getElementById("login-message-alert").innerHTML = $('endDate-startDate').value;
		return;
	}
	var timeZone = getTimezoneName();
	var src = document.getElementById("reportframe").src;

	/*
	 * @author gkottala @feature : 4359 The time displays for user actions
	 * in user activity report differs in "Manage this site " and
	 * "Particiaption" page of profile Root Cause:Missing time zone
	 * parameter Fix:passing the timezone as parameter
	 */
	src = src+"&timeZone="+timeZone;

	var url = src.split('&startDate');

	// document.getElementById("reportframe").src="/Reports/frameset?__report=designs/useractivityreport.rptdesign&Fsite=2&timeZone="+timeZone+"&userId="+$('activityUserId').value+"&startDate="+currentstartDate+"&endDate="+currentendDate+"&buketname=";
	document.getElementById("reportframe").src = url[0]+"&startDate="+currentstartDate+"&endDate="+currentendDate;

}


function days_between(d1, d2) {

	// The number of milliseconds in one day
	var ONE_DAY = 1000 * 60 * 60 * 24
	var day1 = d1.split("-");
	var day2 = d2.split("-");
	var date1 = new Date(day1[2],day1[0],day1[1]);
	var date2 = new Date(day2[2],day2[0],day2[1]);
	// Convert both dates to milliseconds
	var date1_ms = date1.getTime()
	var date2_ms = date2.getTime()

	// Calculate the difference in milliseconds
	var difference_ms = Math.abs(date1_ms - date2_ms)

	// Convert back to days and return
	return (Math.round(difference_ms/ONE_DAY)+1)

}

var topicId="";
function postOpenCommentForm(div,id,msg){
	try{
		var form=$('postForm_'+id);
		var comment=$('commentText_'+id).value;
		comment = comment.htmlEntities();
		comment = comment.specialCharacterEntities();
		if(comment==$('resType-answer').value || comment==$('resType_comment').value || comment==$('resType_thoughts').value)
			comment=' ';
		comment = comment.strip();
		if(comment==''){

			$('error_msg'+id).innerHTML=$('resError_msg').value;
			$('error_msg'+id).style.display="block";
		}else{
			topicId=id; 
			$('commentText_'+id).value=comment;
			for(var i=0;i<comment.length;i++){

				if(comment.charCodeAt(i)==8220){
					v=comment.substring(0,i) + '"' + comment.substring(i+1, v.length);

				}
				if(comment.charCodeAt(i)==8221){
					v=comment.substring(0,i) + '"' + comment.substring(i+1, v.length);

				}

			}
			$('error_msg'+id).style.display="none";
			submitForm(div,form,setVoteCommentCounts);
			$('commentText_'+id).value=msg;
		}
	}catch(e){alert(e);
	}
}
var tId = 0;
function postCommentForm(div,id,msg){
	//alert(id);
	var android = (navigator.appVersion.indexOf("Android") == -1) ? false : true;
	try{
		var form=$('postForm_'+id);
		if(!ipad && !iphone && !android){
			var instanceId =$('instanceId_'+id).value;	
			var tempPostComment ="  "+instance[instanceId].e.body.innerHTML;
			tempPostComment = tempPostComment.fontEntities();
			tempPostComment = tempPostComment.styleEntities();
			$('commentText_'+id).value=tempPostComment;
		}
		var comment=$('commentText_'+id).value;
		if(!ipad && !iphone && !android){
			$('plainTextDiv').innerHTML = comment;
		}
		comment = comment.anchorEntities();
		comment = comment.string_create_urls();
		comment = comment.specialCharacterEntities();
		if(comment==$('resType-answer').value || comment==$('resType_comment').value || comment==$('resType_thoughts').value)
			comment='';
		comment = comment.strip();
		if(ipad || iphone || android){
			var msgContent = comment;
		} else {
			var msgContent = $('plainTextDiv').textContent || $('plainTextDiv').innerText;
		}
		if(msgContent!=null){
			if(msgContent.strip() == ""){

				$('error_msg'+id).innerHTML=$('resError_msg').value;
				$('error_msg'+id).style.display="block";
				if(ipad || iphone || android){
					$('commentText_'+id).value='';
				} else {
					instance[instanceId].e.body.innerHTML = '&nbsp;';
				}
			}else{
				topicId=id; 
				tId=id;

				/*
				 * validate the comment text against the curse words and post only if no
				 * curse words found.
				 */
				if(validateCurseFilter1(comment)) {
					if(!ipad && !iphone && !android){
						var instanceId =$('instanceId_'+id).value;
						var tempPostComment1 ="  "+instance[instanceId].e.body.innerHTML;
						tempPostComment1 = tempPostComment1.fontEntities();
						tempPostComment1 = tempPostComment1.styleEntities();
						$('commentText_'+id).value=tempPostComment1;
					}
					$('commentText_'+id).value = $('commentText_'+id).value.anchorEntities();
					$('commentText_'+id).value = $('commentText_'+id).value.string_create_urls();
					$('commentText_'+id).value = $('commentText_'+id).value.specialCharacterEntities();
					var v = $('commentText_'+id).value;
					for(var i=0;i<v.length;i++){

						if(v.charCodeAt(i)==8220){
							v=v.substring(0,i) + '"' + v.substring(i+1, v.length);

						}
						if(v.charCodeAt(i)==8221){
							v=v.substring(0,i) + '"' + v.substring(i+1, v.length);

						}

					}
					$('commentText_'+id).value =v;
					$('error_msg'+id).style.display="none";
					submitForm(div,form,setCommentCounts);

					// $('commentText_'+id).value=msg;

					/*
					 * @author: mkonusu @bug: DS-4090 - when posting a comment or reply
					 * and we use filter/curse keywords, a warning message displays and
					 * all entered text is removed @fix: removed clearing the text box
					 * value and moved the
					 */
					if(ipad || iphone || android){
						$('commentText_'+id).value='';
					} else {
						instance[instanceId].e.body.innerHTML='';
						instance[instanceId].defaultsetting();
					}
				}
			}
		}
	}catch(e){alert(e);
	}

}
function validateCurseFilter1(comment)
{
	var cursetext = comment;
	return curseFilter(cursetext);
}
function setVoteCommentCounts(resp){	
	setCommentCounts(resp); 
	setVoteCounts(resp); 
}
/**
* Author: vveerabathini
* Bug: DS - 3707
* Fix: updated code to fix popularity value
*/
function setCommentCounts(resp){
	var android = (navigator.appVersion.indexOf("Android") == -1) ? false : true;
	if(ipad || iphone || android){
		$('commentText_'+tId).style.width ="100%";
		$('commentText_'+tId).style.height ="100px";
	}
	if(!ipad && !iphone && !android){
		var instanceId = $('instanceId_'+tId).value;
	}
	if($('topicTypeId_'+tId).value==3){
		if($('commentText_'+tId)) {
			if(!ipad && !iphone && !android){
				instance[instanceId]=null;
				instance[instanceId] = new TINY.editor.edit('editor_'+tId,{
					id:'commentText_'+tId,
					width:650,
					height:124,
					cssclass:'te',
					controlclass:'tecontrol',
					rowclass:'teheader',
					dividerclass:'tedivider',
					controls:['bold','italic','underline','strikethrough','|','subscript','superscript','|','charmap','|','link','|',
					          'orderedlist','unorderedlist','|','outdent','indent','|','leftalign','centeralign','rightalign','blockjustify'],
					          footer:false,
					          xhtml:true,
					          css:'body{background-color:#fff;font-family:Arial, Helvetica, sans-serif;font-size:13px;padding:0px;margin:0px;}',
					          bodyid:'editor_'+tId,
					          footerclass:'tefooter'
				});
			}
		}
	} 

	if($('popular_div_'+topicId))
		$('popular_div_'+topicId).innerHTML = "Popularity: "+$('popularityVal_'+topicId).value;
	if($('showTopCmtCount_'+topicId)){

		if($('cmtCount_'+topicId).value==1){
			$('cnt_'+topicId).innerHTML=$('cmtCount_'+topicId).value;			
			$('showTopCmtCount_'+topicId).innerHTML=$('cmtCount_'+topicId).value+" "+$('res_CmtTxt').value;
		}else{
			if($('cmtCount_'+topicId).value<=3) {
				$('cnt_'+topicId).innerHTML=$('cmtCount_'+topicId).value;
			}
			$('showTopCmtCount_'+topicId).innerHTML=$('cmtCount_'+topicId).value+" "+$('res_comments').value;
		} 
	} 
	if($('showBottomCmtCount_'+topicId)){
		if($('cmtCount_'+topicId).value<=3) {
			$('cnt_'+topicId).innerHTML=$('cmtCount_'+topicId).value;
		}
		$('showBottomCmtCount_'+topicId).innerHTML="("+$('cmtCount_'+topicId).value+")"; 
	}  


}
function setVoteCounts(resp){
	if($('showVoteCount_'+topicId)){
		if($('vtCount_'+topicId).value==1){

			$('showVoteCount_'+topicId).innerHTML=$('vtCount_'+topicId).value+" "+$('res_VoteCount').value;
		}else{
			$('showVoteCount_'+topicId).innerHTML=$('vtCount_'+topicId).value+" "+$('res_Votes').value;
		}  
	}
}
function setDetailCounts(resp){

	if($('error_msg')){
		$('error_msg').innerHTML = '';
		$('error_msg').style.display="none";
	} 
	var id = $('topicId').value; 
	if($('popular_div_'+id)) {
		if($('popularityDetVal_'+id)){
			$('popular_div_'+id).innerHTML = $('resPopularity_div').value + ": "+$('popularityDetVal_'+id).value;
		}else{
			$('popular_div_'+id).innerHTML = $('resPopularity_div').value + ": "+$('popularityVal_'+id).value;
		}
	}
	if($('topTypeId').value==3){
		if($('showTopCmtCount_'+id)){

			if($('cmtCount_'+id).value==1){

				$('showTopCmtCount_'+id).innerHTML=$('cmtCount_'+id).value+" "+$('res_CmtTxt').value;
			}else{
				$('showTopCmtCount_'+id).innerHTML=$('cmtCount_'+id).value+" "+$('res_comments').value;
			} 
		}
		if($('showVoteCount_'+id)){
			if($('vtCount_'+id).value==1){ 
				$('showVoteCount_'+id).innerHTML=$('vtCount_'+id).value+" "+$('res_VoteCount').value;
			} else {
				$('showVoteCount_'+id).innerHTML=$('vtCount_'+id).value+" "+$('res_Votes').value;

			}  
		} 
		/**
		*@Author :mmalyala
		*@Bug : 4097 As a Collaborize site owner, I wanted to add a new answer to a Vote and Suggest question and it's not accepting.
		*@Fix : comment label text changes based on comment count.
		* here $('cmtCount_'+topicId).value represents comment count after posting the comment in detail view.
		* if comment count is 0 comment label text should be "Be the first to submit an answer"
		* if comment count is greater than 0 comment label text should be "Don't see an answer you like, suggest one of your own!"
		*/ 
		if($('cmtCount_'+topicId).value>=0){
			if($('submitAnswer')){ 
				if($('cmtCount_'+topicId).value==0){
					if($('resSubmit_First')){
						$('submitAnswer').innerHTML =$('resSubmit_First').value;
					}
				} else {
					if($('resSubmit_Suggest')){
						$('submitAnswer').innerHTML =$('resSubmit_Suggest').value;
					}
				} 
			}
		}
	} else {
		if($('showTopCmtCount_'+id)){
			if($('cmtCount_'+id).value==1){				
				$('showTopCmtCount_'+id).innerHTML=$('cmtCount_'+id).value+" "+$('res_CmtTxt').value;
			} else {
				$('showTopCmtCount_'+id).innerHTML=$('cmtCount_'+id).value+" "+$('res_comments').value;
			} 
		}
	} 
	if($('isUserVoted')){
		if($('isUserVoted').value == "true" && $('reVoteEnabled').value=="false") {
			$('submitAnswer').innerHTML="";
			$('commentTextDiv').style.visibility="hidden";
			$('post-button').style.visibility="hidden";
		}
	} 
}
String.prototype.htmlEntities = function () {
	return this.replace(/<script/g,'&lt;script').replace(/<\/script>/g,'&lt;/script&gt;').replace(/<font/g,'&lt;font').replace(/<\/font>/g,'&lt;/font&gt;').replace(/<span/g,'&lt;span').replace(/<\/span>/g,'&lt;/span&gt;').replace(/<!--/g,'&lt;!--').replace(/-->/g,'--&gt;');
};
function postComment(div, msg,yesno) {
	try {
		var rad_val;
		var radio;
		var android = (navigator.appVersion.indexOf("Android") == -1) ? false : true;
		for ( var i = 0; i < document.postForm.commentType.length; i++) {
			if (document.postForm.commentType[i].checked) {
				rad_val = document.postForm.commentType[i].value;
			}
		}
		if(yesno!=null){
			for ( var i = 0; i < document.selectedForm.procon.length; i++) {
				if (document.selectedForm.procon[i].checked) {
					radio = document.selectedForm.procon[i].value;
					$('radio').value=radio;
				}
			}
		}		//alert($('radio').value);
		if (rad_val == null) {
			rad_val = 'Pro';
		}
		if(!ipad && !iphone && !android){
			var v ="  "+instance5.e.body.innerHTML;
			v = v.fontEntities();
			v = v.styleEntities();
			$('commentText').value = v;
			$('plainTextDiv').innerHTML = v;
		}
		var comment= $('commentText').value;
		comment = comment.anchorEntities();
		comment = comment.string_create_urls();
		comment = comment.specialCharacterEntities();
		if(comment==$('resType-answer').value || comment==$('resType_comment').value || comment==$('resType_thoughts').value)
			comment=' ';
		if(comment == "<br>")$('plainTextDiv').innerHTML = ' ';
		comment = comment.strip();
		if(ipad || iphone || android){
			var msgContent = comment;			
		} else {
			var msgContent = $('plainTextDiv').textContent || $('plainTextDiv').innerText;
		}
		if(msgContent!=null){

			if (msgContent.strip() == "") {

				$('error_msg').innerHTML = $('resError_msg').value;
				$('error_msg').style.display="block";
				if(ipad || iphone || android){
					$('commentText').value = '';
				} else {
					instance5.e.body.innerHTML ='';
				}

			} else {
				/*
				 * validate the comment text against the curse words and post only if no curse words found.
				 */
				if(validateCurseFilter1(comment)) {
					for(var i=0;i<comment.length;i++){

						if(comment.charCodeAt(i)==8220){
							comment =comment.substring(0,i) + '"' + comment.substring(i+1, comment.length);
						}
						if(comment.charCodeAt(i)==8221){
							comment=comment.substring(0,i) + '"' + comment.substring(i+1, comment.length);
						}

					}
					$('commentText').value=comment;
					$('error_msg').style.display="none";
					submitForm('PaginatinDiv', document.postForm,setDetailCounts);
					// $('commentText').value = msg;

					/*
					 * @author: mkonusu @bug: DS-4090 - when posting a comment or
					 * reply and we use filter/curse keywords, a warning message
					 * displays and all entered text is removed @fix: removed
					 * clearing the text box value and moved the
					 */
					if(ipad || iphone || android){
						$('commentText').value = '';
					} else {
						instance5.e.body.innerHTML ='';
						instance5.defaultsetting();
					}
				}
			}
		}
	} catch (e) {
		alert(e);
	}

}

function cmtPageControl(startNo, pageNo) {
	$('cmtStartNo').value = startNo;
	$('cmtPageNo').value = pageNo;
	var rad_val;
	try {
		for ( var i = 0; i < document.selectedForm.procon.length; i++) {
			if (document.selectedForm.procon[i].checked) {
				rad_val = document.selectedForm.procon[i].value;
			}
		}
	} catch (e) {
		//alert(e);
		rad_val = null;
	}
	if (rad_val == null) {
		rad_val = 'Pro';
	}
	$('typeval').value = rad_val;
	submitForm('PaginatinDiv', document.paginationForm);
}
function callBackFunReply(resp) {
	//alert('callBackFunReply'+resp.responseText);
	var commentId = $('replyCommentId').value;
	if($('subcomment_' + commentId)){
		$('subcomment_' + commentId).innerHTML = resp.responseText;
		var topicId=$('replyTopicId_'+commentId).value;
		if($('popular_div_'+topicId)) 
			$('popular_div_'+topicId).innerHTML = $('resPopularity_div').value + ": "+$('replyTopicPop_'+commentId).value;
	}else{
		$('postReplyResponseDiv').innerHTML = resp.responseText;
		var topicId=$('replyTopicId_'+commentId).value;
		if($('popular_div_'+topicId)) 
			$('popular_div_'+topicId).innerHTML = $('resPopularity_div').value + ": "+$('replyTopicPop_'+commentId).value;
		$('postReplyResponseDiv').innerHTML ="";
	}

	hidereplypopup();
}
function callBackFun(resp) {
	$('parentcomment').innerHTML = resp.responseText;
}
function showtopic(id,approvalId)
{
	var android = (navigator.appVersion.indexOf("Android") == -1) ? false : true;
	var show_topic = id;
	var HideDiv = $$('.topicdesc');
    var cntOpen=1;
	var cntClose=1;
	Effect.toggle(show_topic, 'blind',{ duration: 0.5, afterFinish: expandcollapsetext })
	var ua = navigator.userAgent.toLowerCase();
	var ua_index = ua.indexOf('msie');
	var ua_version = ua.charAt(ua_index+5);
	if(ua.indexOf('msie') != -1 && ua_version < 8)
	{
		if(document.getElementById(approvalId))
		{
			if(document.getElementById(id).style.display=="none")
			{
				document.getElementById(approvalId).style.top="0px";
			}
			else
			{
				document.getElementById(approvalId).style.top="8px";
			}
		}
	}
	//to set the width and the height of the textarea in ipad ::: fix	
	if(ipad || iphone || android)
	{
		var textArea = document.getElementsByTagName('textarea');
		for(var i=0;i<textArea.length;i++){
			textArea[i].style.width = "100%";
			textArea[i].style.height = "100px";			
		}
	}     
}

function expandcollapsetext()
{
	var HideDiv = $$('.topicdesc');
 	var cntOpen=0;
	var cntClose=0;

	if($('expandall').innerHTML==$('resExpand').value ) 
	{
		$('expandall').innerHTML=$('resCollapse').value;
	} else if($('expandall').innerHTML==$('resCollapse').value ) 
	{
		$('expandall').innerHTML=$('resExpand').value;
	} else if($('expandall').innerHTML==$('resExpandAll').value)
	{
		for(var i=0; i<HideDiv.length; i++)
		{
			if(HideDiv[i].style.display === ''){				
				cntOpen++;
			}	
		}
		if (HideDiv.length === cntOpen)
		{
			$('expandall').innerHTML=$('resCollapseAll').value;
		}
	} else if($('expandall').innerHTML==$('resCollapseAll').value)
	{
		for(var i=0; i<HideDiv.length; i++)
		{
			if(HideDiv[i].style.display === 'none')
			{				
				cntClose++;
			}	
		}
		if (HideDiv.length === cntClose)
		{
			$('expandall').innerHTML=$('resExpandAll').value;
		}
	}
}
var timeout         = 500;
var closetimer		= 0;
var ddmenuitem      = 0;
var manage_obj;
//open hidden layer
function mopen(id, manage_id,manage_id2) {
	manage_obj = document.getElementById(manage_id);
	manage_obj2 = document.getElementById(manage_id2);
	if (manage_obj)
		manage_obj.className = 'manage-background';
	if(document.getElementById(manage_id2)){		
		manage_obj2.className = '';
	}
	// cancel close timer
	mcancelclosetime();
	// close old layer
	if (ddmenuitem)
		ddmenuitem.style.visibility = 'hidden';
	// get new layer and show it
	ddmenuitem = document.getElementById(id);
	ddmenuitem.style.visibility = 'visible';
}
// close showed layer
function mclose()
{
	if(manage_obj)
		manage_obj.className  = '';
	if(ddmenuitem) ddmenuitem.style.visibility = 'hidden';
}

// go close timer
function mclosetime()
{
	closetimer = window.setTimeout(mclose, timeout);
}

// cancel close timer
function mcancelclosetime()
{
	if(manage_obj)
		manage_obj.className = 'manage-background';
	if(closetimer)
	{
		window.clearTimeout(closetimer);
		closetimer = null;
	}
}

// close layer when click-out
document.onclick = mclose; 
//-->
/**
 * @Author : mmalyala
 * @Bug No : 3703
 * @Fix : new site model popup related changes.
 */
function changetab(id)
{

	if(id=='asktab')
	{
		document.askQuestionForm.reset();
		clearAskQuestionForm();
		hidetopics();
		$('newModelWindowValue').value = "true";
		$('askQuestionAlertDiv').hide();
		$('asktab').className='ask-tab-selected';
		$('invitetab').className='invite-tab-normal';
		$('customizetab').className='customize-tab-normal';
		$('curve-div').className='curves-normal';
		if($('normal-view'))
		{
			$('normal-view').show(); 
		}
		else if($('ask_question'))
		{
			$('ask_question').show(); 
		}
		$('ask_question').show();
		$('invitepeople').hide();
		$('customizeid').hide();
	}
	else if(id=='invitetab')
	{
		if($('resInvitations') != null){
			$("invitations").value =$('resInvitations').value;
		}
		$('invite_errorlist').hide();
		$('asktab').className='ask-tab-normal';
		$('invitetab').className='invite-tab-selected';
		$('customizetab').className='customize-tab-normal';
		$('curve-div').className='curves';
		$('ask_question').hide();
		$('invitepeople').show();
		$('customizeid').hide();
		if($('samplequestions')){
			$('samplequestions').hide();
		}


	}
	else if(id=='customizetab')
	{
		$('asktab').className='ask-tab-normal';
		$('invitetab').className='invite-tab-normal';
		$('customizetab').className='customize-tab-selected';
		$('curve-div').className='curves';
		$('ask_question').hide();
		$('invitepeople').hide();
		$('customizeid').show();
		if($('samplequestions')){
			$('samplequestions').hide();
		}
	}

}
function changepreviewtab(id)
{
	if(id=='preview-asktab')
	{
		$('preview-asktab').className='ask-tab-selected';
		$('preview-invitetab').className='invite-tab-normal';
		$('preview-customizetab').className='customize-tab-normal';
		$('curve-div').className='curves-normal';
		$('preview_ask_question').show();
		$('preview_invitepeople').hide();
		$('preview_customizeid').hide();
	}
	else if(id=='preview-invitetab')
	{
		if($('resInvitations') != null){
			$("invitations").value =$('resInvitations').value;
		}
		$('invite_errorlist').hide();
		$('preview-asktab').className='ask-tab-normal';
		$('preview-invitetab').className='invite-tab-selected';
		$('preview-customizetab').className='customize-tab-normal';
		$('curve-div').className='curves';
		$('preview_ask_question').hide();
		$('preview_invitepeople').show();
		$('preview_customizeid').hide();
	}
	else if(id=='preview-customizetab')
	{
		$('preview-asktab').className='ask-tab-normal';
		$('preview-invitetab').className='invite-tab-normal';
		$('preview-customizetab').className='customize-tab-selected';
		$('curve-div').className='curves';
		$('preview_ask_question').hide();
		$('preview_invitepeople').hide();
		$('preview_customizeid').show();
	}

}
function getPageSizeWithScroll()
{	
	if (window.innerHeight && window.scrollMaxY) 
	{// Firefox
		yWithScroll = window.innerHeight + window.scrollMaxY;
	xWithScroll = window.innerWidth + window.scrollMaxX;
	} else if (document.body.scrollHeight > document.body.offsetHeight)
	{ // all but Explorer Mac
		yWithScroll = document.body.scrollHeight;
	xWithScroll = document.body.scrollWidth;
	} 
	else 
	{ // works in Explorer 6 Strict, Mozilla (not FF) and Safari
		yWithScroll = document.body.offsetHeight;
	xWithScroll = document.body.offsetWidth;
	}
	//alert(yWithScroll);
	arrayPageSizeWithScroll = new Array(xWithScroll,yWithScroll);
	// alert( 'The height is ' + yWithScroll + ' and the width is ' +
	// xWithScroll );
	if(document.getElementById('PageInner')){
		document.getElementById('PageInner').value = arrayPageSizeWithScroll[1]+'px';
	}
	return arrayPageSizeWithScroll;
}

function growCommunityPopup() {
	if($('displayId'))
	{
		$('displayId').hide();
	}
	loadDivContent('pagecontent',document.getElementById("sendFriendsInvite").value+"&dt="+new Date().getTime(),seteditor);
}

function showNewMessagesPopup() {
	if($('displayId'))
	{
		$('displayId').hide();
	}
	loadDivContent('pagecontent',document.getElementById("viewMyInbox").value+"&tabView=myInboxTabView&inboxfilterBy=status&inboxfilterValues=UNREAD&dt="+new Date().getTime())
}

function showHaveQuestionPopup() {
	if($('displayId'))
	{
		$('displayId').hide();
	}
	showpopupwindow('sendmessageId');
}

function viewLoginPopup()
{
	hidePopupAlert();
	/**
	 * @Author : mmalyla
	 * @Bug : 4047 As a collaborize user, When we click on login after session
	 *      time out getting blurring screen.
	 * @Fix: login popup calling method changed to showLoginPopup(this method is
	 *       updated for browser specific poups )
	 */
	window.scrollTo(0,0);
	showLoginPopup();
}

/*
* @author: mkonusu
* @bug: DS-3963
* @fix: added code to hide forgot pwd screen
*/
function showLoginPopup() {
	document.forgotpasswordform.reset();
	$("forgot-pwd-div").style.display="none";
	$("logId").style.display="block";
	if($("loglaterId") != null){
		$("loglaterId").style.display="block";
	}
	$("forgotpassId").style.display="none";

	showpopupwindow("login-popup");
}

function viewpopup(id)
{ 
	//alert(id);
	if($('currentPopupDivId') && id != "session-message") {
		$('currentPopupDivId').value = id;
	}
	var ASk = document.getElementById('ask');
	var myPos = new Array();
	var ua = navigator.userAgent.toLowerCase();
	var ua_index = ua.indexOf('msie');
	var ua_version = ua.charAt(ua_index+5);
	if(ua.indexOf('msie') != -1 && ua_version < 8)
	{
		if(id == 'ask-new')
		{
			var myPos = new Array();
			myPos = findPos(ASk);
			var fx = myPos[0];
			var fy = myPos[1];
			$('ask-question-popup-new').style.top = fy+-31+'px';
			$('ask-question-popup-new').style.left = fx-75+'px';
			$('ask-question-popup-new').style.display = 'block'; 
			$("topicTitle").focus();
		}
		if(id == 'ask-question-edit-popup')
		{
			var myPos = new Array();
			myPos = findPos(ASk);
			var fx = myPos[0];
			var fy = myPos[1];
			$('ask-question-edit-popup').style.top = fy+-31+'px';
			$('ask-question-edit-popup').style.left = fx-65+'px';
			$('ask-question-edit-popup').style.display = 'block'; 
		}
		if(id == 'ask-question-preview-popup')
		{
			var myPos = new Array();
			myPos = findPos(ASk);
			var fx = myPos[0];
			var fy = myPos[1];
			$('ask-question-preview-popup').style.top = fy+-31+'px';
			$('ask-question-preview-popup').style.left = fx-65+'px';
			$('ask-question-preview-popup').style.display = 'block'; 
			$('preview-opacitydiv').style.width = $("opacitydiv").style.width;
			$('preview-opacitydiv').style.height = $('ask-question-preview-popup').offsetHeight+'px';
			$("preview-opacitydiv").style.visibility = 'visible';
		}

	}
	else
	{
		if(id == 'ask-new')
		{
			var myPos = new Array();
			myPos = findPos(ASk);
			var fx = myPos[0];
			var fy = myPos[1];
			$('ask-question-popup-new').style.top = fy+-29+'px';
			$('ask-question-popup-new').style.left = fx+-7+'px';
			$('ask-question-popup-new').style.display = 'block';  
			$("topicTitle").focus();
		}
		if(id == 'ask-question-edit-popup')
		{
			//alert('123');
			var myPos = new Array();
			myPos = findPos(ASk);
			var fx = myPos[0];
			var fy = myPos[1];
			$('ask-question-edit-popup').style.top = fy+-29+'px';
			$('ask-question-edit-popup').style.left = fx+-7+'px';
			$('ask-question-edit-popup').style.display = 'block';  
		}
		if(id == 'ask-question-preview-popup')
		{
			var myPos = new Array();
			myPos = findPos(ASk);
			var fx = myPos[0];
			var fy = myPos[1];
			$('ask-question-preview-popup').style.top = fy+-29+'px';
			$('ask-question-preview-popup').style.left = fx+-7+'px';
			$('ask-question-preview-popup').style.display = 'block';  
			$('preview-opacitydiv').style.width = $("opacitydiv").style.width;
			$('preview-opacitydiv').style.height = $('ask-question-preview-popup').offsetHeight+'px';
			$("preview-opacitydiv").style.visibility = 'visible';
		}
	}
	$("opacitydiv").style.visibility = 'visible';
	var dimensions = getPageSizeWithScroll();
	$("opacitydiv").style.width = dimensions[0];
	$("opacitydiv").style.height = document.getElementById('PageInner').value;
}

/*
@Author : gkottala
@Bug No:  DS-4190,  As an Account Owner, when I send invites, then cancel before sending, the text that was entered in the Customize invite note/message is blanked out along with all of the email addresses. 
@Fix : Show the browser when click on cancel button.
*/ 
function clearEmailFileName(){

	document.getElementById('emailFilename').value = "";
	document.getElementById('displayFilename').style.display="none";
	document.getElementById('importEmail').style.display="block";
	document.getElementById('textId').style.display="block";
	$('invalidFile').style.display = "none";
}

/*
@Author : gkottala
	@Bug No:  DS-4190,  As an Account Owner, when I send invites, then cancel before sending, the text that was entered in the Customize invite note/message is blanked out along with all of the email addresses. 
	@Fix : Show the default not message when click on close button after sending the invititions. 
 */ 
function showDefaultMsg(){
	instance7.e.body.innerHTML = document.getElementById('defaultNote').value;
}

function hidepopup(id)
{
	/*
	* @author: mkonusu
	* @purpose: used to hide popup when session expire popup opens
	* if hidden popup is not session expire popup then clear current displayed popup div id. 
	*/
	var android = (navigator.appVersion.indexOf("Android") == -1) ? false : true;
	if($('currentPopupDivId')) {
		if($('isSessionExpirePopupOpened').value == ""  && $('currentPopupDivId').value == id && $('currentPopupDivId').value!= "session-message") {
			$('currentPopupDivId').value = "";
		}
		//alert("after hidepopup "+$('currentPopupDivId').value);
	}

	/*
	 * @author: mkonusu
	 * @purpose: used to hide popup when session expire popup opens
	 * hide div id for ask-question popup is different. Setting correct value to hide the div.
	 */
	if(id == "ask-new") {
		id = "ask-question-popup-new";
	} else if(id == "ask-question-popup-new") {
		if($('currentPopupDivId')) {
			$('currentPopupDivId').value = "";
		}
	}
	$(id).style.display = 'none';
	divs_transparentDiv.style.display="none";
	if($('opacitydiv'))
	{
		$('opacitydiv').style.visibility="hidden";
	}
	if($('showMsgResult'))
	{
		$('showMsgResult').hide();
	}
	if(divs_transparentDiv)
	{
		divs_transparentDiv.style.display="none";
	}
	if(id == 'delete-popup'){
		document.getElementById("deleteDesc").value=" ";

		if(document.getElementById("actionTopicId") != null){
			var val = document.getElementById("actionTopicId").value;
			$(val).selectedIndex = 0;
		}
	}
	if($('msgcontent'))
	{
		if(instance3 && !ipad && !iphone && !android){
			instance3.e.body.innerHTML ='&nbsp;';
		}
	}
	if($('promoteDesc'))
	{
		if(instance5!=null && !ipad && !iphone && !android){
			instance5.e.body.innerHTML ='&nbsp;';
		}
	}
	if($("promoteMesg"))
	{
		if(ipad || iphone || android){
			$("promoteMesg").innerHTML = "";
		} else { 
			$("promoteMesg").innerHTML = "&nbsp;";
		}
	}
	if(id == 'deletealert-popup'){
		if(document.getElementById("actionTopicId") != null){
			var val = document.getElementById("actionTopicId").value;
			// $(val).selectedIndex = 0;

		}
	}
	if(id == 'replydeletealert-popup'){
		if(document.getElementById("actionTopicId") != null){
			var val = document.getElementById("actionTopicId").value;
		}
	}
	if(id == 'rolechangealert-popup'){
		if(document.getElementById("actionTopicId") != null){
			var val = document.getElementById("actionTopicId").value;
			alert(val);
		}
	}
	if(id == 'rolechangealert-popup'){
		if(document.getElementById("actionTopicId") != null){
			var val = document.getElementById("actionTopicId").value;
			alert(val);
		}
	}
	if(id == 'broadcastId'){
		document.getElementById("brshowMsgResult").style.display = 'none';
		document.getElementById("brsubject").value="";
		document.getElementById("brmsgcontent").value="";
	}
	/*  * @author gkottala
	* @bug: resend status message is not hiding when click on cancel 
	* @fix: Hide the resend status message when click on cancel 
	*/ 
	if(id == 'resendInviteId'){
		$("invite_status").innerHTML ='';
		$("invite_status").hide();
	}
	if(id == 'notificationPopupId'){
		document.getElementById("errorMessageDetails").innerHTML="";
		document.getElementById("errorMessageDetails").style.display="none";
	}
}
function hidestartsitepopup(id)
{
	$("opacitystart-popup").style.visibility = 'hidden';
	$(id).style.display = 'none';
}
function questionsubmit()
{
	$('ask_question_conformation').style.display = 'block';	
}

function showdiscription(id1,id2)
{
	$(id1).show();
	$(id2).hide();
}
/* @author pgudipalli

* @bug:   DS-3883

* @fix: Getting page height and width functionality */ 

function getPageSizeWithScroll(){	
	if (window.innerHeight && window.scrollMaxY) {// Firefox
		yWithScroll = window.innerHeight + window.scrollMaxY;
	xWithScroll = window.innerWidth + window.scrollMaxX;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		yWithScroll = document.body.scrollHeight;
	xWithScroll = document.body.scrollWidth;
	} else { // works in Explorer 6 Strict, Mozilla (not FF) and Safari
		yWithScroll = document.body.offsetHeight;
	xWithScroll = document.body.offsetWidth;
	}
	arrayPageSizeWithScroll = new Array(xWithScroll,yWithScroll);
	// alert( 'The height is ' + yWithScroll + ' and the width is ' +
	// xWithScroll );
	document.getElementById('PageInner').value = arrayPageSizeWithScroll[1]+'px';
	return arrayPageSizeWithScroll;
}
window.onresize = function(){repositionTransparentDiv();}
window.onscroll = function(){repositionTransparentDiv();}
var divs_transparentDiv = document.createElement('div');
var divs_transparentcharDiv = document.createElement('div');
var divs_opacityDiv = document.createElement('div');
var popupDivEdit = document.createElement('div');
var popupDiv;
var bodyWidth;
var bodyHeight;

/*
 * @author pgudipalli
 * 
 * @bug: DS-3883
 * 
 * @fix: Creation of opacity div
 */ 

function __overlay(id)
{
	var brSize = getPageSizeWithScroll();
	bodyWidth = brSize[0];
	bodyHeight = brSize[1];
	divs_transparentDiv.style.width=bodyWidth+'px';
	var ua = navigator.userAgent.toLowerCase();if(ua.indexOf('msie') != -1){divs_transparentDiv.style.height=bodyHeight+'px';}else{divs_transparentDiv.style.height=window.outerHeight+'px';}
	divs_transparentDiv.className ='transparentdiv';
	if(id == 'confirmbox-preview' || id == 'confirmbox'){
		divs_transparentDiv.className ='transparentdiv';
	}
	document.body.appendChild(divs_transparentDiv);
	divs_transparentDiv.style.display="block";
}
function __overlaycharpopup(id)
{
	var brSize = getPageSizeWithScroll();
	bodyWidth = brSize[0];
	bodyHeight = brSize[1];
	divs_transparentcharDiv.style.width=bodyWidth+'px';
	divs_transparentcharDiv.style.height=bodyHeight+'px';
	divs_transparentcharDiv.className ='transparentdiv-charpopup';
	document.body.appendChild(divs_transparentcharDiv);
	divs_transparentcharDiv.style.display="block";
}
function __overlayloader(id)
{
	var brSize = getPageSizeWithScroll();
	bodyWidth = brSize[0];
	bodyHeight = brSize[1];
	divs_opacityDiv.style.width=bodyWidth+'px';
	var ua = navigator.userAgent.toLowerCase();if(ua.indexOf('msie') != -1){divs_opacityDiv.style.height=bodyHeight+'px';}else{divs_opacityDiv.style.height=window.outerHeight+'px';}
	divs_opacityDiv.className ='transparentdiv-loader';
	document.body.appendChild(divs_opacityDiv);
	divs_opacityDiv.style.display="block";
}
/* @author pgudipalli

* @bug:   DS-3883

* @fix: Reposition of opacity div */ 

function repositionTransparentDiv()
{
	var brSize = getPageSizeWithScroll();
	bodyWidth = brSize[0];
	bodyHeight = brSize[1];
	if(popupDiv)
	{
		var popupWidth=popupDiv.clientWidth;
		divs_transparentDiv.style.width=bodyWidth+'px';
		divs_transparentDiv.style.height=bodyHeight+'px';
		popupDiv.style.left=(bodyWidth-popupWidth)/2+'px';
		popupDiv.style.top='100px';
	}
	else if(divs_opacityDiv)
	{
		divs_opacityDiv.style.width=bodyWidth+'px';
		divs_opacityDiv.style.height=bodyHeight+'px';
	}
}

/* @author pgudipalli

* @bug:   DS-3883

* @fix: Popup position functionality */ 

function showpopupwindow(id)
{
	if(document.getElementById('loader'))
	{
		hideloader();
	}
	/*
	* @author: mkonusu
	* @purpose: used to show popup when session expire popup closes to extend
	* if session extends the show the currently displayed popup. 
	* Before opening session expire popup, if current displayed popup exists then store the divid as a hidden value.
	*/
	if(id == "ask-new") {
		viewpopup(id);
		return;
	} else if(id == "ask-question-edit-popup") {
		showtopiceditpreview();
		return;
	} else if(id == "confirmbox") {
		showalert();	
		return;
	} else if(id == "confirmbox-preview") {
		showtopicpreview();
		return;
	}
	if(id == "ask-question-popup") {
		$('newModelWindowValue').value = "true";

		var typeList = $("typelist").getElementsByTagName('li');

		if(typeList != null){

			if(typeList.length>2){
				$('multiQuesType').show();
			}else if(typeList.length==2){
				if(typeList[0].id!="multiplechoice"){
					$('multiQuesType').show();
				}else{
					$('singleQuesType').show();
				}
			}else{
				$('singleQuesType').show();
			}
		}
	}
	if(id=='notificationPopupId' && ipad || iphone || android){
		var txtArea =  document.getElementById('msgcontent');
		txtArea.style.width="100%";		
	}

	if($('currentPopupDivId') && id != "session-message") {
		$('currentPopupDivId').value = id;
	}
	if(id== 'login-popup')
	{
		clearLoginForm();
	}
	if($('widget-preview'))
	{
		hidewidget();
	}
	if(id=="promote-popup")
	{
		window.scrollTo(0,0);
		if(ipad || iphone || android)
		{
			var txtArea =  document.getElementById('promoteDesc');
			txtArea.style.width="100%";
			txtArea.style.height="100px";
		}
	}
	popupDiv=$(id);
	__overlay(id);
	popupDiv.style.display='block';
	var popupWidth=popupDiv.clientWidth;
	var popupHeight=popupDiv.clientHeight;
	popupDiv.style.left=(bodyWidth-popupWidth)/2+'px';
	popupDiv.style.top='100px';
	if(id == 'classroom-preview-popup')
	{
		$('preview-opacitydiv').style.width = $("opacitydiv").style.width;
		$('preview-opacitydiv').style.height = $('classroom-preview-popup').offsetHeight+'px';
		$("preview-opacitydiv").style.visibility = 'visible';
	}
	if(id == 'ask-question-preview-popup-model')
	{
		$('preview-opacitydiv').style.width = $("opacitydiv").style.width;
		$('preview-opacitydiv').style.height = $('ask-question-preview-popup-model').offsetHeight-55+'px';
		$("preview-opacitydiv").style.visibility = 'visible';
	}
}
/* @author pgudipalli

* @bug:   DS-3883

* @fix: Finding popup position */ 

function findPos(obj)
{
	var curleft = curtop = 0;
	if (obj.offsetParent)
	{
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		while (obj = obj.offsetParent)
		{
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
	}
	return [curleft,curtop];
}
var instance5;
var instance2;
function setinstance()
{
	var android = (navigator.appVersion.indexOf("Android") == -1) ? false : true;
	if($('commentText')){
		if(ipad || iphone || android){
			var txtArea = document.getElementById('commentText');
			txtArea.style.width = '100%';
			txtArea.style.height = '120px';
			txtArea.style.marginTop = '10px';
		} else {
			instance5 = new TINY.editor.edit('editor5',{
				id:'commentText',
				width:625,
				height:124,
				cssclass:'te',
				controlclass:'tecontrol',
				rowclass:'teheader',
				dividerclass:'tedivider',
				controls:['bold','italic','underline','strikethrough','|','subscript','superscript','|','charmap','|','link','|',
				          'orderedlist','unorderedlist','|','outdent','indent','|','leftalign','centeralign','rightalign','blockjustify'],
				          footer:false,
				          xhtml:true,
				          css:'body{background-color:#fff;font-family:Arial, Helvetica, sans-serif;font-size:13px;padding:0px;margin:0px;}',
				          bodyid:'editor5',
				          footerclass:'tefooter'
			});	
		}
	}
	if($('subcommentText')){
		if(!ipad && !iphone && !android){
			instance2 = new TINY.editor.edit('editor2',{
				id:'subcommentText',
				width:560,
				height:104,
				cssclass:'te',
				controlclass:'tecontrol',
				rowclass:'teheader',
				dividerclass:'tedivider',
				controls:['bold','italic','underline','strikethrough','|','subscript','superscript','|','charmap','|','link','|',
				          'orderedlist','unorderedlist','|','outdent','indent','|','leftalign','centeralign','rightalign','blockjustify'],
				          footer:false,
				          xhtml:true,
				          css:'body{background-color:#fff;font-family:Arial, Helvetica, sans-serif;font-size:13px;padding:0px;margin:0px;}',
				          bodyid:'editor2',
				          footerclass:'tefooter'
			});
		}
	}
}

var replyScreenName;
function showreplypopup(commentId,screenName)
{  
	var android = (navigator.appVersion.indexOf("Android") == -1) ? false : true;
	window.scrollTo(0,0);
	if(instance2==null){
		if($('subcommentText')){
			if(ipad || iphone || android){
				var txtArea = document.getElementById('subcommentText');
				txtArea.style.width = '560px';
				txtArea.style.height = '120px';
			} else {
				instance2 = new TINY.editor.edit('editor2',{
					id:'subcommentText',
					width:560,
					height:104,
					cssclass:'te',
					controlclass:'tecontrol',
					rowclass:'teheader',
					dividerclass:'tedivider',
					controls:['bold','italic','underline','strikethrough','|','subscript','superscript','|','charmap','|','link','|',
					          'orderedlist','unorderedlist','|','outdent','indent','|','leftalign','centeralign','rightalign','blockjustify'],
					          footer:false,
					          xhtml:true,
					          css:'body{background-color:#fff;font-family:Arial, Helvetica, sans-serif;font-size:13px;padding:0px;margin:0px;}',
					          bodyid:'editor2',
					          footerclass:'tefooter'
				});
			}
		}
	}
	$('replyCommentId').value=commentId;
	//$('screenId').innerHTML=screenName;
	replyScreenName = screenName;
	var eHTML="";
	eHTML+=$('replying-to').value;
	eHTML+="   <span>"+replyScreenName+"</span>";
	$('replymsg').innerHTML=eHTML;
	showpopupwindow('reply-popup');
}
function replyComment(){
	var android = (navigator.appVersion.indexOf("Android") == -1) ? false : true;
	try{
		if(ipad || iphone || android){
			var replyComment=document.getElementById('subcommentText').value;
		}	
		else {
			var v ="  "+instance2.e.body.innerHTML;
			v = v.fontEntities();
			v = v.styleEntities();
			var replyComment=v;
			$('plainTextDiv').innerHTML = v;
			replyComment = replyComment.anchorEntities();
			replyComment = replyComment.string_create_urls();
			replyComment = replyComment.specialCharacterEntities();
		}	
		replyComment=replyComment.strip();
		if(ipad || iphone || android){
			var msgContent = replyComment;			
		} else {
			var msgContent = $('plainTextDiv').textContent || $('plainTextDiv').innerText;
		}
		if(replyComment == "<br>"){msgContent = ' ';}
		if(msgContent!=null){
			if(msgContent.strip() == ""){
				//$('replymsg').show();
				//$('replymsg').innerHTML=$('resReply_msg').value;
				var eHTML="";
				eHTML+=$('replying-to').value;
				eHTML+="   <span>"+replyScreenName+"</span>";
				eHTML+="<span style='color:#FF0000; margin: 10px 0pt 10px 20px ! important;'>"+$('resReply_msg').value+"</span>";
				$('replymsg').innerHTML=eHTML;

			}
			else
			{	
				/*
				 * validate the comment text against the curse words and post only if no curse words found.
				 */			
				if(validateCurseFilter1(replyComment)) {
					var v1 = replyComment;
					for(var i=0;i<v1.length;i++){

						if(v1.charCodeAt(i)==8220){
							v1 = v1.substring(0,i) + '"' + v1.substring(i+1, v1.length);
						}

						if(v1.charCodeAt(i)==8221){
							v1 = v1.substring(0,i) + '"' + v1.substring(i+1, v1.length);
						}
					}
					$('subcommentText').value=v1;
					//$('replymsg').style.display ="none";
					$('replymsg').innerHTML="";
					var eHTML="";
					eHTML+=$('replying-to').value;
					eHTML+=" <span>"+replyScreenName+"</span>";
					$('replymsg').innerHTML=eHTML;
					postForm(document.replyForm,callBackFunReply);
					$('subcommentText').value="";
					hidereplypopup();

					/*
					 * @author: mkonusu @bug: DS-4090 - when posting a comment or
					 * reply and we use filter/curse keywords, a warning message
					 * displays and all entered text is removed @fix: removed
					 * clearing the text box value and moved the
					 */

					if(!ipad && !iphone && !android){
						instance2.e.body.innerHTML ='';	
						instance2.defaultsetting();
					}
				}
			}
		}}catch(e){alert(e);}
		//document.replyForm.submit();
}

function uploadPhoto(){
	//postForm(document.uploadPhotoForm,callBackuploadFile);
	var fileName=$('filePath').value.strip();
	var pattern=new Array();
	pattern[0]=/.bmp/;
	pattern[1]=/.png/;
	pattern[2]=/.gif/;
	pattern[3]=/.jpeg/;
	pattern[4]=/.JPG/;
	var matchPos1 =null;
	for(var i=0;i<pattern.length;i++){
		matchPos1=fileName.search(pattern[i]);
		if(matchPos1!=null && matchPos1!=-1)break;
	}
	/* if(matchPos1==-1)matchPos1 =fileName.search(/.png/);
	if(matchPos1==-1)matchPos1 =fileName.search(/.gif/);
	if(matchPos1==-1)matchPos1 =fileName.search(/.jpeg/);
	if(matchPos1==-1)matchPos1 =fileName.search(/.JPG/);*/
	if(matchPos1 != -1){
		document.uploadPhotoForm.submit();
	}else{
		$('errorUpload').innerHTML=$('resError_Upload').value;
	}

}
function callBackuploadFile(resp){
	alert('back');
}
function hidereplypopup()
{
	var android = (navigator.appVersion.indexOf("Android") == -1) ? false : true;
	$('subcommentText').value="";
	if(!ipad && !iphone && !android){
		instance2.e.body.innerHTML ='';	
		instance2.defaultsetting();
	}
	divs_transparentDiv.style.display="none";
	document.getElementById("reply-popup").style.display = 'none';
	$('replymsg').innerHTML="";
	var eHTML="";
	eHTML+=$('replying-to').value;
	eHTML+=" <span>"+replyScreenName+"</span>";
	$('replymsg').innerHTML=eHTML;
}
function viewaddtopics(id1,id2,id3)
{
	if(!id3)
	{
		$('hourField').options[0].selected=true;
		$('minuteField').options[0].selected=true;
		$('ampmField').options[0].selected=true;
		$('dateFieldVal').value="";
		$('dateField').value="";
		$(id1).show();
		$(id2).hide();
	}
	else
	{
		$(id1).show();
		$(id2).hide();
		$(id3).show();
	}
}
function closeaddtopics(id1,id2,id3)
{
	if(!id3)
	{
		$('hourField').options[0].selected=true;
		$('minuteField').options[0].selected=true;
		$('ampmField').options[0].selected=true;
		$('dateFieldVal').value="";
		$('dateField').value="";
		$(id1).hide();
		$(id2).show();
	}
	else
	{
		$(id1).hide();
		$(id2).show();
		$(id3).hide();
	}
}

function loginAlertMsg(){
	var msg = $('resPopup-alert').value+"<br><a href='javascript:viewLoginPopup();'> "+$('resPopup-login').value+" "+$('resPopup-now').value+" </a> ";
	var action="<a href='javascript:hidePopupAlert();'>"+$('resPopup-close').value+"</a>";
	showPopupAlert(msg, action);
}
function showPopupAlert(msg, action){
	$('popup-alert').innerHTML = msg;
	$('popup-alert-action').innerHTML = action;
	showpopupwindow('login-message');
}
function showLogoutPopupAlert(msg){
	var msg = msg + "<br><a href='javascript:viewLoginPopup();'> "+$('resPopup-login').value+" "+$('resPopup-now').value+"</a>";
	var action = "<a href=\'javascript:hidePopupAlert();\'>"+$('resPopup-close').value+".</a>";
	$('popup-alert').innerHTML = msg;
	$('popup-alert-action').innerHTML = action;
	showpopupwindow('login-message');
}
function showLoginPopupAlert(msg){
	var action = "<a href=\'javascript:hidePopupAlert();\'>"+$('resPopup-close').value+".</a>";
	$('popup-alert').innerHTML = msg;
	$('popup-alert-action').innerHTML = action;
	showpopupwindow('login-message');
}
function hidePopupAlert(){
	$('popup-alert').innerHTML = "";
	$('popup-alert-action').innerHTML = "";
	hidepopup('login-message');
}
/*function addRow(tableID) 
{
	var table = $(tableID);
	var rowCount = table.rows.length;
	var row = table.insertRow(rowCount);
	$("rowCount").value = rowCount + 1;

	var cell1 = row.insertCell(0);
	cell1.innerHTML='Choice'
		cell1.className='mutli-choice-text';
	row.id="rowId["+ (rowCount+1) +"]";


	var cell2 = row.insertCell(1);
	cell2.innerHTML = rowCount + 1;
	cell2.className='mutli-choice-text';

	var cell3 = row.insertCell(2);
	cell3.innerHTML=':' 
		cell3.className='mutli-choice-text';

	var cell4 = row.insertCell(3);
	var element1 = document.createElement("input");
	element1.type = "text";
	element1.name = "optionId["+ (rowCount+1) +"]";
	element1.id = "optionId["+ (rowCount+1) +"]";	
	element1.setAttribute("maxLength", "140"
			themeId = objs[i].value;
	themeName = objs[i].id;
	break;
	);
	element1.setAttribute("size", "40");
	element1.setAttribute("onkeyup", "return ismaxlength(this)");
	cell4.appendChild(element1);
	cell4.className='mutli-choice-textfield';

	var cell5 = row.insertCell(4); 
	cell5.id = "errorMultiChoiceId["+ (rowCount+1) +"]";
	cell5.className='error-multichoice-msg';
	$('noofOptions').value=rowCount+1;
}*/
function addRow(tableID) 
{
	var table = document.getElementById(tableID); 

	var rowCount = table.rows.length;
	var row = table.insertRow(table.rows.length);
	$("rowCount").value = table.rows.length;

	var cell1 = row.insertCell(0);
	cell1.innerHTML=$('resCell').value;
	cell1.className='mutli-choice-text';
	row.id="rowId["+ (rowCount+1) +"]";

	var cell2 = row.insertCell(1);
	cell2.innerHTML = "&nbsp;";
	cell2.className='mutli-choice-text';

	var cell3 = row.insertCell(2);
	var element2 = document.createElement("input");
	element2.type = "text";
	element2.name = "optionId["+ (rowCount+1) +"]";
	element2.id = "optionId["+ (rowCount+1) +"]";	
	element2.setAttribute("maxLength", "140");
	element2.setAttribute("onkeyup", "return ismaxlength(this)");
	element2.setAttribute("onkeydown", "removeErrorMessage('askQuestionAlertDiv');");
	cell3.appendChild(element2);
	cell3.className="choice";

	var cell4 = row.insertCell(3);
	cell4.innerHTML = "<div onclick='javascript:deleteRow(this);removeErrorMessage(\"askQuestionAlertDiv\");' class='delete-icon'>x</div>";

	var cell5 = row.insertCell(4); 
	cell5.id = "errorMultiChoiceId["+ (rowCount+1) +"]";
	cell5.className='error-multichoice-msg';
	$('noofOptions').value=rowCount+1;	

	/*
	 * Author : vveerabathini New Feature : DS-4232 Added code updating
	 * multiple choice selection drop down based on choices.
	 */
	/**
	 * Author : vveerabathini Feature : 4232 Subtask 4539 Enable/Disable the
	 * dropdown based on select/deselect the "Allow Multiple Choice
	 * Selections Up To Box" and Update drop down based choice addition and
	 * deletion. fix : Added code populate dropdown based selection of allow
	 * multiple choice box
	 */		
	var multiSelVal = 2;
	if($('multipleChoiceId').value!=null) {
		multiSelVal = $('multipleChoiceId').value;
	}
	if($('multipleChoiceId').disabled)
	{			
		var sHTML = "<select id='multipleChoiceId' name='multipleChoiceId' disabled>";
		var cnt = rowCount+1;
		var len = cnt+1;
		var ofText = $('ofText').value;
		for(var i=1;i<len;i++) {
			sHTML +="<option value='"+i+"'>"+i+" "+ofText+" "+cnt+"</option>";
		}
		sHTML +="</select>";
		$('multiplechoiceseldetail').innerHTML = sHTML;
		if(cnt<multiSelVal) {
			multiSelVal = cnt;
		}
		$('multipleChoiceId').options[multiSelVal-1].selected=true;
	} else {
		var sHTML = "<select id='multipleChoiceId' name='multipleChoiceId'>";
		var cnt = rowCount+1;
		var len = cnt+1;
		var ofText = $('ofText').value;
		for(var i=1;i<len;i++) {
			sHTML +="<option value='"+i+"'>"+i+" "+ofText+" "+cnt+"</option>";
		}
		sHTML +="</select>";
		$('multiplechoiceseldetail').innerHTML = sHTML;
		if(cnt<multiSelVal) {
			multiSelVal = cnt;
		}
		$('multipleChoiceId').options[multiSelVal-1].selected=true;
	}

}
function changenormalbackground(ele)
{
	ele.className='tabmain-hover';

}
function changehoverbackground(ele)
{
	ele.className='tabmain';

}

function playHelpVideo() {
	if($('displayId'))
	{
		$('displayId').hide();
	}
	if(document.getElementById("currentSiteType").value == 1) {
		if(document.getElementById("logUserId").value == 0) {
			showpopupwindow("video-play-user");
		} else {
			showpopupwindow("video-play-moderator");
		}
	} else {
		showpopupwindow("cringley-video-play-user");
	}
}

function playCringelyHelpVideo() {
	if($('displayId'))
	{
		$('displayId').hide();
	}
	showpopupwindow("cringley-video-play-user");
}

function playModeratorHelpVideo() {
	if($('displayId'))
	{
		$('displayId').hide();
	}
	showpopupwindow("video-play-moderator");
}

function showReachCommunityPopup() {
	document.getElementById("newmsgsubject").value="";
	document.getElementById("newmsgcontent").value="";
	document.getElementById("sendmessageId").style.display="none";
	document.getElementById("showMsgResult").innerHTML = "";
	document.getElementById("showMsgResult").style.display="none";	
	var groupitems = document.getElementsByName("groupSequence");
	//$("entirecommunity").checked = true;
	for(i=0;i<groupitems.length;i++)
	{
		groupitems[i].checked = false;       
	}
	showpopupwindow('sendmessageId');
}

function showCommunicateModPopup() {
	if($('displayId'))
	{
		$('displayId').hide();
	}
	showpopupwindow('sendmessageId');
}

function showPublishedTopicsPopup() {
	if($('displayId'))
	{
		$('displayId').hide();
	}
	showloader();
	changeStatusTab(5,document.getElementById("listTopics").value+"&dt="+new Date().getTime());
}

function showModGrowCommunity() {
	if($('displayId'))
	{
		$('displayId').hide();
	}
	loadDivContent('pagecontent',document.getElementById("inviteUsers").value+"&dt="+new Date().getTime(),seteditor);
}

function showApprovedMembers() {
	if($('displayId'))
	{
		$('displayId').hide();
	}
	loadDivContent('pagecontent',document.getElementById("manageUsers").value+"&status=QUEUED&changestatus=APPROVE&dt="+new Date().getTime());
}

function showApprovedTopics() {
	changeListingTab(4,document.getElementById("listTopics").value+"&dt="+new Date().getTime());
}

function changevalue(ele)
{

	if($('logUserId').value=="0" || $('logUserId').value==0) { 
		showLogoutPopupAlert("<spring:message code='collaborize.login.post.comment'/>");
	} else  { 

		if($('resType_comment') !=null && (ele.value==$('resType_comment').value)||($('resType-answer')!= null && ele.value==$('resType-answer').value)||($('resType_thoughts')!=null && ele.value==$('resType_thoughts').value)|| ele.value == 'Tell your community about the results' || ele.value=="Enter your friends email Id's" || ele.value=="Separate email addresses with a comma" || ele.value=="Enter screen name, email, first name or last name" ||ele.value == "I have been using collaborize site tool for some time and I am finding it  interesting. I would like to invite you to join us by following the link below")
		{
			ele.value='';
		} else if(ele.value=='')
		{
			if(ele.id=="searchReportUser" || ele.id=="searchUser" || ele.id=="searchGroupUser" )
			{
				ele.value="Enter screen name, email, first name or last name";
			}
		}
		ele.style.color='#333333';		
	}
}

function showcoustomize(id)
{
	showpopupwindow('ask-question-popup');
	changetab('customizetab');
	hidepopupconfirm();
	if(id=='yes')
	{

		$('customize_theme_conformation').style.display='block';
	}
	else
	{
		$('customize_theme_conformation').style.display='none';
	}
}

function hidepopupconfirm()
{
	$('confirmbox').style.display='none';
	$("opacitycoinfirmdiv").style.visibility = 'hidden';
}
/*user management*/

function viewUserDetails(url,userId,state){

	loadDivContent('result',url+'&userId='+userId,function(){showUserDetailsResult(state)});
}
function showUserDetailsResult(ele){

	var data = trim(document.getElementById("result").innerHTML);
	showpopupwindow('userdetailspopup');
	var details = data.split("#!");
	// document.getElementById("userdetailspopup").style.display="block";
	document.getElementById("udfname").innerHTML=details[0];
	document.getElementById("udlname").innerHTML=details[1];
	if(ele=='active') {
		document.getElementById("udsname").innerHTML=details[2];	
		document.getElementById("udpassword").innerHTML="******";
	} else {
		document.getElementById("udsname").innerHTML="";	
		document.getElementById("udpassword").innerHTML="";
	}
	document.getElementById("udemail").innerHTML=details[3];
}

function trim (str) {
	return str.replace(/^[\ ]{1,}/,"").replace(/[\ ]{1,}$/,"");

} 

function sendBroadcast(url,divId,ele){
	var emailIds=$('emailIds').value;
	url=url+'&ids='+emailIds;
	var subject=trim(document.getElementById("brsubject").value);
	var content=trim(document.getElementById("brmsgcontent").value);
	if(subject==""){
		document.getElementById("brsubject").focus();
		document.getElementById("brshowMsgResult").innerHTML="<p>"+$('resEnter_subject').value+"</p>";
		document.getElementById("brshowMsgResult").style.display="block";
		return ;
	}
	/*
 			 @Author : mmalyala
 			 @Bug No : 3865
	 		 @Fix    : subject length validation condition and message added. 		 	
	 */
	if(subject.length>150){
		document.getElementById("brsubject").focus();
		document.getElementById("brshowMsgResult").innerHTML="<p>"+$('resEnter_subject_length').value+"</p>";
		document.getElementById("brshowMsgResult").style.display="block";
		return ;
	}
	if(content==""){
		document.getElementById("brmsgcontent").focus();
		document.getElementById("brshowMsgResult").innerHTML="<p>"+$('resEnter_message').value+"</p>";
		document.getElementById("brshowMsgResult").style.display="block";
		return ;
	}
	if(validateCurseFilter1(content)&&validateCurseFilter1(subject)){
		/**
		 * @Author : mmalyala
		 * @Bug No : 4442 As any user, I should always receive community messages in my inbox.
		 * @Fix    : parameter name messageText changed to content.	 	
		 */
		url +="&subject="+escape(subject)+"&content="+escape(content); 
		loadDivContent(divId,url,function(){showBroadcastResult(ele,url)});


	}
}

function showBroadcastResult(ele,url){
	var android = (navigator.appVersion.indexOf("Android") == -1) ? false : true;
	if(!ipad && !iphone && !android){
		msginstance.e.body.innerHTML="";
	}
	document.getElementById("newmsgsubject").value="";
	document.getElementById("newmsgcontent").value="";
	document.getElementById("showMsgResult").style.display="block";		
	document.forms[0].reset();
	/*
	 * @Author : pgudipalli @Bug No : 3884 @Fix : hiding the overlay div.
	 */


	hidepopup('sendmessageId');
	$("sendBroadCastAncher").href="javascript:sendMessageSelection('"+url+"','result',this);disablethis('sendBroadCastAncher');";
	$("sendBroadCastAncher").className="button small primary vote"; 
}
function sendMsgToModerator(url,divId,ele){
	try{
		//alert(url+'  '+divId);
		var subject=trim(document.getElementById("mosubject").value);
		var content=trim(document.getElementById("momsgcontent").value);
		if(subject==""){
			document.getElementById("mosubject").focus();
			document.getElementById("moshowMsgResult").innerHTML="<p>"+$('resEnter_subject').value+"</p>";
			document.getElementById("moshowMsgResult").style.display="block";
			return ;
		}
		/*
 			 @Author : mmalyala
 			 @Bug No : 3865
	 		 @Fix    : subject length validation condition and message added. 		 	
		 */
		if(subject.length>150){
			document.getElementById("mosubject").focus();
			document.getElementById("moshowMsgResult").innerHTML="<p>"+$('resEnter_subject_length').value+"</p>";
			document.getElementById("moshowMsgResult").style.display="block";
			return ;
		}
		if(content==""){
			document.getElementById("momsgcontent").focus();
			document.getElementById("moshowMsgResult").innerHTML="<p>"+$('resEnter_message').value+"</p>";
			document.getElementById("moshowMsgResult").style.display="block";
			return ;
		}
		if(validateCurseFilter1(content)&&validateCurseFilter1(subject)){
			url +="&subject="+escape(subject)+"&content="+escape(content);
			loadDivContent(divId,url,function(){showMoMsgResult(ele)});
		}  
	}catch(e){
		alert(e);
	}
}
function showMoMsgResult(ele){
	//alert(ele);
	document.getElementById("mosubject").value="";
	document.getElementById("momsgcontent").value="";
	document.getElementById("moshowMsgResult").style.display="none";		
	document.forms[0].reset();
	document.getElementById("messagetomoderatorId").style.display="none";  
	divs_transparentDiv.style.display="none";
}
function closeModeratorPopup(){ 
	divs_transparentDiv.style.display="none";
	document.getElementById("mosubject").value="";
	document.getElementById("momsgcontent").value="";
	document.getElementById("messagetomoderatorId").style.display="none";
	document.getElementById("moshowMsgResult").style.display="none";
}
function sendModeratorMsg(url,divId,ele){
	var subject=trim(document.getElementById("mmsubject").value);
	var content=trim(document.getElementById("mmmsgcontent").value);
	if(subject==""){
		document.getElementById("mmsubject").focus();
		document.getElementById("mmshowMsgResult").innerHTML="<p>"+$('resEnter_subject').value+"</p>";
		document.getElementById("mmshowMsgResult").style.display="block";
		return ;
	}
	/*
 		 @Author : mmalyala
 		 @Bug No : 3865
	 	 @Fix    : subject length validation condition and message added. 		 	
	 */
	if(subject.length>150){
		document.getElementById("mmsubject").focus();
		document.getElementById("mmshowMsgResult").innerHTML="<p>"+$('resEnter_subject_length').value+"</p>";
		document.getElementById("mmshowMsgResult").style.display="block";
		return ;
	}
	if(content==""){
		document.getElementById("mmmsgcontent").focus();
		document.getElementById("mmshowMsgResult").innerHTML="<p>"+$('resEnter_message').value+"</p>";
		document.getElementById("mmshowMsgResult").style.display="block";
		return ;
	}
	url +="&subject="+escape(subject)+"&content="+escape(content);
	loadDivContent(divId,url,function(){showModeratorMsgResult(ele)});
}

function showModeratorMsgResult(ele){
	var android = (navigator.appVersion.indexOf("Android") == -1) ? false : true;
	if(!ipad && !iphone && !android){
		msginstance.e.body.innerHTML="";
	}
	divs_transparentDiv.style.display="none";
	document.getElementById("newmsgsubject").value="";
	document.getElementById("newmsgcontent").value="";
	document.getElementById("showMsgResult").style.display="none";		
	document.forms[0].reset();
	document.getElementById("sendmessageId").style.display="none";  
	// $("opacitydiv").style.visibility = 'hidden';
}

function showfooterdiv(id)
{
	var footer = $('footer-main');
	var myPos = new Array();
	myPos = findPos(footer);
	var fx = myPos[0];
	var fy = myPos[1];
	$(id).show();
	$(id).style.top = fy-10+'px';
	$(id).style.left = fx+400+'px';
}
function hidefooterdiv(id)
{
	if(id == 'supportDiv')
	{
		setTimeout("$('supportDiv').hide();",3000);
	}
	else if(id == 'suggestionsDiv')
	{
		$('suggestionsDiv').hide();
	}
}

/*
* @author gkottala
* @Bug : DS-4181 As an Account Owner, when I go to the manage members pages to view active or pending members the display only shows 10 people at a time and there is no way to go to the end of the list immedeately.
* Display the page based on value of page no textbox.
*/

function displayPage(startNo, e, pageNo,noOfPages,url,divId){
	/*Author: Avinash
	* Fix: added validation to check alphabet in pagination
	* Bug: DS-5548
	*/
	var pattern = /[A-Za-z]/i;
	var checkalphabet =  pattern.test(pageNo);
	var keycode;
	if (window.event) keycode = window.event.keyCode;
	else if (e) keycode = e.which;

	if(keycode == 13){
		if(pageNo<1 || pageNo>noOfPages || checkalphabet){

			$("errmsg").innerHTML = "Page No should be between 1 and "+noOfPages;
			$("errmsg").show();
		}else{
			changeUserPageControl(startNo, pageNo, url,divId)
		}
	}

}


function changeUserPageControl(startNo, pageNo, url,divId) {	 
	url =url+"&userstartNo="+startNo+"&userpageNo="+pageNo;

	if(divId=='pagecontent'){
		loadDivContent(divId,url);
	}else if(divId=='searchresults-tab'){
		searchActiveUser(divId,url);
	}else if(divId=='activereportusers'){
		changeUser(url);
	}else if(divId=='activereportusers'){
		changeUser(url);
	}else{
		chageusertab(divId,url);
	}
}

function broadcastclose()
{ 
	divs_transparentDiv.style.display="none";
	document.getElementById("brsubject").value="";
	document.getElementById("brmsgcontent").value="";
	document.getElementById("broadcastId").style.display="none";
	document.getElementById("brshowMsgResult").innerHTML = "";
	document.getElementById("brshowMsgResult").style.display="none";
}
function modMessageClose()
{ 
	divs_transparentDiv.style.display="none";
	document.getElementById("mmsubject").value="";
	document.getElementById("mmmsgcontent").value="";
	document.getElementById("modMessageId").style.display="none";
	document.getElementById("mmshowMsgResult").innerHTML = "";
	document.getElementById("mmshowMsgResult").style.display="none";	
}


function changeCustomTheme(url, action) {
	if(document.getElementById('customize-theme-popup'))
	{
		document.getElementById('customize-theme-popup').style.display="none";
	}
	if(document.getElementById('confirmbox'))
	{
		document.getElementById('confirmbox').style.display="none";
	}
	showloader();
	var themeId;
	var themeName;
	var preview = "";
	var objs = document.getElementsByName("theme");
	for(i=0; i<objs.length; i++) {
		if(objs[i].checked) {
			themeId = objs[i].value;
			themeName = objs[i].id;
			break;
		}
	}
	if(action == "themePreview") {
		preview = "&themePreview=0";
		// hidepopup('ask-question-popup');
		// $('themehidden').value=themeName;
	}

	if(themeId >0) {
		window.location.href = url +"&themeId="+themeId+preview;
	} else {
		alert("Please select one theme");
	}
}

function customizeTheme() {
	window.scrollTo(0,0);
	showloader();
	if($('confirmbox')) {
		$('confirmbox').hide();
	}
	setTimeout("showpopupwindow('customize-theme-popup')",1000);
}
function showalert()
{
	/*
	* @author: mkonusu
	* @purpose: used to hide popup when session expire popup opens
	* if hidden popup is not session expire popup then clear current displayed popup div id. 
	*/
	if($('currentPopupDivId')) {
		$('currentPopupDivId').value = 'confirmbox';
	}
	var Container = $('view');
	window.scrollTo(0,0);		
	var myPos = new Array();
	myPos = findPos(Container);
	var fx = myPos[0];
	var fy = myPos[1];
	var ua = navigator.userAgent.toLowerCase();

	if(ua.indexOf('msie') != -1)
	{
		$('confirmbox').style.top = fy+350+'px';
		$('confirmbox').style.left = fx+350+'px';
		$('confirmbox').style.display='block';
		$('confirmbox').style.position='absolute';
		$("opacitycoinfirmdiv").style.visibilty='visible';
	}
	else
	{	
		$('confirmbox').style.display='block';
		$('confirmbox').style.top = fy+350+'px';
		$('confirmbox').style.left = fx+350+'px';
		$('confirmbox').style.position='absolute';
		$("opacitycoinfirmdiv").style.visibilty='visible';

	}
	$("opacitycoinfirmdiv").style.visibility = 'visible';
	var dimensions = getPageSizeWithScroll();
	$("opacitycoinfirmdiv").style.width = dimensions[0];
	$("opacitycoinfirmdiv").style.height = document.getElementById('PageInner').value;

}
function showtopicpreview()
{
	/*
	* @author: mkonusu
	* @purpose: used to show popup when session expire popup closes to extend
	* if session extends the show the currently displayed popup. 
	* Before opening session expire popup, if current displayed popup exists then store the divid as a hidden value.
	*/
	if($('currentPopupDivId')) {
		$('currentPopupDivId').value = 'confirmbox-preview';
	}
	var ASk = document.getElementById('ask');
	window.scrollTo(0,0);		
	var myPos = new Array();
	myPos = findPos(ASk);
	var fx = myPos[0];
	var fy = myPos[1];	
	$('confirmbox-preview').style.display='block';
	$('confirmbox-preview').style.top = fy+39+'px';
	$('confirmbox-preview').style.left = fx+100+'px';
	$('confirmbox-preview').style.position='absolute';
	$("opacitycoinfirmdiv").style.visibilty='visible';


	$("opacitycoinfirmdiv").style.visibility = 'visible';
	var dimensions = getPageSizeWithScroll();
	$("opacitycoinfirmdiv").style.width = dimensions[0];
	$("opacitycoinfirmdiv").style.height = document.getElementById('PageInner').value;

}

function showtopiceditpreview()
{
	if($('ask-question-preview-popup-model'))
	{
		$('ask-question-preview-popup-model').hide();
		$("preview-opacitydiv").style.visibility = 'hidden';
	}
	/*
	* @author: mkonusu
	* @purpose: used to show popup when session expire popup closes to extend
	* if session extends the show the currently displayed popup. 
	* Before opening session expire popup, if current displayed popup exists then store the divid as a hidden value.
	*/
	if($('currentPopupDivId')) {
		$('currentPopupDivId').value = "ask-question-edit-popup";
	}
	if($('ask-question-preview-popup')) {
		$("opacitycoinfirmdiv").style.visibility = 'hidden';
		$("preview-opacitydiv").style.visibility = 'hidden';
		$('ask-question-preview-popup').hide();
	}
	if($('ask-question-edit-popup-model'))
	{
		popupDiv=$('ask-question-edit-popup-model');
		__overlay('ask-question-edit-popup-model');
		popupDiv.style.display='block';
		var popupWidth=popupDiv.clientWidth;
		var popupHeight=popupDiv.clientHeight;
		popupDiv.style.left=(bodyWidth-popupWidth)/2+'px';
		popupDiv.style.top='100px';
	}
	else if($('ask-question-edit-popup'))
	{
		var ASk = document.getElementById('ask');
		var ua = navigator.userAgent.toLowerCase();	
		if(ua.indexOf('msie') != -1)
		{
			var myPos = new Array();
			myPos = findPos(ASk);
			var fx = myPos[0];
			var fy = myPos[1];
			$('ask-question-edit-popup').style.top = fy+-31+'px';
			$('ask-question-edit-popup').style.left = fx+-10+'px';
			$('ask-question-edit-popup').style.display = 'block'; 
		}
		else
		{	
			var myPos = new Array();
			myPos = findPos(ASk);
			var fx = myPos[0];
			var fy = myPos[1];
			$('ask-question-edit-popup').style.top = fy+-29+'px';
			$('ask-question-edit-popup').style.left = fx+-7+'px';
			$('ask-question-edit-popup').style.display = 'block';  

		}
		$("opacitydiv").style.visibility = 'visible';
		var dimensions = getPageSizeWithScroll();
		$("opacitydiv").style.width = dimensions[0];
		$("opacitydiv").style.height = document.getElementById('PageInner').value;
	}
}
/*
* @author pgudipalli
* @Feature class room product edit option after preview.
* 
*/
function showclassroomeditpreview()
{
	if($('currentPopupDivId')) {
		$('currentPopupDivId').value = "ask-question-edit-popup";
	}
	if($('classroom-preview-popup')) {
		$("opacitycoinfirmdiv").style.visibility = 'hidden';
		$('classroom-preview-popup').hide();
		$("preview-opacitydiv").style.visibility = 'hidden';
	}
	showpopupwindow("classroom-question-popup-new");
}
function curseFilter(FormName,FieldName)
{

	if(!document.forms[FormName])
		return true;

	var textFieldObj = document.forms[FormName].elements[FieldName];

	if(!textFieldObj)
		return true;

	var compare_text= textFieldObj.value;

	return curseFilter(compare_text);
}

function curseFilter(compare_text)
{
	if(stripBlanks(compare_text)=="")
		return true;

	var strCurseWords;
	var curseFilterArray;
	var foundCurseWordList=new Array();
	var foundCount=0;

	/*
	 * @author gkottala @Bug : 4378 As a moderator, when updating the curse word
	 * filter, i.e adding or removing words, it doesn't take affect for all
	 * users unless they clear their cache. This is not correct behavior.
	 * Removed the hardcoded curseFilter values
	 */

	// alert("value"+ $('curseFilter').value);
	if($('curseFilter') && $('curseFilter').value.strip()!= "") {
		strCurseWords = $('curseFilter').value;
		// alert(strCurseWords +' strCurseWords');

		curseFilterArray = strCurseWords.split(",");

		// compare_text = compare_text.replace(/^\s+|\s+$/g, ' ');
		compare_text = compare_text.replace(/<[^>]+>/g,' ');
		compare_text = compare_text.replace(/&nbsp;/g,' ');
		compare_text = compare_text.replace(/[\(\)\.\-\_,]/g, ' ');
		compare_text =  compare_text.toLowerCase();



		for(var i=0; i < curseFilterArray.length; i++)
		{
			var curseFilterWord = curseFilterArray[i].toLowerCase().replace(/^\s+|\s+$/g, '');
			// alert("curseFilterWord:1"+curseFilterWord);

			// if curse filter word is blank like in typical case ( ass , ' ') then
			// continue
			if(curseFilterWord == '')
				continue;

			/*
			 * Note: DON'T CHANGE/MOVE THE CASE ORDER
			 */

			// only one word in the description
			if(compare_text == curseFilterWord) {
				foundCurseWordList[foundCount++] = curseFilterWord;// compare_text.substring(foundPos,(foundPos+curseFilterArray[i].length));
				continue;
			}

		//case 1: MIDDLE Word occurence:  first check space word space -
		var spaceCursewordSpace = " " + curseFilterWord + " ";
		foundPos = compare_text.indexOf(spaceCursewordSpace);
		// alert("case 1 :: spaceCursewordSpace:"+spaceCursewordSpace+"::
		// foundPos: "+foundPos);
		if(foundPos != -1)
		{
			foundCurseWordList[foundCount++] = curseFilterWord;// compare_text.substring(foundPos,(foundPos+curseFilterArray[i].length));
			continue;
		}

		//case 2: FIRST Word occurence:  check for space followed by word, if it first word
		var cursewordSpace = curseFilterWord + " ";
		foundPos = compare_text.indexOf(cursewordSpace);
		// alert("case 2 :: cursewordSpace:"+cursewordSpace+":: foundPos:
		// "+foundPos);
		if(foundPos == 0)
		{
			foundCurseWordList[foundCount++] = curseFilterWord;// compare_text.substring(foundPos,(foundPos+curseFilterArray[i].length));
			continue;
		}

		//case 3: LAST Word occurence:  check for word followed by space, if it last word
		var spaceCurseword = " "+ curseFilterWord;
		var foundPos = compare_text.indexOf(spaceCurseword);
		// alert("case 3 :: spaceCurseword:"+spaceCurseword+":: foundPos:
		// "+foundPos);
		if(foundPos != -1 && foundPos == (compare_text.length-spaceCurseword.length))
		{
			foundCurseWordList[foundCount++] = curseFilterWord;// compare_text.substring(foundPos,(foundPos+curseFilterArray[i].length));
			continue;
		}

		}
	}

	/*for(var i=0; i<curseFilterArray.length; i++)
	 {
	  for(var j=0; j<(compare_text.length); j++)
	  {
		   if(curseFilterArray[i].toLowerCase()==compare_text.substring(j).toLowerCase())
		   {
			foundCurseWordList[foundCount]=compare_text.substring(j,(j+curseFilterArray[i].length));
			foundCount++;
		   }
	  }
	 }*/

	if(foundCount > 0)
	{
		var alert_text="";
		for(var k=0; k < foundCount; k++)
		{
			alert_text+="\n" + "(" + (k+1) + ")  " + foundCurseWordList[k];
		}

		if(stripBlanks(alert_text) ==  "")
			return true;


		alert("The form cannot be submitted.\nThe following curse words were found:\n_______________________________\n" + alert_text + "\n_______________________________");
		// document.getElementById("errorTopicDesc").innerHTML="The following
		// curse words were found: " + alert_text ;
		return false;
	}


	return true;

}
function stripBlanks(fld) {
	var result = "";
	var c = 0;
	for (i=0; i<fld.length; i++) {
		if (fld.charAt(i) != " " || c > 0) {
			result += fld.charAt(i);
			if (fld.charAt(i) != " ") c = result.length;
		}
	}
	return result.substr(0,c);
}

function getTimezoneName() {
	//Date (year, month, day, hour, minute, second, ms)
	var dt = new Date();
	tmSummer = new Date(Date.UTC(dt.getFullYear(), dt.getMonth() , dt.getDate(), dt.getHours(), 0, 0, 0));
	so = -1 * tmSummer.getTimezoneOffset();
	tmWinter = new Date(Date.UTC(dt.getFullYear(), dt.getMonth() , dt.getDate(), dt.getHours(), 0, 0, 0));
	wo = -1 * tmWinter.getTimezoneOffset();

	if (-660 == so && -660 == wo) return 'Pacific/Midway';
	if (-600 == so && -600 == wo) return 'Pacific/Tahiti';
	if (-570 == so && -570 == wo) return 'Pacific/Marquesas';
	if (-540 == so && -600 == wo) return 'America/Adak';
	if (-540 == so && -540 == wo) return 'Pacific/Gambier';
	if (-480 == so && -540 == wo) return 'US/Alaska';
	if (-480 == so && -480 == wo) return 'Pacific/Pitcairn';
	if (-420 == so && -480 == wo) return 'US/Pacific';
	if (-420 == so && -420 == wo) return 'US/Arizona';
	if (-360 == so && -420 == wo) return 'US/Mountain';
	if (-360 == so && -360 == wo) return 'America/Guatemala';
	if (-360 == so && -300 == wo) return 'Pacific/Easter';
	if (-300 == so && -360 == wo) return 'US/Central';
	if (-300 == so && -300 == wo) return 'America/Bogota';
	if (-240 == so && -300 == wo) return 'US/Eastern';
	if (-240 == so && -240 == wo) return 'America/Caracas';
	if (-240 == so && -180 == wo) return 'America/Santiago';
	if (-180 == so && -240 == wo) return 'Canada/Atlantic';
	if (-180 == so && -180 == wo) return 'America/Montevideo';
	if (-180 == so && -120 == wo) return 'America/Sao_Paulo';
	if (-150 == so && -210 == wo) return 'America/St_Johns';
	if (-120 == so && -180 == wo) return 'America/Godthab';
	if (-120 == so && -120 == wo) return 'America/Noronha';
	if (-60 == so && -60 == wo) return 'Atlantic/Cape_Verde';
	if (0 == so && -60 == wo) return 'Atlantic/Azores';
	if (0 == so && 0 == wo) return 'Africa/Casablanca';
	if (60 == so && 0 == wo) return 'Europe/London';
	if (60 == so && 60 == wo) return 'Africa/Algiers';
	if (60 == so && 120 == wo) return 'Africa/Windhoek';
	if (120 == so && 60 == wo) return 'Europe/Amsterdam';
	if (120 == so && 120 == wo) return 'Africa/Harare';
	if (180 == so && 120 == wo) return 'Europe/Athens';
	if (180 == so && 180 == wo) return 'Africa/Nairobi';
	if (240 == so && 180 == wo) return 'Europe/Moscow';
	if (240 == so && 240 == wo) return 'Asia/Dubai';
	if (270 == so && 210 == wo) return 'Asia/Tehran';
	if (270 == so && 270 == wo) return 'Asia/Kabul';
	if (300 == so && 240 == wo) return 'Asia/Baku';
	if (300 == so && 300 == wo) return 'Asia/Karachi';
	if (330 == so && 330 == wo) return 'Asia/Calcutta';
	if (345 == so && 345 == wo) return 'Asia/Katmandu';
	if (360 == so && 300 == wo) return 'Asia/Yekaterinburg';
	if (360 == so && 360 == wo) return 'Asia/Colombo';
	if (390 == so && 390 == wo) return 'Asia/Rangoon';
	if (420 == so && 360 == wo) return 'Asia/Almaty';
	if (420 == so && 420 == wo) return 'Asia/Bangkok';
	if (480 == so && 420 == wo) return 'Asia/Krasnoyarsk';
	if (480 == so && 480 == wo) return 'Australia/Perth';
	if (540 == so && 480 == wo) return 'Asia/Irkutsk';
	if (540 == so && 540 == wo) return 'Asia/Tokyo';
	if (570 == so && 570 == wo) return 'Australia/Darwin';
	if (570 == so && 630 == wo) return 'Australia/Adelaide';
	if (600 == so && 540 == wo) return 'Asia/Yakutsk';
	if (600 == so && 600 == wo) return 'Australia/Brisbane';
	if (600 == so && 660 == wo) return 'Australia/Sydney';
	if (630 == so && 660 == wo) return 'Australia/Lord_Howe';
	if (660 == so && 600 == wo) return 'Asia/Vladivostok';
	if (660 == so && 660 == wo) return 'Pacific/Guadalcanal';
	if (690 == so && 690 == wo) return 'Pacific/Norfolk';
	if (720 == so && 660 == wo) return 'Asia/Magadan';
	if (720 == so && 720 == wo) return 'Pacific/Fiji';
	if (720 == so && 780 == wo) return 'Pacific/Auckland';
	if (765 == so && 825 == wo) return 'Pacific/Chatham';
	if (780 == so && 780 == wo) return 'Pacific/Enderbury'
	if (840 == so && 840 == wo) return 'Pacific/Kiritimati';
	return 'US/Pacific';
}

function setThemeValue(themeId) {
	var themeObjs = document.getElementsByName("theme");
	if(themeObjs!=null && themeObjs!=undefined && themeObjs.length >0) {
		for(i=0;i<themeObjs.length;i++) {
			if(themeObjs[i].value == themeId) {
				themeObjs[i].checked = true;
				break;
			}
		}
	}

}

/**
* Author: vveerabathini
* Bug: DS - 3681
* Fix: updated code to fix email address with special charcters 
*/
function promoteOrDemoteUser(userId,url,userStatus, emailId){
	//var userType=$('userStatus').value;
	var userEmailId = $('emailId_'+userId).innerHTML;
	var url=url+'&userId='+userId+'&userType='+userStatus;
	rolechangePopupAlert(userId,url,'promoteOrDemoteDiv',userStatus,userEmailId);
	// loadDivContent('promoteOrDemoteDiv',url,function(){promoteOrDemoteUserResponse(userType)});
}

function cancelRoleChange(userId) {
	$("userStatus"+userId).value = $('userRoleId'+userId).value;
	hidepopup('rolechangealert-popup');
}

function rolechangePopupAlert(userId,url,divId,userType,emailId){	
	var action = "<div class='cringely-btns-main' id='rolechangealert-action'><a href=\'javascript:cancelRoleChange(\""+userId+"\");\'>"+$('cancelJs').value+"</a> &nbsp; <a href=\'javascript:loadDivContent(\""+divId+"\",\""+url+"\",function(){promoteOrDemoteUserResponse(\""+userId+"\",\""+userType+"\")});hidepopup(\"rolechangealert-popup\");\' class='button small primary vote'>"+$('okJs').value+"</a></div>";
	$('rolechangealert-action').innerHTML = action;
	$('userEmailId').innerHTML = emailId;
	if(userType == 5) {
		$('userRole').innerHTML = "Moderator Admin" ;
	} else if(userType == 2) {
		$('userRole').innerHTML = "Moderator" ;
	} else if(userType == 3) {
		$('userRole').innerHTML = "Authenicate User" ;
	}
	showpopupwindow('rolechangealert-popup');
	try{
		this.href=false;
	}catch(e){
		//alert(e);		
	}
}
function promoteOrDemoteUserResponse(userId,userType){
	$('userRoleId'+userId).value = userType;
	$('promoteDemoteDiv').show();
	$('promoteDemoteDiv').innerHTML=$('res_promoteDiv').value;

	if(userType==3){
		if($(userId)){
			$(userId).style.display="block";
		}
	}else{

		if($(userId)){
			$(userId).style.display="none";
		}
	}
}


function setAlertMessage(alertMsgMainDiv, alertMsgSubDiv, alertMsg) {
	//window.scroll(0,0);
	if(alertMsg.strip() == "") {
		$(alertMsgMainDiv).style.display = "none";
		$(alertMsgSubDiv).innerHTML = "";
	} else {
		$(alertMsgMainDiv).style.display = "block";
		$(alertMsgSubDiv).innerHTML = alertMsg;	  }
}

function sendPersonalMessage(userId,screenName,title)
{
	try{
		var emailId = $('emailId_'+userId).innerHTML;
		document.getElementById("toMailId").value=emailId;
		document.getElementById("subject").value=title!=null?title:title='';
		document.getElementById("isSingle").value= "true";
		document.getElementById("ids").value=userId;
		var ua = navigator.userAgent.toLowerCase();
		if(ua.indexOf('msie') != -1)
		{
			if(document.getElementById('inboxSortVal1'))
			{
				document.getElementById('inboxSortVal1').style.visibility='hidden';
			}

		}
		showpopupwindow('notificationPopupId');

	}catch(e){
		alert(e);
	}

}
function clickUrl()
{

	var regexp = /((ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?)/gi;
	if(document.getElementById('detailDiv'))
	{
		var divval = $('detailDiv').innerHTML;
		$('detailDiv').innerHTML = divval.replace(regexp,"<a href=\"$1\" class=\"dynamicLink\">$1</a>")
	}
	else if(document.getElementById('Proparentcomment'))
	{
		var divval = $('Proparentcomment').innerHTML;
		$('Proparentcomment').innerHTML = divval.replace(regexp,"<a href=\"$1\" class=\"dynamicLink\">$1</a>")
	}
}
/**
* Author: vveerabathini
* Bug: DS - 3681
* Fix: updated code to fix email address with special charcters 
*/

function sendInvites(inviteUrl){
	var android = (navigator.appVersion.indexOf("Android") == -1) ? false : true;
	try{
		var ids = trim (document.getElementById("emailIds").value);
		//var note = trim (document.getElementById("note").value);
		if(ipad || iphone || android){
			var note=trim($('formattedNote').value);
		} else {
			var note=trim(instance7.e.body.innerHTML);
		}

		if(ids[ids.length-1]==","){ 
			ids = ids.substring(0,ids.length-1);
		} 

		if(ids=="" || ids.length<1){
			document.getElementById("mesg-div").innerHTML = "<br><br><br>&nbsp;&nbsp;&nbsp;"+$('resMesg-emails').value;
			document.getElementById("emailIds").focus();
		}else if(ids=='' || ids==$('resEnter-email').value){
			document.getElementById("mesg-div").innerHTML = $('resMesg-atleast').value;
		}else{
			var url = inviteUrl+"&ids="+encodeURIComponent(ids)+"&note="+escape(note);
			loadDivContent("pagecontent",url,seteditor);
			// window.location.href=url;
		}
	}catch(e){
		alert(e);
	}
}
function showInviteResult(status,resp){
	//alert(resp);
}
function showInviteFrnds(){
	try{
		document.getElementById("mesg-div").innerHTML = "";
		if(document.getElementById('invite_frn').style.display=='none'){
			document.getElementById('emailIds').value="";
			document.getElementById('invite_frn').style.display='block';
			document.getElementById('resultDiv').style.display='none'; 
		}
	}catch(e){
		alert(e);
	}
}
function invitePreview()
{
	var android = (navigator.appVersion.indexOf("Android") == -1) ? false : true;
	try{
		document.getElementById("mesg-div").innerHTML = "";
		if(document.getElementById('invite_frn').style.display=='block')
		{
			var ids=document.getElementById('emailIds').value.strip();
			var newCode=ids.replace(/\,/g,', ');
			//var note =document.getElementById("note").value;
			if(ipad || iphone || android){
				var note=trim($('formattedNote').value);
			} else {
				var note=trim(instance7.e.body.innerHTML);
			}
			if(ids=='' || ids==$('resEnter-email').value){
				document.getElementById("mesg-div").innerHTML = $('resMesg-atleast').value;
			}else{

				document.getElementById('preview_mailid').innerHTML=newCode;
				document.getElementById('note-div').innerHTML=note;
				document.getElementById('invite_frn').style.display='none';
				document.getElementById('preview-invite').style.display='block';
			}
		}
		else
		{ 
			document.getElementById('invite_frn').style.display='block';
			document.getElementById('preview-invite').style.display='none';
		}
	}catch(e){
		alert(e);
	}
}
function backToInviteFriend()
{
	try{


		document.getElementById('preview-invite').style.display='none';
		document.getElementById('invite_frn').style.display='block';

	}catch(e){
		//alert(e);
	}
}
function hidethemepopup(url,id)
{	
	showloader();
	$("opacitydiv").style.visibility = 'hidden';
	$(id).style.display = 'none';
	if(url)
	{
		window.location.href = url;
	}
	$("msgcontent").value="";
}
function imposeMaxLength(Object, MaxLen)
{
	var length = Object.value.length;  
	if(length <= MaxLen) 
		return true;
	else 
		return false;

	// return (Object.value.length <= MaxLen);
}

function changeimportTab(id){

	var DivIds = new Array();
	DivIds[0] = "validuserstabId";
	DivIds[1] = "invaliduserstabId";

	for (i=0;i<DivIds.length;i++)
	{ 	 
		if(id=="validuserstabId")
		{
			$(id).className="one selected"; 
			$('validuserstab').show();
			if($('invaliduserstabId')){
				$('invaliduserstabId').className="two";
				$('invaliduserstab').hide();}
		}
		else if(id=="invaliduserstabId")
		{
			$(id).className="two selected"; 
			$('invaliduserstab').show();
			if($('validuserstabId')){
				$('validuserstabId').className="one"; 
				$('validuserstab').hide();}
		}

	}

}
function sendInviteList(){
	/*
	@Author : gkottala
	@Bug No:  DS-4190,  As an Account Owner, when I send invites, then cancel before sending, the text that was entered in the Customize invite note/message is blanked out along with all of the email addresses. 
	@Fix : data is cleared invitations have been sent.
	*/ 

	$('note').value = "";
	$('invitations').value = "";
	$('displayFilename').style.display = "none";
	$('importEmail').style.display = "";
	$('textId').style.display = "";
	document.getElementById('emailFilename').value = "";
	$('displayFilename').style.display = "none";
	$('displayFilename').style.display = "none";
	$('imp-userlist').style.display="none";
	submitForm('imp-userlist-result',document.impUserForm,setResult); 
}

/*
@Author : mmalyala
@Bug No:  3677
@Fix :  After clicking submit button in all places of application, disablethis() method will call to disable the button to avoid double click problems.
This method will remove the href for requested submit button and change the class to gray out the button.
*/ 
function disablethis(id){
	if($(id)!=null) {
		$(id).href="javascript:void(0);";
		$(id).className="button-gray"; 
	}
}
function disablethisimage(id){
	if($(id)!=null) {
		$(id).href="javascript:void(0);"; 
	}
}
function setResult(resp){
	showpopupwindow('imp-userlist');
	document.getElementById("listcontent").style.display="none";
	document.getElementById("cancellist").style.display="block";
	document.getElementById("imp-userlist-result").style.display="block"; 
}
function checkallusers(){
	var checkAll = document.getElementById("checkallids");
	var allitems = document.getElementsByName("ids"); 
	if(checkAll.checked){
		for(i=0;i<allitems.length;i++){
			allitems[i].checked = true;
		}
	}
	if(checkAll.checked==false){
		for(i=0;i<allitems.length;i++){
			allitems[i].checked = false;
		}
	}
}
function checkindivialuser(){
	var allitems = document.getElementsByName("ids"); 
	var checkAll = document.getElementById("checkallids");
	var totaltrue=0;
	for(i=0;i<allitems.length;i++){
		if(allitems[i].checked == false){
			checkAll.checked=false;
		}
		if(allitems[i].checked == true){
			totaltrue=totaltrue+1;
		}
	}
	if(totaltrue == allitems.length ){
		checkAll.checked=true;
	}
} 


function resendInvite(userId,title)
{
	try{

		document.getElementById("isSingle").value= "true";
		//document.getElementById("resendUserId").value=emailId;
		document.getElementById("selectedUserId").value=userId;
		var ua = navigator.userAgent.toLowerCase();
		if(ua.indexOf('msie') != -1)
		{
			if(document.getElementById('inboxSortVal1'))
			{
				document.getElementById('inboxSortVal1').style.visibility='hidden';
			}

		}
		showpopupwindow('resendInviteId');

	}catch(e){
		alert(e);
	}

}

function resendInvitations(div,url){
	var inviteMsg = $('note').value;
	$('note').value=$('resNote').value;
	if(curseFilter(inviteMsg)){
		var userId = $('selectedUserId').value
		// alert(userId);
		url +='&userId='+userId+'&resend=' +true+'&note='+inviteMsg; 
		// alert(url);
		loadDivContent('',url);
		counter=counter+1;
		hidepopup('resendInviteId');
		$("invite_status").innerHTML = $('resendinvite_status').value +'!';
		$("invite_status").show();
	}

}

function hideResendpopup(id)
{
	$("opacitydiv").style.visibility = 'hidden';
	$('note').value= $('resNote').value;
	$(id).style.display = 'none';
	if($('showMsgResult'))
	{
		$('showMsgResult').hide();
	}
} 
function sendinvitationuser()
{ /**Author :spenumatsa
	@bug: DS-4188 : As an Account Owner, when sending invites using the batch csv process, there are times when the send invitations button is clickable multiple times which may cause a system problem or duplicate emails to be sent.
 */
	disablethis('sendInviteUserSubmitButton');
	if($('fileName').value!='')
	{
		browseFile();
	}
	else if($('invitations').value!=$('resInvitations').value)
	{
		browseFile();
	}
	else
	{
		var sHTML;
		sHTML = '<a id="importlink" href="javascript:openwindow();"> ';
		sHTML+='Click here';
		sHTML+='</a>&nbsp;';
		$('invalidFile').innerHTML=$('resinvalidFile').value+"<br/>"+sHTML+$('resinemailfile').value;
	}
}
function setUserSearchString(){
	//alert($('userSearchString').value);
	var userSearch =$('userSearchString').value;
	chageusertab('searchresults-tab',userSearch);
}
function showtopics(id)
{
	var ua = navigator.userAgent.toLowerCase();
	if(ua.indexOf('msie') != -1 )
	{
		var typeList = $("typelist").getElementsByTagName('li');
		for(var i=0; i<typeList.length; i++)
		{
			$(typeList[i]).style.visibility="visible";
			$('attachmedia').style.visibility="visible";
			$('previewbutton').style.visibility="visible";
			$('addpdfdetail').style.visibility="visible";

		}
	}
	Effect.Appear('attachmedia');
	Effect.Appear('previewbutton');
}
function hidetopics(){
	changetopic();
	deletesubfield('addphotodetail','photoId');
	deletesubfield('addvideodetail','videoId');
	deletesubfield('addpdfdetail','pdfId');

}
function selecttopic(id)
{
	/**
	 *	@Author: mmalyala
	 *	@Bug : 4431 When configuring topic types off for a site they should go away for all 
	 *	users (currently moderators still see them)
	 *	@Fix : topic type enabled conditions related changes.											
	 */
	var typeList = $("typelist").getElementsByTagName('li');
	/**
	 * Change link will appear only if more than one topic type is enabled
	 * for that site.
	 */
	if(typeList.length>2){
		$('changequestiontype').show();
	}else{
		if(typeList.length==2){
			if(typeList[0].id!="multiplechoice"){
				$('changequestiontype').show();
			}
		}
	}

	for(var i=0; i<typeList.length; i++)
	{
		var ua = navigator.userAgent.toLowerCase();
		if(ua.indexOf('msie') != -1 )
		{
			$(typeList[i]).childNodes[0].className ='itemdefinition-change';
		}
		else
		{
			$(typeList[i]).childNodes[1].className ='itemdefinition-change';
		}
		$(typeList[i]).hide();
		/**
		 * Changed typeList[0] to specific name to avoid problems when some
		 * topic types are disabled.
		 */
		if(id=='yesorno')
		{
			$('topicTypeId').value = 1;
			$('yesorno').show();
		}
		else if(id=="multiplechoice")
		{
			$('multiplechoice').hide();
			$('topicTypeId').value = 2; 
			var rowCnt =  $('rowCount').value;
			$('mlOptionCnt').value = 2;
			$('rowCount').value = 2;
			/**
			 * Author : vveerabathini Feature : 4232 Subtask 4539
			 * Enable/Disable the dropdown based on select/deselect the
			 * "Allow Multiple Choice Selections Up To Box" and Update drop
			 * down based choice addition and deletion. fix : Added code
			 * populate default dropdown when change topic type in ask flow
			 */
			if($('choiceLabel')!=null) {
				var choiceLabel = $('choiceLabel').value;
			}
			if($('choiceOptionText1')!=null) {
				var choiceOptionText1 = $('choiceOptionText1').value;
				var choiceOptionText2 = $('choiceOptionText2').value;
			}
			var CHTML= "";
			CHTML +="<table id='dataTable'  width='100%' border='0'>";
			CHTML +="<tr>";
			CHTML +="<td  class='mutli-choice-text'>"+choiceLabel+"</td>";
			CHTML +="<td class='mutli-choice-text' >&nbsp;</td>";
			CHTML +="<td width='100%' class='choice'> <INPUT type='text' id='optionId[1]' name='optionId[1]' maxlength='140' onkeyup='return ismaxlength(this)' onkeydown='removeErrorMessage(\"askQuestionAlertDiv\");'/> </td>";
			CHTML +="<td width='55%' id='errorMultiChoiceId[1]' class='error-multichoice-msg'></td>";
			CHTML +="</tr>";
			CHTML +="<tr>";
			CHTML +="<td  class='mutli-choice-text'>"+choiceLabel+"</td>";
			CHTML +="<td class='mutli-choice-text' >&nbsp;</td>";
			CHTML +="<td width='100%' class='choice'> <INPUT type='text' id='optionId[2]' name='optionId[2]' maxlength='140' onkeyup='return ismaxlength(this)' onkeydown='removeErrorMessage(\"askQuestionAlertDiv\");'/> </td>";
			CHTML +="<td width='55%' id='errorMultiChoiceId[2]' class='error-multichoice-msg'></td>";
			CHTML +="</tr>";
			CHTML +="</table>";

			$('multiplechoicedisplay').style.display="block";				
			document.getElementById('choices').innerHTML = CHTML;
			$('multipleChoice').checked=false;
			var sHTML = "<select id='multipleChoiceId' name='multipleChoiceId' disabled>";
			sHTML +="<option value='1'>"+choiceOptionText1+"</option>";
			sHTML +="<option value='2' selected>"+choiceOptionText2+"</option>";
			sHTML +="</select>";
			$('multiplechoiceseldetail').innerHTML = sHTML;
		}
		else if(id=="openforum")
		{
			$('topicTypeId').value = 4;
			$('openforum').show();
		}
		else if(id=="suggestandvote")
		{
			$('topicTypeId').value = 3;
			$('suggestandvote').show();
		}else if(id=="multiplechoicefirsttime")
		{
			$('topicTypeId').value = 2;
			$('multiplechoice').hide();

			$('multiplechoicedisplay').style.display="block";
		}
	}
}
function selecttopicuser(id)
{
	/**
	 *	@Author: mmalyala
	 *	@Bug : 4431 When configuring topic types off for a site they should go away for all 
	 *	users (currently moderators still see them)
	 *	@Fix : topic type enabled conditions related changes.											
	 */
	var typeList = $("typelist").getElementsByTagName('li');

	// old code
	// $('changequestiontype').show();

	/**
	 * @Author : Gowri
	 * @bug : DS-3610 When three types of questions are disabled for a site,
	 *      when user select the remaining one site Change link is
	 *      displayed.
	 * @Fix : Show the change link when question types more than 1
	 */
	/**
	 * Change link will appear only if more than one topic type is enabled
	 * for that site.
	 */
	if(typeList.length>2){
		$('changequestiontype').show();
	}else{
		if(typeList.length==2){
			if(typeList[0].id!="multiplechoice"){
				$('changequestiontype').show();
			}
		}
	}

	for(var i=0; i<typeList.length; i++)
	{
		var ua = navigator.userAgent.toLowerCase();
		if(ua.indexOf('msie') != -1 )
		{
			$(typeList[i]).childNodes[0].className ='itemdefinition-change';
		}
		else
		{
			$(typeList[i]).childNodes[1].className ='itemdefinition-change';
		}
		$(typeList[i]).hide();
		if(id=='yesorno')
		{
			$('topicTypeId').value = 1;
			$('yesorno').show();
		}
		else if(id=='multiplechoice')
		{
			$('multiplechoice').hide();
			$('topicTypeId').value = 2; 
			$('multiplechoicedisplay').style.display="none";
			var rowCnt =  $('rowCount').value;
			$('mlOptionCnt').value = 2;
			$('rowCount').value = 2;
			/**
			 * Author : vveerabathini Feature : 4232 Subtask 4539
			 * Enable/Disable the dropdown based on select/deselect the
			 * "Allow Multiple Choice Selections Up To Box" and Update drop
			 * down based choice addition and deletion. fix : Added code
			 * populate default dropdown when change topic type in ask flow
			 */
			if($('choiceLabel')!=null) {
				var choiceLabel = $('choiceLabel').value;
			}
			if($('choiceOptionText1')!=null) {
				var choiceOptionText1 = $('choiceOptionText1').value;
				var choiceOptionText2 = $('choiceOptionText2').value;
			}
			var CHTML= "";
			CHTML +="<table id='dataTable'  width='100%' border='0'>";
			CHTML +="<tr>";
			CHTML +="<td  class='mutli-choice-text'>"+choiceLabel+"</td>";
			CHTML +="<td class='mutli-choice-text' >&nbsp;</td>";
			CHTML +="<td width='100%' class='choice'> <INPUT type='text' id='optionId[1]' name='optionId[1]' maxlength='140' onkeyup='return ismaxlength(this)' onkeydown='removeErrorMessage(\"askQuestionAlertDiv\");'/> </td>";
			CHTML +="<td width='55%' id='errorMultiChoiceId[1]' class='error-multichoice-msg'></td>";
			CHTML +="</tr>";
			CHTML +="<tr>";
			CHTML +="<td  class='mutli-choice-text'>"+choiceLabel+"</td>";
			CHTML +="<td class='mutli-choice-text' >&nbsp;</td>";
			CHTML +="<td width='100%' class='choice'> <INPUT type='text' id='optionId[2]' name='optionId[2]' maxlength='140' onkeyup='return ismaxlength(this)' onkeydown='removeErrorMessage(\"askQuestionAlertDiv\");'/> </td>";
			CHTML +="<td width='55%' id='errorMultiChoiceId[2]' class='error-multichoice-msg'></td>";
			CHTML +="</tr>";
			CHTML +="</table>";
			document.getElementById('choices').innerHTML = CHTML;
			$('multiplechoicedisplay').show();
			/**
			 * Author : vveerabathini Feature : 4232 Subtask 4539
			 * Enable/Disable the dropdown based on select/deselect the
			 * "Allow Multiple Choice Selections Up To Box" and Update drop
			 * down based choice addition and deletion. fix : Added code
			 * populate default dropdown when change topic type in ask flow
			 * for user
			 */
			$('multipleChoice').checked=false;
			var sHTML = "<select id='multipleChoiceId' name='multipleChoiceId' disabled>";
			sHTML +="<option value='1'>"+choiceOptionText1+"</option>";
			sHTML +="<option value='2' selected>"+choiceOptionText2+"</option>";
			sHTML +="</select>";
			$('multiplechoiceseldetail').innerHTML = sHTML;
			$('multiplechoicedisplay').show();
		}
		else if(id=="openforum")
		{
			$('topicTypeId').value = 4;
			$('openforum').show();
		}
		else if(id=="suggestandvote")
		{
			$('topicTypeId').value = 3;
			$('suggestandvote').show();
		}else if(id=="multiplechoicefirsttime")
		{
			$('topicTypeId').value = 2;
			$('multiplechoice').hide();

			document.getElementById('multiplechoicedisplay').style.display = "block"; 
			// $('multiplechoicedisplay').show();
		}
	}
}
function changetopic()
{		

	$('changequestiontype').hide();
	if($('multiplechoicedisplay')!=null) {
		$('multiplechoicedisplay').style.display="none";
	}
	var typeList = $("typelist").getElementsByTagName('li');
	$('topicTypeId').value = 0;
	for(var i=0; i<typeList.length; i++)
	{			
		if($(typeList[i]).id != 'multiplechoicedisplay')
		{
			var ua = navigator.userAgent.toLowerCase();
			if(ua.indexOf('msie') != -1 )
			{
				$(typeList[i]).childNodes[0].className ='itemdefinition';
			}
			else
			{
				$(typeList[i]).childNodes[1].className ='itemdefinition';
			}
			Effect.Appear(typeList[i]);
		}
	}
}
function showsubfiled(ele,id)
{
	if($("mesgDiv")){
		$("mesgDiv").style.display="none";
	}
	$('addphotodetail').hide();
	$('addvideodetail').hide();
	$('addpdfdetail').hide();
	if($('PhotoTitle'))
		$('PhotoTitle').value="";
	if($('phototxt'))
		$('phototxt').value="";
	if($('DocumentTitle'))
		$('DocumentTitle').value="";
	if($('doctxt'))
		$('doctxt').value="";
	if($('photoKey'))
		$('photoKey').value="";
	if($('photoPath'))
		$('photoPath').value="";
	if($('documentKey'))
		$('documentKey').value="";
	if($('documentPath'))
		$('documentPath').value="";
	if($('showphotodiv')){
		$('showphotodiv').hide();
		$('browsefileid').show();
	}
	if( $('showdocdiv')){
		$('showdocdiv').hide();
		$('browsedocfileid').show();
	}

	if(ele.checked==true)
	{					
		//$('photo').value="";
		document.getElementById('browsefileid').innerHTML = 
			document.getElementById('browsefileid').innerHTML;

		$('PhotoTitle').value="";
		$('video').value="";
		$('VideoTitle').value="";
		$('DocumentTitle').value="";
		$('document').value="";
		document.getElementById('browsedocfileid').innerHTML = document.getElementById('browsedocfileid').innerHTML;
		Effect.Appear(id);
	}
	else
	{

		$(id).hide();	
	}
}
function showsubtestfiled(ele,id)
{
	if(ele.checked==true)
	{
		Effect.Appear(id);
	}
	else
	{
		if(id=='adddescriptiondetail')
		{
			instance1.e.body.innerHTML ='';
		}
		else if(id=='addenddatedetail')
		{
			$('hourField').options[0].selected=true;
			$('minuteField').options[0].selected=true;
			$('ampmField').options[0].selected=true;
			$('dateFieldVal').value="";
			$('dateField').value="";
		}
		$(id).hide();
	}
}
function deletesubfield(id,name)
{
	if(id=='adddescriptiondetail')
	{
		instance1.e.body.innerHTML ='';
	}
	else if(id=='addenddatedetail')
	{
		$('hourField').options[0].selected=true;
		$('minuteField').options[0].selected=true;
		$('ampmField').options[0].selected=true;
		$('dateFieldVal').value="";
		$('dateField').value="";
	}
	else if(id=='addphotodetail') 
	{
		if($('photo')){
			//$('photo').value="";	
			document.getElementById('browsefileid').innerHTML = 
				document.getElementById('browsefileid').innerHTML;
		}
		if($('PhotoTitle'))
			$('PhotoTitle').value="";
		if($('phototxt'))
			$('phototxt').value="";
		if($('photoKey'))
			$('photoKey').value="";
		if($('photoPath'))
			$('photoPath').value="";
		if($('showphotodiv')){
			$('showphotodiv').hide();
			$('browsefileid').show();
		}
		if($('photopreviewkey'))
			$('photopreviewkey').value="";
		if($('photopreviewpath'))
			$('photopreviewpath').value="";
		if($('photopreviewfilename'))
			$('photopreviewfilename').value="";
	} 
	else if(id=='addpdfdetail') 
	{
		if($('document')){
			//$('document').value="";	
			document.getElementById('browsedocfileid').innerHTML = 
				document.getElementById('browsedocfileid').innerHTML;
		}
		if($('DocumentTitle'))
			$('DocumentTitle').value="";
		if($('doctxt'))
			$('doctxt').value="";
		if($('documentKey'))
			$('documentKey').value="";
		if($('documentPath'))
			$('documentPath').value="";
		if( $('showdocdiv')){
			$('showdocdiv').hide();
			$('browsedocfileid').show();
		}
		if($('docpreviewkey'))
			$('docpreviewkey').value="";
		if($('docpreviewpath'))
			$('docpreviewpath').value="";
		if($('docpreviewfilename'))
			$('docpreviewfilename').value="";
	} 
	else if(id=='addvideodetail') 
	{
		if($('VideoTitle'))
			$('VideoTitle').value="";
		if($('video'))
			$('video').value="";		
		if($('videoTag'))
			$('videoTag').value="";
		if($('videotitlekey'))
			$('videotitlekey').value="";
		if($('video'))
			$('video').value="";
	}
	$(id).hide();
	$(name).checked = false;
	document.getElementById('mesgDiv').style.display = "none";
	// clearPreviewAttachmentFeilds();
}
function showpreview(siteType)
{
	/**
 			 @Author : mmalyala
 			 @Bug No : 3703
	 		 @Fix    : Added new attribute to check requested page is new site model page or not.  		 	
	 */
	if($('newModelWindowValue')){
		$('frompreviewmodeltopic').value=$('newModelWindowValue').value;
	}else{
		if($('frompreviewmodeltopic') != null){
			$('frompreviewmodeltopic').value=false;
		}
	}
	var android = (navigator.appVersion.indexOf("Android") == -1) ? false : true;
	var topicTitleId = $('topicTitle').value;
	if(!ipad && !iphone && !android){
		var v ="  "+instance1.e.body.innerHTML;
		topicTitleId = topicTitleId.htmlEntities();
		topicTitleId = topicTitleId.specialCharacterEntities();
		$('topicTitle').value = topicTitleId;
		$('topicDescription').value = v;
	}
	var topicDescriptionId =  $('topicDescription').value;
	topicDescriptionId = topicDescriptionId.anchorEntities();
	topicDescriptionId = topicDescriptionId.string_create_urls();
	topicDescriptionId = topicDescriptionId.specialCharacterEntities();
	$('topicDescription').value = topicDescriptionId;
	if($('questionSubmitResultDiv')!=null) {
		$('questionSubmitResultDiv').style.display="none";
	}
	if(validateAskQuestionForm() && validateTopicType() && validateMultiChoice() && checkDateValidations()
			&& validateCurseFilter() && validTopicAttachment() && validateCategories()) {
		$('xml').value = "";
		var xmlContent = constructTopicXml(document.askQuestionForm);
		$('xml').value = xmlContent;
		changeVideoWidthtopic();

		if(document.getElementById('multi-categories').style.display=="none" && $('categoryId').value!=0){
			$('categoryIds').value = $('categoryId').value;
		}else{
			var id = document.getElementById('multi-categories');
			var inputs = document.getElementById('multi-categories').getElementsByTagName('input');
			var i;
			var j=0;
			var stringArray= new Array();
			for(i=0;i<inputs.length;i++)
			{
				if(inputs[i].type=="checkbox" && inputs[i].checked)	{
					stringArray[j]=inputs[i].value;
					$('categoryIds').value = stringArray[j] + "," + $('categoryIds').value;
					j++;					
				}
			}
		}
		document.askQuestionForm.submit();

	}
	else
	{

		enablePublishButton('createTopicSubmit' , siteType);
	}
}

function disablethisPublishButton(id){

	$(id).href="javascript:void(0);";
	$(id).className="button-gray"; 	

}

function enablePublishButton(id,siteType){	
	if($(id) != null){
		$(id).href="javascript:showpreview(' ');";
		$(id).className="button primary";  
	}

}

function showpreviewclassroom(flow)
{
	/**
 			 @Author : mmalyala
 			 @Bug No : 3703
	 		 @Fix    : Added new attribute to check requested page is new site model page or not.  		 	
	 */

	var android = (navigator.appVersion.indexOf("Android") == -1) ? false : true;
	var topicTitleId = $('topicTitle').value;
	if(!ipad && !iphone && !android){
		var v ="  "+instance1.e.body.innerHTML;
		topicTitleId = topicTitleId.htmlEntities();
		topicTitleId = topicTitleId.specialCharacterEntities();
		$('topicTitle').value = topicTitleId;
		$('topicDescription').value = v;
	}
	var topicDescriptionId =  $('topicDescription').value;
	topicDescriptionId = topicDescriptionId.anchorEntities();
	topicDescriptionId = topicDescriptionId.string_create_urls();
	topicDescriptionId = topicDescriptionId.specialCharacterEntities();
	$('topicDescription').value = topicDescriptionId;
	if($('questionSubmitResultDiv')!=null) {
		$('questionSubmitResultDiv').style.display="none";
	}
	if(validateAskQuestionForm() && validateTopicType() && validateMultiChoice() && checkDateValidations()
			&& validateCurseFilter() && validTopicAttachment() && validateCategories()) {
		$('xml').value = "";

		if(flow=='edit'){
			$('xml').value = constructTopicXml(document.askQuestionEditForm);
		}else{
			$('xml').value = constructTopicXml(document.getElementById('askQuestionForm'));;
		}
		changeVideoWidthtopic();

		if(document.getElementById('multi-categories').style.display=="none" && $('categoryId').value!=0){
			$('categoryIds').value = $('categoryId').value;
		}else{
			var id = document.getElementById('multi-categories');
			var inputs = document.getElementById('multi-categories').getElementsByTagName('input');
			var i;
			var j=0;
			var stringArray= new Array();

			for(i=0;i<inputs.length;i++)
			{
				if(inputs[i].type=="checkbox" && inputs[i].checked)	{
					stringArray[j]=inputs[i].value;
					$('categoryIds').value = stringArray[j] + "," + $('categoryIds').value;
					j++;					
				}
			}
		}
		if(flow=='edit'){
			document.askQuestionEditForm.submit();
		}else{
			document.getElementById('askQuestionForm').submit();
		}

	}
	else
	{
		enablePublishButtonClassroom('createTopicSubmitClassroom');
	}
}
function enablePublishButtonClassroom(id){	
	if($(id) != null){
		$(id).href="javascript:showpreviewclassroom(' ');";
		$(id).className="button medium primary";  
	}

}

function hidepreview()
{
	$('normal-view').show();
	$("previewdiv").hide();
}
function showsamplequestions()
{
	if($('normal-view'))
	{
		$('normal-view').hide();
	}
	else if($('ask_question'))
	{
		$('ask_question').hide();
	}
	$('samplequestions').show();
}
function hidesamplequestions()
{
	if($('normal-view'))
	{
		$('normal-view').show();
	}
	else if($('ask_question'))
	{
		$('ask_question').show();
	}
	$('samplequestions').hide();
}
function deleteRow(ele,type) 
{
	var i=ele.parentNode.parentNode.rowIndex;
	$('dataTable').deleteRow(i);
	/*
	 * Author : vveerabathini New Feature : DS-4232 Added code updating
	 * multiple choice selection drop down based on choices.
	 */
	/**
	 * Author : vveerabathini Feature : 4232 Subtask 4539 Enable/Disable
	 * the dropdown based on select/deselect the "Allow Multiple Choice
	 * Selections Up To Box" and Update drop down based choice addition
	 * and deletion. fix : Added code populate default dropdown when
	 * delete the choice rows
	 */
	if(type!="changetopic") {
		var table = document.getElementById('dataTable'); 
		var rows = table.rows.length;

		var multiSelVal = 2;
		if($('multipleChoiceId').value!=null) {
			multiSelVal = $('multipleChoiceId').value;
		}

		if($('multipleChoiceId').disabled)
		{	
			var sHTML = "<select id='multipleChoiceId' name='multipleChoiceId' disabled>";
			var cnt = rows;
			var len = rows+1;
			var ofText = $('ofText').value;
			for(var j=1;j<len;j++) {
				sHTML +="<option value='"+j+"'>"+j+" "+ofText+" "+cnt+"</option>";
			}
			sHTML +="</select>";
			$('multiplechoiceseldetail').innerHTML = sHTML;
			$('rowCount').value = $('rowCount').value;
			if(cnt<multiSelVal) {
				multiSelVal = cnt;
			}
			$('multipleChoiceId').options[multiSelVal-1].selected=true;
		} else {
			var sHTML = "<select id='multipleChoiceId' name='multipleChoiceId'>";
			var cnt = rows;
			var len = rows+1;
			var ofText = $('ofText').value;
			for(var j=1;j<len;j++) {
				sHTML +="<option value='"+j+"'>"+j+" "+ofText+" "+cnt+"</option>";
			}
			sHTML +="</select>";
			$('multiplechoiceseldetail').innerHTML = sHTML;
			$('rowCount').value = $('rowCount').value;
			if(cnt<multiSelVal) {
				multiSelVal = cnt;
			}
			$('multipleChoiceId').options[multiSelVal-1].selected=true;
		}
	} 
}
function showdiv()
{
	$('getcontent').style.display="inline";
	$('getcontent1').style.display="inline";
}
function hidediv()
{
	$('getcontent').hide();
}
function getQuestion(ele)
{
	var question_text = ele.innerHTML;
	question_text = question_text.strip();
	$('samplequestions').hide();
	if($('normal-view'))
	{
		$('normal-view').show();
		$('topicTitle').value = question_text;
	}
	else if($('ask_question'))
	{
		$('ask_question').show();
		$('topicTitle').value = question_text;
	}

}
function selectmodeltopic()
{
	var topic = $('topicTypeId').value	;

	if(topic == 2)	
	{
		$('multiple_choice').show();
	}
	else  
	{
		$('multiple_choice').hide();
	}
}
function clearPage()
{
	var android = (navigator.appVersion.indexOf("Android") == -1) ? false : true;
	document.askQuestionForm.reset();
	clearAskModalQuestionForm();
	if(!ipad && !iphone && !android){
		instance1.e.body.innerHTML ='';
	}
}
function showblockpopup(ele)
{
	reference = ele.parentNode.parentNode;
	var myPos = new Array();
	myPos = findPos(ele);
	var fx = myPos[0];
	var fy = myPos[1];
	$('block-popup').style.display = 'block'; 
	$('block-popup').style.top = fy-45+'px';
	$('block-popup').style.left = fx-90+'px';

}
function hideblockpopup(id)
{
	document.getElementById(id).style.display = 'none'; 
}
function showmorepopup(id)
{
	var more_id = document.getElementById(id);
	var myPos = new Array();
	myPos = findPos(more_id);
	var fx = myPos[0];
	var fy = myPos[1];
	$('more-popup').style.display = 'block'; 
	$('more-popup').style.top = fy-64+'px';
	$('more-popup').style.left = fx-98+'px';

}
function showalertspopup(id)
{
	/*
	 * @author: mkonusu
	 * @purpose: used to show popup when session expire popup closes to extend
	 * if session extends the show the currently displayed popup. 
	 * Before opening session expire popup, if current displayed popup exists then store the divid as a hidden value.
	 */
	if($('currentPopupDivId') && id != "session-message") {
		$('currentPopupDivId').value = id;
	}
	window.scrollTo(0,0);	
	hideblockpopup('more-popup');
	hideblockpopup('block-popup');
	var Container = document.getElementById('view');
	var myPos = new Array();
	myPos = findPos(Container);
	var fx = myPos[0];
	var fy = myPos[1];
	$(id).style.display = 'block'; 
	$(id).style.top = fy+44+'px';
	$(id).style.left = fx+188+'px';
	/*
	 * @Author : pgudipalli @Bug No : 3884 @Fix : added overlay div
	 * functionality .
	 */
	__overlay(id);
}
function changebackground(ele)
{
	ele.style.background="#fafabe";
}
function changebackgroundnormal(ele)
{
	ele.style.background="";
}

function siteInValidCharSet(objValue,charset)
{
	for (var i=0;i<objValue.length;i++){
		if (charset.indexOf(objValue.substr(i,1))!=-1){
			return false;
		}	
	}
	return true;
}

/**
* According to RFC 2822, the local-part of the e-mail may use any of these ASCII characters: 
	* Upper case and Lower case letters (case insensitive) 
	* The digits 0 through 9 
	* The characters, ! # $ % & ' * + - / = ? ^ _ ` { | } ~ 
	* The character "." provided that it is not the first or last character in the local-part. 
	*  
	* @param emailId
	* @return boolean
	*/
	/**
	 * Author: vveerabathini Bug: DS - 3681 Fix: used isRFC822ValidEmail() to
	 * validate email address
	 */
	function isRFC822ValidEmail(emailId) {

	var sQtext = '[^\\x0d\\x22\\x5c\\x80-\\xff]';
	var sDtext = '[^\\x0d\\x5b-\\x5d\\x80-\\xff]';
	var sAtom = '[^\\x00-\\x20\\x22\\x28\\x29\\x2c\\x2e\\x3a-\\x3c\\x3e\\x40\\x5b-\\x5d\\x7f-\\xff]+';
	var sQuotedPair = '\\x5c[\\x00-\\x7f]';
	var sDomainLiteral = '\\x5b(' + sDtext + '|' + sQuotedPair + ')*\\x5d';
	var sQuotedString = '\\x22(' + sQtext + '|' + sQuotedPair + ')*\\x22';

	var sDomain_ref = sAtom;

	var sSubDomain = '(' + sDomain_ref + '|' + sDomainLiteral + ')';
	var sWord = '(' + sAtom + '|' + sQuotedString + ')';
	var sDomain = sSubDomain + '(\\x2e' + sSubDomain + ')*';
	var sLocalPart = sWord + '(\\x2e' + sWord + ')*';

	var sAddrSpec = sLocalPart + '\\x40' + sDomain; // complete RFC822 email
	// address spec

	var sValidEmail = '^' + sAddrSpec + '$'; // as whole string

	var validEmail = new RegExp(sValidEmail);

	if (validEmail.test(emailId)) {
		return true;
	}

	return false;
}
var instance7;
function seteditor()
{
	if($('formattedNote')) {
		var android = (navigator.appVersion.indexOf("Android") == -1) ? false : true;
		if(ipad || iphone || android){
			var txtArea = document.getElementById('formattedNote');
			txtArea.style.marginTop = "10px";
			txtArea.style.width = "90%";
		} else {
			instance7 = new TINY.editor.edit('editor7',{
				id:'formattedNote',
				width:600,
				height:144,
				cssclass:'te',
				controlclass:'tecontrol',
				rowclass:'teheader',
				dividerclass:'tedivider',
				controls:['bold','italic','underline','strikethrough','|','subscript','superscript','|','charmap','|','link',
				          'orderedlist','unorderedlist','|','outdent','indent','|','leftalign','centeralign','rightalign','blockjustify'],
				          footer:false,
				          xhtml:true,
				          css:'body{background-color:#fff;font-family:Arial, Helvetica, sans-serif;font-size:13px;padding:0px;margin:0px;}',
				          bodyid:'editor7',
				          footerclass:'tefooter'
			});	
		}
	}
}

var sessionTimer;
var sessionExpirePageTimer;

//set timer to invoke method to display session expire popup window
function setSessionTimer1() {
	sessionTimer = setTimeout("showSessionExtPopup1()", (1000*60*80));
}

// clear session expire timer
function removeSessiontimer1() {
	sessionTimer = clearTimeout(sessionTimer);
}

// reset session expire timer
function resetSessionTimer1() {
	if($('logUserIdExists')) {
		removeSessiontimer1();
		setSessionTimer1();
	}
}

// show session expire popup and set timer to redirect to session expire page
function showSessionExtPopup1() {
	setSessionExpirePageTimer1();
	$('isSessionExpirePopupOpened').value = "true";
	if($("currentPopupDivId").value != "") {
		hidepopup($("currentPopupDivId").value);
	}
	showpopupwindow('session-message');
}

// make ajax call to extend session
function refreshSession1() {
	removeSessionExpirePagetimer1();
	sendRequest($('refershSessionUrl').value, refreshSessionHandler1)
}

// set timer to redirect to session expire page
function setSessionExpirePageTimer1() {
	sessionExpirePageTimer = setTimeout("redirectToSessionExpirePage1()", (1000*60*20))
}

// clears redirect session expire page timer
function removeSessionExpirePagetimer1() {
	clearTimeout(sessionExpirePageTimer);
}

// handler to refresh session
function refreshSessionHandler1(resp) {
	hidepopup('session-message');
	$('isSessionExpirePopupOpened').value = "";
	if($("currentPopupDivId").value != "") {
		showpopupwindow($("currentPopupDivId").value);
	}
}

// redirect to session expire page
function redirectToSessionExpirePage1() {
	window.location.href = $("performSessionExpiryUrl").value;
}

/*
* Author : vveerabathini
* New Feature : DS-4232
* Added new method showAllowMultipleDropdown(ele,id) to show mutiple drop down 
*/

function showAllowMultipleDropdown(ele,id)
{
	/**
	* Author : vveerabathini
	* Feature : 4232 Subtask 4539 Enable/Disable the dropdown based on select/deselect the "Allow Multiple Choice Selections Up To Box" and Update drop down based choice addition and deletion.
	* fix : Added code enable/disable the dropdown based on selection
	*/
	var multiSelVal = 2;
	if($('multipleChoiceId').value!=null) {
		multiSelVal = $('multipleChoiceId').value;
	}

	if(ele.checked==true)
	{
		$('multipleChoiceId').disabled=false;
		$('multipleChoiceId').options[multiSelVal-1].selected=true;
	}
	else
	{
		multiSelVal =2;
		$('multipleChoiceId').disabled=true;
		$('multipleChoiceId').options[multiSelVal-1].selected=true;
	}
}
function showmulicategories()
{
	$("post-link").hide();
	$("categorylabel").innerHTML ="Select Categories:";
	$("categoryId").hide();
	if($("show-categories")) {
		if($("show-categories").style.display == "none") {
			$("show-categories").style.display = "block";
		}
	}
	$("multi-categories").show();
	var catId = $('categoryId').value;
	$('categoryId').value=0;
	var id = document.getElementById('multi-categories');
	var inputs = document.getElementById('multi-categories').getElementsByTagName('input');
	var i;
	var j=0;
	var stringArray= new Array();
	for(i=0;i<inputs.length;i++)
	{
		if(inputs[i].type=="checkbox")	{
			if(inputs[i].value == catId) {
				inputs[i].checked = true;
			} else {
				inputs[i].checked = false;
			}
		}
	}

}

function removedate(id)
{
	document.getElementById(id).value="";
	if(id=='dateFieldEditVal')
	{
		document.getElementById('remove-date-icon-edit').style.visibility="hidden";
	}
	else
	{
		document.getElementById('remove-date-icon').style.visibility="hidden";
	}
}
function reloadinstacne()
{
	var ua = navigator.userAgent.toLowerCase();
	var ua_index = ua.indexOf('msie');
	var ua_version = ua.charAt(ua_index+5);
	if(ua.indexOf('msie') != -1)
	{
		if($('subcommentText')){
			instance2 = new TINY.editor.edit('editor2',{
				id:'subcommentText',
				width:560,
				height:104,
				cssclass:'te',
				controlclass:'tecontrol',
				rowclass:'teheader',
				dividerclass:'tedivider',
				controls:['bold','italic','underline','strikethrough','|','subscript','superscript','|','charmap','|','link','|',
				          'orderedlist','unorderedlist','|','outdent','indent','|','leftalign','centeralign','rightalign','blockjustify'],
				          footer:false,
				          xhtml:true,
				          css:'body{background-color:#fff;font-family:Arial, Helvetica, sans-serif;font-size:13px;padding:0px;margin:0px;}',
				          bodyid:'editor2',
				          footerclass:'tefooter'
			});
		}
		if($('commentText')){
			instance5 = new TINY.editor.edit('editor5',{
				id:'commentText',
				width:625,
				height:124,
				cssclass:'te',
				controlclass:'tecontrol',
				rowclass:'teheader',
				dividerclass:'tedivider',
				controls:['bold','italic','underline','strikethrough','|','subscript','superscript','|','charmap','|','link','|',
				          'orderedlist','unorderedlist','|','outdent','indent','|','leftalign','centeralign','rightalign','blockjustify'],
				          footer:false,
				          xhtml:true,
				          css:'body{background-color:#fff;font-family:Arial, Helvetica, sans-serif;font-size:13px;padding:0px;margin:0px;}',
				          bodyid:'editor5',
				          footerclass:'tefooter'
			});	
		}
	}
}
//login.js

isIE=true;
if(navigator.appName.toUpperCase() == 'NETSCAPE'){
	isIE=false;
	//window.onfocus=setFocustoAlert;
}
function removeErrorMessage(id)
{
	if($(id)){
		$(id).style.display = "none";
	}
}
var gridXmlObj = [];
/*
 * bug:5727 bug refreshing for every event of validation
 * route cause: added validation in validateLoginForm()
 * fixed
 * 
 * 
 * */
function validateLoginForm() {
	if(isValidate()){
		sendLoginRequest($('username').value.strip(), $('password').value.strip());
	}
	else{
		return false;
	}
} 

function isValidate(){
	$('username').value = $('username').value.strip();
	$('password').value = $('password').value.strip();
	var username = $('username').value.strip();
	var pwd = $('password').value.strip();

	var msg = "";
	if(username=="" || username==null || username.length==0){
		msg= $('enterEmailAddress').value;
		$("username").focus();
	} else if(!isRFC822ValidEmail($("username").value.strip())){
		/**
		 * Author: vveerabathini
		 * Bug: DS - 3681
		 * Fix: used isRFC822ValidEmail() to validate email address
		 */
		msg=$('validEmail').value+"<br />";
		$("username").focus();
	} else if(pwd=="" || pwd==null ||pwd.length==0){
		msg=$('enterPassword').value+"<br>";
		$("password").focus();
	}
	if(msg==""){
		return true;
	} else {
		$('alertMsgDiv').style.display = "block";
		$('alertMsg').innerHTML = msg;
		return false;
	}
	return false;
}

function inValidCharSet(objValue, charset) {
	var result = true;
	var str = objValue.value.strip();
	if (str.length <= 0) {
		result = true;
	}

	for (var i = 0; i < str.length; i = i + 1) {
		if (charset.indexOf(str.substr(i, 1)) > 0) {
			result = false;
			break;
		}
	}
	return result;
}

function replaceMSSymbols(str){
	str=escape(str);
	str=replaceAll(str,"%u2019","%27");
	str=replaceAll(str,"%u201C","%22");
	str=replaceAll(str,"%u201D","%22");
	str=replaceAll(str,"%u02C6","%5E");
	str=replaceAll(str,"%u2018","%27");

	return str;
}

function validateEmail(ele) {
	var retVal=true;
	var emailFilter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})$/;
	var uEmail = ele.value.strip();

	if(uEmail == '') {
		retVal = false; 
	} else if(!emailFilter.test(uEmail)) {
		retVal = false;
	}
	ele.value = ele.value.strip();
	return retVal; 
}

function validateForgotEmail(ele) {

	var retVal=true;
	var emailFilter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})$/;
	var uEmail = ele.value.strip();

	if(uEmail == '') {
		retVal = false; 
	} else if(!emailFilter.test(uEmail)) {
		retVal = false;
	}
	ele.value = ele.value.strip();
	return retVal; 
}

function loginResponse(resp) {
	$('errorEmailAddress').value = $('username').value;
	if(resp.status==200) {
		//var respTxt = resp.responseText;	
		gridXmlObj=[];	
		gridXmlObj = buildObj(gridXmlObj,resp.responseXML.firstChild);

		if(gridXmlObj.collaborize.exists._value == "false") {
			if($('login-popup'))
			{
				showpopupwindow('login-popup');
			}
			if($('loader'))
			{
				hideloader();
			}
			$('alertMsgDiv').style.display = "block";
			$('alertMsg').innerHTML = gridXmlObj.collaborize.failMessage._value;
			$('username').value = $('errorEmailAddress').value;
			$('password').value ="";
		} else if(gridXmlObj.collaborize.exists._value == "true") {

			if($('dTopicId') && $('dTopicId').value > 0) {
				showTopicDetailView($('dTopicId').value);
			} else if($('dResourcePage') && $('dResourcePage').value == "results") {
				showResultsView();
			} else {
				showHomePage();
			}
		} else {
			//alert("exception");
		}
	}
}
function showLoginFailurePopup() {
	showpopupwindow("login-popup");
	$('alertMsgDiv').style.display = "block";
	$('alertMsg').innerHTML = $("errorloginFailureMessage").value;
	$("username").value = $("errorFailureEmailId").value;
}

function showPrivateLoginFailureMsg() {
	$('alertMsgDiv').style.display = "block";
	$('alertMsg').innerHTML = $("errorloginFailureMessage").value;
	$("username").value = $("errorFailureEmailId").value;
}
function showRegister(isAnonymous) {
	if(document.getElementById('login-popup'))
	{
		hidepopup('login-popup');
	}
	if($('displayId'))
	{
		$('displayId').hide();
	}
	/*
	 * @author gkottala
	 * @Bug : 4561 Alert messages are not getting refreshed in register page of private site
	 * @Fix : Alert message div set to empty when click on 'Register Now' buttons. 
	 */
	document.getElementById("mesgDiv").style.display="none";
	document.getElementById("mesg").innerHTML="";

	if(isAnonymous) {
		getPrivateRegisterForm();
	} else {
		getRegisterForm();
	}
}

function  showRegistrationForm() {
	if(document.getElementById('login-popup'))
	{
		hidepopup('login-popup');
	}
	showpopupwindow('register-popup');
}

function privateRegistrationFormResponseHandler(resp) { 
	$("registerFormDiv").innerHTML = resp.responseText;

	clearRegistrationForm();
	showPrivateRegistrationForm();
}	

function showPrivateRegistrationForm() {
	$('anon-login').hide();
	$('anon-registration').show();
}

/**
 * Response Handler for create a post question	
 */
function registrationFormResponseHandler(resp) { 
	$("registerDiv").innerHTML = resp.responseText;
	clearRegistrationForm();
	showRegistrationForm();
}	

function clearRegistrationForm() {
	$('fname').value = "";
	$('lname').value = "";
	$('sname').value = "";
	$('password1').value = "";
	$('cfpassword').value = "";
	$('register-email').value = "";
	$('captcha').value = "";
	$('aggreement').checked = false;
}

function clearLoginForm(){
	$('username').value = "";
	$('password').value = "";
	$('alertMsgDiv').style.display = "none";
	$('alertMsg').innerHTML = "";
}


/*function validateEmail(ele)
	{	
		var retVal=true;
		var emailFilter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})$/;
		var uEmail =  ele.value.strip();
		var eEmail = document.getElementById("mesg");

		if(uEmail == '') 
		{
			  retVal = false; 
			  eEmail.innerHTML = "Please enter the valid email.<br/>";eEmail.style.display = "block";
		}else if(!emailFilter.test(uEmail)) 
		{
			 retVal = false;
			 eEmail.innerHTML = "Please enter the valid email.<br/>";eEmail.style.display = "block";
		}
		return retVal; 
	}*/

function validateCaptcha(ele)
{
	var uCaptcha = ele.value.strip();
	//var eCaptcha = document.getElementById("mesg");
	if(uCaptcha == '' || uCaptcha== $('enterCaptcha').value) 
	{
		//eCaptcha.innerHTML = "Enter the text shown below.Letters are casesensitive.<br/>";eCaptcha.style.display = "block"; retVal = false;
		ele.focus();
		return false;
	}
	else
	{
		//eCaptcha.innerHTML="";
		return true;
	}
}
var instance7;
function showResult(ele){		
	showpopupwindow('classroom-question-editpopup');
	if($('topicDescription')) {
		var instance1 = new TINY.editor.edit('editor1',{
			id:'topicDescription',
			width:610,
			height:110,
			cssclass:'te',
			controlclass:'tecontrol',
			rowclass:'teheader',
			dividerclass:'tedivider',
			controls:['bold','italic','underline','strikethrough','|','subscript','superscript','|','charmap','|','link','|',
			          'orderedlist','unorderedlist','|','outdent','indent','|','leftalign','centeralign','rightalign','blockjustify'],
			          footer:false,
			          xhtml:true,
			          css:'body{background-color:#fff;font-family:Arial, Helvetica, sans-serif;font-size:13px;padding:0px;margin:0px;}',
			          bodyid:'editor1',
			          footerclass:'tefooter'
		}); 
	}
	if($("moderatorActionDetailUserMessage")){
		instance7 = new TINY.editor.edit('editor7',{
			id:'moderatorActionDetailUserMessage',
			width:610,
			height:124,
			cssclass:'te',
			controlclass:'tecontrol',
			rowclass:'teheader',
			dividerclass:'tedivider',
			controls:['bold','italic','underline','strikethrough','|','subscript','superscript','|','charmap','|','link','|',
			          'orderedlist','unorderedlist','|','outdent','indent','|','leftalign','centeralign','rightalign','blockjustify'],
			          footer:false,
			          xhtml:true,
			          css:'body{background-color:#fff;font-family:Arial, Helvetica, sans-serif;font-size:13px;padding:0px;margin:0px;}',
			          bodyid:'editor7',
			          footerclass:'tefooter'
		});	
	}	
	var dateVal = $("dateFieldEdit").value.strip();  
	if(dateVal != null && dateVal != "") {
		convertEditDateVal(dateVal);
	}
	var resp = document.getElementById('resultForm').innerHTML.strip();	
	if(resp.indexOf("captchaError")>=0){
		document.getElementById("mesgDiv").style.display="block";
		document.getElementById("mesg").innerHTML=$('textCasesensitive').value;			
	}else{
		document.getElementById("newuserpopup").style.display="none";
		document.getElementById("resultDiv").style.display="block";
	} 
}
/**
 * Convert date values
 */
function convertEditDateVal(dateVal) {
	//var dateVal = $("dateFieldEditVal").value.strip();  
	var dateValstr = dateVal.split("-");
	var curr_month = dateValstr[1];
	var curr_date = dateValstr[2];
	var curr_year = dateValstr[0];
	var currentDate = curr_month + "-" + curr_date + "-" + curr_year;
	// var currentDateFormat = currentDate.replace(/-/g, "/");
	$("dateFieldEdit").value = currentDate;
}

function viewforgotpopup(){
	document.getElementById("logId").style.display="none";
	if(document.getElementById("loglaterId") != null){
		document.getElementById("loglaterId").style.display="none";
	}

	/**
	 * @author: mkonusu
	 * @bug: DS-3963
	 * @fix: clear form
	 */		
	document.forgotpasswordform.reset();
	document.getElementById("forgotpassId").style.display="block";
	document.getElementById("forgotPwd").style.display="block";
	document.getElementById("successMessage").style.display="none";

}
function viewloginpopup(){

	/**
	 * @author: mkonusu
	 * @bug: DS-3963
	 * @fix: clear form
	 */
	clearLoginForm();
	document.getElementById("forgot-pwd-div").style.display="none";
	document.getElementById("logId").style.display="block";
	if(document.getElementById("loglaterId") != null){
		document.getElementById("loglaterId").style.display="block";
	}
	document.getElementById("forgotpassId").style.display="none";

}

function showTermsofUse(url){
	document.getElementById("registerId").style.display="none";
	document.getElementById("tId").style.display="block";
	sendRequest(url,assetContentResponse);

}
function assetContentResponse(resp){
	$('register-content-bodyDiv').innerHTML=resp.responseText;
}

function backToRegister(){
	document.getElementById("tId").style.display="none";
	document.getElementById("registerId").style.display="block";

}

function isRegisterExist(){	
	if(validateUser('register')){
		postRegisterUser();
		//loadDivContent(divId,checkUrl,function(){validateResult(url,ele,divId,url2)});
	}		
}

function  postRegisterUser() {
	if(document.getElementById('register-popup'))
	{
		hidepopup('register-popup');
	}
	postForm(document.registerform, registerUserResponseHandler);
}

/**
 * Response Handler for create a post question	
 */
function registerUserResponseHandler(resp) {
	if(document.getElementById('register-popup'))
	{
		showpopupwindow('register-popup');
	}
	if($('loader'))
	{
		hideloader();
	}
	var responseTxt = resp.responseText;

	var membershipTypeId = $("hidMemberShipId").value;
	var hidAnonEnabled = $("hidAnonEnabled").value;
	if(responseTxt.indexOf("<state>0</state>")>0) {

		if(hidAnonEnabled  == "true") {
			$('register-popup').hide();
		}
		var msg = "";
		var action =  "";

		if(membershipTypeId == 1) {
			msg = $('congratulationsMemberReturn').value;
			action =  "<a href='javascript:showHomePage();'>"+$('closeJs').value+"</a>";
		} else if(membershipTypeId == 2) {
			msg = $('successfulActiveComplete').value;
			action =  "<a href='javascript:showHomePage();'>"+$('closeJs').value+"</a>";
		} else if(membershipTypeId == 4) {
			msg = $('thankqRegistration').value;
			action =  "<a href='javascript:hidePopupAlert();'>"+$('closeJs').value+"</a>";
			if(hidAnonEnabled  == "false") {
				$('anon-login').show();
				$('anon-registration').hide();
			}
		} 


		showPopupAlert(msg, action);
	} else if(responseTxt.indexOf("<state>1</state>")>0) {
		document.getElementById("mesgDiv").style.display="block";
		document.getElementById("mesg").innerHTML=$('emailAlreadyExist').value;
	} else if(responseTxt.indexOf("<state>2</state>")>0) {
		document.getElementById("mesgDiv").style.display="block";
		document.getElementById("mesg").innerHTML=$('screenNameAlreadyExist').value;
	} else if(responseTxt.indexOf("<state>3</state>")>0) {
		document.getElementById("mesgDiv").style.display="block";
		document.getElementById("mesg").innerHTML=$('screenNameAlreadyExist').value+"<br>"+$('emailAlreadyExist').value;
	} else if(responseTxt.indexOf("<state>4</state>")>0) {
		document.getElementById("mesgDiv").style.display="block";
		document.getElementById("mesg").innerHTML=$('internalServerError').value;
	}  else if(responseTxt.indexOf("<state>5</state>")>0) {
		document.getElementById("mesgDiv").style.display="block";
		document.getElementById("mesg").innerHTML=$('validCaptcha').value;
	}
}

function validateResult(url,ele,divId,url2){ 
	var resp =  document.getElementById(divId).innerHTML.strip(); 
	if(resp.indexOf("captchaError")<0 && resp.indexOf("true")>=0 ){ 
		if(resp.indexOf("true")>=0)
			saveUser(url,ele,divId,url2);
	}else{
		if(resp.indexOf("captchaError")>=0)
			resp=resp.replace("captchaError",$('validCaptcha').value);
		if(resp.indexOf("true")>=0)
			resp=resp.replace("true","");
		document.getElementById("mesgDiv").style.display="block";
		document.getElementById("mesg").innerHTML = resp;
		return;
	}
}

function saveUser(url,ele,divId,url2){	 
	document.getElementById(divId).innerHTML="";
	var fname =  document.getElementById("fname").value.strip();
	var lname = document.getElementById("lname").value.strip();
	var sname =  document.getElementById("sname").value.strip();
	var password =  document.getElementById("cfpassword").value.strip();
	var email =  document.getElementById("email").value.strip();
	var typeId= document.getElementById("typeId").value.strip();
	if(typeId==1 || typeId=="1"){
		url = url +"&firstName="+replaceMSSymbols(fname)+"&lastName="+replaceMSSymbols(lname)+"&screenName="+replaceMSSymbols(sname)+"&password="+password+"&email="+email+"&isRegiesterPage=true";
		window.location.href=url;
	}else{
		url2=url2+"&firstName="+replaceMSSymbols(fname)+"&lastName="+replaceMSSymbols(lname)+"&screenName="+replaceMSSymbols(sname)+"&password="+password+"&email="+email+"&isRegiesterPage=true";
		loadDivContent(divId,url2,function(){showResult(ele)});
	}

}

function validateUser(str){
	var password=document.getElementById("password1").value.strip();
	var cfpassword=document.getElementById("cfpassword").value.strip();
	var agg=document.getElementById("aggreement").checked;
	var val_name=/^[\w|\.|\- ]+$/gi;
	var val_email=/^[\w,\.]+\@+[\w]+\.+([a-z]{2,})$|(^[\w,\.]+\@+[\w]+\.+([a-z]{2,})+(\.)+([a-z]{2,})+$)/g;
	var fname = document.getElementById("fname").value;
	var passStr="password1";
	if(str=="newuser")
		passStr="password";

	if(!validateName(document.getElementById("fname"))){
		document.getElementById("mesgDiv").style.display="block";
		document.getElementById("mesg").innerHTML=$('enterFirstName').value;
		document.getElementById("fname").focus();
		return false;

	} else if(!fname.match(val_name)) {
		document.getElementById("mesgDiv").style.display="block";
		document.getElementById("mesg").innerHTML=$('validFirstName').value;
		document.getElementById("fname").focus();
		return false;
	} else if(!validateName(document.getElementById("lname"))){
		document.getElementById("mesgDiv").style.display="block";
		document.getElementById("mesg").innerHTML=$('enterLastName').value;
		document.getElementById("lname").focus();
		return;
	} else if(!document.getElementById("lname").value.match(val_name)) {
		document.getElementById("mesgDiv").style.display="block";
		document.getElementById("mesg").innerHTML=$('validLastName').value;
		document.getElementById("lname").focus();
		return false;
	}else if(!validateName(document.getElementById("sname"))){
		document.getElementById("mesgDiv").style.display="block";
		document.getElementById("mesg").innerHTML=$('enterScreenName').value;
		document.getElementById("sname").focus();
		return;
	}else if(!document.getElementById("sname").value.match(val_name)) {
		document.getElementById("mesgDiv").style.display="block";
		document.getElementById("mesg").innerHTML=$('validScreenName').value;
		document.getElementById("sname").focus();
		return false;
	}else if(!validateName(document.getElementById("password1"))){
		document.getElementById("mesgDiv").style.display="block";
		document.getElementById("mesg").innerHTML=$('providePassword').value;
		document.getElementById("password1").focus();
		return;
	}/*else if(!inValidCharSet(document.getElementById("password1"), " #&%\\'+ ")) {
	document.getElementById("mesgDiv").style.display="block";
			document.getElementById("mesg").innerHTML="Please enter valid password name ";
			document.getElementById("password1").focus();
			return false;
		}*/else if(password.length <=5){
			document.getElementById("mesgDiv").style.display="block";
			document.getElementById("mesg").innerHTML=$('minimumLetters').value;
			document.getElementById("password1").focus();
			return;
		}else if(!validateName(document.getElementById("cfpassword"))){
			document.getElementById("mesgDiv").style.display="block";
			document.getElementById("mesg").innerHTML=$('enterConfirmPassword').value;
			document.getElementById("cfpassword").focus();
			return;
		}/* else if(!inValidCharSet(document.getElementById("cfpassword"), " #&%\\'+ ")) {
	document.getElementById("mesgDiv").style.display="block";
			document.getElementById("mesg").innerHTML="Please enter valid searchActiveUser password";
			document.getElementById("cfpassword").focus();
			return false;
		}*/else if(cfpassword.length <=5){
			document.getElementById("mesgDiv").style.display="block";
			document.getElementById("mesg").innerHTML=$('minimumLetters').value;
			document.getElementById("cfpassword").focus();
			return;
		}else if(password!=cfpassword){
			document.getElementById("mesgDiv").style.display="block";
			document.getElementById("mesg").innerHTML=$('equalConfirmPassword').value;
			document.getElementById("cfpassword").focus();
			return;
		}else if($("register-email").value == ""){			
			document.getElementById("mesgDiv").style.display="block";
			document.getElementById("mesg").innerHTML=$('provideEmailId').value;
			document.getElementById("register-email").focus();
			return false;
		}else if(!isRFC822ValidEmail($("register-email").value.strip())){			
			/**
			* Author: vveerabathini
			* Bug: DS - 3681
			* Fix: used isRFC822ValidEmail() to validate email address
			*/
			document.getElementById("mesgDiv").style.display="block";
	document.getElementById("mesg").innerHTML=$('validEmailId').value;
	document.getElementById("register-email").focus();
	return false;
		}else if(!validateCaptcha(document.getElementById("captcha"))){
			document.getElementById("mesgDiv").style.display="block";
			document.getElementById("mesg").innerHTML=$('textCasesensitive').value;	
			document.getElementById("captcha").focus();
			return false;
		}else if(!agg){
			document.getElementById("mesgDiv").style.display="block";
			document.getElementById("mesg").innerHTML=$('acceptTermsService').value;	
			return false;
		}
	return true;
}

var forgotPasssword=0;   
function getPassword(){

	if(forgotPasssword != 0) {
		return;
	}

	if(validateForgotPassword()){
		/*@Author :spenumatsa
		 *@Bug : DS-4385 : User receiving more than one "password reset instructions" mails when he click's more than once on submit button in forgot password field.
		 * */
		//disablethisSubmmitButton('forgotsubmit');
		$('recipientDiv').innerHTML =$('forgot-email').value;
		if(document.getElementById('login-popup'))
		{
			hidepopup('login-popup');
		}
		postForm(document.forgotpasswordform, forgotPasswordResponseHandler);	     

	}	
}

function checkforgotPasssword(){
	if(forgotPasssword==1){
		return false;
	} else if(forgotPasssword==0){
		return true;
	}
}

function disablethisSubmmitButton(id){
	$(id).href="javascript:void(0);";
	$(id).className="button-gray";  
	forgotPasssword=1;		 
}


function forgotPasswordResponseHandler(resp) {
	if(document.getElementById('login-popup'))
	{
		showpopupwindow('login-popup');
	}
	/*@Author :spenumatsa
	 *@Bug : DS-4385 : User receiving more than one "password reset instructions" mails when he click's more than once on submit button in forgot password field.
	 * */
	//enableSubmitButton('forgotsubmit');
	var responseTxt = resp.responseText;
	if($('loader'))
	{
		hideloader();
	}
	//alert(responseTxt);
	if(responseTxt.indexOf("<state>false</state>")>0) {
		document.getElementById("forgot-pwd-div").style.display="block";
		document.getElementById("forgot-pwd-div").innerHTML="<p>"+$('notFoundEmail').value+"</p>";

	} else if(responseTxt.indexOf("<state>true</state>")>0) {
		document.getElementById("forgot-pwd-div").style.display="none";
		document.getElementById("forgotPwd").style.display="none";

		document.getElementById("successMessage").style.display="block";
		//document.getElementById("forgot-pwd-div").innerHTML="<p>Your account details have been emailed to you. <a href='javascript:viewloginpopup();'>Login</a> now.</p>";
	}else if(responseTxt.indexOf("<userStatus>PENDING</userStatus>")>0){
		document.getElementById("forgot-pwd-div").style.display="block";
		document.getElementById("forgot-pwd-div").innerHTML="<p>Sorry, your account has not yet been activated.</p>";
	}
}

function disablethisSubmmitButton(id){
	$(id).href="javascript:void(0);";
	$(id).className="button-gray"; 	
	forgotPasssword=1;
	passwordUser=1;
}


function validateForgotPassword(){
	if(!validateName(document.getElementById("forgot-email"))){

		document.getElementById("forgot-pwd-div").style.display="block";
		document.getElementById("forgot-pwd-div").innerHTML= "<p>"+$('enterEmailAddress').value+"</p>";
		document.getElementById("forgot-email").focus();
		return false;

	}else if(!isRFC822ValidEmail($("forgot-email").value.strip())){
		/**
		 * Author: vveerabathini
		 * Bug: DS - 3681
		 * Fix: used isRFC822ValidEmail() to validate email address
		 */
		document.getElementById("forgot-pwd-div").style.display="block";
		document.getElementById("forgot-pwd-div").innerHTML="<p>"+$('validEmail').value+"</p>";
		document.getElementById("forgot-email").focus();
		return false;
	}
	return true;
}


function validateName(obj) {
	if(obj!=null){
		if(obj.value.strip() ==""){
			return false;
		}
	}
	obj.value = obj.value.strip();
	return true;
}

function listPage(url) {
	window.location.href = url;
}

function submitRegisterForm() {
	isRegisterExist();
	return false;
}

function submitForgotpwdForm() {
	getPassword();
	return false;
}

/**
 * Author: vveerabathini
 * Bug: DS - 4445 OOC : User getting a page with the True or False upon pressing on enter key after giving valid and invalid email id in the forgot password field.
 * Fix: Added new method for occ forgot-password form
 */
function submitForgotpwdOccForm() {
	getPasswordUser();
	return false;
}	

function cancelPrivateRegister() {
	$("anon-registration").hide();
	$("anon-login").show();
}

function enableOocSubmitButton(id){		
	$(id).className="notify";
	passwordUser=0;
}

var passwordUser=0;
function getPasswordUser(){	  
	if(passwordUser != 0) {
		return;
	}		
	if(validateForgotPasswordUser()){
		disablethisSubmmitButton('oocSubmit');				
		postForm(document.forgotpasswordformUser, forgotPasswordResponseHandlerUser);			
	}		
}  

function validateForgotPasswordUser(){

	//alert(document.getElementById("forgot-email-user").value);
	if(!validateName(document.getElementById("forgot-email-user"))){

		document.getElementById("forgot-pwd-divuserSuccess").style.display="none";
		document.getElementById("forgot-pwd-divuser").style.display="block";
		document.getElementById("forgot-pwd-divuser").innerHTML= "<p>"+$('enterEmailAddress').value+"</p>";
		document.getElementById("forgot-email-user").focus();
		return false;

	}else if(!isRFC822ValidEmail($("forgot-email-user").value.strip())){
		/**
		 * Author: vveerabathini
		 * Bug: DS - 3681
		 * Fix: used isRFC822ValidEmail() to validate email address
		 */
		document.getElementById("forgot-pwd-divuserSuccess").style.display="none";
		document.getElementById("forgot-pwd-divuser").style.display="block";
		document.getElementById("forgot-pwd-divuser").innerHTML="<p>"+$('validEmail').value+"</p>";
		document.getElementById("forgot-email-user").focus();
		return false;
	}
	return true;
}
function forgotPasswordResponseHandlerUser(resp) {
	var responseTxt = resp.responseText;
	enableOocSubmitButton("oocSubmit");
	//	alert(responseTxt);
	if(responseTxt.indexOf("<state>false</state>")>0) {
		document.getElementById("forgot-pwd-divuserSuccess").style.display="none";
		document.getElementById("forgot-pwd-divuser").style.display="block";
		document.getElementById("forgot-pwd-divuser").innerHTML="<p>"+$('notFoundEmail').value+"</p>";
	} else if(responseTxt.indexOf("<state>true</state>")>0) {
		document.getElementById("forgot-pwd-divuser").style.display="none";
		$("forgot-email-user").value="";
		//document.getElementById("forgotPwd").style.display="none";
		document.getElementById("forgot-pwd-divuserSuccess").style.display="block";
		document.getElementById("forgot-pwd-divuserSuccess").innerHTML="<p>"+$('accountDetailsEmail').value+" <a href='javascript:showforgotUser();'>"+$('loginJs').value+"</a>&nbsp;"+$('nowJs').value+"</p>";
	}
}
//profile.js
var gridXmlObj = [];
function switchProfileTab(url){
	//$("sortBy").value=tabId;

	window.location.href=url;
}
function submitThisForm() {
	changePassword();
	return false;
}
function changePassword(){
	var val = $("pwd").value.strip();
	var CurrentPwdVal = $('currentPassword').value.strip();

	try{
		if(isValidPasswordForm(val)){ 
			var pwd1=$('newPassword').value;
			var pwd2=$('cfPassword').value; 
			if(CurrentPwdVal=="" || CurrentPwdVal==null)
			{	
				$('result').style.display='block';
				$('result').innerHTML = $('enterCurrentPassword').value;
			}
			else if(val != CurrentPwdVal){
				$('result').style.display='block';
				$('result').innerHTML = $('inncorrectCurrentPassword').value;
			}
			else if(pwd1==pwd2){

				postForm(document.editPasswordForm,passwordChangeCallback);
				$('cfPassword').value=pwd2;
				$('password').value=pwd2;
			}else{
				$('result').style.display='block';
				$('result').innerHTML = $('newPwdConfirmPwd').value;
			}
		}
	} catch(e){
		//alert(e);
	}

}


function passwordChangeCallback(resp){

	if(resp.status==200) {
		if(resp.responseText.indexOf('true')>0){
			$('pwd').value=$('newPassword').value;
			hidepopup('password-change-popup');
		}else if (resp.responseText.indexOf('false')>0){

		}else{ 
			gridXmlObj=[];	
			//hidepopup('password-change-popup');
			showPrfilepopup('password-confirmation-popup');
			gridXmlObj = buildObj(gridXmlObj,resp.responseXML.firstChild);
			var sitesHTML = "";
			var failedSitesHTML = "";

			/**
			 * @author: mkonusu
			 * @bug: DS - 3618
			 * @fix: if only one item is available then the object returns 
			 * undefined as length. added condition to compare undefined value
			 */
			if(gridXmlObj.collaborize.site.length == "undefined" || gridXmlObj.collaborize.site.length == undefined) {
				if(gridXmlObj.collaborize.site.siteStatus._value == "N") {
					sitesHTML = gridXmlObj.collaborize.site.siteName._value;
				} else {
					failedSitesHTML = gridXmlObj.collaborize.site.siteName._value;
				}
			} else {
				for(i =0; i< gridXmlObj.collaborize.site.length; i++) {
					var site = gridXmlObj.collaborize.site[i];
					if(site.siteStatus._value == "N") {
						sitesHTML += site.siteName._value + "<br>";
					} else {
						failedSitesHTML += site.siteName._value;
					}
				}
			}
			$("pwdAdminSites").innerHTML = sitesHTML;
			if(failedSitesHTML != "") {
				$("pwdFailedAdminSites").innerHTML = failedSitesHTML;
				$("pwdFailedSitesDiv").style.display = "";
			} else {
				$("pwdFailedSitesDiv").style.display = "none";
			}
			/**
			 * @author: vsharab
			 * @bug: DS - 5829
			 * @fix: added condition to hide the password popup for classroom sites
			 */
			hidepopup('password-change-popup');
            if(document.getElementById("siteType").value != 3){
                      showPrfilepopup('password-confirmation-popup');
                                  }
                               else{
	                        confirmPassword();
	                       hidepopup('password-confirmation-popup');				
                                   }
		                           }  
		
	                            }
                                }

function exportUserList(url){
	window.location.href=url;
}
function editProfile(){
	try{
		enableUserProfileButton("saveUserProfileId");
		$('editId').hide();
		$('usersuccess').hide();
		$('screenName').style.display='block';
		$('firstName').style.display="block";
		$('lastName').style.display="block";
		/**
		 *	@Author : mmalyala
		 *	@Bug : 3576 
		 *	@Fix : populating current values in edit text boxes.
		 */
		$('screenName').value=trim($('currentScreenName').value);
		$('firstName').value=trim($('currentFirstName').value);
		$('lastName').value=trim($('currentLastName').value);
		$('savebutton').style.display="block";
		$('scrn').style.display="none";
		$('first').style.display="none";
		$('last').style.display="none";

		//$('scrn').style.display="none";
	}catch(e){
		alert(e);
	}
}
function hideEditProfile(){
	try{
		$('editId').show();
		$('usersuccess').hide();
		$('userdetials').hide();
		$('screenName').style.display='none';
		$('firstName').style.display="none";
		$('lastName').style.display="none";
		$('savebutton').style.display="none";
		$('scrn').style.display="block";
		$('first').style.display="block";
		$('last').style.display="block";
		//$('scrn').style.display="none";
	}catch(e){
		alert(e);
	}
}
function profilePageControl(startNo, pageNo) {

	$('profileStartNo').value = startNo;
	$('profilePageNo').value = pageNo;
	submitForm('manageprofile', document.paginationForm);
}
function mytopicsPageControl(startNo, pageNo) {

	$('profileStartNo').value = startNo;
	$('profilePageNo').value = pageNo;
	submitForm('pagecontent', document.paginationForm);
}

function inboxPageControl(startNo, pageNo) {

	$('profileStartNo').value = startNo;
	$('profilePageNo').value = pageNo;
	submitForm('pagecontent', document.paginationForm);
}


function saveUserProfile(screen){
	try{
		$('usersuccess').innerHTML='';
		if(isValidateUserForm(screen)){
			postForm(document.editprofileForm,saveUserProfileCallback);
		}else{
			enableUserProfileButton("saveUserProfileId");
		}
	}catch(e){
		alert(e);
	}
}

function enableUserProfileButton(id){	
	if($(id) != null){
		$(id).href="javascript:saveUserProfile();";
		$(id).className="button small primary vote";  
	}

}


function isValidPasswordForm(password){
	var cpassword = trim($("currentPassword").value);
	var npassword = trim($("newPassword").value);
	var cfpassword = trim($("cfPassword").value);
	//var file = document.getElementById("file").value;

	//alert(cpassword +' '+npassword +' '+cfpassword);
	var msg = "";
	if((cpassword!="" && cpassword!=null && cpassword.length>0) || (npassword!="" && npassword!=null && npassword.length>0) || (cfpassword!="" && cfpassword!=null && cfpassword.length>0) ){

		if(cpassword=="" || cpassword==null ||cpassword.length==0){

			//msg=$('enterCurrentPassword').value;
			$("currentPassword").focus();
		}else if(npassword.length<=5){
			msg=$('minimumLetters').value;
			$("newPassword").focus();
			if(npassword=="" || npassword==null  || npassword.indexOf(' ')>=0 ){	
				//message need to be change
				msg=$('enterNewPassword').value;
				$("newPassword").focus();
			} 
		}else if(cfpassword.length<=5){
			msg=$('minimumconformLetters').value;
			$("cfPassword").focus();
			if(cfpassword=="" || cfpassword==null || cfpassword.indexOf(' ')>=0 ){	
				msg=$('enterNewCofirmPassword').value;
				$("cfPassword").focus();
			}
		}else if(npassword!=cfpassword){
			msg=$('newPwdConfirmPwd').value;

			$("cfPassword").focus();	
		}else if(cpassword == npassword){
			msg=$('newPwdCurrentPwd').value;
			$("newPassword").focus();
		}
		/*else if(!inValidCharSet($("newPassword"), " #&%\\'+ ")) {
				msg="Please enter valid new password.";
				$("newPassword").focus();
			}*/

		/*else if(!inValidCharSet($("cfrPassword"), " #&%\\'+ ")) {
					msg="Please enter valid confirm new password.";

					$("cfrPassword").focus();
			}*/
		else{
			if(npassword!=cfpassword){
				msg=$('newPwdConfirmPwd').value;
				$("cfrPassword").focus();
			}

		}
	}

	if(msg==""){
		return true;
	}else{
		$("result").style.display='block';
		$("result").innerHTML=msg;
		//document.getElementById("").style.display="block";				
		return false;
	}

}
function inValidCharSet(objValue,charset)
{
	var result = true;
	var str = objValue.value.strip();
	if (str.length <= 0) {
		result = true;
	}

	for (var i = 0; i < str.length; i = i + 1) {
		if (charset.indexOf(str.substr(i, 1)) > 0) {
			result = false;
			break;
		}
	}
	return result;
}
function isValidateUserForm(screen){

	var fname = $("firstName").value.strip();
	var lname = $("lastName").value.strip();
	var sname = $("screenName").value.strip();
	var val_name=/^[\w|\.|\- ]+$/gi;

	var msg = "";
	if(sname=="" || sname==null ||sname.length==0){
		msg=$('enterScreenName').value;
		$("screenName").focus();
	} else if(!sname.match(val_name)) {
		msg=$('validScreenName').value;
		$("screenName").focus();
	}else if(sname.length<3){
		/*@Author : spenumatsa
		@Bug : DS-4230 
          @Fix : checking for minimum 3 character length for screen name ,first name and last name.
		 */
		msg=$('validScreenNameMin').value;
		$("screenName").focus();
	}else if(fname=="" || fname==null ||fname.length==0){
		msg=$('enterFirstName').value;
		$("firstName").focus();
	} else if(!fname.match(val_name)) {
		msg=$('validFirstName').value;
		$("firstName").focus();
	}else if(fname.length<3){
		msg=$('validFirstNameMin').value;
		$("firstName").focus();
	}else if(lname=="" || lname==null ||lname.length==0){
		msg=$('enterLastName').value;
		$("lastName").focus();
	}else if(!lname.match(val_name)) {
		msg=$('validLastName').value;
		$("lastName").focus();
	}else if(lname.length<3){
		msg=$('validLastNameMin').value;
		$("lastName").focus();
	}

	if(msg==""){
		return true;
	}else{
		$('userdetials').style.display="block";
		$('usersuccess').style.display="none";
		$('userdetials').innerHTML=msg;
		return false;
	}
}
function saveUserProfileCallback(resp){
	//alert(resp.responseText)
	if(resp.status==200) {

		gridXmlObj=[];	
		gridXmlObj = buildObj(gridXmlObj,resp.responseXML.firstChild);
		//var value = gridXmlObj.collaborize.Message._value;
		$('editId').show();
		$('scrn').innerHTML=$('screenName').value.strip();
		$('first').innerHTML=$('firstName').value.strip();
		$('last').innerHTML=$('lastName').value.strip();
		/**
		 *	@Author : mmalyala
		 *	@Bug : 3576 
		 *	@Fix : newly updated values are stored in hidden fields.
		 */
		$('currentScreenName').value=$('screenName').value.strip();
		$('currentFirstName').value=$('firstName').value.strip();
		$('currentLastName').value=$('lastName').value.strip();

		$('userdetials').style.display="none";
		$('usersuccess').style.display="block";
		$('usersuccess').innerHTML = gridXmlObj.collaborize.Message._value;
		$('screenName').style.display='none';
		$('firstName').style.display="none";
		$('lastName').style.display="none";
		$('savebutton').style.display="none";
		$('scrn').style.display="block";
		$('first').style.display="block";
		$('last').style.display="block";

	}
}


function showWeekDayOption() {

	if($('dailynotify').checked || $('nonenotify').checked) {
		disableWeekDay();
	} else {
		enableWeekDay();
	}
}
function showWeekDayOptionUnsubscribe() {

	if($('dailynotify').checked || $('nonenotify').checked == false) {
		disableWeekDay();
	} else {
		enableWeekDay();
	}
}

function disableWeekDay() {
	$('weekday').selectedIndex = 0;
	$('weekday').disabled = true;
}

function enableWeekDay() {
	$('weekday').selectedIndex = 0;
	$('weekday').disabled = false;
}
function updateSettings(url){
	document.getElementById('result').style.display="block";
	if(document.getElementById("unsubSiteEmailsEnabled")!=null) {
		if(document.getElementById("unsubSiteEmailsEnabled").checked){
			url = url+"&unsubSiteEmailsEnabled=true";
		}
	}
	if(document.getElementById("fwdMsgGrpMemtoEmailEnabled").checked){
		url = url+"&fwdMsgGrpMemtoEmailEnabled=true";
	}
	if(document.getElementById("fwdmsgModeratorToEmailEnabled").checked){
		url = url+"&fwdmsgModeratorToEmailEnabled=true";
	}	 
	if(document.getElementById("subscribeNewCommentEnabled")!=null &&
			document.getElementById("subscribeNewCommentEnabled").checked){
		url = url+"&subscribeNewCommentEnabled=true";
	}else{
		url = url+"&subscribeNewCommentEnabled=false";
	}
	if(document.getElementById("subscribeNewTopicEnabled")!=null &&
			document.getElementById("subscribeNewTopicEnabled").checked){
		url = url+"&subscribeNewTopicEnabled=true";
	}else{
		url = url+"&subscribeNewTopicEnabled=false";
	}
	if(document.getElementById("subscribeNewUserEnabled")!=null && 
			document.getElementById("subscribeNewUserEnabled").checked){
		url = url+"&subscribeNewUserEnabled=true";
	}else{
		url = url+"&subscribeNewUserEnabled=false";
	}
	if(document.getElementById("dailynotify")!=null && 
			document.getElementById("dailynotify").checked){
		url = url+"&daily=true&weekly=false&dayofweek=0";
	}else if(document.getElementById("weeklynotify")!=null && 
			document.getElementById("weeklynotify").checked){
		var dow = document.getElementById("weekday").value;
		url = url+"&daily=false&weekly=true&dayofweek="+dow;
	}else{
		url = url+"&daily=false&weekly=false&dayofweek=0";
	}
	//alert(url);
	loadDivContent('result',url);
}

/* unsubscribe: This function is used for appending the conditions to the URL and then to process the request. */ 	
function updateUnsubscribeSettings(url){

	if(document.getElementById("unsubSiteEmailsEnabled")!=null) {
		if(document.getElementById("unsubSiteEmailsEnabled").checked){
			url = url+"&unsubSiteEmailsEnabled=true";
		}
	}
	if(document.getElementById("fwdMsgGrpMemtoEmailEnabled").checked){
		url = url+"&fwdMsgGrpMemtoEmailEnabled=true";
	}
	if(document.getElementById("fwdmsgModeratorToEmailEnabled").checked){
		url = url+"&fwdmsgModeratorToEmailEnabled=true";
	}	 
	if(document.getElementById("subscribeNewCommentEnabled")!=null &&
			document.getElementById("subscribeNewCommentEnabled").checked){
		url = url+"&subscribeNewCommentEnabled=true";
	}else{
		url = url+"&subscribeNewCommentEnabled=false";
	}
	if(document.getElementById("subscribeNewTopicEnabled")!=null &&
			document.getElementById("subscribeNewTopicEnabled").checked){
		url = url+"&subscribeNewTopicEnabled=true";
	}else{
		url = url+"&subscribeNewTopicEnabled=false";
	}
	if(document.getElementById("subscribeNewUserEnabled")!=null && 
			document.getElementById("subscribeNewUserEnabled").checked){
		url = url+"&subscribeNewUserEnabled=true";
	}else{
		url = url+"&subscribeNewUserEnabled=false";
	}
	/**
	*	@Author : Sricharan
	*	@Bug : 5277 
	*	@Fix : Condition was written so that when we disable the check box ,data will not sent to db.
	*/
	if(document.getElementById("nonenotify").checked == false)
	{
		url=url+"&daily=false&weekly=false&dayofweek=0";
	}
	if(document.getElementById("dailynotify")!=null && 
			document.getElementById("dailynotify").checked){
		url = url+"&daily=true&weekly=false&dayofweek=0";
	}else if(document.getElementById("weeklynotify")!=null && 
			document.getElementById("weeklynotify").checked){
		var dow = document.getElementById("weekday").value;
		url = url+"&daily=false&weekly=true&dayofweek="+dow;
	}else{
		url = url+"&daily=false&weekly=false&dayofweek=0";
	}
	url = url+"&userId="+document.getElementById("userId").value;
	//alert(url);
	loadDivContent('subResult',url,respunsubscribe);
}
function respunsubscribe(resp) {

	document.getElementById('outerWrapperThanku').style.display="block";
	document.getElementById('settingsContent').style.display="none";
}
function changeProfileTab(ele)
{	
	var DivIds = new Array();
	DivIds[0] = "topicsdivId";
	DivIds[1] = "activitydivId";
	DivIds[2] = "watchlistdivId";
	DivIds[3] = "inboxdivId";
	DivIds[4] = "settingsdivId";
	var _changeelement = ele.parentNode.parentNode;
	for (i=0;i<DivIds.length;i++)
	{
		$(DivIds[i]).hide();
		document.getElementsByClassName("tab-selected")[0].className="tab-normal";

		if(ele.innerHTML=="Topics")
		{
			_changeelement.className="tab-selected";
			$('topicsdivId').show();
		}
		else if(ele.innerHTML=="Activity")
		{
			_changeelement.className="tab-selected";
			$('activitydivId').show();
		}
		else if(ele.innerHTML=="Watch List(s)")
		{
			_changeelement.className="tab-selected";
			$('watchlistdivId').show();
		}
		else if(ele.innerHTML=="Inbox")
		{
			_changeelement.className="tab-selected";
			$('inboxdivId').show();
		}
		else if(ele.innerHTML=="Settings")
		{
			_changeelement.className="tab-selected";
			$('settingsdivId').show();
		}
	}
}

function showpopup(ele)
{

	var PopupIds = new Array();
	PopupIds[0] = "notificationPopupId";
	PopupIds[1] = "newuserpopup";
	PopupIds[2] = "importlistpopup";
	PopupIds[3] = "moderatorMessageDiv";
	PopupIds[4] = "importTopicsPopup";

	for (i=0;i<PopupIds.length;i++)
	{

		if($(PopupIds[i])!=undefined)
			$(PopupIds[i]).hide();
		if(ele.id=="showmessageId")
		{
			$('notificationPopupId').show();
		}
		else if(ele.id=="newuserId")
		{
			$('newuserpopup').show();
		}
		else if(ele.id=="importlistId")
		{
			$('importlistpopup').show();
		}
		else if(ele.id=="moderatorMessageId")
		{
			$('moderatorMessageDiv').show();
		}
		else if(ele.id=="importTopicsId")
		{
			$('importTopicsPopup').show();
		}
	}
}


function showTab(url){
	window.location.href=url;
}


function showNotificationDiv(userId,screenName,topicId)
{
	window.scrollTo(0,0);
	var android = (navigator.appVersion.indexOf("Android") == -1) ? false : true;
	var title = null;
	try{
		if(topicId!=null) {
			title = $('tTitle_'+topicId).innerHTML;
			title = title.unescapeHTML();
		} else {
			title = " ";
		}
		/**
			  @Author : vveerabathini
			  @Bug : 4361 Displaying "To" field as blank when we try to send message from "My Topics" page of profile in particular scenario 
			  @Fix : Changed input field name of to file toMailId
		 */
		$('toMailId').value=screenName;
		$('subject').value=title!=null?title:title='';
		$('isSingle').value= "true";
		$('ids').value=userId;
		if(ipad || iphone || android){
			$('msgcontent').value= "";
		}
		var ua = navigator.userAgent.toLowerCase();
		if(ua.indexOf('msie') != -1)
		{
			if(document.getElementById('inboxSortVal1'))
			{
				document.getElementById('inboxSortVal1').style.visibility='hidden';
			}

		}
		showpopupwindow('notificationPopupId');

	}catch(e){
		alert(e);
	}

}
function hidenewuserpopup(ele)
{
	$('notificationPopupId').hide();
	document.getElementById("opacitydiv").style.visibility = "hidden";
	var ua = navigator.userAgent.toLowerCase();
	if(ua.indexOf('msie') != -1)
	{
		if(document.getElementById('inboxSortVal1'))
		{
			document.getElementById('inboxSortVal1').style.visibility='visible';
		}

	}
}
function showNotificationPopup(ele)
{
	$('notificationPopupId').show();

}
function sendNotification(url,divId,ele){
	var ids=document.getElementById("ids").value;
	var isSingle = document.getElementById("isSingle").value;
	var subject=trim(document.getElementById("subject").value);
	var content=trim(document.getElementById("msgcontent").value);

	if(subject==""){
		document.getElementById("subject").focus();
		document.getElementById("showMsgResult").innerHTML="<b><br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"+$('resEnter_subject').value+"</b><br><br>";
		document.getElementById("showMsgResult").style.display="block";
		return ;
	}
	/*
 		 @Author : mmalyala
 		 @Bug No : 3865
	 	 @Fix    : subject length validation condition and message added. 		 	
	 */
	if(subject.length>150){
		document.getElementById("subject").focus();
		document.getElementById("showMsgResult").innerHTML="<b><br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"+$('resEnter_subject_length').value+"</b><br><br>";
		document.getElementById("showMsgResult").style.display="block";
		return ;
	}
	if(content==""){
		document.getElementById("msgcontent").focus();
		document.getElementById("showMsgResult").innerHTML="<b><br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"+$('resEnter_message').value+"</b><br><br>";
		document.getElementById("showMsgResult").style.display="block";
		return ;
	}

	url +="&ids="+ids+"&isSingle="+isSingle+"&subject="+escape(subject)+"&content="+escape(content);
	loadDivContent(divId,url,function(){sendNotificationResult(ele)});
	document.getElementById("subject").value="";
	document.getElementById("msgcontent").value="";
	document.getElementById("opacitydiv").style.visibility = "hidden";
	var ua = navigator.userAgent.toLowerCase();
	if(ua.indexOf('msie') != -1)
	{
		if(document.getElementById('inboxSortVal1'))
		{
			document.getElementById('inboxSortVal1').style.visibility='visible';
		}

	}
}
function sendNotificationResult(ele){		
	//document.getElementById("showResult").style.display="block";		
	//document.getElementById("showResult").innerHTML="<b>Messege Sent successfully</b><br><br>";
	document.getElementById("showMsgResult").innerHTML=" ";
	document.forms[0].reset();
	if(document.getElementById("showMsgResult").style.display=="block")
		document.getElementById("showMsgResult").style.display="none";
	document.getElementById("notificationPopupId").style.display="none";  
}


function checkAllMsg(divObj1,divObj2,divObj3)
{
	var selectedSections;
	var checkAll = document.getElementById(divObj1);
	var allLocs = document.getElementsByName(divObj2);	
	var checkAll1 = document.getElementById(divObj3);
	if(checkAll.checked)
	{
		for(i=0;i<allLocs.length;i++)
		{
			if(!allLocs[i].disabled) {
				allLocs[i].checked = true; 
			}
		}
		checkAll1.checked = true;
	}
	if(checkAll.checked==false)
	{
		for(i=0;i<allLocs.length;i++)
		{
			if(!allLocs[i].disabled) {
				allLocs[i].checked = false;
			}
		}
		checkAll1.checked = false;
	}
}

function checkMsgItems(srcObjName, targetObjName,targetObjName1) {
	if(isMsgChecked(srcObjName)) {
		document.getElementById(targetObjName).checked = true;
		document.getElementById(targetObjName1).checked = true;
	} else {
		document.getElementById(targetObjName).checked = false;
		document.getElementById(targetObjName1).checked = false;
	}
}

function isMsgChecked(srcObjName) {
	var  obj = document.getElementsByName(srcObjName);
	var exists = true;
	if(obj.length>0) {
		for(i=0;i<obj.length;i++) {
			if(!obj[i].checked) {
				exists = false;
				break;
			}
		}
	}
	return exists;
}

function markAsRead(url,divId,ele){
	if(document.getElementById("mesgResult").style.display=="block")
		document.getElementById("mesgResult").style.display="none";

	var itemIds =  $('managemessages').getElementsByTagName('input');
	var ids = "";

	var idCnt = 0;
	for(i=0;i<itemIds.length;i++) {
		if(itemIds[i].checked){
			idCnt = idCnt  + 1;
			ids += itemIds[i].value+",";

		}
	}
	if(ids!="" && ids.length>0){
		ids = ids.substring(0,ids.length-1);
	}else{
		document.getElementById("mesgResult").innerHTML="<b>"+$('selectOneMessage').value+"</b><br><br>";
		document.getElementById("mesgResult").style.display="block";
		return ;
	}
	url+="&ids="+ids+"&reqType=inbox";
	//window.location.href=url;
	var qs = new Querystring(url)

	loadDivContent('manageprofile',url,inboxCallBack);

}
function inboxCallBack(status,resp){ 
	$('inboxCount').innerHTML=$('inboxMsgCount').value; 
	if($('inboxMsgCount').value==0){
		$('inboxDropDown').style.display="none";
	}else{
		$('inboxDropDown').style.display="block";
	}
}
function unWatchedTopic(watchlistId,url,ele,divId,watchlistType){

	sendRequest(url+'&watchlistType='+watchlistType+'&watchlistId='+watchlistId,removeFromWatchListProfile);
}
function removeFromWatchListProfile(resp)
{
	var respString = resp.responseText;
	var respArray = respString.split(",");
	var typeArray = respArray[0].split("~");
	var watchlistType = typeArray[1];
	var  idArray = respArray[1].split("~");
	var watchlistId = idArray[1];
	var respMsgArray = respArray[2].split("~");
	var watchlistResp = respMsgArray[1];

	if(watchlistResp){

		chageProfileTab('watchlist-tab',$('removefromwatchlistURL').value);
	}

}
function checkAllMessages () {
	var checked=false;
	try{
		var collection = $('managemessages').getElementsByTagName('input');
		//alert( $('managemessages').getElementsByTagName('input')+','+collection.length+','+checked);
		if (checked == false){
			checked = true
		}
		else{
			checked = false
		}
		for (var x=0; x<collection.length; x++) {

			if (collection[x].type.toUpperCase()=='CHECKBOX'){

				collection[x].checked = checked;
			}
		}
	}catch(e){ alert(e);
	}
}
function unCheckAllMessages () {
	var checked=true;
	try{
		var collection = $('managemessages').getElementsByTagName('input');
		//alert( $('managemessages').getElementsByTagName('input')+','+collection.length+','+checked);
		if (checked == false){
			checked = true
		}
		else{
			checked = false
		}
		for (var x=0; x<collection.length; x++) {

			if (collection[x].type.toUpperCase()=='CHECKBOX'){

				collection[x].checked = checked;
			}
		}
	}catch(e){ alert(e);
	}
}

function checkReadMessages(ids) {

	var checked=true;
	try{
		var collectionUnCheck = $('managemessages').getElementsByTagName('input');
		for (var x=0; x<collectionUnCheck.length; x++) {

			if (collectionUnCheck[x].type.toUpperCase()=='CHECKBOX'){

				collectionUnCheck[x].checked = false;
			}
		}
		var collection = ids.split(',');
		//alert(collection.length);
		for (var x=0; x<collection.length; x++) {
			if($(collection[x])!=null){
				if($(collection[x]).type.toUpperCase()=='CHECKBOX'){
					$(collection[x]).checked = checked;
					//	alert(collection[x]);
				}
			}
		}
	}catch(e){ alert(e);
	}
}
function removeMessagesFromList(url,ele){
	if(document.getElementById("mesgResult").style.display=="block")
		document.getElementById("mesgResult").style.display="none";

	var itemIds = $('managemessages').getElementsByTagName('input');
	var ids = "";
	var idCnt = 0;
	for(i=0;i<itemIds.length;i++) {
		if(itemIds[i].checked){
			idCnt = idCnt  + 1;
			ids += itemIds[i].value+",";
		}
	}
	if(ids!="" && ids.length>0){
		ids = ids.substring(0,ids.length-1);
	}else{
		document.getElementById("mesgResult").innerHTML="<b>"+$('selectOneMessage').value+"</b><br><br>";
		document.getElementById("mesgResult").style.display="block";
		return ;
	}
	var startNo =$('profileStartNo').value;
	var pageNo = $('profilePageNo').value;
	//alert(pageNo+" "+startNo);
	url+="&messageIds="+ids+"&reqType=inbox"+"&profilepageNo="+pageNo+"&profilestartNo"+startNo;
	//window.location.href=url;
	loadDivContent('manageprofile',url,inboxCallBack);
}


function removeMessage(url,mesgId){
	window.location.href=url+"&messageIds="+mesgId+"&reqType=inbox";
}


function findPos(obj)
{
	var curleft = curtop = 0;
	if (obj.offsetParent)
	{
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		while (obj = obj.offsetParent)
		{
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
	}
	return [curleft,curtop];
}


function popupdisplay(ele)
{
	var m=document.getElementById("notificationPopupId");
	var myPos = new Array();
	myPos = findPos(ele);
	var fx = myPos[0];
	var fy = myPos[1];
	m.style.position="absolute";
	if(fx > 900 )
	{
		m.style.top = fy+'px';
		m.style.left = fx-330+'px';
	}

	else if(fx > 550 )
	{
		m.style.top = fy+25+'px';
		m.style.left = fx-380+'px';
	}

	else
	{
		if(ele.parentNode.id=='replyId')
		{
			var ua = navigator.userAgent.toLowerCase();
			if(ua.indexOf('msie') != -1)
			{
				m.style.top = fy+20+'px';
				m.style.left = fx-400+'px';
			}
			else
			{	
				m.style.top = fy+20+'px';
				m.style.left = fx-90+'px';
			}
		}

		else
		{
			m.style.top = fy+20+'px';
			m.style.left = fx-90+'px';
		}
	}
	try{
		m.style.display="block";
		//$("opacitydiv").style.visibility = "visible";
	}
	catch(e){alert(e);}
}

function gotoPage(url,pageType){
	var pageNo=Number(document.getElementById("cPageNo").value);
	var noOfPages = Number(document.getElementById("noOfPages").value);

	if(pageType=="last"){
		pageNo = noOfPages;
	}else if(pageType=="next"){
		pageNo = pageNo+1;
	}else if(pageType=="previous"){
		pageNo = pageNo-1;
	}else if(pageType=="first"){
		pageNo = 1;
	}else if(pageType=="page"){
		pageNo = Number(document.getElementById("listPage").value);	 
	}
	if(pageNo<=noOfPages)
		window.location.href = url+"&pageNo="+pageNo;
}


function gotoCommentsPage(url,pageType,listName,pos){


	var proPageNo=Number(document.getElementById("proPageNo").value);
	var proNoOfPages = Number(document.getElementById("proNoOfPages").value);

	if(listName=="proComments"){
		if(pageType=="last"){
			proPageNo = proNoOfPages;
		}else if(pageType=="next"){
			proPageNo = proPageNo+1;
		}else if(pageType=="previous"){

			proPageNo = proPageNo-1;
			if(proPageNo==0){
				proPageNo=1;

			}
		}else if(pageType=="first"){
			proPageNo = 1;
		}else if(pageType=="page"){

			if(pos==1){
				proPageNo = Number(document.getElementById("proCommentsListPage1").value);
			}
			if(pos==2){
				proPageNo = Number(document.getElementById("proCommentsListPage2").value);
			}

		}
		if(proPageNo<=proNoOfPages){

			window.location.href = url+"&pageNo="+proPageNo+"&type=Pro";
		}
	}else if(listName=="conComments"){
		var conPageNo=Number(document.getElementById("conPageNo").value);
		var conNoOfPages = Number(document.getElementById("conNoOfPages").value);

		if(pageType=="last"){
			conPageNo = conNoOfPages;
		}else if(pageType=="next"){
			conPageNo = conPageNo+1;
		}else if(pageType=="previous"){
			conPageNo = conPageNo-1;
			if(conPageNo==0){
				conPageNo=1;

			}
		}else if(pageType=="first"){
			conPageNo = 1;
		}else if(pageType=="page"){

			if(pos==1){
				conPageNo = Number(document.getElementById("conCommentsListPage1").value);
			}
			if(pos==2){
				conPageNo = Number(document.getElementById("conCommentsListPage2").value);
			}
		}
		if(conPageNo<=conNoOfPages){
			window.location.href = url+"&pageNo="+conPageNo+"&type=Con";
		}
	}
	else if(listName=='prosort'){

		var sortVal;
		if(pos==1){
			sortVal=document.getElementById("proSortColumn1").value;
		}
		if(pos==2){
			sortVal=document.getElementById("proSortColumn2").value;
		}

		if(sortVal=='dateAsc'){
			sortVal=sortVal+"&isAsc=true"
		}

		window.location.href = url+"&pageNo="+proPageNo+"&type=pro&sortBy="+sortVal;

	}else if(listName=='consort'){

		var conPageNo=Number(document.getElementById("conPageNo").value);
		var conNoOfPages = Number(document.getElementById("conNoOfPages").value);
		var sortVal;
		if(pos==1){
			sortVal=document.getElementById("conSortColumn1").value;
		}
		if(pos==2){
			sortVal=document.getElementById("conSortColumn2").value;
		}

		if(sortVal=='dateAsc'){
			sortVal=sortVal+"&isAsc=true"
		}

		window.location.href = url+"&pageNo="+conPageNo+"&type=con&sortBy="+sortVal;

	}

}

function gotoPage1(url,pageType,listName){
	var inboxpageNo=Number(document.getElementById("cInboxPageNo").value);
	var votespageNo=Number(document.getElementById("cVotesPageNo").value);
	var commentspageNo=Number(document.getElementById("cCommentsPageNo").value);
	var inboxnoOfPages = Number(document.getElementById("inboxnoOfPages").value);
	var votesnoOfPages = Number(document.getElementById("votesnoOfPages").value);
	var commentsnoOfPages = Number(document.getElementById("commentsnoOfPages").value);

	if(listName=="inbox"){		
		if(pageType=="last"){
			inboxpageNo = inboxnoOfPages;
		}else if(pageType=="next"){
			inboxpageNo = inboxpageNo+1;
		}else if(pageType=="previous"){
			inboxpageNo = inboxpageNo-1;
		}else if(pageType=="first"){
			inboxpageNo = 1;
		}else if(pageType=="page"){
			inboxpageNo= Number(document.getElementById("inboxPage").value);
		}
		if(inboxpageNo>inboxnoOfPages)
			inboxpageNo = Number(document.getElementById("cInboxPageNo").value); 

	}else if(listName=="votes"){
		if(pageType=="last"){
			votespageNo = votesnoOfPages;
		}else if(pageType=="next"){
			votespageNo = votespageNo+1;
		}else if(pageType=="previous"){
			votespageNo = votespageNo-1;
		}else if(pageType=="first"){
			votespageNo = 1;
		}else if(pageType=="page"){
			inboxpageNo= Number(document.getElementById("votesPage").value);
		}
		if(inboxpageNo>votesnoOfPages)
			inboxpageNo = Number(document.getElementById("cVotesPageNo").value); 	

	}else if(listName=="comments"){
		if(pageType=="last"){
			commentspageNo = commentsnoOfPages;
		}else if(pageType=="next"){
			commentspageNo = commentspageNo+1;
		}else if(pageType=="previous"){
			commentspageNo = commentspageNo-1;
		}else if(pageType=="first"){
			commentspageNo = 1;
		}else if(pageType=="page"){
			inboxpageNo= Number(document.getElementById("commentsPage").value);
		}
		if(inboxpageNo>commentsnoOfPages)
			inboxpageNo = Number(document.getElementById("cCommentsPageNo").value); 		

	}
	window.location.href = url+"&inboxpageNo="+inboxpageNo+"&votespageNo="+votespageNo+"&commentspageNo="+commentspageNo;
}




function sendModaratorPopup(ele)
{
	var m=document.getElementById("moderatorMessageDiv");
	var myPos = new Array();
	myPos = findPos(ele);
	var fx = myPos[0];
	var fy = myPos[1];
	m.style.position="absolute";
	if(fx > 700 )
	{
		m.style.top = fy+50+'px';
		m.style.left = fx-684+'px';
	}
	else
	{
		m.style.top = fy+20+'px';
		m.style.left = fx-10+'px';
	}
	m.style.display="block";
	$("opacitydiv").style.visibility = "visible";
	document.getElementById("inboxSortVal").style.visibility="hidden";
	document.getElementById("inboxSortVal1").style.visibility="hidden";
}


function showFwdDiv(ele)
{
	window.scrollTo(0,0);
	var myPos = new Array();
	myPos = findPos(ele);
	var fx = myPos[0];
	var fy = myPos[1];
	$("fwdDiv").style.top = fy-500+'px';
	$("fwdDiv").style.left = 50+'px';
	$("fwdDiv").style.display = 'block';
	$("opacitydiv-video").style.visibility = 'visible';
	if($('pwdemail'))
	{
		$('pwdemail').focus();
	}
	if($('fwdMainContent').style.display=="none"){	
		if($('mesg'))
		{
			$('mesg').style.display='none';
		}
		$('fwdMainContent').style.display='block';
		$('pwdemail').value="";
	}
}

function closeFwdDiv()
{
	$("fwdDiv").style.display = 'none';
	$("opacitydiv-video").style.visibility = 'hidden';
}

function forgotpassword(url){
	var pUrl = document.getElementById("pUrl").value;
	url = "/portal/portal/default/"+pUrl+"/"+pUrl+"-CollaborizeWindow?action=b&cacheability=PAGE&actionEvent=forgotpassword";
	var email = document.getElementById('pwdemail').value.strip();
	if(isRFC822ValidEmail(email)){
		/**
		* Author: vveerabathini
		* Bug: DS - 3681
		* Fix: used isRFC822ValidEmail() to validate email address
		*/
		loadDivContent('mesg2',url+'&email='+email,function(){showForgotResult()}); 
	}
} 
function showForgotResult(){
	var status = trim(document.getElementById("mesg2").innerHTML);
	if(status.indexOf("false")>=0){
		document.getElementById("result").innerHTML = $('notFoundEmail').value; 
	}else{
		document.getElementById("result").innerHTML = $('accountDetailsEmail').value;
	}
	document.getElementById('pwdresultmesg').style.display='block';
	document.getElementById('mesg1').style.display='none';
	document.getElementById('fwdMainContent').style.display='none';
}

function validateCurrentEmail(ele)
{	
	var retVal=true;
	var emailFilter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})$/;
	var uEmail = trim(ele.value);
	//var eEmail = document.getElementById('mesg1');

	if(uEmail == '') 
	{
		retVal = false; 
		emailError.innerHTML = $('enterEmailAddress').value+'<br/>';
		emailError.style.display = 'block';
	}else if(!emailFilter.test(uEmail)) 
	{
		retVal = false;
		emailError.innerHTML = $('validEmail').value+'<br/>';
		emailError.style.clor = 'red';
		emailError.style.display = 'block';
	}
	alert(retVal);
	return retVal; 
}




function changeeditorialTab(ele)
{

	var DivIds = new Array();
	DivIds[0] = "aboutusdivId";
	DivIds[1] = "privacydivId";
	DivIds[2] = "guideLinesdivId";
	DivIds[3] = "termsdivId";
	DivIds[4] = "contactUsdivId";

	var _changeelement = ele.parentNode.parentNode;

	for (i=0;i<DivIds.length;i++)
	{
		$(DivIds[i]).hide();
		document.getElementsByClassName("tab-selected-editorial")[0].className="tab-normal-editorial";

		if(ele.innerHTML==$('aboutUsTab').value)
		{
			_changeelement.className="tab-selected-editorial";
			$('aboutusdivId').show();
		}
		else if(ele.innerHTML==$('privacyPolicyTab').value)
		{
			_changeelement.className="tab-selected-editorial";
			$('privacydivId').show();
		}
		else if(ele.innerHTML==$('guideLinesTab').value)
		{
			_changeelement.className="tab-selected-editorial";
			$('guideLinesdivId').show();
		}
		else if(ele.innerHTML==$('termOfUseTab').value)
		{
			_changeelement.className="tab-selected-editorial";
			$('termsdivId').show();
		}
		else if(ele.innerHTML==$('contactUsTab').value)
		{
			_changeelement.className="tab-selected-editorial";
			$('contactUsdivId').show();
		}
	}
}

function sendMessege(url,divId,ele){

	var ids=document.getElementById("ids").value;
	var isSingle = document.getElementById("isSingle").value;
	var subject=trim(document.getElementById("subject").value);
	var android = (navigator.appVersion.indexOf("Android") == -1) ? false : true;
	if(!ipad && !iphone && !android){
		document.getElementById("msgcontent").value ="  "+instance3.e.body.innerHTML;
	}
	var content=trim(document.getElementById("msgcontent").value);
	if(ipad || iphone || android){
		var inboxContent = content;
	} else {
		$('plainTextDiv').innerHTML = instance3.e.body.innerHTML;
		var inboxContent = $('plainTextDiv').textContent || $('plainTextDiv').innerText;
	}

	content = content.anchorEntities();
	content = content.string_create_urls();
	content = content.specialCharacterEntities();
	if(subject==""){
		document.getElementById("subject").focus();
		document.getElementById("errorMessageDetails").style.display="block";
		document.getElementById("errorMessageDetails").innerHTML="<p>"+$('resEnter_subject').value+"</p>";
		return ;
	}
	/*
 			 @Author : mmalyala
 			 @Bug No : 3865
	 		 @Fix    : subject length validation condition and message added. 		 	
	 */
	if(subject.length>150){
		document.getElementById("subject").focus();
		document.getElementById("errorMessageDetails").innerHTML ="<p>"+$('resEnter_subject_length').value+"</p>";
		document.getElementById("errorMessageDetails").style.display="block";
		return ;
	}
	if(inboxContent == undefined || inboxContent == "undefined" || inboxContent.strip() == ""){
		document.getElementById("errorMessageDetails").innerHTML="<p>"+$('resEnter_message').value+"</p>";
		document.getElementById("errorMessageDetails").style.display="block";
		if(ipad || iphone || android){
			document.getElementById("msgcontent").value ="";
		} else {
			instance3.e.body.innerHTML ='';
		}
		return ;
	}
	if(validateCurseFilter1(content)) {
		url +="&ids="+ids+"&isSingle="+isSingle;
		$('messageText').value=content;
		//document.userForm.action = url;
		$('sendMsgId').action=url;
		postForm($('sendMsgId'),hidepopup('notificationPopupId'));
		//loadDivContent(divId,url,hidepopup('notificationPopupId'));
	}
	if(ipad || iphone || android){
		$('msgcontent').value = '';
	} else {
		instance3.e.body.innerHTML ='';
		instance3.defaultsetting();
	}
}
/*function showMessegeSentResult(){
		document.getElementById("showMsgResult").style.display="block";		
		document.getElementById("showMsgResult").innerHTML="<b>Message Sent successfully</b><br><br>";
		document.forms[0].reset();
		document.getElementById("notificationPopupId").style.display="none";  
	}*/

function showmessagebody(ele,id,status,url,divId){
	try{

		if($('msgbody_'+id).style.display =='none'){
			if($('mesgcol1_'+id).className!="content-td-greybg"){
				$('mesgcol1_'+id).className="content-td-greybg";
				$('mesgcol2_'+id).className="content-td-greybg";
				$('mesgcol3_'+id).className="content-td-greybg";
				url+="&ids="+id;
				loadDivContent('markAsReadSingleUrlResult',url,markAsReadCallback);
			}
			var ua = navigator.userAgent.toLowerCase();
			var ua_index = ua.indexOf('msie');
			if(ua.indexOf('msie') != -1)
			{
				$('msgbody_'+id).style.display="block";
			}
			else
			{
				$('msgbody_'+id).style.display="table";
			}
		}else{
			$('msgbody_'+id).style.display="none";
		}

	}catch(e){alert(e);}
}
function markAsReadCallback(){
	var cnt=$('inboxMsgCount').value; 
	$('inboxMsgCount').value = cnt-1; 
	if($('inboxMsgCount').value==0){
		$('inboxDropDown').style.display="none";
	}else{
		$('inboxDropDown').style.display="block";
		$('inboxCount').innerHTML=$('inboxMsgCount').value; 
	}
}
function memberActiveStatusCallback(){
	var cnt=$('activeMembersCount').value; 
	//$('approveMembersCount').value = cnt-1;
	if($('activeMembersCount').value==0) {
		$('active-tab').innerHTML=$('res_active').value+" ("+$('activeMembersCount').value+")"; 
	} else {
		$('active-tab').innerHTML=$('res_active').value+" ("+$('activeMembersCount').value+")"; 
	}
}
function memberStatusCallback(){
	var cnt=$('approveMembersCount').value; 
	//$('approveMembersCount').value = cnt-1;
	if($('approveMembersCount').value==0) {
		var url = $('activeUrl').value; 
		$('approveMembers').innerHTML=" "; 
		$('alert-popup').style.display="none"; 
		loadDivContent('pagecontent',url);
	} else {
		$('approveMembers').innerHTML=$('res_approveMembers').value+" ("+$('approveMembersCount').value+")"; 
		$('approval-tab').innerHTML=$('res_pendingApproval').value+" ("+$('approveMembersCount').value+")"; 
	}
}
function memberPendingStatusCallback(){
	var cnt=$('pendingactivationMembersCount').value; 
	//$('approveMembersCount').value = cnt-1;
	if($('pendingactivationMembersCount').value==0) {
		$('activation-tab').innerHTML=$('res_pendingActivation').value+" ("+$('pendingactivationMembersCount').value+")"; 
	} else {
		$('activation-tab').innerHTML=$('res_pendingActivation').value+" ("+$('pendingactivationMembersCount').value+")"; 
	}
}
function memberBlockedUserStatusCallback(){
	var cnt=$('blockedcount').value; 
	//$('approveMembersCount').value = cnt-1;
	if($('blockedcount').value==0) {
		$('active-tab').innerHTML=$('res_active').value+" ("+$('actMembersCount').value+")"; 
		$('blocked-tab').innerHTML=$('res_Blocked').value+" ("+$('blockedcount').value+")";  
	} else {
		$('active-tab').innerHTML=$('res_active').value+" ("+$('actMembersCount').value+")"; 
		$('blocked-tab').innerHTML=$('res_Blocked').value+" ("+$('blockedcount').value+")"; 
	}
}
function showmessagebodyback(ele,msgId,status,url,divId)
{ 
	var ua = navigator.userAgent.toLowerCase();
	if(ua.indexOf('msie')!=-1)
	{
		if(document.getElementsByClassName("messagebox-show").length==0)
		{
			ele.parentNode.parentNode.nextSibling.className='messagebox-show';
			ele.parentNode.parentNode.nextSibling.style.display="block";
		}
		else
		{
			document.getElementsByClassName("messagebox-show")[0].style.display="none";
			document.getElementsByClassName("messagebox-show")[0].className='messagebox-hide';
			ele.parentNode.parentNode.nextSibling.className='messagebox-show';
			ele.parentNode.parentNode.nextSibling.style.display="block";

		}
	}
	else
	{
		if(document.getElementsByClassName("messagebox-show").length==0)
		{
			ele.parentNode.parentNode.nextSibling.nextSibling.className='messagebox-show';
			ele.parentNode.parentNode.nextSibling.nextSibling.style.display="block";
		}
		else
		{
			document.getElementsByClassName("messagebox-show")[0].style.display="none";
			document.getElementsByClassName("messagebox-show")[0].className='messagebox-hide';
			ele.parentNode.parentNode.nextSibling.nextSibling.className='messagebox-show';
			ele.parentNode.parentNode.nextSibling.nextSibling.style.display="block";

		}       
	}
	if(status=="UNREAD"){
		url=url+"&ids="+msgId;
		loadDivContent(divId,url,function(){showReadResult(ele)});
		ele.style.fontWeight="normal";
	}

}


/* Client-side access to querystring name=value pairs
	Version 1.3
	28 May 2008

	License (Simplified BSD):
	http://adamv.com/dev/javascript/qslicense.txt
 */
function Querystring(qs) { // optionally pass a querystring to parse
	this.params = {};

if (qs == null) qs = location.search.substring(1, location.search.length);
if (qs.length == 0) return;

//Turn <plus> back to <space>
//See: http://www.w3.org/TR/REC-html40/interact/forms.html#h-17.13.4.1
qs = qs.replace(/\+/g, ' ');
var args = qs.split('&'); // parse out name/value pairs separated via &

//split out each name=value pair
for (var i = 0; i < args.length; i++) {
	var pair = args[i].split('=');
	var name = decodeURIComponent(pair[0]);

	var value = (pair.length==2)
	? decodeURIComponent(pair[1])
			: name;

	this.params[name] = value;
}
}

Querystring.prototype.get = function(key, default_) {
	var value = this.params[key];
	return (value != null) ? value : default_;
}

Querystring.prototype.contains = function(key) {
	var value = this.params[key];
	return (value != null);
}

function showReplyDiv(userId,screenName,replyId)
{
	var replySubject = null;
	try{
		if(replyId!=null) {
			replySubject = $('subject_'+replyId).innerHTML;
			replySubject = replySubject.unescapeHTML();
		} else {
			replySubject = " ";
		}
		/* @author pgudipalli
		 * @bug:     DS-4467* 
			@fix: Changed the Id for The to text field */ 
		document.getElementById("toMailId").value=screenName;
		document.getElementById("subject").value=replySubject!=null?replySubject:replySubject='';
		document.getElementById("isSingle").value= "true";
		document.getElementById("ids").value=userId;
		var ua = navigator.userAgent.toLowerCase();
		if(ua.indexOf('msie') != -1)
		{
			if(document.getElementById('inboxSortVal1'))
			{
				document.getElementById('inboxSortVal1').style.visibility='hidden';
			}

		}
		showpopupwindow('notificationPopupId');

	}catch(e){
		alert(e);
	}

}

function showEmailEdit(){
	$('currentEmail').value=$('current').value;
	clearEmailChangePopup();
	showPrfilepopup('email-change-popup');
}
function showEmailRequest(){
	$('currentEmail').value=$('current').value;
	clearEmailReqPopup();
	showPrfilepopup('email-request-popup');
}
function showEmailApprovePopup(userId,emailId,reqEmail,name){
	$('frmAppMail').innerHTML=emailId;
	$('toAppMail').innerHTML=reqEmail;
	$('userFrName').innerHTML=name;
	$('reqEmail').value=reqEmail;
	$('reqUserId').value=userId;
	showPrfilepopup('email-approve-popup');
}
function clearEmailChangePopup() {
	$("newEmail").value= "";
	$("cfEmail").value= "";
}
function clearEmailReqPopup() {
	$("newEmailReq").value= "";
	$("cfEmailReq").value= "";
}


function showPrfilepopup(id)
{

	var Container = $('view');
	window.scrollTo(0,0);	
	var myPos = new Array();
	myPos = findPos(Container);
	var fx = myPos[0];
	var fy = myPos[1];
	$(id).show();
	if(id == 'email-change-popup')
	{
		$('emailError').style.display="none";
		$('currentEmail').value=$('current').value;
		$(id).style.top = fy+200+'px';
		$(id).style.left = fx+300+'px';
	}else if(id == 'email-request-popup')
	{
		/**
		* @author mmalyala
		* @bug : 4045 Alert continue to display in "request for change of email " window even after cancel
		* @fix : Hide alert div while open the popup.
		*/
		if($('emailReqError')){
			$('emailReqError').style.display="none";
		}
		$('currentEmailReq').value=$('current').value;
		$(id).style.top = fy+200+'px';
		$(id).style.left = fx+300+'px';
	}
	else if(id == 'password-change-popup')
	{
		$('result').style.display="none";
		clearPasswordform();
		$(id).style.top = fy+200+'px';
		$(id).style.left = fx+300+'px';
	}
	else if(id == 'email-confirmation-popup')
	{
		$(id).style.top = fy+200+'px';
		$(id).style.left = fx+250+'px';
	}
	else if(id == 'password-confirmation-popup')
	{
		$(id).style.top = fy+200+'px';
		$(id).style.left = fx+250+'px';
	}else if(id=="email-approve-popup"){
		$(id).style.top = fy+200+'px';
		$(id).style.left = fx+300+'px';
	}
	__overlay(id);
}

function clearPasswordform() {
	$("currentPassword").value ="";
	$("newPassword").value ="";
	$("cfPassword").value ="";
}


function saveEmail(){
	
	var crEmail=document.getElementById('currentEmail').value.strip();
	var newEmail=document.getElementById('newEmail').value.strip();
	var cfEmail=document.getElementById('cfEmail').value.strip();
	if(newEmail=="" || newEmail==null){	

		$('emailError').show();
		$('emailError').innerHTML = $('newEmptyEmail').value;
	}
	else if(!isRFC822ValidEmail(newEmail)){
		/**
		 * Author: vveerabathini
		 * Bug: DS - 3681
		 * Fix: used isRFC822ValidEmail() to validate email address
		 */

		$('emailError').show();
		$('emailError').innerHTML = $('newValidEmail').value;
	}
	else if(cfEmail=="" || cfEmail==null){

		$('emailError').show();
		$('emailError').innerHTML = $('newEpmtyConfirmEmail').value;

	}else if(!isRFC822ValidEmail(cfEmail)){
		/**
		 * Author: vveerabathini
		 * Bug: DS - 3681
		 * Fix: used isRFC822ValidEmail() to validate email address
		 */

		$('emailError').show();
		$('emailError').innerHTML = $('newValidConfirmEmail').value;
	}else if(newEmail!=cfEmail){

		$('emailError').show();
		$('emailError').innerHTML = $('newConfirmEmail').value;
	}	else if(newEmail==crEmail){

		$('emailError').show();
		$('emailError').innerHTML =$('newCurrentEmail').value;
	}else{
		
		
			postForm(document.editEmailForm,editEmailCallback);
		
		}
			
	}


function editEmailCallback(resp){
	gridXmlObj=[];	
	gridXmlObj = buildObj(gridXmlObj,resp.responseXML.firstChild);
	var isAdminExist="user";
	if(gridXmlObj.collaborize.isAdminExist!=undefined)
		isAdminExist= gridXmlObj.collaborize.isAdminExist._value;
	if(isAdminExist=='true'){  
		$("siteemailchangefailureDiv").style.display="";
		$("siteemailchangeconfirmDiv").style.display="none";
		hidepopup('email-change-popup');
		showPrfilepopup('email-confirmation-popup');
	}else if (isAdminExist=='user'){
		if(resp.responseText.indexOf('true')>0){
			$('emailId').innerHTML = $('newEmail').value;
			// bug no 3849
			$('current').value = $('newEmail').value;
			hidepopup('email-change-popup');
		}else{
			$('emailError').style.display="";
			$('emailError').innerHTML = $('emailAlreadyExist').value;	
		}
	}else{ 
		$("from").innerHTML = gridXmlObj.collaborize.from._value;
		$('fromEmailId').value= gridXmlObj.collaborize.from._value;
		$("to").innerHTML = gridXmlObj.collaborize.to._value;
		$('toEmailId').value= gridXmlObj.collaborize.to._value;
		$("siteemailchangefailureDiv").style.display="none";
		$("siteemailchangeconfirmDiv").style.display="";
		var sitesHTML = "";
		var failedSitesHTML = "";

		/**
		 * @author: mkonusu
		 * @bug: DS - 3617
		 * @fix: if only one item is available then the object returns 
		 * undefined as length. added condition to compare undefined value
		 */
		if(gridXmlObj.collaborize.site.length == "undefined" || gridXmlObj.collaborize.site.length == undefined) {
			if(gridXmlObj.collaborize.site.siteStatus._value == "N") {
				sitesHTML = gridXmlObj.collaborize.site.siteName._value;
			} else {
				failedSitesHTML = gridXmlObj.collaborize.site.siteName._value;
			}
		} else {
			for(i =0; i< gridXmlObj.collaborize.site.length; i++) {
				var site = gridXmlObj.collaborize.site[i];
				if(site.siteStatus._value == "N") {
					sitesHTML += site.siteName._value + "<br>";
				} else {
					failedSitesHTML += site.siteName._value;
				}
			}
		}
		if(sitesHTML!=""){
			$("adminSites").innerHTML = sitesHTML;

		}else{
			$("sendButton").style.display="none";
			$('validsitelisthead').style.display="none";
		}
		if(failedSitesHTML!=""){
			$("failedAdminSites").innerHTML = failedSitesHTML;

		}else{
			$('invalidsitelisthead').style.display="none";
		}

		hidepopup('email-change-popup');
		/**
		 * @author: kranthi
		 * @bug: DS - 5680
		 * @fix: added condition to hide the email popup for classroom sites
		 */
		if(document.getElementById("siteType").value != 3){
		showPrfilepopup('email-confirmation-popup');
		}else{
			changeEmail();
		}
		
	}


}
function sendEmailRequest(){

	var crEmail=document.getElementById('currentEmailReq').value.strip();
	var newEmail=document.getElementById('newEmailReq').value.strip();
	var cfEmail=document.getElementById('cfEmailReq').value.strip();
	/*
	 * @author rkarka
	 * @bug DS-4043
	 * @fix Added condition for empty message and showing the error message
	 *  Reopend for email validations and added remining validations.
	 */
	/*@bug:5820
	 *root-cause not added null condition for new and confirm emails and added now
	 * 
	 * */
        if(newEmail=="" || newEmail==null){	

		$('emailReqError').show();
		$('emailReqError').innerHTML = $('newEmptyEmail').value;
	}
        else if(!isRFC822ValidEmail(newEmail)){
		$('emailReqError').show();
		$('emailReqError').innerHTML = $('newValidEmail').value;
	}else if(cfEmail=="" || cfEmail==null){

		$('emailReqError').show();
		$('emailReqError').innerHTML = $('newEpmtyConfirmEmail').value;

	}
         else if(!isRFC822ValidEmail(cfEmail)){
		$('emailReqError').show();
		$('emailReqError').innerHTML = $('newValidConfirmEmail').value;
	}else if(newEmail!=cfEmail){
		$('emailReqError').show();
		$('emailReqError').innerHTML = $('newConfirmEmail').value;
	}	else if(newEmail==crEmail){
		$('emailReqError').show();
		$('emailReqError').innerHTML =$('newCurrentEmail').value;
	}
	else{
		postForm(document.emailRequstForm,sendEmailReqCallback);
	}
} 
function sendEmailReqCallback(resp){ 
	hidepopup('email-request-popup');   
	$('newemailtr').style.display="";
	$('newemailtxt').innerHTML = $('newEmailReq').value;
}

function changeEmail(){
	postForm(document.confirmEmailForm,confirmEmailCallback);

}
function confirmEmailCallback(resp){
	
	
	if(resp.responseText.indexOf('true')>0){
		$('emailId').innerHTML = $('newEmail').value;
		$('current').value = $('newEmail').value;
	}
	hidepopup('email-confirmation-popup');
	hidepopup('email-confirmation-popup');
}

function confirmPassword(){
	postForm(document.confirmPasswordForm,confirmPasswordCallback);

}

function confirmPasswordCallback(resp){
	if(resp.responseText.indexOf('true')>0){
		$('pwd').value=$('newPassword').value; 
		$('pwd').value=$('cfPassword').value; 
	}
	hidepopup('password-confirmation-popup');
}

function approveOrDecline(reqType){
	$('reqType').value= reqType;
	postForm(document.mailReqApproveForm,mailReqApproveFormCallback);

}
function mailReqApproveFormCallback(resp){
	hidepopup('email-approve-popup');
	sendManageusersReq();
	//alert(resp.responseText);
}

/*
* @author gkottala
* @feature : 4139 Report link in manage members screen for each active user. 
* Redirect to the Activity Report.
*/
function showUserActivityReport(url){
	//alert("url  ::"+ url);
	window.location.href=url;
}

/**
* @author: vveerabathini
* @feature: DS - 4131
* @fix: Added code to open popup window with active users list 
*/
function changeUser(url) {
	//showpopupwindow('acitve-users');
	loadDivContent('activereportusers',url,changeusercallback);
} 
function changeusercallback()
{
	if($('acitve-users'))
	{
		showpopupwindow('acitve-users');
	}
} 
/** 
* Method to display search users list based on search string 
* **/
function searchActiveUserReport(div,url){
	if($('acitve-users'))
	{
		hidepopup('acitve-users');
	}
	var searchString =$('searchReportUser').value.strip();
	$('reportUserSearchString').value =url+'&search='+searchString;
	$('searchreportresults-tab').style.display="block";
	chagereportusertab(div,url+'&search='+searchString);	
}
/** 
* changing tabs 
* **/
function chagereportusertab(id,url){
	try{
		var tabs = new Array();
		tabs[0] = "activereport-tab";
		tabs[1] = "searchreportresults-tab";

		for(var i=0;i<tabs.length;i++)
		{
			$(tabs[i]).className='';
			$(id).addClassName('current');
			if(id=='searchreportresults-tab'){
				$('searchreportresults-tab').style.visibility='visible';
			}
		}
		loadDivContent('manageuserdiv',url,changeusercallback);
	}catch(e){
		alert(e);
	}
}
/**
* @author: vveerabathini
* @feature: DS - 4132
* @fix: Added code to display selected user information 
*/
function selectedUserReport(userId,url) {
	hidepopup('acitve-users');
	changeeditorialTab('useractivity',userId);
}
//topics.js
function setTopicState(id){
	instance2=null;
	if($("presentTopicStatus"))
		$("presentTopicStatus").value="0";
	if(document.getElementById(id)){ 
		if(document.getElementById(id).style.display!='none'){
			if($("presentTopicStatus"))
				$("presentTopicStatus").value=id; 
		}
	} 
}
function backToListing(url){ 
	showloader();
	url = setPaginationDetails(url);
	var pTopic="0";
	if($("presentTopicStatus"))
		pTopic=$('presentTopicStatus').value;
	if(pTopic!="0"){
		url=url+"&pTopic="+pTopic;
	}
	window.location.href = url;
}


/*function displayTopicPage(startNo, e, pageNo,noOfPages,url){
var keycode;
	if (window.event) keycode = window.event.keyCode;
	else if (e) keycode = e.which;

	if(keycode == 13){
		if(pageNo<1 || pageNo>noOfPages){

			$("errmsg").innerHTML = "Entered value  between 1 and "+noOfPages;
			$("errmsg").show();
		}else{
			changePageControl(startNo, pageNo, url);
		}
	}

}*/

function changePageControl(startNo, pageNo, url) {
	$("startNo").value = startNo;
	$("pageNo").value = pageNo;	
	url = setPaginationDetails(url);
	if($("searchmode").value=="on"){
		$("searchstartNo").value=startNo;
		$("searchpageNo").value = pageNo;
		document.searchForm1.submit();
	}else{
		window.location.href = url;
	}
}
function gotoTopicPage(url){ 
	url = setPaginationDetails(url);
	showloader();
	window.location.href=url;
}
function changeListingTab(tabId,url){
	$("sortBy").value=tabId;
	$("startNo").value = 1;
	$("pageNo").value = 1;
	gotoTopicPage(url);
}
function changeStatusTab(status,url){
	$("startNo").value = 1;
	$("pageNo").value = 1;
	if(status == 5 || status == "5" ) {
		$("status").value=3;
		$("sortBy").value=1;
		$("isResultsShow").value="false";
		$("categorySelection").value=0;
		$("isCategory").value=false;
	}else{
		$("status").value=status;
	}
	gotoTopicPage(url);
}
function changeCategory(categoryId,isCategory,url){

	if(isCategory == true){
		$("categorySelection").value=categoryId;
	}else{
		$("categoryGrpSelection").value=categoryId;
	}
	$("isCategory").value=isCategory;
	$("sortBy").value=1;
	// $("status").value=1;
	$("startNo").value = 1;
	$("pageNo").value = 1;
	gotoTopicPage(url);
} 

function changeResCategory(categoryId,isCategory,url){
	$("categorySelection").value=categoryId;
	$("isCategory").value=isCategory;
	url=url+"&page=results";
	url = setPaginationDetails(url);
	window.location.href=url;
} 
function changeRating(ele,url,id,score,type,divId){

	var sHtml ="";
	sHtml+= '<div id='+divId+'>';
	sHtml+= '<ul class="rating ' + ele.id + 'star">';
	sHtml+= '<li class="one" id="one"></li>';
	sHtml+= '<li class="two" id="two"></li>';
	sHtml+= '<li class="three" id="three"></li>';
	sHtml+= '<li class="four" id="four"></li>';
	sHtml+= '<li class="five" id="five"></li>';
	sHtml+= '</ul>';
	sHtml+= '</div>';
	ele.parentNode.parentNode.innerHTML=sHtml;
	loadDivContent(divId,url+'&'+type+'='+id+'&score='+score);
}

//add to watch list for a topic in topic listing page ....

function addToWatchList(watchlistId,url,watchlistType)
{
	//alert("watchlistId:  "+watchlistId+" :: url: "+url+" :: ele: "+ele + " :: divId: "+divId+" :: watchlistType: "+watchlistType);

	sendRequest(url+'&watchlistType='+watchlistType+'&watchlistId='+watchlistId,addToWatchListAjaxResponse);


}

//remove from watch list for a topic in topic listing page ....

function removeFromWatchList(watchlistId,url,ele,divId,watchlistType)
{
	//alert("watchlistId:  "+watchlistId+" :: url: "+url+" :: ele: "+ele + " :: divId: "+divId+" :: watchlistType: "+watchlistType);

	sendRequest(url+'&watchlistType='+watchlistType+'&watchlistId='+watchlistId,removeFromWatchListAjaxResponse);

}


function addToWatchListAjaxResponse(resp)
{
	//"watchlistType~[topic || comment],watchlistId~[topicId || commentId],watchlistResp~[success || failure];

	var respString = resp.responseText;

	var respArray = respString.split(",");

	var typeArray = respArray[0].split("~");
	var watchlistType = typeArray[1];


	var  idArray = respArray[1].split("~");
	var watchlistId = idArray[1];

	var respMsgArray = respArray[2].split("~");
	var watchlistResp = respMsgArray[1];

	// alert("addToWatchListAjaxResponse :: " + watchlistType+" ::
	// "+watchlistId+" :: "+watchlistResp);

	if (watchlistType == 3 & watchlistResp == "success") 
	{
		var ajaxWatchTopic = document.getElementById('ajaxWatchTopic_'+watchlistId);
		var ajaxBeenWatchedTopic =  document.getElementById('ajaxBeenWatchedTopic_'+watchlistId);
		var watchTopic = document.getElementById('watchTopic_'+watchlistId);
		var beenWatchedTopic = document.getElementById('beenWatchedTopic_'+watchlistId); 


		if (watchTopic != null)
		{
			//alert("watchTopic: "+watchTopic.style.display);
			watchTopic.style.display = "none";
		}

		if (ajaxWatchTopic != null)
		{
			//alert("ajaxWatchTopic: "+ajaxWatchTopic.style.display);
			ajaxWatchTopic.style.display = "none";
		}

		if (ajaxBeenWatchedTopic != null)
		{
			//alert("ajaxBeenWatchedTopic: "+ajaxBeenWatchedTopic.style.display);
			ajaxBeenWatchedTopic.style.display = "block";
		}


		if (beenWatchedTopic != null)
		{
			//alert("beenWatchedTopic: "+beenWatchedTopic.style.display);
			beenWatchedTopic.style.display = "none";
		}


	} 


	if(watchlistType == 4 && watchlistResp == "success") 
	{
		var ajaxWatchComment = document.getElementById('ajaxWatchComment_'+watchlistId);
		var ajaxBeenWatchedComment =  document.getElementById('ajaxBeenWatchedComment_'+watchlistId);
		var watchComment = document.getElementById('watchComment_'+watchlistId);
		var beenWatchedComment = document.getElementById('beenWatchedComment_'+watchlistId);

		if (watchComment != null)
		{
			//alert("watchComment: "+watchComment.style.display);
			watchComment.style.display = "none";
		}

		if (ajaxWatchComment != null)
		{
			//alert("ajaxWatchComment: "+ajaxWatchComment.style.display);
			ajaxWatchComment.style.display = "none";
		}

		if (ajaxBeenWatchedComment != null)
		{
			//alert("ajaxBeenWatchedComment: "+ajaxBeenWatchedComment.style.display);
			ajaxBeenWatchedComment.style.display = "block";
		}


		if (beenWatchedComment != null)
		{
			//alert("beenWatchedComment: "+beenWatchedComment.style.display);
			beenWatchedComment.style.display = "none";
		}

	} 

	if ((watchlistType == 5  || watchlistType == 6 )& watchlistResp == "success") {
		$('watchCatDiv').hide();
		$('unWatchCatDiv').show();
	}   


	if(watchlistType == 3 && watchlistResp == "failure") 
	{
		alert($('watchTopicRefresh').value);
	}

	if(watchlistType == 4 && watchlistResp == "failure") 
	{
		alert($('watchTopicRefresh').value);
	}

}

function removeFromWatchListAjaxResponse(resp)
{
	//"watchlistType~[topic || comment],watchlistId~[topicId || commentId],watchlistResp~[success || failure];

	var respString = resp.responseText;

	var respArray = respString.split(",");

	var typeArray = respArray[0].split("~");
	var watchlistType = typeArray[1];


	var  idArray = respArray[1].split("~");
	var watchlistId = idArray[1];

	var respMsgArray = respArray[2].split("~");
	var watchlistResp = respMsgArray[1];

	// alert("removeFromWatchListAjaxResponse :: " + watchlistType+" ::
	// "+watchlistId+" :: "+watchlistResp);

	if (watchlistType == 3 & watchlistResp == "success") 
	{

		var ajaxWatchTopic = document.getElementById('ajaxWatchTopic_'+watchlistId);
		var ajaxBeenWatchedTopic =  document.getElementById('ajaxBeenWatchedTopic_'+watchlistId);
		var watchTopic = document.getElementById('watchTopic_'+watchlistId);
		var beenWatchedTopic = document.getElementById('beenWatchedTopic_'+watchlistId); 

		if (ajaxWatchTopic != null)
		{
			//alert("ajaxWatchTopic: "+ajaxWatchTopic.style.display);
			ajaxWatchTopic.style.display = "block";
		}

		if (watchTopic != null)
		{
			//alert("watchTopic: "+watchTopic.style.display);
			watchTopic.style.display = "none";
		}


		if (ajaxBeenWatchedTopic != null)
		{
			//alert("ajaxBeenWatchedTopic: "+ajaxBeenWatchedTopic.style.display);
			ajaxBeenWatchedTopic.style.display = "none";
		}


		if (beenWatchedTopic != null)
		{
			//alert("beenWatchedTopic: "+beenWatchedTopic.style.display);
			beenWatchedTopic.style.display = "none";
		}

	} 

	if(watchlistType == 4 && watchlistResp == "success") 
	{
		var ajaxWatchComment = document.getElementById('ajaxWatchComment_'+watchlistId);
		var ajaxBeenWatchedComment =  document.getElementById('ajaxBeenWatchedComment_'+watchlistId);
		var watchComment = document.getElementById('watchComment_'+watchlistId);
		var beenWatchedComment = document.getElementById('beenWatchedComment_'+watchlistId);



		if (watchComment != null)
		{
			//alert("watchComment: "+watchComment.style.display);
			watchComment.style.display = "none";
		}

		if (ajaxWatchComment != null)
		{
			//alert("ajaxWatchComment: "+ajaxWatchComment.style.display);
			ajaxWatchComment.style.display = "block";
		}

		if (ajaxBeenWatchedComment != null)
		{
			//alert("ajaxBeenWatchedComment: "+ajaxBeenWatchedComment.style.display);
			ajaxBeenWatchedComment.style.display = "none";
		}


		if (beenWatchedComment != null)
		{
			//alert("beenWatchedComment: "+beenWatchedComment.style.display);
			beenWatchedComment.style.display = "none";
		}

	} 

	if ((watchlistType == 5  || watchlistType == 6 )& watchlistResp == "success") {
		$('watchCatDiv').show();
		$('unWatchCatDiv').hide();
	} 

	if(watchlistType == 3 && watchlistResp == "failure") 
	{
		alert($('unwatchTopicRefresh').value);
	}

	if(watchlistType == 4 && watchlistResp == "failure") 
	{
		alert($('unwatchTopicRefresh').value);
	}

} 
function performVote(divId,url,topicId,choiceId,mode){

	url = url+"&topicId="+topicId+"&choiceId="+choiceId+"&mode="+mode;
	loadDivContent(divId,url,function(){showPerformVoteResult(topicId)});
}
function showPerformVoteResult(id){ 
	var android = (navigator.appVersion.indexOf("Android") == -1) ? false : true;
	if(ipad || iphone || android){
		$('commentText_'+id).style.width="100%";
		$('commentText_'+id).style.height="100px";
	} else {
		if($('instanceId_'+id)){
			var instanceId = $('instanceId_'+id).value;
			if($('commentText_'+id)) {
				instance[instanceId]=null;
				instance[instanceId] = new TINY.editor.edit('editor_'+id,{
					id:'commentText_'+id,
					width:650,
					height:124,
					cssclass:'te',
					controlclass:'tecontrol',
					rowclass:'teheader',
					dividerclass:'tedivider',
					controls:['bold','italic','underline','strikethrough','|','subscript','superscript','|','charmap','|','link','|',
					          'orderedlist','unorderedlist','|','outdent','indent','|','leftalign','centeralign','rightalign','blockjustify'],
					          footer:false,
					          xhtml:true,
					          css:'body{background-color:#fff;font-family:Arial, Helvetica, sans-serif;font-size:13px;padding:0px;margin:0px;}',
					          bodyid:'editor_'+id,
					          footerclass:'tefooter'
				});
			}
		}
	}
	if($('showVoteCount_'+id)){ 
		if($('vtCountFromVote_'+id).value==1){

			$('showVoteCount_'+id).innerHTML=$('vtCountFromVote_'+id).value+" Vote";
		}else{
			$('showVoteCount_'+id).innerHTML=$('vtCountFromVote_'+id).value+" Votes";
		}  
	}
	if($('popular_div_'+id)) 
		$('popular_div_'+id).innerHTML = "Popularity: "+$('popularityVal_'+id).value;
}
function doModAction(divId,action,topicId,url,editUrl,topicName,listUrl){
	showloader();
	setTopicState(topicId);
	$("modTopicId").value=topicId;
	/*
		@Author : gkottala
		@Bug No:  4259 Accept,Deny,Edit options are not working in Topic approve topics tab.
		@Root cause:  null checking missing  
		@Fix : Placed if condition for null cheking
	 */	
	if($('actionsOnTopics_'+topicId)!=null && $('actionsOnTopics_'+topicId).value == "promote"){
		if(topicName!='') {
			$("publishResults").innerHTML = topicName;
		} else {
			if(topicId!=null) {
				$("publishResults").innerHTML = $('tTitle_'+topicId).innerHTML;
			} else {
				$("publishResults").innerHTML = " ";
			}
		}
		$("promoteStatus").selectedIndex = 0;
		$("closedTopic").checked = true; 
		$("promoteMesg").innerHTML="";
		setTimeout(" showpopupwindow('promote-popup');",1000);
		return;
	} else if (action == "deny"){
		$("denyMesg").innerHTML="";
		showpopupwindow('deny-popup');
		return;
	} else if(action=="actionsOnTopics"){
		var actVal = $("actionsOnTopics_"+topicId).value;
		if(actVal=="delete"){
			document.getElementById("actionTopicId").value="actionsOnTopics_"+topicId;
			$("deleteMesg").innerHTML="";
			setTimeout("showpopupwindow('delete-popup');",1000);
			return;
		}else if(actVal=="0"){
			return;
		}
		action = actVal;
	}

	if(action!="edit"){
		if(action!="copy") {
			url+="&topicId="+topicId+"&modAction="+action;
			// url = setPaginationDetails(url);
			loadDivContent('modCloseResult',url,function(){performModResult(listUrl)});
		} else {
			var multipleChoice = false;
			/**
			 * Author : vveerabathini
			 * Bug : 4640, when we click on copy for normal multiple topic defaulty it was selecting Allow Multiple selection Check box 
			 * fix: Updated condition based on topic type for setting allow multiple selection choice box value
			 */
			var topicType = $('topicTypeId_'+topicId).value;

			if(topicType == 2) {
				if($('multipleChoice') != null){
					if($('multipleChoice').checked || $("noOfAnswers_"+topicId).value>1) {
						multipleChoice = "on";
					} else {
						multipleChoice = false;
					}
				}
			}
			url+="&topicId="+topicId+"&modAction="+action+"&multipleChoice="+multipleChoice;
			// url = setPaginationDetails(url);
			window.location.href = url;
			//loadDivContent('modCloseResult',url,function(){cloneModResult(listUrl)});
		}
	}else{ 
		editUrl = setPaginationDetails(editUrl);
		editUrl+="&topicId="+topicId+"&modAction="+action;
		window.location.href = editUrl;
		//loadDivContent('contentmain',editUrl,function(){showResult()});
	}
}
function cloneModResult(url2,resp){  
	alert("cloneModResult");
	showtopiceditpreview();
	//showpopupwindow('ask-question-edit-popup');
}
function closeModPublishToResultsPage() {
	if($("modTopicId")) {
		var topicId=$("modTopicId").value.strip();
		$('actionsOnTopics_'+topicId).value = 0;
	}	
	var android = (navigator.appVersion.indexOf("Android") == -1) ? false : true;
	if(ipad || iphone || android){
		document.getElementById('promoteDesc').value = "";
	} else {
		instance5.e.body.innerHTML="";
	}

	hidepopup('promote-popup');
}
function performModAction(divId,action,url,url2){ 
	var topicId=$("modTopicId").value.strip(); 
	var mesg = "";
	var mesgDiv = "";
	var modStatus=1;
	var id ="";
	var  closedTopic = false;
	var android = (navigator.appVersion.indexOf("Android") == -1) ? false : true;
	if(action=="promote"){
		id='promote-popup';
		if(ipad || iphone || android){
			mesg=$("promoteDesc").value.strip(); 
		} else {
			var v ="  "+instance5.e.body.innerHTML;
			$("promoteDesc").value = v;
			mesg=$("promoteDesc").value.strip(); 
		}		
		mesg =mesg.anchorEntities();
		mesg =mesg.string_create_urls();
		mesg =mesg.specialCharacterEntities();
		$("publishdescription").value = mesg;
		modStatus=$("promoteStatus").value.strip();

		closedTopic = $('closedTopic').checked;
		if(closedTopic){
			url+="&closedTopic="+closedTopic;
		}

		if(mesg=='Tell your community about the results')mesg=' ';
		mesg = mesg.strip();
		if(ipad || iphone || android){
			var msgContent = mesg;
		} else {
			$('plainTextDiv').innerHTML = mesg;
			var msgContent = $('plainTextDiv').textContent || $('plainTextDiv').innerText;
		}
		if((msgContent == undefined || msgContent.strip() == "") && (modStatus== "")){
			$("promoteMesg").innerHTML=$('res_publishResults').value;
			if(ipad || iphone || android){
				$("promoteDesc").value = "";
				$("promoteDesc").focus();
			} else {				
				instance5.e.body.innerHTML = '&nbsp;';
				$("promoteStatus").focus();
			}

			return false;
		}
	}else if(action=="deny"){
		id='deny-popup';
		mesg= $("denyDesc").value.strip();
		$("publishdescription").value = mesg;
		if(mesg==""){
			$("denyMesg").innerHTML=$('enterDescription').value; 

			return false;
		} 
	}else if(action=="delete"){
		id='delete-popup';
		mesg = $("deleteDesc").value.strip(); 
		$("publishdescription").value = mesg;
		if(mesg==""){
			$("deleteMesg").innerHTML=$('enterDescription').value; 
			return false;
		}
	}
	url = setPaginationDetails(url);
	if(validateCurseFilter1(mesg)) {
		url+="&topicId="+topicId+"&modStatus="+modStatus+"&modAction="+action;
		document.promoteForm.action = url;
		postForm(document.promoteForm,function(){performModResult(url2)});
		// loadDivContent(divId,url,function(){performModResult(url2)});
		$(id).hide(); 
		// window.location.href=url;
	}
	if(!ipad && !iphone && !android){
		instance5.e.body.innerHTML ='&nbsp;';
		instance5.defaultsetting();
	}
}
/*function performResult(resp){
// alert(resp.responseText);
		var divObj = null;
	if(typeof(div)=="string")	// if obj is string get parent object
		divObj=document.getElementById(div);
	else	// use obj as parent
		divObj=div;
	if(resp.status==200) {
			divObj.innerHTML = resp.responseText;
			alert($('showResultsUrl'));
			performModResult('${showResultsUrl}&page=results',resp);

	}
}*/
function performModResult(url2,resp){  

	var url = url2; 
	gotoTopicPage(url);
	$("opacitydiv").style.visibility = 'hidden';
	$("promoteMesg").innerHTML = "";
}
function setPaginationDetails(url){
	var sortBy=$('sortBy').value;
	var status=$('status').value;
	var isResultsShow = $('isResultsShow').value;
	if(status==1 || status=="1"){
		isResultsShow = true;
	}
	var categoryId = $("categorySelection").value;

	var categoryGrpId = $("categoryGrpSelection").value;


	if(categoryId!=null && categoryId!=""){ 
		if($("isCategory").value==true||$("isCategory").value=='true'){
			url=url+"&categoryId="+categoryId;		
		}else{
			if(categoryGrpId!=null && categoryGrpId!=""){
				url=url+"&categoryGroupId="+categoryGrpId;	
			}
		}
	}
	var pageNo = 1;
	var startNo = 1;
	if($("pageNo")){
		pageNo = $("pageNo").value;
		startNo = $("startNo").value;
	}else{

	}

	url = url + "&sortBy="+sortBy+"&status="+status+"&pageNo="+pageNo+"&startNo="+startNo+"&isResultsShow="+isResultsShow;
	return url;
}

function sendNotifications(name){
	if(document.getElementById('ghost-text') != null){
		if(document.getElementById('ghost-text').innerHTML == "Describe the change(s) you've made."){
			document.getElementById('ghost-text').innerHTML = "";
		}
	}
	document.notifyTopicForm.action = setPaginationDetails(document.notifyTopicForm.action);
	document.notifyTopicForm.submit();
}



function validateEditTopicForm(name)
{
	var send = true;
	var topicTitleId = $('topicTitle').value;
	var android = (navigator.appVersion.indexOf("Android") == -1) ? false : true;
	if(!ipad && !iphone && !android){
		var v ="  "+instance1.e.body.innerHTML;
		topicTitleId = topicTitleId.htmlEntities();
		topicTitleId = topicTitleId.specialCharacterEntities();
		$('topicTitle').value = topicTitleId;
		$('topicDescription').value = v;
	}
	var topicDescriptionId =  $('topicDescription').value;
	topicDescriptionId = topicDescriptionId.anchorEntities();
	topicDescriptionId = topicDescriptionId.string_create_urls();
	topicDescriptionId = topicDescriptionId.specialCharacterEntities();
	$('topicDescription').value = topicDescriptionId;
	if( validateAskQuestionForm() &&  checkEditDateValidations() && validateCurseFilter() && validTopicAttachment()) {

		$('xml').value = "";
		var xmlContent = constructTopicXml(document.editTopicForm);
		$('xml').value = xmlContent;
		changeVideoWidthtopic();

		//document.askQuestionForm.submit();

		/*
		 @Author : mmalyala
		 @Bug No:  3677
		 @Fix :  After clicking submit button in topic page, disablethis() method will call to disable the submit button in topic edit page.		 	
		 */
		showloader();
		if($('classroom-question-editpopup'))
		{
			hidepopup('classroom-question-editpopup');
		}
		document.editTopicForm.action = setPaginationDetails(document.editTopicForm.action);
		document.editTopicForm.submit();
	} else {
		send  = false;
	}
	return;


}
/**
 * Convert date values
 */
function convertEditDate() {
	var dateVal = $("dateFieldEditVal").value.strip();   	
	var dateValstr = dateVal.split("-");
	var curr_month = dateValstr[0];
	var curr_date = dateValstr[1];
	var curr_year = dateValstr[2];
	var currentDate = curr_year + "-" + curr_month + "-" + curr_date;
	// var currentDateFormat = currentDate.replace(/-/g, "/");
	$("dateFieldEdit").value = currentDate;
}

function checkEditDateValidations()
{

	var endDate = $("dateFieldEditVal").value.strip();  
	/*
	Author:Praveena Patri
	 Fix: DS-5789  Collaborize (QA ENV) - Not displaying the topic upon editing the topic in particular scenario
	 Fix:set the null condition for end date..
	 */
	if(endDate == null || endDate == ""){
		$("dateFieldEdit").value="";
	}
	if(endDate != null && endDate != "") {
		convertEditDate();
	}

	/*
	 * if (endDate != null && endDate != "" && !isDate(endDate,'US')) {
	 * setAlertMessage("askQuestionAlertDiv1","askQuestionAlertMsgDiv1","End
	 * date must be entered in 'YYYY-MM-DD' format"); return false; }
	 */

	var d = new Date();
	var curr_date = d.getDate();
	var curr_month = d.getMonth();
	curr_month++;
	var curr_year = d.getFullYear();
	var currentDate = curr_year + "/" + curr_month + "/" + curr_date;
	var currentDateFormat = currentDate.replace(/-/g, "/");

	var endDateFormat = endDate.replace(/-/g, "/");

	if(Date.parse(endDateFormat) < Date.parse(currentDateFormat)  )
	{
		setAlertMessage("askQuestionAlertDiv","askQuestionAlertMsgDiv",$('enddateGreaterCurrentdate').value);
		return false;
	}else if(Date.parse(endDateFormat) == Date.parse(currentDateFormat)  ){
		var presentHours = d.getHours();
		var presentMins = d.getMinutes();  
		var hfe = $('hourFieldEdit').options[$('hourFieldEdit').selectedIndex].value;
		var cme = $('minuteFieldEdit').options[$('minuteFieldEdit').selectedIndex].value;
		var ampme = $('ampmFieldEdit').options[$('ampmFieldEdit').selectedIndex].value;
		if(ampme == "PM"){
			if(hfe!=12)
				hfe=12+hfe*1;
		} 
		if(hfe<presentHours){
			setAlertMessage("askQuestionAlertDiv","askQuestionAlertMsgDiv",$('enddateGreaterCurrentdateTime').value);
			return false;
		}else if(hfe == presentHours){
			if(cme <= presentMins){
				setAlertMessage("askQuestionAlertDiv","askQuestionAlertMsgDiv",$('enddateGreaterCurrentdateTime').value);
				return false;
			}
		}
	}

	return true;

}

function isDate(date,format)
{
	if(!date) return false;
	if(!format) format = 'US';

	switch(format){
	case'FR': RegExpformat = /^(([0-2]\d|[3][0-1])\/([0]\d|[1][0-2])\/([2][0]|[1][9])\d{2})$/; break;
	case'US': RegExpformat = /^([2][0]|[1][9])\d{2}\-([0]\d|[1][0-2])\-([0-2]\d|[3][0-1])$/; break;
	case'SHORTFR': RegExpformat = /^([0-2]\d|[3][0-1])\/([0]\d|[1][0-2])\/\d{2}$/; break;
	case'SHORTUS': RegExpformat = /^\d{2}\-([0]\d|[1][0-2])\-([0-2]\d|[3][0-1])$/; break;
	case'dd MMM yyyy':RegExpformat = /^([0-2]\d|[3][0-1])\s(Jan(vier)?|Feb(rier)?|Mars|Avr(il)?|Mai|Juin|Juil(let)?|Aout|Sep(tembre)?|Oct(obre)?|Nov(ember)?|Dec(embre)?)\s([2][0]|[1][19])\d{2}$/; break;
	case'MMM dd, yyyy':RegExpformat = /^(J(anuary|u(ne|ly))|February|Ma(rch|y)|A(pril|ugust)|(((Sept|Nov|Dec)em)|Octo)ber)\s([0-2]\d|[3][0-1])\,\s([2][0]|[1][9])\d{2}$/; break;
	}

	return RegExpformat.test(date);
}

function isSpecialChar(formField) 
{
	var string = formField.value;

	var iChars = "*+|,\":<>[]{}`\';()@&$#%";
	for (var i = 0; i < string.length; i++) {

		if (iChars.indexOf(string.charAt(i)) != -1)
			return true;
	}

	return false;

} 

function doResultsModAction(divId,action,topicId,resultStatus,url,topicName,topicState){
	var topicstate =topicState;
	var android = (navigator.appVersion.indexOf("Android") == -1) ? false : true;
	if(ipad || iphone || android){
		$('promoteDesc').value = $(topicId+'desc').innerHTML;
	} else {
		instance5.e.body.innerHTML = $(topicId+'desc').innerHTML;
	}
	$('promoteStatus').value=resultStatus;
	if(topicId!=null) {
		if($(topicId+'desc').innerHTML!=null) {
			if(ipad || iphone || android){
				$('promoteDesc').value = $(topicId+'desc').innerHTML;
			} else {
				instance5.e.body.innerHTML = $(topicId+'desc').innerHTML;
			}
			$('promoteDesc').value = $('promoteDesc').value.anchorEntities();
			$('promoteDesc').value = $('promoteDesc').value.string_create_urls();
			$('promoteDesc').value = $('promoteDesc').value.specialCharacterEntities();
		} else {
			$('promoteDesc').value='';
		}
	} 
	else {
		$('promoteDesc').value=resultDesc;
	}

	$("modTopicId").value=topicId;
	if(action=="promote"){
		if(topicName!='') {
			$("publishResults").innerHTML = topicName;
		} else {
			if(topicId!=null) {
				$("publishResults").innerHTML = $('tTitle_'+topicId).innerHTML;
				$("publishResults").innerHTML = $("publishResults").innerHTML.unescapeHTML();
			} else {
				$("publishResults").innerHTML = " ";
			}
		}

		if(topicstate == '3'){
			$('closedTopic').checked = true;
		}else{
			$('closedTopic').checked = false;
		}

		//$("publishResults").innerHTML = topicName;
		showpopupwindow('promote-popup');
		return;
	}
}
function showModeratorComments(commentId){
	try{
		if($('delete_comment_'+commentId+''))
			$('delete_comment_'+commentId+'').style.visibility='visible';
		//$('block_comment_'+commentId+'').style.visibility='visible';
	}catch(e){
		alert(e);
	}
}
function hideModeratorComments(commentId){
	try{
		if($('delete_comment_'+commentId+''))
			$('delete_comment_'+commentId+'').style.visibility='hidden';
		//$('block_comment_'+commentId+'').style.visibility='hidden';
	}catch(e){
		alert(e);
	}
}

function showModeratorSubComments(subcommentId){
	try{
		if($('delete_subcomment_'+subcommentId+''))
			$('delete_subcomment_'+subcommentId+'').style.visibility='visible';
		//$('block_comment_'+commentId+'').style.visibility='visible';
	}catch(e){
		alert(e);
	}
}
function hideModeratorSubComments(subcommentId){
	try{
		if($('delete_subcomment_'+subcommentId+''))
			$('delete_subcomment_'+subcommentId+'').style.visibility='hidden';
		//$('block_comment_'+commentId+'').style.visibility='hidden';
	}catch(e){
		alert(e);
	}
}

/**
 *@Author :mmalyala
 *@Bug : 4097 As a Collaborize site owner, I wanted to add a new answer to a Vote and Suggest question and it's not accepting.
 *@Fix : added topic id as parameter to deletecomment method and assign it to global topicId variable. 
 */

function deleteComment(commentTopicId,url,commentId,type,divId,page,isOpenAnswer){

	/* here topicId is a global variable which is used in ajax response callback methods */
	topicId = commentTopicId;	 
	url=url+'&commentId='+commentId;		
	var rad_val;
	try	{

		for ( var i = 0; i < document.selectedForm.procon.length; i++) {
			if (document.selectedForm.procon[i].checked) {
				rad_val = document.selectedForm.procon[i].value;
			}
		}
	} catch (e) {

		rad_val = null;
	}
	if (rad_val == null) {
		rad_val = 'Pro';
	}	
	if(type=='delete'){
		url=url+'&modaction=delete&radio='+rad_val;
		deletePopupAlert(url,divId);		
	}
}
function deletePopupAlert(url,divId){	
	var action = "<div class='cringely-btns-main' id='deletealert-action'><a href=\'javascript:hidepopup(\"deletealert-popup\");\'>"+$('closeJs').value+"</a> &nbsp; <a href=\'javascript:loadDivContent(\""+divId+"\",\""+url+"\",setTopicCounts);hidepopup(\"deletealert-popup\");\' class='button small primary vote'>"+$('submitJs').value+"</a></div>";
	$('deletealert-action').innerHTML = action;
	showpopupwindow('deletealert-popup');
	try{
		this.href=false;
	}catch(e){
		//alert(e);		
	}

}
function deleteSubComment(url,commentId,subcommentId,type,divId,page,isOpenAnswer){
	var startNo =  $("cmtStartNo").value;
	var pageNo = $("cmtPageNo").value;
	/*
	 * $('hidediv_'+commentId+'').innerHTML = ""; if(!isOpenAnswer) {
	 * $('subcomment_'+commentId+'').innerHTML =""; }
	 */
	url=url+'&commentId='+commentId+'&subcommentId='+subcommentId;
	// alert(type);
	var rad_val;
	try {
		//alert(document.selectedForm.procon.length);
		for ( var i = 0; i < document.selectedForm.procon.length; i++) {
			if (document.selectedForm.procon[i].checked) {
				rad_val = document.selectedForm.procon[i].value;
			}
		}
	} catch (e) {
		//alert(e);
		rad_val = null;
	}
	if (rad_val == null) {
		rad_val = 'Pro';
	}

	if(type=='subdelete'){
		url=url+'&startNo='+startNo+'&pageNo='+pageNo+'&modaction=subdelete&radio='+rad_val;
		replydeletePopupAlert(url,divId);
	}
	//alert(isOpenAnswer);
	/*
	 * if(page!=null && page=='list'){ if(isOpenAnswer){ // alert('gone
	 * to'); //loadDivContent(divId,url,setTopicCounts);
	 * replydeletePopupAlert(url,divId,setTopicCounts); }else{
	 * //loadDivContent(divId,url,setCommentsCounts);
	 * replydeletePopupAlert(url,divId,setCommentsCounts); } }else{
	 * //loadDivContent(divId,url,setTDetailCounts);
	 * replydeletePopupAlert(url,divId,setCommentsCounts); }
	 */
}
function replydeletePopupAlert(url,divId){	
	var action = "<div class='cringely-btns-main' id='replydeletealert-action'><a href=\'javascript:hidepopup(\"replydeletealert-popup\");\'>"+$('closeJs').value+"</a> &nbsp; <a href=\'javascript:loadDivContent(\""+divId+"\",\""+url+"\",setTDetailCounts);hidepopup(\"replydeletealert-popup\");\' class='button small primary vote'>"+$('submitJs').value+"</a></div>";
	$('replydeletealert-action').innerHTML = action;
	showpopupwindow('replydeletealert-popup');
	try{
		this.href=false;
	}catch(e){
		//alert(e);		
	}
}
function setTDetailCounts(status,resp){
	var id = $('topicId').value; 

	if($('topTypeId').value==3){
		if($('showTopCmtCount_'+id)){
			if($('cmtCount_'+id).value==1){
				$('submitAnswer').innerHTML = $('submitUrAnswers').value;
				$('showTopCmtCount_'+id).innerHTML=$('cmtCount_'+id).value+" "+$('res_CmtTxt').value;
			}else{
				$('showTopCmtCount_'+id).innerHTML=$('cmtCount_'+id).value+" "+$('res_comments').value;
			} 
		}
		if($('showVoteCount_'+id)){
			if($('vtCount_'+id).value==1){
				$('showVoteCount_'+id).innerHTML=$('vtCount_'+id).value+" "+$('res_VoteCount').value;
			}else{
				if($('cmtCount_'+id).value==0) {
					$('submitAnswer').innerHTML = $('beFirstSubmit').value;
				}
				$('showVoteCount_'+id).innerHTML=$('vtCount_'+id).value+" "+$('res_Votes').value;
			}  
		} 
	}else{
		if($('showTopCmtCount_'+id)){
			if($('cmtCount_'+id).value==1){
				$('showTopCmtCount_'+id).innerHTML=$('cmtCount_'+id).value+" "+$('res_CmtTxt').value;
			}else{
				$('showTopCmtCount_'+id).innerHTML=$('cmtCount_'+id).value+" "+$('res_comments').value;
			} 
		}
	}
	if($('popular_div_'+id))
		if($('popularityDetVal_'+id)){
			$('popular_div_'+id).innerHTML = "Popularity: "+$('popularityDetVal_'+id).value;
		}else{
			$('popular_div_'+id).innerHTML = "Popularity: "+$('popularityVal_'+id).value;
		}
}
/**
*@Author :mmalyala
*@Bug : 4097 As a Collaborize site owner, I wanted to add a new answer to a Vote and Suggest question and it's not accepting.
*@Fix : here topicId is global variable which is set when we click on delete icon for comment.
*/
function setTopicCounts(status,resp){

	/*
	 *@Author : mmalyala
	 *@Bug :  3975 IF user try to post some comments after deleting existing comments application showing error message. (Question type - Vote or Suggest)
	 *@Fix : editor instance is not created properly so fix is instance creation code is placed here.
	 */
	if($('instanceId_'+topicId)){
		var instanceId = $('instanceId_'+topicId).value;
		if($('topicTypeId_'+topicId).value==3){
			if($('commentText_'+topicId)) {
				instance[instanceId]=null;
				instance[instanceId] = new TINY.editor.edit('editor_'+topicId,{
					id:'commentText_'+topicId,
					width:650,
					height:124,
					cssclass:'te',
					controlclass:'tecontrol',
					rowclass:'teheader',
					dividerclass:'tedivider',
					controls:['bold','italic','underline','strikethrough','|','subscript','superscript','|','charmap','|','link','|',
					          'orderedlist','unorderedlist','|','outdent','indent','|','leftalign','centeralign','rightalign','blockjustify'],
					          footer:false,
					          xhtml:true,
					          css:'body{background-color:#fff;font-family:Arial, Helvetica, sans-serif;font-size:13px;padding:0px;margin:0px;}',
					          bodyid:'editor_'+topicId,
					          footerclass:'tefooter'
				});
			} 
		} 
	}  
	/*
	* $('topicTypeId_'+topicId).value represent topic type value if request comes from expanded view.
	* $('topTypeId').value represent topic type value if request comes from detail view.
	* topic type value =3 then it is a open answer topic.
	* comment label text changes based on comment count.
	* here $('cmtCount_'+topicId).value represents comment count after posting the comment in detail view.
	* if comment count is 0 comment label text should be "Be the first to submit an answer"
	* if comment count is greater than 0 comment label text should be "Don't see an answer you like, suggest one of your own!"
	*/ 
	if( ($('topicTypeId_'+topicId) && $('topicTypeId_'+topicId).value==3 )||($('topTypeId') && $('topTypeId').value==3 ) ){
		if($('cmtCount_'+topicId).value>=0){
			if($('submitAnswer')){
				var labelTxt = $('submitAnswer').innerHTML; 
				if($('cmtCount_'+topicId).value==0){
					if($('resSubmit_First')){
						$('submitAnswer').innerHTML =$('resSubmit_First').value+"!";
					}
				}else{
					if($('resSubmit_Suggest')){
						$('submitAnswer').innerHTML =$('resSubmit_Suggest').value+"!";
					}
				} 
			}
		}
	}
	/*
	* $('popularityDetVal_'+topicId).value represents popularity value after request(post comment or delete comment) processed.
	*/
	if($('popular_div_'+topicId)) {
		if($('popularityDetVal_'+topicId)){
			$('popular_div_'+topicId).innerHTML = "Popularity: "+$('popularityDetVal_'+topicId).value;
		}else{
			$('popular_div_'+topicId).innerHTML = "Popularity: "+$('popularityVal_'+topicId).value;
		}
	}
	/*
	*this method is used to set comments count after request(post comment or delete comment) processed.
	*/
	setCommentsCounts(resp);
	/*
	 *this method is used to set vote count after request(post comment or delete comment) processed.
	 * vote count is not present for topic type =4 i.e forum type question.
	 */
	if( ($('topicTypeId_'+topicId) && $('topicTypeId_'+topicId).value!=4 )||($('topTypeId') && $('topTypeId').value!=4 ) ){
		setVotesCounts(resp);
	}

}
function setCommentsCounts(resp){

	if($('showTopCmtCount_'+topicId)){
		if($('cmtCount_'+topicId).value==1){
			if($('cnt_'+topicId))
				$('cnt_'+topicId).innerHTML=$('cmtCount_'+topicId).value;
			$('showTopCmtCount_'+topicId).innerHTML=$('cmtCount_'+topicId).value+" "+$('res_CmtTxt').value;
		}else{
			if($('cmtCount_'+topicId).value<=3) {
				if($('cnt_'+topicId))
					$('cnt_'+topicId).innerHTML=$('cmtCount_'+topicId).value;
			}
			$('showTopCmtCount_'+topicId).innerHTML=$('cmtCount_'+topicId).value+" "+$('res_comments').value;
		} 
	}
	if($('showBottomCmtCount_'+topicId)){
		if($('cmtCount_'+topicId).value<=3) {
			if($('cnt_'+topicId))
				$('cnt_'+topicId).innerHTML=$('cmtCount_'+topicId).value;
		}
		$('showBottomCmtCount_'+topicId).innerHTML="("+$('cmtCount_'+topicId).value+")"; 
	}
	if($('isUserVoted')){
		if($('isUserVoted').value == "false" && $('reVoteEnabled').value=="false") {
			$('submitAnswer').innerHTML=$('beFirstSubmit').value;
			$('commentTextDiv').style.visibility="visible";
			$('post-button').style.visibility="visible";
		}	
	}
}


// bug 3707

/*
function setTopicCounts(status,resp){
	setCommentsCounts(resp);
	setVotesCounts(resp);
	if($('popular_div_'+topicId))
		if($('popularityDetVal_'+topicId)){
			$('popular_div_'+topicId).innerHTML = "Popularity: "+$('popularityDetVal_'+topicId).value;
		}else{
			$('popular_div_'+topicId).innerHTML = "Popularity: "+$('popularityVal_'+topicId).value;
		}
}
function setCommentsCounts(resp){	
	if($('showTopCmtCount_'+topicId)){
		if($('cmtCount_'+topicId).value==1){
			$('cnt_'+topicId).innerHTML=$('cmtCount_'+topicId).value;
			$('showTopCmtCount_'+topicId).innerHTML=$('cmtCount_'+topicId).value+" "+$('res_CmtTxt').value;
		}else{
			if($('cmtCount_'+topicId).value<=3) {
				$('cnt_'+topicId).innerHTML=$('cmtCount_'+topicId).value;
			}
			$('showTopCmtCount_'+topicId).innerHTML=$('cmtCount_'+topicId).value+" "+$('res_comments').value;
		} 
	}
	if($('showBottomCmtCount_'+topicId)){
		if($('cmtCount_'+topicId).value<=3) {
			$('cnt_'+topicId).innerHTML=$('cmtCount_'+topicId).value;
		}
		$('showBottomCmtCount_'+topicId).innerHTML="("+$('cmtCount_'+topicId).value+")"; 
	}
	if($('isUserVoted')){
		if($('isUserVoted').value == "false" && $('reVoteEnabled').value=="false") {
			$('submitAnswer').innerHTML=$('beFirstSubmit').value;
			$('commentTextDiv').style.visibility="visible";
			$('post-button').style.visibility="visible";
		}	
	}
}
 */
function setVotesCounts(resp){
	if($('showVoteCount_'+topicId)){
		if($('vtCount_'+topicId).value==1){

			$('showVoteCount_'+topicId).innerHTML=$('vtCount_'+topicId).value+" "+$('res_VoteCount').value;
		}else{
			$('showVoteCount_'+topicId).innerHTML=$('vtCount_'+topicId).value+" "+$('res_Votes').value;
		}  
	}
}

function performResModAction(divId,topicId,action,url,url2){ 
	var mesg = "";
	var modStatus=1;
	if(action=="promote"){
		/*
		* @author: mkonusu
		* @bug: DS-4308
		* @cause: sending description content along the ajax request
		* @fix: no need to send description content
		*/
		//mesg=$(topicId+'desc').innerHTML; 
		//mesg = mesg.unescapeHTML();
		if($(topicId+'status') == null){
			modStatus=null;
		}
		if($(topicId+'status') != null) {
			modStatus=$(topicId+'status').value.strip();
		}

	}
	url = setPaginationDetails(url);

	url+="&topicId="+topicId+"&modStatus="+modStatus+"&actionMesg="+escape(mesg)+"&modAction="+action;
	loadDivContent(divId,url,function(){performModResult(url2)});
}
function performModTextAction(divId,action,url,url2){ 
	var topicId=$("modTopicId").value.strip(); 
	var mesg = "";
	var mesgDiv = "";
	var modStatus=1;
	var id ="";
	var android = (navigator.appVersion.indexOf("Android") == -1) ? false : true;
	if(action=="promote"){
		id='promote-popup';
		if(!ipad && !iphone && !android){
			$("promoteDesc").value ="  "+instance5.e.body.innerHTML;
		}
		mesg=$("promoteDesc").value.strip(); 
		if(mesg=="<br>" ||mesg=="&lt;br>" || mesg=="&nbsp;") mesg="";
		mesg =mesg.anchorEntities();
		mesg =mesg.string_create_urls();
		mesg =mesg.specialCharacterEntities();
		$("publishdescription").value = mesg;
		modStatus=$("promoteStatus").value.strip();
		if(mesg=='Tell your community about the results') mesg=' ';
		mesg = mesg.strip();
		if(ipad || iphone || android){
			var msgContent = mesg;
		} else {
			$('plainTextDiv').innerHTML = mesg;
			var msgContent = $('plainTextDiv').textContent || $('plainTextDiv').innerText;
		}
		if((msgContent == undefined || msgContent.strip() == "") && (modStatus== "")){
			$("promoteMesg").innerHTML=$('res_publishResults').value;
			if(ipad || iphone || android){
				$("promoteDesc").value = '';
				$("promoteDesc").focus();
			} else {
				instance5.e.body.innerHTML = '&nbsp;';
				$("promoteStatus").focus();
			}

			return false;
		}
	}else if(action=="deny"){
		id='deny-popup';
		mesg= $("denyDesc").value.strip();
		$("publishdescription").value = mesg;
		if(mesg==""){
			$("denyMesg").innerHTML=$('enterDescription').value; 

			return false;
		} 
	}else if(action=="delete"){
		id='delete-popup';
		mesg = $("deleteDesc").value.strip(); 
		$("publishdescription").value = mesg;
		if(mesg==""){
			$("deleteMesg").innerHTML=$('enterDescription').value; 
			return false;
		}
	}
	url = setPaginationDetails(url);
	if(validateCurseFilter1(mesg)) {
		url+="&topicId="+topicId+"&modStatus="+modStatus+"&modAction="+action;
		document.promoteForm.action = url;
		postForm(document.promoteForm,function(){performModResult(url2)});
		// loadDivContent(divId,url,function(){performModResult(url2)});
		$(id).hide(); 
		// window.location.href=url;
	}

}

function validateAskQuestionForm() {
	setAlertMessage("askQuestionAlertDiv","askQuestionAlertMsgDiv","");
	var topicTitle = $("topicTitle").value.strip();
	if(topicTitle == "")
	{
		setAlertMessage("askQuestionAlertDiv","askQuestionAlertMsgDiv",$('questionNotBlank').value);
		window.scroll(0,0);
		return false;
	}
	if(topicTitle != "")
	{

		if(topicTitle.indexOf("<object")>=0 || topicTitle.indexOf("<embed")>=0 || topicTitle.indexOf("<param")>=0 || topicTitle.indexOf("<iframe")!=-1) {
			setAlertMessage("askQuestionAlertDiv","askQuestionAlertMsgDiv",$('enterValidData').value);
			window.scroll(0,0);
			$("topicTitle").focus();
			return false;
		}
		/*
		* @author: vveerabathini
		* @bug: DS-4311 while posting a topic title with more than 140 characters it throws an exception error.
		* @fix: Added topic title length validation
		*/
		if(topicTitle.strip().length > 140) {
			setAlertMessage("askQuestionAlertDiv","askQuestionAlertMsgDiv",$('enterValidlength').value);
			window.scroll(0,0);
			$("topicTitle").focus();
			return false;
		}
	}	

	var topicDesc = $('topicDescription').value;
	if(topicDesc != "")
	{
		$('topicDescription').value = $('topicDescription').value.fontEntities();
		$('topicDescription').value = $('topicDescription').value.styleEntities();
		topicDesc = $('topicDescription').value;
		/*
		 * @author: mkonusu
		 * @bug: DS-4390 
		 * @cause: start tag is missing at object/param/embed tag validation
		 * @fix: added start tat at object,param,embed tag validation
		 */

		if(topicDesc.indexOf("&lt;object")>=0 || topicDesc.indexOf("&lt;embed")>=0 || topicDesc.indexOf("&lt;param")>=0 || topicDesc.indexOf("&lt;iframe")!=-1) {
			setAlertMessage("askQuestionAlertDiv","askQuestionAlertMsgDiv",$('enterValidData').value);
			window.scroll(0,0);
			return false;
		}
	}
	if(validateCurseFilter1(topicTitle)) {
		return true;
	}
}

/**
 * Validates the topic type
 */
function validateTopicType()
{
	setAlertMessage("askQuestionAlertDiv","askQuestionAlertMsgDiv","");

	var typeList = $("typelist").getElementsByTagName('li');
	if((typeList.length == 1)){
		var idVal = typeList[0].id;
		selecttopicuser(idVal)	
	} 

	var topicType = $("topicTypeId").value;
	if (topicType == undefined || topicType == '0' || topicType == '')
	{
		setAlertMessage("askQuestionAlertDiv","askQuestionAlertMsgDiv",$('chooseQuestion').value);
		window.scroll(0,0);
		return false;
	}
	return true;
}
function createAskQuestion() {
	document.askQuestionForm.submit();
}
function createPreviewQuestion(){ 
	convertDate1();
	var selcatval = $('selcategories').value;
	selcatval = selcatval.replace("[","");
	selcatval = selcatval.replace("]","");
	selcatval = selcatval.replaceAll(" ","");
	$('categoryIds').value = selcatval;
	document.previewQuestionForm.submit();
}
/**
 * Convert date values
 */
function convertDate1() {
	if($("dateFieldVal").value!=null && $("dateFieldVal").value!="") {
		var dateVal = $("dateFieldVal").value;   
		var dateValstr = dateVal.split("-");
		var curr_month = dateValstr[0];
		var curr_date = dateValstr[1];
		var curr_year = dateValstr[2];
		var currentDate = curr_year + "-" + curr_month + "-" + curr_date;
		// var currentDateFormat = currentDate.replace(/-/g, "/");
		$("dateFieldStr").value = currentDate;   
	}
}
/**
 * Validates multiple choice topic type data
 */
/*
 * old code
 * */
/*function validateMultiChoice() 
  {
	  var topicTypeId = $("topicTypeId").value;
      if(topicTypeId == "2")// multi choice type
      {
          var table = $("dataTable");  
          var rowCount = $('rowCount').value;  

          var specialCharArray = new Array();
          var whitespaceArray = new Array();
          var spCharIndex = 0; 
          var whSpaceIndex = 0; 
          var found = false;
          for(var i=0; i < rowCount; i++) 
          {   

              if(document.getElementById("errorMultiChoiceId["+(i+1)+"]") != undefined){
            	  document.getElementById("errorMultiChoiceId["+(i+1)+"]").innerHTML="";
              }

			  var optionId = document.getElementById("optionId["+(i+1)+"]");

              if(optionId){
				  if(i < 2 && optionId.value.strip() == "")
				  {
					 whitespaceArray[whSpaceIndex++] = (i+1);
					 found = true;
				  }
				  else if(optionId.value.strip() == "")
				  {
					  whitespaceArray[whSpaceIndex++] = (i+1);
					  found = true;
				  }
			  }


          }//for
          if(found == true) // To output all validations at once
          {
              if(whSpaceIndex > 0)
              {
                //for(var i=0; i < 2; i++) // 2 fields mandatory & rest
											// optional
                for(var i=0; i < whitespaceArray.length; i++) 
                {
                    //var whSpaceMsg = "Choice " + whitespaceArray[i] + " cannot be blank" ;
                     setAlertMessage("askQuestionAlertDiv","askQuestionAlertMsgDiv",$('optionsNotBlank').value);
					document.getElementById("optionId["+(i+1)+"]").focus();

                }              

              }

              return false; // to output all validations at once and return
          }//if (found == true)
      }//if (topicTypeId == "2")// multi choice type
      return true;
  }*/

/*
 * @Author : gkottala
 * @Bug No : 4179
 * @Fix   : Added proper if to display the X icon and optimize the existing code(Remove the unnecessory loop and repeated values)
 */
function validateMultiChoice() 
{
	var topicTypeId = $("topicTypeId").value;
	if(topicTypeId == "2")// multi choice type
	{
		var table = $("dataTable");  
		var rowCount = $('rowCount').value;  
		var found = false;
		var curse=false;
		var alertVal=rowCount;
		var curalertVal=0;
		for(var i=0; i < rowCount; i++) 
		{   
			var val = document.getElementById("errorMultiChoiceId["+(i+1)+"]");
			if(val != null && val.value != undefined){ 
				document.getElementById("errorMultiChoiceId["+(i+1)+"]").innerHTML="";
			}			  

			var optionId = document.getElementById("optionId["+(i+1)+"]");	
			/*
			 * @Author : spenumatsa
			 * @Bug No : DS-4377
			 * @Fix   : As a moderator, when creating a choice for a multiple choice question, the curse word filter is not blocking expected text.
			 */
			if(optionId) {
				if(!validateCurseFilter1(optionId.value)) {
					curalertVal=(i+1);
					curse=true;				
					break;
				}
			}
			if(optionId){
				if(trim(optionId.value) == "" || trim(optionId.value) == " ")
				{
					alertVal-=1;
					found = true;
					//	 break;
				}
			}	           
		}//for loop end		
		if(found == true && alertVal<2){
			setAlertMessage("askQuestionAlertDiv","askQuestionAlertMsgDiv",$('enterValidChoices').value);
			window.scroll(0,0);
			document.getElementById("optionId["+alertVal+"]").focus();
			return false;
		} 
		/*
		 * Author : vveerabathini
		 * New Feature : DS-4232
		 * Added code to check multiple choice selection is selected or not. 
		 */
		/*if($('multipleChoice').checked == false) {
			setAlertMessage("askQuestionAlertDiv","askQuestionAlertMsgDiv",$('allowSelBox').value);
			document.getElementById("multipleChoice").focus();
			return false;
		  }*/
		/*
		 * @Author : spenumatsa
		 * @Bug No : DS-4377
		 * @Fix   : As a moderator, when creating a choice for a multiple choice question, the curse word filter is not blocking expected text.
		 */
		if(curse==true){				
			document.getElementById("optionId["+curalertVal+"]").focus();
			return false;
		}		  
	}//if end
	return true;
}

function hidePreviewTopicForm() {
	hidepopup("ask-question-edit-popup");
	document.getElementsByName('askQuestionForm1')[0].reset();

}
function constructTopicXml(form) {
	var xmlContent = "";
	var elements = Form.getElements($(form));
	var queryComponents = new Array();
	for (var i = 0; i < elements.length; i++) {
		var method = elements[i].tagName.toLowerCase();
		var parameter = Form.Element.Serializers[method](elements[i], undefined);
		if (parameter) {


			var key = encodeURIComponent(elements[i].name);
			if (key.length != 0 && key != "video" && key != "topicDescription" && key != "topicTitle")  {

				parameter = parameter.replaceAll('<','&lt;').replaceAll('>','&gt;').replaceAll('\'','&apos;').replaceAll('"','&quot;').replaceAll('&','%26');
				/*if (parameter[1].constructor != Array) {
					parameter[1] = [parameter[1]];
				  }*/
				xmlContent += "<nominate>";
				xmlContent += "<key>"+key+"</key>";
				var value = "";
				if(parameter  != "undefined" && parameter !="") {
					value = ""+parameter ;
				}
				value = value.strip();
				if(key == "document" ) {
					xmlContent += "<value><![CDATA["+  removeSpecialCharacters(value)  + "]]></value>";
				} else {
					xmlContent += "<value><![CDATA["+  value  + "]]></value>";
				}

				xmlContent += "</nominate>";
			}
		} 
	}
	return xmlContent;
}

function removeSpecialCharacters(originalFileName) {

	var ua = navigator.userAgent.toLowerCase();

	if(ua.indexOf('msie')  > 0 || ua.indexOf('chrome')  > 0)
	{
		var pos =originalFileName.lastIndexOf( originalFileName.charAt( originalFileName.indexOf(':')+1) ); 
		originalFileName = originalFileName.substring( pos+1);
		originalFileName = originalFileName.replaceAll("+", "_");
		originalFileName = originalFileName.replaceAll("\\", "_");
		originalFileName = originalFileName.replaceAll("'", "_");
		originalFileName = originalFileName.replaceAll("\"", "_");

	} else {
		originalFileName = originalFileName.replaceAll("+", "_");//.replaceAll("'", "_").replaceAll("\\", "_").replaceAll("/", "_").replaceAll("*", "_");
		originalFileName = originalFileName.replaceAll("\\", "_");
		originalFileName = originalFileName.replaceAll("'", "_");
		originalFileName = originalFileName.replaceAll("\"", "_");
	} 
	return originalFileName;
}

/**
 * Convert date values
 */
function convertDate() {
	var dateVal = $("dateFieldVal").value;   
	var dateValstr = dateVal.split("-");
	var curr_month = dateValstr[0];
	var curr_date = dateValstr[1];
	var curr_year = dateValstr[2];
	var currentDate = curr_year + "-" + curr_month + "-" + curr_date;
	// var currentDateFormat = currentDate.replace(/-/g, "/");
	$("dateField").value = currentDate;
}
/**
 * Validates topic title
 */
function validateTopicTitle()
{
	setAlertMessage("askQuestionAlertDiv","askQuestionAlertMsgDiv","");
	var topicTitle = $("topicTitle").value.strip();
	if(topicTitle == "")
	{
		setAlertMessage("askQuestionAlertDiv","askQuestionAlertMsgDiv",$('questionNotBlank').value);
		window.scroll(0,0);
		return false;
	}
	if(topicTitle != "")
	{
		if(topicTitle.indexOf("<object")>=0 || topicTitle.indexOf("<embed")>=0 || topicTitle.indexOf("<param")>=0 || topicTitle.indexOf("<iframe")!=1) {
			setAlertMessage("askQuestionAlertDiv","askQuestionAlertMsgDiv",$('enterValidData').value);
			window.scroll(0,0);
			return false;
		}
	}	
	if(topicTitle.strip().length > 140) {
		setAlertMessage("askQuestionAlertDiv","askQuestionAlertMsgDiv",$('enterValidlength').value);
		window.scroll(0,0);
		return false;
	}

	var topicDesc = $('topicDescription').value;
	if(topicDesc != "")
	{
		if(topicDesc.indexOf("<object")>=0 || topicDesc.indexOf("<embed")>=0 || topicDesc.indexOf("<param")>=0 || topicDesc.indexOf("<iframe")!=-1) {
			setAlertMessage("askQuestionAlertDiv","askQuestionAlertMsgDiv",$('enterValidData').value);
			window.scroll(0,0);
			return false;
		}
	}

	if(validateCurseFilter1(topicTitle)) {
		return true;
	}
}

function validateCurseFilter()
{
	var topicDescription = $("topicDescription").value;
	// var cursetext = $("topicDescription").value;
	// var cursetext = tinyMCE.get('topicDescription').getContent();
	// cursetext = cursetext.replace(/<[^>]+>/g,"");
	// cursetext = cursetext.replace(/&nbsp;/g,"");
	// cursetext = cursetext.replace(/^\s+|\s+$/g, '');
	// cursetext = cursetext.replace(/[\(\)\.\-\_\s,]/g, "");

	return curseFilter(topicDescription);// curseFilter('topicForm','topicDescription');
}

/**
 * Validates date values
 */
function checkDateValidations()
{
	var dateFieldVal = $("dateFieldVal").value.strip(); 
	if(dateFieldVal != null && dateFieldVal != "") {
		convertDate();
	}
	var endDate = $("dateField").value.strip();   
	// alert("endDate: "+endDate);
	/*
	 * if (endDate != null && endDate != "" && !isDate(endDate,'US')) {
	 * setAlertMessage("askQuestionAlertDiv","askQuestionAlertMsgDiv","End date
	 * must be entered in 'YYYY-MM-DD' format"); return false; }
	 */

	var d = new Date();
	var curr_date = d.getDate();
	var curr_month = d.getMonth();
	curr_month++;
	var curr_year = d.getFullYear();
	var currentDate = curr_year + "/" + curr_month + "/" + curr_date;
	var currentDateFormat = currentDate.replace(/-/g, "/");

	var endDateFormat = endDate.replace(/-/g, "/");
	if(endDate != null && endDate != "") 
	{
		if(dateFieldVal != '')
		{
			if(Date.parse(endDateFormat) < Date.parse(currentDateFormat) )
			{
				setAlertMessage("askQuestionAlertDiv","askQuestionAlertMsgDiv",$('enddateGreaterCurrentdate').value);
				window.scroll(0,0);
				return false;
			}
			else if(Date.parse(endDateFormat) == Date.parse(currentDateFormat)  ){
				var presentHours = d.getHours();
				var presentMins = d.getMinutes();  
				var hfe = $('hourField').options[$('hourField').selectedIndex].value;
				var cme = $('minuteField').options[$('minuteField').selectedIndex].value;
				var ampme = $('ampmField').options[$('ampmField').selectedIndex].value;
				if(ampme == "PM"){
					if(hfe!=12)
						hfe=12+hfe*1;
				} 
				if(hfe<presentHours){
					setAlertMessage("askQuestionAlertDiv","askQuestionAlertMsgDiv",$('enddateGreaterCurrentdateTime').value);
					window.scroll(0,0);
					return false;
				}else if(hfe == presentHours){
					if(cme <= presentMins){
						setAlertMessage("askQuestionAlertDiv","askQuestionAlertMsgDiv",$('enddateGreaterCurrentdateTime').value);
						window.scroll(0,0);
						return false;
					}
				}
			}
		}
		else
		{
			$('dateField').value = "";
		}
	}
	return true;

}
function hideTopicForm() {
	/**
	   @Author : mmalyala
	   @Bug No : 3703
	  @Fix    : new site model popup related changes.   
	 */ 
	/**
	   @Author : kranthi
	   @Bug No : 5795
	  @Fix    : commented remove-date-icon since its no need to use according to 5695 fix.   
	 */ 
	hidetopics();   
	reset();
	//$("remove-date-icon").style.visibility = "hidden";
	document.getElementsByName('askQuestionForm')[0].reset(); 
	if($('ask-question-popup-new')){
		hidepopup("ask-question-popup-new");
	}  
}
function reset()
{
	var android = (navigator.appVersion.indexOf("Android") == -1) ? false : true;
	if(!ipad && !iphone && !android){
		instance1.e.body.innerHTML ='';
	}
	$("post-link").show();
	$("categorylabel").innerHTML ="Select A Category:";
	$("categoryId").show();
	if($("show-categories")) {
		if($("show-categories").style.display == "block") {
			$("show-categories").style.display = "none";
		}
	}
	$("multi-categories").hide();
}
function hideClassroomForm() {
	/**
 		@Author : mmalyala
 		@Bug No : 3703
		@Fix    : new site model popup related changes.	 	
	 */ 
	hidetopics(); 
	document.getElementsByName('askQuestionForm')[0].reset();	
	if($('classroom-question-popup-new')){
		hidepopup("classroom-question-popup-new");
	}
	else if($('ask-question-popup-new')){
		hidepopup("ask-question-popup-new");
	}

}
function showSelected()
{
	var selObj = $('showattachId');	
	// var selIndex = selObj.selectedIndex;
	var selValue = selObj.value;
	var attachId = new Array();
	attachId[0] = "photoId";
	attachId[1] = "videoId";
	attachId[2] = "documentId";
	for(var i=0;i<attachId.length;i++)
	{
		$(attachId[i]).hide();
		if(selValue=="1")
		{
			clearAttachments('VideoTitle', 'video');
			clearAttachments('DocumentTitle', 'document');

			$(attachId[0]).show();
		}
		else if(selValue=="2")
		{
			clearAttachments('PhotoTitle', 'photo');
			clearAttachments('DocumentTitle', 'document');

			$(attachId[1]).show();
		}
		else if(selValue=="3")
		{
			clearAttachments('PhotoTitle', 'photo');
			clearAttachments('VideoTitle', 'video');

			$(attachId[2]).show();
		}
	}
}
function clearAttachments(attachmentTitle, attachmentValue) {
	$(attachmentTitle).value = "";
	$(attachmentValue).value = "";
}
function changeVideoWidthtopic()
{
	var val = document.getElementById('video').value;
	var width;
	var width_value;
	var second_width;
	var x;
	if(val.indexOf("object")!= -1 )
	{

		var ob = val.indexOf("object");
		var cot1 = val.indexOf('"',ob+1);
		var cot2 = val.indexOf('"',cot1+1);
		width_value = val.substring(cot1+1,cot2);
		width = val.indexOf("width",cot2);
		var cot3 = val.indexOf('"', width + 1);
		var cot4 = val.indexOf('"',cot3+1);
		width_value2 = val.substring(cot3+1,cot4);
		if(width_value > 420 || width_value2 > 420)
		{
			x = val.replace(width_value,420);
			x = x.replace(width_value2,420);
			var wm=x.replace("<embed ",'<embed wmode="transparent" ');
			/**
			 * @author rkarka
			 * @bug:DS-3557 Ecommerce - Applicatin allowing user to upload more than one videos.
			 * @fix:only allowing first object tag escaping rest of the string entered by user
			 * */
			var indexStart=wm.indexOf("<object");
			var indexEnd=wm.indexOf("</object>");
			wm=wm.substring(indexStart,indexEnd);
			wm=wm+'</object>';
			document.getElementById('video').value = wm;

		}  
	}
	else if(val.indexOf("iframe")!= -1 )
	{
		width = val.indexOf("width",cot2);
		var cot3 = val.indexOf('"', width + 1);
		var cot4 = val.indexOf('"',cot3+1);
		width_value2 = val.substring(cot3+1,cot4);
		if(width_value2 > 420)
		{
			x = val.replace(width_value,420);
			x = x.replace(width_value2,420);
			document.getElementById('video').value = x;

		}  
	} 
	else if(val.indexOf("embed")!= -1) {
		width = val.indexOf("width",cot2);
		var cot3 = val.indexOf('"', width + 1);
		var cot4 = val.indexOf('"',cot3+1);
		width_value2 = val.substring(cot3+1,cot4);
		if(width_value2 > 420)
		{
			x = val.replace(width_value,420);
			x = x.replace(width_value2,420);
			var wm=x.replace("<embed ",'<embed wmode="transparent" ');
			var indexStart=wm.indexOf("<embed");
			var indexEnd=wm.indexOf("/>");
			wm=wm.replace("/>",'></embed>');
			//wm=wm.substring(indexStart,indexEnd);
			//wm=wm+'</embed>';
			document.getElementById('video').value = wm;

		}  
	}
	setCookie("video",val,1);

}
function validTopicAttachment()
{

	/*var selObj = $('showattachId');	
		// var selIndex = selObj.selectedIndex;
		var selValue = selObj.value;
		var attachId = new Array();
		attachId[0] = "photoId";
		attachId[1] = "videoId";
		attachId[2] = "documentId";*/

	if($('photoId').checked==true)
	{
		var photoFileName = $('photo').value.strip().toLowerCase();
		if(photoFileName!="" && !isValidImageFile(photoFileName)) {
			document.getElementById("mesgDiv").style.display="block";
			document.getElementById("mesg").innerHTML=$('validImagePhoto').value;
			return false;
		}
	}
	else if($('videoId').checked==true)
	{
		var videoFileName = $('video').value.strip();
		var videoTitleName = $('VideoTitle').value.strip().toLowerCase();
		if(videoTitleName!="" && !isValidVideoTitle(videoTitleName)) {
			document.getElementById("VideoTitle").focus();
			document.getElementById("mesgDiv").style.display="block";
			document.getElementById("mesg").innerHTML=$('validVideoTitle').value;
			return false;
		}
		if(videoFileName!="" && !isValidVideoFile(videoFileName)) {
			document.getElementById("mesgDiv").style.display="block";
			document.getElementById("mesg").innerHTML=$('validVideoFile').value;
			return false;
		}
	}
	else if($('pdfId').checked==true)
	{
		var attachFlag = true;
		var docFileName = "";
		if($('document').value!=null && $('document').value!="") {
			docFileName = $('document').value.strip().toLowerCase ();
		} else if($('doctxt')) {
			if($('doctxt').value!=null && $('doctxt').value!="") {
				docFileName = $('doctxt').value.strip().toLowerCase ();
			}
		}
		var extArray = new Array(".pdf", ".doc", ".docx", ".docm", ".dot", ".dotm", ".dotx", ".xls", ".xlt", ".xlsx", ".xltx", ".xla", ".xlsm", ".xltm", ".xlsb", ".xlam", ".xlb", ".pot", ".ppt", ".pps", ".ppsx", ".ppam", ".pptm", ".ppsm", ".pptx", ".potm", ".potx");

		for(var i=0; i<extArray.length; i++) {

			if(docFileName!="" && docFileName.lastIndexOf(extArray[i]) != -1)	{		
				attachFlag = false;
				continue;
			} 
		}
		if(docFileName=="") {
			attachFlag = false;
		} 

		if(attachFlag) {
			document.getElementById("mesgDiv").style.display="block";
			document.getElementById("mesg").innerHTML=$('validPdfFile').value;

			return false;
		}
	}
	document.getElementById("mesgDiv").style.display="none";
	return true;
}
function isValidImageFile(logo) {
	if(logo.lastIndexOf(".bmp")>0 || logo.lastIndexOf(".jpg")>0 || logo.lastIndexOf(".jpeg")>0 || logo.lastIndexOf(".gif")>0 || logo.lastIndexOf(".png")>0 || logo.lastIndexOf(".tiff")>0 ) {
		return true;
	}
	return false;
}
function isValidVideoFile(link) {

	if(link.indexOf("<object")!=-1 || link.indexOf("<embed")!=-1 || link.indexOf("<iframe")!=-1) {
		if(link.indexOf("<iframe")!=-1)
		{
			var srcIndex = link.indexOf("src");
			var quoteIndex = link.indexOf('"',srcIndex+5);
			var srcURL = link.substring(srcIndex+4,quoteIndex+1);
			var srcChageURL = link.substring(srcIndex+4,quoteIndex);
			var srcNewURL = srcChageURL;
			// DS-5819 bug fix
			if(srcChageURL.indexOf("?")!=-1)
			{
				srcNewURL+='&amp;wmode=transparent" wmode="transparent"';
			}
			else
			{
				srcNewURL+='?wmode=transparent" wmode="transparent"';
			}
			link = link.replace(srcURL,srcNewURL);
			$('video').value = link;
		} else if(link.indexOf("<object")!=-1) {
			var gtIndex = link.indexOf('/>');
			if(gtIndex!=-1)
			{
				var ltIndex = link.indexOf('<',gtIndex+2);
				var invalidChars = link.substring(gtIndex+1,ltIndex-1);
				if(invalidChars.length>2)
				{
					return false;
				}
			}
			if(link.indexOf("data")!=-1)
			{
				var dataIndex = link.indexOf("data");
				var dataquoteIndex = link.indexOf('"',dataIndex+6);
				var srcURL = link.substring(dataIndex+5,dataquoteIndex+1);
				var srcChageURL = link.substring(dataIndex+5,dataquoteIndex);
				var shtml = '<param name="wmode" value="transparent" />';
				//var srcNewURL = srcChageURL+'?wmode=transparent" wmode="transparent"';
				//link = link.replace(srcURL,srcNewURL);
				var dataurlIndex = link.indexOf('>',dataquoteIndex+2);
				var dataChageURL = link.substring(dataIndex+5,dataurlIndex+1);
				var dataNewURL = dataChageURL+shtml;
				link = link.replace(srcURL,dataNewURL);
				$('video').value = link;
			}
		}
		return true;
	}
	return false;
}
function isValidVideoTitle(name) {
	if(name.indexOf("<object")>0 || name.indexOf("<embed")>0 || name.indexOf("<iframe")!=-1) {
		return false;
	}
	return true;
}
/**
 * Perform validation of ask question form data to create a new question
 */

function validateModelTopicForm()
{
	if(!send) {
		send = true; 
		if(validateTopicTitle() && validateTopicType() && checkDateValidations() && validateMultiChoice()) {
			//document.askQuestionForm.submit();
			postCreateModelTopic();
		} else {
			send  = false;
		}
		return false;
	}

	//var result4 = validateCurseFilter();
	// var result5 = validateMultiChoice();

}

/**
 * Ajax call - send form data to create a post question
 */
function  postCreateModelTopic() {
	var topicTitleId = $('topicTitle').value;
	var android = (navigator.appVersion.indexOf("Android") == -1) ? false : true;
	if(!ipad && !iphone && !android){
		var v ="  "+instance1.e.body.innerHTML;
		topicTitleId = topicTitleId.htmlEntities();
		topicTitleId = topicTitleId.specialCharacterEntities();
		$('topicTitle').value = topicTitleId;
		$('topicDescription').value = v;
	}
	var topicDescriptionId =  $('topicDescription').value;
	topicDescriptionId = topicDescriptionId.anchorEntities();
	topicDescriptionId = topicDescriptionId.string_create_urls();
	topicDescriptionId = topicDescriptionId.specialCharacterEntities();
	$('topicDescription').value = topicDescriptionId;
	postForm(document.askQuestionForm, createModelTopicResponseHandler);
}

/**
 * Response Handler for create a post question	
 */
function createModelTopicResponseHandler(resp) {
	var responseTxt = resp.responseText;
	if(responseTxt.indexOf("success") >0) {
		clearAskModalQuestionForm();
		var msg = $('questionSubmit').value;
		setAlertMessage("askQuestionAlertDiv","askQuestionAlertMsgDiv",msg);
		send=false;
		// show success message
	} else {
		// show error/failure message
	}
	send = false;
}

function clearAskQuestionForm() {
	var android = (navigator.appVersion.indexOf("Android") == -1) ? false : true;
	if($("categorylabel"))
	{
		$("categorylabel").innerHTML ="Select A Category:";
	}
	if($("categoryId"))
	{
		$("categoryId").show();
	}
	if($("show-categories")) {
		if($("show-categories").style.display == "none") {
			$("show-categories").style.display = "block";
		}
		if($("post-link-categories").style.display == "none") {
			$("post-link-categories").style.display = "block";
		}
		$("categoryId").options[0].selected = "true";
	}

	if($("multi-categories"))
	{
		$("multi-categories").hide();
		document.getElementById('multi-categories').getElementsByTagName('input').value = "";
	}
	if($("post-link"))
	{
		$("post-link").show();
	}
	if($("topicTypeId")) {
		$("topicTypeId").value = "0";
	}
	if($("rowCount")) {
		$("rowCount").value = "2";
	}
	$("topicTitle").value = "";
	if($("topicDescription")) {
		$("topicDescription").value = "";
	}
	$("askQuestionAlertDiv").hide();
	if($("dateFieldVal")) {
		$("dateFieldVal").value = "";
		$("dateField").value = "";
		$("hourField").options[0].selected = "true";
		$("minuteField").options[0].selected = "true";
		$("ampmField").options[0].selected = "true";
	}
	if($("multiple_choice")) {
		$("optionId[1]").value = "";
		$("optionId[2]").value = "";
		$("errorMultiChoiceId[1]").value = "";
		$("errorMultiChoiceId[2]").value = "";
		$("multiple_choice").hide();
	}
	if($("multiplechoicedisplay")) {
		$("optionId[1]").value = "";
		$("optionId[2]").value = "";
		$("errorMultiChoiceId[1]").value = "";
		$("errorMultiChoiceId[2]").value = "";
	}
	/**
	 * Author : vveerabathini
	 * Feature : 4232 Subtask 4539 Enable/Disable the dropdown based on select/deselect the "Allow Multiple Choice Selections Up To Box" and Update drop down based choice addition and deletion.
	 * fix : Unsetting the values when reset the ask question window 
	 */
	if($("multi-selection")) {
		$("multipleChoice").checked = false;
		$('multipleChoiceId').disabled=false;
		$("multipleChoiceId[1]").value = "";
	}
	if(!ipad && !iphone && !android){
		instance1.e.body.innerHTML ='';
	}

	for(var i=0;i <=$('noofOptions').value;i++){
		if(i > 2){
			if($('rowId['+(i)+']'))
				$('dataTable').deleteRow($('rowId['+(i)+']').rowIndex);
		}
	}
	$('noofOptions').value="";
	/**
	 *@Author : mmalyala
	 *@Bug: 4007 In first landing page after submitting a question when we are trying to submit a new question also "question submitted "text remains.
	 *@Fix: hide the submit result div when clearing topic details.
	 */
	if($('questionSubmitResultDiv')){
		$('questionSubmitResultDiv').hide();  
	}
}
function clearAskModalQuestionForm() {

	if($("topicTypeId").options[0].selected==false) {
		$("topicTypeId").options[0].selected = "true";
	}
	if($("rowCount")) {
		$("rowCount").value = "2";
	}
	$("categoryId").options[0].selected = "true";
	$("topicTitle").value = "";
	if($("topicDescription")) {
		$("topicDescription").value = "";
		$("yes-or-no-description").hide();
		$("yes-or-no-add-discription").show();
	}
	if($("multiple_choice")) {
		$("optionId[1]").value = "";
		$("optionId[2]").value = "";
		$("errorMultiChoiceId[1]").value = "";
		$("errorMultiChoiceId[2]").value = "";
		$("multiple_choice").hide();
	}
	/**
	 * Author : vveerabathini
	 * Feature : 4232 Subtask 4539 Enable/Disable the dropdown based on select/deselect the "Allow Multiple Choice Selections Up To Box" and Update drop down based choice addition and deletion.
	 * fix : Unsetting the values when reset the ask question window
	 */
	if($("multi-selection")) {
		$("multipleChoice").checked = false;
		$('multipleChoiceId').disabled=false;
		$("multipleChoiceId[1]").value = "";
	}
	$("askQuestionAlertDiv").hide();
	if($("dateFieldVal")) {
		$("dateFieldVal").value = "";
		$("dateField").value = "";
		$("hourField").options[0].selected = "true";
		$("minuteField").options[0].selected = "true";
		$("ampmField").options[0].selected = "true";
		$("yes-or-no-additional-topics").hide();
		$("yes-or-no-additional-topics-link").show();
	}
	if(!ipad && !iphone && !android){
		instance1.e.body.innerHTML ='';
	}

	for(var i=0;i <=$('noofOptions').value;i++){
		if(i > 2){
			if($('rowId['+(i)+']'))
				$('dataTable').deleteRow($('rowId['+(i)+']').rowIndex);
		}
	}
	$('noofOptions').value="";
}
function setvideotag(str){
	if(str=='edit'){
		$('video').value=$('videoVal').value;


	}else{
		$('topicTitleStr').value=unescape($('topicTitleDiv').innerHTML);
		$('topicDescriptionStr').value=unescape($('topicDescriptionDiv').innerHTML);
		// $('xmlVal').value=$('xmltaghidden').innerHTML;
		// $('videoVal').value=$('videotaghidden').innerHTML;
	}

}

function showbrowsefile(){
	$('showphotodiv').hide();
	$('browsefileid').show();
}

function showbrowsedocfile(){
	$('showdocdiv').hide();
	$('browsedocfileid').show();
}

/** Action Block functions */

function createActionBlock() {
	var newcustommessage = document.getElementById("new-custom-message").innerHTML;
	var newMessage = document.getElementById("newMessage").value;
	newcustommessage =  ("  "+instance10.e.body.innerHTML).anchorEntities();
	newcustommessage = newcustommessage.string_create_urls();
	newcustommessage = newcustommessage.specialCharacterEntities();

	if(validateCustomMessage(true)) {

		/* 
				@Author : gkottala
				@Bug No:  4267
				@Fix :  After clicking save button in custom message popup, disablethis() method will call to disable the save button in custom message popup.    
		 */
		disablethis('saveButton');
		newMessage ="  "+instance10.e.body.innerHTML.anchorEntities();
		newMessage = newMessage.string_create_urls();
		$('newMessage').value = newMessage;
		if($('customId'))
		{
			$('customId').hide();
		}
		postForm(document.createActionBlock, createActionBlockHandler);
	} else {

		// enableSaveButton();
		//alert("dont crerate");
	}
}

function validateCustomMessage(iscreate) {
	var id = "";
	if (iscreate) {
		id = "create-custom-message-alert";
	} else {
		id = "edit-custom-message-alert";
	}
	$('new-custom-message').innerHTML = (instance10.e.body.innerHTML).anchorEntities();
	var msgContent = $('new-custom-message').textContent || $('new-custom-message').innerText;
	//var obj = document.getElementById("new-custom-message");

	//var msgContent = obj.textContent || obj.innerText;
	if(msgContent ==  undefined || msgContent.strip() == "") {
		setAlertInfoMessage($('customMessageAlert').value, id);
		return false;
	} else if(msgContent!=null) {
		if(msgContent.strip().length > 70) {
			setAlertInfoMessage($('messageLengthAlert').value, id);
			return false;
		} else if(msgContent.strip().length == 0) {
			setAlertInfoMessage($('customMessageAlert').value, id);
			return false;
		}
	}


	/*
		 @Author : vveerabathini
		 @Bug No:  3802
		 @Fix :  Added custom message alert condition for recipient selection.		 	
	 */ 
	if(iscreate) {
		if(!$('showMod').checked && !$("showEndUser").checked && !validateAnonymus(id)) {
			setAlertInfoMessage($('recipientAlert').value, id);
			return false;
		} 
	}

	/** 
	 * @author: mkonusu
	 * @bug: DS-4018
	 * @fix: removing <br> statements also stripping start and end blank spaces in the message
	 */
	var msgContent = msgContent.strip();
	var msgHtml = $('new-custom-message').innerHTML;

	/** removing new line tags */
	msgHtml = msgHtml.replaceAll('<br>','').replaceAll('<br/>','').strip();

	/** trim spaces at the ends */
	msgHtml = trimHtmlSpaces(msgHtml);

	if(iscreate) {
		if(msgHtml!=null && msgHtml!="") {
			instance10.e.body.innerHTML = msgHtml;
		}
	} else {
		if(msgHtml!=null && msgHtml!="") {
			instance11.e.body.innerHTML = msgHtml;
		}
	}

	return true;
}

function validateAnonymus(id){
	if($('showAnon')) {
		if(!$("showAnon").checked) {
			setAlertInfoMessage($('recipientAlert').value, id);
			return false;
		}
	} else {
		setAlertInfoMessage($('recipientAlert').value, id);
		return false;
	}
	return true;
}

/** method to trim html spaces (&nbsp;) from the message text	*/
function trimHtmlSpaces(msg) {
	var status = true;

	/* verify space characters exists at the start. if exists remove the characters */
	while(status) {
		if(msg.startsWith("&nbsp;")) {
			msg = msg.substring(6,msg.length).strip();
		} else {
			status = false;
		}
	}

	/* verify space characters exists at the end. if exists remove the characters */
	status = true;
	while(status) {
		if(msg.endsWith("&nbsp;")) {
			msg = msg.substring(0,msg.length-6).strip();
		} else {
			status = false;
		}
	}

	return msg;
}

function setAlertInfoMessage(msg, id) {
	if(msg == "") {
		document.getElementById(id).innerHTML = "";
		document.getElementById(id).style.display = "none";
		//disablethis('saveButton');
	} else {
		document.getElementById(id).innerHTML = msg;
		document.getElementById(id).style.display = "";

	}
}


function createActionBlockHandler(resp) {

	setActionBlockMessages(resp.responseText);
	hidepopup('customId');
}

function updateActionBlockHandler(resp) {

	setActionBlockMessages(resp.responseText);
	hidepopup('editId');
}

function editActionBlock() {
	var newcustommessage = document.getElementById("new-custom-message").innerHTML;
	var editMessage = document.getElementById("editMessage").value;
	newcustommessage ="  "+instance11.e.body.innerHTML.anchorEntities();
	newcustommessage = newcustommessage.string_create_urls();
	newcustommessage = newcustommessage.specialCharacterEntities();
	if(validateCustomMessage(false)) {

		/** disable the update button to avoid multiple submissions */
		disablethis('updateButton');

		editMessage ="  "+instance11.e.body.innerHTML.anchorEntities();
		editMessage = editMessage.string_create_urls();

		/** send the request */
		postForm(document.updateActionBlock, updateActionMessage);

	}  
}

function updateSettingsHandler(resp) {
	setActionBlockMessages(resp.responseText);
	if(document.getElementById("removedItemsCount").value >0 ) {
		document.getElementById("removeCount").innerHTML = document.getElementById("removedItemsCount").value;
		document.getElementById("restoreItem").style.display = "";
	} else {
		document.getElementById("restoreItem").style.display = "none";
	}

	hidepopup('displayId');
}

function restoreMessagesHandler(resp) {
	setActionBlockMessages(resp.responseText);
	hidepopup('restoreId');
	if(document.getElementById("removedItemsCount").value >0 ) {
		document.getElementById("removeCount").innerHTML = document.getElementById("removedItemsCount").value;
		document.getElementById("restoreItem").style.display = "";
	} else {
		document.getElementById("restoreItem").style.display = "none";
	}
}

function removeActionBlockHandker(resp) {
	hideblockpopup('block-popup');
	setActionBlockMessages(resp.responseText);
	if(document.getElementById("removedItemsCount").value >0 ) {
		document.getElementById("removeCount").innerHTML = document.getElementById("removedItemsCount").value;
		document.getElementById("restoreItem").style.display = "";
	} else {
		document.getElementById("restoreItem").style.display = "none";
	}
}

function setActionBlockMessages(responesText) {
	//document.getElementById("yellow-alerts-div").innerHTML = resp.responseText;
	document.getElementById("yellow-alerts-container-div").innerHTML = responesText;
	document.getElementById("action-block-messages").innerHTML = "";

	document.getElementById("action-block-messages").innerHTML = document.getElementById("action-messages-container").innerHTML 
	document.getElementById("yellow-alerts-container-div").innerHTML = "";
	// document.getElementById("display-settings-div").style.display = "";

	var obj = document.getElementsByName("hideValues");
	for(i =0; i< obj.length;i++) {
		document.getElementById("blockDiv"+obj[i].value).style.display = "none";
	}
}

function showDisplaySettings() {
	if($('more-popup'))
	{
		$('more-popup').hide();
	}
	sendRequest(document.getElementById("showActionBlocksUrl").value+"&showSettings=0", showDisplaySettingsHandler);

}

function showDisplaySettingsHandler(resp) {

	document.getElementById("display-settings-div").innerHTML = resp.responseText;
	document.getElementById("display-settings-div").innerHTML = document.getElementById("displaySettings").innerHTML 
	document.getElementById("display-settings-div").style.display = "";

	var ids = document.getElementById("messageIds").value;
	var messagesIds = ids.split(",");
	for(i=0;i<messagesIds.length;i++) {
		if(messagesIds[i] != ""){
			sections[sections.length] = 'group'+messagesIds[i];
			Sortable.create('group'+messagesIds[i],{tag:'div',dropOnEmpty: true, containment: sections,only:'lineitem'});
		}
	}
	Sortable.create('page',{tag:'div',only:'section',handle:'handle'});
	removedMessages = new Array();
	showalertspopup('displayId');
}

function showCreatePopup(id) {
	instance10.e.body.innerHTML = "";
	/*document.getElementById("showAdmin").checked = false;
	    document.getElementById("showModAdmin").checked = false;*/
	document.getElementById("showMod").checked = false;
	document.getElementById("showEndUser").checked = false;

	/**
	 * Author : vveerabathini
	 * Bug : 4814, Displaying "Anonymus" setting option in "Add new custom message" of action block for a private site.
	 * fix: Updated code to set anonymus value if it is not null  
	 */
	if(document.getElementById("showAnon")!=null) {
		document.getElementById("showAnon").checked = false;
	}
	$('create-custom-message-alert').style.display = "none";

	/*
			@Author : gkottala
			@Bug No:  4267
			@Fix :  After clicking save button in custom message popup, enable the save button in custom message popup.    
	 */
	enableSaveButton('saveButton');
	showalertspopup(id);
}

/*
		@Author : gkottala
		@Bug No:  4267
		@Fix :  After clicking save button in custom message popup, enable the save button in custom message popup.    
 */	
function enableSaveButton(id){

	$(id).href="javascript:createActionBlock();";
	$(id).className="button small primary vote";  

}
/*@Author :spenumatsa
 *@Bug : DS-4385 : User receiving more than one "password reset instructions" mails when he click's more than once on submit button in forgot password field.
 * */

function enableSubmitButton(id){		
	$(id).className="button small primary vote";
}


function enableEditButton(id){

	$(id).href="javascript:editActionBlock();";
	$(id).className="button small primary vote";  

}

function editMessage(id) {
	showalertspopup('editId')
}

function showblockpopup(ele, id)
{
	document.getElementById("currentMessageId").value = id;
	document.getElementById("editMessageId").value = id;
	document.getElementById("editSettingId").value = document.getElementById("msgSetting"+id).value;

	instance11.e.body.innerHTML =  document.getElementById("message"+id).innerHTML; 
	var settingsVal = document.getElementById("settings"+id).value;
	/*document.getElementById("editShowAdmin").checked = false;
	   document.getElementById("editShowModAdmin").checked = false;*/
	document.getElementById("editShowMod").checked = false;
	document.getElementById("editShowEndUser").checked = false;
	document.getElementById("editShowAnon").checked = false;
	/*if(settingsVal.indexOf("1")>=0) {
		   document.getElementById("editShowAdmin").checked = true; 
	   }
	   if(settingsVal.indexOf("2")>=0) {
		   document.getElementById("editShowModAdmin").checked = true;
	   }*/
	if(settingsVal.indexOf("3")>=0) {
		document.getElementById("editShowMod").checked = true;
	}
	if(settingsVal.indexOf("4")>=0) {
		document.getElementById("editShowEndUser").checked = true;
	}
	if(settingsVal.indexOf("5")>=0) {
		document.getElementById("editShowAnon").checked = true;
	}

	reference = ele.parentNode.parentNode;
	var myPos = new Array();
	myPos = findPos(ele);
	var fx = myPos[0];
	var fy = myPos[1];
	$('block-popup').style.display = 'block'; 
	$('block-popup').style.top = fy-45+'px';
	$('block-popup').style.left = fx-90+'px';

}


function showSettingsPage(obj, pageCount) {
	var totalPageCount = document.getElementById("pageCount").value;
	for(i=0;i<totalPageCount;i++) {
		var imgObj = document.getElementById("paginDiv"+i);
		imgObj.src =   getContext() +  "/site/common/images/common-images/paginationnormal.gif";
		// imgObj.src = getContext() +
		// "/site/common/images/common-images/paginationselected.gif";
		document.getElementById("showDiv"+i+".0").style.display = "none"
			if(i == pageCount) {
				obj.src = getContext() + "/site/common/images/common-images/paginationselected.gif";
				document.getElementById("showDiv"+i+".0").style.display = "";
			}
	}

}

function showBlocksPage(obj, pageCount) {
	var totalPageCount = document.getElementById("pageBlockCount").value;
	for(i=0;i<totalPageCount;i++) {
		var imgObj = document.getElementById("paginBlockDiv"+i);
		imgObj.src =   getContext() +  "/site/common/images/common-images/paginationnormal.gif";
		// imgObj.src = getContext() +
		// "/site/common/images/common-images/paginationselected.gif";
		document.getElementById("showBlockDiv"+i+".0").style.display = "none"
			if(i == pageCount) {
				obj.src = getContext() + "/site/common/images/common-images/paginationselected.gif";
				document.getElementById("showBlockDiv"+i+".0").style.display = "";
			}
	}

}

function getContext() {
	return document.getElementById("pagecontext").value;
}

function checkMessageCount(roleType, obj) {
	/*if(obj.checked == true) {
			var roleSettings = document.getElementsByName(roleType);
			var count = 0;
			var exceeds = false;
			for(i=0; i<roleSettings.length; i++) {
				if(roleSettings[i].checked == true) {
					count = count + 1;
				}
				if(count > 10) {
					exceeds = true;
					break;
				}
			}
			if(exceeds) {
				obj.checked = false;
				setAlertInfoMessage("Max 10 messages can be displayed for a role", "display-settings-message-alert");
				//alert("Max 10 messages can be selected for a role");
			} else {
				setAlertInfoMessage("", "display-settings-message-alert");
			}
		}*/
}

function updateMessageSettings() {
	// get action message and setting id
	// get role settings
	// construct a string
	var actionMessages = document.getElementsByName("actionMessages");
	var displaySettings = "";
	for(i = 0; i<actionMessages.length; i++) {
		var msgId = actionMessages[i].value;
		var settings = "";
		if(msgId.indexOf("-") > 0) {
			msgId = msgId.substring(0,msgId.indexOf("-"));
		}
		settings += "~";
		/*if(document.getElementById("showAdmin"+msgId).checked == true) {
			settings += "1";
			}
			if(document.getElementById("showModeratorAdmin"+msgId).checked == true) {
			settings += "2";
			}*/
		if(document.getElementById("showModerator"+msgId).checked == true) {
			settings += "3";
		}
		if(document.getElementById("showEnduser"+msgId).checked == true) {
			settings += "4";
		}
		if(document.getElementById("showAnonymous"+msgId)) {
			if(document.getElementById("showAnonymous"+msgId).checked == true) {
				settings += "5";
			}
		}
		displaySettings += actionMessages[i].value + settings + ":";
	}

	displaySettings = displaySettings.substring(0, displaySettings.length-1);
	document.getElementById("settingsDetails").value = displaySettings;
	var sortOrder =	 getGroupOrder();
	document.getElementById("sortOrder").value = sortOrder;
	//alert(sortOrder);
	postForm(document.updateActionBlockForm, updateSettingsHandler);
}

function removeActionBlock() {
	var id = document.getElementById("currentMessageId").value;
	var login = "";
	if(document.getElementById("logUserId").value == 0) {
		login = "&anonymousLogin=0";
	}  
	sendRequest(document.getElementById("hideActionBlockUrl").value+"&customMessageId="+id+login, removeActionBlockHandker);
}

function hideActionBlock(id) {
	if(document.getElementById('more-popup').style.display=="block")
	{
		document.getElementById('more-popup').style.display="none"
	}
	document.getElementById("currentMessageId").value = id;
	removeActionBlock();
}

function showRestoreMessages() {
	var login = "";
	if(document.getElementById("logUserId").value == 0) {
		login = "&anonymousLogin=0";
	} 
	if($('more-popup'))
	{
		$('more-popup').hide();
	}
	sendRequest(document.getElementById("showRemovedBlocksUrl").value+login, showRestoreMessagesHandler)
}

function showRestoreMessagesHandler(resp) {
	document.getElementById("restore-action-messages").innerHTML = resp.responseText;
	showalertspopup('restoreId');
}	

function restoreActionMessages() {
	var restoreIds = document.getElementsByName("restoreIds");
	var exists = false;
	if(restoreIds.length >0 ) {
		for(i=0;i<restoreIds.length;i++) {
			if(restoreIds[i].checked) {
				exists = true;
				break;
			}
		}
	}
	if(exists) {
		postForm(document.restoreActionBlockForm, restoreMessagesHandler);
	} else {
		//alert("Select one item to restore ");
		setAlertInfoMessage("Select atleast one message to restore", "restore-message-alert");
	}
}

function hideMessage(id) {

	document.getElementById("showModerator"+id).checked = false;
	document.getElementById("showEnduser"+id).checked = false;
	if(document.getElementById("showAnonymous"+id)) {
		document.getElementById("showAnonymous"+id).checked = false;
	}

	/** hide role setting div */
	document.getElementById("alertSettingsDiv"+id).style.display = "none";

	/** change Hide link Display */

}

function assignToRole(id, isAssign, obj) {
	if(document.getElementById("settingsShowId"+id).innerHTML  == "Display") {
		/** hide role setting div */

		document.getElementById("showModerator"+id).checked =false;
		document.getElementById("showEnduser"+id).checked =false;
		if(document.getElementById("showAnonymous"+id)) {
			document.getElementById("showAnonymous"+id).checked = false;
		}

		document.getElementById("alertSettingsDiv"+id).style.display = "";
		document.getElementById("settingsShowId"+id).innerHTML = "Hide";
	} else {
		document.getElementById("settingsShowId"+id).innerHTML = "Display";
		hideMessage(id);
	}

	/** change Display to Hide */

}

function createNewSection(name) {
	var name = $F('sectionName');
	if (name != '') {
		var newDiv = Builder.node('div', {id: 'group' + (sections.length + 1), className: 'section', style: 'display:none;' }, [
		                                                                                                                        Builder.node('h3', {className: 'handle'}, name)
		                                                                                                                        ]);

		sections.push(newDiv.id);
		$('page').appendChild(newDiv);
		Effect.Appear(newDiv.id);
		destroyLineItemSortables();
		createLineItemSortables();
		createGroupSortable();
	}
}

function createLineItemSortables() {
	for(var i = 0; i < sections.length; i++) {
		Sortable.create(sections[i],{tag:'div',dropOnEmpty: true, containment: sections,only:'lineitem'});
	}
}

function destroyLineItemSortables() {
	for(var i = 0; i < sections.length; i++) {
		Sortable.destroy(sections[i]);
	}
}

function createGroupSortable() {
	Sortable.create('page',{tag:'div',only:'section',handle:'handle'});
}

/*
	Debug Functions for checking the group and item order
 */
function getGroupOrder() {
	var alerttext = "";
	var sections = document.getElementsByClassName('section');
	for(k=0;k<sections.length;k++) {
		var section =  sections[k];
		var sectionID = section.id;
		//var order = Sortable.serialize(sectionID);
		if(!removedBlock(sectionID)) {
			alerttext += sectionID + ':'  ;
		}
	}
	return alerttext;
}

function removedBlock(sectionID) {
	var removed = false;
	for(i=0; i<removedMessages.length; i++) {
		if("group"+removedMessages[i] == sectionID) {
			break;
			removed = true;
		}
	}
	return removed;
}

function editBlock(id) {
	/*
			@Author : gkottala
			@Bug No:  4267
			@Fix :  Enable the enable the save button After clicking update.    
	 */	
	enableEditButton('updateButton');
	$('edit-custom-message-alert').style.display = "none";
	document.getElementById("currentMessageId").value = id;
	document.getElementById("editMessageId").value = id;
	instance11.e.body.innerHTML =  document.getElementById("messageText"+id).innerHTML; 
	hidepopup('displayId');
	showalertspopup('editId')
}

function updateActionMessage(resp) {
	var id = document.getElementById("currentMessageId").value;
	document.getElementById("messageText"+id).innerHTML =  instance11.e.body.innerHTML;
	hidepopup('editId')
	showalertspopup('displayId');
}

function deleteBlock(id) {
	if(confirm("Are you sure want to delete?")) {
		document.getElementById("currentMessageId").value = id;
		postRequest(document.getElementById("removeActionBlockUrl").value,"messageId="+id, deleteActionBlockHandker);
	}
}

var removedMessages = new Array();
function deleteActionBlockHandker() {
	var id = document.getElementById("currentMessageId").value;
	removedMessages[removedMessages.length] = id;
	document.getElementById("group"+id).style.display = "none";
}

function cancelDisplaySettings() {
	refreshActionBlocks();
}

function refreshActionBlocks() {
	if($('displayId'))
	{
		$('displayId').hide();
	}
	sendRequest(document.getElementById("showActionBlocksUrl").value, refreshActionBlocksHandler);
}

function refreshActionBlocksHandler(resp) {
	setActionBlockMessages(resp.responseText);
	if(document.getElementById("removedItemsCount").value >0 ) {
		document.getElementById("removeCount").innerHTML = document.getElementById("removedItemsCount").value;
		document.getElementById("restoreItem").style.display = "";
	} else {
		document.getElementById("restoreItem").style.display = "none";
	}
	hidepopup('displayId');
}

/** Action Block functions */

/** start of make widget methods */

/*
 * @author:mkonusu
 * This method is invoked when user clicks on Make Widget link from 
 *	topics listing page and only for VoteOrSuggest topics.
 *  
 */
function makeWidget(topicId, publishUrl) {

	/** get the hidden widget code and replace topicId and publishUrl values */
	var grabScript = $('make-widget-content').value;
	grabScript = grabScript.replace("#id#",topicId);
	grabScript = grabScript.replace("#publishUrl#",publishUrl);
	$('make-widget-code').value = grabScript;

	/** diplay popup with widget code */
	showpopupwindow('grabcodeId')
}

/** end of make widget methods */

/*
 * Author : vveerabathini
 * New Feature : DS-4232
 * Added new method to performing voting on multi choice topic with multiple answers.
 */	
function performVoteChoice(divId,url,topicId,choiceId,mode){

	if($('multipleChoice').selected) {
		var noOfAnswers = $('noOfAnswers_'+topicId).value;
		var voteResultsCount = $('voteResultsCount_'+topicId).value;
		if(voteResultsCount < noOfAnswers) {
			$('multipleChoice').selected = true;
			$('multipleChoice').disabled = false;
			performVote(divId,url,topicId,choiceId,mode);
		} 
	} else {
		performVote(divId,url,topicId,choiceId,mode);
	}
}

/**
* Validates the topic category
*/
function validateCategories()
{
	setAlertMessage("askQuestionAlertDiv","askQuestionAlertMsgDiv","");
	// alert(document.getElementById('multi-categories').style.display +"--"+ $('catIdchkbox').checked +"  "+ $('categoryId').value);

	if(document.getElementById('multi-categories').style.display=="none" && $('categoryId').value==0){
		setAlertMessage("askQuestionAlertDiv","askQuestionAlertMsgDiv","Please select a category.");
		window.scroll(0,0);
		return false;
	}else if(document.getElementById('multi-categories').style.display!="none"){
		var id = document.getElementById('multi-categories');
		var inputs = document.getElementById('multi-categories').getElementsByTagName('input');
		var i;
		var j=0;
		var stringArray= new Array();
		for(i=0;i<inputs.length;i++)
		{
			if(inputs[i].type=="checkbox" && inputs[i].checked)	{							 
				j++;					
			}
		}
		if(j==0){
			setAlertMessage("askQuestionAlertDiv","askQuestionAlertMsgDiv","Please select atleast one category.");
			window.scroll(0,0);
			return false;
		}
	} 
	return true;
}

//accordian.js
function expandQuestions(obj)
{
	var ua = navigator.userAgent.toLowerCase();
	if(ua.indexOf('msie') != -1)
	{
		var show_question = obj.nextSibling;
	}
	else
	{
		var show_question = obj.nextSibling.nextSibling;
	}
	var questions_box=document.getElementsByClassName('accordion_content');
	var img_ele = document.getElementById('vertical_container').getElementsByTagName('span');
	for(i=0;i<questions_box.length;i++)
	{
		questions_box[i].style.display="none";
	}
	for(i=0;i<img_ele.length;i++)
	{
		img_ele[i].style.backgroundPosition= '-32px -16px';
	}
	show_question.style.height = 'auto';
	Effect.toggle(show_question, 'blind',{ duration: 0.5 });
	obj.childNodes[0].style.backgroundPosition= '-64px -16px';
}
//ajax.js
function loadDivContent(div,url,fnCallback) {
	//clickUrl();
	if(div!="listgroupuserdiv" && div!="groupmaintabcontentDiv")
	{
		showloader();
	}
	//document.getElementsByTagName('body')[0].style.cursor="wait";
	//$('opacitydiv').style.visibility="visible";
	var divObj = null;
	if(typeof(div)=="string")	// if obj is string get parent object
		divObj=document.getElementById(div);
	else	// use obj as parent
		divObj=div;
	var options = {};
	options.method = 'POST';
	options['postBody'] = null;
	options.onSuccess = function(resp) {
		//alert("funciton call back"+fnCallback);
		resetSessionTimer1();
		if(div!="listgroupuserdiv" && div!="groupmaintabcontentDiv")
		{
			hideloader();
		} 
		//document.getElementsByTagName('body')[0].style.cursor="default";
		//$('opacitydiv').style.visibility="hidden";
		if(isExpired(resp.responseText)) {
			return false;
		}
		if(resp.responseText.indexOf("Error Page")>-1) {
			alert("Error in server");
			//location.href= contextPath+ "/jsps/sessionexpire.jsp";
			return false;
		}
		divObj.innerHTML = resp.responseText;
		if(fnCallback!=null) fnCallback(true,resp);
	}
	options.onFailure = function(resp) {
		resetSessionTimer1();

		if(resp.responseText.indexOf("Error Page")>-1) {
			alert("Error in server");
			//location.href= contextPath+ "/jsps/sessionexpire.jsp";
			return false;
		}
		if(fnCallback!=null) fnCallback(false,resp);
	}

	new Ajax.Request(url,options);
}

function loadDivContentUnSubscribe(div,url,fnCallback) {
	//clickUrl();
	//showloader();
	//document.getElementsByTagName('body')[0].style.cursor="wait";
	//$('opacitydiv').style.visibility="visible";
	var divObj = null;
	if(typeof(div)=="string")	// if obj is string get parent object
		divObj=document.getElementById(div);
	else	// use obj as parent
		divObj=div;
	var options = {};
	options.method = 'POST';
	options['postBody'] = null;
	options.onSuccess = function(resp) {
		resetSessionTimer1();
		hideloader();
		//document.getElementsByTagName('body')[0].style.cursor="default";
		//$('opacitydiv').style.visibility="hidden";
		if(isExpired(resp.responseText)) {
			return false;
		}
		if(resp.responseText.indexOf("Error Page")>-1) {
			alert("Error in server");
			//location.href= contextPath+ "/jsps/sessionexpire.jsp";
			return false;
		}

		divObj.innerHTML = resp.responseText;
		if(fnCallback!=null) fnCallback(true,resp);
	}
	options.onFailure = function(resp) {
		resetSessionTimer1();

		if(resp.responseText.indexOf("Error Page")>-1) {
			alert("Error in server");
			//location.href= contextPath+ "/jsps/sessionexpire.jsp";
			return false;
		}
		if(fnCallback!=null) fnCallback(false,resp);
	}

	new Ajax.Request(url,options);
}


function sendRequest (url,fnCallback)
{
	showloader();
	//document.getElementsByTagName('body')[0].style.cursor="wait";
	var options = {};
	options.method = 'POST';
	options['postBody'] = null;
	var mask = document.getElementById("mask");
	options.onSuccess = function(resp) {
		resetSessionTimer1();
		hideloader();
		//document.getElementsByTagName('body')[0].style.cursor="default";
		if(isExpired(resp.responseText)) {
			return false;
		}		
		if(fnCallback!=null) fnCallback(resp);
		//document.body.style.overflow="auto";
		//document.getElementById("mask").style.display="none"
		//document.getElementById("loader").style.display="none"
	}
	options.onFailure = function(resp) {
		resetSessionTimer1();
		//document.getElementsByTagName('body')[0].style.cursor="default";
		if(fnCallback!=null) fnCallback(resp);
		document.location.href=resp.getResponseHeader("url");
	}
	if(mask) {
		mask.style.display="block";
		mask.style.width=document.body.clientWidth;
		mask.style.height=document.body.clientHeight;
		document.getElementById("loader").style.display="block";
	}
	new Ajax.Request(url,options);
}
function sendMemberRequest (url,fnCallback)
{
	//document.getElementsByTagName('body')[0].style.cursor="wait";
	var options = {};
	options.method = 'POST';
	options['postBody'] = null;
	var mask = document.getElementById("mask");
	options.onSuccess = function(resp) {
		resetSessionTimer1();
		hideloader();
		//document.getElementsByTagName('body')[0].style.cursor="default";
		if(isExpired(resp.responseText)) {
			return false;
		}		
		if(fnCallback!=null) fnCallback(resp);
		//document.body.style.overflow="auto";
		//document.getElementById("mask").style.display="none"
		//document.getElementById("loader").style.display="none"
	}
	options.onFailure = function(resp) {
		resetSessionTimer1();
		//document.getElementsByTagName('body')[0].style.cursor="default";
		if(fnCallback!=null) fnCallback(resp);
		document.location.href=resp.getResponseHeader("url");
	}
	if(mask) {
		mask.style.display="block";
		mask.style.width=document.body.clientWidth;
		mask.style.height=document.body.clientHeight;
		document.getElementById("loader").style.display="block";
	}
	new Ajax.Request(url,options);
}
function postForm(form,fnCallback)
{
	showloader();
	//document.getElementsByTagName('body')[0].style.cursor="wait";
	var options = {};
	options.method = 'post';
	options.parameters = Form.serialize(form);

	options.onSuccess = function(resp) {
		resetSessionTimer1();
		if(document.loginForm){showloader();}else{hideloader();}
		//ocument.getElementsByTagName('body')[0].style.cursor="default";
		if(isExpired(resp.responseText)) {
			return false;
		}
		if(fnCallback!=null) fnCallback(resp);
	}
	options.onFailure = function(resp) {
		resetSessionTimer1();
		//document.getElementsByTagName('body')[0].style.cursor="default";
		if(fnCallback!=null) fnCallback(resp);
	}
	options.onComplete=  function(resp) {
		resetSessionTimer1();
		//document.getElementsByTagName('body')[0].style.cursor="default";
		if(fnCallback!=null) fnCallback(resp);
	}

	if(document.getElementById('alertOrError'))
		document.getElementById('alertOrError').innerHTML = "";

	new Ajax.Request(form.action,options);

}

function postRequest(url,parameters, fnCallback)
{
	showloader();
	//document.getElementsByTagName('body')[0].style.cursor="wait";
	var options = {};
	options.method = 'post';
	options.parameters = parameters;

	options.onSuccess = function(resp) {
		resetSessionTimer1();
		hideloader();
		//document.getElementsByTagName('body')[0].style.cursor="default";
		if(isExpired(resp.responseText)) {
			return false;
		}
		if(fnCallback!=null) fnCallback(resp);
	}
	options.onFailure = function(resp) {
		resetSessionTimer1();
		//document.getElementsByTagName('body')[0].style.cursor="default";
		if(fnCallback!=null) fnCallback(resp);
	}
	options.onComplete=  function(resp) {
		resetSessionTimer1();
		//document.getElementsByTagName('body')[0].style.cursor="default";
		if(fnCallback!=null) fnCallback(resp);
	}

	if(document.getElementById('alertOrError')) {
		document.getElementById('alertOrError').innerHTML = "";
	}

	new Ajax.Request(url,options);

}

function submitForm(div,form,fnCallback)
{
	if(div!="groupmaintabcontentDiv"&& div!="listgroupuserdiv")
	{
		showloader();
	}
	//document.getElementsByTagName('body')[0].style.cursor="wait";
	var divObj = null;
	if(typeof(div)=="string")	// if obj is string get parent object
		divObj=document.getElementById(div);
	else	// use obj as parent
		divObj=div;
	var options = {};
	options.method = 'post';
	options.parameters = Form.serialize(form);

	options.onSuccess = function(resp) {
		resetSessionTimer1();
		if(div!="listgroupuserdiv" && div!="groupmaintabcontentDiv")
		{
			hideloader();
		}  
		//document.getElementsByTagName('body')[0].style.cursor="default";
		//$('opacitydiv').style.visibility="hidden";
		if(isExpired(resp.responseText)) {
			return false;
		}
		if(resp.responseText.indexOf("Error Page")>-1) {
			alert("Error in server");
			//location.href= contextPath+ "/jsps/sessionexpire.jsp";
			return false;
		}
		if(document.getElementById(div))
			document.getElementById(div).innerHTML=resp.responseText;
		divObj.innerHTML = resp.responseText;
		if(fnCallback!=null) fnCallback(true,resp);
	}
	options.onFailure = function(resp) {
		resetSessionTimer1();
		if(resp.responseText.indexOf("Error Page")>-1) {
			alert("Error in server");
			//location.href= contextPath+ "/jsps/sessionexpire.jsp";
			return false;
		}
		if(fnCallback!=null) fnCallback(false,resp);
	}

	options.onComplete=  function(resp) {
		//if(fnCallback!=null) fnCallback(resp);
	}

	if(document.getElementById('alertOrError'))
		document.getElementById('alertOrError').innerHTML = "";

	new Ajax.Request(form.action,options);

}

/*
* @author: mkonusu
* verify session expire message exists and redirect to session expire page
* //TODO: use hidden value to store session expire message to avoid hardcode things
*/
function isExpired(responseText) {
	if(responseText.indexOf("For your security, you were logged out due to inactivity")>0) {
		//showHomePage();
		redirectToSessionExpirePage1()
		return true;
	}
	return false;
}

//xml2obj.js
// JavaScript Document
function buildObj(obj, nodeItem) {
	var idx, nodeChild;
	var tObj;
	//Loop through the sibling elements in this level of the XML
	while (nodeItem != null) {
		idx = nodeItem.nodeName;
		if (nodeItem.nodeType == 1) {
			//Recursively process the child nodes
			tObj = buildObj( {}, nodeItem.firstChild);
			//
			//Process any XML node attributes
			var attObj=nodeItem.attributes;
			for(a=0;a<attObj.length;a++){
				tObj[attObj[a].nodeName] = attObj[a].nodeValue;
			}

			//Check the first child, and see if it's a simple text node
			if (nodeItem.nodeValue != null) {
				//Save the value from the TEXT element into the object
				tObj._value = nodeItem.nodeValue;
			} else {
				nodeChild = nodeItem.firstChild;
				if (nodeChild != null) {
					if (nodeChild.nodeType == 3) {
						if (nodeChild.nodeValue != null) {
							//Save the value from the TEXT element into the object
							tObj._value = nodeChild.nodeValue;
						}
					}
				}
			}
			//If there are duplicate nodenames, convert them to an array
			if (obj[idx] != null) {
				if (obj[idx]._type != 'array') {
					obj[idx] = [ obj[idx] ];
					obj[idx]._type = 'array';
					obj[idx][1] = tObj;
				} else {
					obj[idx][ obj[idx].length ] = tObj;
				}
			} else {
				obj[idx] = tObj;
			}

		}	//END OF: if (nodeItem.nodeType == 1)
			//Get the next sibling node in this level of the XML
			nodeItem = nodeItem.nextSibling;
	}	//END OF: while(nodeItem != null)
		return obj;
}
//browser-detect.js
/* http://www.quirksmode.org/js/detect.html  */

var BrowserDetect = {
		init: function () {
	this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
	this.version = this.searchVersion(navigator.userAgent)
	|| this.searchVersion(navigator.appVersion)
	|| "an unknown version";
	this.OS = this.searchString(this.dataOS) || "an unknown OS";
},
searchString: function (data) {
	for (var i=0;i<data.length;i++)	{
		var dataString = data[i].string;
		var dataProp = data[i].prop;
		this.versionSearchString = data[i].versionSearch || data[i].identity;
		if (dataString) {
			if (dataString.indexOf(data[i].subString) != -1)
				return data[i].identity;
		}
		else if (dataProp)
			return data[i].identity;
	}
},
searchVersion: function (dataString) {
	var index = dataString.indexOf(this.versionSearchString);
	if (index == -1) return;
	return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
},
dataBrowser: [
              {
            	  string: navigator.userAgent,
            	  subString: "Chrome",
            	  identity: "Chrome"
              },
              { 	string: navigator.userAgent,
            	  subString: "OmniWeb",
            	  versionSearch: "OmniWeb/",
            	  identity: "OmniWeb"
              },
              {
            	  string: navigator.vendor,
            	  subString: "Apple",
            	  identity: "Safari",
            	  versionSearch: "Version"
              },
              {
            	  prop: window.opera,
            	  identity: "Opera"
              },
              {
            	  string: navigator.vendor,
            	  subString: "iCab",
            	  identity: "iCab"
              },
              {
            	  string: navigator.vendor,
            	  subString: "KDE",
            	  identity: "Konqueror"
              },
              {
            	  string: navigator.userAgent,
            	  subString: "Firefox",
            	  identity: "Firefox"
              },
              {
            	  string: navigator.vendor,
            	  subString: "Camino",
            	  identity: "Camino"
              },
              {		// for newer Netscapes (6+)
              string: navigator.userAgent,
              subString: "Netscape",
              identity: "Netscape"
              },
              {
            	  string: navigator.userAgent,
            	  subString: "MSIE",
            	  identity: "Explorer",
            	  versionSearch: "MSIE"
              },
              {
            	  string: navigator.userAgent,
            	  subString: "Gecko",
            	  identity: "Mozilla",
            	  versionSearch: "rv"
              },
              { 		// for older Netscapes (4-)
              string: navigator.userAgent,
              subString: "Mozilla",
              identity: "Netscape",
              versionSearch: "Mozilla"
              }
              ],
              dataOS : [
                        {
                        	string: navigator.platform,
                        	subString: "Win",
                        	identity: "Windows"
                        },
                        {
                        	string: navigator.platform,
                        	subString: "Mac",
                        	identity: "Mac"
                        },
                        {
                        	string: navigator.userAgent,
                        	subString: "iPhone",
                        	identity: "iPhone/iPod"
                        },
                        {
                        	string: navigator.platform,
                        	subString: "Linux",
                        	identity: "Linux"
                        }
                        ]

};
BrowserDetect.init();
//cutstring.js
/*jsl:option explicit*/
/*jsl:declare document*/
/*
This class is used to cut the string which is having html tags. 
It does not count the html tags, it just count the string inside tags and keeps
the tags as it is.

ex: If the string is "welcome to <b>JS World</b> <br> JS is bla". and If we want to cut the string of 12 charaters then output will be "welcome to <b>JS</b>". 

Here while cutting the string it keeps the tags for the cutting string and skip the rest and without distorbing the div structure.

USAGE:
 var obj = new cutString("welcome to <b>JS World</b> <br> JS is",12);
 var newCutString = obj.cut();
 */
function CutString(string,limit){
	// temparary node to parse the html tags in the string
	this.tempDiv = document.createElement('div');
	this.tempDiv.id = "TempNodeForTest";
	this.tempDiv.innerHTML = string;
	// while parsing text no of characters parsed
	this.charCount = 0;
	this.limitReached = false;
	this.limit = limit;

}
CutString.prototype.cut = function(){
	var newDiv = document.createElement('div');
	this.searchEnd(this.tempDiv, newDiv);
	return newDiv.innerHTML;
};

CutString.prototype.searchEnd = function(parseDiv, newParent){
	var ele;
	var newEle;
	for(var j=0; j< parseDiv.childNodes.length; j++){
		ele = parseDiv.childNodes[j];
		// not text node
		if(ele.nodeType != 3){
			newEle = ele.cloneNode(true);
			newParent.appendChild(newEle);
			if(ele.childNodes.length === 0)
				continue;
			newEle.innerHTML = '';
			var res = this.searchEnd(ele,newEle);
			if(res)
				return res;
			else{
				continue;
			}
		}

		// the limit of the char count reached
		if(ele.nodeValue.length + this.charCount >= this.limit){
			newEle = ele.cloneNode(true);
			newEle.nodeValue = ele.nodeValue.substr(0, this.limit - this.charCount);
			newParent.appendChild(newEle);
			this.limitReached =  true;
			return true;
		}
		newEle = ele.cloneNode(true);
		newParent.appendChild(newEle);
		this.charCount += ele.nodeValue.length;
	}
	return false;
};

function cutHtmlString($string, $limit){
	var output = new CutString($string,$limit);
	return output.cut();
}
//this.js
//sections = document.getElementsByClassName('section');

function createNewSection(name) {
	//var name = $F('sectionName');
	var sectionDivs = document.getElementsByClassName('section');
	if(sectionDivs.length == 0) {
		sections = [ ];
		items    = [];
	} 
	var src = $F('contextPath');
	alert(src);
	if (name != '') {


		var newDiv = Builder.node('div', {id: 'group' + (sections.length + 1), className: 'section', style: 'display:none;' }, [
		                                                                                                                        Builder.node('div', {id: 'divgroup' + (sections.length + 1), className: 'handle'}, "")
		                                                                                                                        ]);
		//alert($('h3group' + (sections.length + 1)))
		sections.push(newDiv.id);
		$('page').appendChild(newDiv);
		var sHTML="";
		sHTML += "<div style='float:left;font-size:12px !important' id='h3group"+ (sections.length)+"' class='samp'>"+name+"</div>";
		sHTML += "<div style='float:right;padding-right:13px; padding-top:3px;'><img src='"+src+"common/images/deletecategory.gif' class='imgc' id="+sections.length+" onclick='deleteGroup(this)' style='cursor:pointer !important;'></div>";
		$('divgroup' + (sections.length)).innerHTML= sHTML;
		Effect.Appear(newDiv.id);
		//destroyLineItemSortables();
		//createLineItemSortables();
		//createGroupSortable();
		//$('sectionName').value ='';
	}
}

function createNewItem(name) {
	//var name = $F('itemName');
	if (name != '') {
		var newI = Builder.node('div', {
			id: 'item_' + (items.length + 1), 
			className: 'lineitem', 
			style: 'display:none;' });
		//newI.innerHTML=name;	
		items.push(newI.id);
		var firstitem = $('group1');
		firstitem.appendChild(newI);
		Effect.Appear(newI.id);
		destroyLineItemSortables();
		createLineItemSortables();
		createGroupSortable();
		//$('itemName').value ='';
	}
}

function createNewItem(name, divId) {
	//var name = $F('itemName');
	var src = $F('contextPath');
	if (name != '') {
		var newI = Builder.node('div', {
			id: 'item_' + (items.length + 1), 
			className: 'lineitem', 
			style: 'display:none;' });
		//newI.innerHTML=name;	
		items.push(newI.id);
		var firstitem = $('group'+divId);
		firstitem.appendChild(newI);
		Effect.Appear(newI.id);
		var sHTML="";
		sHTML += "<div style='float:left;font-size:12px !important' id='catItem_"+ (items.length)+"'>"+name+"</div>";
		sHTML += "<div style='float:right;padding-right:15px;'><img src='"+src+"common/images/deletecategory_disable.gif' onclick='deleteItem("+items.length+");' style='cursor:pointer !important;'></div>";
		newI.innerHTML=sHTML;
		destroyLineItemSortables();
		createLineItemSortables();
		createGroupSortable();
		//$('itemName').value ='';
	}
}

function createLineItemSortables() {
	for(var i = 0; i < sections.length; i++) {
		//if($("group"+sections[i])) {
		Sortable.create(sections[i],{tag:'div',dropOnEmpty: true, containment: sections,only:'lineitem'});
		//}
	}
}

function destroyLineItemSortables() {
	for(var i = 0; i < sections.length; i++) {
		//if($("group"+sections[i])) {
		//alert(sections[i]);
		Sortable.destroy(sections[i]);
		//}
	}
}

function createGroupSortable() {
	Sortable.create('page',{tag:'div',only:'section',handle:'handle'});
}


/*
	Debug Functions for checking the group and item order
 */
/*function getGroupOrder() {
		var sections = document.getElementsByClassName('section');
		var alerttext = '';
		sections.each(function(section) {
			var sectionID = section.id;
			var order = Sortable.serialize(sectionID);
			alerttext += sectionID + ': ' + Sortable.sequence(section) + '\n';
		});
		//return false;
	}*/

function destroyItemss() {
	destroyLineItemSortables();
	sections = new Array();
	items = new Array();
	$('page').innerHTML = "";
}

function constructGroups(grpsList) {
	grpsList.options.length = 0;
	for(i=0;i<sections.length;i++) {
		if($("h3"+sections[i])) {
			grpsList.options[grpsList.options.length] = new Option($("h3"+sections[i]).innerHTML,(i+1));
		}
	}
}

function isSectionAlreadyExists(name) {
	var sections = document.getElementsByClassName('section');
	var exists = false;
	sections.each(function(section) {
		var sectionID = section.id;
		if(($("h3"+sectionID).innerHTML).toLowerCase() == name.toLowerCase()) {
			exists = true;
		}
	});
	return exists;
}

function isItemAlreadyExists(grpId, name) {
	var sections = document.getElementsByClassName('section');
	var grpData = "";
	var alerttext = '';
	var exists = false;
	sections.each(function(section) {
		var sectionID = section.id;
		var order = Sortable.serialize(sectionID);
		alerttext  = ""+Sortable.sequence(section);
		var cats = alerttext.split(",");
		if(cats.length > 0) {
			for(i=0; i<cats.length; i++) {
				if($('catItem_'+cats[i])) {
					if(($('catItem_'+cats[i]).innerHTML).toLowerCase() == name.toLowerCase())  {
						exists = true;
					}
				}
			}
		}
	});
	return exists;
}

function deleteItem(id)
{
	$('item_'+id).remove();
}

function deleteGroup(ele)
{
	var id = ele.id;
	//$('group'+id).remove();
	//var ele = document.getElementById('group2').childNodes[1];
	//ele.style.display = "none";
	//ele.remove();
	var pos = -1;
	for(i=0;i<sections.length;i++) {
		if(sections[i] == 'group'+id) {
			pos = i;
		}
	}
	if(pos>-1) {
		var order = Sortable.serialize('group'+id);
		alerttext  = ""+Sortable.sequence($('group'+id));
		if(alerttext == "") {
			$('group'+id).remove();
			resetSections(pos);
			constructGroups($('grpSel'));
			destroyLineItemSortables();
			createLineItemSortables();
			createGroupSortable();
		}  else {
			setCatErrorInfo("<spring:message code='democrasoft.unable.to.delete'/>");
		}
	}
}

function resetSections(position) {
	var secs = document.getElementsByClassName('section');
	var handle = document.getElementsByClassName('handle');
	var samp = document.getElementsByClassName('samp');
	var imgc = document.getElementsByClassName('imgc');
	for(i=0;i<secs.length;i++) {
		secs[i].id = 'group'+(i+1);
		handle[i].id = 'divgroup'+(i+1);
		samp[i].id = 'h3group'+(i+1);
		imgc[i].id = i+1;

	}

	sections.pop();
}

//widget.js
/** Widget methods */


function addWidget() {
	window.scrollTo(0,0);
	$("widget-text").value = "";
	showpopupwindow('widgetId');
}

function editWidget() {
	$("widget-text").value = $("saveWidgetCode").value;
	showpopupwindow('widgetId');
}
function previewwidget()
{
	//hidepopup('widgetId');
	var Widget = $('banneradd-main');
	var myPos = new Array();
	myPos = findPos(Widget);
	var fx = myPos[0];
	var fy = myPos[1];	
	// showwidget();
	var val = getWidgetValue().strip();		
	if(val !="") 
	{
		if(val.indexOf('<script') == 0 || val.indexOf("<object") == 0 || val.indexOf("<img") == 0 || val.indexOf("<iframe") == 0)
		{
			$('alertMsgWidget').style.display="none";
			var regexscriptone = '(^(<script)+[ {};a-zA-Z0-9().:\/="\'\@,\%\$\&\+\-\_?>]+[<]+[/]+\script\+[>$])';
			var regexscripttwo = '(^(<script)+[ {};a-z0-9().:\/="\'>]+[<]+[/]+\script\+[>]+[ \n]+\<script>\+[ \n{};a-z0-9().:\/="\',#A-Z]+[<]+[/]+\script\+[>])';			
			var regexObj = '(^(<object)+[ {};a-zA-Z0-9<_().:\/="\'\@,\%\$\&\+\-\?>]+[<]+[/]+\object\+[>$])+$';
			var regexImg = '(^(<img )+[ {};a-zA-Z0-9().:\/="\'\@,\%\$\&\+\-\?_]+[>$])+$';
			var regexIframe = '(^(<iframe)+[ {};a-zA-Z0-9().:\/="\'\@#,\%\$\&\+\-\_?>]+[<]+[/]+\iframe\+[>$])+$';
			if(val.match(regexscriptone) || val.match(regexscripttwo) || val.match(regexObj) || val.match(regexImg) || val.match(regexIframe))
			{
				if(val.indexOf('<script')!= -1) 
				{	
					if(val.indexOf('alert')!= -1) 
					{
						$('alertMsgWidget').style.display="block";
						$('alertMsgWidget').innerHTML = $('valid-widget').value;
					}
					else
					{
						document.previewWidgetForm.submit();
					}
				}
				else if(val.indexOf('<object')!= -1)
				{
					if(val.indexOf('<embed')== -1) 
					{
						$('alertMsgWidget').style.display="block";
						$('alertMsgWidget').innerHTML = $('valid-widget').value;
					}
					else
					{
						var embedTagOne= val.indexOf('<embed');
						var embedTagTwo = val.indexOf('<embed', embedTagOne+1);
						if(embedTagTwo != -1)
						{
							$('alertMsgWidget').style.display="block";
							$('alertMsgWidget').innerHTML = $('valid-widget').value;
						}
						else
						{
							document.previewWidgetForm.submit();
						}
					}
				}
				else if(val.indexOf('<img')!= -1)
				{
					var imgTagOne= val.indexOf('<img');
					var imgTagTwo = val.indexOf('<img', imgTagOne+1);
					if(imgTagTwo != -1)
					{
						$('alertMsgWidget').style.display="block";
						$('alertMsgWidget').innerHTML = $('valid-widget').value;
					}
					else
					{
						document.previewWidgetForm.submit();
					}
				}
				else if(val.indexOf('<iframe')!= -1)
				{
					var iframeTagOne= val.indexOf('<iframe');
					var iframeTagTwo = val.indexOf('<iframe', iframeTagOne+1);
					if(iframeTagTwo != -1)
					{
						$('alertMsgWidget').style.display="block";
						$('alertMsgWidget').innerHTML = $('valid-widget').value;
					}
					else if(val.indexOf('src')== -1) 
					{
						$('alertMsgWidget').style.display="block";
						$('alertMsgWidget').innerHTML = $('valid-widget').value;
					}
					else
					{
						document.previewWidgetForm.submit();						
					}

				}

			}
			else
			{
				$('alertMsgWidget').style.display="block";
				$('alertMsgWidget').innerHTML = $('valid-widget').value;
			}
		}
		else
		{
			$('alertMsgWidget').style.display="block";
			$('alertMsgWidget').innerHTML = $('valid-widget').value;
		}


	} else {
		$('alertMsgWidget').style.display="block";
		$('alertMsgWidget').innerHTML = $('enter-widget').value;
	}
}

function getWidgetValue()
{		
	var val = $("widget-text").value.strip();	
	setCookie("widget",val,1);
	var width;
	var width_value;
	var second_width;
	var x;
	if(val.indexOf("<object") == 0 )
	{

		var ob = val.indexOf("object");
		var cot1 = val.indexOf('"',ob+1);
		var cot2 = val.indexOf('"',cot1+1);
		width_value = val.substring(cot1+1,cot2);
		width = val.indexOf("width",cot2);
		var cot3 = val.indexOf('"', width + 1);
		var cot4 = val.indexOf('"',cot3+1);
		width_value2 = val.substring(cot3+1,cot4);
		if(width_value > 230 || width_value2 > 230)
		{
			x = val.replace(width_value,230);
			x = x.replace(width_value2,230);
			var wm=x.replace("<embed ",'<embed wmode="transparent" ');
			$("widget-text").value = wm;
		}  
	}
	else if(val.indexOf("<img") == 0)
	{
		var imgwidth;
		var ob = val.indexOf("width");
		var cot1 = val.indexOf('"',ob+1);
		var cot2 = val.indexOf('"',cot1+1);
		imgwidth = val.substring(cot1+1,cot2);
		if(imgwidth > 230)
		{
			var y = val.replace(imgwidth,230);
			$("widget-text").value = y;
		}
	}
	else if(val.indexOf("<iframe") == 0)
	{
		var iframewidth,iframewidth2;
		var z;
		var ob = val.indexOf("width");
		var cot1 = val.indexOf('"',ob+1);
		var cot2 = val.indexOf('"',cot1+1);
		iframewidth = val.substring(cot1+1,cot2);
		if(iframewidth > 230)
		{
			z = val.replace(iframewidth,230);
			$("widget-text").value = z;
		}

		var ob2 = val.indexOf("width",cot2+1);
		if(ob2)
		{
			var cot3 = val.indexOf('"',ob2+1);
			var cot4 = val.indexOf('px"',cot3+1);
			iframewidth2 = val.substring(cot3+1,cot4);
			if(iframewidth2 > 230)
			{
				z = val.replace(iframewidth2,230);
				$("widget-text").value = z;
			}
			var newVal = $("widget-text").value;
			var srcIndex = newVal.indexOf("src");
			var quoteIndex = newVal.indexOf('"',srcIndex+5);
			var srcURL = newVal.substring(srcIndex+4,quoteIndex+1);
			var srcChageURL = newVal.substring(srcIndex+4,quoteIndex);
			var srcNewURL = srcChageURL+'?wmode=transparent" wmode="transparent"';
			newVal = newVal.replace(srcURL,srcNewURL);
			$('widget-text').value = newVal;
		}
	}
	else if(val.indexOf('<script') == 0) {	

		if(val.indexOf('w=')) {
			var widthIndex = val.indexOf('w=');
			var widthValue = val.substr(widthIndex+2,3);
			widthValue = parseInt(widthValue);
			if(widthValue >= 230) {
				val = val.replace(/[w][=][\d]{3}/g,'w=230');
				$("widget-text").value = val;
			}
		}
		if(val.indexOf('width=')) {
			var widthIndex = val.indexOf('width=');
			var widthValue = val.substr(widthIndex+6,3);
			widthValue = parseInt(widthValue);
			if(widthValue >= 230) {
				val = val.replace(/(width=)[\d]{3}/g,'width=230');
				$("widget-text").value = val;
			}
		}



	}

	return val;
}

function hidewidget()
{
	$('widget-preview').style.display='none';
	$("opacitycoinfirmdiv").style.visibility = 'hidden';
}

function publishwidget()
{
	var val = getCookie("widget");
	setCookie("widget",val,1);
	document.saveWidgetForm.submit();
	// hidewidget();
	// document.getElementById('delete-widget-div').style.display="block";
}

function deletewidget()
{
	showWidgetConfirmation('delete-confirmation');
}

function removeWidget(id)
{
	hidewidgetpopupconfirm('delete-confirmation');
	if(id > 0) {
		sendRequest($('deleteWidgetUrl').value+"&widgetId="+id, deletewidgetHandler);
	}
}

function deletewidgetHandler(resp) {

	window.scrollTo(0,0);
	$("widget-display").innerHTML = '';
	$("widget-display").style.display="none";
	$("widget-div").style.display="block";
	$('delete-widget-div').style.display="none";		
	$("widget-text").value=""; 
}

function showWidgetConfirmation(id)
{
	var Widget = $('widget-display');
	window.scrollTo(400,400);		
	var myPos = new Array();
	myPos = findPos(Widget);
	var fx = myPos[0];
	var fy = myPos[1];
	var ua = navigator.userAgent.toLowerCase();
	var ua_index = ua.indexOf('msie');
	var ua_version = ua.charAt(ua_index+5);
	if(ua.indexOf('msie') != -1 && ua_version < 8)
	{
		window.scroll(400,400);
		if(id=='widget-preview')
		{
			$('widget-preview').style.display='block';
			$('widget-preview').style.top = fy+400+'px';
			$('widget-preview').style.left = fx+280+'px';

		}
		else if(id=="delete-confirmation")
		{
			$('delete-confirmation').style.display='block';
			$('delete-confirmation').style.top = fy+400+'px';
			$('delete-confirmation').style.left = fx+280+'px';
		}
	}
	else
	{
		if(id=='widget-preview')
		{
			$('widget-preview').style.display='block';
			$('widget-preview').style.top = fy+10+'px';
			$('widget-preview').style.left = fx+250+'px';

		}
		else if(id=="delete-confirmation")
		{
			$('delete-confirmation').style.display='block';
			$('delete-confirmation').style.top = fy+10+'px';
			$('delete-confirmation').style.left = fx+250+'px';
		}
	}
	$("opacitycoinfirmdiv").style.visibility = 'visible';	
	var dimensions = getPageSizeWithScroll();
	$("opacitycoinfirmdiv").style.width = dimensions[0];
	$("opacitycoinfirmdiv").style.height = document.getElementById('PageInner').value;
}
function hidewidgetpopupconfirm(id)
{
	$(id).style.display='none';
	$("opacitycoinfirmdiv").style.visibility = 'hidden';
}
//tinyeditor.js
TINY={};
var editorRef;
function T$(i){return document.getElementById(i)}
function T$$$(){return document.all?1:0}

TINY.editor=function(){
	var c=[], offset=-30;
	c['cut']=[1,'Cut','a','cut',1];
	c['copy']=[2,'Copy','a','copy',1];
	c['paste']=[3,'Paste','a','paste',1];
	c['bold']=[4,'Bold','a','bold'];
	c['italic']=[5,'Italic','a','italic'];
	c['underline']=[6,'Underline','a','underline'];
	c['strikethrough']=[7,'Strikethrough','a','strikethrough'];
	c['subscript']=[8,'Subscript','a','subscript'];
	c['superscript']=[9,'Superscript','a','superscript'];
	c['orderedlist']=[10,'Insert Ordered List','a','insertorderedlist'];
	c['unorderedlist']=[11,'Insert Unordered List','a','insertunorderedlist'];
	c['outdent']=[12,'Outdent','a','outdent'];
	c['indent']=[13,'Indent','a','indent'];
	c['leftalign']=[14,'Left Align','a','justifyleft'];
	c['centeralign']=[15,'Center Align','a','justifycenter'];
	c['rightalign']=[16,'Right Align','a','justifyright'];
	c['blockjustify']=[17,'Block Justify','a','justifyfull'];
	c['undo']=[18,'Undo','a','undo'];
	c['redo']=[19,'Redo','a','redo'];
	c['image']=[20,'Insert Image','i','insertimage','Enter Image URL:','http://'];
	c['hr']=[21,'Insert Horizontal Rule','a','inserthorizontalrule'];
	c['link']=[22,'Insert Hyperlink','i','createlink','Enter URL:','http://'];
	c['unlink']=[23,'Remove Hyperlink','a','unlink'];
	c['unformat']=[24,'Remove Formatting','a','removeformat'];
	c['print']=[25,'Print','a','print'];
	c['charmap']=[26,'Character','a','charmap'];
	function edit(n,obj){
		this.n=n; window[n]=this; this.t=T$(obj.id); this.obj=obj; this.xhtml=obj.xhtml;
		var p=document.createElement('div'), w=document.createElement('div'), h=document.createElement('div'),
		l=obj.controls.length, i=0;
		var android = (navigator.appVersion.indexOf("Android") == -1) ? false : true;
		if(!ipad && !iphone && !android){
			this.i=document.createElement('iframe'); this.i.frameBorder=0;this.i.id=obj.bodyid;this.i.id=this.i.id+"_IFR";
			this.i.width=obj.width||'500'; this.i.height=obj.height||'250'; this.ie=T$$$();
			h.className=obj.rowclass||'teheader'; p.className=obj.cssclass||'te'; p.style.width=this.i.width+'px'; p.style.height=this.i.height+'px';this.i.style.height=this.i.height-33+'px';this.i.style.width=this.i.width-4+'px';p.appendChild(h);
		}
		var ua = navigator.userAgent.toLowerCase();
		var ua_index = ua.indexOf('msie');
		var ua_version = ua.charAt(ua_index+5);
		if(ua.indexOf('msie') != -1 && ua_version == 6)
		{
			this.i.style.height=this.i.height+'px';
		}
		else if(ua.indexOf('msie') != -1 && ua_version == 7)
		{
			this.i.style.height=this.i.height-33+'px';
			this.i.style.width=this.i.width-1+'px';
		}
		else if(ua.indexOf('msie') != -1 && ua_version == 8)
		{
			this.i.style.height=this.i.height-33+'px';	
		}
		for(i;i<l;i++){
			var id=obj.controls[i];
			if(id=='n'){
				h=document.createElement('div'); h.className=obj.rowclass||'teheader'; p.appendChild(h)
			}else if(id=='|'){
				var d=document.createElement('div'); d.className=obj.dividerclass||'tedivider'; h.appendChild(d)
			}else if(id=='font'){
				var sel=document.createElement('select'), fonts=obj.fonts||['Verdana','Arial','Georgia'], fl=fonts.length, x=0;
				sel.className='tefont'; sel.onchange=new Function(this.n+'.ddaction(this,"fontname")');
				sel.options[0]=new Option('Font','');
				for(x;x<fl;x++){
					var font=fonts[x];
					sel.options[x+1]=new Option(font,font)
				}
				h.appendChild(sel)
			}else if(id=='size'){
				var sel=document.createElement('select'), sizes=obj.sizes||[1,2,3,4,5,6,7], sl=sizes.length, x=0;
				sel.className='tesize'; sel.onchange=new Function(this.n+'.ddaction(this,"fontsize")');
				for(x;x<sl;x++){
					var size=sizes[x];
					sel.options[x]=new Option(size,size)
				}
				h.appendChild(sel)
			}else if(id=='style'){
				var sel=document.createElement('select'),
				styles=obj.styles||[['Style',''],['Paragraph','<p>'],['Header 1','<h1>'],['Header 2','<h2>'],['Header 3','<h3>'],['Header 4','<h4>'],['Header 5','<h5>'],['Header 6','<h6>']],
				sl=styles.length, x=0;
				sel.className='testyle'; sel.onchange=new Function(this.n+'.ddaction(this,"formatblock")');
				for(x;x<sl;x++){
					var style=styles[x];
					sel.options[x]=new Option(style[0],style[1])
				}
				h.appendChild(sel)
			}else if(c[id]){
				var div=document.createElement('div'), x=c[id], func=x[2], ex, pos=x[0]*offset;
				div.className=obj.controlclass;
				div.style.backgroundPosition='0px '+pos+'px';
				div.title=x[1];
				div.id=x[1];
				ex=func=='a'?'.action("'+x[3]+'",0,this,'+(x[4]||0)+')':'.insert("'+x[4]+'","'+x[5]+'","'+x[3]+'")';
				div.onclick=new Function(this.n+(id=='print'?'.print()':ex));
				if(id=="charmap")
				{
					div.onclick=new Function(this.n+(id=='charmap'?'.charpopup()':ex));
				}
				div.onmouseover=new Function(this.n+'.hover(this,'+pos+',1)');
				div.onmouseout=new Function(this.n+'.hover(this,'+pos+',0)');
				h.appendChild(div);
				if(this.ie){div.unselectable='on'}
			}
		}
		this.t.parentNode.insertBefore(p,this.t);
		if(!ipad && !iphone && !android){
			this.t.style.width=this.i.width+'px';
			w.appendChild(this.t); w.appendChild(this.i);w.style.height=this.i.height+'px'; p.appendChild(w); this.t.style.display='none';
		}
		if(obj.footer){
			var f=document.createElement('div'); f.className=obj.footerclass||'tefooter';
			if(obj.toggle){
				var to=obj.toggle, ts=document.createElement('div');
				ts.className=to.cssclass||'toggle'; ts.innerHTML=obj.toggletext||'source';
				ts.onclick=new Function(this.n+'.toggle(0,this);return false');
				f.appendChild(ts)
			}
			if(obj.resize){
				var ro=obj.resize, rs=document.createElement('div'); rs.className=ro.cssclass||'resize';
				rs.onmousedown=new Function('event',this.n+'.resize(event);return false');
				rs.onselectstart=function(){return false};
				f.appendChild(rs)
			}
			p.appendChild(f)
		}
		if(!ipad && !iphone && !android){
			this.e=this.i.contentWindow.document; this.e.open();
		}
		if($('logUserId').value=="0" || $('logUserId').value==0) { 
			var m='<html><head>', bodyid=obj.bodyid?" id=\""+obj.bodyid+"\"":"";
			if(obj.cssfile){m+='<link rel="stylesheet" href="'+obj.cssfile+'" />'}
			if(obj.css){m+='<style type="text/css">'+obj.css+'</style>'} 
			m+='<script>function fun(){alert("Please login to post comment");}</script></head><body'+bodyid+' onclick="javascript:fun();">'+(obj.content||this.t.value);
			m+='</body></html>';
			this.e.write(m); 
			this.e.close(); this.e.designMode='off'; this.d=1;
		}else{
			var m='<html><head>', bodyid=obj.bodyid?" id=\""+obj.bodyid+"\"":"";
			if(obj.cssfile){m+='<link rel="stylesheet" href="'+obj.cssfile+'" />'}
			if(obj.css){m+='<style type="text/css">'+obj.css+'</style>'}
			m+='</head><body'+bodyid+'>'+(obj.content||this.t.value);
			m+='</body></html>';
			if(!ipad && !iphone && !android){
				this.e.write(m); 
				this.e.close(); this.e.designMode='on'; this.d=1;
			}
		}
		if(this.xhtml){
			try{this.e.execCommand("styleWithCSS",0,0)}
			catch(e){try{this.e.execCommand("useCSS",0,1)}catch(e){}}
		}
	};
	edit.prototype.print=function(){
		this.i.contentWindow.print()
	},
	edit.prototype.charpopup=function(){
		editorRef=this.i.id;
		popupDivEdit.className = "modal";
		popupDivEdit.setAttribute('id','popip_id');
		var popupWidth=popupDivEdit.clientWidth;
		var popupHeight=popupDivEdit.clientHeight;
		var MathCar = document.getElementById(editorRef);
		var myPos = new Array();
		myPos = findPos(MathCar);
		var fx = myPos[0];
		var fy = myPos[1];
		popupDivEdit.style.position="absolute";
		popupDivEdit.style.top=fy-36+'px';
		popupDivEdit.style.left=fx-5+"px";

		popupDivEdit.innerHTML = renderCharTableHTML();
		document.body.appendChild(popupDivEdit); 		
		document.getElementById('charmapView').innerHTML = renderCharMapHTML();
		__overlaycharpopup("popip_id");
	},
	edit.prototype.hover=function(div,pos,dir){
		div.style.backgroundPosition=(dir?'34px ':'0px ')+(pos)+'px'
	},
	edit.prototype.ddaction=function(dd,a){
		var i=dd.selectedIndex, v=dd.options[i].value;
		this.action(a,v)
	},
	edit.prototype.action=function(cmd,val,obj,ie){
		if(ie&&!this.ie){
			alert('Your browser does not support this function.')
		}else{
			/*var style2 = obj.style;
				 style2.backgroundColor = style2.backgroundColor? "":"#cccccc";*/
			if((obj.id =="Insert Unordered List") || (obj.id =="Insert Ordered List"))
			{
				if(obj.id=="Insert Ordered List"){
					T$("Insert Unordered List").style.backgroundColor="";
				}
				else{
					T$("Insert Ordered List").style.backgroundColor="";
				}
			}
			else if((obj.id =="Left Align") || (obj.id =="Center Align") || (obj.id =="Right Align") || (obj.id =="Block Justify"))
			{
				if(obj.id=="Left Align"){
					T$("Center Align").style.backgroundColor="";
					T$("Right Align").style.backgroundColor="";
					T$("Block Justify").style.backgroundColor="";
				}
				else if(obj.id=="Center Align"){
					T$("Left Align").style.backgroundColor="";
					T$("Right Align").style.backgroundColor="";
					T$("Block Justify").style.backgroundColor="";
				}
				else if(obj.id=="Right Align"){
					T$("Left Align").style.backgroundColor="";
					T$("Center Align").style.backgroundColor="";
					T$("Block Justify").style.backgroundColor="";
				}
				else if(obj.id=="Block Justify"){
					T$("Left Align").style.backgroundColor="";
					T$("Center Align").style.backgroundColor="";
					T$("Right Align").style.backgroundColor="";
				}
			}
			else if((obj.id =="Outdent") || (obj.id =="Indent"))
			{
				if(obj.id=="Indent"){
					T$("Outdent").style.backgroundColor="";
					T$("Insert Ordered List").style.backgroundColor="";
					T$("Insert Unordered List").style.backgroundColor="";
				}
				else if(obj.id=="Outdent"){
					T$("Indent").style.backgroundColor="";
					T$("Insert Ordered List").style.backgroundColor="";
					T$("Insert Unordered List").style.backgroundColor="";
				}
			}
			this.e.execCommand(cmd,0,val||null);
		}
	},
	edit.prototype.insert=function(pro,msg,cmd){
		var val=prompt(pro,msg);
		if(val!=null&&val!=''){this.e.execCommand(cmd,0,val)}
	},
	edit.prototype.setfont=function(){
		execCommand('formatblock',0,hType)
	},
	edit.prototype.defaultsetting=function(){
		var teDiv=document.getElementsByClassName('tecontrol');
		for(i=0;i<teDiv.length;i++){
			teDiv[i].style.backgroundColor="";
		}
	},
	edit.prototype.resize=function(e){
		if(this.mv){this.freeze()}
		this.i.bcs=TINY.cursor.top(e);
		this.mv=new Function('event',this.n+'.move(event)');
		this.sr=new Function(this.n+'.freeze()');
		if(this.ie){
			document.attachEvent('onmousemove',this.mv); document.attachEvent('onmouseup',this.sr)
		}else{
			document.addEventListener('mousemove',this.mv,1); document.addEventListener('mouseup',this.sr,1)
		}
	},
	edit.prototype.move=function(e){
		var pos=TINY.cursor.top(e);
		this.i.height=parseInt(this.i.height)+pos-this.i.bcs;
		this.i.bcs=pos
	},
	edit.prototype.freeze=function(){
		if(this.ie){
			document.detachEvent('onmousemove',this.mv); document.detachEvent('onmouseup',this.sr)
		}else{
			document.removeEventListener('mousemove',this.mv,1); document.removeEventListener('mouseup',this.sr,1)
		}
	},
	edit.prototype.toggle=function(post,div){
		if(!this.d){
			var v=this.t.value;
			if(div){div.innerHTML=this.obj.toggletext||'source'}
			if(this.xhtml&&!this.ie){
				v=v.replace(/<strong>(.*)<\/strong>/gi,'<span style="font-weight: bold;">$1</span>');
				v=v.replace(/<em>(.*)<\/em>/gi,'<span style="font-weight: italic;">$1</span>')
			}
			this.e.body.innerHTML=v;
			this.t.style.display='none'; this.i.style.display='block'; this.d=1
		}else{
			var v=this.e.body.innerHTML;
			if(this.xhtml){
				v=v.replace(/<span class="apple-style-span">(.*)<\/span>/gi,'$1');
				v=v.replace(/ class="apple-style-span"/gi,'');
				v=v.replace(/<span style="">/gi,'');
				v=v.replace(/<br>/gi,'<br />');
				v=v.replace(/<br ?\/?>$/gi,'');
				v=v.replace(/^<br ?\/?>/gi,'');
				v=v.replace(/(<img [^>]+[^\/])>/gi,'$1 />');
				v=v.replace(/<b\b[^>]*>(.*?)<\/b[^>]*>/gi,'<strong>$1</strong>');
				v=v.replace(/<i\b[^>]*>(.*?)<\/i[^>]*>/gi,'<em>$1</em>');
				v=v.replace(/<u\b[^>]*>(.*?)<\/u[^>]*>/gi,'<span style="text-decoration:underline">$1</span>');
				v=v.replace(/<(b|strong|em|i|u) style="font-weight: normal;?">(.*)<\/(b|strong|em|i|u)>/gi,'$2');
				v=v.replace(/<(b|strong|em|i|u) style="(.*)">(.*)<\/(b|strong|em|i|u)>/gi,'<span style="$2"><$4>$3</$4></span>');
				v=v.replace(/<span style="font-weight: normal;?">(.*)<\/span>/gi,'$1');
				v=v.replace(/<span style="font-weight: bold;?">(.*)<\/span>/gi,'<strong>$1</strong>');
				v=v.replace(/<span style="font-style: italic;?">(.*)<\/span>/gi,'<em>$1</em>');
				v=v.replace(/<span style="font-weight: bold;?">(.*)<\/span>|<b\b[^>]*>(.*?)<\/b[^>]*>/gi,'<strong>$1</strong>')
			}
			if(div){div.innerHTML=this.obj.toggletext||'wysiwyg'}
			this.t.value=v;
			if(!post){
				this.t.style.height=this.i.height+'px';
				this.i.style.display='none'; this.t.style.display='block'; this.d=0
			}
		}
	},
	edit.prototype.post=function(){
		if(this.d){this.toggle(1)}
	};
	return{edit:edit}
}();

TINY.cursor=function(){
	return{
		top:function(e){
		return T$$$()?window.event.clientY+document.documentElement.scrollTop+document.body.scrollTop:e.clientY+window.scrollY
	}
	}
}();
function renderCharTableHTML()
{
	var Shtml='';
	Shtml+='<table align="center" border="0" cellspacing="0" cellpadding="2">';		
	Shtml+='<tr>';
	Shtml+='<td style="text-align:right;padding-bottom:3px;" colspan="2">';
	Shtml+='<a href="javascript:hidecharpopup();" style="font-size:14px;font-family:Arial;font-weight:bold; color: #000000 !important;text-decoration: none;" title="Close">x</a>';
	Shtml+='</td>';
	Shtml+='</tr>';
	Shtml+='<tr>';
	Shtml+='<td id="charmapView" rowspan="2" align="left">';
	Shtml+='</td>';
	Shtml+='<td width="100" align="center" valign="top">';
	Shtml+='<table border="0" cellpadding="0" cellspacing="0" width="100" style="height:100px;padding-left:3px !important;">';
	Shtml+='<tr>';
	Shtml+='<td id="codeV">';
	Shtml+='&nbsp;';
	Shtml+='</td>';	
	Shtml+='</tr>';
	Shtml+='<tr>';
	Shtml+='<td id="codeN">';
	Shtml+='&nbsp;';
	Shtml+='</td>';
	Shtml+='</tr>';
	Shtml+='</table';
	Shtml+='</td>';
	Shtml+='</tr>';
	Shtml+='<tr>';
	Shtml+='<td valign="bottom" style="padding-bottom: 3px;padding-left:3px !important;">';
	Shtml+='<table width="100" align="center" border="0" cellpadding="2" cellspacing="0">';
	Shtml+='<tr>';
	Shtml+='<td align="center" style="border-left: 1px solid #666699; border-top: 1px solid #666699; border-right: 1px solid #666699;font-size:10px;font-family:Verdana,Arial,Helvetica,sans-serif;">';
	Shtml+='HTML-Code';
	Shtml+='</td>';
	Shtml+='</tr>';
	Shtml+='<tr>';
	Shtml+='<td style="font-size: 16px; font-weight: bold; border-left: 1px solid #666699; border-bottom: 1px solid #666699; border-right: 1px solid #666699;font-family:Verdana,Arial,Helvetica,sans-serif;" id="codeA" align="center">';
	Shtml+='&nbsp;';
	Shtml+='</td>';
	Shtml+='</tr>';
	Shtml+='<tr>';
	Shtml+='<td style="font-size: 1px;">';
	Shtml+='&nbsp;';
	Shtml+='</td>';
	Shtml+='</tr>';
	Shtml+='<tr>';
	Shtml+='<td align="center" style="border-left: 1px solid #666699; border-top: 1px solid #666699; border-right: 1px solid #666699;font-size:10px;font-family:Verdana,Arial,Helvetica,sans-serif;">';
	Shtml+='NUM-Code';
	Shtml+='</td>';
	Shtml+='</tr>';
	Shtml+='<tr>';
	Shtml+='<td style="font-size: 16px; font-weight: bold; border-left: 1px solid #666699; border-bottom: 1px solid #666699; border-right: 1px solid #666699;font-family:Verdana,Arial,Helvetica,sans-serif;" id="codeB" align="center">';
	Shtml+='&nbsp;';
	Shtml+='</td>';
	Shtml+='</tr>';
	Shtml+='</table>';
	Shtml+='</td>';
	Shtml+='</tr>';
	Shtml+='</table>';	
	return Shtml;
}

function showloader()
{
	//window.scrollTo(0,0);
	var dimensions = getPageSizeWithScroll();
	var Outer = document.getElementById('view');
	var myPos = new Array();
	myPos = findPos(Outer);
	var fx = myPos[0];
	var fy = myPos[1];
	var Val = parseInt(document.getElementById('PageInner').value);
	//$("opacitycoinfirmdiv").style.height = Val+40;	
	__overlayloader("loader");	
	if(divs_transparentDiv.style.display=="block")
	{
		divs_transparentDiv.style.display="none";
	}
	//BUG:5768 is fixed  as transperant div is blocking here
	 if($('ask-question-popup')){
		if($('ask-question-popup').style.display=="block"){
			divs_transparentDiv.style.display="block";
		}
	}
	//document.getElementById('loader').style.display = 'block'; 
	//document.getElementById('loader').style.top = fy+135+'px';
	//document.getElementById('loader').style.left = fx+428+'px';
}
function hideloader()
{
	divs_opacityDiv.style.display="none";
	//document.getElementById('loader').style.display = 'none'; 
}
function disableActiveSummery()
{

	if(document.getElementById('nonenotify').checked == true)
	{
		$('dailynotify').checked = true;
	}

	if(document.getElementById('nonenotify').checked == false)
	{
		$('dailynotify').disabled = true;
		$('weeklynotify').disabled = true;
		$('weekday').disabled = true;
	}
	else
	{
		$('dailynotify').disabled = false;
		$('weeklynotify').disabled = false;
		if(document.getElementById('weeklynotify').checked == true)
		{$('weekday').disabled = false;}
	}
}

//charmap.js
var charmap = [
               ['&nbsp;',    '&#160;',  true, 'no-break space'],
               ['&amp;',     '&#38;',   true, 'ampersand'],
               ['&quot;',    '&#34;',   true, 'quotation mark'],
               // finance
               ['&cent;',    '&#162;',  true, 'cent sign'],
               ['&euro;',    '&#8364;', true, 'euro sign'],
               ['&pound;',   '&#163;',  true, 'pound sign'],
               ['&yen;',     '&#165;',  true, 'yen sign'],
               // signs
               ['&copy;',    '&#169;',  true, 'copyright sign'],
               ['&reg;',     '&#174;',  true, 'registered sign'],
               ['&trade;',   '&#8482;', true, 'trade mark sign'],
               ['&permil;',  '&#8240;', true, 'per mille sign'],
               ['&micro;',   '&#181;',  true, 'micro sign'],
               ['&middot;',  '&#183;',  true, 'middle dot'],
               ['&bull;',    '&#8226;', true, 'bullet'],
               ['&hellip;',  '&#8230;', true, 'three dot leader'],
               ['&prime;',   '&#8242;', true, 'minutes / feet'],
               ['&Prime;',   '&#8243;', true, 'seconds / inches'],
               ['&sect;',    '&#167;',  true, 'section sign'],
               ['&para;',    '&#182;',  true, 'paragraph sign'],
               ['&szlig;',   '&#223;',  true, 'sharp s / ess-zed'],
               // quotations
               ['&lsaquo;',  '&#8249;', true, 'single left-pointing angle quotation mark'],
               ['&rsaquo;',  '&#8250;', true, 'single right-pointing angle quotation mark'],
               ['&laquo;',   '&#171;',  true, 'left pointing guillemet'],
               ['&raquo;',   '&#187;',  true, 'right pointing guillemet'],
               ['&lsquo;',   '&#8216;', true, 'left single quotation mark'],
               ['&rsquo;',   '&#8217;', true, 'right single quotation mark'],
               ['&ldquo;',   '&#8220;', true, 'left double quotation mark'],
               ['&rdquo;',   '&#8221;', true, 'right double quotation mark'],
               ['&sbquo;',   '&#8218;', true, 'single low-9 quotation mark'],
               ['&bdquo;',   '&#8222;', true, 'double low-9 quotation mark'],
               ['&lt;',      '&#60;',   true, 'less-than sign'],
               ['&gt;',      '&#62;',   true, 'greater-than sign'],
               ['&le;',      '&#8804;', true, 'less-than or equal to'],
               ['&ge;',      '&#8805;', true, 'greater-than or equal to'],
               ['&ndash;',   '&#8211;', true, 'en dash'],
               ['&mdash;',   '&#8212;', true, 'em dash'],
               ['&macr;',    '&#175;',  true, 'macron'],
               ['&oline;',   '&#8254;', true, 'overline'],
               ['&curren;',  '&#164;',  true, 'currency sign'],
               ['&brvbar;',  '&#166;',  true, 'broken bar'],
               ['&uml;',     '&#168;',  true, 'diaeresis'],
               ['&iexcl;',   '&#161;',  true, 'inverted exclamation mark'],
               ['&iquest;',  '&#191;',  true, 'turned question mark'],
               ['&circ;',    '&#710;',  true, 'circumflex accent'],
               ['&tilde;',   '&#732;',  true, 'small tilde'],
               ['&deg;',     '&#176;',  true, 'degree sign'],
               ['&minus;',   '&#8722;', true, 'minus sign'],
               ['&plusmn;',  '&#177;',  true, 'plus-minus sign'],
               ['&divide;',  '&#247;',  true, 'division sign'],
               ['&frasl;',   '&#8260;', true, 'fraction slash'],
               ['&times;',   '&#215;',  true, 'multiplication sign'],
               ['&sup1;',    '&#185;',  true, 'superscript one'],
               ['&sup2;',    '&#178;',  true, 'superscript two'],
               ['&sup3;',    '&#179;',  true, 'superscript three'],
               ['&frac14;',  '&#188;',  true, 'fraction one quarter'],
               ['&frac12;',  '&#189;',  true, 'fraction one half'],
               ['&frac34;',  '&#190;',  true, 'fraction three quarters'],
               // math / logical
               ['&fnof;',    '&#402;',  true, 'function / florin'],
               ['&int;',     '&#8747;', true, 'integral'],
               ['&sum;',     '&#8721;', true, 'n-ary sumation'],
               ['&infin;',   '&#8734;', true, 'infinity'],
               ['&radic;',   '&#8730;', true, 'square root'],
               ['&sim;',     '&#8764;', false,'similar to'],
               ['&cong;',    '&#8773;', false,'approximately equal to'],
               ['&asymp;',   '&#8776;', true, 'almost equal to'],
               ['&ne;',      '&#8800;', true, 'not equal to'],
               ['&equiv;',   '&#8801;', true, 'identical to'],
               ['&isin;',    '&#8712;', false,'element of'],
               ['&notin;',   '&#8713;', false,'not an element of'],
               ['&ni;',      '&#8715;', false,'contains as member'],
               ['&prod;',    '&#8719;', true, 'n-ary product'],
               ['&and;',     '&#8743;', false,'logical and'],
               ['&or;',      '&#8744;', false,'logical or'],
               ['&not;',     '&#172;',  true, 'not sign'],
               ['&cap;',     '&#8745;', true, 'intersection'],
               ['&cup;',     '&#8746;', false,'union'],
               ['&part;',    '&#8706;', true, 'partial differential'],
               ['&forall;',  '&#8704;', false,'for all'],
               ['&exist;',   '&#8707;', false,'there exists'],
               ['&empty;',   '&#8709;', false,'diameter'],
               ['&nabla;',   '&#8711;', false,'backward difference'],
               ['&lowast;',  '&#8727;', false,'asterisk operator'],
               ['&prop;',    '&#8733;', false,'proportional to'],
               ['&ang;',     '&#8736;', false,'angle'],
               // undefined
               ['&acute;',   '&#180;',  true, 'acute accent'],
               ['&cedil;',   '&#184;',  true, 'cedilla'],
               ['&ordf;',    '&#170;',  true, 'feminine ordinal indicator'],
               ['&ordm;',    '&#186;',  true, 'masculine ordinal indicator'],
               ['&dagger;',  '&#8224;', true, 'dagger'],
               ['&Dagger;',  '&#8225;', true, 'double dagger'],
               // alphabetical special chars
               ['&Agrave;',  '&#192;',  true, 'A - grave'],
               ['&Aacute;',  '&#193;',  true, 'A - acute'],
               ['&Acirc;',   '&#194;',  true, 'A - circumflex'],
               ['&Atilde;',  '&#195;',  true, 'A - tilde'],
               ['&Auml;',    '&#196;',  true, 'A - diaeresis'],
               ['&Aring;',   '&#197;',  true, 'A - ring above'],
               ['&AElig;',   '&#198;',  true, 'ligature AE'],
               ['&Ccedil;',  '&#199;',  true, 'C - cedilla'],
               ['&Egrave;',  '&#200;',  true, 'E - grave'],
               ['&Eacute;',  '&#201;',  true, 'E - acute'],
               ['&Ecirc;',   '&#202;',  true, 'E - circumflex'],
               ['&Euml;',    '&#203;',  true, 'E - diaeresis'],
               ['&Igrave;',  '&#204;',  true, 'I - grave'],
               ['&Iacute;',  '&#205;',  true, 'I - acute'],
               ['&Icirc;',   '&#206;',  true, 'I - circumflex'],
               ['&Iuml;',    '&#207;',  true, 'I - diaeresis'],
               ['&ETH;',     '&#208;',  true, 'ETH'],
               ['&Ntilde;',  '&#209;',  true, 'N - tilde'],
               ['&Ograve;',  '&#210;',  true, 'O - grave'],
               ['&Oacute;',  '&#211;',  true, 'O - acute'],
               ['&Ocirc;',   '&#212;',  true, 'O - circumflex'],
               ['&Otilde;',  '&#213;',  true, 'O - tilde'],
               ['&Ouml;',    '&#214;',  true, 'O - diaeresis'],
               ['&Oslash;',  '&#216;',  true, 'O - slash'],
               ['&OElig;',   '&#338;',  true, 'ligature OE'],
               ['&Scaron;',  '&#352;',  true, 'S - caron'],
               ['&Ugrave;',  '&#217;',  true, 'U - grave'],
               ['&Uacute;',  '&#218;',  true, 'U - acute'],
               ['&Ucirc;',   '&#219;',  true, 'U - circumflex'],
               ['&Uuml;',    '&#220;',  true, 'U - diaeresis'],
               ['&Yacute;',  '&#221;',  true, 'Y - acute'],
               ['&Yuml;',    '&#376;',  true, 'Y - diaeresis'],
               ['&THORN;',   '&#222;',  true, 'THORN'],
               ['&agrave;',  '&#224;',  true, 'a - grave'],
               ['&aacute;',  '&#225;',  true, 'a - acute'],
               ['&acirc;',   '&#226;',  true, 'a - circumflex'],
               ['&atilde;',  '&#227;',  true, 'a - tilde'],
               ['&auml;',    '&#228;',  true, 'a - diaeresis'],
               ['&aring;',   '&#229;',  true, 'a - ring above'],
               ['&aelig;',   '&#230;',  true, 'ligature ae'],
               ['&ccedil;',  '&#231;',  true, 'c - cedilla'],
               ['&egrave;',  '&#232;',  true, 'e - grave'],
               ['&eacute;',  '&#233;',  true, 'e - acute'],
               ['&ecirc;',   '&#234;',  true, 'e - circumflex'],
               ['&euml;',    '&#235;',  true, 'e - diaeresis'],
               ['&igrave;',  '&#236;',  true, 'i - grave'],
               ['&iacute;',  '&#237;',  true, 'i - acute'],
               ['&icirc;',   '&#238;',  true, 'i - circumflex'],
               ['&iuml;',    '&#239;',  true, 'i - diaeresis'],
               ['&eth;',     '&#240;',  true, 'eth'],
               ['&ntilde;',  '&#241;',  true, 'n - tilde'],
               ['&ograve;',  '&#242;',  true, 'o - grave'],
               ['&oacute;',  '&#243;',  true, 'o - acute'],
               ['&ocirc;',   '&#244;',  true, 'o - circumflex'],
               ['&otilde;',  '&#245;',  true, 'o - tilde'],
               ['&ouml;',    '&#246;',  true, 'o - diaeresis'],
               ['&oslash;',  '&#248;',  true, 'o slash'],
               ['&oelig;',   '&#339;',  true, 'ligature oe'],
               ['&scaron;',  '&#353;',  true, 's - caron'],
               ['&ugrave;',  '&#249;',  true, 'u - grave'],
               ['&uacute;',  '&#250;',  true, 'u - acute'],
               ['&ucirc;',   '&#251;',  true, 'u - circumflex'],
               ['&uuml;',    '&#252;',  true, 'u - diaeresis'],
               ['&yacute;',  '&#253;',  true, 'y - acute'],
               ['&thorn;',   '&#254;',  true, 'thorn'],
               ['&yuml;',    '&#255;',  true, 'y - diaeresis'],
               ['&Alpha;',   '&#913;',  true, 'Alpha'],
               ['&Beta;',    '&#914;',  true, 'Beta'],
               ['&Gamma;',   '&#915;',  true, 'Gamma'],
               ['&Delta;',   '&#916;',  true, 'Delta'],
               ['&Epsilon;', '&#917;',  true, 'Epsilon'],
               ['&Zeta;',    '&#918;',  true, 'Zeta'],
               ['&Eta;',     '&#919;',  true, 'Eta'],
               ['&Theta;',   '&#920;',  true, 'Theta'],
               ['&Iota;',    '&#921;',  true, 'Iota'],
               ['&Kappa;',   '&#922;',  true, 'Kappa'],
               ['&Lambda;',  '&#923;',  true, 'Lambda'],
               ['&Mu;',      '&#924;',  true, 'Mu'],
               ['&Nu;',      '&#925;',  true, 'Nu'],
               ['&Xi;',      '&#926;',  true, 'Xi'],
               ['&Omicron;', '&#927;',  true, 'Omicron'],
               ['&Pi;',      '&#928;',  true, 'Pi'],
               ['&Rho;',     '&#929;',  true, 'Rho'],
               ['&Sigma;',   '&#931;',  true, 'Sigma'],
               ['&Tau;',     '&#932;',  true, 'Tau'],
               ['&Upsilon;', '&#933;',  true, 'Upsilon'],
               ['&Phi;',     '&#934;',  true, 'Phi'],
               ['&Chi;',     '&#935;',  true, 'Chi'],
               ['&Psi;',     '&#936;',  true, 'Psi'],
               ['&Omega;',   '&#937;',  true, 'Omega'],
               ['&alpha;',   '&#945;',  true, 'alpha'],
               ['&beta;',    '&#946;',  true, 'beta'],
               ['&gamma;',   '&#947;',  true, 'gamma'],
               ['&delta;',   '&#948;',  true, 'delta'],
               ['&epsilon;', '&#949;',  true, 'epsilon'],
               ['&zeta;',    '&#950;',  true, 'zeta'],
               ['&eta;',     '&#951;',  true, 'eta'],
               ['&theta;',   '&#952;',  true, 'theta'],
               ['&iota;',    '&#953;',  true, 'iota'],
               ['&kappa;',   '&#954;',  true, 'kappa'],
               ['&lambda;',  '&#955;',  true, 'lambda'],
               ['&mu;',      '&#956;',  true, 'mu'],
               ['&nu;',      '&#957;',  true, 'nu'],
               ['&xi;',      '&#958;',  true, 'xi'],
               ['&omicron;', '&#959;',  true, 'omicron'],
               ['&pi;',      '&#960;',  true, 'pi'],
               ['&rho;',     '&#961;',  true, 'rho'],
               ['&sigmaf;',  '&#962;',  true, 'final sigma'],
               ['&sigma;',   '&#963;',  true, 'sigma'],
               ['&tau;',     '&#964;',  true, 'tau'],
               ['&upsilon;', '&#965;',  true, 'upsilon'],
               ['&phi;',     '&#966;',  true, 'phi'],
               ['&chi;',     '&#967;',  true, 'chi'],
               ['&psi;',     '&#968;',  true, 'psi'],
               ['&omega;',   '&#969;',  true, 'omega'],
               // symbols
               ['&alefsym;', '&#8501;', false,'alef symbol'],
               ['&piv;',     '&#982;',  false,'pi symbol'],
               ['&real;',    '&#8476;', false,'real part symbol'],
               ['&thetasym;','&#977;',  false,'theta symbol'],
               ['&upsih;',   '&#978;',  false,'upsilon - hook symbol'],
               ['&weierp;',  '&#8472;', false,'Weierstrass p'],
               ['&image;',   '&#8465;', false,'imaginary part'],
               // arrows
               ['&larr;',    '&#8592;', true, 'leftwards arrow'],
               ['&uarr;',    '&#8593;', true, 'upwards arrow'],
               ['&rarr;',    '&#8594;', true, 'rightwards arrow'],
               ['&darr;',    '&#8595;', true, 'downwards arrow'],
               ['&harr;',    '&#8596;', true, 'left right arrow'],
               ['&crarr;',   '&#8629;', false,'carriage return'],
               ['&lArr;',    '&#8656;', false,'leftwards double arrow'],
               ['&uArr;',    '&#8657;', false,'upwards double arrow'],
               ['&rArr;',    '&#8658;', false,'rightwards double arrow'],
               ['&dArr;',    '&#8659;', false,'downwards double arrow'],
               ['&hArr;',    '&#8660;', false,'left right double arrow'],
               ['&there4;',  '&#8756;', false,'therefore'],
               ['&sub;',     '&#8834;', false,'subset of'],
               ['&sup;',     '&#8835;', false,'superset of'],
               ['&nsub;',    '&#8836;', false,'not a subset of'],
               ['&sube;',    '&#8838;', false,'subset of or equal to'],
               ['&supe;',    '&#8839;', false,'superset of or equal to'],
               ['&oplus;',   '&#8853;', false,'circled plus'],
               ['&otimes;',  '&#8855;', false,'circled times'],
               ['&perp;',    '&#8869;', false,'perpendicular'],
               ['&sdot;',    '&#8901;', false,'dot operator'],
               ['&lceil;',   '&#8968;', false,'left ceiling'],
               ['&rceil;',   '&#8969;', false,'right ceiling'],
               ['&lfloor;',  '&#8970;', false,'left floor'],
               ['&rfloor;',  '&#8971;', false,'right floor'],
               ['&lang;',    '&#9001;', false,'left-pointing angle bracket'],
               ['&rang;',    '&#9002;', false,'right-pointing angle bracket'],
               ['&loz;',     '&#9674;', true,'lozenge'],
               ['&spades;',  '&#9824;', false,'black spade suit'],
               ['&clubs;',   '&#9827;', true, 'black club suit'],
               ['&hearts;',  '&#9829;', true, 'black heart suit'],
               ['&diams;',   '&#9830;', true, 'black diamond suit'],
               ['&ensp;',    '&#8194;', false,'en space'],
               ['&emsp;',    '&#8195;', false,'em space'],
               ['&thinsp;',  '&#8201;', false,'thin space'],
               ['&zwnj;',    '&#8204;', false,'zero width non-joiner'],
               ['&zwj;',     '&#8205;', false,'zero width joiner'],
               ['&lrm;',     '&#8206;', false,'left-to-right mark'],
               ['&rlm;',     '&#8207;', false,'right-to-left mark'],
               ['&shy;',     '&#173;',  false,'soft hyphen']
                ];
/*

tinyMCEPopup.onInit.add(function() {
	tinyMCEPopup.dom.setHTML('charmapView', renderCharMapHTML());
});*/

function renderCharMapHTML() {
	var charsPerRow = 20, tdWidth=20, tdHeight=20, i;
	var html = '<table border="0" cellspacing="1" cellpadding="0" width="' + (tdWidth*charsPerRow) + '"><tr height="' + tdHeight + '">';
	var cols=-1;

	for (i=0; i<charmap.length; i++) {
		if (charmap[i][2]==true) {
			cols++;
			html += ''
				+ '<td class="charmap">'
				+ '<a href="javascript:void(0)" onmouseover="previewChar(\'' + charmap[i][1].substring(1,charmap[i][1].length) + '\',\'' + charmap[i][0].substring(1,charmap[i][0].length) + '\',\'' + charmap[i][3] + '\');" onclick="insertChar(\'' + charmap[i][1].substring(2,charmap[i][1].length-1) + '\');" onmousedown="return false;" title="' + charmap[i][3] + '">'
				+ charmap[i][1]
				             + '</a></td>';
			if ((cols+1) % charsPerRow == 0)
				html += '</tr><tr height="' + tdHeight + '">';
		}
	}

	if (cols % charsPerRow > 0) {
		var padd = charsPerRow - (cols % charsPerRow);
		for (var i=0; i<padd-1; i++)
			html += '<td width="' + tdWidth + '" height="' + tdHeight + '" class="charmap">&nbsp;</td>';
	}

	html += '</tr></table>';

	return html;
}
function hidecharpopup()
{
	document.body.removeChild(popupDivEdit);
	document.body.removeChild(divs_transparentcharDiv);
}
function insertChar(chr) {
	hidecharpopup();
	var ua = navigator.userAgent.toLowerCase();
	if(ua.indexOf('msie') != -1)
	{
		var strValue = '&#' + chr + ';';
		document.getElementById(editorRef).contentWindow.focus();
		var curRange = document.getElementById(editorRef).contentWindow.document.selection.createRange();
		curRange.cutHTML;
		curRange.pasteHTML(strValue);
	}
	else
	{
		document.getElementById(editorRef).contentWindow.document.execCommand('insertHTML',false,'&#' + chr + ';');
		document.getElementById(editorRef).contentWindow.focus();
	}

}

function previewChar(codeA, codeB, codeN) {
	var elmA = document.getElementById('codeA');
	var elmB = document.getElementById('codeB');
	var elmV = document.getElementById('codeV');
	var elmN = document.getElementById('codeN');
	elmN.innerHTML = codeN;
	if (codeA=='#160;') {
		elmV.innerHTML = '__';
	} else {
		elmV.innerHTML = '&' + codeA;
	}

	elmB.innerHTML = '&amp;' + codeA;
	elmA.innerHTML = '&amp;' + codeB;
	elmN.innerHTML = codeN;
}

//groups.js start 
//JavaScript Document
function displayGroupPage(startNo, e, pageNo,noOfPages,url,divId){
	/*Author: Avinash
	* Fix: added validation to check alphabet in pagination
	* Bug: DS-5548
	*/
	var pattern = /[A-Za-z]/i;
	var checkalphabet =  pattern.test(pageNo);
	var keycode;
	if (window.event) keycode = window.event.keyCode;
	else if (e) keycode = e.which;

	if(keycode == 13){

		if(pageNo<1 || pageNo>noOfPages || checkalphabet){

			$("errmsg").innerHTML = "Page No should be between 1 and "+noOfPages;
			$("errmsg").show();
		}else{
			changeGroupPageControl(startNo, pageNo, url,divId)
		}
	}

}

function changeGroupPageControl(startNo, pageNo, url,divId) {	 
	selectedGroupUserStates = new Array();
	url =url+"&process=list&groupstartNo="+startNo+"&grouppageNo="+pageNo;

	if(divId=='pagecontent'){
		//loadDivContent(divId,url);
		window.location.href = url;
	}
}
function deleteGroupDetails(url){
	document.groupsListForm.action +=url;
	document.groupsListForm.submit(); 
}
function groupDeleteStatusResp(resp) {
}

//Start of Manage Members Functions
function showmenu()
{
	if(document.getElementById('flight-menu').className=="flight-menu")
	{
		var Flightmenu = document.getElementById('flight-menu');
		var myPos = new Array();
		myPos = findPos(Flightmenu);
		var fx = myPos[0];
		var fy = myPos[1];
		document.getElementById('period-menu').style.top = fy+30+'px';
		document.getElementById('period-menu').style.left = fx-96+'px';
		document.getElementById('period-menu').style.display="block";
		document.getElementById('flight-menu').className="flight-menu-current";
		document.getElementById('arrow-id').src=getContext() + "/site/common/images/common-images/downarrow_black.gif";
	}
	else
	{
		document.getElementById('period-menu').style.display="none";
		document.getElementById('flight-menu').className="flight-menu";
		document.getElementById('arrow-id').src=getContext() + "/site/common/images/common-images/white_down_arrow.gif";
	}
}

function showmenuitem(ele)
{
	var pathToImages = '/collaborize/site/common/images/common-images/';
	if($('period-menu'))
	{
		$('period-menu').style.display="none";
	}
	var Flightmenu = $('create-flight-menu');
	var myPos = new Array();
	myPos = findPos(ele);
	var fx = myPos[0];
	var fy = myPos[1];
	if($('create-period-menu').style.display=='block')	
	{
		$('create-period-menu').style.display='none';
		$('downarrow-black').style.display='none';
		$('white-down-arrow').style.display='inline';
		Flightmenu.className = "flight-menu";
		$('new-gp-image').src=pathToImages+"newGroupIcon.png";
	}
	else
	{
		$('create-period-menu').style.display='block';
		$('downarrow-black').style.display='inline';
		$('white-down-arrow').style.display='none';
		$('new-gp-image').src=pathToImages+"group_blue.png";
		Flightmenu.className = "flight-menu-current";
		var groupPopupWidth = $('group-details').style.width;
		var ua = navigator.userAgent.toLowerCase();
		var ua_index = ua.indexOf('msie');
		var ua_version = ua.charAt(ua_index+5);
		if(ua.indexOf('msie') != -1 && ua_version == 7)
		{
			$('create-period-menu').style.top = fy+292+'px';
			$('create-period-menu').style.left =((bodyWidth-groupPopupWidth)/2)+178+'px';
		}
		else
		{
			$('create-period-menu').style.top = fy+270+'px';
			$('create-period-menu').style.left = fx+583+'px';
		}
	}
}

//End of Manage Members Script
var selectedGroupUsers = new Array();
var selectedGroupUserStates = new Array();

var deletedGroupUsers = new Array();
var deletedGroupUserStates = new Array();

var isFromListPage = true;
function showCreateGroup(url,isListPage){
	if($('editgroup-popup')){
		$('editgroup-popup').innerHTML="";
	}
	isFromListPage = isListPage;
	removeErrorMessage('alertMsgDivInList');
	selectedGroupUsers = new Array();
	selectedGroupUserStates = new Array();

	deletedGroupUsers = new Array();
	deletedGroupUserStates = new Array();



	loadDivContent('group-details',url,createGroupResponce);
}
function createGroupResponce(resp) {
	showpopupwindow("group-details");	
}
function hideGroupPopup() {
	hidepopup("group-details");
	$('group-details').innerHTML = "";
}
function getGroupUsers(startNo, pageNo, url,divId) {	 
	removeErrorMessage('alertMsgDiv');
	url =url+"&startNo="+startNo+"&pageNo="+pageNo+"&status="+$('uStatus').value;
	if($('tabview').value=="select"){
		$('selectprocess').value="list";
		submitActionOnSelectTab(divId,url,startNo,pageNo,$('uStatus').value,false);
	}else if($('tabview').value=="current"){

		var ids ="";
		for(var i=0;i<deletedGroupUsers.length;i++){
			ids= ids+","+deletedGroupUsers[i];
		}
		if(ids.length>0){
			ids=ids.substring(1,ids.length);
		}
		var states ="";
		for(var i=0;i<deletedGroupUserStates.length;i++){
			states= states+","+deletedGroupUserStates[i];
		}
		if(states.length>0){
			states=states.substring(1,states.length);
		}
		url=url+"&process=list&tabview=current&deletedIds="+ids+"&deletedIdStates="+states;
		//alert(url);
		loadDivContent(divId,url,getGroupCurrentUsersRes);	 
	}else{
		var str = "";
		if($('searchGroupUser')) {
			str = $('searchGroupUser').value;
		}
		//if(str != "" && str!="Enter screen name, email, first name or last name" && str!=null){
			if($('searchGroupUserValue')) {
				$('searchGroupUserValue').value = str;
			}
			$('isFromSearch').value="true";
			url=url+"&searchGroupUserValue="+str;
			//}
			loadDivContent(divId,url,getGroupUsersRes);	 
		}
	}
	function getGroupCurrentUsersRes(resp){
	}
	function submitActionOnSelectTab(divId,url,startNo,pageNo,status,isRemove){	 
		removeErrorMessage('alertMsgDiv');
		$('isSelectTab').value="true";
		var ids ="";
		for(var i=0;i<selectedGroupUsers.length;i++){
			ids= ids+","+selectedGroupUsers[i];
		}
		if(ids.length>0){
			ids=ids.substring(1,ids.length);
		}
		$('selectedTabIds').value=ids;
		var states ="";
		for(var i=0;i<selectedGroupUserStates.length;i++){
			states= states+","+selectedGroupUserStates[i];
		}
		if(states.length>0){
			states=states.substring(1,states.length);
		}
		$('selectedIdStates').value=states; 
		$('selectpageNo').value=pageNo;
		$('selectstartNo').value=startNo;
		$('selectstatus').value=status;
		if(isRemove){
			submitForm(divId, document.groupMainTabChangeForm,function(){removeGroupUsersRes(status)});
		}else{
			submitForm(divId, document.groupMainTabChangeForm,getGroupUsersRes);
		} 
		tabSelection(status);
	}
	function submitActionOnCurrentTab(divId,url,startNo,pageNo,status,isRemove){	 
		removeErrorMessage('alertMsgDiv');
		$('isSelectTab').value="false";  

		var ids ="";
		for(var i=0;i<deletedGroupUsers.length;i++){
			ids= ids+","+deletedGroupUsers[i];
		}
		if(ids.length>0){
			ids=ids.substring(1,ids.length);
		}
		$('deletedIds').value=ids;
		var states ="";
		for(var i=0;i<deletedGroupUserStates.length;i++){
			states= states+","+deletedGroupUserStates[i];
		}
		if(states.length>0){
			states=states.substring(1,states.length);
		}
		$('deletedIdStates').value=states;

		$('selectpageNo').value=pageNo;
		$('selectstartNo').value=startNo;
		$('selectstatus').value=status;
		submitForm(divId, document.groupMainTabChangeForm,getGroupUsersRes); 
		tabSelection(status);
	}
	function removeGroupUsersRes(status){ 

		/*if($('actUsrCnt')){
		$('actUsrCnt').innerHTML = "("+$('usersCountcnt').value+")";
	}
	if($('qudUsrCnt')){
		$('qudUsrCnt').innerHTML = "("+$('approvalscnt').value+")";
	}
	if($('acvUsrCnt')){
		$('acvUsrCnt').innerHTML = "("+$('activationscnt').value+")";
	}
	if($('bckUsrCnt')){
		$('bckUsrCnt').innerHTML = "("+$('blockedcnt').value+")";
	}*/
		tabRemoveSelection(status,$('usersCountcnt').value,$('approvalscnt').value,$('activationscnt').value,$('blockedcnt').value);
	}
	function tabRemoveSelection(status,acnt,qcnt,pcnt,bcnt)
	{
		if(status=="ACTIVE")
		{
			$('groupactive-tab').className="current";
			if($('actUsrCnt')){
				$('actUsrCnt').innerHTML = "("+$('usersCountcnt').value+")";
			}
			if (acnt == 0 && qcnt > 0)
			{
				if($('groupqueued-tab'))
				{
					$('groupqueued-tab').className="current";
				}
				if($('groupactive-tab'))
				{
					$('groupactive-tab').className="";
					$('groupactive-tab').style.display="none";
				}
				if($('qudUsrCnt')){
					$('qudUsrCnt').innerHTML = "("+$('approvalscnt').value+")";
				}
			}
			if (acnt == 0 && qcnt == 0 && pcnt > 0)
			{
				if($('groupactivation-tab'))
				{
					$('groupactivation-tab').className="current";
				}
				if($('groupactive-tab'))
				{
					$('groupactive-tab').className="";
					$('groupactive-tab').style.display="none";
				}
				if($('acvUsrCnt')){
					$('acvUsrCnt').innerHTML = "("+$('activationscnt').value+")";
				}
			}
			if (acnt == 0 && qcnt == 0 && pcnt == 0 && bcnt > 0)
			{
				if($('groupblocked-tab'))
				{
					$('groupblocked-tab').className="current";
				}
				if($('groupactive-tab'))
				{
					$('groupactive-tab').className="";
					$('groupactive-tab').style.display="none";
				}
				if($('bckUsrCnt')){
					$('bckUsrCnt').innerHTML = "("+$('blockedcnt').value+")";
				}
			}
		}
		else if(status=="PENDING")
		{
			if($('groupactivation-tab'))
			{
				$('groupactivation-tab').className="current";
			}
			if($('acvUsrCnt')){
				$('acvUsrCnt').innerHTML = "("+$('activationscnt').value+")";
			}
			if (pcnt == 0 && acnt > 0)
			{
				if($('groupactive-tab'))
				{
					$('groupactive-tab').className="current";
				}
				if($('groupactivation-tab'))
				{
					$('groupactivation-tab').className="";
					$('groupactivation-tab').style.display="none";
				}
				if($('actUsrCnt')){
					$('actUsrCnt').innerHTML = "("+$('usersCountcnt').value+")";
				}
			}
			else if (pcnt == 0 && acnt == 0 && qcnt > 0)
			{
				if($('groupqueued-tab'))
				{
					$('groupqueued-tab').className="current";
				}
				if($('groupactivation-tab'))
				{
					$('groupactivation-tab').className="";
					$('groupactivation-tab').style.display="none";
				}
				if($('qudUsrCnt')){
					$('qudUsrCnt').innerHTML = "("+$('approvalscnt').value+")";
				}
			}
			else if (pcnt == 0 && acnt == 0 && qcnt == 0 && bcnt > 0)
			{
				if($('groupblocked-tab'))
				{
					$('groupblocked-tab').className="current";
				}
				if($('groupactivation-tab'))
				{
					$('groupactivation-tab').className="";
					$('groupactivation-tab').style.display="none";
				}
				if($('bckUsrCnt')){
					$('bckUsrCnt').innerHTML = "("+$('blockedcnt').value+")";
				}
			}
		}
		else if(status=="QUEUED")
		{
			if($('groupqueued-tab'))
			{
				$('groupqueued-tab').className="current";
			}
			if($('qudUsrCnt')){
				$('qudUsrCnt').innerHTML = "("+$('approvalscnt').value+")";
			}
			if (qcnt == 0 && acnt > 0)
			{
				if($('groupactive-tab'))
				{
					$('groupactive-tab').className="current";
				}
				if($('groupqueued-tab'))
				{
					$('groupqueued-tab').className="";
					$('groupqueued-tab').style.display="none";
				}
				if($('actUsrCnt')){
					$('actUsrCnt').innerHTML = "("+$('usersCountcnt').value+")";
				}
			}
			if (qcnt == 0 && acnt == 0 && pcnt > 0)
			{
				if($('groupactivation-tab'))
				{
					$('groupactivation-tab').className="current";
				}
				if($('groupqueued-tab'))
				{
					$('groupqueued-tab').className="";
					$('groupqueued-tab').style.display="none";
				}
				if($('acvUsrCnt')){
					$('acvUsrCnt').innerHTML = "("+$('activationscnt').value+")";
				}
			}
			if (qcnt == 0 && acnt == 0 && pcnt == 0 && bcnt > 0)
			{
				if($('groupblocked-tab'))
				{
					$('groupblocked-tab').className="current";
				}
				if($('groupqueued-tab'))
				{
					$('groupqueued-tab').className="";
					$('groupqueued-tab').style.display="none";
				}
				if($('bckUsrCnt')){
					$('bckUsrCnt').innerHTML = "("+$('blockedcnt').value+")";
				}
			}
		}
		else if(status=="BLOCKED")
		{
			if($('groupblocked-tab'))
			{
				$('groupblocked-tab').className="current";
			}
			if($('bckUsrCnt')){
				$('bckUsrCnt').innerHTML = "("+$('blockedcnt').value+")";
			}
			if (bcnt == 0 && acnt > 0)
			{
				if($('groupactive-tab'))
				{
					$('groupactive-tab').className="current";
				}
				if($('groupblocked-tab'))
				{
					$('groupblocked-tab').className="";
					$('groupblocked-tab').style.display="none";
				}
				if($('actUsrCnt')){
					$('actUsrCnt').innerHTML = "("+$('usersCountcnt').value+")";
				}
			}
			else if (bcnt == 0 && acnt==0 && pcnt > 0)
			{
				if($('groupactivation-tab'))
				{
					$('groupactivation-tab').className="current";
				}
				if($('groupblocked-tab'))
				{
					$('groupblocked-tab').className="";
					$('groupblocked-tab').style.display="none";
				}
				if($('acvUsrCnt')){
					$('acvUsrCnt').innerHTML = "("+$('activationscnt').value+")";
				}
			}
			else if (bcnt == 0 && acnt==0 && pcnt==0 && qcnt > 0)
			{
				if($('groupqueued-tab'))
				{
					$('groupqueued-tab').className="current";
				}
				if($('groupblocked-tab'))
				{
					$('groupblocked-tab').className="";
					$('groupblocked-tab').style.display="none";
				}
				if($('qudUsrCnt')){
					$('qudUsrCnt').innerHTML = "("+$('approvalscnt').value+")";
				}
			}		
		} 
	}
	function tabSelection(status)
	{
		if(status=="ACTIVE")
		{
			if($('groupactive-tab')) {
				$('groupactive-tab').className="current";
			}
			if($('groupactivation-tab'))
			{
				$('groupactivation-tab').className="";
			}
			if($('groupqueued-tab'))
			{
				$('groupqueued-tab').className="";
			}
			if($('groupblocked-tab'))
			{
				$('groupblocked-tab').className="";
			}
			if($('searchgroupresults-tab'))
			{	
				if($('searchGroupUser')) {
					$('searchGroupUser').value = $('searchGroupText').value;
				}
				$('searchgroupresults-tab').className="";
				$('searchgroupresults-tab').style.display='none';
			}
		}
		else if(status=="PENDING")
		{
			if($('groupactivation-tab'))
			{
				$('groupactivation-tab').className="current";
			}
			if($('groupactive-tab'))
			{
				$('groupactive-tab').className="";
			}
			if($('groupqueued-tab'))
			{
				$('groupqueued-tab').className="";
			}
			if($('groupblocked-tab'))
			{
				$('groupblocked-tab').className="";
			}
			if($('searchgroupresults-tab'))
			{
				if($('searchGroupUser')) {
					$('searchGroupUser').value = $('searchGroupText').value;
				}
				$('searchgroupresults-tab').className="";
				$('searchgroupresults-tab').style.display='none';
			}
		}
		else if(status=="QUEUED")
		{
			if($('groupqueued-tab'))
			{
				$('groupqueued-tab').className="current";
			}
			if($('groupactive-tab'))
			{
				$('groupactive-tab').className="";
			}
			if($('groupactivation-tab'))
			{
				$('groupactivation-tab').className="";
			}
			if($('groupblocked-tab'))
			{
				$('groupblocked-tab').className="";
			}
			if($('searchgroupresults-tab'))
			{
				if($('searchGroupUser')) {
					$('searchGroupUser').value = $('searchGroupText').value;
				}
				$('searchgroupresults-tab').className="";
				$('searchgroupresults-tab').style.display='none';
			}
		}
		else if(status=="BLOCKED")
		{
			if($('groupblocked-tab'))
			{
				$('groupblocked-tab').className="current";
			}
			if($('groupactive-tab'))
			{
				$('groupactive-tab').className="";
			}
			if($('groupactivation-tab'))
			{
				$('groupactivation-tab').className="";
			}
			if($('groupqueued-tab'))
			{
				$('groupqueued-tab').className="";
			}
			if($('searchgroupresults-tab'))
			{
				if($('searchGroupUser')) {
					$('searchGroupUser').value = $('searchGroupText').value;
				}
				$('searchgroupresults-tab').className="";
				$('searchgroupresults-tab').style.display='none';
			}
		} else {
			if($('searchgroupresults-tab'))
			{
				$('searchgroupresults-tab').style.visibility='visible';
				$('searchgroupresults-tab').className="current";
			}
			if($('groupactive-tab'))
			{
				$('groupactive-tab').className="";
			}
			if($('groupactivation-tab'))
			{
				$('groupactivation-tab').className="";
			}
			if($('groupqueued-tab'))
			{
				$('groupqueued-tab').className="";
			}
			if($('groupblocked-tab'))
			{
				$('groupblocked-tab').className="";
			}
		}
	}

	function getGroupUsersRes(resp){
		//TODO : compare selected and rendered userIds..
		var checkAll = document.getElementById("chkUserAll");
		var allitems = document.getElementsByName("chkUsers"); 
		var totaltrue=0;
		for(var i=0;i<allitems.length;i++){
			for(var j=0;j<selectedGroupUsers.length;j++){
				if(allitems[i].value==selectedGroupUsers[j]){
					allitems[i].checked=true;
					totaltrue=totaltrue+1;
				}
			} 
		}
		if(totaltrue == allitems.length && totaltrue>0){
			checkAll.checked=true;
		}
		$('create-period-menu').style.display='none';

	}
	function changeGroupUserTab(divId,url,status){
		var pathToImages = '/collaborize/site/common/images/common-images/';
		if($('downarrow-black')) {
			$('downarrow-black').style.display='none';
		}
		if($('white-down-arrow'))
			$('white-down-arrow').style.display='inline';
		if($('create-flight-menu'))
			$('create-flight-menu').className = "flight-menu";
		if($('new-gp-image'))
			$('new-gp-image').src=pathToImages+"newGroupIcon.png";

		removeErrorMessage('alertMsgDiv');
		if($('tabview').value=="select"){
			$('selectprocess').value="list";
			submitActionOnSelectTab(divId,url,1,1,status,false);
		}else if($('tabview').value=="current"){
			$('selectprocess').value="list";
			submitActionOnCurrentTab(divId,url,1,1,status,false); 
		}else{
			url=url+"&status="+status;
			loadDivContent(divId,url,getGroupUsersRes);	 
		} 
		tabSelection(status);

	}
	function changeGroupSelection(divId,url){
		removeErrorMessage('alertMsgDiv');
		if($('groupactive-tab')) {
			$('groupactive-tab').className="";
		}
		if($('groupqueued-tab')) {
			$('groupqueued-tab').className="";
		}
		if($('groupblocked-tab')) {
			$('groupblocked-tab').className="";
		}
		if($('groupactivation-tab')) {
			$('groupactivation-tab').className="";
		}
		loadDivContent(divId,url,getGroupUsersRes);	
		$('downarrow-black').style.display='inline';
		$('white-down-arrow').style.display='none';
		$('create-flight-menu').className = "flight-menu-current";
	}
	function searchGrpUser(divId,url){
		removeErrorMessage('alertMsgDiv');
		if($('groupactive-tab')) {
			$('groupactive-tab').className="";
		}
		if($('groupqueued-tab')) {
			$('groupqueued-tab').className="";
		}
		if($('groupblocked-tab')) {
			$('groupblocked-tab').className="";
		}
		if($('groupactivation-tab')) {
			$('groupactivation-tab').className="";
		}
		$('searchgroupresults-tab').style.display='block';
		$('searchgroupresults-tab').className="current";
		var str = $('searchGroupUser').value;
		//if(str != ""){
		$('searchGroupUserValue').value = str.strip();
		var editGrpId ="";
		if($('editGroupId')) {
			if($('editGroupId').value!= null && $('editGroupId').value!="") {
				editGrpId =$('editGroupId').value;
				$('isEditGroup').value = "true";
				$('grpId').value = editGrpId;
			}
		} else {
			$('isEditGroup').value = "false";
		}
		//url = url+"&searchString="+str;
		//$('groupUserSearch').action=url;	
		$('isFromSearch').value="true";
		submitForm(divId, document.groupUserSearch,getGroupUsersRes);
		//loadDivContent(divId,url,getGroupUsersRes);	
		//}			
	}

	function checkUserAll(){
		removeErrorMessage('alertMsgDiv');
		var checkAll = document.getElementById("chkUserAll");
		var allitems = document.getElementsByName("chkUsers"); 
		if(checkAll.checked){
			for(i=0;i<allitems.length;i++){
				allitems[i].checked = true;
				addToArray(allitems[i].value);
			}
		}
		if(checkAll.checked==false){
			for(i=0;i<allitems.length;i++){
				allitems[i].checked = false;
				removeFromArray(allitems[i].value);
			}		
		}
		//add/remove items to selectGroupUsers Array

	}
	function checkUserIndivial(userId){
		removeErrorMessage('alertMsgDiv');
		var allitems = document.getElementsByName("chkUsers"); 
		var checkAll = document.getElementById("chkUserAll");
		var totaltrue=0;
		for(var i=0;i<allitems.length;i++){
			if(allitems[i].checked == false){
				checkAll.checked=false;
				if(allitems[i].value==userId){
					removeFromArray(allitems[i].value);
				}
			}
			if(allitems[i].checked == true){
				totaltrue=totaltrue+1;
				if(allitems[i].value==userId){
					addToArray(allitems[i].value);	
				}
			}
		}
		if(totaltrue == allitems.length ){
			checkAll.checked=true;
		}
		//add/remove items to selectGroupUsers Array
	} 
	function addToArray(userId){
		var isExist = false;
		for(var i=0;i<selectedGroupUsers.length;i++){
			if(userId==selectedGroupUsers[i]){
				isExist = true;
			}
		}
		if(!isExist){
			selectedGroupUsers[selectedGroupUsers.length]=userId;
			$('selectedCnt').innerHTML = selectedGroupUsers.length;
			selectedGroupUserStates[selectedGroupUserStates.length]=$('userMemStatus'+userId).value;
		}
		/**selected tab show/hide based on selected users count*/
		if(selectedGroupUsers.length==0  ){
			$('selectedLi').style.display="none";
		}else if($('selectedLi').style.display=="none"){
			$('selectedLi').style.display="";
			removeErrorMessage('alertMsgDiv');
		}
	}
	function removeFromArray(userId){
		var isExist = false;
		for(var i=0;i<selectedGroupUsers.length;i++){
			if(userId==selectedGroupUsers[i]){
				isExist = true;
				selectedGroupUsers.splice(i,1);
				selectedGroupUserStates.splice(i,1);
				$('selectedCnt').innerHTML = selectedGroupUsers.length;
			}		
		}
		/**selected tab show/hide based on selected users count*/
		if(selectedGroupUsers.length==0){
			$('selectedLi').style.display="none";
		}else if($('selectedLi').style.display=="none"){
			$('selectedLi').style.display="";
		}
	}
	function saveGroupDetails(){
		/*
		 * bug:5752 bug is fixed
		 * route cause: not bloceked create-period-menu when we click creategroup button
		 * Now bug is fixed
		 * 
		 * */
		/*
		 * bug:5776 bug is fixed
		 * route cause: Condition kept for even null condition
		 * Now bug is fixed
		 * 
		 * */
		if($('downarrow-black')){
			$('downarrow-black').style.display='none';
		} 
		if($('white-down-arrow')){
			$('white-down-arrow').style.display='inline';
		}
		if($('create-period-menu')){

			$('create-period-menu').style.display='none';
		}
		if($('create-flight-menu')){
			$('create-flight-menu').className = "";
		}
		removeErrorMessage('alertMsgDiv');
		var groupName = "";
		if($('createGroupName').value!=null) {
			$('createGroupName').value = $('createGroupName').value.strip();
			groupName = $('createGroupName').value.strip();
		} else if($('createGroupName').innerHTML!=null) {
			groupName = $('createGroupName').innerHTML;
			groupName = groupName.strip();
		}
		if(groupName==""){
			document.getElementById('alertMsg').innerHTML = "Please enter Group Name";
			document.getElementById('alertMsgDiv').style.display = "";
			document.getElementById('createGroupName').focus();
			return;
		}
		if(groupName != "")
		{

			if(groupName.indexOf("<object")>=0 || groupName.indexOf("<embed")>=0 || groupName.indexOf("<param")>=0 || groupName.indexOf("<iframe")!=-1) {
				document.getElementById('alertMsg').innerHTML = "Please enter valid Group Name";
				document.getElementById('alertMsgDiv').style.display = "";
				document.getElementById('createGroupName').focus();
				return;
			}
		}
		/*
         * @author: kranthi
         * @bug: DS-5577
         * fix: commented below code and written above condition line to allow special characters when create the groupname.
         */
		/*var val_name=/^[\w|\.|\- ]+$/gi;
		if(groupName.match(val_name)) {
			groupName = $('createGroupName').value.strip();
			
						//$('alertMsg').innerHTML = "Please enter valid Group Name";
						
						 * bug:5776 bug is fixed
						 * route cause: Condition kept for even null inorder to show alert
						 * Now bug is fixed
						 * 
						 * 
						//$('alertMsgDiv').style.display = "block";
						//$('createGroupName').focus();
						return;
		}*/
		var ids ="";
		for(var i=0;i<selectedGroupUsers.length;i++){
			ids= ids+","+selectedGroupUsers[i];
		}
		if(ids.length>0){
			ids=ids.substring(1,ids.length);
		}else{
			//document.getElementById('alertMsg').innerHTML = "Please select atleast one member";
			//document.getElementById('alertMsgDiv').style.display = "";
			//return;
		}
		$('selectedIds').value=ids;
		submitForm('saveGrpResultDiv', document.createGroup,saveGrpResult);
	}
	function saveGrpResult(resp){ 
		var response = document.getElementById('saveGrpResultDiv').innerHTML.strip(); 
		if(response.indexOf("constaintVoilation")>=0){
			document.getElementById('alertMsg').innerHTML = "Group Name already exist";
			document.getElementById('alertMsgDiv').style.display = "";
			document.getElementById('createGroupName').focus();
			return; 
		}else{ 
			document.manageGroupsForm.submit();
			hideGroupPopup();
		}
		//submitForm('pagecontent', document.manageGroupsForm,mngGrpResult);	 
	}
	function mngGrpResult(resp){

	}
	function changeGroupSelectTab(divId,url){
		removeErrorMessage('alertMsgDiv');
		if($('selected-members'))
		{
			$('selected-members').className="current";
		}
		if($('add-members'))
		{
			$('add-members').className="";
		}
		if($('current-members'))
		{
			$('current-members').className="";
		}
		if($('add-new-memers'))
		{
			$('add-new-memers').className="";
		}
		$('selectprocess').value="maintab";
		submitActionOnSelectTab(divId,url,1,1,'ACTIVE',false);	
	}
	function changeGroupAddMemTab(divId,url,id){
		removeErrorMessage('alertMsgDiv');
		if(id=="add-members")
		{
			$('add-members').className="current";
			$('selected-members').className="";
			if($('selected-members'))
			{
				$('selected-members').className="";
			}
		}
		if(id=="current-members")
		{
			$('current-members').className="current";
			$('add-new-memers').className="";
			if($('selected-members'))
			{
				$('selected-members').className="";
			}
		}
		if(id=="add-new-memers")
		{
			$('add-new-memers').className="current";
			$('current-members').className="";
			if($('selected-members'))
			{
				$('selected-members').className="";
			}
		}
		url=url+"&status=ACTIVE&tabview=addnew";
		loadDivContent(divId,url,getGroupUsersRes);	 
	}
	function changeGroupCurrentTab(divId,url,id){
		removeErrorMessage('alertMsgDiv');
		if($('selected-members'))
		{
			$('selected-members').className="";
		}
		if($('add-members'))
		{
			$('add-members').className="";
		}
		if($('current-members'))
		{
			$('current-members').className="current";
		}
		if($('add-new-memers'))
		{
			$('add-new-memers').className="";
		}

		var ids ="";
		for(var i=0;i<deletedGroupUsers.length;i++){
			ids= ids+","+deletedGroupUsers[i];
		}
		if(ids.length>0){
			ids=ids.substring(1,ids.length);
		}
		var states ="";
		for(var i=0;i<deletedGroupUserStates.length;i++){
			states= states+","+deletedGroupUserStates[i];
		}
		if(states.length>0){
			states=states.substring(1,states.length);
		}

		url=url+"&status=ACTIVE&tabview=current&process=maintab&deletedIds="+ids+"&deletedIdStates="+states;

		loadDivContent(divId,url,getGroupUsersRes);	 
	}
	function getGroupSelectUsersRes(resp){ 
	}
	function displayUserPageChanage(startNo, e, pageNo,noOfPages,url,divId){
		removeErrorMessage('alertMsgDiv');
		var keycode;
		if (window.event) keycode = window.event.keyCode;
		else if (e) keycode = e.which;

		if(keycode == 13){
			if(pageNo<1 || pageNo>noOfPages){
				document.getElementById('alertMsg').innerHTML = "Page No should be between 1 and "+noOfPages;
				document.getElementById('alertMsgDiv').style.display = ""; 
			}else{
				getGroupUsers(startNo, pageNo, url,divId)
			}
		} 
	}
	function removeGroupUser(pageNo,userId,divId,url,activationCnt,pendingapprCnt,pendingActCnt,blockedCnt){
		removeErrorMessage('alertMsgDiv');
		if(!isRemovedUser(userId)){
			deletedGroupUsers[deletedGroupUsers.length]= userId;
			deletedGroupUserStates[deletedGroupUserStates.length]= $('uStatus').value;
			var ids ="";
			for(var i=0;i<deletedGroupUsers.length;i++){
				ids= ids+","+deletedGroupUsers[i];
			}
			if(ids.length>0){
				ids=ids.substring(1,ids.length);
			}
			var states ="";
			for(var i=0;i<deletedGroupUserStates.length;i++){
				states= states+","+deletedGroupUserStates[i];
			}
			if(states.length>0){
				states=states.substring(1,states.length);
			}	
			url=url+"&userId="+userId+"&tabview=current&process=delete&status="+$('uStatus').value+"&pageNo="+pageNo+"&deletedIds="+ids+"&deletedIdStates="+states;
			loadDivContent(divId,url,getGroupUsersRes);		
		}
	}
	function isRemovedUser(userId){
		setTimeout("",1250);  
		for(i=0;i<deletedGroupUsers.length;i++){
			if(deletedGroupUsers[i]==userId){
				return true;
			}
		}
		//setTimeout("alert('hi')",1250); 
		return false;
	}
	function removeSelected(userId,url,divId,url1){
		removeFromArray(userId);
		if(selectedGroupUsers.length==0){
			if($("add-members")) {
				changeGroupAddMemTab('groupmaintabcontentDiv',url1,"add-members");
			} else if($('add-new-memers')) {
				var editGrpId ="";
				if($('editGroupId').value!= null && $('editGroupId').value!="") {
					editGrpId =$('editGroupId').value;
					url1 += "&groupId="+editGrpId; 
				}
				changeGroupAddMemTab('groupmaintabcontentDiv',url1,"add-new-memers");
			}
		}else{
			$('selectprocess').value="list";
			submitActionOnSelectTab(divId,url,1,$('selPageNo').value,$('uStatus').value,true);
		}
	}

	function showEditGroup(url){
		if($('group-details')){
			$('group-details').innerHTML="";
		}
		removeErrorMessage('alertMsgDivInList');
		selectedGroupUsers = new Array();
		selectedGroupUserStates = new Array();

		deletedGroupUsers = new Array();
		deletedGroupUserStates = new Array();

		loadDivContent('editgroup-popup',url,editGroupResponce);
	}

	function editGroupResponce(resp) {
		showpopupwindow("editgroup-popup");	
	}

	function managegroupsview(url){
		window.location.href = url;
	}
	function saveEditGroupDetails(){
		/*
		 * bug:5752 bug is fixed
		 * route cause: not bloceked create-period-menu when we click creategroup button
		 * Now bug is fixed
		 * 
		 * */
		/*
		 * bug:5804 bug is fixed
		 * route cause: not blocked create-period-menu when we click creategroup button
		 * Now bug is fixed
		 * 
		 * */
		if($('downarrow-black')){
			$('downarrow-black').style.display='none';
		} 
		if($('white-down-arrow')){
			$('white-down-arrow').style.display='inline';
		}
		if($('create-period-menu')){

			$('create-period-menu').style.display='none';
		}
		if($('create-flight-menu')){
			$('create-flight-menu').className = "";
		}
		removeErrorMessage('alertMsgDiv');
		var groupName = "";
		if($('editGroupName').value!=null) {
			groupName = $('editGroupName').value.strip();
		} else if($('editGroupName').innerHTML!=null) {
			groupName = $('editGroupName').innerHTML;
		}

		if(groupName==""){
			document.getElementById('alertMsg').innerHTML = "Please enter group name";
			document.getElementById('alertMsgDiv').style.display = "";
			document.getElementById('editGroupName').focus();
			return;
		}
		/* @kranthi
		 * bug:5577 bug is fixed
		 * Implemented code to allow special characters while renaming or editing the group name.
		 * */
		/*var val_name=/^[\w|\.|\- ]+$/gi;
		
		if(groupName.match(val_name)) {
			groupName = $('editGroupName').value.strip();
			//$('alertMsg').innerHTML = "Please enter valid Group Name";
			
			 * bug:5804 bug is fixed
			 * route cause: not blocked create-period-menu when we click creategroup button
			 * Now bug is fixed
			 * 
			 * 
			$('alertMsgDiv').style.display = "block";
			$('editGroupName').focus();
			return;
		}*/
		var ids ="";
		for(var i=0;i<selectedGroupUsers.length;i++){
			ids= ids+","+selectedGroupUsers[i];
		}
		if(ids.length>0){
			ids=ids.substring(1,ids.length);
		} 
		$('selectedIds').value=ids;
		var delIds = "";
		for(var i=0;i<deletedGroupUsers.length;i++){
			delIds= delIds+","+deletedGroupUsers[i];
		}
		if(delIds.length>0){
			delIds=delIds.substring(1,delIds.length);
		} 
		$('delIds').value=delIds;
		submitForm('saveEditGrpResultDiv', document.editGroup,saveEditGrpResult);
	}
	function saveEditGrpResult(resp){
		var response = document.getElementById('saveEditGrpResultDiv').innerHTML.strip(); 
		if(response.indexOf("constaintVoilation")>=0){
			document.getElementById('alertMsg').innerHTML = "Group Name already exist";
			document.getElementById('alertMsgDiv').style.display = "";
			document.getElementById('editGroupName').focus();
			return; 
		}else{ 
			document.manageGroupsForm.submit();
			hidepopup('editgroup-popup');
		}
	}
	//groups.js end


//	set cookie
	function getCookie(c_name)
	{
		var i,x,y,ARRcookies=document.cookie.split(";");
		for (i=0;i<ARRcookies.length;i++)
		{
			x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
			y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
			x=x.replace(/^\s+|\s+$/g,"");
			if (x==c_name)
			{
				return unescape(y);
			}
		}
	}

	function setCookie(c_name,value,exdays)
	{	
		var exdate=new Date();
		exdate.setDate(exdate.getDate() + exdays);
		var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
		document.cookie=c_name + "=" + c_value;	
	}
	//gets the suject,content from send message page
	function sendMessageSelection(url,divId,ele) {


		var subject=trim(document.getElementById("newmsgsubject").value);
		//var content=trim(document.getElementById("newmsgcontent").value);
		//var content=trim(msginstance.e.body.innerHTML);

		//document.getElementById("newmsgcontent").value = msginstance.e.body.innerHTML;
		//var content=trim(document.getElementById("newmsgcontent").value);
		var android = (navigator.appVersion.indexOf("Android") == -1) ? false : true;

		if(ipad || iphone || android){
			var content=trim($('newmsgcontent').value);
			var inboxContentMsg = $('newmsgcontent').value;			
		} else {
			var content=trim(msginstance.e.body.innerHTML);
			$('plainTextDiv').innerHTML = msginstance.e.body.innerHTML;
			var inboxContentMsg = $('plainTextDiv').textContent || $('plainTextDiv').innerText;
		}

		if(subject==""){
			document.getElementById("newmsgsubject").focus();
			document.getElementById("showMsgResult").innerHTML="<p>"+$('resEnter_subject').value+"</p>";
			document.getElementById("showMsgResult").style.display="block";
			return ;
		}
		if(subject.length>150){
			document.getElementById("newmsgsubject").focus();
			document.getElementById("showMsgResult").innerHTML="<p>"+$('resEnter_subject_length').value+"</p>";
			document.getElementById("showMsgResult").style.display="block";
			return ;
		}
		if(inboxContentMsg == null || inboxContentMsg.strip() == ""){
			//document.getElementById("newmsgcontent").focus();
			document.getElementById("showMsgResult").innerHTML="<p>"+$('resEnter_message').value+"</p>";
			document.getElementById("showMsgResult").style.display="block";
			if(ipad || iphone || android){
				$('newmsgcontent').value ='';
			} else {
				msginstance.e.body.innerHTML ='&nbsp;';
			}
			return;
		}

		if(validateCurseFilter1(content)&&validateCurseFilter1(subject)){
			//based on the button that is selected,the corresponding value is appended to the url


			if(document.getElementById("moderators").checked == true) 
			{
				url +="&subject="+escape(subject)+"&content="+escape(content)+"&val="+2;
				loadDivContent(divId,url,function(){showModeratorMsgResult(ele)});

			}
			if(document.getElementById("entirecommunity").checked == true)
			{
				url +="&subject="+escape(subject)+"&content="+escape(content)+"&val="+1;
				loadDivContent(divId,url,function(){showBroadcastResult(ele,url)});  
			}
			if($('groups') != null){
				if(document.getElementById("groups").checked == true) 
				{
					if(validateGroups()){
						url +="&subject="+escape(subject)+"&content="+escape(content)+"&val="+3;
						//getting the selected groups from the jsp
						var id = document.getElementById('period-group');
						var inputs = document.getElementById('period-group').getElementsByTagName('input');
						var i;
						var selectedGroups="";
						for(i=0;i<inputs.length;i++)
						{
							if(inputs[i].type=="checkbox" && inputs[i].checked)	{
								selectedGroups += inputs[i].value;
								selectedGroups += ",";
							}
						}
						//the group ids are added to the string comma separated.And the string is added to the url
						url += "&selectedGroups="+selectedGroups; 
						loadDivContent(divId,url,function(){showModeratorMsgResult(ele)});
					}
				}
			}  
		}
	}
	function validateGroups()
	{
		setAlertMessage("showMsgResult","showMsgResult","");
		// alert(document.getElementById('multi-categories').style.display +"--"+ $('catIdchkbox').checked +"  "+ $('categoryId').value);

		if($('groups').checked && $('groupSequence').value==0){
			document.getElementById("showMsgResult").innerHTML="<p>"+$('select_group').value+"</p>";
			document.getElementById("showMsgResult").style.display="block";
			window.scroll(0,0);
			return false;
		}else if($('groups').checked){
			var id = document.getElementById('period-group');
			var inputs = document.getElementById('period-group').getElementsByTagName('input');
			var i;
			var j=0;
			var stringArray= new Array();
			for(i=0;i<inputs.length;i++)
			{
				if(inputs[i].type=="checkbox" && inputs[i].checked)	{							 
					j++;					
				}
			}
			if(j==0){
				document.getElementById("showMsgResult").innerHTML="<p>"+$('select_group').value+"</p>";
				document.getElementById("showMsgResult").style.display="block";
				window.scroll(0,0);
				return false;
			}
		} 
		return true;
	}
	//closes the send message popup
	function sendmessageclose()
	{ 
		var android = (navigator.appVersion.indexOf("Android") == -1) ? false : true;
		if(!ipad && !iphone && !android){
			msginstance.e.body.innerHTML="";
		}
		divs_transparentDiv.style.display="none";
		document.getElementById("newmsgsubject").value="";
		document.getElementById("newmsgcontent").value="";
		document.getElementById("sendmessageId").style.display="none";
		document.getElementById("showMsgResult").innerHTML = "";
		document.getElementById("showMsgResult").style.display="none";	
		var groupitems = document.getElementsByName("groupSequence");
		$("entirecommunity").checked = true;
		for(i=0;i<groupitems.length;i++)
		{
			groupitems[i].checked = false;       
		}
	}

//	javascript for controlling the buttons and check boxes in send message
	function checkSendMesgGroup(){
		$("groups").checked =true;
		sendMessageChecks();
	}
	function sendMessageChecks()
	{

		var groupitems = document.getElementsByName("groupSequence");
		
		if($("entirecommunity").checked == true || $("moderators").checked == true) 
		{
			for(i=0;i<groupitems.length;i++)
			{
				groupitems[i].checked = false;       
			}
		}
		if($('groups')) {
			if($("groups").checked == true) 
			{
				for(i=0;i<groupitems.length;i++)
				{
					groupitems[i].disabled = false;       
				}
			}
		}
		/*if($("entirecommunity").checked == true || $("moderators").checked == true) {
		for(i=0;i<groupitems.length;i++){
			groupitems[i].checked = false;       
	}
	}
	if(document.getElementById("groupSequence").checked == true){
		$('groups').checked = true;
	}*/
	}
	function hideflightmenu(e)
	{
		var userGroupRefAnchor = document.getElementsByName('userGroupsRef');	
		e = e || window.event;
		var obj;
		if(e.srcElement){
			obj = e.srcElement;
		}else if(e.target){
			obj = e.target;
		}
		if(obj.id=="image-id" || obj.className=="flight-menu" || obj.name=="allGroups")
		{
			if(obj.className=="flight-menu" && obj.parentNode.className=="")
			{
				for (i=0; i<userGroupRefAnchor.length; i++) 
				{
					userGroupRefAnchor[i].className ="flight-menu";
				}
				obj.className="mangeflight-menu-current";
				if($("period-menu"))
				{
					$("period-menu").style.display="block";
				}
			}
			else if(obj.className=="" && obj.parentNode.className=="flight-menu")
			{
				for (i=0; i<userGroupRefAnchor.length; i++) 
				{
					userGroupRefAnchor[i].className ="flight-menu";
				}
				obj.parentNode.className="mangeflight-menu-current";
				if($("period-menu"))
				{
					$("period-menu").style.display="block";
				}
			}
			else
			{
				obj.parentNode.className="flight-menu";
				if($("period-menu"))
					$("period-menu").style.display="none";
				if(obj.name=="allGroups")
				{
					obj.parentNode.className="";
					if($("period-menu"))
						$("period-menu").style.display="block";
				}

			}
			for (i=0; i<userGroupRefAnchor.length; i++) {
				userGroupRefAnchor.className ="mangeflight-menu-current";
			}
		} 
		else 
		{
			if(document.getElementById('flight-menu')){
				if($("period-menu"))
				{
					$("period-menu").style.display="none";
				}
				for (i=0; i<userGroupRefAnchor.length; i++) {
					userGroupRefAnchor[i].className ="flight-menu";
				}
			}
		}

	}
	document.onclick = hideflightmenu;

	function getRegisterForm() {
		var url = $('registerPageUrl').value;
		sendRequest(url, registrationFormResponseHandler);
	}
	function editTopicFocus()
	{
		if($('topicFocusDivId')){
			var topicFocusId = $('topicFocusDivId').value;
			if(topicFocusId!=null && topicFocusId!=''){ 
				if($(topicFocusId)){
					var myPos = findPos($(topicFocusId));
					window.scrollTo(myPos[0],myPos[1]);

				}
			} 
		}
	}

	function searchActiveMembers(div,url){
		if($('searchUser') != null){
			var search=$('searchUser').value.strip();
			//$('userSearchString').value =url+'&search='+search;
			$('searchActiveUserValue').value =search;
			$('searchresults-tab').style.display="block";
			chageusertab(div,url+'&search='+search);
			submitForm('manageuserdiv', document.activeMembersSearch);
		}
	}

	function calOnly(ele) 
	{
		//alert("Please use Calendar");
		var a = ele.value;
		var len = a.length;
		ele.value = a.substring(0,len-1);
	}
	var likeTopicId=0;
	var likeValue=true;
	function togglelike(url,topicId,popularity,islike){
		var val = $('like_'+topicId).innerHTML;

		if(val == "Like")
		{

			islike="true";
		}
		else if(val == "UnLike" || val == "Unlike" || val == "Liked")
		{

			islike="false";
		}

		likeTopicId=topicId;
		likeValue=islike;
		sendRequest(url+'&topicId='+topicId+'&isLike='+islike,likeAjaxResponse);

	}

	function likeAjaxResponse(resp)
	{
		if(resp.status==200){ 
			var popularity = resp.responseText; 
			$('popular_div_'+likeTopicId).innerHTML = "Popularity: "+popularity;
			if($('like_'+likeTopicId).innerHTML == "Like")
			{
				$('like_'+likeTopicId).innerHTML = "Liked";
				$('like_'+likeTopicId).className = "unlike-link";
			}
			else if($('like_'+likeTopicId).innerHTML == "UnLike" || $('like_'+likeTopicId).innerHTML == "Liked")
			{
				$('like_'+likeTopicId).innerHTML = "Like";
				$('like_'+likeTopicId).className = "like-link";
			}

		}	
	}
	function toggleliketext(ele)
	{
		if(ele.innerHTML == "Liked")
		{
			ele.innerHTML = "Unlike";
		}
		else if(ele.innerHTML == "Unlike")
		{
			ele.innerHTML = "Liked";
		}
	}
	
	function encodeurl(url)
	{
		var encurl=encodeURI(url);
		  var intIndexOfMatch=encurl.indexOf('#');
		  while(intIndexOfMatch!=-1){
			  //alert("in if of index of");

		  encurl=encurl.replace('#','%23');
		  intIndexOfMatch=encurl.indexOf('#');
		  }
		 // alert("in encode url"+encurl);
		  window.open(encurl,"Attachmentwindow");
	  
	}
