﻿/// <reference path="http://ajax.microsoft.com/ajax/jQuery/jquery-1.4.1.js " />

//close window btn
function closeWindow() {
    window.close();
}

//print btn
function Print() {
    window.print();
}

/// Auto-tab a form input to the next input field
function WireAutoTab(CurrentElement, NextElement, FieldLength) {
    //Get a reference to the two elements in the tab sequence.
    //var CurrentElement = $('#' + CurrentElementID);
    //var NextElement = $('#' + NextElementID);

    CurrentElement.keyup(function (e) {
        //Retrieve which key was pressed.
        var KeyID = (window.event) ? event.keyCode : e.keyCode;

        //If the user has filled the textbox to the given length and
        //the user just pressed a number or letter, then move the
        //cursor to the next element in the tab sequence.   
        if (CurrentElement.val().length >= FieldLength
            && ((KeyID >= 48 && KeyID <= 90) ||
            (KeyID >= 96 && KeyID <= 105)))
            NextElement.focus();
    });
}

function SetTextboxMasking(txt) {
    $("#" + txt).bind({
        "click": function () {
            /* check for error */
            //if($(this).data("validationFailed"))clearError(this);

            /* check if user clicking for first time */
            if (!$(this).data("init")) {
                $(this).data("init", true);
                $(this).data("initialValue", $(this).val());
                $(this).val("");
            } else {
                if (!$(this).data("valueChanged") || $(this).val() == $(this).data("initialValue")) $(this).val("");
            }
        },
        "blur": function () {
            // set empty texts to their initial value
            if ($(this).val() == "") {
                $(this).val($(this).data("initialValue"))
            } else {
                if ($(this).val() != $(this).data("initialValue")) {
                    $(this).data("valueChanged", true);
                } else {
                    $(this).data("valueChanged", false);
                }
            };
        }
    });
}

/// <reference path="http://ajax.microsoft.com/ajax/jQuery/jquery-1.4.1.js " />
function SetHover(imgctl, offimage, overimage) {
    $("#" + imgctl).hover(function () { $(this).attr("src", overimage); }, function () { $(this).attr("src", offimage); });
    //$("#" + imgid).first().attr("src", newimgpath);
}

function ShowLoading() {

    $.fn.colorbox({
        href: "../../../includes/images/spinny_loader.gif",
        overlayClose: false,
        escKey: false,
        transition: 'none',
        onOpen: function () {
            $('body').addClass('loading');
        },
        onClosed: function () {
            $('body').removeClass('loading');
        }
    });
}

//new loading thing that'll probably be used more with all the redesign stuff

function LoadingOverlay(text) {
    if (text == '' || text == null) {
        var msgtext = 'Your payment and application are being processed. Do not close or navigate away from this window.';
    }
    else {
        var msgtext = text
    }
    var overlay = $('<div></div>').attr('id', 'loadingoverlay').css({
        'height': $('body').height(),
        'width': '100%',
        'background': 'url("../../includes/images/overlay.png")',
        'position': 'fixed',
        'z-index': '20'
    }),
        spinner = $('<div><img src="../../includes/images/loader.gif" /><br /><br /></div>').css({
            'margin': '0px auto',
            'width': '500px',
            'text-align': 'center',
            'margin-top': '375px'
        }),
        msg = $('<span>' + msgtext + '</span>').css({
            'color': '#fff',
            'font-size': '20px'
        });


    spinner.append(msg);
    overlay.append(spinner);
    $('body').prepend(overlay);
}

//A function for making an input "val" only show text in a currency format. Any number of digits, with an optional decimal point.
//If the decimal point exists, then only 2 characters are allowed after it
function CheckFormatCurrency(e, val) {

    var cCode;

    if (window.event) // IE
    {
        cCode = e.keyCode;
    }
    else if (e.which) // Netscape/Firefox/Opera
    {
        cCode = e.which;
    }
    //alert(cCode);
    var strPass = val.value;

    //Grab the index of the decimal point
    var decimalindex = strPass.indexOf('.');
    var cents;
    var decimalexists = false;

    //if we have a decimal point, grab the cents
    if (decimalindex > -1) {
        decimalexists = true;

        cents = strPass.substring(decimalindex + 1);
    }

    //backspace, delete, tab
    if (cCode == 8 || cCode == 9 || cCode == 46)
        return true;
    //number
    else if ((cCode >= 48 && cCode <= 57) || (cCode >= 96 && cCode <= 105)) {
        //If we already have 2 cents digits, then don't add anymore. Money only has 2 cents digits.
        if (decimalexists && cents.length > 1) {
            if (e.preventDefault) e.preventDefault();
            e.returnValue = false;
            return false;
        }
        else
            return true;
    }
    //decimal point/period
    else if (cCode == 190 || cCode == 110) {
        //only add if the decimal point/period does not already exist
        if (!decimalexists)
            return true;
        else {
            if (e.preventDefault) e.preventDefault();
            e.returnValue = false;
            return false;
        }
    }
    //anything else, don't show it.
    else {
        if (e.preventDefault) e.preventDefault();
        e.returnValue = false;
        return false;
    }
}

//Reset a text box if nothing is entered.
function ResetBox(box) {
    if (box.value == "")
        box.value = "0.00";
}

//Clear out the text box if its 0.
function ClearBox(box) {
    if (box.value == "0" || box.value == "0.0" || box.value == "0.00")
        box.value = "";
}

function numericOnly(e, val) {
    var cCode;

    if (window.event) // IE
    {
        cCode = e.keyCode;
    }
    else if (e.which) // Netscape/Firefox/Opera
    {
        cCode = e.which;
    }

    //numbers and backspace and tab
    if ((cCode >= 48 && cCode <= 57) || (cCode >= 96 && cCode <= 105) || cCode == 8 || cCode == 46 || cCode == 9) {
        return true;
    }
    else {
        if (e.preventDefault) e.preventDefault();
        e.returnValue = false;
        return false;
    }
}

/* Binds i-item/tooltip to controls */
function enhancedTooltip() {
    var tt_over, tt_open, tt_ctl, tt_offset, tt_difference = { height: 0, expandup: false }, tt_contentOver, el;

    /* pseudo-viewport */
    viewport = function (event, obj) {
        return {
            clientX: event.clientX,
            clientY: event.clientY,
            currentX: $(window).width(),
            currentY: $(window).height()
        }
    }

    /* set proper cursor style on tooltip'd elements */
    $("[tooltip]").css("cursor", "pointer");

    /* function to bind tooltips with controls - call "bindControls()" for any dynamic tooltips/controls being loaded after dom.complete (say, via ajaxy goodness) */
    var bindControlsInit = function () {
        if ($("[tooltipcontrol]").length) {
            $("[tooltipcontrol]").each(function (index) {
                var control = "#" + $(this).attr('tooltipcontrol');
                $(control).attr("tooltip", $(this).attr('tooltip'));
                $(this).detach();
            })
        }
    };

    /* bind it, bind it good */
    bindControlsInit();
    this.bindControls = bindControlsInit;

    /* zee events for controls */
    $("#tooltipContainer").live("mouseenter mouseleave", function (e) {
        tt_contentOver = tt_over = e.type == "mouseover" ? true : false;
        var _timeout = setTimeout(function () {
            if (!tt_over) {
                tt_open = false;
                $(el).animate({ "opacity": 0 }, 100, function () { $(el).remove() });
            }
        }, 300)
    })

    $("[tooltip]").live("mouseenter mouseleave", function (e) {
        tt_over = e.type == "mouseover" ? true : false;
        if (tt_open && ($(this).attr('id') != tt_ctl.id)) {
            $(el).remove();
            tt_open = false;
        }
        var id = tt_ctl = $(this).attr('id');
        handleTooltip(this, e, id)
    })

    /* handles read more link */
    $("#ttReadmore").live("click", function (e) {
        e.preventDefault();
        $(this).remove();
        $("#ttHidden").css("display", "inline");
        if (tt_difference.expandup) {
            var curTop = $("#tooltipContainer").css("top");
            $("#tooltipContainer").css("top", parseInt(curTop, 10) - tt_difference.height);
        }
    })

    /* creates the tooltip element */
    function handleTooltip(obj, event, item) {
        var that = obj, _height = 0, _width = 0;

        // increase or decrease _timer for how quickly the animation starts
        var _timer = 300;

        // increase or decrease _animation for how quickly the tooltip fades in/out
        var _animation = 300;

        var _timeout = setTimeout(function () {
            if (tt_over && (item == tt_ctl)) {
                if (!tt_open) {
                    var pos, dimensions = viewport(event, obj), heightDifference = 0;
                    tt_open = true;

                    tt_ctl = {
                        id: $(that).attr('id'),
                        text: $(that).attr('tooltip'),
                        width: $(that).width(),
                        height: $(that).height(),
                        offset: $(that).offset()
                    }
                    pos = {
                        ctlx: tt_ctl.offset.left + tt_ctl.width + 4,
                        ctly: tt_ctl.offset.top,
                        ttx: 0,
                        tty: 0
                    }

                    el = _tooltipContainer(tt_ctl.text);

                    $(el).css({ "opacity": 0, "visibility": "hidden" }).appendTo("body");

                    _height = $(el).height();
                    _width = $(el).width();

                    _availRight = dimensions.currentX - dimensions.clientX;
                    _availBottom = dimensions.currentY - (dimensions.clientY + tt_ctl.height);

                    if ($(el).find("#ttHidden").length) {
                        var _h = $(el).height();
                        $(el).find("#ttHidden").css({ "display": "none" });
                        tt_difference.height = heightDifference = _h - $(el).height();
                    }

                    if (_height + 20 > _availBottom) {
                        tt_difference.expandup = true;
                        pos.tty = (pos.ctly - (_height - 6)) + heightDifference
                    } else {
                        tt_difference.expandup = false;
                        pos.tty = pos.ctly
                    };

                    if (_width + 20 > _availRight) {
                        pos.ttx = pos.ctlx - (_width + 10);
                        if (_height + 10 > _availBottom) {
                            _diff = tt_ctl.height + 5;
                            pos.tty = pos.tty - (_diff);
                        } else {
                            pos.tty = pos.tty + tt_ctl.height + 5;
                        }
                    } else { pos.ttx = pos.ctlx };


                    $(el).css({ "left": pos.ttx, "top": pos.tty, "visibility": "visible" }).animate({ "opacity": 1 }, _animation);
                }
            } else {
                if (tt_open && (!tt_contentOver)) {
                    tt_open = false;
                    $(el).animate({ "opacity": 0 }, _animation, function () { $(el).remove() });
                }
            }
        }, _timer)
    }

    /* formats tooltip based on length of text  */
    function formatText(text) {
        // our regex
        var regText = new RegExp("^text\:");
        var regImg = new RegExp("^img\:");

        // let's check our input text
        if (regText.test(text)) {
            var text = text.replace("text:", "");
            return formatText(text);
        } else if (regImg.test(text)) {
            var text = text.replace("img:", "");
            return formatImg(text);
        } else {
            // just assume it's text
            return formatText(text);
        }

        function formatImg(text) {
            var t = "<img src='" + text + "' />";
            return { "text": t, "width": "auto !important", "class": "toolTipImage", readmore: false }
        }

        function formatText(text) {

            var t = text;

            // text.length smaller than _length will be displayed in the standard tooltip.
            var _length = 160;

            // text.length smaller than _length + _threshold will be displayed in a wider tooltip (specified by _width)
            var _threshold = 100;
            var _width = 260;

            if (t.length <= _length) {
                return t;
            } else {
                var _diff = t.length - _length;
                if (_diff <= _threshold) {
                    return { "text": text, "width": _width, "readmore": false }
                } else {
                    var e = t.substr(0, (_length + _threshold));
                    var r = t.substr((_length + _threshold), t.length - (_length + _threshold));

                    e = e + "<span id='ttReadmore'> ... <a href='#'>more</a></span>";
                    r = "<span id='ttHidden'>" + r + "</span>";

                    return { "text": e + r, "width": _width, "readmore": true }

                }
            }
        }
    }

    /* returns the element */
    var _tooltipContainer = function (text) {
        var t,
            text = formatText(text);


        var el = $("<div/>").attr({
            "id": "tooltipContainer"
        })

        if (typeof text === "string") {
            t = text;
        } else {
            t = text;
            if (t.hasOwnProperty("width")) {
                $(el).addClass("width", t['width']);
            }
            if (t.hasOwnProperty("class")) {
                $(el).addClass(t['class']);
            }
            t = text.text;
            _bool = false;
        }

        $(el).clone().attr({
            /* Set the dimensions here - this is the shadow */
            "id": "tooltipContent"
        }).appendTo(el);
        $(el).find("#tooltipContent").html(t);

        return el;
    }
}

/* Lead hover form handling */
var leadForm = {

    settings: {
        timer: undefined,
        url: undefined,
        ms: undefined,
        w: undefined,
        h: undefined
    },

    event: {
        set: function (url, ms, w, h) {
            leadForm.settings.url = url;
            leadForm.settings.ms = ms || 15000;
            leadForm.settings.w = w || 405;
            leadForm.settings.h = h || 690;
            leadForm.event.setTimer();
        },
        setTimer: function () {
            if (leadForm.settings.url) {
                leadForm.settings.timer = setInterval(leadForm.event.show, leadForm.settings.ms);
            }
        },
        show: function () {
            leadForm.event.kill();
            var _count = 0;
            if (EF.Global.Utilities.CookieManager.Check("EFFEDCK", "Count")) {
                _count = parseInt(EF.Global.Utilities.CookieManager.Consume("EFFEDCK", "Count"))
            }
            if (!(EF.Global.Utilities.CookieManager.Check("EFLD", "Viewed", "True") || _count > 1)) {
                $.fn.colorbox({
                    href: leadForm.settings.url,
                    iframe: true,
                    overlayClose: false,
                    innerWidth: leadForm.settings.w,
                    innerHeight: leadForm.settings.h,
                    opacity: 0.3,

                    onClosed: function () {
                        /* Create EFLD cookie */
                        EF.Global.Utilities.CookieManager.Session("EFLD", escape("Viewed=True"));

                        /* Increment counter */
                        _count = parseInt(EF.Global.Utilities.CookieManager.Consume("EFFEDCK", "Count")) + 1;
                        EF.Global.Utilities.CookieManager.Bake("EFFEDCK", "Count=" + _count, "180");
                    },
                    Init: function (url, timeout, width, height, iframe) {
                        /* Create counter cookie, if nec. */
                        if (!EF.Global.Utilities.CookieManager.Check("EFFEDCK", "Count")) {
                            EF.Global.Utilities.CookieManager.Bake("EFFEDCK", "Count=0", "180");
                        }
                        else {
                            var _count = parseInt(EF.Global.Utilities.CookieManager.Consume("EFFEDCK", "Count")) + 1;
                            EF.Global.Utilities.CookieManager.Bake("EFFEDCK", "Count=" + _count, "180");
                        }
                    }
                })
            }
        },

        kill: function () {
            if (leadForm.settings.timer) {
                clearInterval(leadForm.settings.timer);
            }
        }
    }
}

//added to EVA so cookie is properly created without the classic sites
var EF = {
    /* Short hand to return object in global */
    $_script: function () {
        return this.Global.ScriptHandler
    },
    $_util: function () {
        return this.Global.Utilities
    },
    /* -- Global */
    Global: {
        Utilities: {
            CookieManager: {
                /* Create cookie */
                Bake: function (name, value, days) {
                    days = days || 1;
                    var exdate = new Date();
                    exdate.setDate(exdate.getDate() + days);
                    var exdatestring = ((days == null) ? "" : "expires=" + exdate.toUTCString() + ";");
                    var domain = document.domain.toString();
                    var firstperiodindex = domain.indexOf(".", 0);
                    domain = domain.substring(firstperiodindex, domain.length);
                    document.cookie = name + "=" + value + ";" + exdatestring + "path=/;domain=" + domain + ";";
                },
                /* Create session cookie */
                Session: function (name, value) {
                    document.cookie = name + "=" + value + "; path=/";
                },
                Consume: function (name, key) {
                    var arr = this._Check(name);
                    var condition = undefined;
                    if (arr) {
                        arr = unescape(arr).split("&");
                        for (var i = 0; i < arr.length; i++) {
                            var t = arr[i].split("|");
                            for (var g = 0; g < t.length; g++) {
                                t[g] = t[g].split("=");
                            }
                            for (var counter = 0; counter < t.length; counter++) {
                                if (unescape(t[counter][0]) == key) {
                                    condition = t[counter][1];
                                    break;
                                }
                            }
                        }
                        return condition;
                    } else {
                        return condition;
                    }
                },
                /* Checks for key or key/value pair in cookie - hacked together for leadform*/
                Check: function (name, key, value) {
                    var arr = this._Check(name);
                    var condition = false;
                    if (arr) {
                        arr = unescape(arr).split("&");
                        for (var i = 0; i < arr.length; i++) {
                            var t = arr[i].split("|");
                            for (var g = 0; g < t.length; g++) {
                                t[g] = t[g].split("=");
                            }
                            for (var counter = 0; counter < t.length; counter++) {
                                if (arguments.length == 2) {
                                    if (unescape(t[counter][0]) == key) {
                                        condition = true;
                                        break;
                                    }
                                } else {
                                    if (unescape(t[counter][0]) == key & unescape(t[counter][1]) == value) {
                                        condition = true;
                                        break;
                                    }
                                }
                            }
                        }
                        return condition;
                    } else {
                        return condition;
                    }
                },
                /* Helper - returns value of specified cookie */
                _Check: function (name) {
                    var s = document.cookie.split(';');
                    for (var i = 0, l = s.length; i < l; i++) {
                        var c = s[i].toString(), f, r;
                        f = c.substring(0, c.indexOf("="))
                        r = c.substring(c.indexOf("=") + 1, c.length)
                        while (f.charAt(0) == " ") f = f.substring(1, f.length)
                        if (f == name) return r;
                    }
                }
            },
            GetDimensions: function (Width_Height_or_Both) {
                Width_Height_or_Both = Width_Height_or_Both.toLowerCase()
                switch (Width_Height_or_Both) {
                    case "width":
                        return { "width": width() }
                        break;
                    case "height":
                        return { "height": height() }
                        break;
                    case "both":
                        return { "width": width(), "height": height() }
                        break;
                    // If nothing, just return both...        
                    default:
                        return { "width": width(), "height": height() }
                        break;
                        window.location
                }
                function height() {
                    return Math.max(
            Math.max(document.body.scrollHeight, document.documentElement.scrollHeight),
            Math.max(document.body.offsetHeight, document.documentElement.offsetHeight),
            Math.max(document.body.clientHeight, document.documentElement.clientHeight)
          );
                }
                function width() {
                    return Math.max(
            Math.max(document.body.scrollWidth, document.documentElement.scrollWidth),
            Math.max(document.body.offsetWidth, document.documentElement.offsetWidth),
            Math.max(document.body.clientWidth, document.documentElement.clientWidth)
          );
                }
            }
        }
    },
    /* -- Teachers */
    Teachers: {
        /* Start - Liveball Marketing */
        LiveBall: {
            Private: function () {
                var playing = new Boolean();
                return function setter(condition) {
                    if (arguments.length == 0) return playing;
                    playing = condition;
                    if (playing == "true") {
                        EF.Teachers.LiveBall.killTimer(EF.Teachers.LiveBall.Private._timer);
                        return playing;
                    } else if (playing == "false") {
                        EF.Teachers.LiveBall.setTimer();
                        return playing;
                    }
                }
            },
            showModal: function () {
                /* Load ColorBox for pop-in -- Will eventually replace nryo and ThickBox */
                $.fn.colorbox({
                    href: EF.Teachers.LiveBall.Private._liveball,
                    iframe: true,
                    overlayClose: false,
                    innerWidth: EF.Teachers.LiveBall.Private._width,
                    innerHeight: EF.Teachers.LiveBall.Private._height,
                    opacity: 0.3,
                    onLoad: function () {
                        $("select").css("display", "none");
                        $("html").css("overflow-x", "hidden");
                        var dimensions = EF.$_util().GetDimensions('both');
                        $("#cboxOverlay").css({
                            "height": dimensions['height'],
                            "width": dimensions['width']
                        })
                    },
                    onCleanup: function () {
                        $("#cboxClose").css("display", "none")
                        $("select").css("display", "inline");
                        $("html").css("overflow-x", "auto");
                    },
                    onClosed: function () {
                        /* Create EFLD cookie */
                        EF.Global.Utilities.CookieManager.Session("EFLD", escape("Viewed=True"));

                        /* Increment counter */
                        var _count = parseInt(EF.Global.Utilities.CookieManager.Consume("EFFEDCK", "Count")) + 1;
                        EF.Global.Utilities.CookieManager.Bake("EFFEDCK", "Count=" + _count, "180");
                    }
                })
            },
            setTimer: function () {
                EF.Teachers.LiveBall.Private._timer = setTimeout('EF.Teachers.LiveBall.showModal()', EF.Teachers.LiveBall.Private._timeout);
            },
            killTimer: function (timer) {
                try {
                    clearTimeout(timer)
                } catch (err) { }
            },
            Init: function (url, timeout, width, height, iframe) {
                /* Create counter cookie, if nec. */
                if (!EF.Global.Utilities.CookieManager.Check("EFFEDCK", "Count")) {
                    EF.Global.Utilities.CookieManager.Bake("EFFEDCK", "Count=0", "180");
                }

                if (EF.Global.Utilities.CookieManager.Check("EFLD", "Viewed", "True") || EF.Global.Utilities.CookieManager.Check("EFFEDCK", "Count", "3")) return /*silently*/;

                EF.Teachers.LiveBall.Private._liveball = url;
                EF.Teachers.LiveBall.Private._timeout = timeout || 15000;
                EF.Teachers.LiveBall.Private._width = width || 400;
                EF.Teachers.LiveBall.Private._height = height || 690;
                this.setTimer()
            },
            FlashInit: function () {
                return EF.Teachers.LiveBall.Private._temp = new this.Private()
            }
        }
    }
}

/* Equalizes height between left and right column, sets click/blur event for textboxes */
function setEnrollBrick(et, eb, ct, cb) {

    // Controls
    var enrolltxt = "#" + et,
        enrollbtn = "#" + eb,
        checkouttxt = "#" + ct,
        checkoutbtn = "#" + cb,

    /* Error message */
        msgs = {
            regex: "*Tour number format (eg:111111 or 111111-G1)"
        },

    /* Dimensions */
        lh = $("#leftCol").height(),
        rh = $("#rightCol").height(),
        h = Math.max(lh, rh),

    /* Regex */
        tourRegex = "^\s*[A-za-z]{2}-[0-9]{6,7}$|^[0-9]{6,7}$|^[0-9]{6,7}-[gG]{1}[0-9]{1}\s*$";

    /* Set Dimensions */
    $("#leftCol, #rightCol").css({
        "height": h,
        "background": "transparent url('/includes/images/homepage_bottom_bg.gif') repeat-x bottom left"
    });

    /* bind clicks on textboxes */
    $("#rightCol .textbox").bind({
        "keydown": function (e) {
            /* prevent return */

            if ($(this).data("validationFailed")) {
                clearError(this);
                e.preventDefault();
            };

            if (e.which == 13) {
                if (!$(this).data("isValid")) {
                    setError(e.target.id);
                    e.preventDefault();
                }
                else {
                    if (e.target.id == et) {
                        $(enrollbtn).trigger("click");
                        e.preventDefault();
                    } else {
                        $(checkoutbtn).trigger("click");
                        e.preventDefault();
                    }
                }
            }
        },
        "keyup": function (e) {
            $(this).data("valueChanged", true);
            $(this).data("isValid", $(this).val().match(tourRegex));
        },
        "click": function () {
            /* check for error */
            if ($(this).data("validationFailed")) clearError(this);

            /* check if user clicking for first time */
            if (!$(this).data("init")) {
                $(this).data("init", true);
                $(this).data("initialValue", $(this).val());
                $(this).val("");
            } else {
                if (!$(this).data("valueChanged") || $(this).val() == $(this).data("initialValue")) $(this).val("");
            }
        },
        "blur": function () {
            // set empty texts to their initial value
            if ($(this).val() == "") {
                $(this).val($(this).data("initialValue"))
            } else {
                if ($(this).val() != $(this).data("initialValue")) {
                    $(this).data("valueChanged", true);
                } else {
                    $(this).data("valueChanged", false);
                }
            };
        }
    });

    /* bind clicks on buttons */
    $(enrollbtn + "," + checkoutbtn).bind("click", function (e) {
        // enroll button
        e['success'] = function () { return };

        if (e.target.id == eb) {
            if (!$(enrolltxt).data("isValid")) e[_handleResponse(setError, et)]();
            // checkout button
        } else {
            if (!$(checkouttxt).data("isValid")) e[_handleResponse(setError, ct)]();
        }
    });

    function _handleResponse(apply, ctl) {
        return apply(ctl);
    }

    function clearError(ctl) {
        /* clears error, data associated with error */
        $(ctl).removeData("validationFailed");
        $(ctl).val($(ctl).data("InvalidText"));
        $(ctl).css("color", "#000");
        $("#ErrorMsg", "#ValidationSummary").text("").parent().animate({ "opacity": 0 }, 100);
    };

    function setError(ctl) {
        /* prevent multiple visual sets */
        if (!$("#" + ctl).data("validationFailed")) {
            setValue(ctl);
        }

        /* set textbox color, display error */
        function setValue(ctl) {
            $("#" + ctl).data("InvalidText", $("#" + ctl).val());
            $("#" + ctl).data("validationFailed", true);
            $("#" + ctl).val($("#" + ctl).val() + "*");
            $("#" + ctl).css("color", "#ff0000");
            $("#ErrorMsg", "#ValidationSummary").text(msgs.regex).parent().css({ "opacity": 0, "display": "block" }).animate({ "opacity": 1 }, 100);
        }

        /* prevent default action */
        return "preventDefault";
    };
}

/* map ajax call */
function getContent(uri, field, ajaxcallback, element) {
    $.get('/includes/scproxy.aspx', { id: uri, field: field }, function (data, status) {
        setResponse(data, status, ajaxcallback, element)
    });
    function setResponse(data, status, callback, element) {
        if (status == "success") {
            eval(data);
            element ? callback(element, response.text) : callback(response.text);
        }
    }
}
function setColorboxContent(el, msg) {
    $(el).html(msg);
}

/* pop up window - plugged in! */
(function ($, window) {
    /* default popup settings */
    var popup = 'popup',
        url = "about:blank",
        name = "cstpopup",
        width = "750",
        height = "500",
        left = "100",
        top = "100",
        scrollbars = "1",
        status = "1",
        resizable = "1",
        menubar = "0",
        titlebar = "0",
        toolbar = "0",
        location = "0";

    public = $.fn[popup] = $[popup] = function (args) {
        $this = this;
        if (arguments.length) {
            if (this.selector) {
                public.bindControls($this, args);
            } else {
                setEmpty();
                $this = undefined;
            }
        } else {
            if (this.selector) {
                public.bindControls($this);
            } else {
                setEmpty();
                $this = undefined;
            }
        }

        function setEmpty() {
            var $temp = $("<div />");
            public.setVariables(public.constructObj(args), $temp)
            public.showPopup($temp);
        }

        return $this;

    };

    public.showPopup = function (object) {
        var o = object;
        var options = "height=" + $(o).data("_height") + ",left=" + $(o).data("_left")
            + ",location=" + $(o).data("_location") + ",menubar=" + $(o).data("_menubar")
            + ",resizable=" + $(o).data("_resizable") + ",scrollbars=" + $(o).data("_scrollbars")
            + ",status=" + $(o).data("_status") + ",titlebar=" + $(o).data("_titlebar")
            + ",toolbar=" + $(o).data("_toolbar") + ",top=" + $(o).data("_top")
            + ",width=" + $(o).data("_width");
        $['popup']['child'] = window.open($(o).data("_url"), $(o).data("_name"), options);
        $(o).removeData();
    }
    public.bindControls = function (object, args) {
        $that = object;

        if (args) {
            var e = public.updateAttr(args);
            $(object).attr('popup', e);
            return;
        }
        $($that).live("click", function (e) {
            e.preventDefault();
            e.stopPropagation();

            var popupAttr = $(this).attr('popup'), href = $(this).attr('href');
            if (popupAttr) {
                public.setVariables(public.constructObj(popupAttr), this)
                public.showPopup(this);
            } else {
                public.setVariables(this);
                public.showPopup(this);
            }
        });
    }
    public.updateAttr = function (arguments) {
        var temp = null;
        switch (typeof arguments) {
            case "string": temp = arguments;
                break;
            case "object":
                var s = "";
                for (prop in arguments) {
                    s += prop + "=" + arguments[prop] + "&";
                }
                temp = s.substring(0, s.length - 1);
                break;
            default: break;
        }
        return temp;
    }
    public.constructObj = function (object) {
        var temp = null;
        switch (typeof object) {
            case "string":
                var s = object.split("&");
                temp = {};

                if (s.length > 1) {
                    for (i = 0, l = s.length; i < l; i++) {
                        var $s = s[i].split("=");
                        temp[$s[0]] = $s[1];
                    }
                } else {
                    var $s = s[0].split("=");
                    temp[$s[0]] = $s[1];
                }

                return temp;
                break;
            case "object":
                temp = object;
                break;
            case "undefined":
            default: temp = {};
        }
        return temp;
    };
    public.setVariables = function (object) {
        if (arguments.length == 1) {
            obj = object;
            $(obj).data({
                '_url': $(obj).attr('href'),
                '_name': name,
                '_width': width,
                '_height': height,
                '_left': left,
                '_top': top,
                '_scrollbars': scrollbars,
                '_status': status,
                '_resizable': resizable,
                '_menubar': menubar,
                '_titlebar': titlebar,
                '_toolbar': toolbar,
                '_location': location
            });
        } else {
            var obj = arguments[0], $this = arguments[1];
            var d = new Date();
            $($this).data({
                '_url': (function () { return obj['url'] || obj['href'] || $($this).attr('href') || url })(),
                '_name': (function () { return obj['name'] || name })(),
                '_width': (function () { return obj['width'] || obj['w'] || width })(),
                '_height': (function () { return obj['height'] || obj['h'] || height })(),
                '_left': (function () { return obj['left'] || obj['l'] || left })(),
                '_top': (function () { return obj['top'] || obj['t'] || top })(),
                '_scrollbars': (function () { return obj['scrollbars'] || obj['scroll'] || scrollbars })(),
                '_status': (function () { return obj['status'] || status })(),
                '_resizable': (function () { return obj['resizable'] || obj['resize'] || resizable })(),
                '_menubar': (function () { return obj['menubar'] || obj['menu'] || menubar })(),
                '_titlebar': (function () { return obj['titlebar'] || obj['title'] || titlebar })(),
                '_toolbar': (function () { return obj['toolbar'] || obj['tool'] || toolbar })(),
                '_location': (function () { return obj['location'] || obj['address'] || location })()
            });
        }
    };
})(jQuery, this);


/**
* DD_belatedPNG: Adds IE6 support: PNG images for CSS background-image and HTML <IMG/>.
* Author: Drew Diller
* Email: drew.diller@gmail.com
* URL: http://www.dillerdesign.com/experiment/DD_belatedPNG/
* Version: 0.0.8a
* Licensed under the MIT License: http://dillerdesign.com/experiment/DD_belatedPNG/#license
*
* Example usage:
* DD_belatedPNG.fix('.png_bg'); // argument is a CSS selector
* DD_belatedPNG.fixPng( someNode ); // argument is an HTMLDomElement
**/

function DD_load() { var DD_belatedPNG = { ns: "DD_belatedPNG", imgSize: {}, delay: 10, nodesFixed: 0, createVmlNameSpace: function () { if (document.namespaces && !document.namespaces[this.ns]) { document.namespaces.add(this.ns, "urn:schemas-microsoft-com:vml") } }, createVmlStyleSheet: function () { var b, a; b = document.createElement("style"); b.setAttribute("media", "screen"); document.documentElement.firstChild.insertBefore(b, document.documentElement.firstChild.firstChild); if (b.styleSheet) { b = b.styleSheet; b.addRule(this.ns + "\\:*", "{behavior:url(#default#VML)}"); b.addRule(this.ns + "\\:shape", "position:absolute;"); b.addRule("img." + this.ns + "_sizeFinder", "behavior:none; border:none; position:absolute; z-index:-1; top:-10000px; visibility:hidden;"); this.screenStyleSheet = b; a = document.createElement("style"); a.setAttribute("media", "print"); document.documentElement.firstChild.insertBefore(a, document.documentElement.firstChild.firstChild); a = a.styleSheet; a.addRule(this.ns + "\\:*", "{display: none !important;}"); a.addRule("img." + this.ns + "_sizeFinder", "{display: none !important;}") } }, readPropertyChange: function () { var b, c, a; b = event.srcElement; if (!b.vmlInitiated) { return } if (event.propertyName.search("background") != -1 || event.propertyName.search("border") != -1) { DD_belatedPNG.applyVML(b) } if (event.propertyName == "style.display") { c = (b.currentStyle.display == "none") ? "none" : "block"; for (a in b.vml) { if (b.vml.hasOwnProperty(a)) { b.vml[a].shape.style.display = c } } } if (event.propertyName.search("filter") != -1) { DD_belatedPNG.vmlOpacity(b) } }, vmlOpacity: function (b) { if (b.currentStyle.filter.search("lpha") != -1) { var a = b.currentStyle.filter; a = parseInt(a.substring(a.lastIndexOf("=") + 1, a.lastIndexOf(")")), 10) / 100; b.vml.color.shape.style.filter = b.currentStyle.filter; b.vml.image.fill.opacity = a } }, handlePseudoHover: function (a) { setTimeout(function () { DD_belatedPNG.applyVML(a) }, 1) }, fix: function (a) { if (this.screenStyleSheet) { var c, b; c = a.split(","); for (b = 0; b < c.length; b++) { this.screenStyleSheet.addRule(c[b], "behavior:expression(DD_belatedPNG.fixPng(this))") } } }, applyVML: function (a) { a.runtimeStyle.cssText = ""; this.vmlFill(a); this.vmlOffsets(a); this.vmlOpacity(a); if (a.isImg) { this.copyImageBorders(a) } }, attachHandlers: function (i) { var d, c, g, e, b, f; d = this; c = { resize: "vmlOffsets", move: "vmlOffsets" }; if (i.nodeName == "A") { e = { mouseleave: "handlePseudoHover", mouseenter: "handlePseudoHover", focus: "handlePseudoHover", blur: "handlePseudoHover" }; for (b in e) { if (e.hasOwnProperty(b)) { c[b] = e[b] } } } for (f in c) { if (c.hasOwnProperty(f)) { g = function () { d[c[f]](i) }; i.attachEvent("on" + f, g) } } i.attachEvent("onpropertychange", this.readPropertyChange) }, giveLayout: function (a) { a.style.zoom = 1; if (a.currentStyle.position == "static") { a.style.position = "relative" } }, copyImageBorders: function (b) { var c, a; c = { borderStyle: true, borderWidth: true, borderColor: true }; for (a in c) { if (c.hasOwnProperty(a)) { b.vml.color.shape.style[a] = b.currentStyle[a] } } }, vmlFill: function (e) { if (!e.currentStyle) { return } else { var d, f, g, b, a, c; d = e.currentStyle } for (b in e.vml) { if (e.vml.hasOwnProperty(b)) { e.vml[b].shape.style.zIndex = d.zIndex } } e.runtimeStyle.backgroundColor = ""; e.runtimeStyle.backgroundImage = ""; f = true; if (d.backgroundImage != "none" || e.isImg) { if (!e.isImg) { e.vmlBg = d.backgroundImage; e.vmlBg = e.vmlBg.substr(5, e.vmlBg.lastIndexOf('")') - 5) } else { e.vmlBg = e.src } g = this; if (!g.imgSize[e.vmlBg]) { a = document.createElement("img"); g.imgSize[e.vmlBg] = a; a.className = g.ns + "_sizeFinder"; a.runtimeStyle.cssText = "behavior:none; position:absolute; left:-10000px; top:-10000px; border:none; margin:0; padding:0;"; c = function () { this.width = this.offsetWidth; this.height = this.offsetHeight; g.vmlOffsets(e) }; a.attachEvent("onload", c); a.src = e.vmlBg; a.removeAttribute("width"); a.removeAttribute("height"); document.body.insertBefore(a, document.body.firstChild) } e.vml.image.fill.src = e.vmlBg; f = false } e.vml.image.fill.on = !f; e.vml.image.fill.color = "none"; e.vml.color.shape.style.backgroundColor = d.backgroundColor; e.runtimeStyle.backgroundImage = "none"; e.runtimeStyle.backgroundColor = "transparent" }, vmlOffsets: function (d) { var h, n, a, e, g, m, f, l, j, i, k; h = d.currentStyle; n = { W: d.clientWidth + 1, H: d.clientHeight + 1, w: this.imgSize[d.vmlBg].width, h: this.imgSize[d.vmlBg].height, L: d.offsetLeft, T: d.offsetTop, bLW: d.clientLeft, bTW: d.clientTop }; a = (n.L + n.bLW == 1) ? 1 : 0; e = function (b, p, q, c, s, u) { b.coordsize = c + "," + s; b.coordorigin = u + "," + u; b.path = "m0,0l" + c + ",0l" + c + "," + s + "l0," + s + " xe"; b.style.width = c + "px"; b.style.height = s + "px"; b.style.left = p + "px"; b.style.top = q + "px" }; e(d.vml.color.shape, (n.L + (d.isImg ? 0 : n.bLW)), (n.T + (d.isImg ? 0 : n.bTW)), (n.W - 1), (n.H - 1), 0); e(d.vml.image.shape, (n.L + n.bLW), (n.T + n.bTW), (n.W), (n.H), 1); g = { X: 0, Y: 0 }; if (d.isImg) { g.X = parseInt(h.paddingLeft, 10) + 1; g.Y = parseInt(h.paddingTop, 10) + 1 } else { for (j in g) { if (g.hasOwnProperty(j)) { this.figurePercentage(g, n, j, h["backgroundPosition" + j]) } } } d.vml.image.fill.position = (g.X / n.W) + "," + (g.Y / n.H); m = h.backgroundRepeat; f = { T: 1, R: n.W + a, B: n.H, L: 1 + a }; l = { X: { b1: "L", b2: "R", d: "W" }, Y: { b1: "T", b2: "B", d: "H"} }; if (m != "repeat" || d.isImg) { i = { T: (g.Y), R: (g.X + n.w), B: (g.Y + n.h), L: (g.X) }; if (m.search("repeat-") != -1) { k = m.split("repeat-")[1].toUpperCase(); i[l[k].b1] = 1; i[l[k].b2] = n[l[k].d] } if (i.B > n.H) { i.B = n.H } d.vml.image.shape.style.clip = "rect(" + i.T + "px " + (i.R + a) + "px " + i.B + "px " + (i.L + a) + "px)" } else { d.vml.image.shape.style.clip = "rect(" + f.T + "px " + f.R + "px " + f.B + "px " + f.L + "px)" } }, figurePercentage: function (d, c, f, a) { var b, e; e = true; b = (f == "X"); switch (a) { case "left": case "top": d[f] = 0; break; case "center": d[f] = 0.5; break; case "right": case "bottom": d[f] = 1; break; default: if (a.search("%") != -1) { d[f] = parseInt(a, 10) / 100 } else { e = false } } d[f] = Math.ceil(e ? ((c[b ? "W" : "H"] * d[f]) - (c[b ? "w" : "h"] * d[f])) : parseInt(a, 10)); if (d[f] % 2 === 0) { d[f]++ } return d[f] }, fixPng: function (c) { c.style.behavior = "none"; var g, b, f, a, d; if (c.nodeName == "BODY" || c.nodeName == "TD" || c.nodeName == "TR") { return } c.isImg = false; if (c.nodeName == "IMG") { if (c.src.toLowerCase().search(/\.png$/) != -1) { c.isImg = true; c.style.visibility = "hidden" } else { return } } else { if (c.currentStyle.backgroundImage.toLowerCase().search(".png") == -1) { return } } g = DD_belatedPNG; c.vml = { color: {}, image: {} }; b = { shape: {}, fill: {} }; for (a in c.vml) { if (c.vml.hasOwnProperty(a)) { for (d in b) { if (b.hasOwnProperty(d)) { f = g.ns + ":" + d; c.vml[a][d] = document.createElement(f) } } c.vml[a].shape.stroked = false; c.vml[a].shape.appendChild(c.vml[a].fill); c.parentNode.insertBefore(c.vml[a].shape, c) } } c.vml.image.shape.fillcolor = "none"; c.vml.image.fill.type = "tile"; c.vml.color.fill.on = false; g.attachHandlers(c); g.giveLayout(c); g.giveLayout(c.offsetParent); c.vmlInitiated = true; g.applyVML(c) } }; try { document.execCommand("BackgroundImageCache", false, true) } catch (r) { } DD_belatedPNG.createVmlNameSpace(); DD_belatedPNG.createVmlStyleSheet(); }


//Custom Client Side Validator Functions

var pwregexp = new RegExp("^(?=.*[A-Za-z])(?=.*[0-9])(?!.*[^A-Za-z0-9])(?!.*\s).{6,16}$");
var emailregexp = new RegExp("^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$");

//This will check that is single field is not empty, and also that it doesn't match 
//an initial value (if that is given on the validator control)
function requiredField(src, args) {
    if (args.Value == "") {
        var target = $(src).attr("target");

        if (target != null) {
            setControlError($("[id$=" + target + "]"));
        }
        args.IsValid = false;
    }
    else if (args.Value == $(src).attr("initialvalue")) {
        var target = $(src).attr("target");

        if (target != null) {
            setControlError($("[id$=" + target + "]"));
        }
        args.IsValid = false;
    }
    else {
        args.IsValid = true;
    }
}

//This will check that a single selector field (drop downs, radio buttons) has a selection and 
//that selection is not the same as the initial value
function requiredFieldSelector(src, args) {

    var target = $(src).attr("target");

    var ctrl = $("[id$=" + target + "]");

    var value;
    if (ctrl != null) {
        value = ctrl.find(":selected, :checked").val();
    }

    if (value == "") {

        if (target != null) {
            setControlError(ctrl);
        }
        args.IsValid = false;
    }
    else if (value == $(src).attr("initialvalue")) {

        if (target != null) {
            setControlError(ctrl);
        }
        args.IsValid = false;
    }
    else {
        args.IsValid = true;
    }
}

//This will check if 2 fields have the same value
function compareFields(src, args) {

    var ctrl1id = $(src).attr("source");
    var ctrl2id = $(src).attr("target");

    var ctrl1 = $("[id$=" + ctrl1id + "]");
    var ctrl2 = $("[id$=" + ctrl2id + "]");

    if (ctrl1 == null || ctrl2 == null) {
        args.IsValid = true;
    }
    else {
        if (ctrl1.val() == ctrl2.val()) {
            args.IsValid = true;
        }
        else {
            setControlError(ctrl1);
            setControlError(ctrl2);

            var msg = $(src).attr("message");
            if (msg != "") {
                alert(msg);
            }
        }
    }
}

//Will check against the password regex to make sure its a strong password
function strongPassword(src, args) {

    var target = $(src).attr("target");

    var ctrl = $("[id$=" + target + "]");

    var match = args.Value.match(pwregexp);

    if (match == null) {
        args.IsValid = false;

        if (ctrl != null) {
            setControlError(ctrl);
        }
    }
    else {
        args.IsValid = true;
    }
}

//Will check against the email regex to make sure its a valid email address
function validEmail(src, args) {

    var target = $(src).attr("target");

    var ctrl = $("[id$=" + target + "]");

    var match = args.Value.match(emailregexp);

    if (match == null) {
        args.IsValid = false;

        if (ctrl != null) {
            setControlError(ctrl);
        }
    }
    else {
        args.IsValid = true;
    }
}

//Sets the error style to the given control
function setControlError(ctrl) {
    var initial = ctrl.css("border");
    ctrl.first().css("border", "1px solid #c00");
    ctrl.first().focus(function () {
        $(this).css("border", initial);
    });
}

/**
* @license 
* jQuery Tools @VERSION Tooltip - UI essentials
* 
* NO COPYRIGHTS OR LICENSES. DO WHAT YOU LIKE.
* 
* http://flowplayer.org/tools/tooltip/
*
* Since: November 2008
* Date: @DATE 
*/
(function ($) {
    // static constructs
    $.tools = $.tools || { version: '@VERSION' };

    $.tools.tooltip = {

        conf: {

            // default effect variables
            effect: 'toggle',
            fadeOutSpeed: "fast",
            predelay: 0,
            delay: 30,
            opacity: 1,
            tip: 0,

            // 'top', 'bottom', 'right', 'left', 'center'
            position: ['top', 'center'],
            offset: [0, 0],
            relative: false,
            cancelDefault: true,

            // type to event mapping 
            events: {
                def: "mouseenter,mouseleave",
                input: "focus,blur",
                widget: "focus mouseenter,blur mouseleave",
                tooltip: "mouseenter,mouseleave"
            },

            // 1.2
            layout: '<div/>',
            tipClass: 'tooltip'
        },

        addEffect: function (name, loadFn, hideFn) {
            effects[name] = [loadFn, hideFn];
        }
    };


    var effects = {
        toggle: [
			function (done) {
			    var conf = this.getConf(), tip = this.getTip(), o = conf.opacity;
			    if (o < 1) { tip.css({ opacity: o }); }
			    tip.show();
			    done.call();
			},

			function (done) {
			    this.getTip().hide();
			    done.call();
			}
		],

        fade: [
			function (done) {
			    var conf = this.getConf();
			    this.getTip().fadeTo(conf.fadeInSpeed, conf.opacity, done);
			},
			function (done) {
			    this.getTip().fadeOut(this.getConf().fadeOutSpeed, done);
			}
		]
    };


    /* calculate tip position relative to the trigger */
    function getPosition(trigger, tip, conf) {


        // get origin top/left position 
        var top = conf.relative ? trigger.position().top : trigger.offset().top,
			 left = conf.relative ? trigger.position().left : trigger.offset().left,
			 pos = conf.position[0];

        top -= tip.outerHeight() - conf.offset[0];
        left += trigger.outerWidth() + conf.offset[1];

        // iPad position fix
        if (/iPad/i.test(navigator.userAgent)) {
            top -= $(window).scrollTop();
        }

        // adjust Y		
        var height = tip.outerHeight() + trigger.outerHeight();
        if (pos == 'center') { top += height / 2; }
        if (pos == 'bottom') { top += height; }


        // adjust X
        pos = conf.position[1];
        var width = tip.outerWidth() + trigger.outerWidth();
        if (pos == 'center') { left -= width / 2; }
        if (pos == 'left') { left -= width; }

        return { top: top, left: left };
    }



    function Tooltip(trigger, conf) {

        var self = this,
			 fire = trigger.add(self),
			 tip,
			 timer = 0,
			 pretimer = 0,
			 title = trigger.attr("title"),
			 tipAttr = trigger.attr("data-tooltip"),
			 effect = effects[conf.effect],
			 shown,

        // get show/hide configuration
			 isInput = trigger.is(":input"),
			 isWidget = isInput && trigger.is(":checkbox, :radio, select, :button, :submit"),
			 type = trigger.attr("type"),
			 evt = conf.events[type] || conf.events[isInput ? (isWidget ? 'widget' : 'input') : 'def'];


        // check that configuration is sane
        if (!effect) { throw "Nonexistent effect \"" + conf.effect + "\""; }

        evt = evt.split(/,\s*/);
        if (evt.length != 2) { throw "Tooltip: bad events configuration for " + type; }


        // trigger --> show  
        trigger.bind(evt[0], function (e) {

            clearTimeout(timer);
            if (conf.predelay) {
                pretimer = setTimeout(function () { self.show(e); }, conf.predelay);

            } else {
                self.show(e);
            }

            // trigger --> hide
        }).bind(evt[1], function (e) {
            clearTimeout(pretimer);
            if (conf.delay) {
                timer = setTimeout(function () { self.hide(e); }, conf.delay);

            } else {
                self.hide(e);
            }

        });


        // remove default title
        if (title && conf.cancelDefault) {
            trigger.removeAttr("title");
            trigger.data("title", title);
        }

        $.extend(self, {

            show: function (e) {

                // tip not initialized yet
                if (!tip) {

                    // data-tooltip 
                    if (tipAttr) {
                        tip = $(tipAttr);

                        // single tip element for all
                    } else if (conf.tip) {
                        tip = $(conf.tip).eq(0);

                        // autogenerated tooltip
                    } else if (title) {
                        tip = $(conf.layout).addClass(conf.tipClass).appendTo(document.body)
							.hide().append(title);

                        // manual tooltip
                    } else {
                        tip = trigger.next();
                        if (!tip.length) { tip = trigger.parent().next(); }
                    }

                    if (!tip.length) { throw "Cannot find tooltip for " + trigger; }
                }

                if (self.isShown()) { return self; }

                // stop previous animation
                tip.stop(true, true);

                // get position
                var pos = getPosition(trigger, tip, conf);

                // restore title for single tooltip element
                if (conf.tip) {
                    tip.html(trigger.data("title"));
                }

                // onBeforeShow
                e = e || $.Event();
                e.type = "onBeforeShow";
                fire.trigger(e, [pos]);
                if (e.isDefaultPrevented()) { return self; }


                // onBeforeShow may have altered the configuration
                pos = getPosition(trigger, tip, conf);

                // set position
                tip.css({ position: 'absolute', top: pos.top, left: pos.left });

                shown = true;

                // invoke effect 
                effect[0].call(self, function () {
                    e.type = "onShow";
                    shown = 'full';
                    fire.trigger(e);
                });


                // tooltip events       
                var event = conf.events.tooltip.split(/,\s*/);

                if (!tip.data("__set")) {

                    tip.bind(event[0], function () {
                        clearTimeout(timer);
                        clearTimeout(pretimer);
                    });

                    if (event[1] && !trigger.is("input:not(:checkbox, :radio), textarea")) {
                        tip.bind(event[1], function (e) {

                            // being moved to the trigger element
                            if (e.relatedTarget != trigger[0]) {
                                trigger.trigger(evt[1].split(" ")[0]);
                            }
                        });
                    }

                    tip.data("__set", true);
                }

                return self;
            },

            hide: function (e) {

                if (!tip || !self.isShown()) { return self; }

                // onBeforeHide
                e = e || $.Event();
                e.type = "onBeforeHide";
                fire.trigger(e);
                if (e.isDefaultPrevented()) { return; }

                shown = false;

                effects[conf.effect][1].call(self, function () {
                    e.type = "onHide";
                    fire.trigger(e);
                });

                return self;
            },

            isShown: function (fully) {
                return fully ? shown == 'full' : shown;
            },

            getConf: function () {
                return conf;
            },

            getTip: function () {
                return tip;
            },

            getTrigger: function () {
                return trigger;
            }

        });

        // callbacks	
        $.each("onHide,onBeforeShow,onShow,onBeforeHide".split(","), function (i, name) {

            // configuration
            if ($.isFunction(conf[name])) {
                $(self).bind(name, conf[name]);
            }

            // API
            self[name] = function (fn) {
                if (fn) { $(self).bind(name, fn); }
                return self;
            };
        });

    }


    // jQuery plugin implementation
    $.fn.tooltip = function (conf) {

        // return existing instance
        var api = this.data("tooltip");
        if (api) { return api; }

        conf = $.extend(true, {}, $.tools.tooltip.conf, conf);

        // position can also be given as string
        if (typeof conf.position == 'string') {
            conf.position = conf.position.split(/,?\s/);
        }

        // install tooltip for each entry in jQuery object
        this.each(function () {
            api = new Tooltip($(this), conf);
            $(this).data("tooltip", api);
        });

        return conf.api ? api : this;
    };

})(jQuery);



$(document).ready(function () {
    //    $("#ctl00_logo_LoginStatus_DomesticTours").tooltip({
    //        position: "bottom center",
    //        effect: "fade"
    //    });
});


// Displays super check list
var SuperCheck = {
    _selectedIndex: null,
    _offset: null,
    _timer: null,
    _hiding: null,
    _hidden: true,
    elements: {
        element: null,
        list: null,
        wrap: function (el) { return "#" + el },
        unwrap: function (el) { return el.split("#")[1] }
    },
    events: {
        // Bind events to elements
        list: {
            bind: function (callback) {
                this.attachClick(callback);

                //filter used for dropshadow causes :hover issues;
                if ($.browser.msie)
                    this.setHoverForIE();
            },
            attachClick: function (callback) {
                $(SuperCheck.elements.list).delegate("li", "click", function () {
                    if ((SuperCheck._selectedIndex != $(this).index()) && (SuperCheck._selectedIndex != null))
                        $(SuperCheck.elements.list).find("li").eq(SuperCheck._selectedIndex).removeClass("selected");
                    if ((SuperCheck._selectedIndex == $(this).index()) && (SuperCheck._selectedIndex != null))
                        return false;
                    SuperCheck._selectedIndex = $(this).index();
                    $(this).addClass("selected");
                    if (SuperCheck._hiding != true && SuperCheck._hidden != true)
                        SuperCheck._timer = setTimeout("SuperCheck.hide(0)", 0);
                    $(document).unbind("click.closesuper", SuperCheck.events.element.escapeSuper);
                    eval(callback)($(this).attr("selector"));
                });
            },
            bindClick: function () {
                $(SuperCheck.elements.list).hover(function () {
                    if (SuperCheck._timer)
                        clearTimeout(SuperCheck._timer);
                }, function () {
                    if (SuperCheck._hiding != true && SuperCheck._hidden != true)
                        SuperCheck._timer = setTimeout("SuperCheck.hide(200)", 400);
                });
            },
            setHoverForIE: function () {
                $(SuperCheck.elements.list).find("li").bind({
                    "mouseover": function () {
                        $(this).css({
                            "color": "#555555",
                            "background-color": "#cfd4da"
                        })
                    },
                    "mouseout": function () {
                        $(this).css({
                            "color": "#333",
                            "background-color": "#f8f8f8"
                        })
                    }
                })
            }
        },
        element: {
            bind: function () {
                this.bindClick();
            },
            escapeSuper: function (e) {
                if (e.target.id == SuperCheck.elements.unwrap(SuperCheck.elements.element) || e.target.id == SuperCheck.elements.unwrap(SuperCheck.elements.list))
                    return true;
                if (SuperCheck._hiding != true && SuperCheck._hidden != true) {
                    SuperCheck._timer = setTimeout("SuperCheck.hide(0)", 0);
                    $(document).unbind("click.closesuper", SuperCheck.events.element.escapeSuper);
                }
            },
            bindClick: function () {
                $(window).bind("resize", function () { SuperCheck._offset = null });
                $(SuperCheck.elements.element).bind("click", function (e) {
                    if (SuperCheck._hidden) {
                        $(SuperCheck.elements.element).addClass("supercheckDown");
                        $(document).bind("click.closesuper", SuperCheck.events.element.escapeSuper);
                        if (SuperCheck._offset == null)
                            SuperCheck._offset = $(SuperCheck.elements.element).offset();
                        SuperCheck._hidden = false;
                        $(SuperCheck.elements.list).css({
                            "display": "block",
                            "position": "absolute",
                            "left": SuperCheck._offset.left,
                            "top": SuperCheck._offset.top + 16,
                            "z-index": 1000
                        });
                    } else {
                        $(document).unbind("click.closesuper", SuperCheck.events.element.escapeSuper);
                        if (SuperCheck._hiding != true && SuperCheck._hidden != true)
                            SuperCheck._timer = setTimeout("SuperCheck.hide(0)", 0);
                    }
                });
            }
        }
    },
    hide: function (time) {
        SuperCheck._hiding = true;
        $(SuperCheck.elements.element).removeClass("supercheckDown");
        $(SuperCheck.elements.list).stop().animate({
            "opacity": "0"
        }, time, function () {
            $(SuperCheck.elements.list).css({
                "display": "none",
                "opacity": "1"
            });
            SuperCheck._hidden = true;
            SuperCheck._hiding = false;
        });
    },
    init: function (element, list, callback) {
        this.elements.element = this.elements.wrap(element);
        this.elements.list = this.elements.wrap(list);
        SuperCheck.events.element.bind();
        SuperCheck.events.list.bind(callback);
    }
}

//Prints tab content
function printTabContent(idsToRemove) {
    $("<div />").attr({ id: "printThis" }).appendTo("body");
    $("#printThis").html("<div id='tourInfo'>" + $("#tourInfo").html() + "</div><br/><br/><div class='clearfix'></div><div id='tabContent'>" + $("#tabContent").html() + "</div>");

    var count;
    var ids = new Array;
    ids = idsToRemove.split(",");
    for (count = 0; count < ids.length; count++) {
        $("#printThis").find("[id$=" + ids[count] + "]").remove();
    }
    //$("#printThis").find("[id$=Print]").remove();
    //$("#printThis").find("[id$=ReturnToList]").remove();

    $("#printThis").printElement();
}


function CalculateTip(els) {
    // Tour Info and Elements
    this.TourLength = els.tour.tourLength;
    this.TourSize = els.tour.tourSize;
    this.TotalPerPerson = els.label.totalPerson;
    this.TotalForGroup = els.label.totalGroup;
    this.TipForTourDirector = els.input.tourDirector;
    this.TipForBusDriver = els.input.busDriver;
    this.NumberOfDays = els.input.numberOfDays;
    this.NumberOfTravelers = els.input.numberOfTravelers;
    this.Calculate = els.input.calculateTipAmount;
    this.firstRun = null;

    // Tips
    this.TotalToTip = null;
    this.TotalToTipInd = null;
    this.TotalToTipGroup = null;

    // Bind Events
    $$(this.Calculate).live("click", function (evt) {
        evt.preventDefault();
        CalculatedTipSize();
    });

    bindInputEvents($$(this.NumberOfDays), /\D+/, "enter #", true);
    bindInputEvents($$(this.NumberOfTravelers), /\D+/, "enter #", true);
    bindInputEvents($$(this.TipForBusDriver), /^\$?(\d+)\.?(\d{1,2})?$/, "$0", false);
    bindInputEvents($$(this.TipForTourDirector), /^\$?(\d+)\.?(\d{1,2})?$/, "$0", false);

    // Helper to return a jQuery-friendly selector
    function $$(el) {
        return $("#" + el.id);
    }

    function CalculatedTipSize() {
        var _invalidPattern = /\D+/;
        var _tipAmount = /^\$?(\d+)\.?(\d{1,2})?$/;
        var _tryTourDirectorTip = $$(this.TipForTourDirector).val();
        var _tryBusDriverTip = $$(this.TipForBusDriver).val();
        var _tryNumDays = $$(this.NumberOfDays).val();
        var _tryNumTravs = $$(this.NumberOfTravelers).val();

        var tourDirectorTip = _tipAmount.exec(_tryTourDirectorTip);
        var busDriverTip = _tipAmount.exec(_tryBusDriverTip);
        var workingTour, workingBus, totalAmts = null;
        var numOfDaysValid = _invalidPattern.test(_tryNumDays);
        var numOfTravsValid = _invalidPattern.test(_tryNumTravs);

        if (!numOfDaysValid && !numOfTravsValid && tourDirectorTip && busDriverTip) {
            workingTour = parseInt(tourDirectorTip[1], 10) * 100;
            workingBus = parseInt(busDriverTip[1], 10) * 100;

            workingTour = addCents(tourDirectorTip, workingTour);
            workingBus = addCents(busDriverTip, workingBus);
            totalAmts = (workingTour + workingBus) / 100;

            /* Update labels */
            $$(this.TotalPerPerson).text("$" + (totalAmts * _tryNumDays).toFixed(0));
            $$(this.TotalForGroup).text("$" + (totalAmts * _tryNumDays * _tryNumTravs).toFixed(0));
        } else {
            if (numOfDaysValid) {
                $$(this.NumberOfDays).addClass("errorWithInput");
            }
            if (numOfTravsValid) {
                $$(this.NumberOfTravelers).addClass("errorWithInput");
            }
            if (!tourDirectorTip) {
                $$(this.TipForTourDirector).addClass("errorWithInput");
            }
            if (!busDriverTip) {
                $$(this.TipForBusDriver).addClass("errorWithInput");
            }
        }

        function addCents(regexArr, workingSum) {
            if (regexArr[2] && regexArr[2] != "" && regexArr[2] > 0) {
                return workingSum += parseInt(regexArr[2], 10);
            } else {
                return workingSum;
            }
        }
    }

    function SuggestedTipSize() {
        return ((parseInt(this.TourSize, 10) * 9) * parseInt(this.TourLength, 10)).toFixed(2);
    };

    function bindInputEvents(jQueryObj, regexPattern, defaultErrorMsg, boolPattern) {
        jQueryObj.live("click, focus", function (evt) {
            if (!this.firstRun) {
                $(".initialInput").each(function () {
                    $(this).removeClass("initialInput");
                });
                this.firstRun = true;
            }

            if ($(this).hasClass("errorWithInput"))
                $(this).removeClass("errorWithInput");

            var pattern = regexPattern;
            if (pattern.test($(this).val()) == boolPattern) {
                $(this).val("");
            }
        });
        jQueryObj.live("blur", function (evt) {
            if ($(this).val() == "")
                $(this).val(defaultErrorMsg);
        });
    }
}
