function getParentByClassName(element, className)
{
    var parent = element;

    if (className)
    {
        while (parent && parent.className != className)
        {
            parent = parent.parentNode;
        }
    }

    return parent;
}

function getFirstChildByClassRegex(element, tagName, classRegex, stopClassRegex)
{
    var match;
    var child = element.firstChild;

    while (child != null && (!child.className || !child.className.match(stopClassRegex)))
    {
        if (child.tagName && child.tagName == tagName && child.className && child.className.match(classRegex))
        {
            match = child;
            break;
        }
        else
        {
            match = getFirstChildByClassRegex(child, tagName, classRegex, stopClassRegex);

            if (match)
            {
                break;
            }
        }

        child = child.nextSibling;
    }

    return match;
}

function addEventToElement(target, eventType, func, useCapture)
{
    var result = false;

    if (target.addEventListener)
    {
        target.addEventListener(eventType, func, useCapture);
        result = true;
    }
    else if (target.attachEvent)
    {
        result = target.attachEvent("on" + eventType, func);
    }
    else
    {
        alert("Handler could not be attached");
    }

    return result;
}

function addEventToElements(targets, eventType, func, useCapture)
{
    var result = true;

    for (var i = 0; i < targets.length; i++)
    {
        result &= addEventToElement(targets[i], eventType, func, useCapture);
    }

    return result;
}

function removeEventFromElement(target, eventType, func, useCapture)
{
    var result = false;

    if (target.removeEventListener)
    {
        target.removeEventListener(eventType, func, useCapture);
        result = true;
    }
    else if (target.detachEvent)
    {
        result = target.detachEvent("on" + eventType, func);
    }
    else
    {
        alert("Handler could not be removed");
    }

    return result;
}

function removeEventFromElements(targets, eventType, func, useCapture)
{
    var result = true;

    for (var i = 0; i < targets.length; i++)
    {
        result &= removeEventFromElement(targets[i], eventType, func, useCapture);
    }

    return result;
}

function getEvent(event)
{
    if (!event)
    {
        var event = window.event;
    }

    return event;
}

function getEventSource(event)
{
    if (event.srcElement)
    {
        var source = event.srcElement;
    }
    else if (event.currentTarget)
    {
        var source = event.currentTarget;
    }
    else
    {
        alert("Event source not found!");
    }

    return source;
}

//var console = new Console();

function Console()
{
    this.canvas = null;
    this.println = consolePrintln;
    this.show = consoleShow;
}

function consolePrintln(object)
{
    if (!this.canvas)
    {
        this.canvas = window.open("about:blank", "Console", "toolbar = no, width = 640, height = 480, directories = no, status = no, scrollbars = yes, resize = no, menubar = no");
    }

    this.canvas.document.write(object);
    this.canvas.document.write("<br/>");
}

function consoleShow(object)
{
    this.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");

    for (property in object)
    {
        this.println(property + " = " + eval("object." + property));
    }

    this.println("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");
}

/* ********************************************** */
/* Begin functions added for dialog support.      */
/* ********************************************** */

var isIE6withDocType=document.documentElement && document.documentElement.clientHeight;
var isDOM=document.getElementById&&!document.all;

var isDialogDisplayed = false;
var dialogHeight = 0;
var dialogWidth = 0;
var theDialogDiv;
var oldDialogInnerHTML;

function toggleDialogBox(theId,height,width,title,showBackground, resizeOnScroll)
{
    theDialogDiv = document.getElementById(theId);
	dialogHeight = height;
	dialogWidth = width;
	isDialogDisplayed = !isDialogDisplayed;
	dialogBkgdDiv = document.getElementById("dialogBackgroundDiv");

	title = htmlChars(title);

	if (isDialogDisplayed)
	{
        if((showBackground == null) || showBackground)
        {
    	    addDialogTitle(title);
        }
        else
        {
            oldDialogInnerHTML = theDialogDiv.innerHTML;
            theDialogDiv.className = "hiddenDialogDiv";
        }
		setDialogSizeAndPos();
	} else
	{
		theDialogDiv.innerHTML = oldDialogInnerHTML;
	}
	toggleDialogBkgd();
	var viz = isDialogDisplayed ? "visible" : "hidden";
	theDialogDiv.style.visibility = viz;

    if (isDialogDisplayed)
	{
		var keepGoing = true;
		var divElements = theDialogDiv.getElementsByTagName('INPUT');
		for (i=0; i<divElements.length && keepGoing; i++)
		{
			if (divElements[i].type=="text")
			{
				divElements[i].focus();
				divElements[i].select();
				keepGoing = false;
			}
		}

		// if there is no text type, let us select the select type....
		if(keepGoing == true)
		{
            divElements = theDialogDiv.getElementsByTagName('SELECT');
            for (i=0; i<divElements.length; i++)
            {
                divElements[i].focus();
                break;
			}
		}
	}

    if((resizeOnScroll == null) || resizeOnScroll)
    {
        onresize=setDialogSizeAndPos;
        onscroll=setDialogSizeAndPos;
    }
    else
    {
        onresize=null;
        onscroll=null;
    }
}

function addDialogTitle(title)
{
	oldDialogInnerHTML = theDialogDiv.innerHTML;
	title = title ? title : "&nbsp;";

	var titleDiv = "<div class='table-label-bottom' ";
	titleDiv += "style='vertical-align:top;text-align:left;padding:6px;'>\n";
	titleDiv += "<span class='text_bold_12px'>" + title + "</span>\n";
	titleDiv += "</div>\n";
	titleDiv += "<div style='padding:6px;'>\n";
	theDialogDiv.innerHTML = titleDiv + oldDialogInnerHTML + "\n</div>\n";
}

function toggleDialogBkgd()
{
    var keepGoing = true;
	var dbdViz = isDialogDisplayed ? "visible" : "hidden";
	var hfdViz = isDialogDisplayed ? "none" : "block";

	var divElements = document.getElementsByTagName('SELECT');
	for (i=0; i<divElements.length; i++)
	{
		divElements[i].style.display = hfdViz;
	}

	if (isDialogDisplayed)
	{
		divElements = theDialogDiv.getElementsByTagName('SELECT');
		for (i=0; i<divElements.length; i++)
		{
			divElements[i].style.display = "block";
		}
	}

	dialogBkgdDiv.style.visibility = dbdViz;
}

function setDialogSizeAndPos()
{
    resetDialogSizeAndPos(dialogHeight, dialogWidth)
}

function getDialogHeight()
{
    return dialogHeight;
}

function getDialogWidth()
{
    return dialogWidth;
}

function resetDialogSizeAndPos(height, width)
{
    dialogHeight = height;
    dialogWidth = width

	if (isDialogDisplayed)
	{
		var base;

		if (isIE6withDocType)
		{
			base = document.documentElement;
		} else
		{
			base = document.body;
		}

		var ch = base.clientHeight;
		var sh = base.scrollHeight;
		var cw = base.clientWidth;
		var sw = base.scrollWidth;

		var theTop;
		var theLeft;

		if ( (ch - height) < 0 )
		{
			theTop = base.scrollTop;
		} else {
			theTop = parseInt((ch - height)/2) + base.scrollTop;
		}

		if ( (cw - width) < 0 )
		{
			theLeft = base.scrollLeft;
		} else {
			theLeft = parseInt((cw - width)/2) + base.scrollLeft;
		}

        if (isDOM)
		{
			// Appears to be Mozilla
			dialogBkgdDiv.style.height = ((ch > sh)? ch : sh) + "px";
			dialogBkgdDiv.style.width = ((cw > sw)? cw : sw) + "px";
			theDialogDiv.style.top = theTop + "px";
			theDialogDiv.style.left = theLeft + "px";
			theDialogDiv.style.height = height + "px";
			theDialogDiv.style.width = width + "px";
		} else
		{
			dialogBkgdDiv.style.height = (ch > sh)? ch : sh;
			dialogBkgdDiv.style.width = (cw > sw)? cw : sw;
			theDialogDiv.style.top = theTop;
			theDialogDiv.style.left = theLeft;
			theDialogDiv.style.height = height;
			theDialogDiv.style.width = width;
		}
	}
}

//onresize=setDialogSizeAndPos;
//onscroll=setDialogSizeAndPos;

function showWaitState()
{
    var waitDiv = document.getElementById("waitDiv");
	if (waitDiv != null)
	{
		waitDiv.style.visibility = "visible";
	}
}

function checkEnter(e, evalOK, evalCancel)
{
	e = isIE ? window.event : e;
	var characterCode = e.keyCode;

	if(characterCode == 13)
	{
		eval(evalOK);
	} else if (characterCode == 27)
	{
		if (evalCancel != null) eval(evalCancel);
		toggleDialogBox(theDialogDiv.id);
	}
}

function htmlChars(source)
{
   if(source == null)
       return source;

   var target = source;

   target = target.replace(/&/g, "&amp;");
   target = target.replace(/</g, "&lt;");
   target = target.replace(/>/g, "&gt;");

   return target;
}

/* ********************************************** */
/* End functions added for dialog support.        */
/* ********************************************** */

/* ********************************************** */
/* Start functions added for form validation      */
/* ********************************************** */
function isValidCC(cardNumber, cardType)
{
  var isValid = false;
  var ccCheckRegExp = /[^\d ]/;
  isValid = !ccCheckRegExp.test(cardNumber);

  if (isValid)
  {
    var cardNumbersOnly = cardNumber.replace(/ /g,"");
    var cardNumberLength = cardNumbersOnly.length;
    var lengthIsValid = false;
    var prefixIsValid = false;
    var prefixRegExp;

    switch(cardType)
    {
      case "mastercard":
        lengthIsValid = (cardNumberLength == 16);
        prefixRegExp = /^5[1-5]/;
        break;

      case "visa":
        lengthIsValid = (cardNumberLength == 16 || cardNumberLength == 13);
        prefixRegExp = /^4/;
        break;

      case "amex":
        lengthIsValid = (cardNumberLength == 15);
        prefixRegExp = /^3(4|7)/;
        break;

      default:
        prefixRegExp = /^$/;
        alert("Card type not found");
    }

    prefixIsValid = prefixRegExp.test(cardNumbersOnly);
    isValid = prefixIsValid && lengthIsValid;
  }

  if (isValid)
  {
    var numberProduct;
    var numberProductDigitIndex;
    var checkSumTotal = 0;

    for (digitCounter = cardNumberLength - 1;
      digitCounter >= 0;
      digitCounter--)
    {
      checkSumTotal += parseInt (cardNumbersOnly.charAt(digitCounter));
      digitCounter--;
      numberProduct = String((cardNumbersOnly.charAt(digitCounter) * 2));
      for (var productDigitCounter = 0;
        productDigitCounter < numberProduct.length;
        productDigitCounter++)
      {
        checkSumTotal +=
          parseInt(numberProduct.charAt(productDigitCounter));
      }
    }

    isValid = (checkSumTotal % 10 == 0);
  }

  return isValid;
}

function isNotEmpty(elem) {
	var str = elem.value;
    var re = /.+/;
    if(!str.match(re)) {
        return false;
    } else {
        return true;
    }
}

function parseDate(elem) {
    var str = elem.value;
    var list = str.split("-");
    var date = new Date(pnetDate_fullMonths[list[1]] + " " + list[0] + ", " + list[2]);
    return date;
}

//validates that the entry is a positive or negative number
function isNumber(elem) {
	var str = elem.value;
    var re = /^[-]?\d*\.?\d*$/;
    str = str.toString();
    if (!str.match(re)) {
        return false;
    }
    return true;
}
// validates that the entry is 16 characters long
function isLen16(elem) {
	var str = elem.value;
    var re = /\b.{16}\b/;
    if (!str.match(re)) {
        return false;
    } else {
        return true;
    }
}
// validates that the entry is formatted as an e-mail address
function isEmailAddr(elem) {
	var str = elem.value;
    var re = /^[\w-]+(\.[\w-]+)*@([\w-]+\.)+[a-zA-Z]{2,7}$/;
    if (!str.match(re)) {
        return false;
    } else {
        return true;
    }
}
// validate that the user made a selection other than default
function isChosen(select) {
    if (select.selectedIndex == 0) {
        return false;
    } else {
        return true;
    }
}

// validate that the user has checked one of the radio buttons
function isValidRadio(radio) {
    var valid = false;
    for (var i = 0; i < radio.length; i++) {
        if (radio[i].checked) {
            return true;
        }
    }
    return false;
}

function focusElement(formName, elemName) {
    var elem = document.forms[formName].elements[elemName];
    elem.focus();
    elem.select();
}

/* ********************************************** */
/* Start functions added for toggling divs        */
/* ********************************************** */
function toggleEdits(roDiv, formDiv, number) {

    var cancelLink = "_cancelLink" + number;
    if (document.getElementById(roDiv).style.display == "none") {
        document.getElementById(roDiv).style.display = "block";
        document.getElementById(formDiv).style.display = "none";
        document.getElementById(cancelLink).style.display = "none";
        toggleEditLinks('on', number);
    } else {
        document.getElementById(roDiv).style.display = "none";
        document.getElementById(formDiv).style.display = "block";
        document.getElementById(cancelLink).style.display = "block";
        toggleEditLinks('off', number);
    }
}

function toggleEditLinks(status, number) {
    if (status == 'on') {
        for (var i = 0; i < 20; i++) {
            var elem = document.getElementById("_editLink" + i);
            if (elem) {
                if (i == number) {
                    elem.style.display = "block";
                } else {
                    elem.style.visibility = "visible";
                }
            }
        }
    }
    else {
        for (var i = 0; i < 20; i++) {
            var elem = document.getElementById("_editLink" + i);
            if (elem) {
                if (i == number) {
                    elem.style.display = "none";
                } else {
                    elem.style.visibility = "hidden";
                }
            }
        }
    }
}

function trim() {
    //Match spaces at beginning and end of text and replace
    //with null strings
    return this.replace(/^\s+/,'').replace(/\s+$/,'');
}

String.prototype.trim = trim;

function trimFields(form)
{
    if(form != null)
    {
        for(i=0; i < form.elements.length; i++)
        {
            if(form.elements[i].type == "text" || form.elements[i].type == "textarea")
            {
                form.elements[i].value = form.elements[i].value.trim();
            }
        }
    }
}

var pnetDate_months = new Array();
pnetDate_months[0] = "Jan";
pnetDate_months[1] = "Feb";
pnetDate_months[2] = "Mar";
pnetDate_months[3] = "Apr";
pnetDate_months[4] = "May";
pnetDate_months[5] = "Jun";
pnetDate_months[6] = "Jul";
pnetDate_months[7] = "Aug";
pnetDate_months[8] = "Sep";
pnetDate_months[9] = "Oct";
pnetDate_months[10] = "Nov";
pnetDate_months[11] = "Dec";

var pnetDate_fullMonths = new Array();
pnetDate_fullMonths["Jan"] = "January";
pnetDate_fullMonths["Feb"] = "February";
pnetDate_fullMonths["Mar"] = "March";
pnetDate_fullMonths["Apr"] = "April";
pnetDate_fullMonths["May"] = "May";
pnetDate_fullMonths["Jun"] = "June";
pnetDate_fullMonths["Jul"] = "July";
pnetDate_fullMonths["Aug"] = "August";
pnetDate_fullMonths["Sep"] = "September";
pnetDate_fullMonths["Oct"] = "October";
pnetDate_fullMonths["Nov"] = "November";
pnetDate_fullMonths["Dec"] = "December";

var _MINUTE = 60 * 1000;
var _HOUR = _MINUTE * 60;
var _DAY = _HOUR * 24;
var _WEEK = _DAY * 7;
var _YEAR = _WEEK * 52;

function isWholeNumber(value)
{
    var wholeNum = /^\d+$/;

    return wholeNum.test(value);
}

function printTabs(page, section, pageLabel) {
    if (!page) { return false; }
    if (!section) { return false; }
    if (!pageLabel) { return false; }

    var url = "/apps/portalApp/printTabs.jsp?p=" + page + "&s=" + section + "&pl=" + pageLabel;
    window.open(encodeURI(url), 'printable', 'scrollbars,resizable');
}

function GBEntry(iname, iurl, icountry, icomments) {
	this.name = iname;
	this.url = iurl;
	this.country = icountry;
	this.comments = icomments; 
}

var req;

function loadXMLDoc(url) 
{
    // branch for native XMLHttpRequest object
    if (window.XMLHttpRequest) {
        req = new XMLHttpRequest();
        req.onreadystatechange = processReqChange;
        req.open("GET", url, true);
        req.send(null);
    // branch for IE/Windows ActiveX version
    } else if (window.ActiveXObject) {
        req = new ActiveXObject("Microsoft.XMLHTTP");
        if (req) {
            req.onreadystatechange = processReqChange;
            req.open("GET", url, true);
            req.send();
        }
    }
}

function processReqChange() 
{
    // only if req shows "complete"
    if (req.readyState == 4) {
        // only if "OK"
        if (req.status == 200) {
			var response = req.responseXML.documentElement;
		 	showLatestKMPic(response);
        } else {
            alert("There was a problem retrieving the XML data:\n" + req.statusText);
        }
    }
}

function showLatestKMPic(iresponse) {
   if (iresponse != null) {
	    var title = iresponse.getElementsByTagName('title')[1].firstChild.data;
        var content = iresponse.getElementsByTagName('content')[0].firstChild.data;
		var link = iresponse.getElementsByTagName('link')[9].getAttribute("href");
		var start = content.indexOf('img src="') + 9;
		var stop = content.indexOf('"', start);
        content = content.substring(start, stop);
        html = '<div id="moblog-title">' + title + '</div>';
        content = '<a href="' + link + '" target="km"><img src="' + content + '" width="200" class="moblog-pic"></a>'; 
	html += '<div id="moblog-content">' + content + '</div>';
	document.getElementById('moblog').innerHTML = html;
    setTimeout("showLatestKMPic(null)", 180000);
   } else {
	   var url = '/cgi-bin/km.cgi';
	   loadXMLDoc(url);
   }
   
}

window.onload = showLatestKMPic(null);
