// JavaScript Document
// CROWN Copyright, Queensland Treasury
var selectedValuesTemp = "";
var selectedValues = new Array();
var p_regtypeURL = "";
var regIdURL = "";
var formatURL = "";
var p_user_region_nameURL = "";


// Original:  Phil Webb (phil@philwebb.com)  Web Site:  http://www.philwebb.com
// Modified extensively Glen Collins
/***** START MOVE FUNCTION ******/
function move(direction,fbox, tbox) {
var arrFbox = new Array();
var arrTbox = new Array();
var arrLookup = new Array();
var setCheck = new Array();
var i;
var moveCount = 0;
var moveToCount = 0;

// Calculate number of cells selected for move.
for(i = 0; i < fbox.options.length; i++) {
	if (fbox.options[i].selected && fbox.options[i].value != "") {
  	moveCount++;
	}
}
if ((direction ==1) && (tbox.options[0].text != defaultList2Text)){
	moveToCount = moveCount + tbox.options.length;
} else {
	moveToCount = moveCount;
}

if (direction==1 && moveCount==0){
	alert("You haven't selected any region"+listText+" to take accross");
} else if (moveToCount>1 && regionSelectionType == 'single' && direction == 1) {
//Move more than 1 for single with pre-exisitng
	alert("The Report Type Selected in Step 1 only allows one Region to be selected.\n                Please remove existing selected region first.");
} else if (moveCount>1 && regionSelectionType == 'single'){
//Move more than 1 for single
	alert("The Report Type Selected in Step 1 only allows one Region to be moved accros.");
} else if (moveToCount>multiRegionThreshold && regionSelectionType == 'multi'){
//Move more than Threshold
	alert("This Report Type only allows a maximum of "+multiRegionThreshold+" regions to be selected.\n            Current selection will exceed limit by "+(moveToCount-multiRegionThreshold)+" region(s).");
} else if (direction==1 || (direction==2 && moveCount!=0)){
	//alert("Direction = "+direction+"\nType = "+regionSelectionType+"\ntbox.length = "+tbox.options.length+"\nText check ="+(tbox.options[0].text != defaultList2Text));
	if (tbox.options.length > 0 && tbox.options[0].text == defaultList2Text) {
		tbox.options.length = 0;
	}
	for (i = 0; i < tbox.options.length; i++) {
		arrLookup[tbox.options[i].text] = tbox.options[i].value;
		arrTbox[i] = tbox.options[i].text;
	}
	var fLength = 0;
	var tLength = arrTbox.length;
	for(i = 0; i < fbox.options.length; i++) {
		arrLookup[fbox.options[i].text] = fbox.options[i].value;
		if (fbox.options[i].selected && fbox.options[i].value != "") {
			arrTbox[tLength] = fbox.options[i].text;
			tLength++;
		} else {
			arrFbox[fLength] = fbox.options[i].text;
			fLength++;
		}
	}
	arrFbox.sort();
	arrTbox.sort();
	fbox.length = 0;
	tbox.length = 0;
	var c;
	var d = 0;
	var e = 0;
	
	for(c = 0; c < arrFbox.length; c++) {
		var no = new Option();
		no.value = arrLookup[arrFbox[c]];
		no.text = arrFbox[c];
		fbox[c] = no;
		d++;
	}
	for(c = 0; c < arrTbox.length; c++) {
		var no = new Option();
		no.value = arrLookup[arrTbox[c]];
		no.text = arrTbox[c];
		tbox[c] = no;
		e++;
	}
	if (direction==2 && fbox.options.length == 0){
		fbox.length = 1;
		fbox.options[0].text = defaultList2Text;
	}
	for(i = 0; i < 20; i++) {
		if (i < 10){
			ii = "0"+i;
		} else {
			ii = i;
		}
		setCheck[ii] = 0;
	}
	if (direction == 1){
		for (i = 0; i < tbox.options.length; i++) {
			tempValue = tbox.options[i].value;
			tempPlace1 = tempValue.indexOf("_");
			if (tempPlace1 != -1){
				temp = tempValue.substring(tempPlace1+1,tempPlace1+4);
			} else {
				temp = "00";
			}
			setCheck[temp] = setCheck[temp]+1;
		}
		setCustomRegName(tbox);
	}
	if (direction == 2){
		for (i = 0; i < fbox.options.length; i++) {
			tempValue = fbox.options[i].value;
			tempPlace1 = tempValue.indexOf("_");
			temp = tempValue.substring(tempPlace1+1,tempPlace1+4);
			setCheck[temp] = setCheck[temp]+1;
		}
		setCustomRegName(fbox);
	}
	
	for(i = 0; i < 20; i++) {
		if (i < 10){
			ii = "0"+i;
		} else {
			ii = i;
		}
		if (document.getElementById(ii+"_catId") != null) {
			if (setCheck[ii] > 0) {
				document.getElementById(ii+"_catId").disabled = true;
			} else {
				document.getElementById(ii+"_catId").disabled = false;
			}
		}
	}
	setLink();
}
return false;
}
/***** END MOVE FUNCTION ******/


function changeCustomRegNameString(parentId,childElement,nameString){
if (!document.getElementById) return false;
if (!document.getElementsByTagName) return false;
var leftDiv = document.getElementById(parentId);
var firstTxtDiv = leftDiv.getElementsByTagName(childElement)[0];
var text = document.createTextNode(nameString);
firstTxtDiv.replaceChild(text,firstTxtDiv.childNodes[0])
}


function addToList (n,v,listNo) {
	if (listNo == 1){       
		with (document.form1.list1)
		options[length] = new Option ( n, v );
	}
	if (listNo == 2){
		with (document.form1.list2)
		options[length] = new Option ( n, v );
	}
}


function showDIV(a) { // a must be an array
for(var i=0;i < arguments.length;i++)
	document.getElementById(arguments[i]).style.display = "block";
}
 
function hideDIV(a) { // a must be an array
for(var i=0;i < arguments.length;i++)
	document.getElementById(arguments[i]).style.display = "none";
}

function checkDIVShown(a) { // a must be an array
anyfound = false;
for(var i=0;i < arguments.length;i++) {
	if(document.getElementById(arguments[i])){
		if (document.getElementById(arguments[i]).style.display == "block"){ // || document.getElementById(arguments[i]).style.display == ""
			anyfound = true;
		}
	}
}
return anyfound;
}



var level1=new Array();
var level2=new Array();
var level3=new Array();
var level1Full=new Array();

//level3["n01_catId"] ="aa";
parentID = "n02_catId";
checkboxID = "n03_catId";

//alert(level3[parentID]);
if (!level3[parentID]) {
//	alert("X");
}

level3[parentID]= new Array();
//alert(level3[parentID]);
if (!level3[parentID]) {
	alert("Y");
}
//alert (level3["n01_catId"].length);

function setLevelArrays (){
//catBox(checkboxID,level,parentID)
	catBox("n01_catId",1,"");
	catBox("n02_catId",2,"n01_catId");
	catBox("n03_catId",3,"n02_catId");
	catBox("n04_catId",3,"n02_catId");
	catBox("n05_catId",2,"n01_catId");
	catBox("n06_catId",3,"n05_catId");
	catBox("n07_catId",3,"n05_catId");
}

function catBox(checkboxID,level,parentID) {
if (level = 1){
	level1[level1.length]  = checkboxID;
}
if (level = 2){
	level2[level2.length]  = checkboxID;
}
if (level = 3){
	level3[level3.length]  = checkboxID;
	level3[level3.length-1]= new Array();
	level3[level3.length-1][level3[level3.length-1].length]= parentID;
	
}
}

// Takes FORM from browser BACK/FORWARD and splits out elements by comma into "selectedValues" array
function setSelectedValuesArray(type) {
if (type == "back") {
	selectedValuesTemp = document.form1.p_reg.value;
} else if (type == "url" ){
	selectedValuesTemp = regIdURL;
} else {
	alert("break");
	return;
}
var whileCount = 0;
while ((selectedValuesTemp.indexOf(",")!=-1)&&(whileCount<multiRegionThreshold)){
	selectedValues[whileCount] = selectedValuesTemp.substring(0,selectedValuesTemp.indexOf(","));
	selectedValuesTemp = selectedValuesTemp.substring(selectedValuesTemp.indexOf(",")+1,selectedValuesTemp.length);
	whileCount++;
}
selectedValues[selectedValues.length] = selectedValuesTemp;
selectedValuesRemap();
}


function groupRegions(){
regString = "";
delimiter = ",";
loopLength = document.form1.list2.length;
for (i = 0; i < loopLength; i++){
	if ((i==0) && ((document.form1.list2.options[0].value == regionSelectTextOne) || (document.form1.list2.options[0].value == regionSelectTextMany))) {
		regString = "";
	} else if (i==0){
		regString = document.form1.list2.options[i].value;
	}
	else {
		regString = regString + delimiter + document.form1.list2.options[i].value;
	}
}
return regString;
}

function clearSelected(clrbox) {
for(i = 0; i < clrbox.options.length; i++) {
	clrbox.options[i].selected = false;
}
}

function checkCategorySelected(){
var checkone = false;
for(i = 0; i < 100; i++) {
	if (i < 10){
		ii = "0"+i;
	} else {
		ii = i;
	}
	if (document.getElementById("n"+ii+"_catId") != null) {
		if (document.getElementById("n"+ii+"_catId").checked == true) {
			checkone = true;
		}
	}
}
return checkone;
}


function sendForm(){
document.form1.p_reg.value = groupRegions();
if  (document.form1.list2.options[0].text == regionSelectTextOne || document.form1.list2.options[0].text == regionSelectTextMany) {
	alert("You haven't selected any region"+listText+" above.");
	return false;
} else if ((document.form1.list2.length >= 2) && (document.form1.p_user_region_name.value.length == 0)){
	alert("Please populate the \""+customRegName+" (Mandatory)\" field");
	document.getElementById("nameOverride").focus();                
	return false;
} else if (!checkCategorySelected()){
	alert("Please select at least one Topic");
	return false;
} else {
	document.getElementById("submitButton").disabled = true;
	changeCustomRegNameString("submitDiv","span","Report generating (may take up to 30 seconds) ...");
	clearSelected(document.getElementById("reg_pro").list1);
	clearSelected(document.getElementById("reg_pro").list2);
	return true;
}
}


function setCustomRegName(checkBox){
if (checkBox.options.length >= 2){
  if (document.getElementById("ownReg").style.display == "none"){
		document.getElementById("nameOverride").value = "";     
  }
	document.getElementById("ownReg").style.display = "block";
	document.getElementById("nameOverride").focus();
} else {
	document.getElementById("ownReg").style.display = "none";
	document.getElementById("nameOverride").value = "";
}
}

function selectedValuesRemap(){
// Remap from SD_06 to SD_PRO
if(document.getElementById("reg_type4").checked == true){
	for (i=0;selectedValues.length>i;i++){
		/* Brisbane */
		if (selectedValues[i] == 230){selectedValues[i] = 4642}
		/* Gold Coast */
		else if (selectedValues[i] == 4524){selectedValues[i] = 4654}
		/* Sunshine Coast */
		else if (selectedValues[i] == 4525){selectedValues[i] = 4655}
		/* West Moreton */
		else if (selectedValues[i] == 4526){selectedValues[i] = 4656}
		/* Wide Bay-Burnett */
		else if (selectedValues[i] == 232){selectedValues[i] = 4643}
		/* Darling Downs */
		else if (selectedValues[i] == 233){selectedValues[i] = 4644}
		/* South West */
		else if (selectedValues[i] == 234){selectedValues[i] = 4651}
		/* Fitzroy */
		else if (selectedValues[i] == 235){selectedValues[i] = 4645}
		/* Central West */
		else if (selectedValues[i] == 236){selectedValues[i] = 4646}
		/* Mackay */
		else if (selectedValues[i] == 237){selectedValues[i] = 4652}
		/* Northern */
		else if (selectedValues[i] == 238){selectedValues[i] = 4647}
		/* Far North */
		else if (selectedValues[i] == 239){selectedValues[i] = 4653}
		/* North West */
		else if (selectedValues[i] == 240){selectedValues[i] = 4648}
	}
}
}




// Takes "selectedValues" array and checks against all records in select form box, selects, then moves accross
function setSelectedFromBack(type) {
selectedCount = 0;
setSelectedValuesArray(type);
for(i = 0; i < document.form1.list1.length; i++) {
	for (j = 0; j < selectedValues.length;j++) {
		if (selectedValues[j] == document.form1.list1.options[i].value) {
			document.form1.list1.options[i].selected = true;
			selectedCount++
		}
	}
}
//alert("about to migrate selected");
if (selectedCount > 0){
	move(1,document.form1.list1,document.form1.list2);
} else{
	alert("None set: ERROR");
}
}

function adjustString(changeString,type) {
// e.g. of URL part "custom-name=a%28b%29c%2Bd+e%27f-i%22j"
if (type == "toReadable") {
	changeString = adjustStringSub(changeString,"+"," ");
	changeString = adjustStringSub(changeString,"%20"," ");
	changeString = adjustStringSub(changeString,"%28","(");
	changeString = adjustStringSub(changeString,"%29",")");
	changeString = adjustStringSub(changeString,"%2C",",");
	changeString = adjustStringSub(changeString,"%2B","+"); //Note must be done after space/+ above
	changeString = adjustStringSub(changeString,"%27","'");
	changeString = adjustStringSub(changeString,"%22",'"');
} else if (type == "toURL") {
	changeString = adjustStringSub(changeString,"+","%2B"); //Note must be done before space/+ below
	changeString = adjustStringSub(changeString," ","%20");
	changeString = adjustStringSub(changeString,"(","%28");
	changeString = adjustStringSub(changeString,")","%29");
	changeString = adjustStringSub(changeString,",","%2C");
	changeString = adjustStringSub(changeString," ","+");
	changeString = adjustStringSub(changeString,"'","%27");
	changeString = adjustStringSub(changeString,'"',"%22");
}
// enable following line inserting true apostrophe when server support UTF8
// changeString = adjustStringSub("%E2%80%99","''");
// Could also add some other special characters, e.g. endash, emdash.
return changeString
}

function adjustStringSub(adjustStringText,searchString,replaceString) {
var whileCount = 0;
indexTemp = adjustStringText.indexOf(searchString);
while ((indexTemp != -1) && (whileCount < 5)){
	adjustStringText = adjustStringText.substring(0,indexTemp)
	+replaceString
	+adjustStringText.substring(indexTemp+searchString.length,adjustStringText.length);
	indexTemp = adjustStringText.indexOf(searchString);
	whileCount++;
}
return adjustStringText;
}


function extractStringFromURL(searchString) {
//Strip values of p_regtype, regId, and format into variables
var loopString = "";
if (document.URL.indexOf(searchString) != -1){
	rightURL = document.URL.substring(document.URL.indexOf(searchString),document.URL.length);
	if (rightURL.indexOf("&") == -1){
		loopString = rightURL.substring(searchString.length+1,rightURL.length);
	} else {
		loopString = rightURL.substring(searchString.length+1,rightURL.indexOf("&"));
	}
}
return loopString;
}

// Populates fields from URL.
function setFromURL(){
// REGION TYPE
p_regtypeURL = extractStringFromURL("region-type");
if(p_regtypeURL != ""){
	setRadioAndFromList();
	//REGIONS
	regIdURL = extractStringFromURL("region-ids");
	if(regIdURL != ""){setSelectedFromBack("url")};
    //alert(document.form1.list2.options.length);
    //alert(document.form1.list2.options[0].value);
	if ((document.form1.list2.options.length == 1) && (document.form1.list2.options[0].value != "")){
		changeCustomRegNameString("prePopulatedNote","span","Some steps have been pre-selected.  You may advance to Step 3.");
	}
	else if (document.form1.list2.options.length > 1) {
		//CUSTOM REGION NAME
		p_user_region_nameURL = extractStringFromURL("custom-name");
		if (p_user_region_nameURL != "") {
			p_user_region_nameURL = adjustString(p_user_region_nameURL,"toReadable");
			document.form1.p_user_region_name.value = p_user_region_nameURL;
			changeCustomRegNameString("prePopulatedNote","span","Some steps have been pre-selected.  You may advance to Step 3.");
			//document.getElementById("h2Step3").focus();  //Unable to focus on H2
      document.getElementById("categoryAll").focus();
		} else {
			changeCustomRegNameString("prePopulatedNote","span","Multiple regions have been pre-selected.  Please proceed to the second part of Step 2.");		
		}
	}
}
// TO ADD HERE: TOPICS preselect.  Not addded as unsure if needed or ramificaitons with hidden values.
}




// Main called onLoad function (part 1).
function setCheckPart1() {
	document.getElementById("submitButton").disabled = false;
	changeCustomRegNameString("submitDiv","span","");
}

//Main called onLoad funciton (part 2) called on browser first load (all browsers) and IE BACK step.
function setCheckPart2() {
setListFromRadio();
if(document.form1.p_reg.value != ""){
	// Back must have been used
	setSelectedFromBack("back");
} else {
	// May be nothing in URL but check anyway
	setFromURL();
}
//Following line needs to set value to null so "nameOverride" is show/hidden correctly.
document.form1.p_reg.value = "";
setLink();
}

function enableElements(step,setme) {
if (step == 2) {
 return;
} else if (step == 3) {
	for(var i=0;i < $("#category_selection input").get().length;i++){
		$("#category_selection input").get()[i].disabled = !setme;
	}
	if (setme == false) {
		$("#category_selection label").css("color","gray");
	} else {
		$("#category_selection label").css("color","black");
	}
}
}

function setLink() {
var linkValue = urlPath+"?";
var customNameTemp = "";
for(var i=0;i < document.form1.p_regtype.length;i++){
	if (document.form1.p_regtype[i].checked == true){
		linkValue = linkValue+"region-type="+document.form1.p_regtype[i].value;
	}
}
tempRegString = groupRegions();
if (tempRegString != ""){
	linkValue = linkValue+"&region-ids="+tempRegString;
	if (document.form1.p_user_region_name.value != ""){
		customNameTemp = adjustString(document.form1.p_user_region_name.value,"toURL");
		linkValue = linkValue+"&custom-name="+customNameTemp;
	}
}
document.form1.p_url.value = linkValue;
}



function setListFromRadio() {
/*if(document.form1.p_regtype[regTypeDefault].checked != true){*/
	for(var i=0;i < document.form1.p_regtype.length;i++){
		if (document.form1.p_regtype[i].checked == true){
			//alert("a");
			setList(i);
		}
	}
/*}*/
}

function setList(changeNum){
regionSelectionType = regTypeDetails[changeNum].selectType;
if (changeNum != regTypeActive) {
	// Show Previous
	for(var i=0;i < regTypeDetails[regTypeActive].hideTopics.length;i++){
		showDIV(regTypeDetails[regTypeActive].hideTopics[i]);
	}
	// Hide Current
	for(var i=0;i < regTypeDetails[changeNum].hideTopics.length;i++){
		hideDIV(regTypeDetails[changeNum].hideTopics[i]);
	}
}
populateRegionList(changeNum+1);
regTypeActive = changeNum;
setLink();
}


// Adjust from URL section
function setRadioAndFromList() {
regTypeSet = false;
for(var i=0;i < document.form1.p_regtype.length;i++){
	if (p_regtypeURL == regTypeDetails[i].name){
		document.form1.p_regtype[i].checked = true;
		regTypeSet = true;
	}
}
if (regTypeSet == true){
	setListFromRadio();
	changeCustomRegNameString("prePopulatedNote","span","Some steps have been preselected.  You may advance to Step 2.");	
} else {
	//alert("Error");
	return;
}
}
