// start with preventing errors with firebug in FF and Companion.js in IE
if (typeof(console) == 'undefined' || typeof(console.log) == 'undefined')
{
    var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml", "group", "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"];

    if (typeof(console) == 'undefined')
        var console = {};
    for (var i = 0; i < names.length; ++i)
        console[names[i]] = function() {}
    window['loadFirebugConsole'] = function() {}
}
console.log('etzchayim.2006.js loading');

// from http://interglacial.com/hoj/hoj.html
function defined (x) { return typeof(x) != 'undefined'; }
/*
 * http://www.thefutureoftheweb.com/demo/2006-06-21-onload/adddomloadevent.js
 *
 * (c)2006 Jesse Skinner/Dean Edwards/Matthias Miller/John Resig
 * Special thanks to Dan Webb's domready.js Prototype extension
 * and Simon Willison's addLoadEvent
 *
 * For more info, see:
 * http://www.thefutureoftheweb.com/blog/adddomloadevent
 * http://dean.edwards.name/weblog/2006/06/again/
 * http://www.vivabit.com/bollocks/2006/06/21/a-dom-ready-extension-for-prototype
 * http://simon.incutio.com/archive/2004/05/26/addLoadEvent
 * 
 *
 * To use: call addDOMLoadEvent one or more times with functions, ie:
 *
 *    function something() {
 *       // do something
 *    }
 *    addDOMLoadEvent(something);
 *
 *    addDOMLoadEvent(function() {
 *        // do other stuff
 *    });
 *
 */
 
addDOMLoadEvent = (function(){
    // create event function stack
    var load_events = [],
        load_timer,
        script,
        done,
        exec,
        old_onload,
        init = function () {
            done = true;

            // kill the timer
            clearInterval(load_timer);

            // execute each function in the stack in the order they were added
            while (exec = load_events.shift())
                exec();

            if (script) script.onreadystatechange = '';
        };

    return function (func) {
        // if the init function was already ran, just run this function now and stop
        if (done) return func();

        if (!load_events[0]) {
            // for Mozilla/Opera9
            if (document.addEventListener)
                document.addEventListener("DOMContentLoaded", init, false);

            // for Internet Explorer
            /*@cc_on @*/
            /*@if (@_win32)
                document.write("<script id=__ie_onload defer src=//0><\/scr"+"ipt>");
                script = document.getElementById("__ie_onload");
                script.onreadystatechange = function() {
                    if (this.readyState == "complete")
                        init(); // call the onload handler
                };
            /*@end @*/

            // for Safari
            if (/WebKit/i.test(navigator.userAgent)) { // sniff
                load_timer = setInterval(function() {
                    if (/loaded|complete/.test(document.readyState))
                        init(); // call the onload handler
                }, 10);
            }

            // for other browsers set the window.onload, but also execute the old window.onload
            old_onload = window.onload;
            window.onload = function() {
                init();
                if (old_onload) old_onload();
            };
        }

        load_events.push(func);
    }
})();

function alternateOddEvenTable () {
if(document.getElementById) {  
   var table = document.getElementById('oddeventable');  
   var rows = table.getElementsByTagName("tr");  
   for(i = 0; i < rows.length; i++){     
       //manipulate rows
       rows[i].className = (i % 2 == 0) ? "even" : "odd";
   }
 } 
}

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 _AddSpinner (button) {
    button = $(button);
    var spinner = new Element('img', { src: '/images/icons/spinner.gif', width: '20px', height: '20px'});
    button.up().appendChild(spinner);
    button.hide();
    return $(spinner);
}

function _AlertException (exception, label) {
    alert("Sorry. Things didn't go as planned.\nPlease send the following info "
        + "to webmaster at etzchayim dot org :\n\n " + label + ': '+ exception + "\n");
}

var SaveOrigValue = function(event) {
    var elem = event.element();
    try {
        elem.origValue = $F(elem);
        console.log('elem.origValue ='+elem.origValue);
    } catch (err) {
    };
}

var SubmitForm = function(button, url, updateFld, userParameters) {
    var parameters = $H(userParameters || $(button).up('form').serialize(true));
    var spinner = _AddSpinner(button);
    if (updateFld == 'downloadIframe') {
        // Create an IFRAME.
        downloadIframe = document.createElement("iframe");
 
        // Point the IFRAME to the remote src.
        url = url + '?' + parameters.toQueryString();
        downloadIframe.src = url;
 
        // This makes the IFRAME invisible to the user.
        downloadIframe.style.display = "none";
 
        // Add the IFRAME to the page.  This will trigger to download the file
        document.body.appendChild(downloadIframe);

        // and reset the trigger indicator
        button.show();
        spinner.hide();
        console.log('loaded into an iframe ' + url);
    } else if (updateFld) 
        new Ajax.Updater(updateFld, url,
            { parameters: parameters,
              evalScripts: true,
              method: 'post',
              onFailure:  function(){
                   button.show();
                   spinner.hide();
                   console.log('Failed to update ' + updateFld);
              },
              onSuccess: function(transport) {
                   button.show();
                   spinner.hide();
                   console.log('Updating ' + updateFld + ' to ' + transport.responseText);
             }});
    else window.location.href = url + '?' + Object.toQueryString(parameters);
}

function UpdateAny1Fld(event) {
    var fld = event.element();
    return Update1Fld(fld);
} 

function Update1Fld(elem, url, updateFld) {
    var newValue = $F(elem);
    if (!defined(url)) url = '/inc/ajaxUpdate1Fld.php';
    console.log('elem.origValue ='+elem.origValue + ' versus newValue='+newValue );
    if (newValue != elem.origValue) {
        var form = $(elem).up('form');
        console.log(form);
        var hiddenFields = $(form).select('input[type=hidden]');
        var parameters = $H({whichFld: elem.id, 'val[]': newValue});
        hiddenFields.each(function(hidden) { parameters.set(hidden.id, $F(hidden)); });
        if ($('year') && !parameters.get('year')) {
            parameters.set('year', $F('year'));
        }
        console.log(parameters);
        SubmitForm(elem, url, typeof updateFld == 'undefined' ? 'whoCares' : updateFld, parameters); 
    }
}
    
function obfuscatemil (send, show, rest, subject, cc, bcc) {
 var prefix = '&#109;a' + 'i&#108;' + '&#116;o';
 var path = 'hr' + 'ef' + '=';
 var addy249 = send + '&#64;';
 if (typeof subject == "undefined") { subject = ""; } else {
     if (!subject.match(/^\?subject=/)) subject = '?subject=' + subject;
 }
 if (typeof cc == "undefined"     ) { cc      = ""; } else { cc = ((subject) ? '&' : '?') + 'cc=' + cc; }
 if (typeof bcc == "undefined"    ) { bcc     = ""; } else { bcc = ((subject||cc) ? '&' : '?') + 'bcc=' + bcc; }
 addy249 = addy249 + '&#101;&#116;&#122;&#099;&#104;&#097;&#121;&#105;&#109;';
 addy249 = addy249 + '&#46;' + '&#111;rg' + subject+cc+bcc;
 document.write( '<a ' + path + '"' + prefix + ':' + addy249 + '"' + rest + '>' );
 document.write( show );
 document.write( '<\/a>' );
}

function printer_friendly_calendar(toggle) {
        if (toggle) {
           setStyleByClass('a','calendar_links','color', '#333333');
           setStyleByClass('a','calendar_even','color', '#333333');     
           setStyleByClass('a','calendar_odd','color', '#333333');
           setStyleByClass('tr','calendar_title','backgroundColor', '#ffffff');
           setStyleByClass('tr','calendar_title','color', '#333333');
           setStyleByClass('tr','calendar_links','backgroundColor', '#ffffff');
           setStyleByClass('tr','calendar_links','color', '#333333');
           setStyleByClass('tr','calendar_header','backgroundColor', '#ffffff');
           setStyleByClass('tr','calendar_header','color', '#333333');
           setStyleByClass('tr','calendar_even','backgroundColor', '#ffffff');
           setStyleByClass('tr','calendar_even','color', '#333333'); 
           setStyleByClass('tr','calendar_odd','backgroundColor', '#ffffff');
           setStyleByClass('tr','calendar_odd','color', '#333333');
        } else {   
           setStyleByClass('a','calendar_links','color', '#ffffff');
           setStyleByClass('a','calendar_even','color', '#ffffff');     
           setStyleByClass('a','calendar_odd','color', '#ffffff');
           setStyleByClass('tr','calendar_title','backgroundColor', '#566339');
           setStyleByClass('tr','calendar_title','color', '#ffffff');
           setStyleByClass('tr','calendar_links','backgroundColor', '#6A512B');
           setStyleByClass('tr','calendar_links','color', '#ffffff');
           setStyleByClass('tr','calendar_header','backgroundColor', '#7B895D');
           setStyleByClass('tr','calendar_header','color', '#ffffff');
           setStyleByClass('tr','calendar_even','backgroundColor', '#92774F');
           setStyleByClass('tr','calendar_even','color', '#ffffff'); 
           setStyleByClass('tr','calendar_odd','backgroundColor', '#7B895D');
           setStyleByClass('tr','calendar_odd','color', '#ffffff');
        }
}

// taken from  http://developer.apple.com/internet/webcontent/examples/styley_source.html
function setStyleByClass(t,c,p,v){
        var elements = document.getElementsByTagName(t);
        for(var i = 0; i < elements.length; i++){
                var node = elements.item(i);
                for(var j = 0; j < node.attributes.length; j++) {
                        if(node.attributes.item(j).nodeName == 'class') {
                                if(node.attributes.item(j).nodeValue == c) {
                                        eval('node.style.' + p + " = '" +v + "'");
                                }
                        }
                }
        }
}

function SetVisibility (element, visibility) {
    element.style.display = visibility;
}

function ToggleVisibility (element) {
    if (element) {
        var visibile =  (element.style.display == '') ? 'none' : '';
        SetVisibility(element, visibile);
    }   
}

function ToggleForeGroundBackground (element, fg1, bg1, fg2, bg2) {
    if (element) {
        if (element.style.color != fg1) {
            element.style.color = fg1;
            element.style.bgcolor = bg1;
        } else {
            element.style.color = fg2;
            element.style.bgcolor = bg3;
        }
    }   
}

var toggle = 0;
function PrintPage() { 
   ToggleVisibility(document.getElementById('navigationtable'));
   ToggleVisibility(document.getElementById('navigational_list'));      
   ToggleVisibility(document.getElementById('footer'));   
   toggle = 1 - toggle;
   page_local_printer_friendly(toggle);
}

function MM_goToURL() { //v3.0
  var i, args=MM_goToURL.arguments; document.MM_returnValue = false;
  for (i=0; i<(args.length-1); i+=2) eval(args[i]+".location='"+args[i+1]+"'");
}

function MM_callJS(jsStr) { //v2.0
  return eval(jsStr)
}

function setStatusBar(msgStr) { self.status = msgStr; }


// from http://www.javascriptkit.com/javatutors/loadjavascriptcss.shtml
var filesadded = ""; //list of files already added

function LoadScriptFile(filename){
    if (filesadded.indexOf("["+filename+"]")==-1) {
        LoadJsCssFile(filename);
        filesadded +="["+filename+"]" //List of files added in the form "[filename1],[filename2],etc"
    }
}

function LoadJsCssFile(filename) {
    var filetype = filename.match(/\.([a-zA-Z]+)$/)[1];
    console.log('Added file to head: ' + filename);
    if (filetype=="js"){ //if filename is a external JavaScript file
        // inserting via DOM fails in Safari 2.0, so brute force approach
        document.write('<script type="text/javascript" src="'+filename+'"></script>');
//       var fileref=document.createElement('script')
//            fileref.setAttribute("type","text/javascript")
//            fileref.setAttribute("src", filename)
    } else if (filetype=="css"){ //if filename is an external CSS file
        document.write('<link rel="stylesheet" type="text/css" href="'+filename+'">');
//        var fileref=document.createElement("link")
//            fileref.setAttribute("rel", "stylesheet")
//            fileref.setAttribute("type", "text/css")
//            fileref.setAttribute("href", filename)
    }
    if (typeof fileref!="undefined") {
        var head = document.getElementsByTagName("head")[0];
        head.appendChild(fileref);
    }
}

function SortZindex (event) {
    var toBeActive = this;
    var popups = $$('div.scrollableDiv');
    while (toBeActive.tagName != 'DIV' && !toBeActive.hasClassName('scrollableDiv')) {
        toBeActive = toBeActive.up('div');
        
    }
    var minZindex = popups.without(toBeActive).min(function(elem) { return elem.style.zIndex; });
    if (minZindex < 10) minZindex = 10;

    toBeActive.style.zIndex = minZindex+1;
    console.log('setting toBeActive zIndex to ' + minZindex+1);
    popups.without(toBeActive).each(function(elem) {
        elem = $(elem);
        elem.style.zIndex = minZindex;
    });
}

console.log('etzchayim.2006.js FINISHED loading');
