add the rest of Clutch to m0k.org's svn

This commit is contained in:
Charles Kerr
2008-07-10 23:57:46 +00:00
parent f2022675bd
commit 2a1f6c8923
36 changed files with 9681 additions and 0 deletions

367
web/javascript/common.js Normal file
View File

@@ -0,0 +1,367 @@
/*
* Copyright © Dave Perrett and Malcolm Jarvis
* This code is licensed under the GPL version 2.
* For more details, see http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
* Common javascript
*/
var transmission;
var dialog;
// Test for a Webkit build that supports box-shadow: 521+ (release Safari 3 is
// actually 523.10.3). We need 3.1 for CSS animation (dialog sheets) but as it
// degrades gracefully let's not worry too much.
var Safari3 = testSafari3();
var iPhone = RegExp("(iPhone|iPod)").test(navigator.userAgent);
if (iPhone) var scroll_timeout;
/* (is this used?)
function updateLayout()
{
if (iPhone) {
switch(window.orientation) {
case -90:
$('body').addClass('landscape');
break;
case 90:
$('body').addClass('landscape');
break;
default:
$('body.landscape').removeClass('landscape');
break;
}
transmission.hideiPhoneAddressbar(0.4);
}
};
*/
function testSafari3()
{
var minimum = new Array(521,0);
var webKitFields = RegExp("( AppleWebKit/)([^ ]+)").exec(navigator.userAgent);
if (!webKitFields || webKitFields.length < 3) return false;
var version = webKitFields[2].split(".");
for (var i = 0; i < minimum.length; i++) {
var toInt = parseInt(version[i]);
var versionField = isNaN(toInt) ? 0 : toInt;
var minimumField = minimum[i];
if (versionField > minimumField) return true;
if (versionField < minimumField) return false;
}
return true;
};
$(document).ready( function() {
// Initialise a torrent controller to handle events
// Initialise the dialog controller
dialog = new Dialog();
// Initialise the main Transmission controller
transmission = new Transmission();
if ($.browser.safari) {
// Fix div height problem - causes scrollbar flash in
// firefox so have to be safari-specific
$('#torrent_inspector').css('height', '100%');
// Set Filter input to type search (nicely styled input field)
$('#torrent_search')[0].type = 'search';
$('#torrent_search')[0].placeholder = 'Filter';
$('#torrent_search').css('margin-top', 3);
}
if (!Safari3 && !iPhone) {
// Fix for non-Safari-3 browsers: dark borders to replace shadows.
// Opera messes up the menu if we use a border on .trans_menu
// div.outerbox so use ul instead
$('.trans_menu ul, div#jqContextMenu, div.dialog_container div.dialog_window').css('border', '1px solid #777');
// and this kills the border we used to have
$('.trans_menu div.outerbox').css('border', 'none');
} else if (!iPhone) {
// Used for Safari 3.1 CSS animation. Degrades gracefully (so Safari 3
// test is good enough) but we delay our hide/unhide to wait for the
// scrolling - no point making other browsers wait.
$('div#upload_container div.dialog_window').css('top', '-205px');
$('div#prefs_container div.dialog_window').css('top', '-425px');
$('div#dialog_container div.dialog_window').css('top', '-425px');
$('div.dialog_container div.dialog_window').css('-webkit-transition', 'top 0.3s');
// -webkit-appearance makes some links into buttons, but needs
// different padding.
$('div.dialog_container div.dialog_window a').css('padding', '2px 10px 3px');
}
if ($.browser.mozilla) {
$('div#prefs_container div.preference input').css('height', 'auto');
$('div#prefs_container div.preference input').css('padding', '1px');
$('div#prefs_container div.preference input').css('margin-top', '2px');
}
});
/*
* Return a copy of the array
*
* @returns array
*/
Array.prototype.clone = function () {
return this.concat();
};
/**
* "innerHTML = html" is pretty slow in FF. Happily a lot of our innerHTML
* changes are triggered by periodic refreshes on torrents whose state hasn't
* changed sine the last update, so even this simple test helps a lot.
*/
function setInnerHTML( e, html )
{
if( e.innerHTML != html )
e.innerHTML = html;
};
/*
* Converts file & folder byte size values to more
* readable values (bytes, KB, MB, GB or TB).
*
* @param integer bytes
* @returns string
*/
Math.formatBytes = function(bytes) {
var size;
var unit;
// Terabytes (TB).
if ( bytes >= 1099511627776 ) {
size = bytes / 1099511627776;
unit = ' TB';
// Gigabytes (GB).
} else if ( bytes >= 1073741824 ) {
size = bytes / 1073741824;
unit = ' GB';
// Megabytes (MB).
} else if ( bytes >= 1048576 ) {
size = bytes / 1048576;
unit = ' MB';
// Kilobytes (KB).
} else if ( bytes >= 1024 ) {
size = bytes / 1024;
unit = ' KB';
// The file is less than one KB
} else {
size = bytes;
unit = ' bytes';
}
// Single-digit numbers have greater precision
var precision = 1;
if (size < 10) {
precision = 2;
}
size = Math.roundWithPrecision(size, precision);
// Add the decimal if this is an integer
if ((size % 1) == 0 && unit != ' bytes') {
size = size + '.0';
}
return size + unit;
};
/*
* Converts seconds to more readable units (hours, minutes etc).
*
* @param integer seconds
* @returns string
*/
Math.formatSeconds = function(seconds)
{
var result;
var days = Math.floor(seconds / 86400);
var hours = Math.floor((seconds % 86400) / 3600);
var minutes = Math.floor((seconds % 3600) / 60);
var seconds = Math.floor((seconds % 3600) % 60);
if (days > 0 && hours == 0)
result = days + ' days';
else if (days > 0 && hours > 0)
result = days + ' days ' + hours + ' hr';
else if (hours > 0 && minutes == 0)
result = hours + ' hr';
else if (hours > 0 && minutes > 0)
result = hours + ' hr ' + minutes + ' min';
else if (minutes > 0 && seconds == 0)
result = minutes + ' min';
else if (minutes > 0 && seconds > 0)
result = minutes + ' min ' + seconds + ' seconds';
else
result = seconds + ' seconds';
return result;
};
/*
* Converts a unix timestamp to a human readable value
*
* @param integer seconds
* @returns string
*/
Math.formatTimestamp = function(seconds) {
var myDate = new Date(seconds*1000);
return myDate.toGMTString();
};
/*
* Round a float to a specified number of decimal
* places, stripping trailing zeroes
*
* @param float floatnum
* @param integer precision
* @returns float
*/
Math.roundWithPrecision = function(floatnum, precision) {
return Math.round ( floatnum * Math.pow ( 10, precision ) ) / Math.pow ( 10, precision );
};
/*
* Given a numerator and denominator, return a ratio string
*/
Math.ratio = function( numerator, denominator )
{
var result = Math.roundWithPrecision((numerator / denominator), 2);
// check for special cases
if (isNaN(result)) result = 0;
if (result=="Infinity") result = "&infin;";
// Add the decimals if this is an integer
if ((result % 1) == 0)
result = result + '.00';
return result;
};
/*
* Trim whitespace from a string
*/
String.prototype.trim = function () {
return this.replace(/^\s*/, "").replace(/\s*$/, "");
}
/**
* @brief strcmp()-style compare useful for sorting
*/
String.prototype.compareTo = function( that ) {
// FIXME: how to fold these two comparisons together?
if( this < that ) return -1;
if( this > that ) return 1;
return 0;
}
/***
**** Preferences
***/
function Prefs() { }
Prefs.prototype = { };
Prefs._AutoStart = 'auto-start-torrents';
Prefs._RefreshRate = 'refresh_rate';
Prefs._ShowFilter = 'show_filter';
Prefs._ShowInspector = 'show_inspector';
Prefs._FilterMode = 'filter';
Prefs._FilterAll = 'all';
Prefs._FilterSeeding = 'seeding';
Prefs._FilterDownloading = 'downloading';
Prefs._FilterPaused = 'paused';
Prefs._SortDirection = 'sort_direction';
Prefs._SortAscending = 'ascending';
Prefs._SortDescending = 'descending';
Prefs._SortMethod = 'sort_method';
Prefs._SortByAge = 'age';
Prefs._SortByActivity = 'activity';
Prefs._SortByQueue = 'queue_order';
Prefs._SortByName = 'name';
Prefs._SortByProgress = 'percent_completed';
Prefs._SortByState = 'state';
Prefs._SortByTracker = 'tracker';
Prefs._Defaults =
{
'auto-start-torrents': true,
'filter': 'all',
'refresh_rate' : 5,
'show_filter': true,
'show_inspector': false,
'sort_direction': 'ascending',
'sort_method': 'name'
};
/*
* Set a preference option
*/
Prefs.setValue = function( key, val )
{
if( Prefs._Defaults[key] == undefined )
console.warn( "unrecognized preference key '%s'", key );
var days = 30;
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
document.cookie = key+"="+val+"; expires="+date.toGMTString()+"; path=/";
};
/**
* Get a preference option
*
* @param key the preference's key
* @param fallback if the option isn't set, return this instead
*/
Prefs.getValue = function( key, fallback )
{
var val;
if( Prefs._Defaults[key] == undefined )
console.warn( "unrecognized preference key '%s'", key );
var lines = document.cookie.split( ';' );
for( var i=0, len=lines.length; !val && i<len; ++i ) {
var line = lines[i].trim( );
var delim = line.indexOf( '=' );
if( ( delim == key.length ) && line.indexOf( key ) == 0 )
val = line.substring( delim + 1 );
}
// FIXME: we support strings and booleans... add number support too?
if( !val ) val = fallback;
else if( val == 'true' ) val = true;
else if( val == 'false' ) val = false;
return val;
};
/**
* Get an object with all the Clutch preferences set
*
* @pararm o object to be populated (optional)
*/
Prefs.getClutchPrefs = function( o )
{
if( !o )
o = { };
for( var key in Prefs._Defaults )
o[key] = Prefs.getValue( key, Prefs._Defaults[key] );
return o;
};

147
web/javascript/dialog.js Normal file
View File

@@ -0,0 +1,147 @@
/*
* Copyright © Dave Perrett and Malcolm Jarvis
* This code is licensed under the GPL version 2.
* For more details, see http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
* Class Dialog
*/
function Dialog(){
this.initialize();
}
Dialog.prototype = {
/*
* Constructor
*/
initialize: function() {
/*
* Private Interface Variables
*/
this._container = $('#dialog_container');
this._heading = $('#dialog_heading');
this._message = $('#dialog_message');
this._cancel_button = $('#dialog_cancel_button');
this._confirm_button = $('#dialog_confirm_button');
this._callback_function = '';
this._callback_data = null;
// Observe the buttons
this._cancel_button.bind('click', {dialog: this}, this.onCancelClicked );
this._confirm_button.bind('click', {dialog: this}, this.onConfirmClicked );
},
/*--------------------------------------------
*
* E V E N T F U N C T I O N S
*
*--------------------------------------------*/
hideDialog: function( )
{
$('body.dialog_showing').removeClass('dialog_showing');
if (Safari3) {
$('div#dialog_container div.dialog_window').css('top', '-150px');
setTimeout("dialog._container.hide();",500);
} else {
this._container.hide();
transmission.hideiPhoneAddressbar();
}
transmission.updateButtonStates();
},
onCancelClicked: function( event )
{
event.data.dialog.hideDialog( );
},
onConfirmClicked: function( event )
{
var dialog = event.data.dialog;
eval( dialog._callback_function + "(dialog._callback_data)" );
dialog.hideDialog( );
},
/*--------------------------------------------
*
* I N T E R F A C E F U N C T I O N S
*
*--------------------------------------------*/
/*
* Display a confirm dialog
*/
confirm: function(dialog_heading, dialog_message, confirm_button_label, callback_function, callback_data, cancel_button_label) {
if (!iPhone && Safari3) {
$('div#upload_container div.dialog_window').css('top', '-205px');
$('div#prefs_container div.dialog_window').css('top', '-425px');
setTimeout("$('#upload_container').hide();",500);
setTimeout("$('#prefs_container').hide();",500);
} else if (!iPhone) {
$('.dialog_container').hide();
}
setInnerHTML( this._heading[0], dialog_heading );
setInnerHTML( this._message[0], dialog_message );
setInnerHTML( this._cancel_button[0], (cancel_button_label == null) ? 'Cancel' : cancel_button_label );
setInnerHTML( this._confirm_button[0], confirm_button_label );
this._confirm_button.show();
this._callback_function = callback_function;
this._callback_data = callback_data;
$('body').addClass('dialog_showing');
this._container.show();
transmission.updateButtonStates();
if (iPhone) {
transmission.hideiPhoneAddressbar();
} else if (Safari3) {
setTimeout("$('div#dialog_container div.dialog_window').css('top', '0px');",10);
}
},
/*
* Display an alert dialog
*/
alert: function(dialog_heading, dialog_message, cancel_button_label) {
if (!iPhone && Safari3) {
$('div#upload_container div.dialog_window').css('top', '-205px');
$('div#prefs_container div.dialog_window').css('top', '-425px');
setTimeout("$('#upload_container').hide();",500);
setTimeout("$('#prefs_container').hide();",500);
} else if (!iPhone) {
$('.dialog_container').hide();
}
setInnerHTML( this._heading[0], dialog_heading );
setInnerHTML( this._message[0], dialog_message );
// jquery::hide() doesn't work here in Safari for some odd reason
this._confirm_button.css('display', 'none');
setInnerHTML( this._cancel_button[0], cancel_button_label );
// Just in case
if (!iPhone && Safari3) {
$('div#upload_container div.dialog_window').css('top', '-205px');
setTimeout("$('#upload_container').hide();",500);
} else {
$('#upload_container').hide();
}
$('body').addClass('dialog_showing');
transmission.updateButtonStates();
if (iPhone) {
transmission.hideiPhoneAddressbar();
this._container.show();
} else if (Safari3) {
// long pause as we just hid all the dialogs on a timeout - we'll get the error
// scrolling in and immediately disappearing if we're not careful!
//dialogTimeout = null;
this._container.show();
setTimeout("$('div#dialog_container div.dialog_window').css('top', '0px');",500);
} else {
this._container.show();
}
}
}

3549
web/javascript/jquery/jquery-1.2.6.js vendored Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,119 @@
/* Copyright (c) 2007 Paul Bakaus (paul.bakaus@googlemail.com) and Brandon Aaron (brandon.aaron@gmail.com || 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.
*
* $LastChangedDate: 2007-12-20 08:46:55 -0600 (Thu, 20 Dec 2007) $
* $Rev: 4259 $
*
* Version: 1.2
*
* Requires: jQuery 1.2+
*/
(function($){
$.dimensions = {
version: '1.2'
};
// Create innerHeight, innerWidth, outerHeight and outerWidth methods
$.each( [ 'Height', 'Width' ], function(i, name){
// innerHeight and innerWidth
$.fn[ 'inner' + name ] = function() {
if (!this[0]) return;
var torl = name == 'Height' ? 'Top' : 'Left', // top or left
borr = name == 'Height' ? 'Bottom' : 'Right'; // bottom or right
return this.is(':visible') ? this[0]['client' + name] : num( this, name.toLowerCase() ) + num(this, 'padding' + torl) + num(this, 'padding' + borr);
};
// outerHeight and outerWidth
$.fn[ 'outer' + name ] = function(options) {
if (!this[0]) return;
var torl = name == 'Height' ? 'Top' : 'Left', // top or left
borr = name == 'Height' ? 'Bottom' : 'Right'; // bottom or right
options = $.extend({ margin: false }, options || {});
var val = this.is(':visible') ?
this[0]['offset' + name] :
num( this, name.toLowerCase() )
+ num(this, 'border' + torl + 'Width') + num(this, 'border' + borr + 'Width')
+ num(this, 'padding' + torl) + num(this, 'padding' + borr);
return val + (options.margin ? (num(this, 'margin' + torl) + num(this, 'margin' + borr)) : 0);
};
});
// Create scrollLeft and scrollTop methods
$.each( ['Left', 'Top'], function(i, name) {
$.fn[ 'scroll' + name ] = function(val) {
if (!this[0]) return;
return val != undefined ?
// Set the scroll offset
this.each(function() {
this == window || this == document ?
window.scrollTo(
name == 'Left' ? val : $(window)[ 'scrollLeft' ](),
name == 'Top' ? val : $(window)[ 'scrollTop' ]()
) :
this[ 'scroll' + name ] = val;
}) :
// Return the scroll offset
this[0] == window || this[0] == document ?
self[ (name == 'Left' ? 'pageXOffset' : 'pageYOffset') ] ||
$.boxModel && document.documentElement[ 'scroll' + name ] ||
document.body[ 'scroll' + name ] :
this[0][ 'scroll' + name ];
};
});
$.fn.extend({
position: function() {
var left = 0, top = 0, elem = this[0], offset, parentOffset, offsetParent, results;
if (elem) {
// Get *real* offsetParent
offsetParent = this.offsetParent();
// Get correct offsets
offset = this.offset();
parentOffset = offsetParent.offset();
// Subtract element margins
offset.top -= num(elem, 'marginTop');
offset.left -= num(elem, 'marginLeft');
// Add offsetParent borders
parentOffset.top += num(offsetParent, 'borderTopWidth');
parentOffset.left += num(offsetParent, 'borderLeftWidth');
// Subtract the two offsets
results = {
top: offset.top - parentOffset.top,
left: offset.left - parentOffset.left
};
}
return results;
},
offsetParent: function() {
var offsetParent = this[0].offsetParent;
while ( offsetParent && (!/^body|html$/i.test(offsetParent.tagName) && $.css(offsetParent, 'position') == 'static') )
offsetParent = offsetParent.offsetParent;
return $(offsetParent);
}
});
function num(el, prop) {
return parseInt($.curCSS(el.jquery?el[0]:el,prop,true))||0;
};
})(jQuery);

View File

@@ -0,0 +1,6 @@
(function($){$.dimensions={version:'1.2'};$.each(['Height','Width'],function(i,name){$.fn['inner'+name]=function(){if(!this[0])return;var torl=name=='Height'?'Top':'Left',borr=name=='Height'?'Bottom':'Right';return this.is(':visible')?this[0]['client'+name]:num(this,name.toLowerCase())+num(this,'padding'+torl)+num(this,'padding'+borr);};$.fn['outer'+name]=function(options){if(!this[0])return;var torl=name=='Height'?'Top':'Left',borr=name=='Height'?'Bottom':'Right';options=$.extend({margin:false},options||{});var val=this.is(':visible')?this[0]['offset'+name]:num(this,name.toLowerCase())
+num(this,'border'+torl+'Width')+num(this,'border'+borr+'Width')
+num(this,'padding'+torl)+num(this,'padding'+borr);return val+(options.margin?(num(this,'margin'+torl)+num(this,'margin'+borr)):0);};});$.each(['Left','Top'],function(i,name){$.fn['scroll'+name]=function(val){if(!this[0])return;return val!=undefined?this.each(function(){this==window||this==document?window.scrollTo(name=='Left'?val:$(window)['scrollLeft'](),name=='Top'?val:$(window)['scrollTop']()):this['scroll'+name]=val;}):this[0]==window||this[0]==document?self[(name=='Left'?'pageXOffset':'pageYOffset')]||$.boxModel&&document.documentElement['scroll'+name]||document.body['scroll'+name]:this[0]['scroll'+name];};});$.fn.extend({position:function(){var left=0,top=0,elem=this[0],offset,parentOffset,offsetParent,results;if(elem){offsetParent=this.offsetParent();offset=this.offset();parentOffset=offsetParent.offset();offset.top-=num(elem,'marginTop');offset.left-=num(elem,'marginLeft');parentOffset.top+=num(offsetParent,'borderTopWidth');parentOffset.left+=num(offsetParent,'borderLeftWidth');results={top:offset.top-parentOffset.top,left:offset.left-parentOffset.left};}
return results;},offsetParent:function(){var offsetParent=this[0].offsetParent;while(offsetParent&&(!/^body|html$/i.test(offsetParent.tagName)&&$.css(offsetParent,'position')=='static'))
offsetParent=offsetParent.offsetParent;return $(offsetParent);}});function num(el,prop){return parseInt($.curCSS(el.jquery?el[0]:el,prop,true))||0;};})(jQuery);

View File

@@ -0,0 +1,7 @@
(function($){var menu,shadow,trigger,content,hash,currentTarget;var defaults={menuStyle:{listStyle:'none',padding:'1px',margin:'0px',backgroundColor:'#fff',border:'1px solid #999',width:'100px'},itemStyle:{margin:'0px',color:'#000',display:'block',cursor:'default',padding:'3px',border:'1px solid #fff',backgroundColor:'transparent'},itemHoverStyle:{border:'1px solid #0a246a',backgroundColor:'#b6bdd2'},eventPosX:'pageX',eventPosY:'pageY',shadow:true,onContextMenu:null,onShowMenu:null};$.fn.contextMenu=function(id,options){if(!menu){menu=$('<div id="jqContextMenu"></div>').hide().css({position:'absolute',zIndex:'500'}).appendTo('body').bind('click',function(e){e.stopPropagation();});}
if(!shadow){shadow=$('<div></div>').css({backgroundColor:'#000',position:'absolute',opacity:0.2,zIndex:499}).appendTo('body').hide();}
hash=hash||[];hash.push({id:id,menuStyle:$.extend({},defaults.menuStyle,options.menuStyle||{}),itemStyle:$.extend({},defaults.itemStyle,options.itemStyle||{}),itemHoverStyle:$.extend({},defaults.itemHoverStyle,options.itemHoverStyle||{}),bindings:options.bindings||{},shadow:options.shadow||options.shadow===false?options.shadow:defaults.shadow,onContextMenu:options.onContextMenu||defaults.onContextMenu,onShowMenu:options.onShowMenu||defaults.onShowMenu,eventPosX:options.eventPosX||defaults.eventPosX,eventPosY:options.eventPosY||defaults.eventPosY});var index=hash.length-1;$(this).bind('contextmenu',function(e){var bShowContext=(!!hash[index].onContextMenu)?hash[index].onContextMenu(e):true;if(bShowContext)display(index,this,e,options);return false;});return this;};function display(index,trigger,e,options){var cur=hash[index];content=$('#'+cur.id).find('ul:first').clone(true);content.css(cur.menuStyle).find('li').css(cur.itemStyle).hover(function(){$(this).css(cur.itemHoverStyle);},function(){$(this).css(cur.itemStyle);}).find('img').css({verticalAlign:'middle',paddingRight:'2px'});menu.html(content);if(!!cur.onShowMenu)menu=cur.onShowMenu(e,menu);$.each(cur.bindings,function(id,func){$('#'+id,menu).bind('click',function(e){hide();func(trigger,currentTarget);});});menu.css({'left':e[cur.eventPosX],'top':e[cur.eventPosY]}).show();if(cur.shadow)shadow.css({width:menu.width(),height:menu.height(),left:e.pageX+2,top:e.pageY+2}).show();$(document).one('click',hide);}
function hide(){menu.hide();shadow.hide();}
$.contextMenu={defaults:function(userDefaults){$.each(userDefaults,function(i,val){if(typeof val=='object'&&defaults[i]){$.extend(defaults[i],val);}
else defaults[i]=val;});}};})(jQuery);$(function(){$('div.contextMenu').hide();});

View File

@@ -0,0 +1,144 @@
/*
* ContextMenu - jQuery plugin for right-click context menus
*
* Author: Chris Domigan
* Contributors: Dan G. Switzer, II
* Parts of this plugin are inspired by Joern Zaefferer's Tooltip plugin
*
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*
* Version: r2
* Date: 16 July 2007
*
* For documentation visit http://www.trendskitchens.co.nz/jquery/contextmenu/
*
*/
(function($) {
var menu, shadow, trigger, content, hash, currentTarget;
var defaults = {
menuStyle: {
listStyle: 'none',
padding: '1px',
margin: '0px',
backgroundColor: '#fff',
border: '1px solid #999',
width: '100px'
},
itemStyle: {
margin: '0px',
color: '#000',
display: 'block',
cursor: 'default',
padding: '3px',
border: '1px solid #fff',
backgroundColor: 'transparent'
},
itemHoverStyle: {
border: '1px solid #0a246a',
backgroundColor: '#b6bdd2'
},
eventPosX: 'pageX',
eventPosY: 'pageY',
shadow : true,
onContextMenu: null,
onShowMenu: null
};
$.fn.contextMenu = function(id, options) {
if (!menu) { // Create singleton menu
menu = $('<div id="jqContextMenu"></div>')
.hide()
.css({position:'absolute', zIndex:'500'})
.appendTo('body')
.bind('click', function(e) {
e.stopPropagation();
});
}
if (!shadow) {
shadow = $('<div></div>')
.css({backgroundColor:'#000',position:'absolute',opacity:0.2,zIndex:499})
.appendTo('body')
.hide();
}
hash = hash || [];
hash.push({
id : id,
menuStyle: $.extend({}, defaults.menuStyle, options.menuStyle || {}),
itemStyle: $.extend({}, defaults.itemStyle, options.itemStyle || {}),
itemHoverStyle: $.extend({}, defaults.itemHoverStyle, options.itemHoverStyle || {}),
bindings: options.bindings || {},
shadow: options.shadow || options.shadow === false ? options.shadow : defaults.shadow,
onContextMenu: options.onContextMenu || defaults.onContextMenu,
onShowMenu: options.onShowMenu || defaults.onShowMenu,
eventPosX: options.eventPosX || defaults.eventPosX,
eventPosY: options.eventPosY || defaults.eventPosY
});
var index = hash.length - 1;
$(this).bind('contextmenu', function(e) {
// Check if onContextMenu() defined
var bShowContext = (!!hash[index].onContextMenu) ? hash[index].onContextMenu(e) : true;
if (bShowContext) display(index, this, e, options);
return false;
});
return this;
};
function display(index, trigger, e, options) {
var cur = hash[index];
content = $('#'+cur.id).find('ul:first').clone(true);
content.css(cur.menuStyle).find('li').css(cur.itemStyle).hover(
function() {
$(this).css(cur.itemHoverStyle);
},
function(){
$(this).css(cur.itemStyle);
}
).find('img').css({verticalAlign:'middle',paddingRight:'2px'});
// Send the content to the menu
menu.html(content);
// if there's an onShowMenu, run it now -- must run after content has been added
// if you try to alter the content variable before the menu.html(), IE6 has issues
// updating the content
if (!!cur.onShowMenu) menu = cur.onShowMenu(e, menu);
$.each(cur.bindings, function(id, func) {
$('#'+id, menu).bind('click', function(e) {
hide();
func(trigger, currentTarget);
});
});
menu.css({'left':e[cur.eventPosX],'top':e[cur.eventPosY]}).show();
if (cur.shadow) shadow.css({width:menu.width(),height:menu.height(),left:e.pageX+2,top:e.pageY+2}).show();
$(document).one('click', hide);
}
function hide() {
menu.hide();
shadow.hide();
}
// Apply defaults
$.contextMenu = {
defaults : function(userDefaults) {
$.each(userDefaults, function(i, val) {
if (typeof val == 'object' && defaults[i]) {
$.extend(defaults[i], val);
}
else defaults[i] = val;
});
}
};
})(jQuery);
$(function() {
$('div.contextMenu').hide();
});

View File

@@ -0,0 +1,601 @@
/*
* jQuery Form Plugin
* version: 2.12 (06/07/2008)
* @requires jQuery v1.2.2 or later
*
* Examples and documentation at: http://malsup.com/jquery/form/
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*
* Revision: $Id$
*/
(function($) {
/*
Usage Note:
-----------
Do not use both ajaxSubmit and ajaxForm on the same form. These
functions are intended to be exclusive. Use ajaxSubmit if you want
to bind your own submit handler to the form. For example,
$(document).ready(function() {
$('#myForm').bind('submit', function() {
$(this).ajaxSubmit({
target: '#output'
});
return false; // <-- important!
});
});
Use ajaxForm when you want the plugin to manage all the event binding
for you. For example,
$(document).ready(function() {
$('#myForm').ajaxForm({
target: '#output'
});
});
When using ajaxForm, the ajaxSubmit function will be invoked for you
at the appropriate time.
*/
/**
* ajaxSubmit() provides a mechanism for immediately submitting
* an HTML form using AJAX.
*/
$.fn.ajaxSubmit = function(options) {
// fast fail if nothing selected (http://dev.jquery.com/ticket/2752)
if (!this.length) {
console.log('ajaxSubmit: skipping submit process - no element selected');
return this;
}
if (typeof options == 'function')
options = { success: options };
options = $.extend({
url: this.attr('action') || window.location.toString(),
type: this.attr('method') || 'GET'
}, options || {});
// hook for manipulating the form data before it is extracted;
// convenient for use with rich editors like tinyMCE or FCKEditor
var veto = {};
this.trigger('form-pre-serialize', [this, options, veto]);
if (veto.veto) {
log('ajaxSubmit: submit vetoed via form-pre-serialize trigger');
return this;
}
var a = this.formToArray(options.semantic);
if (options.data) {
options.extraData = options.data;
for (var n in options.data)
a.push( { name: n, value: options.data[n] } );
}
// give pre-submit callback an opportunity to abort the submit
if (options.beforeSubmit && options.beforeSubmit(a, this, options) === false) {
log('ajaxSubmit: submit aborted via beforeSubmit callback');
return this;
}
// fire vetoable 'validate' event
this.trigger('form-submit-validate', [a, this, options, veto]);
if (veto.veto) {
log('ajaxSubmit: submit vetoed via form-submit-validate trigger');
return this;
}
var q = $.param(a);
if (options.type.toUpperCase() == 'GET') {
options.url += (options.url.indexOf('?') >= 0 ? '&' : '?') + q;
options.data = null; // data is null for 'get'
}
else
options.data = q; // data is the query string for 'post'
var $form = this, callbacks = [];
if (options.resetForm) callbacks.push(function() { $form.resetForm(); });
if (options.clearForm) callbacks.push(function() { $form.clearForm(); });
// perform a load on the target only if dataType is not provided
if (!options.dataType && options.target) {
var oldSuccess = options.success || function(){};
callbacks.push(function(data) {
$(options.target).html(data).each(oldSuccess, arguments);
});
}
else if (options.success)
callbacks.push(options.success);
options.success = function(data, status) {
for (var i=0, max=callbacks.length; i < max; i++)
callbacks[i](data, status, $form);
};
// are there files to upload?
var files = $('input:file', this).fieldValue();
var found = false;
for (var j=0; j < files.length; j++)
if (files[j])
found = true;
// options.iframe allows user to force iframe mode
if (options.iframe || found) {
// hack to fix Safari hang (thanks to Tim Molendijk for this)
// see: http://groups.google.com/group/jquery-dev/browse_thread/thread/36395b7ab510dd5d
if ($.browser.safari && options.closeKeepAlive)
$.get(options.closeKeepAlive, fileUpload);
else
fileUpload();
}
else
$.ajax(options);
// fire 'notify' event
this.trigger('form-submit-notify', [this, options]);
return this;
// private function for handling file uploads (hat tip to YAHOO!)
function fileUpload() {
var form = $form[0];
if ($(':input[@name=submit]', form).length) {
alert('Error: Form elements must not be named "submit".');
return;
}
var opts = $.extend({}, $.ajaxSettings, options);
var id = 'jqFormIO' + (new Date().getTime());
var $io = $('<iframe id="' + id + '" name="' + id + '" />');
var io = $io[0];
if ($.browser.msie || $.browser.opera)
io.src = 'javascript:false;document.write("");';
$io.css({ position: 'absolute', top: '-1000px', left: '-1000px' });
var xhr = { // mock object
responseText: null,
responseXML: null,
status: 0,
statusText: 'n/a',
getAllResponseHeaders: function() {},
getResponseHeader: function() {},
setRequestHeader: function() {}
};
var g = opts.global;
// trigger ajax global events so that activity/block indicators work like normal
if (g && ! $.active++) $.event.trigger("ajaxStart");
if (g) $.event.trigger("ajaxSend", [xhr, opts]);
var cbInvoked = 0;
var timedOut = 0;
// add submitting element to data if we know it
var sub = form.clk;
if (sub) {
var n = sub.name;
if (n && !sub.disabled) {
options.extraData = options.extraData || {};
options.extraData[n] = sub.value;
if (sub.type == "image") {
options.extraData[name+'.x'] = form.clk_x;
options.extraData[name+'.y'] = form.clk_y;
}
}
}
// take a breath so that pending repaints get some cpu time before the upload starts
setTimeout(function() {
// make sure form attrs are set
var t = $form.attr('target'), a = $form.attr('action');
$form.attr({
target: id,
encoding: 'multipart/form-data',
enctype: 'multipart/form-data',
method: 'POST',
action: opts.url
});
// support timout
if (opts.timeout)
setTimeout(function() { timedOut = true; cb(); }, opts.timeout);
// add "extra" data to form if provided in options
var extraInputs = [];
try {
if (options.extraData)
for (var n in options.extraData)
extraInputs.push(
$('<input type="hidden" name="'+n+'" value="'+options.extraData[n]+'" />')
.appendTo(form)[0]);
// add iframe to doc and submit the form
$io.appendTo('body');
io.attachEvent ? io.attachEvent('onload', cb) : io.addEventListener('load', cb, false);
form.submit();
}
finally {
// reset attrs and remove "extra" input elements
$form.attr('action', a);
t ? $form.attr('target', t) : $form.removeAttr('target');
$(extraInputs).remove();
}
}, 10);
function cb() {
if (cbInvoked++) return;
io.detachEvent ? io.detachEvent('onload', cb) : io.removeEventListener('load', cb, false);
var operaHack = 0;
var ok = true;
try {
if (timedOut) throw 'timeout';
// extract the server response from the iframe
var data, doc;
doc = io.contentWindow ? io.contentWindow.document : io.contentDocument ? io.contentDocument : io.document;
if (doc.body == null && !operaHack && $.browser.opera) {
// In Opera 9.2.x the iframe DOM is not always traversable when
// the onload callback fires so we give Opera 100ms to right itself
operaHack = 1;
cbInvoked--;
setTimeout(cb, 100);
return;
}
xhr.responseText = doc.body ? doc.body.innerHTML : null;
xhr.responseXML = doc.XMLDocument ? doc.XMLDocument : doc;
xhr.getResponseHeader = function(header){
var headers = {'content-type': opts.dataType};
return headers[header];
};
if (opts.dataType == 'json' || opts.dataType == 'script') {
var ta = doc.getElementsByTagName('textarea')[0];
xhr.responseText = ta ? ta.value : xhr.responseText;
}
else if (opts.dataType == 'xml' && !xhr.responseXML && xhr.responseText != null) {
xhr.responseXML = toXml(xhr.responseText);
}
data = $.httpData(xhr, opts.dataType);
}
catch(e){
ok = false;
$.handleError(opts, xhr, 'error', e);
}
// ordering of these callbacks/triggers is odd, but that's how $.ajax does it
if (ok) {
opts.success(data, 'success');
if (g) $.event.trigger("ajaxSuccess", [xhr, opts]);
}
if (g) $.event.trigger("ajaxComplete", [xhr, opts]);
if (g && ! --$.active) $.event.trigger("ajaxStop");
if (opts.complete) opts.complete(xhr, ok ? 'success' : 'error');
// clean up
setTimeout(function() {
$io.remove();
xhr.responseXML = null;
}, 100);
};
function toXml(s, doc) {
if (window.ActiveXObject) {
doc = new ActiveXObject('Microsoft.XMLDOM');
doc.async = 'false';
doc.loadXML(s);
}
else
doc = (new DOMParser()).parseFromString(s, 'text/xml');
return (doc && doc.documentElement && doc.documentElement.tagName != 'parsererror') ? doc : null;
};
};
};
/**
* ajaxForm() provides a mechanism for fully automating form submission.
*
* The advantages of using this method instead of ajaxSubmit() are:
*
* 1: This method will include coordinates for <input type="image" /> elements (if the element
* is used to submit the form).
* 2. This method will include the submit element's name/value data (for the element that was
* used to submit the form).
* 3. This method binds the submit() method to the form for you.
*
* The options argument for ajaxForm works exactly as it does for ajaxSubmit. ajaxForm merely
* passes the options argument along after properly binding events for submit elements and
* the form itself.
*/
$.fn.ajaxForm = function(options) {
return this.ajaxFormUnbind().bind('submit.form-plugin',function() {
$(this).ajaxSubmit(options);
return false;
}).each(function() {
// store options in hash
$(":submit,input:image", this).bind('click.form-plugin',function(e) {
var $form = this.form;
$form.clk = this;
if (this.type == 'image') {
if (e.offsetX != undefined) {
$form.clk_x = e.offsetX;
$form.clk_y = e.offsetY;
} else if (typeof $.fn.offset == 'function') { // try to use dimensions plugin
var offset = $(this).offset();
$form.clk_x = e.pageX - offset.left;
$form.clk_y = e.pageY - offset.top;
} else {
$form.clk_x = e.pageX - this.offsetLeft;
$form.clk_y = e.pageY - this.offsetTop;
}
}
// clear form vars
setTimeout(function() { $form.clk = $form.clk_x = $form.clk_y = null; }, 10);
});
});
};
// ajaxFormUnbind unbinds the event handlers that were bound by ajaxForm
$.fn.ajaxFormUnbind = function() {
this.unbind('submit.form-plugin');
return this.each(function() {
$(":submit,input:image", this).unbind('click.form-plugin');
});
};
/**
* formToArray() gathers form element data into an array of objects that can
* be passed to any of the following ajax functions: $.get, $.post, or load.
* Each object in the array has both a 'name' and 'value' property. An example of
* an array for a simple login form might be:
*
* [ { name: 'username', value: 'jresig' }, { name: 'password', value: 'secret' } ]
*
* It is this array that is passed to pre-submit callback functions provided to the
* ajaxSubmit() and ajaxForm() methods.
*/
$.fn.formToArray = function(semantic) {
var a = [];
if (this.length == 0) return a;
var form = this[0];
var els = semantic ? form.getElementsByTagName('*') : form.elements;
if (!els) return a;
for(var i=0, max=els.length; i < max; i++) {
var el = els[i];
var n = el.name;
if (!n) continue;
if (semantic && form.clk && el.type == "image") {
// handle image inputs on the fly when semantic == true
if(!el.disabled && form.clk == el)
a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y});
continue;
}
var v = $.fieldValue(el, true);
if (v && v.constructor == Array) {
for(var j=0, jmax=v.length; j < jmax; j++)
a.push({name: n, value: v[j]});
}
else if (v !== null && typeof v != 'undefined')
a.push({name: n, value: v});
}
if (!semantic && form.clk) {
// input type=='image' are not found in elements array! handle them here
var inputs = form.getElementsByTagName("input");
for(var i=0, max=inputs.length; i < max; i++) {
var input = inputs[i];
var n = input.name;
if(n && !input.disabled && input.type == "image" && form.clk == input)
a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y});
}
}
return a;
};
/**
* Serializes form data into a 'submittable' string. This method will return a string
* in the format: name1=value1&amp;name2=value2
*/
$.fn.formSerialize = function(semantic) {
//hand off to jQuery.param for proper encoding
return $.param(this.formToArray(semantic));
};
/**
* Serializes all field elements in the jQuery object into a query string.
* This method will return a string in the format: name1=value1&amp;name2=value2
*/
$.fn.fieldSerialize = function(successful) {
var a = [];
this.each(function() {
var n = this.name;
if (!n) return;
var v = $.fieldValue(this, successful);
if (v && v.constructor == Array) {
for (var i=0,max=v.length; i < max; i++)
a.push({name: n, value: v[i]});
}
else if (v !== null && typeof v != 'undefined')
a.push({name: this.name, value: v});
});
//hand off to jQuery.param for proper encoding
return $.param(a);
};
/**
* Returns the value(s) of the element in the matched set. For example, consider the following form:
*
* <form><fieldset>
* <input name="A" type="text" />
* <input name="A" type="text" />
* <input name="B" type="checkbox" value="B1" />
* <input name="B" type="checkbox" value="B2"/>
* <input name="C" type="radio" value="C1" />
* <input name="C" type="radio" value="C2" />
* </fieldset></form>
*
* var v = $(':text').fieldValue();
* // if no values are entered into the text inputs
* v == ['','']
* // if values entered into the text inputs are 'foo' and 'bar'
* v == ['foo','bar']
*
* var v = $(':checkbox').fieldValue();
* // if neither checkbox is checked
* v === undefined
* // if both checkboxes are checked
* v == ['B1', 'B2']
*
* var v = $(':radio').fieldValue();
* // if neither radio is checked
* v === undefined
* // if first radio is checked
* v == ['C1']
*
* The successful argument controls whether or not the field element must be 'successful'
* (per http://www.w3.org/TR/html4/interact/forms.html#successful-controls).
* The default value of the successful argument is true. If this value is false the value(s)
* for each element is returned.
*
* Note: This method *always* returns an array. If no valid value can be determined the
* array will be empty, otherwise it will contain one or more values.
*/
$.fn.fieldValue = function(successful) {
for (var val=[], i=0, max=this.length; i < max; i++) {
var el = this[i];
var v = $.fieldValue(el, successful);
if (v === null || typeof v == 'undefined' || (v.constructor == Array && !v.length))
continue;
v.constructor == Array ? $.merge(val, v) : val.push(v);
}
return val;
};
/**
* Returns the value of the field element.
*/
$.fieldValue = function(el, successful) {
var n = el.name, t = el.type, tag = el.tagName.toLowerCase();
if (typeof successful == 'undefined') successful = true;
if (successful && (!n || el.disabled || t == 'reset' || t == 'button' ||
(t == 'checkbox' || t == 'radio') && !el.checked ||
(t == 'submit' || t == 'image') && el.form && el.form.clk != el ||
tag == 'select' && el.selectedIndex == -1))
return null;
if (tag == 'select') {
var index = el.selectedIndex;
if (index < 0) return null;
var a = [], ops = el.options;
var one = (t == 'select-one');
var max = (one ? index+1 : ops.length);
for(var i=(one ? index : 0); i < max; i++) {
var op = ops[i];
if (op.selected) {
// extra pain for IE...
var v = $.browser.msie && !(op.attributes['value'].specified) ? op.text : op.value;
if (one) return v;
a.push(v);
}
}
return a;
}
return el.value;
};
/**
* Clears the form data. Takes the following actions on the form's input fields:
* - input text fields will have their 'value' property set to the empty string
* - select elements will have their 'selectedIndex' property set to -1
* - checkbox and radio inputs will have their 'checked' property set to false
* - inputs of type submit, button, reset, and hidden will *not* be effected
* - button elements will *not* be effected
*/
$.fn.clearForm = function() {
return this.each(function() {
$('input,select,textarea', this).clearFields();
});
};
/**
* Clears the selected form elements.
*/
$.fn.clearFields = $.fn.clearInputs = function() {
return this.each(function() {
var t = this.type, tag = this.tagName.toLowerCase();
if (t == 'text' || t == 'password' || tag == 'textarea')
this.value = '';
else if (t == 'checkbox' || t == 'radio')
this.checked = false;
else if (tag == 'select')
this.selectedIndex = -1;
});
};
/**
* Resets the form data. Causes all form elements to be reset to their original value.
*/
$.fn.resetForm = function() {
return this.each(function() {
// guard against an input with the name of 'reset'
// note that IE reports the reset function as an 'object'
if (typeof this.reset == 'function' || (typeof this.reset == 'object' && !this.reset.nodeType))
this.reset();
});
};
/**
* Enables or disables any matching elements.
*/
$.fn.enable = function(b) {
if (b == undefined) b = true;
return this.each(function() {
this.disabled = !b
});
};
/**
* Checks/unchecks any matching checkboxes or radio buttons and
* selects/deselects and matching option elements.
*/
$.fn.select = function(select) {
if (select == undefined) select = true;
return this.each(function() {
var t = this.type;
if (t == 'checkbox' || t == 'radio')
this.checked = select;
else if (this.tagName.toLowerCase() == 'option') {
var $sel = $(this).parent('select');
if (select && $sel[0] && $sel[0].type == 'select-one') {
// deselect all other options
$sel.find('option').select(false);
}
this.selected = select;
}
});
};
// helper fn for console logging
// set $.fn.ajaxSubmit.debug to true to enable debug logging
function log() {
if ($.fn.ajaxSubmit.debug && window.console && window.console.log)
window.console.log('[jquery.form] ' + Array.prototype.join.call(arguments,''));
};
})(jQuery);

View File

@@ -0,0 +1,59 @@
(function($){$.fn.ajaxSubmit=function(options){if(!this.length){console.log('ajaxSubmit: skipping submit process - no element selected');return this;}
if(typeof options=='function')
options={success:options};options=$.extend({url:this.attr('action')||window.location.toString(),type:this.attr('method')||'GET'},options||{});var veto={};this.trigger('form-pre-serialize',[this,options,veto]);if(veto.veto){log('ajaxSubmit: submit vetoed via form-pre-serialize trigger');return this;}
var a=this.formToArray(options.semantic);if(options.data){options.extraData=options.data;for(var n in options.data)
a.push({name:n,value:options.data[n]});}
if(options.beforeSubmit&&options.beforeSubmit(a,this,options)===false){log('ajaxSubmit: submit aborted via beforeSubmit callback');return this;}
this.trigger('form-submit-validate',[a,this,options,veto]);if(veto.veto){log('ajaxSubmit: submit vetoed via form-submit-validate trigger');return this;}
var q=$.param(a);if(options.type.toUpperCase()=='GET'){options.url+=(options.url.indexOf('?')>=0?'&':'?')+q;options.data=null;}
else
options.data=q;var $form=this,callbacks=[];if(options.resetForm)callbacks.push(function(){$form.resetForm();});if(options.clearForm)callbacks.push(function(){$form.clearForm();});if(!options.dataType&&options.target){var oldSuccess=options.success||function(){};callbacks.push(function(data){$(options.target).html(data).each(oldSuccess,arguments);});}
else if(options.success)
callbacks.push(options.success);options.success=function(data,status){for(var i=0,max=callbacks.length;i<max;i++)
callbacks[i](data,status,$form);};var files=$('input:file',this).fieldValue();var found=false;for(var j=0;j<files.length;j++)
if(files[j])
found=true;if(options.iframe||found){if($.browser.safari&&options.closeKeepAlive)
$.get(options.closeKeepAlive,fileUpload);else
fileUpload();}
else
$.ajax(options);this.trigger('form-submit-notify',[this,options]);return this;function fileUpload(){var form=$form[0];if($(':input[@name=submit]',form).length){alert('Error: Form elements must not be named "submit".');return;}
var opts=$.extend({},$.ajaxSettings,options);var id='jqFormIO'+(new Date().getTime());var $io=$('<iframe id="'+id+'" name="'+id+'" />');var io=$io[0];if($.browser.msie||$.browser.opera)
io.src='javascript:false;document.write("");';$io.css({position:'absolute',top:'-1000px',left:'-1000px'});var xhr={responseText:null,responseXML:null,status:0,statusText:'n/a',getAllResponseHeaders:function(){},getResponseHeader:function(){},setRequestHeader:function(){}};var g=opts.global;if(g&&!$.active++)$.event.trigger("ajaxStart");if(g)$.event.trigger("ajaxSend",[xhr,opts]);var cbInvoked=0;var timedOut=0;var sub=form.clk;if(sub){var n=sub.name;if(n&&!sub.disabled){options.extraData=options.extraData||{};options.extraData[n]=sub.value;if(sub.type=="image"){options.extraData[name+'.x']=form.clk_x;options.extraData[name+'.y']=form.clk_y;}}}
setTimeout(function(){var t=$form.attr('target'),a=$form.attr('action');$form.attr({target:id,encoding:'multipart/form-data',enctype:'multipart/form-data',method:'POST',action:opts.url});if(opts.timeout)
setTimeout(function(){timedOut=true;cb();},opts.timeout);var extraInputs=[];try{if(options.extraData)
for(var n in options.extraData)
extraInputs.push($('<input type="hidden" name="'+n+'" value="'+options.extraData[n]+'" />').appendTo(form)[0]);$io.appendTo('body');io.attachEvent?io.attachEvent('onload',cb):io.addEventListener('load',cb,false);form.submit();}
finally{$form.attr('action',a);t?$form.attr('target',t):$form.removeAttr('target');$(extraInputs).remove();}},10);function cb(){if(cbInvoked++)return;io.detachEvent?io.detachEvent('onload',cb):io.removeEventListener('load',cb,false);var operaHack=0;var ok=true;try{if(timedOut)throw'timeout';var data,doc;doc=io.contentWindow?io.contentWindow.document:io.contentDocument?io.contentDocument:io.document;if(doc.body==null&&!operaHack&&$.browser.opera){operaHack=1;cbInvoked--;setTimeout(cb,100);return;}
xhr.responseText=doc.body?doc.body.innerHTML:null;xhr.responseXML=doc.XMLDocument?doc.XMLDocument:doc;xhr.getResponseHeader=function(header){var headers={'content-type':opts.dataType};return headers[header];};if(opts.dataType=='json'||opts.dataType=='script'){var ta=doc.getElementsByTagName('textarea')[0];xhr.responseText=ta?ta.value:xhr.responseText;}
else if(opts.dataType=='xml'&&!xhr.responseXML&&xhr.responseText!=null){xhr.responseXML=toXml(xhr.responseText);}
data=$.httpData(xhr,opts.dataType);}
catch(e){ok=false;$.handleError(opts,xhr,'error',e);}
if(ok){opts.success(data,'success');if(g)$.event.trigger("ajaxSuccess",[xhr,opts]);}
if(g)$.event.trigger("ajaxComplete",[xhr,opts]);if(g&&!--$.active)$.event.trigger("ajaxStop");if(opts.complete)opts.complete(xhr,ok?'success':'error');setTimeout(function(){$io.remove();xhr.responseXML=null;},100);};function toXml(s,doc){if(window.ActiveXObject){doc=new ActiveXObject('Microsoft.XMLDOM');doc.async='false';doc.loadXML(s);}
else
doc=(new DOMParser()).parseFromString(s,'text/xml');return(doc&&doc.documentElement&&doc.documentElement.tagName!='parsererror')?doc:null;};};};$.fn.ajaxForm=function(options){return this.ajaxFormUnbind().bind('submit.form-plugin',function(){$(this).ajaxSubmit(options);return false;}).each(function(){$(":submit,input:image",this).bind('click.form-plugin',function(e){var $form=this.form;$form.clk=this;if(this.type=='image'){if(e.offsetX!=undefined){$form.clk_x=e.offsetX;$form.clk_y=e.offsetY;}else if(typeof $.fn.offset=='function'){var offset=$(this).offset();$form.clk_x=e.pageX-offset.left;$form.clk_y=e.pageY-offset.top;}else{$form.clk_x=e.pageX-this.offsetLeft;$form.clk_y=e.pageY-this.offsetTop;}}
setTimeout(function(){$form.clk=$form.clk_x=$form.clk_y=null;},10);});});};$.fn.ajaxFormUnbind=function(){this.unbind('submit.form-plugin');return this.each(function(){$(":submit,input:image",this).unbind('click.form-plugin');});};$.fn.formToArray=function(semantic){var a=[];if(this.length==0)return a;var form=this[0];var els=semantic?form.getElementsByTagName('*'):form.elements;if(!els)return a;for(var i=0,max=els.length;i<max;i++){var el=els[i];var n=el.name;if(!n)continue;if(semantic&&form.clk&&el.type=="image"){if(!el.disabled&&form.clk==el)
a.push({name:n+'.x',value:form.clk_x},{name:n+'.y',value:form.clk_y});continue;}
var v=$.fieldValue(el,true);if(v&&v.constructor==Array){for(var j=0,jmax=v.length;j<jmax;j++)
a.push({name:n,value:v[j]});}
else if(v!==null&&typeof v!='undefined')
a.push({name:n,value:v});}
if(!semantic&&form.clk){var inputs=form.getElementsByTagName("input");for(var i=0,max=inputs.length;i<max;i++){var input=inputs[i];var n=input.name;if(n&&!input.disabled&&input.type=="image"&&form.clk==input)
a.push({name:n+'.x',value:form.clk_x},{name:n+'.y',value:form.clk_y});}}
return a;};$.fn.formSerialize=function(semantic){return $.param(this.formToArray(semantic));};$.fn.fieldSerialize=function(successful){var a=[];this.each(function(){var n=this.name;if(!n)return;var v=$.fieldValue(this,successful);if(v&&v.constructor==Array){for(var i=0,max=v.length;i<max;i++)
a.push({name:n,value:v[i]});}
else if(v!==null&&typeof v!='undefined')
a.push({name:this.name,value:v});});return $.param(a);};$.fn.fieldValue=function(successful){for(var val=[],i=0,max=this.length;i<max;i++){var el=this[i];var v=$.fieldValue(el,successful);if(v===null||typeof v=='undefined'||(v.constructor==Array&&!v.length))
continue;v.constructor==Array?$.merge(val,v):val.push(v);}
return val;};$.fieldValue=function(el,successful){var n=el.name,t=el.type,tag=el.tagName.toLowerCase();if(typeof successful=='undefined')successful=true;if(successful&&(!n||el.disabled||t=='reset'||t=='button'||(t=='checkbox'||t=='radio')&&!el.checked||(t=='submit'||t=='image')&&el.form&&el.form.clk!=el||tag=='select'&&el.selectedIndex==-1))
return null;if(tag=='select'){var index=el.selectedIndex;if(index<0)return null;var a=[],ops=el.options;var one=(t=='select-one');var max=(one?index+1:ops.length);for(var i=(one?index:0);i<max;i++){var op=ops[i];if(op.selected){var v=$.browser.msie&&!(op.attributes['value'].specified)?op.text:op.value;if(one)return v;a.push(v);}}
return a;}
return el.value;};$.fn.clearForm=function(){return this.each(function(){$('input,select,textarea',this).clearFields();});};$.fn.clearFields=$.fn.clearInputs=function(){return this.each(function(){var t=this.type,tag=this.tagName.toLowerCase();if(t=='text'||t=='password'||tag=='textarea')
this.value='';else if(t=='checkbox'||t=='radio')
this.checked=false;else if(tag=='select')
this.selectedIndex=-1;});};$.fn.resetForm=function(){return this.each(function(){if(typeof this.reset=='function'||(typeof this.reset=='object'&&!this.reset.nodeType))
this.reset();});};$.fn.enable=function(b){if(b==undefined)b=true;return this.each(function(){this.disabled=!b});};$.fn.select=function(select){if(select==undefined)select=true;return this.each(function(){var t=this.type;if(t=='checkbox'||t=='radio')
this.checked=select;else if(this.tagName.toLowerCase()=='option'){var $sel=$(this).parent('select');if(select&&$sel[0]&&$sel[0].type=='select-one'){$sel.find('option').select(false);}
this.selected=select;}});};function log(){if($.fn.ajaxSubmit.debug&&window.console&&window.console.log)
window.console.log('[jquery.form] '+Array.prototype.join.call(arguments,''));};})(jQuery);

376
web/javascript/jquery/jquery.min.js vendored Normal file
View File

@@ -0,0 +1,376 @@
(function(){var _jQuery=window.jQuery,_$=window.$;var jQuery=window.jQuery=window.$=function(selector,context){return new jQuery.fn.init(selector,context);};var quickExpr=/^[^<]*(<(.|\s)+>)[^>]*$|^#(\w+)$/,isSimple=/^.[^:#\[\.]*$/,undefined;jQuery.fn=jQuery.prototype={init:function(selector,context){selector=selector||document;if(selector.nodeType){this[0]=selector;this.length=1;return this;}
if(typeof selector=="string"){var match=quickExpr.exec(selector);if(match&&(match[1]||!context)){if(match[1])
selector=jQuery.clean([match[1]],context);else{var elem=document.getElementById(match[3]);if(elem){if(elem.id!=match[3])
return jQuery().find(selector);return jQuery(elem);}
selector=[];}}else
return jQuery(context).find(selector);}else if(jQuery.isFunction(selector))
return jQuery(document)[jQuery.fn.ready?"ready":"load"](selector);return this.setArray(jQuery.makeArray(selector));},jquery:"1.2.6",size:function(){return this.length;},length:0,get:function(num){return num==undefined?jQuery.makeArray(this):this[num];},pushStack:function(elems){var ret=jQuery(elems);ret.prevObject=this;return ret;},setArray:function(elems){this.length=0;Array.prototype.push.apply(this,elems);return this;},each:function(callback,args){return jQuery.each(this,callback,args);},index:function(elem){var ret=-1;return jQuery.inArray(elem&&elem.jquery?elem[0]:elem,this);},attr:function(name,value,type){var options=name;if(name.constructor==String)
if(value===undefined)
return this[0]&&jQuery[type||"attr"](this[0],name);else{options={};options[name]=value;}
return this.each(function(i){for(name in options)
jQuery.attr(type?this.style:this,name,jQuery.prop(this,options[name],type,i,name));});},css:function(key,value){if((key=='width'||key=='height')&&parseFloat(value)<0)
value=undefined;return this.attr(key,value,"curCSS");},text:function(text){if(typeof text!="object"&&text!=null)
return this.empty().append((this[0]&&this[0].ownerDocument||document).createTextNode(text));var ret="";jQuery.each(text||this,function(){jQuery.each(this.childNodes,function(){if(this.nodeType!=8)
ret+=this.nodeType!=1?this.nodeValue:jQuery.fn.text([this]);});});return ret;},wrapAll:function(html){if(this[0])
jQuery(html,this[0].ownerDocument).clone().insertBefore(this[0]).map(function(){var elem=this;while(elem.firstChild)
elem=elem.firstChild;return elem;}).append(this);return this;},wrapInner:function(html){return this.each(function(){jQuery(this).contents().wrapAll(html);});},wrap:function(html){return this.each(function(){jQuery(this).wrapAll(html);});},append:function(){return this.domManip(arguments,true,false,function(elem){if(this.nodeType==1)
this.appendChild(elem);});},prepend:function(){return this.domManip(arguments,true,true,function(elem){if(this.nodeType==1)
this.insertBefore(elem,this.firstChild);});},before:function(){return this.domManip(arguments,false,false,function(elem){this.parentNode.insertBefore(elem,this);});},after:function(){return this.domManip(arguments,false,true,function(elem){this.parentNode.insertBefore(elem,this.nextSibling);});},end:function(){return this.prevObject||jQuery([]);},find:function(selector){var elems=jQuery.map(this,function(elem){return jQuery.find(selector,elem);});return this.pushStack(/[^+>] [^+>]/.test(selector)||selector.indexOf("..")>-1?jQuery.unique(elems):elems);},clone:function(events){var ret=this.map(function(){if(jQuery.browser.msie&&!jQuery.isXMLDoc(this)){var clone=this.cloneNode(true),container=document.createElement("div");container.appendChild(clone);return jQuery.clean([container.innerHTML])[0];}else
return this.cloneNode(true);});var clone=ret.find("*").andSelf().each(function(){if(this[expando]!=undefined)
this[expando]=null;});if(events===true)
this.find("*").andSelf().each(function(i){if(this.nodeType==3)
return;var events=jQuery.data(this,"events");for(var type in events)
for(var handler in events[type])
jQuery.event.add(clone[i],type,events[type][handler],events[type][handler].data);});return ret;},filter:function(selector){return this.pushStack(jQuery.isFunction(selector)&&jQuery.grep(this,function(elem,i){return selector.call(elem,i);})||jQuery.multiFilter(selector,this));},not:function(selector){if(selector.constructor==String)
if(isSimple.test(selector))
return this.pushStack(jQuery.multiFilter(selector,this,true));else
selector=jQuery.multiFilter(selector,this);var isArrayLike=selector.length&&selector[selector.length-1]!==undefined&&!selector.nodeType;return this.filter(function(){return isArrayLike?jQuery.inArray(this,selector)<0:this!=selector;});},add:function(selector){return this.pushStack(jQuery.unique(jQuery.merge(this.get(),typeof selector=='string'?jQuery(selector):jQuery.makeArray(selector))));},is:function(selector){return!!selector&&jQuery.multiFilter(selector,this).length>0;},hasClass:function(selector){return this.is("."+selector);},val:function(value){if(value==undefined){if(this.length){var elem=this[0];if(jQuery.nodeName(elem,"select")){var index=elem.selectedIndex,values=[],options=elem.options,one=elem.type=="select-one";if(index<0)
return null;for(var i=one?index:0,max=one?index+1:options.length;i<max;i++){var option=options[i];if(option.selected){value=jQuery.browser.msie&&!option.attributes.value.specified?option.text:option.value;if(one)
return value;values.push(value);}}
return values;}else
return(this[0].value||"").replace(/\r/g,"");}
return undefined;}
if(value.constructor==Number)
value+='';return this.each(function(){if(this.nodeType!=1)
return;if(value.constructor==Array&&/radio|checkbox/.test(this.type))
this.checked=(jQuery.inArray(this.value,value)>=0||jQuery.inArray(this.name,value)>=0);else if(jQuery.nodeName(this,"select")){var values=jQuery.makeArray(value);jQuery("option",this).each(function(){this.selected=(jQuery.inArray(this.value,values)>=0||jQuery.inArray(this.text,values)>=0);});if(!values.length)
this.selectedIndex=-1;}else
this.value=value;});},html:function(value){return value==undefined?(this[0]?this[0].innerHTML:null):this.empty().append(value);},replaceWith:function(value){return this.after(value).remove();},eq:function(i){return this.slice(i,i+1);},slice:function(){return this.pushStack(Array.prototype.slice.apply(this,arguments));},map:function(callback){return this.pushStack(jQuery.map(this,function(elem,i){return callback.call(elem,i,elem);}));},andSelf:function(){return this.add(this.prevObject);},data:function(key,value){var parts=key.split(".");parts[1]=parts[1]?"."+parts[1]:"";if(value===undefined){var data=this.triggerHandler("getData"+parts[1]+"!",[parts[0]]);if(data===undefined&&this.length)
data=jQuery.data(this[0],key);return data===undefined&&parts[1]?this.data(parts[0]):data;}else
return this.trigger("setData"+parts[1]+"!",[parts[0],value]).each(function(){jQuery.data(this,key,value);});},removeData:function(key){return this.each(function(){jQuery.removeData(this,key);});},domManip:function(args,table,reverse,callback){var clone=this.length>1,elems;return this.each(function(){if(!elems){elems=jQuery.clean(args,this.ownerDocument);if(reverse)
elems.reverse();}
var obj=this;if(table&&jQuery.nodeName(this,"table")&&jQuery.nodeName(elems[0],"tr"))
obj=this.getElementsByTagName("tbody")[0]||this.appendChild(this.ownerDocument.createElement("tbody"));var scripts=jQuery([]);jQuery.each(elems,function(){var elem=clone?jQuery(this).clone(true)[0]:this;if(jQuery.nodeName(elem,"script"))
scripts=scripts.add(elem);else{if(elem.nodeType==1)
scripts=scripts.add(jQuery("script",elem).remove());callback.call(obj,elem);}});scripts.each(evalScript);});}};jQuery.fn.init.prototype=jQuery.fn;function evalScript(i,elem){if(elem.src)
jQuery.ajax({url:elem.src,async:false,dataType:"script"});else
jQuery.globalEval(elem.text||elem.textContent||elem.innerHTML||"");if(elem.parentNode)
elem.parentNode.removeChild(elem);}
function now(){return+new Date;}
jQuery.extend=jQuery.fn.extend=function(){var target=arguments[0]||{},i=1,length=arguments.length,deep=false,options;if(target.constructor==Boolean){deep=target;target=arguments[1]||{};i=2;}
if(typeof target!="object"&&typeof target!="function")
target={};if(length==i){target=this;--i;}
for(;i<length;i++)
if((options=arguments[i])!=null)
for(var name in options){var src=target[name],copy=options[name];if(target===copy)
continue;if(deep&&copy&&typeof copy=="object"&&!copy.nodeType)
target[name]=jQuery.extend(deep,src||(copy.length!=null?[]:{}),copy);else if(copy!==undefined)
target[name]=copy;}
return target;};var expando="jQuery"+now(),uuid=0,windowData={},exclude=/z-?index|font-?weight|opacity|zoom|line-?height/i,defaultView=document.defaultView||{};jQuery.extend({noConflict:function(deep){window.$=_$;if(deep)
window.jQuery=_jQuery;return jQuery;},isFunction:function(fn){return!!fn&&typeof fn!="string"&&!fn.nodeName&&fn.constructor!=Array&&/^[\s[]?function/.test(fn+"");},isXMLDoc:function(elem){return elem.documentElement&&!elem.body||elem.tagName&&elem.ownerDocument&&!elem.ownerDocument.body;},globalEval:function(data){data=jQuery.trim(data);if(data){var head=document.getElementsByTagName("head")[0]||document.documentElement,script=document.createElement("script");script.type="text/javascript";if(jQuery.browser.msie)
script.text=data;else
script.appendChild(document.createTextNode(data));head.insertBefore(script,head.firstChild);head.removeChild(script);}},nodeName:function(elem,name){return elem.nodeName&&elem.nodeName.toUpperCase()==name.toUpperCase();},cache:{},data:function(elem,name,data){elem=elem==window?windowData:elem;var id=elem[expando];if(!id)
id=elem[expando]=++uuid;if(name&&!jQuery.cache[id])
jQuery.cache[id]={};if(data!==undefined)
jQuery.cache[id][name]=data;return name?jQuery.cache[id][name]:id;},removeData:function(elem,name){elem=elem==window?windowData:elem;var id=elem[expando];if(name){if(jQuery.cache[id]){delete jQuery.cache[id][name];name="";for(name in jQuery.cache[id])
break;if(!name)
jQuery.removeData(elem);}}else{try{delete elem[expando];}catch(e){if(elem.removeAttribute)
elem.removeAttribute(expando);}
delete jQuery.cache[id];}},each:function(object,callback,args){var name,i=0,length=object.length;if(args){if(length==undefined){for(name in object)
if(callback.apply(object[name],args)===false)
break;}else
for(;i<length;)
if(callback.apply(object[i++],args)===false)
break;}else{if(length==undefined){for(name in object)
if(callback.call(object[name],name,object[name])===false)
break;}else
for(var value=object[0];i<length&&callback.call(value,i,value)!==false;value=object[++i]){}}
return object;},prop:function(elem,value,type,i,name){if(jQuery.isFunction(value))
value=value.call(elem,i);return value&&value.constructor==Number&&type=="curCSS"&&!exclude.test(name)?value+"px":value;},className:{add:function(elem,classNames){jQuery.each((classNames||"").split(/\s+/),function(i,className){if(elem.nodeType==1&&!jQuery.className.has(elem.className,className))
elem.className+=(elem.className?" ":"")+className;});},remove:function(elem,classNames){if(elem.nodeType==1)
elem.className=classNames!=undefined?jQuery.grep(elem.className.split(/\s+/),function(className){return!jQuery.className.has(classNames,className);}).join(" "):"";},has:function(elem,className){return jQuery.inArray(className,(elem.className||elem).toString().split(/\s+/))>-1;}},swap:function(elem,options,callback){var old={};for(var name in options){old[name]=elem.style[name];elem.style[name]=options[name];}
callback.call(elem);for(var name in options)
elem.style[name]=old[name];},css:function(elem,name,force){if(name=="width"||name=="height"){var val,props={position:"absolute",visibility:"hidden",display:"block"},which=name=="width"?["Left","Right"]:["Top","Bottom"];function getWH(){val=name=="width"?elem.offsetWidth:elem.offsetHeight;var padding=0,border=0;jQuery.each(which,function(){padding+=parseFloat(jQuery.curCSS(elem,"padding"+this,true))||0;border+=parseFloat(jQuery.curCSS(elem,"border"+this+"Width",true))||0;});val-=Math.round(padding+border);}
if(jQuery(elem).is(":visible"))
getWH();else
jQuery.swap(elem,props,getWH);return Math.max(0,val);}
return jQuery.curCSS(elem,name,force);},curCSS:function(elem,name,force){var ret,style=elem.style;function color(elem){if(!jQuery.browser.safari)
return false;var ret=defaultView.getComputedStyle(elem,null);return!ret||ret.getPropertyValue("color")=="";}
if(name=="opacity"&&jQuery.browser.msie){ret=jQuery.attr(style,"opacity");return ret==""?"1":ret;}
if(jQuery.browser.opera&&name=="display"){var save=style.outline;style.outline="0 solid black";style.outline=save;}
if(name.match(/float/i))
name=styleFloat;if(!force&&style&&style[name])
ret=style[name];else if(defaultView.getComputedStyle){if(name.match(/float/i))
name="float";name=name.replace(/([A-Z])/g,"-$1").toLowerCase();var computedStyle=defaultView.getComputedStyle(elem,null);if(computedStyle&&!color(elem))
ret=computedStyle.getPropertyValue(name);else{var swap=[],stack=[],a=elem,i=0;for(;a&&color(a);a=a.parentNode)
stack.unshift(a);for(;i<stack.length;i++)
if(color(stack[i])){swap[i]=stack[i].style.display;stack[i].style.display="block";}
ret=name=="display"&&swap[stack.length-1]!=null?"none":(computedStyle&&computedStyle.getPropertyValue(name))||"";for(i=0;i<swap.length;i++)
if(swap[i]!=null)
stack[i].style.display=swap[i];}
if(name=="opacity"&&ret=="")
ret="1";}else if(elem.currentStyle){var camelCase=name.replace(/\-(\w)/g,function(all,letter){return letter.toUpperCase();});ret=elem.currentStyle[name]||elem.currentStyle[camelCase];if(!/^\d+(px)?$/i.test(ret)&&/^\d/.test(ret)){var left=style.left,rsLeft=elem.runtimeStyle.left;elem.runtimeStyle.left=elem.currentStyle.left;style.left=ret||0;ret=style.pixelLeft+"px";style.left=left;elem.runtimeStyle.left=rsLeft;}}
return ret;},clean:function(elems,context){var ret=[];context=context||document;if(typeof context.createElement=='undefined')
context=context.ownerDocument||context[0]&&context[0].ownerDocument||document;jQuery.each(elems,function(i,elem){if(!elem)
return;if(elem.constructor==Number)
elem+='';if(typeof elem=="string"){elem=elem.replace(/(<(\w+)[^>]*?)\/>/g,function(all,front,tag){return tag.match(/^(abbr|br|col|img|input|link|meta|param|hr|area|embed)$/i)?all:front+"></"+tag+">";});var tags=jQuery.trim(elem).toLowerCase(),div=context.createElement("div");var wrap=!tags.indexOf("<opt")&&[1,"<select multiple='multiple'>","</select>"]||!tags.indexOf("<leg")&&[1,"<fieldset>","</fieldset>"]||tags.match(/^<(thead|tbody|tfoot|colg|cap)/)&&[1,"<table>","</table>"]||!tags.indexOf("<tr")&&[2,"<table><tbody>","</tbody></table>"]||(!tags.indexOf("<td")||!tags.indexOf("<th"))&&[3,"<table><tbody><tr>","</tr></tbody></table>"]||!tags.indexOf("<col")&&[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"]||jQuery.browser.msie&&[1,"div<div>","</div>"]||[0,"",""];div.innerHTML=wrap[1]+elem+wrap[2];while(wrap[0]--)
div=div.lastChild;if(jQuery.browser.msie){var tbody=!tags.indexOf("<table")&&tags.indexOf("<tbody")<0?div.firstChild&&div.firstChild.childNodes:wrap[1]=="<table>"&&tags.indexOf("<tbody")<0?div.childNodes:[];for(var j=tbody.length-1;j>=0;--j)
if(jQuery.nodeName(tbody[j],"tbody")&&!tbody[j].childNodes.length)
tbody[j].parentNode.removeChild(tbody[j]);if(/^\s/.test(elem))
div.insertBefore(context.createTextNode(elem.match(/^\s*/)[0]),div.firstChild);}
elem=jQuery.makeArray(div.childNodes);}
if(elem.length===0&&(!jQuery.nodeName(elem,"form")&&!jQuery.nodeName(elem,"select")))
return;if(elem[0]==undefined||jQuery.nodeName(elem,"form")||elem.options)
ret.push(elem);else
ret=jQuery.merge(ret,elem);});return ret;},attr:function(elem,name,value){if(!elem||elem.nodeType==3||elem.nodeType==8)
return undefined;var notxml=!jQuery.isXMLDoc(elem),set=value!==undefined,msie=jQuery.browser.msie;name=notxml&&jQuery.props[name]||name;if(elem.tagName){var special=/href|src|style/.test(name);if(name=="selected"&&jQuery.browser.safari)
elem.parentNode.selectedIndex;if(name in elem&&notxml&&!special){if(set){if(name=="type"&&jQuery.nodeName(elem,"input")&&elem.parentNode)
throw"type property can't be changed";elem[name]=value;}
if(jQuery.nodeName(elem,"form")&&elem.getAttributeNode(name))
return elem.getAttributeNode(name).nodeValue;return elem[name];}
if(msie&&notxml&&name=="style")
return jQuery.attr(elem.style,"cssText",value);if(set)
elem.setAttribute(name,""+value);var attr=msie&&notxml&&special?elem.getAttribute(name,2):elem.getAttribute(name);return attr===null?undefined:attr;}
if(msie&&name=="opacity"){if(set){elem.zoom=1;elem.filter=(elem.filter||"").replace(/alpha\([^)]*\)/,"")+
(parseInt(value)+''=="NaN"?"":"alpha(opacity="+value*100+")");}
return elem.filter&&elem.filter.indexOf("opacity=")>=0?(parseFloat(elem.filter.match(/opacity=([^)]*)/)[1])/100)+'':"";}
name=name.replace(/-([a-z])/ig,function(all,letter){return letter.toUpperCase();});if(set)
elem[name]=value;return elem[name];},trim:function(text){return(text||"").replace(/^\s+|\s+$/g,"");},makeArray:function(array){var ret=[];if(array!=null){var i=array.length;if(i==null||array.split||array.setInterval||array.call)
ret[0]=array;else
while(i)
ret[--i]=array[i];}
return ret;},inArray:function(elem,array){for(var i=0,length=array.length;i<length;i++)
if(array[i]===elem)
return i;return-1;},merge:function(first,second){var i=0,elem,pos=first.length;if(jQuery.browser.msie){while(elem=second[i++])
if(elem.nodeType!=8)
first[pos++]=elem;}else
while(elem=second[i++])
first[pos++]=elem;return first;},unique:function(array){var ret=[],done={};try{for(var i=0,length=array.length;i<length;i++){var id=jQuery.data(array[i]);if(!done[id]){done[id]=true;ret.push(array[i]);}}}catch(e){ret=array;}
return ret;},grep:function(elems,callback,inv){var ret=[];for(var i=0,length=elems.length;i<length;i++)
if(!inv!=!callback(elems[i],i))
ret.push(elems[i]);return ret;},map:function(elems,callback){var ret=[];for(var i=0,length=elems.length;i<length;i++){var value=callback(elems[i],i);if(value!=null)
ret[ret.length]=value;}
return ret.concat.apply([],ret);}});var userAgent=navigator.userAgent.toLowerCase();jQuery.browser={version:(userAgent.match(/.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/)||[])[1],safari:/webkit/.test(userAgent),opera:/opera/.test(userAgent),msie:/msie/.test(userAgent)&&!/opera/.test(userAgent),mozilla:/mozilla/.test(userAgent)&&!/(compatible|webkit)/.test(userAgent)};var styleFloat=jQuery.browser.msie?"styleFloat":"cssFloat";jQuery.extend({boxModel:!jQuery.browser.msie||document.compatMode=="CSS1Compat",props:{"for":"htmlFor","class":"className","float":styleFloat,cssFloat:styleFloat,styleFloat:styleFloat,readonly:"readOnly",maxlength:"maxLength",cellspacing:"cellSpacing"}});jQuery.each({parent:function(elem){return elem.parentNode;},parents:function(elem){return jQuery.dir(elem,"parentNode");},next:function(elem){return jQuery.nth(elem,2,"nextSibling");},prev:function(elem){return jQuery.nth(elem,2,"previousSibling");},nextAll:function(elem){return jQuery.dir(elem,"nextSibling");},prevAll:function(elem){return jQuery.dir(elem,"previousSibling");},siblings:function(elem){return jQuery.sibling(elem.parentNode.firstChild,elem);},children:function(elem){return jQuery.sibling(elem.firstChild);},contents:function(elem){return jQuery.nodeName(elem,"iframe")?elem.contentDocument||elem.contentWindow.document:jQuery.makeArray(elem.childNodes);}},function(name,fn){jQuery.fn[name]=function(selector){var ret=jQuery.map(this,fn);if(selector&&typeof selector=="string")
ret=jQuery.multiFilter(selector,ret);return this.pushStack(jQuery.unique(ret));};});jQuery.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(name,original){jQuery.fn[name]=function(){var args=arguments;return this.each(function(){for(var i=0,length=args.length;i<length;i++)
jQuery(args[i])[original](this);});};});jQuery.each({removeAttr:function(name){jQuery.attr(this,name,"");if(this.nodeType==1)
this.removeAttribute(name);},addClass:function(classNames){jQuery.className.add(this,classNames);},removeClass:function(classNames){jQuery.className.remove(this,classNames);},toggleClass:function(classNames){jQuery.className[jQuery.className.has(this,classNames)?"remove":"add"](this,classNames);},remove:function(selector){if(!selector||jQuery.filter(selector,[this]).r.length){jQuery("*",this).add(this).each(function(){jQuery.event.remove(this);jQuery.removeData(this);});if(this.parentNode)
this.parentNode.removeChild(this);}},empty:function(){jQuery(">*",this).remove();while(this.firstChild)
this.removeChild(this.firstChild);}},function(name,fn){jQuery.fn[name]=function(){return this.each(fn,arguments);};});jQuery.each(["Height","Width"],function(i,name){var type=name.toLowerCase();jQuery.fn[type]=function(size){return this[0]==window?jQuery.browser.opera&&document.body["client"+name]||jQuery.browser.safari&&window["inner"+name]||document.compatMode=="CSS1Compat"&&document.documentElement["client"+name]||document.body["client"+name]:this[0]==document?Math.max(Math.max(document.body["scroll"+name],document.documentElement["scroll"+name]),Math.max(document.body["offset"+name],document.documentElement["offset"+name])):size==undefined?(this.length?jQuery.css(this[0],type):null):this.css(type,size.constructor==String?size:size+"px");};});function num(elem,prop){return elem[0]&&parseInt(jQuery.curCSS(elem[0],prop,true),10)||0;}var chars=jQuery.browser.safari&&parseInt(jQuery.browser.version)<417?"(?:[\\w*_-]|\\\\.)":"(?:[\\w\u0128-\uFFFF*_-]|\\\\.)",quickChild=new RegExp("^>\\s*("+chars+"+)"),quickID=new RegExp("^("+chars+"+)(#)("+chars+"+)"),quickClass=new RegExp("^([#.]?)("+chars+"*)");jQuery.extend({expr:{"":function(a,i,m){return m[2]=="*"||jQuery.nodeName(a,m[2]);},"#":function(a,i,m){return a.getAttribute("id")==m[2];},":":{lt:function(a,i,m){return i<m[3]-0;},gt:function(a,i,m){return i>m[3]-0;},nth:function(a,i,m){return m[3]-0==i;},eq:function(a,i,m){return m[3]-0==i;},first:function(a,i){return i==0;},last:function(a,i,m,r){return i==r.length-1;},even:function(a,i){return i%2==0;},odd:function(a,i){return i%2;},"first-child":function(a){return a.parentNode.getElementsByTagName("*")[0]==a;},"last-child":function(a){return jQuery.nth(a.parentNode.lastChild,1,"previousSibling")==a;},"only-child":function(a){return!jQuery.nth(a.parentNode.lastChild,2,"previousSibling");},parent:function(a){return a.firstChild;},empty:function(a){return!a.firstChild;},contains:function(a,i,m){return(a.textContent||a.innerText||jQuery(a).text()||"").indexOf(m[3])>=0;},visible:function(a){return"hidden"!=a.type&&jQuery.css(a,"display")!="none"&&jQuery.css(a,"visibility")!="hidden";},hidden:function(a){return"hidden"==a.type||jQuery.css(a,"display")=="none"||jQuery.css(a,"visibility")=="hidden";},enabled:function(a){return!a.disabled;},disabled:function(a){return a.disabled;},checked:function(a){return a.checked;},selected:function(a){return a.selected||jQuery.attr(a,"selected");},text:function(a){return"text"==a.type;},radio:function(a){return"radio"==a.type;},checkbox:function(a){return"checkbox"==a.type;},file:function(a){return"file"==a.type;},password:function(a){return"password"==a.type;},submit:function(a){return"submit"==a.type;},image:function(a){return"image"==a.type;},reset:function(a){return"reset"==a.type;},button:function(a){return"button"==a.type||jQuery.nodeName(a,"button");},input:function(a){return/input|select|textarea|button/i.test(a.nodeName);},has:function(a,i,m){return jQuery.find(m[3],a).length;},header:function(a){return/h\d/i.test(a.nodeName);},animated:function(a){return jQuery.grep(jQuery.timers,function(fn){return a==fn.elem;}).length;}}},parse:[/^(\[) *@?([\w-]+) *([!*$^~=]*) *('?"?)(.*?)\4 *\]/,/^(:)([\w-]+)\("?'?(.*?(\(.*?\))?[^(]*?)"?'?\)/,new RegExp("^([:.#]*)("+chars+"+)")],multiFilter:function(expr,elems,not){var old,cur=[];while(expr&&expr!=old){old=expr;var f=jQuery.filter(expr,elems,not);expr=f.t.replace(/^\s*,\s*/,"");cur=not?elems=f.r:jQuery.merge(cur,f.r);}
return cur;},find:function(t,context){if(typeof t!="string")
return[t];if(context&&context.nodeType!=1&&context.nodeType!=9)
return[];context=context||document;var ret=[context],done=[],last,nodeName;while(t&&last!=t){var r=[];last=t;t=jQuery.trim(t);var foundToken=false,re=quickChild,m=re.exec(t);if(m){nodeName=m[1].toUpperCase();for(var i=0;ret[i];i++)
for(var c=ret[i].firstChild;c;c=c.nextSibling)
if(c.nodeType==1&&(nodeName=="*"||c.nodeName.toUpperCase()==nodeName))
r.push(c);ret=r;t=t.replace(re,"");if(t.indexOf(" ")==0)continue;foundToken=true;}else{re=/^([>+~])\s*(\w*)/i;if((m=re.exec(t))!=null){r=[];var merge={};nodeName=m[2].toUpperCase();m=m[1];for(var j=0,rl=ret.length;j<rl;j++){var n=m=="~"||m=="+"?ret[j].nextSibling:ret[j].firstChild;for(;n;n=n.nextSibling)
if(n.nodeType==1){var id=jQuery.data(n);if(m=="~"&&merge[id])break;if(!nodeName||n.nodeName.toUpperCase()==nodeName){if(m=="~")merge[id]=true;r.push(n);}
if(m=="+")break;}}
ret=r;t=jQuery.trim(t.replace(re,""));foundToken=true;}}
if(t&&!foundToken){if(!t.indexOf(",")){if(context==ret[0])ret.shift();done=jQuery.merge(done,ret);r=ret=[context];t=" "+t.substr(1,t.length);}else{var re2=quickID;var m=re2.exec(t);if(m){m=[0,m[2],m[3],m[1]];}else{re2=quickClass;m=re2.exec(t);}
m[2]=m[2].replace(/\\/g,"");var elem=ret[ret.length-1];if(m[1]=="#"&&elem&&elem.getElementById&&!jQuery.isXMLDoc(elem)){var oid=elem.getElementById(m[2]);if((jQuery.browser.msie||jQuery.browser.opera)&&oid&&typeof oid.id=="string"&&oid.id!=m[2])
oid=jQuery('[@id="'+m[2]+'"]',elem)[0];ret=r=oid&&(!m[3]||jQuery.nodeName(oid,m[3]))?[oid]:[];}else{for(var i=0;ret[i];i++){var tag=m[1]=="#"&&m[3]?m[3]:m[1]!=""||m[0]==""?"*":m[2];if(tag=="*"&&ret[i].nodeName.toLowerCase()=="object")
tag="param";r=jQuery.merge(r,ret[i].getElementsByTagName(tag));}
if(m[1]==".")
r=jQuery.classFilter(r,m[2]);if(m[1]=="#"){var tmp=[];for(var i=0;r[i];i++)
if(r[i].getAttribute("id")==m[2]){tmp=[r[i]];break;}
r=tmp;}
ret=r;}
t=t.replace(re2,"");}}
if(t){var val=jQuery.filter(t,r);ret=r=val.r;t=jQuery.trim(val.t);}}
if(t)
ret=[];if(ret&&context==ret[0])
ret.shift();done=jQuery.merge(done,ret);return done;},classFilter:function(r,m,not){m=" "+m+" ";var tmp=[];for(var i=0;r[i];i++){var pass=(" "+r[i].className+" ").indexOf(m)>=0;if(!not&&pass||not&&!pass)
tmp.push(r[i]);}
return tmp;},filter:function(t,r,not){var last;while(t&&t!=last){last=t;var p=jQuery.parse,m;for(var i=0;p[i];i++){m=p[i].exec(t);if(m){t=t.substring(m[0].length);m[2]=m[2].replace(/\\/g,"");break;}}
if(!m)
break;if(m[1]==":"&&m[2]=="not")
r=isSimple.test(m[3])?jQuery.filter(m[3],r,true).r:jQuery(r).not(m[3]);else if(m[1]==".")
r=jQuery.classFilter(r,m[2],not);else if(m[1]=="["){var tmp=[],type=m[3];for(var i=0,rl=r.length;i<rl;i++){var a=r[i],z=a[jQuery.props[m[2]]||m[2]];if(z==null||/href|src|selected/.test(m[2]))
z=jQuery.attr(a,m[2])||'';if((type==""&&!!z||type=="="&&z==m[5]||type=="!="&&z!=m[5]||type=="^="&&z&&!z.indexOf(m[5])||type=="$="&&z.substr(z.length-m[5].length)==m[5]||(type=="*="||type=="~=")&&z.indexOf(m[5])>=0)^not)
tmp.push(a);}
r=tmp;}else if(m[1]==":"&&m[2]=="nth-child"){var merge={},tmp=[],test=/(-?)(\d*)n((?:\+|-)?\d*)/.exec(m[3]=="even"&&"2n"||m[3]=="odd"&&"2n+1"||!/\D/.test(m[3])&&"0n+"+m[3]||m[3]),first=(test[1]+(test[2]||1))-0,last=test[3]-0;for(var i=0,rl=r.length;i<rl;i++){var node=r[i],parentNode=node.parentNode,id=jQuery.data(parentNode);if(!merge[id]){var c=1;for(var n=parentNode.firstChild;n;n=n.nextSibling)
if(n.nodeType==1)
n.nodeIndex=c++;merge[id]=true;}
var add=false;if(first==0){if(node.nodeIndex==last)
add=true;}else if((node.nodeIndex-last)%first==0&&(node.nodeIndex-last)/first>=0)
add=true;if(add^not)
tmp.push(node);}
r=tmp;}else{var fn=jQuery.expr[m[1]];if(typeof fn=="object")
fn=fn[m[2]];if(typeof fn=="string")
fn=eval("false||function(a,i){return "+fn+";}");r=jQuery.grep(r,function(elem,i){return fn(elem,i,m,r);},not);}}
return{r:r,t:t};},dir:function(elem,dir){var matched=[],cur=elem[dir];while(cur&&cur!=document){if(cur.nodeType==1)
matched.push(cur);cur=cur[dir];}
return matched;},nth:function(cur,result,dir,elem){result=result||1;var num=0;for(;cur;cur=cur[dir])
if(cur.nodeType==1&&++num==result)
break;return cur;},sibling:function(n,elem){var r=[];for(;n;n=n.nextSibling){if(n.nodeType==1&&n!=elem)
r.push(n);}
return r;}});jQuery.event={add:function(elem,types,handler,data){if(elem.nodeType==3||elem.nodeType==8)
return;if(jQuery.browser.msie&&elem.setInterval)
elem=window;if(!handler.guid)
handler.guid=this.guid++;if(data!=undefined){var fn=handler;handler=this.proxy(fn,function(){return fn.apply(this,arguments);});handler.data=data;}
var events=jQuery.data(elem,"events")||jQuery.data(elem,"events",{}),handle=jQuery.data(elem,"handle")||jQuery.data(elem,"handle",function(){if(typeof jQuery!="undefined"&&!jQuery.event.triggered)
return jQuery.event.handle.apply(arguments.callee.elem,arguments);});handle.elem=elem;jQuery.each(types.split(/\s+/),function(index,type){var parts=type.split(".");type=parts[0];handler.type=parts[1];var handlers=events[type];if(!handlers){handlers=events[type]={};if(!jQuery.event.special[type]||jQuery.event.special[type].setup.call(elem)===false){if(elem.addEventListener)
elem.addEventListener(type,handle,false);else if(elem.attachEvent)
elem.attachEvent("on"+type,handle);}}
handlers[handler.guid]=handler;jQuery.event.global[type]=true;});elem=null;},guid:1,global:{},remove:function(elem,types,handler){if(elem.nodeType==3||elem.nodeType==8)
return;var events=jQuery.data(elem,"events"),ret,index;if(events){if(types==undefined||(typeof types=="string"&&types.charAt(0)=="."))
for(var type in events)
this.remove(elem,type+(types||""));else{if(types.type){handler=types.handler;types=types.type;}
jQuery.each(types.split(/\s+/),function(index,type){var parts=type.split(".");type=parts[0];if(events[type]){if(handler)
delete events[type][handler.guid];else
for(handler in events[type])
if(!parts[1]||events[type][handler].type==parts[1])
delete events[type][handler];for(ret in events[type])break;if(!ret){if(!jQuery.event.special[type]||jQuery.event.special[type].teardown.call(elem)===false){if(elem.removeEventListener)
elem.removeEventListener(type,jQuery.data(elem,"handle"),false);else if(elem.detachEvent)
elem.detachEvent("on"+type,jQuery.data(elem,"handle"));}
ret=null;delete events[type];}}});}
for(ret in events)break;if(!ret){var handle=jQuery.data(elem,"handle");if(handle)handle.elem=null;jQuery.removeData(elem,"events");jQuery.removeData(elem,"handle");}}},trigger:function(type,data,elem,donative,extra){data=jQuery.makeArray(data);if(type.indexOf("!")>=0){type=type.slice(0,-1);var exclusive=true;}
if(!elem){if(this.global[type])
jQuery("*").add([window,document]).trigger(type,data);}else{if(elem.nodeType==3||elem.nodeType==8)
return undefined;var val,ret,fn=jQuery.isFunction(elem[type]||null),event=!data[0]||!data[0].preventDefault;if(event){data.unshift({type:type,target:elem,preventDefault:function(){},stopPropagation:function(){},timeStamp:now()});data[0][expando]=true;}
data[0].type=type;if(exclusive)
data[0].exclusive=true;var handle=jQuery.data(elem,"handle");if(handle)
val=handle.apply(elem,data);if((!fn||(jQuery.nodeName(elem,'a')&&type=="click"))&&elem["on"+type]&&elem["on"+type].apply(elem,data)===false)
val=false;if(event)
data.shift();if(extra&&jQuery.isFunction(extra)){ret=extra.apply(elem,val==null?data:data.concat(val));if(ret!==undefined)
val=ret;}
if(fn&&donative!==false&&val!==false&&!(jQuery.nodeName(elem,'a')&&type=="click")){this.triggered=true;try{elem[type]();}catch(e){}}
this.triggered=false;}
return val;},handle:function(event){var val,ret,namespace,all,handlers;event=arguments[0]=jQuery.event.fix(event||window.event);namespace=event.type.split(".");event.type=namespace[0];namespace=namespace[1];all=!namespace&&!event.exclusive;handlers=(jQuery.data(this,"events")||{})[event.type];for(var j in handlers){var handler=handlers[j];if(all||handler.type==namespace){event.handler=handler;event.data=handler.data;ret=handler.apply(this,arguments);if(val!==false)
val=ret;if(ret===false){event.preventDefault();event.stopPropagation();}}}
return val;},fix:function(event){if(event[expando]==true)
return event;var originalEvent=event;event={originalEvent:originalEvent};var props="altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode metaKey newValue originalTarget pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target timeStamp toElement type view wheelDelta which".split(" ");for(var i=props.length;i;i--)
event[props[i]]=originalEvent[props[i]];event[expando]=true;event.preventDefault=function(){if(originalEvent.preventDefault)
originalEvent.preventDefault();originalEvent.returnValue=false;};event.stopPropagation=function(){if(originalEvent.stopPropagation)
originalEvent.stopPropagation();originalEvent.cancelBubble=true;};event.timeStamp=event.timeStamp||now();if(!event.target)
event.target=event.srcElement||document;if(event.target.nodeType==3)
event.target=event.target.parentNode;if(!event.relatedTarget&&event.fromElement)
event.relatedTarget=event.fromElement==event.target?event.toElement:event.fromElement;if(event.pageX==null&&event.clientX!=null){var doc=document.documentElement,body=document.body;event.pageX=event.clientX+(doc&&doc.scrollLeft||body&&body.scrollLeft||0)-(doc.clientLeft||0);event.pageY=event.clientY+(doc&&doc.scrollTop||body&&body.scrollTop||0)-(doc.clientTop||0);}
if(!event.which&&((event.charCode||event.charCode===0)?event.charCode:event.keyCode))
event.which=event.charCode||event.keyCode;if(!event.metaKey&&event.ctrlKey)
event.metaKey=event.ctrlKey;if(!event.which&&event.button)
event.which=(event.button&1?1:(event.button&2?3:(event.button&4?2:0)));return event;},proxy:function(fn,proxy){proxy.guid=fn.guid=fn.guid||proxy.guid||this.guid++;return proxy;},special:{ready:{setup:function(){bindReady();return;},teardown:function(){return;}},mouseenter:{setup:function(){if(jQuery.browser.msie)return false;jQuery(this).bind("mouseover",jQuery.event.special.mouseenter.handler);return true;},teardown:function(){if(jQuery.browser.msie)return false;jQuery(this).unbind("mouseover",jQuery.event.special.mouseenter.handler);return true;},handler:function(event){if(withinElement(event,this))return true;event.type="mouseenter";return jQuery.event.handle.apply(this,arguments);}},mouseleave:{setup:function(){if(jQuery.browser.msie)return false;jQuery(this).bind("mouseout",jQuery.event.special.mouseleave.handler);return true;},teardown:function(){if(jQuery.browser.msie)return false;jQuery(this).unbind("mouseout",jQuery.event.special.mouseleave.handler);return true;},handler:function(event){if(withinElement(event,this))return true;event.type="mouseleave";return jQuery.event.handle.apply(this,arguments);}}}};jQuery.fn.extend({bind:function(type,data,fn){return type=="unload"?this.one(type,data,fn):this.each(function(){jQuery.event.add(this,type,fn||data,fn&&data);});},one:function(type,data,fn){var one=jQuery.event.proxy(fn||data,function(event){jQuery(this).unbind(event,one);return(fn||data).apply(this,arguments);});return this.each(function(){jQuery.event.add(this,type,one,fn&&data);});},unbind:function(type,fn){return this.each(function(){jQuery.event.remove(this,type,fn);});},trigger:function(type,data,fn){return this.each(function(){jQuery.event.trigger(type,data,this,true,fn);});},triggerHandler:function(type,data,fn){return this[0]&&jQuery.event.trigger(type,data,this[0],false,fn);},toggle:function(fn){var args=arguments,i=1;while(i<args.length)
jQuery.event.proxy(fn,args[i++]);return this.click(jQuery.event.proxy(fn,function(event){this.lastToggle=(this.lastToggle||0)%i;event.preventDefault();return args[this.lastToggle++].apply(this,arguments)||false;}));},hover:function(fnOver,fnOut){return this.bind('mouseenter',fnOver).bind('mouseleave',fnOut);},ready:function(fn){bindReady();if(jQuery.isReady)
fn.call(document,jQuery);else
jQuery.readyList.push(function(){return fn.call(this,jQuery);});return this;}});jQuery.extend({isReady:false,readyList:[],ready:function(){if(!jQuery.isReady){jQuery.isReady=true;if(jQuery.readyList){jQuery.each(jQuery.readyList,function(){this.call(document);});jQuery.readyList=null;}
jQuery(document).triggerHandler("ready");}}});var readyBound=false;function bindReady(){if(readyBound)return;readyBound=true;if(document.addEventListener&&!jQuery.browser.opera)
document.addEventListener("DOMContentLoaded",jQuery.ready,false);if(jQuery.browser.msie&&window==top)(function(){if(jQuery.isReady)return;try{document.documentElement.doScroll("left");}catch(error){setTimeout(arguments.callee,0);return;}
jQuery.ready();})();if(jQuery.browser.opera)
document.addEventListener("DOMContentLoaded",function(){if(jQuery.isReady)return;for(var i=0;i<document.styleSheets.length;i++)
if(document.styleSheets[i].disabled){setTimeout(arguments.callee,0);return;}
jQuery.ready();},false);if(jQuery.browser.safari){var numStyles;(function(){if(jQuery.isReady)return;if(document.readyState!="loaded"&&document.readyState!="complete"){setTimeout(arguments.callee,0);return;}
if(numStyles===undefined)
numStyles=jQuery("style, link[rel=stylesheet]").length;if(document.styleSheets.length!=numStyles){setTimeout(arguments.callee,0);return;}
jQuery.ready();})();}
jQuery.event.add(window,"load",jQuery.ready);}
jQuery.each(("blur,focus,load,resize,scroll,unload,click,dblclick,"+"mousedown,mouseup,mousemove,mouseover,mouseout,change,select,"+"submit,keydown,keypress,keyup,error").split(","),function(i,name){jQuery.fn[name]=function(fn){return fn?this.bind(name,fn):this.trigger(name);};});var withinElement=function(event,elem){var parent=event.relatedTarget;while(parent&&parent!=elem)try{parent=parent.parentNode;}catch(error){parent=elem;}
return parent==elem;};jQuery(window).bind("unload",function(){jQuery("*").add(document).unbind();});jQuery.fn.extend({_load:jQuery.fn.load,load:function(url,params,callback){if(typeof url!='string')
return this._load(url);var off=url.indexOf(" ");if(off>=0){var selector=url.slice(off,url.length);url=url.slice(0,off);}
callback=callback||function(){};var type="GET";if(params)
if(jQuery.isFunction(params)){callback=params;params=null;}else{params=jQuery.param(params);type="POST";}
var self=this;jQuery.ajax({url:url,type:type,dataType:"html",data:params,complete:function(res,status){if(status=="success"||status=="notmodified")
self.html(selector?jQuery("<div/>").append(res.responseText.replace(/<script(.|\s)*?\/script>/g,"")).find(selector):res.responseText);self.each(callback,[res.responseText,status,res]);}});return this;},serialize:function(){return jQuery.param(this.serializeArray());},serializeArray:function(){return this.map(function(){return jQuery.nodeName(this,"form")?jQuery.makeArray(this.elements):this;}).filter(function(){return this.name&&!this.disabled&&(this.checked||/select|textarea/i.test(this.nodeName)||/text|hidden|password/i.test(this.type));}).map(function(i,elem){var val=jQuery(this).val();return val==null?null:val.constructor==Array?jQuery.map(val,function(val,i){return{name:elem.name,value:val};}):{name:elem.name,value:val};}).get();}});jQuery.each("ajaxStart,ajaxStop,ajaxComplete,ajaxError,ajaxSuccess,ajaxSend".split(","),function(i,o){jQuery.fn[o]=function(f){return this.bind(o,f);};});var jsc=now();jQuery.extend({get:function(url,data,callback,type){if(jQuery.isFunction(data)){callback=data;data=null;}
return jQuery.ajax({type:"GET",url:url,data:data,success:callback,dataType:type});},getScript:function(url,callback){return jQuery.get(url,null,callback,"script");},getJSON:function(url,data,callback){return jQuery.get(url,data,callback,"json");},post:function(url,data,callback,type){if(jQuery.isFunction(data)){callback=data;data={};}
return jQuery.ajax({type:"POST",url:url,data:data,success:callback,dataType:type});},ajaxSetup:function(settings){jQuery.extend(jQuery.ajaxSettings,settings);},ajaxSettings:{url:location.href,global:true,type:"GET",timeout:0,contentType:"application/x-www-form-urlencoded",processData:true,async:true,data:null,username:null,password:null,accepts:{xml:"application/xml, text/xml",html:"text/html",script:"text/javascript, application/javascript",json:"application/json, text/javascript",text:"text/plain",_default:"*/*"}},lastModified:{},ajax:function(s){s=jQuery.extend(true,s,jQuery.extend(true,{},jQuery.ajaxSettings,s));var jsonp,jsre=/=\?(&|$)/g,status,data,type=s.type.toUpperCase();if(s.data&&s.processData&&typeof s.data!="string")
s.data=jQuery.param(s.data);if(s.dataType=="jsonp"){if(type=="GET"){if(!s.url.match(jsre))
s.url+=(s.url.match(/\?/)?"&":"?")+(s.jsonp||"callback")+"=?";}else if(!s.data||!s.data.match(jsre))
s.data=(s.data?s.data+"&":"")+(s.jsonp||"callback")+"=?";s.dataType="json";}
if(s.dataType=="json"&&(s.data&&s.data.match(jsre)||s.url.match(jsre))){jsonp="jsonp"+jsc++;if(s.data)
s.data=(s.data+"").replace(jsre,"="+jsonp+"$1");s.url=s.url.replace(jsre,"="+jsonp+"$1");s.dataType="script";window[jsonp]=function(tmp){data=tmp;success();complete();window[jsonp]=undefined;try{delete window[jsonp];}catch(e){}
if(head)
head.removeChild(script);};}
if(s.dataType=="script"&&s.cache==null)
s.cache=false;if(s.cache===false&&type=="GET"){var ts=now();var ret=s.url.replace(/(\?|&)_=.*?(&|$)/,"$1_="+ts+"$2");s.url=ret+((ret==s.url)?(s.url.match(/\?/)?"&":"?")+"_="+ts:"");}
if(s.data&&type=="GET"){s.url+=(s.url.match(/\?/)?"&":"?")+s.data;s.data=null;}
if(s.global&&!jQuery.active++)
jQuery.event.trigger("ajaxStart");var remote=/^(?:\w+:)?\/\/([^\/?#]+)/;if(s.dataType=="script"&&type=="GET"&&remote.test(s.url)&&remote.exec(s.url)[1]!=location.host){var head=document.getElementsByTagName("head")[0];var script=document.createElement("script");script.src=s.url;if(s.scriptCharset)
script.charset=s.scriptCharset;if(!jsonp){var done=false;script.onload=script.onreadystatechange=function(){if(!done&&(!this.readyState||this.readyState=="loaded"||this.readyState=="complete")){done=true;success();complete();head.removeChild(script);}};}
head.appendChild(script);return undefined;}
var requestDone=false;var xhr=window.ActiveXObject?new ActiveXObject("Microsoft.XMLHTTP"):new XMLHttpRequest();if(s.username)
xhr.open(type,s.url,s.async,s.username,s.password);else
xhr.open(type,s.url,s.async);try{if(s.data)
xhr.setRequestHeader("Content-Type",s.contentType);if(s.ifModified)
xhr.setRequestHeader("If-Modified-Since",jQuery.lastModified[s.url]||"Thu, 01 Jan 1970 00:00:00 GMT");xhr.setRequestHeader("X-Requested-With","XMLHttpRequest");xhr.setRequestHeader("Accept",s.dataType&&s.accepts[s.dataType]?s.accepts[s.dataType]+", */*":s.accepts._default);}catch(e){}
if(s.beforeSend&&s.beforeSend(xhr,s)===false){s.global&&jQuery.active--;xhr.abort();return false;}
if(s.global)
jQuery.event.trigger("ajaxSend",[xhr,s]);var onreadystatechange=function(isTimeout){if(!requestDone&&xhr&&(xhr.readyState==4||isTimeout=="timeout")){requestDone=true;if(ival){clearInterval(ival);ival=null;}
status=isTimeout=="timeout"&&"timeout"||!jQuery.httpSuccess(xhr)&&"error"||s.ifModified&&jQuery.httpNotModified(xhr,s.url)&&"notmodified"||"success";if(status=="success"){try{data=jQuery.httpData(xhr,s.dataType,s.dataFilter);}catch(e){status="parsererror";}}
if(status=="success"){var modRes;try{modRes=xhr.getResponseHeader("Last-Modified");}catch(e){}
if(s.ifModified&&modRes)
jQuery.lastModified[s.url]=modRes;if(!jsonp)
success();}else
jQuery.handleError(s,xhr,status);complete();if(s.async)
xhr=null;}};if(s.async){var ival=setInterval(onreadystatechange,13);if(s.timeout>0)
setTimeout(function(){if(xhr){xhr.abort();if(!requestDone)
onreadystatechange("timeout");}},s.timeout);}
try{xhr.send(s.data);}catch(e){jQuery.handleError(s,xhr,null,e);}
if(!s.async)
onreadystatechange();function success(){if(s.success)
s.success(data,status);if(s.global)
jQuery.event.trigger("ajaxSuccess",[xhr,s]);}
function complete(){if(s.complete)
s.complete(xhr,status);if(s.global)
jQuery.event.trigger("ajaxComplete",[xhr,s]);if(s.global&&!--jQuery.active)
jQuery.event.trigger("ajaxStop");}
return xhr;},handleError:function(s,xhr,status,e){if(s.error)s.error(xhr,status,e);if(s.global)
jQuery.event.trigger("ajaxError",[xhr,s,e]);},active:0,httpSuccess:function(xhr){try{return!xhr.status&&location.protocol=="file:"||(xhr.status>=200&&xhr.status<300)||xhr.status==304||xhr.status==1223||jQuery.browser.safari&&xhr.status==undefined;}catch(e){}
return false;},httpNotModified:function(xhr,url){try{var xhrRes=xhr.getResponseHeader("Last-Modified");return xhr.status==304||xhrRes==jQuery.lastModified[url]||jQuery.browser.safari&&xhr.status==undefined;}catch(e){}
return false;},httpData:function(xhr,type,filter){var ct=xhr.getResponseHeader("content-type"),xml=type=="xml"||!type&&ct&&ct.indexOf("xml")>=0,data=xml?xhr.responseXML:xhr.responseText;if(xml&&data.documentElement.tagName=="parsererror")
throw"parsererror";if(filter)
data=filter(data,type);if(type=="script")
jQuery.globalEval(data);if(type=="json")
data=eval("("+data+")");return data;},param:function(a){var s=[];if(a.constructor==Array||a.jquery)
jQuery.each(a,function(){s.push(encodeURIComponent(this.name)+"="+encodeURIComponent(this.value));});else
for(var j in a)
if(a[j]&&a[j].constructor==Array)
jQuery.each(a[j],function(){s.push(encodeURIComponent(j)+"="+encodeURIComponent(this));});else
s.push(encodeURIComponent(j)+"="+encodeURIComponent(jQuery.isFunction(a[j])?a[j]():a[j]));return s.join("&").replace(/%20/g,"+");}});jQuery.fn.extend({show:function(speed,callback){return speed?this.animate({height:"show",width:"show",opacity:"show"},speed,callback):this.filter(":hidden").each(function(){this.style.display=this.oldblock||"";if(jQuery.css(this,"display")=="none"){var elem=jQuery("<"+this.tagName+" />").appendTo("body");this.style.display=elem.css("display");if(this.style.display=="none")
this.style.display="block";elem.remove();}}).end();},hide:function(speed,callback){return speed?this.animate({height:"hide",width:"hide",opacity:"hide"},speed,callback):this.filter(":visible").each(function(){this.oldblock=this.oldblock||jQuery.css(this,"display");this.style.display="none";}).end();},_toggle:jQuery.fn.toggle,toggle:function(fn,fn2){return jQuery.isFunction(fn)&&jQuery.isFunction(fn2)?this._toggle.apply(this,arguments):fn?this.animate({height:"toggle",width:"toggle",opacity:"toggle"},fn,fn2):this.each(function(){jQuery(this)[jQuery(this).is(":hidden")?"show":"hide"]();});},slideDown:function(speed,callback){return this.animate({height:"show"},speed,callback);},slideUp:function(speed,callback){return this.animate({height:"hide"},speed,callback);},slideToggle:function(speed,callback){return this.animate({height:"toggle"},speed,callback);},fadeIn:function(speed,callback){return this.animate({opacity:"show"},speed,callback);},fadeOut:function(speed,callback){return this.animate({opacity:"hide"},speed,callback);},fadeTo:function(speed,to,callback){return this.animate({opacity:to},speed,callback);},animate:function(prop,speed,easing,callback){var optall=jQuery.speed(speed,easing,callback);return this[optall.queue===false?"each":"queue"](function(){if(this.nodeType!=1)
return false;var opt=jQuery.extend({},optall),p,hidden=jQuery(this).is(":hidden"),self=this;for(p in prop){if(prop[p]=="hide"&&hidden||prop[p]=="show"&&!hidden)
return opt.complete.call(this);if(p=="height"||p=="width"){opt.display=jQuery.css(this,"display");opt.overflow=this.style.overflow;}}
if(opt.overflow!=null)
this.style.overflow="hidden";opt.curAnim=jQuery.extend({},prop);jQuery.each(prop,function(name,val){var e=new jQuery.fx(self,opt,name);if(/toggle|show|hide/.test(val))
e[val=="toggle"?hidden?"show":"hide":val](prop);else{var parts=val.toString().match(/^([+-]=)?([\d+-.]+)(.*)$/),start=e.cur(true)||0;if(parts){var end=parseFloat(parts[2]),unit=parts[3]||"px";if(unit!="px"){self.style[name]=(end||1)+unit;start=((end||1)/e.cur(true))*start;self.style[name]=start+unit;}
if(parts[1])
end=((parts[1]=="-="?-1:1)*end)+start;e.custom(start,end,unit);}else
e.custom(start,val,"");}});return true;});},queue:function(type,fn){if(jQuery.isFunction(type)||(type&&type.constructor==Array)){fn=type;type="fx";}
if(!type||(typeof type=="string"&&!fn))
return queue(this[0],type);return this.each(function(){if(fn.constructor==Array)
queue(this,type,fn);else{queue(this,type).push(fn);if(queue(this,type).length==1)
fn.call(this);}});},stop:function(clearQueue,gotoEnd){var timers=jQuery.timers;if(clearQueue)
this.queue([]);this.each(function(){for(var i=timers.length-1;i>=0;i--)
if(timers[i].elem==this){if(gotoEnd)
timers[i](true);timers.splice(i,1);}});if(!gotoEnd)
this.dequeue();return this;}});var queue=function(elem,type,array){if(elem){type=type||"fx";var q=jQuery.data(elem,type+"queue");if(!q||array)
q=jQuery.data(elem,type+"queue",jQuery.makeArray(array));}
return q;};jQuery.fn.dequeue=function(type){type=type||"fx";return this.each(function(){var q=queue(this,type);q.shift();if(q.length)
q[0].call(this);});};jQuery.extend({speed:function(speed,easing,fn){var opt=speed&&speed.constructor==Object?speed:{complete:fn||!fn&&easing||jQuery.isFunction(speed)&&speed,duration:speed,easing:fn&&easing||easing&&easing.constructor!=Function&&easing};opt.duration=(opt.duration&&opt.duration.constructor==Number?opt.duration:jQuery.fx.speeds[opt.duration])||jQuery.fx.speeds.def;opt.old=opt.complete;opt.complete=function(){if(opt.queue!==false)
jQuery(this).dequeue();if(jQuery.isFunction(opt.old))
opt.old.call(this);};return opt;},easing:{linear:function(p,n,firstNum,diff){return firstNum+diff*p;},swing:function(p,n,firstNum,diff){return((-Math.cos(p*Math.PI)/2)+0.5)*diff+firstNum;}},timers:[],timerId:null,fx:function(elem,options,prop){this.options=options;this.elem=elem;this.prop=prop;if(!options.orig)
options.orig={};}});jQuery.fx.prototype={update:function(){if(this.options.step)
this.options.step.call(this.elem,this.now,this);(jQuery.fx.step[this.prop]||jQuery.fx.step._default)(this);if(this.prop=="height"||this.prop=="width")
this.elem.style.display="block";},cur:function(force){if(this.elem[this.prop]!=null&&this.elem.style[this.prop]==null)
return this.elem[this.prop];var r=parseFloat(jQuery.css(this.elem,this.prop,force));return r&&r>-10000?r:parseFloat(jQuery.curCSS(this.elem,this.prop))||0;},custom:function(from,to,unit){this.startTime=now();this.start=from;this.end=to;this.unit=unit||this.unit||"px";this.now=this.start;this.pos=this.state=0;this.update();var self=this;function t(gotoEnd){return self.step(gotoEnd);}
t.elem=this.elem;jQuery.timers.push(t);if(jQuery.timerId==null){jQuery.timerId=setInterval(function(){var timers=jQuery.timers;for(var i=0;i<timers.length;i++)
if(!timers[i]())
timers.splice(i--,1);if(!timers.length){clearInterval(jQuery.timerId);jQuery.timerId=null;}},13);}},show:function(){this.options.orig[this.prop]=jQuery.attr(this.elem.style,this.prop);this.options.show=true;this.custom(0,this.cur());if(this.prop=="width"||this.prop=="height")
this.elem.style[this.prop]="1px";jQuery(this.elem).show();},hide:function(){this.options.orig[this.prop]=jQuery.attr(this.elem.style,this.prop);this.options.hide=true;this.custom(this.cur(),0);},step:function(gotoEnd){var t=now();if(gotoEnd||t>this.options.duration+this.startTime){this.now=this.end;this.pos=this.state=1;this.update();this.options.curAnim[this.prop]=true;var done=true;for(var i in this.options.curAnim)
if(this.options.curAnim[i]!==true)
done=false;if(done){if(this.options.display!=null){this.elem.style.overflow=this.options.overflow;this.elem.style.display=this.options.display;if(jQuery.css(this.elem,"display")=="none")
this.elem.style.display="block";}
if(this.options.hide)
this.elem.style.display="none";if(this.options.hide||this.options.show)
for(var p in this.options.curAnim)
jQuery.attr(this.elem.style,p,this.options.orig[p]);}
if(done)
this.options.complete.call(this.elem);return false;}else{var n=t-this.startTime;this.state=n/this.options.duration;this.pos=jQuery.easing[this.options.easing||(jQuery.easing.swing?"swing":"linear")](this.state,n,0,1,this.options.duration);this.now=this.start+((this.end-this.start)*this.pos);this.update();}
return true;}};jQuery.extend(jQuery.fx,{speeds:{slow:600,fast:200,def:400},step:{scrollLeft:function(fx){fx.elem.scrollLeft=fx.now;},scrollTop:function(fx){fx.elem.scrollTop=fx.now;},opacity:function(fx){jQuery.attr(fx.elem.style,"opacity",fx.now);},_default:function(fx){fx.elem.style[fx.prop]=fx.now+fx.unit;}}});jQuery.fn.offset=function(){var left=0,top=0,elem=this[0],results;if(elem)with(jQuery.browser){var parent=elem.parentNode,offsetChild=elem,offsetParent=elem.offsetParent,doc=elem.ownerDocument,safari2=safari&&parseInt(version)<522&&!/adobeair/i.test(userAgent),css=jQuery.curCSS,fixed=css(elem,"position")=="fixed";if(elem.getBoundingClientRect){var box=elem.getBoundingClientRect();add(box.left+Math.max(doc.documentElement.scrollLeft,doc.body.scrollLeft),box.top+Math.max(doc.documentElement.scrollTop,doc.body.scrollTop));add(-doc.documentElement.clientLeft,-doc.documentElement.clientTop);}else{add(elem.offsetLeft,elem.offsetTop);while(offsetParent){add(offsetParent.offsetLeft,offsetParent.offsetTop);if(mozilla&&!/^t(able|d|h)$/i.test(offsetParent.tagName)||safari&&!safari2)
border(offsetParent);if(!fixed&&css(offsetParent,"position")=="fixed")
fixed=true;offsetChild=/^body$/i.test(offsetParent.tagName)?offsetChild:offsetParent;offsetParent=offsetParent.offsetParent;}
while(parent&&parent.tagName&&!/^body|html$/i.test(parent.tagName)){if(!/^inline|table.*$/i.test(css(parent,"display")))
add(-parent.scrollLeft,-parent.scrollTop);if(mozilla&&css(parent,"overflow")!="visible")
border(parent);parent=parent.parentNode;}
if((safari2&&(fixed||css(offsetChild,"position")=="absolute"))||(mozilla&&css(offsetChild,"position")!="absolute"))
add(-doc.body.offsetLeft,-doc.body.offsetTop);if(fixed)
add(Math.max(doc.documentElement.scrollLeft,doc.body.scrollLeft),Math.max(doc.documentElement.scrollTop,doc.body.scrollTop));}
results={top:top,left:left};}
function border(elem){add(jQuery.curCSS(elem,"borderLeftWidth",true),jQuery.curCSS(elem,"borderTopWidth",true));}
function add(l,t){left+=parseInt(l,10)||0;top+=parseInt(t,10)||0;}
return results;};jQuery.fn.extend({position:function(){var left=0,top=0,results;if(this[0]){var offsetParent=this.offsetParent(),offset=this.offset(),parentOffset=/^body|html$/i.test(offsetParent[0].tagName)?{top:0,left:0}:offsetParent.offset();offset.top-=num(this,'marginTop');offset.left-=num(this,'marginLeft');parentOffset.top+=num(offsetParent,'borderTopWidth');parentOffset.left+=num(offsetParent,'borderLeftWidth');results={top:offset.top-parentOffset.top,left:offset.left-parentOffset.left};}
return results;},offsetParent:function(){var offsetParent=this[0].offsetParent;while(offsetParent&&(!/^body|html$/i.test(offsetParent.tagName)&&jQuery.css(offsetParent,'position')=='static'))
offsetParent=offsetParent.offsetParent;return jQuery(offsetParent);}});jQuery.each(['Left','Top'],function(i,name){var method='scroll'+name;jQuery.fn[method]=function(val){if(!this[0])return;return val!=undefined?this.each(function(){this==window||this==document?window.scrollTo(!i?val:jQuery(window).scrollLeft(),i?val:jQuery(window).scrollTop()):this[method]=val;}):this[0]==window||this[0]==document?self[i?'pageYOffset':'pageXOffset']||jQuery.boxModel&&document.documentElement[method]||document.body[method]:this[0][method];};});jQuery.each(["Height","Width"],function(i,name){var tl=i?"Left":"Top",br=i?"Right":"Bottom";jQuery.fn["inner"+name]=function(){return this[name.toLowerCase()]()+
num(this,"padding"+tl)+
num(this,"padding"+br);};jQuery.fn["outer"+name]=function(margin){return this["inner"+name]()+
num(this,"border"+tl+"Width")+
num(this,"border"+br+"Width")+
(margin?num(this,"margin"+tl)+num(this,"margin"+br):0);};});})();

View File

@@ -0,0 +1,364 @@
/* transMenu - v0.1.5 (2007-07-07)
* Copyright (c) 2007 Roman Weich
* http://p.sohei.org
*
*/
(function($)
{
var defaults = {
onClick: function(){
$(this).find('>a').each(function(){
if ( this.href )
{
window.location = this.href;
}
});
},
arrow_char: '&#x25BA;',
selected_char: '&#x2713;',
subDelay: 300,
direction: 'down',
mainDelay: 10
};
var transMenuSettings;
$.fn.transMenu = function(options)
{
var shown = false;
var liOffset = 2;
transMenuSettings = $.extend({}, defaults, options);
var hideDIV = function(div, delay) {
//a timer running to show the div?
if ( div.timer && !div.isVisible ) {
clearTimeout(div.timer);
} else if (div.timer) {
return; //hide-timer already running
}
if ( div.isVisible ) {
div.timer = setTimeout( function() {
//remove events
$(div).find('ul li').unbind('mouseover', liHoverIn).unbind('mouseout', liHoverOut).unbind('click', transMenuSettings.onClick);
$(div).hide();
div.isVisible = false;
div.timer = null;
}, delay);
}
};
var showDIV = function(div, delay) {
if ( div.timer ) {
clearTimeout(div.timer);
}
if ( !div.isVisible ) {
div.timer = setTimeout( function() {
//check if the mouse is still over the parent item - if not dont show the submenu
if (! $('div').parent().is('.hover')) {
return;
}
//assign events to all div>ul>li-elements
$(div).find('ul li').mouseover(liHoverIn).mouseout(liHoverOut).click(transMenuSettings.onClick);
//positioning
if (! $(div).parent().is('.main')) {
$(div).css('left', $(div).parent().parent().width() - liOffset);
}
if (transMenuSettings.direction == 'up') {
$(div).css('top', ($(div).height() * -1) + $(div).parent().parent().height());
}
div.isVisible = true; //we use this over :visible to speed up traversing
$(div).show();
div.timer = null;
}, delay);
}
};
//same as hover.handlehover in jquery - just can't use hover() directly - need the ability to unbind only the one hover event
var testHandleHover = function(e) {
// Check if mouse(over|out) are still within the same parent element
var p = (e.type == "mouseover" ? e.fromElement : e.toElement) || e.relatedTarget;
// Traverse up the tree
while ( p && p != this ) {
try {
p = p.parentNode;
} catch(e) {
p = this;
}
}
// If we actually just moused on to a sub-element, ignore it
if ( p == this ) {
return false;
}
return true;
};
var mainHoverIn = function(e) {
$(this).addClass('hover').siblings('li.hover').removeClass('hover');
if ( shown ) {
hoverIn(this, transMenuSettings.mainDelay);
}
};
var liHoverIn = function(e) {
if ( !testHandleHover(e) ) {
return false;
}
if ( e.target != this ) {
//look whether the target is a direct child of this (maybe an image)
if ( !isChild(this, e.target) ) {
return;
}
}
hoverIn(this, transMenuSettings.subDelay);
};
var hoverIn = function(li, delay) {
//stop running timers from the other menus on the same level - a little faster than $('>*>div', li.parentNode)
var n = li.parentNode.firstChild;
for ( ; n; n = n.nextSibling ) {
if ( n.nodeType == 1 && n.nodeName.toUpperCase() == 'LI' ) {
var div = getOneChild(n, 'DIV');
//clear show-div timer
if ( div && div.timer && !div.isVisible ) {
clearTimeout(div.timer);
div.timer = null;
}
}
}
//is there a timer running to hide one of the parent divs? stop it
var pNode = li.parentNode;
for ( ; pNode; pNode = pNode.parentNode ) {
if ( pNode.nodeType == 1 && pNode.nodeName.toUpperCase() == 'DIV' ) {
if (pNode.timer) {
clearTimeout(pNode.timer);
pNode.timer = null;
$(pNode.parentNode).addClass('hover');
}
}
}
//highlight the current element
$(li).addClass('hover');
var innerDiv = $(li).children('div');
innerDiv = innerDiv.length ? innerDiv[0] : null;
//is the submenu already visible?
if ( innerDiv && innerDiv.isVisible ) {
//hide-timer running?
if ( innerDiv.timer ) {
clearTimeout(innerDiv.timer);
innerDiv.timer = null;
} else {
return;
}
}
//hide all open menus on the same level and below and unhighlight the li item (but not the current submenu!)
$(li.parentNode.getElementsByTagName('DIV')).each( function() {
if ( this != innerDiv && this.isVisible ) {
hideDIV(this, delay);
$(this.parentNode).removeClass('hover');
}
});
//show the submenu, if there is one
if ( innerDiv ) {
showDIV(innerDiv, delay);
}
};
var liHoverOut = function(e) {
if ( !testHandleHover(e) ) {
return false;
}
if ( e.target != this ) {
//return only if the target is no direct child of this
if ( !isChild(this, e.target) ) {
return;
}
}
// Remove the hover from the submenu item, if the mouse is hovering out of the
// menu (this is only for the last open (levelwise) (sub-)menu)
var div = getOneChild(this, 'DIV');
if ( !div ) {
$(this).removeClass('hover');
} else {
if ( !div.isVisible ) {
$(this).removeClass('hover');
}
}
};
var mainHoverOut = function(e) {
//no need to test e.target==this, as no child has the same event bound
var div = getOneChild(this, 'DIV');
var relTarget = e.relatedTarget || e.toElement; //this is undefined sometimes (e.g. when the mouse moves out of the window), so dont remove hover then
var p;
if ( !shown ) {
$(this).removeClass('hover');
//menuitem has no submenu, so dont remove the hover if the mouse goes outside the menu
} else if ( !div && relTarget ) {
p = $(e.target).parents('UL.trans_menu');
if ( p.contains(relTarget)) {
$(this).removeClass('hover');
}
} else if ( relTarget ) {
//remove hover only when moving to anywhere inside the trans_menu
p = $(e.target).parents('UL.trans_menu');
if ( !div.isVisible && (p.contains(relTarget)) ) {
$(this).removeClass('hover');
}
}
};
var mainClick = function() {
var div = getOneChild(this, 'DIV');
//clicked on an open main-menu-item
if ( div && div.isVisible ) {
clean();
$(this).addClass('hover');
} else {
hoverIn(this, transMenuSettings.mainDelay);
shown = true;
$('ul.trans_menu li').addClass('active');
$(document).bind('mousedown', checkMouse);
}
};
var checkMouse = function(e) {
//is the mouse inside a trans_menu? if yes, is it an open (the current) one?
var vis = false;
$(e.target).parents('UL.trans_menu').find('div').each( function(){
if ( this.isVisible ) {
vis = true;
}
});
if ( !vis ) {
clean();
}
};
var clean = function() {
//remove timeout and hide the divs
$('ul.trans_menu div.outerbox').each(function(){
if ( this.timer ) {
clearTimeout(this.timer);
this.timer = null;
}
if ( this.isVisible ) {
$(this).hide();
this.isVisible = false;
}
});
$('ul.trans_menu li').removeClass('hover');
//remove events
$('ul.trans_menu>li li').unbind('mouseover', liHoverIn).unbind('mouseout', liHoverOut).unbind('click', transMenuSettings.onClick);
$(document).unbind('mousedown', checkMouse);
shown = false;
$('ul.trans_menu li').removeClass('active');
};
var getOneChild = function(elem, name) {
if ( !elem ) {
return null;
}
var n = elem.firstChild;
for ( ; n; n = n.nextSibling ) {
if ( n.nodeType == 1 && n.nodeName.toUpperCase() == name ) {
return n;
}
}
return null;
};
var isChild = function(elem, childElem) {
var n = elem.firstChild;
for ( ; n; n = n.nextSibling ) {
if ( n == childElem ) {
return true;
}
}
return false;
};
return this.each(function() {
//add .contains() to mozilla - http://www.quirksmode.org/blog/archives/2006/01/contains_for_mo.html
if (window.Node && Node.prototype && !Node.prototype.contains) {
Node.prototype.contains = function(arg) {
return !!(this.compareDocumentPosition(arg) & 16);
};
}
if (! $(this).is('.trans_menu')) {
$(this).addClass('trans_menu');
}
//add shadows
$('ul', this).shadowBox();
//assign events
$(this).bind('closemenu', function(){clean();}); //assign closemenu-event, through wich the menu can be closed from outside the plugin
//add click event handling, if there are any elements inside the main menu
var liElems = $(this).children('li');
for ( var j = 0; j < liElems.length; j++ ) {
if ( getOneChild(getOneChild(getOneChild(liElems[j], 'DIV'), 'UL'), 'LI') ) {
$(liElems[j]).click(mainClick);
}
}
//add hover event handling and assign classes
$(liElems).hover(mainHoverIn, mainHoverOut).addClass('main').find('>div').addClass('inner');
//add the little arrow before each submenu
if ( transMenuSettings.arrow_char ) {
var arrow_markup = $("<span class='arrow'>" + transMenuSettings.arrow_char + '</span>');
// Mozilla float/position hack
if ($.browser.mozilla) {
arrow_markup.css('margin-top', '-13px');
}
$('div.inner div.outerbox', this).before(arrow_markup);
}
//the floating list elements are destroying the layout..so make it nice again..
$(this).wrap('<div class="main_container"></div>').after('<div style="clear: both; visibility: hidden;"></div>');
});
};
$.fn.transMenu.setDefaults = function(o) {
$.extend(defaults, o);
};
$.fn.shadowBox = function() {
return this.each(function() {
var outer = $('<div class="outerbox"></div>').get(0);
if ( $(this).css('position') == 'absolute' ) {
//if the child(this) is positioned abolute, we have to use relative positioning and shrink the outerbox accordingly to the innerbox
$(outer).css({position:'relative', width:this.offsetWidth, height:this.offsetHeight});
} else {
//shrink the outerbox
$(outer).css('position', 'absolute');
}
//add the boxes
$(this).addClass('innerBox').wrap(outer).
before('<div class="shadowbox1"></div><div class="shadowbox2"></div><div class="shadowbox3"></div>');
});
};
$.fn.selectMenuItem = function() {
if (this.find('span.selected').length == 0) {
this.prepend($("<span class='selected'>" + transMenuSettings.selected_char + "</span>"));
}
return this;
};
$.fn.deselectMenuItem = function() {
return this.find('span.selected').remove();
};
$.fn.menuItemIsSelected = function() {
return (this.find('span.selected').length > 0);
};
$.fn.deselectMenuSiblings = function() {
this.parent().find('span.selected').remove();
this.selectMenuItem();
return this;
};
})(jQuery);

View File

@@ -0,0 +1,30 @@
(function($)
{var defaults={onClick:function(){$(this).find('>a').each(function(){if(this.href)
{window.location=this.href;}});},arrow_char:'&#x25BA;',selected_char:'&#x2713;',subDelay:300,direction:'down',mainDelay:10};var transMenuSettings;$.fn.transMenu=function(options)
{var shown=false;var liOffset=2;transMenuSettings=$.extend({},defaults,options);var hideDIV=function(div,delay){if(div.timer&&!div.isVisible){clearTimeout(div.timer);}else if(div.timer){return;}
if(div.isVisible){div.timer=setTimeout(function(){$(div).find('ul li').unbind('mouseover',liHoverIn).unbind('mouseout',liHoverOut).unbind('click',transMenuSettings.onClick);$(div).hide();div.isVisible=false;div.timer=null;},delay);}};var showDIV=function(div,delay){if(div.timer){clearTimeout(div.timer);}
if(!div.isVisible){div.timer=setTimeout(function(){if(!$('div').parent().is('.hover')){return;}
$(div).find('ul li').mouseover(liHoverIn).mouseout(liHoverOut).click(transMenuSettings.onClick);if(!$(div).parent().is('.main')){$(div).css('left',$(div).parent().parent().width()-liOffset);}
if(transMenuSettings.direction=='up'){$(div).css('top',($(div).height()*-1)+$(div).parent().parent().height());}
div.isVisible=true;$(div).show();div.timer=null;},delay);}};var testHandleHover=function(e){var p=(e.type=="mouseover"?e.fromElement:e.toElement)||e.relatedTarget;while(p&&p!=this){try{p=p.parentNode;}catch(e){p=this;}}
if(p==this){return false;}
return true;};var mainHoverIn=function(e){$(this).addClass('hover').siblings('li.hover').removeClass('hover');if(shown){hoverIn(this,transMenuSettings.mainDelay);}};var liHoverIn=function(e){if(!testHandleHover(e)){return false;}
if(e.target!=this){if(!isChild(this,e.target)){return;}}
hoverIn(this,transMenuSettings.subDelay);};var hoverIn=function(li,delay){var n=li.parentNode.firstChild;for(;n;n=n.nextSibling){if(n.nodeType==1&&n.nodeName.toUpperCase()=='LI'){var div=getOneChild(n,'DIV');if(div&&div.timer&&!div.isVisible){clearTimeout(div.timer);div.timer=null;}}}
var pNode=li.parentNode;for(;pNode;pNode=pNode.parentNode){if(pNode.nodeType==1&&pNode.nodeName.toUpperCase()=='DIV'){if(pNode.timer){clearTimeout(pNode.timer);pNode.timer=null;$(pNode.parentNode).addClass('hover');}}}
$(li).addClass('hover');var innerDiv=$(li).children('div');innerDiv=innerDiv.length?innerDiv[0]:null;if(innerDiv&&innerDiv.isVisible){if(innerDiv.timer){clearTimeout(innerDiv.timer);innerDiv.timer=null;}else{return;}}
$(li.parentNode.getElementsByTagName('DIV')).each(function(){if(this!=innerDiv&&this.isVisible){hideDIV(this,delay);$(this.parentNode).removeClass('hover');}});if(innerDiv){showDIV(innerDiv,delay);}};var liHoverOut=function(e){if(!testHandleHover(e)){return false;}
if(e.target!=this){if(!isChild(this,e.target)){return;}}
var div=getOneChild(this,'DIV');if(!div){$(this).removeClass('hover');}else{if(!div.isVisible){$(this).removeClass('hover');}}};var mainHoverOut=function(e){var div=getOneChild(this,'DIV');var relTarget=e.relatedTarget||e.toElement;var p;if(!shown){$(this).removeClass('hover');}else if(!div&&relTarget){p=$(e.target).parents('UL.trans_menu');if(p.contains(relTarget)){$(this).removeClass('hover');}}else if(relTarget){p=$(e.target).parents('UL.trans_menu');if(!div.isVisible&&(p.contains(relTarget))){$(this).removeClass('hover');}}};var mainClick=function(){var div=getOneChild(this,'DIV');if(div&&div.isVisible){clean();$(this).addClass('hover');}else{hoverIn(this,transMenuSettings.mainDelay);shown=true;$('ul.trans_menu li').addClass('active');$(document).bind('mousedown',checkMouse);}};var checkMouse=function(e){var vis=false;$(e.target).parents('UL.trans_menu').find('div').each(function(){if(this.isVisible){vis=true;}});if(!vis){clean();}};var clean=function(){$('ul.trans_menu div.outerbox').each(function(){if(this.timer){clearTimeout(this.timer);this.timer=null;}
if(this.isVisible){$(this).hide();this.isVisible=false;}});$('ul.trans_menu li').removeClass('hover');$('ul.trans_menu>li li').unbind('mouseover',liHoverIn).unbind('mouseout',liHoverOut).unbind('click',transMenuSettings.onClick);$(document).unbind('mousedown',checkMouse);shown=false;$('ul.trans_menu li').removeClass('active');};var getOneChild=function(elem,name){if(!elem){return null;}
var n=elem.firstChild;for(;n;n=n.nextSibling){if(n.nodeType==1&&n.nodeName.toUpperCase()==name){return n;}}
return null;};var isChild=function(elem,childElem){var n=elem.firstChild;for(;n;n=n.nextSibling){if(n==childElem){return true;}}
return false;};return this.each(function(){if(window.Node&&Node.prototype&&!Node.prototype.contains){Node.prototype.contains=function(arg){return!!(this.compareDocumentPosition(arg)&16);};}
if(!$(this).is('.trans_menu')){$(this).addClass('trans_menu');}
$('ul',this).shadowBox();$(this).bind('closemenu',function(){clean();});var liElems=$(this).children('li');for(var j=0;j<liElems.length;j++){if(getOneChild(getOneChild(getOneChild(liElems[j],'DIV'),'UL'),'LI')){$(liElems[j]).click(mainClick);}}
$(liElems).hover(mainHoverIn,mainHoverOut).addClass('main').find('>div').addClass('inner');if(transMenuSettings.arrow_char){var arrow_markup=$("<span class='arrow'>"+transMenuSettings.arrow_char+'</span>');if($.browser.mozilla){arrow_markup.css('margin-top','-13px');}
$('div.inner div.outerbox',this).before(arrow_markup);}
$(this).wrap('<div class="main_container"></div>').after('<div style="clear: both; visibility: hidden;"></div>');});};$.fn.transMenu.setDefaults=function(o){$.extend(defaults,o);};$.fn.shadowBox=function(){return this.each(function(){var outer=$('<div class="outerbox"></div>').get(0);if($(this).css('position')=='absolute'){$(outer).css({position:'relative',width:this.offsetWidth,height:this.offsetHeight});}else{$(outer).css('position','absolute');}
$(this).addClass('innerBox').wrap(outer).before('<div class="shadowbox1"></div><div class="shadowbox2"></div><div class="shadowbox3"></div>');});};$.fn.selectMenuItem=function(){if(this.find('span.selected').length==0){this.prepend($("<span class='selected'>"+transMenuSettings.selected_char+"</span>"));}
return this;};$.fn.deselectMenuItem=function(){return this.find('span.selected').remove();};$.fn.menuItemIsSelected=function(){return(this.find('span.selected').length>0);};$.fn.deselectMenuSiblings=function(){this.parent().find('span.selected').remove();this.selectMenuItem();return this;};})(jQuery);

96
web/javascript/jquery/json.js vendored Normal file
View File

@@ -0,0 +1,96 @@
(function ($) {
var m = {
'\b': '\\b',
'\t': '\\t',
'\n': '\\n',
'\f': '\\f',
'\r': '\\r',
'"' : '\\"',
'\\': '\\\\'
},
s = {
'array': function (x) {
var a = ['['], b, f, i, l = x.length, v;
for (i = 0; i < l; i += 1) {
v = x[i];
f = s[typeof v];
if (f) {
v = f(v);
if (typeof v == 'string') {
if (b) {
a[a.length] = ',';
}
a[a.length] = v;
b = true;
}
}
}
a[a.length] = ']';
return a.join('');
},
'boolean': function (x) {
return String(x);
},
'null': function (x) {
return "null";
},
'number': function (x) {
return isFinite(x) ? String(x) : 'null';
},
'object': function (x) {
if (x) {
if (x instanceof Array) {
return s.array(x);
}
var a = ['{'], b, f, i, v;
for (i in x) {
v = x[i];
f = s[typeof v];
if (f) {
v = f(v);
if (typeof v == 'string') {
if (b) {
a[a.length] = ',';
}
a.push(s.string(i), ':', v);
b = true;
}
}
}
a[a.length] = '}';
return a.join('');
}
return 'null';
},
'string': function (x) {
if (/["\\\x00-\x1f]/.test(x)) {
x = x.replace(/([\x00-\x1f\\"])/g, function(a, b) {
var c = m[b];
if (c) {
return c;
}
c = b.charCodeAt();
return '\\u00' +
Math.floor(c / 16).toString(16) +
(c % 16).toString(16);
});
}
return '"' + x + '"';
}
};
$.toJSON = function(v) {
var f = isNaN(v) ? s[typeof v] : s['number'];
if (f) return f(v);
};
$.parseJSON = function(v, safe) {
if (safe === undefined) safe = $.parseJSON.safe;
if (safe && !/^("(\\.|[^"\\\n\r])*?"|[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t])+?$/.test(v))
return undefined;
return eval('('+v+')');
};
$.parseJSON.safe = false;
})(jQuery);

13
web/javascript/jquery/json.min.js vendored Normal file
View File

@@ -0,0 +1,13 @@
(function($){var m={'\b':'\\b','\t':'\\t','\n':'\\n','\f':'\\f','\r':'\\r','"':'\\"','\\':'\\\\'},s={'array':function(x){var a=['['],b,f,i,l=x.length,v;for(i=0;i<l;i+=1){v=x[i];f=s[typeof v];if(f){v=f(v);if(typeof v=='string'){if(b){a[a.length]=',';}
a[a.length]=v;b=true;}}}
a[a.length]=']';return a.join('');},'boolean':function(x){return String(x);},'null':function(x){return"null";},'number':function(x){return isFinite(x)?String(x):'null';},'object':function(x){if(x){if(x instanceof Array){return s.array(x);}
var a=['{'],b,f,i,v;for(i in x){v=x[i];f=s[typeof v];if(f){v=f(v);if(typeof v=='string'){if(b){a[a.length]=',';}
a.push(s.string(i),':',v);b=true;}}}
a[a.length]='}';return a.join('');}
return'null';},'string':function(x){if(/["\\\x00-\x1f]/.test(x)){x=x.replace(/([\x00-\x1f\\"])/g,function(a,b){var c=m[b];if(c){return c;}
c=b.charCodeAt();return'\\u00'+
Math.floor(c/16).toString(16)+
(c%16).toString(16);});}
return'"'+x+'"';}};$.toJSON=function(v){var f=isNaN(v)?s[typeof v]:s['number'];if(f)return f(v);};$.parseJSON=function(v,safe){if(safe===undefined)safe=$.parseJSON.safe;if(safe&&!/^("(\\.|[^"\\\n\r])*?"|[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t])+?$/.test(v))
return undefined;return eval('('+v+')');};$.parseJSON.safe=false;})(jQuery);

45
web/javascript/menu.js Normal file
View File

@@ -0,0 +1,45 @@
/*
* Copyright © Dave Perrett and Malcolm Jarvis
* This code is licensed under the GPL version 2.
* For more details, see http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
* Menu Configuration Properties
*/
Menu = {
context: {
menu_style: {
width: '210px',
backgroundColor: '#fff',
border: 'none',
padding: '5px 0',
textAlign: 'left'},
item_style: {
backgroundColor: 'transparent',
margin: '0',
padding: '0 10px 2px 20px',
color: '#000',
fontSize: '14px',
cursor: 'default',
border: 'none'},
item_hover_style: {
backgroundColor: '#24e',
color: '#fff',
border: 'none'},
item_disabled_style: {
backgroundColor: 'transparent',
margin: '0',
padding: '0 10px 2px 20px',
color: '#aaa',
fontSize: '1.5em',
cursor: 'default',
border: 'none'}
}
}

579
web/javascript/torrent.js Normal file
View File

@@ -0,0 +1,579 @@
/*
* Copyright © Dave Perrett and Malcolm Jarvis
* This code is licensed under the GPL version 2.
* For details, see http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
* Class Torrent
*/
function Torrent(controller,data) {
this.initialize(controller,data);
}
// Constants
Torrent._StatusWaitingToCheck = 1;
Torrent._StatusChecking = 2;
Torrent._StatusDownloading = 4;
Torrent._StatusSeeding = 8;
Torrent._StatusPaused = 16;
Torrent._InfiniteTimeRemaining = 215784000; // 999 Hours - may as well be infinite
Torrent._MaxProgressBarWidth = 100; // reduce this to make the progress bar shorter (%)
Torrent.prototype =
{
/*
* Constructor
*/
initialize: function(controller,data)
{
// Create a new <li> element
var element = $('<li/>');
element.addClass('torrent');
element[0].id = 'torrent_' + data.id;
element._torrent = this;
this._element = element;
this._controller = controller;
controller._rows.push( element );
// Create the 'name' <div>
var e = $('<div/>');
e.addClass('torrent_name');
element.append( e );
element._name_container = e;
// Create the 'progress details' <div>
e = $('<div/>');
e.addClass('torrent_progress_details');
element.append(e);
element._progress_details_container = e;
// Create the 'in progress' bar
e = $('<div/>');
e.addClass('torrent_progress_bar incomplete');
e.css('width', '0%');
element.append( e );
element._progress_complete_container = e;
// Create the 'incomplete' bar (initially hidden)
e = $('<div/>');
e.addClass('torrent_progress_bar incomplete');
e.hide();
element.append( e );
element._progress_incomplete_container = e;
// Add the pause/resume button - don't specify the
// image or alt text until the 'refresh()' function
// (depends on torrent state)
var image = $('<div/>');
image.addClass('torrent_pause');
e = $('<a/>');
e.append( image );
element.append( e );
element._pause_resume_button_image = image;
element._pause_resume_button = e;
if (!iPhone) e.bind('click', {element: element}, this.clickPauseResumeButton);
// Create the 'peer details' <div>
e = $('<div/>');
e.addClass('torrent_peer_details');
element.append( e );
element._peer_details_container = e;
// Set the torrent click observer
element.bind('click', {element: element}, this.clickTorrent);
if (!iPhone) element.bind('contextmenu', {element: element}, this.rightClickTorrent);
// Safari hack - first torrent needs to be moved down for some reason. Seems to be ok when
// using <li>'s in straight html, but adding through the DOM gets a bit odd.
if ($.browser.safari)
this._element.css('margin-top', '7px');
// insert the element
$('#torrent_list').append(this._element);
// Update all the labels etc
this.refresh(data);
},
/*--------------------------------------------
*
* S E T T E R S / G E T T E R S
*
*--------------------------------------------*/
/* Return the DOM element for this torrent (a <LI> element) */
element: function() {
return this._element;
},
setElement: function( element ) {
this._element = element;
element._torrent = this;
this.refreshHTML( );
},
activity: function() { return this._download_speed + this._upload_speed; },
comment: function() { return this._comment; },
completed: function() { return this._completed; },
creator: function() { return this._creator; },
dateAdded: function() { return this._date; },
downloadSpeed: function() { return this._download_speed; },
downloadTotal: function() { return this._download_total; },
errorMessage: function() { return this._error_message; },
hash: function() { return this._hashString; },
id: function() { return this._id; },
isActive: function() { return this.state() != Torrent._StatusPaused; },
isDownloading: function() { return this.state() == Torrent._StatusDownloading; },
isSeeding: function() { return this.state() == Torrent._StatusSeeding; },
name: function() { return this._name; },
peersDownloading: function() { return this._peers_downloading; },
peersUploading: function() { return this._peers_uploading; },
size: function() { return this._size; },
state: function() { return this._state; },
stateStr: function() {
switch( this.state() ) {
case Torrent._StatusSeeding: return 'Seeding';
case Torrent._StatusDownloading: return 'Downloading';
case Torrent._StatusPaused: return 'Paused';
case Torrent._StatusChecking: return 'Verifying local data';
case Torrent._StatusWaitingToCheck: return 'Waiting to verify';
default: return 'error';
}
},
swarmSpeed: function() { return this._swarm_speed; },
totalLeechers: function() { return this._total_leechers; },
totalSeeders: function() { return this._total_seeders; },
uploadSpeed: function() { return this._upload_speed; },
uploadTotal: function() { return this._upload_total; },
/*--------------------------------------------
*
* E V E N T F U N C T I O N S
*
*--------------------------------------------*/
/*
* Process a right-click event on this torrent
*/
rightClickTorrent: function(event)
{
// don't stop the event! need it for the right-click menu
var t = event.data.element._torrent;
if ( !t.isSelected( ) )
t._controller.setSelectedTorrent( t );
},
/*
* Process a click event on this torrent
*/
clickTorrent: function( event )
{
// Prevents click carrying to parent element
// which deselects all on click
event.stopPropagation();
var torrent = event.data.element._torrent;
// 'Apple' button emulation on PC :
// Need settable meta-key and ctrl-key variables for mac emulation
var meta_key = event.metaKey
var ctrl_key = event.ctrlKey
if (event.ctrlKey && navigator.appVersion.toLowerCase().indexOf("mac") == -1) {
meta_key = true;
ctrl_key = false;
}
// Shift-Click - Highlight a range between this torrent and the last-clicked torrent
if (iPhone) {
torrent._controller.setSelectedTorrent( torrent, true );
} else if (event.shiftKey) {
torrent._controller.selectRange( torrent, true );
// Need to deselect any selected text
window.focus();
// Apple-Click, not selected
} else if (!torrent.isSelected() && meta_key) {
torrent._controller.selectTorrent( torrent, true );
// Regular Click, not selected
} else if (!torrent.isSelected()) {
torrent._controller.setSelectedTorrent( torrent, true );
// Apple-Click, selected
} else if (torrent.isSelected() && meta_key) {
torrent._controller.deselectTorrent( torrent, true );
// Regular Click, selected
} else if (torrent.isSelected()) {
torrent._controller.setSelectedTorrent( torrent, true );
}
torrent._controller.setLastTorrentClicked(torrent);
},
/*
* Process a click event on the pause/resume button
*/
clickPauseResumeButton: function( event )
{
// prevent click event resulting in selection of torrent
event.stopPropagation();
// either stop or start the torrent
var torrent = event.data.element._torrent;
if( torrent.isActive( ) )
torrent._controller.stopTorrent( torrent );
else
torrent._controller.startTorrent( torrent );
},
/*--------------------------------------------
*
* I N T E R F A C E F U N C T I O N S
*
*--------------------------------------------*/
refresh: function(data) {
this.refreshData( data );
this.refreshHTML( );
},
/*
* Refresh display
*/
refreshData: function(data)
{
// These variables never change after the inital load
if (data.isPrivate) this._is_private = data.isPrivate;
if (data.hashString) this._hashString = data.hashString;
if (data.addedDate) this._date = data.addedDate;
if (data.totalSize) this._size = data.totalSize;
if (data.announceURL) this._tracker = data.announceURL;
if (data.comment) this._comment = data.comment;
if (data.creator) this._creator = data.creator;
if (data.dateCreated) this._creator_date = data.dateCreated;
if (data.path) this._torrent_file = data.path;//FIXME
if (data.name) {
this._name = data.name;
this._name_lc = this._name.toLowerCase( );
}
// Set the regularly-changing torrent variables
this._id = data.id;
this._completed = data.haveUnchecked + data.haveValid;
this._verified = data.haveValid;
this._download_total = data.downloadedEver;
this._upload_total = data.uploadedEver;
this._download_speed = data.rateDownload;
this._upload_speed = data.rateUpload;
this._peers_downloading = data.peersGettingFromUs;
this._peers_uploading = data.peersSendingToUs;
this._peers_total = data.peersKnown;
this._error = data.error;
this._error_message = data.errorString;
this._eta = data.eta;
this._swarm_speed = data.swarmSpeed;
this._total_leechers = data.leechers;
this._total_seeders = data.seeders;
this._state = data.status;
// Get -1 returned sometimes (maybe torrents with errors?)
if( this._total_leechers < 0 )
this._total_leechers = 0;
if( this._total_seeders < 0 )
this._total_seeders = 0;
},
refreshHTML: function()
{
var progress_details;
var peer_details;
var root = this._element;
setInnerHTML( root._name_container[0], this._name );
// Figure out the percent completed
var percent = Math.min( 1.0, ( this._completed / this._size ) );
var css_completed_width = Math.floor( percent * Torrent._MaxProgressBarWidth );
// Add the progress bar
var notDone = this._completed < this._size;
if( notDone )
{
var eta = '';
if( this.isActive( ) )
{
eta = '-';
if (this._eta < 0 || this._eta >= Torrent._InfiniteTimeRemaining )
eta += 'remaining time unknown';
else
eta += Math.formatSeconds(this._eta) + ' remaining';
}
// Create the 'progress details' label
// Eg: '101 MB of 631 MB (16.02%) - 2 hr remaining'
progress_details = Math.formatBytes( this._completed )
+ ' of '
+ Math.formatBytes( this._size )
+ ' ('
+ Math.ratio( this._completed, this._size )
+ '%)'
+ eta;
// Update the 'in progress' bar
var class_name = (this.isActive()) ? 'in_progress' : 'incomplete_stopped';
var e = root._progress_complete_container;
e.removeClass();
e.addClass('torrent_progress_bar');
e.addClass(class_name);
e.css('width', css_completed_width + '%');
// Update the 'incomplete' bar
e = root._progress_incomplete_container;
if( !e.is('.incomplete')) {
e.removeClass();
e.addClass('torrent_progress_bar in_progress');
}
e.css('width', (Torrent._MaxProgressBarWidth - css_completed_width) + '%');
e.show();
// Create the 'peer details' label
// Eg: 'Downloading from 36 of 40 peers - DL: 60.2 KB/s UL: 4.3 KB/s'
if( !this.isDownloading( ) )
peer_details = this.stateStr( );
else {
peer_details = 'Downloading from '
+ this._peers_downloading
+ ' of '
+ this._peers_total
+ ' peers - DL: '
+ Math.formatBytes(this._download_speed)
+ '/s UL: '
+ Math.formatBytes(this._upload_speed)
+ '/s';
}
}
else
{
// Update the 'in progress' bar
var class_name = (this.isActive()) ? 'complete' : 'complete_stopped';
var e = root._progress_complete_container;
e.removeClass();
e.addClass('torrent_progress_bar ' + class_name );
// Create the 'progress details' label
// Eg: '698.05 MB, uploaded 8.59 GB (Ratio: 12.3)'
progress_details = Math.formatBytes( this._size )
+ ', uploaded ';
+ Math.formatBytes( this._upload_total )
+ ' (Ratio '
+ Math.ratio( this._upload_total, this._download_total )
+ ')';
// Hide the 'incomplete' bar
root._progress_incomplete_container.hide();
// Set progress to maximum
root._progress_complete_container.css('width', Torrent._MaxProgressBarWidth + '%');
// Create the 'peer details' label
// Eg: 'Seeding to 13 of 22 peers - UL: 36.2 KB/s'
if( !this.isSeeding( ) )
peer_details = this.stateStr( );
else
peer_details = 'Seeding to '
+ this._peers_uploading
+ ' of '
+ this._peers_total
+ ' peers - UL: '
+ Math.formatBytes(this._upload_speed)
+ '/s';
}
// Update the progress details
setInnerHTML( root._progress_details_container[0], progress_details );
// Update the peer details and pause/resume button
e = root._pause_resume_button_image[0];
if ( this.state() == Torrent._StatusPaused ) {
e.alt = 'Resume';
e.className = "torrent_resume";
} else {
e.alt = 'Pause';
e.className = "torrent_pause";
}
if( this._error_message &&
this._error_message != '' &&
this._error_message != 'other' ) {
peer_details = this._error_message;
}
setInnerHTML( root._peer_details_container[0], peer_details );
},
/*
* Return true if this torrent is selected
*/
isSelected: function() {
var e = this.element( );
return e && $.className.has( e[0], 'selected' );
},
/**
* @param filter one of Prefs._Filter*
* @param search substring to look for, or null
* @return true if it passes the test, false if it fails
*/
test: function( filter, search )
{
var pass = false;
switch( filter )
{
case Prefs._FilterSeeding:
pass = this.isSeeding();
break;
case Prefs._FilterDownloading:
pass = this.isDownloading();
break;
case Prefs._FilterPaused:
pass = !this.isActive();
break;
default:
pass = true;
break;
}
if( !pass )
return false;
if( !search || !search.length )
return pass;
var pos = this._name_lc.indexOf( search.toLowerCase() );
pass = pos != -1;
return pass;
}
};
/** Helper function for Torrent.sortTorrents(). */
Torrent.compareById = function( a, b ) {
return a.id() - b.id();
};
/** Helper function for sortTorrents(). */
Torrent.compareByAge = function( a, b ) {
return a.dateAdded() - b.dateAdded();
};
/** Helper function for sortTorrents(). */
Torrent.compareByName = function( a, b ) {
return a._name_lc.compareTo( b._name_lc );
};
/** Helper function for sortTorrents(). */
Torrent.compareByTracker = function( a, b ) {
return a._tracker.compareTo( b._tracker );
};
/** Helper function for sortTorrents(). */
Torrent.compareByState = function( a, b ) {
return a.state() - b.state();
};
/** Helper function for sortTorrents(). */
Torrent.compareByActivity = function( a, b ) {
return a.activity() - b.activity();
};
/** Helper function for sortTorrents(). */
Torrent.compareByProgress = function( a, b ) {
var a_prog = Math.ratio( a._completed, a._size );
var b_prog = Math.ratio( b._completed, b._size );
if( a_prog !== b_prog )
return a_prog - b_prog;
var a_ratio = Math.ratio( a._upload_total, a._download_total );
var b_ratio = Math.ratio( b._upload_total, b._download_total );
return a_ratio - b_ratio;
}
/**
* @param torrents an array of Torrent objects
* @param sortMethod one of Prefs._SortBy*
* @param sortDirection Prefs._SortAscending or Prefs._SortDescending
*/
Torrent.sortTorrents = function( torrents, sortMethod, sortDirection )
{
switch( sortMethod )
{
case Prefs._SortByActivity:
torrents.sort( this.compareByActivity );
break;
case Prefs._SortByAge:
torrents.sort( this.compareByAge );
break;
case Prefs._SortByQueue:
torrents.sort( this.compareById );
break;
case Prefs._SortByProgress:
torrents.sort( this.compareByProgress );
break;
case Prefs._SortByState:
torrents.sort( this.compareByState );
break;
case Prefs._SortByTracker:
torrents.sort( this.compareByTracker );
break;
case Prefs._SortByName:
torrents.sort( this.compareByName );
break;
default:
console.warn( "unknown sort method: " + sortMethod );
break;
}
if( sortDirection == Prefs._SortDescending )
torrents.reverse( );
return torrents;
};
/**
* @brief fast binary search to find a torrent
* @param torrents an array of torrents sorted by Id
* @param id the id to search for
* @return the index, or -1
*/
Torrent.indexOf = function( torrents, id )
{
var low = 0;
var high = torrents.length;
while( low < high ) {
var mid = Math.floor( ( low + high ) / 2 );
if( torrents[mid].id() < id )
low = mid + 1;
else
high = mid;
}
if( ( low < torrents.length ) && ( torrents[low].id() == id ) ) {
return low;
} else {
return -1; // not found
}
};
/**
* @param torrents an array of torrents sorted by Id
* @param id the id to search for
* @return the torrent, or null
*/
Torrent.lookup = function( torrents, id )
{
var pos = Torrent.indexOf( torrents, id );
return pos >= 0 ? torrents[pos] : null;
};

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,135 @@
/*
* Copyright © Dave Perrett and Malcolm Jarvis
* This code is licensed under the GPL version 2.
* For details, see http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
* Class TransmissionRemote
*/
function RPC() { }
//Prefs.prototype = { }
// Constants
RPC._Root = '/transmission/rpc';
RPC._Encryption = 'encryption';
RPC._EncryptionPreferred = 'preferred';
RPC._EncryptionRequired = 'required';
RPC._UpSpeedLimit = 'speed-limit-up';
RPC._DownSpeedLimit = 'speed-limit-down';
RPC._DownloadDir = 'download-dir';
RPC._PeerPort = 'port';
RPC._UpSpeedLimited = 'speed-limit-up-enabled';
RPC._DownSpeedLimited = 'speed-limit-down-enabled';
function TransmissionRemote( controller )
{
this.initialize( controller );
return this;
}
TransmissionRemote.prototype =
{
/*
* Constructor
*/
initialize: function(controller) {
this._controller = controller;
this._error = '';
},
/*
* Display an error if an ajax request fails, and stop sending requests
*/
ajaxError: function(request, error_string, exception) {
this._error = request.responseText
? request.responseText.trim().replace(/(<([^>]+)>)/ig,"")
: "";
if( !this._error.length )
this._error = 'Server not responding';
dialog.confirm('Connection Failed',
'Could not connect to the server. You may need to reload the page to reconnect.',
'Details',
'alert(transmission.remote._error);',
null,
'Dismiss');
transmission.togglePeriodicRefresh(false);
},
sendRequest: function( url, data, success, contentType )
{
var o = { };
o.cache = false;
o.contentType = contentType;
o.data = data;
o.dataType = 'json';
o.error = this.ajaxError;
o.success = success;
o.type = 'POST';
o.url = url;
$.ajax( o );
},
loadDaemonPrefs: function() {
var tr = this._controller;
var o = { };
o.method = 'session-get';
this.sendRequest( RPC._Root, $.toJSON(o), function(data) {
var o = data.arguments.session;
Prefs.getClutchPrefs( o );
tr.updatePrefs( o );
}, "json" );
},
loadTorrents: function() {
var tr = this._controller;
var o = { };
o.method = 'torrent-get'
o.arguments = { };
o.arguments.fields = 1+2+4+16+32+64+128+1024+2048+4096;
this.sendRequest( RPC._Root, $.toJSON(o), function(data) {
tr.updateTorrents( data.arguments.torrents );
}, "json" );
},
sendTorrentCommand: function( method, torrents ) {
var remote = this;
var o = { };
o.method = method;
o.arguments = { };
o.arguments.ids = [ ];
if( torrents != null )
for( var i=0, len=torrents.length; i<len; ++i )
o.arguments.ids.push( torrents[i].id() );
this.sendRequest( RPC._Root, $.toJSON(o), function( ) {
remote.loadTorrents();
}, "json" );
},
startTorrents: function( torrents ) {
this.sendTorrentCommand( 'torrent-start', torrents );
},
stopTorrents: function( torrents ) {
this.sendTorrentCommand( 'torrent-stop', torrents );
},
removeTorrents: function( torrents ) {
this.sendTorrentCommand( 'torrent-remove', torrents );
},
savePrefs: function( args ) {
var remote = this;
var o = { };
o.method = 'session-set';
o.arguments = args;
this.sendRequest( RPC._Root, $.toJSON(o), function(){
remote.loadDaemonPrefs();
}, "json" );
},
/*
* Upload Torrent by URL
addTorrentByURL: function() {
$('#torrent_upload_form')[0].action = 'remote/index.php?action=addTorrentByURL&param=[]';
$('#torrent_upload_form').ajaxSubmit({dataType: 'script', type: 'POST'});
},
*/
};