﻿//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.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);


//liquid-canvas.js
(function ($) {
    var canvasElements = [];
    var pollCounter = 0;
    var plugins = {};

    function Area(canvas) {
        var stack = [];

        $.extend(this, {
            width: canvas.width, height: canvas.height, ctx: canvas.getContext("2d"),

            save: function () {
                this.ctx.save();
                stack.push({ width: this.width, height: this.height });
            },

            restore: function () {
                this.ctx.restore();
                $.extend(this, stack.pop());
            }
        });
    }

    var Plugin = (function () {
        var shrink = function (area, steps) {
            area.ctx.translate(steps, steps);
            area.width -= 2 * steps;
            area.height -= 2 * steps;
        };
        return {
            action: { paint: function () { } },  // provide a NOP "plugin"
            shrink: shrink,
            defaultShrink: shrink,
            setAction: function (action) { this.action = action; }
        };
    })();

    function newPlugin(hash, opts) {
        return $.extend({}, Plugin, hash, { opts: opts, savedOpts: opts });
    }

    function pluginFromPlugins(plugins) {
        return newPlugin({
            paint: function (area) {
                area.save();
                this.action.opts = $.extend(true, this.action.savedOpts);
                $.each(plugins, function () { this.paint(area); });
                area.restore();
            },

            setAction: function (action) {
                this.action = action; // should call super if it existed ...
                $.each(plugins, function () { this.action = action; });
            }
        });
    }
    var pluginFromApplications = pluginFromPlugins; // it just does the same ...

    function pluginFromName(name, opts) {
        var plugin = plugins[name];
        if (!plugin) throw "Unknown plugin: " + name;
        opts = $.extend({}, plugin.defaultOpts || {}, opts);
        return newPlugin(plugin, opts);
    }

    function parse(s) {
        s += " ";
        var index = 0;

        function err(m) { msg = m + " at " + index + ": ..." + s.substring(index) + "\nin " + s; alert(msg); throw msg; }
        function cur() { return s.charAt(index); }
        function next() { if (index > s.length) throw ("Unexpected end"); return s.charAt(index + 1) }
        function eat() { return s.charAt(index++); }
        function skipWhite() { while (/\s/.exec(cur())) eat(); }
        function check(c) {
            skipWhite();
            for (var i = 0; i < c.length; ++i) {
                if (cur() != c.charAt(i)) err("Expected '" + c.charAt(i) + "' found '" + cur() + "'");
                eat();
            }
        }

        //var parseApplications; // forward reference

        function parseWord() {
            skipWhite();
            for (var word = []; /\w/.exec(cur()); word.push(eat()));
            return word.join("");
        }

        function parseNumber() {
            skipWhite();
            for (var n = []; /\d/.exec(cur()); n.push(eat()));
            return parseInt(n.join(""));
        }

        function parseString() {
            skipWhite();
            var s = [], start = cur();
            if (/[^\'\"]/.exec(start)) { err("String expected") }
            eat();
            while (cur() != start) { if (cur() == "\\") s.eat(); s.push(eat()); }
            check(start);
            return s.join("");
        }

        // Yeah, strange thing - this does the CSS value like parsing
        function parseValue() {
            skipWhite();
            for (var s = []; /[^;}]/.exec(cur()); s.push(eat()));
            return s.join("");
        }

        function parseLiteral() {
            skipWhite();
            if (/\d/.exec(cur())) return parseNumber();
            if (/['"]/.exec(cur())) return parseString();
            return parseValue();
        }

        function parseOpts() {
            check("{");
            skipWhite();
            var opts = {};
            while (cur() != "}") {
                var key = parseWord();
                check(":");
                opts[key] = parseLiteral();
                skipWhite();
                if (cur() == "}") break;
                check(";");
            }
            check("}");
            return opts;
        }

        function parsePlugin() {
            var name = parseWord();
            skipWhite();
            opts = cur() == "{" ? parseOpts() : {};
            return pluginFromName(name, opts);
        }

        function parsePlugins() {
            check("[");
            skipWhite();
            var plugins = [];
            while (cur() != "]") {
                plugins.push(parsePlugin());
                skipWhite();
            }
            check("]");
            return pluginFromPlugins(plugins);
        }

        function parseActors() {
            skipWhite();
            return cur() == "[" ? parsePlugins() : parsePlugin();
        }

        function parseAction() {
            var action;
            skipWhite();
            if (cur() == "(") {
                eat();
                action = parseApplications();
                check(")");
            } else {
                action = parsePlugin();
            }
            return action;
        }

        function parseApplication() {
            var actors = parseActors();
            check("=>");
            var action = parseAction();
            actors.setAction(action);
            return actors;
        }

        function parseApplications() {
            var applications = [];
            while (true) {
                applications.push(parseApplication());
                skipWhite();
                if (cur() != ",") break;
                check(",");
            }
            return pluginFromApplications(applications);
        }

        return parseApplications();
    }

    function checkResize(container, force) {
        var $container = $(container);
        var data = $container.data('liquid-canvas');
        if (!data) return;
        var canvas = data.canvas;
        var $canvas = $(canvas);
        var w = $container.outerWidth();
        var h = $container.outerHeight();

        if (force ||
        canvas.width != w || canvas.height != h ||
        canvas.offsetTop != container.offsetTop || canvas.offsetLeft != container.offsetLeft) {
            pollCounter = 100;
            $canvas.css({ left: container.offsetLeft + "px", top: container.offsetTop + "px" });
            canvas.width = w;
            canvas.height = h;
            var area = new Area(canvas);
            area.save();
            data.paint(area);
            area.restore();
        }
    }

    function checkAllResize(force) {
        $.each(canvasElements, function () { checkResize(this, force); });
    }

    function poll() {
        checkAllResize();
        pollCounter--;
        if (pollCounter < 0) {
            pollCounter = 0;
            setTimeout(poll, 1000);
        } else {
            setTimeout(poll, 1000 / 60);
        }
    }

    jQuery.fn.extend({
        liquidCanvas: function (func) {
            this.each(function () {
                var canvas;
                if (window.G_vmlCanvasManager) {
                    $(this).before('<div width="0" height="0" style="position:absolute; top:0px; left:0px;"></div>');
                    canvas = G_vmlCanvasManager.initElement($(this).prev("div").get(0));
                } else {
                    $(this).before('<canvas width="0" height="0" style="position:absolute; top:0px; left:0px;"></canvas>');
                    canvas = $(this).prev("canvas").get(0);
                }

                var paint;
                if ($.isFunction(func)) {
                    paint = func;
                } else {
                    var plugin = parse(func)
                    paint = function (area) { plugin.paint(area); };
                }

                $(this).data("liquid-canvas", {
                    "canvas": canvas,
                    "paint": paint
                });
                $(this).css({ background: "transparent" });
                if ($(this).css("position") != "absolute") $(this).css({ position: "relative" });

                canvasElements.push(this);
                checkResize(this, true);
            });
        }
    });

    jQuery.extend({
        registerLiquidCanvasPlugin: function (plugin) {
            plugins[plugin.name] = $.extend({}, Plugin, plugin);
        }
    });

    $(document).ready(checkAllResize);
    poll();
})(jQuery);

//liquid-canvas-plugins.js
(function ($) {

    $.registerLiquidCanvasPlugin({
        name: "rect",
        paint: function (area) {
            area.ctx.beginPath();
            area.ctx.rect(0, 0, area.width, area.height);
            area.ctx.closePath();
            if (this.action) this.action.paint(area);  // for chaining
        }
    });

    $.registerLiquidCanvasPlugin({
        name: "roundedRect",
        defaultOpts: { radius: 20 },
        paint: function (area) {
            var ctx = area.ctx;
            var opts = this.opts;
            ctx.beginPath();
            ctx.moveTo(0, opts.radius);
            ctx.lineTo(0, area.height - opts.radius);
            ctx.quadraticCurveTo(0, area.height, opts.radius, area.height);
            ctx.lineTo(area.width - opts.radius, area.height);
            ctx.quadraticCurveTo(area.width, area.height, area.width, area.height - opts.radius);
            ctx.lineTo(area.width, opts.radius);
            ctx.quadraticCurveTo(area.width, 0, area.width - opts.radius, 0);
            ctx.lineTo(opts.radius, 0);
            ctx.quadraticCurveTo(0, 0, 0, opts.radius);
            ctx.closePath();
            if (this.action) this.action.paint(area);  // for chaining
        },
        shrink: function (area, steps) {
            this.defaultShrink(area, steps);
            this.opts.radius -= steps;
        }
    });

    // This is a Liquid Canvas Plugin
    $.registerLiquidCanvasPlugin({
        name: "fill",
        defaultOpts: { color: "#d2e8b3" },
        paint: function (area) {
            area.ctx.fillStyle = this.opts.color;
            this.action.paint(area);
            area.ctx.fill();
        }
    });

    $.registerLiquidCanvasPlugin({  // hmmmmmmm, no rotation? no width??? ah patterns!
        name: "image",
        defaultOpts: { url: "http://www.ruzee.com/files/liquid-canvas-image.png" },
        paint: function (area) {
            var image = new Image();
            image.src = this.opts.url;
            image.onload = function () {
                area.ctx.drawImage(this, 0, 0);
            };
        }
    });

    // This is a Liquid Canvas Plugin
    $.registerLiquidCanvasPlugin({
        name: "gradient",
        defaultOpts: { from: "#fff", to: "#666" },
        paint: function (area) {
            var grad = area.ctx.createLinearGradient(0, 0, 0, area.height);
            grad.addColorStop(0, this.opts.from);
            grad.addColorStop(1, this.opts.to);
            area.ctx.fillStyle = grad;
            this.action.paint(area);
            area.ctx.fill();
        }
    });
    // End of Liquid Canvas Plugin

    $.registerLiquidCanvasPlugin({
        name: "shadow",
        defaultOpts: { width: 3, color: '#000', shift: 1 },
        paint: function (area) {
            var sw = this.opts.width;

            area.ctx.fillStyle = this.opts.color;
            area.ctx.globalAlpha = 1.0 / sw;
            for (var s = 0; s < sw; ++s) {
                this.action.paint(area);
                area.ctx.fill();
                this.action.shrink(area, 1);
            }
            area.ctx.globalAlpha = 1;
            area.ctx.translate(0, -this.opts.shift);
        }
    });

    $.registerLiquidCanvasPlugin({
        name: "border",
        defaultOpts: { color: '#535353', width: 3 },
        paint: function (area) {
            var bw = this.opts.width;
            area.ctx.strokeStyle = this.opts.color;
            area.ctx.lineWidth = bw;
            this.action.shrink(area, bw / 2);
            this.action.paint(area);
            area.ctx.stroke();
            this.action.shrink(area, bw / 2);
        }
    });

})(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
var SWFUpload;

if (SWFUpload == undefined) {
    SWFUpload = function (settings) {
        this.initSWFUpload(settings);
    };
}

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.WINDOW);

    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);

//Video lightbox - modified by Tinna
/* ------------------------------------------------------------------------
* 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: 'facebook', 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);

