﻿var loadingImage = '<img class="loading" src="/images/main/loading.gif" height="32" width="32" alt="Loading..." />';
function fbs_click() { u = location.href; t = document.title; window.open('http://www.facebook.com/sharer.php?u=' + encodeURIComponent(u) + '&t=' + encodeURIComponent(t), 'sharer', 'toolbar=0,status=0,width=626,height=436'); return false; }

/*-----Master Page Load-----*/
$(document).ready(function () {
    var menuIsActive = false;
    $('ul.mainNav > li').hover(function () {
        var menu = this;
        if (typeof menuHide != 'undefined') clearTimeout(menuHide);
        if (menuIsActive) {
            $('ul.mainNav li').removeClass('active');
            $(menu).addClass('active');
        } else {
            if (typeof menuShow != 'undefined') clearTimeout(menuShow);
            menuShow = setTimeout(function () {
                $(menu).addClass('active');
                menuIsActive = true;
            }, 200);
        }
    }, function () {
        if (typeof menuShow != 'undefined') clearTimeout(menuShow);
        if (typeof menuHide != 'undefined') clearTimeout(menuHide);
        menuHide = setTimeout(function () {
            $('ul.mainNav li').removeClass('active');
            $('a.schoolMenu, div.mySchoolsMenu').removeClass('active').removeAttr('data-ajaxcompleted');
            $('a.collegeMenu, ul.collegeMenu').removeClass('active');
            menuIsActive = false;
        }, 500);
    });

    $('div.profileWrapper a.schoolMenu, div.mySchoolsMenu').hover(function () {
        if (typeof schoolMenuHide != 'undefined') clearTimeout(schoolMenuHide);
        if (typeof schoolMenuShow != 'undefined') clearTimeout(schoolMenuShow);
        schoolMenuShow = setTimeout(function () {
            $('a.schoolMenu, div.mySchoolsMenu').addClass("active");
            // only run AJAX if menu hasn't already been requested on this page
            if (!$("div.mySchoolsMenu").attr('data-ajaxcompleted')) {
                $("div.mySchoolsMenu").html('<img src="/images/main/loading.gif" alt="Loading..." style="margin:10px 47%;" />');
                // stop prior (unfinished) ajax requests
                if (typeof req != 'undefined') req.abort();
                req = $.ajax({
                    url: '/_ajax/account/schoolsDropDownMenu.aspx',
                    cache: false,
                    contentType: "text/html",
                    dataType: "html",
                    success: function (data) {
                        $("div.mySchoolsMenu").html(data).attr('data-ajaxcompleted', 'true');
                    }
                });
            }
        }, 200);
    }, function () {
        if (typeof schoolMenuHide != 'undefined') clearTimeout(schoolMenuHide);
        if (typeof schoolMenuShow != 'undefined') clearTimeout(schoolMenuShow);
        schoolMenuHide = setTimeout(function () { $('a.schoolMenu, div.mySchoolsMenu').removeClass('active').removeAttr('data-ajaxcompleted'); }, 200);
    });

    $('div.profileWrapper a.collegeMenu, ul.collegeMenu').hover(function () {
        if (typeof collegeMenuHide != 'undefined') clearTimeout(collegeMenuHide);
        if (typeof collegeMenuShow != 'undefined') clearTimeout(collegeMenuShow);
        collegeMenuShow = setTimeout(function () { $('a.collegeMenu, ul.collegeMenu').addClass("active"); }, 200);
    }, function () {
        if (typeof collegeMenuHide != 'undefined') clearTimeout(collegeMenuHide);
        if (typeof collegeMenuShow != 'undefined') clearTimeout(collegeMenuShow);
        collegeMenuHide = setTimeout(function () { $('a.collegeMenu, ul.collegeMenu').removeClass('active'); }, 200);
    });

    $('ul.mainNav > li div ul li a').click(function () {
        _gaq.push(['_trackEvent', 'Header Nav', 'Click', $(this).text()]);
    });
    if (isIos()) {
        $('ul.mainNav > li').click(function () {
            if (menuIsActive) {
                $('ul.mainNav li').removeClass('active');
                menuIsActive = false;
            }
        });
    }



    $('.searchBox').focus(function () {
        $(this).addClass('focus');
    }).blur(function () {
        if ($(this).val() == '')
            $(this).removeClass('focus');
    });

    bindTabs();

    $('input.selectTextInBox').click(function () { $(this).focus().select(); _gaq.push(['_trackEvent', 'Copy Share', 'Referral Code', 'Referral Code']); });
});

function isIos() {
    return (navigator.platform.indexOf("iPad") != -1   ||
            navigator.platform.indexOf("iPhone") != -1 ||
            navigator.platform.indexOf("iPod") != -1);
}


function bindTabs() { 
    // tabbed content display
    $('div.tabWrapper ul.tabs li a').click(function() {
        var target = $(this).attr('data-tab');
        $('div.tabWrapper ul.tabs li a').removeClass('selected');
        $(this).addClass('selected');
        $('div.tabWrapper div.tab').hide();
        $('#' + target).show();
        if (typeof selectedTab != 'undefined') {
            selectedTab = target;
            if (history.replaceState) {
                history.replaceState({ q: null }, "", "default.aspx?" + BuildQueryString() + "&tab=" + selectedTab);
            }
        }
        return false;
    });
}



/*-----Main Search Bars-----*/
function doHeadSearch() {
    doSearch(document.getElementById('qHead').value)
}
function doFootSearch() {
    doSearch(document.getElementById('qFoot').value)
}
function doSearch(q) {
    if (q.length > 0)
        window.location.href = '/s/?q=' + escape(q) + "&safe=on&cx=partner-pub-4386007180384455:7712495912&cof=FORID:10&ie=UTF-8";
}

/*-----Comment Voting JS-----*/
function commentvote(id, value) {
    jQuery.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "/_ajax/CommentOperations.asmx/Vote",
        data: "{ 'guid': '" + id + "', 'voteValue': " + value + " }"
    });
    return false;
}


/*-----Save Major Without Reload-----*/
function AddMajor(majorId, addLinkId, loadingParagraphId, successParagraphId) {
    $("#" + addLinkId).hide();
    $("#" + loadingParagraphId).show();
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "/_ajax/SaveMajorOperations.asmx/AddMajorToBackpack",
        data: "{ 'majorId': " + majorId.toString() + " }",
        dataType: "json",
        success: function(data, textStatus, XMLHttpRequest) {
            if (data.d == '1') {
                $("#" + loadingParagraphId).hide();
                $("#" + successParagraphId).show();
            }
            else if (data.d == '2') {
                $("#" + loadingParagraphId).hide();
                $("#" + successParagraphId).show();
                $("#" + successParagraphId).empty().html('already added');
            }
        },
        failure: function(functionrequest, textStatus, errorThrown) {
            //Debug code here
        }
    });
    return false;
}

/*------School YMN-------------*/
function AddAndRateBackpack(schoolGuid, interest) {
    switch (interest.toLowerCase()) {
        case "remove":
            $('div.afterDeciding').addClass('decideNo');
            $('div.loadingDecision').addClass('no');
            break;
        case "high":
            $('div.afterDeciding').addClass('decideYes');
            break;
        default:
            $('div.afterDeciding').addClass('decideMaybe');
            $('div.loadingDecision').addClass('maybe');
            break;
    }
    $('div.beforeDeciding').fadeOut(300, function () {
        $('div.loadingDecision').fadeIn(300);
        $('div.ymnBar').addClass('noReview');
        $('p.disclaimer').hide();
    });
    $('div.loadingDecision').promise().done(function () {
        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: "/_ajax/BackPackOperations.asmx/AddUpdateBackpackItemById",
            data: "{ 'schoolId': '" + schoolGuid + "', 'interest': '" + interest + "', 'origin': 'SCHOOL_PAGE' }",
            dataType: "json",
            success: function (data, textStatus, XMLHttpRequest) {
                if (data.d.ServiceResult != 0) {
                    $('p.addedToClient').html("We will attempt to notify this<br />school of your interest.");
                    $('div.loadingDecision').fadeOut(200, function () {
                        $(this).siblings('div.afterDeciding').fadeIn();
                    });
                }
                else {
                    $('div.loadingDecision').fadeOut(200, function () {
                        $(this).siblings('div.afterDeciding').html('<h6>Oops! There was an error.</h6><p>Reload the page and try again.</p>').fadeIn();
                    });
                }
            },
            error: function () {
                $('div.loadingDecision').fadeOut(200, function () {
                    $(this).siblings('div.afterDeciding').html('<h6>Oops! There was an error.</h6><p>Reload the page and try again.</p>').fadeIn();
                });
            }
        });
    });
    
    return false;
}
function schoolBump(schoolGuid) {
    $('div.decisionDisplay').fadeOut(300, function() {
        $('div.afterDeciding').addClass('decideYes');
        $('div.loadingDecision').fadeIn(300);
    });
    $('div.loadingDecision').promise().done(function () {
        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: "/_ajax/BackPackOperations.asmx/AddUpdateBackpackItemById",
            data: "{ 'schoolId': '" + schoolGuid + "', 'interest': 'High', 'origin': 'SCHOOL_PAGE' }",
            dataType: "json",
            success: function (data, textStatus, XMLHttpRequest) {
                if (data.d.ServiceResult != 0) {
                    $('p.addedToClient').html("We will attempt to notify this<br />school of your interest.");
                    $('div.loadingDecision').fadeOut(200, function () {
                        $(this).siblings('div.afterDeciding').fadeIn();
                    });
                }
                else {
                    $('div.loadingDecision').fadeOut(200, function () {
                        $(this).siblings('div.afterDeciding').html('<h6>Oops! There was an error.</h6><p>Reload the page and try again.</p>').fadeIn();
                    });
                }
            },
            failure: function (functionrequest, textStatus, errorThrown) {
                $('div.loadingDecision').fadeOut(200, function () {
                    $(this).siblings('div.afterDeciding').html('<h6>Oops! There was an error.</h6><p>Reload the page and try again.</p>').fadeIn();
                });
            }
        });
    });
    return false;
}

$(document).ready(function () {
    if (!isIos()) {
        $("div.ymnBtn a.yes").qtip({ content: { text: 'Try to tell this school I\'m interested<br />and save for later reference.' }, position: { at: 'top center', my: 'bottom center'} });
        $("div.ymnBtn a.maybe").qtip({ content: { text: 'Save for later reference.' }, position: { at: 'top center', my: 'bottom center'} });
        $("div.ymnBtn a.no").qtip({ content: { text: 'Remove from my<br />recommendations.' }, position: { at: 'top center', my: 'bottom center'} });
        $("div.decisionDisplay.decideMaybe p.maybe a").qtip({ content: { text: 'Try to tell this<br />school I\'m interested.' }, position: { at: 'top center', my: 'bottom center'} });
    }
});

/*-------------School page--------------*/
$(document).ready(function() {
    $('div.schoolHeader').clone().appendTo('div.schoolHeaderFloating');
    $('div.schoolHeaderFloating').find('a').removeAttr('id');
    $('div.schoolHeaderFloating').find('a.helpIcon').remove();
    $('div.schoolHeaderFloating').find('a.yes, a.maybe, a.no').each(function() {
        var onclick = $(this).attr('onclick');
        if (!($.browser.msie && $.browser.version.substr(0, 1) < 8)) {
            onclick = onclick.replace('School YMN', 'School YMN - Floating');
            $(this).attr('onclick', onclick);
        }
    });
    if (!isIos()) { 
        if ($('div.schoolHeader').length) {
            var schoolHeaderOffset = $('div.schoolHeader').offset();
            $(window).scroll(function() {
                if ($(this).scrollTop() > schoolHeaderOffset.top) {
                    $('div.schoolHeaderFloating').show();
                } else {
                    $('div.schoolHeaderFloating').hide();
                }
            });
        }
    }
    
    $('div.reviewMenu').hover(function() {
        var menuOffset = $(this).position();
        var ymnOffset = $(this).closest('div.ymnBar').position();
        $(this).addClass('hover');
        $(this).closest('div.ymnBar').siblings('div.reviewMenuBody').css({ 'left': menuOffset.left, 'top': menuOffset.top + ymnOffset.top + 33 }).show();
    }, function() {
        var menu = $(this);
        menu.removeClass('hover');
        $(this).closest('div.ymnBar').siblings('div.reviewMenuBody').hide().hover(function() {
            $(this).show();
            menu.addClass('hover');
        }, function() {
            $(this).hide();
            menu.removeClass('hover');
        });
    });
});

/*------Colorbox popup options-----*/
var colorboxDefaults = { width: '700px', height: '70%', iframe: true };
var colorboxDefaultsInline = { maxWidth: '700px', maxHeight: '70%', inline: true };
var colorboxDefaultsForm = { width: '530px', height: '530px', iframe: true };

/*------URL Parameters-----*/
// Read a page's GET URL variables and return them as an associative array.
function getUrlVars() {
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for (var i = 0; i < hashes.length; i++) {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}

//replace value of a parameter in a querystring
function replaceQueryString(url, param, value) {
    var re = new RegExp("([?|&])" + param + "=.*?(&|$)", "i");
    if (url.match(re))
        return url.replace(re, '$1' + param + "=" + value + '$2');
    else
        return url + '&' + param + "=" + value;
}

//checking if variable is undefined
function isUndefined(x) {
    if ((x == null && x !== null) || typeof (x) == undefined || x == 'undefined' || x == undefined)
        return true;
    else
        return false;
}

// This function decodes the any string
// that's been encoded using URL encoding technique
function URLDecode(psEncodeString) {
    // Create a regular expression to search all +s in the string
    var lsRegExp = /\+/g;
    // Return the decoded string
    return unescape(String(psEncodeString).replace(lsRegExp, " "));
}


// allows use of indexOf on arrays in all browsers to quickly find elements without looping
if (!Array.prototype.indexOf) {
    Array.prototype.indexOf = function(searchElement) {
        "use strict"; if (this === void 0 || this === null)
            throw new TypeError(); var t = Object(this); var len = t.length >>> 0; if (len === 0)
            return -1; var n = 0; if (arguments.length > 0) {
            n = Number(arguments[1]); if (n !== n)
                n = 0; else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0))
                n = (n > 0 || -1) * Math.floor(Math.abs(n));
        }
        if (n >= len)
            return -1; var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0); for (; k < len; k++) {
            if (k in t && t[k] === searchElement)
                return k;
        }
        return -1;
    };
}
