// For IE hover flicker bug
try {
  document.execCommand('BackgroundImageCache', false, true);
} catch(e) {}

$(document).ready(function(){
	$("#modFilter").click(function(){
		$("#modFilter").removeClass("open");
	});
	// Add pdf icons to pdf links
	//$("a[href$='.pdf']").addClass("pdf");
	//$("a[href$='.pdf']").not(":has('img')").addClass("pdf");
	 
	// Add txt icons to document links (doc)
	//$("a[href$='.doc'], a[href$='.docx']").addClass("doc");
	
	// Add txt icons to document links (xls)
	//$("a[href$='.xls'], a[href$='.xlsx']").addClass("xls");
	
	// Add txt icons to document links (ppt)
	//$("a[href$='.ppt'], a[href$='.pptx']").addClass("ppt");
	
	// Add txt icons to document links (rtf, txt)
	//$("a[href$='.txt'], a[href$='.rft']").addClass("txt");

	// Add zip icons to Zip file links (zip, rar)
	//$("a[href$='.zip'], a[href$='.rar']").addClass("zip"); 	
	
	// Add email icons to email links
	//$("a[href^='mailto:']").addClass("email");

	//Add external link icon to external links - 
	


	//$('a').filter(function() {
	//Compare the anchor tag's host name with location's host name
	   // return this.hostname && this.hostname !== location.hostname);
	  //}).addClass("external");



});

$(function() {
    $("body").addClass("jsEnabled");
    // $("#featureArea #navPrimary").homeTabs();
    $("#shareMiami, #navAudience, #navCampus, #modFilter").clickShow({ toggle: "h3" });
    $("#navGallery").experienceGallery();
    $("#traditionsGalleryNav").traditionsGallery();
    $("#myInsideGuide ul").toggleDrawer();
    $("#myExperience").experienceStory();
    $("#featuredNews").simpleGallery();
    $(".simpleGalleryFeature").simpleGallery();
    $(".simpleGalleryExperience").simpleGallery({ individualLinksNav: false, displayCounter: true });
    $("#majorsList .content").simpleGallery({ individualLinksNav: false, navBeforeGallery: false, displayCounter: false });
    $("#majorsList").tabbedContent();
    $("input:file").styleFileUploads();
    $("#modSearch .text, #comments textarea, #modSearchArchive .text").inputClear();
    $(".modLinkList").expandLinkList();
    $("#modMoreSuccess").expandMoreSuccess();
    $("#mediaGallery.image").mediaGallery();
    $("#mediaGallery.audio").mediaGallery({ itemsPerPage: 4, mediaType: "audio" });
    $("#mediaGallery.video").mediaGallery({ itemsPerPage: 10, mediaType: "video" });
    $(".tabbedContent").flexibleTabbedContent();
    $("#blogDiscussions .content").simpleGallery({ individualLinksNav: false, navBeforeGallery: false, displayCounter: false });
    $("#admissionFeature").simpleGallery({ individualLinksNav: true, navBeforeGallery: false, displayCounter: false });
    $("#admissionFeature .simpleGalleryNav").before("<h4 class='navTitle'> &nbsp; </h4>");
    // zebra tables
    $("#content table").each(function() {
        $("tr:nth-child(odd)").addClass("odd");
    });
});

(function($) {

    // On click, toggle the open state of an item
    $.fn.clickShow = function(options) {
        var opts = $.extend({
            toggle: '.toggle', // selector that will toggle the open/close state
            open: '.open', 	// selector that will trigger open state
            close: '.close', // selector that will trigger close state
            className: "open"	// class to add to object on open
        }, options);

        return this.each(function() {
            var obj = $(this);
            var togglerButtons = obj.find(opts.toggle);
            var openButtons = obj.find(opts.open);
            var closeButtons = obj.find(opts.close);
            var className = opts.className;

            togglerButtons.click(function() {
                obj.toggleClass(className);
                return false;
            });

            openButtons.click(function() {
                if (!obj.hasClass(className)) {
                    obj.siblings().removeClass(className);
                    obj.addClass(className);
                    return false;
                }
            });

            closeButtons.click(function() {
                obj.removeClass(className);
                return false;
            });
        });
    };

    // Toggle expansion of Link List module to view all links
    $.fn.expandLinkList = function(options) {
        var opts = $.extend({
            moreLinkClass: 'moreLink',
            openStateClass: 'showAll',
            openStateText: 'More',
            closeStateText: 'Less'
        }, options);

        return this.each(function() {
            var obj = $(this);
            var links = obj.find("ul").find("li");

            // Create the More link
            if (links.length > 3) {
                var showAllClass = opts.openStateClass;

                obj.append("<a class='" + opts.moreLinkClass + "' href='#'>" + opts.openStateText + "</a>");
                var moreLink = obj.find("." + opts.moreLinkClass);

                // Hide more than 3 links
                links.each(function(i) {
                    if (i > 2)
                        $(this).hide();
                });

                // Toggle state of all select fields on the page
                moreLink.toggle(
					function() {
					    // Show all links
					    links.show();
					    obj.addClass(showAllClass);
					    $(this).text(opts.closeStateText);
					},
					function() {
					    // Hide more than 3 links
					    links.each(function(i) {
					        if (i > 2)
					            $(this).hide();
					    });
					    obj.removeClass(showAllClass);
					    $(this).text(opts.openStateText);
					}
				);
            }
        });
    };

    $.fn.mediaGallery = function(options) {
        var opts = $.extend({
            itemsPerPage: 12, 	// number of items to be shown at one time
            displayCounter: true, // whether or not a counter should be displayed
            mediaType: "image"	// type of media to display  
        }, options);

        return this.each(function() {
            swfobject.switchOffAutoHideShow();

            var obj = $(this);
            var galleryNav = obj.children("#galleryNav");
            var galleryItems = galleryNav.children();
            var galleryItemsCount = galleryItems.length;
            var type = opts.mediaType;

            var itemsPerPage = opts.itemsPerPage;
            var currentPage = 1;
            var totalPages = Math.ceil(galleryItemsCount / itemsPerPage);

            // add HTML to create the gallery structure
            obj.prepend("<div id='showcase'></div>");
            var showcase = obj.children("#showcase");

            galleryNav.wrap("<div id='galleryNavWrapper'></div>");
            var navWrapper = $("#galleryNavWrapper");
            obj.append("<p id='counter'></p>")
				.append("<div id='prevNext'><a class='button disabled' href='#' id='prev'>Previous</a> <a class='button' href='#' id='next'>Next</a></div>");

            var increment = navWrapper.height();
            var totalHeight = increment * totalPages;

            changeCounter(0);

            obj.find("#prev").bind(
				"click", {
				    amount: -1
				},
				navClickHandler
			);
            obj.find("#next").bind(
				"click", {
				    amount: 1
				},
				navClickHandler
			);

            galleryItems.each(function(i) {

                // get the href from the a tag and the alt from the thumbnail
                // these will be used later to create the large image
                var content = $(this).children(".content");
                var media = $(this).children(".media")
                var mediaSrc = media.attr("href");
                var mediaAlt = "";

                if (type == "image") {
                    mediaAlt = media.children("img").attr("alt");
                }


                content.remove();

                $(this).bind(
					"click",
					{
					    type: type,
					    mediaSrc: mediaSrc,
					    mediaAlt: mediaAlt,
					    showcase: showcase,
					    content: content,
					    siblings: $(this).siblings()
					},
					clickHandler
				);

                if (i == 0) {
                    $(this).click();
                }
            });

            function clickHandler(e) {
                var content = e.data.content;
                var type = e.data.type;
                var mediaSrc = e.data.mediaSrc;
                var mediaAlt = e.data.mediaAlt;

                swfobject.removeSWF("mediaFlash");

                //$("#mediaFlash").show().empty().remove();

                // Add the full image if it hasn't been added already
                if (type == "image") {
                    if (content.children(".fullMedia").length == 0) {
                        content.prepend("<div class='fullMedia'><img alt='" + mediaAlt + "' class='fullMedia' src='" + mediaSrc + "' /></div>");
                    }
                }
                else if (type == "video") {
                    $(".fullMedia").empty().remove();

                    var output = "";
                    if (content.children(".fullMedia").length == 0) {
                        output = "<div class='fullMedia'>";
                        output += "<div id='mediaFlash'></div>";
                        output += "</div>";
                    }

                    content.prepend(output);
                    e.data.showcase.empty().append(content).show();

                    swfobject.embedSWF("/flash/Miami_video_MG.swf", "mediaFlash", "384", "320", "9.0.0", null, { var1: mediaSrc }, { wmode: "transparent" }, null);
                }
                else if (type == "audio") {
                    $(".fullMedia").empty().remove();

                    var output = "";
                    if (content.children(".fullMedia").length == 0) {
                       // var title = content.children("h3").remove().text();
                        output = "<div class='fullMedia'><div class='audioWrapper'>";
                       // output += "<h3>" + title + "</h3>";
                        output += "<div id='mediaFlash'></div>";
                        output += "</div></div>";
                    }

                    content.prepend(output);
                    e.data.showcase.empty().append(content).show();

                    swfobject.embedSWF("/flash/Miami_audio_MG.swf", "mediaFlash", "400", "55", "9.0.0", null, { var1: mediaSrc }, { wmode: "transparent" }, null);
                }

                // Toggle active state
                e.data.siblings.removeClass("active");
                $(this).addClass("active");

                if (type == "image") {
                    e.data.showcase.empty().append(content).show();
                }
                return false;
            }

            function navClickHandler(e) {
                var amount = e.data.amount;
                var pageToChangeTo = currentPage + amount

                if (pageToChangeTo > 0 && pageToChangeTo <= totalPages) {
                    swapGalleryItems($(this), amount);
                }

                return false;
            }

            var curPos = 0;
            function swapGalleryItems(item, i) {
                var isDisbaled = item.hasClass("disabled");

                var id = item.attr("id");

                if (!isDisbaled && id == "prev") {
                    curPos = curPos + increment;
                    changeCounter(i);
                }
                else if (!isDisbaled && id == "next") {
                    curPos = curPos - increment;
                    changeCounter(i);
                }

                if (curPos == 0) {
                    $("#prev").addClass("disabled");
                    $("#next").removeClass("disabled");
                }
                else if (Math.abs(curPos) == totalHeight - increment) {
                    $("#next").addClass("disabled");
                    $("#prev").removeClass("disabled");
                }
                else {
                    $("#prev, #next").removeClass("disabled");
                }

                if (!isDisbaled) {
                    galleryNav.stop().animate({ top: curPos });
                    //clearActiveStates();
                }
            }

            function changeCounter(i) {
                var startCounter, endCounter = 0;

                currentPage = currentPage + i;

                startCounter = ((currentPage - 1) * itemsPerPage) + 1;

                endCounter = startCounter + itemsPerPage - 1;
                if (endCounter > galleryItemsCount) {
                    endCounter = galleryItemsCount;
                }

                obj.find("#counter").html("Displaying " + startCounter + "-" + endCounter + " <span>( of " + galleryItemsCount + ")</span>");
            }
        });
    }

    //
    $.fn.experienceGallery = function(options) {
        var opts = $.extend({
            showcase: '#showcase', 	// container that active content will appear in
            itemsPerPage: 6				// number of items to be shown at one time
        }, options);

        return this.each(function() {
            var obj = $(this);
            var showcase = $(opts.showcase).hide();
            var itemsPerPage = opts.itemsPerPage;

            var items = obj.children("li");
            var count = items.length;
            var currentPage = 1;
            var totalPages = Math.ceil(count / itemsPerPage);
            var increment = items.eq(0).outerWidth() * itemsPerPage;
            var totalWidth = increment * totalPages;

            obj.wrap("<div id='galleryWrapper'></div>")
				.wrap("<div id='galleryNavWrapper'></div>");

            var galleryWrapper = $("#galleryWrapper")
									.prepend("<a class='button disabled' href='#' id='prev'>Previous</a>")
									.append("<a class='button' href='#' id='next'>Next</a>")
									.append("<p id='counter'>Page of " + currentPage + " of " + totalPages + "</p>");


            var curPos = 0;

            galleryWrapper.children(".button").click(function() {
                var isDisbaled = $(this).hasClass("disabled");

                var id = $(this).attr("id");

                if (!isDisbaled && id == "prev") {
                    curPos = curPos + increment;
                    updateCounter(-1);

                }
                else if (!isDisbaled && id == "next") {
                    curPos = curPos - increment;
                    updateCounter(1);
                }

                if (curPos == 0) {
                    $("#prev").addClass("disabled");
                    $("#next").removeClass("disabled");
                }
                else if (Math.abs(curPos) == (totalWidth - increment)) {
                    $("#next").addClass("disabled");
                    $("#prev").removeClass("disabled");
                }
                else {
                    $("#prev, #next").removeClass("disabled");
                }

                if (!isDisbaled) {
                    obj.stop().animate({ left: curPos });
                    clearActiveStates();
                }

                return false;
            });

            items.children("a").each(function() {
                if ($.browser.msie && $.browser.version == "6.0")
                    var isIe = true;

                $(this).bind(
					"mouseenter",
					{
					    content: $(this).parent().children(".content").html(),
					    image: $(this).parent().children(".content").children("a").attr("href"),
					    parent: $(this).parent(),
					    isIE: isIe
					},
					mouseEnterHandler)
            });

            function mouseEnterHandler(e) {
                showcase.empty()
						.prepend("<img src='" + e.data.image + "' />")
						.append(e.data.content);
                showcase.show();

                if (e.data.isIE) {
                    pngfix();
                }

                items.removeClass("active");
                e.data.parent.addClass("active");
            }

            function clearActiveStates() {
                showcase.hide().empty();
                items.removeClass("active");
            }

            function updateCounter(i) {
                currentPage += i;
                $("#counter").text("Page of " + currentPage + " of " + totalPages);
            }
        });
    };

    // Show a layer when a link is clicked
    $.fn.experienceStory = function(options) {
        var opts = $.extend({
            className: 'open',
            openLinkParent: '#showcase',
            closeLinkParent: null // container to append close button to, if not defiend the obj is used
        }, options);

        return this.each(function() {
            var obj = $(this);

            obj.hide();

            $(opts.openLinkParent).append("<a href='#' id='viewStory'>View my story&nbsp;<span>&nbsp;&nbsp;&nbsp;</span></a>");
            var openLink = $("#viewStory");

            obj.append("<a class='close' href='#'>Close</a>");
            var closeLink = $(".close");

            openLink.click(function() {
                if (!$(this).hasClass("disabled")) {
                    $("#myFeed").addClass("pushToBack");
                    $(this).addClass("disabled");

                    obj.fadeIn();
                }
                return false;
            });

            closeLink.click(function() {
                obj.fadeOut("slow", function() {
                    $("#myFeed").removeClass("pushToBack");
                    openLink.removeClass("disabled");
                });
                return false;
            })

        });
    };

    // On hover, toggle the open state of an item
    $.fn.hoverClass = function(options) {
        var opts = $.extend({
            className: 'open'
        }, options);

        return this.each(function() {
            var obj = $(this);

            obj.hover(
				function() { obj.addClass(opts.className); },
				function() { obj.removeClass(opts.className); }
			);
        });
    };

    // Clear out the default text in a specified input when it gains focus
    // If focus is lost and field is empty replace with default text
    $.fn.inputClear = function() {

        return this.each(function() {
            var obj = $(this);
            var type = obj.attr("type");

            if (type == "text" || type == "password" || obj.is("textarea")) {
                var value = obj.val();

                obj.focus(function() {
                    if (obj.val() == value) {
                        obj.val("");
                    }
                });

                obj.blur(function() {
                    if (obj.val() == "") {
                        obj.val(value);
                    }
                });
            }
        });
    };

    // Swap items in a gallery
    $.fn.simpleGallery = function(options) {
        var opts = $.extend({
            individualLinksNav: true, // true creates links for each item, false creates prevnext buttons
            displayCounter: false, // whether or not a counter should be displayed
            navBeforeGallery: true	// whether the code for the counter is placed before or after existing HTML
        }, options);

        return this.each(function() {

            var obj = $(this);
            var active = null;

            var galleryItems = obj.children("ul").children("li");
            var counter = 1;

            if (galleryItems.length > 1) {
                var nav = "";
                if (opts.individualLinksNav)
                    nav = buildIndividualLinksNav();
                else {
                    nav = buildPrevNextNav();
                }

                if (opts.navBeforeGallery)
                    obj.children("ul").before(nav);
                else
                    obj.children("ul").after(nav);

                obj.find(".simpleGalleryNav a").each(function() {
                    var parent = $(this).parent();
                    if ($(this).hasClass("next")) {
                        $(this).bind("click", nextClickHandler);
                    }
                    else if ($(this).hasClass("previous")) {
                        $(this).bind("click", previousClickHandler);
                    }
                    else {
                        $(this).bind(
							"click",
							{
							    parent: parent,
							    loc: parent.prevAll().length,
							    siblings: parent.siblings()
							},
							itemClickHandler
						);
                    }

                });
            }

            // Nav with a previous and next button
            function buildPrevNextNav() {
                var navItems = "";
                navItems += "<a class='previous' href='#'>Previous</a>";

                if (opts.displayCounter)
                    navItems += "<span class='counter'>Image " + counter + " of " + galleryItems.length + "</span>";

                navItems += "<a class='next' href='#'>Next</a>";

                galleryItems.each(function(i) {
                    if (i == 0) {
                        active = $(this).show();
                    } else {
                        $(this).hide();
                    }
                });

                return "<div class='simpleGalleryNav'>" + navItems + "</div>";
            }

            // Separate nav link for each individual gallery item
            function buildIndividualLinksNav() {
                var navItems = "";

                galleryItems.each(function(i) {
                    if (i == 0) {
                        active = $(this).show();
                        navItems += ("<li class='first active'><a href='#'>" + (i + 1) + "</a></li>");
                    } else {
                        $(this).hide();
                        navItems += ("<li><a href='#'>" + (i + 1) + "</a></li>");
                    }
                });

                return "<ul class='simpleGalleryNav'>" + navItems + "</ul>";
            }

            function nextClickHandler(e) {
                var next = active.next();
                if (next.length) {
                    active.hide();
                    active = next.show();
                    changeCounter(1);
                }
                return false;
            }

            function previousClickHandler(e) {
                var prev = active.prev();
                if (prev.length) {
                    active.hide();
                    active = prev.show();
                    changeCounter(-1);
                }
                return false;
            }

            function itemClickHandler(e) {
                active.hide();

                // set active nav item
                e.data.siblings.removeClass("active");
                e.data.parent.addClass("active");

                // show gallery item
                active = active.parent().children().eq(e.data.loc).show();

                return false;
            }

            function changeCounter(i) {
                counter = counter + i;
                obj.find(".counter").text("Image " + counter + " of " + galleryItems.length);
            }
        });
    };

    // Hide all upload file fields and replace with an input and an image
    // This allows for styling and customization of the field
    $.fn.styleFileUploads = function() {

        return this.each(function() {
            var obj = $(this);

            var fakeFileUpload = $('<div class="fakefile"/>');

            fakeFileUpload
				.append($('<img src="/styles/images/traditions/buttons/browse.gif"/>'))
				.append($('<input/>'));

            obj
				.wrap("<div class='fileUpload'></div>")
				.addClass("hidden")
				.change(function() {
				    obj.parent().children(".fakefile").children("input").val(obj.val());
				})
				.parent().append(fakeFileUpload);
        });
    };

    // Creates area of content with tabs to show/hide content
    $.fn.tabbedContent = function(options) {
        var opts = $.extend({
            triggers: '.trigger', // selector that will toggle the open/close state
            openTab: 0, 			// item that should be open by default, counts from 0
            maintainState: false	// whether or not it should remember the open tab when the user leaves the page
        }, options);

        var openTab = opts.openTab;
        var containerId = $(this).attr("id");
        var maintainState = opts.maintainState;


        return this.each(function() {
            var obj = $(this);
            var triggers = obj.find(opts.triggers);

            if (maintainState) {
                // check for existing cookie
                var className = readCookie(containerId);
            }

            if (!className) {
                if (openTab >= obj.children().length || openTab < 0 || openTab == "") {
                    openTab = 0;
                }

                var className = obj.children("div:eq(" + openTab + ")").attr("id");
            }


            obj.attr("class", className);

            //fixes an IE6 issue where the CSS would not be properly applied when the classname is changed
            triggers.hide().show();

            triggers.click(function() {
                var id = $(this).parent().attr("id");
                obj.attr("class", id);

                if (maintainState) {
                    createCookie(containerId, id, .002);
                }
            });

        });
    };

    // Creates area of content with tabs to show/hide content
    $.fn.flexibleTabbedContent = function(options) {
        var opts = $.extend({
            tabClass: '.tab', 	// selector used to designate a tab
            content: '.content', // selector that contains the content of each tab
            title: '.title'		// selector that contains the title of each tab
        }, options);

        var tabClass = opts.tabClass;
        var content = opts.content;
        var title = opts.title;
        var openTab = opts.openTab;
        var maintainState = opts.maintainState;

        return this.each(function() {
            var obj = $(this);
            var tabs = obj.children(tabClass);
            var tabTitles = obj.find(opts.title);

            obj.prepend(buildNav());
            obj.children("ul:eq(0)").find("a").each(function(i) {

                var href = $(this).attr("href");
                href = "#" + href.split("#")[1];

                $(this).bind(
						"click",
						{
						    id: href,
						    targetTab: obj.find(href),
						    siblings: $(this).parent().siblings(),
						    parent: $(this).parent()
						},
						clickHandler
				);

                // make the first item active
                if (i == 0) {
                    $(this).click();
                }
                /*
                if(hash == href) {
                $(this).click();
                }
                */
            });

            function clickHandler(e) {
                e.data.siblings.removeClass("active");
                e.data.parent.addClass("active");

                tabs.removeClass("active");
                e.data.targetTab.addClass("active");

                return false;
            }

            function buildNav() {
                var output = "";

                if (tabs.length > 0) {
                    output = "<ul class='navTabbedContent'>";

                    tabs.each(function(i) {
                        var id = $(this).attr("id");
                        var tabContent = $(this).children(content);
                        var tabTitle = $(this).children(title).css({ "position": "absolute", "left": "-999em" });

                        var cssClass = "";
                        if (i == 0) {
                            cssClass = "first";
                        }

                        output += buildListItem("#" + id, tabTitle.text(), cssClass);
                    });

                    output += "</ul>";
                }

                return output;
            }

            function buildListItem(href, text, cssClass) {
                var output = "";

                if (cssClass != "") {
                    output = "<li class='" + cssClass + "'>";
                }
                else {
                    output = "<li>";
                }
                output += "<a href='" + href + "'>" + text + "</a>";
                output += "</li>";

                return output;
            }

        });
    };

    // Open/Close drawers cotnaining content
    $.fn.toggleDrawer = function(options) {
        var opts = $.extend({
            content: '.content', // selector that contains the content to show/hide
            triggers: '.trigger', // selector that will toggle the open/close state
            toggleable: true, 	// determines whether the trigger can be used to close the drawer
            closeOthers: true, 	// should other open drawers be closed when a new one is opened?
            open: -1, 	// the item that should be open by default, counts from 0, -1 for none
            slide: true, 	// whether the drawer should slide open/closed or just 'pop' open
            speed: 200			// time in millesconds it takes to open and close the drawer. Only avaliable if slide: true
        }, options);

        var content = opts.content;
        var toggleable = opts.toggleable;
        var closeOthers = opts.closeOthers;
        var speed = opts.speed;
        var open = opts.open;
        var slide = opts.slide;

        if (jQuery.browser.version <= 418.8 && $.browser.safari) {
            slide = false;
        }

        return this.each(function(i) {
            var obj = $(this);
            var triggers = obj.find(opts.triggers);

            var contentObj = obj.find(content)

            if (contentObj.attr("style") == undefined || contentObj.attr("style") == "") {
                contentObj.hide();
            }

            if (open >= 0 && open <= obj.children().length) {
                obj.eq(i).addClass("open");
                obj.eq(i).children(content).show();
            }

            triggers.click(function() {
                var parent = $(this).parent();
                var content = opts.content;

                if (parent.hasClass("open") && toggleable) {
                    closeDrawer(parent);
                }
                else {
                    openDrawer(parent);
                }

                return false;
            });
        });

        function closeDrawer(drawers) {
            if (!slide) {
                drawers.children(content).hide();
                drawers.removeClass("open");
            } else {
                drawers.children(content).slideUp(speed, function() {
                    drawers.removeClass("open");
                });
            }
        }

        function openDrawer(drawers) {
            // Close siblings
            closeDrawer(drawers.siblings(".open"));

            if (!slide) {
                // Open current
                drawers.addClass("open");
                drawers.children(content).show();
            } else {
                // Open current
                drawers.addClass("open");
                drawers.children(content).slideDown(speed);
            }
        }
    };

    $.fn.traditionsGallery = function(options) {
        var opts = $.extend({
            itemsPerPage: 10	// number of items to be shown at one time
        }, options);

        return this.each(function() {
            var obj = $(this);
            var itemsPerPage = opts.itemsPerPage;

            var items = obj.children("li");
            var count = items.length;
            var currentPage = 1;
            var totalPages = Math.ceil(count / itemsPerPage);
            var increment = items.eq(0).outerHeight({ margin: true }) * 3;
            var totalHeight = increment * totalPages;

            obj.wrap("<div id='galleryWrapper'></div>")
				.wrap("<div id='galleryNavWrapper'></div>");

            var galleryWrapper = $("#galleryWrapper")
									.append("<a class='button disabled' href='#' id='prev'>Previous</a>")
									.append("<p id='counter'>Page of " + currentPage + " of " + totalPages + "</p>")
									.append("<a class='button' href='#' id='next'>Next</a>");

            $(this).find(".content").prepend("<div></div>");

            items.each(function(i) {
                var remainder = i % itemsPerPage;
                if (remainder == 0) {
                    $(this).addClass("first");
                }
                else if (remainder == 2 || remainder == 6) {
                    $(this).children(".content").addClass("alt");
                }
            });

            var curPos = 0;
            
            if (totalPages == 1) {
                $("#next").addClass("disabled");
            }

            galleryWrapper.children(".button").click(function() {
                var isDisbaled = $(this).hasClass("disabled");

                var id = $(this).attr("id");

                if (!isDisbaled && id == "prev") {
                    curPos = curPos + increment;
                    updateCounter(-1);
                }
                else if (!isDisbaled && id == "next") {
                    curPos = curPos - increment;
                    updateCounter(1);
                }

                if (curPos == 0) {
                    $("#prev").addClass("disabled");
                    $("#next").removeClass("disabled");
                }
                else if (Math.abs(curPos) == (totalHeight - increment)) {
                    $("#next").addClass("disabled");
                    $("#prev").removeClass("disabled");
                }
                else {
                    $("#prev, #next").removeClass("disabled");
                }

                if (!isDisbaled) {
                    //obj.stop().animate({top: curPos});
                    obj.fadeOut(800, function() {
                        obj.css("top", curPos + "px");
                        obj.fadeIn(1500);
                    });
                    clearActiveStates();
                }

                return false;
            });

            items.each(function() {
                $(this).bind(
					"mouseenter mouseleave",
					{},
					mouseEnterHandler);
                $(this).bind(
					"click",
					{
					    href: $(this).children("a").attr("href")
					},
					itemClickHandler)
            });


            function mouseEnterHandler() {
                if (!$(this).hasClass("active")) {
                    items.removeClass("active");
                    $(this).addClass("active");
                }
                else {
                    items.removeClass("active");
                }
            }

            function itemClickHandler(e) {
                window.location = e.data.href;
            }

            function clearActiveStates() {
                items.removeClass("active");
            }

            function updateCounter(i) {
                currentPage += i;
                $("#counter").text("Page of " + currentPage + " of " + totalPages);
            }
        });
    };

    $.fn.homeTabs = function() {
        var isIE6 = false;
        // IE6 doesn't behave well with the tabs navigation
        jQuery.each(jQuery.browser, function(i) {
            if ($.browser.msie && jQuery.browser.version <= "6.0") {
                isIE6 = true;
            }
        });

        return this.each(function() {
            var obj = $(this);

            obj.children("li").each(function() {

                $(this).children(".content").append("<a class='close' href='#'>Close</a>");

                $(".close").click(function() {
                    if (!isIE6) {
                        obj.stop().animate({
							height: "29px"
                        }, "", "", function() {
                            obj.removeClass("open");
                            obj.children("li").removeClass("open");
                        });
                    }
                    else {
						obj.css("height", "29px");
                        obj.removeClass("open");
                        obj.children("li").removeClass("open");
                    }
                    return false;
                });

                $(this).hover(
					function() {
					    if (!$(this).hasClass("open")) {
					        $(this).addClass("active");
					        $(this).append("<a class='highlight' href='#'>highlight</a>");

					        if (!obj.hasClass("open")) {
					            if (!isIE6) {
					                obj.stop().animate({
					                    height: "53px"
					                });
					            }
					            else {
					                obj.css("height", "53px");
					            }
					        }

					        $(".highlight").click(function() {
					            if (!obj.hasClass("open")) {
					                if (!isIE6) {
					                    obj.stop().animate({
					                        height: "350px"
					                    });
					                }
					                else {
					                    obj.css("height", "350px");
					                }
					            }
					            obj.addClass("open");
					            $(this).parent().addClass("open");
					            $(this).parent().siblings().removeClass("open");
					            $(".highlight").remove();
					            return false;
					        });
					    }
					},
					function() {
					    $(this).removeClass("active");
					    $(".highlight").remove();

					    if (!obj.hasClass("open")) {
					        if (!isIE6) {
					            obj.stop().animate({
									height: "29px"
					            });
					        }
					        else {
								obj.css("height", "29px");
					        }
					    }
					}
				);

            });
        });
    };












    // Toggle expansion of Link List module to view all links
    $.fn.expandMoreSuccess = function(options) {
        var opts = $.extend({
            moreLinkClass: 'moreLink',
            openStateClass: 'showAll',
            openStateText: 'More',
            closeStateText: 'Less'
        }, options);

        return this.each(function() {
            var obj = $(this);
            var links = obj.find("ul").find("li");

            // Create the More link
            if (links.length > 6) {
                var showAllClass = opts.openStateClass;

                obj.append("<p class='btm'><a class='" + opts.moreLinkClass + "' href='#'>" + opts.openStateText + "</a></p>");
                var moreLink = obj.find("." + opts.moreLinkClass);

                // Hide more than 3 links
                links.each(function(i) {
                    if (i > 5)
                        $(this).hide();
                });

                // Toggle state of all select fields on the page
                moreLink.toggle(
					function() {
					    // Show all links
					    links.show();
					    obj.addClass(showAllClass);
					    $(this).text(opts.closeStateText);
					},
					function() {
					    // Hide more than 3 links
					    links.each(function(i) {
					        if (i > 5)
					            $(this).hide();
					    });
					    obj.removeClass(showAllClass);
					    $(this).text(opts.openStateText);
					}
				);
            }
        });
    };
})(jQuery);



/*
* Thickbox 3.1 - One Box To Rule Them All.
* By Cody Lindley (http://www.codylindley.com)
* Copyright (c) 2007 cody lindley
* Licensed under the MIT License: http://www.opensource.org/licenses/mit-license.php
*/

var tb_pathToImage = "/styles/images/loadingAnimation.gif";
/*!!!!!!!!!!!!!!!!! edit below this line at your own risk !!!!!!!!!!!!!!!!!!!!!!!*/
//on page load call tb_init
$(document).ready(function() {
    tb_init('a.thickbox, area.thickbox, input.thickbox'); //pass where to apply thickbox
    imgLoader = new Image(); // preload image
    imgLoader.src = tb_pathToImage;
});
//add thickbox to href & area elements that have a class of .thickbox
function tb_init(domChunk) {
    $(domChunk).click(function() {
        var t = this.title || this.name || null;
        var a = this.href || this.alt;
        var g = this.rel || false;
        tb_show(t, a, g);
        this.blur();
        return false;
    });
}
function tb_show(caption, url, imageGroup) {//function called when the user clicks on a thickbox link
    try {
        if (typeof document.body.style.maxHeight === "undefined") {//if IE 6
            $("body", "html").css({ height: "100%", width: "100%" });
            $("html").css("overflow", "hidden");
            if (document.getElementById("TB_HideSelect") === null) {//iframe to hide select elements in ie6
                $("body").append("<iframe allowtransparency='true' background-color='transparent' id='TB_HideSelect'></iframe><div id='TB_overlay'></div><div id='TB_window'></div>");
                $("#TB_overlay").click(tb_remove);
            }
        } else {//all others
            if (document.getElementById("TB_overlay") === null) {
                $("body").append("<div id='TB_overlay'></div><div id='TB_window'></div>");
                $("#TB_overlay").click(tb_remove);
            }
        }

        if (tb_detectMacXFF()) {
            $("#TB_overlay").addClass("TB_overlayMacFFBGHack"); //use png overlay so hide flash
        } else {
            $("#TB_overlay").addClass("TB_overlayBG"); //use background and opacity
        }

        if (caption === null) { caption = ""; }
        $("body").append("<div id='TB_load'><img src='" + imgLoader.src + "' /></div>"); //add loader to the page
        $('#TB_load').show(); //show loader

        var baseURL;
        if (url.indexOf("?") !== -1) { //ff there is a query string involved
            baseURL = url.substr(0, url.indexOf("?"));
        } else {
            baseURL = url;
        }

        var urlString = /\.jpg$|\.jpeg$|\.png$|\.gif$|\.bmp$/;
        var urlType = baseURL.toLowerCase().match(urlString);
        if (urlType == '.jpg' || urlType == '.jpeg' || urlType == '.png' || urlType == '.gif' || urlType == '.bmp') {//code to show images

            TB_PrevCaption = "";
            TB_PrevURL = "";
            TB_PrevHTML = "";
            TB_NextCaption = "";
            TB_NextURL = "";
            TB_NextHTML = "";
            TB_imageCount = "";
            TB_FoundURL = false;
            if (imageGroup) {
                TB_TempArray = $("a[@rel=" + imageGroup + "]").get();
                for (TB_Counter = 0; ((TB_Counter < TB_TempArray.length) && (TB_NextHTML === "")); TB_Counter++) {
                    var urlTypeTemp = TB_TempArray[TB_Counter].href.toLowerCase().match(urlString);
                    if (!(TB_TempArray[TB_Counter].href == url)) {
                        if (TB_FoundURL) {
                            TB_NextCaption = TB_TempArray[TB_Counter].title;
                            TB_NextURL = TB_TempArray[TB_Counter].href;
                            TB_NextHTML = "<span id='TB_next'>&nbsp;&nbsp;<a href='#'>Next &gt;</a></span>";
                        } else {
                            TB_PrevCaption = TB_TempArray[TB_Counter].title;
                            TB_PrevURL = TB_TempArray[TB_Counter].href;
                            TB_PrevHTML = "<span id='TB_prev'>&nbsp;&nbsp;<a href='#'>&lt; Prev</a></span>";
                        }
                    } else {
                        TB_FoundURL = true;
                        TB_imageCount = "Image " + (TB_Counter + 1) + " of " + (TB_TempArray.length);
                    }
                }
            }
            imgPreloader = new Image();
            imgPreloader.onload = function() {
                imgPreloader.onload = null;

                // Resizing large images - orginal by Christian Montoya edited by me.
                var pagesize = tb_getPageSize();
                var x = pagesize[0] - 150;
                var y = pagesize[1] - 150;
                var imageWidth = imgPreloader.width;
                var imageHeight = imgPreloader.height;
                if (imageWidth > x) {
                    imageHeight = imageHeight * (x / imageWidth);
                    imageWidth = x;
                    if (imageHeight > y) {
                        imageWidth = imageWidth * (y / imageHeight);
                        imageHeight = y;
                    }
                } else if (imageHeight > y) {
                    imageWidth = imageWidth * (y / imageHeight);
                    imageHeight = y;
                    if (imageWidth > x) {
                        imageHeight = imageHeight * (x / imageWidth);
                        imageWidth = x;
                    }
                }
                // End Resizing

                TB_WIDTH = imageWidth + 30;
                TB_HEIGHT = imageHeight + 60;
                $("#TB_window").append("<a href='' id='TB_ImageOff' title='Close'><img id='TB_Image' src='" + url + "' width='" + imageWidth + "' height='" + imageHeight + "' alt='" + caption + "'/></a>" + "<div id='TB_caption'>" + caption + "<div id='TB_secondLine'>" + TB_imageCount + TB_PrevHTML + TB_NextHTML + "</div></div><div id='TB_closeWindow'><a href='#' id='TB_closeWindowButton' title='Close'>close</a> or Esc Key</div>");

                $("#TB_closeWindowButton").click(tb_remove);

                if (!(TB_PrevHTML === "")) {
                    function goPrev() {
                        if ($(document).unbind("click", goPrev)) { $(document).unbind("click", goPrev); }
                        $("#TB_window").remove();
                        $("body").append("<div id='TB_window'></div>");
                        tb_show(TB_PrevCaption, TB_PrevURL, imageGroup);
                        return false;
                    }
                    $("#TB_prev").click(goPrev);
                }

                if (!(TB_NextHTML === "")) {
                    function goNext() {
                        $("#TB_window").remove();
                        $("body").append("<div id='TB_window'></div>");
                        tb_show(TB_NextCaption, TB_NextURL, imageGroup);
                        return false;
                    }
                    $("#TB_next").click(goNext);

                }
                document.onkeydown = function(e) {
                    if (e == null) { // ie
                        keycode = event.keyCode;
                    } else { // mozilla
                        keycode = e.which;
                    }
                    if (keycode == 27) { // close
                        tb_remove();
                    } else if (keycode == 190) { // display previous image
                        if (!(TB_NextHTML == "")) {
                            document.onkeydown = "";
                            goNext();
                        }
                    } else if (keycode == 188) { // display next image
                        if (!(TB_PrevHTML == "")) {
                            document.onkeydown = "";
                            goPrev();
                        }
                    }
                };

                tb_position();
                $("#TB_load").remove();
                $("#TB_ImageOff").click(tb_remove);
                $("#TB_window").css({ display: "block" }); //for safari using css instead of show
            };

            imgPreloader.src = url;
        } else {//code to show html

            var queryString = url.replace(/^[^\?]+\??/, '');
            var params = tb_parseQuery(queryString);
            TB_WIDTH = (params['width'] * 1) + 30 || 630; //defaults to 630 if no paramaters were added to URL
            TB_HEIGHT = (params['height'] * 1) + 40 || 440; //defaults to 440 if no paramaters were added to URL
            ajaxContentW = TB_WIDTH - 30;
            ajaxContentH = TB_HEIGHT - 45;

            if (url.indexOf('TB_iframe') != -1) {// either iframe or ajax window    
                urlNoQuery = url.split('TB_');
                $("#TB_iframeContent").remove();
                if (params['modal'] != "true") {//iframe no modal
                    $("#TB_window").append("<div id='TB_title'><div id='TB_ajaxWindowTitle'>" + caption + "</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton' title='Close'>close</a> or Esc Key</div></div><iframe allowtransparency='true' background-color='transparent' frameborder='0' hspace='0' src='" + urlNoQuery[0] + "' id='TB_iframeContent' name='TB_iframeContent" + Math.round(Math.random() * 1000) + "' onload='tb_showIframe()' style='width:" + (ajaxContentW + 29) + "px;height:" + (ajaxContentH + 17) + "px;' > </iframe>");
                } else {//iframe modal
                    $("#TB_overlay").unbind();
                    $("#TB_window").append("<iframe allowtransparency='true' background-color='transparent' frameborder='0' hspace='0' src='" + urlNoQuery[0] + "' id='TB_iframeContent' name='TB_iframeContent" + Math.round(Math.random() * 1000) + "' onload='tb_showIframe()' style='width:" + (ajaxContentW + 29) + "px;height:" + (ajaxContentH + 17) + "px;'> </iframe>");
                }
            } else {// not an iframe, ajax
                if ($("#TB_window").css("display") != "block") {
                    if (params['modal'] != "true") {//ajax no modal
                        $("#TB_window").append("<div id='TB_title'><div id='TB_ajaxWindowTitle'>" + caption + "</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton'>close</a> or Esc Key</div></div><div id='TB_ajaxContent' style='width:" + ajaxContentW + "px;height:" + ajaxContentH + "px'></div>");
                    } else {//ajax modal
                        $("#TB_overlay").unbind();
                        $("#TB_window").append("<div id='TB_ajaxContent' class='TB_modal' style='width:" + ajaxContentW + "px;height:" + ajaxContentH + "px;'></div>");
                    }
                } else {//this means the window is already up, we are just loading new content via ajax
                    $("#TB_ajaxContent")[0].style.width = ajaxContentW + "px";
                    $("#TB_ajaxContent")[0].style.height = ajaxContentH + "px";
                    $("#TB_ajaxContent")[0].scrollTop = 0;
                    $("#TB_ajaxWindowTitle").html(caption);
                }
            }

            $("#TB_closeWindowButton").click(tb_remove);

            if (url.indexOf('TB_inline') != -1) {
                $("#TB_ajaxContent").append($('#' + params['inlineId']).children());
                $("#TB_window").unload(function() {
                    $('#' + params['inlineId']).append($("#TB_ajaxContent").children()); // move elements back when you're finished
                });
                tb_position();
                $("#TB_load").remove();
                $("#TB_window").css({ display: "block" });
            } else if (url.indexOf('TB_iframe') != -1) {
                tb_position();
                if ($.browser.safari) {//safari needs help because it will not fire iframe onload
                    $("#TB_load").remove();
                    $("#TB_window").css({ display: "block" });
                }
            } else {
                $("#TB_ajaxContent").load(url += "&random=" + (new Date().getTime()), function() {//to do a post change this load method
                    tb_position();
                    $("#TB_load").remove();
                    tb_init("#TB_ajaxContent a.thickbox");
                    $("#TB_window").css({ display: "block" });
                });
            }

        }
        if (!params['modal']) {
            document.onkeyup = function(e) {
                if (e == null) { // ie
                    keycode = event.keyCode;
                } else { // mozilla
                    keycode = e.which;
                }
                if (keycode == 27) { // close
                    tb_remove();
                }
            };
        }

    } catch (e) {
        //nothing here
    }
}
//helper functions below
function tb_showIframe() {
    $("#TB_load").remove();
    $("#TB_window").css({ display: "block" });
}
function tb_remove() {
    $("#TB_imageOff").unbind("click");
    $("#TB_closeWindowButton").unbind("click");
    $("#TB_window").fadeOut("fast", function() { $('#TB_window,#TB_overlay,#TB_HideSelect').trigger("unload").unbind().remove(); });
    $("#TB_load").remove();
    if (typeof document.body.style.maxHeight == "undefined") {//if IE 6
        $("body", "html").css({ height: "auto", width: "auto" });
        $("html").css("overflow", "");
    }
    document.onkeydown = "";
    document.onkeyup = "";
    return false;
}
function tb_position() {
    $("#TB_window").css({ marginLeft: '-' + parseInt((TB_WIDTH / 2), 10) + 'px', width: TB_WIDTH + 'px' });
    if (!(jQuery.browser.msie && jQuery.browser.version < 7)) { // take away IE6
        $("#TB_window").css({ marginTop: '-' + parseInt((TB_HEIGHT / 2), 10) + 'px' });
    }
}
function tb_parseQuery(query) {
    var Params = {};
    if (!query) { return Params; } // return empty object
    var Pairs = query.split(/[;&]/);
    for (var i = 0; i < Pairs.length; i++) {
        var KeyVal = Pairs[i].split('=');
        if (!KeyVal || KeyVal.length != 2) { continue; }
        var key = unescape(KeyVal[0]);
        var val = unescape(KeyVal[1]);
        val = val.replace(/\+/g, ' ');
        Params[key] = val;
    }
    return Params;
}
function tb_getPageSize() {
    var de = document.documentElement;
    var w = window.innerWidth || self.innerWidth || (de && de.clientWidth) || document.body.clientWidth;
    var h = window.innerHeight || self.innerHeight || (de && de.clientHeight) || document.body.clientHeight;
    arrayPageSize = [w, h];
    return arrayPageSize;
}
function tb_detectMacXFF() {
    var userAgent = navigator.userAgent.toLowerCase();
    if (userAgent.indexOf('mac') != -1 && userAgent.indexOf('firefox') != -1) {
        return true;
    }
}



