function seatSelectBookingOptions(bookingOptionElements) {

    function disable() {
        var buttons = bookingOptionElements.find('.primary-button');
        buttons.removeClass('primary-button').addClass('disabled-button');
        buttons.attr('disabled', 'disabled');

    }

    function enable() {
        var buttons = bookingOptionElements.find('.disabled-button');
        buttons.removeClass('disabled-button').addClass('primary-button');
        buttons.removeAttr('disabled');
    }

    return {disable : disable,
        enable: enable};
}



function BookingOptions() {
    var bestAvailableContainer = $('#best-available-booking-option');
    var syosContainer = $('#syos-booking-option');
    var loader = bestAvailableContainer.find('div.loader');
    var loaderSyos = syosContainer.find('div.loader');
    var syosNotice = $("#syos-booking-option .notice");
    this.init = function() {
        attachSelectYourOwnSeatEvents();
        attachBestAvailableEvents();
        attachChoosePerformance();
    };

    function attachSelectYourOwnSeatEvents() {
        $("#select_your_own_seat_link").click(function(e) {
            loaderSyos.addClass('ajax-loader-small');
            var parentForm = $(this).parent();
            var link = parentForm.attr('action');
            parentForm.attr('action', link.replace('performance_id', $("#performance-date").val()));
        });
    }

    function attachChoosePerformance() {
        $("#performance-date").live("change", (function(e) {
            $('.best-available-booking-option-content').html('');
            $('.best-available-booking-option-footer').hide();
            showDescriptionAndContinueLink();
        }));
    }

    function attachBestAvailableEvents() {
        var continueLink = bestAvailableContainer.find('#best-available-details #best_available_continue_button');

        continueLink.click(function(e)
        {
            e.preventDefault();
            loader.addClass('ajax-loader-small');
            getZonePriceDetails($(this).parent().attr("action"));
            return false;
        });
    }

    function getZonePriceDetails(link) {
        var zonePriceLink = link.replace('performance_id', $("#performance-date").val());
        var useCache = $.cookie("promotion_code") === null;
        zonePriceLink += (useCache ? "" : "?cache=false");
        $.ajax({
            url: zonePriceLink,
            success: function(data) {
                $('.best-available-booking-option-content').html(data);

                var bestAvailableBookingOption = new BestAvailableBookingOption(bestAvailableContainer);
                bestAvailableBookingOption.init();

                hideDescriptionAndContinueLink();
            },
            error: function(xhr) {
                var errorMsg = xhr.getResponseHeader("ErrorMsg");
                (new ErrorDialog()).show(errorMsg || "Error getting best available pricing zones.");
            },
            complete: function() {
                loader.removeClass('ajax-loader-small');
            }
        });
    }

    function showDescriptionAndContinueLink() {
        bestAvailableContainer.children('div#best-available-details').show();
    }

    function hideDescriptionAndContinueLink() {
        bestAvailableContainer.children('div#best-available-details').hide();
    }
}

function BestAvailableBookingOption(bestAvailableContainer)
{
    var zonePriceSelectionContainer = bestAvailableContainer.find('div#zone-selection');
    var addToCartButton = bestAvailableContainer.find('#add-to-cart-button');
    var errorMessageDiv = bestAvailableContainer.find("#add-to-cart-error");
    var captcha = new Captcha("#recaptcha-container");

    var loader = bestAvailableContainer.find('div#loader');
    var errorMessageDialog;

    var noSeatSelectedMessage = "Please specify a number of seats.";
    var moreThanAllowedSeatsSelectedMessage = "You cannot select more than 12 seats total.";
    var emptyCaptchaMessage = "For security purposes, you must enter the characters in the box above";
    var bestAvailableOption;

    this.init = function() {
        bestAvailableContainer.find('.best-available-booking-option-footer').show();
        attachAddToCart();
        errorMessageDialog = new ModalDialog(errorMessageDiv, function(element) {
            return {
                autoOpen: false,
                minHeight: 20,
                title: "We're Sorry!",
                dialogClass: 'seat-error-dialog'
            };
        });

        bestAvailableOption = new BestAvailableOption(bestAvailableContainer);
        bestAvailableOption.updateBestAvailableSelectionView();
    };

    function attachAddToCart() {
        addToCartButton.unbind('click');
        addToCartButton.bind('click', function(e) {
            if (!isValidSeatSelection() || !isValidCaptcha()) {
                return;
            }

            var seatsSelection = [];
            $.each(bestAvailableOption.selectedSeats(), function(index, row) {
                var numberOfSeats = row[1];
                var priceTypeId = row[0];
                if (numberOfSeats !== 0) {
                    seatsSelection.push({'no_of_seats': numberOfSeats,'price_type_id': priceTypeId });
                }
            });

            var zoneId = zonePriceSelectionContainer.find('select#zone-selector').val();
            var requestData = {'best_available_selection' :
            {'zone_id' : zoneId ,
                'performance_id': $("#performance-date").val(),
                'seat_selection_by_price_type' :seatsSelection
            },
                'production_id': CONVOY.application.production.production_id
            };

            $.extend(requestData, captcha.requestData());

            disableAddToCartButton();
            showLoader($("#selection-action .loader-small"));

            $.ajax({
                url: '/performance/reserve_best_available_seats',
                type: 'POST',
                data: requestData,
                success: function(data, status, xhr) {
                    handleSuccess(data, xhr);
                },
                error: function(xhr) {
                    handleFailure(xhr);
                }
            });
        });
    }

    function handleSuccess(data, xhr)
    {
        var url = xhr.getResponseHeader("BrowserRedirectTo");
        if (!!url) {
            $(location).attr('href', url);
        }
        else {
            hideLoader($("#selection-action .loader-small"));
            var waitTime = parseInt(xhr.getResponseHeader("WaitDuration"), 10);
            var token = xhr.getResponseHeader("ActiveUserToken");
            (new WaitingRoom(data, token)).wait(waitTime, waitTimeOver);
        }
    }

    function waitTimeOver() {
        enableAddToCartButton();
        hideLoader($("#selection-action .loader-small"));
        addToCartButton.click();
    }

    function handleFailure(xhr) {
        var errorMessage = xhr.getResponseHeader("ErrorMsg");
        hideLoader($("#selection-action .loader-small"));
        displayErrorMessage(errorMessage);
        enableAddToCartButton();
        captcha.reload();
    }

    function disableAddToCartButton() {
        addToCartButton.removeClass('primary-button').addClass('disabled-button');
        addToCartButton.attr('disabled', 'disabled');
    }

    function showLoader(loader) {
        loader.addClass('ajax-loader-small');
    }

    function hideLoader(loader) {
        loader.removeClass('ajax-loader-small');
    }

    function enableAddToCartButton() {
        addToCartButton.removeClass('disabled-button').addClass('primary-button');
        addToCartButton.removeAttr('disabled');
    }

    function isValidSeatSelection() {
        var totalSeats = totalSeatsSelected();
        if (totalSeats > 0 && totalSeats <= 12) {
            return true;
        }
        if (totalSeats === 0) {
            displayErrorMessage(noSeatSelectedMessage);
        }
        if (totalSeats > 12) {
            displayErrorMessage(moreThanAllowedSeatsSelectedMessage);
        }
        return false;
    }

    function isValidCaptcha() {
        if (!captcha.isValid()) {
            displayErrorMessage(emptyCaptchaMessage);
            return false;
        }
        return true;
    }

    function displayErrorMessage(msg) {
        errorMessageDialog.show(msg);
    }

    function totalSeatsSelected() {
        return bestAvailableOption.seatCount();
    }
}


function BestAvailableOption(container) {
    this.updateBestAvailableSelectionView = function() {
        attachOnChangeZoneSelectDisplayPriceTypes();
        this.updatePriceTypesForZone(0);
    };

    function showPriceTypesFor(zoneId) {
        var zonePriceSelectionContainer = container.find('div#zone-selection');
        var zonePriceDetails = zonePriceSelectionContainer.find('#selection-row0');
        zonePriceSelectionContainer.find(".zone-price-details").hide();
        zonePriceSelectionContainer.find("#zone-price-details-" + zoneId).show();
    }

    function attachOnChangeZoneSelectDisplayPriceTypes() {
        container.find('select#zone-selector').live('change', function(e) {
            var zoneId = parseInt($(this).val(), 10);
            self.updatePriceTypesForZone(zoneId);
        });
    }

    function displayErrorMessage(message) {
        errorMessageDialog.show(message);
    }

    function disableAddToCartButton() {
        addToCartButton.removeClass('primary-button').addClass('disabled-button');
        addToCartButton.attr('disabled', 'disabled');
    }

    function enableAddToCartButton() {
        addToCartButton.removeClass('disabled-button').addClass('primary-button');
        addToCartButton.removeAttr('disabled');
    }

    this.updatePriceTypesForZone = function(zoneId) {
        container.find("#zone-price-type").show();

        showPriceTypesFor(zoneId);
        var priceTypes = container.find("#zone-selection #zone-price-details-" + zoneId).find('select').length;
        if (priceTypes > 0) {
            $('#recaptcha-container').show();
            enableAddToCartButton();
        }
        else {
            $('#recaptcha-container').hide();
            displayErrorMessage(seatsSoldOutMessage);
            disableAddToCartButton();
        }
    };

    this.seatCount = function() {
        var seatsCount = 0;
        $.each(this.selectedSeats(), function(index, value) {
            seatsCount += value[1];
        });
        return seatsCount;
    };

    this.selectedSeats = function() {
        var zoneId = container.find('select#zone-selector').val();
        var seats = [];
        container.find("#zone-selection #zone-price-details-" + zoneId).find('select').each(function(value, element) {
            var seat = [];
            seat.push($(element).closest('.selection-row').attr('price_type_id'));
            seat.push(parseInt($(element).val(), 10));
            seats.push(seat);
        });
        return seats;
    };

    var self = this;

    var seatsSoldOutMessage = "Seats for the selected location are sold out. Please select another location.";
    var addToCartButton = container.find('#add-to-cart-button');
    var errorMessageDiv = container.find("#add-to-cart-error");
    var errorMessageDialog = new ModalDialog(errorMessageDiv, function(element) {
        return {
            autoOpen: false,
            minHeight: 20,
            title: "We're Sorry!",
            dialogClass: 'seat-error-dialog'
        };
    });
}

(function($) {
    $(function() {
        var performancesTable = function(element) {

            var performanceTableElement = element;

            function init() {
                attachEvents();
                getPerformancesForPage(getPaginationLink(1));
            }

            function showPerformancesLoader() {
                showLoader($('.performance-table'));
            }

            function getPerformancesForPage(pageLink) {
                showPerformancesLoader();
                $.ajax({
                    url: pageLink,
                    success: function(data) {
                        var dataObject = $(data);
                        updatePromoCodeApplicableMessage(dataObject.find("#performance-message-hidden"));
                        updateAvailableOnSalePerformances(dataObject.find("#available-performances"));
                        performanceTableElement.html(dataObject);
                        attachEvents();
                        selectPerformanceBasedOnFragment();
                    }
                });
            }

            function updatePromoCodeApplicableMessage(selectionMessage) {
                $('#performance-message').html(selectionMessage.html());
                selectionMessage.remove();
            }

            function updateAvailableOnSalePerformances(performancesSelectData) {
                var seatSelectionOptions = seatSelectBookingOptions($('div#booking-options .booking-option'));
                var performancesAvailable = performancesSelectData.find("select#performance-date").length > 0;
                $('div#available-performances').html(performancesSelectData.html());

                if (performancesAvailable) {
                    seatSelectionOptions.enable();
                }
                else {
                    seatSelectionOptions.disable();
                    $(".performance-message").html(performancesSelectData.html());
                }

                performancesSelectData.remove();
            }

            function getPaginationLink(pageNumber) {
                var promotionCode = $.cookie("promotion_code");
                var promotionCodeQueryString = promotionCode ? ("&promotion_code=" + promotionCode) : "";
                return "/production/" + CONVOY.application.production.production_id + "/list_performances?page=" +
                       pageNumber + promotionCodeQueryString;
            }

            function attachEvents() {
                attachPaginationToPageLinks();
                attachViewAllBehaviour();
                attachPerformanceBuyEvents();
                hideLoader($('.performance-table'));
                performanceTableElement.attr('loaded', 'true');
                applyPaginationSeparator();
            }

            function clickablePaginationLinks() {
                return performanceTableElement.find('.pagination a');
            }

            function attachViewAllBehaviour() {
                performanceTableElement.find(".view-all").click(function(e) {
                    e.preventDefault();
                    showPerformancesLoader();
                    getPerformancesForPage($(this).attr('href'));
                    return false;
                });
            }

            function attachPaginationToPageLinks() {
                var clickablePagination = clickablePaginationLinks();
                clickablePagination.each(function() {
                    element = $(this);
                    var results = new RegExp('[\\?&]page=([^&#]*)').exec(element.attr('href'));
                    var pageNumber = results[1] || 1;
                    element.attr('href', getPaginationLink(pageNumber));
                });

                clickablePagination.click(function(e) {
                    e.preventDefault();
                    showPerformancesLoader();
                    getPerformancesForPage($(this).attr('href'));
                    return false;
                });
            }

            function buyTicketLinks() {
                return performanceTableElement.find('input.buy-button');
            }

            function attachPerformanceBuyEvents() {
                buyTicketLinks().click(function(e) {
                    var performance_id = $(this).attr('performance');

                    $.bbq.pushState({
                        tab: 'buy_tickets',
                        performance: performance_id });
                });
            }

            function paginationLinksAbove() {
                return performanceTableElement.find('div#pagination_links_container_above').children();
            }

            function paginationLinksBelow() {
                return performanceTableElement.find('div#pagination_links_container_below').children();
            }

            function applyPaginationSeparator()
            {
                applyPaginationStyle(paginationLinksAbove());
                applyPaginationStyle(paginationLinksBelow());
            }

            function applyPaginationStyle(paginationLinks)
            {
                var filteredLinks = paginationLinks.slice(1, paginationLinks.length - 2);
                filteredLinks.each(function() {
                    $(this).addClass('pagination-separator');
                });
            }

            return {
                init : init,
                showPerformancesLoader : showPerformancesLoader
            };

        }($('.performance-table'));

        $(document).ready(function() {
            $("#tabs").tabs({
                event: 'change' //disable auto tabbing
            });
            $("#tabs .tab a").click(function() {
                var selected_tab = $(this).parent().attr('id');
                $.bbq.pushState({tab: selected_tab});
            });

            if ($('.performance-table').attr('loaded') == 'false') {
                performancesTable.init();
            }

            var bookingOptions = new BookingOptions();
            bookingOptions.init();
        });
    });
})(jQuery);


function initSeatingChartDialog() {

    $("#view-seating-chart").live("click", function(e) {
        e.preventDefault();
        var dialog = $("#seating-chart").dialog({
            autoOpen: false,
            title: 'Seating Chart',
            width: 424,
            resizable: false
        });
        dialog.dialog('open');
        return false;
    });
}


function changeSelectedPerformance(performance_id) {
  var performanceDropDown = $("#performance-date option[value='" + performance_id + "']");
  performanceDropDown.attr('selected', 'selected');
  performanceDropDown.change();
}

function selectPerformanceBasedOnFragment() {
  var performance_id = $.bbq.getState('performance');
  if( !performance_id ) {
    return;
  }

  changeSelectedPerformance(performance_id);
}

function showTab(tab_id)
{
  var index = $('#tabs li').index($('#' + tab_id));
  var tabs = $("#tabs").tabs();
  tabs.tabs('select', index);
}

function selectTabBasedOnFragment() {
  var tab = $.bbq.getState('tab') || 'overview';
  showTab(tab);
}


function initBBQ() {
  $(window).bind( 'hashchange', function(e) {
    selectPerformanceBasedOnFragment();
    selectTabBasedOnFragment();
  });

  // fire an initial event to handle any #params in the request we just loaded
  $(window).trigger('hashchange');
}


(function($) {
    $(function() {
        var promotion = new Promotion($("#promotion-form"));
        promotion.init();
        initSeatingChartDialog();

        initBBQ();
    });
})(jQuery);


function AjaxForm(form) {

    var self = this;

    this.submitWithoutValidation = function(onSuccess, onError, onComplete) {
        if (onError === undefined) {
            onError = function() {};
        }
        if (onComplete === undefined) {
            onComplete = function() {};
        }

        form.find(".loader").addClass('ajax-loader');
        form.find(".loader-small").addClass('ajax-loader-small');
        $.ajax({
            type: "POST",
            url: form.find('input[name=submit_url]').attr('value'),
            data: form.serialize(),
            success: onSuccess,
            error: function(data) {
                form.find(".loader").removeClass('ajax-loader');
                form.find(".loader-small").removeClass('ajax-loader-small');
                form.find('.continue').attr('disabled', false);
                onError(data);
            },
            complete: onComplete
        });
        form.find('.continue').attr('disabled', 'disabled');
        return true;
    };

    this.submit = function(onSuccess, onError,onComplete) {
        if (!form.valid()) { return true; }
        return self.submitWithoutValidation(onSuccess, onError, onComplete);
    };

}

function PromotionFormValidator(promotionForm, errorContainer)
{
    var errorMessage = "The promotion code you have entered is invalid. Please try again.";
    var validationRules = {
        rules :{
            "promotion_code": {
                required: true
            }
        },
        messages:{
            "promotion_code": {
                required: errorMessage
            }
        },
        errorPlacement: function(error) {
            errorContainer.showError(error);
        },
        success: function(){
            errorContainer.hideError();
        }
    };

    this.init = function()
    {
        promotionForm.validate(validationRules);
    };

}


function PromotionErrorContainer(errorContainer) {

    function showError(errorMessage) {
        var errorMessageDiv = errorContainer.find(".error");
        errorMessageDiv.html(errorMessage);
        errorContainer.removeClass('invisible');
    }

    function hideError() {
        errorContainer.addClass('invisible');
    }

    return { showError : showError, hideError: hideError};
}

function Promotion(formElement) {
    var errorContainer = $(".error-container");
    errorContainer.addClass('invisible');
    var buttonElement = formElement.find("#add-promo-code");
    var promotionErrorContainer = new PromotionErrorContainer(errorContainer);

    this.init = function() {

        (new PromotionFormValidator(formElement, promotionErrorContainer)).init();

        formElement.submit(function() {
            if(!formElement.valid())
            {return false;}
            buttonElement.removeClass("promo-code-button");
            errorContainer.addClass('invisible');
            var form = new AjaxForm(formElement);
            form.submit(OnSuccess, OnError, OnComplete);
            return false;
        });

        buttonElement.click(function() {
            formElement.submit();
        });
    };

    function OnSuccess(data, status, xhr) {
        var url = xhr.getResponseHeader("BrowserRedirectTo");
        if (url) {
            window.location.reload(false);
        }
    }

    function OnError(xhr) {
        var errorMessage = xhr.getResponseHeader("ErrorMsg");
        promotionErrorContainer.showError(errorMessage);
    }

    function OnComplete() {
        buttonElement.addClass("promo-code-button");
    }
}

function WaitingRoom(messageHtml, token) {

    var timeoutId;
    var closedByTimeout = false;

    function waitingRoomDialogParameters(element) {
        return {
            width: 500,
            title: "Waiting Room...",
            modal: true,
            position: "center",
            draggable: false,
            dialogClass: 'waiting-room',
            resizable: false,
            autoOpen: false,
            close: dialogClose
        };
    }

    this.wait = function(durationInSeconds, callback) {
        dialog.show(messageHtml);
        timeoutId = setTimeout(function() {
            onTimeout(callback);
        }, durationInSeconds * 1000);
    };

    function onTimeout(callback) {
        closedByTimeout = true;
        dialog.close();
        setToken();
        callback();
    }

    function dialogClose() {
        clearTimeout(timeoutId);
        if (timeoutId && !closedByTimeout) {
            reloadPage();
        }
    }

    function reloadPage() {
        window.location.reload(false);
    }

    function setToken() {
        $.cookie("first_time_with_token", token, { path : "/" });
    }

    var dialog = new ModalDialog($("#add-to-cart-button"), waitingRoomDialogParameters);

}

function Captcha(element) {
    var self = this;
    var challengeFieldSelector = "#recaptcha_challenge_field";
    var responseFieldSelector = "#recaptcha_response_field";

    self.challengeValue = function() {
        return $(element).find(challengeFieldSelector).val();
    };

    self.responseValue = function() {
        return $(element).find(responseFieldSelector).val();
    };

    self.visible = function() {
        return ($(element).length > 0);
    };

    self.requestData = function() {
        requestHash = {};
        if(this.visible()) {
            $.extend(requestHash, {
                'recaptcha_challenge_field': this.challengeValue(),
                'recaptcha_response_field': this.responseValue()
            });
        }
        return requestHash;
    };

    self.isValid = function() {
        if(this.visible()) {
            return this.responseValue().length > 0;
        }
        return true;
    };

    self.reload = function() {
        if(Recaptcha) {
            Recaptcha.reload();
        }
    };

}

/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

/**
 * Create a cookie with the given name and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
 *       used when the cookie was set.
 *
 * @param String name The name of the cookie.
 * @param String value The value of the cookie.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * Get the value of a cookie with the given name.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String name The name of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

/*
 * jQuery BBQ: Back Button & Query Library - v1.2.1 - 2/17/2010
 * http://benalman.com/projects/jquery-bbq-plugin/
 *
 * Copyright (c) 2010 "Cowboy" Ben Alman
 * Dual licensed under the MIT and GPL licenses.
 * http://benalman.com/about/license/
 */
(function($, p) {
    var i,m = Array.prototype.slice,r = decodeURIComponent,a = $.param,c,l,v,b = $.bbq = $.bbq || {},q,u,j,e = $.event.special,d = "hashchange",A = "querystring",D = "fragment",y = "elemUrlAttr",g = "location",k = "href",t = "src",x = /^.*\?|#.*$/g,w = /^.*\#/,h,C = {};

    function E(F) {
        return typeof F === "string"
    }

    function B(G) {
        var F = m.call(arguments, 1);
        return function() {
            return G.apply(this, F.concat(m.call(arguments)))
        }
    }

    function n(F) {
        return F.replace(/^[^#]*#?(.*)$/, "$1")
    }

    function o(F) {
        return F.replace(/(?:^[^?#]*\?([^#]*).*$)?.*/, "$1")
    }

    function f(H, M, F, I, G) {
        var O,L,K,N,J;
        if (I !== i) {
            K = F.match(H ? /^([^#]*)\#?(.*)$/ : /^([^#?]*)\??([^#]*)(#?.*)/);
            J = K[3] || "";
            if (G === 2 && E(I)) {
                L = I.replace(H ? w : x, "")
            } else {
                N = l(K[2]);
                I = E(I) ? l[H ? D : A](I) : I;
                L = G === 2 ? I : G === 1 ? $.extend({}, I, N) : $.extend({}, N, I);
                L = a(L);
                if (H) {
                    L = L.replace(h, r)
                }
            }
            O = K[1] + (H ? "#" : L || !K[1] ? "?" : "") + L + J
        } else {
            O = M(F !== i ? F : p[g][k])
        }
        return O
    }

    a[A] = B(f, 0, o);
    a[D] = c = B(f, 1, n);
    c.noEscape = function(G) {
        G = G || "";
        var F = $.map(G.split(""), encodeURIComponent);
        h = new RegExp(F.join("|"), "g")
    };
    c.noEscape(",/");
    $.deparam = l = function(I, F) {
        var H = {},G = {"true":!0,"false":!1,"null":null};
        $.each(I.replace(/\+/g, " ").split("&"), function(L, Q) {
            var K = Q.split("="),P = r(K[0]),J,O = H,M = 0,R = P.split("]["),N = R.length - 1;
            if (/\[/.test(R[0]) && /\]$/.test(R[N])) {
                R[N] = R[N].replace(/\]$/, "");
                R = R.shift().split("[").concat(R);
                N = R.length - 1
            } else {
                N = 0
            }
            if (K.length === 2) {
                J = r(K[1]);
                if (F) {
                    J = J && !isNaN(J) ? +J : J === "undefined" ? i : G[J] !== i ? G[J] : J
                }
                if (N) {
                    for (; M <= N; M++) {
                        P = R[M] === "" ? O.length : R[M];
                        O = O[P] = M < N ? O[P] || (R[M + 1] && isNaN(R[M + 1]) ? {} : []) : J
                    }
                } else {
                    if ($.isArray(H[P])) {
                        H[P].push(J)
                    } else {
                        if (H[P] !== i) {
                            H[P] = [H[P],J]
                        } else {
                            H[P] = J
                        }
                    }
                }
            } else {
                if (P) {
                    H[P] = F ? i : ""
                }
            }
        });
        return H
    };
    function z(H, F, G) {
        if (F === i || typeof F === "boolean") {
            G = F;
            F = a[H ? D : A]()
        } else {
            F = E(F) ? F.replace(H ? w : x, "") : F
        }
        return l(F, G)
    }

    l[A] = B(z, 0);
    l[D] = v = B(z, 1);
    $[y] || ($[y] = function(F) {
        return $.extend(C, F)
    })({a:k,base:k,iframe:t,img:t,input:t,form:"action",link:k,script:t});
    j = $[y];
    function s(I, G, H, F) {
        if (!E(H) && typeof H !== "object") {
            F = H;
            H = G;
            G = i
        }
        return this.each(function() {
            var L = $(this),J = G || j()[(this.nodeName || "").toLowerCase()] || "",K = J && L.attr(J) || "";
            L.attr(J, a[I](K, H, F))
        })
    }

    $.fn[A] = B(s, A);
    $.fn[D] = B(s, D);
    b.pushState = q = function(I, F) {
        if (E(I) && /^#/.test(I) && F === i) {
            F = 2
        }
        var H = I !== i,G = c(p[g][k], H ? I : {}, H ? F : 2);
        p[g][k] = G + (/#/.test(G) ? "" : "#")
    };
    b.getState = u = function(F, G) {
        return F === i || typeof F === "boolean" ? v(F) : v(G)[F]
    };
    b.removeState = function(F) {
        var G = {};
        if (F !== i) {
            G = u();
            $.each($.isArray(F) ? F : arguments, function(I, H) {
                delete G[H]
            })
        }
        q(G, 2)
    };
    e[d] = $.extend(e[d], {add:function(F) {
        var H;

        function G(J) {
            var I = J[D] = c();
            J.getState = function(K, L) {
                return K === i || typeof K === "boolean" ? l(I, K) : l(I, L)[K]
            };
            H.apply(this, arguments)
        }

        if ($.isFunction(F)) {
            H = F;
            return G
        } else {
            H = F.handler;
            F.handler = G
        }
    }})
})(jQuery, this);
/*
 * jQuery hashchange event - v1.2 - 2/11/2010
 * http://benalman.com/projects/jquery-hashchange-plugin/
 *
 * Copyright (c) 2010 "Cowboy" Ben Alman
 * Dual licensed under the MIT and GPL licenses.
 * http://benalman.com/about/license/
 */
(function($, i, b) {
    var j,k = $.event.special,c = "location",d = "hashchange",l = "href",f = $.browser,g = document.documentMode,h = f.msie && (g === b || g < 8),e = "on" + d in i && !h;

    function a(m) {
        m = m || i[c][l];
        return m.replace(/^[^#]*#?(.*)$/, "$1")
    }

    $[d + "Delay"] = 100;
    k[d] = $.extend(k[d], {setup:function() {
        if (e) {
            return false
        }
        $(j.start)
    },teardown:function() {
        if (e) {
            return false
        }
        $(j.stop)
    }});
    j = (function() {
        var m = {},r,n,o,q;

        function p() {
            o = q = function(s) {
                return s
            };
            if (h) {
                n = $('<iframe src="javascript:0"/>').hide().insertAfter("body")[0].contentWindow;
                q = function() {
                    return a(n.document[c][l])
                };
                o = function(u, s) {
                    if (u !== s) {
                        var t = n.document;
                        t.open().close();
                        t[c].hash = "#" + u
                    }
                };
                o(a())
            }
        }

        m.start = function() {
            if (r) {
                return
            }
            var t = a();
            o || p();
            (function s() {
                var v = a(),u = q(t);
                if (v !== t) {
                    o(t = v, u);
                    $(i).trigger(d)
                } else {
                    if (u !== t) {
                        i[c][l] = i[c][l].replace(/#.*/, "") + "#" + u
                    }
                }
                r = setTimeout(s, $[d + "Delay"])
            })()
        };
        m.stop = function() {
            if (!n) {
                r && clearTimeout(r);
                r = 0
            }
        };
        return m
    })()
})(jQuery, this);

jQuery.url=function(){var segments={};var parsed={};var options={url:window.location,strictMode:false,key:["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],q:{name:"queryKey",parser:/(?:^|&)([^&=]*)=?([^&]*)/g},parser:{strict:/^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,loose:/^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/}};var parseUri=function(){str=decodeURI(options.url);var m=options.parser[options.strictMode?"strict":"loose"].exec(str);var uri={};var i=14;while(i--){uri[options.key[i]]=m[i]||""}uri[options.q.name]={};uri[options.key[12]].replace(options.q.parser,function($0,$1,$2){if($1){uri[options.q.name][$1]=$2}});return uri};var key=function(key){if(!parsed.length){setUp()}if(key=="base"){if(parsed.port!==null&&parsed.port!==""){return parsed.protocol+"://"+parsed.host+":"+parsed.port+"/"}else{return parsed.protocol+"://"+parsed.host+"/"}}return(parsed[key]==="")?null:parsed[key]};var param=function(item){if(!parsed.length){setUp()}return(parsed.queryKey[item]===null)?null:parsed.queryKey[item]};var setUp=function(){parsed=parseUri();getSegments()};var getSegments=function(){var p=parsed.path;segments=[];segments=parsed.path.length==1?{}:(p.charAt(p.length-1)=="/"?p.substring(1,p.length-1):path=p.substring(1)).split("/")};return{setMode:function(mode){strictMode=mode=="strict"?true:false;return this},setUrl:function(newUri){options.url=newUri===undefined?window.location:newUri;setUp();return this},segment:function(pos){if(!parsed.length){setUp()}if(pos===undefined){return segments.length}return(segments[pos]===""||segments[pos]===undefined)?null:segments[pos]},attr:key,param:param}}();

var config = new Object();
var tt_Debug = true
var tt_Enabled = true
var TagsToTip = true
config.Above = false
config.BgColor = '#E2E7FF'
config.BgImg = ''
config.BorderColor = '#003099'
config.BorderStyle = 'solid'
config.BorderWidth = 1
config.CenterMouse = false
config.ClickClose = false
config.ClickSticky = false
config.CloseBtn = false
config.CloseBtnColors = ['#990000','#FFFFFF','#DD3333','#FFFFFF']
config.CloseBtnText = '&nbsp;X&nbsp;'
config.CopyContent = true
config.Delay = 400
config.Duration = 0
config.Exclusive = false
config.FadeIn = 100
config.FadeOut = 100
config.FadeInterval = 30
config.Fix = null
config.FollowMouse = true
config.FontColor = '#000044'
config.FontFace = 'Verdana,Geneva,sans-serif'
config.FontSize = '8pt'
config.FontWeight = 'normal'
config.Height = 0
config.JumpHorz = false
config.JumpVert = true
config.Left = false
config.OffsetX = 14
config.OffsetY = 8
config.Opacity = 100
config.Padding = 3
config.Shadow = false
config.ShadowColor = '#C0C0C0'
config.ShadowWidth = 5
config.Sticky = false
config.TextAlign = 'left'
config.Title = ''
config.TitleAlign = 'left'
config.TitleBgColor = ''
config.TitleFontColor = '#FFFFFF'
config.TitleFontFace = ''
config.TitleFontSize = ''
config.TitlePadding = 2
config.Width = 0;
config.UseMouseClickedPosition = true;

function Tip() {
    tt_Tip(arguments, null)
}
function TagToTip() {
    var t2t = tt_GetElt(arguments[0]);
    if (t2t)tt_Tip(arguments, t2t)
}
function UnTip() {
    tt_OpReHref();
    if (tt_aV[DURATION] < 0 && (tt_iState & 0x2))tt_tDurt.Timer("tt_HideInit()", -tt_aV[DURATION], true); else if (!(tt_aV[STICKY] && (tt_iState & 0x2)))tt_HideInit()
}
var tt_aElt = new Array(10),tt_aV = new Array(),tt_sContent,tt_t2t,tt_t2tDad,tt_musX,tt_musY,tt_over,tt_x,tt_y,tt_w,tt_h;
function tt_Extension() {
    tt_ExtCmdEnum();
    tt_aExt[tt_aExt.length] = this;
    return this
}
function tt_SetTipPos(x, y) {
    var css = tt_aElt[0].style;
    tt_x = x;
    tt_y = y;
    css.left = x + "px";
    css.top = y + "px";
    if (tt_ie56) {
        var ifrm = tt_aElt[tt_aElt.length - 1];
        if (ifrm) {
            ifrm.style.left = css.left;
            ifrm.style.top = css.top
        }
    }
}
function tt_HideInit() {
    if (tt_iState) {
        tt_ExtCallFncs(0, "HideInit");
        tt_iState &= ~(0x4 | 0x8);
        if (tt_flagOpa && tt_aV[FADEOUT]) {
            tt_tFade.EndTimer();
            if (tt_opa) {
                var n = Math.round(tt_aV[FADEOUT] / (tt_aV[FADEINTERVAL] * (tt_aV[OPACITY] / tt_opa)));
                tt_Fade(tt_opa, tt_opa, 0, n);
                return
            }
        }
        tt_tHide.Timer("tt_Hide();", 1, false)
    }
}
function tt_Hide() {
    if (tt_db && tt_iState) {
        tt_OpReHref();
        if (tt_iState & 0x2) {
            tt_aElt[0].style.visibility = "hidden";
            tt_ExtCallFncs(0, "Hide")
        }
        tt_tShow.EndTimer();
        tt_tHide.EndTimer();
        tt_tDurt.EndTimer();
        tt_tFade.EndTimer();
        if (!tt_op && !tt_ie) {
            tt_tWaitMov.EndTimer();
            tt_bWait = false
        }
        if (tt_aV[CLICKCLOSE] || tt_aV[CLICKSTICKY])tt_RemEvtFnc(document, "mouseup", tt_OnLClick);
        tt_ExtCallFncs(0, "Kill");
        if (tt_t2t && !tt_aV[COPYCONTENT])tt_UnEl2Tip();
        tt_iState = 0;
        tt_over = null;
        tt_ResetMainDiv();
        if (tt_aElt[tt_aElt.length - 1])tt_aElt[tt_aElt.length - 1].style.display = "none"
    }
}
function tt_GetElt(id) {
    return(document.getElementById ? document.getElementById(id) : document.all ? document.all[id] : null)
}
function tt_GetDivW(el) {
    return(el ? (el.offsetWidth || el.style.pixelWidth || 0) : 0)
}
function tt_GetDivH(el) {
    return(el ? (el.offsetHeight || el.style.pixelHeight || 0) : 0)
}
function tt_GetScrollX() {
    return(window.pageXOffset || (tt_db ? (tt_db.scrollLeft || 0) : 0))
}
function tt_GetScrollY() {
    return(window.pageYOffset || (tt_db ? (tt_db.scrollTop || 0) : 0))
}
function tt_GetClientW() {
    return tt_GetWndCliSiz("Width")
}
function tt_GetClientH() {
    return tt_GetWndCliSiz("Height")
}
function tt_GetEvtX(e) {
    return(e ? ((typeof(e.pageX) != tt_u) ? e.pageX : (e.clientX + tt_GetScrollX())) : 0)
}
function tt_GetEvtY(e) {
    return(e ? ((typeof(e.pageY) != tt_u) ? e.pageY : (e.clientY + tt_GetScrollY())) : 0)
}
function tt_AddEvtFnc(el, sEvt, PFnc) {
    if (el) {
        if (el.addEventListener)el.addEventListener(sEvt, PFnc, false); else el.attachEvent("on" + sEvt, PFnc)
    }
}
function tt_RemEvtFnc(el, sEvt, PFnc) {
    if (el) {
        if (el.removeEventListener)el.removeEventListener(sEvt, PFnc, false); else el.detachEvent("on" + sEvt, PFnc)
    }
}
function tt_GetDad(el) {
    return(el.parentNode || el.parentElement || el.offsetParent)
}
function tt_MovDomNode(el, dadFrom, dadTo) {
    if (dadFrom)dadFrom.removeChild(el);
    if (dadTo)dadTo.appendChild(el)
}
var tt_aExt = new Array(),tt_db,tt_op,tt_ie,tt_ie56,tt_bBoxOld,tt_body,tt_ovr_,tt_flagOpa,tt_maxPosX,tt_maxPosY,tt_iState = 0,tt_opa,tt_bJmpVert,tt_bJmpHorz,tt_elDeHref,tt_tShow = new Number(0),tt_tHide = new Number(0),tt_tDurt = new Number(0),tt_tFade = new Number(0),tt_tWaitMov = new Number(0),tt_bWait = false,tt_u = "undefined";
function tt_Init() {
    tt_MkCmdEnum();
    if (!tt_Browser() || !tt_MkMainDiv())return;
    tt_IsW3cBox();
    tt_OpaSupport();
    tt_AddEvtFnc(document, "mousemove", tt_MouseMove);
    tt_AddEvtFnc(document, "mouseup", tt_Move);
    if (TagsToTip || tt_Debug)tt_SetOnloadFnc();
    tt_AddEvtFnc(window, "unload", tt_Hide)
}
function tt_MouseMove(e) {
    if (tt_aV[USEMOUSECLICKEDPOSITION] != undefined && !tt_aV[USEMOUSECLICKEDPOSITION]) {
        tt_Move(e);
    }
}
function tt_MkCmdEnum() {
    var n = 0;
    for (var i in config)eval("window." + i.toString().toUpperCase() + " = " + n++);
    tt_aV.length = n
}
function tt_Browser() {
    var n,nv,n6,w3c;
    n = navigator.userAgent.toLowerCase(),nv = navigator.appVersion;
    tt_op = (document.defaultView && typeof(eval("w" + "indow" + "." + "o" + "p" + "er" + "a")) != tt_u);
    tt_ie = n.indexOf("msie") != -1 && document.all && !tt_op;
    if (tt_ie) {
        var ieOld = (!document.compatMode || document.compatMode == "BackCompat");
        tt_db = !ieOld ? document.documentElement : (document.body || null);
        if (tt_db)tt_ie56 = parseFloat(nv.substring(nv.indexOf("MSIE") + 5)) >= 5.5 && typeof document.body.style.maxHeight == tt_u
    } else {
        tt_db = document.documentElement || document.body || (document.getElementsByTagName ? document.getElementsByTagName("body")[0] : null);
        if (!tt_op) {
            n6 = document.defaultView && typeof document.defaultView.getComputedStyle != tt_u;
            w3c = !n6 && document.getElementById
        }
    }
    tt_body = (document.getElementsByTagName ? document.getElementsByTagName("body")[0] : (document.body || null));
    if (tt_ie || n6 || tt_op || w3c) {
        if (tt_body && tt_db) {
            if (document.attachEvent || document.addEventListener)return true
        } else tt_Err("wz_tooltip.js must be included INSIDE the body section," + " immediately after the opening <body> tag.", false)
    }
    tt_db = null;
    return false
}
function tt_MkMainDiv() {
    if (tt_body.insertAdjacentHTML)tt_body.insertAdjacentHTML("afterBegin", tt_MkMainDivHtm()); else if (typeof tt_body.innerHTML != tt_u && document.createElement && tt_body.appendChild)tt_body.appendChild(tt_MkMainDivDom());
    if (window.tt_GetMainDivRefs && tt_GetMainDivRefs())return true;
    tt_db = null;
    return false
}
function tt_MkMainDivHtm() {
    return('<div id="WzTtDiV"></div>' + (tt_ie56 ? ('<iframe id="WzTtIfRm" src="javascript:false" scrolling="no" frameborder="0" style="filter:Alpha(opacity=0);position:absolute;top:0px;left:0px;display:none;"></iframe>') : ''))
}
function tt_MkMainDivDom() {
    var el = document.createElement("div");
    if (el)el.id = "WzTtDiV";
    return el
}
function tt_GetMainDivRefs() {
    tt_aElt[0] = tt_GetElt("WzTtDiV");
    if (tt_ie56 && tt_aElt[0]) {
        tt_aElt[tt_aElt.length - 1] = tt_GetElt("WzTtIfRm");
        if (!tt_aElt[tt_aElt.length - 1])tt_aElt[0] = null
    }
    if (tt_aElt[0]) {
        var css = tt_aElt[0].style;
        css.visibility = "hidden";
        css.position = "absolute";
        css.overflow = "hidden";
        return true
    }
    return false
}
function tt_ResetMainDiv() {
    tt_SetTipPos(0, 0);
    tt_aElt[0].innerHTML = "";
    tt_aElt[0].style.width = "0px";
    tt_h = 0
}
function tt_IsW3cBox() {
    var css = tt_aElt[0].style;
    css.padding = "10px";
    css.width = "40px";
    tt_bBoxOld = (tt_GetDivW(tt_aElt[0]) == 40);
    css.padding = "0px";
    tt_ResetMainDiv()
}
function tt_OpaSupport() {
    var css = tt_body.style;
    tt_flagOpa = (typeof(css.KhtmlOpacity) != tt_u) ? 2 : (typeof(css.KHTMLOpacity) != tt_u) ? 3 : (typeof(css.MozOpacity) != tt_u) ? 4 : (typeof(css.opacity) != tt_u) ? 5 : (typeof(css.filter) != tt_u) ? 1 : 0
}
function tt_SetOnloadFnc() {
    tt_AddEvtFnc(document, "DOMContentLoaded", tt_HideSrcTags);
    tt_AddEvtFnc(window, "load", tt_HideSrcTags);
    if (tt_body.attachEvent)tt_body.attachEvent("onreadystatechange", function() {
        if (tt_body.readyState == "complete")tt_HideSrcTags()
    });
    if (/WebKit|KHTML/i.test(navigator.userAgent)) {
        var t = setInterval(function() {
            if (/loaded|complete/.test(document.readyState)) {
                clearInterval(t);
                tt_HideSrcTags()
            }
        }, 10)
    }
}
function tt_HideSrcTags() {
    if (!window.tt_HideSrcTags || window.tt_HideSrcTags.done)return;
    window.tt_HideSrcTags.done = true;
    if (!tt_HideSrcTagsRecurs(tt_body))tt_Err("There are HTML elements to be converted to tooltips.\nIf you" + " want these HTML elements to be automatically hidden, you" + " must edit wz_tooltip.js, and set TagsToTip in the global" + " tooltip configuration to true.", true)
}
function tt_HideSrcTagsRecurs(dad) {
    var ovr,asT2t;
    var a = dad.childNodes || dad.children || null;
    for (var i = a ? a.length : 0; i;) {
        --i;
        if (!tt_HideSrcTagsRecurs(a[i]))return false;
        ovr = a[i].getAttribute ? (a[i].getAttribute("onmouseover") || a[i].getAttribute("onclick")) : (typeof a[i].onmouseover == "function") ? (a[i].onmouseover || a[i].onclick) : null;
        if (ovr) {
            asT2t = ovr.toString().match(/TagToTip\s*\(\s*'[^'.]+'\s*[\),]/);
            if (asT2t && asT2t.length) {
                if (!tt_HideSrcTag(asT2t[0]))return false
            }
        }
    }
    return true
}
function tt_HideSrcTag(sT2t) {
    var id,el;
    id = sT2t.replace(/.+'([^'.]+)'.+/, "$1");
    el = tt_GetElt(id);
    if (el) {
        if (tt_Debug && !TagsToTip)return false; else el.style.display = "none"
    } else tt_Err("Invalid ID\n'" + id + "'\npassed to TagToTip()." + " There exists no HTML element with that ID.", true);
    return true
}
function tt_Tip(arg, t2t) {
    if (!tt_db || (tt_iState & 0x8))return;
    if (tt_iState)tt_Hide();
    if (!tt_Enabled)return;
    tt_t2t = t2t;
    if (!tt_ReadCmds(arg))return;
    tt_iState = 0x1 | 0x4;
    tt_AdaptConfig1();
    tt_MkTipContent(arg);
    tt_MkTipSubDivs();
    tt_FormatTip();
    tt_bJmpVert = false;
    tt_bJmpHorz = false;
    tt_maxPosX = tt_GetClientW() + tt_GetScrollX() - tt_w - 1;
    tt_maxPosY = tt_GetClientH() + tt_GetScrollY() - tt_h - 1;
    tt_AdaptConfig2();
    tt_OverInit();
    tt_ShowInit();
    tt_Move(null);
}
function tt_ReadCmds(a) {
    var i;
    i = 0;
    for (var j in config)tt_aV[i++] = config[j];
    if (a.length & 1) {
        for (i = a.length - 1; i > 0; i -= 2)tt_aV[a[i - 1]] = a[i];
        return true
    }
    tt_Err("Incorrect call of Tip() or TagToTip().\n" + "Each command must be followed by a value.", true);
    return false
}
function tt_AdaptConfig1() {
    tt_ExtCallFncs(0, "LoadConfig");
    if (!tt_aV[TITLEBGCOLOR].length)tt_aV[TITLEBGCOLOR] = tt_aV[BORDERCOLOR];
    if (!tt_aV[TITLEFONTCOLOR].length)tt_aV[TITLEFONTCOLOR] = tt_aV[BGCOLOR];
    if (!tt_aV[TITLEFONTFACE].length)tt_aV[TITLEFONTFACE] = tt_aV[FONTFACE];
    if (!tt_aV[TITLEFONTSIZE].length)tt_aV[TITLEFONTSIZE] = tt_aV[FONTSIZE];
    if (tt_aV[CLOSEBTN]) {
        if (!tt_aV[CLOSEBTNCOLORS])tt_aV[CLOSEBTNCOLORS] = new Array("", "", "", "");
        for (var i = 4; i;) {
            --i;
            if (!tt_aV[CLOSEBTNCOLORS][i].length)tt_aV[CLOSEBTNCOLORS][i] = (i & 1) ? tt_aV[TITLEFONTCOLOR] : tt_aV[TITLEBGCOLOR]
        }
        if (!tt_aV[TITLE].length)tt_aV[TITLE] = " "
    }
    if (tt_aV[OPACITY] == 100 && typeof tt_aElt[0].style.MozOpacity != tt_u && !Array.every)tt_aV[OPACITY] = 99;
    if (tt_aV[FADEIN] && tt_flagOpa && tt_aV[DELAY] > 100)tt_aV[DELAY] = Math.max(tt_aV[DELAY] - tt_aV[FADEIN], 100)
}
function tt_AdaptConfig2() {
    if (tt_aV[CENTERMOUSE]) {
        tt_aV[OFFSETX] -= ((tt_w - (tt_aV[SHADOW] ? tt_aV[SHADOWWIDTH] : 0)) >> 1);
        tt_aV[JUMPHORZ] = false
    }
}
function tt_MkTipContent(a) {
    if (tt_t2t) {
        if (tt_aV[COPYCONTENT])tt_sContent = tt_t2t.innerHTML; else tt_sContent = ""
    } else tt_sContent = a[0];
    tt_ExtCallFncs(0, "CreateContentString")
}
function tt_MkTipSubDivs() {
    var sCss = 'position:relative;margin:0px;padding:0px;border-width:0px;left:0px;top:0px;line-height:normal;width:auto;',sTbTrTd = ' cellspacing="0" cellpadding="0" border="0" style="' + sCss + '"><tbody style="' + sCss + '"><tr><td ';
    tt_aElt[0].style.width = tt_GetClientW() + "px";
    tt_aElt[0].innerHTML = ('' + (tt_aV[TITLE].length ? ('<div id="WzTiTl" style="position:relative;z-index:1;">' + '<table id="WzTiTlTb"' + sTbTrTd + 'id="WzTiTlI" style="' + sCss + '">' + tt_aV[TITLE] + '</td>' + (tt_aV[CLOSEBTN] ? ('<td align="right" style="' + sCss + 'text-align:right;">' + '<span id="WzClOsE" style="position:relative;left:2px;padding-left:2px;padding-right:2px;' + 'cursor:' + (tt_ie ? 'hand' : 'pointer') + ';" onmouseover="tt_OnCloseBtnOver(1)" onmouseout="tt_OnCloseBtnOver(0)" onclick="tt_HideInit()">' + tt_aV[CLOSEBTNTEXT] + '</span></td>') : '') + '</tr></tbody></table></div>') : '') + '<div id="WzBoDy" style="position:relative;z-index:0;">' + '<table' + sTbTrTd + 'id="WzBoDyI" style="' + sCss + '">' + tt_sContent + '</td></tr></tbody></table></div>' + (tt_aV[SHADOW] ? ('<div id="WzTtShDwR" style="position:absolute;overflow:hidden;"></div>' + '<div id="WzTtShDwB" style="position:relative;overflow:hidden;"></div>') : ''));
    tt_GetSubDivRefs();
    if (tt_t2t && !tt_aV[COPYCONTENT])tt_El2Tip();
    tt_ExtCallFncs(0, "SubDivsCreated")
}
function tt_GetSubDivRefs() {
    var aId = new Array("WzTiTl", "WzTiTlTb", "WzTiTlI", "WzClOsE", "WzBoDy", "WzBoDyI", "WzTtShDwB", "WzTtShDwR");
    for (var i = aId.length; i; --i)tt_aElt[i] = tt_GetElt(aId[i - 1])
}
function tt_FormatTip() {
    var css,w,h,pad = tt_aV[PADDING],padT,wBrd = tt_aV[BORDERWIDTH],iOffY,iOffSh,iAdd = (pad + wBrd) << 1;
    if (tt_aV[TITLE].length) {
        padT = tt_aV[TITLEPADDING];
        css = tt_aElt[1].style;
        css.background = tt_aV[TITLEBGCOLOR];
        css.paddingTop = css.paddingBottom = padT + "px";
        css.paddingLeft = css.paddingRight = (padT + 2) + "px";
        css = tt_aElt[3].style;
        css.color = tt_aV[TITLEFONTCOLOR];
        if (tt_aV[WIDTH] == -1)css.whiteSpace = "nowrap";
        css.fontFamily = tt_aV[TITLEFONTFACE];
        css.fontSize = tt_aV[TITLEFONTSIZE];
        css.fontWeight = "bold";
        css.textAlign = tt_aV[TITLEALIGN];
        if (tt_aElt[4]) {
            css = tt_aElt[4].style;
            css.background = tt_aV[CLOSEBTNCOLORS][0];
            css.color = tt_aV[CLOSEBTNCOLORS][1];
            css.fontFamily = tt_aV[TITLEFONTFACE];
            css.fontSize = tt_aV[TITLEFONTSIZE];
            css.fontWeight = "bold"
        }
        if (tt_aV[WIDTH] > 0)tt_w = tt_aV[WIDTH]; else {
            tt_w = tt_GetDivW(tt_aElt[3]) + tt_GetDivW(tt_aElt[4]);
            if (tt_aElt[4])tt_w += pad;
            if (tt_aV[WIDTH] < -1 && tt_w > -tt_aV[WIDTH])tt_w = -tt_aV[WIDTH]
        }
        iOffY = -wBrd
    } else {
        tt_w = 0;
        iOffY = 0
    }
    css = tt_aElt[5].style;
    css.top = iOffY + "px";
    if (wBrd) {
        css.borderColor = tt_aV[BORDERCOLOR];
        css.borderStyle = tt_aV[BORDERSTYLE];
        css.borderWidth = wBrd + "px"
    }
    if (tt_aV[BGCOLOR].length)css.background = tt_aV[BGCOLOR];
    if (tt_aV[BGIMG].length)css.backgroundImage = "url(" + tt_aV[BGIMG] + ")";
    css.padding = pad + "px";
    css.textAlign = tt_aV[TEXTALIGN];
    if (tt_aV[HEIGHT]) {
        css.overflow = "auto";
        if (tt_aV[HEIGHT] > 0)css.height = (tt_aV[HEIGHT] + iAdd) + "px"; else tt_h = iAdd - tt_aV[HEIGHT]
    }
    css = tt_aElt[6].style;
    css.color = tt_aV[FONTCOLOR];
    css.fontFamily = tt_aV[FONTFACE];
    css.fontSize = tt_aV[FONTSIZE];
    css.fontWeight = tt_aV[FONTWEIGHT];
    css.textAlign = tt_aV[TEXTALIGN];
    if (tt_aV[WIDTH] > 0)w = tt_aV[WIDTH]; else if (tt_aV[WIDTH] == -1 && tt_w)w = tt_w; else {
        w = tt_GetDivW(tt_aElt[6]);
        if (tt_aV[WIDTH] < -1 && w > -tt_aV[WIDTH])w = -tt_aV[WIDTH]
    }
    if (w > tt_w)tt_w = w;
    tt_w += iAdd;
    if (tt_aV[SHADOW]) {
        tt_w += tt_aV[SHADOWWIDTH];
        iOffSh = Math.floor((tt_aV[SHADOWWIDTH] * 4) / 3);
        css = tt_aElt[7].style;
        css.top = iOffY + "px";
        css.left = iOffSh + "px";
        css.width = (tt_w - iOffSh - tt_aV[SHADOWWIDTH]) + "px";
        css.height = tt_aV[SHADOWWIDTH] + "px";
        css.background = tt_aV[SHADOWCOLOR];
        css = tt_aElt[8].style;
        css.top = iOffSh + "px";
        css.left = (tt_w - tt_aV[SHADOWWIDTH]) + "px";
        css.width = tt_aV[SHADOWWIDTH] + "px";
        css.background = tt_aV[SHADOWCOLOR]
    } else iOffSh = 0;
    tt_SetTipOpa(tt_aV[FADEIN] ? 0 : tt_aV[OPACITY]);
    tt_FixSize(iOffY, iOffSh)
}
function tt_FixSize(iOffY, iOffSh) {
    var wIn,wOut,h,add,pad = tt_aV[PADDING],wBrd = tt_aV[BORDERWIDTH],i;
    tt_aElt[0].style.width = tt_w + "px";
    tt_aElt[0].style.pixelWidth = tt_w;
    wOut = tt_w - ((tt_aV[SHADOW]) ? tt_aV[SHADOWWIDTH] : 0);
    wIn = wOut;
    if (!tt_bBoxOld)wIn -= (pad + wBrd) << 1;
    tt_aElt[5].style.width = wIn + "px";
    if (tt_aElt[1]) {
        wIn = wOut - ((tt_aV[TITLEPADDING] + 2) << 1);
        if (!tt_bBoxOld)wOut = wIn;
        tt_aElt[1].style.width = wOut + "px";
        tt_aElt[2].style.width = wIn + "px"
    }
    if (tt_h) {
        h = tt_GetDivH(tt_aElt[5]);
        if (h > tt_h) {
            if (!tt_bBoxOld)tt_h -= (pad + wBrd) << 1;
            tt_aElt[5].style.height = tt_h + "px"
        }
    }
    tt_h = tt_GetDivH(tt_aElt[0]) + iOffY;
    if (tt_aElt[8])tt_aElt[8].style.height = (tt_h - iOffSh) + "px";
    i = tt_aElt.length - 1;
    if (tt_aElt[i]) {
        tt_aElt[i].style.width = tt_w + "px";
        tt_aElt[i].style.height = tt_h + "px"
    }
}
function tt_DeAlt(el) {
    var aKid;
    if (el) {
        if (el.alt)el.alt = "";
        if (el.title)el.title = "";
        aKid = el.childNodes || el.children || null;
        if (aKid) {
            for (var i = aKid.length; i;)tt_DeAlt(aKid[--i])
        }
    }
}
function tt_OpDeHref(el) {
    if (!tt_op)return;
    if (tt_elDeHref)tt_OpReHref();
    while (el) {
        if (el.hasAttribute && el.hasAttribute("href")) {
            el.t_href = el.getAttribute("href");
            el.t_stats = window.status;
            el.removeAttribute("href");
            el.style.cursor = "hand";
            tt_AddEvtFnc(el, "mousedown", tt_OpReHref);
            window.status = el.t_href;
            tt_elDeHref = el;
            break
        }
        el = tt_GetDad(el)
    }
}
function tt_OpReHref() {
    if (tt_elDeHref) {
        tt_elDeHref.setAttribute("href", tt_elDeHref.t_href);
        tt_RemEvtFnc(tt_elDeHref, "mousedown", tt_OpReHref);
        window.status = tt_elDeHref.t_stats;
        tt_elDeHref = null
    }
}
function tt_El2Tip() {
    var css = tt_t2t.style;
    tt_t2t.t_cp = css.position;
    tt_t2t.t_cl = css.left;
    tt_t2t.t_ct = css.top;
    tt_t2t.t_cd = css.display;
    tt_t2tDad = tt_GetDad(tt_t2t);
    tt_MovDomNode(tt_t2t, tt_t2tDad, tt_aElt[6]);
    css.display = "block";
    css.position = "static";
    css.left = css.top = css.marginLeft = css.marginTop = "0px"
}
function tt_UnEl2Tip() {
    var css = tt_t2t.style;
    css.display = tt_t2t.t_cd;
    tt_MovDomNode(tt_t2t, tt_GetDad(tt_t2t), tt_t2tDad);
    css.position = tt_t2t.t_cp;
    css.left = tt_t2t.t_cl;
    css.top = tt_t2t.t_ct;
    tt_t2tDad = null
}
function tt_OverInit() {
    if (window.event)tt_over = window.event.target || window.event.srcElement; else tt_over = tt_ovr_;
    tt_DeAlt(tt_over);
    tt_OpDeHref(tt_over)
}
function tt_ShowInit() {
    tt_tShow.Timer("tt_Show()", tt_aV[DELAY], true);
    if (tt_aV[CLICKCLOSE] || tt_aV[CLICKSTICKY])tt_AddEvtFnc(document, "mouseup", tt_OnLClick)
}
function tt_Show() {
    var css = tt_aElt[0].style;
    css.zIndex = Math.max((window.dd && dd.z) ? (dd.z + 2) : 0, 1010);
    if (tt_aV[STICKY] || !tt_aV[FOLLOWMOUSE])tt_iState &= ~0x4;
    if (tt_aV[EXCLUSIVE])tt_iState |= 0x8;
    if (tt_aV[DURATION] > 0)tt_tDurt.Timer("tt_HideInit()", tt_aV[DURATION], true);
    tt_ExtCallFncs(0, "Show")
    css.visibility = "visible";
    tt_iState |= 0x2;
    if (tt_aV[FADEIN])tt_Fade(0, 0, tt_aV[OPACITY], Math.round(tt_aV[FADEIN] / tt_aV[FADEINTERVAL]));
    tt_ShowIfrm()
}
function tt_ShowIfrm() {
    if (tt_ie56) {
        var ifrm = tt_aElt[tt_aElt.length - 1];
        if (ifrm) {
            var css = ifrm.style;
            css.zIndex = tt_aElt[0].style.zIndex - 1;
            css.display = "block"
        }
    }
}

function isMouseEvent(eventObject)
{
    if(!eventObject)
    {return false;}
    
    var eventType = eventObject.type;
    return (eventType == "mouseup" || eventType == "mousedown" || eventType == "mousemove" || eventType == "mouseover");
}

function tt_Move(eventObject) {
    if (eventObject)tt_ovr_ = eventObject.target || eventObject.srcElement;

    if(!eventObject && isMouseEvent(window.event))
    {
        eventObject = window.event;
    }
    
    if (eventObject) {
        tt_musX = tt_GetEvtX(eventObject);
        tt_musY = tt_GetEvtY(eventObject)
    }

    if (tt_iState & 0x4) {
        if (!tt_op && !tt_ie) {
            if (tt_bWait)return;
            tt_bWait = true;
            tt_tWaitMov.Timer("tt_bWait = false;", 1, true)
        }
        if (tt_aV[FIX]) {
            tt_iState &= ~0x4;
            tt_PosFix()
        } else if (!tt_ExtCallFncs(eventObject, "MoveBefore"))tt_SetTipPos(tt_Pos(0), tt_Pos(1));
        tt_ExtCallFncs([tt_musX,tt_musY], "MoveAfter")
    }
}
function tt_Pos(iDim) {
    var iX,bJmpMod,cmdAlt,cmdOff,cx,iMax,iScrl,iMus,bJmp;
    if (iDim) {
        bJmpMod = tt_aV[JUMPVERT];
        cmdAlt = ABOVE;
        cmdOff = OFFSETY;
        cx = tt_h;
        iMax = tt_maxPosY;
        iScrl = tt_GetScrollY();
        iMus = tt_musY;
        bJmp = tt_bJmpVert
    } else {
        bJmpMod = tt_aV[JUMPHORZ];
        cmdAlt = LEFT;
        cmdOff = OFFSETX;
        cx = tt_w;
        iMax = tt_maxPosX;
        iScrl = tt_GetScrollX();
        iMus = tt_musX;
        bJmp = tt_bJmpHorz
    }
    if (bJmpMod) {
        if (tt_aV[cmdAlt] && (!bJmp || tt_CalcPosAlt(iDim) >= iScrl + 16))iX = tt_PosAlt(iDim); else if (!tt_aV[cmdAlt] && bJmp && tt_CalcPosDef(iDim) > iMax - 16)iX = tt_PosAlt(iDim); else iX = tt_PosDef(iDim)
    } else {
        iX = iMus;
        if (tt_aV[cmdAlt])iX -= cx + tt_aV[cmdOff] - (tt_aV[SHADOW] ? tt_aV[SHADOWWIDTH] : 0); else iX += tt_aV[cmdOff]
    }
    if (iX > iMax)iX = bJmpMod ? tt_PosAlt(iDim) : iMax;
    if (iX < iScrl)iX = bJmpMod ? tt_PosDef(iDim) : iScrl;
    return iX
}
function tt_PosDef(iDim) {
    if (iDim)tt_bJmpVert = tt_aV[ABOVE]; else tt_bJmpHorz = tt_aV[LEFT];
    return tt_CalcPosDef(iDim)
}
function tt_PosAlt(iDim) {
    if (iDim)tt_bJmpVert = !tt_aV[ABOVE]; else tt_bJmpHorz = !tt_aV[LEFT];
    return tt_CalcPosAlt(iDim)
}
function tt_CalcPosDef(iDim) {
    return iDim ? (tt_musY + tt_aV[OFFSETY]) : (tt_musX + tt_aV[OFFSETX])
}
function tt_CalcPosAlt(iDim) {
    var cmdOff = iDim ? OFFSETY : OFFSETX;
    var dx = tt_aV[cmdOff] - (tt_aV[SHADOW] ? tt_aV[SHADOWWIDTH] : 0);
    if (tt_aV[cmdOff] > 0 && dx <= 0)dx = 1;
    return((iDim ? (tt_musY - tt_h) : (tt_musX - tt_w)) - dx)
}
function tt_PosFix() {
    var iX,iY;
    if (typeof(tt_aV[FIX][0]) == "number") {
        iX = tt_aV[FIX][0];
        iY = tt_aV[FIX][1]
    } else {
        if (typeof(tt_aV[FIX][0]) == "string")el = tt_GetElt(tt_aV[FIX][0]); else el = tt_aV[FIX][0];
        iX = tt_aV[FIX][1];
        iY = tt_aV[FIX][2];
        if (!tt_aV[ABOVE] && el)iY += tt_GetDivH(el);
        for (; el; el = el.offsetParent) {
            iX += el.offsetLeft || 0;
            iY += el.offsetTop || 0
        }
    }
    if (tt_aV[ABOVE])iY -= tt_h;
    tt_SetTipPos(iX, iY)
}
function tt_Fade(a, now, z, n) {
    if (n) {
        now += Math.round((z - now) / n);
        if ((z > a) ? (now >= z) : (now <= z))now = z; else tt_tFade.Timer("tt_Fade(" + a + "," + now + "," + z + "," + (n - 1) + ")", tt_aV[FADEINTERVAL], true)
    }
    now ? tt_SetTipOpa(now) : tt_Hide()
}
function tt_SetTipOpa(opa) {
    tt_SetOpa(tt_aElt[5], opa);
    if (tt_aElt[1])tt_SetOpa(tt_aElt[1], opa);
    if (tt_aV[SHADOW]) {
        opa = Math.round(opa * 0.8);
        tt_SetOpa(tt_aElt[7], opa);
        tt_SetOpa(tt_aElt[8], opa)
    }
}
function tt_OnCloseBtnOver(iOver) {
    var css = tt_aElt[4].style;
    iOver <<= 1;
    css.background = tt_aV[CLOSEBTNCOLORS][iOver];
    css.color = tt_aV[CLOSEBTNCOLORS][iOver + 1]
}
function tt_OnLClick(e) {
    e = e || window.event;
    if (!((e.button && e.button & 2) || (e.which && e.which == 3))) {
        if (tt_aV[CLICKSTICKY] && (tt_iState & 0x4)) {
            tt_aV[STICKY] = true;
            tt_iState &= ~0x4
        } else if (tt_aV[CLICKCLOSE])tt_HideInit()
    }
}
function tt_Int(x) {
    var y;
    return(isNaN(y = parseInt(x)) ? 0 : y)
}
Number.prototype.Timer = function(s, iT, bUrge) {
    if (!this.value || bUrge)this.value = window.setTimeout(s, iT)
}
Number.prototype.EndTimer = function() {
    if (this.value) {
        window.clearTimeout(this.value);
        this.value = 0
    }
}
function tt_GetWndCliSiz(s) {
    var db,y = window["inner" + s],sC = "client" + s,sN = "number";
    if (typeof y == sN) {
        var y2;
        return(((db = document.body) && typeof(y2 = db[sC]) == sN && y2 && y2 <= y) ? y2 : ((db = document.documentElement) && typeof(y2 = db[sC]) == sN && y2 && y2 <= y) ? y2 : y)
    }
    return(((db = document.documentElement) && (y = db[sC])) ? y : document.body[sC])
}
function tt_SetOpa(el, opa) {
    var css = el.style;
    tt_opa = opa;
    if (tt_flagOpa == 1) {
        if (opa < 100) {
            if (typeof(el.filtNo) == tt_u)el.filtNo = css.filter;
            var bVis = css.visibility != "hidden";
            css.zoom = "100%";
            if (!bVis)css.visibility = "visible";
            css.filter = "alpha(opacity=" + opa + ")";
            if (!bVis)css.visibility = "hidden"
        } else if (typeof(el.filtNo) != tt_u)css.filter = el.filtNo
    } else {
        opa /= 100.0;
        switch (tt_flagOpa) {case 2:css.KhtmlOpacity = opa;break;case 3:css.KHTMLOpacity = opa;break;case 4:css.MozOpacity = opa;break;case 5:css.opacity = opa;break
        }
    }
}
function tt_Err(sErr, bIfDebug) {
    if (tt_Debug || !bIfDebug)alert("Tooltip Script Error Message:\n\n" + sErr)
}
function tt_ExtCmdEnum() {
    var s;
    for (var i in config) {
        s = "window." + i.toString().toUpperCase();
        if (eval("typeof(" + s + ") == tt_u")) {
            eval(s + " = " + tt_aV.length);
            tt_aV[tt_aV.length] = null
        }
    }
}
function tt_ExtCallFncs(arg, sFnc) {
    var b = false;
    for (var i = tt_aExt.length; i;) {
        --i;
        var fnc = tt_aExt[i]["On" + sFnc];
        if (fnc && fnc(arg))b = true
    }
    return b
}
tt_Init();
if (typeof config == "undefined")alert("Error:\nThe core tooltip script file 'wz_tooltip.js' must be included first, before the plugin files!");
config.Balloon = false
config.BalloonImgPath = "/images/calendar_bubble/"
config.BalloonEdgeSize = 6
config.BalloonStemWidth = 15
config.BalloonStemHeight = 19
config.BalloonStemOffset = -7
config.BalloonImgExt = "png";
var balloon = new tt_Extension();
balloon.OnLoadConfig = function() {
    if (tt_aV[BALLOON]) {
        balloon.padding = Math.max(tt_aV[PADDING] - tt_aV[BALLOONEDGESIZE], 0);
        balloon.width = tt_aV[WIDTH];
        tt_aV[BORDERWIDTH] = 0;
        tt_aV[WIDTH] = 0;
        tt_aV[PADDING] = 0;
        tt_aV[BGCOLOR] = "";
        tt_aV[BGIMG] = "";
        tt_aV[SHADOW] = false;
        if (tt_aV[BALLOONIMGPATH].charAt(tt_aV[BALLOONIMGPATH].length - 1) != '/')tt_aV[BALLOONIMGPATH] += "/";
        return true
    }
    return false
};
balloon.OnCreateContentString = function() {
    if (!tt_aV[BALLOON])return false;
    var aImg,sImgZ,sCssCrn,sVaT,sVaB,sCss0;
    if (tt_aV[BALLOONIMGPATH] == config.BalloonImgPath)aImg = balloon.aDefImg; else aImg = Balloon_CacheImgs(tt_aV[BALLOONIMGPATH], tt_aV[BALLOONIMGEXT]);
    sCss0 = 'padding:0;margin:0;border:0;line-height:0;overflow:hidden;';
    sCssCrn = ' style="position:relative;width:' + tt_aV[BALLOONEDGESIZE] + 'px;' + sCss0 + 'overflow:hidden;';
    sVaT = 'vertical-align:top;" valign="top"';
    sVaB = 'vertical-align:bottom;" valign="bottom"';
    sImgZ = '" style="' + sCss0 + '" />';
    tt_sContent = '<table border="0" cellpadding="0" cellspacing="0" style="width:auto;padding:0;margin:0;left:0;top:0;"><tr>' + '<td' + sCssCrn + sVaB + '>' + '<img src="' + aImg[1].src + '" width="' + tt_aV[BALLOONEDGESIZE] + '" height="' + tt_aV[BALLOONEDGESIZE] + sImgZ + '</td>' + '<td valign="bottom" style="position:relative;' + sCss0 + '">' + '<img id="bALlOOnT" style="position:relative;top:6px;z-index:1;display:none;' + sCss0 + '" src="' + aImg[9].src + '" width="' + tt_aV[BALLOONSTEMWIDTH] + '" height="' + tt_aV[BALLOONSTEMHEIGHT] + '" />' + '<div style="position:relative;z-index:0;top:0;' + sCss0 + 'width:auto;height:' + tt_aV[BALLOONEDGESIZE] + 'px;background-image:url(' + aImg[2].src + ');">' + '</div>' + '</td>' + '<td' + sCssCrn + sVaB + '>' + '<img src="' + aImg[3].src + '" width="' + tt_aV[BALLOONEDGESIZE] + '" height="' + tt_aV[BALLOONEDGESIZE] + sImgZ + '</td>' + '</tr><tr>' + '<td style="position:relative;background-repeat:repeat;' + sCss0 + 'width:' + tt_aV[BALLOONEDGESIZE] + 'px;background-image:url(' + aImg[8].src + ');">' + '<img width="' + tt_aV[BALLOONEDGESIZE] + '" height="100%" src="' + aImg[8].src + sImgZ + '</td>' + '<td id="bALlO0nBdY" style="position:relative;line-height:normal;background-repeat:repeat;' + ';background-image:url(' + aImg[0].src + ')' + ';color:' + tt_aV[FONTCOLOR] + ';font-family:' + tt_aV[FONTFACE] + ';font-size:' + tt_aV[FONTSIZE] + ';font-weight:' + tt_aV[FONTWEIGHT] + ';text-align:' + tt_aV[TEXTALIGN] + ';padding:' + balloon.padding + 'px' + ';width:' + ((balloon.width > 0) ? (balloon.width + 'px') : 'auto') + ';">' + tt_sContent + '</td>' + '<td style="position:relative;background-repeat:repeat;' + sCss0 + 'width:' + tt_aV[BALLOONEDGESIZE] + 'px;background-image:url(' + aImg[4].src + ');">' + '<img width="' + tt_aV[BALLOONEDGESIZE] + '" height="100%" src="' + aImg[4].src + sImgZ + '</td>' + '</tr><tr>' + '<td' + sCssCrn + sVaT + '>' + '<img src="' + aImg[7].src + '" width="' + tt_aV[BALLOONEDGESIZE] + '" height="' + tt_aV[BALLOONEDGESIZE] + sImgZ + '</td>' + '<td valign="top" style="position:relative;' + sCss0 + ';background-image:url(' + aImg[6].src + ');background-repeat:repeat-x;">' + '<img id="bALlOOnB" style="position:relative;left:2px;z-index:1;display:none;' + sCss0 + '" src="' + aImg[10].src + '" width="' + tt_aV[BALLOONSTEMWIDTH] + '" height="' + tt_aV[BALLOONSTEMHEIGHT] + '" />' + '</td>' + '<td' + sCssCrn + sVaT + '>' + '<img src="' + aImg[5].src + '" width="' + tt_aV[BALLOONEDGESIZE] + '" height="' + tt_aV[BALLOONEDGESIZE] + sImgZ + '</td>' + '</tr></table>';
    return true
};
balloon.OnSubDivsCreated = function() {
    if (tt_aV[BALLOON]) {
        var bdy = tt_GetElt("bALlO0nBdY");
        if (tt_t2t && !tt_aV[COPYCONTENT] && bdy)tt_MovDomNode(tt_t2t, tt_GetDad(tt_t2t), bdy);
        balloon.iStem = tt_aV[ABOVE] * 1;
        balloon.aStem = [tt_GetElt("bALlOOnT"),tt_GetElt("bALlOOnB")];
        balloon.aStem[balloon.iStem].style.display = "inline";
        if (balloon.width < -1)Balloon_MaxW(bdy);
        return true
    }
    return false
};
balloon.OnMoveAfter = function() {
    if (tt_aV[BALLOON]) {
        var iStem = (tt_aV[ABOVE] != tt_bJmpVert) * 1;
        if (iStem != balloon.iStem) {
            balloon.aStem[balloon.iStem].style.display = "none";
            balloon.aStem[iStem].style.display = "inline";
            balloon.iStem = iStem
        }
        balloon.aStem[iStem].style.left = Balloon_CalcStemX() + "px";
        return true
    }
    return false
};
function Balloon_CalcStemX() {
    var x = tt_musX - tt_x + tt_aV[BALLOONSTEMOFFSET] - tt_aV[BALLOONEDGESIZE];
    return Math.max(Math.min(x, tt_w - tt_aV[BALLOONSTEMWIDTH] - (tt_aV[BALLOONEDGESIZE] << 1) - 2), 2)
}
function Balloon_CacheImgs(sPath, sExt) {
    var asImg = ["background","lt","t","rt","r","rb","b","lb","l","stemt","stemb"],n = asImg.length,aImg = new Array(n),img;
    while (n) {
        --n;
        img = aImg[n] = new Image();
        img.src = sPath + asImg[n] + "." + sExt
    }
    return aImg
}
function Balloon_MaxW(bdy) {
    if (bdy) {
        var iAdd = tt_bBoxOld ? (balloon.padding << 1) : 0,w = tt_GetDivW(bdy);
        if (w > -balloon.width + iAdd)bdy.style.width = (-balloon.width + iAdd) + "px"
    }
}
function Balloon_PreCacheDefImgs() {
    if (config.BalloonImgPath.charAt(config.BalloonImgPath.length - 1) != '/')config.BalloonImgPath += "/";
    balloon.aDefImg = Balloon_CacheImgs(config.BalloonImgPath, config.BalloonImgExt)
}
Balloon_PreCacheDefImgs();
if (typeof config == "undefined")alert("Error:\nThe core tooltip script file 'wz_tooltip.js' must be included first, before the plugin files!");
config.CenterWindow = false
config.CenterAlways = false
var ctrwnd = new tt_Extension();
ctrwnd.OnLoadConfig = function() {
    if (tt_aV[CENTERWINDOW]) {
        if (tt_aV[STICKY]) {
            if (tt_aV[CENTERALWAYS]) {
                if (tt_ie)tt_AddEvtFnc(window, "scroll", Ctrwnd_DoCenter); else tt_aElt[0].style.position = "fixed";
                tt_AddEvtFnc(window, "resize", Ctrwnd_DoCenter)
            }
            return true
        }
        tt_aV[CENTERWINDOW] = false
    }
    return false
};
ctrwnd.OnMoveBefore = Ctrwnd_DoCenter;
ctrwnd.OnKill = function() {
    if (tt_aV[CENTERWINDOW] && tt_aV[CENTERALWAYS]) {
        tt_RemEvtFnc(window, "resize", Ctrwnd_DoCenter);
        if (tt_ie)tt_RemEvtFnc(window, "scroll", Ctrwnd_DoCenter); else tt_aElt[0].style.position = "absolute"
    }
    return false
};
function Ctrwnd_DoCenter() {
    if (tt_aV[CENTERWINDOW]) {
        var x,y,dx,dy;
        if (tt_ie || !tt_aV[CENTERALWAYS]) {
            dx = tt_GetScrollX();
            dy = tt_GetScrollY()
        } else {
            dx = 0;
            dy = 0
        }
        x = (tt_GetClientW() - tt_w) / 2 + dx + tt_aV[OFFSETX];
        y = (tt_GetClientH() - tt_h) / 2 + dy + tt_aV[OFFSETY];
        tt_SetTipPos(x, y);
        return true
    }
    return false
}
(function($) {
    $.widget("cultural_district.wzTooltip", {_options:{},_init:function() {
        var self = this;
        var element = this.element;
        var o = this.options;
        self._options = $.extend({balloon:true,above:true,centerMouse:false,offsetX:0,offsetY:0,padding:10,width:100,fontColor:'#333',bgColor:'#ffffff',borderColor:'#4d4d4d',followMouse:false,duration:0,sticky:true,fadeIn:0,fadeOut:0, useMouseClickedPosition:true}, o || {});
    },show:function(containerClass, showOptions) {
        var self = this;
        self._options = $.extend(self._options, showOptions || {});
        config.UseMouseClickedPosition = self._options.useMouseClickedPosition;
        config.Balloon = self._options.balloon;
        config.BalloonImgExt = 'png';
        config.BalloonStemOffset = self._options.balloonStemOffset;
        config.BalloonStemHeight = 14;
        config.Above = self._options.above;
        config.CenterMouse = self._options.centerMouse;
        config.OffsetX = self._options.offsetX;
        config.OffsetY = self._options.offsetY;
        config.Padding = self._options.padding;
        config.Width = self._options.width;
        config.FontColor = self._options.fontColor;
        config.FollowMouse = self._options.followMouse;
        config.Fix = self._options.fix;
        config.ClickClose = self._options.clickClose;
        config.CloseBtn = self._options.closeButton;
        config.Sticky = self._options.sticky;
        config.Delay = self._options.delay;
        config.Duration = self._options.duration;
        config.BgColor = self._options.bgColor;
        config.BorderColor = self._options.borderColor;
        config.FadeIn = self._options.fadeIn;
        config.FadeOut = self._options.fadeOut;
        Tip.call(this.element[0], this.getContent(containerClass))
    },hide:function() {
        tt_HideInit();
    },getContent:function(containerClass) {
        var self = this;
        var outer = $(document.createElement('div'));
        var inner = $(document.createElement('div'));
        inner.addClass(containerClass);
        inner.attr('id', '');
        inner.html(self._options.content.html());
        outer.append(inner);
        return outer.html();
    }});
    $.extend($.cultural_district.wzTooltip, {defaults:{content:$("<div>someContent</div>"),clickClose:true,closeButton:false,balloonStemOffset:-40,delay:300,fadeIn:0, useMouseClickedPosition:true}});
})(jQuery);

function AjaxForm(form) {

    var self = this;

    this.submitWithoutValidation = function(onSuccess, onError, onComplete) {
        if (onError === undefined) {
            onError = function() {};
        }
        if (onComplete === undefined) {
            onComplete = function() {};
        }

        form.find(".loader").addClass('ajax-loader');
        form.find(".loader-small").addClass('ajax-loader-small');
        $.ajax({
            type: "POST",
            url: form.find('input[name=submit_url]').attr('value'),
            data: form.serialize(),
            success: onSuccess,
            error: function(data) {
                form.find(".loader").removeClass('ajax-loader');
                form.find(".loader-small").removeClass('ajax-loader-small');
                form.find('.continue').attr('disabled', false);
                onError(data);
            },
            complete: onComplete
        });
        form.find('.continue').attr('disabled', 'disabled');
        return true;
    };

    this.submit = function(onSuccess, onError,onComplete) {
        if (!form.valid()) { return true; }
        return self.submitWithoutValidation(onSuccess, onError, onComplete);
    };

}

(

  function($){

    $.widget("cultural_district.action_bar", {
        _init: function(){
          var self=this, element=this.element, o=this.options;
          self.refresh();
        },

        refresh: function(){
          var self=this, element=this.element, o=this.options;
          self._apply_forward_to_url();
          self._attach_events();

          $.getJSON(o.url, function(data){

              var action_links = data.action_links;
              self._show_timer(data.time_remaining_to_complete_order);

              if(action_links) {
                 self._load_menu_items(action_links);
                 if ("logout" in action_links){
                     element.find("#login").addClass("logged-in");
                 }
              }
            }
          );
        },

        show: function(){
          this.element.show();
        },

        _load_menu_items: function(data){
          var self=this;
          var element = this.element;
          if(data) {
              $.each(data, function(menu_name, menu_data){
                  var href = menu_data.url+'?forward_to='+ self._get_forward_to_url();
                  var link = '<a href="'+ href +'">'+menu_data.title+'</a>';
                  element.find("."+menu_name).html(link);
                }
              );
          }
        },

        _apply_forward_to_url: function() {
            var self=this;
            $.each($(".forward_to"), function(index, element) {
                element = $(element).find("a");
                var href = element.attr('href') + '?forward_to=' + self._get_forward_to_url();
                element.attr('href', href);
            });
        },

        _attach_events: function() {
            var self=this, element=this.element, o=this.options;
            self._assign_login_click_event();
            (new ActionBarPromoCode()).init();
        },

        _get_forward_to_url: function()
        {
            var queryStringJson = $.deparam.querystring();
            if(queryStringJson.forward_to !== undefined) {
                return queryStringJson.forward_to;
            }

            return window.location.pathname;
        },

        _show_timer : function(expiration_time_interval)
        {
            if(expiration_time_interval === null) {
                return;
            }

            expirationTimer(expiration_time_interval, 120, $('#expiration-timer'), ModalDialog, Countdown).start();
        },

        _assign_login_click_event: function(){
            var self = this, element = this.element, o = this.options;

            element.find("#login").removeClass("logged-in");
            element.find("#login a").click(function(event) {
                event.preventDefault();
                self._trigger("_login_clicked", event, this);
            });
            self._trigger("_login_link_loaded", null, element.find("#login a"));
        }
      }
    );

    $.extend($.cultural_district.action_bar, {
        defaults: {
          url: "/action_bar"
        }
      }
    );

  }

)(jQuery);



(
  function($){

    $.widget("cultural_district.login_widget",{

        _options: {},
        _init: function(){
          var self=this,element=this.element,o=this.options;

          _options = o;
          var parent_div = $("<div />");
          parent_div.addClass("login-widget-container");
          parent_div.load(o.login_form_path,function(){
              element.wzTooltip({content: parent_div,
                  clickClose:false,
                  width:275,
                  offsetY:10,
                  balloonStemOffset:0,
                  delay:0,
                  fadeIn:0,
                  fix: [element[0], -5, 0],
                  above: false});
              self._trigger("_loaded",null,element);
            }
          );
        },

        show:function(){
          var self=this,element=this.element,o=this.options;
          element.wzTooltip("show", "login-widget");
          self._attachFormActions();
          setTimeout(function(){
              $(".login-widget form #user_email").focus();
            },0);
        },

        hide:function(){
          var self=this,element=this.element,o=this.options;
          element.wzTooltip("hide");
          self._clearErrors();
        },

        loginSuccess: function() {
            var self=this,element=this.element;
            self._trigger("_login_successful", null, element);
        },

        loginFailed: function(errMsg) {
            this._displayErrors({"login_error": errMsg});
            this._loginComplete();
            this._setLoginFrameSource("");
        },

        _loginComplete : function() {
            this._clearPassword();
            $(".login-widget .progress").removeClass("ajax-loader");
        },

        _attachFormActions: function() {
            var self = this,element = this.element,o = this.options;

            var loginForm = $(".login-widget form");
            self.validator = loginForm.validate(_options.validationRules);

            loginForm.submit(function(e) {
                if (!$(e.currentTarget).valid()) {
                    return false;
                }

                self._performLoginOperation();

                return false;
            });

            $(".login-widget .cancel-link").mousedown(function() {
                self.hide();
            });
            $(".login-widget .forgot-password").mousedown(function(e){
                e.preventDefault();
                self.hide();
                window.location.href = $(this).attr("href");
            });
        },

        _performLoginOperation: function(){
            var self=this,element=this.element,o=this.options;
            self._clearErrors();
            $(".login-widget .progress").addClass("ajax-loader");

            self._setLoginFrameSource($("#login-widget form").serialize());
        },

        _setLoginFrameSource: function(src) {
            var existingSource = $("#login_iframe").attr("src");
            var url = $.url.setUrl(existingSource);                 
            var protocol = url.attr("protocol");
            var host = url.attr("host");
            var port = url.attr("port");
            if ((port !== null) && (port !== '')) {
                   host = host + ":" + port;
            }
            iframeSource = protocol + "://"+host+"/login_iframe.html"+"#"+src+"&protocol="+window.location.protocol;
            $("#login_iframe").attr("src", iframeSource);
        },

        _clearErrors: function(){
          $(".login-widget .login-error").empty();
          $(".login-widget .validation-msg").empty();
          $(".login-widget .password-error .validation-msg").empty();
        },

        _clearPassword: function(){
          $(".login-widget .password").val('');
        },

        _clearEmail: function(){
          $(".login-widget .email").val('');
        },

        _displayErrors: function(json){
          var self=this;
          if (typeof(json.email) !== "undefined") {
            self.validator.showErrors( {'user[email]': json.email} );
          }
          if (typeof(json.password) !== "undefined"){
            self.validator.showErrors( {'user[password]': json.password} );
          }
          if (typeof(json.login_error) !== "undefined"){
            $(".login-widget .login-error").html(self._errorDiv(json.login_error));
          }
        },

        _errorDiv: function(error_message){
          errordiv = $("<div />");
          errordiv.html(error_message).addClass("login_widget_error");
          return errordiv;
        }
      }
    );

    $.extend($.cultural_district.login_widget,{
        defaults: {
          login_form_path: "/session_widget",
          validationRules: {}
        }
      }
    );

  }

)(jQuery);



function TooltipWidget(triggerElement, contentElement, widgetClassName, options) {

    var defaults = { content: contentElement,
        clickClose:false,
        width:275,
        offsetY:10,
        balloonStemOffset:0,
        delay:0,
        fadeIn:0,
        fix: [triggerElement[0], -5, 0],
        above: false};

    var settings = $.extend(true, {}, defaults, options);

    this.init = function() {
        triggerElement.wzTooltip(settings);
        return this;
    };

    this.show = function() {
        triggerElement.wzTooltip("show", widgetClassName);
        return this;
    };

    this.hide = function() {
        triggerElement.wzTooltip("hide");
        return this;
    };

    this.remove = function() {
        this.hide();
        $("." + widgetClassName).remove();
    };
}
function PromoCodeValidator(promoCodeForm)
{
    this.init = function() {
        promoCodeForm.validate({
            rules :{
                "promotion_code": {
                    required: true
                }
            },
            messages:{
                "promotion_code": {
                    required: "Please enter a valid promo code"
                }
            }
        });
    };

}

function ActionBarPromoCode() {
    var triggerElement = $("#promo_code_link a");
    var contentElement = $("#promo_code_widget_content");

    var widgetClassName = "promo_code_widget";
    var widget;

    this.init = function() {
        triggerElement.click(function(event) {
            event.preventDefault();
            widget = (new TooltipWidget(triggerElement, contentElement, widgetClassName, {width: 220})).init().show();

            attachActions();
        });
    };

    function attachActions() {

        var widgetElement = $("." + widgetClassName);

        widgetElement.find(".cancel-link").click(function(event) {
            widget.remove();
        });

        var promoCodeForm = widgetElement.find("#promo_code_form");
        (new PromoCodeValidator(promoCodeForm)).init();

        promoCodeForm.submit(function(event) {
            $(".error-message").hide();
            event.preventDefault();
            (new AjaxForm(promoCodeForm)).submit(onSuccess, onError);
            return false;
        });

    }

    function onSuccess(data, status, xhr) {
        var url = xhr.getResponseHeader("BrowserRedirectTo");
        $(location).attr('href', url);
    }

    function onError(xhr) {
        var error_msg = xhr.getResponseHeader("ErrorMsg");
        $("." + widgetClassName).find(".error-message").html(error_msg).show();
    }

}



/* http://keith-wood.name/countdown.html
   Countdown for jQuery v1.5.6.
   Written by Keith Wood (kbwood{at}iinet.com.au) January 2008.
   Dual licensed under the GPL (http://dev.jquery.com/browser/trunk/jquery/GPL-LICENSE.txt) and 
   MIT (http://dev.jquery.com/browser/trunk/jquery/MIT-LICENSE.txt) licenses. 
   Please attribute the author if you use it. */
(function($){function Countdown(){this.regional=[];this.regional['']={labels:['Years','Months','Weeks','Days','Hours','Minutes','Seconds'],labels1:['Year','Month','Week','Day','Hour','Minute','Second'],compactLabels:['y','m','w','d'],timeSeparator:':',isRTL:false};this._defaults={until:null,since:null,timezone:null,serverSync:null,format:'dHMS',layout:'',compact:false,description:'',expiryUrl:'',expiryText:'',alwaysExpire:false,onExpiry:null,onTick:null};$.extend(this._defaults,this.regional[''])}var w='countdown';var Y=0;var O=1;var W=2;var D=3;var H=4;var M=5;var S=6;$.extend(Countdown.prototype,{markerClassName:'hasCountdown',_timer:setInterval(function(){$.countdown._updateTargets()},980),_timerTargets:[],setDefaults:function(a){this._resetExtraLabels(this._defaults,a);extendRemove(this._defaults,a||{})},UTCDate:function(a,b,c,e,f,g,h,i){if(typeof b=='object'&&b.constructor==Date){i=b.getMilliseconds();h=b.getSeconds();g=b.getMinutes();f=b.getHours();e=b.getDate();c=b.getMonth();b=b.getFullYear()}var d=new Date();d.setUTCFullYear(b);d.setUTCDate(1);d.setUTCMonth(c||0);d.setUTCDate(e||1);d.setUTCHours(f||0);d.setUTCMinutes((g||0)-(Math.abs(a)<30?a*60:a));d.setUTCSeconds(h||0);d.setUTCMilliseconds(i||0);return d},periodsToSeconds:function(a){return a[0]*31557600+a[1]*2629800+a[2]*604800+a[3]*86400+a[4]*3600+a[5]*60+a[6]},_settingsCountdown:function(a,b){if(!b){return $.countdown._defaults}var c=$.data(a,w);return(b=='all'?c.options:c.options[b])},_attachCountdown:function(a,b){var c=$(a);if(c.hasClass(this.markerClassName)){return}c.addClass(this.markerClassName);var d={options:$.extend({},b),_periods:[0,0,0,0,0,0,0]};$.data(a,w,d);this._changeCountdown(a)},_addTarget:function(a){if(!this._hasTarget(a)){this._timerTargets.push(a)}},_hasTarget:function(a){return($.inArray(a,this._timerTargets)>-1)},_removeTarget:function(b){this._timerTargets=$.map(this._timerTargets,function(a){return(a==b?null:a)})},_updateTargets:function(){for(var i=0;i<this._timerTargets.length;i++){this._updateCountdown(this._timerTargets[i])}},_updateCountdown:function(a,b){var c=$(a);b=b||$.data(a,w);if(!b){return}c.html(this._generateHTML(b));c[(this._get(b,'isRTL')?'add':'remove')+'Class']('countdown_rtl');var d=this._get(b,'onTick');if(d){var e=b._hold!='lap'?b._periods:this._calculatePeriods(b,b._show,new Date());d.apply(a,[e])}var f=b._hold!='pause'&&(b._since?b._now.getTime()<b._since.getTime():b._now.getTime()>=b._until.getTime());if(f&&!b._expiring){b._expiring=true;if(this._hasTarget(a)||this._get(b,'alwaysExpire')){this._removeTarget(a);var g=this._get(b,'onExpiry');if(g){g.apply(a,[])}var h=this._get(b,'expiryText');if(h){var i=this._get(b,'layout');b.options.layout=h;this._updateCountdown(a,b);b.options.layout=i}var j=this._get(b,'expiryUrl');if(j){window.location=j}}b._expiring=false}else if(b._hold=='pause'){this._removeTarget(a)}$.data(a,w,b)},_changeCountdown:function(a,b,c){b=b||{};if(typeof b=='string'){var d=b;b={};b[d]=c}var e=$.data(a,w);if(e){this._resetExtraLabels(e.options,b);extendRemove(e.options,b);this._adjustSettings(a,e);$.data(a,w,e);var f=new Date();if((e._since&&e._since<f)||(e._until&&e._until>f)){this._addTarget(a)}this._updateCountdown(a,e)}},_resetExtraLabels:function(a,b){var c=false;for(var n in b){if(n.match(/[Ll]abels/)){c=true;break}}if(c){for(var n in a){if(n.match(/[Ll]abels[0-9]/)){a[n]=null}}}},_adjustSettings:function(a,b){var c=this._get(b,'serverSync');c=(c?c.apply(a,[]):null);var d=new Date();var e=this._get(b,'timezone');e=(e==null?-d.getTimezoneOffset():e);b._since=this._get(b,'since');if(b._since!=null){b._since=this.UTCDate(e,this._determineTime(b._since,null));if(b._since&&c){b._since.setMilliseconds(b._since.getMilliseconds()+d.getTime()-c.getTime())}}b._until=this.UTCDate(e,this._determineTime(this._get(b,'until'),d));if(c){b._until.setMilliseconds(b._until.getMilliseconds()+d.getTime()-c.getTime())}b._show=this._determineShow(b)},_destroyCountdown:function(a){var b=$(a);if(!b.hasClass(this.markerClassName)){return}this._removeTarget(a);b.removeClass(this.markerClassName).empty();$.removeData(a,w)},_pauseCountdown:function(a){this._hold(a,'pause')},_lapCountdown:function(a){this._hold(a,'lap')},_resumeCountdown:function(a){this._hold(a,null)},_hold:function(a,b){var c=$.data(a,w);if(c){if(c._hold=='pause'&&!b){c._periods=c._savePeriods;var d=(c._since?'-':'+');c[c._since?'_since':'_until']=this._determineTime(d+c._periods[0]+'y'+d+c._periods[1]+'o'+d+c._periods[2]+'w'+d+c._periods[3]+'d'+d+c._periods[4]+'h'+d+c._periods[5]+'m'+d+c._periods[6]+'s');this._addTarget(a)}c._hold=b;c._savePeriods=(b=='pause'?c._periods:null);$.data(a,w,c);this._updateCountdown(a,c)}},_getTimesCountdown:function(a){var b=$.data(a,w);return(!b?null:(!b._hold?b._periods:this._calculatePeriods(b,b._show,new Date())))},_get:function(a,b){return(a.options[b]!=null?a.options[b]:$.countdown._defaults[b])},_determineTime:function(k,l){var m=function(a){var b=new Date();b.setTime(b.getTime()+a*1000);return b};var n=function(a){a=a.toLowerCase();var b=new Date();var c=b.getFullYear();var d=b.getMonth();var e=b.getDate();var f=b.getHours();var g=b.getMinutes();var h=b.getSeconds();var i=/([+-]?[0-9]+)\s*(s|m|h|d|w|o|y)?/g;var j=i.exec(a);while(j){switch(j[2]||'s'){case's':h+=parseInt(j[1],10);break;case'm':g+=parseInt(j[1],10);break;case'h':f+=parseInt(j[1],10);break;case'd':e+=parseInt(j[1],10);break;case'w':e+=parseInt(j[1],10)*7;break;case'o':d+=parseInt(j[1],10);e=Math.min(e,$.countdown._getDaysInMonth(c,d));break;case'y':c+=parseInt(j[1],10);e=Math.min(e,$.countdown._getDaysInMonth(c,d));break}j=i.exec(a)}return new Date(c,d,e,f,g,h,0)};var o=(k==null?l:(typeof k=='string'?n(k):(typeof k=='number'?m(k):k)));if(o)o.setMilliseconds(0);return o},_getDaysInMonth:function(a,b){return 32-new Date(a,b,32).getDate()},_generateHTML:function(c){c._periods=periods=(c._hold?c._periods:this._calculatePeriods(c,c._show,new Date()));var d=false;var e=0;var f=$.extend({},c._show);for(var g=0;g<c._show.length;g++){d|=(c._show[g]=='?'&&periods[g]>0);f[g]=(c._show[g]=='?'&&!d?null:c._show[g]);e+=(f[g]?1:0)}var h=this._get(c,'compact');var i=this._get(c,'layout');var j=(h?this._get(c,'compactLabels'):this._get(c,'labels'));var k=this._get(c,'timeSeparator');var l=this._get(c,'description')||'';var m=function(a){var b=$.countdown._get(c,'compactLabels'+periods[a]);return(f[a]?periods[a]+(b?b[a]:j[a])+' ':'')};var n=function(a){var b=$.countdown._get(c,'labels'+periods[a]);return(f[a]?'<span class="countdown_section"><span class="countdown_amount">'+periods[a]+'</span><br/>'+(b?b[a]:j[a])+'</span>':'')};return(i?this._buildLayout(c,f,i,h):((h?'<span class="countdown_row countdown_amount'+(c._hold?' countdown_holding':'')+'">'+m(Y)+m(O)+m(W)+m(D)+(f[H]?this._minDigits(periods[H],2):'')+(f[M]?(f[H]?k:'')+this._minDigits(periods[M],2):'')+(f[S]?(f[H]||f[M]?k:'')+this._minDigits(periods[S],2):''):'<span class="countdown_row countdown_show'+e+(c._hold?' countdown_holding':'')+'">'+n(Y)+n(O)+n(W)+n(D)+n(H)+n(M)+n(S))+'</span>'+(l?'<span class="countdown_row countdown_descr">'+l+'</span>':'')))},_buildLayout:function(c,d,e,f){var g=this._get(c,(f?'compactLabels':'labels'));var h=function(a){return($.countdown._get(c,(f?'compactLabels':'labels')+c._periods[a])||g)[a]};var j=function(a,b){return Math.floor(a/b)%10};var k={desc:this._get(c,'description'),sep:this._get(c,'timeSeparator'),yl:h(Y),yn:c._periods[Y],ynn:this._minDigits(c._periods[Y],2),ynnn:this._minDigits(c._periods[Y],3),y1:j(c._periods[Y],1),y10:j(c._periods[Y],10),y100:j(c._periods[Y],100),y1000:j(c._periods[Y],1000),ol:h(O),on:c._periods[O],onn:this._minDigits(c._periods[O],2),onnn:this._minDigits(c._periods[O],3),o1:j(c._periods[O],1),o10:j(c._periods[O],10),o100:j(c._periods[O],100),o1000:j(c._periods[O],1000),wl:h(W),wn:c._periods[W],wnn:this._minDigits(c._periods[W],2),wnnn:this._minDigits(c._periods[W],3),w1:j(c._periods[W],1),w10:j(c._periods[W],10),w100:j(c._periods[W],100),w1000:j(c._periods[W],1000),dl:h(D),dn:c._periods[D],dnn:this._minDigits(c._periods[D],2),dnnn:this._minDigits(c._periods[D],3),d1:j(c._periods[D],1),d10:j(c._periods[D],10),d100:j(c._periods[D],100),d1000:j(c._periods[D],1000),hl:h(H),hn:c._periods[H],hnn:this._minDigits(c._periods[H],2),hnnn:this._minDigits(c._periods[H],3),h1:j(c._periods[H],1),h10:j(c._periods[H],10),h100:j(c._periods[H],100),h1000:j(c._periods[H],1000),ml:h(M),mn:c._periods[M],mnn:this._minDigits(c._periods[M],2),mnnn:this._minDigits(c._periods[M],3),m1:j(c._periods[M],1),m10:j(c._periods[M],10),m100:j(c._periods[M],100),m1000:j(c._periods[M],1000),sl:h(S),sn:c._periods[S],snn:this._minDigits(c._periods[S],2),snnn:this._minDigits(c._periods[S],3),s1:j(c._periods[S],1),s10:j(c._periods[S],10),s100:j(c._periods[S],100),s1000:j(c._periods[S],1000)};var l=e;for(var i=0;i<7;i++){var m='yowdhms'.charAt(i);var o=new RegExp('\\{'+m+'<\\}(.*)\\{'+m+'>\\}','g');l=l.replace(o,(d[i]?'$1':''))}$.each(k,function(n,v){var a=new RegExp('\\{'+n+'\\}','g');l=l.replace(a,v)});return l},_minDigits:function(a,b){a=''+a;if(a.length>=b){return a}a='0000000000'+a;return a.substr(a.length-b)},_determineShow:function(a){var b=this._get(a,'format');var c=[];c[Y]=(b.match('y')?'?':(b.match('Y')?'!':null));c[O]=(b.match('o')?'?':(b.match('O')?'!':null));c[W]=(b.match('w')?'?':(b.match('W')?'!':null));c[D]=(b.match('d')?'?':(b.match('D')?'!':null));c[H]=(b.match('h')?'?':(b.match('H')?'!':null));c[M]=(b.match('m')?'?':(b.match('M')?'!':null));c[S]=(b.match('s')?'?':(b.match('S')?'!':null));return c},_calculatePeriods:function(f,g,h){f._now=h;f._now.setMilliseconds(0);var i=new Date(f._now.getTime());if(f._since){if(h.getTime()<f._since.getTime()){f._now=h=i}else{h=f._since}}else{i.setTime(f._until.getTime());if(h.getTime()>f._until.getTime()){f._now=h=i}}var j=[0,0,0,0,0,0,0];if(g[Y]||g[O]){var k=$.countdown._getDaysInMonth(h.getFullYear(),h.getMonth());var l=$.countdown._getDaysInMonth(i.getFullYear(),i.getMonth());var m=(i.getDate()==h.getDate()||(i.getDate()>=Math.min(k,l)&&h.getDate()>=Math.min(k,l)));var n=function(a){return(a.getHours()*60+a.getMinutes())*60+a.getSeconds()};var o=Math.max(0,(i.getFullYear()-h.getFullYear())*12+i.getMonth()-h.getMonth()+((i.getDate()<h.getDate()&&!m)||(m&&n(i)<n(h))?-1:0));j[Y]=(g[Y]?Math.floor(o/12):0);j[O]=(g[O]?o-j[Y]*12:0);var p=function(a,b,c){var d=(a.getDate()==c);var e=$.countdown._getDaysInMonth(a.getFullYear()+b*j[Y],a.getMonth()+b*j[O]);if(a.getDate()>e){a.setDate(e)}a.setFullYear(a.getFullYear()+b*j[Y]);a.setMonth(a.getMonth()+b*j[O]);if(d){a.setDate(e)}return a};if(f._since){i=p(i,-1,l)}else{h=p(new Date(h.getTime()),+1,k)}}var q=Math.floor((i.getTime()-h.getTime())/1000);var r=function(a,b){j[a]=(g[a]?Math.floor(q/b):0);q-=j[a]*b};r(W,604800);r(D,86400);r(H,3600);r(M,60);r(S,1);if(q>0&&!f._since){var s=[1,12,4.3482,7,24,60,60];var t=S;var u=1;for(var v=S;v>=Y;v--){if(g[v]){if(j[t]>=u){j[t]=0;q=1}if(q>0){j[v]++;q=0;t=v;u=1}}u*=s[v]}}return j}});function extendRemove(a,b){$.extend(a,b);for(var c in b){if(b[c]==null){a[c]=null}}return a}$.fn.countdown=function(a){var b=Array.prototype.slice.call(arguments,1);if(a=='getTimes'||a=='settings'){return $.countdown['_'+a+'Countdown'].apply($.countdown,[this[0]].concat(b))}return this.each(function(){if(typeof a=='string'){$.countdown['_'+a+'Countdown'].apply($.countdown,[this].concat(b))}else{$.countdown._attachCountdown(this,a)}})};$.countdown=new Countdown()})(jQuery);

function ModalDialog(reference_element, dialog_params) {

    var dialog = null;
    var data_div = $(document.createElement('div'));

    function show(message) {
        if (dialog === null)
        {
            initialize(reference_element);
        }
        data_div.empty().append(message);
        dialog.dialog("open");
    }

    function initialize(reference_element) {
        dialog = data_div.dialog(dialog_params(reference_element));
    }

    function close()
    {
        dialog.dialog('close');
    }

    function destroy()
    {
        dialog.dialog('destroy');
    }

    return {
        show: show,
        destroy: destroy,
        close: close
    };
}


function ErrorDialog() {
    return new ModalDialog($(document.createElement('div')), function(element) {
        return {
            autoOpen: false,
            minHeight: 20,
            title: "We're Sorry!",
            dialogClass: 'error-dialog'
        };
    });

}



function time(time_in_seconds) {

    function to_string() {
        if (time_in_seconds < 60) {
            return time_in_seconds + " seconds";
        }
        else {
            return Math.round(time_in_seconds / 60) + " minutes";
        }
    }

    return {
        to_string: to_string
    };

}

function elementDetails(element) {

    var element_padding_left = (+element.css("padding-left").replace("px", ""));
    var left = element.offset().left;
    var top = element.offset().top;

    return {
        left: left,
        top: top,
        padding_left: element_padding_left,
        width: element.width(),
        height: element.height()
    };
}

function warningDialogParameters(reference_element) {

    var reference_element_details = elementDetails(reference_element);
    var dialog_width = 300;

    function get_left_position() {
        return reference_element_details.left + reference_element_details.padding_left +
               reference_element_details.width - dialog_width;
    }

    function get_top_position() {
        return reference_element_details.top + reference_element_details.height;
    }

    return {
        position:[get_left_position(), get_top_position()],
        width:dialog_width,
        resizable: false,
        autoOpen: false,
        minHeight: 0,
        title: "Please note..."
    };
}


function ExpiredDialogParameters(reference_element)
{
    return $.extend(warningDialogParameters(reference_element), {
        closeOnEscape : false,
        modal:true,
        buttons: {
            Ok: function() {
                $(this).dialog("close");
            }
        },
        close: function() {
            reference_element.trigger('expirationDialogClosed');
        }});
}

function Countdown(element)
{
    function From(expiration_time_interval)
    {
        var warning_time = null;

        function warn_after(warning_time_interval)
        {
            warning_time = warning_time_interval;
            return {start : start};
        }

        function start()
        {
            element.countdown({until: expiration_time_interval, compact: true, format: 'MS',
                description: '', onTick: on_timer_tick});
            element.removeClass('.expiration-timer-hidden').addClass('expiration-timer-visible');
        }

        function stop(){
            element.countdown('pause');            
        }

        function on_timer_tick(periods)
        {
            switch ($.countdown.periodsToSeconds(periods))
            {
                case warning_time:
                    element.trigger('approaching_deadline');
                    break;
                case 0:
                    element.trigger('expired');
            }
        }

        return {
            warn_after : warn_after,
            start : start,
            stop: stop
        };
    }

    return {
        from : From
    };
}



function expirationTimer(expiration_time_interval, warning_time_interval, element, dialog, countdown) {


    var message_dialog = dialog(element, warningDialogParameters);
    var expired_message = "<div>Time Out </div>" +
                          "<div>You have exceeded the time limit and your seats have been released. </div>";


    function bind_timer_events() {
        var approaching_deadline_event = 'approaching_deadline';
        var expired_event = 'expired';

        element.unbind(approaching_deadline_event).bind(approaching_deadline_event, show_warning);
        element.unbind(expired_event).bind(expired_event, show_expired);
    }

    function start()
    {
        var timer = countdown(element).from(expiration_time_interval);
        $("body").bind("payment_successful", function(){
            timer.stop();
        });
        timer.warn_after(warning_time_interval).start();
        show_message(get_formatted_warning_message(expiration_time_interval));
    }

    function show_warning()
    {
        show_message(get_formatted_warning_message(warning_time_interval));
    }

    function show_expired()
    {
        var expired_message_dialog = dialog(element, ExpiredDialogParameters);
        message_dialog.close();
        expired_message_dialog.show(expired_message);
    }

    function show_message(message)
    {
        message_dialog.show(message);
    }

    function get_formatted_warning_message(time_in_seconds)
    {
        return 'You have about ' + time(time_in_seconds).to_string() + ' remaining to complete your purchase.' +
               ' Seats not purchased within this period will be released.';
    }

    bind_timer_events();

    return {  start: start  };

}

function LoginWidgetValidator()
{
    var validationRules = {
        rules :{
            "user[email]": {
                required: true,
                email: true
            },
            "user[password]": {
                required: true
            }
        },
        messages:{
            "user[email]": {
                required: "Email address is required.",
                email: "Please enter a valid email address, example: you@yourdomain.com."
            },
            "user[password]": {
                required: "Password is required."
            }
        }
    };

    function getValidatorRules()                        
    {
        return validationRules;
    }

    return {
        getValidatorRules : getValidatorRules
    };
}


(function($) {

    $(function()
    {
        $.ajaxSetup({
            timeout:900000
        });

        $('.action-bar').action_bar();

        $('li#expiration-timer').bind('expirationDialogClosed', function() {
            var element = $("<div></div>").addClass("ui-widget-overlay");
            element.css({ width: $(document).width(), height: $(document).height()});
            $('body').append(element);
            location.reload();
        });

        $("li#login").login_widget({validationRules: new LoginWidgetValidator().getValidatorRules()});

        $('.action-bar').bind("action_bar_login_clicked", function(event, ui) {
            $("li#login").login_widget("show");
        });

        $('li#login').bind("login_widget_login_successful", function(event, ui) {
            $('.action-bar').action_bar("refresh");
            $("li#login").login_widget("hide");
        });

        $('body').bind("login_widget_loaded", function(event, ui) {
            $('.action-bar').action_bar("show");
        });
    });


})(jQuery);

function showLoader(loaderDiv)
{
    jQuery(loaderDiv).html('');
    jQuery(loaderDiv).addClass("ajax-loader");
}

function hideLoader(loaderDiv)
{
    jQuery(loaderDiv).removeClass("ajax-loader");
}



(function($) {
    $(function() {
        var search_form = $(".search-form");
        search_form.find(".search").click(function(){
            $(this).parent('form').submit();
        });

        search_form.submit(function(event) {
            var searchString = $(event.target).find("input[name=q]").val();
            if($.trim(searchString).length === 0) {
                return false;
            }
        });
    });

})(jQuery);

var allUIMenus = [];
$.fn.menu = function(options) {
    var caller = this;
    var options = options;
    var m = new Menu(caller, options);
    allUIMenus.push(m);
    $(this).mousedown(function() {
        if (!m.menuOpen) {
            m.showLoading()
        }
    }).hover(function() {
        if (m.menuOpen == false) {
            m.showMenu()
        } else {
            m.kill()
        }
        ;
        return false
    })
};
function Menu(caller, options) {
    var menu = this;
    var caller = $(caller);
    var container = $('<div class="fg-menu-container ui-widget ui-widget-content ui-corner-all">' + options.content + '</div>');
    this.menuOpen = false;
    this.menuExists = false;
    var options = jQuery.extend({content:null,width:180,maxHeight:180,positionOpts:{posX:'left',posY:'bottom',offsetX:0,offsetY:0,directionH:'right',directionV:'down',detectH:true,detectV:true,linkToFront:false},showSpeed:200,callerOnState:'ui-state-active',loadingState:'ui-state-loading',linkHover:'ui-state-hover',linkHoverSecondary:'li-hover',crossSpeed:200,crumbDefaultText:'Choose an option:',backLink:true,backLinkText:'Back',flyOut:false,flyOutOnState:'ui-state-default',nextMenuLink:'ui-icon-triangle-1-e',topLinkText:'All',nextCrumbLink:'ui-icon-carat-1-e'}, options);
    var killAllMenus = function() {
        $.each(allUIMenus, function(i) {
            if (allUIMenus[i].menuOpen) {
                allUIMenus[i].kill()
            }
        })
    };
    this.kill = function() {
        caller.removeClass(options.loadingState).removeClass('fg-menu-open').removeClass(options.callerOnState);
        container.find('li').removeClass(options.linkHoverSecondary).find('a').removeClass(options.linkHover);
        if (options.flyOutOnState) {
            container.find('li a').removeClass(options.flyOutOnState)
        }
        ;
        if (options.callerOnState) {
            caller.removeClass(options.callerOnState)
        }
        ;
        if (container.is('.fg-menu-ipod')) {
            menu.resetDrilldownMenu()
        }
        ;
        if (container.is('.fg-menu-flyout')) {
            menu.resetFlyoutMenu()
        }
        ;
        container.parent().hide();
        menu.menuOpen = false;
//        $(document).unbind('click', killAllMenus);
//        $(document).unbind('keydown')
    };
    this.showLoading = function() {
        caller.addClass(options.loadingState)
    };
    this.showMenu = function() {
        killAllMenus();
        menu.kill();
        menu.create();
        caller.addClass('fg-menu-open').addClass(options.callerOnState);
        container.parent().show().click(function() {
//            menu.kill();
//            return false
        });
        container.hide().slideDown(options.showSpeed).find('.fg-menu:eq(0)');
        menu.menuOpen = true;
        caller.removeClass(options.loadingState);
//        $(document).click(killAllMenus);
//        $(document).keydown(function(event) {
//            var e;
//            if (event.which != "") {
//                e = event.which
//            } else if (event.charCode != "") {
//                e = event.charCode
//            } else if (event.keyCode != "") {
//                e = event.keyCode
//            }
//            var menuType = ($(event.target).parents('div').is('.fg-menu-flyout')) ? 'flyout' : 'ipod';
//            switch (e) {case 37:if (menuType == 'flyout') {
//                $(event.target).trigger('mouseout');
//                if ($('.' + options.flyOutOnState).size() > 0) {
//                    $('.' + options.flyOutOnState).trigger('mouseover')
//                }
//            };if (menuType == 'ipod') {
//                $(event.target).trigger('mouseout');
//                if ($('.fg-menu-footer').find('a').size() > 0) {
//                    $('.fg-menu-footer').find('a').trigger('click')
//                }
//                ;
//                if ($('.fg-menu-header').find('a').size() > 0) {
//                    $('.fg-menu-current-crumb').prev().find('a').trigger('click')
//                }
//                ;
//                if ($('.fg-menu-current').prev().is('.fg-menu-indicator')) {
//                    $('.fg-menu-current').prev().trigger('mouseover')
//                }
//            };return false;break;case 38:if ($(event.target).is('.' + options.linkHover)) {
//                var prevLink = $(event.target).parent().prev().find('a:eq(0)');
//                if (prevLink.size() > 0) {
//                    $(event.target).trigger('mouseout');
//                    prevLink.trigger('mouseover')
//                }
//            } else {
//                container.find('a:eq(0)').trigger('mouseover')
//            }return false;break;case 39:if ($(event.target).is('.fg-menu-indicator')) {
//                if (menuType == 'flyout') {
//                    $(event.target).next().find('a:eq(0)').trigger('mouseover')
//                } else if (menuType == 'ipod') {
//                    $(event.target).trigger('click');
//                    setTimeout(function() {
//                        $(event.target).next().find('a:eq(0)').trigger('mouseover')
//                    }, options.crossSpeed)
//                }
//            };return false;break;case 40:if ($(event.target).is('.' + options.linkHover)) {
//                var nextLink = $(event.target).parent().next().find('a:eq(0)');
//                if (nextLink.size() > 0) {
//                    $(event.target).trigger('mouseout');
//                    nextLink.trigger('mouseover')
//                }
//            } else {
//                container.find('a:eq(0)').trigger('mouseover')
//            }return false;break;case 27:killAllMenus();break;case 13:if ($(event.target).is('.fg-menu-indicator') && menuType == 'ipod') {
//                $(event.target).trigger('click');
//                setTimeout(function() {
//                    $(event.target).next().find('a:eq(0)').trigger('mouseover')
//                }, options.crossSpeed)
//            };break
//            }
//        });
    };
    this.create = function() {
        container.css({width:options.width}).appendTo(caller).find('ul').not('.fg-menu-breadcrumb').addClass('fg-menu');
        container.find('ul, li a').addClass('ui-corner-all');
        container.find('ul').attr('role', 'menu').eq(0).attr('aria-activedescendant', 'active-menuitem').attr('aria-labelledby', caller.attr('id'));
        container.find('li').attr('role', 'menuitem');
        container.find('li:has(ul)').attr('aria-haspopup', 'true').find('ul').attr('aria-expanded', 'false');
        container.find('a').attr('tabindex', '-1');
        if (container.find('ul').size() > 1) {
            if (options.flyOut) {
                menu.flyout(container, options)
            } else {
                menu.drilldown(container, options)
            }
        } else {
//            container.find('a').click(function() {
//                menu.chooseItem(this);
//                return false
//            })
        }
        ;
        if (options.linkHover) {
            var allLinks = container.find('.fg-menu li a');
            allLinks.hover(function() {
                var menuitem = $(this);
                $('.' + options.linkHover).removeClass(options.linkHover).blur().parent().removeAttr('id');
                $(this).addClass(options.linkHover).focus().parent().attr('id', 'active-menuitem')
            }, function() {
                $(this).removeClass(options.linkHover).blur().parent().removeAttr('id')
            })
        }
        ;
        if (options.linkHoverSecondary) {
            container.find('.fg-menu li').hover(function() {
                $(this).siblings('li').removeClass(options.linkHoverSecondary);
                if (options.flyOutOnState) {
                    $(this).siblings('li').find('a').removeClass(options.flyOutOnState)
                }
                $(this).addClass(options.linkHoverSecondary)
            }, function() {
                $(this).removeClass(options.linkHoverSecondary)
            })
        }
        ;
        menu.setPosition(container, caller, options);
        menu.menuExists = true
    };
    this.chooseItem = function(item) {
        menu.kill();
        $('#menuSelection').text($(item).text())
    }
}
;
Menu.prototype.flyout = function(container, options) {
    var menu = this;
    this.resetFlyoutMenu = function() {
        var allLists = container.find('ul ul');
        allLists.removeClass('ui-widget-content').hide()
    };
    container.addClass('fg-menu-flyout').find('li:has(ul)').each(function() {
        var linkWidth = container.width();
        var showTimer,hideTimer;
        var allSubLists = $(this).find('ul');
        allSubLists.css({left:linkWidth,width:linkWidth}).hide();
        $(this).find('a:eq(0)').addClass('fg-menu-indicator').html('<span>' + $(this).find('a:eq(0)').text() + '</span><span class="ui-icon ' + options.nextMenuLink + '"></span>').hover(function() {
            clearTimeout(hideTimer);
            var subList = $(this).next();
            if (!fitVertical(subList, $(this).offset().top)) {
                subList.css({top:'auto',bottom:0})
            }
            ;
            if (!fitHorizontal(subList, $(this).offset().left + 100)) {
                subList.css({left:'auto',right:linkWidth,'z-index':999})
            }
            ;
            showTimer = setTimeout(function() {
                subList.addClass('ui-widget-content').show(options.showSpeed).attr('aria-expanded', 'true')
            }, 300)
        }, function() {
            clearTimeout(showTimer);
            var subList = $(this).next();
            hideTimer = setTimeout(function() {
                subList.removeClass('ui-widget-content').hide(options.showSpeed).attr('aria-expanded', 'false')
            }, 400)
        });
        $(this).find('ul a').hover(function() {
            clearTimeout(hideTimer);
            if ($(this).parents('ul').prev().is('a.fg-menu-indicator')) {
                $(this).parents('ul').prev().addClass(options.flyOutOnState)
            }
        }, function() {
            hideTimer = setTimeout(function() {
                allSubLists.hide(options.showSpeed);
                container.find(options.flyOutOnState).removeClass(options.flyOutOnState)
            }, 500)
        })
    });
//    container.find('a').click(function() {
//        menu.chooseItem(this);
//    })
};
Menu.prototype.drilldown = function(container, options) {
    var menu = this;
    var topList = container.find('.fg-menu');
    var breadcrumb = $('<ul class="fg-menu-breadcrumb ui-widget-header ui-corner-all ui-helper-clearfix"></ul>');
    var crumbDefaultHeader = $('<li class="fg-menu-breadcrumb-text">' + options.crumbDefaultText + '</li>');
    var firstCrumbText = (options.backLink) ? options.backLinkText : options.topLinkText;
    var firstCrumbClass = (options.backLink) ? 'fg-menu-prev-list' : 'fg-menu-all-lists';
    var firstCrumbLinkClass = (options.backLink) ? 'ui-state-default ui-corner-all' : '';
    var firstCrumbIcon = (options.backLink) ? '<span class="ui-icon ui-icon-triangle-1-w"></span>' : '';
    var firstCrumb = $('<li class="' + firstCrumbClass + '"><a href="#" class="' + firstCrumbLinkClass + '">' + firstCrumbIcon + firstCrumbText + '</a></li>');
    container.addClass('fg-menu-ipod');
    if (options.backLink) {
        breadcrumb.addClass('fg-menu-footer').appendTo(container).hide()
    } else {
        breadcrumb.addClass('fg-menu-header').prependTo(container)
    }
    ;
    breadcrumb.append(crumbDefaultHeader);
    var checkMenuHeight = function(el) {
        if (el.height() > options.maxHeight) {
            el.addClass('fg-menu-scroll')
        }
        ;
        el.css({height:options.maxHeight})
    };
    var resetChildMenu = function(el) {
        el.removeClass('fg-menu-scroll').removeClass('fg-menu-current').height('auto')
    };
    this.resetDrilldownMenu = function() {
        $('.fg-menu-current').removeClass('fg-menu-current');
        topList.animate({left:0}, options.crossSpeed, function() {
            $(this).find('ul').each(function() {
                $(this).hide();
                resetChildMenu($(this))
            });
            topList.addClass('fg-menu-current')
        });
        $('.fg-menu-all-lists').find('span').remove();
        breadcrumb.empty().append(crumbDefaultHeader);
        $('.fg-menu-footer').empty().hide();
        checkMenuHeight(topList)
    };
    topList.addClass('fg-menu-content fg-menu-current ui-widget-content ui-helper-clearfix').css({width:container.width()}).find('ul').css({width:container.width(),left:container.width()}).addClass('ui-widget-content').hide();
    checkMenuHeight(topList);
    topList.find('a').each(function() {
        if ($(this).next().is('ul')) {
            $(this).addClass('fg-menu-indicator').each(function() {
                $(this).html('<span>' + $(this).text() + '</span><span class="ui-icon ' + options.nextMenuLink + '"></span>')
            }).click(function() {
                var nextList = $(this).next();
                var parentUl = $(this).parents('ul:eq(0)');
                var parentLeft = (parentUl.is('.fg-menu-content')) ? 0 : parseFloat(topList.css('left'));
                var nextLeftVal = Math.round(parentLeft - parseFloat(container.width()));
                var footer = $('.fg-menu-footer');
                resetChildMenu(parentUl);
                checkMenuHeight(nextList);
                topList.animate({left:nextLeftVal}, options.crossSpeed);
                nextList.show().addClass('fg-menu-current').attr('aria-expanded', 'true');
                var setPrevMenu = function(backlink) {
                    var b = backlink;
                    var c = $('.fg-menu-current');
                    var prevList = c.parents('ul:eq(0)');
                    c.hide().attr('aria-expanded', 'false');
                    resetChildMenu(c);
                    checkMenuHeight(prevList);
                    prevList.addClass('fg-menu-current').attr('aria-expanded', 'true');
                    if (prevList.hasClass('fg-menu-content')) {
                        b.remove();
                        footer.hide()
                    }
                };
                if (options.backLink) {
                    if (footer.find('a').size() == 0) {
                        footer.show();
                        $('<a href="#"><span class="ui-icon ui-icon-triangle-1-w"></span> <span>Back</span></a>').appendTo(footer).click(function() {
                            var b = $(this);
                            var prevLeftVal = parseFloat(topList.css('left')) + container.width();
                            topList.animate({left:prevLeftVal}, options.crossSpeed, function() {
                                setPrevMenu(b)
                            });
                            return false
                        })
                    }
                } else {
                    if (breadcrumb.find('li').size() == 1) {
                        breadcrumb.empty().append(firstCrumb);
                        firstCrumb.find('a').click(function() {
                            menu.resetDrilldownMenu();
                            return false
                        })
                    }
                    $('.fg-menu-current-crumb').removeClass('fg-menu-current-crumb');
                    var crumbText = $(this).find('span:eq(0)').text();
                    var newCrumb = $('<li class="fg-menu-current-crumb"><a href="javascript://" class="fg-menu-crumb">' + crumbText + '</a></li>');
                    newCrumb.appendTo(breadcrumb).find('a').click(function() {
                        if ($(this).parent().is('.fg-menu-current-crumb')) {
                            menu.chooseItem(this)
                        } else {
                            var newLeftVal = -($('.fg-menu-current').parents('ul').size() - 1) * 180;
                            topList.animate({left:newLeftVal}, options.crossSpeed, function() {
                                setPrevMenu()
                            });
                            $(this).parent().addClass('fg-menu-current-crumb').find('span').remove();
                            $(this).parent().nextAll().remove()
                        }
                        ;
                        return false
                    });
                    newCrumb.prev().append(' <span class="ui-icon ' + options.nextCrumbLink + '"></span>')
                }
                ;
                return false
            })
        } else {
            $(this).click(function() {
                menu.chooseItem(this);
                return false
            })
        }
    })
};
Menu.prototype.setPosition = function(widget, caller, options) {
    var el = widget;
    var referrer = caller;
    var dims = {callerHeight:referrer.height(),refX:referrer.offset().left,refY:referrer.offset().top,refW:referrer.getTotalWidth(),refH:referrer.getTotalHeight()};
    var options = options;
    var xVal,yVal;
    var helper = $('<div class="positionHelper"></div>');
    helper.css({position:'absolute',left:0,top:0,width:dims.refW,height:dims.refH});
    el.wrap(helper);
    switch (options.positionOpts.posX) {case'left':xVal = 0;break;case'center':xVal = dims.refW / 2;break;case'right':xVal = dims.refW;break
    }
    ;
    switch (options.positionOpts.posY) {case'top':yVal = 0;break;case'center':yVal = dims.refH / 2;break;case'bottom':yVal = dims.refH;break
    }
    ;
    xVal += options.positionOpts.offsetX;
    yVal = referrer.height();
    if (options.positionOpts.directionV == 'up') {
        el.css({top:'auto',bottom:yVal});
        if (options.positionOpts.detectV && !fitVertical(el)) {
            el.css({bottom:'auto',top:yVal})
        }
    } else {
        el.css({bottom:'auto',top:yVal});
        if (options.positionOpts.detectV && !fitVertical(el)) {
            el.css({top:'auto',bottom:dims.refH})
        }
    }
    ;
    if (options.positionOpts.directionH == 'left') {
        el.css({left:'auto',right:xVal});
        if (options.positionOpts.detectH && !fitHorizontal(el)) {
            el.css({right:'auto',left:xVal})
        }
    } else {
        el.css({right:'auto',left:xVal});
        if (options.positionOpts.detectH && !fitHorizontal(el)) {
            el.css({left:'auto',right:xVal})
        }
    }
    ;
    if (options.positionOpts.linkToFront) {
        referrer.clone().addClass('linkClone').css({position:'absolute',top:0,right:'auto',bottom:'auto',left:0,width:referrer.width(),height:referrer.height()}).insertAfter(el)
    }
};
function sortBigToSmall(a, b) {
    return b - a
}
;
jQuery.fn.getTotalWidth = function() {
    return $(this).width() + parseInt($(this).css('paddingRight')) + parseInt($(this).css('paddingLeft')) + parseInt($(this).css('borderRightWidth')) + parseInt($(this).css('borderLeftWidth'))
};
jQuery.fn.getTotalHeight = function() {
    return $(this).height() + parseInt($(this).css('paddingTop')) + parseInt($(this).css('paddingBottom')) + parseInt($(this).css('borderTopWidth')) + parseInt($(this).css('borderBottomWidth'))
};
function getScrollTop() {
    return self.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop
}
;
function getScrollLeft() {
    return self.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft
}
;
function getWindowHeight() {
    var de = document.documentElement;
    return self.innerHeight || (de && de.clientHeight) || document.body.clientHeight
}
;
function getWindowWidth() {
    var de = document.documentElement;
    return self.innerWidth || (de && de.clientWidth) || document.body.clientWidth
}
;
function fitHorizontal(el, leftOffset) {
    var leftVal = parseInt(leftOffset) || $(el).offset().left;
    return(leftVal + $(el).width() <= getWindowWidth() + getScrollLeft() && leftVal - getScrollLeft() >= 0)
}
;
function fitVertical(el, topOffset) {
    var topVal = parseInt(topOffset) || $(el).offset().top;
    return(topVal + $(el).height() <= getWindowHeight() + getScrollTop() && topVal - getScrollTop() >= 0)
}
;
Number.prototype.pxToEm = String.prototype.pxToEm = function(settings) {
    settings = jQuery.extend({scope:'body',reverse:false}, settings);
    var pxVal = (this == '') ? 0 : parseFloat(this);
    var scopeVal;
    var getWindowWidth = function() {
        var de = document.documentElement;
        return self.innerWidth || (de && de.clientWidth) || document.body.clientWidth
    };
    if (settings.scope == 'body' && $.browser.msie && (parseFloat($('body').css('font-size')) / getWindowWidth()).toFixed(1) > 0.0) {
        var calcFontSize = function() {
            return(parseFloat($('body').css('font-size')) / getWindowWidth()).toFixed(3) * 16
        };
        scopeVal = calcFontSize()
    } else {
        scopeVal = parseFloat(jQuery(settings.scope).css("font-size"))
    }
    ;
    var result = (settings.reverse == true) ? (pxVal * scopeVal).toFixed(2) + 'px' : (pxVal / scopeVal).toFixed(2) + 'em';
    return result
};

$(document).ready(function() {
    $('#navigation ul.main li.top-level .menu-panel').each(function(index, item) {

        $(item).parent().menu({
            content: $(item).html(),
            flyOut: true,
            width: 'auto'
        });
    });
});


(function($) {
    $(document).ready(function() {
        //jQuery validator default settings
        $.validator.setDefaults({
            errorClass : 'validation-msg',
            errorElement: "div",
            onfocusout: function(element) {
                $(element).valid();
            }
        });
    });

    $.validator.addMethod(
            "notdigits",
            function(value, element) {
                return this.optional(element) || !(/^\d*$/.test(value));
            });

    $.validator.addMethod("validContribution", function(value, element) {
        var amount = $(element.form).find("#contribution_amount").val();
        var otherAmount = $(element.form).find("#contribution_other_amount").val();
        if (parseFloat(otherAmount) <= 0.00 && amount > 0){
          return false;  
        }
        return amount > 0 || otherAmount >= 0.01;
    });


})(jQuery);