/* checked with jsLint 2009 10 28 */
// tutorial #1
function showName() {
    name = ""; name = window.prompt('Enter your name: ', '');
    document.write('hello ' + name + ' !');
}
function openWindow(url, name, w, h, l, t) {
    features = 'dependent=1,width=' + w + ',height=' + h + ',left=' + l + ',top=' + t;
    popupWin = window.open(url, name, features);
    if (!popupWin.opener) { popupWin.opener = self; }
}
// tutorial #4
// section for rollover script
overImg = []; outImg = [];
outImg[0] = new Image(); outImg[0].src = "images/enter1.gif";
overImg[0] = new Image(); overImg[0].src = "images/enter2.gif";
outImg[1] = new Image(); outImg[1].src = "images/keio.gif";
overImg[1] = new Image(); overImg[1].src = "images/inria.gif";
function chgImg(img, type) {
    switch (type) {
        case "over": document.images[img].src = overImg[img].src; break;
        case "out": document.images[img].src = outImg[img].src; break;
    } 
}
// section for banner ads display
function gotoAd() { location.href = "http://" + adURLs[thisAd]; }
adImages = ["images/mit.gif", "images/inria.gif", "images/keio.gif"];
adURLs = ["www.lcs.mit.edu", "www.inria.fr", "www.keio.ac.jp"]; thisAd = 0;
function cycleAds() {
    if (++thisAd === adImages.length) { thisAd = 0; } //move to next ad
    document.images.adBanner.src = adImages[thisAd]; //display current
    setTimeout(cycleAds, 3000);  //change ad every 3 seconds
}
// tutorial #5
function exploreIt(name, obj) {
    if (!obj) { alert(name + ' object not in browser!'); return; }
    msg = name + ' object info:\n';
    for (propname in obj) {
        if (typeof obj[propname] === 'string') {
            msg += propname + ": " + obj[propname] + "\n";
        } 
    }
    alert(msg);
}
//getMouse example
xMouse = 0; yMouse = 0; xMouse2 = 0; yMouse2 = 0; // globals
document.onmousemove = getMouse; // start event listener
function getMouse(e) {
    e = e || window.event; de = document.documentElement; b = document.body;
    xMouse = e.clientX + (de.scrollLeft || b.scrollLeft) - (de.clientLeft || 0);
    yMouse = e.clientY + (de.scrollTop || b.scrollTop) - (de.clientTop || 0);
    xMouse2 = e.clientX; yMouse2 = e.clientY;
}
// functions for popup box demo
function hideLayer() {
    document.getElementById("popObj").style.top = "-500px";
}
function popLayer(a) {
    if (!cap[a]) {
        cap[a] = '<span class="pop">This popup (#' + a + ') needs description text!<\/span>';
    }
    desc = "<table class='pop' summary='*'>\n<tr class='pop'><td class='pop'>\n";
    desc += cap[a] + "<\/td><\/tr><\/table>";
    document.getElementById("popObj").innerHTML = desc;
    document.getElementById("popObj").style.left = xMouse + 15 + 'px';
    document.getElementById("popObj").style.top = yMouse - 5 + 'px';
}
// initialization for popups
cap = [];  // array of popup captions
cap[0] = 'These popups can have varying width. ';
cap[0] += 'It is dependent upon the text message.';
cap[1] = 'You can have <strong>two<\/strong> lines<br/>and HTML content.';
cap[2] = 'You can also have images like this:<br/><div class="pop">';
cap[2] += '<img src="images/zcrypt.gif"><\/div>';
cap[3] = 'You can put in a really long<br/>description if it is nessary to';
cap[3] += '<br \/>explain something in detail,<br/>';
cap[3] += 'like a warning about content<br/>or privacy.';
cap[4] = 'You can also have links like these:<br/>';
cap[4] += '<a href="http://google.com/">Google<\/a><br/>';
cap[4] += '<a href="http://amazon.com/">Amazon<\/a><br/>';
cap[4] += '<a href="http://mapqest.com/">MapQuest<\/a><br/>';
cap[4] += 'With a change in the onmouseout event handler.';
// tutorial #6
// rollover color change example
function change(thistag) {
    styleObj = document.getElementById(thistag).style; styleObj.color = "red";
}
function back(thistag) {
    styleObj = document.getElementById(thistag).style; styleObj.color = "grey";
}
/* color fade example */
fadept = 0; // global to remember fade state
function fade(thisone) {
    col = "#000";
    switch (fadept) {
        case 0: col = '#000'; break;
        case 1: col = '#333'; break;
        case 2: col = '#666'; break;
        case 3: col = '#999'; break;
        case 4: col = '#aaa'; break;
        case 5: col = '#ccc'; break;
        case 6: col = '#ddd'; break;
        case 7: col = '#eee'; break;
        case 8: col = '#fff'; break;
    }
    fadept += 1;  // increment for next time around
    if (fadept > 8) { fadept = 0; } // hit end so reset
    styleObj = document.getElementById(thisone).style;
    styleObj.color = col;
}
/* fontsize zoom example */
zoompt = 0;
function zoom(tagname) {
    switch (zoompt) {
        case 0: siz = '8pt'; break;
        case 1: siz = '10pt'; break;
        case 2: siz = '12pt'; break;
        case 3: siz = '14pt'; break;
        case 4: siz = '16pt'; break;
        case 5: siz = '18pt'; break;
        case 6: siz = '20pt'; break;
        case 7: siz = '22pt'; break;
        case 8: siz = '24pt'; break;
    }
    zoompt += 1;      // set for next time around
    if (zoompt > 8) { zoompt = 0; } // hit end so reset
    styleObj = document.getElementById(tagname).style;
    styleObj.fontSize = siz;
}
// collapsing text example
function expand(thistag) {
    styleObj = document.getElementById(thistag).style;
    if (styleObj.display === 'none') { styleObj.display = 'block'; }
    else { styleObj.display = 'none'; }
}
// tutorial #7
//marquee example
function scrollShow() {
    document.getElementById('elId').value = mmsg.substring(beg, end);
    window.status = mmsg.substring(beg, end);
}
function scrollInit() {
    mmsg = "JR's marquee demonstration -- "; msgId = null;
    cnt = mmsg.length; beg = 0; end = 0; mmsg += mmsg; rate = 20;
}
function stopMsg() { clearTimeout(msgId); scrollInit(); scrollShow(); }
function scrollMsg() {
    if (end < 2 * cnt) { end++; } else { end = cnt; }
    if (end > cnt) { beg = end - cnt; }
    scrollShow(); msgId = setTimeout(scrollMsg, 1000 / rate);
}
//popup expander
pLim = 10; pStep = 20; pid = null; pLev = 1; step = 0; wWid = 1; wHei = 1;
iObj = []; expFlag = []; xPosn = []; yPosn = []; xSize = []; ySize = [];
function popit2() {
    step++; if (step > pStep) { return; }
    wid = step * xSize[pid] / pStep; hei = step * ySize[pid] / pStep;
    if (expFlag[pid] == -1) {
        wid = (pStep - step) * xSize[pid] / pStep;
        hei = (pStep - step) * ySize[pid] / pStep;
    }
    l = xPosn[pid] - (wid / 2); if (l < pLim) { l = pLim; }
    if (l > wWid - wid - pLim) { l = wWid - wid - pLim; }
    t = yPosn[pid] - (hei / 2); if (t < pLim) { t = pLim; }
    if (t > wHei - hei - pLim) { t = wHei - hei - pLim; }
    iObj[pid].left = l + 'px'; iObj[pid].top = t + 'px';
    if (wid < 9) { iObj[pid].display = 'none'; }
    iObj[pid].width = wid + 'px'; setTimeout(popit2, 1);
}
function popit(id, width, height) {
    pLev++; step = 0;
    pid = id; xSize[pid] = width; ySize[pid] = height;
    obj = document.getElementById(pid);
    obj.title = 'Click image to close'; iObj[pid] = obj.style;
    iObj[pid].display = 'block'; iObj[pid].zIndex = pLev;
    iObj[pid].position = 'fixed'; iObj[pid].top = '20px';
    if (expFlag[pid] === undefined) {
        expFlag[pid] = -1; xPosn[pid] = 0; yPosn[pid] = 0;
    }
    wWid = document.documentElement.clientWidth;
    wHei = document.documentElement.clientHeight;
    if (expFlag[pid] === -1) {
        xPosn[pid] = xMouse; yPosn[pid] = yMouse2;
    }
    expFlag[pid] *= -1; popit2();
}
//News Scroller********
p6 = '<h1 class="scroll">News!!!<\/h1><p>Message goes here!<\/p>';
p6 += '<p><em>Note: <\/em>Hover on newsbox to stop scrolling!';
function createLayer() {
    nmsg = '<div id="layer' + this.name + '" style="position:relative;overflow:hidden;';
    nmsg += 'float:' + this.initFl + ';background-color:#' + this.initBg;
    nmsg += ';border:0px solid grey;width:' + this.initW + 'px;height:' + this.initH;
    nmsg += 'px;" onmouseover="' + this.name + '.scrollLoop(0)" onmouseout="';
    nmsg += this.name + '.scrollLoop(' + this.speed + ')">';
    nmsg += '<div id="' + this.name + '" style="position:absolute;top:';
    nmsg += this.initH + 'px;left:0px;border:0px solid grey;width:';
    nmsg += this.widthB + 'px;height:' + this.heightB + 'px;background-color:#';
    nmsg += this.Bg + '">' + this.content + '<\/div><\/div>'; document.write(nmsg);
    if (this.scrollLayer) { this.timer = setInterval(this.name + '.scrollLayer()', '30'); }
}
function getElement() { this.elem = document.getElementById(this.name); }
function scrollLoop(s) { this.speed = s; }
function scrollLayer() {
    if (parseInt(this.elem.style.top, 10) > (this.elem.offsetHeight * (-1))) {
        this.elem.style.top = parseInt(this.elem.style.top, 10) - this.speed + 'px';
    } else { this.elem.style.top = this.initH + 'px'; } 
}
function scrollerObj(name, initH, initW, heightB, widthB, content, initBg, Bg, speed, initFl) {
    this.name = name; this.initH = initH; this.initW = initW; this.heightB = heightB;
    this.widthB = widthB; this.content = content; this.initBg = initBg;
    this.Bg = Bg; this.initFl = initFl; this.speed = parseInt(speed, 10);
    this.timer = name + "Timer";
    this.getElement = getElement; this.createLayer = createLayer;
    this.scrollLayer = scrollLayer; this.scrollLoop = scrollLoop;
    this.createLayer(); this.getElement(); this.scrollLayer();
}
//News Scroller********
// dynamic content example
sayNo = -1; say = []; say[0] = "ZERO"; say[1] = "ONE"; say[2] = "TWO";
function showsay() {
    sayNo++; if (sayNo >= say.length) { sayNo = 0; }
    obj = document.getElementById('say'); obj.innerHTML = say[sayNo];
    setTimeout(showsay, 2000);
}
// tutorial #9
// multiple toggle buttons
offs = ["Start", "True", "One"]; // off values array
ons = ["Stop", "False", "Two"]; // on values array
flips = [false, false, false]; // button state array
function toggleInit() { // set initial captions
    for (p = 0; p <= 2; p++) {
        bObj = document.getElementById('b' + p);
        bObj.style.background = "lightgreen";
        bObj.style.width = "45px"; bObj.value = offs[p];
    } 
}
function toggle(pn) { // p has switch posn number
    p = parseInt(pn, 10); // be sure it is a number
    if (flips[p]) {
        //state is true so switch off actions go here
        switch (p) {
            //  case '0':b0_turnOff();break; 
            //  case '0':b1_turnOff();break; 
            //  case '0':b2_turnOff();break; 
            //  case default:alert('Error: Defining button actions'); 
        }
        document.getElementById('b' + p).value = offs[p];
        document.getElementById('b' + p).style.background = "lightgreen";
    } else {
        //state is false so switch on actions go here
        switch (p) {
            //  case '0':b0_turnOn();break; 
            //  case '0':b1_turnOn();break; 
            //  case '0':b2_turnOn();break; 
            //  case default:alert('Error: Defining button actions'); 
        }
        document.getElementById('b' + p).value = ons[p];
        document.getElementById('b' + p).style.background = "red";
    }
    flips[p] = !flips[p]; // reset button state
}
/* site agreement example */
function doYes(entry) {
    if (entry === true) {
        window.location.href = "http://home.cogeco.ca/~ve3ll/sitemap.htm";
    } else { alert("Sorry - you must sign agreement to access Sitemap!"); }
}
// tutorial #10
function writeform() {
    selobj = document.getElementById('selform');
    newobj = document.getElementById('newform');
    p = document.getElementById('menu').selectedIndex + 1;
    if (p == 1) { // write the 1st form here
        txt = 'Person 1: ' + '<input type="text"/><br/>';
        txt += 'Person 2: ' + '<input type="text"/>';
    }
    if (p == 2) { // write the 2nd form here
        txt = 'Name: ' + '<input type="text"/><br/>';
        txt += 'Addr: ' + '<input type="text"/>';
    }
    newobj.innerHTML = txt; selobj.style.display = 'block';
}
function add2list(sourceID, targetID) {
    source = document.getElementById(sourceID);
    target = document.getElementById(targetID);
    numberOfItems = source.options.length;
    insertPt = target.options.length; // insert at end
    if (target.options[0].text === "") { insertPt = 0; } // null option fix
    for (i = 0; i < numberOfItems; i++) {
        if (source.options[i].selected === true) {
            msg = source.options[i].text;
            for (j = 0; j < target.options.length; j++) {
                if (msg === target.options[j].text) { j = 99; } 
            }
            if (j < 99) {
                target.options[insertPt] = new Option(msg);
                insertPt = target.options.length;
            }
        } 
    }
}
function takefromlist(targetID) {
    target = document.getElementById(targetID);
    if (target.options.length < 0) { return; }
    for (var i = (target.options.length - 1); i >= 0; i--) {
        if (target.options[i].selected) {
            target.options[i] = null;
            if (target.options.length === 0) { target.options[0] = new Option(""); }
        } 
    }
}
function newColor(entry, areaID) { // use DOM access only
    if (!areaID) { areaID = "body"; } // default to whole body
    document.getElementById(areaID).style.background = entry;
}
function selColor(el) {
    obj = document.getElementById(el);
    newColor(obj.options[obj.selectedIndex].text);
}
function ChangeColor(id) {
    entry = document.getElementById(id).value.toUpperCase();
    strlen = entry.length; validChar = '0123456789ABCDEF';
    if (strlen !== 6) {
        alert("Must be EXACTLY 6 characters long"); return false;
    }
    // Check for legal characters in string
    for (i = 0; i < 6; i++) {
        if (validChar.indexOf(entry.charAt(i)) < 0) {
            alert("Must be in RRGGBB hexcode form!"); return false;
        }
    }
    if (entry.charAt(0) || "#") { entry = "#" + entry; }
    newColor(entry); return true;
}
// tutorial #11
var maxLen, errMsg; invChars = /\W/;  //global default settings
function initCount(ident, maxChars, displayId, chkStr) { // init settings
    taObj = document.getElementById(ident); maxLen = maxChars;
    errMsg = "Sorry! Text entry stopped at limit of " + maxLen + " characters.";
    if (chkStr !== "") { invChars = chkStr; }
    if (chkStr.toLowerCase() === "nocheck") { invChars = ""; }
    if (displayId.toLowerCase() === "noshow") { return; }
    dispObj = document.getElementById(displayId);
    dispObj.innerHTML = maxLen - taObj.value.length;
}
function taCount(ident, displayId) {
    taObj = document.getElementById(ident);
    taLength = taObj.value.length; // look at current length
    if (taLength > maxLen) { // clip characters
        taObj.value = taObj.value.substring(0, maxLen); alert(errMsg);
    }
    taLength = taObj.value.length; oldLength = 0;
    while (oldLength < taLength) { //validate characters
        tChar = taObj.value.charAt(oldLength);
        if ((invChars !== "") && invChars.test(tChar)) {
            alert('Invalid char[' + tChar + '] Letters, numbers or hyphens only.');
            tStr = taObj.value; tail = tStr.substring(oldLength + 1);
            taObj.value = tStr.substring(0, oldLength) + tail; taLength--;
        } else { oldLength++; }
    }
    if (displayId.toLowerCase() === "noshow") { return; }
    dispObj = document.getElementById(displayId);
    dispObj.innerHTML = (maxLen - taObj.value.length);
}
// tutorial #12
function chkForm(p) { //validate form fields
    myFlds = ['acct', 'pass1', 'pass2', 'email']; //tie to html ids
    if (p === 'no') { //param flags clear form
        for (i = 0; i < myFlds.length; i++) { document.getElementById(myFlds[i]).value = ''; }
        return false;
    }
    if (p) { document.getElementById(p).value = ''; return false; }
    /* first step is to fetch all entry values */
    idVal = document.getElementById(myFlds[0]).value;
    p1Val = document.getElementById(myFlds[1]).value;
    p2Val = document.getElementById(myFlds[2]).value;
    mailVal = document.getElementById(myFlds[3]).value;
    /* check id field for required length */
    if (idVal.length < 4) { alert('Bad account entry'); return false; }
    /* check re-entered password */
    if (p1Val.length < 1) { alert('Must enter a password'); return false; }
    if (p1Val !== p2Val) { alert('Password entries must match'); return false; }
    /* validate email -- can do much more checking if you want */
    at = mailVal.indexOf('@'); len = mailVal.length; dot = mailVal.lastIndexOf('.');
    if (at >= dot) { alert('Not a valid email address'); return false; }
    if (dot >= len - 2) { alert('Not a valid email domain'); return false; }
    /* if this point reached, the form is good */
    alert('This form is valid'); return true;
}
function verify(id, p2) { //check single digit values only
    if (p2) { //clear request
        for (idx = 0; idx < 99; idx++) {
            if (!document.getElementById(id + idx)) { return false; }
            document.getElementById(id + idx).value = "";
        }
        return false;
    }
    for (idx = 0; idx < 99; idx++) { //if field is blank,set focus to it
        if (!document.getElementById(id + idx)) {
            alert('Form has been sent!'); return true;
        }
        obj = document.getElementById(id + idx); temp = obj.value;
        if (isNaN(parseInt(temp, 10))) {
            alert('Entry must contain exactly one digit!');
            obj.value = ""; obj.focus(); return false;
        }
    }
    alert('Form has been sent!'); return true;
}
function isHex(entry) {
    validChar = '0123456789ABCDEF'; // characters allowed in hex
    strlen = entry.length;   // how long is test string
    if (strlen < 1) { alert('Enter Something!'); return false; }
    entry = entry.toUpperCase();   // lowercase characters?
    // Now scan string for illegal characters
    for (i = 0; i < strlen; i++) {
        if (validChar.indexOf(entry.charAt(i)) < 0) {
            alert('Entry must be in hexadecimal format!'); return false;
        }
    } // end scan loop
    alert('ok!'); return true;
}
function isit(id, expectedval) {
    inputval = document.getElementById(id).value.toUpperCase();
    if (inputval !== expectedval) {
        alert('You must enter the word ' + expectedval);
    } else { alert('ok!'); }
}
function validmany(inFld) {
    ok = false; valAns = ['RED', 'WHITE', 'BLUE']; // list of correct answers
    inO = document.getElementById(inFld); inputval = inO.value.toUpperCase();
    for (i = 0; i < valAns.length; i++) { if (valAns[i] === inputval) { ok = true; } }
    inO.style.background = 'lime'; if (!ok) { inO.style.background = 'pink'; }
    return ok;
}
now = new Date(); // set current date object
function uCase(formobj) { formobj.o.value = formobj.i.value.toUpperCase(); }
function lCase(formobj) { formobj.o.value = formobj.i.value.toLowerCase(); }
function toStr(formobj) { formobj.o.value = now.toString(); }
function toUTC(formobj) { formobj.o.value = now.toUTCString(); }
function toLocal(formobj) {
    formobj.o.value = now.toLocaleString();
}
function CountWords(this_field, show_word_count, show_char_count) {
    if (show_word_count === undefined) { show_word_count = true; } //show is default
    if (show_char_count === undefined) { show_char_count = false; } //noshow is deft
    el = document.getElementById(this_field);
    char_count = el.value.length;          // very crude measure
    fullStr = el.value + " "; // add space delimiter to end of text
    initial_whitespace_rExp = /^[^A-Za-z0-9]+/gi; //use for complex whitespace
    left_trimmedStr = fullStr.replace(initial_whitespace_rExp, " ");
    non_alphanumerics_rExp = /[^A-Za-z0-9]+/gi;   // and for delimiters
    cleanedStr = left_trimmedStr.replace(non_alphanumerics_rExp, " ");
    splitString = cleanedStr.split(" "); word_count = splitString.length - 1;
    if (fullStr.length < 2) { word_count = 0; }
    if (word_count === 1) { wordOrWords = " word"; } else { wordOrWords = " words"; }
    if (char_count === 1) { charOrChars = " character"; } else { charOrChars = " characters"; }
    if (show_word_count && show_char_count) {
        msg = "Word Count:\n" + " " + word_count + wordOrWords + "\n";
        msg += " " + char_count + charOrChars; window.alert(msg);
    } else {
        if (show_word_count) { alert("Word Count:  " + word_count + wordOrWords); }
        else {
            if (show_char_count) {
                window.alert("Character Count:  " + char_count + charOrChars);
            }
        }
    }
    return word_count;
}
// tutorial #13 - cookies
function bakeCookie(name, value) {
    args = arguments; argc = args.length;
    expires = (argc > 2) ? args[2] : null;
    path = (argc > 3) ? args[3] : null;
    domain = (argc > 4) ? args[4] : null;
    secure = (argc > 5) ? args[5] : false;
    expDate = new Date(); day = 24 * 60 * 60 * 1000;
    if (expires) { expDate.setTime(expDate.getTime() + expires * day); }
    document.cookie = name + "=" + escape(value) +
    ((expires === null) ? "" : (";expires=" + expDate.toUTCString())) +
    ((path === null) ? "" : (";path=" + path)) +
    ((domain === null) ? "" : (";domain=" + domain)) +
    ((secure === true) ? ";secure" : "");
}
function eatCookieVal(name) {
    endstr = document.cookie.indexOf(";", name);
    if (endstr === -1) { endstr = document.cookie.length; }
    return unescape(document.cookie.substring(name, endstr));
}
function eatCookie(name) {
    arg = name + "="; alen = arg.length; clen = document.cookie.length; i = 0;
    while (i < clen) {
        j = i + alen;
        if (document.cookie.substring(i, j) === arg) { return eatCookieVal(j); }
        i = document.cookie.indexOf(" ", i) + 1;
        if (i === 0) { break; }
    } 
}
function newColor2(entry, areaID) { // use DOM method
    bakeCookie("colorSet", entry, 7); // save for a week
    if (!areaID) { areaID = "body"; } // default to whole body
    document.getElementById(areaID).style.background = entry;
}
function isColorSet(areaID) { // points at color element
    colorSet = null;
    if (!(colorSet = eatCookie("colorSet"))) { colorSet = null; }
    if (colorSet !== null) { newColor2(colorSet, areaID); }
}
// tutorial #14
function jumpto(el) {
    obj = document.getElementById(el);
    window.location.href = obj.options[obj.selectedIndex].value;
}
