// Vovici JavaScript Functions
// For assistance, please e-mail techsupport@vovici.com
// (c) 2008 Vovici Corp.

//Version 3.01 10/13/00
//Version 5.00 03/06/02 BP
//Version 6.00 07/29/03
//Version 7.00 12/01/04 DI

// Implement swapNode for mozilla so table randomization works properly
try {
	if (!Node.prototype.swapNode) {
		Node.prototype.swapNode = function (node) {
			var nextSibling = this.nextSibling;
			var parentNode = this.parentNode;
			node.parentNode.replaceChild(this, node);
			parentNode.insertBefore(node, nextSibling);  
		}
	}
} catch(e) {}

function RandomizeChoices(QuestionName, SelectedValue) {
	//Randomizes the contents of an option list.
	//Don't move the first item which is the placeholder.
	//(e.g., "", or "(Click to choose)")

	var y;
	var XText, XValue;
	var YText, YValue;

	var ChoiceList = document.PdcSurvey.elements[GetFormIndex(QuestionName)];
	var OptionCount = ChoiceList.options.length - 1;
	var SelectedIndex = SelectedValue;

	// Loop thru the options.
	for (var x=1;x<OptionCount;x++){
	   	// Swap the current option with a randomly select different option
		y = Math.floor(Math.random() * OptionCount) + 1;
		XText = ChoiceList.options[x].text;
		XValue = ChoiceList.options[x].value;
		YText = ChoiceList.options[y].text;
		YValue = ChoiceList.options[y].value;
		ChoiceList.options[x] = new Option(YText, YValue);
		ChoiceList.options[y] = new Option(XText, XValue);

        // Preserve the selection.
        if (SelectedValue == XValue) {
			SelectedIndex = y;
		} else if (SelectedValue == YValue) {
			SelectedIndex = x;
		}
	}
	// Reset the selection.
	ChoiceList.selectedIndex = SelectedIndex;
	return;
}

// Randomize the rows in a table.
function RandomizeTable(id, oddeven) {
	var table = document.getElementById(id);
	var tbodyElements = table.getElementsByTagName("tbody");
	var tbody = tbodyElements.item(0);
	var trElements = tbody.getElementsByTagName("tr");
	var rowsHtml = new Array();
	var visCount = 0;
	for (var i = 0; i < trElements.length; i++) {
		var tr = trElements.item(i);
		if (tr.swapNode) {
			rowsHtml.push(tr);
		} else {
			rowsHtml.push(tr.innerHTML);
		}
	}
	PdcShuffleArray(rowsHtml);
	for (var i = 0; i < trElements.length; i++) {
		var tr = trElements.item(i);
		if (tr.swapNode) {
			tr.swapNode(rowsHtml[i]);
		} else {
			tr.innerHTML = rowsHtml[i];
		}
	}
	if (oddeven) {
		var trElements = tbody.getElementsByTagName("tr");
		for (var i = 0; i < trElements.length; i++) {
			var tr = trElements.item(i);
			if (tr.style.display == "") {				
				visCount++;
				if(visCount % 2 == 1) {
				    tr.className="odd-row";
			    } else {
				    tr.className="even-row";
			    }
		    }		
	    }
	}
}
	
// Autojump based on a list selection.
function SelectJump(sel, JumpString) {
   var SelArr = JumpString.split(";");
   var ValArr = new Array();

   for (var i=0;i<SelArr.length;i++){
     if (SelArr[i].length > 0) {
       ValArr = SelArr[i].split("|");
         if((ValArr.length == 2) && (parseInt(sel.options[sel.selectedIndex].value) == parseInt(ValArr[0]))){
            window.location = ValArr[1]
            break;
         }
      }
   }
}

//Return true if the supplied value is an integer.
function IsInteger(Value) {
	//Test if parseInt returns a number. See the doc about NaN for why the code is written this way.
	if ((Value == "") || (isNaN(parseInt(Value))))
		{return false;}
	else
		{return true;}
}

//Return true if the supplied value is a number.
function IsNumber(Value) {
	//Test if parseFloat returns a number. See the doc about NaN for why the code is written this way.
	if ((Value == "") || (isNaN(parseFloat(Value))))
		{return false;}
	else
		{return true;}
}

//Return the index of the specified form element.
function GetFormIndex(ElementName) {
	var i;
	for(i=0;i<document.PdcSurvey.elements.length;i++) {
		if (document.PdcSurvey.elements[i].name == ElementName) {
			return i;
		}
	}
	return -1;
}

//Selects the specified option
function PdcSelectOption(id) {
	PdcGetElement(id).checked = true;
}

//Return the index of the selected option from the array.
function PdcSelectedOption(optionArray) {
	for(var x=0;x<optionArray.length;x++) {
		//The option could a radio button which is check or a selected list item. If either of those
		//cases is true return the index.
		if (((optionArray[x].type == "radio") && optionArray[x].checked) || optionArray[x].selected)
			return x;
	}
	return -1;
}

//Return the index of the selected option from the array. Return -1 if unanswered.
function PdcSelectedAnsweredOption(optionArray) {
	for(var x=0;x<optionArray.length;x++) {
		//The option could a radio button which is check or a selected list item. If either of those
		//cases is true return the index.
		if (((optionArray[x].type == "radio") && optionArray[x].checked) || (optionArray[x].selected && optionArray[x].value != "0"))
			return x;
	}
	return -1;
}

//Return true if all topics in the table have unique choice selections.
function PdcValidateRankings(TopicList) {
	var index;
	var choiceValues = new Array();

	for (var x=0;x<TopicList.length;x++){
		//Get the selected index
		index = PdcSelectedAnsweredOption(document.PdcSurvey[TopicList[x]]);

		//If there is a selected index test if it has already been set.
		if (index != -1) {
			if (choiceValues[index] == 1) {
				return false;
			} else {
				choiceValues[index] = 1;
			}
		}
	}
	return true;
}

//Store a cookie with the supplied name/value (path and expires are optional).
function SetCookie(Name, Value, Path, Expires) {
	var CookieString;

	CookieString = Name + "=" + escape(Value)

	if (Path) CookieString += "; path=" + Path;
	if (Expires) CookieString += "; expires=" + Expires.toGMTString();

	document.cookie = CookieString
}

//Answer the stored value for the named cookie.
function GetCookieValue(Name) {
	var Cookies;
	var NameValuePair;
	var CookieString = document.cookie;

	//Get an array of cookie pairs by splitting on ;
	Cookies = CookieString.split("; ");

	for (var i=0;i<Cookies.length;i++){
		NameValuePair = Cookies[i].split("=");
		if (NameValuePair[0] == Name) {
			return unescape(NameValuePair[1]);
		}
	}
}

//Save the current page.
function SaveCurrentPage(PageValue) {
	var d = new Date();
	var cookieValue;

	if (PageValue == undefined)  {
		cookieValue = document.PdcSurvey.PdcCurrentPage.value; }
	else {
		cookieValue = PageValue; }

	//Set the cookie to expire in one month.
	d.setMonth(d.getMonth() + 1);
	SetCookie(CurrentPageCookieName(), cookieValue, "/", d);
}

//Check if there was a previous current page.
function CheckCurrentPage() {
	var CurrentPage = GetCookieValue(CurrentPageCookieName());

	//Verify that current page is non-null and not an empty string.
	//Verify that there is a nextpage field on this page.
	//Defect 925. Was comparing to null which is not cross-browser
	//If the user submitted the survey dont change next page (the user will then go to the normal next page).
	if ((CurrentPage) && (CurrentPage != "") && (document.PdcSurvey.PdcNextPage) && (CurrentPage != 'submitted'))
		document.PdcSurvey.PdcNextPage.value = CurrentPage;
}

//Answer the name of the cookie to save the current page with.
function CurrentPageCookieName() {
	var ProjectName;

	ProjectName = document.PdcSurvey.PdcProjectID.value;
	if (ProjectName == "")
		return "PdcCurrentPage";
	else
		return "Pdc" + ProjectName;
}

function PdcGetElement(elementName) {
	var reference = null;
	if (document.getElementById) {
		reference = document.getElementById(elementName);
	}
	if (reference == null && document.all) {
		reference = document.all[elementName];
	}
	if (reference == null) {
		reference = document.PdcSurvey[elementName];
	}
	return reference;
}

function PdcShuffleArray(A) {
	for (var X=0;(X<A.length);X++){
   		// swap the current option with a randomly selected different option
   		Y = Math.floor(Math.random() * A.length);
   		XText = A[X];
   	     	YText = A[Y];
   	     	A[X] = YText;
   	     	A[Y] = XText;
   	}
   	return A.join(" ");
}

function PdcRemoveOption(QuestionName, ChoiceValue) {
	//Remove the specified Choice from a selection list

	var ChoiceList = document.PdcSurvey.elements[GetFormIndex(QuestionName)];
	var OptionCount = ChoiceList.options.length;

	// Loop thru the options.
	for (var x=1;x<OptionCount;x++){
	   	if (ChoiceList.options[x].value == ChoiceValue){
	   		ChoiceList.options[x] = null;
	   		break;
	   	}
	}
}

function PdcSelectedCount() {
	//Answer the number of selected buttons
	var Selected=0;

	for (var x=0;x<arguments.length;x++){
		if (PdcGetElement(arguments[x]).checked) {Selected += 1;}
	}
	return Selected;
}


function PdcClearCheckboxes() {
	for (var x=0;x<arguments.length;x++){
		PdcGetElement(arguments[x]).checked = false;
	}
}

function PdcZeroNotAnswered() {
	for (var x=0;x<arguments.length;x++){
		if (PdcGetElement(arguments[x]).value == '') {
			PdcGetElement(arguments[x]).value = '0';
		}
	}
}


function PdcJumpToQuestion(QuestionId, Message) {
	//Jump to the question and notify the user.
	window.location = QuestionId;
	alert(Message);
}

function PdcAnyButtonSelected() {
	//Takes an array of buttons and returns true if any of them are selected.
	for (var x=0;x<arguments.length;x++){
		if (PdcGetElement(arguments[x]).checked) {return true;}
	}
	return false;
}

function PdcAnyAnswered() {
	//Takes an array of text fields and answers true if any have values.
	for (var x=0;x<arguments.length;x++){
		if (PdcGetElement(arguments[x]).value != '') {return true;}
	}
	return false;
}

function PdcAnyNotAnswered() {
	//Takes an array of text fields and answers true if any have blank values.
	for (var x=0;x<arguments.length;x++){
		if (PdcGetElement(arguments[x]).value == '') {return true;}
	}
	return false;
}

function PdcGetUrlParameter(parameterName) {
	//Return the value for the specfied named parameter (passed in the URL).

	//Get the query string minus the ?
	var queryString = location.search.substring(1);

	//Split the args by & and the look at each named pair.
	var args = queryString.split("&");
	for (var x=0;x<args.length;x++) {
		var pair = args[x].split("=");
		if ((pair.length == 2) && (pair[0] == parameterName)) {
			return unescape(pair[1]);
		}
	}
	
	//If parameter not found, return a blank string
	return '';
}

function PdcFieldTotal() {
	//Takes an array of text fields and answers the total.
	var Total = 0;
    var TextValue;

	//Loop thru the arguments, for each text field get the value and if numeric add to the total.
	for (var x=0;x<arguments.length;x++){
		TextValue = PdcGetElement(arguments[x]).value
		if (IsNumber(TextValue)) Total += parseFloat(TextValue)
	}
	return Total;
}

function PdcSelectedButtons() {
	//Answer a serial string of selected buttons
	var Selected='';
	for (var x=0;x<arguments.length;x++){
		var choice = PdcGetElement(arguments[x]);
		if(choice) {
			if (choice.checked) {
				Selected += arguments[x] + '|';
			}
		}
	}
	if (Selected != '') {Selected = Selected.substring(0, Selected.length-1)}
	return Selected;
}

function PdcDisplayDrilldown() {
	// Loop through each topic.
	var viscount = 0;
	var value = arguments[0];
	var oddeven = arguments[1];
	for (var x=2;x<arguments.length;x++){
		var pair = arguments[x].split("|");
		if (document.PdcSurvey[pair[0]].value != value) {
			PdcGetElement(pair[1]).style.display="none";
		} else if (oddeven) {
			viscount++;
			if(viscount % 2 == 1) {
				PdcGetElement(pair[1]).className="odd-row";
			} else {
				PdcGetElement(pair[1]).className="even-row";
			}
		}

	}
}

function PdcTopicVisible(row) {
	if (PdcGetElement(row).style.display=="none") {
	   return false;
	}
	return true;
}

function PdcHideTableRows(QstHdg, TopicCount, VisibleRows) {
	for(i = TopicCount; i > 0; i--) {
		if (i > VisibleRows) {
			var fieldName = QstHdg + "T" + i;
			PdcGetElement(fieldName).style.display="none";
		}
	}
}

function PdcHideTableColumns(DepQst, DepValue, ColumnPrefix, ChoiceCount) {
	for(i = 1; i <= ChoiceCount; i++) {
		if (document.PdcSurvey[DepQst + '_' + i].value != DepValue) {
			ColumnName = ColumnPrefix + i;
			cells = document.getElementsByName(ColumnName);
			for(j = 0; j < cells.length; j++){
				cells[j].style.display = "none";
			}
		}
	}
}

function PdcHideTableSelectColumns(DepQst, DepValue, ColumnPrefix, ChoiceCount, TableSide, TopicCount) {
	for(k = 1; k <= ChoiceCount; k++) {
		if (document.PdcSurvey[DepQst + '_' + k].value != DepValue) {
			PdcHideTableColumns(DepQst, DepValue, ColumnPrefix, ChoiceCount);
			for(j = 1; j <= TopicCount; j++){
				QuestionName = TableSide + '_' + j;
				PdcRemoveOption(QuestionName, k);
			}
		}
	}
}

function PdcCreateSlider(fieldName, minVal, maxVal, stepVal, preselectedValue, defaultValue, imagePath, totalFunction) {
	var slider = new Bs_Slider();
	slider.fieldName = fieldName;
	slider.minVal = minVal;
	slider.maxVal = maxVal;
	slider.height = 26;
	slider.width = 121;
	slider.valueInterval = stepVal;
	slider.arrowAmount= stepVal;
	if (isNaN(parseFloat(defaultValue))) {
		slider.valueDefault = preselectedValue;
	} else {
		try {
			slider.valueDefault = parseFloat(defaultValue);
		} catch(e) {
			slider.valueDefault = preselectedValue;
		}
	}
	if (imagePath == '') {
		slider.imgDir = '/';
	} else {
		slider.imgDir = imagePath;
	}
	slider.setSliderIcon('slBar.gif', 13, 18);
	slider.setBackgroundImage('slBkgrnd.gif', 'no-repeat');
	slider.setArrowIconLeft('slArrowL.gif', 16, 16);
	slider.setArrowIconRight('slArrowR.gif', 16, 16);
	slider.useInputField = 2;
	slider.colorbar = new Object();
	slider.colorbar['color'] = 'blue';
	slider.colorbar['height'] = 5;
	slider.colorbar['widthDifference'] = -12;
	slider.colorbar['offsetLeft'] = 5;
	slider.colorbar['offsetTop'] = 9;
	slider.drawInto(fieldName + 'S');
	if (totalFunction) {
		slider.attachOnChange(totalFunction);
	}
	// Remove mouse over event
	var sliderText = document.getElementById(fieldName);
	try {
		sliderText.onmouseover = null;
	} catch(ex) {};
}

function PdcQuestionAnswered() {
	//Takes an array of text fields and answers true if any have values.
	for (var x=0;x<arguments.length;x++){		
		if ((PdcGetElement(arguments[x]).value != '') && (PdcGetElement(arguments[x]).value != '0')) {return true;}
	}
	return false;
}

function PdcShowJumpPage(Path, InfuseKeys) {
	var url = document.PdcSurvey.action + "?jump=1&P=" + Path + "&PdcProjectID=" + escape(document.PdcSurvey.PdcProjectID.value) + "&PdcSurveyName=" + escape(document.PdcSurvey.PdcSurveyName.value);	
	if (InfuseKeys) {
		var KeyArr = InfuseKeys.split(";");
		for (var i=0;i<KeyArr.length;i++){
			url = url + "&" + KeyArr[0] + "=" + escape(document.PdcSurvey.elements[GetFormIndex(KeyArr[0])].value);
		}
	}
	
	if (window.showModalDialog){		
		window.showModalDialog(url, document.PdcSurvey, "status:no;resizable:yes;center:yes;help:no;minimize:no;maximize:yes;scroll:yes;statusbar:no;");
	} else {
		window.open(url, document.PdcSurvey.PdcProjectID.value + "JUMP", "modal=yes, location=no, menubar=no, resizable=yes, scrollbars=yes, status=no, toolbar=no, dialog=yes");
	}
}

// Used by EFM 2.0
function PdcShowJumpPageEx() {
	var is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
	var url = document.PdcSurvey.action + "?s=" + document.PdcSurvey.PdcSessionId.value + "&jump=1";
	if (!is_chrome && window.showModalDialog){		
		window.showModalDialog(url, document.PdcSurvey, "status:no;resizable:yes;center:yes;help:no;minimize:no;maximize:yes;scroll:yes;statusbar:no;");
	} else {
		window.open(url, document.PdcSurvey.PdcSessionId.value + "JUMP", "modal=yes, location=no, menubar=no, resizable=yes, scrollbars=yes, status=no, toolbar=no, dialog=yes");
	}
}