// ==========
// Misc functions for the NGS interactive functionality

var email_regexp = /^(?:\w+\.?)*\w+@(?:\w+\.?)*\w+$/;

// ==========
// Functions for handling cookies

function cookie_set(name, value, duration) {
    var expire = new Date();
    // -1 duration will have cookie expire immediately (delete cookie)
    // 0 duration will have cookie expire when browser is closed
    if (duration != 0) {
        expire.setDate(expire.getDate() + duration);
    }

    cookieStr = "" + name + "=" + value + ((duration != 0) ? "; expires=" + expire.toGMTString() : "") + "; path=/";

    document.cookie = cookieStr;
}

function cookie_get(name) {
    if (document.cookie.length > 0) {
        var cookie_vals = new Array();
        var nv = new Array();
        cookie_vals = document.cookie.split(';');
        for (i = 0; i < cookie_vals.length; i++) {
            nv = cookie_vals[i].split('=');
            // TODO: need to check length - make sure there are two elements
            if (trim(name) == trim(nv[0])) {
                return trim(nv[1]);
            }
        }
        return null;
    } else {
        return null;
    }
}

// Might not need this - use get
function cookie_is_set(name) {
    return (cookie_get(name) != null ? true: false);
}

function cookie_del(name) {
    if (cookie_is_set(name)) {
        cookie_set(name, "", -1);
    }
}

// ==========
//

// Show a hidden div in a fixed position
//   the style (before getting here) should be:
//      display: none;
//      position: absolute;
function showDiv(oDiv, xpos, ypos) {
    if (oDiv != null) {
        oDiv.style.left = "" + xpos + "px";
        oDiv.style.top = "" + ypos +"px";
        oDiv.style.display = "block";
    }
}

function hideDiv(oDiv) {
    if (oDiv != null) {
        oDiv.style.display = "none";
    }
}

// ==========
// Show the send to a friend window

function showSendEmailWindow(oEvent) {
//    window.open("send_to_friend.html","","height=285,width=440,location=no,menubar=no,resizable=no,status=no,toolbar=no");
    new Effect.Appear('ngk_send_wrapper', {duration:3});
}

function closeSendEmailWindow() {
  new Effect.Fade('ngk_send_wrapper', {duration:3});
}

//=========
// Functions for Sending the favorites email

function sendFavoritesEmail() {
    var form = document.forms["send_email_form"]
    if (form != null) {
        var user_email = form.user_email.value
        var friend_email = form.friend_email.value
        if (user_email == null || user_email.length == 0 || !email_regexp.test(user_email)) {
            alert("You must enter a valid email address.");
            form.user_email.focus();
        }
        if (friend_email == null || friend_email.length == 0 || !email_regexp.test(friend_email)) {
            alert("You must enter a valid email address for your friend.");
            form.friend_email.focus();
        }
        else {
            favs_send(user_email, friend_email);
            closeSendEmailWindow();
            // TODO: Don't think we need this any more
//            var oDiv = document.getElementById("ngk_send_wrapper");
            // TODO: Get the email addresses and pass them to the server
//            if (oDiv != null) {
//                hideDiv(oDiv);
//            }
        }
    }
}

// NOTE: The two places to send the favorites email are slightly different
// TODO: Should clean this up so things are more consistent
function sendFavoritesEmail2() {
    var form = document.forms["share_faves"]
    if (form != null) {
        var user_email = "";
        var friend_email = form.friend_email.value
        if (friend_email == null || friend_email.length == 0 || !email_regexp.test(friend_email)) {
            alert("You must enter a valid email address for your friend.");
            form.friend_email.focus();
        }
        else {
            favs_send(user_email, friend_email);
        }
    }
}

function favs_send(from_addr, to_addr) {
    var myConn = new XHConn();
    if (!myConn) alert("XMLHTTP not available. Try a newer/better browser.");
    document.body.style.cursor = "wait";
    var fnWhenDone = function (oXML) { favs_done(oXML.responseText); };
    paramStr = "cmd=send&to=" + to_addr;
    myConn.connect("servlet/FavoritesService", "POST", paramStr, fnWhenDone);
}

function favs_done(responseText) {
    // Check status
    var regexp = new RegExp("^NACK:", "g");
    if (result = regexp.exec(responseText) != null) {
        alert("Error sending Favorites link:\n" + responseText.slice(regexp.lastIndex));
    }
    else {
        alert("Favorites Link Sent!");
    }
    document.body.style.cursor = "auto";
}

//=========
// Functions for Ecards

function sendEcard() {
    var form = document.forms["email_form"]
    if (form != null) {
        var to_email = form.to_email.value
        if (to_email == null || to_email.length == 0 || !email_regexp.test(to_email)) {
            alert("You must enter a valid email address for your friend.");
            form.to_email.focus();
        }
        else {
            ecard_send(selected_ecard_id, to_email);
        }
    }
}

function ecard_send(ecard_id, to_addr) {
    var myConn = new XHConn();
    if (!myConn) alert("XMLHTTP not available. Try a newer/better browser.");
    document.body.style.cursor = "wait";
    var fnWhenDone = function (oXML) { ecard_done(oXML.responseText); };
    paramStr = "cmd=send_my&id=" + ecard_id + "&to=" + to_addr;
    myConn.connect("servlet/EcardService", "POST", paramStr, fnWhenDone);
}

function ecard_done(responseText) {
    // Check status
    var regexp = new RegExp("^NACK:", "g");
    if (result = regexp.exec(responseText) != null) {
        alert("Error sending ECard:\n" + responseText.slice(regexp.lastIndex));
    }
    else {
        alert("E-Card Sent!");
    }
    document.body.style.cursor = "auto";
}

var selected_ecard_id = null;

function SelectEcard(div, id) {
    if (div != null) {
        var divList = getElementsByClass("img", "send_ecard_img_highlight");
        // "unselect" all ecards
        for (var i = 0; i < divList.length; i++) {
            divList[i].className = "send_ecard_img";
        }
        // Select this ecard
        div.className = "send_ecard_img_highlight";
        div.selected = true;
    }
    selected_ecard_id = id;
}

//==========

// From FG:
function openPop(theURL, winName, features) {
	window.open(theURL, winName, features);
}

//==========
// Function for changing Latest & Greatest display

function showLatestGreatest(id) {
    var divList = getDivsByClass("latest_greatest_selection");
    if (id < 0 || id > divList.length - 1) {
        return;
    }

    for (var i = 0; i < divList.length; i++) {
        divList[i].style.display = "none";
    }
    divList[id].style.display = "block";
}

function getElementsByClass(element, class_name) {
    var divList = document.getElementsByTagName(element);
    var elems = new Array();
    var divNum = 0;
    for (var i = 0; i < divList.length; i++) {
        // TODO: This won't work if there are multiple classes for the element
        if (divList[i].className == class_name) {
            elems[divNum]= divList[i];
            divNum++;
        }
    }

    return elems;
}

function getDivsByClass(class_name) {
    return getElementsByClass("div", class_name);
}

// ==========
// Functions for working with favorites in the MyPage area

function RemoveFromRecentFavs(c_id) {
    rem_rec_send(c_id);
}

function rem_rec_send(c_id) {
    var myConn = new XHConn();
    if (!myConn) alert("XMLHTTP not available. Try a newer/better browser.");
    document.body.style.cursor = "wait";
    var fnWhenDone = function (oXML) { rem_rec_done(oXML.responseText); };
    paramStr = "cmd=remrec&contentId=" + c_id;
    myConn.connect("servlet/FavoritesService", "POST", paramStr, fnWhenDone);
}

function rem_rec_done(responseText) {
    // Returns new recent favorites content
    // TODO: check status
    UpdateDiv("recent_favs_content", responseText);
    document.body.style.cursor = "auto";
}

function RemoveFromFavs(c_id, category_id) {
    rem_fav_send(c_id, category_id);
}

function rem_fav_send(c_id, category_id) {
    var myConn = new XHConn();
    if (!myConn) alert("XMLHTTP not available. Try a newer/better browser.");
    document.body.style.cursor = "wait";
    var fnWhenDone = function (oXML) { rem_fav_done(category_id, oXML.responseText); };
    paramStr = "cmd=remcat&contentId=" + c_id + "&categoryId=" + category_id;
    myConn.connect("servlet/FavoritesService", "POST", paramStr, fnWhenDone);
}

function rem_fav_done(category_id, responseText) {
    var map = [
        ["Animal",   "my_favs_animals"],
        ["Game",     "my_favs_games"],
        ["Activity", "my_favs_activities"],
        ["Video",    "my_favs_videos"],
        ["Article",  "my_favs_stories"],
    ];
    var oDiv;
    var i = 0;
    var found = false;
    while (!found && i < map.length) {
        if (map[i][0] == category_id) {
            found = true;
            oDiv = document.getElementById(map[i][1]);
        }
        i++;
    }

    if (!oDiv) {
        // TODO: might want to force a refresh
    }
    oDiv.innerHTML = responseText;
    document.body.style.cursor = "auto";
}

// ==========
// Functions for registration and login
//

function enterKeypress(oEvent, func) {
    if (oEvent.keyCode == 13) {
        // Return code pressed
        func();
    }
}

// Login

function DoLogin() {
    var form = document.forms["login"];
    if (form != null) {
        var user = form.login_user.value;
        var pwd = form.login_pwd.value;
        if (user == null || user.length == 0) {
            alert("You must enter a user name.");
            form.login_user.focus();
        }
        else if (pwd == null || pwd.length == 0) {
            alert("You must enter a password.");
            form.login_pwd.focus();
        }
        else {
            var hash = hex_md5(pwd + user.toUpperCase());
            login_send(user, hash);
        }
    }
    else {
        // Error: Can't find the form
    }
}

function login_send(user, pwd) {
    var myConn = new XHConn();
    if (!myConn) alert("XMLHTTP not available. Try a newer/better browser.");
    document.body.style.cursor = "wait";
    var fnWhenDone = function (oXML) { login_done(oXML.responseText); };
    var str = "cmd=login&name=" + user + "&hash=" + pwd;
    myConn.connect("servlet/UserProfileService", "POST", str, fnWhenDone);
}

function login_done(responseText) {
    var regexp = new RegExp("^NACK:", "g");
    if (result = regexp.exec(responseText) != null) {
        alert("Login Error:\n" + responseText.slice(regexp.lastIndex));
    }
    else {
        window.location.href = "mypage_home.jsp";
    }
    document.body.style.cursor = "auto";
}

// Registration

function DoRegister() {
    var form = document.forms["register"];
    if (form != null) {
        var user = form.reg_user.value;
        var pwd1 = form.reg_pwd1.value;
        var pwd2 = form.reg_pwd2.value;
        var email = form.reg_email.value;
        var bday_month = form.reg_bd_month.value;
        var bday_day = form.reg_bd_day.value;
        var bday_year = form.reg_bd_year.value;
        var page_name = form.reg_pagename.value;
        var gender = ((form.boy_girl[0].checked) ? form.boy_girl[0].value : form.boy_girl[1].value);

        // Do validation
        if (user == null || user.length == 0) {
            alert("You must enter a user name.");
            form.reg_user.focus();
        }
        else if (pwd1 == null || pwd1.length == 0
                || pwd2 == null || pwd2.length == 0) {
            alert("You must enter a password.");
            form.reg_pwd1.focus();
        }
        else if (pwd1 != pwd2) {
            alert("Passwords do not match");
            form.reg_pwd1.focus();
        }
        else if (email == null || email.length == 0 || !email_regexp.test(email)) {
            alert("You must enter a valid email address");
            form.reg_email.focus();
        }
        // TODO: Add date validation
        if (page_name == null || page_name.length == 0) {
            alert("Please enter a name for your page.");
            form.reg_pagename.focus();
        }
        if (!form.boy_girl[0].checked && !form.boy_girl[1].checked) {
            alert("Please check boy or girl.");
            form.boy_girl.focus();
        }
        else {
            var hash = hex_md5(pwd1 + user.toUpperCase());

            var map = new Array();
            map[0] = ["user", user];
            map[1] = ["pwd", hash];
            map[2] = ["email", email];
            map[3] = ["bday", bday_month + "/" + bday_day + "/" + bday_year];
            map[4] = ["pagename", page_name];
            map[5] = ["gender", gender];
            map[6] = ["ps", pwd1];

            register_send(user, map)
        }
    }
    else {
        // Error: Can't find the form
    }
}

function register_send(user, map) {
    var myConn = new XHConn();
    if (!myConn) alert("XMLHTTP not available. Try a newer/better browser.");
    document.body.style.cursor = "wait";
    var fnWhenDone = function (oXML) { register_done(oXML.responseText); };
    var parms = "";
    for (var i = 0; i < map.length; i++) {
        parms += "&" + map[i][0] + "=" + map[i][1];
    }
    var str = "cmd=register" + parms;
    myConn.connect("servlet/UserProfileService", "POST", str, fnWhenDone);
}

function register_done(responseText) {
    var regexp = new RegExp("^NACK:", "g");
    if (result = regexp.exec(responseText) != null) {
        alert("Registration Error:\n" + responseText.slice(regexp.lastIndex));
    }
    else {
        window.location.href = "mypage_home.jsp";
    }
    document.body.style.cursor = "auto";
}

// Forgot password

function DoForgot() {
    var form = document.forms["forgot"];
    if (form != null) {
        var user = form.forgot_user.value;
        if (user == null || user.length == 0) {
            alert("You must enter a user name.");
            form.reg_forgot_user.focus();
        }
        else {
            forgot_send(user);
        }
    }
    else {
        // Error: Can't find the form
    }
}

function forgot_send(user) {
    var myConn = new XHConn();
    if (!myConn) alert("XMLHTTP not available. Try a newer/better browser.");
    document.body.style.cursor = "wait";
    var fnWhenDone = function (oXML) { forgot_done(oXML.responseText); };
    var str = "cmd=forgot&name=" + user;
    myConn.connect("servlet/UserProfileService", "POST", str, fnWhenDone);
}

function forgot_done(responseText) {
    var regexp = new RegExp("^NACK:", "g");
    if (result = regexp.exec(responseText) != null) {
        alert(responseText.slice(regexp.lastIndex));
    }
    else {
        alert("A new password has been sent.");
    }
    document.body.style.cursor = "auto";
}

// Logout

function Logout() {
    cookie_del("userId");
    window.location.href = "mypage_login.jsp";
}

// ==========
// Functions for working with settings

function changeTheme(id) {
    settheme_send(id);
}

function lookupTheme(id) {
    var i = 0;
    var found = false;
    var theme_file = null;
    while (!found && i < theme_map.length) {
        if (theme_map[i][0] == id) {
            found = true;
            theme_file = theme_map[i][1];
        }
        i++;
    }
    return theme_file;
}

function settheme_send(id) {
    var myConn = new XHConn();
    if (!myConn) alert("XMLHTTP not available. Try a newer/better browser.");
    document.body.style.cursor = "wait";
    var fnWhenDone = function (oXML) { settheme_done(id, oXML.responseText); };
    var str = "cmd=setTheme&id=" + id;
    myConn.connect("servlet/UserProfileService", "POST", str, fnWhenDone);
}

function settheme_done(id, responseText) {
    if (responseText != "ACK") {
        alert("Unable to save theme setting: " + responseText);
    }
    else {
        oThemeCSSLink = document.getElementById("theme_css");
        var css_file = lookupTheme(id);
        oThemeCSSLink.href = "/staticfiles/" + css_file;
        oThemeSelect = document.getElementById("theme_select");
        if (oThemeSelect != null) {
            oThemeSelect.value = id;
        }
    }
    document.body.style.cursor = "auto";
}

function setPageName() {
    var oNewNameInput = document.getElementById("page_name_input");
    if (oNewNameInput != null) {
        var new_name = oNewNameInput.value;
        // TODO: Need to check name against dirty word list
        setpagename_send(new_name);
    }
}

function setpagename_send(page_name) {
    var myConn = new XHConn();
    if (!myConn) alert("XMLHTTP not available. Try a newer/better browser.");
    document.body.style.cursor = "wait";
    var fnWhenDone = function (oXML) { setpagename_done(oXML.responseText); };
    var str = "cmd=setPageName&pageName=" + page_name;
    myConn.connect("servlet/UserProfileService", "POST", str, fnWhenDone);
}

function setpagename_done(responseText) {
    var oName = document.getElementById("page_name_disp");
    if (oName != null) {
        oName.innerHTML = responseText;
    }
    else {
        alert("Can't find the page name element");
    }
    document.body.style.cursor = "auto";
}

function setPwd() {
    var form = document.forms["change_password"];
    if (form != null) {
        var cur_pwd = form.cur_pwd.value;
        var new_pwd1 = form.new_pwd1.value;
        var new_pwd2 = form.new_pwd2.value;
        var user_name = form.user_name.value;

        if (cur_pwd == null || cur_pwd.length == 0
            || new_pwd1 == null || new_pwd1.length == 0
            || new_pwd2 == null || new_pwd2.length == 0) {
            alert("You must fill in all password fields");
        }
        else if ( new_pwd1 != new_pwd2) {
            alert("New passwords do not match.");
            form.new_pwd1.value = "";
            form.new_pwd2.value = "";
            form.new_pwd1.focus();
        }
        else {
            // Generate hash values before sending
            var cur_hash = hex_md5(cur_pwd + user_name.toUpperCase());
            var new_hash = hex_md5(new_pwd1 + user_name.toUpperCase());
            setpwd_send(cur_hash, new_hash, new_pwd1);
        }
    }
}

function setpwd_send(cur_hash, new_hash, new_pwd) {
    var myConn = new XHConn();
    if (!myConn) alert("XMLHTTP not available. Try a newer/better browser.");
    document.body.style.cursor = "wait";
    var fnWhenDone = function (oXML) { setpwd_done(oXML.responseText); };
    var str = "cmd=setPwd&curPwd=" + cur_hash + "&newPwd=" + new_hash + "&newRaw=" + new_pwd;
    myConn.connect("servlet/UserProfileService", "POST", str, fnWhenDone);
}

function setpwd_done(responseText) {
    if (responseText == "ACK") {
        alert("Password changed.");
    }
    else {
        alert("Unable to change password: " + responseText);
    }
    var form = document.forms["change_password"];
    if (form != null) {
        form.cur_pwd.value = "";
        form.new_pwd1.value = "";
        form.new_pwd2.value = "";
        form.cur_pwd.focus();
    }
    document.body.style.cursor = "auto";
}

// ==========
// Functions for working with surveys

function submitSurvey_click() {
    // Get Data
    var surveyForm = document.forms["survey_input"];
    var survey_id = surveyForm.survey_id.value;
    var num_questions = surveyForm.num_questions.value;
    var answers = new Array();
    var answer;
    var radios;
    for (i = 1; i <= num_questions; i++) {
        eval("radios = surveyForm.q_"+i+"_answer");
        for (j = 0; j < radios.length; j++) {
            if (radios[j].checked) {
                answers[i-1] = [radios[j].getAttribute("q_id"), radios[j].value];
                break;
            }
        }
    }
    submitSurvey_send(survey_id, answers);
}

function submitSurvey_send(s_id, answers) {
    var myConn = new XHConn();
    if (!myConn) alert("XMLHTTP not available. Try a newer/better browser.");
    document.body.style.cursor = "wait";
    var fnWhenDone = function (oXML) { submitSurvey_done(oXML.responseText); };
    var str = "cmd=submit&id=" + s_id + "&answers=";
    for (i = 0; i < answers.length; i++) {
        if (i != 0) {
            str += ",";
        }
        str += answers[i][0] + "=" + answers[i][1];
    }
    myConn.connect("servlet/SurveyService", "POST", str, fnWhenDone);
}

function submitSurvey_done(responseText) {
    var oContainer = document.getElementById("survey");
    oContainer.innerHTML = responseText;
    document.body.style.cursor = "auto";
}

// ----------

// TODO: Finish this - Not ready yet
function validateForm(form_name, opt_func) {
    var form = document.forms[form_name];
    if (form == null) {
        // Can't find form
        return false;
    }

    var error = false;
    var regexp = null;
    for (var i = 0; i < form.elements.length; i++) {
        var e = form.elements[i];
        if (e.type == "text" && e.regexp != null) {
            regexp = new RegExp(e.regexp);
            e.valid = regexp.test(e.value);
            if (!e.valid) {
                error = true;
            }
        }
    }

    if (error) {
        alert("Form data is not valid");
    }

    return error;
}

// ----------
// Game Stuff

function GetGameBkgndColor() {
    var tmpColor = "#9F9F9F";
    var bgColor;
    var oDiv = document.getElementById("games_tbl");
    if (oDiv != null) {
        if (oDiv.currentStyle) {
            tmpColor = oDiv.currentStyle["backgroundColor"];
        }
        else if (window.getComputedStyle) {
            tmpColor = window.getComputedStyle(oDiv, null).getPropertyValue("background-color");
        }
    }

    // Color could be rgb(rrr, ggg, bbb)
    var color = new RGBColor(tmpColor);
    if (color.ok) { // 'ok' is true when the parsing was a success
        bgColor = color.toHex();
    }
    else {
        bgColor = "#9F9F9F";
    }

    return bgColor;
}

function WriteGame(game_base, game_src, height, width) {
    var game_width = 672;
    var game_height = 501;
    var background_color = GetGameBkgndColor();
/*
    var blob =
    "<object codebase=\"http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,19,0\""
    + " classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\""
    + " height=\"" + game_height + "\""
    + " width=\"" + game_width + "\">"
    + "<param name=\"movie\" value=\"/staticfiles" + game_src + "\"></param>"
    + "<param name=\"base\" value=\"/staticfiles" + game_base + "\"></param>"
    + "<param name=\"bgcolor\" value=\"" + background_color + "\"></param>"
    + "<param name=\"FlashVars\" value=\"xmldoc=/staticfiles&amp;soundspath=/staticfiles/NGS/NGKids/SiteAssets/flash/sounds/&amp;videospath=/staticfiles/NGS/NGKids/SiteAssets/flash/videos/&amp;imagespath=/staticfiles/NGS/NGKids/SiteAssets/flash/images/\">"
    + "<param value=\"high\" name=\"quality\">"
    + "<embed bgcolor=\"" + background_color + "\""
    + " type=\"application/x-shockwave-flash\" pluginspage=\"http://www.macromedia.com/go/getflashplayer\" quality=\"high\""
    + " src=\"/staticfiles" + game_src + "\""
    + " base=\"/staticfiles" + game_base + "\""
    + " flashvars=\"xmldoc=/staticfiles&amp;soundspath=/staticfiles/NGS/NGKids/SiteAssets/flash/sounds/&amp;videospath=/staticfiles/NGS/NGKids/SiteAssets/flash/videos/&amp;imagespath=/staticfiles/NGS/NGKids/SiteAssets/flash/images/&quot;\""
    + " height=\"" + game_height + "\""
    + " width=\"" + game_width + "\">"
    + "</object>";

    var oDiv = document.getElementById("thegame");
    if (oDiv != null) {
        oDiv.innerHTML = blob;
    }
*/

    var randForCacheClear = Math.random()*100000;
    var swfFileName = "/staticfiles" + game_src + "?rand=" + randForCacheClear;
//    var so = new SWFObject(swfFileName, "flash_game_swf", "672", "501", "7", background_color);
    var so = new SWFObject(swfFileName, "flash_game_swf", width, height, "7", background_color);
    so.addParam("base", "/staticfiles" + game_base);
    so.write("thegame");

    /*
  <!--
<td class="landing_feature_game">
  <div id="flash_game">
    <noscript>
      <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,19,0" width="672" height="501">
        <param name="movie" value="/staticfiles/NGS/NGKids/Game/GameFiles/armadillo/armadillo_alley.swf"/>
        <param name="base" value="/staticfiles/NGS/NGKids/Game/GameFiles/armadillo/" />
        <param name="FlashVars" value="xmldoc=/staticfiles&soundspath=/staticfiles/NGS/NGKids/SiteAssets/flash/sounds/&videospath=/staticfiles/NGS/NGKids/SiteAssets/flash/videos/&imagespath=/staticfiles/NGS/NGKids/SiteAssets/flash/images/" />
        <param name="quality" value="high"/>
        <embed src="/staticfiles/NGS/NGKids/Game/GameFiles/armadillo/armadillo_alley.swf" FlashVars="xmldoc=/staticfiles&soundspath=/staticfiles/NGS/NGKids/SiteAssets/flash/sounds/&videospath=/staticfiles/NGS/NGKids/SiteAssets/flash/videos/&imagespath=/staticfiles/NGS/NGKids/SiteAssets/flash/images/" quality="high" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" width="672" height="501" base="/staticfiles/NGS/NGKids/Game/GameFiles/armadillo/">
        </embed>
      </object>
    </noscript>
  </div>
  <script type="text/javascript">
    var randForCacheClear = Math.random()*100000;
    var swfFileName = "/staticfiles/NGS/NGKids/Game/GameFiles/armadillo/armadillo_alley.swf?rand="+randForCacheClear;
    var so = new SWFObject(swfFileName, "flash_game_swf", "672", "501", "7", "#69CAE2");
    so.addParam("base", "/staticfiles/NGS/NGKids/Game/GameFiles/armadillo/");
    so.write("flash_game");
  </script>
</td>
  -->
     */
}

// ==========
// Check these for dup code
// ==========

// ========== May want some of these in the future ==========

// ==========
// Functions for rating content

var ratingSet = false;
var rating = 0;
var tmpRating = 0;

function rating_rollover(oEvent) {
    var oDiv = (oEvent.target || oEvent.srcElement);
    var divXOff = oDiv.offsetLeft;
    var relX = oEvent.clientX - divXOff;

    var oDebugX = document.getElementById("xval");
    var oDebugY = document.getElementById("yval");
    if (oDebugX != null) {
        oDebugX.innerHTML = oEvent.clientX;
    }
    if (oDebugY != null) {
        oDebugY.innerHTML = oEvent.clientY;
    }

    tmpRating = parseInt(relX / 16) + 1;

    var oDebugRating = document.getElementById("rating");
    if (oDebugRating != null) {
        oDebugRating.innerHTML = tmpRating;
    }

    switch (tmpRating) {
    case 1:
        oDiv.style.backgroundImage = "url(/staticfiles/NGS/NGKids/SiteAssets/img/RatingsBox_1.gif)";
        break;
    case 2:
        oDiv.style.backgroundImage = "url(/staticfiles/NGS/NGKids/SiteAssets/img/RatingsBox_2.gif)";
        break;
    case 3:
        oDiv.style.backgroundImage = "url(/staticfiles/NGS/NGKids/SiteAssets/img/RatingsBox_3.gif)";
        break;
    case 4:
        oDiv.style.backgroundImage = "url(/staticfiles/NGS/NGKids/SiteAssets/img/RatingsBox_4.gif)";
        break;
    case 5:
        oDiv.style.backgroundImage = "url(/staticfiles/NGS/NGKids/SiteAssets/img/RatingsBox_5.gif)";
        break;
    }
}

function rating_out(oEvent) {
    var oDiv = (oEvent.target || oEvent.srcElement);

    var oDebugX = document.getElementById("xval");
    var oDebugY = document.getElementById("yval");
    if (oDebugX != null) {
        oDebugX.innerHTML = 0;
    }
    if (oDebugY != null) {
        oDebugY.innerHTML = 0;
    }

    var oDebugRating = document.getElementById("rating");

    if (ratingSet == false) {
      oDiv.style.backgroundImage = "url(/staticfiles/NGS/NGKids/SiteAssets/img/RatingsBox_0.gif)";
      if (oDebugRating != null) {
          oDebugRating.innerHTML = 0;
      }
    }
    else {
        switch (rating) {
        case 1:
            oDiv.style.backgroundImage = "url(/staticfiles/NGS/NGKids/SiteAssets/img/RatingsBox_1.gif)";
            break;
        case 2:
            oDiv.style.backgroundImage = "url(/staticfiles/NGS/NGKids/SiteAssets/img/RatingsBox_2.gif)";
            break;
        case 3:
            oDiv.style.backgroundImage = "url(/staticfiles/NGS/NGKids/SiteAssets/img/RatingsBox_3.gif)";
            break;
        case 4:
            oDiv.style.backgroundImage = "url(/staticfiles/NGS/NGKids/SiteAssets/img/RatingsBox_4.gif)";
            break;
        case 5:
            oDiv.style.backgroundImage = "url(/staticfiles/NGS/NGKids/SiteAssets/img/RatingsBox_5.gif)";
            break;
        }

        if (oDebugRating != null) {
            oDebugRating.innerHTML = rating;
        }
    }
}

function rating_click(oEvent, c_id) {
    ratingSet = true;
    rating = tmpRating;
    rating_send(rating, c_id);
}

function rating_send(rating, c_id) {
    var myConn = new XHConn();
    if (!myConn) alert("XMLHTTP not available. Try a newer/better browser.");
    var fnWhenDone = function (oXML) { rating_done(oXML.responseText); };
    var ratingStr = "contentId=" + c_id + "&rating=" + rating;
    myConn.connect("/ngkids_mypage/servlet/RatingsService", "POST", ratingStr, fnWhenDone);
}

function rating_done(responseTxt) {
    // TODO: Should check response
/* For Debug
    oResultTxt = document.getElementById("rating_result");
    if (!oResultTxt) alert("Fubar!");
    oResultTxt.innerHTML = "Thank you for rating this content:";

    newP = document.createElement("p");
    newPTxt = document.createTextNode(responseTxt);
    newP.appendChild(newPTxt);
    oResultTxt.appendChild(newP);
*/
}

// ==========

function SendLink(url) {
//    window.open("/ngkids_mypage/SendLink.html","","height=285,width=440,location=no,menubar=no,resizable=no,status=no,toolbar=no");
//    window.open("/ngkids_mypage/servlet/SendToService?cmd=form&url=" + url,"","height=285,width=440,location=no,menubar=no,resizable=no,status=no,toolbar=no");
    window.open("/ngkids_mypage/SendLink.jsp?url=" + url,"","height=285,width=440,location=no,menubar=no,resizable=no,status=no,toolbar=no");
}

function link_send(url, from_addr, to_addr) {
    var myConn = new XHConn();
    if (!myConn) alert("XMLHTTP not available. Try a newer/better browser.");
    var fnWhenDone = function (oXML) { link_done(oXML.responseText); };
    var paramStr = "cmd=send&url=" + url + "&from=" + from_addr + "&to=" + to_addr;
    myConn.connect("/ngkids_mypage/servlet/SendToService", "POST", paramStr, fnWhenDone);
}

function link_done(responseText) {
    var regexp = new RegExp("^NACK:");
    if (result = regexp.exec(responseText) != null) {
        alert("Error sending link:\n" + responseText.slice(regexp.lastIndex));
    }
    else {
        alert("Link Sent!");
    }

    window.close();
}

function SendLinkEmail(url) {
    var form = document.forms["send_link"]
    if (form != null) {
        var from_email = form.from_email.value;
        var to_email = form.to_email.value
        var regexp = new RegExp(".+@.+\....*"); // Simplistic email address validation
        if (from_email == null || from_email.length == 0 || !regexp.test(from_email)) {
            alert("You must enter a valid email address for yourself.");
            form.from_email.focus();
            return false;
        }
        else if (to_email == null || to_email.length == 0 || !regexp.test(to_email)) {
            alert("You must enter a valid email address for your friend.");
            form.to_email.focus();
            return false;
        }
        else {
            link_send(url, from_email, to_email);
            return true;
        }
    }
}

// ==========
// Utility functions for communicating with the server
/*
function TestSend() {
    var dat = 5;
    var params = [["cmd", 1],["id", dat]];
    var callback = function (oXML) { TestSendDone(); };
    var callback_params = [dat];
    send_to_server(params, callback, callback_params);
}

function TestSendDone(str, params) {
    var str2 = str + "\n";
    for each (var p in params) {
        str2 += ", " + p;
    }
    alert("str2: " + str2);
}

function send_to_server(params, callback, callback_params) {
    var myConn = new XHConn();

    if (!myConn) {
        alert("XMLHTTP not available. Try a newer/better browser.");
        return;
    }

    var str = "";
    for (var i = 0; i < params.length; i++) {
        if (i > 0) {
            str += "&";
        }
        str += params[i][0] + "=" + params[i][1];
    }

    callback(str, callback_params);

//    var fnWhenDone = function (oXML) { submitPoll_done(oXML.responseText); };
//    var str = "cmd=submit&pollId=" + p_id + "&answerId=" + p_answer;
//    myConn.connect("servlet/PollService", "POST", str, fnWhenDone);
}
*/

// ==========

function UpdateDiv(id, content) {
    var oDiv = document.getElementById(id);
    if (!oDiv) {
        // Can't find the div so force a reload to get the update
        location.reload(true);
    }
    else {
        oDiv.innerHTML = content;
    }
}


// ==========
//

function trim(str) {
    var t = str;
    t = t.replace(/^\s*/, "");
    t = t.replace(/\s*$/, "");
    return t;
}

