function toggleStar(star, alert)
{
	if (!star)
		return;
	
	var con = true;
	var id = star.id.replace('star', '');
	
	if( star.src.indexOf('star.gif') > 0 ) 
	{ 
		MM_swapImage(star.id,'','justis_images/star_selected.gif',1)
		if (star.title.indexOf('My Documents') > 0)
		{
		    star.setAttribute('title', 'Remove from My Documents')
		}
		else
		{
		    star.setAttribute('title', 'Remove from Saved Searches')
		}
		updateStars(id, 1);
	} 
	else 
	{ 
		if(alert && alert.src.indexOf('alert_selected.gif') > 0 ) 
		{
			con = confirm('Removing this search will also cancel the alert. Continue?');
		}
		
		if (con == true)
		{
			MM_swapImage(star.id,'','justis_images/star.gif',1) 
		    if (star.title.indexOf('My Documents') > 0)
		    {
		        star.setAttribute('title', 'Add to My Documents')
		    }
		    else
		    {
		        star.setAttribute('title', 'Add to Saved Searches')
		    }
			updateStars(id, 0);
			if(alert && alert.src.indexOf('alert_selected.gif') > 0 )
				toggleAlert(alert);
		}
		
	}
}

function toggleAlert(alert)
{
	if (!alert)
		return
	
	var id = alert.id.replace('alert', '');

	if( alert.src.indexOf('alert.gif') > 0 ) 
	{ 
		MM_swapImage(alert.id,'','justis_images/alert_selected.gif',1)
		alert.setAttribute('title', 'Cancel alert')
	
		var star = document.getElementById('star' + id)
		
		if (star.src.indexOf('star.gif') > 0 ) 
		    toggleStar(star, alert)
	
		updateAlerts(id, 1);
		ShowEditor(id)		
	} 
	else 
	{ 
		if (confirm("Are you sure you want to cancel the alert for this search?") == true)
		{
			MM_swapImage(alert.id,'','justis_images/alert.gif',1) 
    		alert.setAttribute('title', 'Set up alert')

			updateAlerts(id, 0);
			
			
		}
	}

	lastAlert = alert;
	
}

function hideAlerting(cancel)
{
	if (document.getElementById('AlertRecipients').value.length == 0 && cancel != true)
	{
		alert('Please specify the recipient of this alert');
	}
	else
	{
		document.getElementById('alerting').style.display='';
	}
	
	//alert(lastAlert);
	if (lastAlert != null && cancel == true)
	{
		toggleAlert(lastAlert)
		//alert(lastAlert);
	}
	
}

var lastEdited = "";
var lastAlert = null;
var editorInterval = null;

function ShowEditor(trailid,title)
{

    if(title)
    {
        var titl = document.getElementById('searcheditortitle');
        titl.innerHTML = title;
    }

	var isie = ( navigator.userAgent.toLowerCase().indexOf("msie") != -1 );

	var sel = document.getElementById('groupsSelect')
	sel.style.display = 'none';

	var modal = document.getElementById('modal');
	modal.style.display='block';
		
	var win = getWindow();
	if (win.ScrollHeight > win.Height)
	{
		modal.style.height = win.ScrollHeight + 'px';
		modal.style.width = win.Width - 19 + 'px';
	}
	else
	{
		modal.style.height = win.Height + 'px';
		modal.style.width = win.Width + 'px';
	}		
	
	var se = document.getElementById('searcheditor')
	
	document.getElementById('ItemSearchString').value = "Loading..."
	document.getElementById('ItemDatabases').value = "Loading..."
	document.getElementById('ItemName').value = "Loading..."
	document.getElementById('AlertRecipients').value = "Loading..."
	document.getElementById('AlertSubject').value = "Loading..."
	document.getElementById('MaxResults').value = "Loading..."
	
	se.style.display='block';

	setMiddle('searcheditor')
	if (editorInterval != null)
    {
	    clearInterval(editorInterval);
	}
	editorInterval = setInterval("setMiddle('searcheditor')", 50);
		
	document.getElementById('ItemTrailID').value = trailid;	

	getDetails(trailid);
	
	
}

	function setMiddle(div)
	{
		var myDiv = document.getElementById(div)
		
		myWin = getWindow()
		myDiv.style.position = 'absolute'
		myDiv.style.top = myWin.Scrolled + (myWin.Height/3) - (myDiv.offsetHeight/2) + 'px'
		
		myDiv.style.left = (myWin.Width/2) - (myDiv.offsetWidth/2) + 'px'
		
	}


function GenToolbar(details, saved, alerting)
{

	if (details[0].Line.Item.EntityID)		
	{
		var optionsHtml = "<ul class=\"nav\"><li><a href=\"document.aspx?doc=" + details[0].Line.Item.DocReference + "\" style=\"background: url(justis_images/document_ico.gif) no-repeat 5px; padding-left: 24px;\">View Document</a></li>"
		
		if (saved.src.indexOf('star_selected.gif') <= 0 ) 
			optionsHtml += "<li class=\"separator\"></li><li><a href=\"javascript:;\" onclick=\"toggleStar(document.getElementById('star" + details[0].Line.Item.TrailId + "'));setBackgroundImage(this, document.getElementById('star" + details[0].Line.Item.TrailId + "').src); this.innerHTML = (this.innerHTML =='Add to My Documents') ? 'Remove from My Documents' : 'Add to My Documents'\" style=\"background: url(justis_images/star.gif) no-repeat 5px; padding-left: 24px;\" >Add to My Documents</a></li>"
		else 
			optionsHtml += "<li class=\"separator\"></li><li><a href=\"javascript:;\" onclick=\"toggleStar(document.getElementById('star" + details[0].Line.Item.TrailId + "'));setBackgroundImage(this, document.getElementById('star" + details[0].Line.Item.TrailId + "').src); this.innerHTML = (this.innerHTML =='Add to My Documents') ? 'Remove from My Documents' : 'Add to My Documents'\" style=\"background: url(justis_images/star_selected.gif) no-repeat 5px; padding-left: 24px;\" >Remove from My Documents</a></li>"
	
		document.getElementById('itemMenuOptions').innerHTML = optionsHtml;
	}
	else
	{	
		var optionsHtml = "<ul class=\"nav\"><li><a href=\"search.aspx?search=saved&action=run\" style=\"background: url(justis_images/search_ico.gif) no-repeat 5px; padding-left: 24px;\">Run Search</a></li><li class=\"separator\"></li><li><a href=\"search.aspx?search=saved&action=load\" style=\"background: url(justis_images/search_ico.gif) no-repeat 5px; padding-left: 24px;\">Load Search</a></li>"
			
		if (saved)
		{
			if (saved.src.indexOf('star_selected.gif') <= 0 ) 
				optionsHtml += "<li class=\"separator\"></li><li><a href=\"javascript:;\" onclick=\"toggleStar(document.getElementById('star" + details[0].Line.Item.TrailId + "'));setBackgroundImage(this, document.getElementById('star" + details[0].Line.Item.TrailId + "').src); this.innerHTML = (this.innerHTML =='Add to Saved Searches') ? 'Remove from Saved Searches' : 'Add to Saved Searches'\" style=\"background: url(justis_images/star.gif) no-repeat 5px; padding-left: 24px;\" >Add to Saved Searches</a></li>"
			else 
				optionsHtml += "<li class=\"separator\"></li><li><a href=\"javascript:;\" onclick=\"toggleStar(document.getElementById('star" + details[0].Line.Item.TrailId + "'));setBackgroundImage(this, document.getElementById('star" + details[0].Line.Item.TrailId + "').src);this.innerHTML = (this.innerHTML =='Add to Saved Searches') ? 'Remove from Saved Searches' : 'Add to Saved Searches'\" style=\"background: url(justis_images/star_selected.gif) no-repeat 5px; padding-left: 24px;\" >Remove from Saved Searches</a></li>"
		}
				
		if (alerting && alerting.src.indexOf('alert_selected.gif') <= 0 ) 
		{
			optionsHtml += "<li class=\"separator\"></li><li><a href=\"javascript:;\" onclick=\"toggleAlert(document.getElementById('alert" + details[0].Line.Item.TrailId + "'))\" style=\"background: url(justis_images/alert.gif) no-repeat 5px; padding-left: 24px;\" >Create Alert</a></li>"
		}
		else
		{
			optionsHtml += "<li class=\"separator\"></li><li><a href=\"javascript:;\" onclick=\"toggleAlert(document.getElementById('alert" + details[0].Line.Item.TrailId + "'))\" style=\"background: url(justis_images/alert_selected.gif) no-repeat 5px; padding-left: 24px;\" >Remove Alert</a></li>"
		}
		
		
	}
	
	optionsHtml += "</ul>";
	document.getElementById('itemMenuOptions').innerHTML = optionsHtml
}

function SaveChanges(Line)
{
	var TrailID = document.getElementById('ItemTrailID').value
	var Name = document.getElementById('ItemName').value

	var alerting = ( document.getElementById('alert'+ TrailID) && document.getElementById('alert'+ TrailID).src.indexOf('alert_selected.gif') > 0 )
	var Recipients = document.getElementById('AlertRecipients').value;
	var Subject = document.getElementById('AlertSubject').value;
	var MaxResults = document.getElementById('MaxResults').value;

	
	if (Name.length > 0)
	{
		saveEdit(TrailID, Name);
	}
	else
	{
		alert("Please enter a name");
		return;
	}

	if (alerting == true)
	{
		if (Recipients.length > 0)
		{
			saveAlert(TrailID, Recipients, Subject, MaxResults)
			HideEditor(false);
		}
		else
		{
			alert("Please specify who to send alert to");
		}
	}
	else
	{
		
		HideEditor();
	}
	

}

function HideEditor(cancel)
{
	var sel = document.getElementById('groupsSelect')
	sel.style.display = '';

	var TrailID = document.getElementById('ItemTrailID').value
	var Recipients = document.getElementById('AlertRecipients').value
	var alerting = ( document.getElementById('alert'+ TrailID) && document.getElementById('alert'+ TrailID).src.indexOf('alert_selected.gif') > 0 )
	
	if (alerting == true && cancel == true && Recipients.length == 0)
	{
		toggleAlert(document.getElementById('alert'+ TrailID));
	}
	else
	{
		
	}
		
	document.getElementById('modal').style.display='none';
	document.getElementById('searcheditor').style.display = 'none';

	if (editorInterval != null)
    {
        clearInterval(editorInterval);
        editorInterval = null;
	}
	
	var sel = document.getElementById('groupsSelect')
	sel.style.display = '';
	
}

function saveEdit(TrailID, NewName)
{
	var fname = document.getElementById('FriendlyName' + TrailID);
	
	if (fname.innerHTML != NewName)
	{
	
		update(TrailID, NewName);
		fname.innerHTML = NewName;
	}
}

function getCheckedValues()
{
	if (!document.forms[0].checks)
		return "";
	
	var values = '';
		
	var countCheckBoxes = document.forms[0].checks.length;
	
	if(!countCheckBoxes)
		return document.forms[0].checks.value;
	else
		for (var i=0; i <= countCheckBoxes -1; i++)
		{
			//alert(document.forms[0].checks[i].checked )
			if (document.forms[0].checks[i].checked == true)
			{
				values +=  document.forms[0].checks[i].value + ",";
				//alert(values)
			}
		}
		
	return values.substring(0, values.length - 1)
}

function setBackgroundImage(of, to)
{
	of.style.backgroundImage = 'url('+ to + ')';

}

function saveSearch(groupName)
{
	var url="InlineJustis.aspx?ss=search&group=" + groupName + "&cb=" + Math.random();
	http=getHttpObject();
		
	http.onreadystatechange = MyJustisReadyStateChange
	http.open("GET", url , true) 
	http.send(null)
	
	alert('Search saved to My Justis');
}

function saveDocument(groupName)
{
	var url="InlineJustis.aspx?sd=document&group=" + groupName + "&cb=" + Math.random();
	http=getHttpObject();
		
	http.onreadystatechange = MyJustisReadyStateChange
	http.open("GET", url , true) 
	http.send(null)
	
	alert('Document saved to My Justis');
}

function getUserGroups()
{
	var url="InlineJustis.aspx?a=GetGroups&cb=" + Math.random();
	http2=getHttpObject();
		
	http2.onreadystatechange = ReadyStateGroups
	http2.open("GET", url , true) 
	http2.send(null)
}

function getAlert(UserTrailID)
{
	//alert(UserTrailID);
	var url="InlineJustis.aspx?a=GetAlert&id=" + UserTrailID + "&cb=" + Math.random();
	http2=getHttpObject();
		
	http2.onreadystatechange = ReadyStateAlert
	http2.open("GET", url , true) 
	http2.send(null)
}

function getDetails(UserTrailID)
{
	//alert(UserTrailID);
	var url="InlineJustis.aspx?a=GetDetails&id=" + UserTrailID + "&cb=" + Math.random();
	http2=getHttpObject();
		
	http2.onreadystatechange = ReadyStateDetail
	http2.open("GET", url , true) 
	http2.send(null)
}


function ReadyStateAlert()
{
	if ( http2.readyState == 4 )
	{
		var alert = eval("( [" + http2.responseText + " ])") ;
		
		if (alert.length == 0)
			return;
		
		document.getElementById('AlertRecipients').value = alert[0].Recipients;
		document.getElementById('AlertSubject').value = alert[0].Subject;
		document.getElementById('MaxResults').value = alert[0].MaxResults;
		
		document.getElementById("alertformloading").style.display = 'none'
		document.getElementById("alertform").style.display = 'block'
	}
}

function ReadyStateDetail()
{
	if ( http2.readyState == 4 )
	{
		var details = eval("( [" + http2.responseText + " ])") ;
		
		document.getElementById('ItemSearchString').value = ""
		document.getElementById('ItemDatabases').value = ""
		document.getElementById('ItemName').value = ""
		document.getElementById('AlertRecipients').value = ""
		document.getElementById('AlertSubject').value = ""
		document.getElementById('MaxResults').value = ""
		
		if (details.length == 0)
			return;
			
		var star = document.getElementById('star' + details[0].Line.Item.TrailId);
		var alerting = document.getElementById('alert' + details[0].Line.Item.TrailId);
	
		if (alerting && alerting.src.indexOf('alert_selected.gif') >= 0 ) 
		{
			document.getElementById('alerting').style.display = 'block';
		}
		else
		{
			document.getElementById('alerting').style.display = 'none';
		}
	
		GenToolbar(details, star, alerting);
	
		
		if(details[0].Line.Item)
		{
			if(details[0].Line.Item.SearchString)
				document.getElementById('ItemSearchString').value = details[0].Line.Item.SearchString.replace('&amp;','&');
			if(details[0].Line.Item.Datasources)
				document.getElementById('ItemDatabases').value = details[0].Line.Item.Datasources.replace('&amp;','&');

			if(details[0].Line.Item.FriendlyName)
				document.getElementById('ItemName').value = details[0].Line.Item.FriendlyName.replace('&amp;','&');
			else if(details[0].Line.Item.Name)
				document.getElementById('ItemName').value = details[0].Line.Item.Name.replace('&amp;','&');
		}
		
		if(details[0].Line.Alert)
		{
			document.getElementById('AlertRecipients').value = details[0].Line.Alert.Recipients;
			document.getElementById('AlertSubject').value = details[0].Line.Alert.Subject;
			document.getElementById('MaxResults').value = details[0].Line.Alert.MaxResults;
		}
			
		document.getElementById("alertformloading").style.display = 'none'
		document.getElementById("alertform").style.display = 'block'
		
		document.getElementById("itemformloading").style.display = 'none'
		document.getElementById("itemform").style.display = 'block'
				
	}
}

function ReadyStateGroups()
{
	if ( http2.readyState == 4 )
	{
		//alert(http2.responseText);
	
		var groups = eval("( [" + http2.responseText + " ])") ;
		
		if ( !groups || !groups.length || groups.length < 0 )
			return;
		
		var divGroups = document.getElementById('groups');
		var dropGroups = document.getElementById('groupsSelect');
		
		var htmlGroups = "Filter By Client Codes"
		
		//var htmlGroupsDropDown = "<option value=\"\">Client Code Actions</option><option value=\"\" disabled=\"disabled\">-----------------------------</option><option value=\"new\">Apply New Client Code</option><option value=\"remove\">Delete Client Code</option><option value=\"-1\">Clear Client Code</option><option value=\"\" disabled=\"disabled\">-----------------------------</option><option value=\"\" disabled=\"disabled\">Apply Existing Client Codes</option>";	
		
		dropGroups.innerHTML = "";
		
		dropGroups.options[dropGroups.options.length] = new Option("Client Code Actions", "");
		dropGroups.options[dropGroups.options.length-1].disabled = true;
		dropGroups.options[dropGroups.options.length-1].style.color = "#999999";
		dropGroups.options[dropGroups.options.length] = new Option("-----------------------------", "");
		dropGroups.options[dropGroups.options.length-1].disabled = true;
		dropGroups.options[dropGroups.options.length-1].style.color = "#999999";
		dropGroups.options[dropGroups.options.length] = new Option("Apply New Client Code", "new");
		dropGroups.options[dropGroups.options.length] = new Option("Delete Client Code", "remove");
		dropGroups.options[dropGroups.options.length] = new Option("Clear Client Code", "-1");
		dropGroups.options[dropGroups.options.length] = new Option("-----------------------------", "");
		dropGroups.options[dropGroups.options.length-1].disabled = true;
		dropGroups.options[dropGroups.options.length-1].style.color = "#999999";
		dropGroups.options[dropGroups.options.length] = new Option("Apply Existing Client Codes", "");
		dropGroups.options[dropGroups.options.length-1].disabled = true;
		dropGroups.options[dropGroups.options.length-1].style.color = "#999999";
		
		for (i = 0; i<groups.length;i++)
		{			
			dropGroups.options[dropGroups.options.length] = new Option("    " + groups[i].GroupName, groups[i].GroupName);
			htmlGroups += "<div><a href=\"myjustis.aspx?my=mytrail&amp;group=" + groups[i].GroupID + "\">" + groups[i].GroupName + "</a></div>"					
			//htmlGroupsDropDown += "<option value=\"" + groups[i].GroupName  + "\">&nbsp;&nbsp;&nbsp;&nbsp;" + groups[i].GroupName + "</option>"
		}

		if (groups.length == 0)
		{
			dropGroups.options[dropGroups.options.length] = new Option("No Client Codes defined","");
			//htmlGroupsDropDown += "<option selected value=\"\">No Client Codes defined</option>";
			dropGroups.disabled = "disabled";
		}
		else
		{
			dropGroups.disabled = ""; 
		}
		
		htmlGroups += "<div style=\"text-align:right;margin-top:10px;\"><a href=\"javascript:;\">Delete Client Codes</a></div> "
					
		divGroups.innerHTML = htmlGroups;
		//dropGroups.innerHTML = htmlGroupsDropDown;
	}
}

var http;
var http2;
var statusTimeout;

	function updateAlerts(id, value)
	{
		var url="InlineJustis.aspx?id=" + id + "&alert=" + value
		http=getHttpObject();
		
		http.onreadystatechange = MyJustisReadyStateChange
		http.open("GET", url , true) 
		http.send(null)
	}

	function saveAlert(id, recipients, subject, maxResults)
	{
		var url="InlineJustis.aspx?id=" + id + "&rec=" + recipients + "&sub=" + subject + "&max=" + maxResults
		http=getHttpObject();
		
		http.onreadystatechange = MyJustisReadyStateChange
		http.open("GET", url , true) 
		http.send(null)
	}

	function updateStars(id, value)
	{
		var url="InlineJustis.aspx?id=" + id + "&starred=" + value
		http=getHttpObject();
		
		http.onreadystatechange = MyJustisReadyStateChange
		http.open("GET", url , true) 
		http.send(null)
	}

	function update(id, string)
	{		
		var url="InlineJustis.aspx?id=" + id + "&name=" + string
		http=getHttpObject();
		
		http.onreadystatechange = MyJustisReadyStateChange
		http.open("GET", url , true) 
		http.send(null)
	}

	function updateGrouping(ids, groupName)
	{	
		if (groupName == "" || ids == "" && groupName != "remove")
		{
			if (ids == "")
				alert('Use the checkboxes to select what you want to apply or remove a client code from.');
			
			if (groupName == "")
				alert('Invalid client code.');
			
			return 
		}
		else if (groupName == "new")
		{
			groupName = prompt("Enter a new client code.");
		}
		else if (groupName == "remove")
		{
			window.location = "myjustis.aspx?my=clientcodes"
			return;
		}
		
		
		if (groupName != null)
		{
			var url="InlineJustis.aspx?ids=" + ids + "&group=" + groupName
			http=getHttpObject();
		
			http.onreadystatechange = MyJustisReadyStateChange
			http.open("GET", url , true) 
			http.send(null)
		}
	}
	
	function deleteGroups(groupids)
	{
		if (groupids != null)
		{
			var url="InlineJustis.aspx?a=removegroup&groupids=" + groupids
			http=getHttpObject();
		
			http.onreadystatechange = MyJustisReadyStateChange
			http.open("GET", url , true) 
			http.send(null)
		}
		else
		{
			alert("Please check the client code(s) you want to remove");
		}
	}
	
	function hideRows()
	{
		selected = getCheckedValues().split(',');
		
		if (selected == "")
			return;
		
		for (i=0; i < selected.length; i++)
		{
			
			document.getElementById("Group"+selected[i]).style.display = 'none';
		}
	}
	
	function updatePreference( pk, pv )
	{
		if (pv == false) { pv = 'N' }
		if (pv == true) { pv = 'Y' }
		
		var url="InlineJustis.aspx?pk=" + pk + "&pv=" + pv + "&cb=" + Math.random()
		http=getHttpObject();
		
		http.onreadystatechange = MyJustisReadyStateChange
		http.open("GET", url , true) 
		http.send(null)
	}
	
	function resetPreferences( rp )
	{
		var url="InlineJustis.aspx?rp=" + rp + "&cb=" + Math.random()
		http=getHttpObject();
		
		http.onreadystatechange = MyJustisReadyStateChange
		http.open("GET", url , true) 
		http.send(null)
	}
	
	function MyJustisReadyStateChange()
	{
		if ( http && http.readyState == 4 )
		{
			document.getElementById('status').innerHTML = '';
			eval(http.responseText);
		}
	}
	
	function getHttpObject()
	{
		if (window.XMLHttpRequest) 
		{
			xhttp = new XMLHttpRequest();
		} // branch for IE/Windows ActiveX version
		else if (window.ActiveXObject) 
		{
			xhttp = new ActiveXObject("Microsoft.XMLHTTP"); 	
		}	
		
		return xhttp;
	}
