/* http://www.JSON.org/json2.js 2009-06-29 Public Domain. NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. See http://www.JSON.org/js.html This file creates a global JSON object containing two methods: stringify and parse. JSON.stringify(value, replacer, space) value any JavaScript value, usually an object or array. replacer an optional parameter that determines how object values are stringified for objects. It can be a function or an array of strings. space an optional parameter that specifies the indentation of nested structures. If it is omitted, the text will be packed without extra whitespace. If it is a number, it will specify the number of spaces to indent at each level. If it is a string (such as '\t' or ' '), it contains the characters used to indent at each level. This method produces a JSON text from a JavaScript value. When an object value is found, if the object contains a toJSON method, its toJSON method will be called and the result will be stringified. A toJSON method does not serialize: it returns the value represented by the name/value pair that should be serialized, or undefined if nothing should be serialized. The toJSON method will be passed the key associated with the value, and this will be bound to the object holding the key. For example, this would serialize Dates as ISO strings. Date.prototype.toJSON = function (key) { function f(n) { // Format integers to have at least two digits. return n < 10 ? '0' + n : n; } return this.getUTCFullYear() + '-' + f(this.getUTCMonth() + 1) + '-' + f(this.getUTCDate()) + 'T' + f(this.getUTCHours()) + ':' + f(this.getUTCMinutes()) + ':' + f(this.getUTCSeconds()) + 'Z'; }; You can provide an optional replacer method. It will be passed the key and value of each member, with this bound to the containing object. The value that is returned from your method will be serialized. If your method returns undefined, then the member will be excluded from the serialization. If the replacer parameter is an array of strings, then it will be used to select the members to be serialized. It filters the results such that only members with keys listed in the replacer array are stringified. Values that do not have JSON representations, such as undefined or functions, will not be serialized. Such values in objects will be dropped; in arrays they will be replaced with null. You can use a replacer function to replace those with JSON values. JSON.stringify(undefined) returns undefined. The optional space parameter produces a stringification of the value that is filled with line breaks and indentation to make it easier to read. If the space parameter is a non-empty string, then that string will be used for indentation. If the space parameter is a number, then the indentation will be that many spaces. Example: text = JSON.stringify(['e', {pluribus: 'unum'}]); // text is '["e",{"pluribus":"unum"}]' text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t'); // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]' text = JSON.stringify([new Date()], function (key, value) { return this[key] instanceof Date ? 'Date(' + this[key] + ')' : value; }); // text is '["Date(---current time---)"]' JSON.parse(text, reviver) This method parses a JSON text to produce an object or array. It can throw a SyntaxError exception. The optional reviver parameter is a function that can filter and transform the results. It receives each of the keys and values, and its return value is used instead of the original value. If it returns what it received, then the structure is not modified. If it returns undefined then the member is deleted. Example: // Parse the text. Values that look like ISO date strings will // be converted to Date objects. myData = JSON.parse(text, function (key, value) { var a; if (typeof value === 'string') { a = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value); if (a) { return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], +a[5], +a[6])); } } return value; }); myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) { var d; if (typeof value === 'string' && value.slice(0, 5) === 'Date(' && value.slice(-1) === ')') { d = new Date(value.slice(5, -1)); if (d) { return d; } } return value; }); This is a reference implementation. You are free to copy, modify, or redistribute. This code should be minified before deployment. See http://javascript.crockford.com/jsmin.html USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO NOT CONTROL. */ /*jslint evil: true */ /*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply, call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours, getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join, lastIndex, length, parse, prototype, push, replace, slice, stringify, test, toJSON, toString, valueOf */ // Create a JSON object only if one does not already exist. We create the // methods in a closure to avoid creating global variables. var JSON = JSON || {}; (function () { function f(n) { // Format integers to have at least two digits. return n < 10 ? '0' + n : n; } if (typeof Date.prototype.toJSON !== 'function') { Date.prototype.toJSON = function (key) { return isFinite(this.valueOf()) ? this.getUTCFullYear() + '-' + f(this.getUTCMonth() + 1) + '-' + f(this.getUTCDate()) + 'T' + f(this.getUTCHours()) + ':' + f(this.getUTCMinutes()) + ':' + f(this.getUTCSeconds()) + 'Z' : null; }; String.prototype.toJSON = Number.prototype.toJSON = Boolean.prototype.toJSON = function (key) { return this.valueOf(); }; } var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, gap, indent, meta = { // table of character substitutions '\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"' : '\\"', '\\': '\\\\' }, rep; function quote(string) { // If the string contains no control characters, no quote characters, and no // backslash characters, then we can safely slap some quotes around it. // Otherwise we must also replace the offending characters with safe escape // sequences. escapable.lastIndex = 0; return escapable.test(string) ? '"' + string.replace(escapable, function (a) { var c = meta[a]; return typeof c === 'string' ? c : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }) + '"' : '"' + string + '"'; } function str(key, holder) { // Produce a string from holder[key]. var i, // The loop counter. k, // The member key. v, // The member value. length, mind = gap, partial, value = holder[key]; // If the value has a toJSON method, call it to obtain a replacement value. if (value && typeof value === 'object' && typeof value.toJSON === 'function') { value = value.toJSON(key); } // If we were called with a replacer function, then call the replacer to // obtain a replacement value. if (typeof rep === 'function') { value = rep.call(holder, key, value); } // What happens next depends on the value's type. switch (typeof value) { case 'string': return quote(value); case 'number': // JSON numbers must be finite. Encode non-finite numbers as null. return isFinite(value) ? String(value) : 'null'; case 'boolean': case 'null': // If the value is a boolean or null, convert it to a string. Note: // typeof null does not produce 'null'. The case is included here in // the remote chance that this gets fixed someday. return String(value); // If the type is 'object', we might be dealing with an object or an array or // null. case 'object': // Due to a specification blunder in ECMAScript, typeof null is 'object', // so watch out for that case. if (!value) { return 'null'; } // Make an array to hold the partial results of stringifying this object value. gap += indent; partial = []; // Is the value an array? if (Object.prototype.toString.apply(value) === '[object Array]') { // The value is an array. Stringify every element. Use null as a placeholder // for non-JSON values. length = value.length; for (i = 0; i < length; i += 1) { partial[i] = str(i, value) || 'null'; } // Join all of the elements together, separated with commas, and wrap them in // brackets. v = partial.length === 0 ? '[]' : gap ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' : '[' + partial.join(',') + ']'; gap = mind; return v; } // If the replacer is an array, use it to select the members to be stringified. if (rep && typeof rep === 'object') { length = rep.length; for (i = 0; i < length; i += 1) { k = rep[i]; if (typeof k === 'string') { v = str(k, value); if (v) { partial.push(quote(k) + (gap ? ': ' : ':') + v); } } } } else { // Otherwise, iterate through all of the keys in the object. for (k in value) { if (Object.hasOwnProperty.call(value, k)) { v = str(k, value); if (v) { partial.push(quote(k) + (gap ? ': ' : ':') + v); } } } } // Join all of the member texts together, separated with commas, // and wrap them in braces. v = partial.length === 0 ? '{}' : gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' : '{' + partial.join(',') + '}'; gap = mind; return v; } } // If the JSON object does not yet have a stringify method, give it one. if (typeof JSON.stringify !== 'function') { JSON.stringify = function (value, replacer, space) { // The stringify method takes a value and an optional replacer, and an optional // space parameter, and returns a JSON text. The replacer can be a function // that can replace values, or an array of strings that will select the keys. // A default replacer method can be provided. Use of the space parameter can // produce text that is more easily readable. var i; gap = ''; indent = ''; // If the space parameter is a number, make an indent string containing that // many spaces. if (typeof space === 'number') { for (i = 0; i < space; i += 1) { indent += ' '; } // If the space parameter is a string, it will be used as the indent string. } else if (typeof space === 'string') { indent = space; } // If there is a replacer, it must be a function or an array. // Otherwise, throw an error. rep = replacer; if (replacer && typeof replacer !== 'function' && (typeof replacer !== 'object' || typeof replacer.length !== 'number')) { throw new Error('JSON.stringify'); } // Make a fake root object containing our value under the key of ''. // Return the result of stringifying the value. return str('', {'': value}); }; } // If the JSON object does not yet have a parse method, give it one. if (typeof JSON.parse !== 'function') { JSON.parse = function (text, reviver) { // The parse method takes a text and an optional reviver function, and returns // a JavaScript value if the text is a valid JSON text. var j; function walk(holder, key) { // The walk method is used to recursively walk the resulting structure so // that modifications can be made. var k, v, value = holder[key]; if (value && typeof value === 'object') { for (k in value) { if (Object.hasOwnProperty.call(value, k)) { v = walk(value, k); if (v !== undefined) { value[k] = v; } else { delete value[k]; } } } } return reviver.call(holder, key, value); } // Parsing happens in four stages. In the first stage, we replace certain // Unicode characters with escape sequences. JavaScript handles many characters // incorrectly, either silently deleting them, or treating them as line endings. cx.lastIndex = 0; if (cx.test(text)) { text = text.replace(cx, function (a) { return '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }); } // In the second stage, we run the text against regular expressions that look // for non-JSON patterns. We are especially concerned with '()' and 'new' // because they can cause invocation, and '=' because it can cause mutation. // But just to be safe, we want to reject all unexpected forms. // We split the second stage into 4 regexp operations in order to work around // crippling inefficiencies in IE's and Safari's regexp engines. First we // replace the JSON backslash pairs with '@' (a non-JSON character). Second, we // replace all simple value tokens with ']' characters. Third, we delete all // open brackets that follow a colon or comma or that begin the text. Finally, // we look to see that the remaining characters are only whitespace or ']' or // ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval. if (/^[\],:{}\s]*$/. test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@'). replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']'). replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) { // In the third stage we use the eval function to compile the text into a // JavaScript structure. The '{' operator is subject to a syntactic ambiguity // in JavaScript: it can begin a block or an object literal. We wrap the text // in parens to eliminate the ambiguity. j = eval('(' + text + ')'); // In the optional fourth stage, we recursively walk the new structure, passing // each name/value pair to a reviver function for possible transformation. return typeof reviver === 'function' ? walk({'': j}, '') : j; } // If the text is not JSON parseable, then a SyntaxError is thrown. throw new SyntaxError('JSON.parse'); }; } }()); // Default value for session support var saveToSessionEnabled = true; function getInternetExplorerVersion() { if(navigator.appName == 'Microsoft Internet Explorer') { var rv = navigator.userAgent; var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})"); if(re.exec(rv) != null) rv = parseFloat( RegExp.$1 ); return rv } return false; } function advEncode(str) { str = escape(str); str = str.replace(/[*+\/@\"]|%20/g, function (s) { switch (s) { case "*" : s = "%2A"; break; case "+" : s = "%2B"; break; case "/" : s = "%2F"; break; case "@" : s = "%40"; break; case "%20": s = "+"; break; } return s; }); return str; } function advDecode(str) { str = unescape(str); str = str.replace(/%2A|%2B|%2F|%40|%22|[+]/g, function (s) { switch (s) { case "%2A": s = "*"; break; case "%2B": s = "+"; break; case "%2F": s = "/"; break; case "%40": s = "@"; break; case "+" : s = "%20"; break; } return s; }); str = unescape(str); return str; } function checkBrowser() { Modernizr.on('flash', function( result ) { if (result) { // the browser has flash } else { //jQuery("#noflashdiv").show(); } }); // Debug resizeText(); } // Preloads given image jQuery.preloadImages = function() { for(var i = 0; i").attr("src", arguments[i]); } }; function requestImage(url, layer, resize) { request = url.replace('image-resize', 'image-request'); jQuery.ajax({ url: request, cache: false, success: function(data) { data = data.split(':'); if(data[0] != 'OK') { if(confirm("Could not render due to server load. Would you like to try again?")) { updateImage(layer, url); } else deleteLayer(layer); return false; } url = data[1]; var image = new Image(); image.onload = function() { jQuery("#uploaded-image-" + layer + " img:first").css("margin", "0px 0px"); jQuery("#uploaded-image-" + layer + " img:first").attr("src", url); var w = image.width; var h = image.height; if (resize) { jQuery("#uploaded-image-" + layer).width(w); jQuery("#uploaded-image-" + layer).height(h); } }; image.src = url; } }); } //Updating image on layer function updateImage(layer, url) { var hidden = (imageList[layer][8] == 'display: none;'); if(hidden) return false; jQuery("#uploaded-image-" + layer + " img:first").css("margin", "10px 10px"); jQuery("#uploaded-image-" + layer + " img:first").attr("src", "i/ajax-loader.gif"); //window.alert(imageList[layer][0]+","+imageList[layer][1]+","+imageList[layer][2]); if (imageList[layer][1]==2) { var resize = false; } else { var resize = true; } requestImage(url, layer, resize); } function preloadBackground(url) { jQuery("#workplace").hide(); jQuery("#preloader-background").html(''); jQuery("#preloader-background").show(); var image = new Image(); image.onload = function() { jQuery("#workspace").css("background", "url(" + url + ") no-repeat"); jQuery("#preloader-background").hide(); jQuery("#preloader-background").html(''); jQuery("#workplace").show(); }; image.src = url; } var $template; // Updates chosen template function creatorChangeTemplate(template) { $template = template; if($template != '') { jQuery("#workplace").css( "height", templateDims[$template][1]+20+"px" ); jQuery("#preloader-background").css( "height", templateDims[$template][1]+20+"px" ); jQuery("#workspace").css( "width", templateDims[$template][0]+"px" ); jQuery("#workspace").css( "height", templateDims[$template][1]+"px" ); preloadBackground("/background/"+$template+"/true/"); } }; var $background = "FFFFFF"; // Updates chosen background function creatorChangeBackground(background, reload) { $background = background; if(typeof(reload) == "undefined") preloadBackground("/background/" + $template + "/" + $background + "/"); jQuery("#selected-color").val("#" + $background); jQuery("#selected-color-view").css('background', "#" + $background); }; function creatorChangeForeground( color, reload ) { if( typeof( reload ) == "undefined" ) { jQuery("#fgreload").css("background","url(/foreground/"+color+"/) no-repeat"); } jQuery("#fg_col_code").val('#'+color); //jQuery("div.fg_colors").hide(); jQuery("#fg_col_code").css('background-color', '#'+color); jQuery("#usercolour").css( 'background-color', '#'+color); jQuery("#usercolour").attr( 'setting', color); }; function creatorChangeForegroundFromInput(reload ) { var fg_color = jQuery("#fg_col_code").val(); if( typeof( reload ) == "undefined" ) { jQuery("#fgreload").css("background","url(/foreground/"+fg_color+"/) no-repeat"); } jQuery("div.fg_colors").hide(); jQuery("#fg_col_code").css('background-color', fg_color); jQuery("#usercolour").css( 'background-color', fg_color); jQuery("#usercolour").attr( 'setting', fg_color.substring(1,7)); }; var imageList = new Array(); // Adds image to image list function addImageToList(imageName, static, width, height, folderName, brightness, imgNum, offsets, elementName, cssOptions, alpha, extra, rotation) { rotation = typeof(rotation) != 'undefined' ? parseInt(rotation) : 0; rotation = rotation % 360; if(rotation < 0) rotation = rotation + 360; alpha = typeof(alpha) != 'undefined' ? parseInt(alpha) : 100; if(alpha < 5) alpha = 5; if(alpha > 100) alpha = 100; if(imageList.length == 0) { //jQuery("#image-list-cont").show(); jQuery(".slidebox").show(); jQuery(".divAlign").show(); jQuery(".tip").show(); jQuery(".tip2").hide(); } toggleWorkspace(); // element id var imgNum = imageList.length; if( imgNum >= 150 ) { alert('You can add up to 150 elements per project.'); return; } if(typeof(extra) == "undefined") { extra = {"width" : width, "height" : height }; while(width > 300) { width = parseInt(width / 2); height = parseInt(height / 2); } } /*if(width > Math.ceil(extra.width/3)) { width = Math.ceil(extra.width/3); height = Math.ceil(extra.height/3); }*/ imageList[imgNum] = [ imageName, static, width, height, brightness, imgNum, offsets ]; imageList[imgNum][8] = cssOptions; imageList[imgNum][9] = folderName; imageList[imgNum][10] = alpha; imageList[imgNum][11] = extra; imageList[imgNum][12] = rotation; if(typeof(elementName) != "undefined" && elementName != null) { imageList[imgNum][7] = advEncode(elementName); } else { // layer type switch( static ) { case '0': imageList[imgNum][7] = 'Upload layer #'+imageList.length; break; case '2': imageList[imgNum][7] = 'Text layer #'+imageList.length; break; case '1': imageList[imgNum][7] = 'Clipart layer #'+imageList.length; break; } } addToWorkspace( imgNum ); jQuery("#image-list").prepend( '
  • '+advDecode(imageList[imgNum][7])+'
  • '); loadBrightness(imgNum); selectLayerOn('img_'+imgNum); if(static == 2) { $("#uploaded-image-" + imgNum).dblclick(function() { editText(imgNum); }); var pos = $("#workspace").offset(); jQuery("#uploaded-image-" + imgNum).attr("title", "Double click to edit this text."); setTooltip("#uploaded-image-" + imgNum, "Double click to edit this text.", pos.left + 550, pos.top - 30, true); } updateLayers(); saveToSession(); return imgNum; }; function checkLayerDPI(imgNum, info) { var imageName = jQuery("#uploaded-image-"+imgNum).attr("title"); var w = imageList[imgNum][11].width; var h = imageList[imgNum][11].height; var nw = jQuery("#uploaded-image-"+imgNum).width(); var nh = jQuery("#uploaded-image-"+imgNum).height(); if(nw > Math.ceil(w/3)) { var force = info; if(info) force = !confirm("Sizing the image to this size may result in quality loss. Are you sure you wish to enlarge to this size? Selecting Cancel will enlarge the image to the maximum recommended size."); if(!force) { imageList[imgNum][2] = nw; imageList[imgNum][3] = nh; link = returnImageLink(imgNum); updateImage(imgNum, link); saveToSession(); return false; } nw = Math.ceil(w/3); nh = Math.ceil(h/3); } imageList[imgNum][2] = nw; imageList[imgNum][3] = nh; jQuery("#uploaded-image-"+imgNum).width(nw); jQuery("#uploaded-image-"+imgNum).height(nh); link = returnImageLink(imgNum); updateImage(imgNum, link); saveToSession(); } function setResizable(imgNum, info) { jQuery("#uploaded-image-"+imgNum).resizable({ aspectRatio: true, start: function(event, ui) { ui.position.left = imageList[imgNum][6].left; ui.position.top = imageList[imgNum][6].top; }, resize: function(event, ui) { ui.position.left = imageList[imgNum][6].left; ui.position.top = imageList[imgNum][6].top; jQuery("#uploaded-image-" + imgNum + " img:first").css("margin", "10px 10px"); jQuery("#uploaded-image-" + imgNum + " img:first").attr("src", "i/ajax-loader.gif"); }, stop: function(event, ui) { checkLayerDPI(imgNum, info); saveAfterResize(event, ui); } }); } // Add element to workspace function addToWorkspace( imgNum ) { link = returnImageLink( imgNum ); var imageName = imageList[imgNum][0]; if(imageList[imgNum][1] != 1) { var width = imageList[imgNum][11]['width']; var height = imageList[imgNum][11]['height']; } else { var width = imageList[imgNum][2]; var height = imageList[imgNum][3]; } jQuery("#workspace").append( '
    '); updateImage(imgNum, link); if( imageList[imgNum][8] == 'display: none;' ) return; if(imageList[imgNum][1] != 2) { setResizable(imgNum, false); } jQuery("#uploaded-image-"+imgNum).draggable({ //containment: '#workspace', stop: function(event, ui) { imageList[imgNum][6] = ui.position; // top, left saveToSession(); } }); setImageOffsets( imgNum ); saveToSession(); }; // Format image link (for manipiulation) function returnImageLink( imgNum ) { var imageName = imageList[imgNum][0]; var static = imageList[imgNum][1]; var width = imageList[imgNum][2]; var height = imageList[imgNum][3]; var brightness = imageList[imgNum][4]; var folder = imageList[imgNum][9]; var alpha = imageList[imgNum][10]; var rotation = imageList[imgNum][12]; var result = '/ajax/image-resize/'+imageName+'/folder='+folder+';w='+width+';h='+height+';b='+brightness+';a='+alpha+';r='+rotation+';static='+static+'.img'; return result; }; // Sets image offsets function setImageOffsets( imgNum ) { if( imageList[imgNum][6] != null ) { offsets = imageList[imgNum][6]; jQuery("#uploaded-image-"+imgNum).css("top", offsets.top+"px"); jQuery("#uploaded-image-"+imgNum).css("left", offsets.left+"px"); } else { offset = imgNum*15; jQuery("#uploaded-image-"+imgNum).css("top", offset+"px"); jQuery("#uploaded-image-"+imgNum).css("left", offset+"px"); imageList[imgNum][6] = { "top":offset, "left":offset } } if(imageList[imgNum][1] != 2) { setResizable(imgNum, false); } }; // Updates layers function updateLayers() { //jQuery(".tip").slideUp(); var list = jQuery("#image-list li"); var counter = 0; var maxNum = imageList.length-1; jQuery.each( list, function(i, val) { var imgNum = jQuery(val).attr('alt'); if( imgNum != null ) { jQuery("#uploaded-image-"+imgNum).css( "z-index", maxNum-counter ); imageList[imgNum][5] = maxNum-counter; counter++; } }); saveToSession(); }; // Highlights layer on the list function highlightLayer(imgId) { $("#image-list li").removeClass('over'); $("#"+imgId).addClass('over'); }; function unhighlight(imgId) { $('#'+imgId).removeClass('over'); //$("#image-list li:last").addClass('ac'); }; // Selects layer on the list function selectLayer(it) { $("#image-list li").removeClass('ac'); $(it).addClass('ac'); loadBrightness($(it).attr("alt")); }; function selectLayerOn(imgId) { $("#image-list li").removeClass('ac'); $("#"+imgId).addClass('ac'); }; // Brightness selection function selectBrightness( val ) { //$('#brightness a').removeClass('ac'); //$(it).addClass("ac"); val = parseInt(val); if(!(val >= -6 && val <= 6)) return; var selectedLayer = $('#image-list li.ac').attr("alt"); //imageList[selectedLayer][4] = $(it).attr("alt"); imageList[selectedLayer][4] = val; // update image link link = returnImageLink(selectedLayer); updateImage(selectedLayer, link); saveToSession(); return false; }; //Align left function alignLeft() { var pos = 0; var selectedLayer = $('#image-list li.ac').attr("alt"); jQuery("#uploaded-image-"+selectedLayer).css("left", pos+"px"); imageList[selectedLayer][6]['left'] = pos; link = returnImageLink(selectedLayer); updateImage(selectedLayer, link); saveToSession(); return false; } //Align centre function alignCentre() { var selectedLayer = $('#image-list li.ac').attr("alt"); var width = imageList[selectedLayer][2]; var canvasWidth = templateDims[$template][0]; var pos = Math.round((canvasWidth-width)/2); jQuery("#uploaded-image-"+selectedLayer).css("left", pos+"px"); imageList[selectedLayer][6]['left'] = pos; link = returnImageLink(selectedLayer); updateImage(selectedLayer, link); saveToSession(); return false; } //Align right function alignRight() { var selectedLayer = $('#image-list li.ac').attr("alt"); var width = imageList[selectedLayer][2]; var canvasWidth = templateDims[$template][0]; var pos = canvasWidth-width; jQuery("#uploaded-image-"+selectedLayer).css("left", pos+"px"); imageList[selectedLayer][6]['left'] = pos; link = returnImageLink(selectedLayer); updateImage(selectedLayer, link); saveToSession(); return false; } //Align top function alignTop() { var pos = 0; var selectedLayer = $('#image-list li.ac').attr("alt"); jQuery("#uploaded-image-"+selectedLayer).css("top", pos+"px"); imageList[selectedLayer][6]['top'] = pos; link = returnImageLink(selectedLayer); updateImage(selectedLayer, link); saveToSession(); return false; } //Align middle function alignMiddle() { var selectedLayer = $('#image-list li.ac').attr("alt"); var height = imageList[selectedLayer][3]; var canvasHeight = templateDims[$template][1]; var pos = Math.round((canvasHeight-height)/2); jQuery("#uploaded-image-"+selectedLayer).css("top", pos+"px"); imageList[selectedLayer][6]['top'] = pos; link = returnImageLink(selectedLayer); updateImage(selectedLayer, link); saveToSession(); return false; } //Align middle function alignBottom() { var selectedLayer = $('#image-list li.ac').attr("alt"); var height = imageList[selectedLayer][3]; var canvasHeight = templateDims[$template][1]; var pos = canvasHeight-height; jQuery("#uploaded-image-"+selectedLayer).css("top", pos+"px"); imageList[selectedLayer][6]['top'] = pos; link = returnImageLink(selectedLayer); updateImage(selectedLayer, link); saveToSession(); return false; } //Alpha selection function selectAlpha(val) { var selectedLayer = $('#image-list li.ac').attr("alt"); imageList[selectedLayer][10] = val; link = returnImageLink(selectedLayer); updateImage(selectedLayer, link); saveToSession(); return false; }; function selectRotation(val) { var selectedLayer = $('#image-list li.ac').attr("alt"); var rotation = val % 360; if(rotation < 0) rotation = rotation + 360; //Resize image to base size var w = Math.ceil(imageList[selectedLayer][11].width/3); var h = Math.ceil(imageList[selectedLayer][11].height/3); var tmp = w; if(rotation % 180 == 90) tmp = h; if(rotation % 180 == 45) tmp = Math.ceil((w + h)/2); if(rotation % 180 == 135) tmp = Math.ceil((w + h)/2); imageList[selectedLayer][2] = tmp; imageList[selectedLayer][12] = rotation; var link = returnImageLink(selectedLayer); updateImage(selectedLayer, link); saveToSession(); return false; } // Loads selected brightness function loadBrightness(imgId) { //window.alert('loadBrightness('+imgId+')'); var selectedBr = imageList[imgId][4]; var selectedAlpha = imageList[imgId][10]; var selectedRotation = imageList[imgId][12]; if(selectedRotation > 180) selectedRotation -= 360; $('#slider').slider('value', selectedBr); $('#alpha-slider').slider('value', selectedAlpha); $('#rotation-slider').slider('value', selectedRotation); //$('#brightness a').removeClass('ac'); //$('#br_'+selectedBr).addClass("ac"); }; // Saves workspace to php session function saveToSession() { if(!saveToSessionEnabled ) return; var postdata = JSON.stringify(imageList); jQuery.ajax({ type: 'post', cache: false, url: '/save/', data: 'postdata='+postdata, success: function(msg) { //alert(postdata + "\n" + msg); //Debug } }); }; // Loads workspace from session function loadSavedWorkspace() { jQuery.ajax({ type: 'get', dataType: 'text', cache: false, url: '/read/', success: function(msg){ saveToSessionEnabled = false; var saved = JSON.parse( msg ); if( saved != null ) { for( var i=0; saved[i]; i++ ) { saved[i][11].text = advEncode(saved[i][11].text); addImageToList( saved[i][0], saved[i][1], saved[i][2], saved[i][3], saved[i][9], saved[i][4], saved[i][5], saved[i][6], saved[i][7], saved[i][8], saved[i][10], saved[i][11], saved[i][12]) } } saveToSessionEnabled = true; } }); }; // Clear workspace from session function clearSession() { if( confirm( 'This option clears the existing design from the workspace so that you can start a new design. Do you wish to proceed?' ) ) { jQuery.ajax({ type: 'get', cache: false, url: '/clear/', success: function(msg){ document.location.reload(); } }); } }; // Show Workspace function toggleWorkspace() { jQuery("#preloader-background").hide(); jQuery("#preloader-background").html( '' ); jQuery("#workplace").show(); }; function toggleForeground() { jQuery("div.fg_colors").toggle(); } // Layer deletion support function deleteLayer(imgNum) { jQuery("#img_"+imgNum).css( "display", "none" ); jQuery("#uploaded-image-"+imgNum).css( "display", "none" ); imageList[imgNum][8] = 'display: none;'; saveToSession(); }; // Changes text button options function changeTextButton( buttonID, otherbuttons ) { var option = jQuery("#"+buttonID).attr( "setting" ); switch( option ) { case "on": // set it off if( typeof( otherbuttons ) == "undefined" ) { jQuery("#"+buttonID).attr( "setting", "off" ); } break; case "off": // set it on if( typeof( otherbuttons ) != "undefined" ) { jQuery("." + otherbuttons).attr( "setting", "off" ); } jQuery("#"+buttonID).attr( "setting", "on" ); break; } }; function editText(id) { var extra = imageList[id][11]; jQuery("#usertext").val(advDecode(extra.text)); jQuery("#userfont").attr("alt", extra.font); jQuery("#userfontsize").val(extra.size); if(jQuery("#userbold").attr("setting") != extra.bold) $("#userbold").click(); if(jQuery("#useritalic").attr("setting") != extra.italic) $("#useritalic").click(); if(jQuery("#userunder").attr("setting") != extra.underline) $("#userunder").click(); creatorChangeForeground(extra.colour); switch(extra.format) { case 'h': $("#userhori").click(); break; case 'v': $("#usevert").click(); break; case 'c': $("#usercirc").click(); break; } $("#text-add").hide(); $("#text-loading").hide(); $("#text-edit").show(); $("#text-edit-do").attr("alt", id); } function replaceText(id) { $("#text-edit").hide(); $("#text-add").show(); if(typeof(id) == "undefined") { $("#usertext").val(""); saveToSession(); return false; } var pos = $("#uploaded-image-" + id).position(); var width = $("#uploaded-image-" + id).css('width').split('px'); var height = $("#uploaded-image-" + id).css('height').split('px'); deleteLayer(id); createText(pos.left, pos.top, width[0], height[0]); $("#usertext").val(""); saveToSession(); return false; } // Send text options /* function createText(posx, posy) { $("#text-loading").show(); var text = jQuery("#usertext").val(); jQuery("#usertext").val(""); var font = jQuery("#userfont").attr("alt"); var size = jQuery("#userfontsize").val(); // buttons var colour = jQuery("#usercolour").attr( "setting" ); var bold = jQuery("#userbold").attr( "setting" ); var italic = jQuery("#useritalic").attr( "setting" ); var underline = jQuery("#userunder").attr( "setting" ); // text format //var format = jQuery("input[name=textformat]:checked").val(); // h v c var hor = jQuery("#userhori").attr( "setting" ); var ver = jQuery("#usevert").attr( "setting" ); var cir = jQuery("#usercirc").attr( "setting" ); switch( true ) { case hor=='on': var format = 'h'; break; case ver=='on': var format = 'v'; break; case cir=='on': var format = 'c'; break; } var center = jQuery("#usecenter").attr("setting"); // config string var configString = 'font='+font+';size='+size+';colour='+colour+';b='+bold+';i='+italic+';u='+underline+';c='+center+';format='+format+';'; // conds if( text.length <= 0 ) { alert('Please fill in some text first.'); jQuery("#usertext").focus(); return; } // ajax var encoded = advEncode(text); //alert(encoded); //Debug jQuery.ajax({ type: 'post', dataType: 'text', cache: false, data: 'text='+encoded, url: '/text/new/'+configString+'/', success: function(msg){ var saved = JSON.parse( msg ); if( saved != null ) { jQuery("ul.cat_y").append('
  • '); //jQuery("#imgcategory").val("y").trigger("change"); fullName = text; if(fullName.length > 11) fullName = fullName.substr(0, 10) + '...'; fullName = advEncode(fullName); var extra = { "width" : saved.width, "height" : saved.height, "text" : advEncode(encoded), "font" : font, "size" : size, "colour" : colour, "bold" : bold, "italic" : italic, "underline" : underline, "format" : format }; var imgNum = addTextToList( saved.name, '2', saved.width/3, saved.height, '', '0', null, null, fullName, 'filter: none;', 100, extra); $("#text-loading").hide(); if(typeof(posx) != "undefined") $('#uploaded-image-' + imgNum).css('left', posx); if(typeof(posy) != "undefined") $('#uploaded-image-' + imgNum).css('top', posy); imageList[imgNum][6] = $('#uploaded-image-' + imgNum).position(); saveToSession(); } } }); }; */ /* disabled imagged text */ function createText(posx, posy, boxWidth, boxHeight) { $("#text-loading").show(); var text = jQuery("#usertext").val(); jQuery("#usertext").val(""); var font = jQuery("#userfont").attr("alt"); var size = jQuery("#userfontsize").val(); // buttons var colour = jQuery("#usercolour").attr( "setting" ); var bold = jQuery("#userbold").attr( "setting" ); var italic = jQuery("#useritalic").attr( "setting" ); var underline = jQuery("#userunder").attr( "setting" ); // text format //var format = jQuery("input[name=textformat]:checked").val(); // h v c var hor = jQuery("#userhori").attr( "setting" ); var ver = jQuery("#usevert").attr( "setting" ); var cir = jQuery("#usercirc").attr( "setting" ); switch( true ) { case hor=='on': var format = 'h'; break; case ver=='on': var format = 'v'; break; case cir=='on': var format = 'c'; break; } var center = jQuery("#usecenter").attr("setting"); var maxWidth = 0; if(boxWidth != undefined) { maxWidth = boxWidth; } maxWidth = Math.round(maxWidth); // config string var configString = 'font='+font+';size='+size+';colour='+colour+';b='+bold+';i='+italic+';u='+underline+';c='+center+';format='+format+';maxWidth=' + maxWidth + ';'; // conds if( text.length <= 0 ) { alert('Please fill in some text first.'); jQuery("#usertext").focus(); return; } // ajax var encoded = advEncode(text); //alert(encoded); //Debug jQuery.ajax({ type: 'post', dataType: 'text', cache: false, data: 'text='+encoded, url: '/text/new/'+configString+'/', success: function(msg){ var saved = JSON.parse( msg ); if( saved != null ) { jQuery("ul.cat_y").append('
  • '); //jQuery("#imgcategory").val("y").trigger("change"); fullName = text; if(fullName.length > 11) fullName = fullName.substr(0, 10) + '...'; fullName = advEncode(fullName); var newWidth = saved.width/3; var newHeight = saved.height/3; if(boxWidth != undefined) { newWidth = boxWidth } if(boxHeight != undefined) { if(newHeight < boxHeight) { newHeight = boxHeight; } } var extra = { "width" : newWidth, "height" : newHeight, "text" : advEncode(encoded), "font" : font, "size" : size, "colour" : colour, "bold" : bold, "italic" : italic, "underline" : underline, "format" : format }; var imgNum = addImageToList( saved.name, '2', saved.width/3, saved.height, '', '0', null, null, fullName, 'filter: none;', 100, extra); $("#text-loading").hide(); if(typeof(posx) != "undefined") $('#uploaded-image-' + imgNum).css('left', posx); if(typeof(posy) != "undefined") $('#uploaded-image-' + imgNum).css('top', posy); imageList[imgNum][6] = $('#uploaded-image-' + imgNum).position(); saveToSession(); setTextResizable(); } } }); }; function saveAfterResize(event, ui) { var elementID = ui.element.attr('id').split('-'); var elementNum = elementID[2]; var width = ui.element.css('width').split('px'); var height = ui.element.css('height').split('px'); imageList[elementNum][11]['width'] = width[0]; imageList[elementNum][11]['height'] = height[0]; imageList[elementNum][13] = true; // resized if(imageList[elementNum][1]!=1 && imageList[elementNum][1]!=0) { editText(elementNum); replaceText(elementNum); } saveToSession(); } function setTextResizable() { $('.ui-draggable').resizable({ stop: function(event, ui) { saveAfterResize(event, ui); } }); $.each($('.ui-draggable'), function(index, element) { var elementID = $(this).attr('id').split('-'); var elementNum = elementID[2]; if(imageList[elementNum][12] != "0") { $(this).resizable('disable'); } }); } // Resize block of text function resizeText() { $('.ui-draggable').draggable(); setTextResizable(); }; // Get files jpg (output) + prj (ZIP file) function getFiles() { document.location='/save-project/'; }; // Enable file loader function showFileLoader() { jQuery("#ziploader").show(); }; // slider function slider() { $('#slider').slider({ value: 0, min: -6, max: 6, step: 1, stop: function(event, ui) { selectBrightness( ui.value ); } }); }; function sliderAlpha() { $("#alpha-slider").slider({ value: 100, min: 5, max: 100, step: 5, stop: function(event, ui) { selectAlpha(ui.value); } }); } function sliderRotation() { $("#rotation-slider").slider({ value: 0, min: -180, max: 180, step: 45, stop: function(event, ui) { selectRotation(ui.value); } }); } // function to add class "ac" to elems function cleanAc(value, toFind) { $(value).find(toFind).removeClass('ac'); }; function addAc() { $('#template_sel a').click(function() { cleanAc('#template_sel', 'a'); $(this).addClass("ac"); }); $('#tools > .text_tool input.butt').click(function() { if($(this).hasClass("userbutts") || $(this).hasClass("abutts")) { if($(this).hasClass("userbutts")) $('.userbutts').removeClass('ac'); if($(this).hasClass("abutts")) $('.abutts').removeClass('ac'); $(this).addClass("ac"); $(this).blur(); } else { if($(this).hasClass("ac")) { $(this).removeClass('ac'); $(this).blur(); } else { $(this).addClass("ac"); $(this).blur(); } } }); }; function setTooltip(elementName, tooltipDescription, pos_x, pos_y, highlight) { $(elementName).hover(function() { $('#menutip').show().text(tooltipDescription); pos_x = typeof(pos_x) != 'undefined' ? pos_x : $(elementName).offset().left; pos_y = typeof(pos_y) != 'undefined' ? pos_y : $(elementName).offset().top + 42; $('#menutip').css('left', pos_x); $('#menutip').css('top', pos_y); if(highlight == true && $('#menutip').text() != '') $("#menutip").effect("highlight", {}, 1000); }, function() { $('#menutip').hide().text(''); }); } function tooltip() { setTooltip('#new_design',"Delete existing design and start again."); setTooltip('#load_design',"This option allows you to load a previously saved design created using this tool (.prj format). Your project was saved as a ZIP file. You will need to open the ZIP file and extract the PRJ file, which you can upload here."); setTooltip('#save_design',"This option saves your project to your computer as a ZIP file. The ZIP file will contain two files. One is the JPG file which you can submit for printing. The other is a PRJ file which you can reload into this tool at a later date to continue editing your design."); setTooltip('#upload_image',"This option allows you to upload your own images in JPG or PNG format."); setTooltip('#userhori',"Horizontal text"); setTooltip('#usevert',"Vertical text"); setTooltip('#usercirc',"Circular text"); setTooltip('#useleft',"Align text to the left"); setTooltip('#usecenter',"Centred text"); var content = "To design a 2 page booklet, use the left frame for the back side, and the right frame for the front side. To design a 4 page booklet, do an additional second design using the left fram for page 2, and right frame for page 3."; var target = "#help-booklet"; var pos = $(target).offset(); if (pos!=null) { setTooltip(target, content, pos.left + 20, pos.top); } var target = "#help-dvdbook"; var pos = $(target).offset(); if (pos!=null) { setTooltip(target, content, pos.left + 20, pos.top); } } $(document).ready(function(){ slider(); sliderAlpha(); sliderRotation(); addAc(); tooltip(); }); function showCategory(categoryID) { categoryID = typeof(categoryID) != 'undefined' ? categoryID : $('#imgcategory').val(); jQuery("ul.images").hide(); jQuery("ul.cat_"+categoryID).show(); }; function getHex() { $("#entered-hex").val(""); $("#background-hex").show(); $("#background-overwrite").hide(); $("#background-more").hide(); return false; } function setHex(check) { check = typeof(check) != 'undefined' ? check : true; $("#background-hex").hide(); $("#background-overwrite").show(); $("#background-more").show(); if(!check) return false; hex = $("#entered-hex").val(); if(hex[0] == '#') hex = hex.substr(1); hex = hex.toUpperCase(); var len = hex.length; var valid = (len == 6 ? true : false); for(var i = 0; i < len && valid; i++) { var c = hex.charCodeAt(i); if(!(c >= 65 && c <= 70) && !(c >= 48 && c <= 57)) valid = false; } if(valid == false) { alert("Invalid hex value."); return false; } creatorChangeBackground(hex); return false; } //Section: Advanced Font Features (List & Preview) function showFontList() { var fselect = $('a#userfont'); var flist = $('div#font-list'); var pos = fselect.offset(); var height = fselect.height(); flist.css('top', (pos.top + height + 5) + 'px'); flist.css('left', pos.left + 'px'); flist.show(); var sel = $('a#userfont').attr('alt'); $('div#font-list a.highlight').removeClass('highlight'); $('#font-select-' + sel).addClass('highlight'); return false; } function fontPreview(font) { if(font == false) { showCategory(); $('div.font-preview').hide(); return false; } $('ul.images').hide(); $('div#font-preview-' + font).show(); } function fontSet(font, txt) { fontPreview(false); $('#font-list').hide(); //$('input#userfont').val(txt); $('a#userfont').attr('alt', font); return false; } //Project Preview function fullscreenPreview() { var url = "predisplay.php"; var params = 'width='+screen.width; params += ', height='+screen.height; params += ', top=0, left=0'; params += ', fullscreen=yes'; hWindow = window.open(url, '', params); if(window.focus) hWindow.focus(); return false; } /*! modernizr 3.6.0 (Custom Build) | MIT * * https://modernizr.com/download/?-flash-setclasses !*/ !function(e,n,t){function o(e,n){return typeof e===n}function i(){var e,n,t,i,a,s,r;for(var l in f)if(f.hasOwnProperty(l)){if(e=[],n=f[l],n.name&&(e.push(n.name.toLowerCase()),n.options&&n.options.aliases&&n.options.aliases.length))for(t=0;t', '', '', '', '', '', '', ''].join(""); }; // Private: getFlashVars builds the parameter string that will be passed // to flash in the flashvars param. SWFUpload.prototype.getFlashVars = function () { // Build a string from the post param object var paramString = this.buildParamString(); var httpSuccessString = this.settings.http_success.join(","); // Build the parameter string return ["movieName=", encodeURIComponent(this.movieName), "&uploadURL=", encodeURIComponent(this.settings.upload_url), "&useQueryString=", encodeURIComponent(this.settings.use_query_string), "&requeueOnError=", encodeURIComponent(this.settings.requeue_on_error), "&httpSuccess=", encodeURIComponent(httpSuccessString), "&assumeSuccessTimeout=", encodeURIComponent(this.settings.assume_success_timeout), "&params=", encodeURIComponent(paramString), "&filePostName=", encodeURIComponent(this.settings.file_post_name), "&fileTypes=", encodeURIComponent(this.settings.file_types), "&fileTypesDescription=", encodeURIComponent(this.settings.file_types_description), "&fileSizeLimit=", encodeURIComponent(this.settings.file_size_limit), "&fileUploadLimit=", encodeURIComponent(this.settings.file_upload_limit), "&fileQueueLimit=", encodeURIComponent(this.settings.file_queue_limit), "&debugEnabled=", encodeURIComponent(this.settings.debug_enabled), "&buttonImageURL=", encodeURIComponent(this.settings.button_image_url), "&buttonWidth=", encodeURIComponent(this.settings.button_width), "&buttonHeight=", encodeURIComponent(this.settings.button_height), "&buttonText=", encodeURIComponent(this.settings.button_text), "&buttonTextTopPadding=", encodeURIComponent(this.settings.button_text_top_padding), "&buttonTextLeftPadding=", encodeURIComponent(this.settings.button_text_left_padding), "&buttonTextStyle=", encodeURIComponent(this.settings.button_text_style), "&buttonAction=", encodeURIComponent(this.settings.button_action), "&buttonDisabled=", encodeURIComponent(this.settings.button_disabled), "&buttonCursor=", encodeURIComponent(this.settings.button_cursor) ].join(""); }; // Public: getMovieElement retrieves the DOM reference to the Flash element added by SWFUpload // The element is cached after the first lookup 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; }; // Private: buildParamString takes the name/value pairs in the post_params setting object // and joins them up in to a string formatted "name=value&name=value" 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("&"); }; // Public: Used to remove a SWFUpload instance from the page. This method strives to remove // all references to the SWF, and other objects so memory is properly freed. // Returns true if everything was destroyed. Returns a false if a failure occurs leaving SWFUpload in an inconsistant state. // Credits: Major improvements provided by steffen SWFUpload.prototype.destroy = function () { try { // Make sure Flash is done before we try to remove it this.cancelUpload(null, false); // Remove the SWFUpload DOM nodes var movieElement = null; movieElement = this.getMovieElement(); if (movieElement && typeof(movieElement.CallFunction) === "unknown") { // We only want to do this in IE // Loop through all the movie's properties and remove all function references (DOM/JS IE 6/7 memory leak workaround) for (var i in movieElement) { try { if (typeof(movieElement[i]) === "function") { movieElement[i] = null; } } catch (ex1) {} } // Remove the Movie Element from the page try { movieElement.parentNode.removeChild(movieElement); } catch (ex) {} } // Remove IE form fix reference window[this.movieName] = null; // Destroy other references 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; } }; // Public: displayDebugInfo prints out settings and configuration // information about this SWFUpload instance. // This function (and any references to it) can be deleted when placing // SWFUpload in production. 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("") ); }; /* Note: addSetting and getSetting are no longer used by SWFUpload but are included the maintain v2 API compatibility */ // Public: (Deprecated) addSetting adds a setting value. If the value given is undefined or null then the default_value is used. SWFUpload.prototype.addSetting = function (name, value, default_value) { if (value == undefined) { return (this.settings[name] = default_value); } else { return (this.settings[name] = value); } }; // Public: (Deprecated) getSetting gets a setting. Returns an empty string if the setting was not found. SWFUpload.prototype.getSetting = function (name) { if (this.settings[name] != undefined) { return this.settings[name]; } return ""; }; // Private: callFlash handles function calls made to the Flash element. // Calls are made with a setTimeout for some functions to work around // bugs in the ExternalInterface library. SWFUpload.prototype.callFlash = function (functionName, argumentArray) { argumentArray = argumentArray || []; var movieElement = this.getMovieElement(); var returnValue, returnString; // Flash's method if calling ExternalInterface methods (code adapted from MooTools). try { returnString = movieElement.CallFunction('' + __flash__argumentsToXML(argumentArray, 0) + ''); returnValue = eval(returnString); } catch (ex) { throw "Call to " + functionName + " failed"; } // Unescape file post param values if (returnValue != undefined && typeof returnValue.post === "object") { returnValue = this.unescapeFilePostParams(returnValue); } return returnValue; }; /* ***************************** -- Flash control methods -- Your UI should use these to operate SWFUpload ***************************** */ // WARNING: this function does not work in Flash Player 10 // Public: selectFile causes a File Selection Dialog window to appear. This // dialog only allows 1 file to be selected. SWFUpload.prototype.selectFile = function () { this.callFlash("SelectFile"); }; // WARNING: this function does not work in Flash Player 10 // Public: selectFiles causes a File Selection Dialog window to appear/ This // dialog allows the user to select any number of files // Flash Bug Warning: Flash limits the number of selectable files based on the combined length of the file names. // If the selection name length is too long the dialog will fail in an unpredictable manner. There is no work-around // for this bug. SWFUpload.prototype.selectFiles = function () { this.callFlash("SelectFiles"); }; // Public: startUpload starts uploading the first file in the queue unless // the optional parameter 'fileID' specifies the ID SWFUpload.prototype.startUpload = function (fileID) { this.callFlash("StartUpload", [fileID]); }; // Public: cancelUpload cancels any queued file. The fileID parameter may be the file ID or index. // If you do not specify a fileID the current uploading file or first file in the queue is cancelled. // If you do not want the uploadError event to trigger you can specify false for the triggerErrorEvent parameter. SWFUpload.prototype.cancelUpload = function (fileID, triggerErrorEvent) { if (triggerErrorEvent !== false) { triggerErrorEvent = true; } this.callFlash("CancelUpload", [fileID, triggerErrorEvent]); }; // Public: stopUpload stops the current upload and requeues the file at the beginning of the queue. // If nothing is currently uploading then nothing happens. SWFUpload.prototype.stopUpload = function () { this.callFlash("StopUpload"); }; /* ************************ * Settings methods * These methods change the SWFUpload settings. * SWFUpload settings should not be changed directly on the settings object * since many of the settings need to be passed to Flash in order to take * effect. * *********************** */ // Public: getStats gets the file statistics object. SWFUpload.prototype.getStats = function () { return this.callFlash("GetStats"); }; // Public: setStats changes the SWFUpload statistics. You shouldn't need to // change the statistics but you can. Changing the statistics does not // affect SWFUpload accept for the successful_uploads count which is used // by the upload_limit setting to determine how many files the user may upload. SWFUpload.prototype.setStats = function (statsObject) { this.callFlash("SetStats", [statsObject]); }; // Public: getFile retrieves a File object by ID or Index. If the file is // not found then 'null' is returned. SWFUpload.prototype.getFile = function (fileID) { if (typeof(fileID) === "number") { return this.callFlash("GetFileByIndex", [fileID]); } else { return this.callFlash("GetFile", [fileID]); } }; // Public: addFileParam sets a name/value pair that will be posted with the // file specified by the Files ID. If the name already exists then the // exiting value will be overwritten. SWFUpload.prototype.addFileParam = function (fileID, name, value) { return this.callFlash("AddFileParam", [fileID, name, value]); }; // Public: removeFileParam removes a previously set (by addFileParam) name/value // pair from the specified file. SWFUpload.prototype.removeFileParam = function (fileID, name) { this.callFlash("RemoveFileParam", [fileID, name]); }; // Public: setUploadUrl changes the upload_url setting. SWFUpload.prototype.setUploadURL = function (url) { this.settings.upload_url = url.toString(); this.callFlash("SetUploadURL", [url]); }; // Public: setPostParams changes the post_params setting SWFUpload.prototype.setPostParams = function (paramsObject) { this.settings.post_params = paramsObject; this.callFlash("SetPostParams", [paramsObject]); }; // Public: addPostParam adds post name/value pair. Each name can have only one value. SWFUpload.prototype.addPostParam = function (name, value) { this.settings.post_params[name] = value; this.callFlash("SetPostParams", [this.settings.post_params]); }; // Public: removePostParam deletes post name/value pair. SWFUpload.prototype.removePostParam = function (name) { delete this.settings.post_params[name]; this.callFlash("SetPostParams", [this.settings.post_params]); }; // Public: setFileTypes changes the file_types setting and the file_types_description setting SWFUpload.prototype.setFileTypes = function (types, description) { this.settings.file_types = types; this.settings.file_types_description = description; this.callFlash("SetFileTypes", [types, description]); }; // Public: setFileSizeLimit changes the file_size_limit setting SWFUpload.prototype.setFileSizeLimit = function (fileSizeLimit) { this.settings.file_size_limit = fileSizeLimit; this.callFlash("SetFileSizeLimit", [fileSizeLimit]); }; // Public: setFileUploadLimit changes the file_upload_limit setting SWFUpload.prototype.setFileUploadLimit = function (fileUploadLimit) { this.settings.file_upload_limit = fileUploadLimit; this.callFlash("SetFileUploadLimit", [fileUploadLimit]); }; // Public: setFileQueueLimit changes the file_queue_limit setting SWFUpload.prototype.setFileQueueLimit = function (fileQueueLimit) { this.settings.file_queue_limit = fileQueueLimit; this.callFlash("SetFileQueueLimit", [fileQueueLimit]); }; // Public: setFilePostName changes the file_post_name setting SWFUpload.prototype.setFilePostName = function (filePostName) { this.settings.file_post_name = filePostName; this.callFlash("SetFilePostName", [filePostName]); }; // Public: setUseQueryString changes the use_query_string setting SWFUpload.prototype.setUseQueryString = function (useQueryString) { this.settings.use_query_string = useQueryString; this.callFlash("SetUseQueryString", [useQueryString]); }; // Public: setRequeueOnError changes the requeue_on_error setting SWFUpload.prototype.setRequeueOnError = function (requeueOnError) { this.settings.requeue_on_error = requeueOnError; this.callFlash("SetRequeueOnError", [requeueOnError]); }; // Public: setHTTPSuccess changes the http_success setting 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]); }; // Public: setHTTPSuccess changes the http_success setting SWFUpload.prototype.setAssumeSuccessTimeout = function (timeout_seconds) { this.settings.assume_success_timeout = timeout_seconds; this.callFlash("SetAssumeSuccessTimeout", [timeout_seconds]); }; // Public: setDebugEnabled changes the debug_enabled setting SWFUpload.prototype.setDebugEnabled = function (debugEnabled) { this.settings.debug_enabled = debugEnabled; this.callFlash("SetDebugEnabled", [debugEnabled]); }; // Public: setButtonImageURL loads a button image sprite SWFUpload.prototype.setButtonImageURL = function (buttonImageURL) { if (buttonImageURL == undefined) { buttonImageURL = ""; } this.settings.button_image_url = buttonImageURL; this.callFlash("SetButtonImageURL", [buttonImageURL]); }; // Public: setButtonDimensions resizes the Flash Movie and button 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]); }; // Public: setButtonText Changes the text overlaid on the button SWFUpload.prototype.setButtonText = function (html) { this.settings.button_text = html; this.callFlash("SetButtonText", [html]); }; // Public: setButtonTextPadding changes the top and left padding of the text overlay 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]); }; // Public: setButtonTextStyle changes the CSS used to style the HTML/Text overlaid on the button SWFUpload.prototype.setButtonTextStyle = function (css) { this.settings.button_text_style = css; this.callFlash("SetButtonTextStyle", [css]); }; // Public: setButtonDisabled disables/enables the button SWFUpload.prototype.setButtonDisabled = function (isDisabled) { this.settings.button_disabled = isDisabled; this.callFlash("SetButtonDisabled", [isDisabled]); }; // Public: setButtonAction sets the action that occurs when the button is clicked SWFUpload.prototype.setButtonAction = function (buttonAction) { this.settings.button_action = buttonAction; this.callFlash("SetButtonAction", [buttonAction]); }; // Public: setButtonCursor changes the mouse cursor displayed when hovering over the button SWFUpload.prototype.setButtonCursor = function (cursor) { this.settings.button_cursor = cursor; this.callFlash("SetButtonCursor", [cursor]); }; /* ******************************* Flash Event Interfaces These functions are used by Flash to trigger the various events. All these functions a Private. Because the ExternalInterface library is buggy the event calls are added to a queue and the queue then executed by a setTimeout. This ensures that events are executed in a determinate order and that the ExternalInterface bugs are avoided. ******************************* */ 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") { // Queue the event this.eventQueue.push(function () { this.settings[handlerName].apply(this, argumentArray); }); // Execute the next queued event setTimeout(function () { self.executeNextEvent(); }, 0); } else if (this.settings[handlerName] !== null) { throw "Event handler " + handlerName + " is unknown or is not a function"; } }; // Private: Causes the next event in the queue to be executed. Since events are queued using a setTimeout // we must queue them in order to garentee that they are executed in order. 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); } }; // Private: unescapeFileParams is part of a workaround for a flash bug where objects passed through ExternalInterface cannot have // properties that contain characters that are not valid for JavaScript identifiers. To work around this // the Flash Component escapes the parameter names and we must unescape again before passing them along. 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; }; // Private: Called by Flash to see if JS can call in to Flash (test if External Interface is working) SWFUpload.prototype.testExternalInterface = function () { try { return this.callFlash("TestExternalInterface"); } catch (ex) { return false; } }; // Private: This event is called by Flash when it has finished loading. Don't modify this. // Use the swfupload_loaded_handler event setting to execute custom code when SWFUpload has loaded. SWFUpload.prototype.flashReady = function () { // Check that the movie element is loaded correctly with its ExternalInterface methods defined var movieElement = this.getMovieElement(); if (!movieElement) { this.debug("Flash called back ready but the flash movie can't be found."); return; } this.cleanUp(movieElement); this.queueEvent("swfupload_loaded_handler"); }; // Private: removes Flash added fuctions to the DOM node to prevent memory leaks in IE. // This function is called by Flash each time the ExternalInterface functions are created. SWFUpload.prototype.cleanUp = function (movieElement) { // Pro-actively unhook all the Flash functions try { if (this.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) { } // Fix Flashes own cleanup code so if the SWFMovie was removed from the page // it doesn't display errors. window["__flash__removeCallback"] = function (instance, name) { try { if (instance) { instance[name] = null; } } catch (flashEx) { } }; }; /* This is a chance to do something before the browse window opens */ SWFUpload.prototype.fileDialogStart = function () { this.queueEvent("file_dialog_start_handler"); }; /* Called when a file is successfully added to the queue. */ SWFUpload.prototype.fileQueued = function (file) { file = this.unescapeFilePostParams(file); this.queueEvent("file_queued_handler", file); }; /* Handle errors that occur when an attempt to queue a file fails. */ SWFUpload.prototype.fileQueueError = function (file, errorCode, message) { file = this.unescapeFilePostParams(file); this.queueEvent("file_queue_error_handler", [file, errorCode, message]); }; /* Called after the file dialog has closed and the selected files have been queued. You could call startUpload here if you want the queued files to begin uploading immediately. */ 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"; } // Convert undefined to true so if nothing is returned from the upload_start_handler it is // interpretted as 'true'. 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); }; /* Called by SWFUpload JavaScript and Flash functions when debug is enabled. By default it writes messages to the internal debug console. You can override this event and have messages written where you want. */ SWFUpload.prototype.debug = function (message) { this.queueEvent("debug_handler", message); }; /* ********************************** Debug Console The debug console is a self contained, in page location for debug message to be sent. The Debug Console adds itself to the body if necessary. The console is automatically scrolled as messages appear. If you are using your own debug handler or when you deploy to production and have debug disabled you can remove these functions to reduce the file size and complexity. ********************************** */ // Private: debugMessage is the default debug_handler. If you want to print debug messages // call the debug() function. When overriding the function your own function should // check to see if the debug setting is true before outputting debug information. 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); } }; /* Cookie Plug-in This plug in automatically gets all the cookies for this site and adds them to the post_params. Cookies are loaded only on initialization. The refreshCookies function can be called to update the post_params. The cookies will override any other post params with the same name. */ var SWFUpload; if (typeof(SWFUpload) === "function") { SWFUpload.prototype.initSettings = function (oldInitSettings) { return function () { if (typeof(oldInitSettings) === "function") { oldInitSettings.call(this); } this.refreshCookies(false); // The false parameter must be sent since SWFUpload has not initialzed at this point }; }(SWFUpload.prototype.initSettings); // refreshes the post_params and updates SWFUpload. The sendToFlash parameters is optional and defaults to True SWFUpload.prototype.refreshCookies = function (sendToFlash) { if (sendToFlash === undefined) { sendToFlash = true; } sendToFlash = !!sendToFlash; // Get the post_params object var postParams = this.settings.post_params; // Get the cookies var i, cookieArray = document.cookie.split(';'), caLength = cookieArray.length, c, eqIndex, name, value; for (i = 0; i < caLength; i++) { c = cookieArray[i]; // Left Trim spaces while (c.charAt(0) === " ") { c = c.substring(1, c.length); } eqIndex = c.indexOf("="); if (eqIndex > 0) { name = c.substring(0, eqIndex); value = c.substring(eqIndex + 1); postParams[name] = value; } } if (sendToFlash) { this.setPostParams(postParams); } }; } /* Speed Plug-in Features: *Adds several properties to the 'file' object indicated upload speed, time left, upload time, etc. - currentSpeed -- String indicating the upload speed, bytes per second - averageSpeed -- Overall average upload speed, bytes per second - movingAverageSpeed -- Speed over averaged over the last several measurements, bytes per second - timeRemaining -- Estimated remaining upload time in seconds - timeElapsed -- Number of seconds passed for this upload - percentUploaded -- Percentage of the file uploaded (0 to 100) - sizeUploaded -- Formatted size uploaded so far, bytes *Adds setting 'moving_average_history_size' for defining the window size used to calculate the moving average speed. *Adds several Formatting functions for formatting that values provided on the file object. - SWFUpload.speed.formatBPS(bps) -- outputs string formatted in the best units (Gbps, Mbps, Kbps, bps) - SWFUpload.speed.formatTime(seconds) -- outputs string formatted in the best units (x Hr y M z S) - SWFUpload.speed.formatSize(bytes) -- outputs string formatted in the best units (w GB x MB y KB z B ) - SWFUpload.speed.formatPercent(percent) -- outputs string formatted with a percent sign (x.xx %) - SWFUpload.speed.formatUnits(baseNumber, divisionArray, unitLabelArray, fractionalBoolean) - Formats a number using the division array to determine how to apply the labels in the Label Array - factionalBoolean indicates whether the number should be returned as a single fractional number with a unit (speed) or as several numbers labeled with units (time) */ var SWFUpload; if (typeof(SWFUpload) === "function") { SWFUpload.speed = {}; SWFUpload.prototype.initSettings = (function (oldInitSettings) { return function () { if (typeof(oldInitSettings) === "function") { oldInitSettings.call(this); } this.ensureDefault = function (settingName, defaultValue) { this.settings[settingName] = (this.settings[settingName] == undefined) ? defaultValue : this.settings[settingName]; }; // List used to keep the speed stats for the files we are tracking this.fileSpeedStats = {}; this.speedSettings = {}; this.ensureDefault("moving_average_history_size", "10"); this.speedSettings.user_file_queued_handler = this.settings.file_queued_handler; this.speedSettings.user_file_queue_error_handler = this.settings.file_queue_error_handler; this.speedSettings.user_upload_start_handler = this.settings.upload_start_handler; this.speedSettings.user_upload_error_handler = this.settings.upload_error_handler; this.speedSettings.user_upload_progress_handler = this.settings.upload_progress_handler; this.speedSettings.user_upload_success_handler = this.settings.upload_success_handler; this.speedSettings.user_upload_complete_handler = this.settings.upload_complete_handler; this.settings.file_queued_handler = SWFUpload.speed.fileQueuedHandler; this.settings.file_queue_error_handler = SWFUpload.speed.fileQueueErrorHandler; this.settings.upload_start_handler = SWFUpload.speed.uploadStartHandler; this.settings.upload_error_handler = SWFUpload.speed.uploadErrorHandler; this.settings.upload_progress_handler = SWFUpload.speed.uploadProgressHandler; this.settings.upload_success_handler = SWFUpload.speed.uploadSuccessHandler; this.settings.upload_complete_handler = SWFUpload.speed.uploadCompleteHandler; delete this.ensureDefault; }; })(SWFUpload.prototype.initSettings); SWFUpload.speed.fileQueuedHandler = function (file) { if (typeof this.speedSettings.user_file_queued_handler === "function") { file = SWFUpload.speed.extendFile(file); return this.speedSettings.user_file_queued_handler.call(this, file); } }; SWFUpload.speed.fileQueueErrorHandler = function (file, errorCode, message) { if (typeof this.speedSettings.user_file_queue_error_handler === "function") { file = SWFUpload.speed.extendFile(file); return this.speedSettings.user_file_queue_error_handler.call(this, file, errorCode, message); } }; SWFUpload.speed.uploadStartHandler = function (file) { if (typeof this.speedSettings.user_upload_start_handler === "function") { file = SWFUpload.speed.extendFile(file, this.fileSpeedStats); return this.speedSettings.user_upload_start_handler.call(this, file); } }; SWFUpload.speed.uploadErrorHandler = function (file, errorCode, message) { file = SWFUpload.speed.extendFile(file, this.fileSpeedStats); SWFUpload.speed.removeTracking(file, this.fileSpeedStats); if (typeof this.speedSettings.user_upload_error_handler === "function") { return this.speedSettings.user_upload_error_handler.call(this, file, errorCode, message); } }; SWFUpload.speed.uploadProgressHandler = function (file, bytesComplete, bytesTotal) { this.updateTracking(file, bytesComplete); file = SWFUpload.speed.extendFile(file, this.fileSpeedStats); if (typeof this.speedSettings.user_upload_progress_handler === "function") { return this.speedSettings.user_upload_progress_handler.call(this, file, bytesComplete, bytesTotal); } }; SWFUpload.speed.uploadSuccessHandler = function (file, serverData) { if (typeof this.speedSettings.user_upload_success_handler === "function") { file = SWFUpload.speed.extendFile(file, this.fileSpeedStats); return this.speedSettings.user_upload_success_handler.call(this, file, serverData); } }; SWFUpload.speed.uploadCompleteHandler = function (file) { file = SWFUpload.speed.extendFile(file, this.fileSpeedStats); SWFUpload.speed.removeTracking(file, this.fileSpeedStats); if (typeof this.speedSettings.user_upload_complete_handler === "function") { return this.speedSettings.user_upload_complete_handler.call(this, file); } }; // Private: extends the file object with the speed plugin values SWFUpload.speed.extendFile = function (file, trackingList) { var tracking; if (trackingList) { tracking = trackingList[file.id]; } if (tracking) { file.currentSpeed = tracking.currentSpeed; file.averageSpeed = tracking.averageSpeed; file.movingAverageSpeed = tracking.movingAverageSpeed; file.timeRemaining = tracking.timeRemaining; file.timeElapsed = tracking.timeElapsed; file.percentUploaded = tracking.percentUploaded; file.sizeUploaded = tracking.bytesUploaded; } else { file.currentSpeed = 0; file.averageSpeed = 0; file.movingAverageSpeed = 0; file.timeRemaining = 0; file.timeElapsed = 0; file.percentUploaded = 0; file.sizeUploaded = 0; } return file; }; // Private: Updates the speed tracking object, or creates it if necessary SWFUpload.prototype.updateTracking = function (file, bytesUploaded) { var tracking = this.fileSpeedStats[file.id]; if (!tracking) { this.fileSpeedStats[file.id] = tracking = {}; } // Sanity check inputs bytesUploaded = bytesUploaded || tracking.bytesUploaded || 0; if (bytesUploaded < 0) { bytesUploaded = 0; } if (bytesUploaded > file.size) { bytesUploaded = file.size; } var tickTime = (new Date()).getTime(); if (!tracking.startTime) { tracking.startTime = (new Date()).getTime(); tracking.lastTime = tracking.startTime; tracking.currentSpeed = 0; tracking.averageSpeed = 0; tracking.movingAverageSpeed = 0; tracking.movingAverageHistory = []; tracking.timeRemaining = 0; tracking.timeElapsed = 0; tracking.percentUploaded = bytesUploaded / file.size; tracking.bytesUploaded = bytesUploaded; } else if (tracking.startTime > tickTime) { this.debug("When backwards in time"); } else { // Get time and deltas var now = (new Date()).getTime(); var lastTime = tracking.lastTime; var deltaTime = now - lastTime; var deltaBytes = bytesUploaded - tracking.bytesUploaded; if (deltaBytes === 0 || deltaTime === 0) { return tracking; } // Update tracking object tracking.lastTime = now; tracking.bytesUploaded = bytesUploaded; // Calculate speeds tracking.currentSpeed = (deltaBytes * 8 ) / (deltaTime / 1000); tracking.averageSpeed = (tracking.bytesUploaded * 8) / ((now - tracking.startTime) / 1000); // Calculate moving average tracking.movingAverageHistory.push(tracking.currentSpeed); if (tracking.movingAverageHistory.length > this.settings.moving_average_history_size) { tracking.movingAverageHistory.shift(); } tracking.movingAverageSpeed = SWFUpload.speed.calculateMovingAverage(tracking.movingAverageHistory); // Update times tracking.timeRemaining = (file.size - tracking.bytesUploaded) * 8 / tracking.movingAverageSpeed; tracking.timeElapsed = (now - tracking.startTime) / 1000; // Update percent tracking.percentUploaded = (tracking.bytesUploaded / file.size * 100); } return tracking; }; SWFUpload.speed.removeTracking = function (file, trackingList) { try { trackingList[file.id] = null; delete trackingList[file.id]; } catch (ex) { } }; SWFUpload.speed.formatUnits = function (baseNumber, unitDivisors, unitLabels, singleFractional) { var i, unit, unitDivisor, unitLabel; if (baseNumber === 0) { return "0 " + unitLabels[unitLabels.length - 1]; } if (singleFractional) { unit = baseNumber; unitLabel = unitLabels.length >= unitDivisors.length ? unitLabels[unitDivisors.length - 1] : ""; for (i = 0; i < unitDivisors.length; i++) { if (baseNumber >= unitDivisors[i]) { unit = (baseNumber / unitDivisors[i]).toFixed(2); unitLabel = unitLabels.length >= i ? " " + unitLabels[i] : ""; break; } } return unit + unitLabel; } else { var formattedStrings = []; var remainder = baseNumber; for (i = 0; i < unitDivisors.length; i++) { unitDivisor = unitDivisors[i]; unitLabel = unitLabels.length > i ? " " + unitLabels[i] : ""; unit = remainder / unitDivisor; if (i < unitDivisors.length -1) { unit = Math.floor(unit); } else { unit = unit.toFixed(2); } if (unit > 0) { remainder = remainder % unitDivisor; formattedStrings.push(unit + unitLabel); } } return formattedStrings.join(" "); } }; SWFUpload.speed.formatBPS = function (baseNumber) { var bpsUnits = [1073741824, 1048576, 1024, 1], bpsUnitLabels = ["Gbps", "Mbps", "Kbps", "bps"]; return SWFUpload.speed.formatUnits(baseNumber, bpsUnits, bpsUnitLabels, true); }; SWFUpload.speed.formatTime = function (baseNumber) { var timeUnits = [86400, 3600, 60, 1], timeUnitLabels = ["d", "h", "m", "s"]; return SWFUpload.speed.formatUnits(baseNumber, timeUnits, timeUnitLabels, false); }; SWFUpload.speed.formatBytes = function (baseNumber) { var sizeUnits = [1073741824, 1048576, 1024, 1], sizeUnitLabels = ["GB", "MB", "KB", "bytes"]; return SWFUpload.speed.formatUnits(baseNumber, sizeUnits, sizeUnitLabels, true); }; SWFUpload.speed.formatPercent = function (baseNumber) { return baseNumber.toFixed(2) + " %"; }; SWFUpload.speed.calculateMovingAverage = function (history) { var vals = [], size, sum = 0.0, mean = 0.0, varianceTemp = 0.0, variance = 0.0, standardDev = 0.0; var i; var mSum = 0, mCount = 0; size = history.length; // Check for sufficient data if (size >= 8) { // Clone the array and Calculate sum of the values for (i = 0; i < size; i++) { vals[i] = history[i]; sum += vals[i]; } mean = sum / size; // Calculate variance for the set for (i = 0; i < size; i++) { varianceTemp += Math.pow((vals[i] - mean), 2); } variance = varianceTemp / size; standardDev = Math.sqrt(variance); //Standardize the Data for (i = 0; i < size; i++) { vals[i] = (vals[i] - mean) / standardDev; } // Calculate the average excluding outliers var deviationRange = 2.0; for (i = 0; i < size; i++) { if (vals[i] <= deviationRange && vals[i] >= -deviationRange) { mCount++; mSum += history[i]; } } } else { // Calculate the average (not enough data points to remove outliers) mCount = size; for (i = 0; i < size; i++) { mSum += history[i]; } } return mSum / mCount; }; } /* SWFUpload.SWFObject Plugin Summary: This plugin uses SWFObject to embed SWFUpload dynamically in the page. SWFObject provides accurate Flash Player detection and DOM Ready loading. This plugin replaces the Graceful Degradation plugin. Features: * swfupload_load_failed_hander event * swfupload_pre_load_handler event * minimum_flash_version setting (default: "9.0.28") * SWFUpload.onload event for early loading Usage: Provide handlers and settings as needed. When using the SWFUpload.SWFObject plugin you should initialize SWFUploading in SWFUpload.onload rather than in window.onload. When initialized this way SWFUpload can load earlier preventing the UI flicker that was seen using the Graceful Degradation plugin. Notes: You must provide set minimum_flash_version setting to "8" if you are using SWFUpload for Flash Player 8. The swfuploadLoadFailed event is only fired if the minimum version of Flash Player is not met. Other issues such as missing SWF files, browser bugs or corrupt Flash Player installations will not trigger this event. The swfuploadPreLoad event is fired as soon as the minimum version of Flash Player is found. It does not wait for SWFUpload to load and can be used to prepare the SWFUploadUI and hide alternate content. swfobject's onDomReady event is cross-browser safe but will default to the window.onload event when DOMReady is not supported by the browser. Early DOM Loading is supported in major modern browsers but cannot be guaranteed for every browser ever made. */ /* SWFObject v2.1 Copyright (c) 2007-2008 Geoff Stearns, Michael Williams, and Bobby van der Sluis This software is released under the MIT License */ var swfobject=function(){var b="undefined",Q="object",n="Shockwave Flash",p="ShockwaveFlash.ShockwaveFlash",P="application/x-shockwave-flash",m="SWFObjectExprInst",j=window,K=document,T=navigator,o=[],N=[],i=[],d=[],J,Z=null,M=null,l=null,e=false,A=false;var h=function(){var v=typeof K.getElementById!=b&&typeof K.getElementsByTagName!=b&&typeof K.createElement!=b,AC=[0,0,0],x=null;if(typeof T.plugins!=b&&typeof T.plugins[n]==Q){x=T.plugins[n].description;if(x&&!(typeof T.mimeTypes!=b&&T.mimeTypes[P]&&!T.mimeTypes[P].enabledPlugin)){x=x.replace(/^.*\s+(\S+\s+\S+$)/,"$1");AC[0]=parseInt(x.replace(/^(.*)\..*$/,"$1"),10);AC[1]=parseInt(x.replace(/^.*\.(.*)\s.*$/,"$1"),10);AC[2]=/r/.test(x)?parseInt(x.replace(/^.*r(.*)$/,"$1"),10):0}}else{if(typeof j.ActiveXObject!=b){var y=null,AB=false;try{y=new ActiveXObject(p+".7")}catch(t){try{y=new ActiveXObject(p+".6");AC=[6,0,21];y.AllowScriptAccess="always"}catch(t){if(AC[0]==6){AB=true}}if(!AB){try{y=new ActiveXObject(p)}catch(t){}}}if(!AB&&y){try{x=y.GetVariable("$version");if(x){x=x.split(" ")[1].split(",");AC=[parseInt(x[0],10),parseInt(x[1],10),parseInt(x[2],10)]}}catch(t){}}}}var AD=T.userAgent.toLowerCase(),r=T.platform.toLowerCase(),AA=/webkit/.test(AD)?parseFloat(AD.replace(/^.*webkit\/(\d+(\.\d+)?).*$/,"$1")):false,q=false,z=r?/win/.test(r):/win/.test(AD),w=r?/mac/.test(r):/mac/.test(AD);/*@cc_on q=true;@if(@_win32)z=true;@elif(@_mac)w=true;@end@*/return{w3cdom:v,pv:AC,webkit:AA,ie:q,win:z,mac:w}}();var L=function(){if(!h.w3cdom){return }f(H);if(h.ie&&h.win){try{K.write("