var globalIsBoy = false;
var domain = "http://activity.campwareagle.org";
//var domain = "http://localhost:8888";
var majorArray = [];
var elecArray = [];
var majorPriorityArray = Array();
var elecPriorityArray = Array();
var editMajors = false;
var editElectives = false;
var majorMin = 16;
var majorMax = 16;
var majorSections = [];
var majorSectionMins = [];
var majorSectionAct = [];
var elecMin = 16;
var elecMax = 16;
var elecSections = [];
var elecSectionMins = [];
var elecSectionAct = [];
var numBoyMaj = 0;
var numGirlMaj = 0;
var numBoyElec = 0;
var numGirlElec = 0;
var boyMajs = new Array();
var girlMajs = new Array();
var boyElecs = new Array();
var girlElecs = new Array();
var predate = false;
var majorInstructions = '<h3>Major Activities</h3><p>Below is the list of available "Major" activities. Outdoor, Creative and General Majors are designed primarily for the camper to learn or improve upon a skill and normally meet four times during the session. 7 day campers will participate in two major activities. 14 day campers will participate in four major activities.</p><p>Please choose <strong>exactly 16</strong> activities below. Please note that you must select at least 4 Outdoor and 4 Creative activities, though more may be selected within each area.</p><p>You will be given the opportunity to prioritize these activities next.</p>'

$(document).ready(function() {
    $("#login").fadeIn("slow");
    $("#login_button").click(function() {
        if ($("#username").val() == "mish" && $("#password").val() == "mash") {
            $("#login").fadeOut("slow");
            $("#camperInfo").fadeIn("slow");
        } else if ($("#username").val() == "office" && $("#password").val() == "helper") {
            $("#login").fadeOut("slow");
            $("#camperInfo").fadeIn("slow");
            var d = new Date();
            var curr_year = d.getFullYear();
            var prev_year = curr_year - 1;
            $('<option value="'+curr_year+'"></option>').html(curr_year).appendTo("#cpredateyear");
            $('<option value="'+prev_year+'"></option>').html(prev_year).appendTo("#cpredateyear");
            $("#predate").fadeIn();
            predate = true;
        }else {
            alert("Invalid username or password. Please try again.");
        }
        return false;
    });
    $("#login_reset").click(function() {
        $("#username").val("");
        $("#password").val("");
    });

    $("#infoNext").click(function() {
        var errMsg = "";
        var bolValid = true;
        if ($("#cfirstname").val() == "") {
            errMsg += "Please enter a first name.\n";
            bolValid = false;
        }
        if ($("#clastname").val() == "") {
            errMsg += "Please enter a last name.\n";
            bolValid = false;
        }
        if ($("#ccampercode").val() == "") {
            errMsg += "Please enter a camper code.\n";
            bolValid = false;
        }
        if (!$("input[@name='gender']:checked").val()) {
            errMsg += "Please select your camper's gender.\n";
            bolValid = false;
        }
        if ($("#cage").val() == -1) {
            errMsg += "Please select your camper's age.\n";
            bolValid = false;
        }
        if ($("#cbirthyear").val() == -1) {
            errMsg += "Please select a valid birthdate.\n";
            bolValid = false;
        }
        if (bolValid) {
            $("#camperInfo").fadeOut("slow");
            checkGender();
            $("#majorWrapper").html(majorInstructions);
            loadActivities(globalIsBoy, true, "majorWrapper");
            $("#majorWrapper").fadeIn("slow");
        } else {
            alert(errMsg);
        }
        return false;
    });

    $("#cage").change(function() {

        checkAge();
    });

    checkAge();
    $.ajax({
        type: "GET",
        url: domain + "/data/boys_majors.xml",
        dataType: "xml",
        success: function(xml) {
            $(xml).find('area').each(function() {
                $(this).find('activity').each(function() {
                    //boyMajs(numBoyMaj) = $(this).find('name').text();
                    numBoyMaj++;
                });
            });
        },
        error: function(xhr, thrownError) {
            alert(xhr.responseXML);
            alert(thrownError);
        }
    });
    $.ajax({
        type: "GET",
        url: domain + "/data/boys_electives.xml",
        dataType: "xml",
        success: function(xml) {
            $(xml).find('area').each(function() {
                $(this).find('activity').each(function() {
                    //boyElecs(numBoyElec) = $(this).find('name').text();
                    numBoyElec++;
                });
            });
        },
        error: function(xhr, thrownError) {
            alert(xhr.responseXML);
            alert(thrownError);
        }
    });
    $.ajax({
        type: "GET",
        url: domain + "/data/girls_majors.xml",
        dataType: "xml",
        success: function(xml) {
            $(xml).find('area').each(function() {
                $(this).find('activity').each(function() {
                    //girlMajs(numGirlMaj) = $(this).find('name').text();
                    numGirlMaj++;
                });
            });
        },
        error: function(xhr, thrownError) {
            alert(xhr.responseXML);
            alert(thrownError);
        }
    });
    $.ajax({
        type: "GET",
        url: domain + "/data/girls_electives.xml",
        dataType: "xml",
        success: function(xml) {
            $(xml).find('area').each(function() {
                $(this).find('activity').each(function() {
                    //girlElecs(numGirlElec) = $(this).find('name').text();
                    numGirlElec++;
                });
            });
        },
        error: function(xhr, thrownError) {
            alert(xhr.responseXML);
            alert(thrownError);
        }
    });
});


function checkGender(){
    if ( $("#cgenderboy").is(':checked') ){

            //if ($("#cgenderboy").val() == "boy") {
        globalIsBoy = true;
    } else {
        globalIsBoy = false;
    }
}

function checkAge() {
    if ($("#cage").val() > 0) {

        var d = new Date();
        var curr_year = d.getFullYear();
        var yr = curr_year - $("#cage").val();
        var yrLow = yr - 1;
        var yrHigh = yr + 1;
        //            $("#cdatepicker").datepicker({ changeYear: true, yearRange: yrLow + ':' + yr, onSelect: function(dateText, inst) {
        //                $("#cdatepicker").text(dateText);
        //            }
        $("#cbirthyear").text('');
        $("#cbirthyear").append($("<option></option>").attr("value", "-1").text('Select One'))
        for (var i = yrLow; i <= yrHigh; i++) {
            $('#cbirthyear').append($("<option></option>").attr("value", i).text(i));
        }

    }
}
//http://jacwright.com/projects/javascript/date_format
Date.prototype.format = function(format) { var returnStr = ''; var replace = Date.replaceChars; for (var i = 0; i < format.length; i++) { var curChar = format.charAt(i); if (replace[curChar]) { returnStr += replace[curChar].call(this); } else { returnStr += curChar; } } return returnStr; }; Date.replaceChars = { shortMonths: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], longMonths: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'], shortDays: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'], longDays: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'], d: function() { return (this.getDate() < 10 ? '0' : '') + this.getDate(); }, D: function() { return Date.replaceChars.shortDays[this.getDay()]; }, j: function() { return this.getDate(); }, l: function() { return Date.replaceChars.longDays[this.getDay()]; }, N: function() { return this.getDay() + 1; }, S: function() { return (this.getDate() % 10 == 1 && this.getDate() != 11 ? 'st' : (this.getDate() % 10 == 2 && this.getDate() != 12 ? 'nd' : (this.getDate() % 10 == 3 && this.getDate() != 13 ? 'rd' : 'th'))); }, w: function() { return this.getDay(); }, z: function() { return "Not Yet Supported"; }, W: function() { return "Not Yet Supported"; }, F: function() { return Date.replaceChars.longMonths[this.getMonth()]; }, m: function() { return (this.getMonth() < 9 ? '0' : '') + (this.getMonth() + 1); }, M: function() { return Date.replaceChars.shortMonths[this.getMonth()]; }, n: function() { return this.getMonth() + 1; }, t: function() { return "Not Yet Supported"; }, L: function() { return (((this.getFullYear() % 4 == 0) && (this.getFullYear() % 100 != 0)) || (this.getFullYear() % 400 == 0)) ? '1' : '0'; }, o: function() { return "Not Supported"; }, Y: function() { return this.getFullYear(); }, y: function() { return ('' + this.getFullYear()).substr(2); }, a: function() { return this.getHours() < 12 ? 'am' : 'pm'; }, A: function() { return this.getHours() < 12 ? 'AM' : 'PM'; }, B: function() { return "Not Yet Supported"; }, g: function() { return this.getHours() % 12 || 12; }, G: function() { return this.getHours(); }, h: function() { return ((this.getHours() % 12 || 12) < 10 ? '0' : '') + (this.getHours() % 12 || 12); }, H: function() { return (this.getHours() < 10 ? '0' : '') + this.getHours(); }, i: function() { return (this.getMinutes() < 10 ? '0' : '') + this.getMinutes(); }, s: function() { return (this.getSeconds() < 10 ? '0' : '') + this.getSeconds(); }, e: function() { return "Not Yet Supported"; }, I: function() { return "Not Supported"; }, O: function() { return (-this.getTimezoneOffset() < 0 ? '-' : '+') + (Math.abs(this.getTimezoneOffset() / 60) < 10 ? '0' : '') + (Math.abs(this.getTimezoneOffset() / 60)) + '00'; }, P: function() { return (-this.getTimezoneOffset() < 0 ? '-' : '+') + (Math.abs(this.getTimezoneOffset() / 60) < 10 ? '0' : '') + (Math.abs(this.getTimezoneOffset() / 60)) + ':' + (Math.abs(this.getTimezoneOffset() % 60) < 10 ? '0' : '') + (Math.abs(this.getTimezoneOffset() % 60)); }, T: function() { var m = this.getMonth(); this.setMonth(0); var result = this.toTimeString().replace(/^.+ \(?([^\)]+)\)?$/, '$1'); this.setMonth(m); return result; }, Z: function() { return -this.getTimezoneOffset() * 60; }, c: function() { return this.format("Y-m-d") + "T" + this.format("H:i:sP"); }, r: function() { return this.toString(); }, U: function() { return this.getTime() / 1000; } };

function getDateString(mo, da, yr) {
    var myDate = new Date();
    mo = mo - 1
    myDate.setFullYear(yr, mo, da);
    return myDate.format("F j, Y");

}

function setReorder() {
    $("#orderList").sortable({ 
        opacity: 0.7,
        revert: true,
        scroll: true,
        handle: $(".removeItem").add(".removeItem a img"),
        placeholder: 'ui-state-highlight',
        update: function() { ReorderOnDrop(); }
    });
    $("#orderList").disableSelection();
}

function ReorderOnDrop() {
    var items = $(".major-priority");
    majorPriorityArray = Array();
    
    for (var x = 0; x < items.length; x++) {
        majorPriorityArray[x] = items[x].id;
    }
}

function setElectiveReorder() {
    $("#orderListElective").sortable({
        opacity: 0.7,
        revert: true,
        scroll: true,
        handle: $(".removeItem").add(".removeItem a img"),
        placeholder: 'ui-state-highlight',
        update: function() { ReorderElectiveOnDrop(); }
    });
    $("#orderListElective").disableSelection();
}

function ReorderElectiveOnDrop() {
    var items = $(".elective-priority");
    elecPriorityArray = Array();

    for (var x = 0; x < items.length; x++) {
        elecPriorityArray[x] = items[x].id;
    }
}


function loadActivities(isBoy, isMajors, wrapperDiv){
    var earl;
    
    if(isBoy){
        if (isMajors){
            earl = domain + "/data/boys_majors.xml";
        }else{
            earl = domain + "/data/boys_electives.xml";
        }
    }else{
        if(isMajors){
            earl = domain + "/data/girls_majors.xml";
        }else{
            earl = domain + "/data/girls_electives.xml";
        }
    }
    $.ajax({
        type: "GET",
        url: earl,
        dataType: "xml",
        success: function(xml) {
        var counter = 0;
        if (!isMajors){
            for(foo in majorArray){
                counter++;
            }
        }
        $(xml).find('area').each(function() {
            
            var name = $(this).find('desc').text(); //.trim();
            name = $.trim(name);
            var min = $(this).find('minimum').text(); //.trim();
            min = $.trim(min);
            if(isMajors){
                majorSectionMins[name] = min - 0;
                majorSectionAct[name] = 0;
            } else {
                elecSectionMins[name] = min - 0;
                elecSectionAct[name] = 0;
            }
            if (min > 0) {
                $('<div id="' + name + '"></div>').html('<legend><b><span id="area' + name + '">' + name + '</span></b></legend><div class="instructions">Please choose at least ' + min + '.</div>').appendTo('#' + wrapperDiv);
                $('<div class="instructions"></div>').html('You have chosen <span id="num_' + name + '">0</span>.<p />').appendTo('#' + name);
            } else {
                $('<div id="' + name + '"></div>').html('<b><span id="area' + name + '">' + name + '</span></b><div class="instructions"><br/></div>').appendTo('#' + wrapperDiv);
            }
            $(this).find('activity').each(function() {
                counter++;
                var id = $(this).find('id').text(); //.trim();
                id = $.trim(id);
                var act = $(this).find('name').text(); //.trim();
                act = $.trim(act);
                if (isMajors) {
                    majorArray[id] = act;
                    $('<div></div>').html('<input type="checkbox" name="' + name + '_' + id + '" value="' + id + '" /> ' + counter + '. ' + act).appendTo('#' + name);
                } else {
                    elecArray[id] = act;
                    $('<div></div>').html('<input type="checkbox" name="' + name + '_' + id + '" value="' + id + '" /> ' + counter + '. ' + act + '<div id="div_for_' + id + '" style="display:none;">I want to go to this class <select id="c' + id + '_num" name="' + id + '_num"><option value="1">Once</option><option value="2">Twice</option></select></div>').appendTo('#' + name);
                    $("#c" + id + "_num").change(function() {
                        var divNum = "#num_" + name;
                        var n = parseInt($(divNum).text(), 10);
                        if ($(this).val() == 1) {
                            $(divNum).text(n - 1);
                            elecSectionAct[name] = elecSectionAct[name] - 1;
                        } else {
                            $(divNum).text(n + 1);
                            elecSectionAct[name] = elecSectionAct[name] + 1;
                        }
                        $("#floatingElecCounter").text(getTotal(isMajors));
                    });
                }
            });
            $('<div class="instructions"></div>').html('<br/> ').appendTo('#' + name);
            $('<div class="instructions"></div>').html('<hr><br/> ').appendTo('#' + name);
        });
        var numAreas = 0;
        if (isMajors){
            for (goo in majorSectionAct){
                numAreas++;
            }
            if (numAreas < 2){
                for (goo in majorSectionAct){
                    $("#area" + goo).html('');
                }
            }
        } else {
            for (goo in elecSectionAct){
                numAreas++;
            }
            if (numAreas < 2){
                for (goo in elecSectionAct){
                    $("#area" + goo).html('');
                }
            }
        }
        
        $("INPUT[type='checkbox']").click(function() {
            if (!isMajors) {
                $("#div_for_" + $(this).val()).slideToggle("slow");
                var chkName = $(this).attr("name");
                var spl = chkName.split('_');
                var sect = spl[0];
                var divNum = "#num_" + spl[0];
                var n = parseInt($(divNum).text(), 10);
                var numTimes = $("#c" + $(this).val() + "_num").val();
                var comeon = n - 0;
                var thistoo = numTimes - 0;
                if ($(this).is(":checked")) {
                    $(divNum).text(comeon + thistoo);
                    elecSectionAct[sect] = comeon + thistoo;
                } else {
                    $(divNum).text(comeon - thistoo);
                    elecSectionAct[sect] = comeon - thistoo;
                }
                
                $("#floatingElecCounter").text(getTotal(isMajors));
            } else {
                var chkName = $(this).attr("name");
                var spl = chkName.split('_');
                var divNum = "#num_" + spl[0];
                var sect = spl[0];
                var n = parseInt($(divNum).text(), 10);
                if ($(this).is(":checked")) {
                    $(divNum).text(n + 1);
                    majorSectionAct[sect] = majorSectionAct[sect] - 0 + 1;
                    
                } else {
                    $(divNum).text(n - 1);
                    majorSectionAct[sect] = majorSectionAct[sect] - 0 - 1;
                }
                
                $("#floatingMajorCounter").text(getTotal(isMajors));
            }
        });

        if (isMajors) {
            $('<div></div>').html('<input type="button" id="majorPrev" value="" class="prev-button" /><input type="button" id="majorNext" value="" class="next-button" />').appendTo("#" + wrapperDiv);
            $('<div id="cmajorcounter" class="activity-counter"></div>').html('<span id="floatingMajorCounter">0</span>/'+majorMin + '<div class="floating-box">total chosen<div>').appendTo("#"+wrapperDiv);

            $("#majorNext").click(function() {
                var e = validateMinMax(isMajors);
                if (e == ''){
                    $("#" + wrapperDiv).fadeOut("slow");
                    loadMajorPriorities(isBoy, "majorPriority");
                    $("#majorPriority").fadeIn("slow");
                } else {
                    alert(e);
                }   
            });
            $("#majorPrev").click(function() {
                $("#" + wrapperDiv).fadeOut("slow")
                $("#camperInfo").fadeIn("slow");
            });
        } else {
            $('<div></div>').html('<input type="button" id="elecPrev" value="" class="prev-button" /><input type="button" id="elecNext" value="" class="next-button" />').appendTo("#" + wrapperDiv);
            $('<div id="celeccounter" class="activity-counter"></div>').html('<span id="floatingElecCounter">0</span>/'+elecMin + '<div class="floating-box">total chosen<div>').appendTo("#"+wrapperDiv);
            $("#elecNext").click(function() {
                var e = validateMinMax(isMajors);
                if (e == ''){
                    $("#" + wrapperDiv).fadeOut("slow");
                    loadElectivePriorities(isBoy, "electivePriority");
                    $("#electivePriority").fadeIn("slow");
                } else {
                    alert(e);
                }  
            });
            $("#elecPrev").click(function() {
                $("#" + wrapperDiv).fadeOut("slow")
                $("#electiveWrapper").fadeIn("slow");
            });
        }

    },
    error: function(xhr, thrownError) {
        alert(xhr.responseXML);
        alert(thrownError);
    }
});


}

function getTotal(isMajors){
    var total = 0;
    var sectionAct;
    if (isMajors){
        
        sectionAct = majorSectionAct;
    } else {
        
        sectionAct = elecSectionAct;
    }
    for ( i in sectionAct ){
        
        total = total + sectionAct[i];
    }
    return total;
}

function validateMinMax(isMajors){
    var total = 0;
    var errMsg = '';
    
    var totalMin;
    var totalMax;
    var sectionMins;
    var sectionAct;
    if (isMajors){
        totalMin = majorMin;
        totalMax = majorMax;
        sectionMins = majorSectionMins;
        sectionAct = majorSectionAct;
    } else {
        totalMin = elecMin;
        totalMax = elecMax;
        sectionMins = elecSectionMins;
        sectionAct = elecSectionAct;
    }
    
    for ( i in sectionAct ){
        if (sectionAct[i] < sectionMins[i]){
            errMsg = errMsg + 'Please select at least ' + sectionMins[i] + ' activities in the ' + i + ' section.\n';
        }
        total = total + sectionAct[i];
    }
    if (total < totalMin){
        errMsg = errMsg + 'Please select at least ' + totalMin + ' activities total.';
    }
    if (total > totalMax){
        errMsg = errMsg + 'Please select a maximum of ' + totalMax + ' activities total';
    } 
    return errMsg;  
}

function parseXml(xml) {
    if ($.browser.msie) {
        //alert(xml);
        //alert("IE");
        var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
        xmlDoc.loadXML(xml);
        xml = xmlDoc;
    }
    return xml;
}


function loadMajorPriorities(isBoy, wrapperDiv) {
    
    //$("<div></div>").html('').appendTo("#" + wrapperDiv);
    var list = '<h3>Major Activities</h3><div><p>Please drag and drop the activities into priority order, highest at the top.</p></div><ul id="orderList">';
    $("#majorWrapper").find(":checkbox").each(function() {
        if (this.checked) {
            //alert($(this).attr("id"));
            list = list + '<li class="ui-state-default major-priority" id="' + $(this).val() + '"><div class="removeItem"><img src="img/dragdropicon.gif" class="dragicon" />' + majorArray[$(this).val()] + '</div></li>';  
        }
    });
    list = list + '</ul><div style="clear: both;"></div>';
    $("#" + wrapperDiv).html(list);
    $("<div></div>").html('<input type="button" id="majPriPrev" value="" class="prev-button" /><input type="button" id="majPriNext" value="" class="next-button" />').appendTo("#" + wrapperDiv);
    $("#majPriPrev").click(function() {
        $("#" + wrapperDiv).fadeOut("slow");
        $("#majorWrapper").fadeIn("slow");
    });
    $("#majPriNext").click(function() {
        ReorderOnDrop();
        $("#" + wrapperDiv).fadeOut("slow");
        if (editMajors) {
            loadConfirmation();
            $("#confirm").fadeIn("slow");
        } else {
            if ($("#electiveWrapper").html() == "") {
                $("#electiveWrapper").html('<h3>Elective Activities</h3><p>Below is the list of available "Elective" activities. Elective activities are designed primarily for fun and normally meet only once or twice.</p><p>Please choose ' + elecMax + ' activities below. You may select each activity up to two times. Any activity chosen twice will count as two of your ' + elecMax + ' selections.</p><p>You will be given the opportunity to prioritize these activities next.</p>');
                loadActivities(isBoy, false, "electiveWrapper");
            }
            $("#electiveWrapper").fadeIn("slow");
        }
    });
    setReorder();
}

function loadElectivePriorities(isBoy, wrapperDiv) {

    var list = '<h3>Elective Activities</h3><div><p>Please drag and drop the activities into priority order, highest at the top.</p></div><ul id="orderListElective">';
    $("#electiveWrapper").find(":checkbox").each(function() {
        if (this.checked) {

            var divname = $(this).val() + "_num";
            //alert(divname);
            var mult = $("#c" + divname).val();
            for (var j = 0; j < mult; j++) {
                list = list + '<li class="ui-state-default elective-priority" id="' + $(this).val() + '"><div class="removeItem"><img src="img/dragdropicon.gif" class="dragicon" />' + elecArray[$(this).val()] + '</div></li>';
            }
        }
    });
    list = list + '</ul><div style="clear: both;"></div>';
    $("#" + wrapperDiv).html(list);
    $("<div></div>").html('<input type="button" id="elecPriPrev" value="" class="prev-button" /><input type="button" id="elecPriNext" value="" class="next-button" />').appendTo("#" + wrapperDiv);
    $("#elecPriPrev").click(function() {
        
        $("#" + wrapperDiv).fadeOut("slow");
        $("#electiveWrapper").fadeIn("slow");
    });
    $("#elecPriNext").click(function() {
        ReorderElectiveOnDrop();
        $("#" + wrapperDiv).fadeOut("slow");
        loadConfirmation();
        $("#confirm").fadeIn("slow");
    });
    setElectiveReorder();
}

function loadConfirmation() {
    editMajors = false;
    editElectives = false;
    var electiveList = '<div><b>Elective Activities</b><br /><a href="#" id="editelectives">Edit</a></div>';
    var majorList = '<div><b>Major Activities</b><br /><a href="#" id="editmajors">Edit</a></div>';
    for (var i = 0; i < majorPriorityArray.length; i++) {
        var j = i + 1;
        majorList = majorList + '<div>' + j + '. ' + majorArray[majorPriorityArray[i]] + '</div>';
    }
    for (var i = 0; i < elecPriorityArray.length; i++){
        var j = i + 1;
        electiveList = electiveList + '<div>' + j + '. ' + elecArray[elecPriorityArray[i]] + '</div>';
    }
    
    var editname = '<div id="cnname" name="ccnname"><input type="text" name="cnfname" id="ccnfname" size="10" /><input type="text" name="cnlname" id="ccnlname" size="10" /></div>';
    var editgender = '<div id="cnfgender" name="ccnfgender"><input type="radio" id="cnfgenderboy" name="ccnfgender" value="boy" />Boy <input type="radio" id="cnfgendergirl" name="ccnfgender" value="girl" />Girl</div>';
    var editcode = '<div id="cncode" name="ccncode"><input type="text" name="cnfcode" id="ccnfcode" /></div>';
    var editage = '<div><select id="cnage" name="ccnage"></select></div>';
    var editbday = '<div><select id="cnbirthmonth" name="ccnbrithmonth"></select> <select id="cnbirthday" name="ccnbirthday"></select>, <select id="cnbirthyear" name="ccnbirthyear"></select></div>';
    var editdiv = '<div id="cnfedit" style="margin-top:5px;margin-bottom:10px;width:250px;float:left;display:none">' + editname + editgender + editcode + editage + editbday + '</div>';
    var intro = '<h3>Confirmation</h3><div class="instructions">Please confirm your camper\'s information and activity selections below.</div>';
    var ci = '<div style="margin-top:5px;margin-bottom:10px;width:200px;float:left;"><div>Camper Name:</div><div>Camper Gender:</div><div>Unique Camper ID:</div><div>Camper Age:</div><div>Camper Birthday:</div></div>';
    var ci2 = '<div style="margin-top:5px;margin-bottom:10px;width:200px;float:left;" id="cnfinfo"><div id="conf-name"></div><div id="conf-gender"></div><div id="conf-code"></div><div id="conf-age"></div><div id="conf-bday"></div></div>';
    var editinfo = '<div style="float:right"><a href="#" id="editinfo">Edit</a></div><div style="float:right"><a href="#" id="editdone" style="display:none;">Done</a></div>';
    var cols = '<div style="clear:left;"><hr></div><div style="width:250px;float:left;">' + majorList + '</div><div style="width:250px;float:left;">' + electiveList + '</div>';
    $("#confirm").html('<form id="submission" action="congrats.php" method="POST">' + intro + ci + ci2 + editdiv + editinfo + cols + '</form>');
    $('<div style="clear:left;"></div>').html('<input type="hidden" id="centry" name="entry" value="" /><input type="submit" id="cnfConfirm" value="" class="submit-button" />').appendTo("#submission");
    if (predate){
        $('<div></div>').html('<input type="hidden" id="cpredateval" name="predateval" value="" />').appendTo("#submission");
    }
    $("#cnage").html($("#cage").html());
    $("#cnage").change(function() {
        if ($("#cnage").val() > 0) {

            var d = new Date();
            var curr_year = d.getFullYear();
            var yr = curr_year - $("#cnage").val();
            var yrLow = yr - 1;
            var yrHigh = yr + 1;
            //            $("#cdatepicker").datepicker({ changeYear: true, yearRange: yrLow + ':' + yr, onSelect: function(dateText, inst) {
            //                $("#cdatepicker").text(dateText);
            //            }
            $("#cnbirthyear").text('');
            $("#cnbirthyear").append($("<option></option>").attr("value", "-1").text('Select One'))
            for (var i = yrLow; i <= yrHigh; i++) {
                $('#cnbirthyear').append($("<option></option>").attr("value", i).text(i));
            }

        }
    });
    $("#cnbirthmonth").html($("#cbirthmonth").html());
    $("#cnbirthday").html($("#cbirthday").html());
    $("#cnbirthyear").html($("#cbirthyear").html());
    editInfo();
    $("#editinfo").click(function() {
        $("#ccnfname").val($("#cfirstname").val());
        $("#ccnlname").val($("#clastname").val());
        if ($("#cgenderboy").is(':checked')) {
            $("#cnfgenderboy").attr("checked", "checked");
        } else {
            $("#cnfgendergirl").attr("checked", "checked");
        }
        $("#ccnfcode").val($("#ccampercode").val());
        $("#cnage").val($("#cage").val());
        $("#cnbirthmonth").val($("#cbirthmonth").val());
        $("#cnbirthday").val($("#cbirthday").val());
        $("#cnbirthyear").val($("#cbirthyear").val());
        $("#cnfinfo").toggle();
        $("#cnfedit").toggle();
        $("#editinfo").toggle();
        $("#editdone").toggle();
        return false;
    });
    $("#editdone").click(function() {
        if ($("#cnfgenderboy").is(':checked')) {
            if ($("#conf-gender").html() == 'girl'){
                var answer = confirm ("By changing gender, you will have to re-select all activities. Is that OK? Click CANCEL to change back.");
                if (!answer){
                    return;
                } else {
                    $("#cgenderboy").attr("checked", "checked");
                    checkGender();
                    $("#confirm").fadeOut("slow");
                    $("#majorWrapper").html(majorInstructions);
                    loadActivities(globalIsBoy, true, "majorWrapper");
                    $("#majorWrapper").fadeIn("slow");
                }
            }
            
        } else {
            if ($("#conf-gender").html() == 'boy'){
                var answer = confirm ("By changing gender, you will have to re-select all activities. Is that OK? Click CANCEL to change back.");
                if (!answer){
                    return;
                }else{
                    $("#cgendergirl").attr("checked", "checked");
                    checkGender();
                    $("#confirm").fadeOut("slow");
                    $("#majorWrapper").html(majorInstructions);
                    loadActivities(globalIsBoy, true, "majorWrapper");
                    $("#majorWrapper").fadeIn("slow");
                }
            }
            
        }
        checkGender();
        $("#cfirstname").val($("#ccnfname").val());
        $("#clastname").val($("#ccnlname").val());
        $("#ccampercode").val($("#ccnfcode").val());
        $("#cage").val($("#cnage").val());
        $("#cbirthmonth").val($("#cnbirthmonth").val());
        $("#cbirthday").val($("#cnbirthday").val());
        $("#cbirthyear").html($("#cnbirthyear").html());
        $("#cbirthyear").val($("#cnbirthyear").val());
        editInfo();
        $("#cnfedit").toggle();
        $("#cnfinfo").toggle();
        $("#editdone").toggle();
        $("#editinfo").toggle();
    });
    $("#editmajors").click(function() {
        editMajors = true;
        $("#confirm").fadeOut();
        $("#majorWrapper").fadeIn("slow");
    });
    $("#editelectives").click(function() {
        editElectives = true;
        $("#confirm").fadeOut("slow");
        $("#electiveWrapper").fadeIn("slow");
    });
//    $("#cnfConfirm").click(function() {
        //alert(createHeader());
        //alert(createEntry());
//        var en = createEntry();
//        $("#centry").val(en);
//        return true;
//    });
}

function editInfo() {
    var m = $("#cbirthmonth").val();
    var d = $("#cbirthday").val();
    var y = $("#cbirthyear").val();
    var bday = getDateString(m, d, y);
    var boygirl = 'girl';
    if (globalIsBoy) {
        boygirl = 'boy';
    }
    $("#conf-name").html($("#cfirstname").val() + ' ' + $("#clastname").val());
    $("#conf-gender").html(boygirl);
    $("#conf-code").html($("#ccampercode").val());
    $("#conf-age").html($("#cage").val());
    $("#conf-bday").html(bday);
    var en = createEntry();
    $("#centry").val(en);
    if (predate){
        var pre = $("#cpredateyear").val() + '-' + doubleDigit($("#cpredatemonth").val()) + '-' + doubleDigit($("#cpredateday").val());
        //alert(pre);
        $("#cpredateval").val(pre);
    }
    //var cur = new Date();
    //2007-05-17 19:38:42

}

function getAllActivities(){

}

function createHeader() {
    var ret = "'Camper First Name','Camper Last Name','Camper Gender','Unique Code','Camper Age','Camper Birth Month','Camper Birth Day','Camper Birth Year',";
    for (var i in majorArray) {
        ret = ret + "'" + majorArray[i].replaceAll("'", "") + "',";
    }
    for (var j in elecArray) {
        ret = ret + "'" + elecArray[j].replaceAll("'", "") + "',";
    }
    ret = ret + "'Date','User'";
    return ret;
}


function createEntry() {
    var g = 'Girl';
    if (globalIsBoy){
        g = 'Boy';
    }
    getAllActivities();
    var ret = "'" + $("#cfirstname").val().replaceAll("'", "").replaceAll('"',"") + "','" + $("#clastname").val().replaceAll("'", "").replaceAll('"',"") + "','" + g + "','" + $("#ccampercode").val().toLowerCase() + "','" + $("#cage").val() + "','" + $("#cbirthmonth").val() + "','" + $("#cbirthday").val() + "','" + $("#cbirthyear").val() + "',";
    if(!globalIsBoy){
        for (var y = 0; y < numBoyMaj + numBoyElec; y++){
            ret = ret + ',';
        }
    }
    
    for (var i in majorArray) {
        var one = "";
        for (var j = 0; j < majorPriorityArray.length; j++) {
            if (majorPriorityArray[j] == i) {
                one = one + doubleDigit(j + 1) + " ";
            }
        }
        if (one != ""){
            one = "'" + $.trim(one) + "'";
        }
        ret = ret + one + ",";
    }
    for (var i in elecArray) {
        var one = "";
        for (var j = 0; j < elecPriorityArray.length; j++) {
            if (elecPriorityArray[j] == i) {
                one = one + doubleDigit(j + 1) + " ";
            }
        }
        if (one != "") {
            one = "'" + $.trim(one) + "'";
        }
        ret = ret + one + ",";
    }
    if(globalIsBoy){
        for (var y = 0; y < numGirlMaj + numGirlElec; y++){
            ret = ret + ',';
        }
    }
    //ret = ret + cur.format("Y-m-d H:i:s");
    return ret;
}

function doubleDigit(num) {
    if (num < 10) {
        num = "0" + num;
    }
    return num;
}

// Replaces all instances of the given substring.
String.prototype.replaceAll = function(
    strTarget, // The substring you want to replace
    strSubString // The string you want to replace in.
    ){
    var strText = this;
    var intIndexOfMatch = strText.indexOf( strTarget );
      
    // Keep looping while an instance of the target string
    // still exists in the string.
    while (intIndexOfMatch != -1){
        // Relace out the current instance.
        strText = strText.replace( strTarget, strSubString )
          
        // Get the index of any next matching substring.
        intIndexOfMatch = strText.indexOf( strTarget );
    }
      
    // Return the updated string with ALL the target strings
    // replaced out with the new substring.
    return( strText );
}