/***********************************
    Global JavaScript Functions
************************************/
function common() {
var c;
c.upperCase = CP_select;
return c;
}

function CP_select(x) {
 var y=document.getElementById(x).value;
 alert(y);
}


function selectAllChildren(input, idString)
{
	var ids = new Array();
	var index = idString.indexOf("-");
	var count = 0;
	
	while (index > 0)
	{
		ids[count] = idString.substring(0, index);
		
		idString = idString.substring(index+1);
		count = count + 1;
		
			index = idString.indexOf("-");
		if (index < 0)
			ids[count] = idString;
	}
	
	for (var i = 0; i < ids.length; i++)
	{
		var child = document.getElementById(ids[i]);
		
		if (input.checked == true)
                child.checked = true; 
            
        else 
        	child.checked = false;
	}
}

function movepic(img_name,img_src) 
{
	document[img_name].src=img_src;
}

/****************************
 * popupWindow(url)
 *
 * Opens a new window with the
 * provided URL.
 ****************************/
function popupWindow(myurl, wide, tall)
{
    var WindowArgs = "toolbar=no," + "location=no," + "directories=no," + "status=no,";
    WindowArgs = WindowArgs+"top=10,left=10,scrollbars=yes,resizable=yes,width=" + wide +",height=" + tall;
    window.open(myurl, "EParliament", WindowArgs);
}






/*********************************************
 * popupCalendar(dateField)
 *
 * Opens a new window for the Calendar
 * and the date you choose will be displayed
 * in the dateField.
 *********************************************/
 function popupCalendar(webroot, dateField)
 {    
    w = window.open(webroot + "/common/popUpCalendar.html","calendar","width=200,height=230");
    w.moveTo(window.outerWidth/2-100,window.outerHeight/2-100);
    var d = w.document;
    d.newVar = dateField;
    d.close();
 }
 


/****************************
 * popupWindowWithMenu(url)
 *
 * Opens a new window with the
 * provided URL.
 ****************************/
function popupWindowWithMenu(url)
{
    var WindowArgs = "menubar=yes," + "toolbar=no," + "location=no," + "directories=no," + "status=yes,";
    window.open(url, "CtdbLink", WindowArgs+"top=10,left=10,scrollbars=yes,resizable=yes,width=600,height=400");
}

/****************************
 * popupWindowWithMenuToobar(url)
 *
 * Opens a new window with the
 * provided URL.
 ****************************/
function popupWindowWithMenuToolbar(url)
{
    var WindowArgs = "menubar=yes," + "toolbar=yes," + "location=no," + "directories=no," + "status=yes,";
    window.open(url, "CtdbLink", WindowArgs+"top=10,left=10,scrollbars=yes,resizable=yes,width=600,height=400");
}

/****************************
 * popupWindowWithMenuToobar(url)
 *
 * Opens a new window with the
 * provided URL.
 ****************************/
function popupWindowWithMenuLocationToolbar(url,title)
{
    var WindowArgs = "menubar=yes," + "toolbar=yes," + "location=yes," + "directories=no," + "status=yes,";
    window.open(url, title, WindowArgs+"top=10,left=10,scrollbars=yes,resizable=yes,width=600,height=400");
}

var toggle = "ALL";

/****************************
 * confirmDelete(url, item)
 *
 * Prompts user for a confirmation
 * before attempting to delete
 ****************************/
function confirmDelete(url, item)
{
    ok = confirm("Are you sure you want to remove this " + item + "?");
    if (ok == true)
    {
        window.location = url;
    }
}

/****************************
 * confirmAdmin(url, item, sysadmin)
 *
 * Prompts user for a confirmation
 * before attempting to add or remove
 * admin privileges to a user
 ****************************/
function confirmAdmin(url, item, sysadmin)
{
    if(sysadmin == 'false')
    {
        ok = confirm("Are you sure you want to remove System Administrator Privileges from " + item + "?");
        if (ok == true)
        {
            window.location = url;
        }
    }
    else
    {
        ok = confirm("Are you sure you want to add System Administrator Privileges to " + item + "?");
        if (ok == true)
        {
            window.location = url;
        }
    }
}

/****************************
 * selectAll(thisForm)
 *
 * Selects all checkboxes of
 * the passed in form.
 ****************************/
function selectAll(thisForm)
{       
    for(var i=0; i < thisForm.elements.length; i++)
    {
        var el = thisForm.elements[i];
      
        if(toggle == 'ALL')
            el.checked = true;
        else
            el.checked = false;
    }
 
    toggle = toggle == 'ALL' ? "NONE" : "ALL";
}

/****************************
 * selectAll(thisForm)
 *
 * Selects all options of
 * the passed in form select object.
 ****************************/
function selectAllOptions(obj)
{
    for(var i = 0; i < obj.options.length; i++)
    {
        obj.options[i].selected = true;
    }
}

/****************************
 * sortItems(obj)
 *
 * Sorts items in a select
 * box.
 ****************************/
function sortItems(obj)  
{   var temp_opts = new Array();
    var temp = new Object();
    for (var i=0; i<obj.options.length; i++)
        temp_opts[i] = obj.options[i];
    
    for (var x=0; x<temp_opts.length-1; x++)  
    {   for (var y=(x+1); y<temp_opts.length; y++)  
        {   if(temp_opts[x].text > temp_opts[y].text)  
            {   temp = temp_opts[x].text;
                temp_opts[x].text = temp_opts[y].text;
                temp_opts[y].text = temp;
                temp = temp_opts[x].value;
                temp_opts[x].value = temp_opts[y].value;
                temp_opts[y].value = temp;
            }
        }
    }

    for (var i=0; i<obj.options.length; i++) 
    {   obj.options[i].value = temp_opts[i].value;
        obj.options[i].text = temp_opts[i].text;
    }
} // end function sortItems()

/*******************************************
 * transferItem(source, destination, sort)
 *
 * Transfers items from one select
 * box to a different text box. With 
 * an optional sort flag.
 *******************************************/
function transferItem(source, destination, sort)
{   var i = 0;
    var newitem;
    var retval = false;
        
    while (i < source.options.length)
    {   if (source.options[i].selected) 
        {   
	        var value=source.options[i].value;
	        var duplicate = false;
			for (j=0; j < destination.options.length; j++)
			{
				if (destination.options[j].value == value)
				{ // its a duplicate, dont add it
					duplicate = true;
				}
			} 
			if ( ! duplicate)
			{
	        	newitem = new Option(source.options[i].text, source.options[i].value, 0, 0);
            	destination.options[destination.options.length] = newitem;
            	retval = true;
            	source.options[i] = null;
            } 
            else
            {
	            source.options[i] = null;
	            i = i+1;
            }
        }
        else
            i = i + 1;
    }
    
    // Sort items 
    if(sort == "YES")
        sortItems(destination);
    else
        sortItems(source);
    
    return retval;
} // enf function transferItem()

/*******************************************
 * transferItem(source, sort)
 *
 * Removes an item from a select box
 * With an optional sort flag.
 *******************************************/
function removeItem(source, sort)
{   var i = 0;
    var newitem;
    var retval = false;

    while (i < source.options.length)
    {   if (source.options[i].selected)
        {
            source.options[i] = null;
//            i = i+1;
        }
        else 
            i = i + 1;
    }

    // Sort items
    if(sort == "YES")
        sortItems(source);

    return retval;
} // enf function transferItem()

/*******************************************
 * transferTextItemToSelect(source1, source2, destination, sort)
 *
 * Transfers items from one or two input
 * boxes to a different select box. With
 * an optional sort flag.
 *******************************************/
function transferTextItemToSelect(source1, source2, destination, sort)
{   var i = 0;
    var tmpitem;
    var newitem;
    var retval = false;

    var value1=trimStr(source1.value);
    if(value1 == "")
    {
        alert("Please enter a value to move.");
        return false;
    }

    var duplicate = false;
    for (j=0; j < destination.options.length; j++)
    {
        if (destination.options[j].value == value1)
        { // its a duplicate, dont add it
            duplicate = true;
        }
    }

    var value2 = trimStr(source2.value + "");
    if (value2 == "")
    {
        tmpitem = value1;
    }
    else
    {
        tmpitem = value1 + " : " + value2;
    }

    if (!duplicate)
    {
        newitem = new Option(tmpitem, tmpitem, 0, 0);
        destination.options[destination.options.length] = newitem;
        retval = true;
        source1.value = "";
        source2.value = "";
    }
    else
    {
        source1.value = "";
        source2.vaule = "";
        i = i+1;
    }

    // Sort items
    if(sort == "YES")
        sortItems(destination);

    return retval;
} // enf function transferItem()


/*******************************************
 * swapItm(src, dest)
 *
 * Swaps items up and down in a select box.
 *******************************************/
function swapItem(src, dest)
{   var multiple = 0;
    
    for(index=0; index<src.options.length; index++)
    {   if(src.options[index].selected)
            multiple++;
    }
    
    if(multiple > 1)
        alert("Please select only one item to move.");
    else if(multiple == 0)
        alert("Please select an item to move.");
    else
    {   if(dest == "UP")
        {   if(src.options.length >= 0)
            {   if(src.selectedIndex > 0)
                {   var moveTo = eval(src.selectedIndex - 1);
                    var moveFrom = eval(src.selectedIndex);
                    moveFromItem = new Option(src.options[moveFrom].text,src.options[moveFrom].value);
                    var moveToItem = new Option(src.options[moveTo].text,src.options[moveTo].value);
                    src.options[moveTo] = moveFromItem;
                    src.options[moveFrom] = moveToItem;
                    src.options[moveTo].selected = true;                    
                }
            }
        }
        else
        {   if(src.options.length >= 0)
            {   if(src.selectedIndex < eval(src.options.length - 1))
                {   var moveTo = eval(src.selectedIndex + 1);
                    var moveFrom = eval(src.selectedIndex);
                    moveFromItem = new Option(src.options[moveFrom].text,src.options[moveFrom].value);
                    var moveToItem = new Option(src.options[moveTo].text,src.options[moveTo].value);
                    src.options[moveTo] = moveFromItem;
                    src.options[moveFrom] = moveToItem;             
                    src.options[moveTo].selected = true;                    
                }
            }
        }
    }
} // end function swapItem()

//***************** Image Swapping functions for Navigation
// generated js
function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}
//***************** END image swapping functions for navigation

// Function trims white space from strings
// param str: string to be trimmed
function trimStr(str)
{   var resultStr = "";
    resultStr = trimLeft(str);
    resultStr = trimRight(resultStr);
    return resultStr;
} // end function trimStr()

//trimStr(str) helper functions
function trimLeft(str)
{
    var resultStr = "";
    var i = len = 0;

    if (str+"" == "undefined" || str == null)
        return null;

    str += "";

    if (str.length == 0)
        resultStr = "";
    else
    {
        len = str.length;

        while ((i <= len) && (str.charAt(i) == " "))
            i++;
        resultStr = str.substring(i, len);
     }

     return resultStr;
} // end trimLeft

function trimRight(str)
{
    var resultStr = "";
    var i = 0;

    if (str+"" == "undefined" || str == null)
        return null;

    str += "";

    if (str.length == 0)
        resultStr = "";
    else
    {
          i = str.length - 1;
          while ((i >= 0) && (str.charAt(i) == " "))
             i--;

          resultStr = str.substring(0, i + 1);
    }

    return resultStr;
} // end trimRight


/****************************
 * calculate(inputbox, children, ctype)
 * This matches the business logic for calcuation implemented in the back-end code
 * in InputHandler.java
 *
 * Does calcuations and updates value of inputbox
 ****************************/
function calculate(inputbox, children, ctype)
{
    if( children.length < 2 )
    {
        return;
    }

    // if first child does not have an answer put in and the calculation type is 
    //difference or division, no answer is provided
    if( (ctype == 'Difference' || ctype == 'Division') && 
        (trimStr(document.getElementById(children[0]).value).length == 0) )
    {
        alert("This calculated question with calculation type " + ctype + " has no answer yet.  The first question used for calculation is blank.");
        inputbox.value="";
        return;
    }
    var denominator = 0;
    for( var i = 1; i < children.length; i++)
    {
        if (trimStr(document.getElementById(children[i]).value).length > 0)
        {
        	denominator++;
        }
    }

    if ((ctype == 'Division') && (denominator == 0))
    {
        alert("This calculated question with calculation type " + ctype + " has no answer yet.  The denominator used for calculation is blank.");
        inputbox.value="";
        return;
    }

    var result = 0;
    var count = 0; // count == 0 means result is not set

    var invalidCalculatedType = false;
    for( var i = 0; i < children.length; i++)
    {
        var values = getParameterValues(document.getElementById(children[i]), children[i]);
        // values is an array of strings after trimming

        for( var k = 0; k < values.length; k++)
        {       
            if( count == 0 )
            {
                // result not set yet
                result = Number(values[k]);
            }
            else
            {
                if( (ctype == 'Sum') || (ctype == 'Average') )
                {
                    result += Number(values[k]);
                }
                else if( ctype == 'Difference' )
                {
                    result -= Number(values[k]);
                }
                else if( ctype == 'Multiplication' )
                {
                    result *= Number(values[k]);
                }
                else if( ctype == 'Division' )
                {
                    result /= Number(values[k]);        
                }
                else
                {
                    invalidCalculatedType = true;
                    break;
                }
            }
            count++;
        }
    }

    if( invalidCalculatedType )
    {
        alert("System Error: Invalid calculation type. ");
        inputbox.value="";
        return;
    }

    if( (count != 0) && (ctype == 'Average') )    
    {
        result /= count;
    }

    if( count == 0 )
    { 
        // all blank
        alert ("No value.  Answers used for calculation are blank.");
        inputbox.value="";
        return;
    }

    if( !isFinite(result) )
    {
        alert ("Not numeric.  Answers used for calculation are blank or not numeric or cause division by 0.");
        inputbox.value="";
        return;
    }

    inputbox.value=result;
    return;
}

/****************************
 * Returns an string array containing values of input boxes.
 * Similar to the HTTPServletRequest.getParameterValues().
 * The inputed string is trimmed first.  For multi select and checkboxes, the answer is not 
 * trimmed, assuming options are non blank.
 *
 * @param object The object returned from getElementById.
 * @param strName The name of the objects for use with checkboxes.
 ****************************/
function getParameterValues(object, strName)
{
   var values = new Array();

   if(object.type == "select-multiple")
   {
       for(var i = 0; i < object.options.length; i++) 
       {
           if(object.options[i].selected) 
           {
               values[values.length] = object.options[i].value;
           }
       }
   }
   else if(object.type == "checkbox")
   {
       var objects = document.getElementsByName(strName);
       for( var i = 0; i < objects.length; i++)
       {
           if(objects[i].checked)
           {
               values[values.length] = objects[i].value;
           }
       }
   }
   else
   {
      // single answer
      var value = trimStr(object.value);
      if( value.length > 0 )
      {
          values[values.length] = value;
      }
   }
   return values;
}
/****************************
 * applyskipruleisblank(inputbox, children)
 *
 * apply skiprule of operator type of is blank on the children questions 
 * when setting blank to answers to parent question during editing response  
 * answers on the inputbox.  Only works on checkbox with skip rule of disable.
 ****************************/
function applyskipruleisblank(inputbox, children)
{
	for( var i = 0; i < children.length; i++)
	{
		var child = document.getElementById(children[i]); 
		var reason = "reason_" + children[i].substr(3, children[i].length - 3);

		var reasonArea = document.getElementById(reason);
        if( child != null && reasonArea != null)
        {   	
        	if (inputbox.checked)
        	{
            	child.checked = true;            	
            	reasonArea.value="Skip Rule applies."           	
            }
        	else if (!inputbox.checked)
        	{
            	child.checked = false;
            	reasonArea.value="";
            }
        }
	} 
}
/****************************
 * applyskiprule(inputbox, children, stype, soption, svalue)
 *
 * applyskiprule on the children questions based on the skip options (soption) 
 * and skip values (svalue) check on the inputbox
 ****************************/
function applyskiprule(inputbox, children, stype, soption, svalue)
{
    var inputbox_value = "";
    var hasMultipleValue = false;

    // get value
    var inputbox_name = inputbox.name;
    if( inputbox.type == 'radio' || inputbox.type == 'checkbox' )
    {
        inputboxes = document.getElementsByName(inputbox_name);
        var numSelected = 0;
        for( var i = 0; i < inputboxes.length; i++)
        {
            if( inputboxes[i].checked )
            {
                inputbox_value = inputboxes[i].value;
                numSelected ++;
            }
        }
        if( numSelected > 1 )
        {
            hasMultipleValue = true;
        }
    }
    else if (inputbox.type == 'select')
    {
        for(var i=0; i < inputbox.options.length; i++)
        {
            if( inputbox.options[i].selected )
            {
                inputbox_value = inputbox.options[i].value;
            }
        }
    }
    else if( inputbox.type=='select-multiple')
    {
        var numSelected = 0;
        for(var i=0; i < inputbox.options.length; i++)
        {
            if( inputbox.options[i].selected )
            {
                inputbox_value = inputbox.options[i].value;
                numSelected ++;
            }
        }
        if( numSelected > 1 )
        {
            hasMultipleValue = true;
        }
    }
    else 
    {
        inputbox_value = trimStr(inputbox.value); 
    }        

    // apply rule
    if( stype == 'Equals' )
    {
        if( !hasMultipleValue && inputbox_value == svalue )
        {
            doskip(soption, children);
        }
        else
        {
            undoskip(soption, children);
        }
    }
    else if( stype == 'Has Any Value' || stype == 'Is Blank' )
    {
        var flag = (stype == 'Has Any Value');
        if(inputbox_value.length == 0)
        {
            flag = !flag;
        }

        if( flag )
        {
            doskip(soption, children);        
        }        
        else
        {
            undoskip(soption, children);
        }
    }
}

/****************************
 * doskip(soption, children)
 *
 * clears value and disables the children if necessary
 ****************************/
function doskip(soption, children)
{
    if( soption == 'Disable' )
    {
        for( var i = 0; i < children.length; i++)
        {
            var child = document.getElementById(children[i]);

            if( child != null && (child.type == 'radio' || child.type == 'checkbox') )
            {
                childrenTmp = document.getElementsByName(children[i]);
                for(var j=0; j < childrenTmp.length; j++)
                {
                     childrenTmp[j].checked = false;
                     childrenTmp[j].disabled = true;
                }
            } 
            if( child != null )
            {
                if( child.type == 'text' )
                {
                    child.value = '';
                }
                else if (child.type == 'select' || child.type=='select-multiple')
                {
                    for(var j=0; j < child.options.length; j++)
                    {
                         child.options[j].selected = false;
                    }
                }
                // may need to clear other types
                child.disabled = true;
            }
        }
    }
}

/****************************
 * undoskip(soption, children)
 *
 * enables children objects 
 ****************************/
function undoskip(soption, children)
{
    if( soption == 'Disable' )
    {
        for( var i = 0; i < children.length; i++)
        {
            var child = document.getElementById(children[i]);
            if( child != null )
            {
                if (child.type == 'radio' || child.type == 'checkbox')
                {
                    childrenTmp = document.getElementsByName(children[i]);
                    for(var j=0; j < childrenTmp.length; j++)
                    {
                        childrenTmp[j].disabled = false;
                    }
                } 
                child.disabled = false;
            }
        }
    }
}

function applyAllSkipRules()
{

	applyTheSkipRules ("INPUT");
	applyTheSkipRules ("SELECT");
	applyTheSkipRules ("TEXTAREA");
	
}
function applyTheSkipRules (tagType)
{
	var elements = document.getElementsByTagName (tagType);
	//elements = document.all;
	for (i=0; i < elements.length; i++)
	{
		if (elements[i].onchange && elements[i].name.indexOf('Q_') >-1)
		{
			elements[i].onchange();
		}
	}
}

function applyAllSkipRulesEditPage()
{

	applyTheSkipRulesEditPage ("INPUT");
	applyTheSkipRulesEditPage ("SELECT");
	applyTheSkipRulesEditPage ("TEXTAREA");
	
}

function applyTheSkipRulesEditPage (tagType)
{
        // Edit page uses different id and name tag as the data entry page
        // For example, if the question id is 12, the final edit page uses
        // id="12" instead of id="Q_12" as on the data entry page.    
        // So fire all onchange and do not check for Q_.
	var elements = document.getElementsByTagName (tagType);

	for (i=0; i < elements.length; i++)
	{
		if (elements[i].onchange )
		{
			elements[i].onchange();
		}
	}
}



function applyAllCalculations ()
{
	applyTheCalculations ('INPUT');
	applyTheCalculations ('SELECT');
	applyTheCalculations ('TEXTAREA');
}
function applyTheCalculations(tagType) 
{
	var elements = document.getElementsByTagName (tagType);
	for (i=0; i<elements.length; i++)
	{
		if (elements[i].onclick && elements[i].name.indexOf('Q_') > -1)
		{
			elements[i].onclick();
		}
	}
}


function unescapeErrors() {
    var errors = document.getElementsByTagName ('LI');
    for (j = 0; j < errors.length; j++) {
        var error = errors[j].innerHTML;
        var lt = error.indexOf ("&lt;");
        var newStr = error.substring (0, lt);
        newStr += "<";
        newStr += error.substring (lt+ 4, error.indexOf ("&gt;"));
        newStr += ">";
        newStr += error.substring (error.indexOf ("&gt;") + 4, error.lastIndexOf ("&lt;"));
        newStr += "<";
        newStr += error.substring (error.lastIndexOf ("&lt;") +4, error.lastIndexOf ("&gt;"));
        newStr += ">";
        
        newStr += error.substring (error.lastIndexOf ("&gt;") +4, error.length);

        errors[j].innerHTML = newStr;
    }

}
