function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      if (oldonload) {
        oldonload();
      }
      func();
    }
  }
}

function reportErrors(errors) {
    if (errors) {
        var message = "";
        for( var i=0; i<errors.length; i++ ) {
            message += errors[i] + "\n"; 
        }
        alert (message);
    }
}

function renderDomainNameLabel(domain) {
	return "<a href='javascript:viewDomainPopup(\"" + domain + "\");'>"	+ domain + "</a>";
}
function renderHostNameLabel(host) {
	return "<a href='javascript:viewHostPopup(\"" + host + "\");'>"	+ host + "</a>";
}

function makeTablesPretty() {
  if( !document.getElementsByTagName ) return false;
  var tables = document.getElementsByTagName('table');

  // go through each table and add the altrow class to every second row
  for( var i=0; i<tables.length; i++ ) {
    var table = tables[i].className;
    if( table ) {
      if( table.match('pretty') ) {
        var fix_rows = tables[i].rows;
        for( var j=2; j<fix_rows.length; j+=2 ) {
          fix_rows[j].className += ' altrow';
        }

      }
    }
  }
}
var counter = 0;
/**
 * Use this function on page load to populate a list into the parentId. the htmlListId
 * represents the identifier of an input element.
 */
function loadDynamicList(parentId, htmlListId, seperator) {
	var array = new Array();
	var ipV4Addresses = document.getElementById(htmlListId);
	
	if (ipV4Addresses != null) {
		array = ipV4Addresses.value.split(seperator);
		for	(var i=0; i < array.length; i++) {
			if (array[i].length > 0) {
				addItemToList(parentId, null, array[i], null);
			}
		}
	}
}

/**
 * This function adds a value to a list with ID of parentId. If the inputId is
 * null the inputValue is used or else a value will be extracted from the
 * inputId.
 */	
function addItemToList(parentId, inputId, inputValue, validateFunction) {
	counter = counter + 1;
	var parent = document.getElementById(parentId);
	var input = document.getElementById(inputId);
	var value = "";
	parent.style.display = "block";
	
	if (input != null) {
		value = input.value;
	} else {
		value = inputValue;
	} 
	
	if (validateFunction != null) {
		var result = validateFunction(value);
		if (result[0] == METHOD_RESULT_PASS) {
			resetFieldError(input);
		} else if (result[0] == METHOD_RESULT_FAIL) {
			setFieldError(input, result[1]);
			return;
		}
	}	
	
	var childId = parent.id + "_"+ counter;
	parent.innerHTML = parent.innerHTML + "<span id='" + childId + "'><input type='hidden' id='in_" + childId + "' name='in_" + 
					childId + "' value='" + value + "'/><input type='checkbox' id='ck_" + childId + "'/>" + value +
					"<br/></span>";
	if (input != null) {
		input.value = "";
		input.focus();
	}
} 
	
/**
 * This function removes all selected elements from a parent element.
 */
function removeItemFromList(parentId) {
	//alert("Remove ID: " + childId);
	var parent = document.getElementById(parentId);
	var children = parent.childNodes;
	var toBeDeleted = new Array();
	var index = 0;
	
	if (children != null) {
		if (children.length == 0) {
			alert("Warning: There is nothing to remove.");
		    return;
		}
		
		for (var i = 0; i < children.length; i++) {
			var checkbox = document.getElementById("ck_" + children[i].id);
			if (checkbox != null && checkbox.checked) {
				toBeDeleted[index] = (children[i]);
				index++;
			}
		}
		
		if (toBeDeleted.length == 0) {
			alert("Please select an IP address to remove.");
		    return;
		}
		for (var i in toBeDeleted) {
			parent.removeChild(toBeDeleted[i]);
		}
	}
	//alert("Children: " + children);
	if (!parent.hasChildNodes()) {
		parent.style.display = "none";
	}
}
/**
 * 
 */
function removeCheckedItemsFromElement(strParent) {
	var eleParent = document.getElementById(strParent);
	var eleArrChildren = eleParent.childNodes;
	var eleArrRemove = new Array();				// elements to be removed
	// determine selected elements adding them to the remove list
	for (var i = 0; i < eleArrChildren.length; i++) {	// use this for loop style for opera
		var checkbox = document.getElementById("ck_" + eleArrChildren[i].id);
		if (checkbox != null && checkbox.checked) {
			eleArrRemove.push(eleArrChildren[i]);
		}
	}
	// remove the selected elements
	for (var i = 0; i < eleArrRemove.length; i++) {
		eleParent.removeChild(eleArrRemove[i]);
	}
}
/**
 *
 */
function removeCheckedItemsFromElements(strArrElements) {
	for (var i = 0; i < strArrElements.length; i++) {
		removeCheckedItemsFromElement(strArrElements[i]);
	}
}
/**
 *
 */
function addInputsToElementAndReset(fncFunc, strParent, strarrInputs) {
	var eleParent = document.getElementById(strParent);
	var strarrValues = new Array();		// values of inputs
	for (var i = 0; i < strarrInputs.length; i++) {
		strarrValues.push(getAndResetValueById(strarrInputs[i]));
	}
	fncFunc(eleParent, new Date().getTime(), strarrValues);
}
/**
 *
 */
function getAndResetValueById(strInput) {
	var strResult;
	var eleInput = document.getElementById(strInput);
	switch (eleInput.type) {
		case 'text':
				strResult = eleInput.value;
				eleInput.value = '';
				break;
		case 'select-one':
				if (eleInput.selectedIndex == null || eleInput.selectedIndex == -1) {
					strResult = '';
				} else {
					strResult = eleInput[eleInput.selectedIndex].value;
				}
				eleInput.selectedIndex == -1;
				break;
		default:
				strResult = '';
	}
	return strResult;
}
//addLoadEvent(makeTablesPretty);

function setupListSortImages(contextPath, headingLinkId, sortAscending) {
	if (headingLinkId != null) {
		var headingLink = document.getElementById(headingLinkId);
		if (headingLink != null) {
			if (sortAscending) {
				headingLink.innerHTML += " <img class='sortImg' src='" + contextPath + "/res/image/sort-up.gif'/>"; 
			} else {
				headingLink.innerHTML += " <img class='sortImg' src='" + contextPath + "/res/image/sort-down.gif'/>"; 
			}
		}
	}
}
function updateSelectTextField(theSelect, fieldId) {
	var theField = document.getElementById(fieldId);
	theField.value = theSelect.options[theSelect.selectedIndex].text;
}
function popup(url){
	var theWindow = window.open(url, 'AR_POPUP', 'directories=no,menubar=no,location=no,resizable=yes,scrollbars=yes,width=700,height=550');
	theWindow.focus();
}
function popup2(url, title){
	var theWindow = window.open(url, title, 'directories=no,menubar=no,location=no,resizable=yes,scrollbars=yes,width=800,height=550');
	theWindow.focus();
}
function goBack(url) {
	if (backUrl == null) {
		return true;
	} else {
		window.location = backUrl;
		return false;
	}
}
function isipv6(addr) {
	var ipv6 = new Array(0, 0, 0, 0, 0, 0, 0, 0); // eight 16-bit integers
	if (addr.indexOf("::") != addr.lastIndexOf("::")) {
		// ambigious
		return null;
	}
	var left;
	var right;
	var compression = addr.split("::");
	if (compression.length == 1) {
		var left = compression[0].split(":");
		if (left.length == 7) {
			// last one must be ipv4 to be valid
			var hx = ipv4tohex(left.pop());
			if (hx) {
				left.push(hx[0], hx[1]);
			}
			if (left.length != 8) {
				return null;
			}
		}
		if (left.length != 8) {
			return null;
		}
		var right = new Array();
	} else {
		var left = compression[0].split(":");
		if (left[left.length - 1] == '') {
			left.pop();
		}
		var right = compression[1].split(":");
		if (right[0] == '') {
			right.shift();
		}
		if (right.length > 0) {
			// last in right could be ipv4
			var hx = ipv4tohex(right[right.length - 1]);
			if (hx) {
				right.pop();
				right.push(hx[0], hx[1]);
			} // if null, then assume v6, caught later
		}
		if ((left.length + right.length) >= 8) {
			return null;
		}
	}

	for (var i = 0; i < left.length; i++) {
		if (/^[0-9a-fA-F]{1,4}$/.test(left[i])) {
			ipv6[i] = parseInt(left[i], 16);
		} else {
			return null;
		}
	}
	right.reverse();
	for (var i = 0, j = 7; i < right.length; i++, j--) {
		if (/^[0-9a-fA-F]{1,4}$/.test(right[i])) {
			ipv6[j] = parseInt(right[i], 16);
		} else {
			return null;
		}
	}
	// work out longest run of zeros
	var st = -1, len = 0, cur = 0;
	for (var i = 0; i < ipv6.length; i++) {
		if (ipv6[i] != 0) {
			if (cur > len) {
				st = i - cur;
				len = cur;
			}
			cur = 0;
		} else {
			cur++;
		}
	}
	if (cur > len) {
		st = i - cur;
		len = cur;
	}
	if (len == 1 && (st == 0 || st == 7)) {
		st = -1;
		for (var i = 1; i < 7; i++) {
			if (ipv6[i] == 0) {
				st = i;
				break;
			}
		}
	}
	// print the results
	var result = "";
	for (var i = 0; i < ipv6.length; i++) {
		if (st == i) {
			if (st == 0) {
				result = result + ":";
			}
			result = result + ":";
			i = i + len - 1;
		} else {
			result = result + ipv6[i].toString(16);
			if ((i + 1) < ipv6.length) {
				result = result + ":";
			}
		}
	}
	return result;
}
function ipv4tohex(addr) {
	var ipv4 = new Array(0, 0, 0, 0);
	var spl = addr.split(".");
	if (spl.length != 4) {
		return null;
	}

	for (var i = 0; i < 4; i++) {
		if (!(/^[0-9]{1,3}$/.test(spl[i]))) {
			return null;
		}
	}

	ipv4[0] = parseInt(spl[0], 10);
	ipv4[1] = parseInt(spl[1], 10);
	ipv4[2] = parseInt(spl[2], 10);
	ipv4[3] = parseInt(spl[3], 10);
	
	if (isNaN(ipv4[0]) || (ipv4[0] > 0xFF) || (ipv4[0] < 0x0)
			|| isNaN(ipv4[1]) || (ipv4[1] > 0xFF) || (ipv4[1] < 0x0)
			|| isNaN(ipv4[2]) || (ipv4[2] > 0xFF) || (ipv4[2] < 0x0)
			|| isNaN(ipv4[3]) || (ipv4[3] > 0xFF) || (ipv4[3] < 0x0)) {
		return null;
	}
	
	return new Array(((ipv4[0] << 8) | ipv4[1]).toString(16), ((ipv4[2] << 8) | ipv4[3]).toString(16));
}
function isipv4(addr) {
	var ipv4 = new Array(0, 0, 0, 0); // four 8-bit integers
	// four eight bit integers seperated by period
	var spl = addr.split(".");
	if (spl.length != 4) {
		return null;
	}

	for (var i = 0; i < 4; i++) {
		if (!(/^[0-9]{1,3}$/.test(spl[i]))) {
			return null;
		}
	}
	
	// store the integers
	ipv4[0] = parseInt(spl[0], 10);
	ipv4[1] = parseInt(spl[1], 10);
	ipv4[2] = parseInt(spl[2], 10);
	ipv4[3] = parseInt(spl[3], 10);
	
	// ensure each was a valid 8-bit integer
	if (isNaN(ipv4[0]) || (ipv4[0] > 0xFF) || (ipv4[0] < 0x0)
			|| isNaN(ipv4[1]) || (ipv4[1] > 0xFF) || (ipv4[1] < 0x0)
			|| isNaN(ipv4[2]) || (ipv4[2] > 0xFF) || (ipv4[2] < 0x0)
			|| isNaN(ipv4[3]) || (ipv4[3] > 0xFF) || (ipv4[3] < 0x0)) {
		return null;
	}
	
	// return the compressed form
	return ipv4[0] + "." + ipv4[1] + "."
			+ ipv4[2] + "." + ipv4[3];
}
function contains(item, array) {
	for (var i = 0; i < array.length; i++) {
		if (item == array[i]) {
			return true;
		}
	}
	return false;
}
function remExistingIp(ipvArray, ipName) {
	var goodies = new Array();
	for (var i = 0; i < ipvArray.length; i++) {
		var checkbox = document.getElementById('ck_' + ipName + '_' + i);
		if (checkbox == null || !checkbox.checked) {
			goodies.push(ipvArray[i]);
		}
	}
	ipvArray.splice(0, ipvArray.length); // remove all
	for (var i = 0; i < goodies.length; i++) {
		ipvArray[i] = goodies[i];
	}
}
function addNewIp(ipInputFieldId, ipv4Array, ipv6Array) {
	var ipInputField = document.getElementById(ipInputFieldId);
	var invalids = "";
	var input = ipInputField.value.split(/\s+/);
	ipInputField.value = "";
	for (var i = 0; i < input.length; i++) {
		if (input[i].length > 0) {
			var addr = isipv4(input[i]);
			if (addr) {
				if (!contains(addr, ipv4Array)) {
					ipv4Array.push(addr);
				}
			} else {
				addr = isipv6(input[i]);
				if (addr) {
					if (!contains(addr, ipv6Array)) {
						ipv6Array.push(addr);
					}
				} else {
					// not ipv4 or ipv6
					if (invalids.length != 0) {
						invalids = invalids + " ";
					}
					invalids = invalids + input[i];
				}
			}
		}
	}
	if (invalids.length > 0) {
		ipInputField.value = invalids;
		setFieldError(ipInputField, "invalid ip addresses");
	} else {
		resetFieldError(ipInputField);
	}
}
function drawIp(ipAddressArray, ipName, originalIpAddresses) {
	var html = "<table>";
	if (originalIpAddresses != null) {
		for (var i = 0; i < originalIpAddresses.length; i++) {
			if (!contains(originalIpAddresses[i], ipAddressArray)) {
				html += '<tr><td>&nbsp;</td><td class="deleted">' + originalIpAddresses[i] + '</td></tr>';
			}
		}
	}
	if (ipAddressArray.length > 0) {
		for (var i = 0; i < ipAddressArray.length; i++) {
			html += '<tr><td>'
				+ '<input type="checkbox" id="ck_' + ipName + '_' + i + '"/>'
				+ '<input type="hidden" name="' + ipName + '" value="'
				+ ipAddressArray[i] + '"/></td><td>'
				+ ipAddressArray[i] + '</td></tr>';
		}
	} else {
		html += "<tr><td colspan='2'>None</td></tr>";
	}
	document.getElementById(ipName).innerHTML = html + "</table>";
}
function hideElement(id) {
	if (document.getElementById) { // DOM3 = IE5, NS6
		document.getElementById(id).style.display = 'none';
	} else {
		if (document.layers) { // Netscape 4
			document.id.display = 'none';
		} else { // IE 4
			document.all.id.style.display = 'none';
		}
	}
}
function showElement(id) {
	if (document.getElementById) { // DOM3 = IE5, NS6
		document.getElementById(id).style.display = 'block';
	} else {
		if (document.layers) { // Netscape 4
			document.id.display = 'block';
		} else { // IE 4
			document.all.id.style.display = 'block';
		}
	}
}
function strikeThroughElement(id) {
	if (document.getElementById) { // DOM3 = IE5, NS6
		document.getElementById(id).style.textDecoration = 'line-through';
	} else {
		if (document.layers) { // Netscape 4
			document.id.textDecoration = 'line-through';
		} else { // IE 4
			document.all.id.style.textDecoration = 'line-through';
		}
	}
}
function unStrikeThroughElement(id) {
	if (document.getElementById) { // DOM3 = IE5, NS6
		document.getElementById(id).style.textDecoration = 'none';
	} else {
		if (document.layers) { // Netscape 4
			document.id.textDecoration = 'none';
		} else { // IE 4
			document.all.id.style.textDecoration = 'none';
		}
	}
}
function getArrayElementsAsString(theArray) {
	var result = '';
	for (var i = 0; i < theArray.length; i++) {
		result += theArray[i] + ' ';
	}
	return result;
}
function bothArraysHaveSameElements(arrayOne, arrayTwo) {
	if (arrayOne == null && arrayTwo == null) {
		return true;
	} else if (arrayOne == null && arrayTwo != null) {
		if (arrayTwo.length < 1) {
			return true;
		}
	} else if (arrayOne != null && arrayTwo == null) {
		if (arrayOne.length < 1) {
			return true;
		}
	} else if(arrayOne.length != arrayTwo.length) {
		return false;
	} else {
		for (var i = 0; i < arrayOne.length; i++) {
			if (!contains(arrayOne[i], arrayTwo)) {
				return false;
			}
		}
		return true;
	}
	return false;
}
function setSelectOptions(selectId, optionsArray, onchange) {
	var selectElementParentSpan = document.getElementById(selectId + 'Span');
	var temp = '<select onchange="' + onchange + '" id="' + selectId + '" name="' + selectId + '"><option value=""></option>';
	if (optionsArray != null) {
		for (var i = 0; i < optionsArray.length; i++) {
			temp += ('<option value="' + optionsArray[i] + '">' + optionsArray[i] + '</option>');
		}
	}
	temp += '</select>';
	selectElementParentSpan.innerHTML = temp;
}
function disableButton(button) {
	if (document.all || document.getElementById) {
		button.disabled = true;
	} else if (button) {
		button.oldOnClick = button.onclick;
		button.onclick = null;
		button.oldValue = button.value;
		button.value = 'DISABLED';
	}
}
function enableButton(button) {
	if (document.all || document.getElementById) {
		button.disabled = false;
	} else if (button) {
		button.onclick = button.oldOnClick;
		button.value = button.oldValue;
	}
}
function setSelectedIndexByValue(theSelect, theValue) {
	if (theSelect != null && theValue != null) {
		var selectOptions = theSelect.options;
		if (selectOptions != null && selectOptions.length > 1) {
			for (var i = 0; i < selectOptions.length; i++) {
				if (selectOptions[i].value == (theValue + '')) {
					theSelect.selectedIndex = i;
					break;
				}
			}
		}
	}
}
function drawDomainRegistrationPeriodSelect(createMinYears, createMaxYears,
		parentElementId, paramName, originalValue, forceRenew, defaultPeriod) {
	var parentElement = document.getElementById(parentElementId);
	var result = '';
	if (originalValue == null || originalValue == '' || originalValue < 1) {
		originalValue = defaultPeriod;
	}
	if (createMaxYears > 0 && createMinYears > 0) {
		if (createMinYears <= createMaxYears) {
			result += '<select name="' + paramName + '"/>';
			if (!forceRenew) {
				result += '<option value=""></option>';
			}
			for (var i = createMinYears; i <= createMaxYears; i++) {
				result += ('<option value="' + i + '"');
				if (i == originalValue) {
					result += ' selected="selected"';
				}
				if (i > 1) {
					result += ('>' + i + ' Years</option>');
				} else {
					result += ('>' + i + ' Year</option>');
				}
			}
			result += '</select>';
		}
	}
	parentElement.innerHTML = result;
}
function setIFrameHeightToMax(frameId) {
	var theFrame = document.getElementById(frameId)
	var minHeight = 500;
	if (theFrame.contentDocument) {  // firefox
		var temp = theFrame.contentDocument.documentElement.scrollHeight;
		if (temp < minHeight) {
			theFrame.height =  minHeight;
		} else {
			theFrame.height = temp + 10;
		}
	} else { // IE
		var temp = theFrame.contentWindow.document.body.scrollHeight;
		if (temp < minHeight) {
			theFrame.style.height =  minHeight;
		} else {
			theFrame.style.height = temp + 10;
		}
	}
}
function checkAll(fields) {
    if (fields.length) {
 		for (i = 0; i < fields.length; i++) {
			fields[i].checked = true;
		}
	} else {
	    fields.checked = true;
	}
}
function uncheckAll(fields) {
    if (fields.length) {
		for (i = 0; i < fields.length; i++) {
			fields[i].checked = false;
		}
    } else {
        fields.checked = false;
    }
}
