///////////////////////////////////////////////////////////////////////////////
// $Id: cgpublisher.js,v 1.30 2006/11/03 01:29:55 richard Exp $
///////////////////////////////////////////////////////////////////////////////

// Array Extensions

if (!Array.prototype.push) Array.prototype.push = function() {
    for (var i=0; i<arguments.length; i++) this[this.length] = arguments[i];
    return this.length;
}

Array.prototype.find = function(value, start) {
    start = start || 0;
    for (var i=start; i<this.length; i++)
        if (this[i]==value)
            return i;
    return -1;
}

Array.prototype.has = function(value) {
    return this.find(value)!==-1;
}

// Functional

function map(list, func) {
    var result = [];
    func = func || function(v) {return v};
    for (var i=0; i < list.length; i++) result.push(func(list[i], i, list));
    return result;
}

function filter(list, func) {
    var result = [];
    func = func || function(v) {return v};
    map(list, function(v) { if (func(v)) result.push(v) } );
    return result;
}

// DOM

function getElem(elem) {
    if (document.getElementById) {
        if (typeof elem == "string") {
            var eid = elem;
            elem = document.getElementById(elem);
            if (elem === null) {
                msg = 'cannot get element "'+eid+'": element does not exist';
                throw msg;
            }
        } else if (typeof elem != "object") {
            throw 'cannot get element: invalid datatype';
        }
    } else throw 'cannot get element: unsupported DOM';
    return elem;
}

function hasClass(elem, className) {
    return getElem(elem).className.split(' ').has(className);
}

function getElementsByClass(className, tagName, parentNode) {
    parentNode = !isUndefined(parentNode) ? getElem(parentNode) : document;
    if (isUndefined(tagName)) tagName = '*';
    return filter(parentNode.getElementsByTagName(tagName),
        function(elem) { return hasClass(elem, className) });
}

function setContent(elem, html) {
    elem.innerHTML = html;
}

// DOM Events

function listen(event, eid, func) {
    elem = getElem(eid);
    if (elem.addEventListener)  // W3C DOM
        elem.addEventListener(event,func,false);
    else if (elem.attachEvent)  // IE DOM
        elem.attachEvent('on'+event, function(){ func(new W3CDOM_Event(elem)) } );
        // for IE we use a wrapper function that passes in a simplified faux Event object.
    else throw 'cannot add event listener to "'+elem+'"';
}

function mlisten(event, elem_list, func) {
    map(elem_list, function(elem) { listen(event, elem, func) } );
}

function W3CDOM_Event(currentTarget) {
    this.currentTarget  = currentTarget;
    this.preventDefault = function() { window.event.returnValue = false }
    return this;
}

// Misc Cleaning-After-Microsoft Stuff

function isUndefined(v) {
    var undef;
    return v===undef;
}

// Centering the popup window

// Set window width and horizontal location (bigger window for hi-res monitors)
if (screen.availWidth > 800) var bigPopupWidth = true;
var defaultPopupWidth = bigPopupWidth ? 1024 : 600;
var x = (screen.availWidth-defaultPopupWidth)/2;

// Set window height and vertical location
if (screen.availHeight > 600) var bigPopupHeight = true;
var defaultPopupHeight = bigPopupHeight ? 600 : 400;
// move pop-up window up a little bit: multiply y co-ordinate by two thirds.
var y = ((screen.availHeight-defaultPopupHeight)/2)*(2/3);

// Set the default popup features for '(meaning)' links
var _POPUP_FEATURES = 'toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width='+defaultPopupWidth+',height='+defaultPopupHeight+',screenX='+x+',screenY='+y+',top='+y+',left='+x;

function raw_popup(url, target, features) {
    // pops up a window containing url optionally named target, optionally having features
    if (isUndefined(features)) features = _POPUP_FEATURES;
    if (isUndefined(target  )) target   = '_blank';
    var theWindow = window.open(url, target, features);
    theWindow.focus();
    return theWindow;
}

function link_popup(src, features) {
    // to be used in an html event handler as in: <a href="..." onclick="link_popup(this,...)" ...
    // pops up a window grabbing the url from the event source's href
    return raw_popup(src.getAttribute('href'), src.getAttribute('target') || '_blank', features);
}

function event_popup(e) {
    // to be passed as an event listener
    // pops up a window grabbing the url from the event source's href
    link_popup(e.currentTarget);
    e.preventDefault();
}

function event_popup_features(features) {
    // generates an event listener similar to event_popup, but allowing window features
    return function(e) { link_popup(e.currentTarget, features); e.preventDefault() }
}

function event_submit(e) {
    // to be passed as an event listener
    // prevents multiple submits of a form (the currentTarget)
    var d = new Date();
    var ts = d.getSeconds() + d.getMinutes() * 60 + d.getHours() * 360;
    if (isUndefined(e.currentTarget.submitted)) {
        e.currentTarget.submitted = ts;
    } else {
        var diff = ts - e.currentTarget.submitted;
        if (diff > 1 && diff < 5) {
            alert('Please be patient, your request is being processed.');
            e.preventDefault();
        } else if (diff <= 1) {
            e.preventDefault();
        }
   }
}

///////////////////////////////////////////////////////////////////////////////
// Historic Handler For New Browser Window 
///////////////////////////////////////////////////////////////////////////////
// Deprecated in preferecnce of listener popups.

function windowOpen(url, name, width, height, scroll) {
    // centered pop-up window coordinates;
    var x = (screen.availWidth-width)/2;
    var y = (screen.availHeight-height)/2;
    // process scroll parameter
    scroll = scroll ? "scrollbars=yes,resizable=yes," : "scrollbars=no,resizable=no,";
    // open a pop-up window
    window.open(url,name,"toolbar=no,location=no,status=no,menubar=no,"+scroll+"width="+width+",height="+height+",screenX="+x+",screenY="+y+",top="+y+",left="+x);
}

///////////////////////////////////////////////////////////////////////////////
// Put 'footer' div at the bottom of the page 
///////////////////////////////////////////////////////////////////////////////
function getWindowHeight() {
    var windowHeight = 0;
    if (typeof(window.innerHeight) == 'number') {
        windowHeight = window.innerHeight;
    }
    else if (document.documentElement && document.documentElement.clientHeight) {
        windowHeight = document.documentElement.clientHeight;
    }
    else if (document.body && document.body.clientHeight) {
        windowHeight = document.body.clientHeight;
    }
    return windowHeight;
}

function setFooter() {
    // only run if there is a <div id="wrapper"> present on the page.
    if (document.getElementById('wrapper')) {
        var windowHeight = getWindowHeight();
        if (windowHeight > 0) {
            // Find the height of body content
            var contentHeight = document.getElementById('wrapper').offsetHeight;
            var footerElement = document.getElementById('footer');
            var footerHeight  = footerElement.offsetHeight;
            if (windowHeight - (contentHeight + footerHeight) >= 0) {
                footerElement.style.position = 'relative';
                footerElement.style.top = (windowHeight - (contentHeight + footerHeight)) + 'px';
            }
            else {
                footerElement.style.position = 'static';
            }
        }
    }
}

///////////////////////////////////////////////////////////////////////////////
// Add listeners for dynamic footer placement and popup links
///////////////////////////////////////////////////////////////////////////////

// Put the footer at the bottom of short pages when pages load
window.onload = function() {
    setFooter();
}

// Put the footer at the bottom of short pages when windows are resized.
window.onresize = function() {
    setFooter();
}

// Popup windows for anchors with a class='pop'
listen('load', window, function() {
    mlisten('click', getElementsByClass('pop','a'), event_popup);
});

listen('load', window, function() {
    mlisten('submit', document.forms, event_submit);
});


///////////////////////////////////////////////////////////////////////////////
// Sign in Convenience Functions
///////////////////////////////////////////////////////////////////////////////

function focususername() {
    if (document.cgpsignin.__ac_name) {
        //alert('focususername called.')
        document.cgpsignin.__ac_name.focus();
        document.cgpsignin.__ac_name.select();
    }
}
function clearname() {
//    alert(document.cgpsignin.__ac_name.value);
    if (document.cgpsignin.__ac_name.value == "Type Your Email Address") {
	    document.cgpsignin.__ac_name.value = "";
    }
}


function cgpsigninhandler() {
    var lvalue;

    lvalue = document.cgpsignin.__ac_name.value

    if (!lvalue | lvalue == "Type Your Username")
    {
        alert("Please type your username.");
        return false;
    }
    if(!document.cgpsignin.__ac_password.value)
    {
        alert("Please type your password.");
        return false;
    }
    
    document.cgpsignin.submit()

    return false;
}

///////////////////////////////////////////////////////////////////////////////
// DHTML display hiding
///////////////////////////////////////////////////////////////////////////////
function setElementHidden(elemid, active) {
    e = getElem(elemid);
    if (active) {
          e.style.display = 'block';
    } else {
          e.style.display = 'none';
    }
}

function toggle(name) {
   style = getElem(name+'-hideme').style
   button = getElem(name+'-button')
   if (style.display == 'block') {
       style.display = 'none';
       setContent(button, 'show '+name);
   } else {
       style.display = 'block';
       setContent(button, 'hide');
   }
}

///////////////////////////////////////////////////////////////////////////////
// FORM Processing
///////////////////////////////////////////////////////////////////////////////
function insert_tab_indexes() {
    forms = document.forms;
    ti = 1;
    for (i=0; i < forms.length; i++) {
        form = forms[i];
        for (j=0; j<form.elements.length; j++) {
            element = form.elements[j];
            if (!element.name || !element.type || element.type == 'hidden')
                continue
            element.setAttribute('tabindex', ti++);
        }
    }
}
