﻿/*------------Generic Search Tool JS---------------*/
String.prototype.trim = function() { return this.replace(/^\s+|\s+$/, ''); };

//set selected vales of chkeckboxes in a checkbox list
function setCheckBoxes(NodeId, values) {
    for (var i = 0; i < values.length; i++) {
        jQuery('#' + NodeId + ' input[type="checkbox"]').each(function() {
            var currentValue;
            nearestLabel = $(this).closest('div.checker').next('label');
            if (nearestLabel.has('a')) {
                currentValue = nearestLabel.children('a').text();
            } else {
                currentValue = nearestLabel.text();
            }
            if (currentValue == values[i]) {
                jQuery(this).prop("checked", true);
            }
        });
    }
}
// check all checkboxes in a checkbox list
function setAllCheckBoxes(NodeId) {
    $("#" + NodeId + " input:checkbox").prop("checked", true);
}
// uncheck all checkboxes in a checkbox list
function clearAllCheckBoxes(NodeId) {
    $("#" + NodeId + " input:checkbox").prop("checked", false);
}

function uncheckBox(list, item) {
    $('#' + list + ' label').each(function() {
        var label;
        var forInput = $(this).attr('for');
        if ($(this).children('a').size() > 0) {
            label = $(this).children('a').text();
        } else {
            label = $(this).text();
        }
        if (label == item) {
            $('input[id="' + forInput + '"]').attr("checked", false);
        }
    });
}




//set drop down
function SetDDL(ddlId, val) {
    if (!isUndefined(val)) {
        jQuery("select#" + ddlId + " option").each(function() {
            var currentValue = $(this).val();
            if (currentValue == val)
                jQuery(this).attr("selected", true);
        });
    }
}
//clearing title
function ClearHiddenTitleVal() {
    $("#title").val(null);
}
function ClearHiddenPageVal() {
    $("#returnpage").val(null);
}
//====================================


function goToSchool(event, value) {
    q = value;
    if (q.length > 0)
        window.location.href = '/s/?q=' + escape(q) + "&cx=013514770356652780808:gabniubyimi&cof=FORID:9&ie=UTF-8";
}


$(document).ready(function() {
    var isIE6or7 = ($.browser.msie && ($.browser.version == '7.0' || $.browser.version == '6.0'));
    if (!isIE6or7) {
        // wrapper search filter options into a dropdown
        $('.searchOptsWrapper').each(function(i) {
            cat = $(this).children('.searchOpts').attr('data-cat').toLowerCase();
            $(this).wrap('<div class="filterDropdown" />').before("Select " + cat + ". . .").css({ 'display': 'none' });
        });
        $('.searchOpts').after('<div class="dropdownCap" />');
        $('.filterDropdown').click(function(event) {
            event.stopPropagation();
            $('.searchOptsWrapper', this).toggle();
            $(this).toggleClass('active');
            $(this).siblings('.filterDropdown').removeClass('active');
            $(this).siblings().children('.searchOptsWrapper').hide();
        });
        // hide menu when anything outside of it is clicked . . .
        $('body').click(function() { $('.searchOptsWrapper').hide(); $('.filterDropdown').removeClass('active'); });
    }

    $('.advSearchSelector').click(function(event) {
        $('.menu .close').unbind().click(function(event) {
            event.stopPropagation();
            $('.advSearchSelector').removeClass('active');
        });
        $('.menu').unbind().click(function(event) {
            event.stopPropagation();
        });
        event.stopPropagation();
        if (!$(this).hasClass('disabled')) {
            $(this).closest('.searchFilters').siblings().children('.advSearchSelector').removeClass('active');
            $(this).toggleClass('active');
        }
    });

    $('body').click(function() {
        $('.advSearchSelector').removeClass('active');
    });

    bindYMNButtons();

    // clear simple search filters when linked is clicked to prevent users from attempting to select multiple
    $('a.simpleSearchLink').click(function() {
        $(this).closest('div.searchFilters').children('.loading').fadeIn();
    });
});

function bindYMNButtons() {
    // set width of YMN messages depending on table width
    var listingWidth = $('#schoolListingYMN').outerWidth();
    var paddingLeft = 146;
    if ($('#schoolListingYMN').hasClass('extraColumn')) paddingLeft = 200;
    $('div.ymnMsg').css({ 'left': -listingWidth + 1, 'width': listingWidth - paddingLeft });

    // update hidden radio buttons when Y/M/N buttons are clicked
    $('.decisionBtn div').click(function() {
        $radio = $(this).next('input');

        $radio.click();
        if (!$radio.attr("checked")) {
            $(this).removeClass('checked');
        } else {
            $("div.decisionBtn:has(input[name='" + $radio.attr('name') + "'])").children('div').removeClass('checked');
            $(this).addClass('checked');
        }

        // update and display the YMN message
        var decision = $(this).attr('class').split(' ')[0];
        $parentRow = $(this).closest('tr');
        var schoolName = $parentRow.find('td.nameColumn a.blue').html();
        var msgHTML = '<strong>';
        switch (decision) {
            case "yesOnlyButton": case "yesButton": msgHTML += 'I\'m interested in ' + schoolName + '.</strong>'; break;
            case "maybeButton": msgHTML += 'I\'m thinking about ' + schoolName + '.</strong>'; break;
            case "noButton": msgHTML += schoolName + ' isn\'t for me.</strong>'; break;
        }
        switch (decision) {
            case "yesOnlyButton": msgHTML += (isRegistered ? 'We\'ll attempt to notify this school and add it to your list.' : 'Submit this form so we can let them know.'); break;
            case "yesButton": msgHTML += (isRegistered ? 'We\'ll attempt to notify this school and add it to your list.' : '<span>Register</span> to attempt to them know and add it to your list.'); break;
            case "maybeButton": msgHTML += (isRegistered ? 'We\'ve added it to your list.' : '<span>Register</span> to add it to your list.'); break;
            case "noButton": msgHTML += (isRegistered ? 'It won\'t show up on your list of recommended schools.' : '<span>Register</span> to get a list of recommended schools.'); break;
        }
        msgHTML += '<div class="closeYMNMsg"></div>';

        if (isRegistered && processLeads) {
            var radioText = $radio.next('label').text();
            var interest = 'low';
            if (radioText.split(',')[1] == 'true')
                interest = 'remove';
            else if (radioText.split(',')[0] == 'true')
                interest = 'high';
            var schoolId = radioText.split(',')[2];
            var origin = radioText.split(',')[3];
            $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: "/_ajax/BackPackOperations.asmx/AddUpdateBackpackItemById",
                data: "{ 'schoolId': " + schoolId + ", 'interest': '" + interest + "', 'origin': '" + origin + "' }",
                dataType: "json",
                success: function(data, textStatus, XMLHttpRequest) {
                    if (data.d.ServiceResult == 0)
                        msgHTML = '<strong>Sorry, an error occurred.</strong>We could not complete your request.<div class="closeYMNMsg"></div>';

                    showYMNmessage($parentRow, msgHTML, listingWidth);
                },
                error: function() {
                    msgHTML = '<strong>Sorry, an error occurred.</strong>We could not complete your request.<div class="closeYMNMsg"></div>';
                    showYMNmessage($parentRow, msgHTML, listingWidth);
                }
            });
        }
        else {
            showYMNmessage($parentRow, msgHTML, listingWidth);

            //Register link click inside schoolListingYMN notification window
            $('div.ymnMsgWrapper div.ymnMsg span').click(function() {
                $('div.footerRow div.registerContainer input').click();
                return false;
            });
        }

        $('.closeYMNMsg').click(function() {
            $(this).parent('.ymnMsg').fadeOut('fast');
        });
    });
}

function showYMNmessage(parentRow, msgHTML, width) {
    parentRow.find('div.ymnMsg').html(msgHTML);
    $('div.closeYMNMsg').css({ 'left': width - 20 });
    parentRow.find('div.ymnMsg').fadeIn(400, function() {
        var that = this;
        var hideMsg = setTimeout(function() { $(that).fadeOut("slow") }, 7500);
    });
}

var openTreeItemsArray = new Array();

//Majors Folder Tree
function openMajor(linkNum) {
    openMajorFull(linkNum, false);
}

function openMajorFull(linkNum, auto) {
    var linkObj = document.getElementById('major' + linkNum);
    var divObj = "#majorDiv" + linkNum.toString();
    if (linkObj.className == "open") {
        $(divObj).hide();
        linkObj.setAttribute("class", "closed");
        linkObj.setAttribute("className", "closed");
        for (var j = 0; j < openTreeItemsArray.length; j++) {
            if (openTreeItemsArray[j] == linkNum)
                openTreeItemsArray.splice(j, 1);
        }
    }
    else if (linkObj.className == "closed") {
        $(divObj).show();
        linkObj.setAttribute("class", "open");
        linkObj.setAttribute("className", "open");
        if (!auto)
            openTreeItemsArray.push(linkNum.toString());
    }
    $.cookie("openTreeItems", openTreeItemsArray, { path: '/' });

    return false;
}

function unfoldTree() {
    openTreeItemsArray = $.cookie("openTreeItems").split(/,/);
    for (var j = 0; j < openTreeItemsArray.length; j++)
        openMajorFull(openTreeItemsArray[j], true);
}


(function($) {
    $.addBox = {
        defaults: {
            max: 20,
            box: '',
            warningContainer: '',
            tooManyWarning: 'Too many',
            dupWarning: 'Can\'t add twice',
            emptyMessage: 'Nothing selected',
            clearLink: ''
        }
    };
    var methods = {
        init: function(options) {
            var targetId = $(this).attr('id');

            if (options.box == '' || options.box == 'undefined' || options.box == null)
                options.box = targetId + 'Box';
            if (options.warningContainer == '' || options.warningContainer == 'undefined' || options.warningContainer == null)
                options.warningContainer = targetId + 'Warning';
            if (options.clearLink == '' || options.clearLink == 'undefined' || options.clearLink == null)
                options.clearLink = targetId + 'Clear';

            var options = $.extend({}, $.addBox.defaults, options);
            return this.each(function() {
                data = $(this).data('addBox');
                if (!data) {
                    $(this).data('addBox', {
                        list: [],
                        target: targetId,
                        settings: options
                    });
                }
                $(this).focus(function() { $(this).addClass('focus'); }).blur(function() { $(this).removeClass('focus'); });
                $(this).before('<div class="warning" id="' + options.warningContainer + '"></div>');
                $(this).after('<div class="selectedItemsBox" id="' + options.box + '"><p>' + options.emptyMessage + '</p></div><a href="#" style="display: none;" id="' + options.clearLink + '" class="linkRemove" onclick="$(\'#' + targetId + '\').addBox(\'empty\'); return false;">Clear This List</a>');
            });
        },
        add: function(item, update, type) {
            var data = $(this).data('addBox');
            if (data.list.length >= data.settings.max) {
                $('#' + data.settings.warningContainer).html(data.settings.tooManyWarning).show(250);
                return false;
            } else {
                $('#' + data.settings.warningContainer).hide();
                if (data.list.indexOf(item) != -1) {
                    $('#' + data.settings.warningContainer).html(data.settings.dupWarning).show(250);
                    return false;
                } else {
                    data.list.unshift(item);
                    $.fn.addBox('printList', data.settings, data.list, data.target);
                    $(this).data('addBox', data);
                    if (update != false) UpdateResults(item, type);
                }
            }

        },
        remove: function(id) {
            var data = $(this).data('addBox');
            data.list.splice(id, 1);
            $.fn.addBox('printList', data.settings, data.list, data.target);
            if (data.list.length == 0)
                $('#' + data.settings.clearLink).hide();
            $(this).data('addBox', data);
            UpdateResults();
        },
        printList: function(settings, list, target) {
            var htm = '<h5>Currently Selected</h5>';
            if (list.length == 0) {
                htm = '<p>' + settings.emptyMessage + '</p>';
                $('#' + settings.clearLink).hide();
            } else {
                for (var i = 0; i < list.length; i++) {
                    htm += '<a href="#" onclick="$(\'#' + target + '\').addBox(\'remove\', ' + i + '); return false;">' + list[i] + '</a>';
                }
                $('#' + settings.clearLink).show();
            }
            $('#' + settings.box).html(htm);
        },
        empty: function() {
            var data = $(this).data('addBox');
            $('#' + data.settings.clearLink).hide();
            $('#' + data.settings.warningContainer).hide();
            data.list = [];
            $.fn.addBox('printList', data.settings, data.list, data.target);
            UpdateResults();
        },
        list: function() {
            var data = $(this).data('addBox');
            return data.list;
        }
    };
    $.fn.extend({
        addBox: function(method) {
            if (methods[method]) {
                return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
            } else if (typeof method === 'object' || !method) {
                return methods.init.apply(this, arguments);
            } else {
                $.error('Method ' + method + ' does not exist on jQuery.addBox');
            }
        },
        addSchoolToListing: function(e, item) {
            $(this).val("");
            if (item instanceof Array)
                item = item[0];
            if (item != "" && item != null && item != 'undefined')
                return $.fn.addBox.apply(this, ['add', item, true, 'school']);
            else
                return false;
        },
        addMajorToListing: function(e, item) {
            $(this).val("");
            if (item instanceof Array)
                item = item[0];
            if (item != "" && item != null && item != 'undefined')
                return $.fn.addBox.apply(this, ['add', item, true, 'major']);
            else
                return false;
        }
    });
})(jQuery);

function addList(element, list) {
    for (i = 0; i < list.length; i++)
        $(element).addBox('add', list[i], false);
    UpdateResults();
}


