window.onload = prep;

var isIE = (navigator.userAgent.indexOf("MSIE") > 0);

function prep()
{
	prepQuestions();
	
	if (window.prepButtons)
	{
		prepButtons();
	}
	
	loadOverlay();
	
	if (window.loadMore)
	{
		loadMore();
	}
}

function openPopup(id, results)
{
	var loc = "diabetes.org";
	if (window.location.hostname.indexOf("stage") > -1) loc = "diabetes-v1.stage.imc2.com";
	if (window.location.hostname.indexOf("dev") > -1) loc = "diabetes-v1.dev.imc2.com"; 
	
	
	if (!id)
	{		
		//window.open("cmrm/index.jsp", "", "height=599,width=830,status=1,resizable=0,scrollbars=1");
		window.open(window.location.protocol + "//myhealthadvisor." + loc + "/cmrm/index.jsp", "", "height=599,width=830,status=1,resizable=0,scrollbars=1");
	}
	else
	{
		//window.open("/mha/questions-reload.do?id=" + id, "", "height=599,width=830,status=1,resizable=0,scrollbars=1");
		window.open(window.location.protocol + "//myhealthadvisor." + loc + "/mha/questions-reload.do?id=" + id, "", "height=599,width=830,status=1,resizable=0,scrollbars=1");
	}
	
	return false;
}

function openPdf(path)
{
	var w = window.open(path, "", "height=600,width=800,status=1,resizable=0,scrollbars=1");
	
	return false;
}

function openLaunchPage()
{
	if (self.opener.location.href == "http://10.100.1.180/index.jsp")
	{
		self.opener.focus();
		
		return false;
	}
	else
	{
		return true;
	}
}

function prepQuestions()
{
	var divs = document.getElementById("content").getElementsByTagName("div");
	
	for (var j = 0; j < divs.length; j++)
	{
		if (divs[j].className.indexOf("choices") == 0)
		{
			var inputs = divs[j].getElementsByTagName("div");
			
			// if the input is selected (FF refresh? or redirect with errors), make sure the button looks correct
			
			for (var i = 0; i < inputs.length; i++)
			{
				/*if (false && divs[j].className.indexOf("checkbox") > 0 && divs[j].className.indexOf("small") < 0) // just in case the code is needed later
				{
					inputs[i].onclick = toggleButton;
				}
				else*/
				{
					inputs[i].onclick = toggleButton;
					
					if (isIE)
					{
						//inputs[i].getElementsByTagName("span")[0].onclick = toggleButton; // the span shows through the label, and its onclick is not triggered, otherwise
						inputs[i].onmouseover = function () {if (this.className == "") this.className = "hover";};
						inputs[i].onmouseout = function () {if (this.className == "hover") this.className = "";};
					}
				}
			}
			
			inputs = divs[j].getElementsByTagName("input");
			
			for (var i = 0; i < inputs.length; i++)
			{
				if (inputs[i].checked)
				{
					inputs[i].parentNode.className = "selected";
				}
			}
		}
	
		// work-around for IE z-index bug
		// tried CSS work-around, but not much luck
		// http://randsco.com/index.php/2005/09/11/changing_z_index_on_hover#sol060510
	
		//if (isIE)
		{
			divs[j].parentNode.style.zIndex = 5000 - j;
		}
	}
	
	var labels = document.getElementsByTagName("label");
	
	for (var j = 0; j < labels.length; j++)
	{
		if (labels[j].className == "checkbox")
		{
			labels[j].previousSibling.className = "checkbox";
			
			labels[j].onclick = function()
				{
					
					this.className = (this.previousSibling.checked ? "checkbox" : "checkbox checked checkbox-checked");
					
					//if (navigator.userAgent.indexOf("WebKit") >= 0) this.previousSibling.checked = !this.previousSibling.checked; // for Safari
				};				
				
			if (labels[j].previousSibling.checked)
			{
			
				labels[j].className = "checkbox checked checkbox-checked";
			}
		}
	}
}

function toggleButton(e)
{
	if (!e) e = window.event;
	
	e.cancelBubble = true;
	if (e.stopPropagation) e.stopPropagation();
	
	// check if this is an element passed in; is there a way to check for an element type, instead of event type?
	if (e.srcElement || e.target)
	{
		e = (window.event) ? e.srcElement : e.target;
	}
	
	if (e.tagName.toUpperCase() == "A")
	{
		if (e.previousSibling.type.toUpperCase() == "CHECKBOX")
		{
			e.previousSibling.checked = !e.previousSibling.checked;
		}
		else
		{
			e.previousSibling.checked = true;
		}
		
		e = e.parentNode;
	}
	else if (e.tagName.toUpperCase() == "SPAN")
	{
		if (isIE)
		{
			if (e.parentNode.previousSibling.type.toUpperCase() == "CHECKBOX")
			{
				e.parentNode.previousSibling.checked = !e.parentNode.parentNode.previousSibling.checked;
			}
			else
			{
				e.parentNode.previousSibling.checked = true;
			}
		}
		
		e = e.parentNode.parentNode;
	}
	else if (e.tagName.toUpperCase() == "INPUT")
	{
		return; // this gets triggered after label; only need to do it once
	}
	else // it's a LABEL
	{
		if (isIE)
		{
			if (e.parentNode.parentNode.previousSibling.type.toUpperCase() == "CHECKBOX")
			{
				e.parentNode.parentNode.previousSibling.checked = !e.parentNode.parentNode.previousSibling.checked;
			}
			else
			{
				e.parentNode.parentNode.previousSibling.checked = true;
			}
		}
		
		e = e.parentNode.parentNode.parentNode;
	}
	
	// TODO: figure out a better way of determining this; it probably has something to do with event bubbling
	if (e.className.toUpperCase() == "QUESTION")
	{
		return;
	}
	
	var inputs = e.parentNode.getElementsByTagName("input");
	
	if (e.parentNode.className.indexOf("checkbox") > 0)
	{
		if (e.className == "" || e.className == "hover")
		{
			e.className = "selected";
		}
		else
		{
			e.className = "";
		}
	}
	else
	{
		for (var i = 0; i < inputs.length; i++)
		{
			if (e.id == inputs[i].parentNode.id)
			{
				e.className = "selected";
			}
			else
			{
				inputs[i].parentNode.className = "";
			}
		}
	}
}

function loadOverlay()
{
	var parent = document.getElementById("overlay-container");
	
	var child = document.createElement("a");
	
	child.id = "overlay-back";
	
	child.href="javascript:void(0);"; // for IE to be able to use :hover
	
/*	child.onclick = function (){var box=document.getElementById("privacy-statement");box.parentNode.removeChild(box);if (document.getElementById("flash-results"))document.getElementById("flash-results").style.visibility = "visible";};*/
	child.onclick = resetOverlay; //function (){vis("hidden");document.getElementById("overlay-text").innerHTML = ""};
	
	parent.appendChild(child);
	
	parent = child;
	
	child = document.createTextNode("Close");
	
	parent.appendChild(child);
	
	child = document.createElement("a");
	
	child.id = "overlay-up";
	
	child.href="javascript:void(0);"; // for IE to be able to use :hover
	
	child.onmouseover = scrollUp;
	child.onmouseout = stopScroll;
	
	parent.parentNode.appendChild(child);
	
	child = document.createElement("a");
	
	child.id = "overlay-down";
	
	child.href="javascript:void(0);"; // for IE to be able to use :hover
	
	child.onmouseover = scrollDown;
	child.onmouseout = stopScroll;
	
	parent.parentNode.appendChild(child);
	
	/*if (document.getElementById("flash-results"))
	{
		document.getElementById("flash-results").style.visibility = "hidden";
	}*/
	
}

function resetOverlay()
{
	var x = document.getElementById("overlay-text");
	
	var clipstring = "rect(" + clipTopInit + "px," + clipWidthInit + "px," + clipBottomInit + "px,0px)";
	
	x.style.clip = clipstring;
	
	x.style.top = topperInit + "px";
	
	x.innerHTML = "";
	
	vis("hidden");
	
	clipTop = clipTopInit;
	
	clipWidth = clipWidthInit;
	
	clipBottom = clipBottomInit;
	
	topper = topperInit;
}

var progressTries = 0;
var progressTimeout;
var fakeProgress = 0;

function getProgress()
{
	loadTextDoc("/data/get-job-percent-complete.jsp", displayProgress);
}

function displayProgress(value)
{
	if (value != 100)
	{
		if (value == 0)
		{
			progressTries++;
			
			fakeProgress += Math.floor(Math.random()*3);
			
			fakeProgress = Math.min(fakeProgress, 99);
			
			document.getElementById("results-progress-bar").nextSibling.innerHTML = fakeProgress + "%";
			
			document.getElementById("results-progress-bar").getElementsByTagName("div")[0].style.width = fakeProgress + "%";
			
			if (progressTries > 2)
			{
				getStatus();
			}
		}
		else
		{
			value = Math.max(value, fakeProgress);
			
			document.getElementById("results-progress-bar").nextSibling.innerHTML = value + "%";
			
			document.getElementById("results-progress-bar").getElementsByTagName("div")[0].style.width = value + "%";
		}
		
		progressTimeout = setTimeout("getProgress()", 15000);
	}
	else
	{
		document.location.href = "processed.jsp";
	}
}

function getStatus()
{
	loadTextDoc("/data/get-job-status.jsp", checkStatus);
}

function checkStatus(value)
{
	if (value != "Enabled")
	{
		clearTimeout(progressTimeout);
		
		document.location.href = "failed.jsp";
	}
}

function showPrivacy()
{
	loadTextDoc("/cmrm/media/text/privacy.txt", displayOverlay);
}

function showTerms()
{
	loadTextDoc("/cmrm/media/text/terms.txt", displayOverlay);
}

function scrollUp()
{
	scrollayer('overlay-text', -10,100);
}

function scrollDown()
{
	scrollayer('overlay-text', 10,100);
}

function displayOverlay(text)
{
	document.getElementById("overlay-text").innerHTML = text;
	
	init();
}

function showErrorMessage()
{
	if (document.getElementById("error-box"))
	{
		return;
	}
	
	var parent = document.createElement("div");
	
	parent.id = "error-box";
	
	var root = parent;
	
	var child = document.createElement("div");
	
	parent.appendChild(child);
	
	parent = child;
	
	child = document.createElement("h2");
	
	parent.appendChild(child);
	
	parent = child;
	
	child = document.createTextNode("The information was incomplete or incorrect");
	
	parent.appendChild(child);
	
	parent = parent.parentNode;
	
	child = document.createElement("p");
	
	parent.appendChild(child);
	
	parent = child;
	
	var tempChild = document.createElement("img");
	
	tempChild.src = "/cmrm/media/images/errors/icon.gif";
	
	tempChild.setAttribute("style", "float: left;margin-right: 5px;margin-bottom: 5px;");
	
	parent.appendChild(tempChild);
	
	child = document.createTextNode("The information was incomplete or incorrect. There were errors, which are identified in red. Please fix these errors. You can get more detail by moving your mouse cursor over the icon.");
	
	parent.appendChild(child);
	
	parent = parent.parentNode.parentNode;
	
	child = document.createElement("a");
	
	child.id = "close-errors";
	
	child.href="javascript:void(0);"; // for IE to be able to use :hover
	
	child.onclick = function (){var box=document.getElementById("error-box");box.parentNode.removeChild(box);};
	
	parent.appendChild(child);
	
	parent = child;
	
	child = document.createTextNode("Close");
	
	parent.appendChild(child);
	
	document.body.appendChild(root);
		
	var ps = document.getElementsByTagName("p");
	
	// work-around for IE z-index bug
	// http://randsco.com/index.php/2005/09/11/changing_z_index_on_hover#sol060510
	
	if (isIE)
	{
		for (var j = 0; j < ps.length; j++)
		{
			if (ps[j].className.indexOf("error") == 0)
			{
				ps[j].getElementsByTagName("a")[0].style.zIndex = 6000 - j;
			}
		}
	}
}

function getOffsetTop(obj)
{
  var ret = 0;
  
  if (!obj.id)
  {
  	//obj = document.getElementById(obj);
  }
  
  ret += obj.offsetTop;
  
  while (obj.offsetParent)
  {
    obj = obj.offsetParent;
    ret += obj.offsetTop;
  }
  
  return ret;
}

function getOffsetLeft(obj)
{
  var ret = 0;
  
  if (!obj.id)
  {
  	//obj = document.getElementById(obj);
  }
  
  ret += obj.offsetLeft;
  
  while (obj.offsetParent)
  {
    obj = obj.offsetParent;
    ret += obj.offsetLeft;
  }
  
  return ret;
}

function setCurrent(e)
{
	var sections = document.getElementById("sections").getElementsByTagName("span");
	
	for (var i = 0; i < sections.length; i++)
	{
		if (sections[i].id == "sections-" + e)
		{
			sections[i].className = "current";
			
			if (sections[i].blur)
			{
				sections[i].blur();
			}
			
			document.getElementById(e).style.display = "block";
		}
		else
		{
			sections[i].className = "";
			
			document.getElementById(sections[i].id.substring(9)).style.display = "none";
		}
	}
}

function showPlan()
{
	window.open("/data/chart-data-init.do?Flash=1", "plan", "height=600,width=800,status=1,resizable=1,scrollbars=1");
	//window.open("/cmrm/plan/", "plan", "height=600,width=800,status=1,resizable=1,scrollbars=1");
}

/* http://www.quirksmode.org/js/layerscroll.html */

var clipTopInit = 0;
var clipWidthInit = 625;
var clipBottomInit = 310;
var topperInit = 25;

var clipTop = clipTopInit;
var clipWidth = clipWidthInit;
var clipBottom = clipBottomInit;
var topper = topperInit;

var lyrheight = 0;
var time,amount,theTime,theHeight,DHTML;

function init()
{
	DHTML = (document.getElementById || document.all || document.layers)
	if (!DHTML) return;
	
	// hide from non-IE first...
	if (document.all)
	{
		vis("visible");
	}

	var x = new getObj('overlay-text');
	
	if (document.layers)
	{
		lyrheight = x.style.clip.bottom;
		lyrheight += 20;
		x.style.clip.top = clipTop;
		x.style.clip.left = 0;
		x.style.clip.right = clipWidth;
		x.style.clip.bottom = clipBottom;
	}
	else if (document.getElementById || document.all)
	{
		lyrheight = x.obj.offsetHeight;
		
		var clipstring = 'rect('+clipTop+'px,'+clipWidth+'px,'+clipBottom+'px,0)';
		
		x.style.clip = clipstring;
	}
	
	// ...and from IE last; it needs the visibility to be able to calculate the correct height
	if (!document.all)
	{
		vis("visible");
	}
}

function scrollayer(layername,amt,tim)
{
	if (!DHTML) return;
	thelayer = new getObj(layername);
	if (!thelayer) return;
	amount = amt;
	theTime = tim;
	realscroll();
}

function stopScroll()
{
	if (time) clearTimeout(time);
}

function realscroll()
{
	if (!DHTML) return;
	
	clipTop += amount;
	
	clipBottom += amount;
	
	topper -= amount;
	
	if (clipTop < 0 || clipBottom > lyrheight)
	{
		clipTop -= amount;
		clipBottom -= amount;
		topper += amount;
		return;
	}
	
	if (document.getElementById || document.all)
	{
		clipstring = 'rect('+clipTop+'px,'+clipWidth+'px,'+clipBottom+'px,0)'
		thelayer.style.clip = clipstring;
		thelayer.style.top = topper + 'px';
	}
	else if (document.layers)
	{
		thelayer.style.clip.top = clipTop;
		thelayer.style.clip.bottom = clipBottom;
		thelayer.style.top = topper;
	}
	
	time = setTimeout('realscroll()',theTime);
}

function vis(val)
{
	if (!DHTML) return;
	var f = new getObj('overlay-backdrop');
	f.style.visibility = val;
	f = new getObj('overlay-container');
	f.style.visibility = val;
}

function getObj(name)
{
  if (document.getElementById)
  {
    this.obj = document.getElementById(name);
	this.style = document.getElementById(name).style;
  }
  else if (document.all)
  {
    this.obj = document.all[name];
	this.style = document.all[name].style;
  }
  else if (document.layers)
  {
   	this.obj = document.layers[name];
   	this.style = document.layers[name];
  }
}