﻿//jsonstringify.js
JSONstring = {
    compactOutput: false,
    includeProtos: false,
    includeFunctions: false,
    detectCirculars: true,
    restoreCirculars: true,
    make: function(arg, restore) {
        this.restore = restore;
        this.mem = []; this.pathMem = [];
        return this.toJsonStringArray(arg).join('');
    },
    toObject: function(x) {
        if (!this.cleaner) {
            try { this.cleaner = new RegExp('^("(\\\\.|[^"\\\\\\n\\r])*?"|[,:{}\\[\\]0-9.\\-+Eaeflnr-u \\n\\r\\t])+?$') }
            catch (a) { this.cleaner = /^(true|false|null|\[.*\]|\{.*\}|".*"|\d+|\d+\.\d+)$/ }
        };
        if (!this.cleaner.test(x)) { return {} };
        eval("this.myObj=" + x);
        if (!this.restoreCirculars || !alert) { return this.myObj };
        if (this.includeFunctions) {
            var x = this.myObj;
            for (var i in x) {
                if (typeof x[i] == "string" && !x[i].indexOf("JSONincludedFunc:")) {
                    x[i] = x[i].substring(17);
                    eval("x[i]=" + x[i])
                }
            }
        };
        this.restoreCode = [];
        this.make(this.myObj, true);
        var r = this.restoreCode.join(";") + ";";
        eval('r=r.replace(/\\W([0-9]{1,})(\\W)/g,"[$1]$2").replace(/\\.\\;/g,";")');
        eval(r);
        return this.myObj
    },
    toJsonStringArray: function(arg, out) {
        if (!out) { this.path = [] };
        out = out || [];
        var u; // undefined
        switch (typeof arg) {
            case 'object':
                this.lastObj = arg;
                if (this.detectCirculars) {
                    var m = this.mem; var n = this.pathMem;
                    for (var i = 0; i < m.length; i++) {
                        if (arg === m[i]) {
                            out.push('"JSONcircRef:' + n[i] + '"'); return out
                        }
                    };
                    m.push(arg); n.push(this.path.join("."));
                };
                if (arg) {
                    if (arg.constructor == Array) {
                        out.push('[');
                        for (var i = 0; i < arg.length; ++i) {
                            this.path.push(i);
                            if (i > 0)
                                out.push(',\n');
                            this.toJsonStringArray(arg[i], out);
                            this.path.pop();
                        }
                        out.push(']');
                        return out;
                    } else if (typeof arg.toString != 'undefined') {
                        out.push('{');
                        var first = true;
                        for (var i in arg) {
                            if (!this.includeProtos && arg[i] === arg.constructor.prototype[i]) { continue };
                            this.path.push(i);
                            var curr = out.length;
                            if (!first)
                                out.push(this.compactOutput ? ',' : ',\n');
                            this.toJsonStringArray(i, out);
                            out.push(':');
                            this.toJsonStringArray(arg[i], out);
                            if (out[out.length - 1] == u)
                                out.splice(curr, out.length - curr);
                            else
                                first = false;
                            this.path.pop();
                        }
                        out.push('}');
                        return out;
                    }
                    return out;
                }
                out.push('null');
                return out;
            case 'unknown':
            case 'undefined':
            case 'function':
                if (!this.includeFunctions) { out.push(u); return out };
                arg = "JSONincludedFunc:" + arg;
                out.push('"');
                var a = ['\n', '\\n', '\r', '\\r', '"', '\\"'];
                arg += ""; for (var i = 0; i < 6; i += 2) { arg = arg.split(a[i]).join(a[i + 1]) };
                out.push(arg);
                out.push('"');
                return out;
            case 'string':
                if (this.restore && arg.indexOf("JSONcircRef:") == 0) {
                    this.restoreCode.push('this.myObj.' + this.path.join(".") + "=" + arg.split("JSONcircRef:").join("this.myObj."));
                };
                out.push('"');
                var a = ['\n', '\\n', '\r', '\\r', '"', '\\"'];
                arg += ""; for (var i = 0; i < 6; i += 2) { arg = arg.split(a[i]).join(a[i + 1]) };
                out.push(arg);
                out.push('"');
                return out;
            default:
                out.push(String(arg));
                return out;
        }
    }
};

//jquery.checkbox.min.js
(function ($) { var i = function (e) { if (!e) var e = window.event; e.cancelBubble = true; if (e.stopPropagation) e.stopPropagation() }; $.fn.checkbox = function (f) { try { document.execCommand('BackgroundImageCache', false, true) } catch (e) { } var g = { cls: 'jquery-checkbox', empty: '/Content/jquery-ui/plugins/checkbox/empty.png' }; g = $.extend(g, f || {}); var h = function (a) { var b = a.checked; var c = a.disabled; var d = $(a); if (a.stateInterval) clearInterval(a.stateInterval); a.stateInterval = setInterval(function () { if (a.disabled != c) d.trigger((c = !!a.disabled) ? 'disable' : 'enable'); if (a.checked != b) d.trigger((b = !!a.checked) ? 'check' : 'uncheck') }, 10); return d }; return this.each(function () { var a = this; var b = h(a); if (a.wrapper) a.wrapper.remove(); a.wrapper = $('<span class="' + g.cls + '"><span class="mark"><img src="' + g.empty + '" /></span></span>'); a.wrapperInner = a.wrapper.children('span:eq(0)'); a.wrapper.hover(function (e) { a.wrapperInner.addClass(g.cls + '-hover'); i(e) }, function (e) { a.wrapperInner.removeClass(g.cls + '-hover'); i(e) }); b.css({ position: 'absolute', zIndex: -1, visibility: 'hidden' }).after(a.wrapper); var c = false; if (b.attr('id')) { c = $('label[for=' + b.attr('id') + ']'); if (!c.length) c = false } if (!c) { c = b.closest ? b.closest('label') : b.parents('label:eq(0)'); if (!c.length) c = false } if (c) { c.hover(function (e) { a.wrapper.trigger('mouseover', [e]) }, function (e) { a.wrapper.trigger('mouseout', [e]) }); c.click(function (e) { b.trigger('click', [e]); i(e); return false }) } a.wrapper.click(function (e) { b.trigger('click', [e]); i(e); return false }); b.click(function (e) { i(e) }); b.bind('disable', function () { a.wrapperInner.addClass(g.cls + '-disabled') }).bind('enable', function () { a.wrapperInner.removeClass(g.cls + '-disabled') }); b.bind('check', function () { a.wrapper.addClass(g.cls + '-checked') }).bind('uncheck', function () { a.wrapper.removeClass(g.cls + '-checked') }); $('img', a.wrapper).bind('dragstart', function () { return false }).bind('mousedown', function () { return false }); if (window.getSelection) a.wrapper.css('MozUserSelect', 'none'); if (a.checked) a.wrapper.addClass(g.cls + '-checked'); if (a.disabled) a.wrapperInner.addClass(g.cls + '-disabled') }) } })(jQuery);

//jquery.progressbar.min.js
(function($) {
    $.extend({ progressBar: new function() {
        this.defaults = { steps: 10, step_duration: 10, max: 100, showText: true, textFormat: 'percentage', width: 400, height: 13, callback: null, boxImage: '/Content/Images/meniga_progressbar.gif', barImage: { 0: '/Content/Images/meniga_progressbar_green.gif', 50: '/Content/Images/meniga_progressbar_yellow.gif', 83: '/Content/Images/meniga_progressbar_red.gif' }, running_value: 0, value: 0, image: null }; this.construct = function(arg1, arg2) {
            var argvalue = null; var argconfig = null; if (arg1 != null) { if (!isNaN(arg1)) { argvalue = arg1; if (arg2 != null) { argconfig = arg2; } } else { argconfig = arg1; } }
            return this.each(function(child) {
                var pb = this; var config = this.config; if (argvalue != null && this.bar != null && this.config != null) {
                    this.config.value = argvalue
                    if (argconfig != null)
                        pb.config = $.extend(this.config, argconfig); config = pb.config;
                } else {
                    var $this = $(this); var config = $.extend({}, $.progressBar.defaults, argconfig); config.id = $this.attr('id') ? $this.attr('id') : Math.ceil(Math.random() * 100000); if (argvalue == null)
                        argvalue = $this.html().replace("%", "")
                    config.value = argvalue; config.running_value = 0; config.image = getBarImage(config); $this.html(""); var bar = document.createElement('img'); var text = document.createElement('span'); var $bar = $(bar); var $text = $(text); pb.bar = $bar; $bar.attr('id', config.id + "_pbImage"); $text.attr('id', config.id + "_pbText"); $text.html(getText(config)); $bar.attr('title', getText(config)); $bar.attr('alt', getText(config)); $bar.attr('src', config.boxImage); $bar.attr('width', config.width); $bar.css("width", config.width + "px"); $bar.css("height", config.height + "px"); $bar.css("background-image", "url(" + config.image + ")"); $bar.css("background-position", ((config.width * -1)) + 'px 50%'); $bar.css("padding", "0"); $bar.css("margin", "0"); $this.append($bar); $this.append($text);
                }
                function getPercentage(config) { return config.running_value * 100 / config.max; }
                function getBarImage(config) {
                    var image = config.barImage; if (typeof (config.barImage) == 'object') { for (var i in config.barImage) { if (config.running_value >= parseInt(i)) { image = config.barImage[i]; } else { break; } } }
                    return image;
                }
                function getText(config) { if (config.showText) { if (config.textFormat == 'percentage') { return " " + Math.round(config.running_value) + "%"; } else if (config.textFormat == 'fraction') { return " " + config.running_value + '/' + config.max; } } }
                config.increment = Math.round((config.value - config.running_value) / config.steps); if (config.increment < 0)
                    config.increment *= -1; if (config.increment < 1)
                    config.increment = 1; var t = setInterval(function() {
                        var pixels = config.width / 100; var stop = false; if (config.running_value > config.value) { if (config.running_value - config.increment < config.value) { config.running_value = config.value; } else { config.running_value -= config.increment; } }
                        else if (config.running_value < config.value) { if (config.running_value + config.increment > config.value) { config.running_value = config.value; } else { config.running_value += config.increment; } }
                        if (config.running_value == config.value)
                            clearInterval(t); var $bar = $("#" + config.id + "_pbImage"); var $text = $("#" + config.id + "_pbText"); var image = getBarImage(config); if (image != config.image) { $bar.css("background-image", "url(" + image + ")"); config.image = image; }
                        $bar.css("background-position", (((config.width * -1)) + (getPercentage(config) * pixels)) + 'px 50%'); $bar.attr('title', getText(config)); $text.html(getText(config)); if (config.callback != null && typeof (config.callback) == 'function')
                            config.callback(config); pb.config = config;
                    }, config.step_duration);
            });
        };
    } 
    }); $.fn.extend({ progressBar: $.progressBar.construct });
})(jQuery);

//jquery.calculation.min.js
(function($) { var defaults = { reNumbers: /(-|-\$)?(\d+(,\d{3})*(\.\d{1,})?|\.\d{1,})/g, cleanseNumber: function(v) { return v.replace(/[^0-9.\-]/g, "") }, useFieldPlugin: (!!$.fn.getValue), onParseError: null, onParseClear: null }; $.Calculation = { version: "0.4.05", setDefaults: function(options) { $.extend(defaults, options) } }; $.fn.parseNumber = function(options) { var aValues = []; options = $.extend(options, defaults); this.each(function() { var $el = $(this), sMethod = ($el.is(":input") ? (defaults.useFieldPlugin ? "getValue" : "val") : "text"), v = $el[sMethod]().match(defaults.reNumbers, ""); if (v == null) { v = 0; if (jQuery.isFunction(options.onParseError)) options.onParseError.apply($el, [sMethod]); $.data($el[0], "calcParseError", true) } else { v = options.cleanseNumber.apply(this, [v[0]]); if ($.data($el[0], "calcParseError") && jQuery.isFunction(options.onParseClear)) { options.onParseClear.apply($el, [sMethod]); $.data($el[0], "calcParseError", false) } } aValues.push(parseFloat(v, 10)) }); return aValues }; $.fn.calc = function(expr, vars, cbFormat, cbDone) { var $this = this, exprValue = "", precision = 0, $el, parsedVars = {}, tmp, sMethod, _, bIsError = false; for (var k in vars) { expr = expr.replace((new RegExp("(" + k + ")", "g")), "_.$1"); if (!!vars[k] && !!vars[k].jquery) { parsedVars[k] = vars[k].parseNumber() } else { parsedVars[k] = vars[k] } } this.each(function(i, el) { var p, len; $el = $(this); sMethod = ($el.is(":input") ? (defaults.useFieldPlugin ? "setValue" : "val") : "text"); _ = {}; for (var k in parsedVars) { if (typeof parsedVars[k] == "number") { _[k] = parsedVars[k] } else if (typeof parsedVars[k] == "string") { _[k] = parseFloat(parsedVars[k], 10) } else if (!!parsedVars[k] && (parsedVars[k] instanceof Array)) { tmp = (parsedVars[k].length == $this.length) ? i : 0; _[k] = parsedVars[k][tmp] } if (isNaN(_[k])) _[k] = 0; p = _[k].toString().match(/\.\d+$/gi); len = (p) ? p[0].length - 1 : 0; if (len > precision) precision = len } try { exprValue = eval(expr); if (precision) exprValue = Number(exprValue.toFixed(Math.max(precision, 4))); if (!!cbFormat) exprValue = cbFormat(exprValue) } catch (e) { exprValue = e; bIsError = true } $el[sMethod](exprValue.toString()) }); if (!!cbDone) cbDone(this); return this }; $.each(["sum", "avg", "min", "max"], function(i, method) { $.fn[method] = function(bind, selector) { if (arguments.length == 0) return math[method](this.parseNumber()); var bSelOpt = selector && (selector.constructor == Object) && !(selector instanceof jQuery); var opt = bind && bind.constructor == Object ? bind : { bind: bind || "keyup", selector: (!bSelOpt) ? selector : null, oncalc: null }; if (bSelOpt) opt = jQuery.extend(opt, selector); if (!!opt.selector) opt.selector = $(opt.selector); var self = this, sMethod, doCalc = function() { var value = math[method](self.parseNumber(opt)); if (!!opt.selector) { sMethod = (opt.selector.is(":input") ? (defaults.useFieldPlugin ? "setValue" : "val") : "text"); opt.selector[sMethod](value.toString()) } if (jQuery.isFunction(opt.oncalc)) opt.oncalc.apply(self, [value, opt]) }; doCalc(); return self.bind(opt.bind, doCalc) } }); var math = { sum: function(a) { var total = 0, precision = 0; $.each(a, function(i, v) { var p = v.toString().match(/\.\d+$/gi), len = (p) ? p[0].length - 1 : 0; if (len > precision) precision = len; total += v }); if (precision) total = Number(total.toFixed(precision)); return total }, avg: function(a) { return math.sum(a) / a.length }, min: function(a) { return Math.min.apply(Math, a) }, max: function(a) { return Math.max.apply(Math, a) } } })(jQuery);

//jquery.numberformatter-1.1.2.js
(function(jQuery) {

    function FormatData(dec, group, neg) {
        this.dec = dec;
        this.group = group;
        this.neg = neg;
    };

    function formatCodes(locale) {

        // default values
        var dec = ".";
        var group = ",";
        var neg = "-";

        if (locale == "us" ||
             locale == "ae" ||
             locale == "eg" ||
             locale == "il" ||
             locale == "jp" ||
             locale == "sk" ||
             locale == "th" ||
             locale == "cn" ||
             locale == "hk" ||
             locale == "tw" ||
             locale == "au" ||
             locale == "ca" ||
             locale == "gb" ||
             locale == "in"
            ) {
            dec = ".";
            group = ",";
        }

        else if (locale == "de" ||
             locale == "vn" ||
             locale == "es" ||
             locale == "dk" ||
             locale == "at" ||
             locale == "gr" ||
             locale == "br"
            ) {
            dec = ",";
            group = ".";
        }
        else if (locale == "cz" ||
              locale == "fr" ||
             locale == "fi" ||
             locale == "ru" ||
             locale == "se"
            ) {
            group = " ";
            dec = ",";
        }
        else if (locale == "ch") {
            group = "'";
            dec = ".";
        }

        return new FormatData(dec, group, neg);

    };

    jQuery.formatNumber = function(number, options) {
        var options = jQuery.extend({}, jQuery.fn.parse.defaults, options);
        var formatData = formatCodes(options.locale.toLowerCase());

        var dec = formatData.dec;
        var group = formatData.group;
        var neg = formatData.neg;

        var numString = new String(number);
        numString = numString.replace(".", dec).replace("-", neg);
        return numString;
    };

    jQuery.fn.parse = function(options) {

        var options = jQuery.extend({}, jQuery.fn.parse.defaults, options);

        var formatData = formatCodes(options.locale.toLowerCase());

        var dec = formatData.dec;
        var group = formatData.group;
        var neg = formatData.neg;

        var valid = "1234567890.-";

        var array = [];
        this.each(function() {

            var text = new String(jQuery(this).text());
            if (jQuery(this).is(":input"))
                text = new String(jQuery(this).val());

            // now we need to convert it into a number
            while (text.indexOf(group) > -1)
                text = text.replace(group, '');
            text = text.replace(dec, ".").replace(neg, "-");
            var validText = "";
            var hasPercent = false;
            if (text.charAt(text.length - 1) == "%")
                hasPercent = true;
            for (var i = 0; i < text.length; i++) {
                if (valid.indexOf(text.charAt(i)) > -1)
                    validText = validText + text.charAt(i);
            }
            var number = new Number(validText);
            if (hasPercent) {
                number = number / 100;
                number = number.toFixed(validText.length - 1);
            }
            array.push(number);
        });

        return array;
    };

    jQuery.parseSingle = function(formatted, options) {

        var options = jQuery.extend({}, jQuery.fn.parse.defaults, options);
        var text = formatted;
        var formatData = formatCodes(options.locale.toLowerCase());

        var dec = formatData.dec;
        var group = formatData.group;
        var neg = formatData.neg;

        var valid = "1234567890.-";

        // now we need to convert it into a number
        while (text.indexOf(group) > -1)
            text = text.replace(group, '');
        text = text.replace(dec, ".").replace(neg, "-");
        var validText = "";
        var hasPercent = false;
        if (text.charAt(text.length - 1) == "%")
            hasPercent = true;
        for (var i = 0; i < text.length; i++) {
            if (valid.indexOf(text.charAt(i)) > -1)
                validText = validText + text.charAt(i);
        }
        var number = new Number(validText);
        if (hasPercent) {
            number = number / 100;
            number = number.toFixed(validText.length - 1);
        }

        return number;
    };

    jQuery.fn.format = function(options) {

        var options = jQuery.extend({}, jQuery.fn.format.defaults, options);

        var formatData = formatCodes(options.locale.toLowerCase());

        var dec = formatData.dec;
        var group = formatData.group;
        var neg = formatData.neg;

        var validFormat = "0#-,.";

        return this.each(function() {

            var text = new String(jQuery(this).text());
            if (jQuery(this).is(":input"))
                text = new String(jQuery(this).val());

            var prefix = "";
            var negativeInFront = false;
            for (var i = 0; i < options.format.length; i++) {
                if (validFormat.indexOf(options.format.charAt(i)) == -1)
                    prefix = prefix + options.format.charAt(i);
                else if (i == 0 && options.format.charAt(i) == '-') {
                    negativeInFront = true;
                    continue;
                }
                else
                    break;
            }
            var suffix = "";
            for (var i = options.format.length - 1; i >= 0; i--) {
                if (validFormat.indexOf(options.format.charAt(i)) == -1)
                    suffix = options.format.charAt(i) + suffix;
                else
                    break;
            }

            options.format = options.format.substring(prefix.length);
            options.format = options.format.substring(0, options.format.length - suffix.length);

            if (options.raw != true) {
                // now we need to convert it into a number
                while (text.indexOf(group) > -1)
                    text = text.replace(group, '');
                var number = new Number(text.replace(dec, ".").replace(neg, "-"));
            } else {
                var number = new Number(text);
            }

            if (suffix == "%")
                number = number * 100;

            var returnString = "";

            var decimalValue = number % 1;
            if (options.format.indexOf(".") > -1) {
                var decimalPortion = dec;
                var decimalFormat = options.format.substring(options.format.lastIndexOf(".") + 1);
                var decimalString = new String(decimalValue.toFixed(decimalFormat.length));
                decimalString = decimalString.substring(decimalString.lastIndexOf(".") + 1);
                for (var i = 0; i < decimalFormat.length; i++) {
                    if (decimalFormat.charAt(i) == '#' && decimalString.charAt(i) != '0') {
                        decimalPortion += decimalString.charAt(i);
                        continue;
                    }
                    else if (decimalFormat.charAt(i) == '#' && decimalString.charAt(i) == '0') {
                        var notParsed = decimalString.substring(i);
                        if (notParsed.match('[1-9]')) {
                            decimalPortion += decimalString.charAt(i);
                            continue;
                        }
                        else {
                            break;
                        }
                    }
                    else if (decimalFormat.charAt(i) == "0") {
                        decimalPortion += decimalString.charAt(i);
                    }
                }
                returnString += decimalPortion
            }
            else
                number = Math.round(number);

            var ones = Math.floor(number);
            if (number < 0)
                ones = Math.ceil(number);

            var onePortion = "";
            if (ones == 0) {
                onePortion = "0";
            }
            else {
                var onesFormat = "";
                if (options.format.indexOf(".") == -1)
                    onesFormat = options.format;
                else
                    onesFormat = options.format.substring(0, options.format.indexOf("."));
                var oneText = new String(Math.abs(ones));
                var groupLength = 9999;
                if (onesFormat.lastIndexOf(",") != -1)
                    groupLength = onesFormat.length - onesFormat.lastIndexOf(",") - 1;
                var groupCount = 0;
                for (var i = oneText.length - 1; i > -1; i--) {
                    onePortion = oneText.charAt(i) + onePortion;

                    groupCount++;

                    if (groupCount == groupLength && i != 0) {
                        onePortion = group + onePortion;
                        groupCount = 0;
                    }

                }
            }
            returnString = onePortion + returnString;

            if (number < 0 && negativeInFront && prefix.length > 0) {
                prefix = neg + prefix;
            }
            else if (number < 0) {
                returnString = neg + returnString;
            }

            if (!options.decimalSeparatorAlwaysShown) {
                if (returnString.lastIndexOf(dec) == returnString.length - 1) {
                    returnString = returnString.substring(0, returnString.length - 1);
                }
            }
            returnString = prefix + returnString + suffix;

            if (jQuery(this).is(":input"))
                jQuery(this).val(returnString);
            else
                jQuery(this).text(returnString);

        });
    };

    jQuery.formatSingle = function(unformatted, options) {

        var text = "" + unformatted;
        var options = jQuery.extend({}, jQuery.fn.format.defaults, options);

        var formatData = formatCodes(options.locale.toLowerCase());

        var dec = formatData.dec;
        var group = formatData.group;
        var neg = formatData.neg;

        var validFormat = "0#-,.";

        var prefix = "";
        var negativeInFront = false;
        for (var i = 0; i < options.format.length; i++) {
            if (validFormat.indexOf(options.format.charAt(i)) == -1)
                prefix = prefix + options.format.charAt(i);
            else if (i == 0 && options.format.charAt(i) == '-') {
                negativeInFront = true;
                continue;
            }
            else
                break;
        }
        var suffix = "";
        for (var i = options.format.length - 1; i >= 0; i--) {
            if (validFormat.indexOf(options.format.charAt(i)) == -1)
                suffix = options.format.charAt(i) + suffix;
            else
                break;
        }

        options.format = options.format.substring(prefix.length);
        options.format = options.format.substring(0, options.format.length - suffix.length);

        if (options.raw != true) {
            // now we need to convert it into a number
            while (text.indexOf(group) > -1)
                text = text.replace(group, '');
            var number = new Number(text.replace(dec, ".").replace(neg, "-"));
        } else {
            var number = new Number(text);
        }

        if (suffix == "%")
            number = number * 100;

        var returnString = "";

        var decimalValue = number % 1;
        if (options.format.indexOf(".") > -1) {
            var decimalPortion = dec;
            var decimalFormat = options.format.substring(options.format.lastIndexOf(".") + 1);
            var decimalString = new String(decimalValue.toFixed(decimalFormat.length));
            decimalString = decimalString.substring(decimalString.lastIndexOf(".") + 1);
            for (var i = 0; i < decimalFormat.length; i++) {
                if (decimalFormat.charAt(i) == '#' && decimalString.charAt(i) != '0') {
                    decimalPortion += decimalString.charAt(i);
                    continue;
                }
                else if (decimalFormat.charAt(i) == '#' && decimalString.charAt(i) == '0') {
                    var notParsed = decimalString.substring(i);
                    if (notParsed.match('[1-9]')) {
                        decimalPortion += decimalString.charAt(i);
                        continue;
                    }
                    else {
                        break;
                    }
                }
                else if (decimalFormat.charAt(i) == "0") {
                    decimalPortion += decimalString.charAt(i);
                }
            }
            returnString += decimalPortion
        }
        else
            number = Math.round(number);

        var ones = Math.floor(number);
        if (number < 0)
            ones = Math.ceil(number);

        var onePortion = "";
        if (ones == 0) {
            onePortion = "0";
        }
        else {
            var onesFormat = "";
            if (options.format.indexOf(".") == -1)
                onesFormat = options.format;
            else
                onesFormat = options.format.substring(0, options.format.indexOf("."));
            var oneText = new String(Math.abs(ones));
            var groupLength = 9999;
            if (onesFormat.lastIndexOf(",") != -1)
                groupLength = onesFormat.length - onesFormat.lastIndexOf(",") - 1;
            var groupCount = 0;
            for (var i = oneText.length - 1; i > -1; i--) {
                onePortion = oneText.charAt(i) + onePortion;

                groupCount++;

                if (groupCount == groupLength && i != 0) {
                    onePortion = group + onePortion;
                    groupCount = 0;
                }

            }
        }
        returnString = onePortion + returnString;

        if (number < 0 && negativeInFront && prefix.length > 0) {
            prefix = neg + prefix;
        }
        else if (number < 0) {
            returnString = neg + returnString;
        }

        if (!options.decimalSeparatorAlwaysShown) {
            if (returnString.lastIndexOf(dec) == returnString.length - 1) {
                returnString = returnString.substring(0, returnString.length - 1);
            }
        }
        returnString = prefix + returnString + suffix;

        return returnString;
    };

    jQuery.fn.parse.defaults = {
        locale: "us",
        decimalSeparatorAlwaysShown: false
    };

    jQuery.fn.format.defaults = {
        format: "#,###.00",
        locale: "us",
        decimalSeparatorAlwaysShown: false
    };


})(jQuery);

//selectToUISlider.jQuery.js
jQuery.fn.selectToUISlider = function(settings) {
    var selects = jQuery(this);

    var options = jQuery.extend({
        labels: 3, //number of visible labels
        tooltip: true, //show tooltips, boolean
        tooltipSrc: 'text', //accepts 'value' as well
        labelSrc: 'value', //accepts 'value' as well	,
        sliderOptions: null
    }, settings);

    var handleIds = (function() {
        var tempArr = [];
        selects.each(function() {
            tempArr.push('handle_' + jQuery(this).attr('id'));
        });
        return tempArr;
    })();

    var selectOptions = (function() {
        var opts = [];
        selects.eq(0).find('option').each(function() {
            opts.push({
                value: jQuery(this).attr('value'),
                text: jQuery(this).text()
            });
        });
        return opts;
    })();

    var groups = (function() {
        if (selects.eq(0).find('optgroup').size() > 0) {
            var groupedData = [];
            selects.eq(0).find('optgroup').each(function(i) {
                groupedData[i] = {};
                groupedData[i].label = jQuery(this).attr('label');
                groupedData[i].options = [];
                jQuery(this).find('option').each(function() {
                    groupedData[i].options.push({ text: jQuery(this).text(), value: jQuery(this).attr('value') });
                });
            });
            return groupedData;
        }
        else return null;
    })();

    function isArray(obj) {
        return obj.constructor == Array;
    }
    function ttText(optIndex) {
        return (options.tooltipSrc == 'text') ? selectOptions[optIndex].text : selectOptions[optIndex].value;
    }

    var sliderOptions = {
        step: 1,
        min: 0,
        orientation: 'horizontal',
        max: selectOptions.length - 1,
        range: selects.length > 1, //multiple select elements = true
        slide: function(e, ui) {//slide function
            var myValue = ui.value;

            //Added by Tinna - this variable must be declared in the view where the slider is
            if (_savedSliderValue != null) {
                myValue = _savedSliderValue;
                _savedSliderValue = null;
            }

            var thisHandle = jQuery(ui.handle);
            var textval = ttText(myValue);
            thisHandle
				.attr('aria-valuetext', textval)
				.attr('aria-valuenow', myValue)
				.find('.ui-slider-tooltip .ttContent')
					.text(textval);

            var currSelect = jQuery('#' + thisHandle.attr('id').split('handle_')[1]);
            currSelect.find('option').eq(myValue).attr('selected', 'selected');
        },
        values: (function() {
            var values = [];
            selects.each(function() {
                values.push(jQuery(this).get(0).selectedIndex);
            });
            return values;
        })()
    };

    options.sliderOptions = (settings) ? jQuery.extend(sliderOptions, settings.sliderOptions) : sliderOptions;

    selects.bind('change keyup click', function() {
        var thisIndex = jQuery(this).get(0).selectedIndex;
        var thisHandle = jQuery('#handle_' + jQuery(this).attr('id'));
        var handleIndex = thisHandle.data('handleNum');
        thisHandle.parents('.ui-slider:eq(0)').slider("values", handleIndex, thisIndex);
    });


    var sliderComponent = jQuery('<div></div>');

    selects.each(function(i) {
        var hidett = '';

        var thisLabel = jQuery('label[for=' + jQuery(this).attr('id') + ']');
        var labelText = (thisLabel.size() > 0) ? 'Slider control for ' + thisLabel.text() + '' : '';
        var thisLabelId = thisLabel.attr('id') || thisLabel.attr('id', 'label_' + handleIds[i]).attr('id');


        if (options.tooltip == false) { hidett = ' style="display: none;"'; }
        jQuery('<a ' +
				'href="#" tabindex="0" ' +
				'id="' + handleIds[i] + '" ' +
				'class="ui-slider-handle" ' +
				'role="slider" ' +
				'aria-labelledby="' + thisLabelId + '" ' +
				'aria-valuemin="' + options.sliderOptions.min + '" ' +
				'aria-valuemax="' + options.sliderOptions.max + '" ' +
				'aria-valuenow="' + options.sliderOptions.values[i] + '" ' +
				'aria-valuetext="' + ttText(options.sliderOptions.values[i]) + '" ' +
			'><span class="screenReaderContext">' + labelText + '</span>' +
			'<span class="ui-slider-tooltip ui-widget-content ui-corner-all"' + hidett + '><span class="ttContent"></span>' +
				'<span class="ui-tooltip-pointer-down ui-widget-content"><span class="ui-tooltip-pointer-down-inner"></span></span>' +
			'</span></a>')
			.data('handleNum', i)
			.appendTo(sliderComponent);
    });

    if (groups) {
        var inc = 0;
        var scale = sliderComponent.append('<dl class="ui-slider-scale ui-helper-reset" role="presentation"></dl>').find('.ui-slider-scale:eq(0)');
        jQuery(groups).each(function(h) {
            scale.append('<dt style="width: ' + (100 / groups.length).toFixed(2) + '%' + '; left:' + (h / (groups.length - 1) * 100).toFixed(2) + '%' + '"><span>' + this.label + '</span></dt>'); //class name becomes camelCased label
            var groupOpts = this.options;
            jQuery(this.options).each(function(i) {
                var style = (inc == selectOptions.length - 1 || inc == 0) ? 'style="display: none;"' : '';
                var labelText = (options.labelSrc == 'text') ? groupOpts[i].text : groupOpts[i].value;
                scale.append('<dd style="left:' + leftVal(inc) + '"><span class="ui-slider-label">' + labelText + '</span><span class="ui-slider-tic ui-widget-content"' + style + '></span></dd>');
                inc++;
            });
        });
    }
    else {
        var scale = sliderComponent.append('<ol class="ui-slider-scale ui-helper-reset" role="presentation"></ol>').find('.ui-slider-scale:eq(0)');
        jQuery(selectOptions).each(function(i) {
            var style = (i == selectOptions.length - 1 || i == 0) ? 'style="display: none;"' : '';
            var labelText = (options.labelSrc == 'text') ? this.text : this.value;
            scale.append('<li style="left:' + leftVal(i) + '"><span class="ui-slider-label">' + labelText + '</span><span class="ui-slider-tic ui-widget-content"' + style + '></span></li>');
        });
    }

    function leftVal(i) {
        return (i / (selectOptions.length - 1) * 100).toFixed(2) + '%';

    }

    if (options.labels > 1) sliderComponent.find('.ui-slider-scale li:last span.ui-slider-label, .ui-slider-scale dd:last span.ui-slider-label').addClass('ui-slider-label-show');

    var increm = Math.max(1, Math.round(selectOptions.length / options.labels));
    for (var j = 0; j < selectOptions.length; j += increm) {
        if ((selectOptions.length - j) > increm) {//don't show if it's too close to the end label
            sliderComponent.find('.ui-slider-scale li:eq(' + j + ') span.ui-slider-label, .ui-slider-scale dd:eq(' + j + ') span.ui-slider-label').addClass('ui-slider-label-show');
        }
    }

    sliderComponent.find('.ui-slider-scale dt').each(function(i) {
        jQuery(this).css({
            'left': ((100 / (groups.length)) * i).toFixed(2) + '%'
        });
    });


    sliderComponent
	.insertAfter(jQuery(this).eq(this.length - 1))
	.slider(options.sliderOptions)
	.attr('role', 'application')
	.find('.ui-slider-label')
	.each(function() {
	    jQuery(this).css('marginLeft', -jQuery(this).width() / 2);
	});

    sliderComponent.find('.ui-tooltip-pointer-down-inner').each(function() {
        var bWidth = jQuery('.ui-tooltip-pointer-down-inner').css('borderTopWidth');
        var bColor = jQuery(this).parents('.ui-slider-tooltip').css('backgroundColor')
        jQuery(this).css('border-top', bWidth + ' solid ' + bColor);
    });

    var values = sliderComponent.slider('values');

    if (isArray(values)) {
        jQuery(values).each(function(i) {
            sliderComponent.find('.ui-slider-tooltip .ttContent').eq(i).text(ttText(this));
        });
    }
    else {
        sliderComponent.find('.ui-slider-tooltip .ttContent').eq(0).text(ttText(values));
    }

    return this;
}


//swfupload.js - Modified by Tinna on 4.7.2011: Added graceful Flash downgrading.
var SWFUpload;

if (SWFUpload == undefined) {
    SWFUpload = function (settings) {
        if (hasFlashVersionOrBetter(7, 0)) {
            this.initSWFUpload(settings);
        } else {
            var targetElement = document.getElementById(settings.button_placeholder_id) || settings.button_placeholder;

            if (targetElement == undefined) {
                throw "Could not find the placeholder element: " + settings.button_placeholder_id;
            }

            targetElement.parentNode.parentNode.innerHTML = MenigaLang.translate("UseBasicImport").format('<a class="underline" href="javascript:jQuery.OpenWindow(\'http://get.adobe.com/flashplayer/\', true)">', '</a>', '<a href="javascript:jQuery.UseBasicImport()" class="underline">', '</a>');
        }
    };
}

SWFUpload.prototype.initSWFUpload = function(userSettings) {
    try {
        this.customSettings = {}; // A container where developers can place their own settings associated with this instance.
        this.settings = {};
        this.eventQueue = [];
        this.movieName = "SWFUpload_" + SWFUpload.movieCount++;
        this.movieElement = null;

        SWFUpload.instances[this.movieName] = this;

        this.initSettings(userSettings);
        this.loadFlash();
        this.displayDebugInfo();
    } catch (ex) {
        delete SWFUpload.instances[this.movieName];
        throw ex;
    }
};

SWFUpload.instances = {};
SWFUpload.movieCount = 0;
SWFUpload.version = "2.2.1 2009-03-30";
SWFUpload.QUEUE_ERROR = {
    QUEUE_LIMIT_EXCEEDED: -100,
    FILE_EXCEEDS_SIZE_LIMIT: -110,
    ZERO_BYTE_FILE: -120,
    INVALID_FILETYPE: -130
};
SWFUpload.UPLOAD_ERROR = {
    HTTP_ERROR: -200,
    MISSING_UPLOAD_URL: -210,
    IO_ERROR: -220,
    SECURITY_ERROR: -230,
    UPLOAD_LIMIT_EXCEEDED: -240,
    UPLOAD_FAILED: -250,
    SPECIFIED_FILE_ID_NOT_FOUND: -260,
    FILE_VALIDATION_FAILED: -270,
    FILE_CANCELLED: -280,
    UPLOAD_STOPPED: -290
};
SWFUpload.FILE_STATUS = {
    QUEUED: -1,
    IN_PROGRESS: -2,
    ERROR: -3,
    COMPLETE: -4,
    CANCELLED: -5
};
SWFUpload.BUTTON_ACTION = {
    SELECT_FILE: -100,
    SELECT_FILES: -110,
    START_UPLOAD: -120,
    JAVASCRIPT: -130
};
SWFUpload.CURSOR = {
    ARROW: -1,
    HAND: -2
};
SWFUpload.WINDOW_MODE = {
    WINDOW: "window",
    TRANSPARENT: "transparent",
    OPAQUE: "opaque"
};

SWFUpload.completeURL = function(url) {
    try {
        var path = "";
        if (typeof (url) !== "string" || url.match(/^https?:\/\//i) || url.match(/^\//) || url === "") {
            return url;
        }

        var indexSlash = window.location.pathname.lastIndexOf("/");
        if (indexSlash <= 0) {
            path = "/";
        } else {
            path = window.location.pathname.substr(0, indexSlash) + "/";
        }

        return path + url;
    } catch (ex) {
        return url;
    }
};

SWFUpload.prototype.initSettings = function(userSettings) {
    this.ensureDefault = function(settingName, defaultValue) {
        var setting = userSettings[settingName];
        if (setting != undefined) {
            if (typeof (setting) === "object" && !(setting instanceof Array)) {
                var clone = {};
                for (var key in setting) {
                    if (setting.hasOwnProperty(key)) {
                        clone[key] = setting[key];
                    }
                }
                this.settings[settingName] = clone;
            } else {
                this.settings[settingName] = setting;
            }
        } else {
            this.settings[settingName] = defaultValue;
        }
    };

    this.ensureDefault("upload_url", "");
    this.ensureDefault("preserve_relative_urls", false);
    this.ensureDefault("file_post_name", "Filedata");
    this.ensureDefault("post_params", {});
    this.ensureDefault("use_query_string", false);
    this.ensureDefault("requeue_on_error", false);
    this.ensureDefault("http_success", []);
    this.ensureDefault("assume_success_timeout", 0);

    this.ensureDefault("file_types", "*.*");
    this.ensureDefault("file_types_description", "All Files");
    this.ensureDefault("file_size_limit", 0); // Default zero means "unlimited"
    this.ensureDefault("file_upload_limit", 0);
    this.ensureDefault("file_queue_limit", 0);

    this.ensureDefault("flash_url", "swfupload.swf");
    this.ensureDefault("prevent_swf_caching", true);

    this.ensureDefault("button_image_url", "");
    this.ensureDefault("button_width", 1);
    this.ensureDefault("button_height", 1);
    this.ensureDefault("button_text", "");
    this.ensureDefault("button_text_style", "color: #000000; font-size: 16pt;");
    this.ensureDefault("button_text_top_padding", 0);
    this.ensureDefault("button_text_left_padding", 0);
    this.ensureDefault("button_action", SWFUpload.BUTTON_ACTION.SELECT_FILES);
    this.ensureDefault("button_disabled", false);
    this.ensureDefault("button_placeholder_id", "");
    this.ensureDefault("button_placeholder", null);
    this.ensureDefault("button_cursor", SWFUpload.CURSOR.ARROW);
    this.ensureDefault("button_window_mode", SWFUpload.WINDOW_MODE.TRANSPARENT);

    this.ensureDefault("debug", false);
    this.settings.debug_enabled = this.settings.debug; // Here to maintain v2 API

    this.settings.return_upload_start_handler = this.returnUploadStart;
    this.ensureDefault("swfupload_loaded_handler", null);
    this.ensureDefault("file_dialog_start_handler", null);
    this.ensureDefault("file_queued_handler", null);
    this.ensureDefault("file_queue_error_handler", null);
    this.ensureDefault("file_dialog_complete_handler", null);

    this.ensureDefault("upload_start_handler", null);
    this.ensureDefault("upload_progress_handler", null);
    this.ensureDefault("upload_error_handler", null);
    this.ensureDefault("upload_success_handler", null);
    this.ensureDefault("upload_complete_handler", null);

    this.ensureDefault("button_action_handler", null);

    this.ensureDefault("debug_handler", this.debugMessage);

    this.ensureDefault("custom_settings", {});

    this.customSettings = this.settings.custom_settings;

    if (!!this.settings.prevent_swf_caching) {
        this.settings.flash_url = this.settings.flash_url + (this.settings.flash_url.indexOf("?") < 0 ? "?" : "&") + "preventswfcaching=" + new Date().getTime();
    }

    if (!this.settings.preserve_relative_urls) {
        this.settings.upload_url = SWFUpload.completeURL(this.settings.upload_url);
        this.settings.button_image_url = SWFUpload.completeURL(this.settings.button_image_url);
    }

    delete this.ensureDefault;
};

SWFUpload.prototype.loadFlash = function() {
    var targetElement, tempParent;

    if (document.getElementById(this.movieName) !== null) {
        throw "ID " + this.movieName + " is already in use. The Flash Object could not be added";
    }

    targetElement = document.getElementById(this.settings.button_placeholder_id) || this.settings.button_placeholder;

    if (targetElement == undefined) {
        throw "Could not find the placeholder element: " + this.settings.button_placeholder_id;
    }

    var wrapperType = (targetElement.currentStyle && targetElement.currentStyle["display"] || window.getComputedStyle && document.defaultView.getComputedStyle(targetElement, null).getPropertyValue("display")) !== "block" ? "span" : "div";

    tempParent = document.createElement(wrapperType);
    tempParent.innerHTML = this.getFlashHTML(); // Using innerHTML is non-standard but the only sensible way to dynamically add Flash in IE (and maybe other browsers)
    targetElement.parentNode.replaceChild(tempParent.firstChild, targetElement);

    if (window[this.movieName] == undefined) {
        window[this.movieName] = this.getMovieElement();
    }

};

SWFUpload.prototype.getFlashHTML = function() {
    return ['<object id="', this.movieName, '" type="application/x-shockwave-flash" data="', this.settings.flash_url, '" width="', this.settings.button_width, '" height="', this.settings.button_height, '" class="swfupload">',
				'<param name="wmode" value="', this.settings.button_window_mode, '" />',
				'<param name="movie" value="', this.settings.flash_url, '" />',
				'<param name="quality" value="high" />',
				'<param name="menu" value="false" />',
				'<param name="allowScriptAccess" value="always" />',
				'<param name="flashvars" value="' + this.getFlashVars() + '" />',
				'</object>'].join("");
};

SWFUpload.prototype.getFlashVars = function() {
    var paramString = this.buildParamString();
    var httpSuccessString = this.settings.http_success.join(",");

    return ["movieName=", encodeURIComponent(this.movieName),
			"&amp;uploadURL=", encodeURIComponent(this.settings.upload_url),
			"&amp;useQueryString=", encodeURIComponent(this.settings.use_query_string),
			"&amp;requeueOnError=", encodeURIComponent(this.settings.requeue_on_error),
			"&amp;httpSuccess=", encodeURIComponent(httpSuccessString),
			"&amp;assumeSuccessTimeout=", encodeURIComponent(this.settings.assume_success_timeout),
			"&amp;params=", encodeURIComponent(paramString),
			"&amp;filePostName=", encodeURIComponent(this.settings.file_post_name),
			"&amp;fileTypes=", encodeURIComponent(this.settings.file_types),
			"&amp;fileTypesDescription=", encodeURIComponent(this.settings.file_types_description),
			"&amp;fileSizeLimit=", encodeURIComponent(this.settings.file_size_limit),
			"&amp;fileUploadLimit=", encodeURIComponent(this.settings.file_upload_limit),
			"&amp;fileQueueLimit=", encodeURIComponent(this.settings.file_queue_limit),
			"&amp;debugEnabled=", encodeURIComponent(this.settings.debug_enabled),
			"&amp;buttonImageURL=", encodeURIComponent(this.settings.button_image_url),
			"&amp;buttonWidth=", encodeURIComponent(this.settings.button_width),
			"&amp;buttonHeight=", encodeURIComponent(this.settings.button_height),
			"&amp;buttonText=", encodeURIComponent(this.settings.button_text),
			"&amp;buttonTextTopPadding=", encodeURIComponent(this.settings.button_text_top_padding),
			"&amp;buttonTextLeftPadding=", encodeURIComponent(this.settings.button_text_left_padding),
			"&amp;buttonTextStyle=", encodeURIComponent(this.settings.button_text_style),
			"&amp;buttonAction=", encodeURIComponent(this.settings.button_action),
			"&amp;buttonDisabled=", encodeURIComponent(this.settings.button_disabled),
			"&amp;buttonCursor=", encodeURIComponent(this.settings.button_cursor)
		].join("");
};

SWFUpload.prototype.getMovieElement = function() {
    if (this.movieElement == undefined) {
        this.movieElement = document.getElementById(this.movieName);
    }

    if (this.movieElement === null) {
        throw "Could not find Flash element";
    }

    return this.movieElement;
};

SWFUpload.prototype.buildParamString = function() {
    var postParams = this.settings.post_params;
    var paramStringPairs = [];

    if (typeof (postParams) === "object") {
        for (var name in postParams) {
            if (postParams.hasOwnProperty(name)) {
                paramStringPairs.push(encodeURIComponent(name.toString()) + "=" + encodeURIComponent(postParams[name].toString()));
            }
        }
    }

    return paramStringPairs.join("&amp;");
};

SWFUpload.prototype.destroy = function() {
    try {
        this.cancelUpload(null, false);

        this.callFlash("StopExternalInterfaceCheck");

        var movieElement = this.cleanUp();

        if (movieElement) {
            try {
                movieElement.parentNode.removeChild(movieElement);
            } catch (ex) { }
        }

        window[this.movieName] = null;

        SWFUpload.instances[this.movieName] = null;
        delete SWFUpload.instances[this.movieName];

        this.movieElement = null;
        this.settings = null;
        this.customSettings = null;
        this.eventQueue = null;
        this.movieName = null;


        return true;
    } catch (ex2) {
        return false;
    }
};

SWFUpload.prototype.displayDebugInfo = function() {
    this.debug(
		[
			"---SWFUpload Instance Info---\n",
			"Version: ", SWFUpload.version, "\n",
			"Movie Name: ", this.movieName, "\n",
			"Settings:\n",
			"\t", "upload_url:               ", this.settings.upload_url, "\n",
			"\t", "flash_url:                ", this.settings.flash_url, "\n",
			"\t", "use_query_string:         ", this.settings.use_query_string.toString(), "\n",
			"\t", "requeue_on_error:         ", this.settings.requeue_on_error.toString(), "\n",
			"\t", "http_success:             ", this.settings.http_success.join(", "), "\n",
			"\t", "assume_success_timeout:   ", this.settings.assume_success_timeout, "\n",
			"\t", "file_post_name:           ", this.settings.file_post_name, "\n",
			"\t", "post_params:              ", this.settings.post_params.toString(), "\n",
			"\t", "file_types:               ", this.settings.file_types, "\n",
			"\t", "file_types_description:   ", this.settings.file_types_description, "\n",
			"\t", "file_size_limit:          ", this.settings.file_size_limit, "\n",
			"\t", "file_upload_limit:        ", this.settings.file_upload_limit, "\n",
			"\t", "file_queue_limit:         ", this.settings.file_queue_limit, "\n",
			"\t", "debug:                    ", this.settings.debug.toString(), "\n",

			"\t", "prevent_swf_caching:      ", this.settings.prevent_swf_caching.toString(), "\n",

			"\t", "button_placeholder_id:    ", this.settings.button_placeholder_id.toString(), "\n",
			"\t", "button_placeholder:       ", (this.settings.button_placeholder ? "Set" : "Not Set"), "\n",
			"\t", "button_image_url:         ", this.settings.button_image_url.toString(), "\n",
			"\t", "button_width:             ", this.settings.button_width.toString(), "\n",
			"\t", "button_height:            ", this.settings.button_height.toString(), "\n",
			"\t", "button_text:              ", this.settings.button_text.toString(), "\n",
			"\t", "button_text_style:        ", this.settings.button_text_style.toString(), "\n",
			"\t", "button_text_top_padding:  ", this.settings.button_text_top_padding.toString(), "\n",
			"\t", "button_text_left_padding: ", this.settings.button_text_left_padding.toString(), "\n",
			"\t", "button_action:            ", this.settings.button_action.toString(), "\n",
			"\t", "button_disabled:          ", this.settings.button_disabled.toString(), "\n",

			"\t", "custom_settings:          ", this.settings.custom_settings.toString(), "\n",
			"Event Handlers:\n",
			"\t", "swfupload_loaded_handler assigned:  ", (typeof this.settings.swfupload_loaded_handler === "function").toString(), "\n",
			"\t", "file_dialog_start_handler assigned: ", (typeof this.settings.file_dialog_start_handler === "function").toString(), "\n",
			"\t", "file_queued_handler assigned:       ", (typeof this.settings.file_queued_handler === "function").toString(), "\n",
			"\t", "file_queue_error_handler assigned:  ", (typeof this.settings.file_queue_error_handler === "function").toString(), "\n",
			"\t", "upload_start_handler assigned:      ", (typeof this.settings.upload_start_handler === "function").toString(), "\n",
			"\t", "upload_progress_handler assigned:   ", (typeof this.settings.upload_progress_handler === "function").toString(), "\n",
			"\t", "upload_error_handler assigned:      ", (typeof this.settings.upload_error_handler === "function").toString(), "\n",
			"\t", "upload_success_handler assigned:    ", (typeof this.settings.upload_success_handler === "function").toString(), "\n",
			"\t", "upload_complete_handler assigned:   ", (typeof this.settings.upload_complete_handler === "function").toString(), "\n",
			"\t", "debug_handler assigned:             ", (typeof this.settings.debug_handler === "function").toString(), "\n"
		].join("")
	);
};

SWFUpload.prototype.addSetting = function(name, value, default_value) {
    if (value == undefined) {
        return (this.settings[name] = default_value);
    } else {
        return (this.settings[name] = value);
    }
};

SWFUpload.prototype.getSetting = function(name) {
    if (this.settings[name] != undefined) {
        return this.settings[name];
    }

    return "";
};

SWFUpload.prototype.callFlash = function(functionName, argumentArray) {
    argumentArray = argumentArray || [];

    var movieElement = this.getMovieElement();
    var returnValue, returnString;

    try {
        returnString = movieElement.CallFunction('<invoke name="' + functionName + '" returntype="javascript">' + __flash__argumentsToXML(argumentArray, 0) + '</invoke>');
        returnValue = eval(returnString);
    } catch (ex) {
        throw "Call to " + functionName + " failed";
    }

    if (returnValue != undefined && typeof returnValue.post === "object") {
        returnValue = this.unescapeFilePostParams(returnValue);
    }

    return returnValue;
};

SWFUpload.prototype.selectFile = function() {
    this.callFlash("SelectFile");
};

SWFUpload.prototype.selectFiles = function() {
    this.callFlash("SelectFiles");
};

SWFUpload.prototype.startUpload = function(fileID) {
    this.callFlash("StartUpload", [fileID]);
};

SWFUpload.prototype.cancelUpload = function(fileID, triggerErrorEvent) {
    if (triggerErrorEvent !== false) {
        triggerErrorEvent = true;
    }
    this.callFlash("CancelUpload", [fileID, triggerErrorEvent]);
};

SWFUpload.prototype.stopUpload = function() {
    this.callFlash("StopUpload");
};

SWFUpload.prototype.requeueUpload = function(indexOrFileID) {
    return this.callFlash("RequeueUpload", [indexOrFileID]);
};

SWFUpload.prototype.getStats = function() {
    return this.callFlash("GetStats");
};

SWFUpload.prototype.setStats = function(statsObject) {
    this.callFlash("SetStats", [statsObject]);
};

SWFUpload.prototype.getFile = function(fileID) {
    if (typeof (fileID) === "number") {
        return this.callFlash("GetFileByIndex", [fileID]);
    } else {
        return this.callFlash("GetFile", [fileID]);
    }
};

SWFUpload.prototype.addFileParam = function(fileID, name, value) {
    return this.callFlash("AddFileParam", [fileID, name, value]);
};

SWFUpload.prototype.removeFileParam = function(fileID, name) {
    this.callFlash("RemoveFileParam", [fileID, name]);
};

SWFUpload.prototype.setUploadURL = function(url) {
    this.settings.upload_url = url.toString();
    this.callFlash("SetUploadURL", [url]);
};

SWFUpload.prototype.setPostParams = function(paramsObject) {
    this.settings.post_params = paramsObject;
    this.callFlash("SetPostParams", [paramsObject]);
};

SWFUpload.prototype.addPostParam = function(name, value) {
    this.settings.post_params[name] = value;
    this.callFlash("SetPostParams", [this.settings.post_params]);
};

SWFUpload.prototype.removePostParam = function(name) {
    delete this.settings.post_params[name];
    this.callFlash("SetPostParams", [this.settings.post_params]);
};

SWFUpload.prototype.setFileTypes = function(types, description) {
    this.settings.file_types = types;
    this.settings.file_types_description = description;
    this.callFlash("SetFileTypes", [types, description]);
};

SWFUpload.prototype.setFileSizeLimit = function(fileSizeLimit) {
    this.settings.file_size_limit = fileSizeLimit;
    this.callFlash("SetFileSizeLimit", [fileSizeLimit]);
};

SWFUpload.prototype.setFileUploadLimit = function(fileUploadLimit) {
    this.settings.file_upload_limit = fileUploadLimit;
    this.callFlash("SetFileUploadLimit", [fileUploadLimit]);
};

SWFUpload.prototype.setFileQueueLimit = function(fileQueueLimit) {
    this.settings.file_queue_limit = fileQueueLimit;
    this.callFlash("SetFileQueueLimit", [fileQueueLimit]);
};

SWFUpload.prototype.setFilePostName = function(filePostName) {
    this.settings.file_post_name = filePostName;
    this.callFlash("SetFilePostName", [filePostName]);
};

SWFUpload.prototype.setUseQueryString = function(useQueryString) {
    this.settings.use_query_string = useQueryString;
    this.callFlash("SetUseQueryString", [useQueryString]);
};

SWFUpload.prototype.setRequeueOnError = function(requeueOnError) {
    this.settings.requeue_on_error = requeueOnError;
    this.callFlash("SetRequeueOnError", [requeueOnError]);
};

SWFUpload.prototype.setHTTPSuccess = function(http_status_codes) {
    if (typeof http_status_codes === "string") {
        http_status_codes = http_status_codes.replace(" ", "").split(",");
    }

    this.settings.http_success = http_status_codes;
    this.callFlash("SetHTTPSuccess", [http_status_codes]);
};

SWFUpload.prototype.setAssumeSuccessTimeout = function(timeout_seconds) {
    this.settings.assume_success_timeout = timeout_seconds;
    this.callFlash("SetAssumeSuccessTimeout", [timeout_seconds]);
};

SWFUpload.prototype.setDebugEnabled = function(debugEnabled) {
    this.settings.debug_enabled = debugEnabled;
    this.callFlash("SetDebugEnabled", [debugEnabled]);
};

SWFUpload.prototype.setButtonImageURL = function(buttonImageURL) {
    if (buttonImageURL == undefined) {
        buttonImageURL = "";
    }

    this.settings.button_image_url = buttonImageURL;
    this.callFlash("SetButtonImageURL", [buttonImageURL]);
};

SWFUpload.prototype.setButtonDimensions = function(width, height) {
    this.settings.button_width = width;
    this.settings.button_height = height;

    var movie = this.getMovieElement();
    if (movie != undefined) {
        movie.style.width = width + "px";
        movie.style.height = height + "px";
    }

    this.callFlash("SetButtonDimensions", [width, height]);
};
SWFUpload.prototype.setButtonText = function(html) {
    this.settings.button_text = html;
    this.callFlash("SetButtonText", [html]);
};
SWFUpload.prototype.setButtonTextPadding = function(left, top) {
    this.settings.button_text_top_padding = top;
    this.settings.button_text_left_padding = left;
    this.callFlash("SetButtonTextPadding", [left, top]);
};

SWFUpload.prototype.setButtonTextStyle = function(css) {
    this.settings.button_text_style = css;
    this.callFlash("SetButtonTextStyle", [css]);
};
SWFUpload.prototype.setButtonDisabled = function(isDisabled) {
    this.settings.button_disabled = isDisabled;
    this.callFlash("SetButtonDisabled", [isDisabled]);
};
SWFUpload.prototype.setButtonAction = function(buttonAction) {
    this.settings.button_action = buttonAction;
    this.callFlash("SetButtonAction", [buttonAction]);
};

SWFUpload.prototype.setButtonCursor = function(cursor) {
    this.settings.button_cursor = cursor;
    this.callFlash("SetButtonCursor", [cursor]);
};

SWFUpload.prototype.queueEvent = function(handlerName, argumentArray) {
    // Warning: Don't call this.debug inside here or you'll create an infinite loop

    if (argumentArray == undefined) {
        argumentArray = [];
    } else if (!(argumentArray instanceof Array)) {
        argumentArray = [argumentArray];
    }

    var self = this;
    if (typeof this.settings[handlerName] === "function") {
        this.eventQueue.push(function() {
            this.settings[handlerName].apply(this, argumentArray);
        });

        setTimeout(function() {
            self.executeNextEvent();
        }, 0);

    } else if (this.settings[handlerName] !== null) {
        throw "Event handler " + handlerName + " is unknown or is not a function";
    }
};

SWFUpload.prototype.executeNextEvent = function() {
    // Warning: Don't call this.debug inside here or you'll create an infinite loop

    var f = this.eventQueue ? this.eventQueue.shift() : null;
    if (typeof (f) === "function") {
        f.apply(this);
    }
};

SWFUpload.prototype.unescapeFilePostParams = function(file) {
    var reg = /[$]([0-9a-f]{4})/i;
    var unescapedPost = {};
    var uk;

    if (file != undefined) {
        for (var k in file.post) {
            if (file.post.hasOwnProperty(k)) {
                uk = k;
                var match;
                while ((match = reg.exec(uk)) !== null) {
                    uk = uk.replace(match[0], String.fromCharCode(parseInt("0x" + match[1], 16)));
                }
                unescapedPost[uk] = file.post[k];
            }
        }

        file.post = unescapedPost;
    }

    return file;
};

SWFUpload.prototype.testExternalInterface = function() {
    try {
        return this.callFlash("TestExternalInterface");
    } catch (ex) {
        return false;
    }
};

SWFUpload.prototype.flashReady = function() {
    var movieElement = this.getMovieElement();

    if (!movieElement) {
        this.debug("Flash called back ready but the flash movie can't be found.");
        return;
    }

    this.cleanUp();

    this.queueEvent("swfupload_loaded_handler");
};

SWFUpload.prototype.cleanUp = function() {
    var movieElement = this.getMovieElement();

    try {
        if (movieElement && typeof (movieElement.CallFunction) === "unknown") { // We only want to do this in IE
            this.debug("Removing Flash functions hooks (this should only run in IE and should prevent memory leaks)");
            for (var key in movieElement) {
                try {
                    if (typeof (movieElement[key]) === "function") {
                        movieElement[key] = null;
                    }
                } catch (ex) {
                }
            }
        }
    } catch (ex1) {

    }

    window["__flash__removeCallback"] = function(instance, name) {
        try {
            if (instance) {
                instance[name] = null;
            }
        } catch (flashEx) {

        }
    };

    return movieElement;
};

SWFUpload.prototype.buttonAction = function() {
    this.queueEvent("button_action_handler");
};

SWFUpload.prototype.fileDialogStart = function() {
    this.queueEvent("file_dialog_start_handler");
};

SWFUpload.prototype.fileQueued = function(file) {
    file = this.unescapeFilePostParams(file);
    this.queueEvent("file_queued_handler", file);
};

SWFUpload.prototype.fileQueueError = function(file, errorCode, message) {
    file = this.unescapeFilePostParams(file);
    this.queueEvent("file_queue_error_handler", [file, errorCode, message]);
};

SWFUpload.prototype.fileDialogComplete = function(numFilesSelected, numFilesQueued, numFilesInQueue) {
    this.queueEvent("file_dialog_complete_handler", [numFilesSelected, numFilesQueued, numFilesInQueue]);
};

SWFUpload.prototype.uploadStart = function(file) {
    file = this.unescapeFilePostParams(file);
    this.queueEvent("return_upload_start_handler", file);
};

SWFUpload.prototype.returnUploadStart = function(file) {
    var returnValue;
    if (typeof this.settings.upload_start_handler === "function") {
        file = this.unescapeFilePostParams(file);
        returnValue = this.settings.upload_start_handler.call(this, file);
    } else if (this.settings.upload_start_handler != undefined) {
        throw "upload_start_handler must be a function";
    }

    if (returnValue === undefined) {
        returnValue = true;
    }

    returnValue = !!returnValue;

    this.callFlash("ReturnUploadStart", [returnValue]);
};



SWFUpload.prototype.uploadProgress = function(file, bytesComplete, bytesTotal) {
    file = this.unescapeFilePostParams(file);
    this.queueEvent("upload_progress_handler", [file, bytesComplete, bytesTotal]);
};

SWFUpload.prototype.uploadError = function(file, errorCode, message) {
    file = this.unescapeFilePostParams(file);
    this.queueEvent("upload_error_handler", [file, errorCode, message]);
};

SWFUpload.prototype.uploadSuccess = function(file, serverData, responseReceived) {
    file = this.unescapeFilePostParams(file);
    this.queueEvent("upload_success_handler", [file, serverData, responseReceived]);
};

SWFUpload.prototype.uploadComplete = function(file) {
    file = this.unescapeFilePostParams(file);
    this.queueEvent("upload_complete_handler", file);
};

SWFUpload.prototype.debug = function(message) {
    this.queueEvent("debug_handler", message);
};

SWFUpload.prototype.debugMessage = function(message) {
    if (this.settings.debug) {
        var exceptionMessage, exceptionValues = [];

        // Check for an exception object and print it nicely
        if (typeof message === "object" && typeof message.name === "string" && typeof message.message === "string") {
            for (var key in message) {
                if (message.hasOwnProperty(key)) {
                    exceptionValues.push(key + ": " + message[key]);
                }
            }
            exceptionMessage = exceptionValues.join("\n") || "";
            exceptionValues = exceptionMessage.split("\n");
            exceptionMessage = "EXCEPTION: " + exceptionValues.join("\nEXCEPTION: ");
            SWFUpload.Console.writeLine(exceptionMessage);
        } else {
            SWFUpload.Console.writeLine(message);
        }
    }
};

SWFUpload.Console = {};
SWFUpload.Console.writeLine = function(message) {
    var console, documentForm;

    try {
        console = document.getElementById("SWFUpload_Console");

        if (!console) {
            documentForm = document.createElement("form");
            document.getElementsByTagName("body")[0].appendChild(documentForm);

            console = document.createElement("textarea");
            console.id = "SWFUpload_Console";
            console.style.fontFamily = "monospace";
            console.setAttribute("wrap", "off");
            console.wrap = "off";
            console.style.overflow = "auto";
            console.style.width = "700px";
            console.style.height = "350px";
            console.style.margin = "5px";
            documentForm.appendChild(console);
        }

        console.value += message + "\n";

        console.scrollTop = console.scrollHeight - console.clientHeight;
    } catch (ex) {
        alert("Exception: " + ex.name + " Message: " + ex.message);
    }
};

//swfupload fileprogress
/*
A simple class for displaying file information and progress
Note: This is a demonstration only and not part of SWFUpload.
Note: Some have had problems adapting this class in IE7. It may not be suitable for your application.
*/

// Constructor
// file is a SWFUpload file object
// targetID is the HTML element id attribute that the FileProgress HTML structure will be added to.
// Instantiating a new FileProgress object with an existing file will reuse/update the existing DOM elements
function FileProgress(file, targetID) {
    this.fileProgressID = file.id;

    this.opacity = 100;
    this.height = 0;

    this.fileProgressWrapper = document.getElementById(this.fileProgressID);
    if (!this.fileProgressWrapper) {
        this.fileProgressWrapper = document.createElement("div");
        this.fileProgressWrapper.className = "progressWrapper";
        this.fileProgressWrapper.id = this.fileProgressID;

        this.fileProgressElement = document.createElement("div");
        this.fileProgressElement.className = "progressContainer";

        var progressCancel = document.createElement("a");
        progressCancel.className = "progressCancel";
        progressCancel.href = "#";
        progressCancel.style.visibility = "hidden";
        progressCancel.appendChild(document.createTextNode(" "));

        var progressText = document.createElement("div");
        progressText.className = "progressName";
        progressText.appendChild(document.createTextNode(file.name));

        var progressBar = document.createElement("div");
        progressBar.className = "progressBarInProgress";

        var progressStatus = document.createElement("div");
        progressStatus.className = "progressBarStatus";
        progressStatus.innerHTML = "&nbsp;";

        this.fileProgressElement.appendChild(progressCancel);
        this.fileProgressElement.appendChild(progressText);
        this.fileProgressElement.appendChild(progressStatus);
        this.fileProgressElement.appendChild(progressBar);

        this.fileProgressWrapper.appendChild(this.fileProgressElement);

        document.getElementById(targetID).appendChild(this.fileProgressWrapper);
    } else {
        this.fileProgressElement = this.fileProgressWrapper.firstChild;
        this.reset();
    }

    this.height = this.fileProgressWrapper.offsetHeight;
    this.setTimer(null);
}

FileProgress.prototype.setTimer = function(timer) {
    this.fileProgressElement["FP_TIMER"] = timer;
};
FileProgress.prototype.getTimer = function(timer) {
    return this.fileProgressElement["FP_TIMER"] || null;
};

FileProgress.prototype.reset = function() {
    this.fileProgressElement.className = "progressContainer";

    this.fileProgressElement.childNodes[2].innerHTML = "&nbsp;";
    this.fileProgressElement.childNodes[2].className = "progressBarStatus";

    this.fileProgressElement.childNodes[3].className = "progressBarInProgress";
    this.fileProgressElement.childNodes[3].style.width = "0%";

    //this.appear();
    $("#" + this.fileProgressID).fadeIn('fast');
};

FileProgress.prototype.setProgress = function(percentage) {
    this.fileProgressElement.className = "progressContainer green";
    this.fileProgressElement.childNodes[3].className = "progressBarInProgress";
    this.fileProgressElement.childNodes[3].style.width = percentage + "%";

    //this.appear();
    $("#" + this.fileProgressID).fadeIn('fast');
};
FileProgress.prototype.setComplete = function() {
    this.fileProgressElement.className = "progressContainer blue";
    this.fileProgressElement.childNodes[3].className = "progressBarComplete";
    this.fileProgressElement.childNodes[3].style.width = "";

    //var oSelf = this;
    //this.setTimer(setTimeout(function() {
    //    oSelf.disappear();
    //}, 10000));

    setTimeout(function() {
        $("#" + this.fileProgressID).fadeOut('slow', 3000);
    }, 10000);
};
FileProgress.prototype.setError = function() {
    this.fileProgressElement.className = "progressContainer red";
    this.fileProgressElement.childNodes[3].className = "progressBarError";
    this.fileProgressElement.childNodes[3].style.width = "";

    //var oSelf = this;
    //this.setTimer(setTimeout(function() {
    //    oSelf.disappear();
    //}, 5000));

    setTimeout(function() {
        $("#" + this.fileProgressID).fadeOut('slow');
    }, 5000);
};
FileProgress.prototype.setCancelled = function() {
    this.fileProgressElement.className = "progressContainer";
    this.fileProgressElement.childNodes[3].className = "progressBarError";
    this.fileProgressElement.childNodes[3].style.width = "";

    //var oSelf = this;
    //this.setTimer(setTimeout(function() {
    //    oSelf.disappear();
    //}, 2000));

    setTimeout(function() {
    $("#" + this.fileProgressID).fadeOut('slow');
    }, 2000);
};
FileProgress.prototype.setStatus = function(status) {
    this.fileProgressElement.childNodes[2].innerHTML = status;
};

// Show/Hide the cancel button
FileProgress.prototype.toggleCancel = function(show, swfUploadInstance) {
    this.fileProgressElement.childNodes[0].style.visibility = show ? "visible" : "hidden";
    if (swfUploadInstance) {
        var fileID = this.fileProgressID;
        this.fileProgressElement.childNodes[0].onclick = function() {
            swfUploadInstance.cancelUpload(fileID);
            return false;
        };
    }
};

//swfupload handlers
function cancelQueue(instance) {
    document.getElementById(instance.customSettings.cancelButtonId).disabled = true;
    instance.stopUpload();
    var stats;

    do {
        stats = instance.getStats();
        instance.cancelUpload();
    } while (stats.files_queued !== 0);

}

function fileDialogStart() {
    /* I don't need to do anything here */
}
function fileQueued(file) {
    try {
        // You might include code here that prevents the form from being submitted while the upload is in
        // progress.  Then you'll want to put code in the Queue Complete handler to "unblock" the form
        var progress = new FileProgress(file, this.customSettings.progressTarget);
        progress.setStatus("Pending...");
        progress.toggleCancel(true, this);

    } catch (ex) {
        this.debug(ex);
    }

}

function fileQueueError(file, errorCode, message) {
    try {
        if (errorCode === SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED) {
            jQuery.ShowError("You have attempted to queue too many files.\n" + (message === 0 ? "You have reached the upload limit." : "You may select " + (message > 1 ? "up to " + message + " files." : "one file.")));
            return;
        }

        var progress = new FileProgress(file, this.customSettings.progressTarget);
        progress.setError();
        progress.toggleCancel(false);

        switch (errorCode) {
            case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
                progress.setStatus("File is too big.");
                this.debug("Error Code: File too big, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
                break;
            case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
                progress.setStatus("Cannot upload Zero Byte files.");
                this.debug("Error Code: Zero byte file, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
                break;
            case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE:
                progress.setStatus("Invalid File Type.");
                this.debug("Error Code: Invalid File Type, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
                break;
            case SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED:
                jQuery.ShowError("You have selected too many files.  " + (message > 1 ? "You may only add " + message + " more files" : "You cannot add any more files."));
                break;
            default:
                if (file !== null) {
                    progress.setStatus("Unhandled Error");
                }
                this.debug("Error Code: " + errorCode + ", File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
                break;
        }
    } catch (ex) {
        this.debug(ex);
    }
}

function fileDialogComplete(numFilesSelected, numFilesQueued) {
    try {
        if (this.getStats().files_queued > 0) {
            document.getElementById(this.customSettings.cancelButtonId).disabled = false;
        }

        /* I want auto start and I can do that here */
        this.startUpload();
    } catch (ex) {
        this.debug(ex);
    }
}

function uploadStart(file) {
    try {
        /* I don't want to do any file validation or anything,  I'll just update the UI and return true to indicate that the upload should start */
        var progress = new FileProgress(file, this.customSettings.progressTarget);
        progress.setStatus("Uploading...");
        progress.toggleCancel(true, this);
    }
    catch (ex) {
    }

    return true;
}

function uploadProgress(file, bytesLoaded, bytesTotal) {

    try {
        var percent = Math.ceil((bytesLoaded / bytesTotal) * 100);

        var progress = new FileProgress(file, this.customSettings.progressTarget);
        progress.setProgress(percent);
        progress.setStatus("Uploading...");
    } catch (ex) {
        this.debug(ex);
    }
}

function uploadSuccess(file, serverData) {
    try {
        var progress = new FileProgress(file, this.customSettings.progressTarget);
        progress.setComplete();
        progress.setStatus("Complete.");
        progress.toggleCancel(false);

    } catch (ex) {
        this.debug(ex);
    }
}

function uploadComplete(file) {
    try {
        /*  I want the next upload to continue automatically so I'll call startUpload here */
        if (this.getStats().files_queued === 0) {
            document.getElementById(this.customSettings.cancelButtonId).disabled = true;
        } else {
            this.startUpload();
        }
    } catch (ex) {
        this.debug(ex);
    }

}

function uploadError(file, errorCode, message) {
    try {
        var progress = new FileProgress(file, this.customSettings.progressTarget);
        progress.setError();
        progress.toggleCancel(false);

        switch (errorCode) {
            case SWFUpload.UPLOAD_ERROR.HTTP_ERROR:
                progress.setStatus("Upload Error: " + message);
                this.debug("Error Code: HTTP Error, File name: " + file.name + ", Message: " + message);
                break;
            case SWFUpload.UPLOAD_ERROR.MISSING_UPLOAD_URL:
                progress.setStatus("Configuration Error");
                this.debug("Error Code: No backend file, File name: " + file.name + ", Message: " + message);
                break;
            case SWFUpload.UPLOAD_ERROR.UPLOAD_FAILED:
                progress.setStatus("Upload Failed.");
                this.debug("Error Code: Upload Failed, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
                break;
            case SWFUpload.UPLOAD_ERROR.IO_ERROR:
                progress.setStatus("Server (IO) Error");
                this.debug("Error Code: IO Error, File name: " + file.name + ", Message: " + message);
                break;
            case SWFUpload.UPLOAD_ERROR.SECURITY_ERROR:
                progress.setStatus("Security Error");
                this.debug("Error Code: Security Error, File name: " + file.name + ", Message: " + message);
                break;
            case SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED:
                progress.setStatus("Upload limit exceeded.");
                this.debug("Error Code: Upload Limit Exceeded, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
                break;
            case SWFUpload.UPLOAD_ERROR.SPECIFIED_FILE_ID_NOT_FOUND:
                progress.setStatus("File not found.");
                this.debug("Error Code: The file was not found, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
                break;
            case SWFUpload.UPLOAD_ERROR.FILE_VALIDATION_FAILED:
                progress.setStatus("Failed Validation.  Upload skipped.");
                this.debug("Error Code: File Validation Failed, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
                break;
            case SWFUpload.UPLOAD_ERROR.FILE_CANCELLED:
                if (this.getStats().files_queued === 0) {
                    document.getElementById(this.customSettings.cancelButtonId).disabled = true;
                }
                progress.setStatus("Cancelled");
                progress.setCancelled();
                break;
            case SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED:
                progress.setStatus("Stopped");
                break;
            default:
                progress.setStatus("Unhandled Error: " + error_code);
                this.debug("Error Code: " + errorCode + ", File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
                break;
        }
    } catch (ex) {
        this.debug(ex);
    }
}

//jquery-asyncUpload-0.1.js
(function($) {
    $.fn.makeAsyncUploader = function(options) {
        return this.each(function() {
            var id = $(this).attr("id");
            var container = $("<span class='asyncUploader'/>");
            container.append($("<div class='ProgressBar'> <div>&nbsp;</div> </div>"));
            container.append($("<span id='" + id + "_completedMessage'/>"));
            container.append($("<span id='" + id + "_uploading'>Uploading... <input type='button' value='Cancel'/></span>"));
            container.append($("<span id='" + id + "_swf'/>"));
            container.append($("<input type='hidden' name='" + id + "_filename'/>"));
            container.append($("<input type='hidden' name='" + id + "_guid'/>"));
            $(this).before(container).remove();
            $("div.ProgressBar", container).hide();
            $("span[id$=_uploading]", container).hide();


            var swfu;
            var width = 109, height = 22;
            if (options) {
                width = options.width || width;
                height = options.height || height;
            }
            var defaults = {
                flash_url: "/scripts/upload/swfupload.swf",
                upload_url: "/Categories/ImportTransactions",
                file_size_limit: "5 MB",
                file_types: "*.*",
                file_types_description: "All Files",
                debug: false,
                allowSecondUpload: true,

                button_image_url: "blankButton.png",
                button_width: width,
                button_height: height,
                button_placeholder_id: id + "_swf",
                button_text: "<font face='Arial' size='13pt'>Choose file</span>",
                button_text_left_padding: (width - 70) / 2,
                button_text_top_padding: 1,

                file_queued_handler: function(file) { swfu.startUpload(); },

                file_queue_error_handler: function(file, code, msg) { alert("Sorry, your file wasn't uploaded: " + msg); },

                upload_error_handler: function(file, code, msg) { alert("Sorry, your file wasn't uploaded: " + msg); },

                upload_start_handler: function() {
                    swfu.setButtonDimensions(0, height);
                    $("input[name$=_filename]", container).val("");
                    $("input[name$=_guid]", container).val("");
                    $("div.ProgressBar div", container).css("width", "0px");
                    $("div.ProgressBar", container).show();
                    $("span[id$=_uploading]", container).show();
                    $("span[id$=_completedMessage]", container).html("").hide();

                    if (options.disableDuringUpload)
                        $(options.disableDuringUpload).attr("disabled", "disabled");
                },

                upload_success_handler: function(file, response) {
                    $("input[name$=_filename]", container).val(file.name);
                    $("input[name$=_guid]", container).val(response);
                    $("span[id$=_completedMessage]", container).html("Uploaded <b>{0}</b> ({1} KB)"
                                .replace("{0}", file.name)
                                .replace("{1}", Math.round(file.size / 1024))
                            );
                },

                upload_complete_handler: function() {
                    var clearup = function() {                        
                        $("div.ProgressBar", container).hide();
                        $("span[id$=_completedMessage]", container).show();
                        $("span[id$=_uploading]", container).hide();

                        if (options.allowSecondUpload) {
                            swfu.setButtonDimensions(width, height);
                        }
                    };
                    if ($("input[name$=_filename]", container).val() != "") // Success
                        $("div.ProgressBar div", container).animate({ width: "100%" }, { duration: "fast", queue: false, complete: clearup });
                    else // Fail
                        clearup();

                    if (options.disableDuringUpload)
                        $(options.disableDuringUpload).removeAttr("disabled");
                },

                upload_progress_handler: function(file, bytes, total) {
                    var percent = 100 * bytes / total;
                    $("div.ProgressBar div", container).animate({ width: percent + "%" }, { duration: 500, queue: false });
                }
            };
            swfu = new SWFUpload($.extend(defaults, options || {}));

            $("span[id$=_uploading] input[type='button']", container).click(function() {
                swfu.cancelUpload(null, false);
            });

            if (options.existingFilename || "" != "") {
                $("span[id$=_completedMessage]", container).html("Uploaded <b>{0}</b> ({1} KB)"
                                .replace("{0}", options.existingFilename)
                                .replace("{1}", options.existingFileSize ? Math.round(options.existingFileSize / 1024) : "?")
                            ).show();
                $("input[name$=_filename]", container).val(options.existingFilename);
            }
            if (options.existingGuid || "" != "")
                $("input[name$=_guid]", container).val(options.existingGuid);
        });
    }
})(jQuery);

//jquery.calculator.min.js
(function($) { var p = 'calculator'; function Calculator() { this._curInst = null; this._disabledFields = []; this._showingCalculator = false; this._showingKeystrokes = false; this._keyDefs = { '_0': ['0', this.digit, null, '', '0', '0'], '_1': ['1', this.digit, null, '', '1', '1'], '_2': ['2', this.digit, null, '', '2', '2'], '_3': ['3', this.digit, null, '', '3', '3'], '_4': ['4', this.digit, null, '', '4', '4'], '_5': ['5', this.digit, null, '', '5', '5'], '_6': ['6', this.digit, null, '', '6', '6'], '_7': ['7', this.digit, null, '', '7', '7'], '_8': ['8', this.digit, null, '', '8', '8'], '_9': ['9', this.digit, null, '', '9', '9'], '_A': ['A', this.digit, null, 'hex-digit', 'A', 'a'], '_B': ['B', this.digit, null, 'hex-digit', 'B', 'b'], '_C': ['C', this.digit, null, 'hex-digit', 'C', 'c'], '_D': ['D', this.digit, null, 'hex-digit', 'D', 'd'], '_E': ['E', this.digit, null, 'hex-digit', 'E', 'e'], '_F': ['F', this.digit, null, 'hex-digit', 'F', 'f'], '_.': ['.', this.digit, null, 'decimal', 'DECIMAL', '.'], '_+': ['+', this.binary, this._add, 'arith add', 'ADD', '+'], '_-': ['-', this.binary, this._subtract, 'arith subtract', 'SUBTRACT', '-'], '_*': ['*', this.binary, this._multiply, 'arith multiply', 'MULTIPLY', '*'], '_/': ['/', this.binary, this._divide, 'arith divide', 'DIVIDE', '/'], '_%': ['%', this.unary, this._percent, 'arith percent', 'PERCENT', '%'], '_=': ['=', this.unary, this._equals, 'arith equals', 'EQUALS', '='], '+-': ['±', this.unary, this._plusMinus, 'arith plus-minus', 'PLUS_MINUS', '#'], 'PI': ['pi', this.unary, this._pi, 'pi', 'PI', 'p'], '1X': ['1/x', this.unary, this._inverse, 'fn inverse', 'INV', 'i'], 'LG': ['log', this.unary, this._log, 'fn log', 'LOG', 'l'], 'LN': ['ln', this.unary, this._ln, 'fn ln', 'LN', 'n'], 'EX': ['eⁿ', this.unary, this._exp, 'fn exp', 'EXP', 'E'], 'SQ': ['x²', this.unary, this._sqr, 'fn sqr', 'SQR', '@'], 'SR': ['√', this.unary, this._sqrt, 'fn sqrt', 'SQRT', '!'], 'XY': ['x^y', this.binary, this._power, 'fn power', 'POWER', '^'], 'RN': ['rnd', this.unary, this._random, 'random', 'RANDOM', '?'], 'SN': ['sin', this.unary, this._sin, 'trig sin', 'SIN', 's'], 'CS': ['cos', this.unary, this._cos, 'trig cos', 'COS', 'o'], 'TN': ['tan', this.unary, this._tan, 'trig tan', 'TAN', 't'], 'AS': ['asin', this.unary, this._asin, 'trig asin', 'ASIN', 'S'], 'AC': ['acos', this.unary, this._acos, 'trig acos', 'ACOS', 'O'], 'AT': ['atan', this.unary, this._atan, 'trig atan', 'ATAN', 'T'], 'MC': ['#memClear', this.unary, this._memClear, 'memory mem-clear', 'MEM_CLEAR', 'x'], 'MR': ['#memRecall', this.unary, this._memRecall, 'memory mem-recall', 'MEM_RECALL', 'r'], 'MS': ['#memStore', this.unary, this._memStore, 'memory mem-store', 'MEM_STORE', 'm'], 'M+': ['#memAdd', this.unary, this._memAdd, 'memory mem-add', 'MEM_ADD', '>'], 'M-': ['#memSubtract', this.unary, this._memSubtract, 'memory mem-subtract', 'MEM_SUBTRACT', '<'], 'BB': ['#base2', this.control, this._base2, 'base base2', 'BASE_2', 'B'], 'BO': ['#base8', this.control, this._base8, 'base base8', 'BASE_8', 'C'], 'BD': ['#base10', this.control, this._base10, 'base base10', 'BASE_10', 'D'], 'BH': ['#base16', this.control, this._base16, 'base base16', 'BASE_16', 'H'], 'DG': ['#degrees', this.control, this._degrees, 'angle degrees', 'DEGREES', 'G'], 'RD': ['#radians', this.control, this._radians, 'angle radians', 'RADIANS', 'R'], 'BS': ['#backspace', this.control, this._undo, 'undo', 'UNDO', 8, 'BSp'], 'CE': ['#clearError', this.control, this._clearError, 'clear-error', 'CLEAR_ERROR', 36, 'Hom'], 'CA': ['#clear', this.control, this._clear, 'clear', 'CLEAR', 35, 'End'], '@X': ['#close', this.control, this._close, 'close', 'CLOSE', 27, 'Esc'], '@U': ['#use', this.control, this._use, 'use', 'USE', 13, 'Ent'], '@E': ['#erase', this.control, this._erase, 'erase', 'ERASE', 46, 'Del'], '  ': ['', this.space, null, 'space', 'SPACE'], '_ ': ['', this.space, null, 'half-space', 'HALF_SPACE'], '??': ['??', this.unary, this._noOp] }; this._keyCodes = {}; this._keyChars = {}; for (var a in this._keyDefs) { if (this._keyDefs[a][4]) { this[this._keyDefs[a][4]] = a } if (this._keyDefs[a][5]) { if (typeof this._keyDefs[a][5] == 'number') { this._keyCodes[this._keyDefs[a][5]] = a } else { this._keyChars[this._keyDefs[a][5]] = a } } } this.regional = []; this.regional[''] = { decimalChar: '.', buttonText: '...', buttonStatus: 'Open the calculator', closeText: 'Close', closeStatus: 'Close the calculator', useText: 'Use', useStatus: 'Use the current value', eraseText: 'Erase', eraseStatus: 'Erase the value from the field', backspaceText: 'BS', backspaceStatus: 'Erase the last digit', clearErrorText: 'CE', clearErrorStatus: 'Erase the last number', clearText: 'CA', clearStatus: 'Reset the calculator', memClearText: 'MC', memClearStatus: 'Clear the memory', memRecallText: 'MR', memRecallStatus: 'Recall the value from memory', memStoreText: 'MS', memStoreStatus: 'Store the value in memory', memAddText: 'M+', memAddStatus: 'Add to memory', memSubtractText: 'M-', memSubtractStatus: 'Subtract from memory', base2Text: 'Bin', base2Status: 'Switch to binary', base8Text: 'Oct', base8Status: 'Switch to octal', base10Text: 'Dec', base10Status: 'Switch to decimal', base16Text: 'Hex', base16Status: 'Switch to hexadecimal', degreesText: 'Deg', degreesStatus: 'Switch to degrees', radiansText: 'Rad', radiansStatus: 'Switch to radians', isRTL: false }; this._defaults = { showOn: 'focus', buttonImage: '', buttonImageOnly: false, isOperator: null, showAnim: 'show', showOptions: {}, duration: 'normal', appendText: '', calculatorClass: '', prompt: '', layout: this.standardLayout, value: 0, base: 10, precision: 10, useDegrees: false, constrainInput: true, onButton: null, onClose: null }; $.extend(this._defaults, this.regional['']); this.mainDiv = $('<div id="' + this._mainDivId + '" style="display: none;"></div>').click(this._focusEntry) } $.extend(Calculator.prototype, { markerClassName: 'hasCalculator', digit: 'd', binary: 'b', unary: 'u', control: 'c', space: 's', _mainDivId: 'calculator-div', _inlineClass: 'calculator-inline', _appendClass: 'calculator-append', _triggerClass: 'calculator-trigger', _disableClass: 'calculator-disabled', _inlineEntryClass: 'calculator-keyentry', _resultClass: 'calculator-result', _focussedClass: 'calculator-focussed', _keystrokeClass: 'calculator-keystroke', _coverClass: 'calculator-cover', standardLayout: ['  BSCECA', '_1_2_3_+@X', '_4_5_6_-@U', '_7_8_9_*@E', '_0_._=_/'], scientificLayout: ['@X@U@E  BSCECA', 'DGRD    _ MC_ _7_8_9_+', 'SNASSRLG_ MR_ _4_5_6_-', 'CSACSQLN_ MS_ _1_2_3_*', 'TNATXYEX_ M+_ _0_.+-_/', 'PIRN1X  _ M-_   _%_='], setDefaults: function(a) { extendRemove(this._defaults, a || {}); return this }, addKeyDef: function(a, b, c, d, e, f, g, h) { this._keyDefs[a] = [b, (typeof c == 'boolean' ? (c ? this.binary : this.unary) : c), d, e, f, g, h]; if (f) { this[f] = a } if (g) { if (typeof g == 'number') { this._keyCodes[g] = a } else { this._keyChars[g] = a } } return this }, _attachCalculator: function(a, b) { var c = $(a); var d = a.nodeName.toLowerCase() != 'input'; var e = (!d ? c : $('<input type="text" class="' + this._inlineEntryClass + '"/>')); var f = { _input: e, _inline: d, _mainDiv: (d ? $('<div class="' + this._inlineClass + '"></div>') : this.mainDiv) }; f.settings = $.extend({}, b || {}); this._connectCalculator(a, f); if (d) { c.append(e).append(f._mainDiv).bind('click.calculator', function() { e.focus() }); this._reset(f, '0', true); this._setValue(f); this._updateCalculator(f) } }, _connectCalculator: function(d, e) { var f = $(d); if (f.hasClass(this.markerClassName)) { return } var g = this._get(e, 'appendText'); var h = this._get(e, 'isRTL'); if (g) { f[h ? 'before' : 'after']('<span class="' + this._appendClass + '">' + g + '</span>') } if (!e._inline) { var i = this._get(e, 'showOn'); if (i == 'focus' || i == 'both') { f.focus(this._showCalculator) } if (i == 'button' || i == 'both' || i == 'opbutton') { var j = this._get(e, 'buttonText'); var k = this._get(e, 'buttonStatus'); var l = this._get(e, 'buttonImage'); var m = $(this._get(e, 'buttonImageOnly') ? $('<img/>').attr({ src: l, alt: k, title: k }) : $('<button type="button" title="' + k + '"></button>').html(l == '' ? j : $('<img/>').attr({ src: l }))); f[h ? 'before' : 'after'](m); m.addClass(this._triggerClass).click(function() { if ($.calculator._showingCalculator && $.calculator._lastInput == d) { $.calculator._hideCalculator() } else { $.calculator._showCalculator(d) } return false }) } } e._input.keydown(this._doKeyDown).keyup(this._doKeyUp).keypress(this._doKeyPress); if (e._inline) { e._mainDiv.keydown(this._doKeyDown).keyup(this._doKeyUp).keypress(this._doKeyPress); e._input.focus(function() { if (!$.calculator._isDisabledCalculator(f[0])) { e._focussed = true; $('.' + $.calculator._resultClass, e._mainDiv).addClass($.calculator._focussedClass) } }).blur(function() { e._focussed = false; $('.' + $.calculator._resultClass, e._mainDiv).removeClass($.calculator._focussedClass) }) } f.addClass(this.markerClassName).bind("setData.calculator", function(a, b, c) { e.settings[b] = c }).bind("getData.calculator", function(a, b) { return this._get(e, b) }); $.data(d, p, e); $.data(e._input[0], p, e) }, _destroyCalculator: function(a) { var b = $(a); if (!b.hasClass(this.markerClassName)) { return } var c = $.data(a, p); c._input.unbind('keydown', this._doKeyDown).unbind('keyup', this._doKeyUp).unbind('keypress', this._doKeyPress); b.siblings('.' + this._appendClass).remove().end().siblings('.' + this._triggerClass).remove().end().prev('.' + this._inlineEntryClass).remove().end().removeClass(this.markerClassName).unbind('focus', this._showCalculator).unbind('click.calculator').empty(); $.removeData(c._input[0], p); $.removeData(a, p) }, _enableCalculator: function(b) { var c = $(b); if (!c.hasClass(this.markerClassName)) { return } var d = b.nodeName.toLowerCase(); if (d == 'input') { b.disabled = false; c.siblings('button.' + this._triggerClass).each(function() { this.disabled = false }).end().siblings('img.' + this._triggerClass).css({ opacity: '1.0', cursor: '' }) } else if (d == 'div' || d == 'span') { c.find('.' + this._inlineEntryClass + ',button').attr('disabled', '').end().children('.' + this._disableClass).remove() } this._disabledFields = $.map(this._disabledFields, function(a) { return (a == b ? null : a) }) }, _disableCalculator: function(b) { var c = $(b); if (!c.hasClass(this.markerClassName)) { return } var d = b.nodeName.toLowerCase(); if (d == 'input') { b.disabled = true; c.siblings('button.' + this._triggerClass).each(function() { this.disabled = true }).end().siblings('img.' + this._triggerClass).css({ opacity: '0.5', cursor: 'default' }) } else if (d == 'div' || d == 'span') { var e = c.children('.' + this._inlineClass); var f = e.offset(); var g = { left: 0, top: 0 }; e.parents().each(function() { if ($(this).css('position') == 'relative') { g = $(this).offset(); return false } }); c.find('.' + this._inlineEntryClass + ',button').attr('disabled', 'disabled').end().prepend('<div class="' + this._disableClass + '" style="width: ' + e.outerWidth() + 'px; height: ' + e.outerHeight() + 'px; left: ' + (f.left - g.left) + 'px; top: ' + (f.top - g.top) + 'px;"></div>') } this._disabledFields = $.map(this._disabledFields, function(a) { return (a == b ? null : a) }); this._disabledFields[this._disabledFields.length] = b }, _isDisabledCalculator: function(a) { return (a && $.inArray(a, this._disabledFields) > -1) }, _changeCalculator: function(a, b, c) { var d = b || {}; if (typeof b == 'string') { d = {}; d[b] = c } var e = $.data(a, p); if (e) { if (this._curInst == e) { this._hideCalculator() } extendRemove(e.settings, d); if (e._inline) { this._setValue(e) } this._updateCalculator(e) } }, _showCalculator: function(b) { b = b.target || b; if ($.calculator._isDisabledCalculator(b) || $.calculator._lastInput == b) { return } var c = $.data(b, p); $.calculator._hideCalculator(null, ''); $.calculator._lastInput = b; $.calculator._pos = $.calculator._findPos(b); $.calculator._pos[1] += b.offsetHeight; var d = false; $(b).parents().each(function() { d |= $(this).css('position') == 'fixed'; return !d }); if (d && $.browser.opera) { $.calculator._pos[0] -= document.documentElement.scrollLeft; $.calculator._pos[1] -= document.documentElement.scrollTop } var e = { left: $.calculator._pos[0], top: $.calculator._pos[1] }; $.calculator._pos = null; c._mainDiv.css({ position: 'absolute', display: 'block', top: '-1000px', width: ($.browser.opera ? '1000px' : 'auto') }); $.calculator._reset(c, c._input.val(), true); $.calculator._updateCalculator(c); e = $.calculator._checkOffset(c, e, d); c._mainDiv.css({ position: (d ? 'fixed' : 'absolute'), display: 'none', left: e.left + 'px', top: e.top + 'px' }); var f = $.calculator._get(c, 'showAnim') || 'show'; var g = $.calculator._get(c, 'duration'); var h = function() { $.calculator._showingCalculator = true; var a = $.calculator._getBorders(c._mainDiv); c._mainDiv.find('iframe.' + $.calculator._coverClass).css({ left: -a[0], top: -a[1], width: c._mainDiv.outerWidth(), height: c._mainDiv.outerHeight() }) }; if ($.effects && $.effects[f]) { c._mainDiv.show(f, $.calculator._get(c, 'showOptions'), g, h) } else { c._mainDiv[f](g, h) } if (g == '') { h() } if (c._input[0].type != 'hidden') { c._input[0].focus() } $.calculator._curInst = c }, _reset: function(a, b, c) { var d = this._get(a, 'base'); var e = this._get(a, 'decimalChar'); b = '' + (b || 0); b = (e != '.' ? b.replace(new RegExp(e), '.') : b); a.curValue = (d == 10 ? parseFloat(b) : parseInt(b, d)) || 0; a.dispValue = this._setDisplay(a); a.prevValue = a._savedValue = 0; a.memory = (c ? 0 : a.memory); a._pendingOp = a._savedOp = this._noOp; a._newValue = true }, _setValue: function(a) { a.curValue = this._get(a, 'value') || 0; a.dispValue = this._setDisplay(a) }, _updateCalculator: function(a) { var b = this._getBorders(a._mainDiv); a._mainDiv.html(this._generateHTML(a)).find('iframe.' + this._coverClass).css({ left: -b[0], top: -b[1], width: a._mainDiv.outerWidth(), height: a._mainDiv.outerHeight() }); a._mainDiv.removeClass().addClass(this._get(a, 'calculatorClass') + ' ' + (this._get(a, 'isRTL') ? 'calculator-rtl ' : '') + (a._inline ? this._inlineClass : '')); if (this._curInst == a) { a._input.focus() } }, _getBorders: function(c) { var d = function(a) { var b = ($.browser.msie ? 1 : 0); return { thin: 1 + b, medium: 3 + b, thick: 5 + b}[a] || a }; return [parseFloat(d(c.css('border-left-width'))), parseFloat(d(c.css('border-top-width')))] }, _checkOffset: function(a, b, c) { var d = a._input ? this._findPos(a._input[0]) : null; var e = window.innerWidth || document.documentElement.clientWidth; var f = window.innerHeight || document.documentElement.clientHeight; var g = document.documentElement.scrollLeft || document.body.scrollLeft; var h = document.documentElement.scrollTop || document.body.scrollTop; if (($.browser.msie && parseInt($.browser.version, 10) < 7) || $.browser.opera) { var i = 0; $('.calculator-row', a._mainDiv).find('button:last').each(function() { i = Math.max(i, this.offsetLeft + this.offsetWidth + parseInt($(this).css('margin-right'), 10)) }); a._mainDiv.css('width', i) } if (this._get(a, 'isRTL') || (b.left + a._mainDiv.outerWidth() - g) > e) { b.left = Math.max((c ? 0 : g), d[0] + (a._input ? a._input.outerWidth() : 0) - (c ? g : 0) - a._mainDiv.outerWidth() - (c && $.browser.opera ? document.documentElement.scrollLeft : 0)) } else { b.left -= (c ? g : 0) } if ((b.top + a._mainDiv.outerHeight() - h) > f) { b.top = Math.max((c ? 0 : h), d[1] - (c ? h : 0) - a._mainDiv.outerHeight() - (c && $.browser.opera ? document.documentElement.scrollTop : 0)) } else { b.top -= (c ? h : 0) } return b }, _findPos: function(a) { while (a && (a.type == 'hidden' || a.nodeType != 1)) { a = a.nextSibling } var b = $(a).offset(); return [b.left, b.top] }, _hideCalculator: function(a, b) { var c = this._curInst; if (!c || (a && c != $.data(a, p))) { return } if (this._showingCalculator) { b = (b != null ? b : this._get(c, 'duration')); var d = this._get(c, 'showAnim'); if (b != '' && $.effects && $.effects[d]) { c._mainDiv.hide(d, this._get(c, 'showOptions'), b) } else { c._mainDiv[(b == '' ? 'hide' : (d == 'slideDown' ? 'slideUp' : (d == 'fadeIn' ? 'fadeOut' : 'hide')))](b) } } var e = this._get(c, 'onClose'); if (e) { e.apply((c._input ? c._input[0] : null), [(c._inline ? c.curValue : c._input.val()), c]) } if (this._showingCalculator) { this._showingCalculator = false; this._lastInput = null } this._curInst = null }, _checkExternalClick: function(a) { if (!$.calculator._curInst) { return } var b = $(a.target); if (!b.parents().andSelf().is('#' + $.calculator._mainDivId) && !b.hasClass($.calculator.markerClassName) && !b.parents().andSelf().hasClass($.calculator._triggerClass) && $.calculator._showingCalculator) { $.calculator._hideCalculator(null, '') } }, _focusEntry: function() { if ($.calculator._curInst && $.calculator._curInst._input) { $.calculator._curInst._input.focus() } }, _doKeyDown: function(e) { var a = false; var b = $.data(e.target, p); var c = (b && b._inline ? $(e.target).parent()[0] : null); if (e.keyCode == 9) { $.calculator.mainDiv.stop(true, true); $.calculator._hideCalculator(null, ''); if (b && b._inline) { b._input.blur() } } else if ($.calculator._showingCalculator || (c && !$.calculator._isDisabledCalculator(c))) { if (e.keyCode == 18) { if (!$.calculator._showingKeystrokes) { b._mainDiv.find('.' + $.calculator._keystrokeClass).show(); $.calculator._showingKeystrokes = true } a = true } else { var d = $.calculator._keyCodes[e.keyCode]; if (d) { $('button[keystroke=' + d + ']', b._mainDiv).not(':disabled').click(); a = true } } } else if (e.keyCode == 36 && e.ctrlKey && b && !b._inline) { $.calculator._showCalculator(this) } if (a) { e.preventDefault(); e.stopPropagation() } return !a }, _doKeyUp: function(e) { if ($.calculator._showingKeystrokes) { var a = $.data(e.target, p); a._mainDiv.find('.' + $.calculator._keystrokeClass).hide(); $.calculator._showingKeystrokes = false } }, _doKeyPress: function(e) { var a = $.data(e.target, p); if (!a) { return true } var b = (a && a._inline ? $(e.target).parent()[0] : null); var c = String.fromCharCode(e.charCode == undefined ? e.keyCode : e.charCode); var d = $.calculator._get(a, 'base'); var f = $.calculator._get(a, 'decimalChar'); var g = $.calculator._get(a, 'showOn'); var h = $.calculator._get(a, 'isOperator') || $.calculator._isOperator; if (!$.calculator._showingCalculator && !b && (g == 'operator' || g == 'opbutton') && h.apply(a._input, [c, e, a._input.val(), d, f])) { $.calculator._showCalculator(this); $.calculator._showingCalculator = true } if ($.calculator._showingCalculator || (b && !$.calculator._isDisabledCalculator(b))) { var i = $.calculator._keyChars[c == f ? '.' : c]; if (i) { $('button[keystroke=' + i + ']', a._mainDiv).not(':disabled').click() } return false } if (c >= ' ' && $.calculator._get(a, 'constrainInput')) { var j = new RegExp('^-?' + (d == 10 ? '[0-9]*(\\' + f + '[0-9]*)?' : '[' + '0123456789abcdef'.substring(0, d) + ']*') + '$'); return (a._input.val() + c).toLowerCase().match(j) != null } return true }, _isOperator: function(a, b, c, d, e) { return a > ' ' && !(a == '-' && c == '') && ('0123456789abcdef'.substr(0, d) + '.' + e).indexOf(a.toLowerCase()) == -1 }, _get: function(a, b) { return a.settings[b] !== undefined ? a.settings[b] : this._defaults[b] }, _generateHTML: function(a) { var b = this._get(a, 'isRTL'); var c = this._get(a, 'prompt'); var d = this._get(a, 'layout'); var e = this._get(a, 'base'); var f = this._get(a, 'useDegrees'); var g = (!c ? '' : '<div class="calculator-prompt">' + c + '</div>') + '<div class="calculator-result' + (a._focussed ? ' ' + this._focussedClass : '') + '"><span>' + a.dispValue + '</span></div>'; for (var i = 0; i < d.length; i++) { g += '<div class="calculator-row">'; for (var j = 0; j < d[i].length; j += 2) { var h = d[i].substr(j, 2); var l = this._keyDefs[h] || this._keyDefs['??']; var m = (l[0].charAt(0) == '#' ? this._get(a, l[0].substr(1) + 'Text') : l[0]); var n = (l[0].charAt(0) == '#' ? this._get(a, l[0].substr(1) + 'Status') : ''); var o = (l[3] ? l[3].split(' ') : []); for (var k = 0; k < o.length; k++) { o[k] = 'calculator-' + o[k] } o = o.join(' '); g += (l[1] == this.space ? '<span class="calculator-' + l[3] + '"></span>' : (a._inline && (l[2] == '._close' || l[2] == '._erase') ? '' : '<button type="button" keystroke="' + h + '"' + (l[1] == this.control ? ' class="calculator-ctrl' + (l[0].replace(/^#base/, '') == e ? ' calculator-base-active' : '') + (l[0] == '#degrees' && f ? ' calculator-angle-active' : '') + (l[0] == '#radians' && !f ? ' calculator-angle-active' : '') : (l[1] == this.digit ? (parseInt(l[0], 16) >= e || (e != 10 && l[0] == '.') ? ' disabled="disabled"' : '') + ' class="calculator-digit' : (l[1] == this.binary ? ' class="calculator-oper' : ' class="calculator-oper' + (l[0].match(/^#mem(Clear|Recall)$/) && !a.memory ? ' calculator-mem-empty' : '')))) + (o ? ' ' + o : '') + '" ' + (n ? 'title="' + n + '"' : '') + '>' + (h == '_.' ? this._get(a, 'decimalChar') : m) + (l[5] && l[5] != l[0] ? '<span class="' + this._keystrokeClass + (l[6] ? ' calculator-keyname' : '') + '">' + (l[6] || l[5]) + '</span>' : '') + '</button>')) } g += '</div>' } g += '<div style="clear: both;"></div>' + (!a._inline && $.browser.msie && parseInt($.browser.version, 10) < 7 ? '<iframe src="javascript:false;" class="' + this._coverClass + '"></iframe>' : ''); g = $(g); g.find('button').mousedown(function() { $(this).addClass('calculator-key-down') }).mouseup(function() { $(this).removeClass('calculator-key-down') }).mouseout(function() { $(this).removeClass('calculator-key-down') }).click(function() { $.calculator._handleButton(a, $(this)) }); return g }, _setDisplay: function(a) { var b = this._get(a, 'precision'); var c = new Number(a.curValue).toFixed(b).valueOf(); var d = c.replace(/^.+(e.+)$/, '$1').replace(/^[^e].*$/, ''); if (d) { c = new Number(c.replace(/e.+$/, '')).toFixed(b).valueOf() } return parseFloat(c.replace(/0+$/, '') + d).toString(this._get(a, 'base')).toUpperCase().replace(/\./, this._get(a, 'decimalChar')) }, _sendButton: function(a, b) { var c = this._get(a, 'onButton'); if (c) { c.apply((a._input ? a._input[0] : null), [b, a.dispValue, a]) } }, _handleButton: function(a, b) { var c = this._keyDefs[b.attr('keystroke')]; if (!c) { return } var d = b.text().substr(0, b.text().length - b.children('.calculator-keystroke').text().length); switch (c[1]) { case this.control: c[2].apply(this, [a, d]); break; case this.digit: this._digit(a, d); break; case this.binary: this._binaryOp(a, c[2], d); break; case this.unary: this._unaryOp(a, c[2], d); break } if ($.calculator._showingCalculator || a._inline) { a._input.focus() } }, _noOp: function(a) { }, _digit: function(a, b) { var c = this._get(a, 'decimalChar'); a.dispValue = (a._newValue ? '' : a.dispValue); if (b == c && a.dispValue.indexOf(b) > -1) { return } a.dispValue = (a.dispValue + b).replace(/^0(\d)/, '$1').replace(new RegExp('^(-?)([\\.' + c + '])'), '$10$2'); if (c != '.') { a.dispValue = a.dispValue.replace(new RegExp('^' + c), '0.') } var d = this._get(a, 'base'); var e = (c != '.' ? a.dispValue.replace(new RegExp(c), '.') : a.dispValue); a.curValue = (d == 10 ? parseFloat(e) : parseInt(e, d)); a._newValue = false; this._sendButton(a, b); this._updateCalculator(a) }, _binaryOp: function(a, b, c) { if (!a._newValue && a._pendingOp) { a._pendingOp(a); var d = this._get(a, 'base'); a.curValue = (d == 10 ? a.curValue : Math.floor(a.curValue)); a.dispValue = this._setDisplay(a) } a.prevValue = a.curValue; a._newValue = true; a._pendingOp = b; this._sendButton(a, c); this._updateCalculator(a) }, _add: function(a) { a.curValue = a.prevValue + a.curValue }, _subtract: function(a) { a.curValue = a.prevValue - a.curValue }, _multiply: function(a) { a.curValue = a.prevValue * a.curValue }, _divide: function(a) { a.curValue = a.prevValue / a.curValue }, _power: function(a) { a.curValue = Math.pow(a.prevValue, a.curValue) }, _unaryOp: function(a, b, c) { a._newValue = true; b.apply(this, [a]); var d = this._get(a, 'base'); a.curValue = (d == 10 ? a.curValue : Math.floor(a.curValue)); a.dispValue = this._setDisplay(a); this._sendButton(a, c); this._updateCalculator(a) }, _plusMinus: function(a) { a.curValue = -1 * a.curValue; a.dispValue = this._setDisplay(a); a._newValue = false }, _pi: function(a) { a.curValue = Math.PI }, _percent: function(a) { if (a._pendingOp == this._add) { a.curValue = a.prevValue * (1 + a.curValue / 100) } else if (a._pendingOp == this._subtract) { a.curValue = a.prevValue * (1 - a.curValue / 100) } else if (a._pendingOp == this._multiply) { a.curValue = a.prevValue * a.curValue / 100 } else if (a._pendingOp == this._divide) { a.curValue = a.prevValue / a.curValue * 100 } a._savedOp = a._pendingOp; a._pendingOp = this._noOp }, _equals: function(a) { if (a._pendingOp == this._noOp) { if (a._savedOp != this._noOp) { a.prevValue = a.curValue; a.curValue = a._savedValue; a._savedOp(a) } } else { a._savedOp = a._pendingOp; a._savedValue = a.curValue; a._pendingOp(a); a._pendingOp = this._noOp } }, _memAdd: function(a) { a.memory += a.curValue }, _memSubtract: function(a) { a.memory -= a.curValue }, _memStore: function(a) { a.memory = a.curValue }, _memRecall: function(a) { a.curValue = a.memory }, _memClear: function(a) { a.memory = 0 }, _sin: function(a) { this._trig(a, Math.sin) }, _cos: function(a) { this._trig(a, Math.cos) }, _tan: function(a) { this._trig(a, Math.tan) }, _trig: function(a, b) { var c = this._get(a, 'useDegrees'); a.curValue = b(a.curValue * (c ? Math.PI / 180 : 1)) }, _asin: function(a) { this._atrig(a, Math.asin) }, _acos: function(a) { this._atrig(a, Math.acos) }, _atan: function(a) { this._atrig(a, Math.atan) }, _atrig: function(a, b) { a.curValue = b(a.curValue); if (this._get(a, 'useDegrees')) { a.curValue = a.curValue / Math.PI * 180 } }, _inverse: function(a) { a.curValue = 1 / a.curValue }, _log: function(a) { a.curValue = Math.log(a.curValue) / Math.log(10) }, _ln: function(a) { a.curValue = Math.log(a.curValue) }, _exp: function(a) { a.curValue = Math.exp(a.curValue) }, _sqr: function(a) { a.curValue *= a.curValue }, _sqrt: function(a) { a.curValue = Math.sqrt(a.curValue) }, _random: function(a) { a.curValue = Math.random() }, _base2: function(a, b) { this._changeBase(a, b, 2) }, _base8: function(a, b) { this._changeBase(a, b, 8) }, _base10: function(a, b) { this._changeBase(a, b, 10) }, _base16: function(a, b) { this._changeBase(a, b, 16) }, _changeBase: function(a, b, c) { a.settings.base = c; a.curValue = (c == 10 ? a.curValue : Math.floor(a.curValue)); a.dispValue = this._setDisplay(a); a._newValue = true; this._sendButton(a, b); this._updateCalculator(a) }, _degrees: function(a, b) { this._degreesRadians(a, b, true) }, _radians: function(a, b) { this._degreesRadians(a, b, false) }, _degreesRadians: function(a, b, c) { a.settings.useDegrees = c; this._sendButton(a, b); this._updateCalculator(a) }, _undo: function(a, b) { a.dispValue = a.dispValue.substr(0, a.dispValue.length - 1) || '0'; var c = this._get(a, 'base'); a.curValue = (c == 10 ? parseFloat(a.dispValue) : parseInt(a.dispValue, c)); this._sendButton(a, b); this._updateCalculator(a) }, _clearError: function(a, b) { a.dispValue = '0'; a.curValue = 0; a._newValue = true; this._sendButton(a, b); this._updateCalculator(a) }, _clear: function(a, b) { this._reset(a, 0, false); this._sendButton(a, b); this._updateCalculator(a) }, _close: function(a, b) { this._finished(a, b, a._input.val()) }, _use: function(a, b) { if (a._pendingOp != this._noOp) { this._unaryOp(a, this._equals, b) } this._finished(a, b, a.dispValue) }, _erase: function(a, b) { this._reset(a, 0, false); this._updateCalculator(a); this._finished(a, b, '') }, _finished: function(a, b, c) { if (a._inline) { this._curInst = a } else { a._input.val(c) } this._sendButton(a, b); this._hideCalculator(a._input[0]) } }); function extendRemove(a, b) { $.extend(a, b); for (var c in b) { if (b[c] == null || b[c] == undefined) { a[c] = b[c] } } return a }; $.fn.calculator = function(a) { var b = Array.prototype.slice.call(arguments, 1); if (a == 'isDisabled') { return $.calculator['_' + a + 'Calculator'].apply($.calculator, [this[0]].concat(b)) } return this.each(function() { typeof a == 'string' ? $.calculator['_' + a + 'Calculator'].apply($.calculator, [this].concat(b)) : $.calculator._attachCalculator(this, a) }) }; $.calculator = new Calculator(); $(function() { $(document.body).append($.calculator.mainDiv).mousedown($.calculator._checkExternalClick) }) })(jQuery);

//calculator localization - TKG
(function($) { 

    $.calculator.regional['is'] = {
        decimalChar: ',',
        buttonText: MenigaLang.translate('CalcOpen'), buttonStatus: MenigaLang.translate('CalcOpenTooltip'),
        closeText: MenigaLang.translate('CalcClose'), closeStatus: MenigaLang.translate('CalcCloseTooltip'),
        useText: MenigaLang.translate('CalcUse'), useStatus: MenigaLang.translate('CalcUseTooltip'),
        eraseText: MenigaLang.translate('CalcErase'), eraseStatus: MenigaLang.translate('CalcEraseTooltip'),
        backspaceText: MenigaLang.translate('CalcBS'), backspaceStatus: MenigaLang.translate('CalcBSTooltip'),
        clearErrorText: MenigaLang.translate('CalcCE'), clearErrorStatus: MenigaLang.translate('CalcCETooltip'),
        clearText: MenigaLang.translate('CalcCS'), clearStatus: MenigaLang.translate('CalcCSTooltip'),
        isRTL: false
    };
    $.calculator.setDefaults($.calculator.regional['is']);

})(jQuery);


//Video lightbox

/* ------------------------------------------------------------------------
* Class: prettyPhoto
* Use: Lightbox clone for jQuery
* Author: Stephane Caron (http://www.no-margin-for-errors.com)
* Version: 3.0
* ------------------------------------------------------------------------- */

(function ($) {
    $.prettyPhoto = { version: '3.0' }; $.fn.prettyPhoto = function (pp_settings) {
        pp_settings = jQuery.extend({ animation_speed: 'fast', slideshow: false, autoplay_slideshow: false, opacity: 0.80, show_title: true, allow_resize: true, default_width: 640, default_height: 505, counter_separator_label: '/', theme: 'light_rounded', hideflash: false, wmode: 'opaque', autoplay: true, modal: false, overlay_gallery: true, keyboard_shortcuts: true, changepicturecallback: function () { }, callback: function () { }, markup: '<div class="pp_pic_holder"><div class="ppt">&nbsp;</div><div class="pp_top"><div class="pp_left"></div><div class="pp_middle"></div><div class="pp_right"></div></div><div class="pp_content_container"><div class="pp_left"><div class="pp_right"><div class="pp_content"><div class="pp_loaderIcon"></div><div class="pp_fade"><a href="#" class="pp_expand" title="Expand the image">Expand</a><div class="pp_hoverContainer"><a class="pp_next" href="#">next</a><a class="pp_previous" href="#">previous</a></div><div id="pp_full_res"></div><div class="pp_details clearfix"><p class="pp_description"></p><a class="pp_close" href="#">Close</a><div class="pp_nav"><a href="#" class="pp_arrow_previous">Previous</a><p class="currentTextHolder">0/0</p><a href="#" class="pp_arrow_next">Next</a></div></div></div></div></div></div></div><div class="pp_bottom"><div class="pp_left"></div><div class="pp_middle"></div><div class="pp_right"></div></div></div><div class="pp_overlay"></div>', gallery_markup: '<div class="pp_gallery"><a href="#" class="pp_arrow_previous">Previous</a><ul>{gallery}</ul><a href="#" class="pp_arrow_next">Next</a></div>', image_markup: '<img id="fullResImage" src="" />', flash_markup: '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="{width}" height="{height}"><param name="wmode" value="{wmode}" /><param name="allowfullscreen" value="true" /><param name="allowscriptaccess" value="always" /><param name="movie" value="{path}" /><embed src="{path}" type="application/x-shockwave-flash" allowfullscreen="true" allowscriptaccess="always" width="{width}" height="{height}" wmode="{wmode}"></embed></object>', quicktime_markup: '<object classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B" codebase="http://www.apple.com/qtactivex/qtplugin.cab" height="{height}" width="{width}"><param name="src" value="{path}"><param name="autoplay" value="{autoplay}"><param name="type" value="video/quicktime"><embed src="{path}" height="{height}" width="{width}" autoplay="{autoplay}" type="video/quicktime" pluginspage="http://www.apple.com/quicktime/download/"></embed></object>', iframe_markup: '<iframe src ="{path}" width="{width}" height="{height}" frameborder="no"></iframe>', inline_markup: '<div class="pp_inline clearfix">{content}</div>', custom_markup: '' }, pp_settings); var matchedObjects = this, percentBased = false, correctSizes, pp_open, pp_contentHeight, pp_contentWidth, pp_containerHeight, pp_containerWidth, windowHeight = $(window).height(), windowWidth = $(window).width(), pp_slideshow; doresize = true, scroll_pos = _get_scroll(); $(window).unbind('resize').resize(function () { _center_overlay(); _resize_overlay(); }); if (pp_settings.keyboard_shortcuts) {
            $(document).unbind('keydown').keydown(function (e) {
                if (typeof $pp_pic_holder != 'undefined') {
                    if ($pp_pic_holder.is(':visible')) {
                        switch (e.keyCode) {
                            case 37: $.prettyPhoto.changePage('previous'); break; case 39: $.prettyPhoto.changePage('next'); break; case 27: if (!settings.modal)
                                    $.prettyPhoto.close(); break;
                        }; return false;
                    };
                };
            });
        }
        $.prettyPhoto.initialize = function () {
            settings = pp_settings; if ($.browser.msie && parseInt($.browser.version) == 6) settings.theme = "light_square"; _buildOverlay(this); if (settings.allow_resize)
                $(window).scroll(function () { _center_overlay(); }); _center_overlay(); set_position = jQuery.inArray($(this).attr('href'), pp_images); $.prettyPhoto.open(); return false;
        }
        $.prettyPhoto.open = function () {
            if (typeof settings == "undefined") { settings = pp_settings; if ($.browser.msie && $.browser.version == 6) settings.theme = "light_square"; _buildOverlay(this); pp_images = $.makeArray(arguments[0]); pp_titles = (arguments[1]) ? $.makeArray(arguments[1]) : $.makeArray(""); pp_descriptions = (arguments[2]) ? $.makeArray(arguments[2]) : $.makeArray(""); isSet = (pp_images.length > 1) ? true : false; set_position = 0; }
            if ($.browser.msie && $.browser.version == 6) $('select').css('visibility', 'hidden'); if (settings.hideflash) $('object,embed').css('visibility', 'hidden'); _checkPosition($(pp_images).size()); $('.pp_loaderIcon').show(); if ($ppt.is(':hidden')) $ppt.css('opacity', 0).show(); $pp_overlay.show().fadeTo(settings.animation_speed, settings.opacity); $pp_pic_holder.find('.currentTextHolder').text((set_position + 1) + settings.counter_separator_label + $(pp_images).size()); $pp_pic_holder.find('.pp_description').show().html(unescape(pp_descriptions[set_position])); (settings.show_title && pp_titles[set_position] != "") ? $ppt.html(unescape(pp_titles[set_position])) : $ppt.html('&nbsp;'); movie_width = (parseFloat(grab_param('width', pp_images[set_position]))) ? grab_param('width', pp_images[set_position]) : settings.default_width.toString(); movie_height = (parseFloat(grab_param('height', pp_images[set_position]))) ? grab_param('height', pp_images[set_position]) : settings.default_height.toString(); if (movie_width.indexOf('%') != -1 || movie_height.indexOf('%') != -1) { movie_height = parseFloat(($(window).height() * parseFloat(movie_height) / 100) - 150); movie_width = parseFloat(($(window).width() * parseFloat(movie_width) / 100) - 150); percentBased = true; } else { percentBased = false; }
            $pp_pic_holder.fadeIn(function () { imgPreloader = ""; switch (_getFileType(pp_images[set_position])) { case 'image': imgPreloader = new Image(); nextImage = new Image(); if (isSet && set_position > $(pp_images).size()) nextImage.src = pp_images[set_position + 1]; prevImage = new Image(); if (isSet && pp_images[set_position - 1]) prevImage.src = pp_images[set_position - 1]; $pp_pic_holder.find('#pp_full_res')[0].innerHTML = settings.image_markup; $pp_pic_holder.find('#fullResImage').attr('src', pp_images[set_position]); imgPreloader.onload = function () { correctSizes = _fitToViewport(imgPreloader.width, imgPreloader.height); _showContent(); }; imgPreloader.onerror = function () { alert('Image cannot be loaded. Make sure the path is correct and image exist.'); $.prettyPhoto.close(); }; imgPreloader.src = pp_images[set_position]; break; case 'youtube': correctSizes = _fitToViewport(movie_width, movie_height); movie = 'http://www.youtube.com/v/' + grab_param('v', pp_images[set_position]); if (settings.autoplay) movie += "&autoplay=1"; toInject = settings.flash_markup.replace(/{width}/g, correctSizes['width']).replace(/{height}/g, correctSizes['height']).replace(/{wmode}/g, settings.wmode).replace(/{path}/g, movie); break; case 'vimeo': correctSizes = _fitToViewport(movie_width, movie_height); movie_id = pp_images[set_position]; var regExp = /http:\/\/(www\.)?vimeo.com\/(\d+)/; var match = movie_id.match(regExp); movie = 'http://player.vimeo.com/video/' + match[2] + '?title=0&amp;byline=0&amp;portrait=0'; if (settings.autoplay) movie += "&autoplay=1;"; vimeo_width = correctSizes['width'] + '/embed/?moog_width=' + correctSizes['width']; toInject = settings.iframe_markup.replace(/{width}/g, vimeo_width).replace(/{height}/g, correctSizes['height']).replace(/{path}/g, movie); break; case 'quicktime': correctSizes = _fitToViewport(movie_width, movie_height); correctSizes['height'] += 15; correctSizes['contentHeight'] += 15; correctSizes['containerHeight'] += 15; toInject = settings.quicktime_markup.replace(/{width}/g, correctSizes['width']).replace(/{height}/g, correctSizes['height']).replace(/{wmode}/g, settings.wmode).replace(/{path}/g, pp_images[set_position]).replace(/{autoplay}/g, settings.autoplay); break; case 'flash': correctSizes = _fitToViewport(movie_width, movie_height); flash_vars = pp_images[set_position]; flash_vars = flash_vars.substring(pp_images[set_position].indexOf('flashvars') + 10, pp_images[set_position].length); filename = pp_images[set_position]; filename = filename.substring(0, filename.indexOf('?')); toInject = settings.flash_markup.replace(/{width}/g, correctSizes['width']).replace(/{height}/g, correctSizes['height']).replace(/{wmode}/g, settings.wmode).replace(/{path}/g, filename + '?' + flash_vars); break; case 'iframe': correctSizes = _fitToViewport(movie_width, movie_height); frame_url = pp_images[set_position]; frame_url = frame_url.substr(0, frame_url.indexOf('iframe') - 1); toInject = settings.iframe_markup.replace(/{width}/g, correctSizes['width']).replace(/{height}/g, correctSizes['height']).replace(/{path}/g, frame_url); break; case 'custom': correctSizes = _fitToViewport(movie_width, movie_height); toInject = settings.custom_markup; break; case 'inline': myClone = $(pp_images[set_position]).clone().css({ 'width': settings.default_width }).wrapInner('<div id="pp_full_res"><div class="pp_inline clearfix"></div></div>').appendTo($('body')); correctSizes = _fitToViewport($(myClone).width(), $(myClone).height()); $(myClone).remove(); toInject = settings.inline_markup.replace(/{content}/g, $(pp_images[set_position]).html()); break; }; if (!imgPreloader) { $pp_pic_holder.find('#pp_full_res')[0].innerHTML = toInject; _showContent(); }; }); return false;
        }; $.prettyPhoto.changePage = function (direction) { currentGalleryPage = 0; if (direction == 'previous') { set_position--; if (set_position < 0) { set_position = 0; return; }; } else if (direction == 'next') { set_position++; if (set_position > $(pp_images).size() - 1) { set_position = 0; } } else { set_position = direction; }; if (!doresize) doresize = true; $('.pp_contract').removeClass('pp_contract').addClass('pp_expand'); _hideContent(function () { $.prettyPhoto.open(); }); }; $.prettyPhoto.changeGalleryPage = function (direction) { if (direction == 'next') { currentGalleryPage++; if (currentGalleryPage > totalPage) { currentGalleryPage = 0; }; } else if (direction == 'previous') { currentGalleryPage--; if (currentGalleryPage < 0) { currentGalleryPage = totalPage; }; } else { currentGalleryPage = direction; }; itemsToSlide = (currentGalleryPage == totalPage) ? pp_images.length - ((totalPage) * itemsPerPage) : itemsPerPage; $pp_pic_holder.find('.pp_gallery li').each(function (i) { $(this).animate({ 'left': (i * itemWidth) - ((itemsToSlide * itemWidth) * currentGalleryPage) }); }); }; $.prettyPhoto.startSlideshow = function () { if (typeof pp_slideshow == 'undefined') { $pp_pic_holder.find('.pp_play').unbind('click').removeClass('pp_play').addClass('pp_pause').click(function () { $.prettyPhoto.stopSlideshow(); return false; }); pp_slideshow = setInterval($.prettyPhoto.startSlideshow, settings.slideshow); } else { $.prettyPhoto.changePage('next'); }; }
        $.prettyPhoto.stopSlideshow = function () { $pp_pic_holder.find('.pp_pause').unbind('click').removeClass('pp_pause').addClass('pp_play').click(function () { $.prettyPhoto.startSlideshow(); return false; }); clearInterval(pp_slideshow); pp_slideshow = undefined; }
        $.prettyPhoto.close = function () { clearInterval(pp_slideshow); $pp_pic_holder.stop().find('object,embed').css('visibility', 'hidden'); $('div.pp_pic_holder,div.ppt,.pp_fade').fadeOut(settings.animation_speed, function () { $(this).remove(); }); $pp_overlay.fadeOut(settings.animation_speed, function () { if ($.browser.msie && $.browser.version == 6) $('select').css('visibility', 'visible'); if (settings.hideflash) $('object,embed').css('visibility', 'visible'); $(this).remove(); $(window).unbind('scroll'); settings.callback(); doresize = true; pp_open = false; delete settings; }); }; _showContent = function () {
            $('.pp_loaderIcon').hide(); $ppt.fadeTo(settings.animation_speed, 1); projectedTop = scroll_pos['scrollTop'] + ((windowHeight / 2) - (correctSizes['containerHeight'] / 2)); if (projectedTop < 0) projectedTop = 0; $pp_pic_holder.find('.pp_content').animate({ 'height': correctSizes['contentHeight'] }, settings.animation_speed); $pp_pic_holder.animate({ 'top': projectedTop, 'left': (windowWidth / 2) - (correctSizes['containerWidth'] / 2), 'width': correctSizes['containerWidth'] }, settings.animation_speed, function () {
                $pp_pic_holder.find('.pp_hoverContainer,#fullResImage').height(correctSizes['height']).width(correctSizes['width']); $pp_pic_holder.find('.pp_fade').fadeIn(settings.animation_speed); if (isSet && _getFileType(pp_images[set_position]) == "image") { $pp_pic_holder.find('.pp_hoverContainer').show(); } else { $pp_pic_holder.find('.pp_hoverContainer').hide(); }
                if (correctSizes['resized']) $('a.pp_expand,a.pp_contract').fadeIn(settings.animation_speed); if (settings.autoplay_slideshow && !pp_slideshow && !pp_open) $.prettyPhoto.startSlideshow(); settings.changepicturecallback(); pp_open = true;
            }); _insert_gallery();
        }; function _hideContent(callback) { $pp_pic_holder.find('#pp_full_res object,#pp_full_res embed').css('visibility', 'hidden'); $pp_pic_holder.find('.pp_fade').fadeOut(settings.animation_speed, function () { $('.pp_loaderIcon').show(); callback(); }); }; function _checkPosition(setCount) { if (set_position == setCount - 1) { $pp_pic_holder.find('a.pp_next').css('visibility', 'hidden'); $pp_pic_holder.find('a.pp_next').addClass('disabled').unbind('click'); } else { $pp_pic_holder.find('a.pp_next').css('visibility', 'visible'); $pp_pic_holder.find('a.pp_next.disabled').removeClass('disabled').bind('click', function () { $.prettyPhoto.changePage('next'); return false; }); }; if (set_position == 0) { $pp_pic_holder.find('a.pp_previous').css('visibility', 'hidden').addClass('disabled').unbind('click'); } else { $pp_pic_holder.find('a.pp_previous.disabled').css('visibility', 'visible').removeClass('disabled').bind('click', function () { $.prettyPhoto.changePage('previous'); return false; }); }; (setCount > 1) ? $('.pp_nav').show() : $('.pp_nav').hide(); }; function _fitToViewport(width, height) { resized = false; _getDimensions(width, height); imageWidth = width, imageHeight = height; if (((pp_containerWidth > windowWidth) || (pp_containerHeight > windowHeight)) && doresize && settings.allow_resize && !percentBased) { resized = true, fitting = false; while (!fitting) { if ((pp_containerWidth > windowWidth)) { imageWidth = (windowWidth - 200); imageHeight = (height / width) * imageWidth; } else if ((pp_containerHeight > windowHeight)) { imageHeight = (windowHeight - 200); imageWidth = (width / height) * imageHeight; } else { fitting = true; }; pp_containerHeight = imageHeight, pp_containerWidth = imageWidth; }; _getDimensions(imageWidth, imageHeight); }; return { width: Math.floor(imageWidth), height: Math.floor(imageHeight), containerHeight: Math.floor(pp_containerHeight), containerWidth: Math.floor(pp_containerWidth) + 40, contentHeight: Math.floor(pp_contentHeight), contentWidth: Math.floor(pp_contentWidth), resized: resized }; }; function _getDimensions(width, height) { width = parseFloat(width); height = parseFloat(height); $pp_details = $pp_pic_holder.find('.pp_details'); $pp_details.width(width); detailsHeight = parseFloat($pp_details.css('marginTop')) + parseFloat($pp_details.css('marginBottom')); $pp_details = $pp_details.clone().appendTo($('body')).css({ 'position': 'absolute', 'top': -10000 }); detailsHeight += $pp_details.height(); detailsHeight = (detailsHeight <= 34) ? 36 : detailsHeight; if ($.browser.msie && $.browser.version == 7) detailsHeight += 8; $pp_details.remove(); pp_contentHeight = height + detailsHeight; pp_contentWidth = width; pp_containerHeight = pp_contentHeight + $ppt.height() + $pp_pic_holder.find('.pp_top').height() + $pp_pic_holder.find('.pp_bottom').height(); pp_containerWidth = width; }
        function _getFileType(itemSrc) { if (itemSrc.match(/youtube\.com\/watch/i)) { return 'youtube'; } else if (itemSrc.match(/vimeo\.com/i)) { return 'vimeo'; } else if (itemSrc.indexOf('.mov') != -1) { return 'quicktime'; } else if (itemSrc.indexOf('.swf') != -1) { return 'flash'; } else if (itemSrc.indexOf('iframe') != -1) { return 'iframe'; } else if (itemSrc.indexOf('custom') != -1) { return 'custom'; } else if (itemSrc.substr(0, 1) == '#') { return 'inline'; } else { return 'image'; }; }; function _center_overlay() { if (doresize && typeof $pp_pic_holder != 'undefined') { scroll_pos = _get_scroll(); titleHeight = $ppt.height(), contentHeight = $pp_pic_holder.height(), contentwidth = $pp_pic_holder.width(); projectedTop = (windowHeight / 2) + scroll_pos['scrollTop'] - (contentHeight / 2); $pp_pic_holder.css({ 'top': projectedTop, 'left': (windowWidth / 2) + scroll_pos['scrollLeft'] - (contentwidth / 2) }); }; }; function _get_scroll() { if (self.pageYOffset) { return { scrollTop: self.pageYOffset, scrollLeft: self.pageXOffset }; } else if (document.documentElement && document.documentElement.scrollTop) { return { scrollTop: document.documentElement.scrollTop, scrollLeft: document.documentElement.scrollLeft }; } else if (document.body) { return { scrollTop: document.body.scrollTop, scrollLeft: document.body.scrollLeft }; }; }; function _resize_overlay() { windowHeight = $(window).height(), windowWidth = $(window).width(); if (typeof $pp_overlay != "undefined") $pp_overlay.height($(document).height()); }; function _insert_gallery() {
            if (isSet && settings.overlay_gallery && _getFileType(pp_images[set_position]) == "image") {
                itemWidth = 52 + 5; navWidth = (settings.theme == "facebook") ? 58 : 38; itemsPerPage = Math.floor((correctSizes['containerWidth'] - 100 - navWidth) / itemWidth); itemsPerPage = (itemsPerPage < pp_images.length) ? itemsPerPage : pp_images.length; totalPage = Math.ceil(pp_images.length / itemsPerPage) - 1; if (totalPage == 0) { navWidth = 0; $pp_pic_holder.find('.pp_gallery .pp_arrow_next,.pp_gallery .pp_arrow_previous').hide(); } else { $pp_pic_holder.find('.pp_gallery .pp_arrow_next,.pp_gallery .pp_arrow_previous').show(); }; galleryWidth = itemsPerPage * itemWidth + navWidth; $pp_pic_holder.find('.pp_gallery').width(galleryWidth).css('margin-left', -(galleryWidth / 2)); $pp_pic_holder.find('.pp_gallery ul').width(itemsPerPage * itemWidth).find('li.selected').removeClass('selected'); goToPage = (Math.floor(set_position / itemsPerPage) <= totalPage) ? Math.floor(set_position / itemsPerPage) : totalPage; if (itemsPerPage) { $pp_pic_holder.find('.pp_gallery').hide().show().removeClass('disabled'); } else { $pp_pic_holder.find('.pp_gallery').hide().addClass('disabled'); }
                $.prettyPhoto.changeGalleryPage(goToPage); $pp_pic_holder.find('.pp_gallery ul li:eq(' + set_position + ')').addClass('selected');
            } else { $pp_pic_holder.find('.pp_content').unbind('mouseenter mouseleave'); $pp_pic_holder.find('.pp_gallery').hide(); } 
        }
        function _buildOverlay(caller) {
            theRel = $(caller).attr('rel'); galleryRegExp = /\[(?:.*)\]/; isSet = (galleryRegExp.exec(theRel)) ? true : false; pp_images = (isSet) ? jQuery.map(matchedObjects, function (n, i) { if ($(n).attr('rel').indexOf(theRel) != -1) return $(n).attr('href'); }) : $.makeArray($(caller).attr('href')); pp_titles = (isSet) ? jQuery.map(matchedObjects, function (n, i) { if ($(n).attr('rel').indexOf(theRel) != -1) return ($(n).find('img').attr('alt')) ? $(n).find('img').attr('alt') : ""; }) : $.makeArray($(caller).find('img').attr('alt')); pp_descriptions = (isSet) ? jQuery.map(matchedObjects, function (n, i) { if ($(n).attr('rel').indexOf(theRel) != -1) return ($(n).attr('title')) ? $(n).attr('title') : ""; }) : $.makeArray($(caller).attr('title')); $('body').append(settings.markup); $pp_pic_holder = $('.pp_pic_holder'), $ppt = $('.ppt'), $pp_overlay = $('div.pp_overlay'); if (isSet && settings.overlay_gallery) {
                currentGalleryPage = 0; toInject = ""; for (var i = 0; i < pp_images.length; i++) {
                    var regex = new RegExp("(.*?)\.(jpg|jpeg|png|gif)$"); var results = regex.exec(pp_images[i]); if (!results) { classname = 'default'; } else { classname = ''; }
                    toInject += "<li class='" + classname + "'><a href='#'><img src='" + pp_images[i] + "' width='50' alt='' /></a></li>";
                }; toInject = settings.gallery_markup.replace(/{gallery}/g, toInject); $pp_pic_holder.find('#pp_full_res').after(toInject); $pp_pic_holder.find('.pp_gallery .pp_arrow_next').click(function () { $.prettyPhoto.changeGalleryPage('next'); $.prettyPhoto.stopSlideshow(); return false; }); $pp_pic_holder.find('.pp_gallery .pp_arrow_previous').click(function () { $.prettyPhoto.changeGalleryPage('previous'); $.prettyPhoto.stopSlideshow(); return false; }); $pp_pic_holder.find('.pp_content').hover(function () { $pp_pic_holder.find('.pp_gallery:not(.disabled)').fadeIn(); }, function () { $pp_pic_holder.find('.pp_gallery:not(.disabled)').fadeOut(); }); itemWidth = 52 + 5; $pp_pic_holder.find('.pp_gallery ul li').each(function (i) { $(this).css({ 'position': 'absolute', 'left': i * itemWidth }); $(this).find('a').unbind('click').click(function () { $.prettyPhoto.changePage(i); $.prettyPhoto.stopSlideshow(); return false; }); });
            }; if (settings.slideshow) {
                $pp_pic_holder.find('.pp_nav').prepend('<a href="#" class="pp_play">Play</a>')
                $pp_pic_holder.find('.pp_nav .pp_play').click(function () { $.prettyPhoto.startSlideshow(); return false; });
            }
            $pp_pic_holder.attr('class', 'pp_pic_holder ' + settings.theme); $pp_overlay.css({ 'opacity': 0, 'height': $(document).height(), 'width': $(document).width() }).bind('click', function () { if (!settings.modal) $.prettyPhoto.close(); }); $('a.pp_close').bind('click', function () { $.prettyPhoto.close(); return false; }); $('a.pp_expand').bind('click', function (e) { if ($(this).hasClass('pp_expand')) { $(this).removeClass('pp_expand').addClass('pp_contract'); doresize = false; } else { $(this).removeClass('pp_contract').addClass('pp_expand'); doresize = true; }; _hideContent(function () { $.prettyPhoto.open(); }); return false; }); $pp_pic_holder.find('.pp_previous, .pp_nav .pp_arrow_previous').bind('click', function () { $.prettyPhoto.changePage('previous'); $.prettyPhoto.stopSlideshow(); return false; }); $pp_pic_holder.find('.pp_next, .pp_nav .pp_arrow_next').bind('click', function () { $.prettyPhoto.changePage('next'); $.prettyPhoto.stopSlideshow(); return false; }); _center_overlay();
        }; return this.unbind('click').click($.prettyPhoto.initialize);
    }; function grab_param(name, url) { name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]"); var regexS = "[\\?&]" + name + "=([^&#]*)"; var regex = new RegExp(regexS); var results = regex.exec(url); return (results == null) ? "" : results[1]; } 
})(jQuery);
