/* Contains javascript for Lyza Commons
 * @author Dave Brown
 */

var isDirty = false;
var savingForm = false;
var loadBlurbs = true;
var okToExit = false;
var renewLockTimeout = null;

function confirmExit()
{
    if( isDirty && !savingForm ) {
        return "You have attempted to leave the page. If you have made any changes to the data without clicking the Apply button, your changes will be lost.  Are you sure you want to exit this page?";
    }
}

// AJAX stuff
var httpObjs = new Array(10);

for( var i = 0; i < httpObjs.length; i++ ) {
    httpObjs[i] = null;
}

String.prototype.unescapeHtml = function () {
    var temp = document.createElement("div");
    temp.innerHTML = this;
    var result = temp.childNodes[0].nodeValue;
    temp.removeChild(temp.firstChild);
    return result;
}

function trimToPixels(text, length, fontSize)
{
    var tmp = text;
    var trimmed = text;
    if (visualLength(trimmed, fontSize) > length)
    {
        trimmed += "...";
        while( visualLength(trimmed) > length) {
            tmp = tmp.substring(0, tmp.length-1);
            trimmed = tmp + "...";
        }
    }
    return trimmed;
}

function breakAtWidth(text, width, fontSize)
{
    var tmp = '';
    var currentChar = 0;
    var currentLength = 0;
    var charPos = 0;
    var returnString = '';
    var charsSinceSpace = 0;
    var lastSpaceCharPos = -1;
    var charWidth = visualLength(text, fontSize)/text.length;

    while( charPos < text.length ) {
        currentChar = text.charAt(charPos);
        if( currentChar == ' ') {
            lastSpaceCharPos = tmp.length;
            charsSinceSpace = 0;
        }
        tmp += currentChar;
        var charLength = charWidth;
        if( charLength+currentLength >= width ) {
            if( lastSpaceCharPos != -1 ) {
                returnString += tmp.substring(0, lastSpaceCharPos) + '<br>';
                currentLength = (tmp.length-lastSpaceCharPos)*charWidth;
                tmp = tmp.substring(lastSpaceCharPos);
                charsSinceSpace = 0;
                lastSpaceCharPos = -1;
            } else {
                returnString += tmp + '<br />';
                tmp = '';
                currentLength = 0;
            }
        } else {
            if( lastSpaceCharPos != -1) {
                charsSinceSpace++;
            }
            currentLength += charLength;
        }
        charPos++;
    }
    if( tmp.length > 0 ) {
        returnString += tmp;
    }
    return nl2br(returnString);
}


function getQueryParameter(url, name )
{
    name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
    var regexS = "[\\?&]"+name+"=([^&#]*)";
    var regex = new RegExp( regexS );
    var results = regex.exec( url );
    if( results == null )
        return "";
    else
        return results[1];
}


function visualLength(text, fontSize) {

    if( fontSize == null ) {
        fontSize = 10;
    }
    var ruler = window.document.getElementById('ruler');
    ruler.style.fontSize = fontSize + 'px';
    ruler.innerHTML = text;
    return ruler.offsetWidth;
}

function checkEmailAddress(emailAddress){
    var filter=/^.+@.+\..{2,3}$/

    if (filter.test(emailAddress))
        return true;
    else {
        return false;
    }
}

function onKeyDownTrapEnter(e, maxChars, enterCallback) {

    if (typeof e == 'undefined') {
        e = window.event;
    }
    var source;
    if (typeof e.target != 'undefined') {
        source = e.target;
    }
    else if (typeof e.srcElement != 'undefined') {
        source = e.srcElement;
    }
    if( (e.which == 13 || e.keyCode == 13) && !e.shiftKey ) {
        enterCallback();
    } else {
        limitText(source, maxChars);
    }
}

function nl2br(text){
    var re_nlchar = null;
    text = escape(text);
    if(text.indexOf('%0D%0A') > -1){
        re_nlchar = /%0D%0A/g ;
    }else if(text.indexOf('%0A') > -1){
        re_nlchar = /%0A/g ;
    }else if(text.indexOf('%0D') > -1){
        re_nlchar = /%0D/g ;
    }
    if( re_nlchar != null ) {
        return unescape( text.replace(re_nlchar,'<br />') );
    } else {
        return unescape(text);
    }
}

function activePegboardLink() {
// empty stub, will be overriden if in commonsView
}

function addTermAndSearch(term) {
    var searchField =  document.getElementById('searchField');
    if( term.indexOf(' ' ) > -1 ) {
        term = '"' + term + '"';
    }
    searchField.value = term;
    document.getElementById('searchForm').submit();
    return false;
}

function clearSearchTerms() {
    document.getElementById('searchField').value = '';
    
}

function addFilterAndSearch(filter, tag, overwrite) {
    var searchField =  document.getElementById('searchField');
    var filterString = filter + '"' + tag + '"';
    if( overwrite == null || !overwrite ) {
        if( searchField.value.toLowerCase().indexOf(filterString.toLowerCase()) == -1) {
            if( searchField.value.length > 0 ) {
                searchField.value += ' ';
            }
            searchField.value += filterString;
        }
    }
    else {
        searchField.value = filterString;
    }
    document.getElementById('searchForm').submit();
    return false;
}

function sendRequest(url, callback, method)
{
    httpObj = getAvailableHTTP();
    httpObj.open(method, url, true);
    httpObj.onreadystatechange = onData;
    httpObj.callback = callback;
    httpObj.send(null);
}

function sendRequestSynchronous(url, callback, method)
{
    httpObj = getAvailableHTTP();
    httpObj.open(method, url, false);
    // httpObj.onreadystatechange = onData;
    //httpObj.callback = callback;
    httpObj.send(null);
}
function newHTTP()
{
    try {
        return new XMLHttpRequest();
    } catch (e) {
        return new ActiveXObject("Microsoft.XMLHTTP");
    }
}
function onData()
{
    i = getReadyHTTP();
    if ( i != -1 ) {
        if( httpObjs[i].status != 200 ) {
        // alert("Error sending request to server. Please ensure the Commons Server is running.");
        }
        else {
            var response = eval("(" + httpObjs[i].responseText + ")");
            if( eval(httpObjs[i].callback) ) {
                httpObjs[i].callback(httpObjs[i].status, response);
            }
        }
        httpObjs[i] = null;
    }
}

function getAvailableHTTP()
{
    for( var i = 0; i < httpObjs.length; i++ ) {
        if( httpObjs[i] == null ) {
            httpObjs[i] = newHTTP();
            return httpObjs[i];
        }
    }
}

function getReadyHTTP()
{
    for( var i = 0; i < httpObjs.length; i++ ) {
        if( httpObjs[i] != null && httpObjs[i].readyState == 4 ) {
            return i;
        }
    }
    return -1;
}

function recommendObject(dataObjectId)
{
    if (!window.focus)
        return true;

    var win = window.open("recommend.jsp?id=" + dataObjectId, 'recommend', 'width=350,height=260,scrollbars=no');
    win.focus();
    return false;
}

function traceLineage(name, dataObjectId, workbookId, operatorModelId, columnModelId, action)
{
    if (!window.focus) {
        return true;
    }
    var win = window.open("traceLineage.jsp?id=" + dataObjectId + "&workbookId=" + workbookId +  "&operatorModelId=" + operatorModelId + "&columnModelId=" + columnModelId + "&action=" + action, '_blank');
    return false;
}



function addOption(selectControl, text, value, classname)
{
    var newOpt = new Option(text, value);
    var selLength = selectControl.length;
    selectControl.options[selLength] = newOpt;
    selectControl.options[selLength].className = classname;
}
    

function openPrintView(url)
{
    if (!window.focus)
        return true;

    var win = window.open(url, 'printview', 'width=800,height=550,scrollbars=yes');
    win.focus();
    return false;
}


function displayColumnList(dataObjectId, modelType)
{
    if (!window.focus)
        return true;

    width = 250;
    height = 375;
    window.open('consumables/columnList.jsp?id=' + dataObjectId + '&model_type=' + modelType, 'columnlist', 'width=' + width + ',height=' + height + ',scrollbars=no,resizable=yes');
    return false;
}

function trim(str) {
    str = str.replace(/^\s+/, '');
    for (var i = str.length - 1; i >= 0; i--) {
        if (/\S/.test(str.charAt(i))) {
            str = str.substring(0, i + 1);
            break;
        }
    }
    return str;
}

function endsWith(str, s){
    var reg = new RegExp (s + "$");
    return reg.test(str);
}

function startsWith(str, s){
    var reg = new RegExp("^" + s);
    return reg.test(str);
}

var aryRequired = new Array();
var intArrayCount = 0;
var requiredFields = "The following fields are required:\n\n";

function defineRequired(strElementName, strDisplayMessage, blnIsEmail, blnIsNumber)
{
    var objRequired = new Object();
    objRequired.ElementName = strElementName;
    objRequired.DisplayMessage = strDisplayMessage;
    objRequired.IsEmail = blnIsEmail;
    objRequired.IsNumber = blnIsNumber;
    aryRequired[intArrayCount] = objRequired;
    intArrayCount++;
}

function checkForm(objForm)
{
    for (var i = 0; i < aryRequired.length; i++) {
        var blnFail = true;
        var objElement = document.getElementsByName(aryRequired[i].ElementName)[0];
        if (objElement.value != "") {
            if (aryRequired[i].IsEmail){
                if (checkEmail(objElement.value))
                    blnFail = false;
            }
            else if (aryRequired[i].IsNumber) {
                if (!isNaN(objElement.value))
                    blnFail = false;
            }
            else
                blnFail = false;
        }

        if (blnFail) {
            alert(requiredFields);
            if (objElement.length && !objElement.type)
                objElement[0].focus();
            else
                objElement.focus();
            return false;
        }
    }
    savingForm = true;
    return true;
}

function oninputblur(e) {

    if (typeof e == 'undefined') {
        var e = window.event;
    }
    var source;
    if (typeof e.target != 'undefined') {
        source = e.target;
    }
    else if (typeof e.srcElement != 'undefined') {
        source = e.srcElement;
    }
    else {
        return true;
    }
    if ( source.value != tempInputValue ) {
        isDirty = true;
    }
}
function oninputfocus(e)
{
    if (typeof e == 'undefined') {
        var e = window.event;
    }
    var source;
    if (typeof e.target != 'undefined') {
        source = e.target;
    }
    else if (typeof e.srcElement != 'undefined') {
        source = e.srcElement;
    } else {
        return true;
    }
    tempInputValue = source.value;
}


function addEvent(obj, evType, fn){

    if ( obj.addEventListener ){
        obj.addEventListener(evType, fn, false);
        return true;
    }
    else if (obj.attachEvent){
        var r = obj.attachEvent("on"+evType, fn);
        return r;
    }
    else {
        return false;
    }
}

function insertAfter(parent, node, referenceNode)
{
    parent.insertBefore(node, referenceNode.nextSibling);
}

function clearText(event, defaultText, typedTextClass)
{
    onInputFocus(event);
    var evt = window.event || event;
    if (!evt.target) { //if event obj doesn't support e.target, presume it does e.srcElement
        evt.target = evt.srcElement //extend obj with custom e.target prop
    }
    textField = evt.target;
    if( textField.value == defaultText ) {
        textField.value = "";
    }
    textField.className = typedTextClass;
}

function clearTextColor(event, defaultText, textColor)
{
    onInputFocus(event);
    var evt = window.event || event;
    if (!evt.target) { //if event obj doesn't support e.target, presume it does e.srcElement
        evt.target = evt.srcElement //extend obj with custom e.target prop
    }
    textField = evt.target;
    if( textField.value == defaultText ) {
        textField.value = "";
    }
    textField.style.color = textColor;
}


function clearTextCommonsInput(event, defaultText)
{
    var evt = window.event || event;
    if (!evt.target) { //if event obj doesn't support e.target, presume it does e.srcElement
        evt.target = evt.srcElement //extend obj with custom e.target prop
    }
    textField = evt.target;
    if( textField.value == 'Password')
    {
        var passwordInput = document.createElement('input');
        passwordInput.id = textField.id;
        if( textField.value == defaultText ) {
            passwordInput.value = '';
        }
        passwordInput.type = 'password';
        passwordInput.style.height = textField.style.height;
        passwordInput.style.width = textField.style.width;
        document.getElementById(textField.id).parentNode.replaceChild(passwordInput, document.getElementById(textField.id));
        window.setTimeout(function(){
            passwordInput.focus();
        }, 0);
    } else if ( textField.value == 'Username' ) {
        if( textField.value == defaultText ) {
            textField.value = '';
        }
        textField.style.color = 'black';
        textField.style.fontStyle = '';
    }
}

// returns true if the string only contains characters A-Z or a-z
function isAlpha(str){
    var re = /[^a-zA-Z]/g
    if (re.test(str)) return false;
    return true;
}

/* START commonsSearch object */

if (!commonsSearch)	var commonsSearch = {};

commonsSearch.init = function ()
{
    this.clearBtn = false;
}

// called when on user input - toggles clear fld btn
commonsSearch.onChange = function (fldID, btnID)
{
    // check whether to show delete button
    var fld = document.getElementById( fldID );
    var btn = document.getElementById( btnID );
    if (fld.value.length > 0 && !this.clearBtn)
    {
        btn.style.background = "white url('images/srch_r_f2.gif') no-repeat top left";
        btn.fldID = fldID; // btn remembers it's field
        btn.onclick = this.clearBtnClick;
        this.clearBtn = true;
    } else if (fld.value.length == 0 && this.clearBtn)
{
        btn.style.background = "white url('images/srch_r.gif') no-repeat top left";
        btn.onclick = null;
        this.clearBtn = false;
    }
}


// clears field
commonsSearch.clearFld = function (fldID,btnID)
{
    var fld = document.getElementById( fldID );
    fld.value = "";
    this.onChange(fldID,btnID);
}

// called by btn.onclick event handler - calls clearFld for this button
commonsSearch.clearBtnClick = function ()
{
    commonsSearch.clearFld(this.fldID, this.id);
    // must be defined by user
    clearSearch();
}

/* END commonsSearch object */


/* for tooltips */
var prevTooltip;

/* for exhibit options menu*/
var prevPopupMenu = null;
var popupTriggerDiv = null;


function onClickHandler(e) {

    var evt = window.event || e
    if (!evt.target) { //if event obj doesn't support e.target, presume it does e.srcElement
        evt.target = evt.srcElement //extend obj with custom e.target prop
    }

    if( popupTriggerDiv != evt.target && prevPopupMenu != null) {
        hidePopupMenu();

    }
    return true; // i.e. follow the link
}



function popupMenu(e, menuData) {

    var windowWidth = getWindowWidth();

    var evt = window.event || e;
    if (!evt.target) { //if event obj doesn't support e.target, presume it does e.srcElement
        evt.target = evt.srcElement //extend obj with custom e.target prop
    }
    popupTriggerDiv = evt.target;

    popupMenuDiv = document.createElement('div');
    popupMenuDiv.id = 'popupMenu';

    if( prevPopupMenu ) {
        prevPopupMenu.style.visibility = 'hidden';
    }

    var height = 0;
    for( var i = 0; i < menuData.menuItems.length; i++ ) {
        menuItemDiv = document.createElement('div');
        menuItemDiv.className = 'popupMenuItem';
        menuItemDiv.innerHTML = '<a href="#" onclick="popupMenuClickHandler(\'' + menuData.menuItems[i].option + '\',\'' + menuData.divId + '\' )">' + menuData.menuItems[i].displayText + '</a>';
        popupMenuDiv.appendChild(menuItemDiv);

        height += 16;
        if( i+1 < menuData.menuItems.length ) {
            menuSepDiv = document.createElement('div');
            menuSepDiv.className = 'popupMenuSeperator';
            popupMenuDiv.appendChild(menuSepDiv);
            height += 3;
        }
    }

    document.body.appendChild(popupMenuDiv);

    if(popupMenuDiv.style.visibility == 'visible') {
        popupMenuDiv.style.visibility = 'hidden';
    } else {

        if(popupMenuDiv.offsetWidth) {
            ew = popupMenuDiv.offsetWidth;
        } else if(popupMenuDiv.clip.width) {
            ew = popupMenuDiv.clip.width;
        }

        y = mouseY(e) + 16;
        x = mouseX(e) - (ew / 4);

        if (x < 2) {
            x = 2;
        } else if(x + ew > windowWidth) {
            x = windowWidth - ew - 4;
        }
        popupMenuDiv.style.height = height + 'px';
        popupMenuDiv.style.left = x + 'px';
        popupMenuDiv.style.top = y + 'px';
        popupMenuDiv.style.visibility = 'visible';

        prevPopupMenu = popupMenuDiv;
        document.documentElement.onclick = onClickHandler;
    }
}

function hidePopupMenu() {
    if( prevPopupMenu ) {
        document.body.removeChild(prevPopupMenu);
        prevPopupMenu = null;
    }
}

function getWindowWidth() {

    if(window.innerWidth) {
        return window.innerWidth;
    }

    return document.body.clientWidth
}

function mouseX(e) {

    if(e.pageX) {
        return e.pageX;
    }
    return e.clientX + (document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft);
}

function mouseY(e) {

    if(e.pageY) {
        return e.pageY;
    }

    return e.clientY + (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop);
}

function tooltip(e, o) {

    var windowWidth = getWindowWidth();

    o = document.getElementById(o);

    if( o == null ) {
        return;
    }
    if(prevTooltip && prevTooltip != o) {
        prevTooltip.style.visibility = 'hidden';
    }

    if(o.style.visibility == 'visible') {
        o.style.visibility = 'hidden';
    } else {

        if(o.offsetWidth) {
            ew = o.offsetWidth;
        } else if(o.clip.width) {
            ew = o.clip.width;
        }

        y = mouseY(e) + 16;
        x = mouseX(e) - (ew / 4);

        if (x < 2) {
            x = 2;
        } else if(x + ew > windowWidth) {
            x = windowWidth - ew - 4;
        }

        o.style.left = x + 'px';
        o.style.top = y + 'px';

        o.style.visibility = 'visible';

        prevTooltip = o;
    }
}


// blurb stuff
function sendLink(subject, blurbText) {

    document.getElementById('blurb').value = blurbText;
    var subjectControl = document.getElementById('subject');
    subjectControl.value = subject;
    document.getElementById('blurb').focus();
    return false;
}

function urlify(text) {
    var urlRegex = /([^\"]https?:\/\/[^\s]+)/g;
    return text.replace(urlRegex, function(url) {
        return '<a href="' + url + '">' + url + '</a>';
    })
}

function limitText(limitField, limitNum, associatedButton) {

    if (limitField.value.length > limitNum) {
        limitField.value = limitField.value.substring(0, limitNum);
    } else {
    //    document.getElementById('remainingChars').innerHTML = limitNum - limitField.value.length + ' <fmt:message key="blurbs.remainingChars" />';
    }

    if( associatedButton != null ) {
        associatedButton.disabled = (limitField.value.length == 0);
    }
}

function addTag(dataObjectTagsDiv, tagId, tag) {

    dataObjectTagsDiv.innerHTML += tag;

}

function renewDataObjectLock(dataObjectId) {
    sendRequest('renewDataObjectLock.htm?dataObjectId=' + dataObjectId, renewDataObjectLockCallback, 'POST');
    return false;
}

function releaseDataObjectLock(dataObjectId) {
    sendRequestSynchronous('releaseDataObjectLock.htm?dataObjectId=' + dataObjectId, releaseDataObjectLockCallback, 'POST');
    return false;
}

function releaseDataObjectLockCallback(status, response){
    okToExit = true;
    
}
function renewDataObjectLockCallback(status, response){
    if( response.status == 0 ) {
        renewLockTimeout = setTimeout("renewDataObjectLock('" + response.dataObjectId + "')", 60000);
    }
    else {
        alert("Error resetting lock.");
    }
}
function waitForReleaseDataObjectLock() {
    if ( okToExit ){
        changeFilter('all', 0);
    }
    else {
        setTimeout(waitForReleaseDataObjectLock, 10);
    }
}

function toggle(div_id, parent) {
    var el = parent == null ? document.getElementById(div_id) : document.getElementById(div_id);
    if ( el.style.display == 'none' ) {
        el.style.display = 'block';
    }
    else {
        el.style.display = 'none';
    }
}

function openCenteredPopup(url, name, w, h)
{
    // Fudge factors for window decoration space.
    // In my tests these work well on all platforms & browsers.
    w += 32;
    h += 96;
    wleft = (screen.width - w) / 2;
    wtop = (screen.height - h) / 2;
    // IE5 and other old browsers might allow a window that is
    // partially offscreen or wider than the screen. Fix that.
    // (Newer browsers fix this for us, but let's be thorough.)
    if (wleft < 0) {
        w = screen.width;
        wleft = 0;
    }
    if (wtop < 0) {
        h = screen.height;
        wtop = 0;
    }
    var win = window.open(url,
        name,
        'width=' + w + ', height=' + h + ', ' +
        'left=' + wleft + ', top=' + wtop + ', ' +
        'location=no, menubar=no, ' +
        'status=no, toolbar=no, scrollbars=no, resizable=yes');
    win.resizeTo(w, h);
    // Just in case left and top are ignored
    win.moveTo(wleft, wtop);
    win.focus();
    return win;
}

function blanket_size(popUpDivVar, popupWidth, popupHeight, iframe) {
    var viewportheight;
    if (typeof window.innerWidth != 'undefined') {
        viewportheight = window.innerHeight;
    } else {
        viewportheight = document.documentElement.clientHeight;
    }
    var blanket_height = viewportheight;
    if( !iframe ) {
        if ((viewportheight > document.body.parentNode.scrollHeight) && (viewportheight > document.body.parentNode.clientHeight)) {
            blanket_height = viewportheight;
        } else {
            if (document.body.parentNode.clientHeight > document.body.parentNode.scrollHeight) {
                blanket_height = document.body.parentNode.clientHeight;
            } else {
                blanket_height = document.body.parentNode.scrollHeight;
            }
        }
    }

    var blanket = document.getElementById('blanket');
    blanket.style.height = blanket_height + 'px';
    var popUpDiv = document.getElementById(popUpDivVar);
    popUpDiv_height=blanket_height/2-(popupHeight/2); // half popup's height
    popUpDiv.style.top = popUpDiv_height + 'px';
}

function window_pos(popUpDivVar, popupWidth, popupHeight, iframe) {
    var viewportwidth;
    if (typeof window.innerWidth != 'undefined') {
        viewportwidth = window.innerWidth;
    } else {
        viewportwidth = document.documentElement.clientWidth;
    }
    window_width = viewportwidth;
    if( !iframe ) {
        if ((viewportwidth > document.body.parentNode.scrollWidth) && (viewportwidth > document.body.parentNode.clientWidth)) {
            window_width = viewportwidth;
        } else {
            if (document.body.parentNode.clientWidth > document.body.parentNode.scrollWidth) {
                window_width = document.body.parentNode.clientWidth;
            } else {
                window_width = document.body.parentNode.scrollWidth;
            }
        }
    }
    
    var popUpDiv = document.getElementById(popUpDivVar);
    window_width=window_width/2-(popupWidth/2); // half popup's width
    popUpDiv.style.left = window_width + 'px';
}

function popupPanel(windowname, width, height, iframe) {
    blanket_size(windowname, width, height, iframe);
    window_pos(windowname, width, height, iframe);
    toggle('blanket');
    toggle(windowname);
}

function selectAll(theSelect)
{
    var shareGroup;

    theSelect.multiple = true;
    // get the selected sharegroup
    for( shareGroup = 0; shareGroup < theSelect.length; shareGroup++ ) {
        theSelect.options[shareGroup].selected = true;
    }
}

function setupFormEvents(theForm) {
    // loop through all inputs and text areas and add listener
    for( i = 0; i < theForm.elements.length; i++) {
        if( theForm.elements[i].type == "text" || theForm.elements[i].type == "textarea" || theForm.elements[i].type == "checkbox") {
            addEvent(theForm.elements[i], 'focus', oninputfocus);
            addEvent(theForm.elements[i], 'blur', oninputblur);
        }
    }
}

var MONTH_NAMES=new Array('January','February','March','April','May','June','July','August','September','October','November','December','Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec');
var DAY_NAMES=new Array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sun','Mon','Tue','Wed','Thu','Fri','Sat');
function LZ(x){
    return(x<0||x>9?"":"0")+x
}
function isDate(val,format){
    var date=getDateFromFormat(val,format);
    if(date==0){
        return false;
    }
    return true;
}
function compareDates(date1,dateformat1,date2,dateformat2){
    var d1=getDateFromFormat(date1,dateformat1);
    var d2=getDateFromFormat(date2,dateformat2);
    if(d1==0 || d2==0){
        return -1;
    }else if(d1 > d2){
        return 1;
    }
    return 0;
}
function formatDate(date,format){
    format=format+"";
    var result="";
    var i_format=0;
    var c="";
    var token="";
    var y=date.getFullYear()+"";
    var M=date.getMonth()+1;
    var d=date.getDate();
    var E=date.getDay();
    var H=date.getHours();
    var m=date.getMinutes();
    var s=date.getSeconds();
    var yyyy,yy,MMM,MM,dd,hh,h,mm,ss,ampm,HH,H,KK,K,kk,k;
    var value=new Object();
    if(y.length < 4){
        y=""+(y-0+1900);
    }
    value["y"]=""+y;
    value["yyyy"]=y;
    value["yy"]=y.substring(2,4);
    value["M"]=M;
    value["MM"]=LZ(M);
    value["MMM"]=MONTH_NAMES[M-1];
    value["NNN"]=MONTH_NAMES[M+11];
    value["d"]=d;
    value["dd"]=LZ(d);
    value["E"]=DAY_NAMES[E+7];
    value["EE"]=DAY_NAMES[E];
    value["H"]=H;
    value["HH"]=LZ(H);
    if(H==0){
        value["h"]=12;
    }else if(H>12){
        value["h"]=H-12;
    }else{
        value["h"]=H;
    }
    value["hh"]=LZ(value["h"]);
    if(H>11){
        value["K"]=H-12;
    }else{
        value["K"]=H;
    }
    value["k"]=H+1;
    value["KK"]=LZ(value["K"]);
    value["kk"]=LZ(value["k"]);
    if(H > 11){
        value["a"]="PM";
    }else{
        value["a"]="AM";
    }
    value["m"]=m;
    value["mm"]=LZ(m);
    value["s"]=s;
    value["ss"]=LZ(s);
    while(i_format < format.length){
        c=format.charAt(i_format);
        token="";
        while((format.charAt(i_format)==c) &&(i_format < format.length)){
            token += format.charAt(i_format++);
        }
        if(value[token] != null){
            result=result + value[token];
        }else{
            result=result + token;
        }
    }
    return result;
}
function _isInteger(val){
    var digits="1234567890";
    for(var i=0;i < val.length;i++){
        if(digits.indexOf(val.charAt(i))==-1){
            return false;
        }
    }
    return true;
}
function _getInt(str,i,minlength,maxlength){
    for(var x=maxlength;x>=minlength;x--){
        var token=str.substring(i,i+x);
        if(token.length < minlength){
            return null;
        }
        if(_isInteger(token)){
            return token;
        }
    }
    return null;
}
function getDateFromFormat(val,format){
    val=val+"";
    format=format+"";
    var i_val=0;
    var i_format=0;
    var c="";
    var token="";
    var token2="";
    var x,y;
    var now=new Date();
    var year=now.getFullYear();
    var month=now.getMonth()+1;
    var date=1;
    var hh=now.getHours();
    var mm=now.getMinutes();
    var ss=now.getSeconds();
    var ampm="";
    while(i_format < format.length){
        c=format.charAt(i_format);
        token="";
        while((format.charAt(i_format)==c) &&(i_format < format.length)){
            token += format.charAt(i_format++);
        }
        if(token=="yyyy" || token=="yy" || token=="y"){
            if(token=="yyyy"){
                x=4;
                y=4;
            }
            if(token=="yy"){
                x=2;
                y=2;
            }
            if(token=="y"){
                x=2;
                y=4;
            }
            year=_getInt(val,i_val,x,y);
            if(year==null){
                return 0;
            }
            i_val += year.length;
            if(year.length==2){
                if(year > 70){
                    year=1900+(year-0);
                }else{
                    year=2000+(year-0);
                }
            }
        }else if(token=="MMM"||token=="NNN"){
            month=0;
            for(var i=0;i<MONTH_NAMES.length;i++){
                var month_name=MONTH_NAMES[i];
                if(val.substring(i_val,i_val+month_name.length).toLowerCase()==month_name.toLowerCase()){
                    if(token=="MMM"||(token=="NNN"&&i>11)){
                        month=i+1;
                        if(month>12){
                            month -= 12;
                        }
                        i_val += month_name.length;
                        break;
                    }
                }
            }
            if((month < 1)||(month>12)){
                return 0;
            }
        }else if(token=="EE"||token=="E"){
            for(var i=0;i<DAY_NAMES.length;i++){
                var day_name=DAY_NAMES[i];
                if(val.substring(i_val,i_val+day_name.length).toLowerCase()==day_name.toLowerCase()){
                    i_val += day_name.length;
                    break;
                }
            }
        }else if(token=="MM"||token=="M"){
            month=_getInt(val,i_val,token.length,2);
            if(month==null||(month<1)||(month>12)){
                return 0;
            }
            i_val+=month.length;
        }else if(token=="dd"||token=="d"){
            date=_getInt(val,i_val,token.length,2);
            if(date==null||(date<1)||(date>31)){
                return 0;
            }
            i_val+=date.length;
        }else if(token=="hh"||token=="h"){
            hh=_getInt(val,i_val,token.length,2);
            if(hh==null||(hh<1)||(hh>12)){
                return 0;
            }
            i_val+=hh.length;
        }else if(token=="HH"||token=="H"){
            hh=_getInt(val,i_val,token.length,2);
            if(hh==null||(hh<0)||(hh>23)){
                return 0;
            }
            i_val+=hh.length;
        }else if(token=="KK"||token=="K"){
            hh=_getInt(val,i_val,token.length,2);
            if(hh==null||(hh<0)||(hh>11)){
                return 0;
            }
            i_val+=hh.length;
        }else if(token=="kk"||token=="k"){
            hh=_getInt(val,i_val,token.length,2);
            if(hh==null||(hh<1)||(hh>24)){
                return 0;
            }
            i_val+=hh.length;
            hh--;
        }else if(token=="mm"||token=="m"){
            mm=_getInt(val,i_val,token.length,2);
            if(mm==null||(mm<0)||(mm>59)){
                return 0;
            }
            i_val+=mm.length;
        }else if(token=="ss"||token=="s"){
            ss=_getInt(val,i_val,token.length,2);
            if(ss==null||(ss<0)||(ss>59)){
                return 0;
            }
            i_val+=ss.length;
        }else if(token=="a"){
            if(val.substring(i_val,i_val+2).toLowerCase()=="am"){
                ampm="AM";
            }else if(val.substring(i_val,i_val+2).toLowerCase()=="pm"){
                ampm="PM";
            }else{
                return 0;
            }
            i_val+=2;
        }else{
            if(val.substring(i_val,i_val+token.length)!=token){
                return 0;
            }else{
                i_val+=token.length;
            }
        }
    }
    if(i_val != val.length){
        return 0;
    }
    if(month==2){
        if( ((year%4==0)&&(year%100 != 0) ) ||(year%400==0) ){
            if(date > 29){
                return 0;
            }
        }else{
            if(date > 28){
                return 0;
            }
        }
    }
    if((month==4)||(month==6)||(month==9)||(month==11)){
        if(date > 30){
            return 0;
        }
    }
    if(hh<12 && ampm=="PM"){
        hh=hh-0+12;
    }else if(hh>11 && ampm=="AM"){
        hh-=12;
    }
    var newdate=new Date(year,month-1,date,hh,mm,ss);
    return newdate.getTime();
}
function parseDate(val){
    var preferEuro=(arguments.length==2)?arguments[1]:false;
    generalFormats=new Array('y-M-d','MMM d, y','MMM d,y','y-MMM-d','d-MMM-y','MMM d');
    monthFirst=new Array('M/d/y','M-d-y','M.d.y','MMM-d','M/d','M-d');
    dateFirst =new Array('d/M/y','d-M-y','d.M.y','d-MMM','d/M','d-M');
    var checkList=new Array('generalFormats',preferEuro?'dateFirst':'monthFirst',preferEuro?'monthFirst':'dateFirst');
    var d=null;
    for(var i=0;i<checkList.length;i++){
        var l=window[checkList[i]];
        for(var j=0;j<l.length;j++){
            d=getDateFromFormat(val,l[j]);
            if(d!=0){
                return new Date(d);
            }
        }
    }
    return null;
}

function setupInputs() {

    var inputElements = document.getElementsByTagName("input");
    for (var i = 0; i < inputElements.length; i++) {
        if( inputElements[i].type == 'text' || inputElements[i].type == 'password') {
            if( inputElements[i].getAttribute('ignoreRestyle') == null ) {
                inputElements[i].style.border = 'solid 2px #DFDFDF';
                if( inputElements[i].onfocus == null ) {
                    inputElements[i].onfocus = onInputFocus;
                }
                if( inputElements[i].onblur == null ) {
                    inputElements[i].onblur = onInputBlur;
                }
            }
        }
    }

    var textAreaElements = document.getElementsByTagName("textarea");
    for ( i = 0; i < textAreaElements.length; i++) {
        if( textAreaElements[i].getAttribute('ignoreRestyle') == null ) {
            textAreaElements[i].style.border = 'solid 2px #DFDFDF';
            if( textAreaElements[i].onfocus == null ) {
                textAreaElements[i].onfocus = onInputFocus;
            }
            if( textAreaElements[i].onblur == null ) {
                textAreaElements[i].onblur = onInputBlur;
            }
        }
    }
}

function onInputFocus(e) {

    var evt = window.event || e;
    if (!evt.target) { //if event obj doesn't support e.target, presume it does e.srcElement
        evt.target = evt.srcElement //extend obj with custom e.target prop
    }
    if( evt.target.getAttribute('ignoreRestyle') == null ) {
        evt.target.style.border = 'solid 2px #6ea637';
    }
    return
}

function onInputBlur(e) {
    var evt = window.event || e;
    if (!evt.target) { //if event obj doesn't support e.target, presume it does e.srcElement
        evt.target = evt.srcElement //extend obj with custom e.target prop
    }
    if( evt.target.getAttribute('ignoreRestyle') == null ) {
        blurbInput(evt.target);
    }
}

function blurbInput(element) {
    element.style.border = 'solid 2px #dfdfdf';
}

function getTableContent(dataObjectId, rows, callback) {

    sendRequest('getTableContent.htm?dataObjectId=' + dataObjectId + '&rows=' + rows, callback, 'POST');
    return false;
}

function getArticleContent(dataObjectId, callback) {

    sendRequest('getArticleContent.htm?dataObjectId=' + dataObjectId, callback, 'POST');
    return false;
}

