/* Javascript for inclusion in Dashboard page */

function bodyLoaded()
{
	var contentPane=document.getElementById("contentPane");
	if (contentPane==null) return;
	
	if(maxCols<=0) maxCols=3;
	if(maxRows<=0) maxRows=3;
	curRows=maxRows;
	
	buildLayoutOptions();

	/*Auto size items to fit available area unless size explicitly set*/
	if(itemWidth<=0)
	{
		var w=contentPane.clientWidth;
		//if (!g_isIE) w-=getScrollBarWidth(); // issue 3662
		itemWidth = Math.floor((w - (itemSpacing*(maxCols-1))) / maxCols);
		if (itemWidth<minItemWidth) itemWidth=minItemWidth;
	}
	if(itemHeight<=0)
	{
		var headerHeight = document.getElementById("headerRow").clientHeight;
		var contextHeight = 0;
		if (document.getElementById("contextRow")!=null) contextHeight = document.getElementById("contextRow").clientHeight;
		var h=document.getElementById("theBody").clientHeight-headerHeight-contextHeight - 1;

		if (g_dashSelMode == "Tabbed")
		{
			if (document.getElementById("dashTabsPlaceholder") != null) h -= (document.getElementById("dashTabsPlaceholder").clientHeight + 1);
		}

		itemHeight = Math.floor((h - (itemSpacing*(maxRows-1))) / maxRows);
		if (itemHeight < minItemHeight) itemHeight = minItemHeight;
		
	}

	dif_bringSelectedIframeToTop(true);
	dif_allowDragOffScreen(false);
	doResize();

	loadItems();
}

function addAll ()
{
	removeAll();
	setStatus("addAll");			
	var e =document.getElementById("selDbItem");
	e.disabled=true;
	var delayMs=loadDelayMs;
	var cnt=0;
	var max = maxCols*maxRows;
	
	for (var i=0; i<e.options.length; i++)
	{
		var o=e.options[i];
		var v=o.value;
		if (v!=null && v.length!=0 && v.indexOf("(")==-1)
		{
			//showItem(v,null,false,true);
			window.setTimeout("showItem('" + v + "', null, false, true);", (cnt++)*delayMs);
			if (cnt>=max) break;
		}
	}

	window.setTimeout("saveAfterLoad=true; afterLoad(); document.getElementById('selDbItem').disabled=false;", cnt*delayMs);
}

function removeAll ()
{
	setStatus("removeAll");
	var e =document.getElementById("selDbItem");
	e.disabled=true;
	var delayMs=removeDelayMs;
	var delay=0;
	for (var i=0; i<=iframeNo; i++)
	{
		var frameid="itemframe"+i;
		removeItem(frameid, false);
	}
	setStatus("removedAll");	
	doSave(false,false,true);
	e.disabled=false;
}

function setIsDraggingItems(tf)
{
	draggingItems=tf;

	if (draggingItems)
	{
		var e=document.getElementById("selDbItem");
		if (e!=null) e.disabled='true';
	}
	else
	{
		var e=document.getElementById("selDbItem");
		if (e!=null) e.disabled='';
		doSave();
	}
}

function checkGrid()
{
	while (curRows>1)
	{
		var itemY=(curRows-1)*(itemHeight+itemSpacing);

		var found=false;
		for(var gX=0; gX<maxCols; gX++)
		{
			itemX=gX*(itemWidth+itemSpacing);
			if(isItemAt(itemX,itemY))
			{
				found=true;
				break;
			}
		}

		if (found==false && removeRows)
		{
			// Remove row
			curRows--;
			doResize();
		}
		else
		{
			break;
		}
	}
}

function showItem(p_itemId, p_order, p_doSave, p_silent)
{
	var gX=0, gY=0, itemX=0; itemY=0;
	if (p_order!=null)
	{
		for (var i=1; i<p_order; i++)
		{
			gX++;
			if (gX>=maxCols) {gX=0; gY++;}
		}
		itemX=gX*(itemWidth+itemSpacing);
		itemY=gY*(itemHeight+itemSpacing);
	}
	else
	{
		do
		{
			if (gY>=maxRows)
			{
				if (p_silent==null || p_silent==false)
				{
					alert(g_msg_dash_MaximumItemsDisplayed_Line1 + "\n" + g_msg_dash_MaximumItemsDisplayed_Line2);
				}
				return false;
			}

			itemX=gX*(itemWidth+itemSpacing);
			itemY=gY*(itemHeight+itemSpacing);
			if(isItemAt(itemX,itemY) == false) break;
			gX++;
			if (gX>=maxCols) {gX=0; gY++;}
		}
		while(true);
	}

	if (gY >= curRows)
	{
		var addRows=gY-curRows+1;
		curRows+=addRows;
		doResize();
	}

	iframeNo++;
	var frameid="itemframe"+iframeNo;

	var page = "ItemPage.aspx";
	page+="?frameid="+frameid;
	page+="&itemid="+ p_itemId;
	page+="&dashboardid="+ document.db_page.dashboardid.value;
	page+="&dashcontextid="+ document.db_page.dashcontextid.value;
	//alert(page);

	var e = document.createElement("iframe");
	e.id=frameid;
	e.name=frameid;
	e.scrolling="no";
	e.src=page;
	e.style.height=itemHeight+"px";
	e.style.width=itemWidth+"px";
	e.style.position='absolute';
	e.style.left=itemX+"px";
	e.style.top=itemY+"px";
	// record original position of item incase need to swap 2 items (don't use e.style.origleft and e.style.origtop - firefox)
	e.origleft=e.style.left;
	e.origtop=e.style.top;
	e.dbitemid=p_itemId;
	e.frameborder="0";
	e.style.border="0";

	var dbe=document.getElementById("dbElements");
	dbe.appendChild(e);

	if (p_doSave!=null && p_doSave==true)
	{
		doSave();
	}
}

function removeItem(frameid, p_doSave)
{
	//alert("removeItem="+frameid);
	var e = document.getElementById(frameid);
	if (e!=null)
	{
		var dbe=document.getElementById("dbElements");
		dbe.removeChild(e);

		checkGrid();
		if (p_doSave!=null && p_doSave==true)
		{
			doSave();
		}
	}
}

// New Dashboard selected by user
// (change location rather than submit form to allow broser F5 action without warning)
function showDashboard(dashboardId)
{
	var f = document.db_page;
	var contextId = document.db_page.dashcontextid.value;
	window.location = g_PageName + "?dashboardid=" + dashboardId + "&dashcontextid=" + contextId + "&resetFilt=true";
}

// New grid layout selected by user
// (change location rather than submit form to allow broser F5 action without warning)
function onChgLayout(dd)
{
	var f = document.db_page;
	var contextId = document.db_page.dashcontextid.value;
	var dashboardId = document.db_page.dashboardid.value;
	var layout = dd.value;
	window.location = g_PageName + "?dashboardid=" + dashboardId + "&dashcontextid=" + contextId + "&chgLayout=" + layout;
}

function afterLoad()
{
	var applyBut = document.getElementById("FiltersApply");
	if (applyBut != null) applyBut.disabled = false;
	
	isLoading=false;
	setStatus("loaded");
	if (saveAfterLoad)
	{
		saveAfterLoad=false;
		doSave();
	}

	if (refreshIntervalSecs>0)
	{
		refreshCoundownSecs=refreshIntervalSecs;
		if (oiauto!=null) clearInterval(oiauto);
		oiauto = setInterval('autoRefreshCountdown()' , 1000);
	}
}

// display countdown until auto-refresh and do refresh when 0 reached
function autoRefreshCountdown()
{				
	if ("loading"==g_status || "addAll"==g_status || oiauto==null)
	{
		refreshCoundownSecs=refreshIntervalSecs;
		return;
	}

	refreshCoundownSecs--;
	if (refreshCoundownSecs==0)
	{
		//document.db_page.submit();
		refreshAllItems();
		return;
	}

	var secs=refreshCoundownSecs;
	var hours = Math.floor(secs/3600);
	secs -= hours*3600;
	var mins = Math.floor(secs/60);
	secs -= mins*60;

	if (refreshCoundownSecs<=15)
	{
		var s=g_msg_dash_AutoRefreshIn;
		s+=" " + refreshCoundownSecs;
		dispStatus(s);	
	}
}

function setStatus(s)
{
	g_status = s;

	var show = s;
	if ("saving"==s) show=g_msg_dash_SavingLayout;
	else if ("saved"==s) show=g_msg_dash_LayoutSaved;
	else if ("loading"==s)
	{
		var e =document.getElementById("selDbItem");
		if (e!=null) e.disabled=true;
		show=g_msg_dash_LoadingDashboard;
	}
	else if ("loaded"==s)
	{
		var e =document.getElementById("selDbItem");
		if (e!=null) e.disabled=false;
		show=g_msg_dash_DashboardLoaded;
	}
	else if ("addAll"==s) show=g_msg_dash_AddingItems;
	else if ("removeAll"==s) show=g_msg_dash_RemovingItems;
	else if ("removedAll"==s) show="";

	dispStatus(show);
}

function dispStatus(s)
{
	window.status=s;
}

// Save layout to cookie
// 
// Format: "#" + dashboardId + ":" + dashItems + ":" + gridSize + "#"...
// dashItems = comma separated list of item ids (-1 = no item)
// gridSize = XxY e.g. 3x2
function doSave(p_forceSave, p_quietSave, p_removedAll)
{
	if (p_forceSave==null) p_forceSave=false;
	if (p_quietSave==null) p_quietSave=false;
	if (p_removedAll==null) p_removedAll=false;
	
	var dashboardId = document.db_page.dashboardid.value;
	if (dashboardId==null || dashboardId.length==0) return;
	if (isLoading)
	{
		saveAfterLoad=true;
		return;
	}
	if (draggingItems) return false;

	// Get all layouts saved from cookie value
	var curLayouts = getCookie("dashboardLayout");
	if (curLayouts==null) curLayouts="";
	var splitCurLayouts = curLayouts.split("#");
	
	// Get prefix of current dashboard layout string in layouts
	var thisDashPrefix = dashboardId + ":";
	
	// Get currently saved item layout for this dashboard (if any)
	var dashItems=new Array();
	if (!p_removedAll) // if all Items removed then start with blank layout for dashbaord
	{
		for (var i=0; i<splitCurLayouts.length; i++)
		{
			var dl = splitCurLayouts[i];
			var splitElements = dl.split(":");
			if (splitElements.length >=2 && splitElements[0]==dashboardId)
			{
				dashItems=splitElements[1].split(",");
				//alert("dashItems=" + dashItems);
			}
		}
	}
	
	// Update currently saved item layout for this dashboard
	// (If currently saved Layout contains more Items then keep layout of these incase larger layout grid is chosen)
	var gX=0, gY=0, itemX=0; itemY=0;
	var pos=0;
	while(true)
	{
		if (gY>=maxRows) break;
		itemX=gX*(itemWidth+itemSpacing);
		itemY=gY*(itemHeight+itemSpacing);
		var item=getItemAt(itemX,itemY);
		var saveItemId=(item!=null ? item.dbitemid : "-1"); // -1 = blank item
		dashItems[pos]=saveItemId;
		pos ++;
		gX++;
		if (gX>=maxCols) {gX=0; gY++;}
	}
	//alert("new dashItems=" + dashItems);

	// Get Dashboard grid size e.g. 4x3
	var gridSize=maxCols + "x" + maxRows;
  // construct Layout string for this dashboard
	var thisDashLayout = dashboardId + ":" + dashItems + ":" + gridSize;
	//alert("thisDashLayout=" + thisDashLayout);
	
	// Save layout (if changed) with other layouts in a cookie (for a year)
	var save=true;
	var newLayouts = "#" + thisDashLayout;
	var maxLayouts=10; // only store last 10 dashboard layouts
	var cntLayouts=1;

	// get all other dashboard layouts saved and check if current dashboard layout has changed
	for (var i=0; i<splitCurLayouts.length; i++)
	{
		var dl = splitCurLayouts[i];
		if (dl==null || dl.length==0) continue;
		if (!p_forceSave && dl==thisDashLayout)
		{
			// don't save if this dashboard layout hasn't changed
			save=false;
			break;
		}
		else if (dl.indexOf(thisDashPrefix)!=0)
		{
			if (cntLayouts<maxLayouts)
			{
				newLayouts += "#" + dl;
				cntLayouts++;
			}
		}
	}
	
	if (save)
	{
		if (!p_quietSave) setIsSavingLayout(true);
		var expires=new Date();
		expires.setFullYear(expires.getFullYear() + 1);
		setCookie("dashboardLayout", newLayouts, expires);
		if (!p_quietSave) setIsSavingLayout(false);

		// check if saved
		if (newLayouts!=getCookie("dashboardLayout")) dispStatus(g_msg_dash_LayoutErrorSaving);
		
		//dispStatus("cntLayouts=" + cntLayouts + ", len=" + newLayouts.length + ", cookielen=" + getCookie("dashboardLayout").length);
	}	

	return false;
}

function setIsSavingLayout(tf)
{
	savingLayout=tf;

	if (savingLayout)
	{
		var e=document.getElementById("selDbItem");
		if (e!=null) e.disabled='true';

		setStatus("saving");
	}
	else
	{
		var e=document.getElementById("selDbItem");
		if (e!=null) e.disabled='';
		setStatus("saved");
	}
}

function getItemAt(x,y)
{
	x=x+"px";
	y=y+"px";
	for (var i=1; i<=iframeNo; i++)
	{
		var id="itemframe"+i;
		var e = document.getElementById(id);
		if (e!=null && e.style.left==x && e.style.top==y) {return e;}
	}
	return null;
}

function isItemAt(x,y)
{
	x=x+"px";
	y=y+"px";
	for (var i=1; i<=iframeNo; i++)
	{
		var id="itemframe"+i;
		var e = document.getElementById(id);
		if (e!=null && e.style.left==x && e.style.top==y) {return true;}
	}
	return false;
}

function getCumulativeOffset(element)
{
	var t=0,l=0;
	do
	{
		t+=element.offsetTop||0;
		l+=element.offsetLeft||0;
		element=element.offsetParent;
	}
	while (element);
	return [l,t];
}

function doResize()
{
	itemsCellWidth= (maxCols * itemWidth) + ((maxCols-1) * itemSpacing);
	itemsCellHeight= (curRows * itemHeight) + ((curRows-1) * itemSpacing);
	contentPaneWidth=itemsCellWidth;
	contentPaneHeight=itemsCellHeight;

	var e=document.getElementById("contentPane");
	e.width=contentPaneWidth;

	var e=document.getElementById("itemsCell");
	e.height=itemsCellHeight;

	dif_setGridSize(itemWidth+itemSpacing, itemHeight+itemSpacing);
	dif_setWinSize(itemsCellWidth+itemSpacing,itemsCellHeight+itemSpacing);
}

function toggleHold()
{
	if ("loading"==g_status || "addAll"==g_status || refreshIntervalSecs==0) return;

	var stext = document.getElementById("ahold");				
	if(oiauto!=null)
	{
		clearInterval(oiauto);
		oiauto=null;
		//stext.innerHTML = "Manual";
		stext.className = "dbheadlink autoLinkOff";
		dispStatus(g_msg_dash_AutoRefreshOff);
	}
	else
	{
		refreshCoundownSecs=refreshIntervalSecs;
		if (oiauto!=null) clearInterval(oiauto);
		oiauto = setInterval('autoRefreshCountdown()' , 1000);
		stext.className = "dbheadlink";
		dispStatus(g_msg_dash_AutoRefreshOn);
	}
}

function refreshAllItems()
{
	if ("loading"==g_status || "addAll"==g_status) return;

	setStatus("loading");
	var delayMs=loadDelayMs;
	var delay=0;
	for (var i=0; i<window.frames.length; i++)
	{
		var f=window.frames[i];
		if (f.refresh!=null)
		{
			window.setTimeout("if (window.frames[" + i + "]!=null && window.frames[" + i + "].refresh!=null) window.frames[" + i + "].refresh()", (delay++)*delayMs);
		}
	}
	window.setTimeout("afterLoad();", delay*delayMs);
}

function LogOut()
{
	/* logout and close window without javascript warning (IE only) */
	window.open("Dologout.aspx?action=close", "_self");
}

// Dropdown with XxY layout options
function buildLayoutOptions()
{
	var dd=document.getElementById("layout");
	if (dd==null) return;

	//Build options
	var options=dd.options;
	for(var x=1; x<=4; x++)
	{
		for(var y=1; y<=4; y++)
		{
			var layout=x + "x" + y;
			options[options.length] = new Option(layout,layout);
		}
	}
	
	//Set Selected option
	var curLayout=maxCols + "x" + maxRows;
	dd.value=curLayout;
	//Add option to list if necessary
	if (dd.selectedIndex==-1 || options[dd.selectedIndex].value != curLayout)
	{
		options[options.length] = new Option(curLayout,curLayout);
		dd.value=curLayout;
	}
}

// Tell Dashboard when drag starts/ends
function setDragging(tf)
{	
	// If begin drag then enable hidden div covering each Item
	// (Prevents any iframes embedded in Items from stopping dragiframe code from working)
	for (var i=0; i<window.frames.length; i++)
	{
		var f=window.frames[i];
		if (f.g_isItem!=null && f.g_isItem)
		{
			//if (f.g_isBeingDragged) continue;
			var e=f.document.getElementById("dragCover");
			if (e!=null) e.style.display=(tf ? "block" : "none");			
		}
	}
}

function toggleSupportInfo()
{
	var i=document.getElementById('SupportInfo');
	var d=document.getElementById('SupportInfoDimmer');
	if (i==null || d==null) return;

	var isDisp = ("block" == i.style.display);
	
	if (isDisp) i.style.display = d.style.display = "none";
	else i.style.display = d.style.display = "block";
}

function DashTabs_Click(oWebTab, oTab, oEvent)
{
	showDashboard(oTab.Key);
}


function DashFltEnableAllBtns()
{
	$(".dbFilterPanel input").attr('disabled', '');
	$(".dbFilterPanel select").attr('disabled', '');
	$(".dbFilterButtons input").attr('disabled', '');
}

function DashFltDisableAllBtns()
{
	$(".dbFilterPanel input").attr('disabled', 'true');
	$(".dbFilterPanel select").attr('disabled', 'true');
	$(".dbFilterButtons input").attr('disabled', 'true');
}

// Update Dashboard filters area (when filter changed)
function DashFltUpdFiltersArea(sender)
{
	DashFltShowPleaseWait();

	//dont update filters if apply button clicked.
	if (sender.id != 'FiltersApply')
	{
		setTimeout("__doPostBack('UpdatePanelFilters','');", 600);
	}
}

// Show wait message when dashboard filter panel being updated
function DashFltShowPleaseWait()
{
	$('.loadingPanel').css('display', 'inline');
	$(".DashFiltDisablePanel").css('display', 'block');
}

var qs = false;
//var link = "http://www.dynistics.com/dashboardcontact.aspx";
var link = 'http://www.dynistics.com/ContactForm.aspx';
function loadContact()
{
    if(qs==false)
    {
        
        var query = window.location.search.substring(1);
        var x = query.indexOf('visitor');
        if(x>0)
        {
            if(query.length >= x+32)
            {
                query = query.substring(x+1,x+32);
                link += '?V' + query;
                qs = true;
            }
        } 
    }
}

function OpenContact()
{
	openCenteredWindow("_blank", 470, 650, link);
}