﻿var schedule = function() {
    var hours = 16; // hours between 12pm and 4am
    var NOT_SEL = "notSelected",
		SEL_USER = "selectedByUser",
		SEL_FRIEND = "selectedByFriend",
		SEL_USER_FRIEND = "selectedByUserAndFriend";

    /* extracted from SWFObject 2.0 - make this public Bobby! */
    var UNDEF = "undefined",
		OBJECT = "object",

		win = window,
		doc = document,
		nav = navigator;

    /* Centralized function for browser feature detection
    - Proprietary feature detection (conditional compiling) is used to detect Internet Explorer's features
    - User agent string detection is only used when no alternative is possible
    - Is executed directly for optimal performance
    */
    var ua = function() {
        var w3cdom = typeof doc.getElementById != UNDEF && typeof doc.getElementsByTagName != UNDEF && typeof doc.createElement != UNDEF && typeof doc.appendChild != UNDEF && typeof doc.replaceChild != UNDEF && typeof doc.removeChild != UNDEF && typeof doc.cloneNode != UNDEF,
			playerVersion = [0, 0, 0],
			d = null;
        var u = nav.userAgent.toLowerCase(),
			p = nav.platform.toLowerCase(),
			webkit = /webkit/.test(u) ? parseFloat(u.replace(/^.*webkit\/(\d+(\.\d+)?).*$/, "$1")) : false, // returns either the webkit version or false if not webkit
			ie = false,
			windows = p ? /win/.test(p) : /win/.test(u),
			mac = p ? /mac/.test(p) : /mac/.test(u);
        /*@cc_on
        ie = true;
        @if (@_win32)
        windows = true;
        @elif (@_mac)
				mac = true;
			@end
        @*/
        return { w3cdom: w3cdom, webkit: webkit, ie: ie, win: windows, mac: mac };
    } ();

    var addLegend = function() {
        var user = swfobject.getQueryParamValue("user");
        if (!jQuery('#lnkScheduleCompare') && user.length < 1) { return; }
        var legend = "<h4>Legend:</h4>";
        legend += "<ul>";
        if (jQuery('#lnkScheduleCompare')) {
            legend += "<li class='" + NOT_SEL + "'>I'm not going.</li>";
            legend += "<li class='" + SEL_USER + "'>I'm going!</li>";
        }
        if (user.length > 0) {
            legend += "<li class='" + SEL_FRIEND + "'>" + user + " is going.</li>";
            if (jQuery('#lnkScheduleCompare')) { legend += "<li class='" + SEL_USER_FRIEND + "'>We're both going!</li>"; }
        }
        legend += "</ul>";
        var scheduleLegend = jQuery("#scheduleLegend");
        if (scheduleLegend) { scheduleLegend.innerHTML = legend; }
    };
    var addStageColumnClasses = function() {
        var locations = jQuery("#schedule p");

        if (typeof (locations) != UNDEF && typeof (stages) != UNDEF) {
            for (var i = 0; i < locations.length; i++) {
                for (var j = 0; j < stages.length; j++) {
                    if (locations[i].innerHTML.replace('&amp;', '&') == stages[j]) {
                        locations[i].parentNode.className = locations[i].parentNode.className + " col" + (j + 1);
                    }
                }
            }
        }
    };
    var addStylesheet = function(href, rel, title) {
        var stylesheet = doc.createElement("link");
        stylesheet.setAttribute("type", "text/css");
        stylesheet.setAttribute("rel", rel);
        stylesheet.setAttribute("href", href);
        if (title) { stylesheet.setAttribute("title", title); }
        var head = getHeadElement();

        head.appendChild(stylesheet);
    };
    var addStyles = function() {
        addStylesheet(schedule.stylePath + "/ScheduleJS.css", "stylesheet");
        if (ua.ie) { addStylesheet(schedule.stylePath + "/ScheduleJSIE.css", "stylesheet"); }
        //addStylesheet(schedule.stylePath + "/ScheduleOnly.css","alternate stylesheet","Schedule Only");
    };
    var addStyle = function(media, rules) {
        var s = doc.createElement("style");
        s.setAttribute("type", "text/css");
        s.setAttribute("media", media);
        s.innerHTML = rules;
        var head = getHeadElement();

        head.appendChild(s);
    };
    var createScheduleTable = function() {
        var divCalendar = doc.createElement("div");
        var tableMarkup = "<table id='tblCalendar' summary='calendar layout'>";
        tableMarkup += getScheduleTableRow("", true);
        tableMarkup += "<tbody>";
        for (var i = 0; i < hours + 1; i++) {
            tableMarkup += getScheduleTableRow(i * 100, false);
            if (i < hours) { tableMarkup += getScheduleTableRow(i * 100 + 30, false); }
        }
        tableMarkup += "</tbody></table>";
        divCalendar.innerHTML = tableMarkup;
        var schedule = jQuery('#schedule');

        if (schedule[0]) { schedule[0].appendChild(divCalendar); }
    };
    var getScheduleTableRow = function(hour, isHead) {
        var hour12 = (hour.toString().match(/30$/) ? hour - 30 : hour) / 100;
        hour12 = ((hour12 == 0) ? hour12 + 12 : ((hour12 > 12) ? hour12 - 12 : hour12)) + (hour.toString().match(/30$/) ? ":30" : ""); // get hour based on 12-hour clock
        hour12 += (hour > 1130) ? "am" : "pm";
        var rowHour = (hour < 1200 ? hour + 1200 : (hour == 1200 ? "0000" : hour - 1200)).toString();
        switch (rowHour.length) {
            case 2:
                rowHour = "00" + rowHour;
                break;
            case 3:
                rowHour = "0" + rowHour;
                break;
        }
        var rowHTML = (isHead ? "<thead>" : "") + "<tr" + (isHead ? "" : " id='tr" + rowHour + "'") + "><th scope='row' class='" + (isHead ? "origin" : "time") + "'>" + (isHead ? "" : hour12) + "</th>";
        if (typeof (stages) != UNDEF) {
            for (var i = 0; i < stages.length; i++) {
                if (isHead) {
                    rowHTML += "<th id='colHead" + (i + 1) + "' class='stage' style='width:" + 100 / (stages.length + 1) + "%;'>" + stages[i] + "</th>";
                } else {
                    rowHTML += (hour > 0) ? "" : "<td id='col" + (i + 1) + "' rowspan='" + ((hours * 2) + 1) + "' class='stageList " + ((i % 2 == 0) ? "even" : "odd") + "'></td>";
                }
            }
        }
        rowHTML += "</tr>" + ((isHead) ? "</thead>" : "");
        return rowHTML;
    };
    var getCheckBox = function(parent) {
        var inputs = jQuery('#' + parent + ' input[type="checkbox"]')

        if (inputs.length >= 1) { return inputs[0] }
        //        if (typeof (inputs) != UNDEF) {
        //            for (var i = 0; i < inputs.length; i++) {
        //                if (inputs[i].getAttribute("type") == "checkbox") { return inputs[i]; }
        //            }
        //        }
    };
    var showTooltip = function(e) {
        TagToTip(this.id, STICKY, true, CLICKCLOSE, true, FADEIN, 200, FADEOUT, 200, BALLOON, true, BALLOONIMGPATH, schedule.tooltipImagePath, OFFSETX, -17);
        var chk = getCheckBox(this.id);
        if (chk) {
            // add schedule toggler to tooltip
            var lnkScheduleAdd = doc.createElement("a");
            lnkScheduleAdd.setAttribute("href", "#");
            lnkScheduleAdd.setAttribute("rel", this.id);
            lnkScheduleAdd.innerHTML = (chk.checked ? "Remove from" : "Add to") + " my schedule!";
            lnkScheduleAdd.onclick = function(e) {
                var chk = getCheckBox(this.rel);
                if (chk) {
                    chk.checked = !chk.checked;
                    chkSelect_Click(chk);
                }
                return false;
            };
            jQuery('#bALlO0nBdY')[0].appendChild(lnkScheduleAdd);
        }
    };
    var chkSelect_Click = function(sender) {
        var c = sender.parentNode.className;
        var selByFriend = c.indexOf(" " + SEL_FRIEND) != -1;
        c = c + ((sender.checked) ? (selByFriend ? " " + SEL_USER_FRIEND : " " + SEL_USER) : ((c.indexOf(" " + SEL_USER) != -1) ? c.substring(0, c.indexOf(" " + SEL_USER)) : c));
        sender.parentNode.className = c;
    };
    var addCheckboxEvents = function() {
        var inputs = jQuery('#schedule input[type="checkbox"]'); //schedule[0].getElementsByTagName("input");

        inputs.each(function(i) {
            this.onclick = function() { chkSelect_Click(this); };
            chkSelect_Click(this);
        });

        //        if (typeof (inputs) != UNDEF) {
        //            for (var i = 0; i < inputs.length; i++) {
        //                if (inputs[i].getAttribute("type") == "checkbox") {
        //                    inputs[i].onclick = function() { chkSelect_Click(this) };
        //                    chkSelect_Click(inputs[i]);
        //                }
        //            }
        //        }
    };
    var addEventsToColumns = function() {
        // add events to stage columns
        var vevents = jQuery('.vevent');
        //alert("vevents: " + vevents);
        for (var i = 0; i < vevents.length; i++) {
            var c = vevents[i].className;
            var col = c.substr(c.indexOf("col") + 3, 1);

            if (!isNaN(col)) {
                jQuery('#col' + col)[0].appendChild(vevents[i]);
            }
        }
    };
    var positionEvents = function() {
        // position events for each stage
        var stageLists = jQuery('.stageList');

        stageLists.each(function(i) {
            vevents = this.getElementsByTagName("div");
            var base = 0;
            for (var j = 0; j < vevents.length; j++) {
                var c = vevents[j].className;

                // get duration
                var padVert = 10;
                var minIdx = c.indexOf("min") + 3;
                var colIdx = c.indexOf(" col");
                var selIdx = c.indexOf(" sel");
                var min = ((selIdx > -1 && selIdx < colIdx) ? c.substr(minIdx, selIdx - minIdx) : c.substr(minIdx, colIdx - minIdx)) - padVert;
                vevents[j].style.height = ((min > 0) ? min + "px" : "auto");

                // get start position
                var start = c.substr(c.indexOf("start") + 5, 4).replace(" ", "");
                var mTop = parseInt(start.toString().substr(0, start.toString().length - 2) * 60) + parseInt(start.toString().substr(start.toString().length - 2, 2)); // convert minutes of start time to pixels
                if (j > 0) { mTop -= base; } // subtract position of previous event
                vevents[j].style.marginTop = (mTop > 0 ? mTop - 720 : mTop + 720) + "px";
               
                base = base + min + mTop - 710; // reset base to current event
                vevents[j].style.display = "";

                // add event listeners
                vevents[j].onmouseover = showTooltip;
                vevents[j].onmouseout = function(e) { UnTip(); };
            }
        });
    };
    var positionScheduleTools = function() {
        jQuery('#userBox')[0].style.top = (jQuery('#scheduleFilters')[0].offsetTop - jQuery('#scheduleToolsUser')[0].offsetTop + (ua.ie ? 2 : 1)) + "px";
        jQuery('#userBox')[0].style.height = jQuery('#scheduleFilters')[0].offsetHeight - 12 + "px";
        jQuery('#userBox')[0].style.display = "";
    };
    var positionInterval;
    var positionEverything = function() {
        if (typeof (XMLHttpRequest) != "undefined" || win.IE7) {
            positionEvents();
            positionScheduleTools();
            clearInterval(positionInterval);
        }
    };
    var toggleEventsDisplay = function() {
        var vevents = jQuery('.vevent');
        for (var i = 0; i < vevents.length; i++) {
            vevents[i].style.display = (vevents[i].style.display == "none" ? "" : "none");
        }
    };

    /*g39 Addition*/
    var getHeadElement = function() {
        return jQuery("head")[0];
    };

    var initialize = function() {
        jQuery('#userBox')[0].style.display = "none";
        toggleEventsDisplay();
        addStyles();
        addLegend();
        createScheduleTable();
        addStageColumnClasses();
        addCheckboxEvents();
        swfobject.addLoadEvent(function() {
            addEventsToColumns();
            positionInterval = setInterval(positionEverything, 50);
        });
    };

    return { // public members
        stylePath: "",
        tooltipImagePath: "",
        initialize: initialize
    }
} ();
