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("::")) {
		return null; // ambigious compression
	}
	var left; // everything to left of compression '::'
	var right; // everything right of compression '::'
	var compression = addr.split("::");
	if (compression.length == 1) {
		// no compression; store all in left, right is empty
		var left = compression[0].split(":");
		if (left.length == 7) {
			// last one must be ipv4 to be valid
			var hx = ipv4_to_hex(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 {
		// was compression; left is everything to left of compression
		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 = ipv4_to_hex(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;
		}
	}
	return ipv6_to_presentation(ipv6);
}

function ipv6_to_presentation(ipv6) {
	var presentaion = null;
	if (is_ipv4_mapped_ipv6(ipv6)) {
		presentation = "::ffff:" + ipv4_from_hex(ipv6[6], ipv6[7]);
	} else {
		presentation = "";
		for (var i = 0; i < ipv6.length; i++) {
			if (i != 0) {
				presentation = presentation + ":";
			}
			presentation = presentation + ipv6[i].toString(16);
		}
	}
	return presentation;
}

function ipv6_to_presentation_compressed(addr) {
	var posZerosStart = -1; // index beginning longest run of zeros
	var maxZerosLength = 1; // only compress if max length > 1
	var curZerosLength = 0;
	for (var i = 0; i < ipv6.length; i++) {
		if (ipv6[i] != 0) {
			if (curZerosLength > maxZerosLength) {
				posZerosStart = i - curZerosLength;
				maxZerosLength = curZerosLength;
			}
			curZerosLength = 0;
		} else {
			curZerosLength++;
		}
	}

	// catch trailing zeros
	if (curZerosLength > maxZerosLength) {
		posZerosStart = i - curZerosLength;
		maxZerosLength = curZerosLength;
	}
	
	// turn into presentation format
	presentation = "";
	for (var i = 0; i < ipv6.length; i++) {
		if (posZerosStart == i) {
			if (posZerosStart == 0) {
				presentation = presentation + ":";
			}
			presentation = presentation + ":";
			i = i + maxZerosLength - 1;
		} else {
			presentation = presentation + ipv6[i].toString(16);
			if ((i + 1) < ipv6.length) {
				presentation = presentation + ":";
			}
		}
	}
	return presentation;
}

function ipv4_from_hex(hi16, lo16) {
	return (hi16 >> 8) + "." + (hi16 & 0xff) + "." + (lo16 >> 8) + "." + (lo16 & 0xff)
}

function is_ipv4_mapped_ipv6(ipv6) {
	// high-order 80 bits are zero, next 16 bits are ones.
	return (ipv6[0] == 0 && ipv6[1] == 0 && ipv6[2] == 0 && ipv6[3] == 0 && ipv6[4] == 0 && ipv6[5] == 0xffff);
}

function ipv4_to_hex(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 ipv4hex = ipv4_to_hex(addr);
	if (ipv4hex) {
		return ipv4_from_hex(parseInt(ipv4hex[0], 16), parseInt(ipv4hex[1], 16));
	}
	return null;
}

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 setSelectOptionsFrom2DArray(selectId, optionsArray, onchange, styleClass) {
    var selectElementParentSpan = document.getElementById(selectId + 'Span');
    var temp = '<select onchange="' + onchange + '" id="' + selectId + '" name="'
        + selectId + '" class="' + styleClass + '"><option value=""></option>';
    if (optionsArray != null) {
        for (var i = 0; i < optionsArray.length; i++) {
            temp += ('<option value="' + optionsArray[i][0] + '">'
                + optionsArray[i][1].replace(/&/g,'&amp;').replace(/>/g,'&gt;').replace(/</g,'&lt;').replace(/"/g,'&quot;')
                + '</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;
    }
}
function plainText2Html(plainText) {
	var result = plainText.replace(/&/g, "&amp;");
	result = result.replace(/\'/g, "&#39;");
	result = result.replace(/\"/g, "&quot;");
	result = result.replace(/</g, "&lt;");
	result = result.replace(/>/g, "&gt;");
	return result;
}
