removed js not in use

rails2
Espen Antonsen 2009-07-21 11:31:53 +02:00
parent 4fd99b4570
commit 5b8a651fd2
48 changed files with 15 additions and 15213 deletions

View File

@ -9,7 +9,7 @@ require File.join(File.dirname(__FILE__), 'boot')
Rails::Initializer.run do |config|
config.gem "authlogic"
config.gem "authlogic"
config.gem 'mime-types', :lib => 'mime/types'
config.gem "image_science"
config.gem "mini_exiftool"

View File

@ -6,13 +6,23 @@ jQuery(function($) {
})
}
var map, locations_on_map = new Array();
var map, latlng
if ( $('#map_canvas').length && $('#album_latitude').val() > '' && $('#album_longitude').val() > '' ) {
latlng = new google.maps.LatLng($('#album_latitude').val(), $('#album_longitude').val());
mapInitialize()
$('#map_canvas').show()
}
if ( $('#map_canvas').length && $('#photo_latitude').val() > '' && $('#photo_longitude').val() > '' ) {
latlng = new google.maps.LatLng($('#photo_latitude').val(), $('#photo_longitude').val());
mapInitialize()
$('#map_canvas').show()
}
$("#album_address").change( function() {
if( !map ) {
mapInitialize()
$('#map_canvas').show()
}
var geocoder = new google.maps.Geocoder()
var address = this.value
if (geocoder) {
@ -26,19 +36,17 @@ jQuery(function($) {
position: results[0].geometry.location
}
)
} else {
alert("No results found")
//alert("No results found")
}
} else {
alert("Geocode was not successful for the following reason: " + status)
//alert("Geocode was not successful for the following reason: " + status)
}
});
}
})
function mapInitialize() {
var latlng = new google.maps.LatLng($('#album_latitude').val(), $('#album_longitude').val());
var myOptions = {
zoom: 13,
center: latlng,

View File

@ -1,963 +0,0 @@
// Copyright (c) 2005-2008 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
// (c) 2005-2008 Ivan Krstic (http://blogs.law.harvard.edu/ivan)
// (c) 2005-2008 Jon Tirsen (http://www.tirsen.com)
// Contributors:
// Richard Livsey
// Rahul Bhargava
// Rob Wills
//
// script.aculo.us is freely distributable under the terms of an MIT-style license.
// For details, see the script.aculo.us web site: http://script.aculo.us/
// Autocompleter.Base handles all the autocompletion functionality
// that's independent of the data source for autocompletion. This
// includes drawing the autocompletion menu, observing keyboard
// and mouse events, and similar.
//
// Specific autocompleters need to provide, at the very least,
// a getUpdatedChoices function that will be invoked every time
// the text inside the monitored textbox changes. This method
// should get the text for which to provide autocompletion by
// invoking this.getToken(), NOT by directly accessing
// this.element.value. This is to allow incremental tokenized
// autocompletion. Specific auto-completion logic (AJAX, etc)
// belongs in getUpdatedChoices.
//
// Tokenized incremental autocompletion is enabled automatically
// when an autocompleter is instantiated with the 'tokens' option
// in the options parameter, e.g.:
// new Ajax.Autocompleter('id','upd', '/url/', { tokens: ',' });
// will incrementally autocomplete with a comma as the token.
// Additionally, ',' in the above example can be replaced with
// a token array, e.g. { tokens: [',', '\n'] } which
// enables autocompletion on multiple tokens. This is most
// useful when one of the tokens is \n (a newline), as it
// allows smart autocompletion after linebreaks.
if(typeof Effect == 'undefined')
throw("controls.js requires including script.aculo.us' effects.js library");
var Autocompleter = { };
Autocompleter.Base = Class.create({
baseInitialize: function(element, update, options) {
element = $(element);
this.element = element;
this.update = $(update);
this.hasFocus = false;
this.changed = false;
this.active = false;
this.index = 0;
this.entryCount = 0;
this.oldElementValue = this.element.value;
if(this.setOptions)
this.setOptions(options);
else
this.options = options || { };
this.options.paramName = this.options.paramName || this.element.name;
this.options.tokens = this.options.tokens || [];
this.options.frequency = this.options.frequency || 0.4;
this.options.minChars = this.options.minChars || 1;
this.options.onShow = this.options.onShow ||
function(element, update){
if(!update.style.position || update.style.position=='absolute') {
update.style.position = 'absolute';
Position.clone(element, update, {
setHeight: false,
offsetTop: element.offsetHeight
});
}
Effect.Appear(update,{duration:0.15});
};
this.options.onHide = this.options.onHide ||
function(element, update){ new Effect.Fade(update,{duration:0.15}) };
if(typeof(this.options.tokens) == 'string')
this.options.tokens = new Array(this.options.tokens);
// Force carriage returns as token delimiters anyway
if (!this.options.tokens.include('\n'))
this.options.tokens.push('\n');
this.observer = null;
this.element.setAttribute('autocomplete','off');
Element.hide(this.update);
Event.observe(this.element, 'blur', this.onBlur.bindAsEventListener(this));
Event.observe(this.element, 'keydown', this.onKeyPress.bindAsEventListener(this));
},
show: function() {
if(Element.getStyle(this.update, 'display')=='none') this.options.onShow(this.element, this.update);
if(!this.iefix &&
(Prototype.Browser.IE) &&
(Element.getStyle(this.update, 'position')=='absolute')) {
new Insertion.After(this.update,
'<iframe id="' + this.update.id + '_iefix" '+
'style="display:none;position:absolute;filter:progid:DXImageTransform.Microsoft.Alpha(opacity=0);" ' +
'src="javascript:false;" frameborder="0" scrolling="no"></iframe>');
this.iefix = $(this.update.id+'_iefix');
}
if(this.iefix) setTimeout(this.fixIEOverlapping.bind(this), 50);
},
fixIEOverlapping: function() {
Position.clone(this.update, this.iefix, {setTop:(!this.update.style.height)});
this.iefix.style.zIndex = 1;
this.update.style.zIndex = 2;
Element.show(this.iefix);
},
hide: function() {
this.stopIndicator();
if(Element.getStyle(this.update, 'display')!='none') this.options.onHide(this.element, this.update);
if(this.iefix) Element.hide(this.iefix);
},
startIndicator: function() {
if(this.options.indicator) Element.show(this.options.indicator);
},
stopIndicator: function() {
if(this.options.indicator) Element.hide(this.options.indicator);
},
onKeyPress: function(event) {
if(this.active)
switch(event.keyCode) {
case Event.KEY_TAB:
case Event.KEY_RETURN:
this.selectEntry();
Event.stop(event);
case Event.KEY_ESC:
this.hide();
this.active = false;
Event.stop(event);
return;
case Event.KEY_LEFT:
case Event.KEY_RIGHT:
return;
case Event.KEY_UP:
this.markPrevious();
this.render();
Event.stop(event);
return;
case Event.KEY_DOWN:
this.markNext();
this.render();
Event.stop(event);
return;
}
else
if(event.keyCode==Event.KEY_TAB || event.keyCode==Event.KEY_RETURN ||
(Prototype.Browser.WebKit > 0 && event.keyCode == 0)) return;
this.changed = true;
this.hasFocus = true;
if(this.observer) clearTimeout(this.observer);
this.observer =
setTimeout(this.onObserverEvent.bind(this), this.options.frequency*1000);
},
activate: function() {
this.changed = false;
this.hasFocus = true;
this.getUpdatedChoices();
},
onHover: function(event) {
var element = Event.findElement(event, 'LI');
if(this.index != element.autocompleteIndex)
{
this.index = element.autocompleteIndex;
this.render();
}
Event.stop(event);
},
onClick: function(event) {
var element = Event.findElement(event, 'LI');
this.index = element.autocompleteIndex;
this.selectEntry();
this.hide();
},
onBlur: function(event) {
// needed to make click events working
setTimeout(this.hide.bind(this), 250);
this.hasFocus = false;
this.active = false;
},
render: function() {
if(this.entryCount > 0) {
for (var i = 0; i < this.entryCount; i++)
this.index==i ?
Element.addClassName(this.getEntry(i),"selected") :
Element.removeClassName(this.getEntry(i),"selected");
if(this.hasFocus) {
this.show();
this.active = true;
}
} else {
this.active = false;
this.hide();
}
},
markPrevious: function() {
if(this.index > 0) this.index--;
else this.index = this.entryCount-1;
this.getEntry(this.index).scrollIntoView(true);
},
markNext: function() {
if(this.index < this.entryCount-1) this.index++;
else this.index = 0;
this.getEntry(this.index).scrollIntoView(false);
},
getEntry: function(index) {
return this.update.firstChild.childNodes[index];
},
getCurrentEntry: function() {
return this.getEntry(this.index);
},
selectEntry: function() {
this.active = false;
this.updateElement(this.getCurrentEntry());
},
updateElement: function(selectedElement) {
if (this.options.updateElement) {
this.options.updateElement(selectedElement);
return;
}
var value = '';
if (this.options.select) {
var nodes = $(selectedElement).select('.' + this.options.select) || [];
if(nodes.length>0) value = Element.collectTextNodes(nodes[0], this.options.select);
} else
value = Element.collectTextNodesIgnoreClass(selectedElement, 'informal');
var bounds = this.getTokenBounds();
if (bounds[0] != -1) {
var newValue = this.element.value.substr(0, bounds[0]);
var whitespace = this.element.value.substr(bounds[0]).match(/^\s+/);
if (whitespace)
newValue += whitespace[0];
this.element.value = newValue + value + this.element.value.substr(bounds[1]);
} else {
this.element.value = value;
}
this.oldElementValue = this.element.value;
this.element.focus();
if (this.options.afterUpdateElement)
this.options.afterUpdateElement(this.element, selectedElement);
},
updateChoices: function(choices) {
if(!this.changed && this.hasFocus) {
this.update.innerHTML = choices;
Element.cleanWhitespace(this.update);
Element.cleanWhitespace(this.update.down());
if(this.update.firstChild && this.update.down().childNodes) {
this.entryCount =
this.update.down().childNodes.length;
for (var i = 0; i < this.entryCount; i++) {
var entry = this.getEntry(i);
entry.autocompleteIndex = i;
this.addObservers(entry);
}
} else {
this.entryCount = 0;
}
this.stopIndicator();
this.index = 0;
if(this.entryCount==1 && this.options.autoSelect) {
this.selectEntry();
this.hide();
} else {
this.render();
}
}
},
addObservers: function(element) {
Event.observe(element, "mouseover", this.onHover.bindAsEventListener(this));
Event.observe(element, "click", this.onClick.bindAsEventListener(this));
},
onObserverEvent: function() {
this.changed = false;
this.tokenBounds = null;
if(this.getToken().length>=this.options.minChars) {
this.getUpdatedChoices();
} else {
this.active = false;
this.hide();
}
this.oldElementValue = this.element.value;
},
getToken: function() {
var bounds = this.getTokenBounds();
return this.element.value.substring(bounds[0], bounds[1]).strip();
},
getTokenBounds: function() {
if (null != this.tokenBounds) return this.tokenBounds;
var value = this.element.value;
if (value.strip().empty()) return [-1, 0];
var diff = arguments.callee.getFirstDifferencePos(value, this.oldElementValue);
var offset = (diff == this.oldElementValue.length ? 1 : 0);
var prevTokenPos = -1, nextTokenPos = value.length;
var tp;
for (var index = 0, l = this.options.tokens.length; index < l; ++index) {
tp = value.lastIndexOf(this.options.tokens[index], diff + offset - 1);
if (tp > prevTokenPos) prevTokenPos = tp;
tp = value.indexOf(this.options.tokens[index], diff + offset);
if (-1 != tp && tp < nextTokenPos) nextTokenPos = tp;
}
return (this.tokenBounds = [prevTokenPos + 1, nextTokenPos]);
}
});
Autocompleter.Base.prototype.getTokenBounds.getFirstDifferencePos = function(newS, oldS) {
var boundary = Math.min(newS.length, oldS.length);
for (var index = 0; index < boundary; ++index)
if (newS[index] != oldS[index])
return index;
return boundary;
};
Ajax.Autocompleter = Class.create(Autocompleter.Base, {
initialize: function(element, update, url, options) {
this.baseInitialize(element, update, options);
this.options.asynchronous = true;
this.options.onComplete = this.onComplete.bind(this);
this.options.defaultParams = this.options.parameters || null;
this.url = url;
},
getUpdatedChoices: function() {
this.startIndicator();
var entry = encodeURIComponent(this.options.paramName) + '=' +
encodeURIComponent(this.getToken());
this.options.parameters = this.options.callback ?
this.options.callback(this.element, entry) : entry;
if(this.options.defaultParams)
this.options.parameters += '&' + this.options.defaultParams;
new Ajax.Request(this.url, this.options);
},
onComplete: function(request) {
this.updateChoices(request.responseText);
}
});
// The local array autocompleter. Used when you'd prefer to
// inject an array of autocompletion options into the page, rather
// than sending out Ajax queries, which can be quite slow sometimes.
//
// The constructor takes four parameters. The first two are, as usual,
// the id of the monitored textbox, and id of the autocompletion menu.
// The third is the array you want to autocomplete from, and the fourth
// is the options block.
//
// Extra local autocompletion options:
// - choices - How many autocompletion choices to offer
//
// - partialSearch - If false, the autocompleter will match entered
// text only at the beginning of strings in the
// autocomplete array. Defaults to true, which will
// match text at the beginning of any *word* in the
// strings in the autocomplete array. If you want to
// search anywhere in the string, additionally set
// the option fullSearch to true (default: off).
//
// - fullSsearch - Search anywhere in autocomplete array strings.
//
// - partialChars - How many characters to enter before triggering
// a partial match (unlike minChars, which defines
// how many characters are required to do any match
// at all). Defaults to 2.
//
// - ignoreCase - Whether to ignore case when autocompleting.
// Defaults to true.
//
// It's possible to pass in a custom function as the 'selector'
// option, if you prefer to write your own autocompletion logic.
// In that case, the other options above will not apply unless
// you support them.
Autocompleter.Local = Class.create(Autocompleter.Base, {
initialize: function(element, update, array, options) {
this.baseInitialize(element, update, options);
this.options.array = array;
},
getUpdatedChoices: function() {
this.updateChoices(this.options.selector(this));
},
setOptions: function(options) {
this.options = Object.extend({
choices: 10,
partialSearch: true,
partialChars: 2,
ignoreCase: true,
fullSearch: false,
selector: function(instance) {
var ret = []; // Beginning matches
var partial = []; // Inside matches
var entry = instance.getToken();
var count = 0;
for (var i = 0; i < instance.options.array.length &&
ret.length < instance.options.choices ; i++) {
var elem = instance.options.array[i];
var foundPos = instance.options.ignoreCase ?
elem.toLowerCase().indexOf(entry.toLowerCase()) :
elem.indexOf(entry);
while (foundPos != -1) {
if (foundPos == 0 && elem.length != entry.length) {
ret.push("<li><strong>" + elem.substr(0, entry.length) + "</strong>" +
elem.substr(entry.length) + "</li>");
break;
} else if (entry.length >= instance.options.partialChars &&
instance.options.partialSearch && foundPos != -1) {
if (instance.options.fullSearch || /\s/.test(elem.substr(foundPos-1,1))) {
partial.push("<li>" + elem.substr(0, foundPos) + "<strong>" +
elem.substr(foundPos, entry.length) + "</strong>" + elem.substr(
foundPos + entry.length) + "</li>");
break;
}
}
foundPos = instance.options.ignoreCase ?
elem.toLowerCase().indexOf(entry.toLowerCase(), foundPos + 1) :
elem.indexOf(entry, foundPos + 1);
}
}
if (partial.length)
ret = ret.concat(partial.slice(0, instance.options.choices - ret.length));
return "<ul>" + ret.join('') + "</ul>";
}
}, options || { });
}
});
// AJAX in-place editor and collection editor
// Full rewrite by Christophe Porteneuve <tdd@tddsworld.com> (April 2007).
// Use this if you notice weird scrolling problems on some browsers,
// the DOM might be a bit confused when this gets called so do this
// waits 1 ms (with setTimeout) until it does the activation
Field.scrollFreeActivate = function(field) {
setTimeout(function() {
Field.activate(field);
}, 1);
};
Ajax.InPlaceEditor = Class.create({
initialize: function(element, url, options) {
this.url = url;
this.element = element = $(element);
this.prepareOptions();
this._controls = { };
arguments.callee.dealWithDeprecatedOptions(options); // DEPRECATION LAYER!!!
Object.extend(this.options, options || { });
if (!this.options.formId && this.element.id) {
this.options.formId = this.element.id + '-inplaceeditor';
if ($(this.options.formId))
this.options.formId = '';
}
if (this.options.externalControl)
this.options.externalControl = $(this.options.externalControl);
if (!this.options.externalControl)
this.options.externalControlOnly = false;
this._originalBackground = this.element.getStyle('background-color') || 'transparent';
this.element.title = this.options.clickToEditText;
this._boundCancelHandler = this.handleFormCancellation.bind(this);
this._boundComplete = (this.options.onComplete || Prototype.emptyFunction).bind(this);
this._boundFailureHandler = this.handleAJAXFailure.bind(this);
this._boundSubmitHandler = this.handleFormSubmission.bind(this);
this._boundWrapperHandler = this.wrapUp.bind(this);
this.registerListeners();
},
checkForEscapeOrReturn: function(e) {
if (!this._editing || e.ctrlKey || e.altKey || e.shiftKey) return;
if (Event.KEY_ESC == e.keyCode)
this.handleFormCancellation(e);
else if (Event.KEY_RETURN == e.keyCode)
this.handleFormSubmission(e);
},
createControl: function(mode, handler, extraClasses) {
var control = this.options[mode + 'Control'];
var text = this.options[mode + 'Text'];
if ('button' == control) {
var btn = document.createElement('input');
btn.type = 'submit';
btn.value = text;
btn.className = 'editor_' + mode + '_button';
if ('cancel' == mode)
btn.onclick = this._boundCancelHandler;
this._form.appendChild(btn);
this._controls[mode] = btn;
} else if ('link' == control) {
var link = document.createElement('a');
link.href = '#';
link.appendChild(document.createTextNode(text));
link.onclick = 'cancel' == mode ? this._boundCancelHandler : this._boundSubmitHandler;
link.className = 'editor_' + mode + '_link';
if (extraClasses)
link.className += ' ' + extraClasses;
this._form.appendChild(link);
this._controls[mode] = link;
}
},
createEditField: function() {
var text = (this.options.loadTextURL ? this.options.loadingText : this.getText());
var fld;
if (1 >= this.options.rows && !/\r|\n/.test(this.getText())) {
fld = document.createElement('input');
fld.type = 'text';
var size = this.options.size || this.options.cols || 0;
if (0 < size) fld.size = size;
} else {
fld = document.createElement('textarea');
fld.rows = (1 >= this.options.rows ? this.options.autoRows : this.options.rows);
fld.cols = this.options.cols || 40;
}
fld.name = this.options.paramName;
fld.value = text; // No HTML breaks conversion anymore
fld.className = 'editor_field';
if (this.options.submitOnBlur)
fld.onblur = this._boundSubmitHandler;
this._controls.editor = fld;
if (this.options.loadTextURL)
this.loadExternalText();
this._form.appendChild(this._controls.editor);
},
createForm: function() {
var ipe = this;
function addText(mode, condition) {
var text = ipe.options['text' + mode + 'Controls'];
if (!text || condition === false) return;
ipe._form.appendChild(document.createTextNode(text));
};
this._form = $(document.createElement('form'));
this._form.id = this.options.formId;
this._form.addClassName(this.options.formClassName);
this._form.onsubmit = this._boundSubmitHandler;
this.createEditField();
if ('textarea' == this._controls.editor.tagName.toLowerCase())
this._form.appendChild(document.createElement('br'));
if (this.options.onFormCustomization)
this.options.onFormCustomization(this, this._form);
addText('Before', this.options.okControl || this.options.cancelControl);
this.createControl('ok', this._boundSubmitHandler);
addText('Between', this.options.okControl && this.options.cancelControl);
this.createControl('cancel', this._boundCancelHandler, 'editor_cancel');
addText('After', this.options.okControl || this.options.cancelControl);
},
destroy: function() {
if (this._oldInnerHTML)
this.element.innerHTML = this._oldInnerHTML;
this.leaveEditMode();
this.unregisterListeners();
},
enterEditMode: function(e) {
if (this._saving || this._editing) return;
this._editing = true;
this.triggerCallback('onEnterEditMode');
if (this.options.externalControl)
this.options.externalControl.hide();
this.element.hide();
this.createForm();
this.element.parentNode.insertBefore(this._form, this.element);
if (!this.options.loadTextURL)
this.postProcessEditField();
if (e) Event.stop(e);
},
enterHover: function(e) {
if (this.options.hoverClassName)
this.element.addClassName(this.options.hoverClassName);
if (this._saving) return;
this.triggerCallback('onEnterHover');
},
getText: function() {
return this.element.innerHTML.unescapeHTML();
},
handleAJAXFailure: function(transport) {
this.triggerCallback('onFailure', transport);
if (this._oldInnerHTML) {
this.element.innerHTML = this._oldInnerHTML;
this._oldInnerHTML = null;
}
},
handleFormCancellation: function(e) {
this.wrapUp();
if (e) Event.stop(e);
},
handleFormSubmission: function(e) {
var form = this._form;
var value = $F(this._controls.editor);
this.prepareSubmission();
var params = this.options.callback(form, value) || '';
if (Object.isString(params))
params = params.toQueryParams();
params.editorId = this.element.id;
if (this.options.htmlResponse) {
var options = Object.extend({ evalScripts: true }, this.options.ajaxOptions);
Object.extend(options, {
parameters: params,
onComplete: this._boundWrapperHandler,
onFailure: this._boundFailureHandler
});
new Ajax.Updater({ success: this.element }, this.url, options);
} else {
var options = Object.extend({ method: 'get' }, this.options.ajaxOptions);
Object.extend(options, {
parameters: params,
onComplete: this._boundWrapperHandler,
onFailure: this._boundFailureHandler
});
new Ajax.Request(this.url, options);
}
if (e) Event.stop(e);
},
leaveEditMode: function() {
this.element.removeClassName(this.options.savingClassName);
this.removeForm();
this.leaveHover();
this.element.style.backgroundColor = this._originalBackground;
this.element.show();
if (this.options.externalControl)
this.options.externalControl.show();
this._saving = false;
this._editing = false;
this._oldInnerHTML = null;
this.triggerCallback('onLeaveEditMode');
},
leaveHover: function(e) {
if (this.options.hoverClassName)
this.element.removeClassName(this.options.hoverClassName);
if (this._saving) return;
this.triggerCallback('onLeaveHover');
},
loadExternalText: function() {
this._form.addClassName(this.options.loadingClassName);
this._controls.editor.disabled = true;
var options = Object.extend({ method: 'get' }, this.options.ajaxOptions);
Object.extend(options, {
parameters: 'editorId=' + encodeURIComponent(this.element.id),
onComplete: Prototype.emptyFunction,
onSuccess: function(transport) {
this._form.removeClassName(this.options.loadingClassName);
var text = transport.responseText;
if (this.options.stripLoadedTextTags)
text = text.stripTags();
this._controls.editor.value = text;
this._controls.editor.disabled = false;
this.postProcessEditField();
}.bind(this),
onFailure: this._boundFailureHandler
});
new Ajax.Request(this.options.loadTextURL, options);
},
postProcessEditField: function() {
var fpc = this.options.fieldPostCreation;
if (fpc)
$(this._controls.editor)['focus' == fpc ? 'focus' : 'activate']();
},
prepareOptions: function() {
this.options = Object.clone(Ajax.InPlaceEditor.DefaultOptions);
Object.extend(this.options, Ajax.InPlaceEditor.DefaultCallbacks);
[this._extraDefaultOptions].flatten().compact().each(function(defs) {
Object.extend(this.options, defs);
}.bind(this));
},
prepareSubmission: function() {
this._saving = true;
this.removeForm();
this.leaveHover();
this.showSaving();
},
registerListeners: function() {
this._listeners = { };
var listener;
$H(Ajax.InPlaceEditor.Listeners).each(function(pair) {
listener = this[pair.value].bind(this);
this._listeners[pair.key] = listener;
if (!this.options.externalControlOnly)
this.element.observe(pair.key, listener);
if (this.options.externalControl)
this.options.externalControl.observe(pair.key, listener);
}.bind(this));
},
removeForm: function() {
if (!this._form) return;
this._form.remove();
this._form = null;
this._controls = { };
},
showSaving: function() {
this._oldInnerHTML = this.element.innerHTML;
this.element.innerHTML = this.options.savingText;
this.element.addClassName(this.options.savingClassName);
this.element.style.backgroundColor = this._originalBackground;
this.element.show();
},
triggerCallback: function(cbName, arg) {
if ('function' == typeof this.options[cbName]) {
this.options[cbName](this, arg);
}
},
unregisterListeners: function() {
$H(this._listeners).each(function(pair) {
if (!this.options.externalControlOnly)
this.element.stopObserving(pair.key, pair.value);
if (this.options.externalControl)
this.options.externalControl.stopObserving(pair.key, pair.value);
}.bind(this));
},
wrapUp: function(transport) {
this.leaveEditMode();
// Can't use triggerCallback due to backward compatibility: requires
// binding + direct element
this._boundComplete(transport, this.element);
}
});
Object.extend(Ajax.InPlaceEditor.prototype, {
dispose: Ajax.InPlaceEditor.prototype.destroy
});
Ajax.InPlaceCollectionEditor = Class.create(Ajax.InPlaceEditor, {
initialize: function($super, element, url, options) {
this._extraDefaultOptions = Ajax.InPlaceCollectionEditor.DefaultOptions;
$super(element, url, options);
},
createEditField: function() {
var list = document.createElement('select');
list.name = this.options.paramName;
list.size = 1;
this._controls.editor = list;
this._collection = this.options.collection || [];
if (this.options.loadCollectionURL)
this.loadCollection();
else
this.checkForExternalText();
this._form.appendChild(this._controls.editor);
},
loadCollection: function() {
this._form.addClassName(this.options.loadingClassName);
this.showLoadingText(this.options.loadingCollectionText);
var options = Object.extend({ method: 'get' }, this.options.ajaxOptions);
Object.extend(options, {
parameters: 'editorId=' + encodeURIComponent(this.element.id),
onComplete: Prototype.emptyFunction,
onSuccess: function(transport) {
var js = transport.responseText.strip();
if (!/^\[.*\]$/.test(js)) // TODO: improve sanity check
throw('Server returned an invalid collection representation.');
this._collection = eval(js);
this.checkForExternalText();
}.bind(this),
onFailure: this.onFailure
});
new Ajax.Request(this.options.loadCollectionURL, options);
},
showLoadingText: function(text) {
this._controls.editor.disabled = true;
var tempOption = this._controls.editor.firstChild;
if (!tempOption) {
tempOption = document.createElement('option');
tempOption.value = '';
this._controls.editor.appendChild(tempOption);
tempOption.selected = true;
}
tempOption.update((text || '').stripScripts().stripTags());
},
checkForExternalText: function() {
this._text = this.getText();
if (this.options.loadTextURL)
this.loadExternalText();
else
this.buildOptionList();
},
loadExternalText: function() {
this.showLoadingText(this.options.loadingText);
var options = Object.extend({ method: 'get' }, this.options.ajaxOptions);
Object.extend(options, {
parameters: 'editorId=' + encodeURIComponent(this.element.id),
onComplete: Prototype.emptyFunction,
onSuccess: function(transport) {
this._text = transport.responseText.strip();
this.buildOptionList();
}.bind(this),
onFailure: this.onFailure
});
new Ajax.Request(this.options.loadTextURL, options);
},
buildOptionList: function() {
this._form.removeClassName(this.options.loadingClassName);
this._collection = this._collection.map(function(entry) {
return 2 === entry.length ? entry : [entry, entry].flatten();
});
var marker = ('value' in this.options) ? this.options.value : this._text;
var textFound = this._collection.any(function(entry) {
return entry[0] == marker;
}.bind(this));
this._controls.editor.update('');
var option;
this._collection.each(function(entry, index) {
option = document.createElement('option');
option.value = entry[0];
option.selected = textFound ? entry[0] == marker : 0 == index;
option.appendChild(document.createTextNode(entry[1]));
this._controls.editor.appendChild(option);
}.bind(this));
this._controls.editor.disabled = false;
Field.scrollFreeActivate(this._controls.editor);
}
});
//**** DEPRECATION LAYER FOR InPlace[Collection]Editor! ****
//**** This only exists for a while, in order to let ****
//**** users adapt to the new API. Read up on the new ****
//**** API and convert your code to it ASAP! ****
Ajax.InPlaceEditor.prototype.initialize.dealWithDeprecatedOptions = function(options) {
if (!options) return;
function fallback(name, expr) {
if (name in options || expr === undefined) return;
options[name] = expr;
};
fallback('cancelControl', (options.cancelLink ? 'link' : (options.cancelButton ? 'button' :
options.cancelLink == options.cancelButton == false ? false : undefined)));
fallback('okControl', (options.okLink ? 'link' : (options.okButton ? 'button' :
options.okLink == options.okButton == false ? false : undefined)));
fallback('highlightColor', options.highlightcolor);
fallback('highlightEndColor', options.highlightendcolor);
};
Object.extend(Ajax.InPlaceEditor, {
DefaultOptions: {
ajaxOptions: { },
autoRows: 3, // Use when multi-line w/ rows == 1
cancelControl: 'link', // 'link'|'button'|false
cancelText: 'cancel',
clickToEditText: 'Click to edit',
externalControl: null, // id|elt
externalControlOnly: false,
fieldPostCreation: 'activate', // 'activate'|'focus'|false
formClassName: 'inplaceeditor-form',
formId: null, // id|elt
highlightColor: '#ffff99',
highlightEndColor: '#ffffff',
hoverClassName: '',
htmlResponse: true,
loadingClassName: 'inplaceeditor-loading',
loadingText: 'Loading...',
okControl: 'button', // 'link'|'button'|false
okText: 'ok',
paramName: 'value',
rows: 1, // If 1 and multi-line, uses autoRows
savingClassName: 'inplaceeditor-saving',
savingText: 'Saving...',
size: 0,
stripLoadedTextTags: false,
submitOnBlur: false,
textAfterControls: '',
textBeforeControls: '',
textBetweenControls: ''
},
DefaultCallbacks: {
callback: function(form) {
return Form.serialize(form);
},
onComplete: function(transport, element) {
// For backward compatibility, this one is bound to the IPE, and passes
// the element directly. It was too often customized, so we don't break it.
new Effect.Highlight(element, {
startcolor: this.options.highlightColor, keepBackgroundImage: true });
},
onEnterEditMode: null,
onEnterHover: function(ipe) {
ipe.element.style.backgroundColor = ipe.options.highlightColor;
if (ipe._effect)
ipe._effect.cancel();
},
onFailure: function(transport, ipe) {
alert('Error communication with the server: ' + transport.responseText.stripTags());
},
onFormCustomization: null, // Takes the IPE and its generated form, after editor, before controls.
onLeaveEditMode: null,
onLeaveHover: function(ipe) {
ipe._effect = new Effect.Highlight(ipe.element, {
startcolor: ipe.options.highlightColor, endcolor: ipe.options.highlightEndColor,
restorecolor: ipe._originalBackground, keepBackgroundImage: true
});
}
},
Listeners: {
click: 'enterEditMode',
keydown: 'checkForEscapeOrReturn',
mouseover: 'enterHover',
mouseout: 'leaveHover'
}
});
Ajax.InPlaceCollectionEditor.DefaultOptions = {
loadingCollectionText: 'Loading options...'
};
// Delayed observer, like Form.Element.Observer,
// but waits for delay after last key input
// Ideal for live-search fields
Form.Element.DelayedObserver = Class.create({
initialize: function(element, delay, callback) {
this.delay = delay || 0.5;
this.element = $(element);
this.callback = callback;
this.timer = null;
this.lastValue = $F(this.element);
Event.observe(this.element,'keyup',this.delayedListener.bindAsEventListener(this));
},
delayedListener: function(event) {
if(this.lastValue == $F(this.element)) return;
if(this.timer) clearTimeout(this.timer);
this.timer = setTimeout(this.onTimerEvent.bind(this), this.delay * 1000);
this.lastValue = $F(this.element);
},
onTimerEvent: function() {
this.timer = null;
this.callback(this.element, $F(this.element));
}
});

View File

@ -1,973 +0,0 @@
// Copyright (c) 2005-2008 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
// (c) 2005-2008 Sammi Williams (http://www.oriontransfer.co.nz, sammi@oriontransfer.co.nz)
//
// script.aculo.us is freely distributable under the terms of an MIT-style license.
// For details, see the script.aculo.us web site: http://script.aculo.us/
if(Object.isUndefined(Effect))
throw("dragdrop.js requires including script.aculo.us' effects.js library");
var Droppables = {
drops: [],
remove: function(element) {
this.drops = this.drops.reject(function(d) { return d.element==$(element) });
},
add: function(element) {
element = $(element);
var options = Object.extend({
greedy: true,
hoverclass: null,
tree: false
}, arguments[1] || { });
// cache containers
if(options.containment) {
options._containers = [];
var containment = options.containment;
if(Object.isArray(containment)) {
containment.each( function(c) { options._containers.push($(c)) });
} else {
options._containers.push($(containment));
}
}
if(options.accept) options.accept = [options.accept].flatten();
Element.makePositioned(element); // fix IE
options.element = element;
this.drops.push(options);
},
findDeepestChild: function(drops) {
deepest = drops[0];
for (i = 1; i < drops.length; ++i)
if (Element.isParent(drops[i].element, deepest.element))
deepest = drops[i];
return deepest;
},
isContained: function(element, drop) {
var containmentNode;
if(drop.tree) {
containmentNode = element.treeNode;
} else {
containmentNode = element.parentNode;
}
return drop._containers.detect(function(c) { return containmentNode == c });
},
isAffected: function(point, element, drop) {
return (
(drop.element!=element) &&
((!drop._containers) ||
this.isContained(element, drop)) &&
((!drop.accept) ||
(Element.classNames(element).detect(
function(v) { return drop.accept.include(v) } ) )) &&
Position.within(drop.element, point[0], point[1]) );
},
deactivate: function(drop) {
if(drop.hoverclass)
Element.removeClassName(drop.element, drop.hoverclass);
this.last_active = null;
},
activate: function(drop) {
if(drop.hoverclass)
Element.addClassName(drop.element, drop.hoverclass);
this.last_active = drop;
},
show: function(point, element) {
if(!this.drops.length) return;
var drop, affected = [];
this.drops.each( function(drop) {
if(Droppables.isAffected(point, element, drop))
affected.push(drop);
});
if(affected.length>0)
drop = Droppables.findDeepestChild(affected);
if(this.last_active && this.last_active != drop) this.deactivate(this.last_active);
if (drop) {
Position.within(drop.element, point[0], point[1]);
if(drop.onHover)
drop.onHover(element, drop.element, Position.overlap(drop.overlap, drop.element));
if (drop != this.last_active) Droppables.activate(drop);
}
},
fire: function(event, element) {
if(!this.last_active) return;
Position.prepare();
if (this.isAffected([Event.pointerX(event), Event.pointerY(event)], element, this.last_active))
if (this.last_active.onDrop) {
this.last_active.onDrop(element, this.last_active.element, event);
return true;
}
},
reset: function() {
if(this.last_active)
this.deactivate(this.last_active);
}
};
var Draggables = {
drags: [],
observers: [],
register: function(draggable) {
if(this.drags.length == 0) {
this.eventMouseUp = this.endDrag.bindAsEventListener(this);
this.eventMouseMove = this.updateDrag.bindAsEventListener(this);
this.eventKeypress = this.keyPress.bindAsEventListener(this);
Event.observe(document, "mouseup", this.eventMouseUp);
Event.observe(document, "mousemove", this.eventMouseMove);
Event.observe(document, "keypress", this.eventKeypress);
}
this.drags.push(draggable);
},
unregister: function(draggable) {
this.drags = this.drags.reject(function(d) { return d==draggable });
if(this.drags.length == 0) {
Event.stopObserving(document, "mouseup", this.eventMouseUp);
Event.stopObserving(document, "mousemove", this.eventMouseMove);
Event.stopObserving(document, "keypress", this.eventKeypress);
}
},
activate: function(draggable) {
if(draggable.options.delay) {
this._timeout = setTimeout(function() {
Draggables._timeout = null;
window.focus();
Draggables.activeDraggable = draggable;
}.bind(this), draggable.options.delay);
} else {
window.focus(); // allows keypress events if window isn't currently focused, fails for Safari
this.activeDraggable = draggable;
}
},
deactivate: function() {
this.activeDraggable = null;
},
updateDrag: function(event) {
if(!this.activeDraggable) return;
var pointer = [Event.pointerX(event), Event.pointerY(event)];
// Mozilla-based browsers fire successive mousemove events with
// the same coordinates, prevent needless redrawing (moz bug?)
if(this._lastPointer && (this._lastPointer.inspect() == pointer.inspect())) return;
this._lastPointer = pointer;
this.activeDraggable.updateDrag(event, pointer);
},
endDrag: function(event) {
if(this._timeout) {
clearTimeout(this._timeout);
this._timeout = null;
}
if(!this.activeDraggable) return;
this._lastPointer = null;
this.activeDraggable.endDrag(event);
this.activeDraggable = null;
},
keyPress: function(event) {
if(this.activeDraggable)
this.activeDraggable.keyPress(event);
},
addObserver: function(observer) {
this.observers.push(observer);
this._cacheObserverCallbacks();
},
removeObserver: function(element) { // element instead of observer fixes mem leaks
this.observers = this.observers.reject( function(o) { return o.element==element });
this._cacheObserverCallbacks();
},
notify: function(eventName, draggable, event) { // 'onStart', 'onEnd', 'onDrag'
if(this[eventName+'Count'] > 0)
this.observers.each( function(o) {
if(o[eventName]) o[eventName](eventName, draggable, event);
});
if(draggable.options[eventName]) draggable.options[eventName](draggable, event);
},
_cacheObserverCallbacks: function() {
['onStart','onEnd','onDrag'].each( function(eventName) {
Draggables[eventName+'Count'] = Draggables.observers.select(
function(o) { return o[eventName]; }
).length;
});
}
};
/*--------------------------------------------------------------------------*/
var Draggable = Class.create({
initialize: function(element) {
var defaults = {
handle: false,
reverteffect: function(element, top_offset, left_offset) {
var dur = Math.sqrt(Math.abs(top_offset^2)+Math.abs(left_offset^2))*0.02;
new Effect.Move(element, { x: -left_offset, y: -top_offset, duration: dur,
queue: {scope:'_draggable', position:'end'}
});
},
endeffect: function(element) {
var toOpacity = Object.isNumber(element._opacity) ? element._opacity : 1.0;
new Effect.Opacity(element, {duration:0.2, from:0.7, to:toOpacity,
queue: {scope:'_draggable', position:'end'},
afterFinish: function(){
Draggable._dragging[element] = false
}
});
},
zindex: 1000,
revert: false,
quiet: false,
scroll: false,
scrollSensitivity: 20,
scrollSpeed: 15,
snap: false, // false, or xy or [x,y] or function(x,y){ return [x,y] }
delay: 0
};
if(!arguments[1] || Object.isUndefined(arguments[1].endeffect))
Object.extend(defaults, {
starteffect: function(element) {
element._opacity = Element.getOpacity(element);
Draggable._dragging[element] = true;
new Effect.Opacity(element, {duration:0.2, from:element._opacity, to:0.7});
}
});
var options = Object.extend(defaults, arguments[1] || { });
this.element = $(element);
if(options.handle && Object.isString(options.handle))
this.handle = this.element.down('.'+options.handle, 0);
if(!this.handle) this.handle = $(options.handle);
if(!this.handle) this.handle = this.element;
if(options.scroll && !options.scroll.scrollTo && !options.scroll.outerHTML) {
options.scroll = $(options.scroll);
this._isScrollChild = Element.childOf(this.element, options.scroll);
}
Element.makePositioned(this.element); // fix IE
this.options = options;
this.dragging = false;
this.eventMouseDown = this.initDrag.bindAsEventListener(this);
Event.observe(this.handle, "mousedown", this.eventMouseDown);
Draggables.register(this);
},
destroy: function() {
Event.stopObserving(this.handle, "mousedown", this.eventMouseDown);
Draggables.unregister(this);
},
currentDelta: function() {
return([
parseInt(Element.getStyle(this.element,'left') || '0'),
parseInt(Element.getStyle(this.element,'top') || '0')]);
},
initDrag: function(event) {
if(!Object.isUndefined(Draggable._dragging[this.element]) &&
Draggable._dragging[this.element]) return;
if(Event.isLeftClick(event)) {
// abort on form elements, fixes a Firefox issue
var src = Event.element(event);
if((tag_name = src.tagName.toUpperCase()) && (
tag_name=='INPUT' ||
tag_name=='SELECT' ||
tag_name=='OPTION' ||
tag_name=='BUTTON' ||
tag_name=='TEXTAREA')) return;
var pointer = [Event.pointerX(event), Event.pointerY(event)];
var pos = Position.cumulativeOffset(this.element);
this.offset = [0,1].map( function(i) { return (pointer[i] - pos[i]) });
Draggables.activate(this);
Event.stop(event);
}
},
startDrag: function(event) {
this.dragging = true;
if(!this.delta)
this.delta = this.currentDelta();
if(this.options.zindex) {
this.originalZ = parseInt(Element.getStyle(this.element,'z-index') || 0);
this.element.style.zIndex = this.options.zindex;
}
if(this.options.ghosting) {
this._clone = this.element.cloneNode(true);
this._originallyAbsolute = (this.element.getStyle('position') == 'absolute');
if (!this._originallyAbsolute)
Position.absolutize(this.element);
this.element.parentNode.insertBefore(this._clone, this.element);
}
if(this.options.scroll) {
if (this.options.scroll == window) {
var where = this._getWindowScroll(this.options.scroll);
this.originalScrollLeft = where.left;
this.originalScrollTop = where.top;
} else {
this.originalScrollLeft = this.options.scroll.scrollLeft;
this.originalScrollTop = this.options.scroll.scrollTop;
}
}
Draggables.notify('onStart', this, event);
if(this.options.starteffect) this.options.starteffect(this.element);
},
updateDrag: function(event, pointer) {
if(!this.dragging) this.startDrag(event);
if(!this.options.quiet){
Position.prepare();
Droppables.show(pointer, this.element);
}
Draggables.notify('onDrag', this, event);
this.draw(pointer);
if(this.options.change) this.options.change(this);
if(this.options.scroll) {
this.stopScrolling();
var p;
if (this.options.scroll == window) {
with(this._getWindowScroll(this.options.scroll)) { p = [ left, top, left+width, top+height ]; }
} else {
p = Position.page(this.options.scroll);
p[0] += this.options.scroll.scrollLeft + Position.deltaX;
p[1] += this.options.scroll.scrollTop + Position.deltaY;
p.push(p[0]+this.options.scroll.offsetWidth);
p.push(p[1]+this.options.scroll.offsetHeight);
}
var speed = [0,0];
if(pointer[0] < (p[0]+this.options.scrollSensitivity)) speed[0] = pointer[0]-(p[0]+this.options.scrollSensitivity);
if(pointer[1] < (p[1]+this.options.scrollSensitivity)) speed[1] = pointer[1]-(p[1]+this.options.scrollSensitivity);
if(pointer[0] > (p[2]-this.options.scrollSensitivity)) speed[0] = pointer[0]-(p[2]-this.options.scrollSensitivity);
if(pointer[1] > (p[3]-this.options.scrollSensitivity)) speed[1] = pointer[1]-(p[3]-this.options.scrollSensitivity);
this.startScrolling(speed);
}
// fix AppleWebKit rendering
if(Prototype.Browser.WebKit) window.scrollBy(0,0);
Event.stop(event);
},
finishDrag: function(event, success) {
this.dragging = false;
if(this.options.quiet){
Position.prepare();
var pointer = [Event.pointerX(event), Event.pointerY(event)];
Droppables.show(pointer, this.element);
}
if(this.options.ghosting) {
if (!this._originallyAbsolute)
Position.relativize(this.element);
delete this._originallyAbsolute;
Element.remove(this._clone);
this._clone = null;
}
var dropped = false;
if(success) {
dropped = Droppables.fire(event, this.element);
if (!dropped) dropped = false;
}
if(dropped && this.options.onDropped) this.options.onDropped(this.element);
Draggables.notify('onEnd', this, event);
var revert = this.options.revert;
if(revert && Object.isFunction(revert)) revert = revert(this.element);
var d = this.currentDelta();
if(revert && this.options.reverteffect) {
if (dropped == 0 || revert != 'failure')
this.options.reverteffect(this.element,
d[1]-this.delta[1], d[0]-this.delta[0]);
} else {
this.delta = d;
}
if(this.options.zindex)
this.element.style.zIndex = this.originalZ;
if(this.options.endeffect)
this.options.endeffect(this.element);
Draggables.deactivate(this);
Droppables.reset();
},
keyPress: function(event) {
if(event.keyCode!=Event.KEY_ESC) return;
this.finishDrag(event, false);
Event.stop(event);
},
endDrag: function(event) {
if(!this.dragging) return;
this.stopScrolling();
this.finishDrag(event, true);
Event.stop(event);
},
draw: function(point) {
var pos = Position.cumulativeOffset(this.element);
if(this.options.ghosting) {
var r = Position.realOffset(this.element);
pos[0] += r[0] - Position.deltaX; pos[1] += r[1] - Position.deltaY;
}
var d = this.currentDelta();
pos[0] -= d[0]; pos[1] -= d[1];
if(this.options.scroll && (this.options.scroll != window && this._isScrollChild)) {
pos[0] -= this.options.scroll.scrollLeft-this.originalScrollLeft;
pos[1] -= this.options.scroll.scrollTop-this.originalScrollTop;
}
var p = [0,1].map(function(i){
return (point[i]-pos[i]-this.offset[i])
}.bind(this));
if(this.options.snap) {
if(Object.isFunction(this.options.snap)) {
p = this.options.snap(p[0],p[1],this);
} else {
if(Object.isArray(this.options.snap)) {
p = p.map( function(v, i) {
return (v/this.options.snap[i]).round()*this.options.snap[i] }.bind(this));
} else {
p = p.map( function(v) {
return (v/this.options.snap).round()*this.options.snap }.bind(this));
}
}}
var style = this.element.style;
if((!this.options.constraint) || (this.options.constraint=='horizontal'))
style.left = p[0] + "px";
if((!this.options.constraint) || (this.options.constraint=='vertical'))
style.top = p[1] + "px";
if(style.visibility=="hidden") style.visibility = ""; // fix gecko rendering
},
stopScrolling: function() {
if(this.scrollInterval) {
clearInterval(this.scrollInterval);
this.scrollInterval = null;
Draggables._lastScrollPointer = null;
}
},
startScrolling: function(speed) {
if(!(speed[0] || speed[1])) return;
this.scrollSpeed = [speed[0]*this.options.scrollSpeed,speed[1]*this.options.scrollSpeed];
this.lastScrolled = new Date();
this.scrollInterval = setInterval(this.scroll.bind(this), 10);
},
scroll: function() {
var current = new Date();
var delta = current - this.lastScrolled;
this.lastScrolled = current;
if(this.options.scroll == window) {
with (this._getWindowScroll(this.options.scroll)) {
if (this.scrollSpeed[0] || this.scrollSpeed[1]) {
var d = delta / 1000;
this.options.scroll.scrollTo( left + d*this.scrollSpeed[0], top + d*this.scrollSpeed[1] );
}
}
} else {
this.options.scroll.scrollLeft += this.scrollSpeed[0] * delta / 1000;
this.options.scroll.scrollTop += this.scrollSpeed[1] * delta / 1000;
}
Position.prepare();
Droppables.show(Draggables._lastPointer, this.element);
Draggables.notify('onDrag', this);
if (this._isScrollChild) {
Draggables._lastScrollPointer = Draggables._lastScrollPointer || $A(Draggables._lastPointer);
Draggables._lastScrollPointer[0] += this.scrollSpeed[0] * delta / 1000;
Draggables._lastScrollPointer[1] += this.scrollSpeed[1] * delta / 1000;
if (Draggables._lastScrollPointer[0] < 0)
Draggables._lastScrollPointer[0] = 0;
if (Draggables._lastScrollPointer[1] < 0)
Draggables._lastScrollPointer[1] = 0;
this.draw(Draggables._lastScrollPointer);
}
if(this.options.change) this.options.change(this);
},
_getWindowScroll: function(w) {
var T, L, W, H;
with (w.document) {
if (w.document.documentElement && documentElement.scrollTop) {
T = documentElement.scrollTop;
L = documentElement.scrollLeft;
} else if (w.document.body) {
T = body.scrollTop;
L = body.scrollLeft;
}
if (w.innerWidth) {
W = w.innerWidth;
H = w.innerHeight;
} else if (w.document.documentElement && documentElement.clientWidth) {
W = documentElement.clientWidth;
H = documentElement.clientHeight;
} else {
W = body.offsetWidth;
H = body.offsetHeight;
}
}
return { top: T, left: L, width: W, height: H };
}
});
Draggable._dragging = { };
/*--------------------------------------------------------------------------*/
var SortableObserver = Class.create({
initialize: function(element, observer) {
this.element = $(element);
this.observer = observer;
this.lastValue = Sortable.serialize(this.element);
},
onStart: function() {
this.lastValue = Sortable.serialize(this.element);
},
onEnd: function() {
Sortable.unmark();
if(this.lastValue != Sortable.serialize(this.element))
this.observer(this.element)
}
});
var Sortable = {
SERIALIZE_RULE: /^[^_\-](?:[A-Za-z0-9\-\_]*)[_](.*)$/,
sortables: { },
_findRootElement: function(element) {
while (element.tagName.toUpperCase() != "BODY") {
if(element.id && Sortable.sortables[element.id]) return element;
element = element.parentNode;
}
},
options: function(element) {
element = Sortable._findRootElement($(element));
if(!element) return;
return Sortable.sortables[element.id];
},
destroy: function(element){
element = $(element);
var s = Sortable.sortables[element.id];
if(s) {
Draggables.removeObserver(s.element);
s.droppables.each(function(d){ Droppables.remove(d) });
s.draggables.invoke('destroy');
delete Sortable.sortables[s.element.id];
}
},
create: function(element) {
element = $(element);
var options = Object.extend({
element: element,
tag: 'li', // assumes li children, override with tag: 'tagname'
dropOnEmpty: false,
tree: false,
treeTag: 'ul',
overlap: 'vertical', // one of 'vertical', 'horizontal'
constraint: 'vertical', // one of 'vertical', 'horizontal', false
containment: element, // also takes array of elements (or id's); or false
handle: false, // or a CSS class
only: false,
delay: 0,
hoverclass: null,
ghosting: false,
quiet: false,
scroll: false,
scrollSensitivity: 20,
scrollSpeed: 15,
format: this.SERIALIZE_RULE,
// these take arrays of elements or ids and can be
// used for better initialization performance
elements: false,
handles: false,
onChange: Prototype.emptyFunction,
onUpdate: Prototype.emptyFunction
}, arguments[1] || { });
// clear any old sortable with same element
this.destroy(element);
// build options for the draggables
var options_for_draggable = {
revert: true,
quiet: options.quiet,
scroll: options.scroll,
scrollSpeed: options.scrollSpeed,
scrollSensitivity: options.scrollSensitivity,
delay: options.delay,
ghosting: options.ghosting,
constraint: options.constraint,
handle: options.handle };
if(options.starteffect)
options_for_draggable.starteffect = options.starteffect;
if(options.reverteffect)
options_for_draggable.reverteffect = options.reverteffect;
else
if(options.ghosting) options_for_draggable.reverteffect = function(element) {
element.style.top = 0;
element.style.left = 0;
};
if(options.endeffect)
options_for_draggable.endeffect = options.endeffect;
if(options.zindex)
options_for_draggable.zindex = options.zindex;
// build options for the droppables
var options_for_droppable = {
overlap: options.overlap,
containment: options.containment,
tree: options.tree,
hoverclass: options.hoverclass,
onHover: Sortable.onHover
};
var options_for_tree = {
onHover: Sortable.onEmptyHover,
overlap: options.overlap,
containment: options.containment,
hoverclass: options.hoverclass
};
// fix for gecko engine
Element.cleanWhitespace(element);
options.draggables = [];
options.droppables = [];
// drop on empty handling
if(options.dropOnEmpty || options.tree) {
Droppables.add(element, options_for_tree);
options.droppables.push(element);
}
(options.elements || this.findElements(element, options) || []).each( function(e,i) {
var handle = options.handles ? $(options.handles[i]) :
(options.handle ? $(e).select('.' + options.handle)[0] : e);
options.draggables.push(
new Draggable(e, Object.extend(options_for_draggable, { handle: handle })));
Droppables.add(e, options_for_droppable);
if(options.tree) e.treeNode = element;
options.droppables.push(e);
});
if(options.tree) {
(Sortable.findTreeElements(element, options) || []).each( function(e) {
Droppables.add(e, options_for_tree);
e.treeNode = element;
options.droppables.push(e);
});
}
// keep reference
this.sortables[element.id] = options;
// for onupdate
Draggables.addObserver(new SortableObserver(element, options.onUpdate));
},
// return all suitable-for-sortable elements in a guaranteed order
findElements: function(element, options) {
return Element.findChildren(
element, options.only, options.tree ? true : false, options.tag);
},
findTreeElements: function(element, options) {
return Element.findChildren(
element, options.only, options.tree ? true : false, options.treeTag);
},
onHover: function(element, dropon, overlap) {
if(Element.isParent(dropon, element)) return;
if(overlap > .33 && overlap < .66 && Sortable.options(dropon).tree) {
return;
} else if(overlap>0.5) {
Sortable.mark(dropon, 'before');
if(dropon.previousSibling != element) {
var oldParentNode = element.parentNode;
element.style.visibility = "hidden"; // fix gecko rendering
dropon.parentNode.insertBefore(element, dropon);
if(dropon.parentNode!=oldParentNode)
Sortable.options(oldParentNode).onChange(element);
Sortable.options(dropon.parentNode).onChange(element);
}
} else {
Sortable.mark(dropon, 'after');
var nextElement = dropon.nextSibling || null;
if(nextElement != element) {
var oldParentNode = element.parentNode;
element.style.visibility = "hidden"; // fix gecko rendering
dropon.parentNode.insertBefore(element, nextElement);
if(dropon.parentNode!=oldParentNode)
Sortable.options(oldParentNode).onChange(element);
Sortable.options(dropon.parentNode).onChange(element);
}
}
},
onEmptyHover: function(element, dropon, overlap) {
var oldParentNode = element.parentNode;
var droponOptions = Sortable.options(dropon);
if(!Element.isParent(dropon, element)) {
var index;
var children = Sortable.findElements(dropon, {tag: droponOptions.tag, only: droponOptions.only});
var child = null;
if(children) {
var offset = Element.offsetSize(dropon, droponOptions.overlap) * (1.0 - overlap);
for (index = 0; index < children.length; index += 1) {
if (offset - Element.offsetSize (children[index], droponOptions.overlap) >= 0) {
offset -= Element.offsetSize (children[index], droponOptions.overlap);
} else if (offset - (Element.offsetSize (children[index], droponOptions.overlap) / 2) >= 0) {
child = index + 1 < children.length ? children[index + 1] : null;
break;
} else {
child = children[index];
break;
}
}
}
dropon.insertBefore(element, child);
Sortable.options(oldParentNode).onChange(element);
droponOptions.onChange(element);
}
},
unmark: function() {
if(Sortable._marker) Sortable._marker.hide();
},
mark: function(dropon, position) {
// mark on ghosting only
var sortable = Sortable.options(dropon.parentNode);
if(sortable && !sortable.ghosting) return;
if(!Sortable._marker) {
Sortable._marker =
($('dropmarker') || Element.extend(document.createElement('DIV'))).
hide().addClassName('dropmarker').setStyle({position:'absolute'});
document.getElementsByTagName("body").item(0).appendChild(Sortable._marker);
}
var offsets = Position.cumulativeOffset(dropon);
Sortable._marker.setStyle({left: offsets[0]+'px', top: offsets[1] + 'px'});
if(position=='after')
if(sortable.overlap == 'horizontal')
Sortable._marker.setStyle({left: (offsets[0]+dropon.clientWidth) + 'px'});
else
Sortable._marker.setStyle({top: (offsets[1]+dropon.clientHeight) + 'px'});
Sortable._marker.show();
},
_tree: function(element, options, parent) {
var children = Sortable.findElements(element, options) || [];
for (var i = 0; i < children.length; ++i) {
var match = children[i].id.match(options.format);
if (!match) continue;
var child = {
id: encodeURIComponent(match ? match[1] : null),
element: element,
parent: parent,
children: [],
position: parent.children.length,
container: $(children[i]).down(options.treeTag)
};
/* Get the element containing the children and recurse over it */
if (child.container)
this._tree(child.container, options, child);
parent.children.push (child);
}
return parent;
},
tree: function(element) {
element = $(element);
var sortableOptions = this.options(element);
var options = Object.extend({
tag: sortableOptions.tag,
treeTag: sortableOptions.treeTag,
only: sortableOptions.only,
name: element.id,
format: sortableOptions.format
}, arguments[1] || { });
var root = {
id: null,
parent: null,
children: [],
container: element,
position: 0
};
return Sortable._tree(element, options, root);
},
/* Construct a [i] index for a particular node */
_constructIndex: function(node) {
var index = '';
do {
if (node.id) index = '[' + node.position + ']' + index;
} while ((node = node.parent) != null);
return index;
},
sequence: function(element) {
element = $(element);
var options = Object.extend(this.options(element), arguments[1] || { });
return $(this.findElements(element, options) || []).map( function(item) {
return item.id.match(options.format) ? item.id.match(options.format)[1] : '';
});
},
setSequence: function(element, new_sequence) {
element = $(element);
var options = Object.extend(this.options(element), arguments[2] || { });
var nodeMap = { };
this.findElements(element, options).each( function(n) {
if (n.id.match(options.format))
nodeMap[n.id.match(options.format)[1]] = [n, n.parentNode];
n.parentNode.removeChild(n);
});
new_sequence.each(function(ident) {
var n = nodeMap[ident];
if (n) {
n[1].appendChild(n[0]);
delete nodeMap[ident];
}
});
},
serialize: function(element) {
element = $(element);
var options = Object.extend(Sortable.options(element), arguments[1] || { });
var name = encodeURIComponent(
(arguments[1] && arguments[1].name) ? arguments[1].name : element.id);
if (options.tree) {
return Sortable.tree(element, arguments[1]).children.map( function (item) {
return [name + Sortable._constructIndex(item) + "[id]=" +
encodeURIComponent(item.id)].concat(item.children.map(arguments.callee));
}).flatten().join('&');
} else {
return Sortable.sequence(element, arguments[1]).map( function(item) {
return name + "[]=" + encodeURIComponent(item);
}).join('&');
}
}
};
// Returns true if child is contained within element
Element.isParent = function(child, element) {
if (!child.parentNode || child == element) return false;
if (child.parentNode == element) return true;
return Element.isParent(child.parentNode, element);
};
Element.findChildren = function(element, only, recursive, tagName) {
if(!element.hasChildNodes()) return null;
tagName = tagName.toUpperCase();
if(only) only = [only].flatten();
var elements = [];
$A(element.childNodes).each( function(e) {
if(e.tagName && e.tagName.toUpperCase()==tagName &&
(!only || (Element.classNames(e).detect(function(v) { return only.include(v) }))))
elements.push(e);
if(recursive) {
var grandchildren = Element.findChildren(e, only, recursive, tagName);
if(grandchildren) elements.push(grandchildren);
}
});
return (elements.length>0 ? elements.flatten() : []);
};
Element.offsetSize = function (element, type) {
return element['offset' + ((type=='vertical' || type=='height') ? 'Height' : 'Width')];
};

File diff suppressed because it is too large Load Diff

View File

@ -1,9 +0,0 @@
.galleria{list-style:none;width:200px}
.galleria li{display:block;width:80px;height:80px;overflow:hidden;float:left;margin:0 10px 10px 0}
.galleria li a{display:none}
.galleria li div{position:absolute;display:none;top:0;left:180px}
.galleria li div img{cursor:pointer}
.galleria li.active div img,.galleria li.active div{display:block}
.galleria li img.thumb{cursor:pointer;top:auto;left:auto;display:block;width:auto;height:auto}
.galleria li .caption{display:block;padding-top:.5em}
* html .galleria li div span{width:400px} /* MSIE bug */

View File

@ -1,532 +0,0 @@
/**
* Galleria (http://monc.se/kitchen)
*
* Galleria is a javascript image gallery written in jQuery.
* It loads the images one by one from an unordered list and displays thumbnails when each image is loaded.
* It will create thumbnails for you if you choose so, scaled or unscaled,
* centered and cropped inside a fixed thumbnail box defined by CSS.
*
* The core of Galleria lies in it's smart preloading behaviour, snappiness and the fresh absence
* of obtrusive design elements. Use it as a foundation for your custom styled image gallery.
*
* MAJOR CHANGES v.FROM 0.9
* Galleria now features a useful history extension, enabling back button and bookmarking for each image.
* The main image is no longer stored inside each list item, instead it is placed inside a container
* onImage and onThumb functions lets you customize the behaviours of the images on the site
*
* Tested in Safari 3, Firefox 2, MSIE 6, MSIE 7, Opera 9
*
* Version 1.0
* Februari 21, 2008
*
* Copyright (c) 2008 David Hellsing (http://monc.se)
* Licensed under the GPL licenses.
* http://www.gnu.org/licenses/gpl.txt
**/
(function($){
var $$;
/**
*
* @desc Convert images from a simple html <ul> into a thumbnail gallery
* @author David Hellsing
* @version 1.0
*
* @name Galleria
* @type jQuery
*
* @cat plugins/Media
*
* @example $('ul.gallery').galleria({options});
* @desc Create a a gallery from an unordered list of images with thumbnails
* @options
* insert: (selector string) by default, Galleria will create a container div before your ul that holds the image.
* You can, however, specify a selector where the image will be placed instead (f.ex '#main_img')
* history: Boolean for setting the history object in action with enabled back button, bookmarking etc.
* onImage: (function) a function that gets fired when the image is displayed and brings the jQuery image object.
* You can use it to add click functionality and effects.
* f.ex onImage(image) { image.css('display','none').fadeIn(); } will fadeIn each image that is displayed
* onThumb: (function) a function that gets fired when the thumbnail is displayed and brings the jQuery thumb object.
* Works the same as onImage except it targets the thumbnail after it's loaded.
*
**/
$$ = $.fn.galleria = function($options) {
// check for basic CSS support
if (!$$.hasCSS()) { return false; }
// init the modified history object
$.historyInit($$.onPageLoad);
// set default options
var $defaults = {
insert : '.galleria_container',
history : true,
clickNext : true,
onImage : function(image,caption,thumb) {},
onThumb : function(thumb) {}
};
// extend the options
var $opts = $.extend($defaults, $options);
// bring the options to the galleria object
for (var i in $opts) {
if (i) {
$.galleria[i] = $opts[i];
}
}
// if no insert selector, create a new division and insert it before the ul
var _insert = ( $($opts.insert).is($opts.insert) ) ?
$($opts.insert) :
jQuery(document.createElement('div')).insertBefore(this);
// create a wrapping div for the image
var _div = $(document.createElement('div')).addClass('galleria_wrapper');
// create a caption span
var _span = $(document.createElement('span')).addClass('caption');
// inject the wrapper in in the insert selector
_insert.addClass('galleria_container').append(_div).append(_span);
//-------------
return this.each(function(){
// add the Galleria class
$(this).addClass('galleria');
// loop through list
$(this).children('li').each(function(i) {
// bring the scope
var _container = $(this);
// build element specific options
var _o = $.meta ? $.extend({}, $opts, _container.data()) : $opts;
// remove the clickNext if image is only child
_o.clickNext = $(this).is(':only-child') ? false : _o.clickNext;
// try to fetch an anchor
var _a = $(this).find('a').is('a') ? $(this).find('a') : false;
// reference the original image as a variable and hide it
var _img = $(this).children('img').css('display','none');
// extract the original source
var _src = _a ? _a.attr('href') : _img.attr('src');
// find a title
var _title = _a ? _a.attr('title') : _img.attr('title');
// create loader image
var _loader = new Image();
// check url and activate container if match
if (_o.history && (window.location.hash && window.location.hash.replace(/\#/,'') == _src)) {
_container.siblings('.active').removeClass('active');
_container.addClass('active');
}
// begin loader
$(_loader).load(function () {
// try to bring the alt
$(this).attr('alt',_img.attr('alt'));
//-----------------------------------------------------------------
// the image is loaded, let's create the thumbnail
var _thumb = _a ?
_a.find('img').addClass('thumb noscale').css('display','none') :
_img.clone(true).addClass('thumb').css('display','none');
if (_a) { _a.replaceWith(_thumb); }
if (!_thumb.hasClass('noscale')) { // scaled tumbnails!
var w = Math.ceil( _img.width() / _img.height() * _container.height() );
var h = Math.ceil( _img.height() / _img.width() * _container.width() );
if (w < h) {
_thumb.css({ height: 'auto', width: _container.width(), marginTop: -(h-_container.height())/2 });
} else {
_thumb.css({ width: 'auto', height: _container.height(), marginLeft: -(w-_container.width())/2 });
}
} else { // Center thumbnails.
// a tiny timer fixed the width/height
window.setTimeout(function() {
_thumb.css({
marginLeft: -( _thumb.width() - _container.width() )/2,
marginTop: -( _thumb.height() - _container.height() )/2
});
}, 1);
}
// add the rel attribute
_thumb.attr('rel',_src);
// add the title attribute
_thumb.attr('title',_title);
// add the click functionality to the _thumb
_thumb.click(function() {
$.galleria.activate(_src);
});
// hover classes for IE6
_thumb.hover(
function() { $(this).addClass('hover'); },
function() { $(this).removeClass('hover'); }
);
_container.hover(
function() { _container.addClass('hover'); },
function() { _container.removeClass('hover'); }
);
// prepend the thumbnail in the container
_container.prepend(_thumb);
// show the thumbnail
_thumb.css('display','block');
// call the onThumb function
_o.onThumb(jQuery(_thumb));
// check active class and activate image if match
if (_container.hasClass('active')) {
$.galleria.activate(_src);
//_span.text(_title);
}
//-----------------------------------------------------------------
// finally delete the original image
_img.remove();
}).error(function () {
// Error handling
_container.html('<span class="error" style="color:red">Error loading image: '+_src+'</span>');
}).attr('src', _src);
});
});
};
/**
*
* @name NextSelector
*
* @desc Returns the sibling sibling, or the first one
*
**/
$$.nextSelector = function(selector) {
return $(selector).is(':last-child') ?
$(selector).siblings(':first-child') :
$(selector).next();
};
/**
*
* @name previousSelector
*
* @desc Returns the previous sibling, or the last one
*
**/
$$.previousSelector = function(selector) {
return $(selector).is(':first-child') ?
$(selector).siblings(':last-child') :
$(selector).prev();
};
/**
*
* @name hasCSS
*
* @desc Checks for CSS support and returns a boolean value
*
**/
$$.hasCSS = function() {
$('body').append(
$(document.createElement('div')).attr('id','css_test').css({ width:'1px', height:'1px', display:'none' })
);
var _v = ($('#css_test').width() != 1) ? false : true;
$('#css_test').remove();
return _v;
};
/**
*
* @name onPageLoad
*
* @desc The function that displays the image and alters the active classes
*
* Note: This function gets called when:
* 1. after calling $.historyInit();
* 2. after calling $.historyLoad();
* 3. after pushing "Go Back" button of a browser
*
**/
$$.onPageLoad = function(_src) {
// get the wrapper
var _wrapper = $('.galleria_wrapper');
// get the thumb
var _thumb = $('.galleria img[rel="'+_src+'"]');
if (_src) {
// new hash location
if ($.galleria.history) {
window.location = window.location.href.replace(/\#.*/,'') + '#' + _src;
}
// alter the active classes
_thumb.parents('li').siblings('.active').removeClass('active');
_thumb.parents('li').addClass('active');
// define a new image
var _img = $(new Image()).attr('src',_src).addClass('replaced');
// empty the wrapper and insert the new image
_wrapper.empty().append(_img);
// insert the caption
_wrapper.siblings('.caption').text(_thumb.attr('title'));
// fire the onImage function to customize the loaded image's features
$.galleria.onImage(_img,_wrapper.siblings('.caption'),_thumb);
// add clickable image helper
if($.galleria.clickNext) {
_img.css('cursor','pointer').click(function() { $.galleria.next(); });
}
} else {
// clean up the container if none are active
_wrapper.siblings().andSelf().empty();
// remove active classes
$('.galleria li.active').removeClass('active');
}
// place the source in the galleria.current variable
$.galleria.current = _src;
};
/**
*
* @name jQuery.galleria
*
* @desc The global galleria object holds four constant variables and four public methods:
* $.galleria.history = a boolean for setting the history object in action with named URLs
* $.galleria.current = is the current source that's being viewed.
* $.galleria.clickNext = boolean helper for adding a clickable image that leads to the next one in line
* $.galleria.next() = displays the next image in line, returns to first image after the last.
* $.galleria.prev() = displays the previous image in line, returns to last image after the first.
* $.galleria.activate(_src) = displays an image from _src in the galleria container.
* $.galleria.onImage(image,caption) = gets fired when the image is displayed.
*
**/
$.extend({galleria : {
current : '',
onImage : function(){},
activate : function(_src) {
if ($.galleria.history) {
$.historyLoad(_src);
} else {
$$.onPageLoad(_src);
}
},
next : function() {
var _next = $($$.nextSelector($('.galleria img[rel="'+$.galleria.current+'"]').parents('li'))).find('img').attr('rel');
$.galleria.activate(_next);
},
prev : function() {
var _prev = $($$.previousSelector($('.galleria img[rel="'+$.galleria.current+'"]').parents('li'))).find('img').attr('rel');
$.galleria.activate(_prev);
}
}
});
})(jQuery);
/**
*
* History extension for jQuery
* Credits to http://www.mikage.to/
*
**/
/*
* jQuery history plugin
*
* Copyright (c) 2006 Taku Sano (Mikage Sawatari)
* Licensed under the MIT License:
* http://www.opensource.org/licenses/mit-license.php
*
* Modified by Lincoln Cooper to add Safari support and only call the callback once during initialization
* for msie when no initial hash supplied.
*/
jQuery.extend({
historyCurrentHash: undefined,
historyCallback: undefined,
historyInit: function(callback){
jQuery.historyCallback = callback;
var current_hash = location.hash;
jQuery.historyCurrentHash = current_hash;
if(jQuery.browser.msie) {
// To stop the callback firing twice during initilization if no hash present
if (jQuery.historyCurrentHash === '') {
jQuery.historyCurrentHash = '#';
}
// add hidden iframe for IE
$("body").prepend('<iframe id="jQuery_history" style="display: none;"></iframe>');
var ihistory = $("#jQuery_history")[0];
var iframe = ihistory.contentWindow.document;
iframe.open();
iframe.close();
iframe.location.hash = current_hash;
}
else if ($.browser.safari) {
// etablish back/forward stacks
jQuery.historyBackStack = [];
jQuery.historyBackStack.length = history.length;
jQuery.historyForwardStack = [];
jQuery.isFirst = true;
}
jQuery.historyCallback(current_hash.replace(/^#/, ''));
setInterval(jQuery.historyCheck, 100);
},
historyAddHistory: function(hash) {
// This makes the looping function do something
jQuery.historyBackStack.push(hash);
jQuery.historyForwardStack.length = 0; // clear forwardStack (true click occured)
this.isFirst = true;
},
historyCheck: function(){
if(jQuery.browser.msie) {
// On IE, check for location.hash of iframe
var ihistory = $("#jQuery_history")[0];
var iframe = ihistory.contentDocument || ihistory.contentWindow.document;
var current_hash = iframe.location.hash;
if(current_hash != jQuery.historyCurrentHash) {
location.hash = current_hash;
jQuery.historyCurrentHash = current_hash;
jQuery.historyCallback(current_hash.replace(/^#/, ''));
}
} else if ($.browser.safari) {
if (!jQuery.dontCheck) {
var historyDelta = history.length - jQuery.historyBackStack.length;
if (historyDelta) { // back or forward button has been pushed
jQuery.isFirst = false;
var i;
if (historyDelta < 0) { // back button has been pushed
// move items to forward stack
for (i = 0; i < Math.abs(historyDelta); i++) {
jQuery.historyForwardStack.unshift(jQuery.historyBackStack.pop());
}
} else { // forward button has been pushed
// move items to back stack
for (i = 0; i < historyDelta; i++) {
jQuery.historyBackStack.push(jQuery.historyForwardStack.shift());
}
}
var cachedHash = jQuery.historyBackStack[jQuery.historyBackStack.length - 1];
if (cachedHash !== undefined) {
jQuery.historyCurrentHash = location.hash;
jQuery.historyCallback(cachedHash);
}
} else if (jQuery.historyBackStack[jQuery.historyBackStack.length - 1] === undefined && !jQuery.isFirst) {
// back button has been pushed to beginning and URL already pointed to hash (e.g. a bookmark)
// document.URL doesn't change in Safari
if (document.URL.indexOf('#') >= 0) {
jQuery.historyCallback(document.URL.split('#')[1]);
} else {
current_hash = location.hash;
jQuery.historyCallback('');
}
jQuery.isFirst = true;
}
}
} else {
// otherwise, check for location.hash
current_hash = location.hash;
if(current_hash != jQuery.historyCurrentHash) {
jQuery.historyCurrentHash = current_hash;
jQuery.historyCallback(current_hash.replace(/^#/, ''));
}
}
},
historyLoad: function(hash){
var newhash;
if (jQuery.browser.safari) {
newhash = hash;
}
else {
newhash = '#' + hash;
location.hash = newhash;
}
jQuery.historyCurrentHash = newhash;
if(jQuery.browser.msie) {
var ihistory = $("#jQuery_history")[0];
var iframe = ihistory.contentWindow.document;
iframe.open();
iframe.close();
iframe.location.hash = newhash;
jQuery.historyCallback(hash);
}
else if (jQuery.browser.safari) {
jQuery.dontCheck = true;
// Manually keep track of the history values for Safari
this.historyAddHistory(hash);
// Wait a while before allowing checking so that Safari has time to update the "history" object
// correctly (otherwise the check loop would detect a false change in hash).
var fn = function() {jQuery.dontCheck = false;};
window.setTimeout(fn, 200);
jQuery.historyCallback(hash);
// N.B. "location.hash=" must be the last line of code for Safari as execution stops afterwards.
// By explicitly using the "location.hash" command (instead of using a variable set to "location.hash") the
// URL in the browser and the "history" object are both updated correctly.
location.hash = newhash;
}
else {
jQuery.historyCallback(hash);
}
}
});

View File

@ -1,73 +0,0 @@
GalleryView - jQuery Content Gallery Plugin
Author: Jack Anderson
Documentation: http://www.spaceforaname.com/galleryview/
Version 2.0 - 2009-05-05
----------------------------------------
Revised required HTML markup for GalleryView
Filmstrip frames are generated automatically (no need for two sets of images)
Moved majority of aesthetic styling to external CSS
Default aesthetics for gallery updated
Set GalleryView to wait until images finish loading before building itself
Added 'current' class to current filmstrip frame for user customization
Allowed for more user-defined styling in panels and filmstrip frames
Filmstrip can now be placed on left and right side of gallery, in addition to top and bottom
Panel images can now be scaled to fit within panel or zoomed & cropped to fill panel
Filmstrip images can now be scaled to fit within frame or zoomed & cropped to fill frame
Panel overlay backgrounds are now only added to those panels with overlays
'pause_on_hover' option now pauses when mouse hovers over filmstrip as well as panel
Added option to start gallery on any frame
Current frame pointer is now built with CSS and its size can be customized easily
Increased size of hitbox on panel-navigation buttons
Updated options:
- filmstrip_position
- new allowable values : 'top', 'right', 'bottom', 'left'
Removed options:
- overlay_height
- overlay_font_size
- overlay_color
- background_color
- overlay_text_color
- caption_text_color
- border
New options:
- show_panels (boolean)
- show_filmstrip (boolean)
- start_frame (integer)
- pointer_size (integer)
- panel_scale
- allowable values : 'crop', 'nocrop'
- frame_scale
- allowable values : 'crop', 'nocrop'
- frame_gap (integer)
Version 1.1 - 2009-04-05
----------------------------------------
Added feature allowing filmstrip w/o panels
Added feature allowing panels w/o filmstrip
Added feature allowing filmstrip placement above or below panels
Added new graphics for panel navigation
Anchored navigation buttons to edges of filmstrip, rather than gallery boundaries
New options:
- filmstrip_position
- allowable values : 'top', 'bottom'
- overlay_position
- allowable values : 'top', 'bottom'
Version 1.0.1 - 2009-03-30
----------------------------------------
Fixed bug allowing blank frames to display in filmstrip
Changed pointer graphic from GIF to PNG to allow for greater customization
Added 'overflow: hidden' to panels to prevent oversized content from breaking gallery
Disabled frame clicking during filmstrip animation
Changed pointer border from 4px to 2px
Version 1.0
----------------------------------------
2009-03-29 : Initial Release

View File

@ -1,19 +0,0 @@
Copyright (c) 2009 John Anderson III
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View File

@ -1,88 +0,0 @@
/*
GalleryView Stylesheet
Use the CSS rules below to modify the look of your gallery.
To create additional rules, use the markup below as a guide to GalleryView's architecture.
<div class="gallery">
<div class="panel">
<img src="path/to/image.jpg" />
<div class="panel-overlay">
...overlay content...
</div>
<div class="overlay-background"></div>
</div>
<ul class="filmstrip">
<li class="frame current">
<img src="path/to/thumbnail.jpg" />
<div class="caption">caption text</div>
</li>
<li class="frame">
<img src="path/to/thumbnail.jpg" />
<div class="caption">caption text</div>
</li>
</ul>
</div>
*/
/* GALLERY LIST */
/* IMPORTANT - Change '#photos' to the ID of your gallery list to prevent a flash of unstyled content */
#photos { visibility: hidden; }
/* GALLERY CONTAINER */
.gallery { background: #ddd; border: 1px solid #aaa; padding: 5px;}
/* LOADING BOX */
.loader { background: url(loader.gif) center center no-repeat #ddd; }
/* GALLERY PANELS */
.panel {}
/* DEFINE HEIGHT OF PANEL OVERLAY */
/* NOTE - It is best to define padding here as well so overlay and background retain identical dimensions */
.panel .panel-overlay,
.panel .overlay-background { height: 60px; padding: 0 1em; }
/* PANEL OVERLAY BACKGROUND */
.panel .overlay-background { background: #222; }
/* PANEL OVERLAY CONTENT */
.panel .panel-overlay { color: white; font-size: 0.7em; }
.panel .panel-overlay a { color: white; text-decoration: underline; font-weight: bold; }
/* FILMSTRIP */
/* 'margin' will define top/bottom margin in completed gallery */
.filmstrip { margin: 5px; }
/* FILMSTRIP FRAMES (contains both images and captions) */
.frame {}
/* WRAPPER FOR FILMSTRIP IMAGES */
.frame .img_wrap { border: 1px solid #aaa; }
/* WRAPPER FOR CURRENT FILMSTRIP IMAGE */
.frame.current .img_wrap { border-color: #000; }
/* FRAME IMAGES */
.frame img { border: none; }
/* FRAME CAPTION */
.frame .caption { font-size: 11px; text-align: center; color: #888; }
/* CURRENT FRAME CAPTION */
.frame.current .caption { color: #000; }
/* POINTER FOR CURRENT FRAME */
.pointer {
border-color: #000;
}
/* TRANSPARENT BORDER FIX FOR IE6 */
/* NOTE - DO NOT CHANGE THIS RULE */
*html .pointer {
filter: chroma(color=pink);
}

File diff suppressed because one or more lines are too long

View File

@ -1,968 +0,0 @@
/*
GalleryView - jQuery Content Gallery Plugin
Author: Jack Anderson
Version: 2.0 (May 5, 2009)
Documentation: http://www.spaceforaname.com/galleryview/
Please use this development script if you intend to make changes to the
plugin code. For production sites, please use jquery.galleryview-2.0-pack.js.
See CHANGELOG.txt for a review of changes and LICENSE.txt for the applicable
licensing information.
*/
//Global variable to check if window is already loaded
//Used for calling GalleryView after page has loaded
var window_loaded = false;
(function($){
$.fn.galleryView = function(options) {
var opts = $.extend($.fn.galleryView.defaults,options);
var id;
var iterator = 0;
var item_count = 0;
var slide_method;
var theme_path;
var paused = false;
//Element dimensions
var gallery_width;
var gallery_height;
var pointer_height;
var pointer_width;
var strip_width;
var strip_height;
var wrapper_width;
var f_frame_width;
var f_frame_height;
var frame_caption_size = 20;
var gallery_padding;
var filmstrip_margin;
var filmstrip_orientation;
//Arrays used to scale frames and panels
var frame_img_scale = new Object();
var panel_img_scale = new Object();
var img_h = new Object();
var img_w = new Object();
//Flag indicating whether to scale panel images
var scale_panel_images = true;
var panel_nav_displayed = false;
//Define jQuery objects for reuse
var j_gallery;
var j_filmstrip;
var j_frames;
var j_frame_img_wrappers;
var j_panels;
var j_pointer;
/************************************************/
/* Plugin Methods */
/************************************************/
//Transition from current item to item 'i'
function showItem(i) {
//Disable next/prev buttons until transition is complete
$('.nav-next-overlay',j_gallery).unbind('click');
$('.nav-prev-overlay',j_gallery).unbind('click');
$('.nav-next',j_gallery).unbind('click');
$('.nav-prev',j_gallery).unbind('click');
j_frames.unbind('click');
//Fade out all frames while fading in target frame
if(opts.show_filmstrip) {
j_frames.removeClass('current').find('img').stop().animate({
'opacity':opts.frame_opacity
},opts.transition_speed);
j_frames.eq(i).addClass('current').find('img').stop().animate({
'opacity':1.0
},opts.transition_speed);
}
//If the gallery has panels and the panels should fade, fade out all panels while fading in target panel
if(opts.show_panels && opts.fade_panels) {
j_panels.fadeOut(opts.transition_speed).eq(i%item_count).fadeIn(opts.transition_speed,function(){
if(!opts.show_filmstrip) {
$('.nav-prev-overlay',j_gallery).click(showPrevItem);
$('.nav-next-overlay',j_gallery).click(showNextItem);
$('.nav-prev',j_gallery).click(showPrevItem);
$('.nav-next',j_gallery).click(showNextItem);
}
});
}
//If gallery has a filmstrip, handle animation of frames
if(opts.show_filmstrip) {
//Slide either pointer or filmstrip, depending on transition method
if(slide_method=='strip') {
//Stop filmstrip if it's currently in motion
j_filmstrip.stop();
if(filmstrip_orientation=='horizontal') {
//Determine distance between pointer (eventual destination) and target frame
var distance = getPos(j_frames[i]).left - (getPos(j_pointer[0]).left+(pointer_width/2)-(f_frame_width/2));
var diststr = (distance>=0?'-=':'+=')+Math.abs(distance)+'px';
//Animate filmstrip and slide target frame under pointer
j_filmstrip.animate({
'left':diststr
},opts.transition_speed,opts.easing,function(){
//Always ensure that there are a sufficient number of hidden frames on either
//side of the filmstrip to avoid empty frames
var old_i = i;
if(i>item_count) {
i = i%item_count;
iterator = i;
j_filmstrip.css('left','-'+((f_frame_width+opts.frame_gap)*i)+'px');
} else if (i<=(item_count-strip_size)) {
i = (i%item_count)+item_count;
iterator = i;
j_filmstrip.css('left','-'+((f_frame_width+opts.frame_gap)*i)+'px');
}
//If the target frame has changed due to filmstrip shifting,
//Make sure new target frame has 'current' class and correct size/opacity settings
if(old_i != i) {
j_frames.eq(old_i).removeClass('current').find('img').css({
'opacity':opts.frame_opacity
});
j_frames.eq(i).addClass('current').find('img').css({
'opacity':1.0
});
}
if(!opts.fade_panels) {
j_panels.hide().eq(i%item_count).show();
}
//Enable navigation now that animation is complete
$('.nav-prev-overlay',j_gallery).click(showPrevItem);
$('.nav-next-overlay',j_gallery).click(showNextItem);
$('.nav-prev',j_gallery).click(showPrevItem);
$('.nav-next',j_gallery).click(showNextItem);
enableFrameClicking();
});
} else {
//Determine distance between pointer (eventual destination) and target frame
var distance = getPos(j_frames[i]).top - (getPos(j_pointer[0]).top+(pointer_height)-(f_frame_height/2));
var diststr = (distance>=0?'-=':'+=')+Math.abs(distance)+'px';
//Animate filmstrip and slide target frame under pointer
j_filmstrip.animate({
'top':diststr
},opts.transition_speed,opts.easing,function(){
//Always ensure that there are a sufficient number of hidden frames on either
//side of the filmstrip to avoid empty frames
var old_i = i;
if(i>item_count) {
i = i%item_count;
iterator = i;
j_filmstrip.css('top','-'+((f_frame_height+opts.frame_gap)*i)+'px');
} else if (i<=(item_count-strip_size)) {
i = (i%item_count)+item_count;
iterator = i;
j_filmstrip.css('top','-'+((f_frame_height+opts.frame_gap)*i)+'px');
}
//If the target frame has changed due to filmstrip shifting,
//Make sure new target frame has 'current' class and correct size/opacity settings
if(old_i != i) {
j_frames.eq(old_i).removeClass('current').find('img').css({
'opacity':opts.frame_opacity
});
j_frames.eq(i).addClass('current').find('img').css({
'opacity':1.0
});
}
if(!opts.fade_panels) {
j_panels.hide().eq(i%item_count).show();
}
//Enable navigation now that animation is complete
$('.nav-prev-overlay',j_gallery).click(showPrevItem);
$('.nav-next-overlay',j_gallery).click(showNextItem);
$('.nav-prev',j_gallery).click(showPrevItem);
$('.nav-next',j_gallery).click(showNextItem);
enableFrameClicking();
});
}
} else if(slide_method=='pointer') {
//Stop pointer if it's currently in motion
j_pointer.stop();
//Get position of target frame
var pos = getPos(j_frames[i]);
if(filmstrip_orientation=='horizontal') {
//Slide the pointer over the target frame
j_pointer.animate({
'left':(pos.left+(f_frame_width/2)-(pointer_width/2)+'px')
},opts.transition_speed,opts.easing,function(){
if(!opts.fade_panels) {
j_panels.hide().eq(i%item_count).show();
}
$('.nav-prev-overlay',j_gallery).click(showPrevItem);
$('.nav-next-overlay',j_gallery).click(showNextItem);
$('.nav-prev',j_gallery).click(showPrevItem);
$('.nav-next',j_gallery).click(showNextItem);
enableFrameClicking();
});
} else {//Slide the pointer over the target frame
j_pointer.animate({
'top':(pos.top+(f_frame_height/2)-(pointer_height)+'px')
},opts.transition_speed,opts.easing,function(){
if(!opts.fade_panels) {
j_panels.hide().eq(i%item_count).show();
}
$('.nav-prev-overlay',j_gallery).click(showPrevItem);
$('.nav-next-overlay',j_gallery).click(showNextItem);
$('.nav-prev',j_gallery).click(showPrevItem);
$('.nav-next',j_gallery).click(showNextItem);
enableFrameClicking();
});
}
}
}
};
//Find padding and border widths applied to element
//If border is non-numerical ('thin','medium', etc) set to zero
function extraWidth(el) {
if(!el) return 0;
if(el.length==0) return 0;
el = el.eq(0);
var ew = 0;
ew += getInt(el.css('paddingLeft'));
ew += getInt(el.css('paddingRight'));
ew += getInt(el.css('borderLeftWidth'));
ew += getInt(el.css('borderRightWidth'));
return ew;
}
//Find padding and border heights applied to element
//If border is non-numerical ('thin','medium', etc) set to zero
function extraHeight(el) {
if(!el) return 0;
if(el.length==0) return 0;
el = el.eq(0);
var eh = 0;
eh += getInt(el.css('paddingTop'));
eh += getInt(el.css('paddingBottom'));
eh += getInt(el.css('borderTopWidth'));
eh += getInt(el.css('borderBottomWidth'));
return eh;
}
//Halt transition timer, move to next item, restart timer
function showNextItem() {
$(document).stopTime("transition");
if(++iterator==j_frames.length) {iterator=0;}
showItem(iterator);
if(!paused) {
$(document).everyTime(opts.transition_interval,"transition",function(){
showNextItem();
});
}
};
//Halt transition timer, move to previous item, restart timer
function showPrevItem() {
$(document).stopTime("transition");
if(--iterator<0) {iterator = item_count-1;}
showItem(iterator);
if(!paused) {
$(document).everyTime(opts.transition_interval,"transition",function(){
showNextItem();
});
}
};
//Get absolute position of element in relation to top-left corner of gallery
//If el=gallery, return position of gallery within browser viewport
function getPos(el) {
var left = 0, top = 0;
var el_id = el.id;
if(el.offsetParent) {
do {
left += el.offsetLeft;
top += el.offsetTop;
} while(el = el.offsetParent);
}
//If we want the position of the gallery itself, return it
if(el_id == id) {return {'left':left,'top':top};}
//Otherwise, get position of element relative to gallery
else {
var gPos = getPos(j_gallery[0]);
var gLeft = gPos.left;
var gTop = gPos.top;
return {'left':left-gLeft,'top':top-gTop};
}
};
//Add onclick event to each frame
function enableFrameClicking() {
j_frames.each(function(i){
//If there isn't a link in this frame, set up frame to slide on click
//Frames with links will handle themselves
if($('a',this).length==0) {
$(this).click(function(){
if(iterator!=i) {
$(document).stopTime("transition");
showItem(i);
iterator = i;
if(!paused) {
$(document).everyTime(opts.transition_interval,"transition",function(){
showNextItem();
});
}
}
});
}
});
};
//Construct gallery panels from '.panel' <div>s
function buildPanels() {
//If there are panel captions, add overlay divs
j_panels.each(function(i){
if($('.panel-overlay',this).length>0) {
$(this).append('<div class="overlay-background"></div>');
}
});
if(!opts.show_filmstrip) {
//Add navigation buttons
$('<img />').addClass('nav-next').attr('src',theme_path+opts.nav_theme+'/next.gif').appendTo(j_gallery).css({
'position':'absolute',
'zIndex':'1100',
'cursor':'pointer',
'top':((opts.panel_height-22)/2)+gallery_padding+'px',
'right':'10px',
'display':'none'
}).click(showNextItem);
$('<img />').addClass('nav-prev').attr('src',theme_path+opts.nav_theme+'/prev.gif').appendTo(j_gallery).css({
'position':'absolute',
'zIndex':'1100',
'cursor':'pointer',
'top':((opts.panel_height-22)/2)+gallery_padding+'px',
'left':'10px',
'display':'none'
}).click(showPrevItem);
$('<img />').addClass('nav-next-overlay').attr('src',theme_path+opts.nav_theme+'/panel-nav-next.gif').appendTo(j_gallery).css({
'position':'absolute',
'zIndex':'1099',
'top':((opts.panel_height-22)/2)+gallery_padding-10+'px',
'right':'0',
'display':'none',
'cursor':'pointer',
'opacity':0.75
}).click(showNextItem);
$('<img />').addClass('nav-prev-overlay').attr('src',theme_path+opts.nav_theme+'/panel-nav-prev.gif').appendTo(j_gallery).css({
'position':'absolute',
'zIndex':'1099',
'top':((opts.panel_height-22)/2)+gallery_padding-10+'px',
'left':'0',
'display':'none',
'cursor':'pointer',
'opacity':0.75
}).click(showPrevItem);
}
j_panels.each(function(i){
$(this).css({
'width':(opts.panel_width-extraWidth(j_panels))+'px',
'height':(opts.panel_height-extraHeight(j_panels))+'px',
'position':'absolute',
'overflow':'hidden',
'display':'none'
});
switch(opts.filmstrip_position) {
case 'top': $(this).css({
'top':strip_height+Math.max(gallery_padding,filmstrip_margin)+'px',
'left':gallery_padding+'px'
}); break;
case 'left': $(this).css({
'top':gallery_padding+'px',
'left':strip_width+Math.max(gallery_padding,filmstrip_margin)+'px'
}); break;
default: $(this).css({'top':gallery_padding+'px','left':gallery_padding+'px'}); break;
}
});
$('.panel-overlay',j_panels).css({
'position':'absolute',
'zIndex':'999',
'width':(opts.panel_width-extraWidth($('.panel-overlay',j_panels)))+'px',
'left':'0'
});
$('.overlay-background',j_panels).css({
'position':'absolute',
'zIndex':'998',
'width':opts.panel_width+'px',
'left':'0',
'opacity':opts.overlay_opacity
});
if(opts.overlay_position=='top') {
$('.panel-overlay',j_panels).css('top',0);
$('.overlay-background',j_panels).css('top',0);
} else {
$('.panel-overlay',j_panels).css('bottom',0);
$('.overlay-background',j_panels).css('bottom',0);
}
$('.panel iframe',j_panels).css({
'width':opts.panel_width+'px',
'height':opts.panel_height+'px',
'border':'0'
});
if(scale_panel_images) {
$('img',j_panels).each(function(i){
$(this).css({
'height':panel_img_scale[i%item_count]*img_h[i%item_count],
'width':panel_img_scale[i%item_count]*img_w[i%item_count],
'position':'relative',
'top':(opts.panel_height-(panel_img_scale[i%item_count]*img_h[i%item_count]))/2+'px',
'left':(opts.panel_width-(panel_img_scale[i%item_count]*img_w[i%item_count]))/2+'px'
});
});
}
};
//Construct filmstrip from '.filmstrip' <ul>
function buildFilmstrip() {
//Add wrapper to filmstrip to hide extra frames
j_filmstrip.wrap('<div class="strip_wrapper"></div>');
if(slide_method=='strip') {
j_frames.clone().appendTo(j_filmstrip);
j_frames.clone().appendTo(j_filmstrip);
j_frames = $('li',j_filmstrip);
}
//If captions are enabled, add caption divs and fill with the image titles
if(opts.show_captions) {
j_frames.append('<div class="caption"></div>').each(function(i){
$(this).find('.caption').html($(this).find('img').attr('title'));
//$(this).find('.caption').html(i);
});
}
j_filmstrip.css({
'listStyle':'none',
'margin':'0',
'padding':'0',
'width':strip_width+'px',
'position':'absolute',
'zIndex':'900',
'top':(filmstrip_orientation=='vertical' && slide_method=='strip'?-((f_frame_height+opts.frame_gap)*iterator):0)+'px',
'left':(filmstrip_orientation=='horizontal' && slide_method=='strip'?-((f_frame_width+opts.frame_gap)*iterator):0)+'px',
'height':strip_height+'px'
});
j_frames.css({
'float':'left',
'position':'relative',
'height':f_frame_height+(opts.show_captions?frame_caption_size:0)+'px',
'width':f_frame_width+'px',
'zIndex':'901',
'padding':'0',
'cursor':'pointer'
});
switch(opts.filmstrip_position) {
case 'top': j_frames.css({
'marginBottom':filmstrip_margin+'px',
'marginRight':opts.frame_gap+'px'
}); break;
case 'bottom': j_frames.css({
'marginTop':filmstrip_margin+'px',
'marginRight':opts.frame_gap+'px'
}); break;
case 'left': j_frames.css({
'marginRight':filmstrip_margin+'px',
'marginBottom':opts.frame_gap+'px'
}); break;
case 'right': j_frames.css({
'marginLeft':filmstrip_margin+'px',
'marginBottom':opts.frame_gap+'px'
}); break;
}
$('.img_wrap',j_frames).each(function(i){
$(this).css({
'height':Math.min(opts.frame_height,img_h[i%item_count]*frame_img_scale[i%item_count])+'px',
'width':Math.min(opts.frame_width,img_w[i%item_count]*frame_img_scale[i%item_count])+'px',
'position':'relative',
'top':(opts.show_captions && opts.filmstrip_position=='top'?frame_caption_size:0)+Math.max(0,(opts.frame_height-(frame_img_scale[i%item_count]*img_h[i%item_count]))/2)+'px',
'left':Math.max(0,(opts.frame_width-(frame_img_scale[i%item_count]*img_w[i%item_count]))/2)+'px',
'overflow':'hidden'
});
});
$('img',j_frames).each(function(i){
$(this).css({
'opacity':opts.frame_opacity,
'height':img_h[i%item_count]*frame_img_scale[i%item_count]+'px',
'width':img_w[i%item_count]*frame_img_scale[i%item_count]+'px',
'position':'relative',
'top':Math.min(0,(opts.frame_height-(frame_img_scale[i%item_count]*img_h[i%item_count]))/2)+'px',
'left':Math.min(0,(opts.frame_width-(frame_img_scale[i%item_count]*img_w[i%item_count]))/2)+'px'
}).mouseover(function(){
$(this).stop().animate({'opacity':1.0},300);
}).mouseout(function(){
//Don't fade out current frame on mouseout
if(!$(this).parent().parent().hasClass('current')) $(this).stop().animate({'opacity':opts.frame_opacity},300);
});
});
$('.strip_wrapper',j_gallery).css({
'position':'absolute',
'overflow':'hidden'
});
if(filmstrip_orientation=='horizontal') {
$('.strip_wrapper',j_gallery).css({
'top':(opts.filmstrip_position=='top'?Math.max(gallery_padding,filmstrip_margin)+'px':opts.panel_height+gallery_padding+'px'),
'left':((gallery_width-wrapper_width)/2)+gallery_padding+'px',
'width':wrapper_width+'px',
'height':strip_height+'px'
});
} else {
$('.strip_wrapper',j_gallery).css({
'left':(opts.filmstrip_position=='left'?Math.max(gallery_padding,filmstrip_margin)+'px':opts.panel_width+gallery_padding+'px'),
'top':Math.max(gallery_padding,opts.frame_gap)+'px',
'width':strip_width+'px',
'height':wrapper_height+'px'
});
}
$('.caption',j_gallery).css({
'position':'absolute',
'top':(opts.filmstrip_position=='bottom'?f_frame_height:0)+'px',
'left':'0',
'margin':'0',
'width':f_frame_width+'px',
'padding':'0',
'height':frame_caption_size+'px',
'overflow':'hidden',
'lineHeight':frame_caption_size+'px'
});
var pointer = $('<div></div>');
pointer.addClass('pointer').appendTo(j_gallery).css({
'position':'absolute',
'zIndex':'1000',
'width':'0px',
'fontSize':'0px',
'lineHeight':'0%',
'borderTopWidth':pointer_height+'px',
'borderRightWidth':(pointer_width/2)+'px',
'borderBottomWidth':pointer_height+'px',
'borderLeftWidth':(pointer_width/2)+'px',
'borderStyle':'solid'
});
//For IE6, use predefined color string in place of transparent (see stylesheet)
var transColor = $.browser.msie && $.browser.version.substr(0,1)=='6' ? 'pink' : 'transparent'
if(!opts.show_panels) { pointer.css('borderColor',transColor); }
switch(opts.filmstrip_position) {
case 'top': pointer.css({
'bottom':(opts.panel_height-(pointer_height*2)+gallery_padding+filmstrip_margin)+'px',
'left':((gallery_width-wrapper_width)/2)+(slide_method=='strip'?0:((f_frame_width+opts.frame_gap)*iterator))+((f_frame_width/2)-(pointer_width/2))+gallery_padding+'px',
'borderBottomColor':transColor,
'borderRightColor':transColor,
'borderLeftColor':transColor
}); break;
case 'bottom': pointer.css({
'top':(opts.panel_height-(pointer_height*2)+gallery_padding+filmstrip_margin)+'px',
'left':((gallery_width-wrapper_width)/2)+(slide_method=='strip'?0:((f_frame_width+opts.frame_gap)*iterator))+((f_frame_width/2)-(pointer_width/2))+gallery_padding+'px',
'borderTopColor':transColor,
'borderRightColor':transColor,
'borderLeftColor':transColor
}); break;
case 'left': pointer.css({
'right':(opts.panel_width-pointer_width+gallery_padding+filmstrip_margin)+'px',
'top':(f_frame_height/2)-(pointer_height)+(slide_method=='strip'?0:((f_frame_height+opts.frame_gap)*iterator))+gallery_padding+'px',
'borderBottomColor':transColor,
'borderRightColor':transColor,
'borderTopColor':transColor
}); break;
case 'right': pointer.css({
'left':(opts.panel_width-pointer_width+gallery_padding+filmstrip_margin)+'px',
'top':(f_frame_height/2)-(pointer_height)+(slide_method=='strip'?0:((f_frame_height+opts.frame_gap)*iterator))+gallery_padding+'px',
'borderBottomColor':transColor,
'borderLeftColor':transColor,
'borderTopColor':transColor
}); break;
}
j_pointer = $('.pointer',j_gallery);
//Add navigation buttons
var navNext = $('<img />');
navNext.addClass('nav-next').attr('src',theme_path+opts.nav_theme+'/next.gif').appendTo(j_gallery).css({
'position':'absolute',
'cursor':'pointer'
}).click(showNextItem);
var navPrev = $('<img />');
navPrev.addClass('nav-prev').attr('src',theme_path+opts.nav_theme+'/prev.gif').appendTo(j_gallery).css({
'position':'absolute',
'cursor':'pointer'
}).click(showPrevItem);
if(filmstrip_orientation=='horizontal') {
navNext.css({
'top':(opts.filmstrip_position=='top'?Math.max(gallery_padding,filmstrip_margin):opts.panel_height+filmstrip_margin+gallery_padding)+((f_frame_height-22)/2)+'px',
'right':((gallery_width+(gallery_padding*2))/2)-(wrapper_width/2)-opts.frame_gap-22+'px'
});
navPrev.css({
'top':(opts.filmstrip_position=='top'?Math.max(gallery_padding,filmstrip_margin):opts.panel_height+filmstrip_margin+gallery_padding)+((f_frame_height-22)/2)+'px',
'left':((gallery_width+(gallery_padding*2))/2)-(wrapper_width/2)-opts.frame_gap-22+'px'
});
} else {
navNext.css({
'left':(opts.filmstrip_position=='left'?Math.max(gallery_padding,filmstrip_margin):opts.panel_width+filmstrip_margin+gallery_padding)+((f_frame_width-22)/2)+13+'px',
'top':wrapper_height+(Math.max(gallery_padding,opts.frame_gap)*2)+'px'
});
navPrev.css({
'left':(opts.filmstrip_position=='left'?Math.max(gallery_padding,filmstrip_margin):opts.panel_width+filmstrip_margin+gallery_padding)+((f_frame_width-22)/2)-13+'px',
'top':wrapper_height+(Math.max(gallery_padding,opts.frame_gap)*2)+'px'
});
}
};
//Check mouse to see if it is within the borders of the panel
//More reliable than 'mouseover' event when elements overlay the panel
function mouseIsOverGallery(x,y) {
var pos = getPos(j_gallery[0]);
var top = pos.top;
var left = pos.left;
return x > left && x < left+gallery_width+(filmstrip_orientation=='horizontal'?(gallery_padding*2):gallery_padding+Math.max(gallery_padding,filmstrip_margin)) && y > top && y < top+gallery_height+(filmstrip_orientation=='vertical'?(gallery_padding*2):gallery_padding+Math.max(gallery_padding,filmstrip_margin));
};
function getInt(i) {
i = parseInt(i,10);
if(isNaN(i)) { i = 0; }
return i;
}
function buildGallery() {
var gallery_images = opts.show_filmstrip?$('img',j_frames):$('img',j_panels);
gallery_images.each(function(i){
img_h[i] = this.height;
img_w[i] = this.width;
if(opts.frame_scale=='nocrop') {
frame_img_scale[i] = Math.min(opts.frame_height/img_h[i],opts.frame_width/img_w[i]);
} else {
frame_img_scale[i] = Math.max(opts.frame_height/img_h[i],opts.frame_width/img_w[i]);
}
if(opts.panel_scale=='nocrop') {
panel_img_scale[i] = Math.min(opts.panel_height/img_h[i],opts.panel_width/img_w[i]);
} else {
panel_img_scale[i] = Math.max(opts.panel_height/img_h[i],opts.panel_width/img_w[i]);
}
});
/************************************************/
/* Apply CSS Styles */
/************************************************/
j_gallery.css({
'position':'relative',
'width':gallery_width+(filmstrip_orientation=='horizontal'?(gallery_padding*2):gallery_padding+Math.max(gallery_padding,filmstrip_margin))+'px',
'height':gallery_height+(filmstrip_orientation=='vertical'?(gallery_padding*2):gallery_padding+Math.max(gallery_padding,filmstrip_margin))+'px'
});
/************************************************/
/* Build filmstrip and/or panels */
/************************************************/
if(opts.show_filmstrip) {
buildFilmstrip();
enableFrameClicking();
}
if(opts.show_panels) {
buildPanels();
}
/************************************************/
/* Add events to various elements */
/************************************************/
if(opts.pause_on_hover || (opts.show_panels && !opts.show_filmstrip)) {
$().mousemove(function(e){
if(mouseIsOverGallery(e.pageX,e.pageY)) {
if(opts.pause_on_hover) {
if(!paused) {
$(document).oneTime(500,"animation_pause",function(){
$(document).stopTime("transition");
paused=true;
});
}
}
if(opts.show_panels && !opts.show_filmstrip && !panel_nav_displayed) {
$('.nav-next-overlay').fadeIn('fast');
$('.nav-prev-overlay').fadeIn('fast');
$('.nav-next',j_gallery).fadeIn('fast');
$('.nav-prev',j_gallery).fadeIn('fast');
panel_nav_displayed = true;
}
} else {
if(opts.pause_on_hover) {
$(document).stopTime("animation_pause");
if(paused) {
$(document).everyTime(opts.transition_interval,"transition",function(){
showNextItem();
});
paused = false;
}
}
if(opts.show_panels && !opts.show_filmstrip && panel_nav_displayed) {
$('.nav-next-overlay').fadeOut('fast');
$('.nav-prev-overlay').fadeOut('fast');
$('.nav-next',j_gallery).fadeOut('fast');
$('.nav-prev',j_gallery).fadeOut('fast');
panel_nav_displayed = false;
}
}
});
}
/****************************************************************/
/* Initiate Automated Animation */
/****************************************************************/
//Hide loading box
j_filmstrip.css('visibility','visible');
j_gallery.css('visibility','visible');
$('.loader',j_gallery).fadeOut('1000',function(){
//Show the 'first' panel
showItem(iterator);
//If we have more than one item, begin automated transitions
if(item_count > 1) {
$(document).everyTime(opts.transition_interval,"transition",function(){
showNextItem();
});
}
});
}
/************************************************/
/* Main Plugin Code */
/************************************************/
return this.each(function() {
//Hide <ul>
$(this).css('visibility','hidden');
//Wrap <ul> in <div> and transfer ID to container <div>
//Assign filmstrip class to <ul>
$(this).wrap("<div></div>");
j_gallery = $(this).parent();
j_gallery.css('visibility','hidden').attr('id',$(this).attr('id')).addClass('gallery');
$(this).removeAttr('id').addClass('filmstrip');
$(document).stopTime("transition");
$(document).stopTime("animation_pause");
id = j_gallery.attr('id');
//If there is no defined panel content, we will scale panel images
scale_panel_images = $('.panel-content',j_gallery).length==0;
//Define dimensions of pointer <div>
pointer_height = opts.pointer_size;
pointer_width = opts.pointer_size*2;
//Determine filmstrip orientation (vertical or horizontal)
//Do not show captions on vertical filmstrips
filmstrip_orientation = (opts.filmstrip_position=='top'||opts.filmstrip_position=='bottom'?'horizontal':'vertical');
if(filmstrip_orientation=='vertical') opts.show_captions = false;
//Determine path between current page and plugin images
//Scan script tags and look for path to GalleryView plugin
$('script').each(function(i){
var s = $(this);
if(s.attr('src') && s.attr('src').match(/jquery\.galleryview/)){
loader_path = s.attr('src').split('jquery.galleryview')[0];
theme_path = s.attr('src').split('jquery.galleryview')[0]+'themes/';
}
});
j_filmstrip = $('.filmstrip',j_gallery);
j_frames = $('li',j_filmstrip);
j_frames.addClass('frame');
//If the user wants panels, generate them using the filmstrip images
if(opts.show_panels) {
for(i=j_frames.length-1;i>=0;i--) {
if(j_frames.eq(i).find('.panel-content').length>0) {
j_frames.eq(i).find('.panel-content').remove().prependTo(j_gallery).addClass('panel');
} else {
p = $('<div>');
p.addClass('panel');
im = $('<img />');
im.attr('src',j_frames.eq(i).find('img').eq(0).attr('src')).appendTo(p);
p.prependTo(j_gallery);
j_frames.eq(i).find('.panel-overlay').remove().appendTo(p);
}
}
} else {
$('.panel-overlay',j_frames).remove();
$('.panel-content',j_frames).remove();
}
//If the user doesn't want a filmstrip, delete it
if(!opts.show_filmstrip) { j_filmstrip.remove(); }
else {
//Wrap the frame images (and links, if applicable) in container divs
//These divs will handle cropping and zooming of the images
j_frames.each(function(i){
if($(this).find('a').length>0) {
$(this).find('a').wrap('<div class="img_wrap"></div>');
} else {
$(this).find('img').wrap('<div class="img_wrap"></div>');
}
});
j_frame_img_wrappers = $('.img_wrap',j_frames);
}
j_panels = $('.panel',j_gallery);
if(!opts.show_panels) {
opts.panel_height = 0;
opts.panel_width = 0;
}
//Determine final frame dimensions, accounting for user-added padding and border
f_frame_width = opts.frame_width+extraWidth(j_frame_img_wrappers);
f_frame_height = opts.frame_height+extraHeight(j_frame_img_wrappers);
//Number of frames in filmstrip
item_count = opts.show_panels?j_panels.length:j_frames.length;
//Number of frames that can display within the gallery block
//64 = width of block for navigation button * 2 + 20
if(filmstrip_orientation=='horizontal') {
strip_size = opts.show_panels?Math.floor((opts.panel_width-((opts.frame_gap+22)*2))/(f_frame_width+opts.frame_gap)):Math.min(item_count,opts.filmstrip_size);
} else {
strip_size = opts.show_panels?Math.floor((opts.panel_height-(opts.frame_gap+22))/(f_frame_height+opts.frame_gap)):Math.min(item_count,opts.filmstrip_size);
}
/************************************************/
/* Determine transition method for filmstrip */
/************************************************/
//If more items than strip size, slide filmstrip
//Otherwise, slide pointer
if(strip_size >= item_count) {
slide_method = 'pointer';
strip_size = item_count;
}
else {slide_method = 'strip';}
iterator = (strip_size<item_count?item_count:0)+opts.start_frame-1;
/************************************************/
/* Determine dimensions of various elements */
/************************************************/
filmstrip_margin = (opts.show_panels?getInt(j_filmstrip.css('marginTop')):0);
j_filmstrip.css('margin','0px');
if(filmstrip_orientation=='horizontal') {
//Width of gallery block
gallery_width = opts.show_panels?opts.panel_width:(strip_size*(f_frame_width+opts.frame_gap))+44+opts.frame_gap;
//Height of gallery block = screen + filmstrip + captions (optional)
gallery_height = (opts.show_panels?opts.panel_height:0)+(opts.show_filmstrip?f_frame_height+filmstrip_margin+(opts.show_captions?frame_caption_size:0):0);
} else {
//Width of gallery block
gallery_height = opts.show_panels?opts.panel_height:(strip_size*(f_frame_height+opts.frame_gap))+22;
//Height of gallery block = screen + filmstrip + captions (optional)
gallery_width = (opts.show_panels?opts.panel_width:0)+(opts.show_filmstrip?f_frame_width+filmstrip_margin:0);
}
//Width of filmstrip
if(filmstrip_orientation=='horizontal') {
if(slide_method == 'pointer') {strip_width = (f_frame_width*item_count)+(opts.frame_gap*(item_count));}
else {strip_width = (f_frame_width*item_count*3)+(opts.frame_gap*(item_count*3));}
} else {
strip_width = (f_frame_width+filmstrip_margin);
}
if(filmstrip_orientation=='horizontal') {
strip_height = (f_frame_height+filmstrip_margin+(opts.show_captions?frame_caption_size:0));
} else {
if(slide_method == 'pointer') {strip_height = (f_frame_height*item_count+opts.frame_gap*(item_count));}
else {strip_height = (f_frame_height*item_count*3)+(opts.frame_gap*(item_count*3));}
}
//Width of filmstrip wrapper (to hide overflow)
wrapper_width = ((strip_size*f_frame_width)+((strip_size-1)*opts.frame_gap));
wrapper_height = ((strip_size*f_frame_height)+((strip_size-1)*opts.frame_gap));
gallery_padding = getInt(j_gallery.css('paddingTop'));
j_gallery.css('padding','0px');
/********************************************************/
/* PLACE LOADING BOX OVER GALLERY UNTIL IMAGES LOAD */
/********************************************************/
galleryPos = getPos(j_gallery[0]);
$('<div>').addClass('loader').css({
'position':'absolute',
'zIndex':'32666',
'opacity':1,
'top':'0px',
'left':'0px',
'width':gallery_width+(filmstrip_orientation=='horizontal'?(gallery_padding*2):gallery_padding+Math.max(gallery_padding,filmstrip_margin))+'px',
'height':gallery_height+(filmstrip_orientation=='vertical'?(gallery_padding*2):gallery_padding+Math.max(gallery_padding,filmstrip_margin))+'px'
}).appendTo(j_gallery);
if(!window_loaded) {
$(window).load(function(){
window_loaded = true;
buildGallery();
});
} else {
buildGallery();
}
});
};
$.fn.galleryView.defaults = {
show_panels: true,
show_filmstrip: true,
panel_width: 600,
panel_height: 400,
frame_width: 60,
frame_height: 40,
start_frame: 1,
filmstrip_size: 3,
transition_speed: 800,
transition_interval: 4000,
overlay_opacity: 0.7,
frame_opacity: 0.3,
pointer_size: 8,
nav_theme: 'dark',
easing: 'swing',
filmstrip_position: 'bottom',
overlay_position: 'bottom',
panel_scale: 'nocrop',
frame_scale: 'crop',
frame_gap: 5,
show_captions: false,
fade_panels: true,
pause_on_hover: false
};
})(jQuery);

View File

@ -1,147 +0,0 @@
/**
* jQuery.timers - Timer abstractions for jQuery
* Written by Blair Mitchelmore (blair DOT mitchelmore AT gmail DOT com)
* Licensed under the WTFPL (http://sam.zoy.org/wtfpl/).
* Date: 2009/02/08
*
* @author Blair Mitchelmore
* @version 1.1.2
*
**/
jQuery.fn.extend({
everyTime: function(interval, label, fn, times, belay) {
return this.each(function() {
jQuery.timer.add(this, interval, label, fn, times, belay);
});
},
oneTime: function(interval, label, fn) {
return this.each(function() {
jQuery.timer.add(this, interval, label, fn, 1);
});
},
stopTime: function(label, fn) {
return this.each(function() {
jQuery.timer.remove(this, label, fn);
});
}
});
jQuery.event.special
jQuery.extend({
timer: {
global: [],
guid: 1,
dataKey: "jQuery.timer",
regex: /^([0-9]+(?:\.[0-9]*)?)\s*(.*s)?$/,
powers: {
// Yeah this is major overkill...
'ms': 1,
'cs': 10,
'ds': 100,
's': 1000,
'das': 10000,
'hs': 100000,
'ks': 1000000
},
timeParse: function(value) {
if (value == undefined || value == null)
return null;
var result = this.regex.exec(jQuery.trim(value.toString()));
if (result[2]) {
var num = parseFloat(result[1]);
var mult = this.powers[result[2]] || 1;
return num * mult;
} else {
return value;
}
},
add: function(element, interval, label, fn, times, belay) {
var counter = 0;
if (jQuery.isFunction(label)) {
if (!times)
times = fn;
fn = label;
label = interval;
}
interval = jQuery.timer.timeParse(interval);
if (typeof interval != 'number' || isNaN(interval) || interval <= 0)
return;
if (times && times.constructor != Number) {
belay = !!times;
times = 0;
}
times = times || 0;
belay = belay || false;
var timers = jQuery.data(element, this.dataKey) || jQuery.data(element, this.dataKey, {});
if (!timers[label])
timers[label] = {};
fn.timerID = fn.timerID || this.guid++;
var handler = function() {
if (belay && this.inProgress)
return;
this.inProgress = true;
if ((++counter > times && times !== 0) || fn.call(element, counter) === false)
jQuery.timer.remove(element, label, fn);
this.inProgress = false;
};
handler.timerID = fn.timerID;
if (!timers[label][fn.timerID])
timers[label][fn.timerID] = window.setInterval(handler,interval);
this.global.push( element );
},
remove: function(element, label, fn) {
var timers = jQuery.data(element, this.dataKey), ret;
if ( timers ) {
if (!label) {
for ( label in timers )
this.remove(element, label, fn);
} else if ( timers[label] ) {
if ( fn ) {
if ( fn.timerID ) {
window.clearInterval(timers[label][fn.timerID]);
delete timers[label][fn.timerID];
}
} else {
for ( var fn in timers[label] ) {
window.clearInterval(timers[label][fn]);
delete timers[label][fn];
}
}
for ( ret in timers[label] ) break;
if ( !ret ) {
ret = null;
delete timers[label];
}
}
for ( ret in timers ) break;
if ( !ret )
jQuery.removeData(element, this.dataKey);
}
}
}
});
jQuery(window).bind("unload", function() {
jQuery.each(jQuery.timer.global, function(index, item) {
jQuery.timer.remove(item);
});
});

Binary file not shown.

Before

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 79 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 82 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 82 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 80 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 79 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 82 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 82 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 80 B

View File

@ -1,49 +0,0 @@
# Mouse Wheel ChangeLog
# 3.0.2
* Fixed delta being opposite value in latest Opera
* No longer fix pageX, pageY for older mozilla browsers
* Removed browser detection
* Cleaned up the code
# 3.0.1
* Bad release... creating a new release due to plugins.jquery.com issue :(
# 3.0
* Uses new special events API in jQuery 1.2.2+
* You can now treat "mousewheel" as a normal event and use .bind, .unbind and .trigger
* Using jQuery.data API for expandos
# 2.2
* Fixed pageX, pageY, clientX and clientY event properties for Mozilla based browsers
# 2.1.1
* Updated to work with jQuery 1.1.3
* Used one instead of bind to do unload event for clean up.
# 2.1
* Fixed an issue with the unload handler
# 2.0
* Major reduction in code size and complexity (internals have change a whole lot)
# 1.0
* Fixed Opera issue
* Fixed an issue with children elements that also have a mousewheel handler
* Added ability to handle multiple handlers

View File

@ -1,11 +0,0 @@
# jQuery Mouse Wheel Plugin
A jQuery plugin that adds cross-browser mouse wheel support.
The latest stable release can be downloaded from the [project page](http://plugins.jquery.com/project/mousewheel)
## License
The mousewheel plugin is dual licensed *(just like jQuery)* under the [MIT](http://www.opensource.org/licenses/mit-license.php) and [GPL](http://www.opensource.org/licenses/gpl-license.php) licenses.
Copyright (c) 2009 [Brandon Aaron](http://brandonaaron.net)

View File

@ -1,60 +0,0 @@
/*! Copyright (c) 2009 Brandon Aaron (http://brandonaaron.net)
* Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
* and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
* Thanks to: http://adomas.org/javascript-mouse-wheel/ for some pointers.
* Thanks to: Mathias Bank(http://www.mathias-bank.de) for a scope bug fix.
*
* Version: 3.0.2
*
* Requires: 1.2.2+
*/
(function($) {
var types = ['DOMMouseScroll', 'mousewheel'];
$.event.special.mousewheel = {
setup: function() {
if ( this.addEventListener )
for ( var i=types.length; i; )
this.addEventListener( types[--i], handler, false );
else
this.onmousewheel = handler;
},
teardown: function() {
if ( this.removeEventListener )
for ( var i=types.length; i; )
this.removeEventListener( types[--i], handler, false );
else
this.onmousewheel = null;
}
};
$.fn.extend({
mousewheel: function(fn) {
return fn ? this.bind("mousewheel", fn) : this.trigger("mousewheel");
},
unmousewheel: function(fn) {
return this.unbind("mousewheel", fn);
}
});
function handler(event) {
var args = [].slice.call( arguments, 1 ), delta = 0, returnValue = true;
event = $.event.fix(event || window.event);
event.type = "mousewheel";
if ( event.wheelDelta ) delta = event.wheelDelta/120;
if ( event.detail ) delta = -event.detail/3;
// Add events and delta to the front of the arguments
args.unshift(event, delta);
return $.event.handle.apply(this, args);
}
})(jQuery);

View File

@ -1,11 +0,0 @@
/* Copyright (c) 2009 Brandon Aaron (http://brandonaaron.net)
* Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
* and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
* Thanks to: http://adomas.org/javascript-mouse-wheel/ for some pointers.
* Thanks to: Mathias Bank(http://www.mathias-bank.de) for a scope bug fix.
*
* Version: 3.0.2
*
* Requires: 1.2.2+
*/
(function(c){var a=["DOMMouseScroll","mousewheel"];c.event.special.mousewheel={setup:function(){if(this.addEventListener){for(var d=a.length;d;){this.addEventListener(a[--d],b,false)}}else{this.onmousewheel=b}},teardown:function(){if(this.removeEventListener){for(var d=a.length;d;){this.removeEventListener(a[--d],b,false)}}else{this.onmousewheel=null}}};c.fn.extend({mousewheel:function(d){return d?this.bind("mousewheel",d):this.trigger("mousewheel")},unmousewheel:function(d){return this.unbind("mousewheel",d)}});function b(f){var d=[].slice.call(arguments,1),g=0,e=true;f=c.event.fix(f||window.event);f.type="mousewheel";if(f.wheelDelta){g=f.wheelDelta/120}if(f.detail){g=-f.detail/3}d.unshift(f,g);return c.event.handle.apply(this,d)}})(jQuery);

View File

@ -1,204 +0,0 @@
<!doctype html>
<html>
<head>
<title>Testing mousewheel plugin</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js"></script>
<script type="text/javascript" src="../jquery.mousewheel.js"></script>
<style>
#test1 {
background-color: #000;
width: 100px;
height: 100px;
color: #fff;
float: left;
}
#test2 {
background-color: #333;
width: 100px;
height: 100px;
color: #fff;
float: left;
}
#test3 {
background-color: #666;
width: 100px;
height: 100px;
color: #fff;
float: left;
}
#test4 {
background-color: #000;
width: 100px;
height: 100px;
color: #fff;
float: left;
}
#test5 {
background-color: #333;
padding: 5px;
width: 400px;
height: 400px;
color: #fff;
float: left;
}
#test6 {
background-color: #666;
padding: 5px;
width: 250px;
height: 250px;
color: #fff;
float: left;
}
#test7 {
background-color: #000;
padding: 5px;
width: 100px;
height: 100px;
color: #fff;
float: left;
}
#forceScroll {
clear: both;
height: 1000px;
}
#logger {
position: absolute;
top: 395px;
left: 12px;
width: 380px;
height: 290px;
overflow: auto;
}
</style>
<script type="text/javascript">
$(function() {
$('#userAgent').html(navigator.userAgent);
$('#test1')
.mousewheel(function(event, delta) {
if (delta > 0)
log('#test1: up ('+delta+')');
else if (delta < 0)
log('#test1: down ('+delta+')');
log('pageX: ' + event.pageX + ' pageY: ' + event.pageY );
});
$('#test2')
.mousewheel(function(event, delta) {
if (delta > 0)
log('#test2: up ('+delta+')');
else if (delta < 0)
log('#test2: down ('+delta+')');
return false; // prevent default
});
$('#test3')
.hover(function() { log('#test3: mouseover'); }, function() { log('#test3: mouseout'); })
.mousewheel(function(event, delta) {
log('#test3: I should not have been logged');
})
.unmousewheel();
var testRemoval = function(event, delta) {
log('#test4: I should not have been logged');
};
$('#test4')
.mousewheel(function(event, delta) {
if (delta > 0)
log('#test4: up ('+delta+')');
else if (delta < 0)
log('#test4: down ('+delta+')');
return false;
})
.mousewheel(testRemoval)
.mousewheel(function(event, delta) {
if (delta > 0)
log('#test4: up ('+delta+') from 2nd handler');
else if (delta < 0)
log('#test4: down ('+delta+') from 2nd handler');
return false;
})
.unmousewheel(testRemoval);
$('#test5')
.mousewheel(function(event, delta) {
if (delta > 0)
log('#test5: up ('+delta+')');
else if (delta < 0)
log('#test5: down ('+delta+')');
event.stopPropagation();
event.preventDefault();
});
$('#test6')
.mousewheel(function(event, delta) {
if (delta > 0)
log('#test6: up ('+delta+')');
else if (delta < 0)
log('#test6: down ('+delta+')');
event.stopPropagation();
event.preventDefault();
});
$('#test7')
.mousewheel(function(event, delta) {
if (delta > 0)
log('#test7: up ('+delta+')');
else if (delta < 0)
log('#test7 down ('+delta+')');
event.preventDefault();
});
function log(msg) {
$('#logger').append(msg+'<br>').scrollTop(999999);
};
});
</script>
</head>
<body>
<h1 id="banner">jQuery mousewheel.js - Test</h1>
<h2 id="userAgent"></h2>
<ul>
<li><strong>Test1</strong> is just using the plain on mousewheel() with a function passed in and does not prevent default. (Also logs the value of pageX and pageY event properties.)</li>
<li><strong>Test2</strong> should prevent the default action.</li>
<li><strong>Test3</strong> should only log a mouseover and mouseout event. Testing unmousewheel().</li>
<li><strong>Test4</strong> has two handlers.</li>
<li><strong>Test5</strong> is like Test2 but has children. The children should not scroll until mousing over them.</li>
<li><strong>Test6</strong> is like Test5 but should not scroll children or parents.</li>
<li><strong>Test7</strong> is like Test6 but has no children. It will propagate the event and scroll test 6 as well.</li>
</ul>
<div id="test1"><p>Test1</p></div>
<div id="test2"><p>Test2</p></div>
<div id="test3"><p>Test3</p></div>
<div id="test4"><p>Test4</p></div>
<div id="test5">
<p>Test5</p>
<div id="test6">
<p>Test6</p>
<div id="test7"><p>Test7</p></div>
</div>
</div>
<div id="logger"></div>
<div id="forceScroll"></div>
</body>
</html>

File diff suppressed because it is too large Load Diff

View File

@ -1,457 +0,0 @@
/**
* jquery.scrollable 1.0.2. Put your HTML scroll.
*
* Copyright (c) 2009 Tero Piirainen
* http://flowplayer.org/tools/scrollable.html
*
* Dual licensed under MIT and GPL 2+ licenses
* http://www.opensource.org/licenses
*
* Launch : March 2008
* Version : 1.0.2 - Tue Feb 24 2009 10:52:08 GMT-0000 (GMT+00:00)
*/
(function($) {
function fireEvent(opts, name, self, arg) {
var fn = opts[name];
if ($.isFunction(fn)) {
try {
return fn.call(self, arg);
} catch (error) {
if (opts.alert) {
alert("Error calling scrollable." + name + ": " + error);
} else {
throw error;
}
return false;
}
}
return true;
}
var current = null;
// constructor
function Scrollable(root, conf) {
// current instance
var self = this;
if (!current) { current = self; }
// horizontal flag
var horizontal = !conf.vertical;
// wrap (root elements for items)
var wrap = $(conf.items, root);
// current index
var index = 0;
// get handle to navigational elements
var navi = root.siblings(conf.navi).eq(0);
var prev = root.siblings(conf.prev).eq(0);
var next = root.siblings(conf.next).eq(0);
var prevPage = root.siblings(conf.prevPage).eq(0);
var nextPage = root.siblings(conf.nextPage).eq(0);
// methods
$.extend(self, {
getVersion: function() {
return [1, 0, 1];
},
getIndex: function() {
return index;
},
getConf: function() {
return conf;
},
getSize: function() {
return self.getItems().size();
},
getPageAmount: function() {
return Math.ceil(this.getSize() / conf.size);
},
getPageIndex: function() {
return Math.ceil(index / conf.size);
},
getRoot: function() {
return root;
},
getItemWrap: function() {
return wrap;
},
getItems: function() {
return wrap.children();
},
/* all seeking functions depend on this */
seekTo: function(i, time, fn) {
// default speed
time = time || conf.speed;
// function given as second argument
if ($.isFunction(time)) {
fn = time;
time = conf.speed;
}
if (i < 0) { i = 0; }
if (i > self.getSize() - conf.size) { return self; }
var item = self.getItems().eq(i);
if (!item.length) { return self; }
// onBeforeSeek
if (fireEvent(conf, "onBeforeSeek", self, i) === false) {
return self;
}
if (horizontal) {
var left = -(item.outerWidth(true) * i);
wrap.animate({left: left}, time, conf.easing, fn ? function() { fn.call(self); } : null);
} else {
var top = -(item.outerHeight(true) * i); // wrap.offset().top - item.offset().top;
wrap.animate({top: top}, time, conf.easing, fn ? function() { fn.call(self); } : null);
}
// navi status update
if (navi.length) {
var klass = conf.activeClass;
var page = Math.ceil(i / conf.size);
page = Math.min(page, navi.children().length - 1);
navi.children().removeClass(klass).eq(page).addClass(klass);
}
// prev buttons disabled flag
if (i === 0) {
prev.add(prevPage).addClass(conf.disabledClass);
} else {
prev.add(prevPage).removeClass(conf.disabledClass);
}
// next buttons disabled flag
if (i >= self.getSize() - conf.size) {
next.add(nextPage).addClass(conf.disabledClass);
} else {
next.add(nextPage).removeClass(conf.disabledClass);
}
current = self;
index = i;
// onSeek after index being updated
fireEvent(conf, "onSeek", self, i);
return self;
},
move: function(offset, time, fn) {
var to = index + offset;
if (conf.loop && to > (self.getSize() - conf.size)) {
to = 0;
}
return this.seekTo(to, time, fn);
},
next: function(time, fn) {
return this.move(1, time, fn);
},
prev: function(time, fn) {
return this.move(-1, time, fn);
},
movePage: function(offset, time, fn) {
return this.move(conf.size * offset, time, fn);
},
setPage: function(page, time, fn) {
var size = conf.size;
var index = size * page;
var lastPage = index + size >= this.getSize();
if (lastPage) {
index = this.getSize() - conf.size;
}
return this.seekTo(index, time, fn);
},
prevPage: function(time, fn) {
return this.setPage(this.getPageIndex() - 1, time, fn);
},
nextPage: function(time, fn) {
return this.setPage(this.getPageIndex() + 1, time, fn);
},
begin: function(time, fn) {
return this.seekTo(0, time, fn);
},
end: function(time, fn) {
return this.seekTo(this.getSize() - conf.size, time, fn);
},
reload: function() {
return load();
},
click: function(index, time, fn) {
var item = self.getItems().eq(index);
var klass = conf.activeClass;
if (!item.hasClass(klass) && (index >= 0 || index < this.getSize())) {
self.getItems().removeClass(klass);
item.addClass(klass);
var delta = Math.floor(conf.size / 2);
var to = index - delta;
// next to last item must work
if (to > self.getSize() - conf.size) { to--; }
if (to !== index) {
return this.seekTo(to, time, fn);
}
}
return self;
}
});
// mousewheel
if ($.isFunction($.fn.mousewheel)) {
root.bind("mousewheel.scrollable", function(e, delta) {
// opera goes to opposite direction
var step = $.browser.opera ? 1 : -1;
self.move(delta > 0 ? step : -step, 50);
return false;
});
}
// prev button
prev.addClass(conf.disabledClass).click(function() {
self.prev();
});
// next button
next.click(function() {
self.next();
});
// prev page button
nextPage.click(function() {
self.nextPage();
});
// next page button
prevPage.addClass(conf.disabledClass).click(function() {
self.prevPage();
});
// keyboard
if (conf.keyboard) {
// unfortunately window.keypress does not work on IE.
$(window).unbind("keypress.scrollable").bind("keypress.scrollable", function(evt) {
var el = current;
if (!el) { return; }
if (horizontal && (evt.keyCode == 37 || evt.keyCode == 39)) {
el.move(evt.keyCode == 37 ? -1 : 1);
return evt.preventDefault();
}
if (!horizontal && (evt.keyCode == 38 || evt.keyCode == 40)) {
el.move(evt.keyCode == 38 ? -1 : 1);
return evt.preventDefault();
}
return true;
});
}
// navi
function load() {
navi.each(function() {
var nav = $(this);
// generate new entries
if (nav.is(":empty") || nav.data("me") == self) {
nav.empty();
nav.data("me", self);
for (var i = 0; i < self.getPageAmount(); i++) {
var item = $("<" + conf.naviItem + "/>").attr("href", i).click(function(e) {
var el = $(this);
el.parent().children().removeClass(conf.activeClass);
el.addClass(conf.activeClass);
self.setPage(el.attr("href"));
return e.preventDefault();
});
if (i === 0) { item.addClass(conf.activeClass); }
nav.append(item);
}
// assign onClick events to existing entries
} else {
// find a entries first -> syntaxically correct
var els = nav.children();
els.each(function(i) {
var item = $(this);
item.attr("href", i);
if (i === 0) { item.addClass(conf.activeClass); }
item.click(function() {
nav.find("." + conf.activeClass).removeClass(conf.activeClass);
item.addClass(conf.activeClass);
self.setPage(item.attr("href"));
});
});
}
});
// item.click()
if (conf.clickable) {
self.getItems().each(function(index, arg) {
var el = $(this);
if (!el.data("set")) {
el.bind("click.scrollable", function() {
self.click(index);
});
el.data("set", true);
}
});
}
// hover
if (conf.hoverClass) {
self.getItems().hover(function() {
$(this).addClass(conf.hoverClass);
}, function() {
$(this).removeClass(conf.hoverClass);
});
}
return self;
}
load();
// interval stuff
var timer = null;
function setTimer() {
timer = setInterval(function() {
self.next();
}, conf.interval);
}
if (conf.interval > 0) {
root.hover(function() {
clearInterval(timer);
}, function() {
setTimer();
});
setTimer();
}
}
// jQuery plugin implementation
jQuery.prototype.scrollable = function(conf) {
// already constructed --> return API
var api = this.eq(typeof conf == 'number' ? conf : 0).data("scrollable");
if (api) { return api; }
var opts = {
// basics
size: 5,
vertical:false,
clickable: true,
loop: false,
interval: 0,
speed: 400,
keyboard: true,
// other
activeClass:'active',
disabledClass: 'disabled',
hoverClass: null,
easing: 'swing',
// navigational elements
items: '.items',
prev: '.prev',
next: '.next',
prevPage: '.prevPage',
nextPage: '.nextPage',
navi: '.navi',
naviItem: 'a',
// callbacks
onBeforeSeek: null,
onSeek: null,
alert: true
};
$.extend(opts, conf);
this.each(function() {
var el = new Scrollable($(this), opts);
$(this).data("scrollable", el);
});
return this;
};
})(jQuery);

File diff suppressed because one or more lines are too long

View File

@ -1,223 +0,0 @@
/**
* http://www.openjs.com/scripts/events/keyboard_shortcuts/
* Version : 2.01.B
* By Binny V A
* License : BSD
*/
shortcut = {
'all_shortcuts':{},//All the shortcuts are stored in this array
'add': function(shortcut_combination,callback,opt) {
//Provide a set of default options
var default_options = {
'type':'keydown',
'propagate':false,
'disable_in_input':false,
'target':document,
'keycode':false
}
if(!opt) opt = default_options;
else {
for(var dfo in default_options) {
if(typeof opt[dfo] == 'undefined') opt[dfo] = default_options[dfo];
}
}
var ele = opt.target;
if(typeof opt.target == 'string') ele = document.getElementById(opt.target);
var ths = this;
shortcut_combination = shortcut_combination.toLowerCase();
//The function to be called at keypress
var func = function(e) {
e = e || window.event;
if(opt['disable_in_input']) { //Don't enable shortcut keys in Input, Textarea fields
var element;
if(e.target) element=e.target;
else if(e.srcElement) element=e.srcElement;
if(element.nodeType==3) element=element.parentNode;
if(element.tagName == 'INPUT' || element.tagName == 'TEXTAREA') return;
}
//Find Which key is pressed
if (e.keyCode) code = e.keyCode;
else if (e.which) code = e.which;
var character = String.fromCharCode(code).toLowerCase();
if(code == 188) character=","; //If the user presses , when the type is onkeydown
if(code == 190) character="."; //If the user presses , when the type is onkeydown
var keys = shortcut_combination.split("+");
//Key Pressed - counts the number of valid keypresses - if it is same as the number of keys, the shortcut function is invoked
var kp = 0;
//Work around for stupid Shift key bug created by using lowercase - as a result the shift+num combination was broken
var shift_nums = {
"`":"~",
"1":"!",
"2":"@",
"3":"#",
"4":"$",
"5":"%",
"6":"^",
"7":"&",
"8":"*",
"9":"(",
"0":")",
"-":"_",
"=":"+",
";":":",
"'":"\"",
",":"<",
".":">",
"/":"?",
"\\":"|"
}
//Special Keys - and their codes
var special_keys = {
'esc':27,
'escape':27,
'tab':9,
'space':32,
'return':13,
'enter':13,
'backspace':8,
'scrolllock':145,
'scroll_lock':145,
'scroll':145,
'capslock':20,
'caps_lock':20,
'caps':20,
'numlock':144,
'num_lock':144,
'num':144,
'pause':19,
'break':19,
'insert':45,
'home':36,
'delete':46,
'end':35,
'pageup':33,
'page_up':33,
'pu':33,
'pagedown':34,
'page_down':34,
'pd':34,
'left':37,
'up':38,
'right':39,
'down':40,
'f1':112,
'f2':113,
'f3':114,
'f4':115,
'f5':116,
'f6':117,
'f7':118,
'f8':119,
'f9':120,
'f10':121,
'f11':122,
'f12':123
}
var modifiers = {
shift: { wanted:false, pressed:false},
ctrl : { wanted:false, pressed:false},
alt : { wanted:false, pressed:false},
meta : { wanted:false, pressed:false} //Meta is Mac specific
};
if(e.ctrlKey) modifiers.ctrl.pressed = true;
if(e.shiftKey) modifiers.shift.pressed = true;
if(e.altKey) modifiers.alt.pressed = true;
if(e.metaKey) modifiers.meta.pressed = true;
for(var i=0; k=keys[i],i<keys.length; i++) {
//Modifiers
if(k == 'ctrl' || k == 'control') {
kp++;
modifiers.ctrl.wanted = true;
} else if(k == 'shift') {
kp++;
modifiers.shift.wanted = true;
} else if(k == 'alt') {
kp++;
modifiers.alt.wanted = true;
} else if(k == 'meta') {
kp++;
modifiers.meta.wanted = true;
} else if(k.length > 1) { //If it is a special key
if(special_keys[k] == code) kp++;
} else if(opt['keycode']) {
if(opt['keycode'] == code) kp++;
} else { //The special keys did not match
if(character == k) kp++;
else {
if(shift_nums[character] && e.shiftKey) { //Stupid Shift key bug created by using lowercase
character = shift_nums[character];
if(character == k) kp++;
}
}
}
}
if(kp == keys.length &&
modifiers.ctrl.pressed == modifiers.ctrl.wanted &&
modifiers.shift.pressed == modifiers.shift.wanted &&
modifiers.alt.pressed == modifiers.alt.wanted &&
modifiers.meta.pressed == modifiers.meta.wanted) {
callback(e);
if(!opt['propagate']) { //Stop the event
//e.cancelBubble is supported by IE - this will kill the bubbling process.
e.cancelBubble = true;
e.returnValue = false;
//e.stopPropagation works in Firefox.
if (e.stopPropagation) {
e.stopPropagation();
e.preventDefault();
}
return false;
}
}
}
this.all_shortcuts[shortcut_combination] = {
'callback':func,
'target':ele,
'event': opt['type']
};
//Attach the function with the event
if(ele.addEventListener) ele.addEventListener(opt['type'], func, false);
else if(ele.attachEvent) ele.attachEvent('on'+opt['type'], func);
else ele['on'+opt['type']] = func;
},
//Remove the shortcut - just specify the shortcut and I will remove the binding
'remove':function(shortcut_combination) {
shortcut_combination = shortcut_combination.toLowerCase();
var binding = this.all_shortcuts[shortcut_combination];
delete(this.all_shortcuts[shortcut_combination])
if(!binding) return;
var type = binding['event'];
var ele = binding['target'];
var callback = binding['callback'];
if(ele.detachEvent) ele.detachEvent('on'+type, callback);
else if(ele.removeEventListener) ele.removeEventListener(type, callback, false);
else ele['on'+type] = false;
}
}

View File

@ -1,283 +0,0 @@
* SWFUpload Core, January 2009, www.swfupload.org, swfupload.googlecode.com
* --------- Version 2.2.0.1-----------
* - Removed requeueUpload due to bugs/poor testing
* = Fixed namespace conflict that broke stopUpload
* --------- Version 2.2.0-----------
* + Added button_placeholder setting that accepts a DOM element.
* + Added ability to requeue any file (including some improvement to internal queue state tracking)
* + UploadErrors caused by a missing upload_url now causes the file to be requeued automatically
* + Added preserve_relative_urls setting
* + SWFUpload now converts relative URLs to absolute URLs to avoid issues with Flash Player interpreting it differently on some clients
* + Added assume_success_timeout setting which allows uploadSuccess to be called after a timeout if, for some reason Flash ignores the server's response
* An additional parameter has been added to the uploadSuccess event to indicate whether a response was received or success was assumed.
* --------- Version 2.2.0 Beta 2 ~ 5-----------
* = Fixed a Queue Limit bug
* + Improved internal event handling code so uploadSuccess fires even when not content is returned from the server (*woot*, except for Macs)
* = Fixed issues in Destroy
* = Fixed issues with Queue Plugin
* + Added periodic checks of the ExternalInterface
* + Improved IE memory leak prevention code
* + Added Speed Plugin
* = Updated Queue Plugin for better multi-plugin compatibility
* --------- Version 2.2.0 Beta 1-----------
* + Added Flash Player 10 Support
* = Added setting for defining a button image
* = Added setting for defining button text
* = Added setting for defining button width, height and padding
* = Added setting for defining what element the Flash Movie should replace
* = Added setting for defining flash wmode
* = Added setting for defining the mouse cursor
* + Added prevent_swf_caching setting as a work-around for issues in Avant Browser (and other IE based browser)
* + Added setting for accepting HTTP Status codes other than 200 as successful
* + Added parameter to cancelUpload that allows the uploadError event for cancelled uploads to be supressed
* + Added pro-active memory leak fix for IE and fixed problems with the destroy function (credits to steffen for patches and testing)
* + Replaced callFlash with CallFunction (using the internal function that Flash uses). Based on code from MooTools.
* = Fixed bug in the Queue plugin that breaks startUpload when passing a file id.
* + Updated Queue plugin to stop the queue if false is returned from the uploadStart handler.
* = Fixed small issues in SWFObject plugin
* = Fixed issue with ExternalInterface string escaping
* - Dropped Graceful Degradation Plugin
* - Dropped v1.0.2 Plugin
* - Dropped Flash Player 8 support
* --------- Version 2.1.0 -----------
* = Fixed GET values so they are escaped properly
* + Added destroy function
* = Added exception handling around browse() calls
* = Minor code cleanup
* + Split Core and Demos
* --------- Version 2.1.0 Beta 2-----------
* = Fixed bug in XHTML fix where it wasn't split correctly by Flash
* = Fixed file params "undefined" in debug output
* + Added requeue_on_error settings so HTTP/IO/Security errors requeue the file instead of discarding it.
This will affect the queue plugin (if an error is occurring the file will be reuploaded and reuploaded).
* = Fixed HTTP/IO error behavior. We'll see how this goes Flash 9 is supposed to call HTTPError followed by an IO error but I suspect they come out of orde sometimes.
* = Fixed invalid characters in file param names. Worked around flash bug by escaping the names. Should be transparent to devs.
* = Fixed missing upload URL logic so it fires consistently
* = Fixed file params not being sent when useQueryString is true
* + Added SWFObject plugin and demo.
* + Added CookieBug demo to demonstrate what they bug really is all about.
* + Added VB.Net version of the Application Demo
* --------- Version 2.1.0 Beta 1-----------
* + Added allowScriptAccess="always" to the embed/object elements so the SWF can be served from different domains.
* = Fixed a type-o in the debug output that prevented the instance id (movieName) from displaying. - Thx Joel
* + Rewrote SWFUpload.js for better code reuse based on sample code from batiste.bieler (thanks!!!)
* + Added queueComplete event to the Queue Plugin
* + Added Simple Upload demo
* = JSLinted all the JavaScript code
* + Added use_query_string setting (and setUseQueryString function) that forces post_param and file_param values to be sent on the query_string instead of the post (for Flash 9 version)
* = Fixed file.type and date properties so a default value is provided (rather than null) when no value is provided by flash.
* = Fixed misc bugs in the demos
* = Fixed ExternalInterface calls being made available for Flash 9 versions <9.0.28 which aren't supported
* + Fixed use of & producing invalid XHTML in the <object> and <embed> tags.
* - Removed the use of the embed tag (using the <object> sample from the Flash Satay method)
* = Updated plugins to work with code rewrite changes.
* = Extracted FileProgress object in to its own file.
* + Added addPostParam and removePostParam functions
* --------- Version 2.0.2 -----------
* = Fixed a bug where post params could not be added to the current file (because it is removed from the queue when it becomes current)
* = Fixed a conversion error when converting kilobytes to bytes in the file size check
* = Fixed a problem in the documentation that said the file_size_limit was bytes when it is actually kilobytes
* + Added formatting to the documentation, a table of contents, and details for each setting .
* + Added units for file_size_limit setting. The setting understands B, KB, MB, GB. Default is KB.
* + Added a check for the ExternalInterface functions in flashReady so SWFUpload will not fire the loaded event if those are not available.
* --------- Version 2.0.1 -----------
* = Fixed a bug where zero-byte files would stop file the queuing process.
* = Finished updating Features Demo
* + Added GetFileByIndex(i) that gets a JavaScript File Object. The index never changes. Finished files continue to be available.
* The JavaScript GetFile function will accept a file_id or an index.
* + Added CheckFileSize constants to replace the magic numbers
* + Added some code in an attempt to fix "Script is running slowly" error messages
* = Better cleanup of FileReference objects
* --------- Version 2.0 -----------
* + Re-created SWFUpload in Actionscript v2 for Flash 8 compatibility. Flash 8 loses POST and Server Data features. The two versions are otherwise fully compatible.
* Flash 8 uses URL to pass post_params/file_params.
* = Changed uploadStart event so it's part of the setTimeout/eventQueue workaround. This allows Flash functions to be called from uploadStart.
* = Renamed uploadComplete to uploadSuccess and fileComplete to uploadComplete. All started uploads call uploadComplete (even if cancelled or stopped).
* = Changed startUpload validation failure behavior. Rather than cancelling the upload the file is now requeued. Devs can cancel
* or do whatever the need to in uploadError to handle the problem.
* = Fixed fileQueueLimit/fileUploadLimit logic so it works correctly.
* = Moved the upload request building to a later point so that the post params and file params can be updated in uploadStart.
* - Removed the last of the UI stuff (ui_container, degraded_container).
* + Started development on Plug-ins. Graceful Degradation, v1.0.2, Cookies, Queue Handling
* = Fixed missing file_status field in FileItem.
* + Added modificationDate to FileItem (file object)
* + Added setStats function that lets you change the file upload count, etc. This will give more power over the queue limits. Not well tested.
* = Renamed compeleted_uploads to successful_uploads in getStats object
* + Added in_progress to getStats object
* --------- Revision 7.0 beta 3 -----------
* + Added an "event queue". Events are added to an array and executeEvent is called on a setTimeout. This prevents out of order issues that occur
* in the Safari browser.
* + Added a check for the UPLOAD_COMPLETE_DATA event constant which only became available in Flash Player 9.0.28. This
* fixes the Flash Version detection (Flash Object Detection) which was accepting Flash Player 9 versions before 9.0.28.
* - Removed old code block that was missed when moving from a Flash Timer to the JavaScript timeout (caused certain cancel events to be called twice)
* = Change ShowUI to the swfUploadLoaded event which will hopefully make it more clear that this is an overrideable event
* = Changed flashReady to behave like the other events (uses setTimeout and the Event Queue).
* --------- Revision 7.0 beta 2 -----------
* = Changed ERROR_CODE_FILE_NOT_FOUND to ERROR_CODE_FILE_ID_NOT_FOUND
* + Grouped the error code constants in objects for queue errors and upload errors.
* + Added an UPLOAD_STOPPED error code.
* = Changed Event calling method (using Timer) in Flash. Timer is no longer called
* instead setTimeout is called in JavaScript. This includes a change to the
* JavaSCript design so the Event methods are not directly overridden but stored
* internally and called if defined (with a setTimeout). This is an effort
* be more compatible with the current Flash Player on Linux
* = Changed the parameter order for the fileQueueError and uploadError events so the fileObj is first, like other events.
* + Added an empty JavaScript object (customSettings) where users can store settings associated with the instance.
* + Worked around an escaping bug in the ExternalInterface library by escaping all backslashes in out-going strings.
* = Updated all the demos.
* --------- Revision 7.0 beta 1 -----------
* = Redesigned the Event Chain
* - Removed much of the queue concepts
* - Removed the fileValidation events. This can be done in the new uploadStart event
* - Removed beginUploadOnQueue feature. This can be done in the new dialogComplete event.
* - Removed use_server_data. This is now always on.
* + Added functions for retrieving queue stats (number of files uploaded, queued, errors, etc)
* + Added a file status property to the FileObject. This indicates, uploaded, error, waiting.
* + Added a single file browser (user cannot select multiple files)
* + Fixed bug (hopefully) caused if Flash call to JavaScript and in the callback JavaSCript calls to Flash
* This only place this does not apply is to uploadStart. If you call in to Flash from uploadStart use a setTimeout to do it.
* --------- Revision 6.2 -----------
* + Added API calls for changing all the changeable settings dynamically
* = Fixed a bug in FileComplete event handler (in the SWF) that caused an error in Debug Players
* and prevent the event from being called
* + Added a setting (use_server_data_event) to indicate whether FileComplete or ServerData should be called.
* The SWFUpload architecture requires that only one file upload success event can be called.
* = Updated all the Demos, especially the Features Demo and the Forms Demo
* --------- Revision 6 -----------
* - Removed the call to setUploadSettings in flashReady. This was a left over call that is unnecessary.
* + Finished the parsing of post params during the init stage. This ommision was hidden by the call to setUploadSettings.
* - Removed the flash_target_id setting. The Flash file should only ever be added to the body tag.
* + Fixed (hopefully for good) another SWF race condition. IE executes the SWF very very early. The this.movieElement value should never be referenced.
* The movie Element should always be retrieved using this.getMovieElement().
* --------- Revision 6 -----------
* + Ported to ActionScript 3. Revision 6 requires Flash Player 9.
* = Fixed bug caused when cancelling single files. Would break any function that searched for a file_id.
* - Removed the automatic cookie sending setting. Devs should just pass the value they want to send in the post_params
* - Removed the query params settings (global and file specific). All params should be sent in the post_params
* + Added post_params which adds post values to the file upload post.
* + Added validate_files setting flag which causes the fileValidation event to be called before each file is uploaded.
* + Added fileValidation event. Return false if validation fails and true if validation is successful.
* + Added server_data parameter to the fileComplete event which returns any text that the upload script returns.
* = Updated all demos to work with Revision 6
* + Added in-code file extension validation. Before a file is queued the extension is checked against the valid extensions.
* Files the have invalid extensions cause the error event to be raised.
* + Added 'file_post_name' setting that allows the post variable name containing the file data to be named something other than 'Filedata'
* = Fixed a race condition in loadFlash where a cached flash movie would execute before this.movieElement could be assigned and loading would fail.
* --------- Revision 5.2 -----------
* = A little more code cleaning and variable renaming
* + Changed from an array queue to a FIFO queue. This eliminates the "current_index" and
* should reduce some memory usage.
* + Added out of order file uploading. Call StartUpload(/file_id/).
* + Added custom query_string parameters in addition to the cookies
* + Added the ability to modify the URL, cookies, params and send to flash
* + Added per file query_string params
* + Added files queued limit. Sometimes you may want the user to only queue one file at a time (or something)
* + Fixed limits so a zero(0) value means unlimited.
* --------- Revision 5 -------------
* = More code cleaning. Ported SWF to FlashDevelop. (Since my Flash Studio trial expired)
* The port to FlashDevelop is a big deal. It significantly changes the code structure
* and could introduce bugs. Also there have been reported issues with the FlashDevelop
* version from swfupload.mammon.se: Doesn't start when reloading in IE. Doesn't start
* in Firefox if the SWF file is visible because of a page scroll.
* + I fixed the Firefox issue by removing the wmode attribute from the embed object.
* + I cannot reproduce the IE issue on my local machine (although I can reproduce it at swfupload.mammon.se)
* + Event Handlers are now attached to the SWFUpload javascript object. The SWF file
* now calls the handlers in the context of the SWFUpload object which means the "this"
* object inside the handler refers to the proper SWFUpload instance.
* + Tested and Fixed upload target cookie attachment
* = Cleaned up / renamed everything for clarity and consistancy
* + File queuing is now subject to the upload limit. If the user attempts to queue more files
* than allowed an error is returned and the files are not queued.
* + Fixed misc bugs and text encodings.
* + Added more debug info for the SWF file.
* + SWF file now obeys the debug setting.
* + Added SetUploadTargetURL function that allows you to "dynamically" change the upload target
* + Added error code for zero byte file uploads which always return an IO error. The files are now rejected
* instead of being uploaded.
* --------- Revision 4 -------------
* = Cleaned up code. Added comments. Reorganized. Added more try..catches. Removed old unused methods.
* - Removed the 'create_ui' setting. The UI is now completely up to the developer.
* + Added upload_backend_cookies setting. Can set a string, or array of cookie names. These values will be
* passed as part of the upload_backend url
*
* = Changed QueueComplete event to only fire if at least one file has been successfully uploaded.
* + Added "Stop Upload" feature.
* = Revised the FLA file to clean things up, better handle errors, etc.
* = Fixed a bug where cancelling the first upload would cause the remaining uploads to fire before calling
* "startUpload". This change is in the FLA.
*
* + Fixed a bug in the upload.swf that prevented further file processing after an error is returned.
* + Added uploadLimit variable. Only complete uploads are counted. Once the limit is reached the flash
* movie will not upload any more files. (The ability to select or queue many files is not affected
* by the upload limit)
* + Added cancelQueue and cancelUpload methods.
* + Added ID property to the FileObj in the upload.swf
* + Added Upload and Queue settings
* + Added methods for generating the flash HTML and inserting it into the DOM.
* - Removed SWFObject
* + Updated the upload.swf and added the "flashReady" event. This will only call back
* for Flash 8 and above. With this we don't need a flash version detect script.
* The script initializes the Flash then waits for the Callback to init the UI.
* + Added seperate ui_target, degraded_target, create_ui settings. This allows fine control
* over what parts of the GUI the script displays and hides
*
* + Changed from a Static Class to an Instance (changed code/class structure)
* + Added "flash_version" setting. When set to zero the version check is skipped
* + Added Debug Console. The Instance class can't do document.write.
* = De-obfuscated SWFObject a bit
* - Removed standalone mode.
* + Added "ui_target" setting. When non-blank the link is added.
* + Added "flash_target" setting. When blank the flash is appended to the <body> tag
* = This fixes ASP.Net not allowing the flash to be added to the Form
* + Added error checking to the callSWF method
*
* -------- -------- -------- -------- -------- -------- -------- --------
* SWFUpload 0.7: Flash upload dialog - http://profandesign.se/swfupload/
* SWFUpload is (c) 2006 Lars Huring, Olov Nilzén and Mammon Media and is released under the MIT License:
* http://www.opensource.org/licenses/mit-license.php
* -------- -------- -------- -------- -------- -------- -------- --------
* SWFUpload 0.7: Flash upload dialog - http://profandesign.se/swfupload/
*
* VERSION HISTORY
* 0.5 - First release
*
* 0.6 - 2006-11-24
* - Got rid of flash overlay
* - SWF size reduced to 840b
* - CSS-only styling of button
* - Add upload to links etc.
*
* 0.7 - 2006-11-27
* - Added filesize param and check in SWF
*
* 0.7.1 - 2006-12-01
* - Added link_mode param for standalone links
* if set to "standalone", createElement("a") won't run.
* - Added link_text param if css isn't needed.
* - Renamed cssClass to css_class for consistency
*
*/

File diff suppressed because it is too large Load Diff

View File

@ -1,121 +0,0 @@
package {
import flash.external.ExternalInterface;
internal class ExternalCall
{
/*public function ExternalCall()
{
}
*/
public static function Simple(callback:String):void {
ExternalInterface.call(callback);
}
public static function FileQueued(callback:String, file_object:Object):void {
ExternalInterface.call(callback, EscapeMessage(file_object));
}
public static function FileQueueError(callback:String, error_code:Number, file_object:Object, message:String):void {
ExternalInterface.call(callback, EscapeMessage(file_object), EscapeMessage(error_code), EscapeMessage(message));
}
public static function FileDialogComplete(callback:String, num_files_selected:Number, num_files_queued:Number, total_num_files_queued:Number):void {
ExternalInterface.call(callback, EscapeMessage(num_files_selected), EscapeMessage(num_files_queued), EscapeMessage(total_num_files_queued));
}
public static function UploadStart(callback:String, file_object:Object):void {
ExternalInterface.call(callback, EscapeMessage(file_object));
}
public static function UploadProgress(callback:String, file_object:Object, bytes_loaded:uint, bytes_total:uint):void {
ExternalInterface.call(callback, EscapeMessage(file_object), EscapeMessage(bytes_loaded), EscapeMessage(bytes_total));
}
public static function UploadSuccess(callback:String, file_object:Object, server_data:String, responseReceived:Boolean):void {
ExternalInterface.call(callback, EscapeMessage(file_object), EscapeMessage(server_data), EscapeMessage(responseReceived));
}
public static function UploadError(callback:String, error_code:Number, file_object:Object, message:String):void {
ExternalInterface.call(callback, EscapeMessage(file_object), EscapeMessage(error_code), EscapeMessage(message));
}
public static function UploadComplete(callback:String, file_object:Object):void {
ExternalInterface.call(callback, EscapeMessage(file_object));
}
public static function Debug(callback:String, message:String):void {
ExternalInterface.call(callback, EscapeMessage(message));
}
public static function Bool(callback:String):Boolean {
return ExternalInterface.call(callback);
}
/* Escapes all the backslashes which are not translated correctly in the Flash -> JavaScript Interface
*
* These functions had to be developed because the ExternalInterface has a bug that simply places the
* value a string in quotes (except for a " which is escaped) in a JavaScript string literal which
* is executed by the browser. These often results in improperly escaped string literals if your
* input string has any backslash characters. For example the string:
* "c:\Program Files\uploadtools\"
* is placed in a string literal (with quotes escaped) and becomes:
* var __flash__temp = "\"c:\Program Files\uploadtools\\"";
* This statement will cause errors when executed by the JavaScript interpreter:
* 1) The first \" is succesfully transformed to a "
* 2) \P is translated to P and the \ is lost
* 3) \u is interpreted as a unicode character and causes an error in IE
* 4) \\ is translated to \
* 5) leaving an unescaped " which causes an error
*
* I fixed this by escaping \ characters in all outgoing strings. The above escaped string becomes:
* var __flash__temp = "\"c:\\Program Files\\uploadtools\\\"";
* which contains the correct string literal.
*
* Note: The "var __flash__temp = " portion of the example is part of the ExternalInterface not part of
* my escaping routine.
*/
private static function EscapeMessage(message:*):* {
if (message is String) {
message = EscapeString(message);
}
else if (message is Array) {
message = EscapeArray(message);
}
else if (message is Object) {
message = EscapeObject(message);
}
return message;
}
private static function EscapeString(message:String):String {
var replacePattern:RegExp = /\\/g; //new RegExp("/\\/", "g");
return message.replace(replacePattern, "\\\\");
}
private static function EscapeArray(message_array:Array):Array {
var length:uint = message_array.length;
var i:uint = 0;
for (i; i < length; i++) {
message_array[i] = EscapeMessage(message_array[i]);
}
return message_array;
}
private static function EscapeObject(message_obj:Object):Object {
for (var name:String in message_obj) {
message_obj[name] = EscapeMessage(message_obj[name]);
}
return message_obj;
}
}
}

View File

@ -1,112 +0,0 @@
package {
import flash.net.FileReference;
internal class FileItem
{
private static var file_id_sequence:Number = 0; // tracks the file id sequence
private var postObject:Object;
public var file_reference:FileReference;
public var id:String;
public var index:Number = -1;
public var file_status:int = 0;
private var js_object:Object;
public static var FILE_STATUS_QUEUED:int = -1;
public static var FILE_STATUS_IN_PROGRESS:int = -2;
public static var FILE_STATUS_ERROR:int = -3;
public static var FILE_STATUS_SUCCESS:int = -4;
public static var FILE_STATUS_CANCELLED:int = -5;
public static var FILE_STATUS_NEW:int = -6; // This file status should never be sent to JavaScript
public function FileItem(file_reference:FileReference, control_id:String, index:Number)
{
this.postObject = {};
this.file_reference = file_reference;
this.id = control_id + "_" + (FileItem.file_id_sequence++);
this.file_status = FileItem.FILE_STATUS_NEW;
this.index = index;
this.js_object = {
id: this.id,
index: this.index,
post: this.GetPostObject()
};
// Cleanly attempt to retrieve the FileReference info
// this can fail and so is wrapped in try..catch
try {
this.js_object.name = this.file_reference.name;
this.js_object.size = this.file_reference.size;
this.js_object.type = this.file_reference.type || "";
this.js_object.creationdate = this.file_reference.creationDate || new Date(0);
this.js_object.modificationdate = this.file_reference.modificationDate || new Date(0);
} catch (ex:Error) {
this.file_status = FileItem.FILE_STATUS_ERROR;
}
this.js_object.filestatus = this.file_status;
}
public function AddParam(name:String, value:String):void {
this.postObject[name] = value;
}
public function RemoveParam(name:String):void {
delete this.postObject[name];
}
public function GetPostObject(escape:Boolean = false):Object {
if (escape) {
var escapedPostObject:Object = { };
for (var k:String in this.postObject) {
if (this.postObject.hasOwnProperty(k)) {
var escapedName:String = FileItem.EscapeParamName(k);
escapedPostObject[escapedName] = this.postObject[k];
}
}
return escapedPostObject;
} else {
return this.postObject;
}
}
// Create the simply file object that is passed to the browser
public function ToJavaScriptObject():Object {
this.js_object.filestatus = this.file_status;
this.js_object.post = this.GetPostObject(true);
return this.js_object;
}
public function toString():String {
return "FileItem - ID: " + this.id;
}
/*
// The purpose of this function is to escape the property names so when Flash
// passes them back to javascript they can be interpretted correctly.
// ***They have to be unescaped again by JavaScript.**
//
// This works around a bug where Flash sends objects this way:
// object.parametername = "value";
// instead of
// object["parametername"] = "value";
// This can be a problem if the parameter name has characters that are not
// allowed in JavaScript identifiers:
// object.parameter.name! = "value";
// does not work but,
// object["parameter.name!"] = "value";
// would have worked.
*/
public static function EscapeParamName(name:String):String {
name = name.replace(/[^a-z0-9_]/gi, FileItem.EscapeCharacter);
name = name.replace(/^[0-9]/, FileItem.EscapeCharacter);
return name;
}
public static function EscapeCharacter():String {
return "$" + ("0000" + arguments[0].charCodeAt(0).toString(16)).substr(-4, 4);
}
}
}

View File

@ -1,79 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<project>
<!-- Output SWF options -->
<output>
<movie disabled="False" />
<movie input="" />
<movie path="swfupload.swf" />
<movie fps="15" />
<movie width="300" />
<movie height="300" />
<movie version="9" />
<movie background="#FFFFFF" />
</output>
<!-- Other classes to be compiled into your SWF -->
<classpaths>
<class path="." />
</classpaths>
<!-- Build options -->
<build>
<option accessible="False" />
<option allowSourcePathOverlap="False" />
<option benchmark="False" />
<option es="False" />
<option loadConfig="" />
<option optimize="True" />
<option showActionScriptWarnings="True" />
<option showBindingWarnings="True" />
<option showDeprecationWarnings="True" />
<option showUnusedTypeSelectorWarnings="True" />
<option strict="True" />
<option useNetwork="True" />
<option useResourceBundleMetadata="True" />
<option warnings="True" />
<option verboseStackTraces="False" />
<option additional="" />
<option customSDK="" />
</build>
<!-- SWC Include Libraries -->
<includeLibraries>
<!-- example: <element path="..." /> -->
</includeLibraries>
<!-- SWC Libraries -->
<libraryPaths>
<!-- example: <element path="..." /> -->
</libraryPaths>
<!-- External Libraries -->
<externalLibraryPaths>
<!-- example: <element path="..." /> -->
</externalLibraryPaths>
<!-- Runtime Shared Libraries -->
<rslPaths>
<!-- example: <element path="..." /> -->
</rslPaths>
<!-- Intrinsic Libraries -->
<intrinsics>
<!-- example: <element path="..." /> -->
</intrinsics>
<!-- Assets to embed into the output SWF -->
<library>
<!-- example: <asset path="..." id="..." update="..." glyphs="..." mode="..." place="..." sharepoint="..." /> -->
</library>
<!-- Class files to compile (other referenced classes will automatically be included) -->
<compileTargets>
<compile path="SWFUpload.as" />
</compileTargets>
<!-- Paths to exclude from the Project Explorer tree -->
<hiddenPaths>
<!-- example: <hidden path="..." /> -->
</hiddenPaths>
<!-- Executed before build -->
<preBuildCommand />
<!-- Executed after build -->
<postBuildCommand alwaysRun="True">deploy.bat</postBuildCommand>
<!-- Other project options -->
<options>
<option showHiddenPaths="False" />
<option testMovie="NewWindow" />
</options>
</project>

File diff suppressed because it is too large Load Diff

View File

@ -1,3 +0,0 @@
@echo off
copy ..\swfupload.js ..\..\samples\demos\swfupload
copy swfupload.swf ..\..\samples\demos\swfupload

View File

@ -1,22 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<!--Flex compiler config for project SWFUpload-v2 generated by FDBuild-->
<!--============-->
<!--This file was generated by a tool.-->
<!--Any modifications you make may be lost.-->
<flex-config>
<compiler>
<source-path append="true">
<path-element>C:\inetpub\wwwroot\other\swfupload\core\Flash</path-element>
<path-element>C:\Program Files (x86)\FlashDevelop\Library\AS3\classes</path-element>
</source-path>
</compiler>
<file-specs>
<path-element>C:\inetpub\wwwroot\other\swfupload\core\Flash\SWFUpload.as</path-element>
</file-specs>
<default-background-color>#FFFFFF</default-background-color>
<default-frame-rate>15</default-frame-rate>
<default-size>
<width>300</width>
<height>300</height>
</default-size>
</flex-config>

View File

@ -1,22 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<!--Flex compiler config for project SWFUpload-v2 generated by FDBuild-->
<!--============-->
<!--This file was generated by a tool.-->
<!--Any modifications you make may be lost.-->
<flex-config>
<compiler>
<source-path append="true">
<path-element>C:\inetpub\wwwroot\other\swfupload\core\Flash</path-element>
<path-element>C:\Program Files (x86)\FlashDevelop\Library\AS3\classes</path-element>
</source-path>
</compiler>
<file-specs>
<path-element>C:\inetpub\wwwroot\other\swfupload\core\Flash\SWFUpload.as</path-element>
</file-specs>
<default-background-color>#FFFFFF</default-background-color>
<default-frame-rate>15</default-frame-rate>
<default-size>
<width>300</width>
<height>300</height>
</default-size>
</flex-config>

View File

@ -1,4 +0,0 @@
/* SWFObject v2.0 rc4 <http://code.google.com/p/swfobject/>
Copyright (c) 2007 Geoff Stearns, Michael Williams, and Bobby van der Sluis
This software is released under the MIT License <http://www.opensource.org/licenses/mit-license.php>
*/

View File

@ -1,53 +0,0 @@
/*
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);
}
};
}

View File

@ -1,98 +0,0 @@
/*
Queue Plug-in
Features:
*Adds a cancelQueue() method for cancelling the entire queue.
*All queued files are uploaded when startUpload() is called.
*If false is returned from uploadComplete then the queue upload is stopped.
If false is not returned (strict comparison) then the queue upload is continued.
*Adds a QueueComplete event that is fired when all the queued files have finished uploading.
Set the event handler with the queue_complete_handler setting.
*/
var SWFUpload;
if (typeof(SWFUpload) === "function") {
SWFUpload.queue = {};
SWFUpload.prototype.initSettings = (function (oldInitSettings) {
return function () {
if (typeof(oldInitSettings) === "function") {
oldInitSettings.call(this);
}
this.queueSettings = {};
this.queueSettings.queue_cancelled_flag = false;
this.queueSettings.queue_upload_count = 0;
this.queueSettings.user_upload_complete_handler = this.settings.upload_complete_handler;
this.queueSettings.user_upload_start_handler = this.settings.upload_start_handler;
this.settings.upload_complete_handler = SWFUpload.queue.uploadCompleteHandler;
this.settings.upload_start_handler = SWFUpload.queue.uploadStartHandler;
this.settings.queue_complete_handler = this.settings.queue_complete_handler || null;
};
})(SWFUpload.prototype.initSettings);
SWFUpload.prototype.startUpload = function (fileID) {
this.queueSettings.queue_cancelled_flag = false;
this.callFlash("StartUpload", [fileID]);
};
SWFUpload.prototype.cancelQueue = function () {
this.queueSettings.queue_cancelled_flag = true;
this.stopUpload();
var stats = this.getStats();
while (stats.files_queued > 0) {
this.cancelUpload();
stats = this.getStats();
}
};
SWFUpload.queue.uploadStartHandler = function (file) {
var returnValue;
if (typeof(this.queueSettings.user_upload_start_handler) === "function") {
returnValue = this.queueSettings.user_upload_start_handler.call(this, file);
}
// To prevent upload a real "FALSE" value must be returned, otherwise default to a real "TRUE" value.
returnValue = (returnValue === false) ? false : true;
this.queueSettings.queue_cancelled_flag = !returnValue;
return returnValue;
};
SWFUpload.queue.uploadCompleteHandler = function (file) {
var user_upload_complete_handler = this.queueSettings.user_upload_complete_handler;
var continueUpload;
if (file.filestatus === SWFUpload.FILE_STATUS.COMPLETE) {
this.queueSettings.queue_upload_count++;
}
if (typeof(user_upload_complete_handler) === "function") {
continueUpload = (user_upload_complete_handler.call(this, file) === false) ? false : true;
} else if (file.filestatus === SWFUpload.FILE_STATUS.QUEUED) {
// If the file was stopped and re-queued don't restart the upload
continueUpload = false;
} else {
continueUpload = true;
}
if (continueUpload) {
var stats = this.getStats();
if (stats.files_queued > 0 && this.queueSettings.queue_cancelled_flag === false) {
this.startUpload();
} else if (this.queueSettings.queue_cancelled_flag === false) {
this.queueEvent("queue_complete_handler", [this.queueSettings.queue_upload_count]);
this.queueSettings.queue_upload_count = 0;
} else {
this.queueSettings.queue_cancelled_flag = false;
this.queueSettings.queue_upload_count = 0;
}
}
};
}

View File

@ -1,342 +0,0 @@
/*
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;
};
}

File diff suppressed because one or more lines are too long

View File

@ -1,12 +0,0 @@
/**
* SWFUpload: http://www.swfupload.org, http://swfupload.googlecode.com
*
* mmSWFUpload 1.0: Flash upload dialog - http://profandesign.se/swfupload/, http://www.vinterwebb.se/
*
* SWFUpload is (c) 2006-2007 Lars Huring, Olov Nilzén and Mammon Media and is released under the MIT License:
* http://www.opensource.org/licenses/mit-license.php
*
* SWFUpload 2 is (c) 2007-2008 Jake Roberts and is released under the MIT License:
* http://www.opensource.org/licenses/mit-license.php
*
*/

View File

@ -1,980 +0,0 @@
/**
* SWFUpload: http://www.swfupload.org, http://swfupload.googlecode.com
*
* mmSWFUpload 1.0: Flash upload dialog - http://profandesign.se/swfupload/, http://www.vinterwebb.se/
*
* SWFUpload is (c) 2006-2007 Lars Huring, Olov Nilzén and Mammon Media and is released under the MIT License:
* http://www.opensource.org/licenses/mit-license.php
*
* SWFUpload 2 is (c) 2007-2008 Jake Roberts and is released under the MIT License:
* http://www.opensource.org/licenses/mit-license.php
*
*/
/* ******************* */
/* Constructor & Init */
/* ******************* */
var SWFUpload;
if (SWFUpload == undefined) {
SWFUpload = function (settings) {
this.initSWFUpload(settings);
};
}
SWFUpload.prototype.initSWFUpload = function (settings) {
try {
this.customSettings = {}; // A container where developers can place their own settings associated with this instance.
this.settings = settings;
this.eventQueue = [];
this.movieName = "SWFUpload_" + SWFUpload.movieCount++;
this.movieElement = null;
// Setup global control tracking
SWFUpload.instances[this.movieName] = this;
// Load the settings. Load the Flash movie.
this.initSettings();
this.loadFlash();
this.displayDebugInfo();
} catch (ex) {
delete SWFUpload.instances[this.movieName];
throw ex;
}
};
/* *************** */
/* Static Members */
/* *************** */
SWFUpload.instances = {};
SWFUpload.movieCount = 0;
SWFUpload.version = "2.2.0 2009-03-25";
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
};
SWFUpload.CURSOR = {
ARROW : -1,
HAND : -2
};
SWFUpload.WINDOW_MODE = {
WINDOW : "window",
TRANSPARENT : "transparent",
OPAQUE : "opaque"
};
// Private: takes a URL, determines if it is relative and converts to an absolute URL
// using the current site. Only processes the URL if it can, otherwise returns the URL untouched
SWFUpload.completeURL = function(url) {
if (typeof(url) !== "string" || url.match(/^https?:\/\//i) || url.match(/^\//)) {
return url;
}
var currentURL = window.location.protocol + "//" + window.location.hostname + (window.location.port ? ":" + window.location.port : "");
var indexSlash = window.location.pathname.lastIndexOf("/");
if (indexSlash <= 0) {
path = "/";
} else {
path = window.location.pathname.substr(0, indexSlash) + "/";
}
return /*currentURL +*/ path + url;
};
/* ******************** */
/* Instance Members */
/* ******************** */
// Private: initSettings ensures that all the
// settings are set, getting a default value if one was not assigned.
SWFUpload.prototype.initSettings = function () {
this.ensureDefault = function (settingName, defaultValue) {
this.settings[settingName] = (this.settings[settingName] == undefined) ? defaultValue : this.settings[settingName];
};
// Upload backend settings
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);
// File Settings
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);
// Flash Settings
this.ensureDefault("flash_url", "swfupload.swf");
this.ensureDefault("prevent_swf_caching", true);
// Button Settings
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);
// Debug Settings
this.ensureDefault("debug", false);
this.settings.debug_enabled = this.settings.debug; // Here to maintain v2 API
// Event Handlers
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("debug_handler", this.debugMessage);
this.ensureDefault("custom_settings", {});
// Other settings
this.customSettings = this.settings.custom_settings;
// Update the flash url if needed
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.flash_url = SWFUpload.completeURL(this.settings.flash_url); // Don't need to do this one since flash doesn't look at it
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;
};
// Private: loadFlash replaces the button_placeholder element with the flash movie.
SWFUpload.prototype.loadFlash = function () {
var targetElement, tempParent;
// Make sure an element with the ID we are going to use doesn't already exist
if (document.getElementById(this.movieName) !== null) {
throw "ID " + this.movieName + " is already in use. The Flash Object could not be added";
}
// Get the element where we will be placing the flash movie
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;
}
// Append the container and load the flash
tempParent = document.createElement("div");
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);
// Fix IE Flash/Form bug
if (window[this.movieName] == undefined) {
window[this.movieName] = this.getMovieElement();
}
};
// Private: getFlashHTML generates the object tag needed to embed the flash in to the document
SWFUpload.prototype.getFlashHTML = function () {
// Flash Satay object syntax: http://www.alistapart.com/articles/flashsatay
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("");
};
// 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),
"&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("");
};
// 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&amp;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("&amp;");
};
// 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('<invoke name="' + functionName + '" returntype="javascript">' + __flash__argumentsToXML(argumentArray, 0) + '</invoke>');
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);
}
};