﻿var bugs = {};
var ptpointer = 1;
var pta = new Array();
var pageName="";
var pageType = "";
var timeout;
var hto;
var vto;
var ctab = "";

var hpdeck = new Array();
var hppointer = 1;
var tile = 0;

var vidp = 0;
var slide = -1;

$(document).ready(function () {
    //the first image that should appear on the grid
    if (window.location.pathname === "/") {
    var firstImage;
    firstImage = $('#imagepre').children()[0].src;
    //set initial background image as the first image
    $(".igrid").css("background-image", "url("+firstImage+")");
    }
    setExamples();
    $("input[example], textarea[example]").live("focus", function () {
        if ($(this).val() == $(this).attr('example')) {
            $(this).val('');
            $(this).removeClass('example');
        }
    });
    $("input[example], textarea[example]").live("blur", function () {
        if ($(this).val() == "") {
            $(this).val($(this).attr("example"));
            $(this).addClass('example');
        }
    });
   


    alternateRows();

    //preload photos if any...
    $(".photos ul.playlist>li>input.background").preload();

    mediapointers($(".media .tabs li a.current").attr("href"));

    try {
        oHandler = $(".selectboxz").msDropDown().data("dd");
        oHandler.visible(true);
        $("#ver").html($.msDropDown.version);
    } catch (err) { };

    /* GENERIC INPUT CONTROLLERS */

    $(".num").keypress(function (e) { return numbersOnly(e); });
    // handle submit for brochure and travel agent Request
    $("input[example], textarea[example]").live("focus", function () {
        if ($(this).val() == $(this).attr('example')) {
            $(this).val('');
            //$(this).addClass('ss-black');
        }
    });

    // print this page
    $(".print").live("click", function () {
        window.print();
        e.preventDefault();
    });

    /* Focus and Exit Form Fields  */
    $("input").focus(function () {
        var ex = $(this).attr("example");
        if (ex == $(this).val()) {
            $(this).val("");
        }
    });
    $("input").blur(function () {
        if ($(this).val() == "") {
            $(this).val($(this).attr("example"));
        }
    });


    /* SET NAVIGATION CONTEXT */
    pageName = $('meta[name=pageName]').attr("content");
    pageType = $('meta[name=pageType]').attr("content");
    pagetop = $("#pagecontext .topparent").val();
    if (pagetop == "") { pagetop = pageType; }
    switch (pagetop) {

        case "about":
            $("#primarynav a.about").addClass("current");
            break;
        case "programs":
            $("#primarynav a.programs").addClass("current");
            break;
        case "admissions":
            $("#primarynav a.admissions").addClass("current");
            break;
        case "students":
            $("#primarynav a.students").addClass("current");
            break;
        case "alumni":
            $("#primarynav a.alumni").addClass("current");
            break;
        case "support":
            $("#primarynav a.support").addClass("current");
            break;
        case "news":
            $("#primarynav a.news").addClass("current");
            break;
        case "blog":
            $("#primarynav a.blog").addClass("current");
            break;
    }

    // inside sidebar nav
    var k = $("#pagecontext .parent").val();
  try {
    $(".cl" + k + ">a").addClass("current");
    $(".cl" + k + ">ul").show();
    $(".cl" + k).parent("ul").show();
}
catch(e) {}
  var k = $("#pagecontext .topparent").val();
try {
  
    $(".cl" + k + ">a").addClass("current");
}
catch(e) {}
    /* END NAVIGATION CONTEXT */


    /* slide show controls */
    nextSlide();  //initialize the slide show...

    $(".slide .sc.forward").live("click", function (e) {
        e.preventDefault();
        nextSlide();
    });
    $(".slide .sc.back").live("click", function (e) {
        e.preventDefault();
        previousSlide();
    });

    $(".minislide .sc.forward").live("click", function (e) {
        e.preventDefault();
        var idx = $(this).parent().parent().index()
        var c = $("ul.minislide li").length - 1;
        idx += 1;
        if (idx > c) { idx = 0; }
        $(this).parent().parent().removeClass("current");
        $("ul.minislide li").eq(idx).addClass("current");
    });
    $(".minislide .sc.back").live("click", function (e) {
        e.preventDefault();
        var idx = $(this).parent().parent().index()
        var c = $("ul.minislide li").length -1;
        idx -= 1;
        if (idx < 0) { idx = c; }
        $(this).parent().parent().removeClass("current");
        $("ul.minislide li").eq(idx).addClass("current");
    });

    /* typical week slides */
    $(".day .sc.forward").live("click", function (e) {
        e.preventDefault();
        var i = $("table.typicalweek td.current").attr("id").substring(3);
        i = parseInt(i) + 1;
        if (i > $("table.typicalweek td").length) { i = 1; }
        $("td.day").removeClass("current");
        $("#day" + i).addClass("current");
        $("div.day").hide();
        $("div.cday").hide();
        $("div.day" + i).show();
        $("div.cday" + i).show();

    });
    $(".day .sc.back").live("click", function (e) {
        e.preventDefault();
        var i = $("table.typicalweek td.current").attr("id").substring(3);
        i = parseInt(i) - 1;
        if (i < 1) { i = $("table.typicalweek td").length; }
        $("td.day").removeClass("current");
        $("#day" + i).addClass("current");
        $("div.day").hide();
        $("div.cday").hide();
        $("div.day" + i).show();
        $("div.cday" + i).show();
    });

    $("ul.pointer li").live("click", function () {
        if ($("ul.tabs li a.current").hasClass("videos") == true) {
            var i = $(this).index();
            i -= 1;
            video.pointer = i;
            video.nextVideo();
        } else {
            nextSlide($(this).index())
        }
    });

    $(".media .tabs li a").live("click", function (e) {
        e.preventDefault();
        var t = $(this).attr("class");
        t = t.replace(" current", "");
        $(".slidewrapper.map").css("margin-left", "0");
        $(".slidewrapper.map").css("position", "inherit");
        if (t == "videos") {
            window.setTimeout(video.play, 500);
        } else {
            vidp = video.currentposition;
            video.pause();
        }

        mediapointers(t);

        $(".media .tabs li a").removeClass("current");
        $(this).addClass("current");

        $(".slidewrapper").hide();
        $(".slidewrapper." + t).show();

        $("ul.pointer li").removeClass("current");
        switch (t) {
            case "videos":
                $("ul.pointer li").eq(video.pointer).addClass("current");
                break;
            case "photos":
                $("ul.pointer li").eq(slide).addClass("current");
                break;

        }
    });

    /*  END SLIDE & MEDIA CONTROLS  */

    $(".programtabs a").live("click", function (e) {
        e.preventDefault();
        $(".programtabs li").removeClass("current");
        var tab = $(this).attr("href");
        $(".tcontainer").hide();
        $("#" + tab).show();
        $(this).parent().addClass("current");
        if (tab == "ct2") {
            $(".fiveyearresources").show();
        } else {
            $(".fiveyearresources").hide();
        }
    });

    /* HOME PAGE IMAGE BOX */

    $("#imagepre img").each(function (i) {
        hpdeck[i] = $(this).attr("src");
    });

    timeout = window.setTimeout(swaptile, 8000);



	$(".relatedVideosList li").live("click", function (e) {
		e.preventDefault();
		$("#modal").show();
		$("#popover div.popcopy").html('<div id="tuberPopUp"></div>');
		$("#tuberPopUp").tubeplayer({
			width: 496, // the width of the player
			height: 311, // the height of the player
			allowFullScreen: "true", // true by default, allow user to go full screen
			autoplay: 1,
			iframed: true,
			showControls: 1,
			initialVideo:  $(this).attr("video"), // the video that is loaded into the player
			preferredQuality: "hd720", // preferred quality: default, small, medium, large, hd720
			onPlay: function (id) { window.setTimeout(video.getDuration, 1000); }, // after the play method is called
			onPlayerEnded: function () {
				$("#popover").hide();
        			$("#modal").hide(); 
				$("#tuberPopUp").tubeplayer("destroy");
				$("#popover div.popcopy").html('');
			},
			onPlayerCued: function () { }, // when a video is cued
			onPause: function () { }, // after the pause method is called
			onStop: function () { }, // after the player is stopped
			onSeek: function (time) { }, // after the video has been seeked to a defined point
			onMute: function () { }, // after the player is muted
			onUnMute: function () { } // after the player is unmuted
		});


		$("#popover").centerInClient();
		$("#popover").show();
		$("#tuberPopUp").tubeplayer("play");

	});
    $("a.popover, img.enlarge-btn").live("click", function (e) {
        e.preventDefault();
        $("#modal").show();
        $("#popover div.popcopy").html('<img src="' + $("a.popover>img.hero").attr("src") + '"/>');
        $("#popover").centerInClient();
        $("#popover").show();

    });

    $(".closeme").live("click", function (e) {
        $("#popover").hide();
        $("#modal").hide();
    });

    /* VIDEO SPECIFIC CONTROLS  */

    $("#videomask, div.playercontrols").live("mouseover", function () {
        window.clearTimeout(vto);
        $("div.playercontrols").fadeIn(250);
    });

    $("#videomask, div.playercontrols").live("mouseout", function () {

        vto = window.setTimeout(video.hideControls, 500);

    });
    $("ul.playercontrols li").live("click", function () {
        var action = $(this).attr("class");
        switch (action) {
            case "vplay":
                $("#tuber").tubeplayer("play");
                break;
            case "vpause":
                $("#tuber").tubeplayer("pause");
                break;
            case "vnext":
                video.nextVideo();
                break;
            case "vprevious":
                video.previousVideo();
                break;
            case "vforward":
                $("#tuber").tubeplayer("seek", 100);
                break;
        }

    });

    $("ul.playercontrols .progressbar").live("click", function (e) {
        var x = e.pageX - this.offsetLeft;
        var xx = parseInt($(this).css("width").replace("px", ""));
        x = x / xx; //percent of the progress bar clicked
        $("#tuber").tubeplayer("seek", video.duration * x);
        video.getDuration();
    });

    $("#tuber").tubeplayer({
        width: 496, // the width of the player
        height: 311, // the height of the player
        allowFullScreen: "true", // true by default, allow user to go full screen
        autoplay: 1,
        iframed: true,
        showControls: 1,
        initialVideo: video.initialVideo(), // the video that is loaded into the player
        preferredQuality: "hd720", // preferred quality: default, small, medium, large, hd720
        onPlay: function (id) { window.setTimeout(video.getDuration, 1000); }, // after the play method is called
        onPlayerEnded: function () { window.setTimeout(video.nextVideo, 250); },
        onPlayerCued: function () { }, // when a video is cued
        onPause: function () { }, // after the pause method is called
        onStop: function () { }, // after the player is stopped
        onSeek: function (time) { }, // after the video has been seeked to a defined point
        onMute: function () { }, // after the player is muted
        onUnMute: function () { } // after the player is unmuted
    });

    /* END VIDEO SPECIFIC CONTROLS */

    /* GENERAL SITE */

    $("td.day a").click(function (e) {
        e.preventDefault();
        var day = $(this).parent().attr("id");
        $("td.day").removeClass("current");
        $(this).parent().addClass("current");
        $("div.day").hide();
        $("div.cday").hide();
        $("div." + day).show();
        $("div.c" + day).show();
    });

    /* FAQ */
    $("h2.faq a").live("click", function (e) {
        e.preventDefault();
        if ($(this).hasClass("open")) {
            $(this).parent().parent().children("div.detail").slideUp(150);
            $(this).removeClass("open");
        } else {
            $("div.detail").slideUp(250);
            $("ul.faq a").removeClass("open");
            $(this).parent().parent().children("div.detail").slideDown(150);
            $(this).addClass("open");
        }
    }); ;


    /* SIDEBAR ACTIONS */

    $(".sidebar ul.courses li").click(function (e) {
        e.preventDefault();
        if ($(this).hasClass("current")) {
            $(this).children("p").hide();
            $(this).removeClass("current");
        } else {
            $(this).children("p").show();
            $(this).addClass("current");
        }

    });

    //AJAX Form Handler
    $("form.formwrapper").submit(function (e) {
        e.preventDefault();
        var f = $(this)
        removeExamples(f);
        var serializedForm = $(f).serialize();
        var action = $(f).attr("action");
        if (serializedForm.length > 0 && action.length > 0) { serializedForm += "&sendto=" + action; }
        $.post("formsprocessor.aspx", serializedForm, function (data) {
            var ra = data.split("||");
            if (ra[0] == "OK") {
                switch (ra[2].toUpperCase()) {
                    case "SUCCESSREDIRECT":
                        if (ra[1].toLowerCase() == "refresh") {
                            window.location.href = window.location.href;
                        } else {
                            window.location.href = ra[1];
                        }
                        break;

                    case "SUCCESSFORM":
                        //set $(f).id to the new forms entity
                        $(f).html(ra[1]);
                        break;

                    default:
                        $(f).html(ra[1]);
                        break;
                }
            } else if (ra[0] == "HASERRORS") {
                $(f).html(ra[1]);
                $("#email-error").fadeIn(120);
                $("#emailID").focus();
               // timeout = window.setTimeout(closeEmailError, 4000);
            } else {
                //uhoh :( internal errors or something??
            }
            // init();
            setExamples(f);
        });
    });

    $("select.autoredir").change(function () { window.location.href = $(this).val(); })


    /* ================ BUG Tracker ====================== */
    $("#reportBug").live("click", function () {
        serializedForm = "location=" + urlencode(window.location.href);
        var action = "BugReporter.aspx?action=show";
        $.post(action, serializedForm, bugs.showBugForm);
    });

    $("form#bugReporter .submit").live("click", function () {
        var serializedForm = $("#bugReporter").serialize();
        var action = "BugReporter.aspx?action=submit";
        $.post(action, serializedForm, bugs.showBugForm);
        $("form#bugReporter, #bugMask").remove();
    });

    $("form#bugReporter #levelID option").live("click", function () {
        $("form#bugReporter #levelID").attr("style", $(this).attr("style"));
    });

    $("form#bugReporter .bugClose").live("click", function () {
        $("form#bugReporter, #bugMask").remove();
    });

});

/* END PAGE READY */


/* =========== Functions ============ */






function setExamples(parent) {
    if (parent === undefined) {
        $("input[example], textarea[example]").each(function () {
            if ($(this).val() == '' || $(this).val() == $(this).attr('example')) {
                $(this).addClass('example');
                $(this).val($(this).attr('example'))
            }
        })
    } else {
        $("input[example], textarea[example]", parent).each(function () {
            if ($(this).val() == '' || $(this).val() == $(this).attr('example')) {
                $(this).addClass('example');
                $(this).val($(this).attr('example'))
            }
        })
    }

}

function removeExamples(parent) {
    if (parent === undefined) {
        $("input[example], textarea[example]").each(function () {
            if ($(this).val() == $(this).attr('example')) {
                $(this).removeClass('example');
                $(this).val('');
            }
        })
    } else {
        $("input[example], textarea[example]", parent).each(function () {
            if ($(this).val() == $(this).attr('example')) {
                $(this).removeClass('example');
                $(this).val('');
            }
        })
    }
}







function alternateRows() {
    $("div.media .intro tr").removeClass("alternate");
    $("div.media .intro tr").each(function (i) {
        if (isEven(i)) {
            $(this).addClass("alternate");
        } else {
            //$(this).addClass("alternate");
        }
    });

}

function mediapointers(t) {
    var i = $(".slidewrapper." + t + " .playlist li").length;
    if (i > 10) { i = 10; }
    var lh = ""
    for (v = 1; v <= i; v = v + 1) {
        lh += "<li></li>"
    }
    $("ul.pointer").html(lh);
}
//inside page slide and video feature//
function nextSlide(sid) {
    if (sid == undefined) {
        sid = slide; 
        sid += 1;
        }

        var i = $(".photos .playlist li").length - 1;
    if(i>9){i=9;}
    if (sid > i) { sid = 0; }

    try{
        var o = $("div.slide").offset();
        $("div.slideoverlay").css("left", o.left + "px");
        $("div.slideoverlay").css("top", o.top + "px");
    } catch(err) {

    }
    $("div.slideoverlay").css("background-image", $("div.slide").css("background-image"));
    $("div.slideoverlay").show();

    $("div.slide").css("background-image", "url(" + $(".photos .playlist li").eq(sid).children("input.background").val() + ")");
    $("div.caption").html($(".photos .playlist li").eq(sid).children("input.caption").val());

    $("div.slideoverlay").fadeOut(400, function () {
        $("div.slideoverlay").hide();
    });

    $("ul.pointer li").removeClass("current");
    $("ul.pointer li").eq(sid).addClass("current");

    slide = sid;
}

function previousSlide() {
    slide -= 1;
    if (slide < 0) { slide = $(".photos .playlist li").length - 1; }
    nextSlide(slide);
}


// video object //
$.tubeplayer.defaults.afterReady = function () {
    //var videocode = $(".playlist li").eq(0).html();
    //$("#tuber").tubeplayer("play", videocode);
    //video.play(0);
};

var video = {
    pointer: 0,
    duration: 0,
    runningtime: "",
    currentposition: 0,
    Me: this,
    initialVideo: function () {
        var videocode = $(".videos .playlist li").eq(0).html();
        return videocode;
    },

    play: function () {

        var videocode = $(".playlist li").eq(video.pointer).html();
        var lz = $(".videos .playlist li").length;
        $("#tuber").tubeplayer("play", videocode);
        $("ul.pointer li").removeClass("current");
        $("ul.pointer li").eq(video.pointer).addClass("current");
    },

    nextVideo: function () {

        video.pointer += 1;
        if (video.pointer > lz - 1) { video.pointer = 0; }
        var videocode = $(".playlist li").eq(video.pointer).html();
        var lz = $(".videos .playlist li").length;
        $("#tuber").tubeplayer("play", videocode);
        $("ul.pointer li").removeClass("current");
        $("ul.pointer li").eq(video.pointer).addClass("current");

    },

    previousVideo: function () {
        var lz = $(".videos .playlist li").length;
        video.pointer -= 2;
        if (video.pointer < 0) { video.pointer = lz + video.pointer; }
        var videocode = $(".videos .playlist li").eq(video.pointer).html();
        $("#tuber").tubeplayer("play", videocode);
        video.pointer += 1;
        if (video.pointer > lz - 1) { video.pointer = 0; }
    },
    pause: function () {
        $("#tuber").tubeplayer("pause");
    },
    hideControls: function () {
        //$("div.playercontrols").fadeOut(800);
    },
    getDuration: function () {
        var vid = $("#tuber").tubeplayer("player");
        var d = $("#tuber").tubeplayer("data");
        video.currentposition = d.currentTime;
        video.duration = vid.getDuration();
        var m = video.duration % 60;
        //m=parseInt(60 * (m/100));
        m = parseInt(m + 0.5)
        video.runningtime = parseInt(video.duration / 60) + ":" + Right("00" + m, 2);
        m = parseInt((video.currentposition * 100) / video.duration)
        $("li.duration").html(video.runningtime);
        //$("ul.playercontrols>li.progressbar>span").css("width", m + "%");
        window.setTimeout(video.getDuration, 250);
    }


};

// home page image feature //
function swaptile() {

    try {
        clearTimeout(timeout);
        var lc = 0;
        var swap = true;
        var x;
        var y;
        var tc = selectTile();
    
        var i = $("." + tc).css("background-image").indexOf(hpdeck[hppointer]);
        while (i > -1) {
            x = Math.floor(Math.random() * 6) + 1
            y = Math.floor(Math.random() * 4) + 1
            tc = tileclass(x, y);
            i = $("." + tc).css("background-image").indexOf(hpdeck[hppointer]);
            lc += 1;
            if (lc > 36) {
                //check that every tile has changed or force the change
                $(".igrid").css("background-image", "url(" + hpdeck[hppointer] + ")");
                hppointer += 1;
                if (hppointer > hpdeck.length - 1) { hppointer = 0; }
                i = -1
                swap = false;
                tile = 0;
                timeout = window.setTimeout(swaptile, 5000);
            }
        }
        if (swap == true) {
            var off = $("." + tc).position();
            var effect = "fade";
            $(".fadegrid").css("top",(off.top) + "px");
            $(".fadegrid").css("left", off.left + "px");
            $(".fadegrid").css("background-position", $("." + tc).css("background-position"));
            $(".fadegrid").css("background-image", "url(" + hpdeck[hppointer] + ")");

        /* The only effect that works when fadegrid is position=relative
            is "fade".  When position is absolute, all effects work, but
            if the browser is not wide enough to display the entire area,
            a scroll bar is briefly displayed as images are switched out.
        */
        switch(effect){
            case "slide":
                $(".fadegrid").slideDown(550, function () {
                    $("." + tc).css("background-image", "url(" + hpdeck[hppointer] + ")");
                    timeout = window.setTimeout(swaptile, 150);
                    $(".fadegrid").fadeOut(1);
                });
                break;

            case "fade":
                $(".fadegrid").fadeIn(250, function () {
                    $("." + tc).css("background-image", "url(" + hpdeck[hppointer] + ")");
                    timeout = window.setTimeout(swaptile,50);
                    $(".fadegrid").fadeOut(1);

                });
                break;
            case "show":
                $(".fadegrid").show(200, function () {
                    $("." + tc).css("background-image", "url(" + hpdeck[hppointer] + ")");
                    timeout = window.setTimeout(swaptile, 150);
                    $(".fadegrid").hide(1);

                    });
                    break;
            }
        }
    } catch (err) {
        var i = 1;
    }
}

function selectTile(pattern) {

    var x = 0;
    var y = 0;
    var tc = "";
    if (pattern == undefined) {pattern = "random"; }

    switch (pattern) {

        case "leftright":
            tc = "aa:ba:ca:da:ab:bb:cb:db:ac:bc:cc:dc:ad:bd:cd:dd:ae:be:ce:de:af:bf:cf:df"
            break;
        case "centerout":
            tc = "bc:cd:cc:bd:cb:ce:ba:bf:ad:dd:cf:ca:ad:dc:ab:de:ae:db:aa:df:af:da:bb:be"
            break;
        default:
            x = Math.floor(Math.random() * 6) + 1;
            y = Math.floor(Math.random() * 4) + 1;
            tc = tileclass(x, y);
            return tc;
    }


    var ra = tc.split(":");
    tc = ra[tile];
    tile += 1;
    if (tile > ra.length - 1) { tile = 0; }
    return tc;


}
function tileclass(x, y) {
    return String.fromCharCode(96 + y) + String.fromCharCode(96 + x);
}

// jquery plugin to preload images from a jquery object array
// usage: $("#selector").preload();
// where #selector returns a jquery object array whose members contain
// elements with a vlaue of the image URL   -zaphod, 2011
$.fn.preload = function () {
    this.each(function () {
        $('<img/>')[0].src = $(this).val();
    });
}

/* END HOME PAGE IMAGE FEATURE */

    function rootURL() {
        var baseURL = "";
        var i = location.href.indexOf('#');
        if (i > 0) {
            baseURL = location.href.slice(0, location.href.indexOf('#'));
        } else {
            baseURL = location.href;
        }
        return baseURL;
    }

function Right(str, n){
    if (n <= 0)
       return "";
    else if (n > String(str).length)
       return str;
    else {
       var iLen = String(str).length;
       return String(str).substring(iLen, iLen - n);
    }
}

// === Bug Reporting ===
bugs.showBugForm = function (r) {
    $("form#bugReporter, #bugMask").remove();
    $("body").append(r);

    $("form#bugReporter #levelID option").css({ "color": "white","width":"100%"});
    $("form#bugReporter #levelID option:eq(0)").css({"color": "black", "background-color": "white"});
    $("form#bugReporter #levelID option:eq(1)").css("background-color", "red");
    $("form#bugReporter #levelID option:eq(2)").css("background-color", "orange");
    $("form#bugReporter #levelID option:eq(3)").css("background-color", "gold");
    $("form#bugReporter #levelID option:eq(4)").css("background-color", "blue");
    $("form#bugReporter #levelID option:eq(5)").css("background-color", "green");
    $("form#bugReporter #levelID").attr("style", $("form#bugReporter #levelID option:selected").attr("style"));
}

