diff --git a/Chapter01/01_web.js b/Chapter01/01_web.js new file mode 100644 index 0000000..872e76e --- /dev/null +++ b/Chapter01/01_web.js @@ -0,0 +1,14 @@ +var http = require("http"); + +function process_request(req, res) { + var body = 'Thanks for calling!\n'; + var content_length = body.length; + res.writeHead(200, { + 'Content-Length': content_length, + 'Content-Type': 'text/plain' + }); + res.end(body); +} + +var s = http.createServer(process_request); +s.listen(8080); diff --git a/Chapter01/02_debug.js b/Chapter01/02_debug.js new file mode 100644 index 0000000..90b3bc6 --- /dev/null +++ b/Chapter01/02_debug.js @@ -0,0 +1,18 @@ + +var http = require("http"); + +var s = http.createServer(function (req, res) { + var body = 'Thanks for calling!\n'; + var content_length = body.lengtth; + res.writeHead(200, { + 'Content-Length': content_length, + 'Content-Type': 'text/plain' + }); + res.end(body); +}); + +/** + * Now run the server, listening on port 8080 + */ +s.listen(8080); + diff --git a/Chapter01/debugging.js b/Chapter01/debugging.js new file mode 100644 index 0000000..9a00864 --- /dev/null +++ b/Chapter01/debugging.js @@ -0,0 +1,14 @@ +var http = require("http"); + +function process_request(req, res) { + var body = 'Thanks for calling!\n'; + var content_length = body.lenggth; + res.writeHead(200, { + 'Content-Length': content_length, + 'Content-Type': 'text/plain' + }); + res.end(body); +} + +var s = http.createServer(process_request); +s.listen(8080); diff --git a/Chapter02/arguments.js b/Chapter02/arguments.js new file mode 100644 index 0000000..9ec00ff --- /dev/null +++ b/Chapter02/arguments.js @@ -0,0 +1,76 @@ + + + + + +function Shape () { +} + +Shape.prototype.X = 0; +Shape.prototype.Y = 0; + +Shape.prototype.move = function (x, y) { + this.X = x; + this.Y = y; +} +Shape.prototype.distance_from_origin = function () { + return Math.sqrt(this.X*this.X + this.Y*this.Y); +} +Shape.prototype.area = function () { + throw new Error("I'm not a real shape yet"); +} + +var s = new Shape(); +s.move(10, 10); +console.log(s.distance_from_origin()); + + +function Square() { +} + +Square.prototype = new Shape(); +Square.prototype.__proto__ = Shape.prototype; +Square.prototype.Width = 0; + +Square.prototype.area = function () { + return this.Width * this.Width; +} + +var sq = new Square(); +sq.move(-5, -5); +sq.Width = 5; +console.log(sq.area()); +console.log(sq.distance_from_origin()); + + +function Rectangle () { +} + +Rectangle.prototype = new Square(); +Rectangle.prototype.__proto__ = Square.prototype; +Rectangle.prototype.Height = 0; + +Rectangle.prototype.area = function () { + return this.Width * this.Height; +} + + +var re = new Rectangle(); +re.move(25, 25); +re.Width = 10; +re.Height = 5; +console.log(re.area()); +console.log(re.distance_from_origin()); + + +console.log(typeof s); +console.log(typeof sq); +console.log(typeof re); + +console.log(sq instanceof Square); +console.log(sq instanceof Shape); +console.log(sq instanceof Rectangle); +console.log(re instanceof Rectangle); +console.log(sq instanceof Square); +console.log(sq instanceof Shape); +console.log(sq instanceof Date); diff --git a/Chapter02/arrays.js b/Chapter02/arrays.js new file mode 100644 index 0000000..149fd55 --- /dev/null +++ b/Chapter02/arrays.js @@ -0,0 +1,100 @@ + +var car1 = []; +var car2 = new Array(); +var car3 = new Array(10); +var car4 = new Array(4, 34, 6, 8, 525, 8693, 281, 88, 28, 95, 346); + + +// creating +var arr1 = []; +// set values + +for (var i = 0; i < 10; i++) { + arr1[i] = i; +} + +// fills in undefined +arr1.length = 20; +arr1[20] = "new value"; + +console.log(arr1.length); +console.log(arr1[0]); +console.log(arr1); + + +// set values with string index +var arr2 = []; + +arr2["cat"] = "meow"; +arr2["dog"] = "woof"; + +console.log(arr2.length); +console.log(arr2[0]); +console.log(arr2); + + + +// mixed indexes (bad idea) +var arr3 = []; + +arr3[2] = 2; +arr3[3] = 3; +arr3["horse"] = "neigh"; +arr3["狗"] = "王"; + + +console.log(arr3.length); +console.log(arr3[0]); +console.log(arr3); + + + +// multi-dimensional +//var arr4 = [][]; not ok +//var arr5 = [3][3]; // not ok + +// to create a 3x3 + +var tx3A = new Array(new Array(3), new Array(3), new Array(3)); +var tx3B = []; + +for (var i = 0; i < 3; i++) { + tx3B[i] = new Array(3); +} + + +console.log(tx3A); +console.log(tx3B); + + + +// why use arrays when objects contain much of the same functionality: V8 optmises heavily, extra operations slice(), push pop, shift, unshift + + +// key operations push pop +// shift unshift + + +var random = new Array(1, 342, 53, 38, 85958, 3584934, 8459, 2, 69, 1396, 146, 194); + + +// print squares +random.forEach(function (element, index, array) { + console.log(element + "^2 = " + element * element); +}); + + +var squares = random.map(function (element, index, array) { + return element * element; +}); +console.log(squares); + +var evens_only = random.filter(function (element, index, array) { + return (element % 2) == 0; +}); +console.log(evens_only); + + + +console.log(random.join(", ")); + diff --git a/Chapter02/global.js b/Chapter02/global.js new file mode 100644 index 0000000..0394c65 --- /dev/null +++ b/Chapter02/global.js @@ -0,0 +1,13 @@ + + + +function printit(var_name) { + console.log(global[var_name]); +} + +global.fish = "swordfish"; +global.pet = "cat"; + +printit("fish"); +printit("pet"); +printit("fruit"); diff --git a/Chapter02/objects.js b/Chapter02/objects.js new file mode 100644 index 0000000..c9db873 --- /dev/null +++ b/Chapter02/objects.js @@ -0,0 +1,5 @@ + + +var obj1 = {}; +var obj2 = new Object(); + diff --git a/Chapter02/test.js b/Chapter02/test.js new file mode 100644 index 0000000..4110d0e --- /dev/null +++ b/Chapter02/test.js @@ -0,0 +1,9 @@ + + +var arr = []; + +arr[0] = 1; +arr[1] = 2; +arr["cat"] = 'meow'; + +console.log(arr.length); \ No newline at end of file diff --git a/Chapter02/trycatch.js b/Chapter02/trycatch.js new file mode 100644 index 0000000..8050b05 --- /dev/null +++ b/Chapter02/trycatch.js @@ -0,0 +1,16 @@ + + +function uhoh () { + throw new Error("Something bad happened!"); +} + +try { + uhoh(); +} catch (e) { + console.log("I caught an error: " + e.message); +} + +console.log("program is still running"); + + + diff --git a/Chapter02/types.txt b/Chapter02/types.txt new file mode 100644 index 0000000..77a1fab --- /dev/null +++ b/Chapter02/types.txt @@ -0,0 +1,67 @@ +BASIC TYPES: + + +there are several core types: + +numbers, strings, booleans, functions, objects + +null, undefined are actually both types, although just particular instances of objects, and arrays a special case of objects. + +if we have a variable in javascript, type is + +typeof x + +note arrays will return 'object'. see section on arrays. + + + +NUMBERS + +- 64bit double precision floating point numbers -- there are no "integer" types in javascript. +- that means you have 53 bits of precision. +- if you are going to represent 64bits in javascript, use strings or separate library +- if you're doing math ops on floating point numbers, be careful + - 0.1 + 0.2 != 0.3 +- integer numbers < 53 bits will be great because they can be exactly rep'd +- dividing by zero gives you (-)Infinity +- you can convert strings to numbers with parseInt or parseFloat + - if they fail, return NaN + - isNaN +- can test for a "valid" number with isFinite() + + + +BOOLEANS: + +- can have the value true or false +- you can force things to boolean with the Booelan(XXX) function, but rarely necessary + + +STRINGS: + +- strings are sequences of unicode characters +- great for most characters around the world +- no separate character data type -- can just use 1-char strings +- to get the length, jut use .length +var s = "my string"; +console.log(s.length); +// or +console.log("my string".length); + +many interesting functions on strings: + +int str.indexOf("there"); +string "hello there".slice(5, 6) == " " // true +string "hello there".substr(5, 1) == " " // true +array "1,2,3,4,5".split(",") + + + +null is a special value indicates non-value +undefined means no such thing or no value set yet + +var x; +-> undefined +console.log(x); +-> undefined + diff --git a/Chapter03/01_php_example.php b/Chapter03/01_php_example.php new file mode 100644 index 0000000..308709c --- /dev/null +++ b/Chapter03/01_php_example.php @@ -0,0 +1,7 @@ +$file = fopen('info.txt', 'r'); +// wait until file is open + +$contents = fread($file, 100000); +// wait until contents are read + +// do something with those contents diff --git a/Chapter03/02_settimeout.js b/Chapter03/02_settimeout.js new file mode 100644 index 0000000..a1264a6 --- /dev/null +++ b/Chapter03/02_settimeout.js @@ -0,0 +1,7 @@ + +setTimeout(function () { + console.log("I've done my work!"); +}, 2000); + + +console.log("I'm waiting for all my work to finish."); diff --git a/Chapter03/03_async_bad.js b/Chapter03/03_async_bad.js new file mode 100644 index 0000000..c9857b1 --- /dev/null +++ b/Chapter03/03_async_bad.js @@ -0,0 +1,20 @@ +var fs = require('fs'); + +var file; +var buf = new Buffer(100000); + +fs.open( + 'info.txt', 'r', + function (err, handle) { + file = handle; + } +); + +fs.read( + file, buf, 0, 100000, null, + function (err, length) { + console.log(buf.toString()); + fs.close(file, function () { /* don't care */ }); + } +); + diff --git a/Chapter03/04_async_good.js b/Chapter03/04_async_good.js new file mode 100644 index 0000000..25ef76a --- /dev/null +++ b/Chapter03/04_async_good.js @@ -0,0 +1,16 @@ + +var fs = require('fs'); + +fs.open( + 'info.txt', 'r', + function (err, handle) { + var buf = new Buffer(100000); + fs.read( + handle, buf, 0, 100000, null, + function (err, length) { + console.log(buf.toString('utf8', 0, length)); + fs.close(handle, function () { /* don't care */ }); + } + ); + } +); diff --git a/Chapter03/05_async_with_error_handling.js b/Chapter03/05_async_with_error_handling.js new file mode 100644 index 0000000..1a4d8be --- /dev/null +++ b/Chapter03/05_async_with_error_handling.js @@ -0,0 +1,27 @@ + + +var fs = require('fs'); + +fs.open( + 'info.txt', 'r', + function (err, handle) { + if (err) { + console.log("ERROR: " + err.code + " (" + err.message + ")"); + return; + } + var buf = new Buffer(100000); + fs.read( + handle, buf, 0, 100000, null, + function (err, length) { + if (err) { + console.log("ERROR: " + err.code + + " (" + err.message + ")"); + return; + } + console.log(buf.toString('utf8', 0, length)); + fs.close(handle, function () { /* don't care */ }); + } + ); + } +); + diff --git a/Chapter03/06_errors_async.js b/Chapter03/06_errors_async.js new file mode 100644 index 0000000..8f60bdc --- /dev/null +++ b/Chapter03/06_errors_async.js @@ -0,0 +1,11 @@ + + +try { + setTimeout(function () { + throw new Error("Uh oh, something bad!"); + }, 2000); +} catch (e) { + console.log("I caught the error: " + e.message); +} + + diff --git a/Chapter03/07_this_self_error.js b/Chapter03/07_this_self_error.js new file mode 100644 index 0000000..d829012 --- /dev/null +++ b/Chapter03/07_this_self_error.js @@ -0,0 +1,44 @@ + +var fs = require('fs'); + +function FileObject () { + + this.filename = ''; + + this.file_exists = function (callback) { + if (!this.filename) { + var e = new Error("invalid_filename"); + e.description = "You need to provide a valid filename"; + callback(e); + return; + } + + console.log("About to open: " + this.filename); + fs.open(this.filename, 'r', function (err, handle) { + if (err) { + console.log("Can't open: " + this.filename); + callback(null, false); + return; + } + + console.log("can open: " + this.filename); + fs.close(handle, function () { }); + callback(null, true); + }); + }; +} + +var fo = new FileObject(); +fo.filename = "file_that_does_not_exist"; + +fo.file_exists(function (err, results) { + if (err) { + console.log("WAT: " + JSON.stringify(err)); + return; + } + + console.log(results ? "file exists!!!" : "bummer!"); +}); + + + diff --git a/Chapter03/08_this_self_fixed.js b/Chapter03/08_this_self_fixed.js new file mode 100644 index 0000000..c70dafd --- /dev/null +++ b/Chapter03/08_this_self_fixed.js @@ -0,0 +1,45 @@ + +var fs = require('fs'); + +function FileObject () { + + this.filename = ''; + + this.file_exists = function (callback) { + var self = this; + + if (!this.filename) { + var e = new Error("invalid_filename"); + e.description = "You need to provide a valid filename"; + callback(e); + return; + } + + console.log("About to open: " + self.filename); + fs.open(this.filename, 'r', function (err, handle) { + if (err) { + console.log("Can't open: " + self.filename); + callback(null, false); + return; + } + + fs.close(handle, function () { }); + callback(null, true); + }); + }; +} + +var fo = new FileObject(); +fo.filename = "file_that_does_not_exist"; + +fo.file_exists(function (err, results) { + if (err) { + console.log("Aw, bummer: " + JSON.stringify(err)); + return; + } + + console.log("file exists!!!"); +}); + + + diff --git a/Chapter03/09_expensive.js b/Chapter03/09_expensive.js new file mode 100644 index 0000000..1518366 --- /dev/null +++ b/Chapter03/09_expensive.js @@ -0,0 +1,14 @@ + + +function compute_intersection(arr1, arr2) { + var results = []; + for (var i = 0 ; i < arr1.length; i++) { + for (var j = 0; j < arr2.length; j++) { + if (arr2[j] == arr1[i]) { + results[results.length] = arr1[j]; + break; + } + } + } +} + diff --git a/Chapter03/10_expensive_nextTick.js b/Chapter03/10_expensive_nextTick.js new file mode 100644 index 0000000..05b5fce --- /dev/null +++ b/Chapter03/10_expensive_nextTick.js @@ -0,0 +1,52 @@ + +function compute_intersection(arr1, arr2, callback) { + + var bigger = arr1.length > arr2.length ? arr1 : arr2; + var smaller = bigger == arr1 ? arr2 : arr1; + var biglen = bigger.length; + var smlen = smaller.length; + + var sidx = 0; + var size = 10; // 100 at a time, can adjust! + var results = []; + + function sub_compute_intersection() { + for (var i = sidx; i < (sidx + size) && i < biglen; i++) { + for (var j = 0; j < smlen; j++) { + if (bigger[i] == smaller[j]) { + results.push(smaller[j]); + break; + } + } + } + + if (i >= biglen) { + callback(null, results); + } else { + sidx += size; + process.nextTick(sub_compute_intersection); + } + } + + sub_compute_intersection(); +} + + + +var a1 = [ 3476, 2457, 7547, 34523, 3, 6, 7,2, 77, 8, 2345, + 7623457, 2347, 23572457, 237457, 234869, 237, + 24572457524] ; +var a2 = [ 3476, 75347547, 2457634563, 56763472, 34574, 2347, + 7, 34652364 , 13461346, 572346, 23723457234, 237, + 234, 24352345, 537, 2345235, 2345675, 34534, + 7582768, 284835, 8553577, 2577257,545634, 457247247, + 2345 ]; + +compute_intersection(a1, a2, function (err, results) { + if (err) { + console.log(err); + } else { + console.log(results); + } +}); + diff --git a/Chapter03/11_sync_fileget.js b/Chapter03/11_sync_fileget.js new file mode 100644 index 0000000..4af0eff --- /dev/null +++ b/Chapter03/11_sync_fileget.js @@ -0,0 +1,8 @@ + +var fs = require('fs'); + +var handle = fs.openSync('info.txt', 'r'); +var buf = new Buffer(100000); +var read = fs.readSync(handle, buf, 0, 10000, null); +console.log(buf.toString('utf8', 0, read)); +fs.closeSync(handle); \ No newline at end of file diff --git a/Chapter03/info.txt b/Chapter03/info.txt new file mode 100644 index 0000000..8bd6648 --- /dev/null +++ b/Chapter03/info.txt @@ -0,0 +1 @@ +asdf diff --git a/Chapter04/01_simple_server.js b/Chapter04/01_simple_server.js new file mode 100644 index 0000000..5511a3e --- /dev/null +++ b/Chapter04/01_simple_server.js @@ -0,0 +1,14 @@ + +var http = require('http'); + +function handle_incoming_request(req, res) { + console.log("INCOMING REQUEST: " + req.method + " " + req.url); + res.writeHead(200, { "Content-Type" : "application/json" }); + res.end(JSON.stringify( { error: null }) + "\n"); +} + + +var s = http.createServer(handle_incoming_request); + +s.listen(8080); + diff --git a/Chapter04/02_load_albums.js b/Chapter04/02_load_albums.js new file mode 100644 index 0000000..94466a5 --- /dev/null +++ b/Chapter04/02_load_albums.js @@ -0,0 +1,39 @@ + +var http = require('http'), + fs = require('fs'); + +function load_album_list(callback) { + // we will just assume that any directory in our 'albums' + // subfolder is an album. + fs.readdir( + "albums", + function (err, files) { + if (err) { + callback(err); + return; + } + callback(null, files); + } + ); +} + +function handle_incoming_request(req, res) { + console.log("INCOMING REQUEST: " + req.method + " " + req.url); + load_album_list(function (err, albums) { + if (err) { + res.writeHead(500, {"Content-Type": "application/json"}); + res.end(JSON.stringify(err) + "\n"); + return; + } + + var out = { error: null, + data: { albums: albums }}; + res.writeHead(200, {"Content-Type": "application/json"}); + res.end(JSON.stringify(out) + "\n"); + }); +} + +var s = http.createServer(handle_incoming_request); + +s.listen(8080); + diff --git a/Chapter04/03_test_folder.js b/Chapter04/03_test_folder.js new file mode 100644 index 0000000..298f026 --- /dev/null +++ b/Chapter04/03_test_folder.js @@ -0,0 +1,53 @@ + +var http = require('http'), + fs = require('fs'); + +function load_album_list(callback) { + // we will just assume that any directory in our 'albums' + // subfolder is an album. + fs.readdir( + "albums", + function (err, files) { + if (err) { + callback(err); + return; + } + + var only_dirs = []; + + for (var i = 0; files && i < files.length; i++) { + fs.stat( + "albums/" + files[i], + function(err, stats) { + if (stats.isDirectory()) { + only_dirs.push(files[i]); + } + } + ); + } + + callback(null, only_dirs); + } + ); +} + +function handle_incoming_request(req, res) { + console.log("INCOMING REQUEST: " + req.method + " " + req.url); + load_album_list(function (err, albums) { + if (err) { + res.writeHead(500, {"Content-Type": "application/json"}); + res.end(JSON.stringify(err) + "\n"); + return; + } + + var out = { error: null, + data: { albums: albums }}; + res.writeHead(200, {"Content-Type": "application/json"}); + res.end(JSON.stringify(out) + "\n"); + }); +} + +var s = http.createServer(handle_incoming_request); + +s.listen(8080); + diff --git a/Chapter04/04_test_folder.js b/Chapter04/04_test_folder.js new file mode 100644 index 0000000..b849f6b --- /dev/null +++ b/Chapter04/04_test_folder.js @@ -0,0 +1,61 @@ + +var http = require('http'), + fs = require('fs'); + +function load_album_list(callback) { + // we will just assume that any directory in our 'albums' + // subfolder is an album. + fs.readdir( + "albums", + function (err, files) { + if (err) { + callback(err); + return; + } + + var only_dirs = []; + + (function iterator(index) { + if (index == files.length) { + callback(null, only_dirs); + return; + } + + fs.stat( + "albums/" + files[index], + function (err, stats) { + if (err) { + callback(err); + return; + } + if (stats.isDirectory()) { + only_dirs.push(files[index]); + } + iterator(index + 1) + } + ); + })(0); + } + ); +} + +function handle_incoming_request(req, res) { + console.log("INCOMING REQUEST: " + req.method + " " + req.url); + load_album_list(function (err, albums) { + if (err) { + res.writeHead(500, {"Content-Type": "application/json"}); + res.end(JSON.stringify(err) + "\n"); + return; + } + + var out = { error: null, + data: { albums: albums }}; + res.writeHead(200, {"Content-Type": "application/json"}); + res.end(JSON.stringify(out) + "\n"); + }); +} + +var s = http.createServer(handle_incoming_request); + +s.listen(8080); + diff --git a/Chapter04/05_multiple_requests.js b/Chapter04/05_multiple_requests.js new file mode 100644 index 0000000..5c195d6 --- /dev/null +++ b/Chapter04/05_multiple_requests.js @@ -0,0 +1,167 @@ + +var http = require('http'), + fs = require('fs'); + + +function load_album_list(callback) { + // we will just assume that any directory in our 'albums' + // subfolder is an album. + fs.readdir( + "albums", + function (err, files) { + if (err) { + callback(make_error("file_error", JSON.stringify(err))); + return; + } + + var only_dirs = []; + + (function iterator(index) { + if (index == files.length) { + callback(null, only_dirs); + return; + } + + fs.stat( + "albums/" + files[index], + function (err, stats) { + if (err) { + callback(make_error("file_error", + JSON.stringify(err))); + return; + } + if (stats.isDirectory()) { + var obj = { name: files[index] }; + only_dirs.push(obj); + } + iterator(index + 1) + } + ); + })(0); + } + ); +} + +function load_album(album_name, callback) { + // we will just assume that any directory in our 'albums' + // subfolder is an album. + fs.readdir( + "albums/" + album_name, + function (err, files) { + if (err) { + if (err.code == "ENOENT") { + callback(no_such_album()); + } else { + callback(make_error("file_error", + JSON.stringify(err))); + } + return; + } + + var only_files = []; + var path = "albums/" + album_name + "/"; + + (function iterator(index) { + if (index == files.length) { + var obj = { short_name: album_name, + photos: only_files }; + callback(null, obj); + return; + } + + fs.stat( + path + files[index], + function (err, stats) { + if (err) { + callback(make_error("file_error", + JSON.stringify(err))); + return; + } + if (stats.isFile()) { + var obj = { filename: files[index], + desc: files[index] }; + only_files.push(obj); + } + iterator(index + 1) + } + ); + })(0); + } + ); +} + + +function handle_incoming_request(req, res) { + console.log("INCOMING REQUEST: " + req.method + " " + req.url); + if (req.url == '/albums.json') { + handle_list_albums(req, res); + } else if (req.url.substr(0, 7) == '/albums' + && req.url.substr(req.url.length - 5) == '.json') { + handle_get_album(req, res); + } else { + send_failure(res, 404, invalid_resource()); + } +} + +function handle_list_albums(req, res) { + load_album_list(function (err, albums) { + if (err) { + send_failure(res, 500, err); + return; + } + + send_success(res, { albums: albums }); + }); +} + +function handle_get_album(req, res) { + // format of request is /albums/album_name.json + var album_name = req.url.substr(7, req.url.length - 12); + load_album( + album_name, + function (err, album_contents) { + if (err && err.error == "no_such_album") { + send_failure(res, 404, err); + } else if (err) { + send_failure(res, 500, err); + } else { + send_success(res, { album_data: album_contents }); + } + } + ); +} + + +function make_error(err, msg) { + var e = new Error(msg); + e.code = err; + return e; +} + +function send_success(res, data) { + res.writeHead(200, {"Content-Type": "application/json"}); + var output = { error: null, data: data }; + res.end(JSON.stringify(output) + "\n"); +} + +function send_failure(res, code, err) { + var code = (err.code) ? err.code : err.name; + res.writeHead(code, { "Content-Type" : "application/json" }); + res.end(JSON.stringify({ error: code, message: err.message }) + "\n"); +} + + +function invalid_resource() { + return make_error("invalid_resource", + "the requested resource does not exist."); +} + +function no_such_album() { + return make_error("no_such_album", + "The specified album does not exist"); +} + + +var s = http.createServer(handle_incoming_request); +s.listen(8080); + diff --git a/Chapter04/06_req_res.js b/Chapter04/06_req_res.js new file mode 100644 index 0000000..48afecd --- /dev/null +++ b/Chapter04/06_req_res.js @@ -0,0 +1,17 @@ + +var http = require('http'); + +function handle_incoming_request(req, res) { + console.log("---------------------------------------------------"); + console.log(req.headers); + console.log("---------------------------------------------------"); + console.log(res); + console.log("---------------------------------------------------"); + res.writeHead(200, { "Content-Type" : "application/json" }); + res.end(JSON.stringify( { error: null }) + "\n"); +} + + +var s = http.createServer(handle_incoming_request); +s.listen(8080); + diff --git a/Chapter04/07_get_params.js b/Chapter04/07_get_params.js new file mode 100644 index 0000000..42196fd --- /dev/null +++ b/Chapter04/07_get_params.js @@ -0,0 +1,188 @@ + +var http = require('http'), + fs = require('fs'), + url = require('url'); + + +function load_album_list(callback) { + // we will just assume that any directory in our 'albums' + // subfolder is an album. + fs.readdir( + "albums", + function (err, files) { + if (err) { + callback(make_error("file_error", JSON.stringify(err))); + return; + } + + var only_dirs = []; + + (function iterator(index) { + if (index == files.length) { + callback(null, only_dirs); + return; + } + + fs.stat( + "albums/" + files[index], + function (err, stats) { + if (err) { + callback(make_error("file_error", + JSON.stringify(err))); + return; + } + if (stats.isDirectory()) { + var obj = { name: files[index] }; + only_dirs.push(obj); + } + iterator(index + 1) + } + ); + })(0); + } + ); +} + +function load_album(album_name, page, page_size, callback) { + fs.readdir( + "albums/" + album_name, + function (err, files) { + if (err) { + if (err.code == "ENOENT") { + callback(no_such_album()); + } else { + callback(make_error("file_error", + JSON.stringify(err))); + } + return; + } + + var only_files = []; + var path = "albums/" + album_name + "/"; + + (function iterator(index) { + if (index == files.length) { + var ps; + // slice fails gracefully if params are out of range + ps = only_files.splice(page * page_size, page_size); + var obj = { short_name: album_name, + photos: ps }; + callback(null, obj); + return; + } + + fs.stat( + path + files[index], + function (err, stats) { + if (err) { + callback(make_error("file_error", + JSON.stringify(err))); + return; + } + if (stats.isFile()) { + var obj = { filename: files[index], desc: files[index] }; + only_files.push(obj); + } + iterator(index + 1) + } + ); + })(0); + } + ); +} + + +function handle_incoming_request(req, res) { + + // parse the query params into an object and get the path + // without them. (2nd param true = parse the params). + req.parsed_url = url.parse(req.url, true); + var core_url = req.parsed_url.pathname; + + // test this fixed url to see what they're asking for + if (core_url == '/albums.json') { + handle_list_albums(req, res); + } else if (core_url.substr(0, 7) == '/albums' + && core_url.substr(core_url.length - 5) == '.json') { + handle_get_album(req, res); + } else { + send_failure(res, 404, invalid_resource()); + } +} + +function handle_list_albums(req, res) { + load_album_list(function (err, albums) { + if (err) { + send_failure(res, 500, err); + return; + } + + send_success(res, { albums: albums }); + }); +} + +function handle_get_album(req, res) { + + // get the GET params + var getp = req.parsed_url.query; + var page_num = getp.page ? getp.page : 0; + var page_size = getp.page_size ? getp.page_size : 1000; + + if (isNaN(parseInt(page_num))) page_num = 0; + if (isNaN(parseInt(page_size))) page_size = 1000; + + // format of request is /albums/album_name.json + var core_url = req.parsed_url.pathname; + + var album_name = core_url.substr(7, core_url.length - 12); + load_album( + album_name, + page_num, + page_size, + function (err, album_contents) { + if (err && err.error == "no_such_album") { + send_failure(res, 404, err); + } else if (err) { + send_failure(res, 500, err); + } else { + send_success(res, { album_data: album_contents }); + } + } + ); +} + + + +function make_error(err, msg) { + var e = new Error(msg); + e.code = err; + return e; +} + +function send_success(res, data) { + res.writeHead(200, {"Content-Type": "application/json"}); + var output = { error: null, data: data }; + res.end(JSON.stringify(output) + "\n"); +} + +function send_failure(res, code, err) { + var code = (err.code) ? err.code : err.name; + res.writeHead(code, { "Content-Type" : "application/json" }); + res.end(JSON.stringify({ error: code, message: err.message }) + "\n"); +} + + +function invalid_resource() { + return make_error("invalid_resource", + "the requested resource does not exist."); +} + +function no_such_album() { + return make_error("no_such_album", + "The specified album does not exist"); +} + + +var s = http.createServer(handle_incoming_request); +s.listen(8080); + diff --git a/Chapter04/08_post_data.js b/Chapter04/08_post_data.js new file mode 100644 index 0000000..dab37f1 --- /dev/null +++ b/Chapter04/08_post_data.js @@ -0,0 +1,304 @@ + +var http = require('http'), + fs = require('fs'), + url = require('url'); + + +function load_album_list(callback) { + // we will just assume that any directory in our 'albums' + // subfolder is an album. + fs.readdir( + "albums", + function (err, files) { + if (err) { + callback(make_error("file_error", JSON.stringify(err))); + return; + } + + var only_dirs = []; + + (function iterator(index) { + if (index == files.length) { + callback(null, only_dirs); + return; + } + + fs.stat( + "albums/" + files[index], + function (err, stats) { + if (err) { + callback(make_error("file_error", + JSON.stringify(err))); + return; + } + if (stats.isDirectory()) { + var obj = { name: files[index] }; + only_dirs.push(obj); + } + iterator(index + 1) + } + ); + })(0); + } + ); +} + +function load_album(album_name, page, page_size, callback) { + // we will just assume that any directory in our 'albums' + // subfolder is an album. + fs.readdir( + "albums/" + album_name, + function (err, files) { + if (err) { + if (err.code == "ENOENT") { + callback(no_such_album()); + } else { + callback(make_error("file_error", + JSON.stringify(err))); + } + return; + } + + var only_files = []; + var path = "albums/" + album_name + "/"; + + (function iterator(index) { + if (index == files.length) { + var ps; + // slice fails gracefully if params are out of range + ps = only_files.splice(page * page_size, page_size); + var obj = { short_name: album_name, + photos: ps }; + callback(null, obj); + return; + } + + fs.stat( + path + files[index], + function (err, stats) { + if (err) { + callback(make_error("file_error", + JSON.stringify(err))); + return; + } + if (stats.isFile()) { + var obj = { filename: files[index], desc: files[index] }; + only_files.push(obj); + } + iterator(index + 1) + } + ); + })(0); + } + ); +} + + + +function do_rename(old_name, new_name, callback) { + + // rename the album folder. + fs.rename( + "albums/" + old_name, + "albums/" + new_name, + callback); +} + + + + +function handle_incoming_request(req, res) { + + // parse the query params into an object and get the path + // without them. (2nd param true = parse the params). + req.parsed_url = url.parse(req.url, true); + var core_url = req.parsed_url.pathname; + + // test this fixed url to see what they're asking for + if (core_url == '/albums.json' && req.method.toLowerCase() == 'get') { + handle_list_albums(req, res); + } else if (core_url.substr(core_url.length - 12) == '/rename.json' + && req.method.toLowerCase() == 'post') { + handle_rename_album(req, res); + } else if (core_url.substr(0, 7) == '/albums' + && core_url.substr(core_url.length - 5) == '.json' + && req.method.toLowerCase() == 'get') { + handle_get_album(req, res); + } else { + send_failure(res, 404, invalid_resource()); + } +} + +function handle_list_albums(req, res) { + load_album_list(function (err, albums) { + if (err) { + send_failure(res, 500, err); + return; + } + + send_success(res, { albums: albums }); + }); +} + +function handle_get_album(req, res) { + + // get the GET params + var getp = req.parsed_url.query; + var page_num = getp.page ? getp.page : 0; + var page_size = getp.page_size ? getp.page_size : 1000; + + if (isNaN(parseInt(page_num))) page_num = 0; + if (isNaN(parseInt(page_size))) page_size = 1000; + + // format of request is /albums/album_name.json + var core_url = req.parsed_url.pathname; + + var album_name = core_url.substr(7, core_url.length - 12); + load_album( + album_name, + page_num, + page_size, + function (err, album_contents) { + if (err && err.error == "no_such_album") { + send_failure(res, 404, err); + } else if (err) { + send_failure(res, 500, err); + } else { + send_success(res, { album_data: album_contents }); + } + } + ); +} + + +function handle_rename_album(req, res) { + + // 1. Get the album name from the URL + var core_url = req.parsed_url.pathname; + var parts = core_url.split('/'); + if (parts.length != 4) { + send_failure(res, 404, invalid_resource(core_url)); + return; + } + + var album_name = parts[2]; + + // 2. get the POST data for the request. this will have the JSON + // for the new name for the album. + var json_body = ''; + req.on( + 'readable', + function () { + var d = req.read(); + console.log(d); + console.log(typeof d); + if (d) { + if (typeof d == 'string') { + json_body += d; + } else if (typeof d == 'object' && d instanceof Buffer) { + json_body += d.toString('utf8'); + } + } + } + ); + + // 3. when we have all the post data, make sure we have valid + // data and then try to do the rename. + req.on( + 'end', + function () { + // did we get a valid body? + if (json_body) { + try { + var album_data = JSON.parse(json_body); + if (!album_data.album_name) { + send_failure(res, 404, missing_data('album_name')); + return; + } + } catch (e) { + // got a body, but not valid json + send_failure(res, 403, bad_json()); + return; + } + + // we have a proposed new album name! + do_rename( + album_name, // old + album_data.album_name, // new + function (err, results) { + if (err && err.code == "ENOENT") { + send_failure(res, 403, no_such_album()); + return; + } else if (err) { + send_failure(res, 500, file_error(err)); + return; + } + send_success(res, null); + } + ); + } else { + send_failure(res, 403, bad_json()); + res.end(); + } + } + ); +} + + + + + + + +function make_error(err, msg) { + var e = new Error(msg); + e.code = err; + return e; +} + + +function send_success(res, data) { + res.writeHead(200, {"Content-Type": "application/json"}); + var output = { error: null, data: data }; + res.end(JSON.stringify(output) + "\n"); +} + + +function send_failure(res, code, err) { + var code = (err.code) ? err.code : err.name; + res.writeHead(code, { "Content-Type" : "application/json" }); + res.end(JSON.stringify({ error: code, message: err.message }) + "\n"); +} + + +function invalid_resource() { + return make_error("invalid_resource", + "the requested resource does not exist."); +} + +function no_such_album() { + return make_error("no_such_album", + "The specified album does not exist"); +} + +function file_error(err) { + var msg = "There was a file error on the server: " + err.message; + return make_error("server_file_error", msg); +} + +function missing_data (missing) { + var msg = missing + ? "Your request is missing: '" + missing + "'" + : "Your request is missing some data."; + return make_error("missing_data", msg); +} + +function bad_json() { + return make_error("invalid_json", + "the provided data is not valid JSON"); +} + + +var s = http.createServer(handle_incoming_request); +s.listen(8080); + diff --git a/Chapter04/09_form_data.html b/Chapter04/09_form_data.html new file mode 100644 index 0000000..265ab12 --- /dev/null +++ b/Chapter04/09_form_data.html @@ -0,0 +1,12 @@ + + + Form Test + + +
+ Name:
+ Age:
+ +
+ + diff --git a/Chapter04/09_form_data.js b/Chapter04/09_form_data.js new file mode 100644 index 0000000..5c4cd02 --- /dev/null +++ b/Chapter04/09_form_data.js @@ -0,0 +1,40 @@ + +var http = require('http'), qs = require('querystring'); + +function handle_incoming_request(req, res) { + var body = ''; + req.on( + 'readable', + function () { + var d = req.read(); + if (d) { + if (typeof d == 'string') { + body += d; + } else if (typeof d == 'object' && d instanceof Buffer) { + body += d.toString('utf8'); + } + } + } + ); + + // 3. when we have all the post data, make sure we have valid + // data and then try to do the rename. + req.on( + 'end', + function () { + if (req.method.toLowerCase() == 'post') { + var POST_data = qs.parse(body); + console.log(POST_data); + } + res.writeHead(200, { "Content-Type" : "application/json" }); + res.end(JSON.stringify( { error: null }) + "\n"); + } + ); + +} + + +var s = http.createServer(handle_incoming_request); + +s.listen(8080); + diff --git a/Chapter04/albums/australia2010/aus_01.jpg b/Chapter04/albums/australia2010/aus_01.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter04/albums/australia2010/aus_02.jpg b/Chapter04/albums/australia2010/aus_02.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter04/albums/australia2010/aus_03.jpg b/Chapter04/albums/australia2010/aus_03.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter04/albums/australia2010/aus_04.jpg b/Chapter04/albums/australia2010/aus_04.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter04/albums/australia2010/aus_05.jpg b/Chapter04/albums/australia2010/aus_05.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter04/albums/australia2010/aus_06.jpg b/Chapter04/albums/australia2010/aus_06.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter04/albums/australia2010/aus_07.jpg b/Chapter04/albums/australia2010/aus_07.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter04/albums/australia2010/aus_08.jpg b/Chapter04/albums/australia2010/aus_08.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter04/albums/australia2010/aus_09.jpg b/Chapter04/albums/australia2010/aus_09.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter04/albums/info.txt b/Chapter04/albums/info.txt new file mode 100644 index 0000000..e69de29 diff --git a/Chapter04/albums/italy2012/picture_01.jpg b/Chapter04/albums/italy2012/picture_01.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter04/albums/italy2012/picture_02.jpg b/Chapter04/albums/italy2012/picture_02.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter04/albums/italy2012/picture_03.jpg b/Chapter04/albums/italy2012/picture_03.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter04/albums/italy2012/picture_04.jpg b/Chapter04/albums/italy2012/picture_04.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter04/albums/italy2012/picture_05.jpg b/Chapter04/albums/italy2012/picture_05.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter04/albums/japan2010/picture_001.jpg b/Chapter04/albums/japan2010/picture_001.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter04/albums/japan2010/picture_002.jpg b/Chapter04/albums/japan2010/picture_002.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter04/albums/japan2010/picture_003.jpg b/Chapter04/albums/japan2010/picture_003.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter04/albums/japan2010/picture_004.jpg b/Chapter04/albums/japan2010/picture_004.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter04/albums/japan2010/picture_005.jpg b/Chapter04/albums/japan2010/picture_005.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter04/albums/japan2010/picture_006.jpg b/Chapter04/albums/japan2010/picture_006.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter04/albums/japan2010/picture_007.jpg b/Chapter04/albums/japan2010/picture_007.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter05/01_mymodule.js b/Chapter05/01_mymodule.js new file mode 100644 index 0000000..d2e6462 --- /dev/null +++ b/Chapter05/01_mymodule.js @@ -0,0 +1,25 @@ + + +function Greeter (lang) { + this.language = language; + this.greet() = function () { + switch (this.language) { + case "en": return "Hello!"; + case "de": return "Hallo!"; + case "jp": return "こんにちは!"; + default: return "No speaka that language"; + } + } +} + +exports.hello_world = function () { + console.log("Hello World"); +} + +exports.goodbye = function () { + console.log("Bye bye!"); +} + +exports.greeter = function (lang) { + return new Greeter(lang); +} diff --git a/Chapter05/02_factory_model_module.js b/Chapter05/02_factory_model_module.js new file mode 100644 index 0000000..6388720 --- /dev/null +++ b/Chapter05/02_factory_model_module.js @@ -0,0 +1,11 @@ +function ABC (parms) { + this.varA = 10; + this.varB = 20; + this.functionA = function (var1, var2) { + console.log(var1 + " " + var2); + } +} + +exports.create_ABC = function (parms) { + return new ABC(parms); +} diff --git a/Chapter05/02_factory_model_test.js b/Chapter05/02_factory_model_test.js new file mode 100644 index 0000000..bcbe409 --- /dev/null +++ b/Chapter05/02_factory_model_test.js @@ -0,0 +1,5 @@ +var fmm = require('./02_factory_model_module.js'); + +var abc = fmm.create_ABC(); + +abc.functionA(4, 5); diff --git a/Chapter05/03_constructor_model_module.js b/Chapter05/03_constructor_model_module.js new file mode 100644 index 0000000..ad8f05d --- /dev/null +++ b/Chapter05/03_constructor_model_module.js @@ -0,0 +1,11 @@ + +function ABC () { + this.varA = 10; + this.varB = 20; + this.functionA = function (var1, var2) { + console.log(var1 + " " + var2); + } +} + + +module.exports = ABC; diff --git a/Chapter05/03_constructor_model_test.js b/Chapter05/03_constructor_model_test.js new file mode 100644 index 0000000..7889355 --- /dev/null +++ b/Chapter05/03_constructor_model_test.js @@ -0,0 +1,3 @@ +var abc = require('./03_constructor_model_module.js'); +var obj = new abc(); +obj.functionA(1, 2); diff --git a/Chapter05/04_album_module/album_mgr/Readme.md b/Chapter05/04_album_module/album_mgr/Readme.md new file mode 100644 index 0000000..b40a0e8 --- /dev/null +++ b/Chapter05/04_album_module/album_mgr/Readme.md @@ -0,0 +1,21 @@ +# Album-Manager + +This is our module for managing photo albums based on a directory. We +assume that, given a path, there is an albums sub-folder, and each of +its individual sub-folders are themselves the albums. Files in those +sub-folders are photos. + + +## Album Manager + +The album manager exposes a single function, `albums`, which returns +an array of `Album` objects for each album it contains. + +## Album Object + +The album object has the follow two properties and one method: + +* `name` -- The name of the album +* `path` -- The path to the album +* `photos()` -- Calling this method will return all the album's photos + diff --git a/Chapter05/04_album_module/album_mgr/lib/album.js b/Chapter05/04_album_module/album_mgr/lib/album.js new file mode 100644 index 0000000..bcb0d73 --- /dev/null +++ b/Chapter05/04_album_module/album_mgr/lib/album.js @@ -0,0 +1,78 @@ +var path = require('path'), + fs = require('fs'); + +function Album (album_path) { + this.name = path.basename(album_path); + this.path = album_path; +} + +Album.prototype.name = null; +Album.prototype.path = null; +Album.prototype._photos = null; + +Album.prototype.photos = function (callback) { + if (this._photos != null) { + callback(null, this._photos); + return; + } + + var self = this; + + fs.readdir( + self.path, + function (err, files) { + if (err) { + if (err.code == "ENOENT") { + callback(no_such_album()); + } else { + callback(make_error("file_error", + JSON.stringify(err))); + } + return; + } + + var only_files = []; + + (function iterator(index) { + if (index == files.length) { + callback(null, only_files); + return; + } + + fs.stat( + self.path + "/" + files[index], + function (err, stats) { + if (err) { + callback(make_error("file_error", + JSON.stringify(err))); + return; + } + if (stats.isFile()) { + only_files.push(files[index]); + } + iterator(index + 1) + } + ); + })(0); + } + ); +}; + + + +exports.create_album = function (path) { + return new Album(path); +}; + + +function make_error(err, msg) { + var e = new Error(msg); + e.code = err; + return e; +} + + +function no_such_album() { + return make_error("no_such_album", + "The specified album does not exist"); +} diff --git a/Chapter05/04_album_module/album_mgr/lib/albums.js b/Chapter05/04_album_module/album_mgr/lib/albums.js new file mode 100644 index 0000000..b8c731d --- /dev/null +++ b/Chapter05/04_album_module/album_mgr/lib/albums.js @@ -0,0 +1,52 @@ + +var fs = require('fs'), + album = require('./album.js'); + + +exports.version = "1.0.0"; + +exports.albums = function (root, callback) { + // we will just assume that any directory in our 'albums' + // subfolder is an album. + fs.readdir( + root + "/albums", + function (err, files) { + if (err) { + callback(err); + return; + } + + var album_list = []; + + (function iterator(index) { + if (index == files.length) { + callback(null, album_list); + return; + } + + fs.stat( + root + "albums/" + files[index], + function (err, stats) { + if (err) { + callback(make_error("file_error", + JSON.stringify(err))); + return; + } + if (stats.isDirectory()) { + var p = root + "albums/" + files[index]; + album_list.push(album.create_album(p)); + } + iterator(index + 1) + } + ); + })(0); + } + ); +}; + +function make_error(err, msg) { + var e = new Error(msg); + e.code = err; + return e; +} + diff --git a/Chapter05/04_album_module/album_mgr/package.json b/Chapter05/04_album_module/album_mgr/package.json new file mode 100644 index 0000000..036c1cc --- /dev/null +++ b/Chapter05/04_album_module/album_mgr/package.json @@ -0,0 +1,3 @@ +{ "name": "album-manager", + "version": "1.0.0", + "main": "./lib/albums.js" } diff --git a/Chapter05/04_album_module/album_mgr/test/album_test.js b/Chapter05/04_album_module/album_mgr/test/album_test.js new file mode 100644 index 0000000..74fb07e --- /dev/null +++ b/Chapter05/04_album_module/album_mgr/test/album_test.js @@ -0,0 +1,41 @@ + +var album_mgr = require('../lib/albums.js'), + path = require('path'); + + +album_mgr.albums( + "./", + function (err, albums) { + if (err) { + console.log("TEST FAILURE: can't load albums\n" + + JSON.stringify(err)); + return; + } + + (function iterator(index) { + if (index == albums.length) { + console.log("PASS!"); + return; + } + + albums[index].photos( + function (err, photos) { + if (err) { + console.log("TEST FAILURE: load album\n" + + JSON.stringify(err)); + return; + } + + var a = albums[index]; + console.log("Album: " + a.name + + "(" + a.path + ")"); + for (var i = 0; i < photos.length; i++) { + console.log(" " + path.basename(photos[i])); + } + console.log(""); + iterator(index+1); + } + ); + })(0); + } +); diff --git a/Chapter05/04_album_module/album_mgr/test/albums/australia2010/aus_01.jpg b/Chapter05/04_album_module/album_mgr/test/albums/australia2010/aus_01.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter05/04_album_module/album_mgr/test/albums/australia2010/aus_02.jpg b/Chapter05/04_album_module/album_mgr/test/albums/australia2010/aus_02.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter05/04_album_module/album_mgr/test/albums/australia2010/aus_03.jpg b/Chapter05/04_album_module/album_mgr/test/albums/australia2010/aus_03.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter05/04_album_module/album_mgr/test/albums/australia2010/aus_04.jpg b/Chapter05/04_album_module/album_mgr/test/albums/australia2010/aus_04.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter05/04_album_module/album_mgr/test/albums/australia2010/aus_05.jpg b/Chapter05/04_album_module/album_mgr/test/albums/australia2010/aus_05.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter05/04_album_module/album_mgr/test/albums/australia2010/aus_06.jpg b/Chapter05/04_album_module/album_mgr/test/albums/australia2010/aus_06.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter05/04_album_module/album_mgr/test/albums/australia2010/aus_07.jpg b/Chapter05/04_album_module/album_mgr/test/albums/australia2010/aus_07.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter05/04_album_module/album_mgr/test/albums/australia2010/aus_08.jpg b/Chapter05/04_album_module/album_mgr/test/albums/australia2010/aus_08.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter05/04_album_module/album_mgr/test/albums/australia2010/aus_09.jpg b/Chapter05/04_album_module/album_mgr/test/albums/australia2010/aus_09.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter05/04_album_module/album_mgr/test/albums/info.txt b/Chapter05/04_album_module/album_mgr/test/albums/info.txt new file mode 100644 index 0000000..e69de29 diff --git a/Chapter05/04_album_module/album_mgr/test/albums/italy2012/picture_01.jpg b/Chapter05/04_album_module/album_mgr/test/albums/italy2012/picture_01.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter05/04_album_module/album_mgr/test/albums/italy2012/picture_02.jpg b/Chapter05/04_album_module/album_mgr/test/albums/italy2012/picture_02.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter05/04_album_module/album_mgr/test/albums/italy2012/picture_03.jpg b/Chapter05/04_album_module/album_mgr/test/albums/italy2012/picture_03.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter05/04_album_module/album_mgr/test/albums/italy2012/picture_04.jpg b/Chapter05/04_album_module/album_mgr/test/albums/italy2012/picture_04.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter05/04_album_module/album_mgr/test/albums/italy2012/picture_05.jpg b/Chapter05/04_album_module/album_mgr/test/albums/italy2012/picture_05.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter05/04_album_module/album_mgr/test/albums/japan2010/picture_001.jpg b/Chapter05/04_album_module/album_mgr/test/albums/japan2010/picture_001.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter05/04_album_module/album_mgr/test/albums/japan2010/picture_002.jpg b/Chapter05/04_album_module/album_mgr/test/albums/japan2010/picture_002.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter05/04_album_module/album_mgr/test/albums/japan2010/picture_003.jpg b/Chapter05/04_album_module/album_mgr/test/albums/japan2010/picture_003.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter05/04_album_module/album_mgr/test/albums/japan2010/picture_004.jpg b/Chapter05/04_album_module/album_mgr/test/albums/japan2010/picture_004.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter05/04_album_module/album_mgr/test/albums/japan2010/picture_005.jpg b/Chapter05/04_album_module/album_mgr/test/albums/japan2010/picture_005.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter05/04_album_module/album_mgr/test/albums/japan2010/picture_006.jpg b/Chapter05/04_album_module/album_mgr/test/albums/japan2010/picture_006.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter05/04_album_module/album_mgr/test/albums/japan2010/picture_007.jpg b/Chapter05/04_album_module/album_mgr/test/albums/japan2010/picture_007.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter05/04_album_module/albums/australia2010/aus_01.jpg b/Chapter05/04_album_module/albums/australia2010/aus_01.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter05/04_album_module/albums/australia2010/aus_02.jpg b/Chapter05/04_album_module/albums/australia2010/aus_02.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter05/04_album_module/albums/australia2010/aus_03.jpg b/Chapter05/04_album_module/albums/australia2010/aus_03.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter05/04_album_module/albums/australia2010/aus_04.jpg b/Chapter05/04_album_module/albums/australia2010/aus_04.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter05/04_album_module/albums/australia2010/aus_05.jpg b/Chapter05/04_album_module/albums/australia2010/aus_05.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter05/04_album_module/albums/australia2010/aus_06.jpg b/Chapter05/04_album_module/albums/australia2010/aus_06.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter05/04_album_module/albums/australia2010/aus_07.jpg b/Chapter05/04_album_module/albums/australia2010/aus_07.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter05/04_album_module/albums/australia2010/aus_08.jpg b/Chapter05/04_album_module/albums/australia2010/aus_08.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter05/04_album_module/albums/australia2010/aus_09.jpg b/Chapter05/04_album_module/albums/australia2010/aus_09.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter05/04_album_module/albums/info.txt b/Chapter05/04_album_module/albums/info.txt new file mode 100644 index 0000000..e69de29 diff --git a/Chapter05/04_album_module/albums/italy2012/picture_01.jpg b/Chapter05/04_album_module/albums/italy2012/picture_01.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter05/04_album_module/albums/italy2012/picture_02.jpg b/Chapter05/04_album_module/albums/italy2012/picture_02.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter05/04_album_module/albums/italy2012/picture_03.jpg b/Chapter05/04_album_module/albums/italy2012/picture_03.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter05/04_album_module/albums/italy2012/picture_04.jpg b/Chapter05/04_album_module/albums/italy2012/picture_04.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter05/04_album_module/albums/italy2012/picture_05.jpg b/Chapter05/04_album_module/albums/italy2012/picture_05.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter05/04_album_module/albums/japan2010/picture_001.jpg b/Chapter05/04_album_module/albums/japan2010/picture_001.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter05/04_album_module/albums/japan2010/picture_002.jpg b/Chapter05/04_album_module/albums/japan2010/picture_002.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter05/04_album_module/albums/japan2010/picture_003.jpg b/Chapter05/04_album_module/albums/japan2010/picture_003.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter05/04_album_module/albums/japan2010/picture_004.jpg b/Chapter05/04_album_module/albums/japan2010/picture_004.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter05/04_album_module/albums/japan2010/picture_005.jpg b/Chapter05/04_album_module/albums/japan2010/picture_005.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter05/04_album_module/albums/japan2010/picture_006.jpg b/Chapter05/04_album_module/albums/japan2010/picture_006.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter05/04_album_module/albums/japan2010/picture_007.jpg b/Chapter05/04_album_module/albums/japan2010/picture_007.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter05/04_album_module/test_album_mgr.js b/Chapter05/04_album_module/test_album_mgr.js new file mode 100644 index 0000000..547df03 --- /dev/null +++ b/Chapter05/04_album_module/test_album_mgr.js @@ -0,0 +1,30 @@ + +var amgr = require('./album_mgr'); + + +amgr.albums('./', function (err, albums) { + if (err) { + console.log("Unexpected error: " + JSON.stringify(err)); + return; + } + + (function iterator(index) { + if (index == albums.length) { + console.log("Done"); + return; + } + + albums[index].photos(function (err, photos) { + if (err) { + console.log("Err loading album: " + JSON.stringify(err)); + return; + } + + console.log(albums[index].name); + console.log(photos); + console.log(""); + iterator(index + 1); + }); + })(0); +}); + diff --git a/Chapter05/05_series.js b/Chapter05/05_series.js new file mode 100644 index 0000000..0e81fe4 --- /dev/null +++ b/Chapter05/05_series.js @@ -0,0 +1,19 @@ + +var async = require("async"); + +async.series({ + + numbers: function (callback) { + setTimeout(function () { + callback(null, [ 1, 2, 3 ]); + }, 1500); + }, + strings: function (callback) { + setTimeout(function () { + callback(null, [ "a", "b", "c" ]); + }, 2000); + } +}, +function (err, results) { + console.log(results); +}); diff --git a/Chapter05/06_parallel.js b/Chapter05/06_parallel.js new file mode 100644 index 0000000..9ed0b8f --- /dev/null +++ b/Chapter05/06_parallel.js @@ -0,0 +1,19 @@ + +var async = require("async"); + +async.parallel({ + + numbers: function (callback) { + setTimeout(function () { + callback(null, [ 1, 2, 3 ]); + }, 1500); + }, + strings: function (callback) { + setTimeout(function () { + callback(null, [ "a", "b", "c" ]); + }, 2000); + } +}, +function (err, results) { + console.log(results); +}); diff --git a/Chapter05/07_auto.js b/Chapter05/07_auto.js new file mode 100644 index 0000000..d2facf2 --- /dev/null +++ b/Chapter05/07_auto.js @@ -0,0 +1,31 @@ + +var async = require("async"); + +async.auto({ + + numbers: function (callback) { + setTimeout(function () { + callback(null, [ 1, 2, 3 ]); + }, 1500); + }, + strings: function (callback) { + setTimeout(function () { + callback(null, [ "a", "b", "c" ]); + }, 2000); + }, + assemble: [ 'numbers', 'strings', function (callback, thus_far) { + callback(null, { + numbers: thus_far.numbers.join(", "), + strings: "'" + thus_far.strings.join("', '") + "'" + }); + }] +}, +function (err, results) { + if (err) + console.log(err); + else + console.log(results); +} + +); + diff --git a/Chapter05/08_async_vs_no_async.js b/Chapter05/08_async_vs_no_async.js new file mode 100644 index 0000000..fa4c522 --- /dev/null +++ b/Chapter05/08_async_vs_no_async.js @@ -0,0 +1,110 @@ + +var fs = require('fs'); +var async = require('async'); + + +function load_file_contents(path, callback) { + fs.open(path, 'r', function (err, f) { + if (err) { + callback(err); + return; + } else if (!f) { + callback(make_error("invalid_handle", + "bad file handle from fs.open")); + return; + } + fs.fstat(f, function (err, stats) { + if (err) { + callback(err); + return; + } + if (stats.isFile()) { + var b = new Buffer(10000); + fs.read(f, b, 0, 10000, null, function (err, br, buf) { + if (err) { + callback(err); + return; + } + + fs.close(f, function (err) { + if (err) { + callback(err); + return; + } + callback(null, b.toString('utf8', 0, br)); + }); + }); + } else { + calback(make_error("not_file", "Can't load directory")); + return; + } + }); + }); +} + + + +function load_file_contents2(path, callback) { + var f; + async.waterfall([ + function (cb) { // cb stands for "callback" + fs.open(path, 'r', cb); + }, + // the handle was passed to the callback at the end of + // the fs.open function call. async passes ALL params to us. + function (handle, cb) { + f = handle + fs.fstat(f, cb); + }, + function (stats, cb) { + var b = new Buffer(100000); + if (stats.isFile()) { + fs.read(f, b, 0, 100000, null, cb); + } else { + calback(make_error("not_file", "Can't load directory")); + } + }, + function (bytes_read, buffer, cb) { + fs.close(f, function (err) { + if (err) + cb(err); + else + cb(null, buffer.toString('utf8', 0, bytes_read)); + }) + } + ], + // called after all fns have finished, or then there is an error. + function (err, file_contents) { + callback(err, file_contents); + }); +} + + + + +load_file_contents( + "test.txt", + function (err, contents) { + if (err) + console.log(err); + else + console.log(contents); + } +); + +load_file_contents2( + "test.txt", + function (err, contents) { + if (err) + console.log(err); + else + console.log(contents); + } +); + +function make_error(err, msg) { + var e = new Error(msg); + e.code = msg; + return e; +} + diff --git a/Chapter05/package.json b/Chapter05/package.json new file mode 100644 index 0000000..a91dee5 --- /dev/null +++ b/Chapter05/package.json @@ -0,0 +1,9 @@ +{ + "name": "Modules-Demo", + "description": "Demonstrates Using Modules, specificaly async", + "version": "0.0.1", + "private": true, + "dependencies": { + "async": "0.1.x" + } +} diff --git a/Chapter05/test.txt b/Chapter05/test.txt new file mode 100644 index 0000000..340fc4c --- /dev/null +++ b/Chapter05/test.txt @@ -0,0 +1,2 @@ +Is that how you get ants, Barry? +Yes it is, other Barry. diff --git a/Chapter06/01_simple_stream.js b/Chapter06/01_simple_stream.js new file mode 100644 index 0000000..e17a0b1 --- /dev/null +++ b/Chapter06/01_simple_stream.js @@ -0,0 +1,32 @@ +// before we used read(), now we'll use streams + +var fs = require('fs'); +var contents; + +// INCEPTION BWAAAAAAA!!!! +var rs = fs.createReadStream("01_simple_stream.js"); + +rs.on('readable', function () { + var str; + var d = rs.read(); + if (d) { + if (typeof d == 'string') { + str = d; + } else if (typeof d == 'object' && d instanceof Buffer) { + str = d.toString('utf8'); + } + if (str) { + if (!contents) + contents = d; + else + contents += str; + } + } +}); + +rs.on('end', function () { + console.log("read in the file contents: "); + console.log(contents.toString('utf8')); +}); + + diff --git a/Chapter06/01x_old_streams/01_simple_stream.js b/Chapter06/01x_old_streams/01_simple_stream.js new file mode 100644 index 0000000..739c80c --- /dev/null +++ b/Chapter06/01x_old_streams/01_simple_stream.js @@ -0,0 +1,21 @@ +// before we used read(), now we'll use streams + +var fs = require('fs'); +var contents; + +// INCEPTION BWAAAAAAA!!!! +var rs = fs.createReadStream("01_simple_stream.js"); + +rs.on('data', function (data) { + if (!contents) + contents = data; + else + contents = contents.concat(data); +}); + +rs.on('end', function () { + console.log("read in the file contents: "); + console.log(contents.toString('utf8')); +}); + + diff --git a/Chapter06/02_static_content_server.js b/Chapter06/02_static_content_server.js new file mode 100644 index 0000000..e76bdbb --- /dev/null +++ b/Chapter06/02_static_content_server.js @@ -0,0 +1,74 @@ +var http = require('http'), + path = require('path'), + fs = require('fs'); + + +function handle_incoming_request(req, res) { + if (req.method.toLowerCase() == 'get' + && req.url.substring(0, 9) == '/content/') { + serve_static_file(req.url.substring(9), res); + } else { + res.writeHead(404, { "Content-Type" : "application/json" }); + + var out = { error: "not_found", + message: "'" + req.url + "' not found" }; + res.end(JSON.stringify(out) + "\n"); + } +} + + +function serve_static_file(file, res) { + var rs = fs.createReadStream(file); + var ct = content_type_for_path(file); + res.writeHead(200, { "Content-Type" : ct }); + + rs.on( + 'error', + function (e) { + res.writeHead(404, { "Content-Type" : "application/json" }); + var out = { error: "not_found", + message: "'" + file + "' not found" }; + res.end(JSON.stringify(out) + "\n"); + return; + } + ); + + rs.on( + 'readable', + function () { + var d = rs.read(); + if (d) { + if (typeof d == 'string') + res.write(d); + else if (typeof d == 'object' && d instanceof Buffer) + res.write(d.toString('utf8')); + } + } + ); + + rs.on( + 'end', + function () { + res.end(); // we're done!!! + } + ); +} + + +function content_type_for_path (file) { + var ext = path.extname(file); + switch (ext.toLowerCase()) { + case '.html': return "text/html"; + case ".js": return "text/javascript"; + case ".css": return 'text/css'; + case '.jpg': case '.jpeg': return 'image/jpeg'; + default: return 'text/plain'; + } +} + + + +var s = http.createServer(handle_incoming_request); + +s.listen(8080); + diff --git a/Chapter06/03_static_content_pauses.js b/Chapter06/03_static_content_pauses.js new file mode 100644 index 0000000..d9c61f1 --- /dev/null +++ b/Chapter06/03_static_content_pauses.js @@ -0,0 +1,73 @@ +var http = require('http'), + path = require('path'), + fs = require('fs'); + + +function handle_incoming_request(req, res) { + if (req.method.toLowerCase() == 'get' + && req.url.substring(0, 9) == '/content/') { + serve_static_file(req.url.substring(9), res); + } else { + res.writeHead(404, { "Content-Type" : "application/json" }); + + var out = { error: "not_found", + message: "'" + req.url + "' not found" }; + res.end(JSON.stringify(out) + "\n"); + } +} + + +function serve_static_file(file, res) { + var rs = fs.createReadStream(file); + + var ct = content_type_for_path(file); + res.writeHead(200, { "Content-Type" : ct }); + + rs.on( + 'error', + function (e) { + res.writeHead(404, { "Content-Type" : "application/json" }); + var out = { error: "not_found", + message: "'" + file + "' not found" }; + res.end(JSON.stringify(out) + "\n"); + } + ); + + rs.on( + 'readable', + function () { + var data = rs.read(); + if (!res.write(data)) { + rs.pause(); + } + } + ); + + res.on('drain', function () { + rs.resume(); + }); + + rs.on( + 'end', + function () { + res.end(); // we're done!!! + } + ); +} + +function content_type_for_path (file) { + var ext = path.extname(file); + switch (ext.toLowerCase()) { + case '.html': return "text/html"; + case ".js": return "text/javascript"; + case ".css": return 'text/css'; + case '.jpg': case '.jpeg': return 'image/jpeg'; + default: return 'text/plain'; + } +} + + +var s = http.createServer(handle_incoming_request); + +s.listen(8080); + diff --git a/Chapter06/04_pipe.js b/Chapter06/04_pipe.js new file mode 100644 index 0000000..6e1bc4e --- /dev/null +++ b/Chapter06/04_pipe.js @@ -0,0 +1,54 @@ +var http = require('http'), + path = require('path'), + fs = require('fs'); + + +function handle_incoming_request(req, res) { + if (req.method.toLowerCase() == 'get' + && req.url.substring(0, 9) == '/content/') { + serve_static_file(req.url.substring(9), res); + } else { + res.writeHead(404, { "Content-Type" : "application/json" }); + + var out = { error: "not_found", + message: "'" + req.url + "' not found" }; + res.end(JSON.stringify(out) + "\n"); + } +} + + +function serve_static_file(file, res) { + var rs = fs.createReadStream(file); + var ct = content_type_for_path(file); + res.writeHead(200, { "Content-Type" : ct }); + + rs.on( + 'error', + function (e) { + res.writeHead(404, { "Content-Type" : "application/json" }); + var out = { error: "not_found", + message: "'" + file + "' not found" }; + res.end(JSON.stringify(out) + "\n"); + return; + } + ); + + rs.pipe(res); +} + +function content_type_for_path (file) { + var ext = path.extname(file); + switch (ext.toLowerCase()) { + case '.html': return "text/html"; + case ".js": return "text/javascript"; + case ".css": return 'text/css'; + case '.jpg': case '.jpeg': return 'image/jpeg'; + default: return 'text/plain'; + } +} + + +var s = http.createServer(handle_incoming_request); + +s.listen(8080); + diff --git a/Chapter06/05_server_static.js b/Chapter06/05_server_static.js new file mode 100644 index 0000000..0bac4d1 --- /dev/null +++ b/Chapter06/05_server_static.js @@ -0,0 +1,232 @@ +var http = require('http'), + path = require("path"), + fs = require('fs'), + url = require('url'); + + +function serve_static_file(file, res) { + var rs = fs.createReadStream("content/" + file); + var ct = content_type_for_path(file); + res.writeHead(200, { "Content-Type" : ct }); + + rs.on( + 'error', + function (e) { + res.writeHead(404, { "Content-Type" : "application/json" }); + var out = { error: "not_found", + message: "'" + file + "' not found" }; + res.end(JSON.stringify(out) + "\n"); + return; + } + ); + + rs.pipe(res); +} + + +function content_type_for_path (file) { + var ext = path.extname(file); + switch (ext.toLowerCase()) { + case '.html': return "text/html"; + case ".js": return "text/javascript"; + case ".css": return 'text/css'; + case '.jpg': case '.jpeg': return 'image/jpeg'; + case '.png': return "image/png"; + default: return 'text/plain'; + } +} + + + +function load_album_list(callback) { + // we will just assume that any directory in our 'albums' + // subfolder is an album. + fs.readdir( + "albums", + function (err, files) { + if (err) { + callback(make_error("file_error"), JSON.stringify(err)); + return; + } + + var only_dirs = []; + + (function iterator(index) { + if (index == files.length) { + callback(null, only_dirs); + return; + } + + fs.stat( + "albums/" + files[index], + function (err, stats) { + if (err) { + callback(make_error("file_error", + JSON.stringify(err))); + return; + } + if (stats.isDirectory()) { + var obj = { name: files[index] }; + only_dirs.push(obj); + } + iterator(index + 1) + } + ); + })(0); + } + ); +} + +function load_album(album_name, page, page_size, callback) { + fs.readdir( + "albums/" + album_name, + function (err, files) { + if (err) { + if (err.code == "ENOENT") { + callback(no_such_album()); + } else { + callback(make_error("file_error", + JSON.stringify(err))); + } + return; + } + + var only_files = []; + + (function iterator(index) { + if (index == files.length) { + var ps; + // slice fails gracefully if params are out of range + ps = only_files.splice(page * page_size, page_size); + var obj = { short_name: album_name, + photos: ps }; + callback(null, obj); + return; + } + + var path = "albums/" + album_name + "/"; + + fs.stat( + path + files[index], + function (err, stats) { + if (err) { + callback(make_error("file_error", + JSON.stringify(err))); + return; + } + if (stats.isFile()) { + var obj = { filename: files[index], desc: files[index] }; + only_files.push(obj); + } + iterator(index + 1) + } + ); + })(0); + } + ); +} + +function handle_incoming_request(req, res) { + + // parse the query params into an object and get the path + // without them. (2nd param true = parse the params). + req.parsed_url = url.parse(req.url, true); + var core_url = req.parsed_url.pathname; + + // test this fixed url to see what they're asking for + if (req.method.toLowerCase() == 'get' + && req.url.substring(0, 9) == '/content/') { + serve_static_file(req.url.substring(9), res); + } else if (core_url == '/albums.json') { + handle_list_albums(req, res); + } else if (core_url.substr(0, 7) == '/albums' + && core_url.substr(core_url.length - 5) == '.json') { + handle_get_album(req, res); + } else { + send_failure(res, 404, invalid_resource()); + } +} + +function handle_list_albums(req, res) { + load_album_list(function (err, albums) { + if (err) { + send_failure(res, 500, err); + return; + } + + send_success(res, { albums: albums }); + }); +} + +function handle_get_album(req, res) { + + // get the GET params + var getp = get_query_params(req); + var page_num = getp.page ? getp.page : 0; + var page_size = getp.page_size ? getp.page_size : 1000; + + if (isNaN(parseInt(page_num))) page_num = 0; + if (isNaN(parseInt(page_size))) page_size = 1000; + + // format of request is /albums/album_name.json + var core_url = req.parsed_url.pathname; + + var album_name = core_url.substr(7, core_url.length - 12); + load_album( + album_name, + page_num, + page_size, + function (err, album_contents) { + if (err && err == "no_such_album") { + send_failure(res, 404, err); + } else if (err) { + send_failure(res, 500, err); + } else { + send_success(res, { album_photos: album_contents }); + } + } + ); +} + + + + +function make_error(err, msg) { + var e = new Error(msg); + e.code = err; + return e; +} + +function send_success(res, data) { + res.writeHead(200, {"Content-Type": "application/json"}); + var output = { error: null, data: data }; + res.end(JSON.stringify(output) + "\n"); +} + +function send_failure(res, code, err) { + var code = (err.code) ? err.code : err.name; + res.writeHead(code, { "Content-Type" : "application/json" }); + res.end(JSON.stringify({ error: code, message: err.message }) + "\n"); +} + + +function invalid_resource() { + return make_error("invalid_resource", + "the requested resource does not exist."); +} + +function no_such_album() { + return make_error("no_such_album", + "The specified album does not exist"); +} + + +function get_query_params(req) { + return req.parsed_url.query; +} + + + + +var s = http.createServer(handle_incoming_request); +s.listen(8080); diff --git a/Chapter06/06_writing_a_file.js b/Chapter06/06_writing_a_file.js new file mode 100644 index 0000000..a9d9acf --- /dev/null +++ b/Chapter06/06_writing_a_file.js @@ -0,0 +1,14 @@ +// before we used read(), now we'll use streams + +var fs = require('fs'); +var contents; + +// INCEPTION BWAAAAAAA!!!! +var rs = fs.createReadStream("01_simple_stream.js"); +var ws = fs.createWriteStream("copy of 01_simple_stream.js"); + + +rs.pipe(ws); + + + diff --git a/Chapter06/albums/australia2010/aus_01.jpg b/Chapter06/albums/australia2010/aus_01.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter06/albums/australia2010/aus_02.jpg b/Chapter06/albums/australia2010/aus_02.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter06/albums/australia2010/aus_03.jpg b/Chapter06/albums/australia2010/aus_03.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter06/albums/australia2010/aus_04.jpg b/Chapter06/albums/australia2010/aus_04.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter06/albums/australia2010/aus_05.jpg b/Chapter06/albums/australia2010/aus_05.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter06/albums/australia2010/aus_06.jpg b/Chapter06/albums/australia2010/aus_06.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter06/albums/australia2010/aus_07.jpg b/Chapter06/albums/australia2010/aus_07.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter06/albums/australia2010/aus_08.jpg b/Chapter06/albums/australia2010/aus_08.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter06/albums/australia2010/aus_09.jpg b/Chapter06/albums/australia2010/aus_09.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter06/albums/info.txt b/Chapter06/albums/info.txt new file mode 100644 index 0000000..e69de29 diff --git a/Chapter06/albums/italy2012/picture_01.jpg b/Chapter06/albums/italy2012/picture_01.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter06/albums/italy2012/picture_02.jpg b/Chapter06/albums/italy2012/picture_02.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter06/albums/italy2012/picture_03.jpg b/Chapter06/albums/italy2012/picture_03.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter06/albums/italy2012/picture_04.jpg b/Chapter06/albums/italy2012/picture_04.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter06/albums/italy2012/picture_05.jpg b/Chapter06/albums/italy2012/picture_05.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter06/albums/japan2010/picture_001.jpg b/Chapter06/albums/japan2010/picture_001.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter06/albums/japan2010/picture_002.jpg b/Chapter06/albums/japan2010/picture_002.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter06/albums/japan2010/picture_003.jpg b/Chapter06/albums/japan2010/picture_003.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter06/albums/japan2010/picture_004.jpg b/Chapter06/albums/japan2010/picture_004.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter06/albums/japan2010/picture_005.jpg b/Chapter06/albums/japan2010/picture_005.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter06/albums/japan2010/picture_006.jpg b/Chapter06/albums/japan2010/picture_006.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter06/albums/japan2010/picture_007.jpg b/Chapter06/albums/japan2010/picture_007.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter06/buffer_sidebar.js b/Chapter06/buffer_sidebar.js new file mode 100644 index 0000000..5340e23 --- /dev/null +++ b/Chapter06/buffer_sidebar.js @@ -0,0 +1,25 @@ + + +var b = new Buffer(10000); +var str = "我叫王马克"; + +b.write(str); // default is utf8, which is what we want + +console.log( b.length ); + + +// byteLength is useful for working with UTF-8 and buffers +console.log( str.length ); +console.log( Buffer.byteLength(str) ); + + +var b1 = new Buffer("My name is "); +var b2 = new Buffer("Marc"); +var b3 = Buffer.concat([ b1, b2 ]); +console.log(b3.toString('utf8')); + + +var bb = new Buffer(100); +bb.fill("\0"); + +console.log(bb.readInt8(0)); diff --git a/Chapter06/content/album.js b/Chapter06/content/album.js new file mode 100644 index 0000000..218d444 --- /dev/null +++ b/Chapter06/content/album.js @@ -0,0 +1,46 @@ +$(function(){ + + var tmpl, // Main template HTML + tdata = {}; // JSON data object that feeds the template + + // Initialise page + var initPage = function() { + + // get our album name. + parts = window.location.href.split("/"); + var album_name = parts[5]; + + // Load the HTML template + $.get("/templates/album.html", function(d){ + tmpl = d; + }); + + // Retrieve the server data and then initialise the page + $.getJSON("/v1/albums/" + album_name + ".json", function (d) { + var photo_d = massage_album(d); + $.extend(tdata, photo_d); + }); + + // When AJAX calls are complete parse the template + // replacing mustache tags with vars + $(document).ajaxStop(function () { + var renderedPage = Mustache.to_html( tmpl, tdata ); + $("body").html( renderedPage ); + }) + }(); +}); + + + +function massage_album(d) { + if (d.error != null) return d; + var obj = { photos: [] }; + + var af = d.data.album_data; + + for (var i = 0; i < af.photos.length; i++) { + var url = "/albums/" + af.short_name + "/" + af.photos[i]; + obj.photos.push({ url: url, desc: af.photos[i] }); + } + return obj; +} diff --git a/Chapter06/content/jquery.mustache.js b/Chapter06/content/jquery.mustache.js new file mode 100644 index 0000000..4d3c952 --- /dev/null +++ b/Chapter06/content/jquery.mustache.js @@ -0,0 +1,648 @@ +/* +Shameless port of a shameless port +@defunkt => @janl => @aq + +See http://github.com/defunkt/mustache for more info. +*/ + +;(function($) { + +/*! + * mustache.js - Logic-less {{mustache}} templates with JavaScript + * http://github.com/janl/mustache.js + */ + +/*global define: false*/ + +var Mustache; + +(function (exports) { + if (typeof module !== "undefined" && module.exports) { + module.exports = exports; // CommonJS + } else if (typeof define === "function") { + define(exports); // AMD + } else { + Mustache = exports; // + + + + + + + diff --git a/Chapter06/templates/content/album.js b/Chapter06/templates/content/album.js new file mode 100644 index 0000000..0dbb4d7 --- /dev/null +++ b/Chapter06/templates/content/album.js @@ -0,0 +1,44 @@ +$(function(){ + + var tmpl, // Main template HTML + tdata = {}; // JSON data object that feeds the template + + // Initialise page + var initPage = function() { + + // get our album name. + parts = window.location.href.split("/"); + var album_name = parts[5]; + + // Load the HTML template + $.get("/templates/album.html", function(d){ + tmpl = d; + }); + + // Retrieve the server data and then initialise the page + $.getJSON("/albums/" + album_name + ".json", function (d) { + var photo_d = massage_album(d); + $.extend(tdata, photo_d); + }); + + // When AJAX calls are complete parse the template + // replacing mustache tags with vars + $(document).ajaxStop(function () { + var renderedPage = Mustache.to_html( tmpl, tdata ); + $("body").html( renderedPage ); + }) + }(); +}); + +function massage_album(d) { + if (d.error != null) return d; + var obj = { photos: [] }; + + var af = d.data.album_data; + + for (var i = 0; i < af.photos.length; i++) { + var url = "/albums/" + af.short_name + "/" + af.photos[i].filename; + obj.photos.push({ url: url, desc: af.photos[i].filename }); + } + return obj; +} diff --git a/Chapter06/templates/content/home.js b/Chapter06/templates/content/home.js new file mode 100644 index 0000000..1dbc5ac --- /dev/null +++ b/Chapter06/templates/content/home.js @@ -0,0 +1,27 @@ +$(function(){ + + var tmpl, // Main template HTML + tdata = {}; // JSON data object that feeds the template + + // Initialise page + var initPage = function() { + + // Load the HTML template + $.get("/templates/home.html", function(d){ + tmpl = d; + }); + + // Retrieve the server data and then initialise the page + $.getJSON("/albums.json", function (d) { + $.extend(tdata, d.data); + }); + + // When AJAX calls are complete parse the template + // replacing mustache tags with vars + $(document).ajaxStop(function () { + var renderedPage = Mustache.to_html( tmpl, tdata ); + $("body").html( renderedPage ); + }) + }(); +}); + diff --git a/Chapter06/templates/content/jquery-1.8.3.min.js b/Chapter06/templates/content/jquery-1.8.3.min.js new file mode 100644 index 0000000..83589da --- /dev/null +++ b/Chapter06/templates/content/jquery-1.8.3.min.js @@ -0,0 +1,2 @@ +/*! jQuery v1.8.3 jquery.com | jquery.org/license */ +(function(e,t){function _(e){var t=M[e]={};return v.each(e.split(y),function(e,n){t[n]=!0}),t}function H(e,n,r){if(r===t&&e.nodeType===1){var i="data-"+n.replace(P,"-$1").toLowerCase();r=e.getAttribute(i);if(typeof r=="string"){try{r=r==="true"?!0:r==="false"?!1:r==="null"?null:+r+""===r?+r:D.test(r)?v.parseJSON(r):r}catch(s){}v.data(e,n,r)}else r=t}return r}function B(e){var t;for(t in e){if(t==="data"&&v.isEmptyObject(e[t]))continue;if(t!=="toJSON")return!1}return!0}function et(){return!1}function tt(){return!0}function ut(e){return!e||!e.parentNode||e.parentNode.nodeType===11}function at(e,t){do e=e[t];while(e&&e.nodeType!==1);return e}function ft(e,t,n){t=t||0;if(v.isFunction(t))return v.grep(e,function(e,r){var i=!!t.call(e,r,e);return i===n});if(t.nodeType)return v.grep(e,function(e,r){return e===t===n});if(typeof t=="string"){var r=v.grep(e,function(e){return e.nodeType===1});if(it.test(t))return v.filter(t,r,!n);t=v.filter(t,r)}return v.grep(e,function(e,r){return v.inArray(e,t)>=0===n})}function lt(e){var t=ct.split("|"),n=e.createDocumentFragment();if(n.createElement)while(t.length)n.createElement(t.pop());return n}function Lt(e,t){return e.getElementsByTagName(t)[0]||e.appendChild(e.ownerDocument.createElement(t))}function At(e,t){if(t.nodeType!==1||!v.hasData(e))return;var n,r,i,s=v._data(e),o=v._data(t,s),u=s.events;if(u){delete o.handle,o.events={};for(n in u)for(r=0,i=u[n].length;r").appendTo(i.body),n=t.css("display");t.remove();if(n==="none"||n===""){Pt=i.body.appendChild(Pt||v.extend(i.createElement("iframe"),{frameBorder:0,width:0,height:0}));if(!Ht||!Pt.createElement)Ht=(Pt.contentWindow||Pt.contentDocument).document,Ht.write(""),Ht.close();t=Ht.body.appendChild(Ht.createElement(e)),n=Dt(t,"display"),i.body.removeChild(Pt)}return Wt[e]=n,n}function fn(e,t,n,r){var i;if(v.isArray(t))v.each(t,function(t,i){n||sn.test(e)?r(e,i):fn(e+"["+(typeof i=="object"?t:"")+"]",i,n,r)});else if(!n&&v.type(t)==="object")for(i in t)fn(e+"["+i+"]",t[i],n,r);else r(e,t)}function Cn(e){return function(t,n){typeof t!="string"&&(n=t,t="*");var r,i,s,o=t.toLowerCase().split(y),u=0,a=o.length;if(v.isFunction(n))for(;u)[^>]*$|#([\w\-]*)$)/,E=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,S=/^[\],:{}\s]*$/,x=/(?:^|:|,)(?:\s*\[)+/g,T=/\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,N=/"[^"\\\r\n]*"|true|false|null|-?(?:\d\d*\.|)\d+(?:[eE][\-+]?\d+|)/g,C=/^-ms-/,k=/-([\da-z])/gi,L=function(e,t){return(t+"").toUpperCase()},A=function(){i.addEventListener?(i.removeEventListener("DOMContentLoaded",A,!1),v.ready()):i.readyState==="complete"&&(i.detachEvent("onreadystatechange",A),v.ready())},O={};v.fn=v.prototype={constructor:v,init:function(e,n,r){var s,o,u,a;if(!e)return this;if(e.nodeType)return this.context=this[0]=e,this.length=1,this;if(typeof e=="string"){e.charAt(0)==="<"&&e.charAt(e.length-1)===">"&&e.length>=3?s=[null,e,null]:s=w.exec(e);if(s&&(s[1]||!n)){if(s[1])return n=n instanceof v?n[0]:n,a=n&&n.nodeType?n.ownerDocument||n:i,e=v.parseHTML(s[1],a,!0),E.test(s[1])&&v.isPlainObject(n)&&this.attr.call(e,n,!0),v.merge(this,e);o=i.getElementById(s[2]);if(o&&o.parentNode){if(o.id!==s[2])return r.find(e);this.length=1,this[0]=o}return this.context=i,this.selector=e,this}return!n||n.jquery?(n||r).find(e):this.constructor(n).find(e)}return v.isFunction(e)?r.ready(e):(e.selector!==t&&(this.selector=e.selector,this.context=e.context),v.makeArray(e,this))},selector:"",jquery:"1.8.3",length:0,size:function(){return this.length},toArray:function(){return l.call(this)},get:function(e){return e==null?this.toArray():e<0?this[this.length+e]:this[e]},pushStack:function(e,t,n){var r=v.merge(this.constructor(),e);return r.prevObject=this,r.context=this.context,t==="find"?r.selector=this.selector+(this.selector?" ":"")+n:t&&(r.selector=this.selector+"."+t+"("+n+")"),r},each:function(e,t){return v.each(this,e,t)},ready:function(e){return v.ready.promise().done(e),this},eq:function(e){return e=+e,e===-1?this.slice(e):this.slice(e,e+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(l.apply(this,arguments),"slice",l.call(arguments).join(","))},map:function(e){return this.pushStack(v.map(this,function(t,n){return e.call(t,n,t)}))},end:function(){return this.prevObject||this.constructor(null)},push:f,sort:[].sort,splice:[].splice},v.fn.init.prototype=v.fn,v.extend=v.fn.extend=function(){var e,n,r,i,s,o,u=arguments[0]||{},a=1,f=arguments.length,l=!1;typeof u=="boolean"&&(l=u,u=arguments[1]||{},a=2),typeof u!="object"&&!v.isFunction(u)&&(u={}),f===a&&(u=this,--a);for(;a0)return;r.resolveWith(i,[v]),v.fn.trigger&&v(i).trigger("ready").off("ready")},isFunction:function(e){return v.type(e)==="function"},isArray:Array.isArray||function(e){return v.type(e)==="array"},isWindow:function(e){return e!=null&&e==e.window},isNumeric:function(e){return!isNaN(parseFloat(e))&&isFinite(e)},type:function(e){return e==null?String(e):O[h.call(e)]||"object"},isPlainObject:function(e){if(!e||v.type(e)!=="object"||e.nodeType||v.isWindow(e))return!1;try{if(e.constructor&&!p.call(e,"constructor")&&!p.call(e.constructor.prototype,"isPrototypeOf"))return!1}catch(n){return!1}var r;for(r in e);return r===t||p.call(e,r)},isEmptyObject:function(e){var t;for(t in e)return!1;return!0},error:function(e){throw new Error(e)},parseHTML:function(e,t,n){var r;return!e||typeof e!="string"?null:(typeof t=="boolean"&&(n=t,t=0),t=t||i,(r=E.exec(e))?[t.createElement(r[1])]:(r=v.buildFragment([e],t,n?null:[]),v.merge([],(r.cacheable?v.clone(r.fragment):r.fragment).childNodes)))},parseJSON:function(t){if(!t||typeof t!="string")return null;t=v.trim(t);if(e.JSON&&e.JSON.parse)return e.JSON.parse(t);if(S.test(t.replace(T,"@").replace(N,"]").replace(x,"")))return(new Function("return "+t))();v.error("Invalid JSON: "+t)},parseXML:function(n){var r,i;if(!n||typeof n!="string")return null;try{e.DOMParser?(i=new DOMParser,r=i.parseFromString(n,"text/xml")):(r=new ActiveXObject("Microsoft.XMLDOM"),r.async="false",r.loadXML(n))}catch(s){r=t}return(!r||!r.documentElement||r.getElementsByTagName("parsererror").length)&&v.error("Invalid XML: "+n),r},noop:function(){},globalEval:function(t){t&&g.test(t)&&(e.execScript||function(t){e.eval.call(e,t)})(t)},camelCase:function(e){return e.replace(C,"ms-").replace(k,L)},nodeName:function(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()},each:function(e,n,r){var i,s=0,o=e.length,u=o===t||v.isFunction(e);if(r){if(u){for(i in e)if(n.apply(e[i],r)===!1)break}else for(;s0&&e[0]&&e[a-1]||a===0||v.isArray(e));if(f)for(;u-1)a.splice(n,1),i&&(n<=o&&o--,n<=u&&u--)}),this},has:function(e){return v.inArray(e,a)>-1},empty:function(){return a=[],this},disable:function(){return a=f=n=t,this},disabled:function(){return!a},lock:function(){return f=t,n||c.disable(),this},locked:function(){return!f},fireWith:function(e,t){return t=t||[],t=[e,t.slice?t.slice():t],a&&(!r||f)&&(i?f.push(t):l(t)),this},fire:function(){return c.fireWith(this,arguments),this},fired:function(){return!!r}};return c},v.extend({Deferred:function(e){var t=[["resolve","done",v.Callbacks("once memory"),"resolved"],["reject","fail",v.Callbacks("once memory"),"rejected"],["notify","progress",v.Callbacks("memory")]],n="pending",r={state:function(){return n},always:function(){return i.done(arguments).fail(arguments),this},then:function(){var e=arguments;return v.Deferred(function(n){v.each(t,function(t,r){var s=r[0],o=e[t];i[r[1]](v.isFunction(o)?function(){var e=o.apply(this,arguments);e&&v.isFunction(e.promise)?e.promise().done(n.resolve).fail(n.reject).progress(n.notify):n[s+"With"](this===i?n:this,[e])}:n[s])}),e=null}).promise()},promise:function(e){return e!=null?v.extend(e,r):r}},i={};return r.pipe=r.then,v.each(t,function(e,s){var o=s[2],u=s[3];r[s[1]]=o.add,u&&o.add(function(){n=u},t[e^1][2].disable,t[2][2].lock),i[s[0]]=o.fire,i[s[0]+"With"]=o.fireWith}),r.promise(i),e&&e.call(i,i),i},when:function(e){var t=0,n=l.call(arguments),r=n.length,i=r!==1||e&&v.isFunction(e.promise)?r:0,s=i===1?e:v.Deferred(),o=function(e,t,n){return function(r){t[e]=this,n[e]=arguments.length>1?l.call(arguments):r,n===u?s.notifyWith(t,n):--i||s.resolveWith(t,n)}},u,a,f;if(r>1){u=new Array(r),a=new Array(r),f=new Array(r);for(;t
a",n=p.getElementsByTagName("*"),r=p.getElementsByTagName("a")[0];if(!n||!r||!n.length)return{};s=i.createElement("select"),o=s.appendChild(i.createElement("option")),u=p.getElementsByTagName("input")[0],r.style.cssText="top:1px;float:left;opacity:.5",t={leadingWhitespace:p.firstChild.nodeType===3,tbody:!p.getElementsByTagName("tbody").length,htmlSerialize:!!p.getElementsByTagName("link").length,style:/top/.test(r.getAttribute("style")),hrefNormalized:r.getAttribute("href")==="/a",opacity:/^0.5/.test(r.style.opacity),cssFloat:!!r.style.cssFloat,checkOn:u.value==="on",optSelected:o.selected,getSetAttribute:p.className!=="t",enctype:!!i.createElement("form").enctype,html5Clone:i.createElement("nav").cloneNode(!0).outerHTML!=="<:nav>",boxModel:i.compatMode==="CSS1Compat",submitBubbles:!0,changeBubbles:!0,focusinBubbles:!1,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0,boxSizingReliable:!0,pixelPosition:!1},u.checked=!0,t.noCloneChecked=u.cloneNode(!0).checked,s.disabled=!0,t.optDisabled=!o.disabled;try{delete p.test}catch(d){t.deleteExpando=!1}!p.addEventListener&&p.attachEvent&&p.fireEvent&&(p.attachEvent("onclick",h=function(){t.noCloneEvent=!1}),p.cloneNode(!0).fireEvent("onclick"),p.detachEvent("onclick",h)),u=i.createElement("input"),u.value="t",u.setAttribute("type","radio"),t.radioValue=u.value==="t",u.setAttribute("checked","checked"),u.setAttribute("name","t"),p.appendChild(u),a=i.createDocumentFragment(),a.appendChild(p.lastChild),t.checkClone=a.cloneNode(!0).cloneNode(!0).lastChild.checked,t.appendChecked=u.checked,a.removeChild(u),a.appendChild(p);if(p.attachEvent)for(l in{submit:!0,change:!0,focusin:!0})f="on"+l,c=f in p,c||(p.setAttribute(f,"return;"),c=typeof p[f]=="function"),t[l+"Bubbles"]=c;return v(function(){var n,r,s,o,u="padding:0;margin:0;border:0;display:block;overflow:hidden;",a=i.getElementsByTagName("body")[0];if(!a)return;n=i.createElement("div"),n.style.cssText="visibility:hidden;border:0;width:0;height:0;position:static;top:0;margin-top:1px",a.insertBefore(n,a.firstChild),r=i.createElement("div"),n.appendChild(r),r.innerHTML="
t
",s=r.getElementsByTagName("td"),s[0].style.cssText="padding:0;margin:0;border:0;display:none",c=s[0].offsetHeight===0,s[0].style.display="",s[1].style.display="none",t.reliableHiddenOffsets=c&&s[0].offsetHeight===0,r.innerHTML="",r.style.cssText="box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;",t.boxSizing=r.offsetWidth===4,t.doesNotIncludeMarginInBodyOffset=a.offsetTop!==1,e.getComputedStyle&&(t.pixelPosition=(e.getComputedStyle(r,null)||{}).top!=="1%",t.boxSizingReliable=(e.getComputedStyle(r,null)||{width:"4px"}).width==="4px",o=i.createElement("div"),o.style.cssText=r.style.cssText=u,o.style.marginRight=o.style.width="0",r.style.width="1px",r.appendChild(o),t.reliableMarginRight=!parseFloat((e.getComputedStyle(o,null)||{}).marginRight)),typeof r.style.zoom!="undefined"&&(r.innerHTML="",r.style.cssText=u+"width:1px;padding:1px;display:inline;zoom:1",t.inlineBlockNeedsLayout=r.offsetWidth===3,r.style.display="block",r.style.overflow="visible",r.innerHTML="
",r.firstChild.style.width="5px",t.shrinkWrapBlocks=r.offsetWidth!==3,n.style.zoom=1),a.removeChild(n),n=r=s=o=null}),a.removeChild(p),n=r=s=o=u=a=p=null,t}();var D=/(?:\{[\s\S]*\}|\[[\s\S]*\])$/,P=/([A-Z])/g;v.extend({cache:{},deletedIds:[],uuid:0,expando:"jQuery"+(v.fn.jquery+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(e){return e=e.nodeType?v.cache[e[v.expando]]:e[v.expando],!!e&&!B(e)},data:function(e,n,r,i){if(!v.acceptData(e))return;var s,o,u=v.expando,a=typeof n=="string",f=e.nodeType,l=f?v.cache:e,c=f?e[u]:e[u]&&u;if((!c||!l[c]||!i&&!l[c].data)&&a&&r===t)return;c||(f?e[u]=c=v.deletedIds.pop()||v.guid++:c=u),l[c]||(l[c]={},f||(l[c].toJSON=v.noop));if(typeof n=="object"||typeof n=="function")i?l[c]=v.extend(l[c],n):l[c].data=v.extend(l[c].data,n);return s=l[c],i||(s.data||(s.data={}),s=s.data),r!==t&&(s[v.camelCase(n)]=r),a?(o=s[n],o==null&&(o=s[v.camelCase(n)])):o=s,o},removeData:function(e,t,n){if(!v.acceptData(e))return;var r,i,s,o=e.nodeType,u=o?v.cache:e,a=o?e[v.expando]:v.expando;if(!u[a])return;if(t){r=n?u[a]:u[a].data;if(r){v.isArray(t)||(t in r?t=[t]:(t=v.camelCase(t),t in r?t=[t]:t=t.split(" ")));for(i=0,s=t.length;i1,null,!1))},removeData:function(e){return this.each(function(){v.removeData(this,e)})}}),v.extend({queue:function(e,t,n){var r;if(e)return t=(t||"fx")+"queue",r=v._data(e,t),n&&(!r||v.isArray(n)?r=v._data(e,t,v.makeArray(n)):r.push(n)),r||[]},dequeue:function(e,t){t=t||"fx";var n=v.queue(e,t),r=n.length,i=n.shift(),s=v._queueHooks(e,t),o=function(){v.dequeue(e,t)};i==="inprogress"&&(i=n.shift(),r--),i&&(t==="fx"&&n.unshift("inprogress"),delete s.stop,i.call(e,o,s)),!r&&s&&s.empty.fire()},_queueHooks:function(e,t){var n=t+"queueHooks";return v._data(e,n)||v._data(e,n,{empty:v.Callbacks("once memory").add(function(){v.removeData(e,t+"queue",!0),v.removeData(e,n,!0)})})}}),v.fn.extend({queue:function(e,n){var r=2;return typeof e!="string"&&(n=e,e="fx",r--),arguments.length1)},removeAttr:function(e){return this.each(function(){v.removeAttr(this,e)})},prop:function(e,t){return v.access(this,v.prop,e,t,arguments.length>1)},removeProp:function(e){return e=v.propFix[e]||e,this.each(function(){try{this[e]=t,delete this[e]}catch(n){}})},addClass:function(e){var t,n,r,i,s,o,u;if(v.isFunction(e))return this.each(function(t){v(this).addClass(e.call(this,t,this.className))});if(e&&typeof e=="string"){t=e.split(y);for(n=0,r=this.length;n=0)r=r.replace(" "+n[s]+" "," ");i.className=e?v.trim(r):""}}}return this},toggleClass:function(e,t){var n=typeof e,r=typeof t=="boolean";return v.isFunction(e)?this.each(function(n){v(this).toggleClass(e.call(this,n,this.className,t),t)}):this.each(function(){if(n==="string"){var i,s=0,o=v(this),u=t,a=e.split(y);while(i=a[s++])u=r?u:!o.hasClass(i),o[u?"addClass":"removeClass"](i)}else if(n==="undefined"||n==="boolean")this.className&&v._data(this,"__className__",this.className),this.className=this.className||e===!1?"":v._data(this,"__className__")||""})},hasClass:function(e){var t=" "+e+" ",n=0,r=this.length;for(;n=0)return!0;return!1},val:function(e){var n,r,i,s=this[0];if(!arguments.length){if(s)return n=v.valHooks[s.type]||v.valHooks[s.nodeName.toLowerCase()],n&&"get"in n&&(r=n.get(s,"value"))!==t?r:(r=s.value,typeof r=="string"?r.replace(R,""):r==null?"":r);return}return i=v.isFunction(e),this.each(function(r){var s,o=v(this);if(this.nodeType!==1)return;i?s=e.call(this,r,o.val()):s=e,s==null?s="":typeof s=="number"?s+="":v.isArray(s)&&(s=v.map(s,function(e){return e==null?"":e+""})),n=v.valHooks[this.type]||v.valHooks[this.nodeName.toLowerCase()];if(!n||!("set"in n)||n.set(this,s,"value")===t)this.value=s})}}),v.extend({valHooks:{option:{get:function(e){var t=e.attributes.value;return!t||t.specified?e.value:e.text}},select:{get:function(e){var t,n,r=e.options,i=e.selectedIndex,s=e.type==="select-one"||i<0,o=s?null:[],u=s?i+1:r.length,a=i<0?u:s?i:0;for(;a=0}),n.length||(e.selectedIndex=-1),n}}},attrFn:{},attr:function(e,n,r,i){var s,o,u,a=e.nodeType;if(!e||a===3||a===8||a===2)return;if(i&&v.isFunction(v.fn[n]))return v(e)[n](r);if(typeof e.getAttribute=="undefined")return v.prop(e,n,r);u=a!==1||!v.isXMLDoc(e),u&&(n=n.toLowerCase(),o=v.attrHooks[n]||(X.test(n)?F:j));if(r!==t){if(r===null){v.removeAttr(e,n);return}return o&&"set"in o&&u&&(s=o.set(e,r,n))!==t?s:(e.setAttribute(n,r+""),r)}return o&&"get"in o&&u&&(s=o.get(e,n))!==null?s:(s=e.getAttribute(n),s===null?t:s)},removeAttr:function(e,t){var n,r,i,s,o=0;if(t&&e.nodeType===1){r=t.split(y);for(;o=0}})});var $=/^(?:textarea|input|select)$/i,J=/^([^\.]*|)(?:\.(.+)|)$/,K=/(?:^|\s)hover(\.\S+|)\b/,Q=/^key/,G=/^(?:mouse|contextmenu)|click/,Y=/^(?:focusinfocus|focusoutblur)$/,Z=function(e){return v.event.special.hover?e:e.replace(K,"mouseenter$1 mouseleave$1")};v.event={add:function(e,n,r,i,s){var o,u,a,f,l,c,h,p,d,m,g;if(e.nodeType===3||e.nodeType===8||!n||!r||!(o=v._data(e)))return;r.handler&&(d=r,r=d.handler,s=d.selector),r.guid||(r.guid=v.guid++),a=o.events,a||(o.events=a={}),u=o.handle,u||(o.handle=u=function(e){return typeof v=="undefined"||!!e&&v.event.triggered===e.type?t:v.event.dispatch.apply(u.elem,arguments)},u.elem=e),n=v.trim(Z(n)).split(" ");for(f=0;f=0&&(y=y.slice(0,-1),a=!0),y.indexOf(".")>=0&&(b=y.split("."),y=b.shift(),b.sort());if((!s||v.event.customEvent[y])&&!v.event.global[y])return;n=typeof n=="object"?n[v.expando]?n:new v.Event(y,n):new v.Event(y),n.type=y,n.isTrigger=!0,n.exclusive=a,n.namespace=b.join("."),n.namespace_re=n.namespace?new RegExp("(^|\\.)"+b.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,h=y.indexOf(":")<0?"on"+y:"";if(!s){u=v.cache;for(f in u)u[f].events&&u[f].events[y]&&v.event.trigger(n,r,u[f].handle.elem,!0);return}n.result=t,n.target||(n.target=s),r=r!=null?v.makeArray(r):[],r.unshift(n),p=v.event.special[y]||{};if(p.trigger&&p.trigger.apply(s,r)===!1)return;m=[[s,p.bindType||y]];if(!o&&!p.noBubble&&!v.isWindow(s)){g=p.delegateType||y,l=Y.test(g+y)?s:s.parentNode;for(c=s;l;l=l.parentNode)m.push([l,g]),c=l;c===(s.ownerDocument||i)&&m.push([c.defaultView||c.parentWindow||e,g])}for(f=0;f=0:v.find(h,this,null,[s]).length),u[h]&&f.push(c);f.length&&w.push({elem:s,matches:f})}d.length>m&&w.push({elem:this,matches:d.slice(m)});for(r=0;r0?this.on(t,null,e,n):this.trigger(t)},Q.test(t)&&(v.event.fixHooks[t]=v.event.keyHooks),G.test(t)&&(v.event.fixHooks[t]=v.event.mouseHooks)}),function(e,t){function nt(e,t,n,r){n=n||[],t=t||g;var i,s,a,f,l=t.nodeType;if(!e||typeof e!="string")return n;if(l!==1&&l!==9)return[];a=o(t);if(!a&&!r)if(i=R.exec(e))if(f=i[1]){if(l===9){s=t.getElementById(f);if(!s||!s.parentNode)return n;if(s.id===f)return n.push(s),n}else if(t.ownerDocument&&(s=t.ownerDocument.getElementById(f))&&u(t,s)&&s.id===f)return n.push(s),n}else{if(i[2])return S.apply(n,x.call(t.getElementsByTagName(e),0)),n;if((f=i[3])&&Z&&t.getElementsByClassName)return S.apply(n,x.call(t.getElementsByClassName(f),0)),n}return vt(e.replace(j,"$1"),t,n,r,a)}function rt(e){return function(t){var n=t.nodeName.toLowerCase();return n==="input"&&t.type===e}}function it(e){return function(t){var n=t.nodeName.toLowerCase();return(n==="input"||n==="button")&&t.type===e}}function st(e){return N(function(t){return t=+t,N(function(n,r){var i,s=e([],n.length,t),o=s.length;while(o--)n[i=s[o]]&&(n[i]=!(r[i]=n[i]))})})}function ot(e,t,n){if(e===t)return n;var r=e.nextSibling;while(r){if(r===t)return-1;r=r.nextSibling}return 1}function ut(e,t){var n,r,s,o,u,a,f,l=L[d][e+" "];if(l)return t?0:l.slice(0);u=e,a=[],f=i.preFilter;while(u){if(!n||(r=F.exec(u)))r&&(u=u.slice(r[0].length)||u),a.push(s=[]);n=!1;if(r=I.exec(u))s.push(n=new m(r.shift())),u=u.slice(n.length),n.type=r[0].replace(j," ");for(o in i.filter)(r=J[o].exec(u))&&(!f[o]||(r=f[o](r)))&&(s.push(n=new m(r.shift())),u=u.slice(n.length),n.type=o,n.matches=r);if(!n)break}return t?u.length:u?nt.error(e):L(e,a).slice(0)}function at(e,t,r){var i=t.dir,s=r&&t.dir==="parentNode",o=w++;return t.first?function(t,n,r){while(t=t[i])if(s||t.nodeType===1)return e(t,n,r)}:function(t,r,u){if(!u){var a,f=b+" "+o+" ",l=f+n;while(t=t[i])if(s||t.nodeType===1){if((a=t[d])===l)return t.sizset;if(typeof a=="string"&&a.indexOf(f)===0){if(t.sizset)return t}else{t[d]=l;if(e(t,r,u))return t.sizset=!0,t;t.sizset=!1}}}else while(t=t[i])if(s||t.nodeType===1)if(e(t,r,u))return t}}function ft(e){return e.length>1?function(t,n,r){var i=e.length;while(i--)if(!e[i](t,n,r))return!1;return!0}:e[0]}function lt(e,t,n,r,i){var s,o=[],u=0,a=e.length,f=t!=null;for(;u-1&&(s[f]=!(o[f]=c))}}else g=lt(g===o?g.splice(d,g.length):g),i?i(null,o,g,a):S.apply(o,g)})}function ht(e){var t,n,r,s=e.length,o=i.relative[e[0].type],u=o||i.relative[" "],a=o?1:0,f=at(function(e){return e===t},u,!0),l=at(function(e){return T.call(t,e)>-1},u,!0),h=[function(e,n,r){return!o&&(r||n!==c)||((t=n).nodeType?f(e,n,r):l(e,n,r))}];for(;a1&&ft(h),a>1&&e.slice(0,a-1).join("").replace(j,"$1"),n,a0,s=e.length>0,o=function(u,a,f,l,h){var p,d,v,m=[],y=0,w="0",x=u&&[],T=h!=null,N=c,C=u||s&&i.find.TAG("*",h&&a.parentNode||a),k=b+=N==null?1:Math.E;T&&(c=a!==g&&a,n=o.el);for(;(p=C[w])!=null;w++){if(s&&p){for(d=0;v=e[d];d++)if(v(p,a,f)){l.push(p);break}T&&(b=k,n=++o.el)}r&&((p=!v&&p)&&y--,u&&x.push(p))}y+=w;if(r&&w!==y){for(d=0;v=t[d];d++)v(x,m,a,f);if(u){if(y>0)while(w--)!x[w]&&!m[w]&&(m[w]=E.call(l));m=lt(m)}S.apply(l,m),T&&!u&&m.length>0&&y+t.length>1&&nt.uniqueSort(l)}return T&&(b=k,c=N),x};return o.el=0,r?N(o):o}function dt(e,t,n){var r=0,i=t.length;for(;r2&&(f=u[0]).type==="ID"&&t.nodeType===9&&!s&&i.relative[u[1].type]){t=i.find.ID(f.matches[0].replace($,""),t,s)[0];if(!t)return n;e=e.slice(u.shift().length)}for(o=J.POS.test(e)?-1:u.length-1;o>=0;o--){f=u[o];if(i.relative[l=f.type])break;if(c=i.find[l])if(r=c(f.matches[0].replace($,""),z.test(u[0].type)&&t.parentNode||t,s)){u.splice(o,1),e=r.length&&u.join("");if(!e)return S.apply(n,x.call(r,0)),n;break}}}return a(e,h)(r,t,s,n,z.test(e)),n}function mt(){}var n,r,i,s,o,u,a,f,l,c,h=!0,p="undefined",d=("sizcache"+Math.random()).replace(".",""),m=String,g=e.document,y=g.documentElement,b=0,w=0,E=[].pop,S=[].push,x=[].slice,T=[].indexOf||function(e){var t=0,n=this.length;for(;ti.cacheLength&&delete e[t.shift()],e[n+" "]=r},e)},k=C(),L=C(),A=C(),O="[\\x20\\t\\r\\n\\f]",M="(?:\\\\.|[-\\w]|[^\\x00-\\xa0])+",_=M.replace("w","w#"),D="([*^$|!~]?=)",P="\\["+O+"*("+M+")"+O+"*(?:"+D+O+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+_+")|)|)"+O+"*\\]",H=":("+M+")(?:\\((?:(['\"])((?:\\\\.|[^\\\\])*?)\\2|([^()[\\]]*|(?:(?:"+P+")|[^:]|\\\\.)*|.*))\\)|)",B=":(even|odd|eq|gt|lt|nth|first|last)(?:\\("+O+"*((?:-\\d)?\\d*)"+O+"*\\)|)(?=[^-]|$)",j=new RegExp("^"+O+"+|((?:^|[^\\\\])(?:\\\\.)*)"+O+"+$","g"),F=new RegExp("^"+O+"*,"+O+"*"),I=new RegExp("^"+O+"*([\\x20\\t\\r\\n\\f>+~])"+O+"*"),q=new RegExp(H),R=/^(?:#([\w\-]+)|(\w+)|\.([\w\-]+))$/,U=/^:not/,z=/[\x20\t\r\n\f]*[+~]/,W=/:not\($/,X=/h\d/i,V=/input|select|textarea|button/i,$=/\\(?!\\)/g,J={ID:new RegExp("^#("+M+")"),CLASS:new RegExp("^\\.("+M+")"),NAME:new RegExp("^\\[name=['\"]?("+M+")['\"]?\\]"),TAG:new RegExp("^("+M.replace("w","w*")+")"),ATTR:new RegExp("^"+P),PSEUDO:new RegExp("^"+H),POS:new RegExp(B,"i"),CHILD:new RegExp("^:(only|nth|first|last)-child(?:\\("+O+"*(even|odd|(([+-]|)(\\d*)n|)"+O+"*(?:([+-]|)"+O+"*(\\d+)|))"+O+"*\\)|)","i"),needsContext:new RegExp("^"+O+"*[>+~]|"+B,"i")},K=function(e){var t=g.createElement("div");try{return e(t)}catch(n){return!1}finally{t=null}},Q=K(function(e){return e.appendChild(g.createComment("")),!e.getElementsByTagName("*").length}),G=K(function(e){return e.innerHTML="",e.firstChild&&typeof e.firstChild.getAttribute!==p&&e.firstChild.getAttribute("href")==="#"}),Y=K(function(e){e.innerHTML="";var t=typeof e.lastChild.getAttribute("multiple");return t!=="boolean"&&t!=="string"}),Z=K(function(e){return e.innerHTML="",!e.getElementsByClassName||!e.getElementsByClassName("e").length?!1:(e.lastChild.className="e",e.getElementsByClassName("e").length===2)}),et=K(function(e){e.id=d+0,e.innerHTML="
",y.insertBefore(e,y.firstChild);var t=g.getElementsByName&&g.getElementsByName(d).length===2+g.getElementsByName(d+0).length;return r=!g.getElementById(d),y.removeChild(e),t});try{x.call(y.childNodes,0)[0].nodeType}catch(tt){x=function(e){var t,n=[];for(;t=this[e];e++)n.push(t);return n}}nt.matches=function(e,t){return nt(e,null,null,t)},nt.matchesSelector=function(e,t){return nt(t,null,null,[e]).length>0},s=nt.getText=function(e){var t,n="",r=0,i=e.nodeType;if(i){if(i===1||i===9||i===11){if(typeof e.textContent=="string")return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=s(e)}else if(i===3||i===4)return e.nodeValue}else for(;t=e[r];r++)n+=s(t);return n},o=nt.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return t?t.nodeName!=="HTML":!1},u=nt.contains=y.contains?function(e,t){var n=e.nodeType===9?e.documentElement:e,r=t&&t.parentNode;return e===r||!!(r&&r.nodeType===1&&n.contains&&n.contains(r))}:y.compareDocumentPosition?function(e,t){return t&&!!(e.compareDocumentPosition(t)&16)}:function(e,t){while(t=t.parentNode)if(t===e)return!0;return!1},nt.attr=function(e,t){var n,r=o(e);return r||(t=t.toLowerCase()),(n=i.attrHandle[t])?n(e):r||Y?e.getAttribute(t):(n=e.getAttributeNode(t),n?typeof e[t]=="boolean"?e[t]?t:null:n.specified?n.value:null:null)},i=nt.selectors={cacheLength:50,createPseudo:N,match:J,attrHandle:G?{}:{href:function(e){return e.getAttribute("href",2)},type:function(e){return e.getAttribute("type")}},find:{ID:r?function(e,t,n){if(typeof t.getElementById!==p&&!n){var r=t.getElementById(e);return r&&r.parentNode?[r]:[]}}:function(e,n,r){if(typeof n.getElementById!==p&&!r){var i=n.getElementById(e);return i?i.id===e||typeof i.getAttributeNode!==p&&i.getAttributeNode("id").value===e?[i]:t:[]}},TAG:Q?function(e,t){if(typeof t.getElementsByTagName!==p)return t.getElementsByTagName(e)}:function(e,t){var n=t.getElementsByTagName(e);if(e==="*"){var r,i=[],s=0;for(;r=n[s];s++)r.nodeType===1&&i.push(r);return i}return n},NAME:et&&function(e,t){if(typeof t.getElementsByName!==p)return t.getElementsByName(name)},CLASS:Z&&function(e,t,n){if(typeof t.getElementsByClassName!==p&&!n)return t.getElementsByClassName(e)}},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace($,""),e[3]=(e[4]||e[5]||"").replace($,""),e[2]==="~="&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),e[1]==="nth"?(e[2]||nt.error(e[0]),e[3]=+(e[3]?e[4]+(e[5]||1):2*(e[2]==="even"||e[2]==="odd")),e[4]=+(e[6]+e[7]||e[2]==="odd")):e[2]&&nt.error(e[0]),e},PSEUDO:function(e){var t,n;if(J.CHILD.test(e[0]))return null;if(e[3])e[2]=e[3];else if(t=e[4])q.test(t)&&(n=ut(t,!0))&&(n=t.indexOf(")",t.length-n)-t.length)&&(t=t.slice(0,n),e[0]=e[0].slice(0,n)),e[2]=t;return e.slice(0,3)}},filter:{ID:r?function(e){return e=e.replace($,""),function(t){return t.getAttribute("id")===e}}:function(e){return e=e.replace($,""),function(t){var n=typeof t.getAttributeNode!==p&&t.getAttributeNode("id");return n&&n.value===e}},TAG:function(e){return e==="*"?function(){return!0}:(e=e.replace($,"").toLowerCase(),function(t){return t.nodeName&&t.nodeName.toLowerCase()===e})},CLASS:function(e){var t=k[d][e+" "];return t||(t=new RegExp("(^|"+O+")"+e+"("+O+"|$)"))&&k(e,function(e){return t.test(e.className||typeof e.getAttribute!==p&&e.getAttribute("class")||"")})},ATTR:function(e,t,n){return function(r,i){var s=nt.attr(r,e);return s==null?t==="!=":t?(s+="",t==="="?s===n:t==="!="?s!==n:t==="^="?n&&s.indexOf(n)===0:t==="*="?n&&s.indexOf(n)>-1:t==="$="?n&&s.substr(s.length-n.length)===n:t==="~="?(" "+s+" ").indexOf(n)>-1:t==="|="?s===n||s.substr(0,n.length+1)===n+"-":!1):!0}},CHILD:function(e,t,n,r){return e==="nth"?function(e){var t,i,s=e.parentNode;if(n===1&&r===0)return!0;if(s){i=0;for(t=s.firstChild;t;t=t.nextSibling)if(t.nodeType===1){i++;if(e===t)break}}return i-=r,i===n||i%n===0&&i/n>=0}:function(t){var n=t;switch(e){case"only":case"first":while(n=n.previousSibling)if(n.nodeType===1)return!1;if(e==="first")return!0;n=t;case"last":while(n=n.nextSibling)if(n.nodeType===1)return!1;return!0}}},PSEUDO:function(e,t){var n,r=i.pseudos[e]||i.setFilters[e.toLowerCase()]||nt.error("unsupported pseudo: "+e);return r[d]?r(t):r.length>1?(n=[e,e,"",t],i.setFilters.hasOwnProperty(e.toLowerCase())?N(function(e,n){var i,s=r(e,t),o=s.length;while(o--)i=T.call(e,s[o]),e[i]=!(n[i]=s[o])}):function(e){return r(e,0,n)}):r}},pseudos:{not:N(function(e){var t=[],n=[],r=a(e.replace(j,"$1"));return r[d]?N(function(e,t,n,i){var s,o=r(e,null,i,[]),u=e.length;while(u--)if(s=o[u])e[u]=!(t[u]=s)}):function(e,i,s){return t[0]=e,r(t,null,s,n),!n.pop()}}),has:N(function(e){return function(t){return nt(e,t).length>0}}),contains:N(function(e){return function(t){return(t.textContent||t.innerText||s(t)).indexOf(e)>-1}}),enabled:function(e){return e.disabled===!1},disabled:function(e){return e.disabled===!0},checked:function(e){var t=e.nodeName.toLowerCase();return t==="input"&&!!e.checked||t==="option"&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,e.selected===!0},parent:function(e){return!i.pseudos.empty(e)},empty:function(e){var t;e=e.firstChild;while(e){if(e.nodeName>"@"||(t=e.nodeType)===3||t===4)return!1;e=e.nextSibling}return!0},header:function(e){return X.test(e.nodeName)},text:function(e){var t,n;return e.nodeName.toLowerCase()==="input"&&(t=e.type)==="text"&&((n=e.getAttribute("type"))==null||n.toLowerCase()===t)},radio:rt("radio"),checkbox:rt("checkbox"),file:rt("file"),password:rt("password"),image:rt("image"),submit:it("submit"),reset:it("reset"),button:function(e){var t=e.nodeName.toLowerCase();return t==="input"&&e.type==="button"||t==="button"},input:function(e){return V.test(e.nodeName)},focus:function(e){var t=e.ownerDocument;return e===t.activeElement&&(!t.hasFocus||t.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},active:function(e){return e===e.ownerDocument.activeElement},first:st(function(){return[0]}),last:st(function(e,t){return[t-1]}),eq:st(function(e,t,n){return[n<0?n+t:n]}),even:st(function(e,t){for(var n=0;n=0;)e.push(r);return e}),gt:st(function(e,t,n){for(var r=n<0?n+t:n;++r",e.querySelectorAll("[selected]").length||i.push("\\["+O+"*(?:checked|disabled|ismap|multiple|readonly|selected|value)"),e.querySelectorAll(":checked").length||i.push(":checked")}),K(function(e){e.innerHTML="

",e.querySelectorAll("[test^='']").length&&i.push("[*^$]="+O+"*(?:\"\"|'')"),e.innerHTML="",e.querySelectorAll(":enabled").length||i.push(":enabled",":disabled")}),i=new RegExp(i.join("|")),vt=function(e,r,s,o,u){if(!o&&!u&&!i.test(e)){var a,f,l=!0,c=d,h=r,p=r.nodeType===9&&e;if(r.nodeType===1&&r.nodeName.toLowerCase()!=="object"){a=ut(e),(l=r.getAttribute("id"))?c=l.replace(n,"\\$&"):r.setAttribute("id",c),c="[id='"+c+"'] ",f=a.length;while(f--)a[f]=c+a[f].join("");h=z.test(e)&&r.parentNode||r,p=a.join(",")}if(p)try{return S.apply(s,x.call(h.querySelectorAll(p),0)),s}catch(v){}finally{l||r.removeAttribute("id")}}return t(e,r,s,o,u)},u&&(K(function(t){e=u.call(t,"div");try{u.call(t,"[test!='']:sizzle"),s.push("!=",H)}catch(n){}}),s=new RegExp(s.join("|")),nt.matchesSelector=function(t,n){n=n.replace(r,"='$1']");if(!o(t)&&!s.test(n)&&!i.test(n))try{var a=u.call(t,n);if(a||e||t.document&&t.document.nodeType!==11)return a}catch(f){}return nt(n,null,null,[t]).length>0})}(),i.pseudos.nth=i.pseudos.eq,i.filters=mt.prototype=i.pseudos,i.setFilters=new mt,nt.attr=v.attr,v.find=nt,v.expr=nt.selectors,v.expr[":"]=v.expr.pseudos,v.unique=nt.uniqueSort,v.text=nt.getText,v.isXMLDoc=nt.isXML,v.contains=nt.contains}(e);var nt=/Until$/,rt=/^(?:parents|prev(?:Until|All))/,it=/^.[^:#\[\.,]*$/,st=v.expr.match.needsContext,ot={children:!0,contents:!0,next:!0,prev:!0};v.fn.extend({find:function(e){var t,n,r,i,s,o,u=this;if(typeof e!="string")return v(e).filter(function(){for(t=0,n=u.length;t0)for(i=r;i=0:v.filter(e,this).length>0:this.filter(e).length>0)},closest:function(e,t){var n,r=0,i=this.length,s=[],o=st.test(e)||typeof e!="string"?v(e,t||this.context):0;for(;r-1:v.find.matchesSelector(n,e)){s.push(n);break}n=n.parentNode}}return s=s.length>1?v.unique(s):s,this.pushStack(s,"closest",e)},index:function(e){return e?typeof e=="string"?v.inArray(this[0],v(e)):v.inArray(e.jquery?e[0]:e,this):this[0]&&this[0].parentNode?this.prevAll().length:-1},add:function(e,t){var n=typeof e=="string"?v(e,t):v.makeArray(e&&e.nodeType?[e]:e),r=v.merge(this.get(),n);return this.pushStack(ut(n[0])||ut(r[0])?r:v.unique(r))},addBack:function(e){return this.add(e==null?this.prevObject:this.prevObject.filter(e))}}),v.fn.andSelf=v.fn.addBack,v.each({parent:function(e){var t=e.parentNode;return t&&t.nodeType!==11?t:null},parents:function(e){return v.dir(e,"parentNode")},parentsUntil:function(e,t,n){return v.dir(e,"parentNode",n)},next:function(e){return at(e,"nextSibling")},prev:function(e){return at(e,"previousSibling")},nextAll:function(e){return v.dir(e,"nextSibling")},prevAll:function(e){return v.dir(e,"previousSibling")},nextUntil:function(e,t,n){return v.dir(e,"nextSibling",n)},prevUntil:function(e,t,n){return v.dir(e,"previousSibling",n)},siblings:function(e){return v.sibling((e.parentNode||{}).firstChild,e)},children:function(e){return v.sibling(e.firstChild)},contents:function(e){return v.nodeName(e,"iframe")?e.contentDocument||e.contentWindow.document:v.merge([],e.childNodes)}},function(e,t){v.fn[e]=function(n,r){var i=v.map(this,t,n);return nt.test(e)||(r=n),r&&typeof r=="string"&&(i=v.filter(r,i)),i=this.length>1&&!ot[e]?v.unique(i):i,this.length>1&&rt.test(e)&&(i=i.reverse()),this.pushStack(i,e,l.call(arguments).join(","))}}),v.extend({filter:function(e,t,n){return n&&(e=":not("+e+")"),t.length===1?v.find.matchesSelector(t[0],e)?[t[0]]:[]:v.find.matches(e,t)},dir:function(e,n,r){var i=[],s=e[n];while(s&&s.nodeType!==9&&(r===t||s.nodeType!==1||!v(s).is(r)))s.nodeType===1&&i.push(s),s=s[n];return i},sibling:function(e,t){var n=[];for(;e;e=e.nextSibling)e.nodeType===1&&e!==t&&n.push(e);return n}});var ct="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",ht=/ jQuery\d+="(?:null|\d+)"/g,pt=/^\s+/,dt=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,vt=/<([\w:]+)/,mt=/]","i"),Et=/^(?:checkbox|radio)$/,St=/checked\s*(?:[^=]|=\s*.checked.)/i,xt=/\/(java|ecma)script/i,Tt=/^\s*\s*$/g,Nt={option:[1,""],legend:[1,"
","
"],thead:[1,"","
"],tr:[2,"","
"],td:[3,"","
"],col:[2,"","
"],area:[1,"",""],_default:[0,"",""]},Ct=lt(i),kt=Ct.appendChild(i.createElement("div"));Nt.optgroup=Nt.option,Nt.tbody=Nt.tfoot=Nt.colgroup=Nt.caption=Nt.thead,Nt.th=Nt.td,v.support.htmlSerialize||(Nt._default=[1,"X
","
"]),v.fn.extend({text:function(e){return v.access(this,function(e){return e===t?v.text(this):this.empty().append((this[0]&&this[0].ownerDocument||i).createTextNode(e))},null,e,arguments.length)},wrapAll:function(e){if(v.isFunction(e))return this.each(function(t){v(this).wrapAll(e.call(this,t))});if(this[0]){var t=v(e,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&t.insertBefore(this[0]),t.map(function(){var e=this;while(e.firstChild&&e.firstChild.nodeType===1)e=e.firstChild;return e}).append(this)}return this},wrapInner:function(e){return v.isFunction(e)?this.each(function(t){v(this).wrapInner(e.call(this,t))}):this.each(function(){var t=v(this),n=t.contents();n.length?n.wrapAll(e):t.append(e)})},wrap:function(e){var t=v.isFunction(e);return this.each(function(n){v(this).wrapAll(t?e.call(this,n):e)})},unwrap:function(){return this.parent().each(function(){v.nodeName(this,"body")||v(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(e){(this.nodeType===1||this.nodeType===11)&&this.appendChild(e)})},prepend:function(){return this.domManip(arguments,!0,function(e){(this.nodeType===1||this.nodeType===11)&&this.insertBefore(e,this.firstChild)})},before:function(){if(!ut(this[0]))return this.domManip(arguments,!1,function(e){this.parentNode.insertBefore(e,this)});if(arguments.length){var e=v.clean(arguments);return this.pushStack(v.merge(e,this),"before",this.selector)}},after:function(){if(!ut(this[0]))return this.domManip(arguments,!1,function(e){this.parentNode.insertBefore(e,this.nextSibling)});if(arguments.length){var e=v.clean(arguments);return this.pushStack(v.merge(this,e),"after",this.selector)}},remove:function(e,t){var n,r=0;for(;(n=this[r])!=null;r++)if(!e||v.filter(e,[n]).length)!t&&n.nodeType===1&&(v.cleanData(n.getElementsByTagName("*")),v.cleanData([n])),n.parentNode&&n.parentNode.removeChild(n);return this},empty:function(){var e,t=0;for(;(e=this[t])!=null;t++){e.nodeType===1&&v.cleanData(e.getElementsByTagName("*"));while(e.firstChild)e.removeChild(e.firstChild)}return this},clone:function(e,t){return e=e==null?!1:e,t=t==null?e:t,this.map(function(){return v.clone(this,e,t)})},html:function(e){return v.access(this,function(e){var n=this[0]||{},r=0,i=this.length;if(e===t)return n.nodeType===1?n.innerHTML.replace(ht,""):t;if(typeof e=="string"&&!yt.test(e)&&(v.support.htmlSerialize||!wt.test(e))&&(v.support.leadingWhitespace||!pt.test(e))&&!Nt[(vt.exec(e)||["",""])[1].toLowerCase()]){e=e.replace(dt,"<$1>");try{for(;r1&&typeof f=="string"&&St.test(f))return this.each(function(){v(this).domManip(e,n,r)});if(v.isFunction(f))return this.each(function(i){var s=v(this);e[0]=f.call(this,i,n?s.html():t),s.domManip(e,n,r)});if(this[0]){i=v.buildFragment(e,this,l),o=i.fragment,s=o.firstChild,o.childNodes.length===1&&(o=s);if(s){n=n&&v.nodeName(s,"tr");for(u=i.cacheable||c-1;a0?this.clone(!0):this).get(),v(o[i])[t](r),s=s.concat(r);return this.pushStack(s,e,o.selector)}}),v.extend({clone:function(e,t,n){var r,i,s,o;v.support.html5Clone||v.isXMLDoc(e)||!wt.test("<"+e.nodeName+">")?o=e.cloneNode(!0):(kt.innerHTML=e.outerHTML,kt.removeChild(o=kt.firstChild));if((!v.support.noCloneEvent||!v.support.noCloneChecked)&&(e.nodeType===1||e.nodeType===11)&&!v.isXMLDoc(e)){Ot(e,o),r=Mt(e),i=Mt(o);for(s=0;r[s];++s)i[s]&&Ot(r[s],i[s])}if(t){At(e,o);if(n){r=Mt(e),i=Mt(o);for(s=0;r[s];++s)At(r[s],i[s])}}return r=i=null,o},clean:function(e,t,n,r){var s,o,u,a,f,l,c,h,p,d,m,g,y=t===i&&Ct,b=[];if(!t||typeof t.createDocumentFragment=="undefined")t=i;for(s=0;(u=e[s])!=null;s++){typeof u=="number"&&(u+="");if(!u)continue;if(typeof u=="string")if(!gt.test(u))u=t.createTextNode(u);else{y=y||lt(t),c=t.createElement("div"),y.appendChild(c),u=u.replace(dt,"<$1>"),a=(vt.exec(u)||["",""])[1].toLowerCase(),f=Nt[a]||Nt._default,l=f[0],c.innerHTML=f[1]+u+f[2];while(l--)c=c.lastChild;if(!v.support.tbody){h=mt.test(u),p=a==="table"&&!h?c.firstChild&&c.firstChild.childNodes:f[1]===""&&!h?c.childNodes:[];for(o=p.length-1;o>=0;--o)v.nodeName(p[o],"tbody")&&!p[o].childNodes.length&&p[o].parentNode.removeChild(p[o])}!v.support.leadingWhitespace&&pt.test(u)&&c.insertBefore(t.createTextNode(pt.exec(u)[0]),c.firstChild),u=c.childNodes,c.parentNode.removeChild(c)}u.nodeType?b.push(u):v.merge(b,u)}c&&(u=c=y=null);if(!v.support.appendChecked)for(s=0;(u=b[s])!=null;s++)v.nodeName(u,"input")?_t(u):typeof u.getElementsByTagName!="undefined"&&v.grep(u.getElementsByTagName("input"),_t);if(n){m=function(e){if(!e.type||xt.test(e.type))return r?r.push(e.parentNode?e.parentNode.removeChild(e):e):n.appendChild(e)};for(s=0;(u=b[s])!=null;s++)if(!v.nodeName(u,"script")||!m(u))n.appendChild(u),typeof u.getElementsByTagName!="undefined"&&(g=v.grep(v.merge([],u.getElementsByTagName("script")),m),b.splice.apply(b,[s+1,0].concat(g)),s+=g.length)}return b},cleanData:function(e,t){var n,r,i,s,o=0,u=v.expando,a=v.cache,f=v.support.deleteExpando,l=v.event.special;for(;(i=e[o])!=null;o++)if(t||v.acceptData(i)){r=i[u],n=r&&a[r];if(n){if(n.events)for(s in n.events)l[s]?v.event.remove(i,s):v.removeEvent(i,s,n.handle);a[r]&&(delete a[r],f?delete i[u]:i.removeAttribute?i.removeAttribute(u):i[u]=null,v.deletedIds.push(r))}}}}),function(){var e,t;v.uaMatch=function(e){e=e.toLowerCase();var t=/(chrome)[ \/]([\w.]+)/.exec(e)||/(webkit)[ \/]([\w.]+)/.exec(e)||/(opera)(?:.*version|)[ \/]([\w.]+)/.exec(e)||/(msie) ([\w.]+)/.exec(e)||e.indexOf("compatible")<0&&/(mozilla)(?:.*? rv:([\w.]+)|)/.exec(e)||[];return{browser:t[1]||"",version:t[2]||"0"}},e=v.uaMatch(o.userAgent),t={},e.browser&&(t[e.browser]=!0,t.version=e.version),t.chrome?t.webkit=!0:t.webkit&&(t.safari=!0),v.browser=t,v.sub=function(){function e(t,n){return new e.fn.init(t,n)}v.extend(!0,e,this),e.superclass=this,e.fn=e.prototype=this(),e.fn.constructor=e,e.sub=this.sub,e.fn.init=function(r,i){return i&&i instanceof v&&!(i instanceof e)&&(i=e(i)),v.fn.init.call(this,r,i,t)},e.fn.init.prototype=e.fn;var t=e(i);return e}}();var Dt,Pt,Ht,Bt=/alpha\([^)]*\)/i,jt=/opacity=([^)]*)/,Ft=/^(top|right|bottom|left)$/,It=/^(none|table(?!-c[ea]).+)/,qt=/^margin/,Rt=new RegExp("^("+m+")(.*)$","i"),Ut=new RegExp("^("+m+")(?!px)[a-z%]+$","i"),zt=new RegExp("^([-+])=("+m+")","i"),Wt={BODY:"block"},Xt={position:"absolute",visibility:"hidden",display:"block"},Vt={letterSpacing:0,fontWeight:400},$t=["Top","Right","Bottom","Left"],Jt=["Webkit","O","Moz","ms"],Kt=v.fn.toggle;v.fn.extend({css:function(e,n){return v.access(this,function(e,n,r){return r!==t?v.style(e,n,r):v.css(e,n)},e,n,arguments.length>1)},show:function(){return Yt(this,!0)},hide:function(){return Yt(this)},toggle:function(e,t){var n=typeof e=="boolean";return v.isFunction(e)&&v.isFunction(t)?Kt.apply(this,arguments):this.each(function(){(n?e:Gt(this))?v(this).show():v(this).hide()})}}),v.extend({cssHooks:{opacity:{get:function(e,t){if(t){var n=Dt(e,"opacity");return n===""?"1":n}}}},cssNumber:{fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":v.support.cssFloat?"cssFloat":"styleFloat"},style:function(e,n,r,i){if(!e||e.nodeType===3||e.nodeType===8||!e.style)return;var s,o,u,a=v.camelCase(n),f=e.style;n=v.cssProps[a]||(v.cssProps[a]=Qt(f,a)),u=v.cssHooks[n]||v.cssHooks[a];if(r===t)return u&&"get"in u&&(s=u.get(e,!1,i))!==t?s:f[n];o=typeof r,o==="string"&&(s=zt.exec(r))&&(r=(s[1]+1)*s[2]+parseFloat(v.css(e,n)),o="number");if(r==null||o==="number"&&isNaN(r))return;o==="number"&&!v.cssNumber[a]&&(r+="px");if(!u||!("set"in u)||(r=u.set(e,r,i))!==t)try{f[n]=r}catch(l){}},css:function(e,n,r,i){var s,o,u,a=v.camelCase(n);return n=v.cssProps[a]||(v.cssProps[a]=Qt(e.style,a)),u=v.cssHooks[n]||v.cssHooks[a],u&&"get"in u&&(s=u.get(e,!0,i)),s===t&&(s=Dt(e,n)),s==="normal"&&n in Vt&&(s=Vt[n]),r||i!==t?(o=parseFloat(s),r||v.isNumeric(o)?o||0:s):s},swap:function(e,t,n){var r,i,s={};for(i in t)s[i]=e.style[i],e.style[i]=t[i];r=n.call(e);for(i in t)e.style[i]=s[i];return r}}),e.getComputedStyle?Dt=function(t,n){var r,i,s,o,u=e.getComputedStyle(t,null),a=t.style;return u&&(r=u.getPropertyValue(n)||u[n],r===""&&!v.contains(t.ownerDocument,t)&&(r=v.style(t,n)),Ut.test(r)&&qt.test(n)&&(i=a.width,s=a.minWidth,o=a.maxWidth,a.minWidth=a.maxWidth=a.width=r,r=u.width,a.width=i,a.minWidth=s,a.maxWidth=o)),r}:i.documentElement.currentStyle&&(Dt=function(e,t){var n,r,i=e.currentStyle&&e.currentStyle[t],s=e.style;return i==null&&s&&s[t]&&(i=s[t]),Ut.test(i)&&!Ft.test(t)&&(n=s.left,r=e.runtimeStyle&&e.runtimeStyle.left,r&&(e.runtimeStyle.left=e.currentStyle.left),s.left=t==="fontSize"?"1em":i,i=s.pixelLeft+"px",s.left=n,r&&(e.runtimeStyle.left=r)),i===""?"auto":i}),v.each(["height","width"],function(e,t){v.cssHooks[t]={get:function(e,n,r){if(n)return e.offsetWidth===0&&It.test(Dt(e,"display"))?v.swap(e,Xt,function(){return tn(e,t,r)}):tn(e,t,r)},set:function(e,n,r){return Zt(e,n,r?en(e,t,r,v.support.boxSizing&&v.css(e,"boxSizing")==="border-box"):0)}}}),v.support.opacity||(v.cssHooks.opacity={get:function(e,t){return jt.test((t&&e.currentStyle?e.currentStyle.filter:e.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":t?"1":""},set:function(e,t){var n=e.style,r=e.currentStyle,i=v.isNumeric(t)?"alpha(opacity="+t*100+")":"",s=r&&r.filter||n.filter||"";n.zoom=1;if(t>=1&&v.trim(s.replace(Bt,""))===""&&n.removeAttribute){n.removeAttribute("filter");if(r&&!r.filter)return}n.filter=Bt.test(s)?s.replace(Bt,i):s+" "+i}}),v(function(){v.support.reliableMarginRight||(v.cssHooks.marginRight={get:function(e,t){return v.swap(e,{display:"inline-block"},function(){if(t)return Dt(e,"marginRight")})}}),!v.support.pixelPosition&&v.fn.position&&v.each(["top","left"],function(e,t){v.cssHooks[t]={get:function(e,n){if(n){var r=Dt(e,t);return Ut.test(r)?v(e).position()[t]+"px":r}}}})}),v.expr&&v.expr.filters&&(v.expr.filters.hidden=function(e){return e.offsetWidth===0&&e.offsetHeight===0||!v.support.reliableHiddenOffsets&&(e.style&&e.style.display||Dt(e,"display"))==="none"},v.expr.filters.visible=function(e){return!v.expr.filters.hidden(e)}),v.each({margin:"",padding:"",border:"Width"},function(e,t){v.cssHooks[e+t]={expand:function(n){var r,i=typeof n=="string"?n.split(" "):[n],s={};for(r=0;r<4;r++)s[e+$t[r]+t]=i[r]||i[r-2]||i[0];return s}},qt.test(e)||(v.cssHooks[e+t].set=Zt)});var rn=/%20/g,sn=/\[\]$/,on=/\r?\n/g,un=/^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,an=/^(?:select|textarea)/i;v.fn.extend({serialize:function(){return v.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?v.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||an.test(this.nodeName)||un.test(this.type))}).map(function(e,t){var n=v(this).val();return n==null?null:v.isArray(n)?v.map(n,function(e,n){return{name:t.name,value:e.replace(on,"\r\n")}}):{name:t.name,value:n.replace(on,"\r\n")}}).get()}}),v.param=function(e,n){var r,i=[],s=function(e,t){t=v.isFunction(t)?t():t==null?"":t,i[i.length]=encodeURIComponent(e)+"="+encodeURIComponent(t)};n===t&&(n=v.ajaxSettings&&v.ajaxSettings.traditional);if(v.isArray(e)||e.jquery&&!v.isPlainObject(e))v.each(e,function(){s(this.name,this.value)});else for(r in e)fn(r,e[r],n,s);return i.join("&").replace(rn,"+")};var ln,cn,hn=/#.*$/,pn=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,dn=/^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,vn=/^(?:GET|HEAD)$/,mn=/^\/\//,gn=/\?/,yn=/)<[^<]*)*<\/script>/gi,bn=/([?&])_=[^&]*/,wn=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,En=v.fn.load,Sn={},xn={},Tn=["*/"]+["*"];try{cn=s.href}catch(Nn){cn=i.createElement("a"),cn.href="",cn=cn.href}ln=wn.exec(cn.toLowerCase())||[],v.fn.load=function(e,n,r){if(typeof e!="string"&&En)return En.apply(this,arguments);if(!this.length)return this;var i,s,o,u=this,a=e.indexOf(" ");return a>=0&&(i=e.slice(a,e.length),e=e.slice(0,a)),v.isFunction(n)?(r=n,n=t):n&&typeof n=="object"&&(s="POST"),v.ajax({url:e,type:s,dataType:"html",data:n,complete:function(e,t){r&&u.each(r,o||[e.responseText,t,e])}}).done(function(e){o=arguments,u.html(i?v("
").append(e.replace(yn,"")).find(i):e)}),this},v.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(e,t){v.fn[t]=function(e){return this.on(t,e)}}),v.each(["get","post"],function(e,n){v[n]=function(e,r,i,s){return v.isFunction(r)&&(s=s||i,i=r,r=t),v.ajax({type:n,url:e,data:r,success:i,dataType:s})}}),v.extend({getScript:function(e,n){return v.get(e,t,n,"script")},getJSON:function(e,t,n){return v.get(e,t,n,"json")},ajaxSetup:function(e,t){return t?Ln(e,v.ajaxSettings):(t=e,e=v.ajaxSettings),Ln(e,t),e},ajaxSettings:{url:cn,isLocal:dn.test(ln[1]),global:!0,type:"GET",contentType:"application/x-www-form-urlencoded; charset=UTF-8",processData:!0,async:!0,accepts:{xml:"application/xml, text/xml",html:"text/html",text:"text/plain",json:"application/json, text/javascript","*":Tn},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":e.String,"text html":!0,"text json":v.parseJSON,"text xml":v.parseXML},flatOptions:{context:!0,url:!0}},ajaxPrefilter:Cn(Sn),ajaxTransport:Cn(xn),ajax:function(e,n){function T(e,n,s,a){var l,y,b,w,S,T=n;if(E===2)return;E=2,u&&clearTimeout(u),o=t,i=a||"",x.readyState=e>0?4:0,s&&(w=An(c,x,s));if(e>=200&&e<300||e===304)c.ifModified&&(S=x.getResponseHeader("Last-Modified"),S&&(v.lastModified[r]=S),S=x.getResponseHeader("Etag"),S&&(v.etag[r]=S)),e===304?(T="notmodified",l=!0):(l=On(c,w),T=l.state,y=l.data,b=l.error,l=!b);else{b=T;if(!T||e)T="error",e<0&&(e=0)}x.status=e,x.statusText=(n||T)+"",l?d.resolveWith(h,[y,T,x]):d.rejectWith(h,[x,T,b]),x.statusCode(g),g=t,f&&p.trigger("ajax"+(l?"Success":"Error"),[x,c,l?y:b]),m.fireWith(h,[x,T]),f&&(p.trigger("ajaxComplete",[x,c]),--v.active||v.event.trigger("ajaxStop"))}typeof e=="object"&&(n=e,e=t),n=n||{};var r,i,s,o,u,a,f,l,c=v.ajaxSetup({},n),h=c.context||c,p=h!==c&&(h.nodeType||h instanceof v)?v(h):v.event,d=v.Deferred(),m=v.Callbacks("once memory"),g=c.statusCode||{},b={},w={},E=0,S="canceled",x={readyState:0,setRequestHeader:function(e,t){if(!E){var n=e.toLowerCase();e=w[n]=w[n]||e,b[e]=t}return this},getAllResponseHeaders:function(){return E===2?i:null},getResponseHeader:function(e){var n;if(E===2){if(!s){s={};while(n=pn.exec(i))s[n[1].toLowerCase()]=n[2]}n=s[e.toLowerCase()]}return n===t?null:n},overrideMimeType:function(e){return E||(c.mimeType=e),this},abort:function(e){return e=e||S,o&&o.abort(e),T(0,e),this}};d.promise(x),x.success=x.done,x.error=x.fail,x.complete=m.add,x.statusCode=function(e){if(e){var t;if(E<2)for(t in e)g[t]=[g[t],e[t]];else t=e[x.status],x.always(t)}return this},c.url=((e||c.url)+"").replace(hn,"").replace(mn,ln[1]+"//"),c.dataTypes=v.trim(c.dataType||"*").toLowerCase().split(y),c.crossDomain==null&&(a=wn.exec(c.url.toLowerCase()),c.crossDomain=!(!a||a[1]===ln[1]&&a[2]===ln[2]&&(a[3]||(a[1]==="http:"?80:443))==(ln[3]||(ln[1]==="http:"?80:443)))),c.data&&c.processData&&typeof c.data!="string"&&(c.data=v.param(c.data,c.traditional)),kn(Sn,c,n,x);if(E===2)return x;f=c.global,c.type=c.type.toUpperCase(),c.hasContent=!vn.test(c.type),f&&v.active++===0&&v.event.trigger("ajaxStart");if(!c.hasContent){c.data&&(c.url+=(gn.test(c.url)?"&":"?")+c.data,delete c.data),r=c.url;if(c.cache===!1){var N=v.now(),C=c.url.replace(bn,"$1_="+N);c.url=C+(C===c.url?(gn.test(c.url)?"&":"?")+"_="+N:"")}}(c.data&&c.hasContent&&c.contentType!==!1||n.contentType)&&x.setRequestHeader("Content-Type",c.contentType),c.ifModified&&(r=r||c.url,v.lastModified[r]&&x.setRequestHeader("If-Modified-Since",v.lastModified[r]),v.etag[r]&&x.setRequestHeader("If-None-Match",v.etag[r])),x.setRequestHeader("Accept",c.dataTypes[0]&&c.accepts[c.dataTypes[0]]?c.accepts[c.dataTypes[0]]+(c.dataTypes[0]!=="*"?", "+Tn+"; q=0.01":""):c.accepts["*"]);for(l in c.headers)x.setRequestHeader(l,c.headers[l]);if(!c.beforeSend||c.beforeSend.call(h,x,c)!==!1&&E!==2){S="abort";for(l in{success:1,error:1,complete:1})x[l](c[l]);o=kn(xn,c,n,x);if(!o)T(-1,"No Transport");else{x.readyState=1,f&&p.trigger("ajaxSend",[x,c]),c.async&&c.timeout>0&&(u=setTimeout(function(){x.abort("timeout")},c.timeout));try{E=1,o.send(b,T)}catch(k){if(!(E<2))throw k;T(-1,k)}}return x}return x.abort()},active:0,lastModified:{},etag:{}});var Mn=[],_n=/\?/,Dn=/(=)\?(?=&|$)|\?\?/,Pn=v.now();v.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=Mn.pop()||v.expando+"_"+Pn++;return this[e]=!0,e}}),v.ajaxPrefilter("json jsonp",function(n,r,i){var s,o,u,a=n.data,f=n.url,l=n.jsonp!==!1,c=l&&Dn.test(f),h=l&&!c&&typeof a=="string"&&!(n.contentType||"").indexOf("application/x-www-form-urlencoded")&&Dn.test(a);if(n.dataTypes[0]==="jsonp"||c||h)return s=n.jsonpCallback=v.isFunction(n.jsonpCallback)?n.jsonpCallback():n.jsonpCallback,o=e[s],c?n.url=f.replace(Dn,"$1"+s):h?n.data=a.replace(Dn,"$1"+s):l&&(n.url+=(_n.test(f)?"&":"?")+n.jsonp+"="+s),n.converters["script json"]=function(){return u||v.error(s+" was not called"),u[0]},n.dataTypes[0]="json",e[s]=function(){u=arguments},i.always(function(){e[s]=o,n[s]&&(n.jsonpCallback=r.jsonpCallback,Mn.push(s)),u&&v.isFunction(o)&&o(u[0]),u=o=t}),"script"}),v.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/javascript|ecmascript/},converters:{"text script":function(e){return v.globalEval(e),e}}}),v.ajaxPrefilter("script",function(e){e.cache===t&&(e.cache=!1),e.crossDomain&&(e.type="GET",e.global=!1)}),v.ajaxTransport("script",function(e){if(e.crossDomain){var n,r=i.head||i.getElementsByTagName("head")[0]||i.documentElement;return{send:function(s,o){n=i.createElement("script"),n.async="async",e.scriptCharset&&(n.charset=e.scriptCharset),n.src=e.url,n.onload=n.onreadystatechange=function(e,i){if(i||!n.readyState||/loaded|complete/.test(n.readyState))n.onload=n.onreadystatechange=null,r&&n.parentNode&&r.removeChild(n),n=t,i||o(200,"success")},r.insertBefore(n,r.firstChild)},abort:function(){n&&n.onload(0,1)}}}});var Hn,Bn=e.ActiveXObject?function(){for(var e in Hn)Hn[e](0,1)}:!1,jn=0;v.ajaxSettings.xhr=e.ActiveXObject?function(){return!this.isLocal&&Fn()||In()}:Fn,function(e){v.extend(v.support,{ajax:!!e,cors:!!e&&"withCredentials"in e})}(v.ajaxSettings.xhr()),v.support.ajax&&v.ajaxTransport(function(n){if(!n.crossDomain||v.support.cors){var r;return{send:function(i,s){var o,u,a=n.xhr();n.username?a.open(n.type,n.url,n.async,n.username,n.password):a.open(n.type,n.url,n.async);if(n.xhrFields)for(u in n.xhrFields)a[u]=n.xhrFields[u];n.mimeType&&a.overrideMimeType&&a.overrideMimeType(n.mimeType),!n.crossDomain&&!i["X-Requested-With"]&&(i["X-Requested-With"]="XMLHttpRequest");try{for(u in i)a.setRequestHeader(u,i[u])}catch(f){}a.send(n.hasContent&&n.data||null),r=function(e,i){var u,f,l,c,h;try{if(r&&(i||a.readyState===4)){r=t,o&&(a.onreadystatechange=v.noop,Bn&&delete Hn[o]);if(i)a.readyState!==4&&a.abort();else{u=a.status,l=a.getAllResponseHeaders(),c={},h=a.responseXML,h&&h.documentElement&&(c.xml=h);try{c.text=a.responseText}catch(p){}try{f=a.statusText}catch(p){f=""}!u&&n.isLocal&&!n.crossDomain?u=c.text?200:404:u===1223&&(u=204)}}}catch(d){i||s(-1,d)}c&&s(u,f,c,l)},n.async?a.readyState===4?setTimeout(r,0):(o=++jn,Bn&&(Hn||(Hn={},v(e).unload(Bn)),Hn[o]=r),a.onreadystatechange=r):r()},abort:function(){r&&r(0,1)}}}});var qn,Rn,Un=/^(?:toggle|show|hide)$/,zn=new RegExp("^(?:([-+])=|)("+m+")([a-z%]*)$","i"),Wn=/queueHooks$/,Xn=[Gn],Vn={"*":[function(e,t){var n,r,i=this.createTween(e,t),s=zn.exec(t),o=i.cur(),u=+o||0,a=1,f=20;if(s){n=+s[2],r=s[3]||(v.cssNumber[e]?"":"px");if(r!=="px"&&u){u=v.css(i.elem,e,!0)||n||1;do a=a||".5",u/=a,v.style(i.elem,e,u+r);while(a!==(a=i.cur()/o)&&a!==1&&--f)}i.unit=r,i.start=u,i.end=s[1]?u+(s[1]+1)*n:n}return i}]};v.Animation=v.extend(Kn,{tweener:function(e,t){v.isFunction(e)?(t=e,e=["*"]):e=e.split(" ");var n,r=0,i=e.length;for(;r-1,f={},l={},c,h;a?(l=i.position(),c=l.top,h=l.left):(c=parseFloat(o)||0,h=parseFloat(u)||0),v.isFunction(t)&&(t=t.call(e,n,s)),t.top!=null&&(f.top=t.top-s.top+c),t.left!=null&&(f.left=t.left-s.left+h),"using"in t?t.using.call(e,f):i.css(f)}},v.fn.extend({position:function(){if(!this[0])return;var e=this[0],t=this.offsetParent(),n=this.offset(),r=er.test(t[0].nodeName)?{top:0,left:0}:t.offset();return n.top-=parseFloat(v.css(e,"marginTop"))||0,n.left-=parseFloat(v.css(e,"marginLeft"))||0,r.top+=parseFloat(v.css(t[0],"borderTopWidth"))||0,r.left+=parseFloat(v.css(t[0],"borderLeftWidth"))||0,{top:n.top-r.top,left:n.left-r.left}},offsetParent:function(){return this.map(function(){var e=this.offsetParent||i.body;while(e&&!er.test(e.nodeName)&&v.css(e,"position")==="static")e=e.offsetParent;return e||i.body})}}),v.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(e,n){var r=/Y/.test(n);v.fn[e]=function(i){return v.access(this,function(e,i,s){var o=tr(e);if(s===t)return o?n in o?o[n]:o.document.documentElement[i]:e[i];o?o.scrollTo(r?v(o).scrollLeft():s,r?s:v(o).scrollTop()):e[i]=s},e,i,arguments.length,null)}}),v.each({Height:"height",Width:"width"},function(e,n){v.each({padding:"inner"+e,content:n,"":"outer"+e},function(r,i){v.fn[i]=function(i,s){var o=arguments.length&&(r||typeof i!="boolean"),u=r||(i===!0||s===!0?"margin":"border");return v.access(this,function(n,r,i){var s;return v.isWindow(n)?n.document.documentElement["client"+e]:n.nodeType===9?(s=n.documentElement,Math.max(n.body["scroll"+e],s["scroll"+e],n.body["offset"+e],s["offset"+e],s["client"+e])):i===t?v.css(n,r,i,u):v.style(n,r,i,u)},n,o?i:t,o,null)}})}),e.jQuery=e.$=v,typeof define=="function"&&define.amd&&define.amd.jQuery&&define("jquery",[],function(){return v})})(window); \ No newline at end of file diff --git a/Chapter06/templates/content/mustache.js b/Chapter06/templates/content/mustache.js new file mode 100644 index 0000000..0148d29 --- /dev/null +++ b/Chapter06/templates/content/mustache.js @@ -0,0 +1,625 @@ +/*! + * mustache.js - Logic-less {{mustache}} templates with JavaScript + * http://github.com/janl/mustache.js + */ + +/*global define: false*/ + +var Mustache; + +(function (exports) { + if (typeof module !== "undefined" && module.exports) { + module.exports = exports; // CommonJS + } else if (typeof define === "function") { + define(exports); // AMD + } else { + Mustache = exports; // + + + + + + + diff --git a/Chapter07/02_basic_routing/content/album.js b/Chapter07/02_basic_routing/content/album.js new file mode 100644 index 0000000..a8ffd36 --- /dev/null +++ b/Chapter07/02_basic_routing/content/album.js @@ -0,0 +1,46 @@ +$(function(){ + + var tmpl, // Main template HTML + tdata = {}; // JSON data object that feeds the template + + // Initialise page + var initPage = function() { + + // get our album name. + parts = window.location.href.split("/"); + var album_name = parts[5]; + + // Load the HTML template + $.get("/templates/album.html", function(d){ + tmpl = d; + }); + + // Retrieve the server data and then initialise the page + $.getJSON("/albums/" + album_name + ".json", function (d) { + var photo_d = massage_album(d); + $.extend(tdata, photo_d); + }); + + // When AJAX calls are complete parse the template + // replacing mustache tags with vars + $(document).ajaxStop(function () { + var renderedPage = Mustache.to_html( tmpl, tdata ); + $("body").html( renderedPage ); + }) + }(); +}); + + + +function massage_album(d) { + if (d.error != null) return d; + var obj = { photos: [] }; + + var af = d.data.album_data; + + for (var i = 0; i < af.photos.length; i++) { + var url = "/albums/" + af.short_name + "/" + af.photos[i].filename; + obj.photos.push({ url: url, desc: af.photos[i].filename }); + } + return obj; +} diff --git a/Chapter07/02_basic_routing/content/home.js b/Chapter07/02_basic_routing/content/home.js new file mode 100644 index 0000000..244cf2f --- /dev/null +++ b/Chapter07/02_basic_routing/content/home.js @@ -0,0 +1,28 @@ +$(function(){ + + var tmpl, // Main template HTML + tdata = {}; // JSON data object that feeds the template + + // Initialise page + var initPage = function() { + + // Load the HTML template + $.get("/templates/home.html", function(d){ + tmpl = d; + }); + + + // Retrieve the server data and then initialise the page + $.getJSON("/albums.json", function (d) { + $.extend(tdata, d.data); + }); + + // When AJAX calls are complete parse the template + // replacing mustache tags with vars + $(document).ajaxStop(function () { + var renderedPage = Mustache.to_html( tmpl, tdata ); + $("body").html( renderedPage ); + }) + }(); +}); + diff --git a/Chapter07/02_basic_routing/content/jquery-1.8.3.min.js b/Chapter07/02_basic_routing/content/jquery-1.8.3.min.js new file mode 100644 index 0000000..83589da --- /dev/null +++ b/Chapter07/02_basic_routing/content/jquery-1.8.3.min.js @@ -0,0 +1,2 @@ +/*! jQuery v1.8.3 jquery.com | jquery.org/license */ +(function(e,t){function _(e){var t=M[e]={};return v.each(e.split(y),function(e,n){t[n]=!0}),t}function H(e,n,r){if(r===t&&e.nodeType===1){var i="data-"+n.replace(P,"-$1").toLowerCase();r=e.getAttribute(i);if(typeof r=="string"){try{r=r==="true"?!0:r==="false"?!1:r==="null"?null:+r+""===r?+r:D.test(r)?v.parseJSON(r):r}catch(s){}v.data(e,n,r)}else r=t}return r}function B(e){var t;for(t in e){if(t==="data"&&v.isEmptyObject(e[t]))continue;if(t!=="toJSON")return!1}return!0}function et(){return!1}function tt(){return!0}function ut(e){return!e||!e.parentNode||e.parentNode.nodeType===11}function at(e,t){do e=e[t];while(e&&e.nodeType!==1);return e}function ft(e,t,n){t=t||0;if(v.isFunction(t))return v.grep(e,function(e,r){var i=!!t.call(e,r,e);return i===n});if(t.nodeType)return v.grep(e,function(e,r){return e===t===n});if(typeof t=="string"){var r=v.grep(e,function(e){return e.nodeType===1});if(it.test(t))return v.filter(t,r,!n);t=v.filter(t,r)}return v.grep(e,function(e,r){return v.inArray(e,t)>=0===n})}function lt(e){var t=ct.split("|"),n=e.createDocumentFragment();if(n.createElement)while(t.length)n.createElement(t.pop());return n}function Lt(e,t){return e.getElementsByTagName(t)[0]||e.appendChild(e.ownerDocument.createElement(t))}function At(e,t){if(t.nodeType!==1||!v.hasData(e))return;var n,r,i,s=v._data(e),o=v._data(t,s),u=s.events;if(u){delete o.handle,o.events={};for(n in u)for(r=0,i=u[n].length;r").appendTo(i.body),n=t.css("display");t.remove();if(n==="none"||n===""){Pt=i.body.appendChild(Pt||v.extend(i.createElement("iframe"),{frameBorder:0,width:0,height:0}));if(!Ht||!Pt.createElement)Ht=(Pt.contentWindow||Pt.contentDocument).document,Ht.write(""),Ht.close();t=Ht.body.appendChild(Ht.createElement(e)),n=Dt(t,"display"),i.body.removeChild(Pt)}return Wt[e]=n,n}function fn(e,t,n,r){var i;if(v.isArray(t))v.each(t,function(t,i){n||sn.test(e)?r(e,i):fn(e+"["+(typeof i=="object"?t:"")+"]",i,n,r)});else if(!n&&v.type(t)==="object")for(i in t)fn(e+"["+i+"]",t[i],n,r);else r(e,t)}function Cn(e){return function(t,n){typeof t!="string"&&(n=t,t="*");var r,i,s,o=t.toLowerCase().split(y),u=0,a=o.length;if(v.isFunction(n))for(;u)[^>]*$|#([\w\-]*)$)/,E=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,S=/^[\],:{}\s]*$/,x=/(?:^|:|,)(?:\s*\[)+/g,T=/\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,N=/"[^"\\\r\n]*"|true|false|null|-?(?:\d\d*\.|)\d+(?:[eE][\-+]?\d+|)/g,C=/^-ms-/,k=/-([\da-z])/gi,L=function(e,t){return(t+"").toUpperCase()},A=function(){i.addEventListener?(i.removeEventListener("DOMContentLoaded",A,!1),v.ready()):i.readyState==="complete"&&(i.detachEvent("onreadystatechange",A),v.ready())},O={};v.fn=v.prototype={constructor:v,init:function(e,n,r){var s,o,u,a;if(!e)return this;if(e.nodeType)return this.context=this[0]=e,this.length=1,this;if(typeof e=="string"){e.charAt(0)==="<"&&e.charAt(e.length-1)===">"&&e.length>=3?s=[null,e,null]:s=w.exec(e);if(s&&(s[1]||!n)){if(s[1])return n=n instanceof v?n[0]:n,a=n&&n.nodeType?n.ownerDocument||n:i,e=v.parseHTML(s[1],a,!0),E.test(s[1])&&v.isPlainObject(n)&&this.attr.call(e,n,!0),v.merge(this,e);o=i.getElementById(s[2]);if(o&&o.parentNode){if(o.id!==s[2])return r.find(e);this.length=1,this[0]=o}return this.context=i,this.selector=e,this}return!n||n.jquery?(n||r).find(e):this.constructor(n).find(e)}return v.isFunction(e)?r.ready(e):(e.selector!==t&&(this.selector=e.selector,this.context=e.context),v.makeArray(e,this))},selector:"",jquery:"1.8.3",length:0,size:function(){return this.length},toArray:function(){return l.call(this)},get:function(e){return e==null?this.toArray():e<0?this[this.length+e]:this[e]},pushStack:function(e,t,n){var r=v.merge(this.constructor(),e);return r.prevObject=this,r.context=this.context,t==="find"?r.selector=this.selector+(this.selector?" ":"")+n:t&&(r.selector=this.selector+"."+t+"("+n+")"),r},each:function(e,t){return v.each(this,e,t)},ready:function(e){return v.ready.promise().done(e),this},eq:function(e){return e=+e,e===-1?this.slice(e):this.slice(e,e+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(l.apply(this,arguments),"slice",l.call(arguments).join(","))},map:function(e){return this.pushStack(v.map(this,function(t,n){return e.call(t,n,t)}))},end:function(){return this.prevObject||this.constructor(null)},push:f,sort:[].sort,splice:[].splice},v.fn.init.prototype=v.fn,v.extend=v.fn.extend=function(){var e,n,r,i,s,o,u=arguments[0]||{},a=1,f=arguments.length,l=!1;typeof u=="boolean"&&(l=u,u=arguments[1]||{},a=2),typeof u!="object"&&!v.isFunction(u)&&(u={}),f===a&&(u=this,--a);for(;a0)return;r.resolveWith(i,[v]),v.fn.trigger&&v(i).trigger("ready").off("ready")},isFunction:function(e){return v.type(e)==="function"},isArray:Array.isArray||function(e){return v.type(e)==="array"},isWindow:function(e){return e!=null&&e==e.window},isNumeric:function(e){return!isNaN(parseFloat(e))&&isFinite(e)},type:function(e){return e==null?String(e):O[h.call(e)]||"object"},isPlainObject:function(e){if(!e||v.type(e)!=="object"||e.nodeType||v.isWindow(e))return!1;try{if(e.constructor&&!p.call(e,"constructor")&&!p.call(e.constructor.prototype,"isPrototypeOf"))return!1}catch(n){return!1}var r;for(r in e);return r===t||p.call(e,r)},isEmptyObject:function(e){var t;for(t in e)return!1;return!0},error:function(e){throw new Error(e)},parseHTML:function(e,t,n){var r;return!e||typeof e!="string"?null:(typeof t=="boolean"&&(n=t,t=0),t=t||i,(r=E.exec(e))?[t.createElement(r[1])]:(r=v.buildFragment([e],t,n?null:[]),v.merge([],(r.cacheable?v.clone(r.fragment):r.fragment).childNodes)))},parseJSON:function(t){if(!t||typeof t!="string")return null;t=v.trim(t);if(e.JSON&&e.JSON.parse)return e.JSON.parse(t);if(S.test(t.replace(T,"@").replace(N,"]").replace(x,"")))return(new Function("return "+t))();v.error("Invalid JSON: "+t)},parseXML:function(n){var r,i;if(!n||typeof n!="string")return null;try{e.DOMParser?(i=new DOMParser,r=i.parseFromString(n,"text/xml")):(r=new ActiveXObject("Microsoft.XMLDOM"),r.async="false",r.loadXML(n))}catch(s){r=t}return(!r||!r.documentElement||r.getElementsByTagName("parsererror").length)&&v.error("Invalid XML: "+n),r},noop:function(){},globalEval:function(t){t&&g.test(t)&&(e.execScript||function(t){e.eval.call(e,t)})(t)},camelCase:function(e){return e.replace(C,"ms-").replace(k,L)},nodeName:function(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()},each:function(e,n,r){var i,s=0,o=e.length,u=o===t||v.isFunction(e);if(r){if(u){for(i in e)if(n.apply(e[i],r)===!1)break}else for(;s0&&e[0]&&e[a-1]||a===0||v.isArray(e));if(f)for(;u-1)a.splice(n,1),i&&(n<=o&&o--,n<=u&&u--)}),this},has:function(e){return v.inArray(e,a)>-1},empty:function(){return a=[],this},disable:function(){return a=f=n=t,this},disabled:function(){return!a},lock:function(){return f=t,n||c.disable(),this},locked:function(){return!f},fireWith:function(e,t){return t=t||[],t=[e,t.slice?t.slice():t],a&&(!r||f)&&(i?f.push(t):l(t)),this},fire:function(){return c.fireWith(this,arguments),this},fired:function(){return!!r}};return c},v.extend({Deferred:function(e){var t=[["resolve","done",v.Callbacks("once memory"),"resolved"],["reject","fail",v.Callbacks("once memory"),"rejected"],["notify","progress",v.Callbacks("memory")]],n="pending",r={state:function(){return n},always:function(){return i.done(arguments).fail(arguments),this},then:function(){var e=arguments;return v.Deferred(function(n){v.each(t,function(t,r){var s=r[0],o=e[t];i[r[1]](v.isFunction(o)?function(){var e=o.apply(this,arguments);e&&v.isFunction(e.promise)?e.promise().done(n.resolve).fail(n.reject).progress(n.notify):n[s+"With"](this===i?n:this,[e])}:n[s])}),e=null}).promise()},promise:function(e){return e!=null?v.extend(e,r):r}},i={};return r.pipe=r.then,v.each(t,function(e,s){var o=s[2],u=s[3];r[s[1]]=o.add,u&&o.add(function(){n=u},t[e^1][2].disable,t[2][2].lock),i[s[0]]=o.fire,i[s[0]+"With"]=o.fireWith}),r.promise(i),e&&e.call(i,i),i},when:function(e){var t=0,n=l.call(arguments),r=n.length,i=r!==1||e&&v.isFunction(e.promise)?r:0,s=i===1?e:v.Deferred(),o=function(e,t,n){return function(r){t[e]=this,n[e]=arguments.length>1?l.call(arguments):r,n===u?s.notifyWith(t,n):--i||s.resolveWith(t,n)}},u,a,f;if(r>1){u=new Array(r),a=new Array(r),f=new Array(r);for(;t
a",n=p.getElementsByTagName("*"),r=p.getElementsByTagName("a")[0];if(!n||!r||!n.length)return{};s=i.createElement("select"),o=s.appendChild(i.createElement("option")),u=p.getElementsByTagName("input")[0],r.style.cssText="top:1px;float:left;opacity:.5",t={leadingWhitespace:p.firstChild.nodeType===3,tbody:!p.getElementsByTagName("tbody").length,htmlSerialize:!!p.getElementsByTagName("link").length,style:/top/.test(r.getAttribute("style")),hrefNormalized:r.getAttribute("href")==="/a",opacity:/^0.5/.test(r.style.opacity),cssFloat:!!r.style.cssFloat,checkOn:u.value==="on",optSelected:o.selected,getSetAttribute:p.className!=="t",enctype:!!i.createElement("form").enctype,html5Clone:i.createElement("nav").cloneNode(!0).outerHTML!=="<:nav>",boxModel:i.compatMode==="CSS1Compat",submitBubbles:!0,changeBubbles:!0,focusinBubbles:!1,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0,boxSizingReliable:!0,pixelPosition:!1},u.checked=!0,t.noCloneChecked=u.cloneNode(!0).checked,s.disabled=!0,t.optDisabled=!o.disabled;try{delete p.test}catch(d){t.deleteExpando=!1}!p.addEventListener&&p.attachEvent&&p.fireEvent&&(p.attachEvent("onclick",h=function(){t.noCloneEvent=!1}),p.cloneNode(!0).fireEvent("onclick"),p.detachEvent("onclick",h)),u=i.createElement("input"),u.value="t",u.setAttribute("type","radio"),t.radioValue=u.value==="t",u.setAttribute("checked","checked"),u.setAttribute("name","t"),p.appendChild(u),a=i.createDocumentFragment(),a.appendChild(p.lastChild),t.checkClone=a.cloneNode(!0).cloneNode(!0).lastChild.checked,t.appendChecked=u.checked,a.removeChild(u),a.appendChild(p);if(p.attachEvent)for(l in{submit:!0,change:!0,focusin:!0})f="on"+l,c=f in p,c||(p.setAttribute(f,"return;"),c=typeof p[f]=="function"),t[l+"Bubbles"]=c;return v(function(){var n,r,s,o,u="padding:0;margin:0;border:0;display:block;overflow:hidden;",a=i.getElementsByTagName("body")[0];if(!a)return;n=i.createElement("div"),n.style.cssText="visibility:hidden;border:0;width:0;height:0;position:static;top:0;margin-top:1px",a.insertBefore(n,a.firstChild),r=i.createElement("div"),n.appendChild(r),r.innerHTML="
t
",s=r.getElementsByTagName("td"),s[0].style.cssText="padding:0;margin:0;border:0;display:none",c=s[0].offsetHeight===0,s[0].style.display="",s[1].style.display="none",t.reliableHiddenOffsets=c&&s[0].offsetHeight===0,r.innerHTML="",r.style.cssText="box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;",t.boxSizing=r.offsetWidth===4,t.doesNotIncludeMarginInBodyOffset=a.offsetTop!==1,e.getComputedStyle&&(t.pixelPosition=(e.getComputedStyle(r,null)||{}).top!=="1%",t.boxSizingReliable=(e.getComputedStyle(r,null)||{width:"4px"}).width==="4px",o=i.createElement("div"),o.style.cssText=r.style.cssText=u,o.style.marginRight=o.style.width="0",r.style.width="1px",r.appendChild(o),t.reliableMarginRight=!parseFloat((e.getComputedStyle(o,null)||{}).marginRight)),typeof r.style.zoom!="undefined"&&(r.innerHTML="",r.style.cssText=u+"width:1px;padding:1px;display:inline;zoom:1",t.inlineBlockNeedsLayout=r.offsetWidth===3,r.style.display="block",r.style.overflow="visible",r.innerHTML="
",r.firstChild.style.width="5px",t.shrinkWrapBlocks=r.offsetWidth!==3,n.style.zoom=1),a.removeChild(n),n=r=s=o=null}),a.removeChild(p),n=r=s=o=u=a=p=null,t}();var D=/(?:\{[\s\S]*\}|\[[\s\S]*\])$/,P=/([A-Z])/g;v.extend({cache:{},deletedIds:[],uuid:0,expando:"jQuery"+(v.fn.jquery+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(e){return e=e.nodeType?v.cache[e[v.expando]]:e[v.expando],!!e&&!B(e)},data:function(e,n,r,i){if(!v.acceptData(e))return;var s,o,u=v.expando,a=typeof n=="string",f=e.nodeType,l=f?v.cache:e,c=f?e[u]:e[u]&&u;if((!c||!l[c]||!i&&!l[c].data)&&a&&r===t)return;c||(f?e[u]=c=v.deletedIds.pop()||v.guid++:c=u),l[c]||(l[c]={},f||(l[c].toJSON=v.noop));if(typeof n=="object"||typeof n=="function")i?l[c]=v.extend(l[c],n):l[c].data=v.extend(l[c].data,n);return s=l[c],i||(s.data||(s.data={}),s=s.data),r!==t&&(s[v.camelCase(n)]=r),a?(o=s[n],o==null&&(o=s[v.camelCase(n)])):o=s,o},removeData:function(e,t,n){if(!v.acceptData(e))return;var r,i,s,o=e.nodeType,u=o?v.cache:e,a=o?e[v.expando]:v.expando;if(!u[a])return;if(t){r=n?u[a]:u[a].data;if(r){v.isArray(t)||(t in r?t=[t]:(t=v.camelCase(t),t in r?t=[t]:t=t.split(" ")));for(i=0,s=t.length;i1,null,!1))},removeData:function(e){return this.each(function(){v.removeData(this,e)})}}),v.extend({queue:function(e,t,n){var r;if(e)return t=(t||"fx")+"queue",r=v._data(e,t),n&&(!r||v.isArray(n)?r=v._data(e,t,v.makeArray(n)):r.push(n)),r||[]},dequeue:function(e,t){t=t||"fx";var n=v.queue(e,t),r=n.length,i=n.shift(),s=v._queueHooks(e,t),o=function(){v.dequeue(e,t)};i==="inprogress"&&(i=n.shift(),r--),i&&(t==="fx"&&n.unshift("inprogress"),delete s.stop,i.call(e,o,s)),!r&&s&&s.empty.fire()},_queueHooks:function(e,t){var n=t+"queueHooks";return v._data(e,n)||v._data(e,n,{empty:v.Callbacks("once memory").add(function(){v.removeData(e,t+"queue",!0),v.removeData(e,n,!0)})})}}),v.fn.extend({queue:function(e,n){var r=2;return typeof e!="string"&&(n=e,e="fx",r--),arguments.length1)},removeAttr:function(e){return this.each(function(){v.removeAttr(this,e)})},prop:function(e,t){return v.access(this,v.prop,e,t,arguments.length>1)},removeProp:function(e){return e=v.propFix[e]||e,this.each(function(){try{this[e]=t,delete this[e]}catch(n){}})},addClass:function(e){var t,n,r,i,s,o,u;if(v.isFunction(e))return this.each(function(t){v(this).addClass(e.call(this,t,this.className))});if(e&&typeof e=="string"){t=e.split(y);for(n=0,r=this.length;n=0)r=r.replace(" "+n[s]+" "," ");i.className=e?v.trim(r):""}}}return this},toggleClass:function(e,t){var n=typeof e,r=typeof t=="boolean";return v.isFunction(e)?this.each(function(n){v(this).toggleClass(e.call(this,n,this.className,t),t)}):this.each(function(){if(n==="string"){var i,s=0,o=v(this),u=t,a=e.split(y);while(i=a[s++])u=r?u:!o.hasClass(i),o[u?"addClass":"removeClass"](i)}else if(n==="undefined"||n==="boolean")this.className&&v._data(this,"__className__",this.className),this.className=this.className||e===!1?"":v._data(this,"__className__")||""})},hasClass:function(e){var t=" "+e+" ",n=0,r=this.length;for(;n=0)return!0;return!1},val:function(e){var n,r,i,s=this[0];if(!arguments.length){if(s)return n=v.valHooks[s.type]||v.valHooks[s.nodeName.toLowerCase()],n&&"get"in n&&(r=n.get(s,"value"))!==t?r:(r=s.value,typeof r=="string"?r.replace(R,""):r==null?"":r);return}return i=v.isFunction(e),this.each(function(r){var s,o=v(this);if(this.nodeType!==1)return;i?s=e.call(this,r,o.val()):s=e,s==null?s="":typeof s=="number"?s+="":v.isArray(s)&&(s=v.map(s,function(e){return e==null?"":e+""})),n=v.valHooks[this.type]||v.valHooks[this.nodeName.toLowerCase()];if(!n||!("set"in n)||n.set(this,s,"value")===t)this.value=s})}}),v.extend({valHooks:{option:{get:function(e){var t=e.attributes.value;return!t||t.specified?e.value:e.text}},select:{get:function(e){var t,n,r=e.options,i=e.selectedIndex,s=e.type==="select-one"||i<0,o=s?null:[],u=s?i+1:r.length,a=i<0?u:s?i:0;for(;a=0}),n.length||(e.selectedIndex=-1),n}}},attrFn:{},attr:function(e,n,r,i){var s,o,u,a=e.nodeType;if(!e||a===3||a===8||a===2)return;if(i&&v.isFunction(v.fn[n]))return v(e)[n](r);if(typeof e.getAttribute=="undefined")return v.prop(e,n,r);u=a!==1||!v.isXMLDoc(e),u&&(n=n.toLowerCase(),o=v.attrHooks[n]||(X.test(n)?F:j));if(r!==t){if(r===null){v.removeAttr(e,n);return}return o&&"set"in o&&u&&(s=o.set(e,r,n))!==t?s:(e.setAttribute(n,r+""),r)}return o&&"get"in o&&u&&(s=o.get(e,n))!==null?s:(s=e.getAttribute(n),s===null?t:s)},removeAttr:function(e,t){var n,r,i,s,o=0;if(t&&e.nodeType===1){r=t.split(y);for(;o=0}})});var $=/^(?:textarea|input|select)$/i,J=/^([^\.]*|)(?:\.(.+)|)$/,K=/(?:^|\s)hover(\.\S+|)\b/,Q=/^key/,G=/^(?:mouse|contextmenu)|click/,Y=/^(?:focusinfocus|focusoutblur)$/,Z=function(e){return v.event.special.hover?e:e.replace(K,"mouseenter$1 mouseleave$1")};v.event={add:function(e,n,r,i,s){var o,u,a,f,l,c,h,p,d,m,g;if(e.nodeType===3||e.nodeType===8||!n||!r||!(o=v._data(e)))return;r.handler&&(d=r,r=d.handler,s=d.selector),r.guid||(r.guid=v.guid++),a=o.events,a||(o.events=a={}),u=o.handle,u||(o.handle=u=function(e){return typeof v=="undefined"||!!e&&v.event.triggered===e.type?t:v.event.dispatch.apply(u.elem,arguments)},u.elem=e),n=v.trim(Z(n)).split(" ");for(f=0;f=0&&(y=y.slice(0,-1),a=!0),y.indexOf(".")>=0&&(b=y.split("."),y=b.shift(),b.sort());if((!s||v.event.customEvent[y])&&!v.event.global[y])return;n=typeof n=="object"?n[v.expando]?n:new v.Event(y,n):new v.Event(y),n.type=y,n.isTrigger=!0,n.exclusive=a,n.namespace=b.join("."),n.namespace_re=n.namespace?new RegExp("(^|\\.)"+b.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,h=y.indexOf(":")<0?"on"+y:"";if(!s){u=v.cache;for(f in u)u[f].events&&u[f].events[y]&&v.event.trigger(n,r,u[f].handle.elem,!0);return}n.result=t,n.target||(n.target=s),r=r!=null?v.makeArray(r):[],r.unshift(n),p=v.event.special[y]||{};if(p.trigger&&p.trigger.apply(s,r)===!1)return;m=[[s,p.bindType||y]];if(!o&&!p.noBubble&&!v.isWindow(s)){g=p.delegateType||y,l=Y.test(g+y)?s:s.parentNode;for(c=s;l;l=l.parentNode)m.push([l,g]),c=l;c===(s.ownerDocument||i)&&m.push([c.defaultView||c.parentWindow||e,g])}for(f=0;f=0:v.find(h,this,null,[s]).length),u[h]&&f.push(c);f.length&&w.push({elem:s,matches:f})}d.length>m&&w.push({elem:this,matches:d.slice(m)});for(r=0;r0?this.on(t,null,e,n):this.trigger(t)},Q.test(t)&&(v.event.fixHooks[t]=v.event.keyHooks),G.test(t)&&(v.event.fixHooks[t]=v.event.mouseHooks)}),function(e,t){function nt(e,t,n,r){n=n||[],t=t||g;var i,s,a,f,l=t.nodeType;if(!e||typeof e!="string")return n;if(l!==1&&l!==9)return[];a=o(t);if(!a&&!r)if(i=R.exec(e))if(f=i[1]){if(l===9){s=t.getElementById(f);if(!s||!s.parentNode)return n;if(s.id===f)return n.push(s),n}else if(t.ownerDocument&&(s=t.ownerDocument.getElementById(f))&&u(t,s)&&s.id===f)return n.push(s),n}else{if(i[2])return S.apply(n,x.call(t.getElementsByTagName(e),0)),n;if((f=i[3])&&Z&&t.getElementsByClassName)return S.apply(n,x.call(t.getElementsByClassName(f),0)),n}return vt(e.replace(j,"$1"),t,n,r,a)}function rt(e){return function(t){var n=t.nodeName.toLowerCase();return n==="input"&&t.type===e}}function it(e){return function(t){var n=t.nodeName.toLowerCase();return(n==="input"||n==="button")&&t.type===e}}function st(e){return N(function(t){return t=+t,N(function(n,r){var i,s=e([],n.length,t),o=s.length;while(o--)n[i=s[o]]&&(n[i]=!(r[i]=n[i]))})})}function ot(e,t,n){if(e===t)return n;var r=e.nextSibling;while(r){if(r===t)return-1;r=r.nextSibling}return 1}function ut(e,t){var n,r,s,o,u,a,f,l=L[d][e+" "];if(l)return t?0:l.slice(0);u=e,a=[],f=i.preFilter;while(u){if(!n||(r=F.exec(u)))r&&(u=u.slice(r[0].length)||u),a.push(s=[]);n=!1;if(r=I.exec(u))s.push(n=new m(r.shift())),u=u.slice(n.length),n.type=r[0].replace(j," ");for(o in i.filter)(r=J[o].exec(u))&&(!f[o]||(r=f[o](r)))&&(s.push(n=new m(r.shift())),u=u.slice(n.length),n.type=o,n.matches=r);if(!n)break}return t?u.length:u?nt.error(e):L(e,a).slice(0)}function at(e,t,r){var i=t.dir,s=r&&t.dir==="parentNode",o=w++;return t.first?function(t,n,r){while(t=t[i])if(s||t.nodeType===1)return e(t,n,r)}:function(t,r,u){if(!u){var a,f=b+" "+o+" ",l=f+n;while(t=t[i])if(s||t.nodeType===1){if((a=t[d])===l)return t.sizset;if(typeof a=="string"&&a.indexOf(f)===0){if(t.sizset)return t}else{t[d]=l;if(e(t,r,u))return t.sizset=!0,t;t.sizset=!1}}}else while(t=t[i])if(s||t.nodeType===1)if(e(t,r,u))return t}}function ft(e){return e.length>1?function(t,n,r){var i=e.length;while(i--)if(!e[i](t,n,r))return!1;return!0}:e[0]}function lt(e,t,n,r,i){var s,o=[],u=0,a=e.length,f=t!=null;for(;u-1&&(s[f]=!(o[f]=c))}}else g=lt(g===o?g.splice(d,g.length):g),i?i(null,o,g,a):S.apply(o,g)})}function ht(e){var t,n,r,s=e.length,o=i.relative[e[0].type],u=o||i.relative[" "],a=o?1:0,f=at(function(e){return e===t},u,!0),l=at(function(e){return T.call(t,e)>-1},u,!0),h=[function(e,n,r){return!o&&(r||n!==c)||((t=n).nodeType?f(e,n,r):l(e,n,r))}];for(;a1&&ft(h),a>1&&e.slice(0,a-1).join("").replace(j,"$1"),n,a0,s=e.length>0,o=function(u,a,f,l,h){var p,d,v,m=[],y=0,w="0",x=u&&[],T=h!=null,N=c,C=u||s&&i.find.TAG("*",h&&a.parentNode||a),k=b+=N==null?1:Math.E;T&&(c=a!==g&&a,n=o.el);for(;(p=C[w])!=null;w++){if(s&&p){for(d=0;v=e[d];d++)if(v(p,a,f)){l.push(p);break}T&&(b=k,n=++o.el)}r&&((p=!v&&p)&&y--,u&&x.push(p))}y+=w;if(r&&w!==y){for(d=0;v=t[d];d++)v(x,m,a,f);if(u){if(y>0)while(w--)!x[w]&&!m[w]&&(m[w]=E.call(l));m=lt(m)}S.apply(l,m),T&&!u&&m.length>0&&y+t.length>1&&nt.uniqueSort(l)}return T&&(b=k,c=N),x};return o.el=0,r?N(o):o}function dt(e,t,n){var r=0,i=t.length;for(;r2&&(f=u[0]).type==="ID"&&t.nodeType===9&&!s&&i.relative[u[1].type]){t=i.find.ID(f.matches[0].replace($,""),t,s)[0];if(!t)return n;e=e.slice(u.shift().length)}for(o=J.POS.test(e)?-1:u.length-1;o>=0;o--){f=u[o];if(i.relative[l=f.type])break;if(c=i.find[l])if(r=c(f.matches[0].replace($,""),z.test(u[0].type)&&t.parentNode||t,s)){u.splice(o,1),e=r.length&&u.join("");if(!e)return S.apply(n,x.call(r,0)),n;break}}}return a(e,h)(r,t,s,n,z.test(e)),n}function mt(){}var n,r,i,s,o,u,a,f,l,c,h=!0,p="undefined",d=("sizcache"+Math.random()).replace(".",""),m=String,g=e.document,y=g.documentElement,b=0,w=0,E=[].pop,S=[].push,x=[].slice,T=[].indexOf||function(e){var t=0,n=this.length;for(;ti.cacheLength&&delete e[t.shift()],e[n+" "]=r},e)},k=C(),L=C(),A=C(),O="[\\x20\\t\\r\\n\\f]",M="(?:\\\\.|[-\\w]|[^\\x00-\\xa0])+",_=M.replace("w","w#"),D="([*^$|!~]?=)",P="\\["+O+"*("+M+")"+O+"*(?:"+D+O+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+_+")|)|)"+O+"*\\]",H=":("+M+")(?:\\((?:(['\"])((?:\\\\.|[^\\\\])*?)\\2|([^()[\\]]*|(?:(?:"+P+")|[^:]|\\\\.)*|.*))\\)|)",B=":(even|odd|eq|gt|lt|nth|first|last)(?:\\("+O+"*((?:-\\d)?\\d*)"+O+"*\\)|)(?=[^-]|$)",j=new RegExp("^"+O+"+|((?:^|[^\\\\])(?:\\\\.)*)"+O+"+$","g"),F=new RegExp("^"+O+"*,"+O+"*"),I=new RegExp("^"+O+"*([\\x20\\t\\r\\n\\f>+~])"+O+"*"),q=new RegExp(H),R=/^(?:#([\w\-]+)|(\w+)|\.([\w\-]+))$/,U=/^:not/,z=/[\x20\t\r\n\f]*[+~]/,W=/:not\($/,X=/h\d/i,V=/input|select|textarea|button/i,$=/\\(?!\\)/g,J={ID:new RegExp("^#("+M+")"),CLASS:new RegExp("^\\.("+M+")"),NAME:new RegExp("^\\[name=['\"]?("+M+")['\"]?\\]"),TAG:new RegExp("^("+M.replace("w","w*")+")"),ATTR:new RegExp("^"+P),PSEUDO:new RegExp("^"+H),POS:new RegExp(B,"i"),CHILD:new RegExp("^:(only|nth|first|last)-child(?:\\("+O+"*(even|odd|(([+-]|)(\\d*)n|)"+O+"*(?:([+-]|)"+O+"*(\\d+)|))"+O+"*\\)|)","i"),needsContext:new RegExp("^"+O+"*[>+~]|"+B,"i")},K=function(e){var t=g.createElement("div");try{return e(t)}catch(n){return!1}finally{t=null}},Q=K(function(e){return e.appendChild(g.createComment("")),!e.getElementsByTagName("*").length}),G=K(function(e){return e.innerHTML="",e.firstChild&&typeof e.firstChild.getAttribute!==p&&e.firstChild.getAttribute("href")==="#"}),Y=K(function(e){e.innerHTML="";var t=typeof e.lastChild.getAttribute("multiple");return t!=="boolean"&&t!=="string"}),Z=K(function(e){return e.innerHTML="",!e.getElementsByClassName||!e.getElementsByClassName("e").length?!1:(e.lastChild.className="e",e.getElementsByClassName("e").length===2)}),et=K(function(e){e.id=d+0,e.innerHTML="
",y.insertBefore(e,y.firstChild);var t=g.getElementsByName&&g.getElementsByName(d).length===2+g.getElementsByName(d+0).length;return r=!g.getElementById(d),y.removeChild(e),t});try{x.call(y.childNodes,0)[0].nodeType}catch(tt){x=function(e){var t,n=[];for(;t=this[e];e++)n.push(t);return n}}nt.matches=function(e,t){return nt(e,null,null,t)},nt.matchesSelector=function(e,t){return nt(t,null,null,[e]).length>0},s=nt.getText=function(e){var t,n="",r=0,i=e.nodeType;if(i){if(i===1||i===9||i===11){if(typeof e.textContent=="string")return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=s(e)}else if(i===3||i===4)return e.nodeValue}else for(;t=e[r];r++)n+=s(t);return n},o=nt.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return t?t.nodeName!=="HTML":!1},u=nt.contains=y.contains?function(e,t){var n=e.nodeType===9?e.documentElement:e,r=t&&t.parentNode;return e===r||!!(r&&r.nodeType===1&&n.contains&&n.contains(r))}:y.compareDocumentPosition?function(e,t){return t&&!!(e.compareDocumentPosition(t)&16)}:function(e,t){while(t=t.parentNode)if(t===e)return!0;return!1},nt.attr=function(e,t){var n,r=o(e);return r||(t=t.toLowerCase()),(n=i.attrHandle[t])?n(e):r||Y?e.getAttribute(t):(n=e.getAttributeNode(t),n?typeof e[t]=="boolean"?e[t]?t:null:n.specified?n.value:null:null)},i=nt.selectors={cacheLength:50,createPseudo:N,match:J,attrHandle:G?{}:{href:function(e){return e.getAttribute("href",2)},type:function(e){return e.getAttribute("type")}},find:{ID:r?function(e,t,n){if(typeof t.getElementById!==p&&!n){var r=t.getElementById(e);return r&&r.parentNode?[r]:[]}}:function(e,n,r){if(typeof n.getElementById!==p&&!r){var i=n.getElementById(e);return i?i.id===e||typeof i.getAttributeNode!==p&&i.getAttributeNode("id").value===e?[i]:t:[]}},TAG:Q?function(e,t){if(typeof t.getElementsByTagName!==p)return t.getElementsByTagName(e)}:function(e,t){var n=t.getElementsByTagName(e);if(e==="*"){var r,i=[],s=0;for(;r=n[s];s++)r.nodeType===1&&i.push(r);return i}return n},NAME:et&&function(e,t){if(typeof t.getElementsByName!==p)return t.getElementsByName(name)},CLASS:Z&&function(e,t,n){if(typeof t.getElementsByClassName!==p&&!n)return t.getElementsByClassName(e)}},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace($,""),e[3]=(e[4]||e[5]||"").replace($,""),e[2]==="~="&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),e[1]==="nth"?(e[2]||nt.error(e[0]),e[3]=+(e[3]?e[4]+(e[5]||1):2*(e[2]==="even"||e[2]==="odd")),e[4]=+(e[6]+e[7]||e[2]==="odd")):e[2]&&nt.error(e[0]),e},PSEUDO:function(e){var t,n;if(J.CHILD.test(e[0]))return null;if(e[3])e[2]=e[3];else if(t=e[4])q.test(t)&&(n=ut(t,!0))&&(n=t.indexOf(")",t.length-n)-t.length)&&(t=t.slice(0,n),e[0]=e[0].slice(0,n)),e[2]=t;return e.slice(0,3)}},filter:{ID:r?function(e){return e=e.replace($,""),function(t){return t.getAttribute("id")===e}}:function(e){return e=e.replace($,""),function(t){var n=typeof t.getAttributeNode!==p&&t.getAttributeNode("id");return n&&n.value===e}},TAG:function(e){return e==="*"?function(){return!0}:(e=e.replace($,"").toLowerCase(),function(t){return t.nodeName&&t.nodeName.toLowerCase()===e})},CLASS:function(e){var t=k[d][e+" "];return t||(t=new RegExp("(^|"+O+")"+e+"("+O+"|$)"))&&k(e,function(e){return t.test(e.className||typeof e.getAttribute!==p&&e.getAttribute("class")||"")})},ATTR:function(e,t,n){return function(r,i){var s=nt.attr(r,e);return s==null?t==="!=":t?(s+="",t==="="?s===n:t==="!="?s!==n:t==="^="?n&&s.indexOf(n)===0:t==="*="?n&&s.indexOf(n)>-1:t==="$="?n&&s.substr(s.length-n.length)===n:t==="~="?(" "+s+" ").indexOf(n)>-1:t==="|="?s===n||s.substr(0,n.length+1)===n+"-":!1):!0}},CHILD:function(e,t,n,r){return e==="nth"?function(e){var t,i,s=e.parentNode;if(n===1&&r===0)return!0;if(s){i=0;for(t=s.firstChild;t;t=t.nextSibling)if(t.nodeType===1){i++;if(e===t)break}}return i-=r,i===n||i%n===0&&i/n>=0}:function(t){var n=t;switch(e){case"only":case"first":while(n=n.previousSibling)if(n.nodeType===1)return!1;if(e==="first")return!0;n=t;case"last":while(n=n.nextSibling)if(n.nodeType===1)return!1;return!0}}},PSEUDO:function(e,t){var n,r=i.pseudos[e]||i.setFilters[e.toLowerCase()]||nt.error("unsupported pseudo: "+e);return r[d]?r(t):r.length>1?(n=[e,e,"",t],i.setFilters.hasOwnProperty(e.toLowerCase())?N(function(e,n){var i,s=r(e,t),o=s.length;while(o--)i=T.call(e,s[o]),e[i]=!(n[i]=s[o])}):function(e){return r(e,0,n)}):r}},pseudos:{not:N(function(e){var t=[],n=[],r=a(e.replace(j,"$1"));return r[d]?N(function(e,t,n,i){var s,o=r(e,null,i,[]),u=e.length;while(u--)if(s=o[u])e[u]=!(t[u]=s)}):function(e,i,s){return t[0]=e,r(t,null,s,n),!n.pop()}}),has:N(function(e){return function(t){return nt(e,t).length>0}}),contains:N(function(e){return function(t){return(t.textContent||t.innerText||s(t)).indexOf(e)>-1}}),enabled:function(e){return e.disabled===!1},disabled:function(e){return e.disabled===!0},checked:function(e){var t=e.nodeName.toLowerCase();return t==="input"&&!!e.checked||t==="option"&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,e.selected===!0},parent:function(e){return!i.pseudos.empty(e)},empty:function(e){var t;e=e.firstChild;while(e){if(e.nodeName>"@"||(t=e.nodeType)===3||t===4)return!1;e=e.nextSibling}return!0},header:function(e){return X.test(e.nodeName)},text:function(e){var t,n;return e.nodeName.toLowerCase()==="input"&&(t=e.type)==="text"&&((n=e.getAttribute("type"))==null||n.toLowerCase()===t)},radio:rt("radio"),checkbox:rt("checkbox"),file:rt("file"),password:rt("password"),image:rt("image"),submit:it("submit"),reset:it("reset"),button:function(e){var t=e.nodeName.toLowerCase();return t==="input"&&e.type==="button"||t==="button"},input:function(e){return V.test(e.nodeName)},focus:function(e){var t=e.ownerDocument;return e===t.activeElement&&(!t.hasFocus||t.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},active:function(e){return e===e.ownerDocument.activeElement},first:st(function(){return[0]}),last:st(function(e,t){return[t-1]}),eq:st(function(e,t,n){return[n<0?n+t:n]}),even:st(function(e,t){for(var n=0;n=0;)e.push(r);return e}),gt:st(function(e,t,n){for(var r=n<0?n+t:n;++r",e.querySelectorAll("[selected]").length||i.push("\\["+O+"*(?:checked|disabled|ismap|multiple|readonly|selected|value)"),e.querySelectorAll(":checked").length||i.push(":checked")}),K(function(e){e.innerHTML="

",e.querySelectorAll("[test^='']").length&&i.push("[*^$]="+O+"*(?:\"\"|'')"),e.innerHTML="",e.querySelectorAll(":enabled").length||i.push(":enabled",":disabled")}),i=new RegExp(i.join("|")),vt=function(e,r,s,o,u){if(!o&&!u&&!i.test(e)){var a,f,l=!0,c=d,h=r,p=r.nodeType===9&&e;if(r.nodeType===1&&r.nodeName.toLowerCase()!=="object"){a=ut(e),(l=r.getAttribute("id"))?c=l.replace(n,"\\$&"):r.setAttribute("id",c),c="[id='"+c+"'] ",f=a.length;while(f--)a[f]=c+a[f].join("");h=z.test(e)&&r.parentNode||r,p=a.join(",")}if(p)try{return S.apply(s,x.call(h.querySelectorAll(p),0)),s}catch(v){}finally{l||r.removeAttribute("id")}}return t(e,r,s,o,u)},u&&(K(function(t){e=u.call(t,"div");try{u.call(t,"[test!='']:sizzle"),s.push("!=",H)}catch(n){}}),s=new RegExp(s.join("|")),nt.matchesSelector=function(t,n){n=n.replace(r,"='$1']");if(!o(t)&&!s.test(n)&&!i.test(n))try{var a=u.call(t,n);if(a||e||t.document&&t.document.nodeType!==11)return a}catch(f){}return nt(n,null,null,[t]).length>0})}(),i.pseudos.nth=i.pseudos.eq,i.filters=mt.prototype=i.pseudos,i.setFilters=new mt,nt.attr=v.attr,v.find=nt,v.expr=nt.selectors,v.expr[":"]=v.expr.pseudos,v.unique=nt.uniqueSort,v.text=nt.getText,v.isXMLDoc=nt.isXML,v.contains=nt.contains}(e);var nt=/Until$/,rt=/^(?:parents|prev(?:Until|All))/,it=/^.[^:#\[\.,]*$/,st=v.expr.match.needsContext,ot={children:!0,contents:!0,next:!0,prev:!0};v.fn.extend({find:function(e){var t,n,r,i,s,o,u=this;if(typeof e!="string")return v(e).filter(function(){for(t=0,n=u.length;t0)for(i=r;i=0:v.filter(e,this).length>0:this.filter(e).length>0)},closest:function(e,t){var n,r=0,i=this.length,s=[],o=st.test(e)||typeof e!="string"?v(e,t||this.context):0;for(;r-1:v.find.matchesSelector(n,e)){s.push(n);break}n=n.parentNode}}return s=s.length>1?v.unique(s):s,this.pushStack(s,"closest",e)},index:function(e){return e?typeof e=="string"?v.inArray(this[0],v(e)):v.inArray(e.jquery?e[0]:e,this):this[0]&&this[0].parentNode?this.prevAll().length:-1},add:function(e,t){var n=typeof e=="string"?v(e,t):v.makeArray(e&&e.nodeType?[e]:e),r=v.merge(this.get(),n);return this.pushStack(ut(n[0])||ut(r[0])?r:v.unique(r))},addBack:function(e){return this.add(e==null?this.prevObject:this.prevObject.filter(e))}}),v.fn.andSelf=v.fn.addBack,v.each({parent:function(e){var t=e.parentNode;return t&&t.nodeType!==11?t:null},parents:function(e){return v.dir(e,"parentNode")},parentsUntil:function(e,t,n){return v.dir(e,"parentNode",n)},next:function(e){return at(e,"nextSibling")},prev:function(e){return at(e,"previousSibling")},nextAll:function(e){return v.dir(e,"nextSibling")},prevAll:function(e){return v.dir(e,"previousSibling")},nextUntil:function(e,t,n){return v.dir(e,"nextSibling",n)},prevUntil:function(e,t,n){return v.dir(e,"previousSibling",n)},siblings:function(e){return v.sibling((e.parentNode||{}).firstChild,e)},children:function(e){return v.sibling(e.firstChild)},contents:function(e){return v.nodeName(e,"iframe")?e.contentDocument||e.contentWindow.document:v.merge([],e.childNodes)}},function(e,t){v.fn[e]=function(n,r){var i=v.map(this,t,n);return nt.test(e)||(r=n),r&&typeof r=="string"&&(i=v.filter(r,i)),i=this.length>1&&!ot[e]?v.unique(i):i,this.length>1&&rt.test(e)&&(i=i.reverse()),this.pushStack(i,e,l.call(arguments).join(","))}}),v.extend({filter:function(e,t,n){return n&&(e=":not("+e+")"),t.length===1?v.find.matchesSelector(t[0],e)?[t[0]]:[]:v.find.matches(e,t)},dir:function(e,n,r){var i=[],s=e[n];while(s&&s.nodeType!==9&&(r===t||s.nodeType!==1||!v(s).is(r)))s.nodeType===1&&i.push(s),s=s[n];return i},sibling:function(e,t){var n=[];for(;e;e=e.nextSibling)e.nodeType===1&&e!==t&&n.push(e);return n}});var ct="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",ht=/ jQuery\d+="(?:null|\d+)"/g,pt=/^\s+/,dt=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,vt=/<([\w:]+)/,mt=/]","i"),Et=/^(?:checkbox|radio)$/,St=/checked\s*(?:[^=]|=\s*.checked.)/i,xt=/\/(java|ecma)script/i,Tt=/^\s*\s*$/g,Nt={option:[1,""],legend:[1,"
","
"],thead:[1,"","
"],tr:[2,"","
"],td:[3,"","
"],col:[2,"","
"],area:[1,"",""],_default:[0,"",""]},Ct=lt(i),kt=Ct.appendChild(i.createElement("div"));Nt.optgroup=Nt.option,Nt.tbody=Nt.tfoot=Nt.colgroup=Nt.caption=Nt.thead,Nt.th=Nt.td,v.support.htmlSerialize||(Nt._default=[1,"X
","
"]),v.fn.extend({text:function(e){return v.access(this,function(e){return e===t?v.text(this):this.empty().append((this[0]&&this[0].ownerDocument||i).createTextNode(e))},null,e,arguments.length)},wrapAll:function(e){if(v.isFunction(e))return this.each(function(t){v(this).wrapAll(e.call(this,t))});if(this[0]){var t=v(e,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&t.insertBefore(this[0]),t.map(function(){var e=this;while(e.firstChild&&e.firstChild.nodeType===1)e=e.firstChild;return e}).append(this)}return this},wrapInner:function(e){return v.isFunction(e)?this.each(function(t){v(this).wrapInner(e.call(this,t))}):this.each(function(){var t=v(this),n=t.contents();n.length?n.wrapAll(e):t.append(e)})},wrap:function(e){var t=v.isFunction(e);return this.each(function(n){v(this).wrapAll(t?e.call(this,n):e)})},unwrap:function(){return this.parent().each(function(){v.nodeName(this,"body")||v(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(e){(this.nodeType===1||this.nodeType===11)&&this.appendChild(e)})},prepend:function(){return this.domManip(arguments,!0,function(e){(this.nodeType===1||this.nodeType===11)&&this.insertBefore(e,this.firstChild)})},before:function(){if(!ut(this[0]))return this.domManip(arguments,!1,function(e){this.parentNode.insertBefore(e,this)});if(arguments.length){var e=v.clean(arguments);return this.pushStack(v.merge(e,this),"before",this.selector)}},after:function(){if(!ut(this[0]))return this.domManip(arguments,!1,function(e){this.parentNode.insertBefore(e,this.nextSibling)});if(arguments.length){var e=v.clean(arguments);return this.pushStack(v.merge(this,e),"after",this.selector)}},remove:function(e,t){var n,r=0;for(;(n=this[r])!=null;r++)if(!e||v.filter(e,[n]).length)!t&&n.nodeType===1&&(v.cleanData(n.getElementsByTagName("*")),v.cleanData([n])),n.parentNode&&n.parentNode.removeChild(n);return this},empty:function(){var e,t=0;for(;(e=this[t])!=null;t++){e.nodeType===1&&v.cleanData(e.getElementsByTagName("*"));while(e.firstChild)e.removeChild(e.firstChild)}return this},clone:function(e,t){return e=e==null?!1:e,t=t==null?e:t,this.map(function(){return v.clone(this,e,t)})},html:function(e){return v.access(this,function(e){var n=this[0]||{},r=0,i=this.length;if(e===t)return n.nodeType===1?n.innerHTML.replace(ht,""):t;if(typeof e=="string"&&!yt.test(e)&&(v.support.htmlSerialize||!wt.test(e))&&(v.support.leadingWhitespace||!pt.test(e))&&!Nt[(vt.exec(e)||["",""])[1].toLowerCase()]){e=e.replace(dt,"<$1>");try{for(;r1&&typeof f=="string"&&St.test(f))return this.each(function(){v(this).domManip(e,n,r)});if(v.isFunction(f))return this.each(function(i){var s=v(this);e[0]=f.call(this,i,n?s.html():t),s.domManip(e,n,r)});if(this[0]){i=v.buildFragment(e,this,l),o=i.fragment,s=o.firstChild,o.childNodes.length===1&&(o=s);if(s){n=n&&v.nodeName(s,"tr");for(u=i.cacheable||c-1;a0?this.clone(!0):this).get(),v(o[i])[t](r),s=s.concat(r);return this.pushStack(s,e,o.selector)}}),v.extend({clone:function(e,t,n){var r,i,s,o;v.support.html5Clone||v.isXMLDoc(e)||!wt.test("<"+e.nodeName+">")?o=e.cloneNode(!0):(kt.innerHTML=e.outerHTML,kt.removeChild(o=kt.firstChild));if((!v.support.noCloneEvent||!v.support.noCloneChecked)&&(e.nodeType===1||e.nodeType===11)&&!v.isXMLDoc(e)){Ot(e,o),r=Mt(e),i=Mt(o);for(s=0;r[s];++s)i[s]&&Ot(r[s],i[s])}if(t){At(e,o);if(n){r=Mt(e),i=Mt(o);for(s=0;r[s];++s)At(r[s],i[s])}}return r=i=null,o},clean:function(e,t,n,r){var s,o,u,a,f,l,c,h,p,d,m,g,y=t===i&&Ct,b=[];if(!t||typeof t.createDocumentFragment=="undefined")t=i;for(s=0;(u=e[s])!=null;s++){typeof u=="number"&&(u+="");if(!u)continue;if(typeof u=="string")if(!gt.test(u))u=t.createTextNode(u);else{y=y||lt(t),c=t.createElement("div"),y.appendChild(c),u=u.replace(dt,"<$1>"),a=(vt.exec(u)||["",""])[1].toLowerCase(),f=Nt[a]||Nt._default,l=f[0],c.innerHTML=f[1]+u+f[2];while(l--)c=c.lastChild;if(!v.support.tbody){h=mt.test(u),p=a==="table"&&!h?c.firstChild&&c.firstChild.childNodes:f[1]===""&&!h?c.childNodes:[];for(o=p.length-1;o>=0;--o)v.nodeName(p[o],"tbody")&&!p[o].childNodes.length&&p[o].parentNode.removeChild(p[o])}!v.support.leadingWhitespace&&pt.test(u)&&c.insertBefore(t.createTextNode(pt.exec(u)[0]),c.firstChild),u=c.childNodes,c.parentNode.removeChild(c)}u.nodeType?b.push(u):v.merge(b,u)}c&&(u=c=y=null);if(!v.support.appendChecked)for(s=0;(u=b[s])!=null;s++)v.nodeName(u,"input")?_t(u):typeof u.getElementsByTagName!="undefined"&&v.grep(u.getElementsByTagName("input"),_t);if(n){m=function(e){if(!e.type||xt.test(e.type))return r?r.push(e.parentNode?e.parentNode.removeChild(e):e):n.appendChild(e)};for(s=0;(u=b[s])!=null;s++)if(!v.nodeName(u,"script")||!m(u))n.appendChild(u),typeof u.getElementsByTagName!="undefined"&&(g=v.grep(v.merge([],u.getElementsByTagName("script")),m),b.splice.apply(b,[s+1,0].concat(g)),s+=g.length)}return b},cleanData:function(e,t){var n,r,i,s,o=0,u=v.expando,a=v.cache,f=v.support.deleteExpando,l=v.event.special;for(;(i=e[o])!=null;o++)if(t||v.acceptData(i)){r=i[u],n=r&&a[r];if(n){if(n.events)for(s in n.events)l[s]?v.event.remove(i,s):v.removeEvent(i,s,n.handle);a[r]&&(delete a[r],f?delete i[u]:i.removeAttribute?i.removeAttribute(u):i[u]=null,v.deletedIds.push(r))}}}}),function(){var e,t;v.uaMatch=function(e){e=e.toLowerCase();var t=/(chrome)[ \/]([\w.]+)/.exec(e)||/(webkit)[ \/]([\w.]+)/.exec(e)||/(opera)(?:.*version|)[ \/]([\w.]+)/.exec(e)||/(msie) ([\w.]+)/.exec(e)||e.indexOf("compatible")<0&&/(mozilla)(?:.*? rv:([\w.]+)|)/.exec(e)||[];return{browser:t[1]||"",version:t[2]||"0"}},e=v.uaMatch(o.userAgent),t={},e.browser&&(t[e.browser]=!0,t.version=e.version),t.chrome?t.webkit=!0:t.webkit&&(t.safari=!0),v.browser=t,v.sub=function(){function e(t,n){return new e.fn.init(t,n)}v.extend(!0,e,this),e.superclass=this,e.fn=e.prototype=this(),e.fn.constructor=e,e.sub=this.sub,e.fn.init=function(r,i){return i&&i instanceof v&&!(i instanceof e)&&(i=e(i)),v.fn.init.call(this,r,i,t)},e.fn.init.prototype=e.fn;var t=e(i);return e}}();var Dt,Pt,Ht,Bt=/alpha\([^)]*\)/i,jt=/opacity=([^)]*)/,Ft=/^(top|right|bottom|left)$/,It=/^(none|table(?!-c[ea]).+)/,qt=/^margin/,Rt=new RegExp("^("+m+")(.*)$","i"),Ut=new RegExp("^("+m+")(?!px)[a-z%]+$","i"),zt=new RegExp("^([-+])=("+m+")","i"),Wt={BODY:"block"},Xt={position:"absolute",visibility:"hidden",display:"block"},Vt={letterSpacing:0,fontWeight:400},$t=["Top","Right","Bottom","Left"],Jt=["Webkit","O","Moz","ms"],Kt=v.fn.toggle;v.fn.extend({css:function(e,n){return v.access(this,function(e,n,r){return r!==t?v.style(e,n,r):v.css(e,n)},e,n,arguments.length>1)},show:function(){return Yt(this,!0)},hide:function(){return Yt(this)},toggle:function(e,t){var n=typeof e=="boolean";return v.isFunction(e)&&v.isFunction(t)?Kt.apply(this,arguments):this.each(function(){(n?e:Gt(this))?v(this).show():v(this).hide()})}}),v.extend({cssHooks:{opacity:{get:function(e,t){if(t){var n=Dt(e,"opacity");return n===""?"1":n}}}},cssNumber:{fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":v.support.cssFloat?"cssFloat":"styleFloat"},style:function(e,n,r,i){if(!e||e.nodeType===3||e.nodeType===8||!e.style)return;var s,o,u,a=v.camelCase(n),f=e.style;n=v.cssProps[a]||(v.cssProps[a]=Qt(f,a)),u=v.cssHooks[n]||v.cssHooks[a];if(r===t)return u&&"get"in u&&(s=u.get(e,!1,i))!==t?s:f[n];o=typeof r,o==="string"&&(s=zt.exec(r))&&(r=(s[1]+1)*s[2]+parseFloat(v.css(e,n)),o="number");if(r==null||o==="number"&&isNaN(r))return;o==="number"&&!v.cssNumber[a]&&(r+="px");if(!u||!("set"in u)||(r=u.set(e,r,i))!==t)try{f[n]=r}catch(l){}},css:function(e,n,r,i){var s,o,u,a=v.camelCase(n);return n=v.cssProps[a]||(v.cssProps[a]=Qt(e.style,a)),u=v.cssHooks[n]||v.cssHooks[a],u&&"get"in u&&(s=u.get(e,!0,i)),s===t&&(s=Dt(e,n)),s==="normal"&&n in Vt&&(s=Vt[n]),r||i!==t?(o=parseFloat(s),r||v.isNumeric(o)?o||0:s):s},swap:function(e,t,n){var r,i,s={};for(i in t)s[i]=e.style[i],e.style[i]=t[i];r=n.call(e);for(i in t)e.style[i]=s[i];return r}}),e.getComputedStyle?Dt=function(t,n){var r,i,s,o,u=e.getComputedStyle(t,null),a=t.style;return u&&(r=u.getPropertyValue(n)||u[n],r===""&&!v.contains(t.ownerDocument,t)&&(r=v.style(t,n)),Ut.test(r)&&qt.test(n)&&(i=a.width,s=a.minWidth,o=a.maxWidth,a.minWidth=a.maxWidth=a.width=r,r=u.width,a.width=i,a.minWidth=s,a.maxWidth=o)),r}:i.documentElement.currentStyle&&(Dt=function(e,t){var n,r,i=e.currentStyle&&e.currentStyle[t],s=e.style;return i==null&&s&&s[t]&&(i=s[t]),Ut.test(i)&&!Ft.test(t)&&(n=s.left,r=e.runtimeStyle&&e.runtimeStyle.left,r&&(e.runtimeStyle.left=e.currentStyle.left),s.left=t==="fontSize"?"1em":i,i=s.pixelLeft+"px",s.left=n,r&&(e.runtimeStyle.left=r)),i===""?"auto":i}),v.each(["height","width"],function(e,t){v.cssHooks[t]={get:function(e,n,r){if(n)return e.offsetWidth===0&&It.test(Dt(e,"display"))?v.swap(e,Xt,function(){return tn(e,t,r)}):tn(e,t,r)},set:function(e,n,r){return Zt(e,n,r?en(e,t,r,v.support.boxSizing&&v.css(e,"boxSizing")==="border-box"):0)}}}),v.support.opacity||(v.cssHooks.opacity={get:function(e,t){return jt.test((t&&e.currentStyle?e.currentStyle.filter:e.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":t?"1":""},set:function(e,t){var n=e.style,r=e.currentStyle,i=v.isNumeric(t)?"alpha(opacity="+t*100+")":"",s=r&&r.filter||n.filter||"";n.zoom=1;if(t>=1&&v.trim(s.replace(Bt,""))===""&&n.removeAttribute){n.removeAttribute("filter");if(r&&!r.filter)return}n.filter=Bt.test(s)?s.replace(Bt,i):s+" "+i}}),v(function(){v.support.reliableMarginRight||(v.cssHooks.marginRight={get:function(e,t){return v.swap(e,{display:"inline-block"},function(){if(t)return Dt(e,"marginRight")})}}),!v.support.pixelPosition&&v.fn.position&&v.each(["top","left"],function(e,t){v.cssHooks[t]={get:function(e,n){if(n){var r=Dt(e,t);return Ut.test(r)?v(e).position()[t]+"px":r}}}})}),v.expr&&v.expr.filters&&(v.expr.filters.hidden=function(e){return e.offsetWidth===0&&e.offsetHeight===0||!v.support.reliableHiddenOffsets&&(e.style&&e.style.display||Dt(e,"display"))==="none"},v.expr.filters.visible=function(e){return!v.expr.filters.hidden(e)}),v.each({margin:"",padding:"",border:"Width"},function(e,t){v.cssHooks[e+t]={expand:function(n){var r,i=typeof n=="string"?n.split(" "):[n],s={};for(r=0;r<4;r++)s[e+$t[r]+t]=i[r]||i[r-2]||i[0];return s}},qt.test(e)||(v.cssHooks[e+t].set=Zt)});var rn=/%20/g,sn=/\[\]$/,on=/\r?\n/g,un=/^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,an=/^(?:select|textarea)/i;v.fn.extend({serialize:function(){return v.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?v.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||an.test(this.nodeName)||un.test(this.type))}).map(function(e,t){var n=v(this).val();return n==null?null:v.isArray(n)?v.map(n,function(e,n){return{name:t.name,value:e.replace(on,"\r\n")}}):{name:t.name,value:n.replace(on,"\r\n")}}).get()}}),v.param=function(e,n){var r,i=[],s=function(e,t){t=v.isFunction(t)?t():t==null?"":t,i[i.length]=encodeURIComponent(e)+"="+encodeURIComponent(t)};n===t&&(n=v.ajaxSettings&&v.ajaxSettings.traditional);if(v.isArray(e)||e.jquery&&!v.isPlainObject(e))v.each(e,function(){s(this.name,this.value)});else for(r in e)fn(r,e[r],n,s);return i.join("&").replace(rn,"+")};var ln,cn,hn=/#.*$/,pn=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,dn=/^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,vn=/^(?:GET|HEAD)$/,mn=/^\/\//,gn=/\?/,yn=/)<[^<]*)*<\/script>/gi,bn=/([?&])_=[^&]*/,wn=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,En=v.fn.load,Sn={},xn={},Tn=["*/"]+["*"];try{cn=s.href}catch(Nn){cn=i.createElement("a"),cn.href="",cn=cn.href}ln=wn.exec(cn.toLowerCase())||[],v.fn.load=function(e,n,r){if(typeof e!="string"&&En)return En.apply(this,arguments);if(!this.length)return this;var i,s,o,u=this,a=e.indexOf(" ");return a>=0&&(i=e.slice(a,e.length),e=e.slice(0,a)),v.isFunction(n)?(r=n,n=t):n&&typeof n=="object"&&(s="POST"),v.ajax({url:e,type:s,dataType:"html",data:n,complete:function(e,t){r&&u.each(r,o||[e.responseText,t,e])}}).done(function(e){o=arguments,u.html(i?v("
").append(e.replace(yn,"")).find(i):e)}),this},v.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(e,t){v.fn[t]=function(e){return this.on(t,e)}}),v.each(["get","post"],function(e,n){v[n]=function(e,r,i,s){return v.isFunction(r)&&(s=s||i,i=r,r=t),v.ajax({type:n,url:e,data:r,success:i,dataType:s})}}),v.extend({getScript:function(e,n){return v.get(e,t,n,"script")},getJSON:function(e,t,n){return v.get(e,t,n,"json")},ajaxSetup:function(e,t){return t?Ln(e,v.ajaxSettings):(t=e,e=v.ajaxSettings),Ln(e,t),e},ajaxSettings:{url:cn,isLocal:dn.test(ln[1]),global:!0,type:"GET",contentType:"application/x-www-form-urlencoded; charset=UTF-8",processData:!0,async:!0,accepts:{xml:"application/xml, text/xml",html:"text/html",text:"text/plain",json:"application/json, text/javascript","*":Tn},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":e.String,"text html":!0,"text json":v.parseJSON,"text xml":v.parseXML},flatOptions:{context:!0,url:!0}},ajaxPrefilter:Cn(Sn),ajaxTransport:Cn(xn),ajax:function(e,n){function T(e,n,s,a){var l,y,b,w,S,T=n;if(E===2)return;E=2,u&&clearTimeout(u),o=t,i=a||"",x.readyState=e>0?4:0,s&&(w=An(c,x,s));if(e>=200&&e<300||e===304)c.ifModified&&(S=x.getResponseHeader("Last-Modified"),S&&(v.lastModified[r]=S),S=x.getResponseHeader("Etag"),S&&(v.etag[r]=S)),e===304?(T="notmodified",l=!0):(l=On(c,w),T=l.state,y=l.data,b=l.error,l=!b);else{b=T;if(!T||e)T="error",e<0&&(e=0)}x.status=e,x.statusText=(n||T)+"",l?d.resolveWith(h,[y,T,x]):d.rejectWith(h,[x,T,b]),x.statusCode(g),g=t,f&&p.trigger("ajax"+(l?"Success":"Error"),[x,c,l?y:b]),m.fireWith(h,[x,T]),f&&(p.trigger("ajaxComplete",[x,c]),--v.active||v.event.trigger("ajaxStop"))}typeof e=="object"&&(n=e,e=t),n=n||{};var r,i,s,o,u,a,f,l,c=v.ajaxSetup({},n),h=c.context||c,p=h!==c&&(h.nodeType||h instanceof v)?v(h):v.event,d=v.Deferred(),m=v.Callbacks("once memory"),g=c.statusCode||{},b={},w={},E=0,S="canceled",x={readyState:0,setRequestHeader:function(e,t){if(!E){var n=e.toLowerCase();e=w[n]=w[n]||e,b[e]=t}return this},getAllResponseHeaders:function(){return E===2?i:null},getResponseHeader:function(e){var n;if(E===2){if(!s){s={};while(n=pn.exec(i))s[n[1].toLowerCase()]=n[2]}n=s[e.toLowerCase()]}return n===t?null:n},overrideMimeType:function(e){return E||(c.mimeType=e),this},abort:function(e){return e=e||S,o&&o.abort(e),T(0,e),this}};d.promise(x),x.success=x.done,x.error=x.fail,x.complete=m.add,x.statusCode=function(e){if(e){var t;if(E<2)for(t in e)g[t]=[g[t],e[t]];else t=e[x.status],x.always(t)}return this},c.url=((e||c.url)+"").replace(hn,"").replace(mn,ln[1]+"//"),c.dataTypes=v.trim(c.dataType||"*").toLowerCase().split(y),c.crossDomain==null&&(a=wn.exec(c.url.toLowerCase()),c.crossDomain=!(!a||a[1]===ln[1]&&a[2]===ln[2]&&(a[3]||(a[1]==="http:"?80:443))==(ln[3]||(ln[1]==="http:"?80:443)))),c.data&&c.processData&&typeof c.data!="string"&&(c.data=v.param(c.data,c.traditional)),kn(Sn,c,n,x);if(E===2)return x;f=c.global,c.type=c.type.toUpperCase(),c.hasContent=!vn.test(c.type),f&&v.active++===0&&v.event.trigger("ajaxStart");if(!c.hasContent){c.data&&(c.url+=(gn.test(c.url)?"&":"?")+c.data,delete c.data),r=c.url;if(c.cache===!1){var N=v.now(),C=c.url.replace(bn,"$1_="+N);c.url=C+(C===c.url?(gn.test(c.url)?"&":"?")+"_="+N:"")}}(c.data&&c.hasContent&&c.contentType!==!1||n.contentType)&&x.setRequestHeader("Content-Type",c.contentType),c.ifModified&&(r=r||c.url,v.lastModified[r]&&x.setRequestHeader("If-Modified-Since",v.lastModified[r]),v.etag[r]&&x.setRequestHeader("If-None-Match",v.etag[r])),x.setRequestHeader("Accept",c.dataTypes[0]&&c.accepts[c.dataTypes[0]]?c.accepts[c.dataTypes[0]]+(c.dataTypes[0]!=="*"?", "+Tn+"; q=0.01":""):c.accepts["*"]);for(l in c.headers)x.setRequestHeader(l,c.headers[l]);if(!c.beforeSend||c.beforeSend.call(h,x,c)!==!1&&E!==2){S="abort";for(l in{success:1,error:1,complete:1})x[l](c[l]);o=kn(xn,c,n,x);if(!o)T(-1,"No Transport");else{x.readyState=1,f&&p.trigger("ajaxSend",[x,c]),c.async&&c.timeout>0&&(u=setTimeout(function(){x.abort("timeout")},c.timeout));try{E=1,o.send(b,T)}catch(k){if(!(E<2))throw k;T(-1,k)}}return x}return x.abort()},active:0,lastModified:{},etag:{}});var Mn=[],_n=/\?/,Dn=/(=)\?(?=&|$)|\?\?/,Pn=v.now();v.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=Mn.pop()||v.expando+"_"+Pn++;return this[e]=!0,e}}),v.ajaxPrefilter("json jsonp",function(n,r,i){var s,o,u,a=n.data,f=n.url,l=n.jsonp!==!1,c=l&&Dn.test(f),h=l&&!c&&typeof a=="string"&&!(n.contentType||"").indexOf("application/x-www-form-urlencoded")&&Dn.test(a);if(n.dataTypes[0]==="jsonp"||c||h)return s=n.jsonpCallback=v.isFunction(n.jsonpCallback)?n.jsonpCallback():n.jsonpCallback,o=e[s],c?n.url=f.replace(Dn,"$1"+s):h?n.data=a.replace(Dn,"$1"+s):l&&(n.url+=(_n.test(f)?"&":"?")+n.jsonp+"="+s),n.converters["script json"]=function(){return u||v.error(s+" was not called"),u[0]},n.dataTypes[0]="json",e[s]=function(){u=arguments},i.always(function(){e[s]=o,n[s]&&(n.jsonpCallback=r.jsonpCallback,Mn.push(s)),u&&v.isFunction(o)&&o(u[0]),u=o=t}),"script"}),v.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/javascript|ecmascript/},converters:{"text script":function(e){return v.globalEval(e),e}}}),v.ajaxPrefilter("script",function(e){e.cache===t&&(e.cache=!1),e.crossDomain&&(e.type="GET",e.global=!1)}),v.ajaxTransport("script",function(e){if(e.crossDomain){var n,r=i.head||i.getElementsByTagName("head")[0]||i.documentElement;return{send:function(s,o){n=i.createElement("script"),n.async="async",e.scriptCharset&&(n.charset=e.scriptCharset),n.src=e.url,n.onload=n.onreadystatechange=function(e,i){if(i||!n.readyState||/loaded|complete/.test(n.readyState))n.onload=n.onreadystatechange=null,r&&n.parentNode&&r.removeChild(n),n=t,i||o(200,"success")},r.insertBefore(n,r.firstChild)},abort:function(){n&&n.onload(0,1)}}}});var Hn,Bn=e.ActiveXObject?function(){for(var e in Hn)Hn[e](0,1)}:!1,jn=0;v.ajaxSettings.xhr=e.ActiveXObject?function(){return!this.isLocal&&Fn()||In()}:Fn,function(e){v.extend(v.support,{ajax:!!e,cors:!!e&&"withCredentials"in e})}(v.ajaxSettings.xhr()),v.support.ajax&&v.ajaxTransport(function(n){if(!n.crossDomain||v.support.cors){var r;return{send:function(i,s){var o,u,a=n.xhr();n.username?a.open(n.type,n.url,n.async,n.username,n.password):a.open(n.type,n.url,n.async);if(n.xhrFields)for(u in n.xhrFields)a[u]=n.xhrFields[u];n.mimeType&&a.overrideMimeType&&a.overrideMimeType(n.mimeType),!n.crossDomain&&!i["X-Requested-With"]&&(i["X-Requested-With"]="XMLHttpRequest");try{for(u in i)a.setRequestHeader(u,i[u])}catch(f){}a.send(n.hasContent&&n.data||null),r=function(e,i){var u,f,l,c,h;try{if(r&&(i||a.readyState===4)){r=t,o&&(a.onreadystatechange=v.noop,Bn&&delete Hn[o]);if(i)a.readyState!==4&&a.abort();else{u=a.status,l=a.getAllResponseHeaders(),c={},h=a.responseXML,h&&h.documentElement&&(c.xml=h);try{c.text=a.responseText}catch(p){}try{f=a.statusText}catch(p){f=""}!u&&n.isLocal&&!n.crossDomain?u=c.text?200:404:u===1223&&(u=204)}}}catch(d){i||s(-1,d)}c&&s(u,f,c,l)},n.async?a.readyState===4?setTimeout(r,0):(o=++jn,Bn&&(Hn||(Hn={},v(e).unload(Bn)),Hn[o]=r),a.onreadystatechange=r):r()},abort:function(){r&&r(0,1)}}}});var qn,Rn,Un=/^(?:toggle|show|hide)$/,zn=new RegExp("^(?:([-+])=|)("+m+")([a-z%]*)$","i"),Wn=/queueHooks$/,Xn=[Gn],Vn={"*":[function(e,t){var n,r,i=this.createTween(e,t),s=zn.exec(t),o=i.cur(),u=+o||0,a=1,f=20;if(s){n=+s[2],r=s[3]||(v.cssNumber[e]?"":"px");if(r!=="px"&&u){u=v.css(i.elem,e,!0)||n||1;do a=a||".5",u/=a,v.style(i.elem,e,u+r);while(a!==(a=i.cur()/o)&&a!==1&&--f)}i.unit=r,i.start=u,i.end=s[1]?u+(s[1]+1)*n:n}return i}]};v.Animation=v.extend(Kn,{tweener:function(e,t){v.isFunction(e)?(t=e,e=["*"]):e=e.split(" ");var n,r=0,i=e.length;for(;r-1,f={},l={},c,h;a?(l=i.position(),c=l.top,h=l.left):(c=parseFloat(o)||0,h=parseFloat(u)||0),v.isFunction(t)&&(t=t.call(e,n,s)),t.top!=null&&(f.top=t.top-s.top+c),t.left!=null&&(f.left=t.left-s.left+h),"using"in t?t.using.call(e,f):i.css(f)}},v.fn.extend({position:function(){if(!this[0])return;var e=this[0],t=this.offsetParent(),n=this.offset(),r=er.test(t[0].nodeName)?{top:0,left:0}:t.offset();return n.top-=parseFloat(v.css(e,"marginTop"))||0,n.left-=parseFloat(v.css(e,"marginLeft"))||0,r.top+=parseFloat(v.css(t[0],"borderTopWidth"))||0,r.left+=parseFloat(v.css(t[0],"borderLeftWidth"))||0,{top:n.top-r.top,left:n.left-r.left}},offsetParent:function(){return this.map(function(){var e=this.offsetParent||i.body;while(e&&!er.test(e.nodeName)&&v.css(e,"position")==="static")e=e.offsetParent;return e||i.body})}}),v.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(e,n){var r=/Y/.test(n);v.fn[e]=function(i){return v.access(this,function(e,i,s){var o=tr(e);if(s===t)return o?n in o?o[n]:o.document.documentElement[i]:e[i];o?o.scrollTo(r?v(o).scrollLeft():s,r?s:v(o).scrollTop()):e[i]=s},e,i,arguments.length,null)}}),v.each({Height:"height",Width:"width"},function(e,n){v.each({padding:"inner"+e,content:n,"":"outer"+e},function(r,i){v.fn[i]=function(i,s){var o=arguments.length&&(r||typeof i!="boolean"),u=r||(i===!0||s===!0?"margin":"border");return v.access(this,function(n,r,i){var s;return v.isWindow(n)?n.document.documentElement["client"+e]:n.nodeType===9?(s=n.documentElement,Math.max(n.body["scroll"+e],s["scroll"+e],n.body["offset"+e],s["offset"+e],s["client"+e])):i===t?v.css(n,r,i,u):v.style(n,r,i,u)},n,o?i:t,o,null)}})}),e.jQuery=e.$=v,typeof define=="function"&&define.amd&&define.amd.jQuery&&define("jquery",[],function(){return v})})(window); \ No newline at end of file diff --git a/Chapter07/02_basic_routing/content/mustache.js b/Chapter07/02_basic_routing/content/mustache.js new file mode 100644 index 0000000..0148d29 --- /dev/null +++ b/Chapter07/02_basic_routing/content/mustache.js @@ -0,0 +1,625 @@ +/*! + * mustache.js - Logic-less {{mustache}} templates with JavaScript + * http://github.com/janl/mustache.js + */ + +/*global define: false*/ + +var Mustache; + +(function (exports) { + if (typeof module !== "undefined" && module.exports) { + module.exports = exports; // CommonJS + } else if (typeof define === "function") { + define(exports); // AMD + } else { + Mustache = exports; // + + + + + + + diff --git a/Chapter07/03_handlers_as_modules/content/album.js b/Chapter07/03_handlers_as_modules/content/album.js new file mode 100644 index 0000000..f1faf68 --- /dev/null +++ b/Chapter07/03_handlers_as_modules/content/album.js @@ -0,0 +1,46 @@ +$(function(){ + + var tmpl, // Main template HTML + tdata = {}; // JSON data object that feeds the template + + // Initialise page + var initPage = function() { + + // get our album name. + parts = window.location.href.split("/"); + var album_name = parts[5]; + + // Load the HTML template + $.get("/templates/album.html", function(d){ + tmpl = d; + }); + + // Retrieve the server data and then initialise the page + $.getJSON("/v1/albums/" + album_name + ".json", function (d) { + var photo_d = massage_album(d); + $.extend(tdata, photo_d); + }); + + // When AJAX calls are complete parse the template + // replacing mustache tags with vars + $(document).ajaxStop(function () { + var renderedPage = Mustache.to_html( tmpl, tdata ); + $("body").html( renderedPage ); + }) + }(); +}); + + + +function massage_album(d) { + if (d.error != null) return d; + var obj = { photos: [] }; + + var af = d.data.album_data; + + for (var i = 0; i < af.photos.length; i++) { + var url = "/albums/" + af.short_name + "/" + af.photos[i].filename; + obj.photos.push({ url: url, desc: af.photos[i].filename }); + } + return obj; +} diff --git a/Chapter07/03_handlers_as_modules/content/home.js b/Chapter07/03_handlers_as_modules/content/home.js new file mode 100644 index 0000000..fa7010b --- /dev/null +++ b/Chapter07/03_handlers_as_modules/content/home.js @@ -0,0 +1,28 @@ +$(function(){ + + var tmpl, // Main template HTML + tdata = {}; // JSON data object that feeds the template + + // Initialise page + var initPage = function() { + + // Load the HTML template + $.get("/templates/home.html", function(d){ + tmpl = d; + }); + + + // Retrieve the server data and then initialise the page + $.getJSON("/v1/albums.json", function (d) { + $.extend(tdata, d.data); + }); + + // When AJAX calls are complete parse the template + // replacing mustache tags with vars + $(document).ajaxStop(function () { + var renderedPage = Mustache.to_html( tmpl, tdata ); + $("body").html( renderedPage ); + }) + }(); +}); + diff --git a/Chapter07/03_handlers_as_modules/content/jquery-1.8.3.min.js b/Chapter07/03_handlers_as_modules/content/jquery-1.8.3.min.js new file mode 100644 index 0000000..83589da --- /dev/null +++ b/Chapter07/03_handlers_as_modules/content/jquery-1.8.3.min.js @@ -0,0 +1,2 @@ +/*! jQuery v1.8.3 jquery.com | jquery.org/license */ +(function(e,t){function _(e){var t=M[e]={};return v.each(e.split(y),function(e,n){t[n]=!0}),t}function H(e,n,r){if(r===t&&e.nodeType===1){var i="data-"+n.replace(P,"-$1").toLowerCase();r=e.getAttribute(i);if(typeof r=="string"){try{r=r==="true"?!0:r==="false"?!1:r==="null"?null:+r+""===r?+r:D.test(r)?v.parseJSON(r):r}catch(s){}v.data(e,n,r)}else r=t}return r}function B(e){var t;for(t in e){if(t==="data"&&v.isEmptyObject(e[t]))continue;if(t!=="toJSON")return!1}return!0}function et(){return!1}function tt(){return!0}function ut(e){return!e||!e.parentNode||e.parentNode.nodeType===11}function at(e,t){do e=e[t];while(e&&e.nodeType!==1);return e}function ft(e,t,n){t=t||0;if(v.isFunction(t))return v.grep(e,function(e,r){var i=!!t.call(e,r,e);return i===n});if(t.nodeType)return v.grep(e,function(e,r){return e===t===n});if(typeof t=="string"){var r=v.grep(e,function(e){return e.nodeType===1});if(it.test(t))return v.filter(t,r,!n);t=v.filter(t,r)}return v.grep(e,function(e,r){return v.inArray(e,t)>=0===n})}function lt(e){var t=ct.split("|"),n=e.createDocumentFragment();if(n.createElement)while(t.length)n.createElement(t.pop());return n}function Lt(e,t){return e.getElementsByTagName(t)[0]||e.appendChild(e.ownerDocument.createElement(t))}function At(e,t){if(t.nodeType!==1||!v.hasData(e))return;var n,r,i,s=v._data(e),o=v._data(t,s),u=s.events;if(u){delete o.handle,o.events={};for(n in u)for(r=0,i=u[n].length;r").appendTo(i.body),n=t.css("display");t.remove();if(n==="none"||n===""){Pt=i.body.appendChild(Pt||v.extend(i.createElement("iframe"),{frameBorder:0,width:0,height:0}));if(!Ht||!Pt.createElement)Ht=(Pt.contentWindow||Pt.contentDocument).document,Ht.write(""),Ht.close();t=Ht.body.appendChild(Ht.createElement(e)),n=Dt(t,"display"),i.body.removeChild(Pt)}return Wt[e]=n,n}function fn(e,t,n,r){var i;if(v.isArray(t))v.each(t,function(t,i){n||sn.test(e)?r(e,i):fn(e+"["+(typeof i=="object"?t:"")+"]",i,n,r)});else if(!n&&v.type(t)==="object")for(i in t)fn(e+"["+i+"]",t[i],n,r);else r(e,t)}function Cn(e){return function(t,n){typeof t!="string"&&(n=t,t="*");var r,i,s,o=t.toLowerCase().split(y),u=0,a=o.length;if(v.isFunction(n))for(;u)[^>]*$|#([\w\-]*)$)/,E=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,S=/^[\],:{}\s]*$/,x=/(?:^|:|,)(?:\s*\[)+/g,T=/\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,N=/"[^"\\\r\n]*"|true|false|null|-?(?:\d\d*\.|)\d+(?:[eE][\-+]?\d+|)/g,C=/^-ms-/,k=/-([\da-z])/gi,L=function(e,t){return(t+"").toUpperCase()},A=function(){i.addEventListener?(i.removeEventListener("DOMContentLoaded",A,!1),v.ready()):i.readyState==="complete"&&(i.detachEvent("onreadystatechange",A),v.ready())},O={};v.fn=v.prototype={constructor:v,init:function(e,n,r){var s,o,u,a;if(!e)return this;if(e.nodeType)return this.context=this[0]=e,this.length=1,this;if(typeof e=="string"){e.charAt(0)==="<"&&e.charAt(e.length-1)===">"&&e.length>=3?s=[null,e,null]:s=w.exec(e);if(s&&(s[1]||!n)){if(s[1])return n=n instanceof v?n[0]:n,a=n&&n.nodeType?n.ownerDocument||n:i,e=v.parseHTML(s[1],a,!0),E.test(s[1])&&v.isPlainObject(n)&&this.attr.call(e,n,!0),v.merge(this,e);o=i.getElementById(s[2]);if(o&&o.parentNode){if(o.id!==s[2])return r.find(e);this.length=1,this[0]=o}return this.context=i,this.selector=e,this}return!n||n.jquery?(n||r).find(e):this.constructor(n).find(e)}return v.isFunction(e)?r.ready(e):(e.selector!==t&&(this.selector=e.selector,this.context=e.context),v.makeArray(e,this))},selector:"",jquery:"1.8.3",length:0,size:function(){return this.length},toArray:function(){return l.call(this)},get:function(e){return e==null?this.toArray():e<0?this[this.length+e]:this[e]},pushStack:function(e,t,n){var r=v.merge(this.constructor(),e);return r.prevObject=this,r.context=this.context,t==="find"?r.selector=this.selector+(this.selector?" ":"")+n:t&&(r.selector=this.selector+"."+t+"("+n+")"),r},each:function(e,t){return v.each(this,e,t)},ready:function(e){return v.ready.promise().done(e),this},eq:function(e){return e=+e,e===-1?this.slice(e):this.slice(e,e+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(l.apply(this,arguments),"slice",l.call(arguments).join(","))},map:function(e){return this.pushStack(v.map(this,function(t,n){return e.call(t,n,t)}))},end:function(){return this.prevObject||this.constructor(null)},push:f,sort:[].sort,splice:[].splice},v.fn.init.prototype=v.fn,v.extend=v.fn.extend=function(){var e,n,r,i,s,o,u=arguments[0]||{},a=1,f=arguments.length,l=!1;typeof u=="boolean"&&(l=u,u=arguments[1]||{},a=2),typeof u!="object"&&!v.isFunction(u)&&(u={}),f===a&&(u=this,--a);for(;a0)return;r.resolveWith(i,[v]),v.fn.trigger&&v(i).trigger("ready").off("ready")},isFunction:function(e){return v.type(e)==="function"},isArray:Array.isArray||function(e){return v.type(e)==="array"},isWindow:function(e){return e!=null&&e==e.window},isNumeric:function(e){return!isNaN(parseFloat(e))&&isFinite(e)},type:function(e){return e==null?String(e):O[h.call(e)]||"object"},isPlainObject:function(e){if(!e||v.type(e)!=="object"||e.nodeType||v.isWindow(e))return!1;try{if(e.constructor&&!p.call(e,"constructor")&&!p.call(e.constructor.prototype,"isPrototypeOf"))return!1}catch(n){return!1}var r;for(r in e);return r===t||p.call(e,r)},isEmptyObject:function(e){var t;for(t in e)return!1;return!0},error:function(e){throw new Error(e)},parseHTML:function(e,t,n){var r;return!e||typeof e!="string"?null:(typeof t=="boolean"&&(n=t,t=0),t=t||i,(r=E.exec(e))?[t.createElement(r[1])]:(r=v.buildFragment([e],t,n?null:[]),v.merge([],(r.cacheable?v.clone(r.fragment):r.fragment).childNodes)))},parseJSON:function(t){if(!t||typeof t!="string")return null;t=v.trim(t);if(e.JSON&&e.JSON.parse)return e.JSON.parse(t);if(S.test(t.replace(T,"@").replace(N,"]").replace(x,"")))return(new Function("return "+t))();v.error("Invalid JSON: "+t)},parseXML:function(n){var r,i;if(!n||typeof n!="string")return null;try{e.DOMParser?(i=new DOMParser,r=i.parseFromString(n,"text/xml")):(r=new ActiveXObject("Microsoft.XMLDOM"),r.async="false",r.loadXML(n))}catch(s){r=t}return(!r||!r.documentElement||r.getElementsByTagName("parsererror").length)&&v.error("Invalid XML: "+n),r},noop:function(){},globalEval:function(t){t&&g.test(t)&&(e.execScript||function(t){e.eval.call(e,t)})(t)},camelCase:function(e){return e.replace(C,"ms-").replace(k,L)},nodeName:function(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()},each:function(e,n,r){var i,s=0,o=e.length,u=o===t||v.isFunction(e);if(r){if(u){for(i in e)if(n.apply(e[i],r)===!1)break}else for(;s0&&e[0]&&e[a-1]||a===0||v.isArray(e));if(f)for(;u-1)a.splice(n,1),i&&(n<=o&&o--,n<=u&&u--)}),this},has:function(e){return v.inArray(e,a)>-1},empty:function(){return a=[],this},disable:function(){return a=f=n=t,this},disabled:function(){return!a},lock:function(){return f=t,n||c.disable(),this},locked:function(){return!f},fireWith:function(e,t){return t=t||[],t=[e,t.slice?t.slice():t],a&&(!r||f)&&(i?f.push(t):l(t)),this},fire:function(){return c.fireWith(this,arguments),this},fired:function(){return!!r}};return c},v.extend({Deferred:function(e){var t=[["resolve","done",v.Callbacks("once memory"),"resolved"],["reject","fail",v.Callbacks("once memory"),"rejected"],["notify","progress",v.Callbacks("memory")]],n="pending",r={state:function(){return n},always:function(){return i.done(arguments).fail(arguments),this},then:function(){var e=arguments;return v.Deferred(function(n){v.each(t,function(t,r){var s=r[0],o=e[t];i[r[1]](v.isFunction(o)?function(){var e=o.apply(this,arguments);e&&v.isFunction(e.promise)?e.promise().done(n.resolve).fail(n.reject).progress(n.notify):n[s+"With"](this===i?n:this,[e])}:n[s])}),e=null}).promise()},promise:function(e){return e!=null?v.extend(e,r):r}},i={};return r.pipe=r.then,v.each(t,function(e,s){var o=s[2],u=s[3];r[s[1]]=o.add,u&&o.add(function(){n=u},t[e^1][2].disable,t[2][2].lock),i[s[0]]=o.fire,i[s[0]+"With"]=o.fireWith}),r.promise(i),e&&e.call(i,i),i},when:function(e){var t=0,n=l.call(arguments),r=n.length,i=r!==1||e&&v.isFunction(e.promise)?r:0,s=i===1?e:v.Deferred(),o=function(e,t,n){return function(r){t[e]=this,n[e]=arguments.length>1?l.call(arguments):r,n===u?s.notifyWith(t,n):--i||s.resolveWith(t,n)}},u,a,f;if(r>1){u=new Array(r),a=new Array(r),f=new Array(r);for(;t
a",n=p.getElementsByTagName("*"),r=p.getElementsByTagName("a")[0];if(!n||!r||!n.length)return{};s=i.createElement("select"),o=s.appendChild(i.createElement("option")),u=p.getElementsByTagName("input")[0],r.style.cssText="top:1px;float:left;opacity:.5",t={leadingWhitespace:p.firstChild.nodeType===3,tbody:!p.getElementsByTagName("tbody").length,htmlSerialize:!!p.getElementsByTagName("link").length,style:/top/.test(r.getAttribute("style")),hrefNormalized:r.getAttribute("href")==="/a",opacity:/^0.5/.test(r.style.opacity),cssFloat:!!r.style.cssFloat,checkOn:u.value==="on",optSelected:o.selected,getSetAttribute:p.className!=="t",enctype:!!i.createElement("form").enctype,html5Clone:i.createElement("nav").cloneNode(!0).outerHTML!=="<:nav>",boxModel:i.compatMode==="CSS1Compat",submitBubbles:!0,changeBubbles:!0,focusinBubbles:!1,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0,boxSizingReliable:!0,pixelPosition:!1},u.checked=!0,t.noCloneChecked=u.cloneNode(!0).checked,s.disabled=!0,t.optDisabled=!o.disabled;try{delete p.test}catch(d){t.deleteExpando=!1}!p.addEventListener&&p.attachEvent&&p.fireEvent&&(p.attachEvent("onclick",h=function(){t.noCloneEvent=!1}),p.cloneNode(!0).fireEvent("onclick"),p.detachEvent("onclick",h)),u=i.createElement("input"),u.value="t",u.setAttribute("type","radio"),t.radioValue=u.value==="t",u.setAttribute("checked","checked"),u.setAttribute("name","t"),p.appendChild(u),a=i.createDocumentFragment(),a.appendChild(p.lastChild),t.checkClone=a.cloneNode(!0).cloneNode(!0).lastChild.checked,t.appendChecked=u.checked,a.removeChild(u),a.appendChild(p);if(p.attachEvent)for(l in{submit:!0,change:!0,focusin:!0})f="on"+l,c=f in p,c||(p.setAttribute(f,"return;"),c=typeof p[f]=="function"),t[l+"Bubbles"]=c;return v(function(){var n,r,s,o,u="padding:0;margin:0;border:0;display:block;overflow:hidden;",a=i.getElementsByTagName("body")[0];if(!a)return;n=i.createElement("div"),n.style.cssText="visibility:hidden;border:0;width:0;height:0;position:static;top:0;margin-top:1px",a.insertBefore(n,a.firstChild),r=i.createElement("div"),n.appendChild(r),r.innerHTML="
t
",s=r.getElementsByTagName("td"),s[0].style.cssText="padding:0;margin:0;border:0;display:none",c=s[0].offsetHeight===0,s[0].style.display="",s[1].style.display="none",t.reliableHiddenOffsets=c&&s[0].offsetHeight===0,r.innerHTML="",r.style.cssText="box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;",t.boxSizing=r.offsetWidth===4,t.doesNotIncludeMarginInBodyOffset=a.offsetTop!==1,e.getComputedStyle&&(t.pixelPosition=(e.getComputedStyle(r,null)||{}).top!=="1%",t.boxSizingReliable=(e.getComputedStyle(r,null)||{width:"4px"}).width==="4px",o=i.createElement("div"),o.style.cssText=r.style.cssText=u,o.style.marginRight=o.style.width="0",r.style.width="1px",r.appendChild(o),t.reliableMarginRight=!parseFloat((e.getComputedStyle(o,null)||{}).marginRight)),typeof r.style.zoom!="undefined"&&(r.innerHTML="",r.style.cssText=u+"width:1px;padding:1px;display:inline;zoom:1",t.inlineBlockNeedsLayout=r.offsetWidth===3,r.style.display="block",r.style.overflow="visible",r.innerHTML="
",r.firstChild.style.width="5px",t.shrinkWrapBlocks=r.offsetWidth!==3,n.style.zoom=1),a.removeChild(n),n=r=s=o=null}),a.removeChild(p),n=r=s=o=u=a=p=null,t}();var D=/(?:\{[\s\S]*\}|\[[\s\S]*\])$/,P=/([A-Z])/g;v.extend({cache:{},deletedIds:[],uuid:0,expando:"jQuery"+(v.fn.jquery+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(e){return e=e.nodeType?v.cache[e[v.expando]]:e[v.expando],!!e&&!B(e)},data:function(e,n,r,i){if(!v.acceptData(e))return;var s,o,u=v.expando,a=typeof n=="string",f=e.nodeType,l=f?v.cache:e,c=f?e[u]:e[u]&&u;if((!c||!l[c]||!i&&!l[c].data)&&a&&r===t)return;c||(f?e[u]=c=v.deletedIds.pop()||v.guid++:c=u),l[c]||(l[c]={},f||(l[c].toJSON=v.noop));if(typeof n=="object"||typeof n=="function")i?l[c]=v.extend(l[c],n):l[c].data=v.extend(l[c].data,n);return s=l[c],i||(s.data||(s.data={}),s=s.data),r!==t&&(s[v.camelCase(n)]=r),a?(o=s[n],o==null&&(o=s[v.camelCase(n)])):o=s,o},removeData:function(e,t,n){if(!v.acceptData(e))return;var r,i,s,o=e.nodeType,u=o?v.cache:e,a=o?e[v.expando]:v.expando;if(!u[a])return;if(t){r=n?u[a]:u[a].data;if(r){v.isArray(t)||(t in r?t=[t]:(t=v.camelCase(t),t in r?t=[t]:t=t.split(" ")));for(i=0,s=t.length;i1,null,!1))},removeData:function(e){return this.each(function(){v.removeData(this,e)})}}),v.extend({queue:function(e,t,n){var r;if(e)return t=(t||"fx")+"queue",r=v._data(e,t),n&&(!r||v.isArray(n)?r=v._data(e,t,v.makeArray(n)):r.push(n)),r||[]},dequeue:function(e,t){t=t||"fx";var n=v.queue(e,t),r=n.length,i=n.shift(),s=v._queueHooks(e,t),o=function(){v.dequeue(e,t)};i==="inprogress"&&(i=n.shift(),r--),i&&(t==="fx"&&n.unshift("inprogress"),delete s.stop,i.call(e,o,s)),!r&&s&&s.empty.fire()},_queueHooks:function(e,t){var n=t+"queueHooks";return v._data(e,n)||v._data(e,n,{empty:v.Callbacks("once memory").add(function(){v.removeData(e,t+"queue",!0),v.removeData(e,n,!0)})})}}),v.fn.extend({queue:function(e,n){var r=2;return typeof e!="string"&&(n=e,e="fx",r--),arguments.length1)},removeAttr:function(e){return this.each(function(){v.removeAttr(this,e)})},prop:function(e,t){return v.access(this,v.prop,e,t,arguments.length>1)},removeProp:function(e){return e=v.propFix[e]||e,this.each(function(){try{this[e]=t,delete this[e]}catch(n){}})},addClass:function(e){var t,n,r,i,s,o,u;if(v.isFunction(e))return this.each(function(t){v(this).addClass(e.call(this,t,this.className))});if(e&&typeof e=="string"){t=e.split(y);for(n=0,r=this.length;n=0)r=r.replace(" "+n[s]+" "," ");i.className=e?v.trim(r):""}}}return this},toggleClass:function(e,t){var n=typeof e,r=typeof t=="boolean";return v.isFunction(e)?this.each(function(n){v(this).toggleClass(e.call(this,n,this.className,t),t)}):this.each(function(){if(n==="string"){var i,s=0,o=v(this),u=t,a=e.split(y);while(i=a[s++])u=r?u:!o.hasClass(i),o[u?"addClass":"removeClass"](i)}else if(n==="undefined"||n==="boolean")this.className&&v._data(this,"__className__",this.className),this.className=this.className||e===!1?"":v._data(this,"__className__")||""})},hasClass:function(e){var t=" "+e+" ",n=0,r=this.length;for(;n=0)return!0;return!1},val:function(e){var n,r,i,s=this[0];if(!arguments.length){if(s)return n=v.valHooks[s.type]||v.valHooks[s.nodeName.toLowerCase()],n&&"get"in n&&(r=n.get(s,"value"))!==t?r:(r=s.value,typeof r=="string"?r.replace(R,""):r==null?"":r);return}return i=v.isFunction(e),this.each(function(r){var s,o=v(this);if(this.nodeType!==1)return;i?s=e.call(this,r,o.val()):s=e,s==null?s="":typeof s=="number"?s+="":v.isArray(s)&&(s=v.map(s,function(e){return e==null?"":e+""})),n=v.valHooks[this.type]||v.valHooks[this.nodeName.toLowerCase()];if(!n||!("set"in n)||n.set(this,s,"value")===t)this.value=s})}}),v.extend({valHooks:{option:{get:function(e){var t=e.attributes.value;return!t||t.specified?e.value:e.text}},select:{get:function(e){var t,n,r=e.options,i=e.selectedIndex,s=e.type==="select-one"||i<0,o=s?null:[],u=s?i+1:r.length,a=i<0?u:s?i:0;for(;a=0}),n.length||(e.selectedIndex=-1),n}}},attrFn:{},attr:function(e,n,r,i){var s,o,u,a=e.nodeType;if(!e||a===3||a===8||a===2)return;if(i&&v.isFunction(v.fn[n]))return v(e)[n](r);if(typeof e.getAttribute=="undefined")return v.prop(e,n,r);u=a!==1||!v.isXMLDoc(e),u&&(n=n.toLowerCase(),o=v.attrHooks[n]||(X.test(n)?F:j));if(r!==t){if(r===null){v.removeAttr(e,n);return}return o&&"set"in o&&u&&(s=o.set(e,r,n))!==t?s:(e.setAttribute(n,r+""),r)}return o&&"get"in o&&u&&(s=o.get(e,n))!==null?s:(s=e.getAttribute(n),s===null?t:s)},removeAttr:function(e,t){var n,r,i,s,o=0;if(t&&e.nodeType===1){r=t.split(y);for(;o=0}})});var $=/^(?:textarea|input|select)$/i,J=/^([^\.]*|)(?:\.(.+)|)$/,K=/(?:^|\s)hover(\.\S+|)\b/,Q=/^key/,G=/^(?:mouse|contextmenu)|click/,Y=/^(?:focusinfocus|focusoutblur)$/,Z=function(e){return v.event.special.hover?e:e.replace(K,"mouseenter$1 mouseleave$1")};v.event={add:function(e,n,r,i,s){var o,u,a,f,l,c,h,p,d,m,g;if(e.nodeType===3||e.nodeType===8||!n||!r||!(o=v._data(e)))return;r.handler&&(d=r,r=d.handler,s=d.selector),r.guid||(r.guid=v.guid++),a=o.events,a||(o.events=a={}),u=o.handle,u||(o.handle=u=function(e){return typeof v=="undefined"||!!e&&v.event.triggered===e.type?t:v.event.dispatch.apply(u.elem,arguments)},u.elem=e),n=v.trim(Z(n)).split(" ");for(f=0;f=0&&(y=y.slice(0,-1),a=!0),y.indexOf(".")>=0&&(b=y.split("."),y=b.shift(),b.sort());if((!s||v.event.customEvent[y])&&!v.event.global[y])return;n=typeof n=="object"?n[v.expando]?n:new v.Event(y,n):new v.Event(y),n.type=y,n.isTrigger=!0,n.exclusive=a,n.namespace=b.join("."),n.namespace_re=n.namespace?new RegExp("(^|\\.)"+b.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,h=y.indexOf(":")<0?"on"+y:"";if(!s){u=v.cache;for(f in u)u[f].events&&u[f].events[y]&&v.event.trigger(n,r,u[f].handle.elem,!0);return}n.result=t,n.target||(n.target=s),r=r!=null?v.makeArray(r):[],r.unshift(n),p=v.event.special[y]||{};if(p.trigger&&p.trigger.apply(s,r)===!1)return;m=[[s,p.bindType||y]];if(!o&&!p.noBubble&&!v.isWindow(s)){g=p.delegateType||y,l=Y.test(g+y)?s:s.parentNode;for(c=s;l;l=l.parentNode)m.push([l,g]),c=l;c===(s.ownerDocument||i)&&m.push([c.defaultView||c.parentWindow||e,g])}for(f=0;f=0:v.find(h,this,null,[s]).length),u[h]&&f.push(c);f.length&&w.push({elem:s,matches:f})}d.length>m&&w.push({elem:this,matches:d.slice(m)});for(r=0;r0?this.on(t,null,e,n):this.trigger(t)},Q.test(t)&&(v.event.fixHooks[t]=v.event.keyHooks),G.test(t)&&(v.event.fixHooks[t]=v.event.mouseHooks)}),function(e,t){function nt(e,t,n,r){n=n||[],t=t||g;var i,s,a,f,l=t.nodeType;if(!e||typeof e!="string")return n;if(l!==1&&l!==9)return[];a=o(t);if(!a&&!r)if(i=R.exec(e))if(f=i[1]){if(l===9){s=t.getElementById(f);if(!s||!s.parentNode)return n;if(s.id===f)return n.push(s),n}else if(t.ownerDocument&&(s=t.ownerDocument.getElementById(f))&&u(t,s)&&s.id===f)return n.push(s),n}else{if(i[2])return S.apply(n,x.call(t.getElementsByTagName(e),0)),n;if((f=i[3])&&Z&&t.getElementsByClassName)return S.apply(n,x.call(t.getElementsByClassName(f),0)),n}return vt(e.replace(j,"$1"),t,n,r,a)}function rt(e){return function(t){var n=t.nodeName.toLowerCase();return n==="input"&&t.type===e}}function it(e){return function(t){var n=t.nodeName.toLowerCase();return(n==="input"||n==="button")&&t.type===e}}function st(e){return N(function(t){return t=+t,N(function(n,r){var i,s=e([],n.length,t),o=s.length;while(o--)n[i=s[o]]&&(n[i]=!(r[i]=n[i]))})})}function ot(e,t,n){if(e===t)return n;var r=e.nextSibling;while(r){if(r===t)return-1;r=r.nextSibling}return 1}function ut(e,t){var n,r,s,o,u,a,f,l=L[d][e+" "];if(l)return t?0:l.slice(0);u=e,a=[],f=i.preFilter;while(u){if(!n||(r=F.exec(u)))r&&(u=u.slice(r[0].length)||u),a.push(s=[]);n=!1;if(r=I.exec(u))s.push(n=new m(r.shift())),u=u.slice(n.length),n.type=r[0].replace(j," ");for(o in i.filter)(r=J[o].exec(u))&&(!f[o]||(r=f[o](r)))&&(s.push(n=new m(r.shift())),u=u.slice(n.length),n.type=o,n.matches=r);if(!n)break}return t?u.length:u?nt.error(e):L(e,a).slice(0)}function at(e,t,r){var i=t.dir,s=r&&t.dir==="parentNode",o=w++;return t.first?function(t,n,r){while(t=t[i])if(s||t.nodeType===1)return e(t,n,r)}:function(t,r,u){if(!u){var a,f=b+" "+o+" ",l=f+n;while(t=t[i])if(s||t.nodeType===1){if((a=t[d])===l)return t.sizset;if(typeof a=="string"&&a.indexOf(f)===0){if(t.sizset)return t}else{t[d]=l;if(e(t,r,u))return t.sizset=!0,t;t.sizset=!1}}}else while(t=t[i])if(s||t.nodeType===1)if(e(t,r,u))return t}}function ft(e){return e.length>1?function(t,n,r){var i=e.length;while(i--)if(!e[i](t,n,r))return!1;return!0}:e[0]}function lt(e,t,n,r,i){var s,o=[],u=0,a=e.length,f=t!=null;for(;u-1&&(s[f]=!(o[f]=c))}}else g=lt(g===o?g.splice(d,g.length):g),i?i(null,o,g,a):S.apply(o,g)})}function ht(e){var t,n,r,s=e.length,o=i.relative[e[0].type],u=o||i.relative[" "],a=o?1:0,f=at(function(e){return e===t},u,!0),l=at(function(e){return T.call(t,e)>-1},u,!0),h=[function(e,n,r){return!o&&(r||n!==c)||((t=n).nodeType?f(e,n,r):l(e,n,r))}];for(;a1&&ft(h),a>1&&e.slice(0,a-1).join("").replace(j,"$1"),n,a0,s=e.length>0,o=function(u,a,f,l,h){var p,d,v,m=[],y=0,w="0",x=u&&[],T=h!=null,N=c,C=u||s&&i.find.TAG("*",h&&a.parentNode||a),k=b+=N==null?1:Math.E;T&&(c=a!==g&&a,n=o.el);for(;(p=C[w])!=null;w++){if(s&&p){for(d=0;v=e[d];d++)if(v(p,a,f)){l.push(p);break}T&&(b=k,n=++o.el)}r&&((p=!v&&p)&&y--,u&&x.push(p))}y+=w;if(r&&w!==y){for(d=0;v=t[d];d++)v(x,m,a,f);if(u){if(y>0)while(w--)!x[w]&&!m[w]&&(m[w]=E.call(l));m=lt(m)}S.apply(l,m),T&&!u&&m.length>0&&y+t.length>1&&nt.uniqueSort(l)}return T&&(b=k,c=N),x};return o.el=0,r?N(o):o}function dt(e,t,n){var r=0,i=t.length;for(;r2&&(f=u[0]).type==="ID"&&t.nodeType===9&&!s&&i.relative[u[1].type]){t=i.find.ID(f.matches[0].replace($,""),t,s)[0];if(!t)return n;e=e.slice(u.shift().length)}for(o=J.POS.test(e)?-1:u.length-1;o>=0;o--){f=u[o];if(i.relative[l=f.type])break;if(c=i.find[l])if(r=c(f.matches[0].replace($,""),z.test(u[0].type)&&t.parentNode||t,s)){u.splice(o,1),e=r.length&&u.join("");if(!e)return S.apply(n,x.call(r,0)),n;break}}}return a(e,h)(r,t,s,n,z.test(e)),n}function mt(){}var n,r,i,s,o,u,a,f,l,c,h=!0,p="undefined",d=("sizcache"+Math.random()).replace(".",""),m=String,g=e.document,y=g.documentElement,b=0,w=0,E=[].pop,S=[].push,x=[].slice,T=[].indexOf||function(e){var t=0,n=this.length;for(;ti.cacheLength&&delete e[t.shift()],e[n+" "]=r},e)},k=C(),L=C(),A=C(),O="[\\x20\\t\\r\\n\\f]",M="(?:\\\\.|[-\\w]|[^\\x00-\\xa0])+",_=M.replace("w","w#"),D="([*^$|!~]?=)",P="\\["+O+"*("+M+")"+O+"*(?:"+D+O+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+_+")|)|)"+O+"*\\]",H=":("+M+")(?:\\((?:(['\"])((?:\\\\.|[^\\\\])*?)\\2|([^()[\\]]*|(?:(?:"+P+")|[^:]|\\\\.)*|.*))\\)|)",B=":(even|odd|eq|gt|lt|nth|first|last)(?:\\("+O+"*((?:-\\d)?\\d*)"+O+"*\\)|)(?=[^-]|$)",j=new RegExp("^"+O+"+|((?:^|[^\\\\])(?:\\\\.)*)"+O+"+$","g"),F=new RegExp("^"+O+"*,"+O+"*"),I=new RegExp("^"+O+"*([\\x20\\t\\r\\n\\f>+~])"+O+"*"),q=new RegExp(H),R=/^(?:#([\w\-]+)|(\w+)|\.([\w\-]+))$/,U=/^:not/,z=/[\x20\t\r\n\f]*[+~]/,W=/:not\($/,X=/h\d/i,V=/input|select|textarea|button/i,$=/\\(?!\\)/g,J={ID:new RegExp("^#("+M+")"),CLASS:new RegExp("^\\.("+M+")"),NAME:new RegExp("^\\[name=['\"]?("+M+")['\"]?\\]"),TAG:new RegExp("^("+M.replace("w","w*")+")"),ATTR:new RegExp("^"+P),PSEUDO:new RegExp("^"+H),POS:new RegExp(B,"i"),CHILD:new RegExp("^:(only|nth|first|last)-child(?:\\("+O+"*(even|odd|(([+-]|)(\\d*)n|)"+O+"*(?:([+-]|)"+O+"*(\\d+)|))"+O+"*\\)|)","i"),needsContext:new RegExp("^"+O+"*[>+~]|"+B,"i")},K=function(e){var t=g.createElement("div");try{return e(t)}catch(n){return!1}finally{t=null}},Q=K(function(e){return e.appendChild(g.createComment("")),!e.getElementsByTagName("*").length}),G=K(function(e){return e.innerHTML="",e.firstChild&&typeof e.firstChild.getAttribute!==p&&e.firstChild.getAttribute("href")==="#"}),Y=K(function(e){e.innerHTML="";var t=typeof e.lastChild.getAttribute("multiple");return t!=="boolean"&&t!=="string"}),Z=K(function(e){return e.innerHTML="",!e.getElementsByClassName||!e.getElementsByClassName("e").length?!1:(e.lastChild.className="e",e.getElementsByClassName("e").length===2)}),et=K(function(e){e.id=d+0,e.innerHTML="
",y.insertBefore(e,y.firstChild);var t=g.getElementsByName&&g.getElementsByName(d).length===2+g.getElementsByName(d+0).length;return r=!g.getElementById(d),y.removeChild(e),t});try{x.call(y.childNodes,0)[0].nodeType}catch(tt){x=function(e){var t,n=[];for(;t=this[e];e++)n.push(t);return n}}nt.matches=function(e,t){return nt(e,null,null,t)},nt.matchesSelector=function(e,t){return nt(t,null,null,[e]).length>0},s=nt.getText=function(e){var t,n="",r=0,i=e.nodeType;if(i){if(i===1||i===9||i===11){if(typeof e.textContent=="string")return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=s(e)}else if(i===3||i===4)return e.nodeValue}else for(;t=e[r];r++)n+=s(t);return n},o=nt.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return t?t.nodeName!=="HTML":!1},u=nt.contains=y.contains?function(e,t){var n=e.nodeType===9?e.documentElement:e,r=t&&t.parentNode;return e===r||!!(r&&r.nodeType===1&&n.contains&&n.contains(r))}:y.compareDocumentPosition?function(e,t){return t&&!!(e.compareDocumentPosition(t)&16)}:function(e,t){while(t=t.parentNode)if(t===e)return!0;return!1},nt.attr=function(e,t){var n,r=o(e);return r||(t=t.toLowerCase()),(n=i.attrHandle[t])?n(e):r||Y?e.getAttribute(t):(n=e.getAttributeNode(t),n?typeof e[t]=="boolean"?e[t]?t:null:n.specified?n.value:null:null)},i=nt.selectors={cacheLength:50,createPseudo:N,match:J,attrHandle:G?{}:{href:function(e){return e.getAttribute("href",2)},type:function(e){return e.getAttribute("type")}},find:{ID:r?function(e,t,n){if(typeof t.getElementById!==p&&!n){var r=t.getElementById(e);return r&&r.parentNode?[r]:[]}}:function(e,n,r){if(typeof n.getElementById!==p&&!r){var i=n.getElementById(e);return i?i.id===e||typeof i.getAttributeNode!==p&&i.getAttributeNode("id").value===e?[i]:t:[]}},TAG:Q?function(e,t){if(typeof t.getElementsByTagName!==p)return t.getElementsByTagName(e)}:function(e,t){var n=t.getElementsByTagName(e);if(e==="*"){var r,i=[],s=0;for(;r=n[s];s++)r.nodeType===1&&i.push(r);return i}return n},NAME:et&&function(e,t){if(typeof t.getElementsByName!==p)return t.getElementsByName(name)},CLASS:Z&&function(e,t,n){if(typeof t.getElementsByClassName!==p&&!n)return t.getElementsByClassName(e)}},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace($,""),e[3]=(e[4]||e[5]||"").replace($,""),e[2]==="~="&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),e[1]==="nth"?(e[2]||nt.error(e[0]),e[3]=+(e[3]?e[4]+(e[5]||1):2*(e[2]==="even"||e[2]==="odd")),e[4]=+(e[6]+e[7]||e[2]==="odd")):e[2]&&nt.error(e[0]),e},PSEUDO:function(e){var t,n;if(J.CHILD.test(e[0]))return null;if(e[3])e[2]=e[3];else if(t=e[4])q.test(t)&&(n=ut(t,!0))&&(n=t.indexOf(")",t.length-n)-t.length)&&(t=t.slice(0,n),e[0]=e[0].slice(0,n)),e[2]=t;return e.slice(0,3)}},filter:{ID:r?function(e){return e=e.replace($,""),function(t){return t.getAttribute("id")===e}}:function(e){return e=e.replace($,""),function(t){var n=typeof t.getAttributeNode!==p&&t.getAttributeNode("id");return n&&n.value===e}},TAG:function(e){return e==="*"?function(){return!0}:(e=e.replace($,"").toLowerCase(),function(t){return t.nodeName&&t.nodeName.toLowerCase()===e})},CLASS:function(e){var t=k[d][e+" "];return t||(t=new RegExp("(^|"+O+")"+e+"("+O+"|$)"))&&k(e,function(e){return t.test(e.className||typeof e.getAttribute!==p&&e.getAttribute("class")||"")})},ATTR:function(e,t,n){return function(r,i){var s=nt.attr(r,e);return s==null?t==="!=":t?(s+="",t==="="?s===n:t==="!="?s!==n:t==="^="?n&&s.indexOf(n)===0:t==="*="?n&&s.indexOf(n)>-1:t==="$="?n&&s.substr(s.length-n.length)===n:t==="~="?(" "+s+" ").indexOf(n)>-1:t==="|="?s===n||s.substr(0,n.length+1)===n+"-":!1):!0}},CHILD:function(e,t,n,r){return e==="nth"?function(e){var t,i,s=e.parentNode;if(n===1&&r===0)return!0;if(s){i=0;for(t=s.firstChild;t;t=t.nextSibling)if(t.nodeType===1){i++;if(e===t)break}}return i-=r,i===n||i%n===0&&i/n>=0}:function(t){var n=t;switch(e){case"only":case"first":while(n=n.previousSibling)if(n.nodeType===1)return!1;if(e==="first")return!0;n=t;case"last":while(n=n.nextSibling)if(n.nodeType===1)return!1;return!0}}},PSEUDO:function(e,t){var n,r=i.pseudos[e]||i.setFilters[e.toLowerCase()]||nt.error("unsupported pseudo: "+e);return r[d]?r(t):r.length>1?(n=[e,e,"",t],i.setFilters.hasOwnProperty(e.toLowerCase())?N(function(e,n){var i,s=r(e,t),o=s.length;while(o--)i=T.call(e,s[o]),e[i]=!(n[i]=s[o])}):function(e){return r(e,0,n)}):r}},pseudos:{not:N(function(e){var t=[],n=[],r=a(e.replace(j,"$1"));return r[d]?N(function(e,t,n,i){var s,o=r(e,null,i,[]),u=e.length;while(u--)if(s=o[u])e[u]=!(t[u]=s)}):function(e,i,s){return t[0]=e,r(t,null,s,n),!n.pop()}}),has:N(function(e){return function(t){return nt(e,t).length>0}}),contains:N(function(e){return function(t){return(t.textContent||t.innerText||s(t)).indexOf(e)>-1}}),enabled:function(e){return e.disabled===!1},disabled:function(e){return e.disabled===!0},checked:function(e){var t=e.nodeName.toLowerCase();return t==="input"&&!!e.checked||t==="option"&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,e.selected===!0},parent:function(e){return!i.pseudos.empty(e)},empty:function(e){var t;e=e.firstChild;while(e){if(e.nodeName>"@"||(t=e.nodeType)===3||t===4)return!1;e=e.nextSibling}return!0},header:function(e){return X.test(e.nodeName)},text:function(e){var t,n;return e.nodeName.toLowerCase()==="input"&&(t=e.type)==="text"&&((n=e.getAttribute("type"))==null||n.toLowerCase()===t)},radio:rt("radio"),checkbox:rt("checkbox"),file:rt("file"),password:rt("password"),image:rt("image"),submit:it("submit"),reset:it("reset"),button:function(e){var t=e.nodeName.toLowerCase();return t==="input"&&e.type==="button"||t==="button"},input:function(e){return V.test(e.nodeName)},focus:function(e){var t=e.ownerDocument;return e===t.activeElement&&(!t.hasFocus||t.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},active:function(e){return e===e.ownerDocument.activeElement},first:st(function(){return[0]}),last:st(function(e,t){return[t-1]}),eq:st(function(e,t,n){return[n<0?n+t:n]}),even:st(function(e,t){for(var n=0;n=0;)e.push(r);return e}),gt:st(function(e,t,n){for(var r=n<0?n+t:n;++r",e.querySelectorAll("[selected]").length||i.push("\\["+O+"*(?:checked|disabled|ismap|multiple|readonly|selected|value)"),e.querySelectorAll(":checked").length||i.push(":checked")}),K(function(e){e.innerHTML="

",e.querySelectorAll("[test^='']").length&&i.push("[*^$]="+O+"*(?:\"\"|'')"),e.innerHTML="",e.querySelectorAll(":enabled").length||i.push(":enabled",":disabled")}),i=new RegExp(i.join("|")),vt=function(e,r,s,o,u){if(!o&&!u&&!i.test(e)){var a,f,l=!0,c=d,h=r,p=r.nodeType===9&&e;if(r.nodeType===1&&r.nodeName.toLowerCase()!=="object"){a=ut(e),(l=r.getAttribute("id"))?c=l.replace(n,"\\$&"):r.setAttribute("id",c),c="[id='"+c+"'] ",f=a.length;while(f--)a[f]=c+a[f].join("");h=z.test(e)&&r.parentNode||r,p=a.join(",")}if(p)try{return S.apply(s,x.call(h.querySelectorAll(p),0)),s}catch(v){}finally{l||r.removeAttribute("id")}}return t(e,r,s,o,u)},u&&(K(function(t){e=u.call(t,"div");try{u.call(t,"[test!='']:sizzle"),s.push("!=",H)}catch(n){}}),s=new RegExp(s.join("|")),nt.matchesSelector=function(t,n){n=n.replace(r,"='$1']");if(!o(t)&&!s.test(n)&&!i.test(n))try{var a=u.call(t,n);if(a||e||t.document&&t.document.nodeType!==11)return a}catch(f){}return nt(n,null,null,[t]).length>0})}(),i.pseudos.nth=i.pseudos.eq,i.filters=mt.prototype=i.pseudos,i.setFilters=new mt,nt.attr=v.attr,v.find=nt,v.expr=nt.selectors,v.expr[":"]=v.expr.pseudos,v.unique=nt.uniqueSort,v.text=nt.getText,v.isXMLDoc=nt.isXML,v.contains=nt.contains}(e);var nt=/Until$/,rt=/^(?:parents|prev(?:Until|All))/,it=/^.[^:#\[\.,]*$/,st=v.expr.match.needsContext,ot={children:!0,contents:!0,next:!0,prev:!0};v.fn.extend({find:function(e){var t,n,r,i,s,o,u=this;if(typeof e!="string")return v(e).filter(function(){for(t=0,n=u.length;t0)for(i=r;i=0:v.filter(e,this).length>0:this.filter(e).length>0)},closest:function(e,t){var n,r=0,i=this.length,s=[],o=st.test(e)||typeof e!="string"?v(e,t||this.context):0;for(;r-1:v.find.matchesSelector(n,e)){s.push(n);break}n=n.parentNode}}return s=s.length>1?v.unique(s):s,this.pushStack(s,"closest",e)},index:function(e){return e?typeof e=="string"?v.inArray(this[0],v(e)):v.inArray(e.jquery?e[0]:e,this):this[0]&&this[0].parentNode?this.prevAll().length:-1},add:function(e,t){var n=typeof e=="string"?v(e,t):v.makeArray(e&&e.nodeType?[e]:e),r=v.merge(this.get(),n);return this.pushStack(ut(n[0])||ut(r[0])?r:v.unique(r))},addBack:function(e){return this.add(e==null?this.prevObject:this.prevObject.filter(e))}}),v.fn.andSelf=v.fn.addBack,v.each({parent:function(e){var t=e.parentNode;return t&&t.nodeType!==11?t:null},parents:function(e){return v.dir(e,"parentNode")},parentsUntil:function(e,t,n){return v.dir(e,"parentNode",n)},next:function(e){return at(e,"nextSibling")},prev:function(e){return at(e,"previousSibling")},nextAll:function(e){return v.dir(e,"nextSibling")},prevAll:function(e){return v.dir(e,"previousSibling")},nextUntil:function(e,t,n){return v.dir(e,"nextSibling",n)},prevUntil:function(e,t,n){return v.dir(e,"previousSibling",n)},siblings:function(e){return v.sibling((e.parentNode||{}).firstChild,e)},children:function(e){return v.sibling(e.firstChild)},contents:function(e){return v.nodeName(e,"iframe")?e.contentDocument||e.contentWindow.document:v.merge([],e.childNodes)}},function(e,t){v.fn[e]=function(n,r){var i=v.map(this,t,n);return nt.test(e)||(r=n),r&&typeof r=="string"&&(i=v.filter(r,i)),i=this.length>1&&!ot[e]?v.unique(i):i,this.length>1&&rt.test(e)&&(i=i.reverse()),this.pushStack(i,e,l.call(arguments).join(","))}}),v.extend({filter:function(e,t,n){return n&&(e=":not("+e+")"),t.length===1?v.find.matchesSelector(t[0],e)?[t[0]]:[]:v.find.matches(e,t)},dir:function(e,n,r){var i=[],s=e[n];while(s&&s.nodeType!==9&&(r===t||s.nodeType!==1||!v(s).is(r)))s.nodeType===1&&i.push(s),s=s[n];return i},sibling:function(e,t){var n=[];for(;e;e=e.nextSibling)e.nodeType===1&&e!==t&&n.push(e);return n}});var ct="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",ht=/ jQuery\d+="(?:null|\d+)"/g,pt=/^\s+/,dt=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,vt=/<([\w:]+)/,mt=/]","i"),Et=/^(?:checkbox|radio)$/,St=/checked\s*(?:[^=]|=\s*.checked.)/i,xt=/\/(java|ecma)script/i,Tt=/^\s*\s*$/g,Nt={option:[1,""],legend:[1,"
","
"],thead:[1,"","
"],tr:[2,"","
"],td:[3,"","
"],col:[2,"","
"],area:[1,"",""],_default:[0,"",""]},Ct=lt(i),kt=Ct.appendChild(i.createElement("div"));Nt.optgroup=Nt.option,Nt.tbody=Nt.tfoot=Nt.colgroup=Nt.caption=Nt.thead,Nt.th=Nt.td,v.support.htmlSerialize||(Nt._default=[1,"X
","
"]),v.fn.extend({text:function(e){return v.access(this,function(e){return e===t?v.text(this):this.empty().append((this[0]&&this[0].ownerDocument||i).createTextNode(e))},null,e,arguments.length)},wrapAll:function(e){if(v.isFunction(e))return this.each(function(t){v(this).wrapAll(e.call(this,t))});if(this[0]){var t=v(e,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&t.insertBefore(this[0]),t.map(function(){var e=this;while(e.firstChild&&e.firstChild.nodeType===1)e=e.firstChild;return e}).append(this)}return this},wrapInner:function(e){return v.isFunction(e)?this.each(function(t){v(this).wrapInner(e.call(this,t))}):this.each(function(){var t=v(this),n=t.contents();n.length?n.wrapAll(e):t.append(e)})},wrap:function(e){var t=v.isFunction(e);return this.each(function(n){v(this).wrapAll(t?e.call(this,n):e)})},unwrap:function(){return this.parent().each(function(){v.nodeName(this,"body")||v(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(e){(this.nodeType===1||this.nodeType===11)&&this.appendChild(e)})},prepend:function(){return this.domManip(arguments,!0,function(e){(this.nodeType===1||this.nodeType===11)&&this.insertBefore(e,this.firstChild)})},before:function(){if(!ut(this[0]))return this.domManip(arguments,!1,function(e){this.parentNode.insertBefore(e,this)});if(arguments.length){var e=v.clean(arguments);return this.pushStack(v.merge(e,this),"before",this.selector)}},after:function(){if(!ut(this[0]))return this.domManip(arguments,!1,function(e){this.parentNode.insertBefore(e,this.nextSibling)});if(arguments.length){var e=v.clean(arguments);return this.pushStack(v.merge(this,e),"after",this.selector)}},remove:function(e,t){var n,r=0;for(;(n=this[r])!=null;r++)if(!e||v.filter(e,[n]).length)!t&&n.nodeType===1&&(v.cleanData(n.getElementsByTagName("*")),v.cleanData([n])),n.parentNode&&n.parentNode.removeChild(n);return this},empty:function(){var e,t=0;for(;(e=this[t])!=null;t++){e.nodeType===1&&v.cleanData(e.getElementsByTagName("*"));while(e.firstChild)e.removeChild(e.firstChild)}return this},clone:function(e,t){return e=e==null?!1:e,t=t==null?e:t,this.map(function(){return v.clone(this,e,t)})},html:function(e){return v.access(this,function(e){var n=this[0]||{},r=0,i=this.length;if(e===t)return n.nodeType===1?n.innerHTML.replace(ht,""):t;if(typeof e=="string"&&!yt.test(e)&&(v.support.htmlSerialize||!wt.test(e))&&(v.support.leadingWhitespace||!pt.test(e))&&!Nt[(vt.exec(e)||["",""])[1].toLowerCase()]){e=e.replace(dt,"<$1>");try{for(;r1&&typeof f=="string"&&St.test(f))return this.each(function(){v(this).domManip(e,n,r)});if(v.isFunction(f))return this.each(function(i){var s=v(this);e[0]=f.call(this,i,n?s.html():t),s.domManip(e,n,r)});if(this[0]){i=v.buildFragment(e,this,l),o=i.fragment,s=o.firstChild,o.childNodes.length===1&&(o=s);if(s){n=n&&v.nodeName(s,"tr");for(u=i.cacheable||c-1;a0?this.clone(!0):this).get(),v(o[i])[t](r),s=s.concat(r);return this.pushStack(s,e,o.selector)}}),v.extend({clone:function(e,t,n){var r,i,s,o;v.support.html5Clone||v.isXMLDoc(e)||!wt.test("<"+e.nodeName+">")?o=e.cloneNode(!0):(kt.innerHTML=e.outerHTML,kt.removeChild(o=kt.firstChild));if((!v.support.noCloneEvent||!v.support.noCloneChecked)&&(e.nodeType===1||e.nodeType===11)&&!v.isXMLDoc(e)){Ot(e,o),r=Mt(e),i=Mt(o);for(s=0;r[s];++s)i[s]&&Ot(r[s],i[s])}if(t){At(e,o);if(n){r=Mt(e),i=Mt(o);for(s=0;r[s];++s)At(r[s],i[s])}}return r=i=null,o},clean:function(e,t,n,r){var s,o,u,a,f,l,c,h,p,d,m,g,y=t===i&&Ct,b=[];if(!t||typeof t.createDocumentFragment=="undefined")t=i;for(s=0;(u=e[s])!=null;s++){typeof u=="number"&&(u+="");if(!u)continue;if(typeof u=="string")if(!gt.test(u))u=t.createTextNode(u);else{y=y||lt(t),c=t.createElement("div"),y.appendChild(c),u=u.replace(dt,"<$1>"),a=(vt.exec(u)||["",""])[1].toLowerCase(),f=Nt[a]||Nt._default,l=f[0],c.innerHTML=f[1]+u+f[2];while(l--)c=c.lastChild;if(!v.support.tbody){h=mt.test(u),p=a==="table"&&!h?c.firstChild&&c.firstChild.childNodes:f[1]===""&&!h?c.childNodes:[];for(o=p.length-1;o>=0;--o)v.nodeName(p[o],"tbody")&&!p[o].childNodes.length&&p[o].parentNode.removeChild(p[o])}!v.support.leadingWhitespace&&pt.test(u)&&c.insertBefore(t.createTextNode(pt.exec(u)[0]),c.firstChild),u=c.childNodes,c.parentNode.removeChild(c)}u.nodeType?b.push(u):v.merge(b,u)}c&&(u=c=y=null);if(!v.support.appendChecked)for(s=0;(u=b[s])!=null;s++)v.nodeName(u,"input")?_t(u):typeof u.getElementsByTagName!="undefined"&&v.grep(u.getElementsByTagName("input"),_t);if(n){m=function(e){if(!e.type||xt.test(e.type))return r?r.push(e.parentNode?e.parentNode.removeChild(e):e):n.appendChild(e)};for(s=0;(u=b[s])!=null;s++)if(!v.nodeName(u,"script")||!m(u))n.appendChild(u),typeof u.getElementsByTagName!="undefined"&&(g=v.grep(v.merge([],u.getElementsByTagName("script")),m),b.splice.apply(b,[s+1,0].concat(g)),s+=g.length)}return b},cleanData:function(e,t){var n,r,i,s,o=0,u=v.expando,a=v.cache,f=v.support.deleteExpando,l=v.event.special;for(;(i=e[o])!=null;o++)if(t||v.acceptData(i)){r=i[u],n=r&&a[r];if(n){if(n.events)for(s in n.events)l[s]?v.event.remove(i,s):v.removeEvent(i,s,n.handle);a[r]&&(delete a[r],f?delete i[u]:i.removeAttribute?i.removeAttribute(u):i[u]=null,v.deletedIds.push(r))}}}}),function(){var e,t;v.uaMatch=function(e){e=e.toLowerCase();var t=/(chrome)[ \/]([\w.]+)/.exec(e)||/(webkit)[ \/]([\w.]+)/.exec(e)||/(opera)(?:.*version|)[ \/]([\w.]+)/.exec(e)||/(msie) ([\w.]+)/.exec(e)||e.indexOf("compatible")<0&&/(mozilla)(?:.*? rv:([\w.]+)|)/.exec(e)||[];return{browser:t[1]||"",version:t[2]||"0"}},e=v.uaMatch(o.userAgent),t={},e.browser&&(t[e.browser]=!0,t.version=e.version),t.chrome?t.webkit=!0:t.webkit&&(t.safari=!0),v.browser=t,v.sub=function(){function e(t,n){return new e.fn.init(t,n)}v.extend(!0,e,this),e.superclass=this,e.fn=e.prototype=this(),e.fn.constructor=e,e.sub=this.sub,e.fn.init=function(r,i){return i&&i instanceof v&&!(i instanceof e)&&(i=e(i)),v.fn.init.call(this,r,i,t)},e.fn.init.prototype=e.fn;var t=e(i);return e}}();var Dt,Pt,Ht,Bt=/alpha\([^)]*\)/i,jt=/opacity=([^)]*)/,Ft=/^(top|right|bottom|left)$/,It=/^(none|table(?!-c[ea]).+)/,qt=/^margin/,Rt=new RegExp("^("+m+")(.*)$","i"),Ut=new RegExp("^("+m+")(?!px)[a-z%]+$","i"),zt=new RegExp("^([-+])=("+m+")","i"),Wt={BODY:"block"},Xt={position:"absolute",visibility:"hidden",display:"block"},Vt={letterSpacing:0,fontWeight:400},$t=["Top","Right","Bottom","Left"],Jt=["Webkit","O","Moz","ms"],Kt=v.fn.toggle;v.fn.extend({css:function(e,n){return v.access(this,function(e,n,r){return r!==t?v.style(e,n,r):v.css(e,n)},e,n,arguments.length>1)},show:function(){return Yt(this,!0)},hide:function(){return Yt(this)},toggle:function(e,t){var n=typeof e=="boolean";return v.isFunction(e)&&v.isFunction(t)?Kt.apply(this,arguments):this.each(function(){(n?e:Gt(this))?v(this).show():v(this).hide()})}}),v.extend({cssHooks:{opacity:{get:function(e,t){if(t){var n=Dt(e,"opacity");return n===""?"1":n}}}},cssNumber:{fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":v.support.cssFloat?"cssFloat":"styleFloat"},style:function(e,n,r,i){if(!e||e.nodeType===3||e.nodeType===8||!e.style)return;var s,o,u,a=v.camelCase(n),f=e.style;n=v.cssProps[a]||(v.cssProps[a]=Qt(f,a)),u=v.cssHooks[n]||v.cssHooks[a];if(r===t)return u&&"get"in u&&(s=u.get(e,!1,i))!==t?s:f[n];o=typeof r,o==="string"&&(s=zt.exec(r))&&(r=(s[1]+1)*s[2]+parseFloat(v.css(e,n)),o="number");if(r==null||o==="number"&&isNaN(r))return;o==="number"&&!v.cssNumber[a]&&(r+="px");if(!u||!("set"in u)||(r=u.set(e,r,i))!==t)try{f[n]=r}catch(l){}},css:function(e,n,r,i){var s,o,u,a=v.camelCase(n);return n=v.cssProps[a]||(v.cssProps[a]=Qt(e.style,a)),u=v.cssHooks[n]||v.cssHooks[a],u&&"get"in u&&(s=u.get(e,!0,i)),s===t&&(s=Dt(e,n)),s==="normal"&&n in Vt&&(s=Vt[n]),r||i!==t?(o=parseFloat(s),r||v.isNumeric(o)?o||0:s):s},swap:function(e,t,n){var r,i,s={};for(i in t)s[i]=e.style[i],e.style[i]=t[i];r=n.call(e);for(i in t)e.style[i]=s[i];return r}}),e.getComputedStyle?Dt=function(t,n){var r,i,s,o,u=e.getComputedStyle(t,null),a=t.style;return u&&(r=u.getPropertyValue(n)||u[n],r===""&&!v.contains(t.ownerDocument,t)&&(r=v.style(t,n)),Ut.test(r)&&qt.test(n)&&(i=a.width,s=a.minWidth,o=a.maxWidth,a.minWidth=a.maxWidth=a.width=r,r=u.width,a.width=i,a.minWidth=s,a.maxWidth=o)),r}:i.documentElement.currentStyle&&(Dt=function(e,t){var n,r,i=e.currentStyle&&e.currentStyle[t],s=e.style;return i==null&&s&&s[t]&&(i=s[t]),Ut.test(i)&&!Ft.test(t)&&(n=s.left,r=e.runtimeStyle&&e.runtimeStyle.left,r&&(e.runtimeStyle.left=e.currentStyle.left),s.left=t==="fontSize"?"1em":i,i=s.pixelLeft+"px",s.left=n,r&&(e.runtimeStyle.left=r)),i===""?"auto":i}),v.each(["height","width"],function(e,t){v.cssHooks[t]={get:function(e,n,r){if(n)return e.offsetWidth===0&&It.test(Dt(e,"display"))?v.swap(e,Xt,function(){return tn(e,t,r)}):tn(e,t,r)},set:function(e,n,r){return Zt(e,n,r?en(e,t,r,v.support.boxSizing&&v.css(e,"boxSizing")==="border-box"):0)}}}),v.support.opacity||(v.cssHooks.opacity={get:function(e,t){return jt.test((t&&e.currentStyle?e.currentStyle.filter:e.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":t?"1":""},set:function(e,t){var n=e.style,r=e.currentStyle,i=v.isNumeric(t)?"alpha(opacity="+t*100+")":"",s=r&&r.filter||n.filter||"";n.zoom=1;if(t>=1&&v.trim(s.replace(Bt,""))===""&&n.removeAttribute){n.removeAttribute("filter");if(r&&!r.filter)return}n.filter=Bt.test(s)?s.replace(Bt,i):s+" "+i}}),v(function(){v.support.reliableMarginRight||(v.cssHooks.marginRight={get:function(e,t){return v.swap(e,{display:"inline-block"},function(){if(t)return Dt(e,"marginRight")})}}),!v.support.pixelPosition&&v.fn.position&&v.each(["top","left"],function(e,t){v.cssHooks[t]={get:function(e,n){if(n){var r=Dt(e,t);return Ut.test(r)?v(e).position()[t]+"px":r}}}})}),v.expr&&v.expr.filters&&(v.expr.filters.hidden=function(e){return e.offsetWidth===0&&e.offsetHeight===0||!v.support.reliableHiddenOffsets&&(e.style&&e.style.display||Dt(e,"display"))==="none"},v.expr.filters.visible=function(e){return!v.expr.filters.hidden(e)}),v.each({margin:"",padding:"",border:"Width"},function(e,t){v.cssHooks[e+t]={expand:function(n){var r,i=typeof n=="string"?n.split(" "):[n],s={};for(r=0;r<4;r++)s[e+$t[r]+t]=i[r]||i[r-2]||i[0];return s}},qt.test(e)||(v.cssHooks[e+t].set=Zt)});var rn=/%20/g,sn=/\[\]$/,on=/\r?\n/g,un=/^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,an=/^(?:select|textarea)/i;v.fn.extend({serialize:function(){return v.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?v.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||an.test(this.nodeName)||un.test(this.type))}).map(function(e,t){var n=v(this).val();return n==null?null:v.isArray(n)?v.map(n,function(e,n){return{name:t.name,value:e.replace(on,"\r\n")}}):{name:t.name,value:n.replace(on,"\r\n")}}).get()}}),v.param=function(e,n){var r,i=[],s=function(e,t){t=v.isFunction(t)?t():t==null?"":t,i[i.length]=encodeURIComponent(e)+"="+encodeURIComponent(t)};n===t&&(n=v.ajaxSettings&&v.ajaxSettings.traditional);if(v.isArray(e)||e.jquery&&!v.isPlainObject(e))v.each(e,function(){s(this.name,this.value)});else for(r in e)fn(r,e[r],n,s);return i.join("&").replace(rn,"+")};var ln,cn,hn=/#.*$/,pn=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,dn=/^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,vn=/^(?:GET|HEAD)$/,mn=/^\/\//,gn=/\?/,yn=/)<[^<]*)*<\/script>/gi,bn=/([?&])_=[^&]*/,wn=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,En=v.fn.load,Sn={},xn={},Tn=["*/"]+["*"];try{cn=s.href}catch(Nn){cn=i.createElement("a"),cn.href="",cn=cn.href}ln=wn.exec(cn.toLowerCase())||[],v.fn.load=function(e,n,r){if(typeof e!="string"&&En)return En.apply(this,arguments);if(!this.length)return this;var i,s,o,u=this,a=e.indexOf(" ");return a>=0&&(i=e.slice(a,e.length),e=e.slice(0,a)),v.isFunction(n)?(r=n,n=t):n&&typeof n=="object"&&(s="POST"),v.ajax({url:e,type:s,dataType:"html",data:n,complete:function(e,t){r&&u.each(r,o||[e.responseText,t,e])}}).done(function(e){o=arguments,u.html(i?v("
").append(e.replace(yn,"")).find(i):e)}),this},v.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(e,t){v.fn[t]=function(e){return this.on(t,e)}}),v.each(["get","post"],function(e,n){v[n]=function(e,r,i,s){return v.isFunction(r)&&(s=s||i,i=r,r=t),v.ajax({type:n,url:e,data:r,success:i,dataType:s})}}),v.extend({getScript:function(e,n){return v.get(e,t,n,"script")},getJSON:function(e,t,n){return v.get(e,t,n,"json")},ajaxSetup:function(e,t){return t?Ln(e,v.ajaxSettings):(t=e,e=v.ajaxSettings),Ln(e,t),e},ajaxSettings:{url:cn,isLocal:dn.test(ln[1]),global:!0,type:"GET",contentType:"application/x-www-form-urlencoded; charset=UTF-8",processData:!0,async:!0,accepts:{xml:"application/xml, text/xml",html:"text/html",text:"text/plain",json:"application/json, text/javascript","*":Tn},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":e.String,"text html":!0,"text json":v.parseJSON,"text xml":v.parseXML},flatOptions:{context:!0,url:!0}},ajaxPrefilter:Cn(Sn),ajaxTransport:Cn(xn),ajax:function(e,n){function T(e,n,s,a){var l,y,b,w,S,T=n;if(E===2)return;E=2,u&&clearTimeout(u),o=t,i=a||"",x.readyState=e>0?4:0,s&&(w=An(c,x,s));if(e>=200&&e<300||e===304)c.ifModified&&(S=x.getResponseHeader("Last-Modified"),S&&(v.lastModified[r]=S),S=x.getResponseHeader("Etag"),S&&(v.etag[r]=S)),e===304?(T="notmodified",l=!0):(l=On(c,w),T=l.state,y=l.data,b=l.error,l=!b);else{b=T;if(!T||e)T="error",e<0&&(e=0)}x.status=e,x.statusText=(n||T)+"",l?d.resolveWith(h,[y,T,x]):d.rejectWith(h,[x,T,b]),x.statusCode(g),g=t,f&&p.trigger("ajax"+(l?"Success":"Error"),[x,c,l?y:b]),m.fireWith(h,[x,T]),f&&(p.trigger("ajaxComplete",[x,c]),--v.active||v.event.trigger("ajaxStop"))}typeof e=="object"&&(n=e,e=t),n=n||{};var r,i,s,o,u,a,f,l,c=v.ajaxSetup({},n),h=c.context||c,p=h!==c&&(h.nodeType||h instanceof v)?v(h):v.event,d=v.Deferred(),m=v.Callbacks("once memory"),g=c.statusCode||{},b={},w={},E=0,S="canceled",x={readyState:0,setRequestHeader:function(e,t){if(!E){var n=e.toLowerCase();e=w[n]=w[n]||e,b[e]=t}return this},getAllResponseHeaders:function(){return E===2?i:null},getResponseHeader:function(e){var n;if(E===2){if(!s){s={};while(n=pn.exec(i))s[n[1].toLowerCase()]=n[2]}n=s[e.toLowerCase()]}return n===t?null:n},overrideMimeType:function(e){return E||(c.mimeType=e),this},abort:function(e){return e=e||S,o&&o.abort(e),T(0,e),this}};d.promise(x),x.success=x.done,x.error=x.fail,x.complete=m.add,x.statusCode=function(e){if(e){var t;if(E<2)for(t in e)g[t]=[g[t],e[t]];else t=e[x.status],x.always(t)}return this},c.url=((e||c.url)+"").replace(hn,"").replace(mn,ln[1]+"//"),c.dataTypes=v.trim(c.dataType||"*").toLowerCase().split(y),c.crossDomain==null&&(a=wn.exec(c.url.toLowerCase()),c.crossDomain=!(!a||a[1]===ln[1]&&a[2]===ln[2]&&(a[3]||(a[1]==="http:"?80:443))==(ln[3]||(ln[1]==="http:"?80:443)))),c.data&&c.processData&&typeof c.data!="string"&&(c.data=v.param(c.data,c.traditional)),kn(Sn,c,n,x);if(E===2)return x;f=c.global,c.type=c.type.toUpperCase(),c.hasContent=!vn.test(c.type),f&&v.active++===0&&v.event.trigger("ajaxStart");if(!c.hasContent){c.data&&(c.url+=(gn.test(c.url)?"&":"?")+c.data,delete c.data),r=c.url;if(c.cache===!1){var N=v.now(),C=c.url.replace(bn,"$1_="+N);c.url=C+(C===c.url?(gn.test(c.url)?"&":"?")+"_="+N:"")}}(c.data&&c.hasContent&&c.contentType!==!1||n.contentType)&&x.setRequestHeader("Content-Type",c.contentType),c.ifModified&&(r=r||c.url,v.lastModified[r]&&x.setRequestHeader("If-Modified-Since",v.lastModified[r]),v.etag[r]&&x.setRequestHeader("If-None-Match",v.etag[r])),x.setRequestHeader("Accept",c.dataTypes[0]&&c.accepts[c.dataTypes[0]]?c.accepts[c.dataTypes[0]]+(c.dataTypes[0]!=="*"?", "+Tn+"; q=0.01":""):c.accepts["*"]);for(l in c.headers)x.setRequestHeader(l,c.headers[l]);if(!c.beforeSend||c.beforeSend.call(h,x,c)!==!1&&E!==2){S="abort";for(l in{success:1,error:1,complete:1})x[l](c[l]);o=kn(xn,c,n,x);if(!o)T(-1,"No Transport");else{x.readyState=1,f&&p.trigger("ajaxSend",[x,c]),c.async&&c.timeout>0&&(u=setTimeout(function(){x.abort("timeout")},c.timeout));try{E=1,o.send(b,T)}catch(k){if(!(E<2))throw k;T(-1,k)}}return x}return x.abort()},active:0,lastModified:{},etag:{}});var Mn=[],_n=/\?/,Dn=/(=)\?(?=&|$)|\?\?/,Pn=v.now();v.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=Mn.pop()||v.expando+"_"+Pn++;return this[e]=!0,e}}),v.ajaxPrefilter("json jsonp",function(n,r,i){var s,o,u,a=n.data,f=n.url,l=n.jsonp!==!1,c=l&&Dn.test(f),h=l&&!c&&typeof a=="string"&&!(n.contentType||"").indexOf("application/x-www-form-urlencoded")&&Dn.test(a);if(n.dataTypes[0]==="jsonp"||c||h)return s=n.jsonpCallback=v.isFunction(n.jsonpCallback)?n.jsonpCallback():n.jsonpCallback,o=e[s],c?n.url=f.replace(Dn,"$1"+s):h?n.data=a.replace(Dn,"$1"+s):l&&(n.url+=(_n.test(f)?"&":"?")+n.jsonp+"="+s),n.converters["script json"]=function(){return u||v.error(s+" was not called"),u[0]},n.dataTypes[0]="json",e[s]=function(){u=arguments},i.always(function(){e[s]=o,n[s]&&(n.jsonpCallback=r.jsonpCallback,Mn.push(s)),u&&v.isFunction(o)&&o(u[0]),u=o=t}),"script"}),v.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/javascript|ecmascript/},converters:{"text script":function(e){return v.globalEval(e),e}}}),v.ajaxPrefilter("script",function(e){e.cache===t&&(e.cache=!1),e.crossDomain&&(e.type="GET",e.global=!1)}),v.ajaxTransport("script",function(e){if(e.crossDomain){var n,r=i.head||i.getElementsByTagName("head")[0]||i.documentElement;return{send:function(s,o){n=i.createElement("script"),n.async="async",e.scriptCharset&&(n.charset=e.scriptCharset),n.src=e.url,n.onload=n.onreadystatechange=function(e,i){if(i||!n.readyState||/loaded|complete/.test(n.readyState))n.onload=n.onreadystatechange=null,r&&n.parentNode&&r.removeChild(n),n=t,i||o(200,"success")},r.insertBefore(n,r.firstChild)},abort:function(){n&&n.onload(0,1)}}}});var Hn,Bn=e.ActiveXObject?function(){for(var e in Hn)Hn[e](0,1)}:!1,jn=0;v.ajaxSettings.xhr=e.ActiveXObject?function(){return!this.isLocal&&Fn()||In()}:Fn,function(e){v.extend(v.support,{ajax:!!e,cors:!!e&&"withCredentials"in e})}(v.ajaxSettings.xhr()),v.support.ajax&&v.ajaxTransport(function(n){if(!n.crossDomain||v.support.cors){var r;return{send:function(i,s){var o,u,a=n.xhr();n.username?a.open(n.type,n.url,n.async,n.username,n.password):a.open(n.type,n.url,n.async);if(n.xhrFields)for(u in n.xhrFields)a[u]=n.xhrFields[u];n.mimeType&&a.overrideMimeType&&a.overrideMimeType(n.mimeType),!n.crossDomain&&!i["X-Requested-With"]&&(i["X-Requested-With"]="XMLHttpRequest");try{for(u in i)a.setRequestHeader(u,i[u])}catch(f){}a.send(n.hasContent&&n.data||null),r=function(e,i){var u,f,l,c,h;try{if(r&&(i||a.readyState===4)){r=t,o&&(a.onreadystatechange=v.noop,Bn&&delete Hn[o]);if(i)a.readyState!==4&&a.abort();else{u=a.status,l=a.getAllResponseHeaders(),c={},h=a.responseXML,h&&h.documentElement&&(c.xml=h);try{c.text=a.responseText}catch(p){}try{f=a.statusText}catch(p){f=""}!u&&n.isLocal&&!n.crossDomain?u=c.text?200:404:u===1223&&(u=204)}}}catch(d){i||s(-1,d)}c&&s(u,f,c,l)},n.async?a.readyState===4?setTimeout(r,0):(o=++jn,Bn&&(Hn||(Hn={},v(e).unload(Bn)),Hn[o]=r),a.onreadystatechange=r):r()},abort:function(){r&&r(0,1)}}}});var qn,Rn,Un=/^(?:toggle|show|hide)$/,zn=new RegExp("^(?:([-+])=|)("+m+")([a-z%]*)$","i"),Wn=/queueHooks$/,Xn=[Gn],Vn={"*":[function(e,t){var n,r,i=this.createTween(e,t),s=zn.exec(t),o=i.cur(),u=+o||0,a=1,f=20;if(s){n=+s[2],r=s[3]||(v.cssNumber[e]?"":"px");if(r!=="px"&&u){u=v.css(i.elem,e,!0)||n||1;do a=a||".5",u/=a,v.style(i.elem,e,u+r);while(a!==(a=i.cur()/o)&&a!==1&&--f)}i.unit=r,i.start=u,i.end=s[1]?u+(s[1]+1)*n:n}return i}]};v.Animation=v.extend(Kn,{tweener:function(e,t){v.isFunction(e)?(t=e,e=["*"]):e=e.split(" ");var n,r=0,i=e.length;for(;r-1,f={},l={},c,h;a?(l=i.position(),c=l.top,h=l.left):(c=parseFloat(o)||0,h=parseFloat(u)||0),v.isFunction(t)&&(t=t.call(e,n,s)),t.top!=null&&(f.top=t.top-s.top+c),t.left!=null&&(f.left=t.left-s.left+h),"using"in t?t.using.call(e,f):i.css(f)}},v.fn.extend({position:function(){if(!this[0])return;var e=this[0],t=this.offsetParent(),n=this.offset(),r=er.test(t[0].nodeName)?{top:0,left:0}:t.offset();return n.top-=parseFloat(v.css(e,"marginTop"))||0,n.left-=parseFloat(v.css(e,"marginLeft"))||0,r.top+=parseFloat(v.css(t[0],"borderTopWidth"))||0,r.left+=parseFloat(v.css(t[0],"borderLeftWidth"))||0,{top:n.top-r.top,left:n.left-r.left}},offsetParent:function(){return this.map(function(){var e=this.offsetParent||i.body;while(e&&!er.test(e.nodeName)&&v.css(e,"position")==="static")e=e.offsetParent;return e||i.body})}}),v.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(e,n){var r=/Y/.test(n);v.fn[e]=function(i){return v.access(this,function(e,i,s){var o=tr(e);if(s===t)return o?n in o?o[n]:o.document.documentElement[i]:e[i];o?o.scrollTo(r?v(o).scrollLeft():s,r?s:v(o).scrollTop()):e[i]=s},e,i,arguments.length,null)}}),v.each({Height:"height",Width:"width"},function(e,n){v.each({padding:"inner"+e,content:n,"":"outer"+e},function(r,i){v.fn[i]=function(i,s){var o=arguments.length&&(r||typeof i!="boolean"),u=r||(i===!0||s===!0?"margin":"border");return v.access(this,function(n,r,i){var s;return v.isWindow(n)?n.document.documentElement["client"+e]:n.nodeType===9?(s=n.documentElement,Math.max(n.body["scroll"+e],s["scroll"+e],n.body["offset"+e],s["offset"+e],s["client"+e])):i===t?v.css(n,r,i,u):v.style(n,r,i,u)},n,o?i:t,o,null)}})}),e.jQuery=e.$=v,typeof define=="function"&&define.amd&&define.amd.jQuery&&define("jquery",[],function(){return v})})(window); \ No newline at end of file diff --git a/Chapter07/03_handlers_as_modules/content/mustache.js b/Chapter07/03_handlers_as_modules/content/mustache.js new file mode 100644 index 0000000..0148d29 --- /dev/null +++ b/Chapter07/03_handlers_as_modules/content/mustache.js @@ -0,0 +1,625 @@ +/*! + * mustache.js - Logic-less {{mustache}} templates with JavaScript + * http://github.com/janl/mustache.js + */ + +/*global define: false*/ + +var Mustache; + +(function (exports) { + if (typeof module !== "undefined" && module.exports) { + module.exports = exports; // CommonJS + } else if (typeof define === "function") { + define(exports); // AMD + } else { + Mustache = exports; // + + + + + + + diff --git a/Chapter07/05_static_middleware/app/handlers/albums.js b/Chapter07/05_static_middleware/app/handlers/albums.js new file mode 100644 index 0000000..1816af2 --- /dev/null +++ b/Chapter07/05_static_middleware/app/handlers/albums.js @@ -0,0 +1,136 @@ + +var helpers = require('./helpers.js'), + async = require('async'), + fs = require('fs'); + +exports.version = "0.1.0"; + +exports.list_all = function (req, res) { + load_album_list(function (err, albums) { + if (err) { + helpers.send_failure(res, 500, err); + return; + } + + helpers.send_success(res, { albums: albums }); + }); +}; + +exports.album_by_name = function (req, res) { + // get the GET params + var getp = req.query; + var page_num = getp.page ? getp.page : 0; + var page_size = getp.page_size ? getp.page_size : 1000; + + if (isNaN(parseInt(page_num))) page_num = 0; + if (isNaN(parseInt(page_size))) page_size = 1000; + + // format of request is /albums/album_name.json + var album_name = req.params.album_name; + load_album( + album_name, + page_num, + page_size, + function (err, album_contents) { + if (err && err.error == "no_such_album") { + helpers.send_failure(res, 404, err); + } else if (err) { + helpers.send_failure(res, 500, err); + } else { + helpers.send_success(res, { album_data: album_contents }); + } + } + ); +}; + +function load_album_list(callback) { + // we will just assume that any directory in our 'albums' + // subfolder is an album. + fs.readdir( + "../static/albums", + function (err, files) { + if (err) { + callback(helpers.make_error("file_error", JSON.stringify(err))); + return; + } + + var only_dirs = []; + async.forEach( + files, + function (element, cb) { + fs.stat( + "../static/albums/" + element, + function (err, stats) { + if (err) { + cb(helpers.make_error("file_error", + JSON.stringify(err))); + return; + } + if (stats.isDirectory()) { + only_dirs.push({ name: element }); + } + cb(null); + } + ); + }, + function (err) { + callback(err, err ? null : only_dirs); + } + ); + } + ); +}; + +function load_album(album_name, page, page_size, callback) { + fs.readdir( + "../static/albums/" + album_name, + function (err, files) { + if (err) { + if (err.code == "ENOENT") { + callback(helpers.no_such_album()); + } else { + callback(helpers.make_error("file_error", + JSON.stringify(err))); + } + return; + } + + var only_files = []; + var path = "../static/albums/" + album_name + "/"; + + async.forEach( + files, + function (element, cb) { + fs.stat( + path + element, + function (err, stats) { + if (err) { + cb(helpers.make_error("file_error", + JSON.stringify(err))); + return; + } + if (stats.isFile()) { + var obj = { filename: element, + desc: element }; + only_files.push(obj); + } + cb(null); + } + ); + }, + function (err) { + if (err) { + callback(err); + } else { + var ps = page_size; + var photos = only_files.splice(page * ps, ps); + var obj = { short_name: album_name, + photos: photos }; + callback(null, obj); + } + } + ); + } + ); +}; + diff --git a/Chapter07/05_static_middleware/app/handlers/helpers.js b/Chapter07/05_static_middleware/app/handlers/helpers.js new file mode 100644 index 0000000..c73bb55 --- /dev/null +++ b/Chapter07/05_static_middleware/app/handlers/helpers.js @@ -0,0 +1,34 @@ + +exports.version = '0.1.0'; + +exports.make_error = function(err, msg) { + var e = new Error(msg); + e.code = err; + return e; +} + + +exports.send_success = function(res, data) { + res.writeHead(200, {"Content-Type": "application/json"}); + var output = { error: null, data: data }; + res.end(JSON.stringify(output) + "\n"); +} + + +exports.send_failure = function(res, code, err) { + var code = (err.code) ? err.code : err.name; + res.writeHead(code, { "Content-Type" : "application/json" }); + res.end(JSON.stringify({ error: code, message: err.message }) + "\n"); +} + + +exports.invalid_resource = function() { + return exports.make_error("invalid_resource", + "the requested resource does not exist."); +} + +exports.no_such_album = function() { + return exports.make_error("no_such_album", + "The specified album does not exist"); +} + diff --git a/Chapter07/05_static_middleware/app/handlers/pages.js b/Chapter07/05_static_middleware/app/handlers/pages.js new file mode 100644 index 0000000..b2c7b12 --- /dev/null +++ b/Chapter07/05_static_middleware/app/handlers/pages.js @@ -0,0 +1,29 @@ + +var helpers = require('./helpers.js'), + fs = require('fs'); + + +exports.version = "0.1.0"; + + +exports.generate = function (req, res) { + + var page = req.params.page_name; + + fs.readFile( + 'basic.html', + function (err, contents) { + if (err) { + send_failure(res, err); + return; + } + + contents = contents.toString('utf8'); + + // replace page name, and then dump to output. + contents = contents.replace('{{PAGE_NAME}}', page); + res.writeHead(200, { "Content-Type": "text/html" }); + res.end(contents); + } + ); +}; diff --git a/Chapter07/05_static_middleware/app/package.json b/Chapter07/05_static_middleware/app/package.json new file mode 100644 index 0000000..3cf0a17 --- /dev/null +++ b/Chapter07/05_static_middleware/app/package.json @@ -0,0 +1,10 @@ +{ + "name": "Photo-Sharing", + "description": "Our Photo Sharing Application with static middleware", + "version": "0.0.2", + "private": true, + "dependencies": { + "express": "3.x", + "async": "0.1.x" + } +} diff --git a/Chapter07/05_static_middleware/app/server.js b/Chapter07/05_static_middleware/app/server.js new file mode 100644 index 0000000..3a04759 --- /dev/null +++ b/Chapter07/05_static_middleware/app/server.js @@ -0,0 +1,29 @@ + +var express = require('express'); +var app = express(); + +var fs = require('fs'), + album_hdlr = require('./handlers/albums.js'), + page_hdlr = require('./handlers/pages.js'), + helpers = require('./handlers/helpers.js'); + +app.use(express.static(__dirname + "/../static")); + +app.get('/v1/albums.json', album_hdlr.list_all); +app.get('/v1/albums/:album_name.json', album_hdlr.album_by_name); +app.get('/pages/:page_name', page_hdlr.generate); +app.get('/pages/:page_name/:sub_page', page_hdlr.generate); + +app.get("/", function (req, res) { + res.redirect("/pages/home"); + res.end(); +}); + +app.get('*', four_oh_four); + +function four_oh_four(req, res) { + res.writeHead(404, { "Content-Type" : "application/json" }); + res.end(JSON.stringify(helpers.invalid_resource()) + "\n"); +} + +app.listen(8080); diff --git a/Chapter07/05_static_middleware/static/albums/australia2010/aus_01.jpg b/Chapter07/05_static_middleware/static/albums/australia2010/aus_01.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter07/05_static_middleware/static/albums/australia2010/aus_02.jpg b/Chapter07/05_static_middleware/static/albums/australia2010/aus_02.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter07/05_static_middleware/static/albums/australia2010/aus_03.jpg b/Chapter07/05_static_middleware/static/albums/australia2010/aus_03.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter07/05_static_middleware/static/albums/australia2010/aus_04.jpg b/Chapter07/05_static_middleware/static/albums/australia2010/aus_04.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter07/05_static_middleware/static/albums/australia2010/aus_05.jpg b/Chapter07/05_static_middleware/static/albums/australia2010/aus_05.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter07/05_static_middleware/static/albums/australia2010/aus_06.jpg b/Chapter07/05_static_middleware/static/albums/australia2010/aus_06.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter07/05_static_middleware/static/albums/australia2010/aus_07.jpg b/Chapter07/05_static_middleware/static/albums/australia2010/aus_07.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter07/05_static_middleware/static/albums/australia2010/aus_08.jpg b/Chapter07/05_static_middleware/static/albums/australia2010/aus_08.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter07/05_static_middleware/static/albums/australia2010/aus_09.jpg b/Chapter07/05_static_middleware/static/albums/australia2010/aus_09.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter07/05_static_middleware/static/albums/info.txt b/Chapter07/05_static_middleware/static/albums/info.txt new file mode 100644 index 0000000..e69de29 diff --git a/Chapter07/05_static_middleware/static/albums/italy2012/picture_01.jpg b/Chapter07/05_static_middleware/static/albums/italy2012/picture_01.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter07/05_static_middleware/static/albums/italy2012/picture_02.jpg b/Chapter07/05_static_middleware/static/albums/italy2012/picture_02.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter07/05_static_middleware/static/albums/italy2012/picture_03.jpg b/Chapter07/05_static_middleware/static/albums/italy2012/picture_03.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter07/05_static_middleware/static/albums/italy2012/picture_04.jpg b/Chapter07/05_static_middleware/static/albums/italy2012/picture_04.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter07/05_static_middleware/static/albums/italy2012/picture_05.jpg b/Chapter07/05_static_middleware/static/albums/italy2012/picture_05.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter07/05_static_middleware/static/albums/japan2010/picture_001.jpg b/Chapter07/05_static_middleware/static/albums/japan2010/picture_001.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter07/05_static_middleware/static/albums/japan2010/picture_002.jpg b/Chapter07/05_static_middleware/static/albums/japan2010/picture_002.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter07/05_static_middleware/static/albums/japan2010/picture_003.jpg b/Chapter07/05_static_middleware/static/albums/japan2010/picture_003.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter07/05_static_middleware/static/albums/japan2010/picture_004.jpg b/Chapter07/05_static_middleware/static/albums/japan2010/picture_004.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter07/05_static_middleware/static/albums/japan2010/picture_005.jpg b/Chapter07/05_static_middleware/static/albums/japan2010/picture_005.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter07/05_static_middleware/static/albums/japan2010/picture_006.jpg b/Chapter07/05_static_middleware/static/albums/japan2010/picture_006.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter07/05_static_middleware/static/albums/japan2010/picture_007.jpg b/Chapter07/05_static_middleware/static/albums/japan2010/picture_007.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter07/05_static_middleware/static/content/album.js b/Chapter07/05_static_middleware/static/content/album.js new file mode 100644 index 0000000..f1faf68 --- /dev/null +++ b/Chapter07/05_static_middleware/static/content/album.js @@ -0,0 +1,46 @@ +$(function(){ + + var tmpl, // Main template HTML + tdata = {}; // JSON data object that feeds the template + + // Initialise page + var initPage = function() { + + // get our album name. + parts = window.location.href.split("/"); + var album_name = parts[5]; + + // Load the HTML template + $.get("/templates/album.html", function(d){ + tmpl = d; + }); + + // Retrieve the server data and then initialise the page + $.getJSON("/v1/albums/" + album_name + ".json", function (d) { + var photo_d = massage_album(d); + $.extend(tdata, photo_d); + }); + + // When AJAX calls are complete parse the template + // replacing mustache tags with vars + $(document).ajaxStop(function () { + var renderedPage = Mustache.to_html( tmpl, tdata ); + $("body").html( renderedPage ); + }) + }(); +}); + + + +function massage_album(d) { + if (d.error != null) return d; + var obj = { photos: [] }; + + var af = d.data.album_data; + + for (var i = 0; i < af.photos.length; i++) { + var url = "/albums/" + af.short_name + "/" + af.photos[i].filename; + obj.photos.push({ url: url, desc: af.photos[i].filename }); + } + return obj; +} diff --git a/Chapter07/05_static_middleware/static/content/home.js b/Chapter07/05_static_middleware/static/content/home.js new file mode 100644 index 0000000..fa7010b --- /dev/null +++ b/Chapter07/05_static_middleware/static/content/home.js @@ -0,0 +1,28 @@ +$(function(){ + + var tmpl, // Main template HTML + tdata = {}; // JSON data object that feeds the template + + // Initialise page + var initPage = function() { + + // Load the HTML template + $.get("/templates/home.html", function(d){ + tmpl = d; + }); + + + // Retrieve the server data and then initialise the page + $.getJSON("/v1/albums.json", function (d) { + $.extend(tdata, d.data); + }); + + // When AJAX calls are complete parse the template + // replacing mustache tags with vars + $(document).ajaxStop(function () { + var renderedPage = Mustache.to_html( tmpl, tdata ); + $("body").html( renderedPage ); + }) + }(); +}); + diff --git a/Chapter07/05_static_middleware/static/content/jquery-1.8.3.min.js b/Chapter07/05_static_middleware/static/content/jquery-1.8.3.min.js new file mode 100644 index 0000000..83589da --- /dev/null +++ b/Chapter07/05_static_middleware/static/content/jquery-1.8.3.min.js @@ -0,0 +1,2 @@ +/*! jQuery v1.8.3 jquery.com | jquery.org/license */ +(function(e,t){function _(e){var t=M[e]={};return v.each(e.split(y),function(e,n){t[n]=!0}),t}function H(e,n,r){if(r===t&&e.nodeType===1){var i="data-"+n.replace(P,"-$1").toLowerCase();r=e.getAttribute(i);if(typeof r=="string"){try{r=r==="true"?!0:r==="false"?!1:r==="null"?null:+r+""===r?+r:D.test(r)?v.parseJSON(r):r}catch(s){}v.data(e,n,r)}else r=t}return r}function B(e){var t;for(t in e){if(t==="data"&&v.isEmptyObject(e[t]))continue;if(t!=="toJSON")return!1}return!0}function et(){return!1}function tt(){return!0}function ut(e){return!e||!e.parentNode||e.parentNode.nodeType===11}function at(e,t){do e=e[t];while(e&&e.nodeType!==1);return e}function ft(e,t,n){t=t||0;if(v.isFunction(t))return v.grep(e,function(e,r){var i=!!t.call(e,r,e);return i===n});if(t.nodeType)return v.grep(e,function(e,r){return e===t===n});if(typeof t=="string"){var r=v.grep(e,function(e){return e.nodeType===1});if(it.test(t))return v.filter(t,r,!n);t=v.filter(t,r)}return v.grep(e,function(e,r){return v.inArray(e,t)>=0===n})}function lt(e){var t=ct.split("|"),n=e.createDocumentFragment();if(n.createElement)while(t.length)n.createElement(t.pop());return n}function Lt(e,t){return e.getElementsByTagName(t)[0]||e.appendChild(e.ownerDocument.createElement(t))}function At(e,t){if(t.nodeType!==1||!v.hasData(e))return;var n,r,i,s=v._data(e),o=v._data(t,s),u=s.events;if(u){delete o.handle,o.events={};for(n in u)for(r=0,i=u[n].length;r").appendTo(i.body),n=t.css("display");t.remove();if(n==="none"||n===""){Pt=i.body.appendChild(Pt||v.extend(i.createElement("iframe"),{frameBorder:0,width:0,height:0}));if(!Ht||!Pt.createElement)Ht=(Pt.contentWindow||Pt.contentDocument).document,Ht.write(""),Ht.close();t=Ht.body.appendChild(Ht.createElement(e)),n=Dt(t,"display"),i.body.removeChild(Pt)}return Wt[e]=n,n}function fn(e,t,n,r){var i;if(v.isArray(t))v.each(t,function(t,i){n||sn.test(e)?r(e,i):fn(e+"["+(typeof i=="object"?t:"")+"]",i,n,r)});else if(!n&&v.type(t)==="object")for(i in t)fn(e+"["+i+"]",t[i],n,r);else r(e,t)}function Cn(e){return function(t,n){typeof t!="string"&&(n=t,t="*");var r,i,s,o=t.toLowerCase().split(y),u=0,a=o.length;if(v.isFunction(n))for(;u)[^>]*$|#([\w\-]*)$)/,E=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,S=/^[\],:{}\s]*$/,x=/(?:^|:|,)(?:\s*\[)+/g,T=/\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,N=/"[^"\\\r\n]*"|true|false|null|-?(?:\d\d*\.|)\d+(?:[eE][\-+]?\d+|)/g,C=/^-ms-/,k=/-([\da-z])/gi,L=function(e,t){return(t+"").toUpperCase()},A=function(){i.addEventListener?(i.removeEventListener("DOMContentLoaded",A,!1),v.ready()):i.readyState==="complete"&&(i.detachEvent("onreadystatechange",A),v.ready())},O={};v.fn=v.prototype={constructor:v,init:function(e,n,r){var s,o,u,a;if(!e)return this;if(e.nodeType)return this.context=this[0]=e,this.length=1,this;if(typeof e=="string"){e.charAt(0)==="<"&&e.charAt(e.length-1)===">"&&e.length>=3?s=[null,e,null]:s=w.exec(e);if(s&&(s[1]||!n)){if(s[1])return n=n instanceof v?n[0]:n,a=n&&n.nodeType?n.ownerDocument||n:i,e=v.parseHTML(s[1],a,!0),E.test(s[1])&&v.isPlainObject(n)&&this.attr.call(e,n,!0),v.merge(this,e);o=i.getElementById(s[2]);if(o&&o.parentNode){if(o.id!==s[2])return r.find(e);this.length=1,this[0]=o}return this.context=i,this.selector=e,this}return!n||n.jquery?(n||r).find(e):this.constructor(n).find(e)}return v.isFunction(e)?r.ready(e):(e.selector!==t&&(this.selector=e.selector,this.context=e.context),v.makeArray(e,this))},selector:"",jquery:"1.8.3",length:0,size:function(){return this.length},toArray:function(){return l.call(this)},get:function(e){return e==null?this.toArray():e<0?this[this.length+e]:this[e]},pushStack:function(e,t,n){var r=v.merge(this.constructor(),e);return r.prevObject=this,r.context=this.context,t==="find"?r.selector=this.selector+(this.selector?" ":"")+n:t&&(r.selector=this.selector+"."+t+"("+n+")"),r},each:function(e,t){return v.each(this,e,t)},ready:function(e){return v.ready.promise().done(e),this},eq:function(e){return e=+e,e===-1?this.slice(e):this.slice(e,e+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(l.apply(this,arguments),"slice",l.call(arguments).join(","))},map:function(e){return this.pushStack(v.map(this,function(t,n){return e.call(t,n,t)}))},end:function(){return this.prevObject||this.constructor(null)},push:f,sort:[].sort,splice:[].splice},v.fn.init.prototype=v.fn,v.extend=v.fn.extend=function(){var e,n,r,i,s,o,u=arguments[0]||{},a=1,f=arguments.length,l=!1;typeof u=="boolean"&&(l=u,u=arguments[1]||{},a=2),typeof u!="object"&&!v.isFunction(u)&&(u={}),f===a&&(u=this,--a);for(;a0)return;r.resolveWith(i,[v]),v.fn.trigger&&v(i).trigger("ready").off("ready")},isFunction:function(e){return v.type(e)==="function"},isArray:Array.isArray||function(e){return v.type(e)==="array"},isWindow:function(e){return e!=null&&e==e.window},isNumeric:function(e){return!isNaN(parseFloat(e))&&isFinite(e)},type:function(e){return e==null?String(e):O[h.call(e)]||"object"},isPlainObject:function(e){if(!e||v.type(e)!=="object"||e.nodeType||v.isWindow(e))return!1;try{if(e.constructor&&!p.call(e,"constructor")&&!p.call(e.constructor.prototype,"isPrototypeOf"))return!1}catch(n){return!1}var r;for(r in e);return r===t||p.call(e,r)},isEmptyObject:function(e){var t;for(t in e)return!1;return!0},error:function(e){throw new Error(e)},parseHTML:function(e,t,n){var r;return!e||typeof e!="string"?null:(typeof t=="boolean"&&(n=t,t=0),t=t||i,(r=E.exec(e))?[t.createElement(r[1])]:(r=v.buildFragment([e],t,n?null:[]),v.merge([],(r.cacheable?v.clone(r.fragment):r.fragment).childNodes)))},parseJSON:function(t){if(!t||typeof t!="string")return null;t=v.trim(t);if(e.JSON&&e.JSON.parse)return e.JSON.parse(t);if(S.test(t.replace(T,"@").replace(N,"]").replace(x,"")))return(new Function("return "+t))();v.error("Invalid JSON: "+t)},parseXML:function(n){var r,i;if(!n||typeof n!="string")return null;try{e.DOMParser?(i=new DOMParser,r=i.parseFromString(n,"text/xml")):(r=new ActiveXObject("Microsoft.XMLDOM"),r.async="false",r.loadXML(n))}catch(s){r=t}return(!r||!r.documentElement||r.getElementsByTagName("parsererror").length)&&v.error("Invalid XML: "+n),r},noop:function(){},globalEval:function(t){t&&g.test(t)&&(e.execScript||function(t){e.eval.call(e,t)})(t)},camelCase:function(e){return e.replace(C,"ms-").replace(k,L)},nodeName:function(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()},each:function(e,n,r){var i,s=0,o=e.length,u=o===t||v.isFunction(e);if(r){if(u){for(i in e)if(n.apply(e[i],r)===!1)break}else for(;s0&&e[0]&&e[a-1]||a===0||v.isArray(e));if(f)for(;u-1)a.splice(n,1),i&&(n<=o&&o--,n<=u&&u--)}),this},has:function(e){return v.inArray(e,a)>-1},empty:function(){return a=[],this},disable:function(){return a=f=n=t,this},disabled:function(){return!a},lock:function(){return f=t,n||c.disable(),this},locked:function(){return!f},fireWith:function(e,t){return t=t||[],t=[e,t.slice?t.slice():t],a&&(!r||f)&&(i?f.push(t):l(t)),this},fire:function(){return c.fireWith(this,arguments),this},fired:function(){return!!r}};return c},v.extend({Deferred:function(e){var t=[["resolve","done",v.Callbacks("once memory"),"resolved"],["reject","fail",v.Callbacks("once memory"),"rejected"],["notify","progress",v.Callbacks("memory")]],n="pending",r={state:function(){return n},always:function(){return i.done(arguments).fail(arguments),this},then:function(){var e=arguments;return v.Deferred(function(n){v.each(t,function(t,r){var s=r[0],o=e[t];i[r[1]](v.isFunction(o)?function(){var e=o.apply(this,arguments);e&&v.isFunction(e.promise)?e.promise().done(n.resolve).fail(n.reject).progress(n.notify):n[s+"With"](this===i?n:this,[e])}:n[s])}),e=null}).promise()},promise:function(e){return e!=null?v.extend(e,r):r}},i={};return r.pipe=r.then,v.each(t,function(e,s){var o=s[2],u=s[3];r[s[1]]=o.add,u&&o.add(function(){n=u},t[e^1][2].disable,t[2][2].lock),i[s[0]]=o.fire,i[s[0]+"With"]=o.fireWith}),r.promise(i),e&&e.call(i,i),i},when:function(e){var t=0,n=l.call(arguments),r=n.length,i=r!==1||e&&v.isFunction(e.promise)?r:0,s=i===1?e:v.Deferred(),o=function(e,t,n){return function(r){t[e]=this,n[e]=arguments.length>1?l.call(arguments):r,n===u?s.notifyWith(t,n):--i||s.resolveWith(t,n)}},u,a,f;if(r>1){u=new Array(r),a=new Array(r),f=new Array(r);for(;t
a",n=p.getElementsByTagName("*"),r=p.getElementsByTagName("a")[0];if(!n||!r||!n.length)return{};s=i.createElement("select"),o=s.appendChild(i.createElement("option")),u=p.getElementsByTagName("input")[0],r.style.cssText="top:1px;float:left;opacity:.5",t={leadingWhitespace:p.firstChild.nodeType===3,tbody:!p.getElementsByTagName("tbody").length,htmlSerialize:!!p.getElementsByTagName("link").length,style:/top/.test(r.getAttribute("style")),hrefNormalized:r.getAttribute("href")==="/a",opacity:/^0.5/.test(r.style.opacity),cssFloat:!!r.style.cssFloat,checkOn:u.value==="on",optSelected:o.selected,getSetAttribute:p.className!=="t",enctype:!!i.createElement("form").enctype,html5Clone:i.createElement("nav").cloneNode(!0).outerHTML!=="<:nav>",boxModel:i.compatMode==="CSS1Compat",submitBubbles:!0,changeBubbles:!0,focusinBubbles:!1,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0,boxSizingReliable:!0,pixelPosition:!1},u.checked=!0,t.noCloneChecked=u.cloneNode(!0).checked,s.disabled=!0,t.optDisabled=!o.disabled;try{delete p.test}catch(d){t.deleteExpando=!1}!p.addEventListener&&p.attachEvent&&p.fireEvent&&(p.attachEvent("onclick",h=function(){t.noCloneEvent=!1}),p.cloneNode(!0).fireEvent("onclick"),p.detachEvent("onclick",h)),u=i.createElement("input"),u.value="t",u.setAttribute("type","radio"),t.radioValue=u.value==="t",u.setAttribute("checked","checked"),u.setAttribute("name","t"),p.appendChild(u),a=i.createDocumentFragment(),a.appendChild(p.lastChild),t.checkClone=a.cloneNode(!0).cloneNode(!0).lastChild.checked,t.appendChecked=u.checked,a.removeChild(u),a.appendChild(p);if(p.attachEvent)for(l in{submit:!0,change:!0,focusin:!0})f="on"+l,c=f in p,c||(p.setAttribute(f,"return;"),c=typeof p[f]=="function"),t[l+"Bubbles"]=c;return v(function(){var n,r,s,o,u="padding:0;margin:0;border:0;display:block;overflow:hidden;",a=i.getElementsByTagName("body")[0];if(!a)return;n=i.createElement("div"),n.style.cssText="visibility:hidden;border:0;width:0;height:0;position:static;top:0;margin-top:1px",a.insertBefore(n,a.firstChild),r=i.createElement("div"),n.appendChild(r),r.innerHTML="
t
",s=r.getElementsByTagName("td"),s[0].style.cssText="padding:0;margin:0;border:0;display:none",c=s[0].offsetHeight===0,s[0].style.display="",s[1].style.display="none",t.reliableHiddenOffsets=c&&s[0].offsetHeight===0,r.innerHTML="",r.style.cssText="box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;",t.boxSizing=r.offsetWidth===4,t.doesNotIncludeMarginInBodyOffset=a.offsetTop!==1,e.getComputedStyle&&(t.pixelPosition=(e.getComputedStyle(r,null)||{}).top!=="1%",t.boxSizingReliable=(e.getComputedStyle(r,null)||{width:"4px"}).width==="4px",o=i.createElement("div"),o.style.cssText=r.style.cssText=u,o.style.marginRight=o.style.width="0",r.style.width="1px",r.appendChild(o),t.reliableMarginRight=!parseFloat((e.getComputedStyle(o,null)||{}).marginRight)),typeof r.style.zoom!="undefined"&&(r.innerHTML="",r.style.cssText=u+"width:1px;padding:1px;display:inline;zoom:1",t.inlineBlockNeedsLayout=r.offsetWidth===3,r.style.display="block",r.style.overflow="visible",r.innerHTML="
",r.firstChild.style.width="5px",t.shrinkWrapBlocks=r.offsetWidth!==3,n.style.zoom=1),a.removeChild(n),n=r=s=o=null}),a.removeChild(p),n=r=s=o=u=a=p=null,t}();var D=/(?:\{[\s\S]*\}|\[[\s\S]*\])$/,P=/([A-Z])/g;v.extend({cache:{},deletedIds:[],uuid:0,expando:"jQuery"+(v.fn.jquery+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(e){return e=e.nodeType?v.cache[e[v.expando]]:e[v.expando],!!e&&!B(e)},data:function(e,n,r,i){if(!v.acceptData(e))return;var s,o,u=v.expando,a=typeof n=="string",f=e.nodeType,l=f?v.cache:e,c=f?e[u]:e[u]&&u;if((!c||!l[c]||!i&&!l[c].data)&&a&&r===t)return;c||(f?e[u]=c=v.deletedIds.pop()||v.guid++:c=u),l[c]||(l[c]={},f||(l[c].toJSON=v.noop));if(typeof n=="object"||typeof n=="function")i?l[c]=v.extend(l[c],n):l[c].data=v.extend(l[c].data,n);return s=l[c],i||(s.data||(s.data={}),s=s.data),r!==t&&(s[v.camelCase(n)]=r),a?(o=s[n],o==null&&(o=s[v.camelCase(n)])):o=s,o},removeData:function(e,t,n){if(!v.acceptData(e))return;var r,i,s,o=e.nodeType,u=o?v.cache:e,a=o?e[v.expando]:v.expando;if(!u[a])return;if(t){r=n?u[a]:u[a].data;if(r){v.isArray(t)||(t in r?t=[t]:(t=v.camelCase(t),t in r?t=[t]:t=t.split(" ")));for(i=0,s=t.length;i1,null,!1))},removeData:function(e){return this.each(function(){v.removeData(this,e)})}}),v.extend({queue:function(e,t,n){var r;if(e)return t=(t||"fx")+"queue",r=v._data(e,t),n&&(!r||v.isArray(n)?r=v._data(e,t,v.makeArray(n)):r.push(n)),r||[]},dequeue:function(e,t){t=t||"fx";var n=v.queue(e,t),r=n.length,i=n.shift(),s=v._queueHooks(e,t),o=function(){v.dequeue(e,t)};i==="inprogress"&&(i=n.shift(),r--),i&&(t==="fx"&&n.unshift("inprogress"),delete s.stop,i.call(e,o,s)),!r&&s&&s.empty.fire()},_queueHooks:function(e,t){var n=t+"queueHooks";return v._data(e,n)||v._data(e,n,{empty:v.Callbacks("once memory").add(function(){v.removeData(e,t+"queue",!0),v.removeData(e,n,!0)})})}}),v.fn.extend({queue:function(e,n){var r=2;return typeof e!="string"&&(n=e,e="fx",r--),arguments.length1)},removeAttr:function(e){return this.each(function(){v.removeAttr(this,e)})},prop:function(e,t){return v.access(this,v.prop,e,t,arguments.length>1)},removeProp:function(e){return e=v.propFix[e]||e,this.each(function(){try{this[e]=t,delete this[e]}catch(n){}})},addClass:function(e){var t,n,r,i,s,o,u;if(v.isFunction(e))return this.each(function(t){v(this).addClass(e.call(this,t,this.className))});if(e&&typeof e=="string"){t=e.split(y);for(n=0,r=this.length;n=0)r=r.replace(" "+n[s]+" "," ");i.className=e?v.trim(r):""}}}return this},toggleClass:function(e,t){var n=typeof e,r=typeof t=="boolean";return v.isFunction(e)?this.each(function(n){v(this).toggleClass(e.call(this,n,this.className,t),t)}):this.each(function(){if(n==="string"){var i,s=0,o=v(this),u=t,a=e.split(y);while(i=a[s++])u=r?u:!o.hasClass(i),o[u?"addClass":"removeClass"](i)}else if(n==="undefined"||n==="boolean")this.className&&v._data(this,"__className__",this.className),this.className=this.className||e===!1?"":v._data(this,"__className__")||""})},hasClass:function(e){var t=" "+e+" ",n=0,r=this.length;for(;n=0)return!0;return!1},val:function(e){var n,r,i,s=this[0];if(!arguments.length){if(s)return n=v.valHooks[s.type]||v.valHooks[s.nodeName.toLowerCase()],n&&"get"in n&&(r=n.get(s,"value"))!==t?r:(r=s.value,typeof r=="string"?r.replace(R,""):r==null?"":r);return}return i=v.isFunction(e),this.each(function(r){var s,o=v(this);if(this.nodeType!==1)return;i?s=e.call(this,r,o.val()):s=e,s==null?s="":typeof s=="number"?s+="":v.isArray(s)&&(s=v.map(s,function(e){return e==null?"":e+""})),n=v.valHooks[this.type]||v.valHooks[this.nodeName.toLowerCase()];if(!n||!("set"in n)||n.set(this,s,"value")===t)this.value=s})}}),v.extend({valHooks:{option:{get:function(e){var t=e.attributes.value;return!t||t.specified?e.value:e.text}},select:{get:function(e){var t,n,r=e.options,i=e.selectedIndex,s=e.type==="select-one"||i<0,o=s?null:[],u=s?i+1:r.length,a=i<0?u:s?i:0;for(;a=0}),n.length||(e.selectedIndex=-1),n}}},attrFn:{},attr:function(e,n,r,i){var s,o,u,a=e.nodeType;if(!e||a===3||a===8||a===2)return;if(i&&v.isFunction(v.fn[n]))return v(e)[n](r);if(typeof e.getAttribute=="undefined")return v.prop(e,n,r);u=a!==1||!v.isXMLDoc(e),u&&(n=n.toLowerCase(),o=v.attrHooks[n]||(X.test(n)?F:j));if(r!==t){if(r===null){v.removeAttr(e,n);return}return o&&"set"in o&&u&&(s=o.set(e,r,n))!==t?s:(e.setAttribute(n,r+""),r)}return o&&"get"in o&&u&&(s=o.get(e,n))!==null?s:(s=e.getAttribute(n),s===null?t:s)},removeAttr:function(e,t){var n,r,i,s,o=0;if(t&&e.nodeType===1){r=t.split(y);for(;o=0}})});var $=/^(?:textarea|input|select)$/i,J=/^([^\.]*|)(?:\.(.+)|)$/,K=/(?:^|\s)hover(\.\S+|)\b/,Q=/^key/,G=/^(?:mouse|contextmenu)|click/,Y=/^(?:focusinfocus|focusoutblur)$/,Z=function(e){return v.event.special.hover?e:e.replace(K,"mouseenter$1 mouseleave$1")};v.event={add:function(e,n,r,i,s){var o,u,a,f,l,c,h,p,d,m,g;if(e.nodeType===3||e.nodeType===8||!n||!r||!(o=v._data(e)))return;r.handler&&(d=r,r=d.handler,s=d.selector),r.guid||(r.guid=v.guid++),a=o.events,a||(o.events=a={}),u=o.handle,u||(o.handle=u=function(e){return typeof v=="undefined"||!!e&&v.event.triggered===e.type?t:v.event.dispatch.apply(u.elem,arguments)},u.elem=e),n=v.trim(Z(n)).split(" ");for(f=0;f=0&&(y=y.slice(0,-1),a=!0),y.indexOf(".")>=0&&(b=y.split("."),y=b.shift(),b.sort());if((!s||v.event.customEvent[y])&&!v.event.global[y])return;n=typeof n=="object"?n[v.expando]?n:new v.Event(y,n):new v.Event(y),n.type=y,n.isTrigger=!0,n.exclusive=a,n.namespace=b.join("."),n.namespace_re=n.namespace?new RegExp("(^|\\.)"+b.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,h=y.indexOf(":")<0?"on"+y:"";if(!s){u=v.cache;for(f in u)u[f].events&&u[f].events[y]&&v.event.trigger(n,r,u[f].handle.elem,!0);return}n.result=t,n.target||(n.target=s),r=r!=null?v.makeArray(r):[],r.unshift(n),p=v.event.special[y]||{};if(p.trigger&&p.trigger.apply(s,r)===!1)return;m=[[s,p.bindType||y]];if(!o&&!p.noBubble&&!v.isWindow(s)){g=p.delegateType||y,l=Y.test(g+y)?s:s.parentNode;for(c=s;l;l=l.parentNode)m.push([l,g]),c=l;c===(s.ownerDocument||i)&&m.push([c.defaultView||c.parentWindow||e,g])}for(f=0;f=0:v.find(h,this,null,[s]).length),u[h]&&f.push(c);f.length&&w.push({elem:s,matches:f})}d.length>m&&w.push({elem:this,matches:d.slice(m)});for(r=0;r0?this.on(t,null,e,n):this.trigger(t)},Q.test(t)&&(v.event.fixHooks[t]=v.event.keyHooks),G.test(t)&&(v.event.fixHooks[t]=v.event.mouseHooks)}),function(e,t){function nt(e,t,n,r){n=n||[],t=t||g;var i,s,a,f,l=t.nodeType;if(!e||typeof e!="string")return n;if(l!==1&&l!==9)return[];a=o(t);if(!a&&!r)if(i=R.exec(e))if(f=i[1]){if(l===9){s=t.getElementById(f);if(!s||!s.parentNode)return n;if(s.id===f)return n.push(s),n}else if(t.ownerDocument&&(s=t.ownerDocument.getElementById(f))&&u(t,s)&&s.id===f)return n.push(s),n}else{if(i[2])return S.apply(n,x.call(t.getElementsByTagName(e),0)),n;if((f=i[3])&&Z&&t.getElementsByClassName)return S.apply(n,x.call(t.getElementsByClassName(f),0)),n}return vt(e.replace(j,"$1"),t,n,r,a)}function rt(e){return function(t){var n=t.nodeName.toLowerCase();return n==="input"&&t.type===e}}function it(e){return function(t){var n=t.nodeName.toLowerCase();return(n==="input"||n==="button")&&t.type===e}}function st(e){return N(function(t){return t=+t,N(function(n,r){var i,s=e([],n.length,t),o=s.length;while(o--)n[i=s[o]]&&(n[i]=!(r[i]=n[i]))})})}function ot(e,t,n){if(e===t)return n;var r=e.nextSibling;while(r){if(r===t)return-1;r=r.nextSibling}return 1}function ut(e,t){var n,r,s,o,u,a,f,l=L[d][e+" "];if(l)return t?0:l.slice(0);u=e,a=[],f=i.preFilter;while(u){if(!n||(r=F.exec(u)))r&&(u=u.slice(r[0].length)||u),a.push(s=[]);n=!1;if(r=I.exec(u))s.push(n=new m(r.shift())),u=u.slice(n.length),n.type=r[0].replace(j," ");for(o in i.filter)(r=J[o].exec(u))&&(!f[o]||(r=f[o](r)))&&(s.push(n=new m(r.shift())),u=u.slice(n.length),n.type=o,n.matches=r);if(!n)break}return t?u.length:u?nt.error(e):L(e,a).slice(0)}function at(e,t,r){var i=t.dir,s=r&&t.dir==="parentNode",o=w++;return t.first?function(t,n,r){while(t=t[i])if(s||t.nodeType===1)return e(t,n,r)}:function(t,r,u){if(!u){var a,f=b+" "+o+" ",l=f+n;while(t=t[i])if(s||t.nodeType===1){if((a=t[d])===l)return t.sizset;if(typeof a=="string"&&a.indexOf(f)===0){if(t.sizset)return t}else{t[d]=l;if(e(t,r,u))return t.sizset=!0,t;t.sizset=!1}}}else while(t=t[i])if(s||t.nodeType===1)if(e(t,r,u))return t}}function ft(e){return e.length>1?function(t,n,r){var i=e.length;while(i--)if(!e[i](t,n,r))return!1;return!0}:e[0]}function lt(e,t,n,r,i){var s,o=[],u=0,a=e.length,f=t!=null;for(;u-1&&(s[f]=!(o[f]=c))}}else g=lt(g===o?g.splice(d,g.length):g),i?i(null,o,g,a):S.apply(o,g)})}function ht(e){var t,n,r,s=e.length,o=i.relative[e[0].type],u=o||i.relative[" "],a=o?1:0,f=at(function(e){return e===t},u,!0),l=at(function(e){return T.call(t,e)>-1},u,!0),h=[function(e,n,r){return!o&&(r||n!==c)||((t=n).nodeType?f(e,n,r):l(e,n,r))}];for(;a1&&ft(h),a>1&&e.slice(0,a-1).join("").replace(j,"$1"),n,a0,s=e.length>0,o=function(u,a,f,l,h){var p,d,v,m=[],y=0,w="0",x=u&&[],T=h!=null,N=c,C=u||s&&i.find.TAG("*",h&&a.parentNode||a),k=b+=N==null?1:Math.E;T&&(c=a!==g&&a,n=o.el);for(;(p=C[w])!=null;w++){if(s&&p){for(d=0;v=e[d];d++)if(v(p,a,f)){l.push(p);break}T&&(b=k,n=++o.el)}r&&((p=!v&&p)&&y--,u&&x.push(p))}y+=w;if(r&&w!==y){for(d=0;v=t[d];d++)v(x,m,a,f);if(u){if(y>0)while(w--)!x[w]&&!m[w]&&(m[w]=E.call(l));m=lt(m)}S.apply(l,m),T&&!u&&m.length>0&&y+t.length>1&&nt.uniqueSort(l)}return T&&(b=k,c=N),x};return o.el=0,r?N(o):o}function dt(e,t,n){var r=0,i=t.length;for(;r2&&(f=u[0]).type==="ID"&&t.nodeType===9&&!s&&i.relative[u[1].type]){t=i.find.ID(f.matches[0].replace($,""),t,s)[0];if(!t)return n;e=e.slice(u.shift().length)}for(o=J.POS.test(e)?-1:u.length-1;o>=0;o--){f=u[o];if(i.relative[l=f.type])break;if(c=i.find[l])if(r=c(f.matches[0].replace($,""),z.test(u[0].type)&&t.parentNode||t,s)){u.splice(o,1),e=r.length&&u.join("");if(!e)return S.apply(n,x.call(r,0)),n;break}}}return a(e,h)(r,t,s,n,z.test(e)),n}function mt(){}var n,r,i,s,o,u,a,f,l,c,h=!0,p="undefined",d=("sizcache"+Math.random()).replace(".",""),m=String,g=e.document,y=g.documentElement,b=0,w=0,E=[].pop,S=[].push,x=[].slice,T=[].indexOf||function(e){var t=0,n=this.length;for(;ti.cacheLength&&delete e[t.shift()],e[n+" "]=r},e)},k=C(),L=C(),A=C(),O="[\\x20\\t\\r\\n\\f]",M="(?:\\\\.|[-\\w]|[^\\x00-\\xa0])+",_=M.replace("w","w#"),D="([*^$|!~]?=)",P="\\["+O+"*("+M+")"+O+"*(?:"+D+O+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+_+")|)|)"+O+"*\\]",H=":("+M+")(?:\\((?:(['\"])((?:\\\\.|[^\\\\])*?)\\2|([^()[\\]]*|(?:(?:"+P+")|[^:]|\\\\.)*|.*))\\)|)",B=":(even|odd|eq|gt|lt|nth|first|last)(?:\\("+O+"*((?:-\\d)?\\d*)"+O+"*\\)|)(?=[^-]|$)",j=new RegExp("^"+O+"+|((?:^|[^\\\\])(?:\\\\.)*)"+O+"+$","g"),F=new RegExp("^"+O+"*,"+O+"*"),I=new RegExp("^"+O+"*([\\x20\\t\\r\\n\\f>+~])"+O+"*"),q=new RegExp(H),R=/^(?:#([\w\-]+)|(\w+)|\.([\w\-]+))$/,U=/^:not/,z=/[\x20\t\r\n\f]*[+~]/,W=/:not\($/,X=/h\d/i,V=/input|select|textarea|button/i,$=/\\(?!\\)/g,J={ID:new RegExp("^#("+M+")"),CLASS:new RegExp("^\\.("+M+")"),NAME:new RegExp("^\\[name=['\"]?("+M+")['\"]?\\]"),TAG:new RegExp("^("+M.replace("w","w*")+")"),ATTR:new RegExp("^"+P),PSEUDO:new RegExp("^"+H),POS:new RegExp(B,"i"),CHILD:new RegExp("^:(only|nth|first|last)-child(?:\\("+O+"*(even|odd|(([+-]|)(\\d*)n|)"+O+"*(?:([+-]|)"+O+"*(\\d+)|))"+O+"*\\)|)","i"),needsContext:new RegExp("^"+O+"*[>+~]|"+B,"i")},K=function(e){var t=g.createElement("div");try{return e(t)}catch(n){return!1}finally{t=null}},Q=K(function(e){return e.appendChild(g.createComment("")),!e.getElementsByTagName("*").length}),G=K(function(e){return e.innerHTML="",e.firstChild&&typeof e.firstChild.getAttribute!==p&&e.firstChild.getAttribute("href")==="#"}),Y=K(function(e){e.innerHTML="";var t=typeof e.lastChild.getAttribute("multiple");return t!=="boolean"&&t!=="string"}),Z=K(function(e){return e.innerHTML="",!e.getElementsByClassName||!e.getElementsByClassName("e").length?!1:(e.lastChild.className="e",e.getElementsByClassName("e").length===2)}),et=K(function(e){e.id=d+0,e.innerHTML="
",y.insertBefore(e,y.firstChild);var t=g.getElementsByName&&g.getElementsByName(d).length===2+g.getElementsByName(d+0).length;return r=!g.getElementById(d),y.removeChild(e),t});try{x.call(y.childNodes,0)[0].nodeType}catch(tt){x=function(e){var t,n=[];for(;t=this[e];e++)n.push(t);return n}}nt.matches=function(e,t){return nt(e,null,null,t)},nt.matchesSelector=function(e,t){return nt(t,null,null,[e]).length>0},s=nt.getText=function(e){var t,n="",r=0,i=e.nodeType;if(i){if(i===1||i===9||i===11){if(typeof e.textContent=="string")return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=s(e)}else if(i===3||i===4)return e.nodeValue}else for(;t=e[r];r++)n+=s(t);return n},o=nt.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return t?t.nodeName!=="HTML":!1},u=nt.contains=y.contains?function(e,t){var n=e.nodeType===9?e.documentElement:e,r=t&&t.parentNode;return e===r||!!(r&&r.nodeType===1&&n.contains&&n.contains(r))}:y.compareDocumentPosition?function(e,t){return t&&!!(e.compareDocumentPosition(t)&16)}:function(e,t){while(t=t.parentNode)if(t===e)return!0;return!1},nt.attr=function(e,t){var n,r=o(e);return r||(t=t.toLowerCase()),(n=i.attrHandle[t])?n(e):r||Y?e.getAttribute(t):(n=e.getAttributeNode(t),n?typeof e[t]=="boolean"?e[t]?t:null:n.specified?n.value:null:null)},i=nt.selectors={cacheLength:50,createPseudo:N,match:J,attrHandle:G?{}:{href:function(e){return e.getAttribute("href",2)},type:function(e){return e.getAttribute("type")}},find:{ID:r?function(e,t,n){if(typeof t.getElementById!==p&&!n){var r=t.getElementById(e);return r&&r.parentNode?[r]:[]}}:function(e,n,r){if(typeof n.getElementById!==p&&!r){var i=n.getElementById(e);return i?i.id===e||typeof i.getAttributeNode!==p&&i.getAttributeNode("id").value===e?[i]:t:[]}},TAG:Q?function(e,t){if(typeof t.getElementsByTagName!==p)return t.getElementsByTagName(e)}:function(e,t){var n=t.getElementsByTagName(e);if(e==="*"){var r,i=[],s=0;for(;r=n[s];s++)r.nodeType===1&&i.push(r);return i}return n},NAME:et&&function(e,t){if(typeof t.getElementsByName!==p)return t.getElementsByName(name)},CLASS:Z&&function(e,t,n){if(typeof t.getElementsByClassName!==p&&!n)return t.getElementsByClassName(e)}},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace($,""),e[3]=(e[4]||e[5]||"").replace($,""),e[2]==="~="&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),e[1]==="nth"?(e[2]||nt.error(e[0]),e[3]=+(e[3]?e[4]+(e[5]||1):2*(e[2]==="even"||e[2]==="odd")),e[4]=+(e[6]+e[7]||e[2]==="odd")):e[2]&&nt.error(e[0]),e},PSEUDO:function(e){var t,n;if(J.CHILD.test(e[0]))return null;if(e[3])e[2]=e[3];else if(t=e[4])q.test(t)&&(n=ut(t,!0))&&(n=t.indexOf(")",t.length-n)-t.length)&&(t=t.slice(0,n),e[0]=e[0].slice(0,n)),e[2]=t;return e.slice(0,3)}},filter:{ID:r?function(e){return e=e.replace($,""),function(t){return t.getAttribute("id")===e}}:function(e){return e=e.replace($,""),function(t){var n=typeof t.getAttributeNode!==p&&t.getAttributeNode("id");return n&&n.value===e}},TAG:function(e){return e==="*"?function(){return!0}:(e=e.replace($,"").toLowerCase(),function(t){return t.nodeName&&t.nodeName.toLowerCase()===e})},CLASS:function(e){var t=k[d][e+" "];return t||(t=new RegExp("(^|"+O+")"+e+"("+O+"|$)"))&&k(e,function(e){return t.test(e.className||typeof e.getAttribute!==p&&e.getAttribute("class")||"")})},ATTR:function(e,t,n){return function(r,i){var s=nt.attr(r,e);return s==null?t==="!=":t?(s+="",t==="="?s===n:t==="!="?s!==n:t==="^="?n&&s.indexOf(n)===0:t==="*="?n&&s.indexOf(n)>-1:t==="$="?n&&s.substr(s.length-n.length)===n:t==="~="?(" "+s+" ").indexOf(n)>-1:t==="|="?s===n||s.substr(0,n.length+1)===n+"-":!1):!0}},CHILD:function(e,t,n,r){return e==="nth"?function(e){var t,i,s=e.parentNode;if(n===1&&r===0)return!0;if(s){i=0;for(t=s.firstChild;t;t=t.nextSibling)if(t.nodeType===1){i++;if(e===t)break}}return i-=r,i===n||i%n===0&&i/n>=0}:function(t){var n=t;switch(e){case"only":case"first":while(n=n.previousSibling)if(n.nodeType===1)return!1;if(e==="first")return!0;n=t;case"last":while(n=n.nextSibling)if(n.nodeType===1)return!1;return!0}}},PSEUDO:function(e,t){var n,r=i.pseudos[e]||i.setFilters[e.toLowerCase()]||nt.error("unsupported pseudo: "+e);return r[d]?r(t):r.length>1?(n=[e,e,"",t],i.setFilters.hasOwnProperty(e.toLowerCase())?N(function(e,n){var i,s=r(e,t),o=s.length;while(o--)i=T.call(e,s[o]),e[i]=!(n[i]=s[o])}):function(e){return r(e,0,n)}):r}},pseudos:{not:N(function(e){var t=[],n=[],r=a(e.replace(j,"$1"));return r[d]?N(function(e,t,n,i){var s,o=r(e,null,i,[]),u=e.length;while(u--)if(s=o[u])e[u]=!(t[u]=s)}):function(e,i,s){return t[0]=e,r(t,null,s,n),!n.pop()}}),has:N(function(e){return function(t){return nt(e,t).length>0}}),contains:N(function(e){return function(t){return(t.textContent||t.innerText||s(t)).indexOf(e)>-1}}),enabled:function(e){return e.disabled===!1},disabled:function(e){return e.disabled===!0},checked:function(e){var t=e.nodeName.toLowerCase();return t==="input"&&!!e.checked||t==="option"&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,e.selected===!0},parent:function(e){return!i.pseudos.empty(e)},empty:function(e){var t;e=e.firstChild;while(e){if(e.nodeName>"@"||(t=e.nodeType)===3||t===4)return!1;e=e.nextSibling}return!0},header:function(e){return X.test(e.nodeName)},text:function(e){var t,n;return e.nodeName.toLowerCase()==="input"&&(t=e.type)==="text"&&((n=e.getAttribute("type"))==null||n.toLowerCase()===t)},radio:rt("radio"),checkbox:rt("checkbox"),file:rt("file"),password:rt("password"),image:rt("image"),submit:it("submit"),reset:it("reset"),button:function(e){var t=e.nodeName.toLowerCase();return t==="input"&&e.type==="button"||t==="button"},input:function(e){return V.test(e.nodeName)},focus:function(e){var t=e.ownerDocument;return e===t.activeElement&&(!t.hasFocus||t.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},active:function(e){return e===e.ownerDocument.activeElement},first:st(function(){return[0]}),last:st(function(e,t){return[t-1]}),eq:st(function(e,t,n){return[n<0?n+t:n]}),even:st(function(e,t){for(var n=0;n=0;)e.push(r);return e}),gt:st(function(e,t,n){for(var r=n<0?n+t:n;++r",e.querySelectorAll("[selected]").length||i.push("\\["+O+"*(?:checked|disabled|ismap|multiple|readonly|selected|value)"),e.querySelectorAll(":checked").length||i.push(":checked")}),K(function(e){e.innerHTML="

",e.querySelectorAll("[test^='']").length&&i.push("[*^$]="+O+"*(?:\"\"|'')"),e.innerHTML="",e.querySelectorAll(":enabled").length||i.push(":enabled",":disabled")}),i=new RegExp(i.join("|")),vt=function(e,r,s,o,u){if(!o&&!u&&!i.test(e)){var a,f,l=!0,c=d,h=r,p=r.nodeType===9&&e;if(r.nodeType===1&&r.nodeName.toLowerCase()!=="object"){a=ut(e),(l=r.getAttribute("id"))?c=l.replace(n,"\\$&"):r.setAttribute("id",c),c="[id='"+c+"'] ",f=a.length;while(f--)a[f]=c+a[f].join("");h=z.test(e)&&r.parentNode||r,p=a.join(",")}if(p)try{return S.apply(s,x.call(h.querySelectorAll(p),0)),s}catch(v){}finally{l||r.removeAttribute("id")}}return t(e,r,s,o,u)},u&&(K(function(t){e=u.call(t,"div");try{u.call(t,"[test!='']:sizzle"),s.push("!=",H)}catch(n){}}),s=new RegExp(s.join("|")),nt.matchesSelector=function(t,n){n=n.replace(r,"='$1']");if(!o(t)&&!s.test(n)&&!i.test(n))try{var a=u.call(t,n);if(a||e||t.document&&t.document.nodeType!==11)return a}catch(f){}return nt(n,null,null,[t]).length>0})}(),i.pseudos.nth=i.pseudos.eq,i.filters=mt.prototype=i.pseudos,i.setFilters=new mt,nt.attr=v.attr,v.find=nt,v.expr=nt.selectors,v.expr[":"]=v.expr.pseudos,v.unique=nt.uniqueSort,v.text=nt.getText,v.isXMLDoc=nt.isXML,v.contains=nt.contains}(e);var nt=/Until$/,rt=/^(?:parents|prev(?:Until|All))/,it=/^.[^:#\[\.,]*$/,st=v.expr.match.needsContext,ot={children:!0,contents:!0,next:!0,prev:!0};v.fn.extend({find:function(e){var t,n,r,i,s,o,u=this;if(typeof e!="string")return v(e).filter(function(){for(t=0,n=u.length;t0)for(i=r;i=0:v.filter(e,this).length>0:this.filter(e).length>0)},closest:function(e,t){var n,r=0,i=this.length,s=[],o=st.test(e)||typeof e!="string"?v(e,t||this.context):0;for(;r-1:v.find.matchesSelector(n,e)){s.push(n);break}n=n.parentNode}}return s=s.length>1?v.unique(s):s,this.pushStack(s,"closest",e)},index:function(e){return e?typeof e=="string"?v.inArray(this[0],v(e)):v.inArray(e.jquery?e[0]:e,this):this[0]&&this[0].parentNode?this.prevAll().length:-1},add:function(e,t){var n=typeof e=="string"?v(e,t):v.makeArray(e&&e.nodeType?[e]:e),r=v.merge(this.get(),n);return this.pushStack(ut(n[0])||ut(r[0])?r:v.unique(r))},addBack:function(e){return this.add(e==null?this.prevObject:this.prevObject.filter(e))}}),v.fn.andSelf=v.fn.addBack,v.each({parent:function(e){var t=e.parentNode;return t&&t.nodeType!==11?t:null},parents:function(e){return v.dir(e,"parentNode")},parentsUntil:function(e,t,n){return v.dir(e,"parentNode",n)},next:function(e){return at(e,"nextSibling")},prev:function(e){return at(e,"previousSibling")},nextAll:function(e){return v.dir(e,"nextSibling")},prevAll:function(e){return v.dir(e,"previousSibling")},nextUntil:function(e,t,n){return v.dir(e,"nextSibling",n)},prevUntil:function(e,t,n){return v.dir(e,"previousSibling",n)},siblings:function(e){return v.sibling((e.parentNode||{}).firstChild,e)},children:function(e){return v.sibling(e.firstChild)},contents:function(e){return v.nodeName(e,"iframe")?e.contentDocument||e.contentWindow.document:v.merge([],e.childNodes)}},function(e,t){v.fn[e]=function(n,r){var i=v.map(this,t,n);return nt.test(e)||(r=n),r&&typeof r=="string"&&(i=v.filter(r,i)),i=this.length>1&&!ot[e]?v.unique(i):i,this.length>1&&rt.test(e)&&(i=i.reverse()),this.pushStack(i,e,l.call(arguments).join(","))}}),v.extend({filter:function(e,t,n){return n&&(e=":not("+e+")"),t.length===1?v.find.matchesSelector(t[0],e)?[t[0]]:[]:v.find.matches(e,t)},dir:function(e,n,r){var i=[],s=e[n];while(s&&s.nodeType!==9&&(r===t||s.nodeType!==1||!v(s).is(r)))s.nodeType===1&&i.push(s),s=s[n];return i},sibling:function(e,t){var n=[];for(;e;e=e.nextSibling)e.nodeType===1&&e!==t&&n.push(e);return n}});var ct="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",ht=/ jQuery\d+="(?:null|\d+)"/g,pt=/^\s+/,dt=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,vt=/<([\w:]+)/,mt=/]","i"),Et=/^(?:checkbox|radio)$/,St=/checked\s*(?:[^=]|=\s*.checked.)/i,xt=/\/(java|ecma)script/i,Tt=/^\s*\s*$/g,Nt={option:[1,""],legend:[1,"
","
"],thead:[1,"","
"],tr:[2,"","
"],td:[3,"","
"],col:[2,"","
"],area:[1,"",""],_default:[0,"",""]},Ct=lt(i),kt=Ct.appendChild(i.createElement("div"));Nt.optgroup=Nt.option,Nt.tbody=Nt.tfoot=Nt.colgroup=Nt.caption=Nt.thead,Nt.th=Nt.td,v.support.htmlSerialize||(Nt._default=[1,"X
","
"]),v.fn.extend({text:function(e){return v.access(this,function(e){return e===t?v.text(this):this.empty().append((this[0]&&this[0].ownerDocument||i).createTextNode(e))},null,e,arguments.length)},wrapAll:function(e){if(v.isFunction(e))return this.each(function(t){v(this).wrapAll(e.call(this,t))});if(this[0]){var t=v(e,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&t.insertBefore(this[0]),t.map(function(){var e=this;while(e.firstChild&&e.firstChild.nodeType===1)e=e.firstChild;return e}).append(this)}return this},wrapInner:function(e){return v.isFunction(e)?this.each(function(t){v(this).wrapInner(e.call(this,t))}):this.each(function(){var t=v(this),n=t.contents();n.length?n.wrapAll(e):t.append(e)})},wrap:function(e){var t=v.isFunction(e);return this.each(function(n){v(this).wrapAll(t?e.call(this,n):e)})},unwrap:function(){return this.parent().each(function(){v.nodeName(this,"body")||v(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(e){(this.nodeType===1||this.nodeType===11)&&this.appendChild(e)})},prepend:function(){return this.domManip(arguments,!0,function(e){(this.nodeType===1||this.nodeType===11)&&this.insertBefore(e,this.firstChild)})},before:function(){if(!ut(this[0]))return this.domManip(arguments,!1,function(e){this.parentNode.insertBefore(e,this)});if(arguments.length){var e=v.clean(arguments);return this.pushStack(v.merge(e,this),"before",this.selector)}},after:function(){if(!ut(this[0]))return this.domManip(arguments,!1,function(e){this.parentNode.insertBefore(e,this.nextSibling)});if(arguments.length){var e=v.clean(arguments);return this.pushStack(v.merge(this,e),"after",this.selector)}},remove:function(e,t){var n,r=0;for(;(n=this[r])!=null;r++)if(!e||v.filter(e,[n]).length)!t&&n.nodeType===1&&(v.cleanData(n.getElementsByTagName("*")),v.cleanData([n])),n.parentNode&&n.parentNode.removeChild(n);return this},empty:function(){var e,t=0;for(;(e=this[t])!=null;t++){e.nodeType===1&&v.cleanData(e.getElementsByTagName("*"));while(e.firstChild)e.removeChild(e.firstChild)}return this},clone:function(e,t){return e=e==null?!1:e,t=t==null?e:t,this.map(function(){return v.clone(this,e,t)})},html:function(e){return v.access(this,function(e){var n=this[0]||{},r=0,i=this.length;if(e===t)return n.nodeType===1?n.innerHTML.replace(ht,""):t;if(typeof e=="string"&&!yt.test(e)&&(v.support.htmlSerialize||!wt.test(e))&&(v.support.leadingWhitespace||!pt.test(e))&&!Nt[(vt.exec(e)||["",""])[1].toLowerCase()]){e=e.replace(dt,"<$1>");try{for(;r1&&typeof f=="string"&&St.test(f))return this.each(function(){v(this).domManip(e,n,r)});if(v.isFunction(f))return this.each(function(i){var s=v(this);e[0]=f.call(this,i,n?s.html():t),s.domManip(e,n,r)});if(this[0]){i=v.buildFragment(e,this,l),o=i.fragment,s=o.firstChild,o.childNodes.length===1&&(o=s);if(s){n=n&&v.nodeName(s,"tr");for(u=i.cacheable||c-1;a0?this.clone(!0):this).get(),v(o[i])[t](r),s=s.concat(r);return this.pushStack(s,e,o.selector)}}),v.extend({clone:function(e,t,n){var r,i,s,o;v.support.html5Clone||v.isXMLDoc(e)||!wt.test("<"+e.nodeName+">")?o=e.cloneNode(!0):(kt.innerHTML=e.outerHTML,kt.removeChild(o=kt.firstChild));if((!v.support.noCloneEvent||!v.support.noCloneChecked)&&(e.nodeType===1||e.nodeType===11)&&!v.isXMLDoc(e)){Ot(e,o),r=Mt(e),i=Mt(o);for(s=0;r[s];++s)i[s]&&Ot(r[s],i[s])}if(t){At(e,o);if(n){r=Mt(e),i=Mt(o);for(s=0;r[s];++s)At(r[s],i[s])}}return r=i=null,o},clean:function(e,t,n,r){var s,o,u,a,f,l,c,h,p,d,m,g,y=t===i&&Ct,b=[];if(!t||typeof t.createDocumentFragment=="undefined")t=i;for(s=0;(u=e[s])!=null;s++){typeof u=="number"&&(u+="");if(!u)continue;if(typeof u=="string")if(!gt.test(u))u=t.createTextNode(u);else{y=y||lt(t),c=t.createElement("div"),y.appendChild(c),u=u.replace(dt,"<$1>"),a=(vt.exec(u)||["",""])[1].toLowerCase(),f=Nt[a]||Nt._default,l=f[0],c.innerHTML=f[1]+u+f[2];while(l--)c=c.lastChild;if(!v.support.tbody){h=mt.test(u),p=a==="table"&&!h?c.firstChild&&c.firstChild.childNodes:f[1]===""&&!h?c.childNodes:[];for(o=p.length-1;o>=0;--o)v.nodeName(p[o],"tbody")&&!p[o].childNodes.length&&p[o].parentNode.removeChild(p[o])}!v.support.leadingWhitespace&&pt.test(u)&&c.insertBefore(t.createTextNode(pt.exec(u)[0]),c.firstChild),u=c.childNodes,c.parentNode.removeChild(c)}u.nodeType?b.push(u):v.merge(b,u)}c&&(u=c=y=null);if(!v.support.appendChecked)for(s=0;(u=b[s])!=null;s++)v.nodeName(u,"input")?_t(u):typeof u.getElementsByTagName!="undefined"&&v.grep(u.getElementsByTagName("input"),_t);if(n){m=function(e){if(!e.type||xt.test(e.type))return r?r.push(e.parentNode?e.parentNode.removeChild(e):e):n.appendChild(e)};for(s=0;(u=b[s])!=null;s++)if(!v.nodeName(u,"script")||!m(u))n.appendChild(u),typeof u.getElementsByTagName!="undefined"&&(g=v.grep(v.merge([],u.getElementsByTagName("script")),m),b.splice.apply(b,[s+1,0].concat(g)),s+=g.length)}return b},cleanData:function(e,t){var n,r,i,s,o=0,u=v.expando,a=v.cache,f=v.support.deleteExpando,l=v.event.special;for(;(i=e[o])!=null;o++)if(t||v.acceptData(i)){r=i[u],n=r&&a[r];if(n){if(n.events)for(s in n.events)l[s]?v.event.remove(i,s):v.removeEvent(i,s,n.handle);a[r]&&(delete a[r],f?delete i[u]:i.removeAttribute?i.removeAttribute(u):i[u]=null,v.deletedIds.push(r))}}}}),function(){var e,t;v.uaMatch=function(e){e=e.toLowerCase();var t=/(chrome)[ \/]([\w.]+)/.exec(e)||/(webkit)[ \/]([\w.]+)/.exec(e)||/(opera)(?:.*version|)[ \/]([\w.]+)/.exec(e)||/(msie) ([\w.]+)/.exec(e)||e.indexOf("compatible")<0&&/(mozilla)(?:.*? rv:([\w.]+)|)/.exec(e)||[];return{browser:t[1]||"",version:t[2]||"0"}},e=v.uaMatch(o.userAgent),t={},e.browser&&(t[e.browser]=!0,t.version=e.version),t.chrome?t.webkit=!0:t.webkit&&(t.safari=!0),v.browser=t,v.sub=function(){function e(t,n){return new e.fn.init(t,n)}v.extend(!0,e,this),e.superclass=this,e.fn=e.prototype=this(),e.fn.constructor=e,e.sub=this.sub,e.fn.init=function(r,i){return i&&i instanceof v&&!(i instanceof e)&&(i=e(i)),v.fn.init.call(this,r,i,t)},e.fn.init.prototype=e.fn;var t=e(i);return e}}();var Dt,Pt,Ht,Bt=/alpha\([^)]*\)/i,jt=/opacity=([^)]*)/,Ft=/^(top|right|bottom|left)$/,It=/^(none|table(?!-c[ea]).+)/,qt=/^margin/,Rt=new RegExp("^("+m+")(.*)$","i"),Ut=new RegExp("^("+m+")(?!px)[a-z%]+$","i"),zt=new RegExp("^([-+])=("+m+")","i"),Wt={BODY:"block"},Xt={position:"absolute",visibility:"hidden",display:"block"},Vt={letterSpacing:0,fontWeight:400},$t=["Top","Right","Bottom","Left"],Jt=["Webkit","O","Moz","ms"],Kt=v.fn.toggle;v.fn.extend({css:function(e,n){return v.access(this,function(e,n,r){return r!==t?v.style(e,n,r):v.css(e,n)},e,n,arguments.length>1)},show:function(){return Yt(this,!0)},hide:function(){return Yt(this)},toggle:function(e,t){var n=typeof e=="boolean";return v.isFunction(e)&&v.isFunction(t)?Kt.apply(this,arguments):this.each(function(){(n?e:Gt(this))?v(this).show():v(this).hide()})}}),v.extend({cssHooks:{opacity:{get:function(e,t){if(t){var n=Dt(e,"opacity");return n===""?"1":n}}}},cssNumber:{fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":v.support.cssFloat?"cssFloat":"styleFloat"},style:function(e,n,r,i){if(!e||e.nodeType===3||e.nodeType===8||!e.style)return;var s,o,u,a=v.camelCase(n),f=e.style;n=v.cssProps[a]||(v.cssProps[a]=Qt(f,a)),u=v.cssHooks[n]||v.cssHooks[a];if(r===t)return u&&"get"in u&&(s=u.get(e,!1,i))!==t?s:f[n];o=typeof r,o==="string"&&(s=zt.exec(r))&&(r=(s[1]+1)*s[2]+parseFloat(v.css(e,n)),o="number");if(r==null||o==="number"&&isNaN(r))return;o==="number"&&!v.cssNumber[a]&&(r+="px");if(!u||!("set"in u)||(r=u.set(e,r,i))!==t)try{f[n]=r}catch(l){}},css:function(e,n,r,i){var s,o,u,a=v.camelCase(n);return n=v.cssProps[a]||(v.cssProps[a]=Qt(e.style,a)),u=v.cssHooks[n]||v.cssHooks[a],u&&"get"in u&&(s=u.get(e,!0,i)),s===t&&(s=Dt(e,n)),s==="normal"&&n in Vt&&(s=Vt[n]),r||i!==t?(o=parseFloat(s),r||v.isNumeric(o)?o||0:s):s},swap:function(e,t,n){var r,i,s={};for(i in t)s[i]=e.style[i],e.style[i]=t[i];r=n.call(e);for(i in t)e.style[i]=s[i];return r}}),e.getComputedStyle?Dt=function(t,n){var r,i,s,o,u=e.getComputedStyle(t,null),a=t.style;return u&&(r=u.getPropertyValue(n)||u[n],r===""&&!v.contains(t.ownerDocument,t)&&(r=v.style(t,n)),Ut.test(r)&&qt.test(n)&&(i=a.width,s=a.minWidth,o=a.maxWidth,a.minWidth=a.maxWidth=a.width=r,r=u.width,a.width=i,a.minWidth=s,a.maxWidth=o)),r}:i.documentElement.currentStyle&&(Dt=function(e,t){var n,r,i=e.currentStyle&&e.currentStyle[t],s=e.style;return i==null&&s&&s[t]&&(i=s[t]),Ut.test(i)&&!Ft.test(t)&&(n=s.left,r=e.runtimeStyle&&e.runtimeStyle.left,r&&(e.runtimeStyle.left=e.currentStyle.left),s.left=t==="fontSize"?"1em":i,i=s.pixelLeft+"px",s.left=n,r&&(e.runtimeStyle.left=r)),i===""?"auto":i}),v.each(["height","width"],function(e,t){v.cssHooks[t]={get:function(e,n,r){if(n)return e.offsetWidth===0&&It.test(Dt(e,"display"))?v.swap(e,Xt,function(){return tn(e,t,r)}):tn(e,t,r)},set:function(e,n,r){return Zt(e,n,r?en(e,t,r,v.support.boxSizing&&v.css(e,"boxSizing")==="border-box"):0)}}}),v.support.opacity||(v.cssHooks.opacity={get:function(e,t){return jt.test((t&&e.currentStyle?e.currentStyle.filter:e.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":t?"1":""},set:function(e,t){var n=e.style,r=e.currentStyle,i=v.isNumeric(t)?"alpha(opacity="+t*100+")":"",s=r&&r.filter||n.filter||"";n.zoom=1;if(t>=1&&v.trim(s.replace(Bt,""))===""&&n.removeAttribute){n.removeAttribute("filter");if(r&&!r.filter)return}n.filter=Bt.test(s)?s.replace(Bt,i):s+" "+i}}),v(function(){v.support.reliableMarginRight||(v.cssHooks.marginRight={get:function(e,t){return v.swap(e,{display:"inline-block"},function(){if(t)return Dt(e,"marginRight")})}}),!v.support.pixelPosition&&v.fn.position&&v.each(["top","left"],function(e,t){v.cssHooks[t]={get:function(e,n){if(n){var r=Dt(e,t);return Ut.test(r)?v(e).position()[t]+"px":r}}}})}),v.expr&&v.expr.filters&&(v.expr.filters.hidden=function(e){return e.offsetWidth===0&&e.offsetHeight===0||!v.support.reliableHiddenOffsets&&(e.style&&e.style.display||Dt(e,"display"))==="none"},v.expr.filters.visible=function(e){return!v.expr.filters.hidden(e)}),v.each({margin:"",padding:"",border:"Width"},function(e,t){v.cssHooks[e+t]={expand:function(n){var r,i=typeof n=="string"?n.split(" "):[n],s={};for(r=0;r<4;r++)s[e+$t[r]+t]=i[r]||i[r-2]||i[0];return s}},qt.test(e)||(v.cssHooks[e+t].set=Zt)});var rn=/%20/g,sn=/\[\]$/,on=/\r?\n/g,un=/^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,an=/^(?:select|textarea)/i;v.fn.extend({serialize:function(){return v.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?v.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||an.test(this.nodeName)||un.test(this.type))}).map(function(e,t){var n=v(this).val();return n==null?null:v.isArray(n)?v.map(n,function(e,n){return{name:t.name,value:e.replace(on,"\r\n")}}):{name:t.name,value:n.replace(on,"\r\n")}}).get()}}),v.param=function(e,n){var r,i=[],s=function(e,t){t=v.isFunction(t)?t():t==null?"":t,i[i.length]=encodeURIComponent(e)+"="+encodeURIComponent(t)};n===t&&(n=v.ajaxSettings&&v.ajaxSettings.traditional);if(v.isArray(e)||e.jquery&&!v.isPlainObject(e))v.each(e,function(){s(this.name,this.value)});else for(r in e)fn(r,e[r],n,s);return i.join("&").replace(rn,"+")};var ln,cn,hn=/#.*$/,pn=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,dn=/^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,vn=/^(?:GET|HEAD)$/,mn=/^\/\//,gn=/\?/,yn=/)<[^<]*)*<\/script>/gi,bn=/([?&])_=[^&]*/,wn=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,En=v.fn.load,Sn={},xn={},Tn=["*/"]+["*"];try{cn=s.href}catch(Nn){cn=i.createElement("a"),cn.href="",cn=cn.href}ln=wn.exec(cn.toLowerCase())||[],v.fn.load=function(e,n,r){if(typeof e!="string"&&En)return En.apply(this,arguments);if(!this.length)return this;var i,s,o,u=this,a=e.indexOf(" ");return a>=0&&(i=e.slice(a,e.length),e=e.slice(0,a)),v.isFunction(n)?(r=n,n=t):n&&typeof n=="object"&&(s="POST"),v.ajax({url:e,type:s,dataType:"html",data:n,complete:function(e,t){r&&u.each(r,o||[e.responseText,t,e])}}).done(function(e){o=arguments,u.html(i?v("
").append(e.replace(yn,"")).find(i):e)}),this},v.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(e,t){v.fn[t]=function(e){return this.on(t,e)}}),v.each(["get","post"],function(e,n){v[n]=function(e,r,i,s){return v.isFunction(r)&&(s=s||i,i=r,r=t),v.ajax({type:n,url:e,data:r,success:i,dataType:s})}}),v.extend({getScript:function(e,n){return v.get(e,t,n,"script")},getJSON:function(e,t,n){return v.get(e,t,n,"json")},ajaxSetup:function(e,t){return t?Ln(e,v.ajaxSettings):(t=e,e=v.ajaxSettings),Ln(e,t),e},ajaxSettings:{url:cn,isLocal:dn.test(ln[1]),global:!0,type:"GET",contentType:"application/x-www-form-urlencoded; charset=UTF-8",processData:!0,async:!0,accepts:{xml:"application/xml, text/xml",html:"text/html",text:"text/plain",json:"application/json, text/javascript","*":Tn},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":e.String,"text html":!0,"text json":v.parseJSON,"text xml":v.parseXML},flatOptions:{context:!0,url:!0}},ajaxPrefilter:Cn(Sn),ajaxTransport:Cn(xn),ajax:function(e,n){function T(e,n,s,a){var l,y,b,w,S,T=n;if(E===2)return;E=2,u&&clearTimeout(u),o=t,i=a||"",x.readyState=e>0?4:0,s&&(w=An(c,x,s));if(e>=200&&e<300||e===304)c.ifModified&&(S=x.getResponseHeader("Last-Modified"),S&&(v.lastModified[r]=S),S=x.getResponseHeader("Etag"),S&&(v.etag[r]=S)),e===304?(T="notmodified",l=!0):(l=On(c,w),T=l.state,y=l.data,b=l.error,l=!b);else{b=T;if(!T||e)T="error",e<0&&(e=0)}x.status=e,x.statusText=(n||T)+"",l?d.resolveWith(h,[y,T,x]):d.rejectWith(h,[x,T,b]),x.statusCode(g),g=t,f&&p.trigger("ajax"+(l?"Success":"Error"),[x,c,l?y:b]),m.fireWith(h,[x,T]),f&&(p.trigger("ajaxComplete",[x,c]),--v.active||v.event.trigger("ajaxStop"))}typeof e=="object"&&(n=e,e=t),n=n||{};var r,i,s,o,u,a,f,l,c=v.ajaxSetup({},n),h=c.context||c,p=h!==c&&(h.nodeType||h instanceof v)?v(h):v.event,d=v.Deferred(),m=v.Callbacks("once memory"),g=c.statusCode||{},b={},w={},E=0,S="canceled",x={readyState:0,setRequestHeader:function(e,t){if(!E){var n=e.toLowerCase();e=w[n]=w[n]||e,b[e]=t}return this},getAllResponseHeaders:function(){return E===2?i:null},getResponseHeader:function(e){var n;if(E===2){if(!s){s={};while(n=pn.exec(i))s[n[1].toLowerCase()]=n[2]}n=s[e.toLowerCase()]}return n===t?null:n},overrideMimeType:function(e){return E||(c.mimeType=e),this},abort:function(e){return e=e||S,o&&o.abort(e),T(0,e),this}};d.promise(x),x.success=x.done,x.error=x.fail,x.complete=m.add,x.statusCode=function(e){if(e){var t;if(E<2)for(t in e)g[t]=[g[t],e[t]];else t=e[x.status],x.always(t)}return this},c.url=((e||c.url)+"").replace(hn,"").replace(mn,ln[1]+"//"),c.dataTypes=v.trim(c.dataType||"*").toLowerCase().split(y),c.crossDomain==null&&(a=wn.exec(c.url.toLowerCase()),c.crossDomain=!(!a||a[1]===ln[1]&&a[2]===ln[2]&&(a[3]||(a[1]==="http:"?80:443))==(ln[3]||(ln[1]==="http:"?80:443)))),c.data&&c.processData&&typeof c.data!="string"&&(c.data=v.param(c.data,c.traditional)),kn(Sn,c,n,x);if(E===2)return x;f=c.global,c.type=c.type.toUpperCase(),c.hasContent=!vn.test(c.type),f&&v.active++===0&&v.event.trigger("ajaxStart");if(!c.hasContent){c.data&&(c.url+=(gn.test(c.url)?"&":"?")+c.data,delete c.data),r=c.url;if(c.cache===!1){var N=v.now(),C=c.url.replace(bn,"$1_="+N);c.url=C+(C===c.url?(gn.test(c.url)?"&":"?")+"_="+N:"")}}(c.data&&c.hasContent&&c.contentType!==!1||n.contentType)&&x.setRequestHeader("Content-Type",c.contentType),c.ifModified&&(r=r||c.url,v.lastModified[r]&&x.setRequestHeader("If-Modified-Since",v.lastModified[r]),v.etag[r]&&x.setRequestHeader("If-None-Match",v.etag[r])),x.setRequestHeader("Accept",c.dataTypes[0]&&c.accepts[c.dataTypes[0]]?c.accepts[c.dataTypes[0]]+(c.dataTypes[0]!=="*"?", "+Tn+"; q=0.01":""):c.accepts["*"]);for(l in c.headers)x.setRequestHeader(l,c.headers[l]);if(!c.beforeSend||c.beforeSend.call(h,x,c)!==!1&&E!==2){S="abort";for(l in{success:1,error:1,complete:1})x[l](c[l]);o=kn(xn,c,n,x);if(!o)T(-1,"No Transport");else{x.readyState=1,f&&p.trigger("ajaxSend",[x,c]),c.async&&c.timeout>0&&(u=setTimeout(function(){x.abort("timeout")},c.timeout));try{E=1,o.send(b,T)}catch(k){if(!(E<2))throw k;T(-1,k)}}return x}return x.abort()},active:0,lastModified:{},etag:{}});var Mn=[],_n=/\?/,Dn=/(=)\?(?=&|$)|\?\?/,Pn=v.now();v.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=Mn.pop()||v.expando+"_"+Pn++;return this[e]=!0,e}}),v.ajaxPrefilter("json jsonp",function(n,r,i){var s,o,u,a=n.data,f=n.url,l=n.jsonp!==!1,c=l&&Dn.test(f),h=l&&!c&&typeof a=="string"&&!(n.contentType||"").indexOf("application/x-www-form-urlencoded")&&Dn.test(a);if(n.dataTypes[0]==="jsonp"||c||h)return s=n.jsonpCallback=v.isFunction(n.jsonpCallback)?n.jsonpCallback():n.jsonpCallback,o=e[s],c?n.url=f.replace(Dn,"$1"+s):h?n.data=a.replace(Dn,"$1"+s):l&&(n.url+=(_n.test(f)?"&":"?")+n.jsonp+"="+s),n.converters["script json"]=function(){return u||v.error(s+" was not called"),u[0]},n.dataTypes[0]="json",e[s]=function(){u=arguments},i.always(function(){e[s]=o,n[s]&&(n.jsonpCallback=r.jsonpCallback,Mn.push(s)),u&&v.isFunction(o)&&o(u[0]),u=o=t}),"script"}),v.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/javascript|ecmascript/},converters:{"text script":function(e){return v.globalEval(e),e}}}),v.ajaxPrefilter("script",function(e){e.cache===t&&(e.cache=!1),e.crossDomain&&(e.type="GET",e.global=!1)}),v.ajaxTransport("script",function(e){if(e.crossDomain){var n,r=i.head||i.getElementsByTagName("head")[0]||i.documentElement;return{send:function(s,o){n=i.createElement("script"),n.async="async",e.scriptCharset&&(n.charset=e.scriptCharset),n.src=e.url,n.onload=n.onreadystatechange=function(e,i){if(i||!n.readyState||/loaded|complete/.test(n.readyState))n.onload=n.onreadystatechange=null,r&&n.parentNode&&r.removeChild(n),n=t,i||o(200,"success")},r.insertBefore(n,r.firstChild)},abort:function(){n&&n.onload(0,1)}}}});var Hn,Bn=e.ActiveXObject?function(){for(var e in Hn)Hn[e](0,1)}:!1,jn=0;v.ajaxSettings.xhr=e.ActiveXObject?function(){return!this.isLocal&&Fn()||In()}:Fn,function(e){v.extend(v.support,{ajax:!!e,cors:!!e&&"withCredentials"in e})}(v.ajaxSettings.xhr()),v.support.ajax&&v.ajaxTransport(function(n){if(!n.crossDomain||v.support.cors){var r;return{send:function(i,s){var o,u,a=n.xhr();n.username?a.open(n.type,n.url,n.async,n.username,n.password):a.open(n.type,n.url,n.async);if(n.xhrFields)for(u in n.xhrFields)a[u]=n.xhrFields[u];n.mimeType&&a.overrideMimeType&&a.overrideMimeType(n.mimeType),!n.crossDomain&&!i["X-Requested-With"]&&(i["X-Requested-With"]="XMLHttpRequest");try{for(u in i)a.setRequestHeader(u,i[u])}catch(f){}a.send(n.hasContent&&n.data||null),r=function(e,i){var u,f,l,c,h;try{if(r&&(i||a.readyState===4)){r=t,o&&(a.onreadystatechange=v.noop,Bn&&delete Hn[o]);if(i)a.readyState!==4&&a.abort();else{u=a.status,l=a.getAllResponseHeaders(),c={},h=a.responseXML,h&&h.documentElement&&(c.xml=h);try{c.text=a.responseText}catch(p){}try{f=a.statusText}catch(p){f=""}!u&&n.isLocal&&!n.crossDomain?u=c.text?200:404:u===1223&&(u=204)}}}catch(d){i||s(-1,d)}c&&s(u,f,c,l)},n.async?a.readyState===4?setTimeout(r,0):(o=++jn,Bn&&(Hn||(Hn={},v(e).unload(Bn)),Hn[o]=r),a.onreadystatechange=r):r()},abort:function(){r&&r(0,1)}}}});var qn,Rn,Un=/^(?:toggle|show|hide)$/,zn=new RegExp("^(?:([-+])=|)("+m+")([a-z%]*)$","i"),Wn=/queueHooks$/,Xn=[Gn],Vn={"*":[function(e,t){var n,r,i=this.createTween(e,t),s=zn.exec(t),o=i.cur(),u=+o||0,a=1,f=20;if(s){n=+s[2],r=s[3]||(v.cssNumber[e]?"":"px");if(r!=="px"&&u){u=v.css(i.elem,e,!0)||n||1;do a=a||".5",u/=a,v.style(i.elem,e,u+r);while(a!==(a=i.cur()/o)&&a!==1&&--f)}i.unit=r,i.start=u,i.end=s[1]?u+(s[1]+1)*n:n}return i}]};v.Animation=v.extend(Kn,{tweener:function(e,t){v.isFunction(e)?(t=e,e=["*"]):e=e.split(" ");var n,r=0,i=e.length;for(;r-1,f={},l={},c,h;a?(l=i.position(),c=l.top,h=l.left):(c=parseFloat(o)||0,h=parseFloat(u)||0),v.isFunction(t)&&(t=t.call(e,n,s)),t.top!=null&&(f.top=t.top-s.top+c),t.left!=null&&(f.left=t.left-s.left+h),"using"in t?t.using.call(e,f):i.css(f)}},v.fn.extend({position:function(){if(!this[0])return;var e=this[0],t=this.offsetParent(),n=this.offset(),r=er.test(t[0].nodeName)?{top:0,left:0}:t.offset();return n.top-=parseFloat(v.css(e,"marginTop"))||0,n.left-=parseFloat(v.css(e,"marginLeft"))||0,r.top+=parseFloat(v.css(t[0],"borderTopWidth"))||0,r.left+=parseFloat(v.css(t[0],"borderLeftWidth"))||0,{top:n.top-r.top,left:n.left-r.left}},offsetParent:function(){return this.map(function(){var e=this.offsetParent||i.body;while(e&&!er.test(e.nodeName)&&v.css(e,"position")==="static")e=e.offsetParent;return e||i.body})}}),v.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(e,n){var r=/Y/.test(n);v.fn[e]=function(i){return v.access(this,function(e,i,s){var o=tr(e);if(s===t)return o?n in o?o[n]:o.document.documentElement[i]:e[i];o?o.scrollTo(r?v(o).scrollLeft():s,r?s:v(o).scrollTop()):e[i]=s},e,i,arguments.length,null)}}),v.each({Height:"height",Width:"width"},function(e,n){v.each({padding:"inner"+e,content:n,"":"outer"+e},function(r,i){v.fn[i]=function(i,s){var o=arguments.length&&(r||typeof i!="boolean"),u=r||(i===!0||s===!0?"margin":"border");return v.access(this,function(n,r,i){var s;return v.isWindow(n)?n.document.documentElement["client"+e]:n.nodeType===9?(s=n.documentElement,Math.max(n.body["scroll"+e],s["scroll"+e],n.body["offset"+e],s["offset"+e],s["client"+e])):i===t?v.css(n,r,i,u):v.style(n,r,i,u)},n,o?i:t,o,null)}})}),e.jQuery=e.$=v,typeof define=="function"&&define.amd&&define.amd.jQuery&&define("jquery",[],function(){return v})})(window); \ No newline at end of file diff --git a/Chapter07/05_static_middleware/static/content/mustache.js b/Chapter07/05_static_middleware/static/content/mustache.js new file mode 100644 index 0000000..0148d29 --- /dev/null +++ b/Chapter07/05_static_middleware/static/content/mustache.js @@ -0,0 +1,625 @@ +/*! + * mustache.js - Logic-less {{mustache}} templates with JavaScript + * http://github.com/janl/mustache.js + */ + +/*global define: false*/ + +var Mustache; + +(function (exports) { + if (typeof module !== "undefined" && module.exports) { + module.exports = exports; // CommonJS + } else if (typeof define === "function") { + define(exports); // AMD + } else { + Mustache = exports; // + + + + + + + + diff --git a/Chapter08/02_create_album/app/data/album.js b/Chapter08/02_create_album/app/data/album.js new file mode 100644 index 0000000..c107cd5 --- /dev/null +++ b/Chapter08/02_create_album/app/data/album.js @@ -0,0 +1,171 @@ + +var fs = require('fs'), + crypto = require("crypto"), + local = require('../local.config.js'), + db = require('./db.js'), + path = require("path"), + async = require('async'), + backhelp = require("./backend_helpers.js"); + +exports.version = "0.1.0"; + + +exports.create_album = function (data, callback) { + var final_album; + var write_succeeded = false; + async.waterfall([ + // validate data. + function (cb) { + try { + backhelp.verify(data, + [ "name", + "title", + "date", + "description" ]); + if (!backhelp.valid_filename(data.name)) + throw invalid_album_name(); + } catch (e) { + cb(e); + return; + } + cb(null, data); + }, + + // create the album in mongo. + function (album_data, cb) { + var write = JSON.parse(JSON.stringify(album_data)); + write._id = album_data.name; + db.albums.insert(write, { w: 1, safe: true }, cb); + }, + + // make sure the folder exists. + function (new_album, cb) { + write_succeeded = true; + final_album = new_album[0]; + fs.mkdir(local.config.static_content + + "albums/" + data.name, cb); + } + ], + function (err, results) { + // convert file errors to something we like. + if (err) { + if (write_succeeded) + db.albums.remove({ _id: data.name }, function () {}); + + if (err instanceof Error && err.code == 11000) + callback(backhelp.album_already_exists()); + else if (err instanceof Error && err.errno != undefined) + callback(backhelp.file_error(err)); + else + callback(err); + } else { + callback(err, err ? null : final_album); + } + }); +}; + + +exports.album_by_name = function (name, callback) { + db.albums.find({ _id: name }).toArray(function (err, results) { + if (err) { + callback(err); + return; + } + + if (results.length == 0) { + callback(null, null); + } else if (results.length == 1) { + callback(null, results[0]); + } else { + console.error("More than one album named: " + name); + console.error(results); + callback(backhelp.db_error()); + } + }); +}; + + +exports.photos_for_album = function (album_name, pn, ps, callback) { + var sort = { date: -1 }; + db.photos.find({ albumid: album_name }) + .skip(pn) + .limit(ps) + .sort("date") + .toArray(callback); +}; + + + +exports.all_albums = function (sort_field, sort_desc, skip, count, callback) { + var sort = {}; + sort[sort_field] = sort_desc ? -1 : 1; + db.albums.find() + .sort(sort) + .limit(count) + .skip(skip) + .toArray(callback); +}; + + + +exports.add_photo = function (photo_data, path_to_photo, callback) { + var final_photo; + var base_fn = path.basename(path_to_photo).toLowerCase(); + async.waterfall([ + // validate data + function (cb) { + try { + backhelp.verify(photo_data, + [ "albumid", + "description", + "date" ]); + + photo_data.filename = base_fn; + + if (!backhelp.valid_filename(photo_data.albumid)) + throw invalid_album_name(); + } catch (e) { + cb(e); + return; + } + + cb(null, photo_data); + }, + + // add the photo to the collection + function (pd, cb) { + pd._id = pd.albumid + "_" + pd.filename; + db.photos.insert(pd, { w: 1, safe: true }, cb); + }, + + // now copy the temp file to static content + function (new_photo, cb) { + final_photo = new_photo[0]; + + var save_path = local.config.static_content + "albums/" + + photo_data.albumid + "/" + base_fn; + + backhelp.file_copy(path_to_photo, save_path, true, cb); + } + ], + function (err, results) { + // convert file errors to something we like. + if (err && err instanceof Error && err.errno != undefined) + callback(backhelp.file_error(err)); + else + callback(err, err ? null : final_photo); + }); + +}; + + + +function invalid_album_name() { + return backhelp.error("invalid_album_name", + "Album names can have letters, #s, _ and, -"); +} +function invalid_filename() { + return backhelp.error("invalid_filename", + "Filenames can have letters, #s, _ and, -"); +} + diff --git a/Chapter08/02_create_album/app/data/backend_helpers.js b/Chapter08/02_create_album/app/data/backend_helpers.js new file mode 100644 index 0000000..76d1754 --- /dev/null +++ b/Chapter08/02_create_album/app/data/backend_helpers.js @@ -0,0 +1,88 @@ + +var fs = require('fs'); + + +exports.verify = function (data, field_names) { + for (var i = 0; i < field_names.length; i++) { + if (!data[field_names[i]]) { + throw exports.error("missing_data", + field_names[i] + " not optional"); + } + } + + return true; +} + +exports.error = function (code, message) { + var e = new Error(message); + e.code = code; + return e; +}; + +exports.file_error = function (err) { + return exports.error("file_error", JSON.stringify(err.message)); +} + + +/** + * Possible signatures: + * src, dst, callback + * src, dst, can_overwrite, callback + */ +exports.file_copy = function () { + + var src, dst, callback; + var can_overwrite = false; + + if (arguments.length == 3) { + src = arguments[0]; + dst = arguments[1]; + callback = arguments[2]; + } else if (arguments.length == 4) { + src = arguments[0]; + dst = arguments[1]; + callback = arguments[3]; + can_overwrite = arguments[2] + } + + function copy(err) { + var is, os; + + if (!err && !can_overwrite) { + return callback(backhelp.error("file_exists", + "File " + dst + " exists.")); + } + + fs.stat(src, function (err) { + if (err) { + return callback(err); + } + + is = fs.createReadStream(src); + os = fs.createWriteStream(dst); + is.on('end', function () { callback(null); }); + is.on('error', function (e) { callback(e); }); + is.pipe(os); + }); + } + + fs.stat(dst, copy); +}; + + + +exports.valid_filename = function (fn) { + var re = /[^\.a-zA-Z0-9_-]/; + return typeof fn == 'string' && fn.length > 0 && !(fn.match(re)); +}; + + +exports.db_error = function () { + return exports.error("server_error", + "Something horrible has happened with our database!"); +} + +exports.album_already_exists = function () { + return exports.error("album_already_exists", + "An album with this name already exists."); +}; diff --git a/Chapter08/02_create_album/app/data/db.js b/Chapter08/02_create_album/app/data/db.js new file mode 100644 index 0000000..23125e8 --- /dev/null +++ b/Chapter08/02_create_album/app/data/db.js @@ -0,0 +1,58 @@ +var Db = require('mongodb').Db, + Connection = require('mongodb').Connection, + Server = require('mongodb').Server, + async = require('async'), + local = require("../local.config.js"); + +var host = local.config.db_config.host + ? local.config.db_config.host + : 'localhost'; +var port = local.config.db_config.port + ? local.config.db_config.port + : Connection.DEFAULT_PORT; +var ps = local.config.db_config.poolSize + ? local.config.db_config.poolSize : 5; + +var db = new Db('PhotoAlbums', + new Server(host, port, + { auto_reconnect: true, + poolSize: ps}), + { w: 1 }); + +/** + * Currently for initialisation, we just want to open + * the database. We won't even attempt to start up + * if this fails, as it's pretty pointless. + */ +exports.init = function (callback) { + async.waterfall([ + // 1. open database connection + function (cb) { + console.log("\n** 1. open db"); + db.open(cb); + }, + + // 2. create collections for our albums and photos. if + // they already exist, then we're good. + function (db_conn, cb) { + console.log("\n** 2. create albums and photos collections."); + db.collection("albums", cb); + }, + + function (albums_coll, cb) { + exports.albums = albums_coll; + db.collection("photos", cb); + }, + + function (photos_coll, cb) { + exports.photos = photos_coll; + cb(null); + } + ], callback); +}; + + +exports.albums = null; +exports.photos = null; + + diff --git a/Chapter08/02_create_album/app/handlers/albums.js b/Chapter08/02_create_album/app/handlers/albums.js new file mode 100644 index 0000000..ac2da86 --- /dev/null +++ b/Chapter08/02_create_album/app/handlers/albums.js @@ -0,0 +1,259 @@ + +var helpers = require('./helpers.js'), + album_data = require("../data/album.js"), + async = require('async'), + fs = require('fs'); + +exports.version = "0.1.0"; + + +/** + * Album class. + */ +function Album (album_data) { + this.name = album_data.name; + this.date = album_data.date; + this.title = album_data.title; + this.description = album_data.description; + this._id = album_data._id; +} + +Album.prototype.name = null; +Album.prototype.date = null; +Album.prototype.title = null; +Album.prototype.description = null; + +Album.prototype.response_obj = function () { + return { name: this.name, + date: this.date, + title: this.title, + description: this.description }; +}; +Album.prototype.photos = function (pn, ps, callback) { + if (this.album_photos != undefined) { + callback(null, this.album_photos); + return; + } + + album_data.photos_for_album( + this.name, + pn, ps, + function (err, results) { + if (err) { + callback(err); + return; + } + + var out = []; + for (var i = 0; i < results.length; i++) { + out.push(new Photo(results[i])); + } + + this.album_photos = out; + callback(null, this.album_photos); + } + ); +}; +Album.prototype.add_photo = function (data, path, callback) { + album_data.add_photo(data, path, function (err, photo_data) { + if (err) + callback(err); + else { + var p = new Photo(photo_data); + if (this.all_photos) + this.all_photos.push(p); + else + this.app_photos = [ p ]; + + callback(null, p); + } + }); +}; + + + + +/** + * Photo class. + */ +function Photo (photo_data) { + this.filename = photo_data.filename; + this.date = photo_data.date; + this.albumid = photo_data.albumid; + this.description = photo_data.description; + this._id = photo_data._id; +} +Photo.prototype._id = null; +Photo.prototype.filename = null; +Photo.prototype.date = null; +Photo.prototype.albumid = null; +Photo.prototype.description = null; +Photo.prototype.response_obj = function() { + return { + filename: this.filename, + date: this.date, + albumid: this.albumid, + description: this.description + }; +}; + + +/** + * Album module methods. + */ +exports.create_album = function (req, res) { + async.waterfall([ + // make sure the albumid is valid + function (cb) { + if (!req.body || !req.body.name) { + cb(helpers.no_such_album()); + return; + } + + // UNDONE: we should add some code to make sure the album + // doesn't already exist! + cb(null); + }, + + function (cb) { + album_data.create_album(req.body, cb); + } + ], + function (err, results) { + if (err) { + helpers.send_failure(res, err); + } else { + var a = new Album(results); + helpers.send_success(res, {album: a.response_obj() }); + } + }); +}; + + +exports.album_by_name = function (req, res) { + async.waterfall([ + // get the album + function (cb) { + if (!req.params || !req.params.album_name) + cb(helpers.no_such_album()); + else + album_data.album_by_name(req.params.album_name, cb); + } + ], + function (err, results) { + if (err) { + helpers.send_failure(res, err); + } else if (!results) { + helpers.send_failure(res, helpers.no_such_album()); + } else { + var a = new Album(album_data); + helpers.send_success(res, { album: a.response_obj() }); + } + }); +}; + + + +exports.list_all = function (req, res) { + album_data.all_albums("date", true, 0, 25, function (err, results) { + if (err) { + helpers.send_failure(res, err); + } else { + var out = []; + if (results) { + for (var i = 0; i < results.length; i++) { + out.push(new Album(results[i]).response_obj()); + } + } + helpers.send_success(res, { albums: out }); + } + }); +}; + + +exports.photos_for_album = function(req, res) { + var page_num = req.query.page ? req.query.page : 0; + var page_size = req.query.page_size ? req.query.page_size : 1000; + + page_num = parseInt(page_num); + page_size = parseInt(page_size); + if (isNaN(page_num)) page_num = 0; + if (isNaN(page_size)) page_size = 1000; + + var album; + async.waterfall([ + function (cb) { + // first get the album. + if (!req.params || !req.params.album_name) + cb(helpers.no_such_album()); + else + album_data.album_by_name(req.params.album_name, cb); + }, + + function (album_data, cb) { + if (!album_data) { + cb(helpers.no_such_album()); + return; + } + album = new Album(album_data); + album.photos(page_num, page_size, cb); + }, + function (photos, cb) { + var out = []; + for (var i = 0; i < photos.length; i++) { + out.push(photos[i].response_obj()); + } + cb(null, out); + } + ], + function (err, results) { + if (err) { + helpers.send_failure(res, err); + return; + } + if (!results) results = []; + var out = { photos: results, + album_data: album.response_obj() }; + helpers.send_success(res, out); + }); +}; + + +exports.add_photo_to_album = function (req, res) { + var album; + async.waterfall([ + // make sure we have everything we need. + function (cb) { + if (!req.body) + cb(helpers.missing_data("POST data")); + else if (!req.files || !req.files.photo_file) + cb(helpers.missing_data("a file")); + else if (!helpers.is_image(req.files.photo_file.name)) + cb(helpers.not_image()); + else + // get the album + album_data.album_by_name(req.params.album_name, cb); + }, + + function (album_data, cb) { + if (!album_data) { + cb(helpers.no_such_album()); + return; + } + + album = new Album(album_data); + req.body.filename = req.files.photo_file.name; + album.add_photo(req.body, req.files.photo_file.path, cb); + } + ], + function (err, p) { + if (err) { + helpers.send_failure(res, err); + return; + } + var out = { photo: p.response_obj(), + album_data: album.response_obj() }; + helpers.send_success(res, out); + }); +}; + diff --git a/Chapter08/02_create_album/app/handlers/helpers.js b/Chapter08/02_create_album/app/handlers/helpers.js new file mode 100644 index 0000000..97ac782 --- /dev/null +++ b/Chapter08/02_create_album/app/handlers/helpers.js @@ -0,0 +1,95 @@ + +var path = require('path'); + + +exports.version = '0.1.0'; + + + +exports.send_success = function(res, data) { + res.writeHead(200, {"Content-Type": "application/json"}); + var output = { error: null, data: data }; + res.end(JSON.stringify(output) + "\n"); +} + + +exports.send_failure = function(res, err) { + var code = (err.code) ? err.code : err.name; + res.writeHead(code, { "Content-Type" : "application/json" }); + res.end(JSON.stringify({ error: code, message: err.message }) + "\n"); +} + + +exports.error_for_resp = function (err) { + if (!err instanceof Error) { + console.error("** Unexpected error type! :" + + err.constructor.name); + return JSON.stringify(err); + } else { + var code = err.code ? err.code : err.name; + return JSON.stringify({ error: code, + message: err.message }); + } +} + +exports.error = function (code, message) { + var e = new Error(message); + e.code = code; + return e; +}; + +exports.file_error = function (err) { + return exports.error("file_error", JSON.stringify(err)); +}; + + +exports.is_image = function (filename) { + switch (path.extname(filename).toLowerCase()) { + case '.jpg': case '.jpeg': case '.png': case '.bmp': + case '.gif': case '.tif': case '.tiff': + return true; + } + + return false; +}; + + +exports.invalid_resource = function () { + return exports.error("invalid_resource", + "The requested resource does not exist."); +}; + + +exports.missing_data = function (what) { + return exports.error("missing_data", + "You must include " + what); +} + + +exports.not_image = function () { + return exports.error("not_image_file", + "The uploaded file must be an image file."); +}; + + +exports.no_such_album = function () { + return exports.error("no_such_album", + "The specified album does not exist"); +}; + + +exports.http_code_for_error = function (err) { + switch (err.message) { + case "no_such_album": + return 403; + case "invalid_resource": + return 404; + } + return 503; +} + + +exports.valid_filename = function (fn) { + var re = /[^\.a-zA-Z0-9_-]/; + return typeof fn == 'string' && fn.length > 0 && !(fn.match(re)); +}; diff --git a/Chapter08/02_create_album/app/handlers/pages.js b/Chapter08/02_create_album/app/handlers/pages.js new file mode 100644 index 0000000..70c9ff4 --- /dev/null +++ b/Chapter08/02_create_album/app/handlers/pages.js @@ -0,0 +1,31 @@ + +var helpers = require('./helpers.js'), + fs = require('fs'); + + +exports.version = "0.1.0"; + + +exports.generate = function (req, res) { + + var page = req.params.page_name; + if (req.params.sub_page && req.params.page_name == 'admin') + page = req.params.page_name + "_" + req.params.sub_page; + + fs.readFile( + 'basic.html', + function (err, contents) { + if (err) { + send_failure(res, err); + return; + } + + contents = contents.toString('utf8'); + + // replace page name, and then dump to output. + contents = contents.replace('{{PAGE_NAME}}', page); + res.writeHead(200, { "Content-Type": "text/html" }); + res.end(contents); + } + ); +}; diff --git a/Chapter08/02_create_album/app/local.config.js b/Chapter08/02_create_album/app/local.config.js new file mode 100644 index 0000000..dc52aa4 --- /dev/null +++ b/Chapter08/02_create_album/app/local.config.js @@ -0,0 +1,12 @@ + + +exports.config = { + db_config: { + host: "localhost", + // use default "port" + poolSize: 20 + }, + + static_content: "../static/" +}; + diff --git a/Chapter08/02_create_album/app/package.json b/Chapter08/02_create_album/app/package.json new file mode 100644 index 0000000..f062c9b --- /dev/null +++ b/Chapter08/02_create_album/app/package.json @@ -0,0 +1,11 @@ +{ + "name": "Photo-Sharing", + "description": "Our Photo Sharing Application with static middleware", + "version": "0.0.2", + "private": true, + "dependencies": { + "express": "3.x", + "async": "0.1.x", + "mongodb": "1.2.x" + } +} diff --git a/Chapter08/02_create_album/app/server.js b/Chapter08/02_create_album/app/server.js new file mode 100644 index 0000000..08e7e1f --- /dev/null +++ b/Chapter08/02_create_album/app/server.js @@ -0,0 +1,48 @@ + +var express = require('express'); +var app = express(); + +var db = require('./data/db.js'), + album_hdlr = require('./handlers/albums.js'), + page_hdlr = require('./handlers/pages.js'), + helpers = require('./handlers/helpers.js'); + +app.use(express.logger('dev')); +app.use(express.bodyParser({ keepExtensions: true })); +app.use(express.static(__dirname + "/../static")); + +app.get('/v1/albums.json', album_hdlr.list_all); +app.put('/v1/albums.json', album_hdlr.create_album); +app.get('/v1/albums/:album_name.json', album_hdlr.album_by_name); +app.get('/v1/albums/:album_name/photos.json', album_hdlr.photos_for_album); +app.put('/v1/albums/:album_name/photos.json', album_hdlr.add_photo_to_album); + + +app.get('/pages/:page_name', page_hdlr.generate); +app.get('/pages/:page_name/:sub_page', page_hdlr.generate); + + +app.get("/", function (req, res) { + res.redirect("/pages/home"); + res.end(); +}); + +app.get('*', four_oh_four); + +function four_oh_four(req, res) { + res.writeHead(404, { "Content-Type" : "application/json" }); + res.end(JSON.stringify(helpers.invalid_resource()) + "\n"); +} + + + +db.init(function (err, results) { + if (err) { + console.error("** FATAL ERROR ON STARTUP: "); + console.error(err); + process.exit(-1); + } + + app.listen(8080); +}); + diff --git a/Chapter08/02_create_album/static/albums/australia2010/aus_01.jpg b/Chapter08/02_create_album/static/albums/australia2010/aus_01.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter08/02_create_album/static/albums/australia2010/aus_02.jpg b/Chapter08/02_create_album/static/albums/australia2010/aus_02.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter08/02_create_album/static/albums/australia2010/aus_03.jpg b/Chapter08/02_create_album/static/albums/australia2010/aus_03.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter08/02_create_album/static/albums/australia2010/aus_04.jpg b/Chapter08/02_create_album/static/albums/australia2010/aus_04.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter08/02_create_album/static/albums/australia2010/aus_05.jpg b/Chapter08/02_create_album/static/albums/australia2010/aus_05.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter08/02_create_album/static/albums/australia2010/aus_06.jpg b/Chapter08/02_create_album/static/albums/australia2010/aus_06.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter08/02_create_album/static/albums/australia2010/aus_07.jpg b/Chapter08/02_create_album/static/albums/australia2010/aus_07.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter08/02_create_album/static/albums/australia2010/aus_08.jpg b/Chapter08/02_create_album/static/albums/australia2010/aus_08.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter08/02_create_album/static/albums/australia2010/aus_09.jpg b/Chapter08/02_create_album/static/albums/australia2010/aus_09.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter08/02_create_album/static/albums/italy2012/picture_01.jpg b/Chapter08/02_create_album/static/albums/italy2012/picture_01.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter08/02_create_album/static/albums/italy2012/picture_02.jpg b/Chapter08/02_create_album/static/albums/italy2012/picture_02.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter08/02_create_album/static/albums/italy2012/picture_03.jpg b/Chapter08/02_create_album/static/albums/italy2012/picture_03.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter08/02_create_album/static/albums/italy2012/picture_04.jpg b/Chapter08/02_create_album/static/albums/italy2012/picture_04.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter08/02_create_album/static/albums/italy2012/picture_05.jpg b/Chapter08/02_create_album/static/albums/italy2012/picture_05.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter08/02_create_album/static/albums/japan2010/picture_001.jpg b/Chapter08/02_create_album/static/albums/japan2010/picture_001.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter08/02_create_album/static/albums/japan2010/picture_002.jpg b/Chapter08/02_create_album/static/albums/japan2010/picture_002.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter08/02_create_album/static/albums/japan2010/picture_003.jpg b/Chapter08/02_create_album/static/albums/japan2010/picture_003.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter08/02_create_album/static/albums/japan2010/picture_004.jpg b/Chapter08/02_create_album/static/albums/japan2010/picture_004.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter08/02_create_album/static/albums/japan2010/picture_005.jpg b/Chapter08/02_create_album/static/albums/japan2010/picture_005.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter08/02_create_album/static/albums/japan2010/picture_006.jpg b/Chapter08/02_create_album/static/albums/japan2010/picture_006.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter08/02_create_album/static/albums/japan2010/picture_007.jpg b/Chapter08/02_create_album/static/albums/japan2010/picture_007.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter08/02_create_album/static/content/admin_add_album.js b/Chapter08/02_create_album/static/content/admin_add_album.js new file mode 100644 index 0000000..f2987d6 --- /dev/null +++ b/Chapter08/02_create_album/static/content/admin_add_album.js @@ -0,0 +1,22 @@ +$(function(){ + + var tmpl, // Main template HTML + tdata = {}; // JSON data object that feeds the template + + // Initialise page + var initPage = function() { + + // Load the HTML template + $.get("/templates/admin_add_album.html", function(d){ + tmpl = d; + }); + + // When AJAX calls are complete parse the template + // replacing mustache tags with vars + $(document).ajaxStop(function () { + var renderedPage = Mustache.to_html( tmpl, tdata ); + $("body").html( renderedPage ); + }) + }(); +}); + diff --git a/Chapter08/02_create_album/static/content/admin_add_photos.js b/Chapter08/02_create_album/static/content/admin_add_photos.js new file mode 100644 index 0000000..350e536 --- /dev/null +++ b/Chapter08/02_create_album/static/content/admin_add_photos.js @@ -0,0 +1,27 @@ +$(function(){ + + var tmpl, // Main template HTML + tdata = {}; // JSON data object that feeds the template + + // Initialise page + var initPage = function() { + + // Load the HTML template + $.get("/templates/admin_add_photos.html", function(d){ + tmpl = d; + }); + + // Retrieve the server data and then initialise the page + $.getJSON("/v1/albums.json", function (d) { + $.extend(tdata, d.data); + }); + + // When AJAX calls are complete parse the template + // replacing mustache tags with vars + $(document).ajaxStop(function () { + var renderedPage = Mustache.to_html( tmpl, tdata ); + $("body").html( renderedPage ); + }) + }(); +}); + diff --git a/Chapter08/02_create_album/static/content/admin_home.js b/Chapter08/02_create_album/static/content/admin_home.js new file mode 100644 index 0000000..65f31a2 --- /dev/null +++ b/Chapter08/02_create_album/static/content/admin_home.js @@ -0,0 +1,27 @@ +$(function(){ + + var tmpl, // Main template HTML + tdata = {}; // JSON data object that feeds the template + + // Initialise page + var initPage = function() { + + // Load the HTML template + $.get("/templates/admin_home.html", function(d){ + tmpl = d; + }); + + // Retrieve the server data and then initialise the page +/* $.getJSON("/v1/albums.json", function (d) { + $.extend(tdata, d.data); + }); + */ + // When AJAX calls are complete parse the template + // replacing mustache tags with vars + $(document).ajaxStop(function () { + var renderedPage = Mustache.to_html( tmpl, tdata ); + $("body").html( renderedPage ); + }) + }(); +}); + diff --git a/Chapter08/02_create_album/static/content/album.js b/Chapter08/02_create_album/static/content/album.js new file mode 100644 index 0000000..c4d918e --- /dev/null +++ b/Chapter08/02_create_album/static/content/album.js @@ -0,0 +1,67 @@ +$(function(){ + + var tmpl, // Main template HTML + tdata = {}; // JSON data object that feeds the template + + // Initialise page + var initPage = function() { + + // get our album name. + var re = "/pages/album/([a-zA-Z0-9_-]+)"; + var results = new RegExp(re).exec(window.location.href); + var album_name = results[1]; + + // Load the HTML template + $.get("/templates/album.html", function(d){ + tmpl = d; + }); + + var p = $.urlParam("page"); + var ps = $.urlParam("page_size"); + if (p < 0) p = 0; + if (ps <= 0) ps = 1000; + + var qs = "?page=" + p + "&page_size=" + ps; + var url = "/v1/albums/" + album_name + "/photos.json" + qs; + + // Retrieve the server data and then initialise the page + $.getJSON(url, function (d) { + var photo_d = massage_album(d); + $.extend(tdata, photo_d); + }); + + // When AJAX calls are complete parse the template + // replacing mustache tags with vars + $(document).ajaxStop(function () { + var renderedPage = Mustache.to_html( tmpl, tdata ); + $("body").html( renderedPage ); + }) + }(); +}); + + +function massage_album(d) { + if (d.error != null) return d; + var obj = { photos: [] }; + + var p = d.data.photos; + var a = d.data.album_data; + + for (var i = 0; i < p.length; i++) { + var url = "/albums/" + a.name + "/" + p[i].filename; + obj.photos.push({ url: url, desc: p[i].description }); + } + + if (obj.photos.length > 0) obj.has_photos = obj.photos.length; + return obj; +} + + +$.urlParam = function(name){ + var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href); + if (!results) + { + return 0; + } + return results[1] || 0; +} \ No newline at end of file diff --git a/Chapter08/02_create_album/static/content/home.js b/Chapter08/02_create_album/static/content/home.js new file mode 100644 index 0000000..fa7010b --- /dev/null +++ b/Chapter08/02_create_album/static/content/home.js @@ -0,0 +1,28 @@ +$(function(){ + + var tmpl, // Main template HTML + tdata = {}; // JSON data object that feeds the template + + // Initialise page + var initPage = function() { + + // Load the HTML template + $.get("/templates/home.html", function(d){ + tmpl = d; + }); + + + // Retrieve the server data and then initialise the page + $.getJSON("/v1/albums.json", function (d) { + $.extend(tdata, d.data); + }); + + // When AJAX calls are complete parse the template + // replacing mustache tags with vars + $(document).ajaxStop(function () { + var renderedPage = Mustache.to_html( tmpl, tdata ); + $("body").html( renderedPage ); + }) + }(); +}); + diff --git a/Chapter08/02_create_album/static/content/jquery-1.8.3.min.js b/Chapter08/02_create_album/static/content/jquery-1.8.3.min.js new file mode 100644 index 0000000..83589da --- /dev/null +++ b/Chapter08/02_create_album/static/content/jquery-1.8.3.min.js @@ -0,0 +1,2 @@ +/*! jQuery v1.8.3 jquery.com | jquery.org/license */ +(function(e,t){function _(e){var t=M[e]={};return v.each(e.split(y),function(e,n){t[n]=!0}),t}function H(e,n,r){if(r===t&&e.nodeType===1){var i="data-"+n.replace(P,"-$1").toLowerCase();r=e.getAttribute(i);if(typeof r=="string"){try{r=r==="true"?!0:r==="false"?!1:r==="null"?null:+r+""===r?+r:D.test(r)?v.parseJSON(r):r}catch(s){}v.data(e,n,r)}else r=t}return r}function B(e){var t;for(t in e){if(t==="data"&&v.isEmptyObject(e[t]))continue;if(t!=="toJSON")return!1}return!0}function et(){return!1}function tt(){return!0}function ut(e){return!e||!e.parentNode||e.parentNode.nodeType===11}function at(e,t){do e=e[t];while(e&&e.nodeType!==1);return e}function ft(e,t,n){t=t||0;if(v.isFunction(t))return v.grep(e,function(e,r){var i=!!t.call(e,r,e);return i===n});if(t.nodeType)return v.grep(e,function(e,r){return e===t===n});if(typeof t=="string"){var r=v.grep(e,function(e){return e.nodeType===1});if(it.test(t))return v.filter(t,r,!n);t=v.filter(t,r)}return v.grep(e,function(e,r){return v.inArray(e,t)>=0===n})}function lt(e){var t=ct.split("|"),n=e.createDocumentFragment();if(n.createElement)while(t.length)n.createElement(t.pop());return n}function Lt(e,t){return e.getElementsByTagName(t)[0]||e.appendChild(e.ownerDocument.createElement(t))}function At(e,t){if(t.nodeType!==1||!v.hasData(e))return;var n,r,i,s=v._data(e),o=v._data(t,s),u=s.events;if(u){delete o.handle,o.events={};for(n in u)for(r=0,i=u[n].length;r").appendTo(i.body),n=t.css("display");t.remove();if(n==="none"||n===""){Pt=i.body.appendChild(Pt||v.extend(i.createElement("iframe"),{frameBorder:0,width:0,height:0}));if(!Ht||!Pt.createElement)Ht=(Pt.contentWindow||Pt.contentDocument).document,Ht.write(""),Ht.close();t=Ht.body.appendChild(Ht.createElement(e)),n=Dt(t,"display"),i.body.removeChild(Pt)}return Wt[e]=n,n}function fn(e,t,n,r){var i;if(v.isArray(t))v.each(t,function(t,i){n||sn.test(e)?r(e,i):fn(e+"["+(typeof i=="object"?t:"")+"]",i,n,r)});else if(!n&&v.type(t)==="object")for(i in t)fn(e+"["+i+"]",t[i],n,r);else r(e,t)}function Cn(e){return function(t,n){typeof t!="string"&&(n=t,t="*");var r,i,s,o=t.toLowerCase().split(y),u=0,a=o.length;if(v.isFunction(n))for(;u)[^>]*$|#([\w\-]*)$)/,E=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,S=/^[\],:{}\s]*$/,x=/(?:^|:|,)(?:\s*\[)+/g,T=/\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,N=/"[^"\\\r\n]*"|true|false|null|-?(?:\d\d*\.|)\d+(?:[eE][\-+]?\d+|)/g,C=/^-ms-/,k=/-([\da-z])/gi,L=function(e,t){return(t+"").toUpperCase()},A=function(){i.addEventListener?(i.removeEventListener("DOMContentLoaded",A,!1),v.ready()):i.readyState==="complete"&&(i.detachEvent("onreadystatechange",A),v.ready())},O={};v.fn=v.prototype={constructor:v,init:function(e,n,r){var s,o,u,a;if(!e)return this;if(e.nodeType)return this.context=this[0]=e,this.length=1,this;if(typeof e=="string"){e.charAt(0)==="<"&&e.charAt(e.length-1)===">"&&e.length>=3?s=[null,e,null]:s=w.exec(e);if(s&&(s[1]||!n)){if(s[1])return n=n instanceof v?n[0]:n,a=n&&n.nodeType?n.ownerDocument||n:i,e=v.parseHTML(s[1],a,!0),E.test(s[1])&&v.isPlainObject(n)&&this.attr.call(e,n,!0),v.merge(this,e);o=i.getElementById(s[2]);if(o&&o.parentNode){if(o.id!==s[2])return r.find(e);this.length=1,this[0]=o}return this.context=i,this.selector=e,this}return!n||n.jquery?(n||r).find(e):this.constructor(n).find(e)}return v.isFunction(e)?r.ready(e):(e.selector!==t&&(this.selector=e.selector,this.context=e.context),v.makeArray(e,this))},selector:"",jquery:"1.8.3",length:0,size:function(){return this.length},toArray:function(){return l.call(this)},get:function(e){return e==null?this.toArray():e<0?this[this.length+e]:this[e]},pushStack:function(e,t,n){var r=v.merge(this.constructor(),e);return r.prevObject=this,r.context=this.context,t==="find"?r.selector=this.selector+(this.selector?" ":"")+n:t&&(r.selector=this.selector+"."+t+"("+n+")"),r},each:function(e,t){return v.each(this,e,t)},ready:function(e){return v.ready.promise().done(e),this},eq:function(e){return e=+e,e===-1?this.slice(e):this.slice(e,e+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(l.apply(this,arguments),"slice",l.call(arguments).join(","))},map:function(e){return this.pushStack(v.map(this,function(t,n){return e.call(t,n,t)}))},end:function(){return this.prevObject||this.constructor(null)},push:f,sort:[].sort,splice:[].splice},v.fn.init.prototype=v.fn,v.extend=v.fn.extend=function(){var e,n,r,i,s,o,u=arguments[0]||{},a=1,f=arguments.length,l=!1;typeof u=="boolean"&&(l=u,u=arguments[1]||{},a=2),typeof u!="object"&&!v.isFunction(u)&&(u={}),f===a&&(u=this,--a);for(;a0)return;r.resolveWith(i,[v]),v.fn.trigger&&v(i).trigger("ready").off("ready")},isFunction:function(e){return v.type(e)==="function"},isArray:Array.isArray||function(e){return v.type(e)==="array"},isWindow:function(e){return e!=null&&e==e.window},isNumeric:function(e){return!isNaN(parseFloat(e))&&isFinite(e)},type:function(e){return e==null?String(e):O[h.call(e)]||"object"},isPlainObject:function(e){if(!e||v.type(e)!=="object"||e.nodeType||v.isWindow(e))return!1;try{if(e.constructor&&!p.call(e,"constructor")&&!p.call(e.constructor.prototype,"isPrototypeOf"))return!1}catch(n){return!1}var r;for(r in e);return r===t||p.call(e,r)},isEmptyObject:function(e){var t;for(t in e)return!1;return!0},error:function(e){throw new Error(e)},parseHTML:function(e,t,n){var r;return!e||typeof e!="string"?null:(typeof t=="boolean"&&(n=t,t=0),t=t||i,(r=E.exec(e))?[t.createElement(r[1])]:(r=v.buildFragment([e],t,n?null:[]),v.merge([],(r.cacheable?v.clone(r.fragment):r.fragment).childNodes)))},parseJSON:function(t){if(!t||typeof t!="string")return null;t=v.trim(t);if(e.JSON&&e.JSON.parse)return e.JSON.parse(t);if(S.test(t.replace(T,"@").replace(N,"]").replace(x,"")))return(new Function("return "+t))();v.error("Invalid JSON: "+t)},parseXML:function(n){var r,i;if(!n||typeof n!="string")return null;try{e.DOMParser?(i=new DOMParser,r=i.parseFromString(n,"text/xml")):(r=new ActiveXObject("Microsoft.XMLDOM"),r.async="false",r.loadXML(n))}catch(s){r=t}return(!r||!r.documentElement||r.getElementsByTagName("parsererror").length)&&v.error("Invalid XML: "+n),r},noop:function(){},globalEval:function(t){t&&g.test(t)&&(e.execScript||function(t){e.eval.call(e,t)})(t)},camelCase:function(e){return e.replace(C,"ms-").replace(k,L)},nodeName:function(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()},each:function(e,n,r){var i,s=0,o=e.length,u=o===t||v.isFunction(e);if(r){if(u){for(i in e)if(n.apply(e[i],r)===!1)break}else for(;s0&&e[0]&&e[a-1]||a===0||v.isArray(e));if(f)for(;u-1)a.splice(n,1),i&&(n<=o&&o--,n<=u&&u--)}),this},has:function(e){return v.inArray(e,a)>-1},empty:function(){return a=[],this},disable:function(){return a=f=n=t,this},disabled:function(){return!a},lock:function(){return f=t,n||c.disable(),this},locked:function(){return!f},fireWith:function(e,t){return t=t||[],t=[e,t.slice?t.slice():t],a&&(!r||f)&&(i?f.push(t):l(t)),this},fire:function(){return c.fireWith(this,arguments),this},fired:function(){return!!r}};return c},v.extend({Deferred:function(e){var t=[["resolve","done",v.Callbacks("once memory"),"resolved"],["reject","fail",v.Callbacks("once memory"),"rejected"],["notify","progress",v.Callbacks("memory")]],n="pending",r={state:function(){return n},always:function(){return i.done(arguments).fail(arguments),this},then:function(){var e=arguments;return v.Deferred(function(n){v.each(t,function(t,r){var s=r[0],o=e[t];i[r[1]](v.isFunction(o)?function(){var e=o.apply(this,arguments);e&&v.isFunction(e.promise)?e.promise().done(n.resolve).fail(n.reject).progress(n.notify):n[s+"With"](this===i?n:this,[e])}:n[s])}),e=null}).promise()},promise:function(e){return e!=null?v.extend(e,r):r}},i={};return r.pipe=r.then,v.each(t,function(e,s){var o=s[2],u=s[3];r[s[1]]=o.add,u&&o.add(function(){n=u},t[e^1][2].disable,t[2][2].lock),i[s[0]]=o.fire,i[s[0]+"With"]=o.fireWith}),r.promise(i),e&&e.call(i,i),i},when:function(e){var t=0,n=l.call(arguments),r=n.length,i=r!==1||e&&v.isFunction(e.promise)?r:0,s=i===1?e:v.Deferred(),o=function(e,t,n){return function(r){t[e]=this,n[e]=arguments.length>1?l.call(arguments):r,n===u?s.notifyWith(t,n):--i||s.resolveWith(t,n)}},u,a,f;if(r>1){u=new Array(r),a=new Array(r),f=new Array(r);for(;t
a",n=p.getElementsByTagName("*"),r=p.getElementsByTagName("a")[0];if(!n||!r||!n.length)return{};s=i.createElement("select"),o=s.appendChild(i.createElement("option")),u=p.getElementsByTagName("input")[0],r.style.cssText="top:1px;float:left;opacity:.5",t={leadingWhitespace:p.firstChild.nodeType===3,tbody:!p.getElementsByTagName("tbody").length,htmlSerialize:!!p.getElementsByTagName("link").length,style:/top/.test(r.getAttribute("style")),hrefNormalized:r.getAttribute("href")==="/a",opacity:/^0.5/.test(r.style.opacity),cssFloat:!!r.style.cssFloat,checkOn:u.value==="on",optSelected:o.selected,getSetAttribute:p.className!=="t",enctype:!!i.createElement("form").enctype,html5Clone:i.createElement("nav").cloneNode(!0).outerHTML!=="<:nav>",boxModel:i.compatMode==="CSS1Compat",submitBubbles:!0,changeBubbles:!0,focusinBubbles:!1,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0,boxSizingReliable:!0,pixelPosition:!1},u.checked=!0,t.noCloneChecked=u.cloneNode(!0).checked,s.disabled=!0,t.optDisabled=!o.disabled;try{delete p.test}catch(d){t.deleteExpando=!1}!p.addEventListener&&p.attachEvent&&p.fireEvent&&(p.attachEvent("onclick",h=function(){t.noCloneEvent=!1}),p.cloneNode(!0).fireEvent("onclick"),p.detachEvent("onclick",h)),u=i.createElement("input"),u.value="t",u.setAttribute("type","radio"),t.radioValue=u.value==="t",u.setAttribute("checked","checked"),u.setAttribute("name","t"),p.appendChild(u),a=i.createDocumentFragment(),a.appendChild(p.lastChild),t.checkClone=a.cloneNode(!0).cloneNode(!0).lastChild.checked,t.appendChecked=u.checked,a.removeChild(u),a.appendChild(p);if(p.attachEvent)for(l in{submit:!0,change:!0,focusin:!0})f="on"+l,c=f in p,c||(p.setAttribute(f,"return;"),c=typeof p[f]=="function"),t[l+"Bubbles"]=c;return v(function(){var n,r,s,o,u="padding:0;margin:0;border:0;display:block;overflow:hidden;",a=i.getElementsByTagName("body")[0];if(!a)return;n=i.createElement("div"),n.style.cssText="visibility:hidden;border:0;width:0;height:0;position:static;top:0;margin-top:1px",a.insertBefore(n,a.firstChild),r=i.createElement("div"),n.appendChild(r),r.innerHTML="
t
",s=r.getElementsByTagName("td"),s[0].style.cssText="padding:0;margin:0;border:0;display:none",c=s[0].offsetHeight===0,s[0].style.display="",s[1].style.display="none",t.reliableHiddenOffsets=c&&s[0].offsetHeight===0,r.innerHTML="",r.style.cssText="box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;",t.boxSizing=r.offsetWidth===4,t.doesNotIncludeMarginInBodyOffset=a.offsetTop!==1,e.getComputedStyle&&(t.pixelPosition=(e.getComputedStyle(r,null)||{}).top!=="1%",t.boxSizingReliable=(e.getComputedStyle(r,null)||{width:"4px"}).width==="4px",o=i.createElement("div"),o.style.cssText=r.style.cssText=u,o.style.marginRight=o.style.width="0",r.style.width="1px",r.appendChild(o),t.reliableMarginRight=!parseFloat((e.getComputedStyle(o,null)||{}).marginRight)),typeof r.style.zoom!="undefined"&&(r.innerHTML="",r.style.cssText=u+"width:1px;padding:1px;display:inline;zoom:1",t.inlineBlockNeedsLayout=r.offsetWidth===3,r.style.display="block",r.style.overflow="visible",r.innerHTML="
",r.firstChild.style.width="5px",t.shrinkWrapBlocks=r.offsetWidth!==3,n.style.zoom=1),a.removeChild(n),n=r=s=o=null}),a.removeChild(p),n=r=s=o=u=a=p=null,t}();var D=/(?:\{[\s\S]*\}|\[[\s\S]*\])$/,P=/([A-Z])/g;v.extend({cache:{},deletedIds:[],uuid:0,expando:"jQuery"+(v.fn.jquery+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(e){return e=e.nodeType?v.cache[e[v.expando]]:e[v.expando],!!e&&!B(e)},data:function(e,n,r,i){if(!v.acceptData(e))return;var s,o,u=v.expando,a=typeof n=="string",f=e.nodeType,l=f?v.cache:e,c=f?e[u]:e[u]&&u;if((!c||!l[c]||!i&&!l[c].data)&&a&&r===t)return;c||(f?e[u]=c=v.deletedIds.pop()||v.guid++:c=u),l[c]||(l[c]={},f||(l[c].toJSON=v.noop));if(typeof n=="object"||typeof n=="function")i?l[c]=v.extend(l[c],n):l[c].data=v.extend(l[c].data,n);return s=l[c],i||(s.data||(s.data={}),s=s.data),r!==t&&(s[v.camelCase(n)]=r),a?(o=s[n],o==null&&(o=s[v.camelCase(n)])):o=s,o},removeData:function(e,t,n){if(!v.acceptData(e))return;var r,i,s,o=e.nodeType,u=o?v.cache:e,a=o?e[v.expando]:v.expando;if(!u[a])return;if(t){r=n?u[a]:u[a].data;if(r){v.isArray(t)||(t in r?t=[t]:(t=v.camelCase(t),t in r?t=[t]:t=t.split(" ")));for(i=0,s=t.length;i1,null,!1))},removeData:function(e){return this.each(function(){v.removeData(this,e)})}}),v.extend({queue:function(e,t,n){var r;if(e)return t=(t||"fx")+"queue",r=v._data(e,t),n&&(!r||v.isArray(n)?r=v._data(e,t,v.makeArray(n)):r.push(n)),r||[]},dequeue:function(e,t){t=t||"fx";var n=v.queue(e,t),r=n.length,i=n.shift(),s=v._queueHooks(e,t),o=function(){v.dequeue(e,t)};i==="inprogress"&&(i=n.shift(),r--),i&&(t==="fx"&&n.unshift("inprogress"),delete s.stop,i.call(e,o,s)),!r&&s&&s.empty.fire()},_queueHooks:function(e,t){var n=t+"queueHooks";return v._data(e,n)||v._data(e,n,{empty:v.Callbacks("once memory").add(function(){v.removeData(e,t+"queue",!0),v.removeData(e,n,!0)})})}}),v.fn.extend({queue:function(e,n){var r=2;return typeof e!="string"&&(n=e,e="fx",r--),arguments.length1)},removeAttr:function(e){return this.each(function(){v.removeAttr(this,e)})},prop:function(e,t){return v.access(this,v.prop,e,t,arguments.length>1)},removeProp:function(e){return e=v.propFix[e]||e,this.each(function(){try{this[e]=t,delete this[e]}catch(n){}})},addClass:function(e){var t,n,r,i,s,o,u;if(v.isFunction(e))return this.each(function(t){v(this).addClass(e.call(this,t,this.className))});if(e&&typeof e=="string"){t=e.split(y);for(n=0,r=this.length;n=0)r=r.replace(" "+n[s]+" "," ");i.className=e?v.trim(r):""}}}return this},toggleClass:function(e,t){var n=typeof e,r=typeof t=="boolean";return v.isFunction(e)?this.each(function(n){v(this).toggleClass(e.call(this,n,this.className,t),t)}):this.each(function(){if(n==="string"){var i,s=0,o=v(this),u=t,a=e.split(y);while(i=a[s++])u=r?u:!o.hasClass(i),o[u?"addClass":"removeClass"](i)}else if(n==="undefined"||n==="boolean")this.className&&v._data(this,"__className__",this.className),this.className=this.className||e===!1?"":v._data(this,"__className__")||""})},hasClass:function(e){var t=" "+e+" ",n=0,r=this.length;for(;n=0)return!0;return!1},val:function(e){var n,r,i,s=this[0];if(!arguments.length){if(s)return n=v.valHooks[s.type]||v.valHooks[s.nodeName.toLowerCase()],n&&"get"in n&&(r=n.get(s,"value"))!==t?r:(r=s.value,typeof r=="string"?r.replace(R,""):r==null?"":r);return}return i=v.isFunction(e),this.each(function(r){var s,o=v(this);if(this.nodeType!==1)return;i?s=e.call(this,r,o.val()):s=e,s==null?s="":typeof s=="number"?s+="":v.isArray(s)&&(s=v.map(s,function(e){return e==null?"":e+""})),n=v.valHooks[this.type]||v.valHooks[this.nodeName.toLowerCase()];if(!n||!("set"in n)||n.set(this,s,"value")===t)this.value=s})}}),v.extend({valHooks:{option:{get:function(e){var t=e.attributes.value;return!t||t.specified?e.value:e.text}},select:{get:function(e){var t,n,r=e.options,i=e.selectedIndex,s=e.type==="select-one"||i<0,o=s?null:[],u=s?i+1:r.length,a=i<0?u:s?i:0;for(;a=0}),n.length||(e.selectedIndex=-1),n}}},attrFn:{},attr:function(e,n,r,i){var s,o,u,a=e.nodeType;if(!e||a===3||a===8||a===2)return;if(i&&v.isFunction(v.fn[n]))return v(e)[n](r);if(typeof e.getAttribute=="undefined")return v.prop(e,n,r);u=a!==1||!v.isXMLDoc(e),u&&(n=n.toLowerCase(),o=v.attrHooks[n]||(X.test(n)?F:j));if(r!==t){if(r===null){v.removeAttr(e,n);return}return o&&"set"in o&&u&&(s=o.set(e,r,n))!==t?s:(e.setAttribute(n,r+""),r)}return o&&"get"in o&&u&&(s=o.get(e,n))!==null?s:(s=e.getAttribute(n),s===null?t:s)},removeAttr:function(e,t){var n,r,i,s,o=0;if(t&&e.nodeType===1){r=t.split(y);for(;o=0}})});var $=/^(?:textarea|input|select)$/i,J=/^([^\.]*|)(?:\.(.+)|)$/,K=/(?:^|\s)hover(\.\S+|)\b/,Q=/^key/,G=/^(?:mouse|contextmenu)|click/,Y=/^(?:focusinfocus|focusoutblur)$/,Z=function(e){return v.event.special.hover?e:e.replace(K,"mouseenter$1 mouseleave$1")};v.event={add:function(e,n,r,i,s){var o,u,a,f,l,c,h,p,d,m,g;if(e.nodeType===3||e.nodeType===8||!n||!r||!(o=v._data(e)))return;r.handler&&(d=r,r=d.handler,s=d.selector),r.guid||(r.guid=v.guid++),a=o.events,a||(o.events=a={}),u=o.handle,u||(o.handle=u=function(e){return typeof v=="undefined"||!!e&&v.event.triggered===e.type?t:v.event.dispatch.apply(u.elem,arguments)},u.elem=e),n=v.trim(Z(n)).split(" ");for(f=0;f=0&&(y=y.slice(0,-1),a=!0),y.indexOf(".")>=0&&(b=y.split("."),y=b.shift(),b.sort());if((!s||v.event.customEvent[y])&&!v.event.global[y])return;n=typeof n=="object"?n[v.expando]?n:new v.Event(y,n):new v.Event(y),n.type=y,n.isTrigger=!0,n.exclusive=a,n.namespace=b.join("."),n.namespace_re=n.namespace?new RegExp("(^|\\.)"+b.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,h=y.indexOf(":")<0?"on"+y:"";if(!s){u=v.cache;for(f in u)u[f].events&&u[f].events[y]&&v.event.trigger(n,r,u[f].handle.elem,!0);return}n.result=t,n.target||(n.target=s),r=r!=null?v.makeArray(r):[],r.unshift(n),p=v.event.special[y]||{};if(p.trigger&&p.trigger.apply(s,r)===!1)return;m=[[s,p.bindType||y]];if(!o&&!p.noBubble&&!v.isWindow(s)){g=p.delegateType||y,l=Y.test(g+y)?s:s.parentNode;for(c=s;l;l=l.parentNode)m.push([l,g]),c=l;c===(s.ownerDocument||i)&&m.push([c.defaultView||c.parentWindow||e,g])}for(f=0;f=0:v.find(h,this,null,[s]).length),u[h]&&f.push(c);f.length&&w.push({elem:s,matches:f})}d.length>m&&w.push({elem:this,matches:d.slice(m)});for(r=0;r0?this.on(t,null,e,n):this.trigger(t)},Q.test(t)&&(v.event.fixHooks[t]=v.event.keyHooks),G.test(t)&&(v.event.fixHooks[t]=v.event.mouseHooks)}),function(e,t){function nt(e,t,n,r){n=n||[],t=t||g;var i,s,a,f,l=t.nodeType;if(!e||typeof e!="string")return n;if(l!==1&&l!==9)return[];a=o(t);if(!a&&!r)if(i=R.exec(e))if(f=i[1]){if(l===9){s=t.getElementById(f);if(!s||!s.parentNode)return n;if(s.id===f)return n.push(s),n}else if(t.ownerDocument&&(s=t.ownerDocument.getElementById(f))&&u(t,s)&&s.id===f)return n.push(s),n}else{if(i[2])return S.apply(n,x.call(t.getElementsByTagName(e),0)),n;if((f=i[3])&&Z&&t.getElementsByClassName)return S.apply(n,x.call(t.getElementsByClassName(f),0)),n}return vt(e.replace(j,"$1"),t,n,r,a)}function rt(e){return function(t){var n=t.nodeName.toLowerCase();return n==="input"&&t.type===e}}function it(e){return function(t){var n=t.nodeName.toLowerCase();return(n==="input"||n==="button")&&t.type===e}}function st(e){return N(function(t){return t=+t,N(function(n,r){var i,s=e([],n.length,t),o=s.length;while(o--)n[i=s[o]]&&(n[i]=!(r[i]=n[i]))})})}function ot(e,t,n){if(e===t)return n;var r=e.nextSibling;while(r){if(r===t)return-1;r=r.nextSibling}return 1}function ut(e,t){var n,r,s,o,u,a,f,l=L[d][e+" "];if(l)return t?0:l.slice(0);u=e,a=[],f=i.preFilter;while(u){if(!n||(r=F.exec(u)))r&&(u=u.slice(r[0].length)||u),a.push(s=[]);n=!1;if(r=I.exec(u))s.push(n=new m(r.shift())),u=u.slice(n.length),n.type=r[0].replace(j," ");for(o in i.filter)(r=J[o].exec(u))&&(!f[o]||(r=f[o](r)))&&(s.push(n=new m(r.shift())),u=u.slice(n.length),n.type=o,n.matches=r);if(!n)break}return t?u.length:u?nt.error(e):L(e,a).slice(0)}function at(e,t,r){var i=t.dir,s=r&&t.dir==="parentNode",o=w++;return t.first?function(t,n,r){while(t=t[i])if(s||t.nodeType===1)return e(t,n,r)}:function(t,r,u){if(!u){var a,f=b+" "+o+" ",l=f+n;while(t=t[i])if(s||t.nodeType===1){if((a=t[d])===l)return t.sizset;if(typeof a=="string"&&a.indexOf(f)===0){if(t.sizset)return t}else{t[d]=l;if(e(t,r,u))return t.sizset=!0,t;t.sizset=!1}}}else while(t=t[i])if(s||t.nodeType===1)if(e(t,r,u))return t}}function ft(e){return e.length>1?function(t,n,r){var i=e.length;while(i--)if(!e[i](t,n,r))return!1;return!0}:e[0]}function lt(e,t,n,r,i){var s,o=[],u=0,a=e.length,f=t!=null;for(;u-1&&(s[f]=!(o[f]=c))}}else g=lt(g===o?g.splice(d,g.length):g),i?i(null,o,g,a):S.apply(o,g)})}function ht(e){var t,n,r,s=e.length,o=i.relative[e[0].type],u=o||i.relative[" "],a=o?1:0,f=at(function(e){return e===t},u,!0),l=at(function(e){return T.call(t,e)>-1},u,!0),h=[function(e,n,r){return!o&&(r||n!==c)||((t=n).nodeType?f(e,n,r):l(e,n,r))}];for(;a1&&ft(h),a>1&&e.slice(0,a-1).join("").replace(j,"$1"),n,a0,s=e.length>0,o=function(u,a,f,l,h){var p,d,v,m=[],y=0,w="0",x=u&&[],T=h!=null,N=c,C=u||s&&i.find.TAG("*",h&&a.parentNode||a),k=b+=N==null?1:Math.E;T&&(c=a!==g&&a,n=o.el);for(;(p=C[w])!=null;w++){if(s&&p){for(d=0;v=e[d];d++)if(v(p,a,f)){l.push(p);break}T&&(b=k,n=++o.el)}r&&((p=!v&&p)&&y--,u&&x.push(p))}y+=w;if(r&&w!==y){for(d=0;v=t[d];d++)v(x,m,a,f);if(u){if(y>0)while(w--)!x[w]&&!m[w]&&(m[w]=E.call(l));m=lt(m)}S.apply(l,m),T&&!u&&m.length>0&&y+t.length>1&&nt.uniqueSort(l)}return T&&(b=k,c=N),x};return o.el=0,r?N(o):o}function dt(e,t,n){var r=0,i=t.length;for(;r2&&(f=u[0]).type==="ID"&&t.nodeType===9&&!s&&i.relative[u[1].type]){t=i.find.ID(f.matches[0].replace($,""),t,s)[0];if(!t)return n;e=e.slice(u.shift().length)}for(o=J.POS.test(e)?-1:u.length-1;o>=0;o--){f=u[o];if(i.relative[l=f.type])break;if(c=i.find[l])if(r=c(f.matches[0].replace($,""),z.test(u[0].type)&&t.parentNode||t,s)){u.splice(o,1),e=r.length&&u.join("");if(!e)return S.apply(n,x.call(r,0)),n;break}}}return a(e,h)(r,t,s,n,z.test(e)),n}function mt(){}var n,r,i,s,o,u,a,f,l,c,h=!0,p="undefined",d=("sizcache"+Math.random()).replace(".",""),m=String,g=e.document,y=g.documentElement,b=0,w=0,E=[].pop,S=[].push,x=[].slice,T=[].indexOf||function(e){var t=0,n=this.length;for(;ti.cacheLength&&delete e[t.shift()],e[n+" "]=r},e)},k=C(),L=C(),A=C(),O="[\\x20\\t\\r\\n\\f]",M="(?:\\\\.|[-\\w]|[^\\x00-\\xa0])+",_=M.replace("w","w#"),D="([*^$|!~]?=)",P="\\["+O+"*("+M+")"+O+"*(?:"+D+O+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+_+")|)|)"+O+"*\\]",H=":("+M+")(?:\\((?:(['\"])((?:\\\\.|[^\\\\])*?)\\2|([^()[\\]]*|(?:(?:"+P+")|[^:]|\\\\.)*|.*))\\)|)",B=":(even|odd|eq|gt|lt|nth|first|last)(?:\\("+O+"*((?:-\\d)?\\d*)"+O+"*\\)|)(?=[^-]|$)",j=new RegExp("^"+O+"+|((?:^|[^\\\\])(?:\\\\.)*)"+O+"+$","g"),F=new RegExp("^"+O+"*,"+O+"*"),I=new RegExp("^"+O+"*([\\x20\\t\\r\\n\\f>+~])"+O+"*"),q=new RegExp(H),R=/^(?:#([\w\-]+)|(\w+)|\.([\w\-]+))$/,U=/^:not/,z=/[\x20\t\r\n\f]*[+~]/,W=/:not\($/,X=/h\d/i,V=/input|select|textarea|button/i,$=/\\(?!\\)/g,J={ID:new RegExp("^#("+M+")"),CLASS:new RegExp("^\\.("+M+")"),NAME:new RegExp("^\\[name=['\"]?("+M+")['\"]?\\]"),TAG:new RegExp("^("+M.replace("w","w*")+")"),ATTR:new RegExp("^"+P),PSEUDO:new RegExp("^"+H),POS:new RegExp(B,"i"),CHILD:new RegExp("^:(only|nth|first|last)-child(?:\\("+O+"*(even|odd|(([+-]|)(\\d*)n|)"+O+"*(?:([+-]|)"+O+"*(\\d+)|))"+O+"*\\)|)","i"),needsContext:new RegExp("^"+O+"*[>+~]|"+B,"i")},K=function(e){var t=g.createElement("div");try{return e(t)}catch(n){return!1}finally{t=null}},Q=K(function(e){return e.appendChild(g.createComment("")),!e.getElementsByTagName("*").length}),G=K(function(e){return e.innerHTML="",e.firstChild&&typeof e.firstChild.getAttribute!==p&&e.firstChild.getAttribute("href")==="#"}),Y=K(function(e){e.innerHTML="";var t=typeof e.lastChild.getAttribute("multiple");return t!=="boolean"&&t!=="string"}),Z=K(function(e){return e.innerHTML="",!e.getElementsByClassName||!e.getElementsByClassName("e").length?!1:(e.lastChild.className="e",e.getElementsByClassName("e").length===2)}),et=K(function(e){e.id=d+0,e.innerHTML="
",y.insertBefore(e,y.firstChild);var t=g.getElementsByName&&g.getElementsByName(d).length===2+g.getElementsByName(d+0).length;return r=!g.getElementById(d),y.removeChild(e),t});try{x.call(y.childNodes,0)[0].nodeType}catch(tt){x=function(e){var t,n=[];for(;t=this[e];e++)n.push(t);return n}}nt.matches=function(e,t){return nt(e,null,null,t)},nt.matchesSelector=function(e,t){return nt(t,null,null,[e]).length>0},s=nt.getText=function(e){var t,n="",r=0,i=e.nodeType;if(i){if(i===1||i===9||i===11){if(typeof e.textContent=="string")return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=s(e)}else if(i===3||i===4)return e.nodeValue}else for(;t=e[r];r++)n+=s(t);return n},o=nt.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return t?t.nodeName!=="HTML":!1},u=nt.contains=y.contains?function(e,t){var n=e.nodeType===9?e.documentElement:e,r=t&&t.parentNode;return e===r||!!(r&&r.nodeType===1&&n.contains&&n.contains(r))}:y.compareDocumentPosition?function(e,t){return t&&!!(e.compareDocumentPosition(t)&16)}:function(e,t){while(t=t.parentNode)if(t===e)return!0;return!1},nt.attr=function(e,t){var n,r=o(e);return r||(t=t.toLowerCase()),(n=i.attrHandle[t])?n(e):r||Y?e.getAttribute(t):(n=e.getAttributeNode(t),n?typeof e[t]=="boolean"?e[t]?t:null:n.specified?n.value:null:null)},i=nt.selectors={cacheLength:50,createPseudo:N,match:J,attrHandle:G?{}:{href:function(e){return e.getAttribute("href",2)},type:function(e){return e.getAttribute("type")}},find:{ID:r?function(e,t,n){if(typeof t.getElementById!==p&&!n){var r=t.getElementById(e);return r&&r.parentNode?[r]:[]}}:function(e,n,r){if(typeof n.getElementById!==p&&!r){var i=n.getElementById(e);return i?i.id===e||typeof i.getAttributeNode!==p&&i.getAttributeNode("id").value===e?[i]:t:[]}},TAG:Q?function(e,t){if(typeof t.getElementsByTagName!==p)return t.getElementsByTagName(e)}:function(e,t){var n=t.getElementsByTagName(e);if(e==="*"){var r,i=[],s=0;for(;r=n[s];s++)r.nodeType===1&&i.push(r);return i}return n},NAME:et&&function(e,t){if(typeof t.getElementsByName!==p)return t.getElementsByName(name)},CLASS:Z&&function(e,t,n){if(typeof t.getElementsByClassName!==p&&!n)return t.getElementsByClassName(e)}},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace($,""),e[3]=(e[4]||e[5]||"").replace($,""),e[2]==="~="&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),e[1]==="nth"?(e[2]||nt.error(e[0]),e[3]=+(e[3]?e[4]+(e[5]||1):2*(e[2]==="even"||e[2]==="odd")),e[4]=+(e[6]+e[7]||e[2]==="odd")):e[2]&&nt.error(e[0]),e},PSEUDO:function(e){var t,n;if(J.CHILD.test(e[0]))return null;if(e[3])e[2]=e[3];else if(t=e[4])q.test(t)&&(n=ut(t,!0))&&(n=t.indexOf(")",t.length-n)-t.length)&&(t=t.slice(0,n),e[0]=e[0].slice(0,n)),e[2]=t;return e.slice(0,3)}},filter:{ID:r?function(e){return e=e.replace($,""),function(t){return t.getAttribute("id")===e}}:function(e){return e=e.replace($,""),function(t){var n=typeof t.getAttributeNode!==p&&t.getAttributeNode("id");return n&&n.value===e}},TAG:function(e){return e==="*"?function(){return!0}:(e=e.replace($,"").toLowerCase(),function(t){return t.nodeName&&t.nodeName.toLowerCase()===e})},CLASS:function(e){var t=k[d][e+" "];return t||(t=new RegExp("(^|"+O+")"+e+"("+O+"|$)"))&&k(e,function(e){return t.test(e.className||typeof e.getAttribute!==p&&e.getAttribute("class")||"")})},ATTR:function(e,t,n){return function(r,i){var s=nt.attr(r,e);return s==null?t==="!=":t?(s+="",t==="="?s===n:t==="!="?s!==n:t==="^="?n&&s.indexOf(n)===0:t==="*="?n&&s.indexOf(n)>-1:t==="$="?n&&s.substr(s.length-n.length)===n:t==="~="?(" "+s+" ").indexOf(n)>-1:t==="|="?s===n||s.substr(0,n.length+1)===n+"-":!1):!0}},CHILD:function(e,t,n,r){return e==="nth"?function(e){var t,i,s=e.parentNode;if(n===1&&r===0)return!0;if(s){i=0;for(t=s.firstChild;t;t=t.nextSibling)if(t.nodeType===1){i++;if(e===t)break}}return i-=r,i===n||i%n===0&&i/n>=0}:function(t){var n=t;switch(e){case"only":case"first":while(n=n.previousSibling)if(n.nodeType===1)return!1;if(e==="first")return!0;n=t;case"last":while(n=n.nextSibling)if(n.nodeType===1)return!1;return!0}}},PSEUDO:function(e,t){var n,r=i.pseudos[e]||i.setFilters[e.toLowerCase()]||nt.error("unsupported pseudo: "+e);return r[d]?r(t):r.length>1?(n=[e,e,"",t],i.setFilters.hasOwnProperty(e.toLowerCase())?N(function(e,n){var i,s=r(e,t),o=s.length;while(o--)i=T.call(e,s[o]),e[i]=!(n[i]=s[o])}):function(e){return r(e,0,n)}):r}},pseudos:{not:N(function(e){var t=[],n=[],r=a(e.replace(j,"$1"));return r[d]?N(function(e,t,n,i){var s,o=r(e,null,i,[]),u=e.length;while(u--)if(s=o[u])e[u]=!(t[u]=s)}):function(e,i,s){return t[0]=e,r(t,null,s,n),!n.pop()}}),has:N(function(e){return function(t){return nt(e,t).length>0}}),contains:N(function(e){return function(t){return(t.textContent||t.innerText||s(t)).indexOf(e)>-1}}),enabled:function(e){return e.disabled===!1},disabled:function(e){return e.disabled===!0},checked:function(e){var t=e.nodeName.toLowerCase();return t==="input"&&!!e.checked||t==="option"&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,e.selected===!0},parent:function(e){return!i.pseudos.empty(e)},empty:function(e){var t;e=e.firstChild;while(e){if(e.nodeName>"@"||(t=e.nodeType)===3||t===4)return!1;e=e.nextSibling}return!0},header:function(e){return X.test(e.nodeName)},text:function(e){var t,n;return e.nodeName.toLowerCase()==="input"&&(t=e.type)==="text"&&((n=e.getAttribute("type"))==null||n.toLowerCase()===t)},radio:rt("radio"),checkbox:rt("checkbox"),file:rt("file"),password:rt("password"),image:rt("image"),submit:it("submit"),reset:it("reset"),button:function(e){var t=e.nodeName.toLowerCase();return t==="input"&&e.type==="button"||t==="button"},input:function(e){return V.test(e.nodeName)},focus:function(e){var t=e.ownerDocument;return e===t.activeElement&&(!t.hasFocus||t.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},active:function(e){return e===e.ownerDocument.activeElement},first:st(function(){return[0]}),last:st(function(e,t){return[t-1]}),eq:st(function(e,t,n){return[n<0?n+t:n]}),even:st(function(e,t){for(var n=0;n=0;)e.push(r);return e}),gt:st(function(e,t,n){for(var r=n<0?n+t:n;++r",e.querySelectorAll("[selected]").length||i.push("\\["+O+"*(?:checked|disabled|ismap|multiple|readonly|selected|value)"),e.querySelectorAll(":checked").length||i.push(":checked")}),K(function(e){e.innerHTML="

",e.querySelectorAll("[test^='']").length&&i.push("[*^$]="+O+"*(?:\"\"|'')"),e.innerHTML="",e.querySelectorAll(":enabled").length||i.push(":enabled",":disabled")}),i=new RegExp(i.join("|")),vt=function(e,r,s,o,u){if(!o&&!u&&!i.test(e)){var a,f,l=!0,c=d,h=r,p=r.nodeType===9&&e;if(r.nodeType===1&&r.nodeName.toLowerCase()!=="object"){a=ut(e),(l=r.getAttribute("id"))?c=l.replace(n,"\\$&"):r.setAttribute("id",c),c="[id='"+c+"'] ",f=a.length;while(f--)a[f]=c+a[f].join("");h=z.test(e)&&r.parentNode||r,p=a.join(",")}if(p)try{return S.apply(s,x.call(h.querySelectorAll(p),0)),s}catch(v){}finally{l||r.removeAttribute("id")}}return t(e,r,s,o,u)},u&&(K(function(t){e=u.call(t,"div");try{u.call(t,"[test!='']:sizzle"),s.push("!=",H)}catch(n){}}),s=new RegExp(s.join("|")),nt.matchesSelector=function(t,n){n=n.replace(r,"='$1']");if(!o(t)&&!s.test(n)&&!i.test(n))try{var a=u.call(t,n);if(a||e||t.document&&t.document.nodeType!==11)return a}catch(f){}return nt(n,null,null,[t]).length>0})}(),i.pseudos.nth=i.pseudos.eq,i.filters=mt.prototype=i.pseudos,i.setFilters=new mt,nt.attr=v.attr,v.find=nt,v.expr=nt.selectors,v.expr[":"]=v.expr.pseudos,v.unique=nt.uniqueSort,v.text=nt.getText,v.isXMLDoc=nt.isXML,v.contains=nt.contains}(e);var nt=/Until$/,rt=/^(?:parents|prev(?:Until|All))/,it=/^.[^:#\[\.,]*$/,st=v.expr.match.needsContext,ot={children:!0,contents:!0,next:!0,prev:!0};v.fn.extend({find:function(e){var t,n,r,i,s,o,u=this;if(typeof e!="string")return v(e).filter(function(){for(t=0,n=u.length;t0)for(i=r;i=0:v.filter(e,this).length>0:this.filter(e).length>0)},closest:function(e,t){var n,r=0,i=this.length,s=[],o=st.test(e)||typeof e!="string"?v(e,t||this.context):0;for(;r-1:v.find.matchesSelector(n,e)){s.push(n);break}n=n.parentNode}}return s=s.length>1?v.unique(s):s,this.pushStack(s,"closest",e)},index:function(e){return e?typeof e=="string"?v.inArray(this[0],v(e)):v.inArray(e.jquery?e[0]:e,this):this[0]&&this[0].parentNode?this.prevAll().length:-1},add:function(e,t){var n=typeof e=="string"?v(e,t):v.makeArray(e&&e.nodeType?[e]:e),r=v.merge(this.get(),n);return this.pushStack(ut(n[0])||ut(r[0])?r:v.unique(r))},addBack:function(e){return this.add(e==null?this.prevObject:this.prevObject.filter(e))}}),v.fn.andSelf=v.fn.addBack,v.each({parent:function(e){var t=e.parentNode;return t&&t.nodeType!==11?t:null},parents:function(e){return v.dir(e,"parentNode")},parentsUntil:function(e,t,n){return v.dir(e,"parentNode",n)},next:function(e){return at(e,"nextSibling")},prev:function(e){return at(e,"previousSibling")},nextAll:function(e){return v.dir(e,"nextSibling")},prevAll:function(e){return v.dir(e,"previousSibling")},nextUntil:function(e,t,n){return v.dir(e,"nextSibling",n)},prevUntil:function(e,t,n){return v.dir(e,"previousSibling",n)},siblings:function(e){return v.sibling((e.parentNode||{}).firstChild,e)},children:function(e){return v.sibling(e.firstChild)},contents:function(e){return v.nodeName(e,"iframe")?e.contentDocument||e.contentWindow.document:v.merge([],e.childNodes)}},function(e,t){v.fn[e]=function(n,r){var i=v.map(this,t,n);return nt.test(e)||(r=n),r&&typeof r=="string"&&(i=v.filter(r,i)),i=this.length>1&&!ot[e]?v.unique(i):i,this.length>1&&rt.test(e)&&(i=i.reverse()),this.pushStack(i,e,l.call(arguments).join(","))}}),v.extend({filter:function(e,t,n){return n&&(e=":not("+e+")"),t.length===1?v.find.matchesSelector(t[0],e)?[t[0]]:[]:v.find.matches(e,t)},dir:function(e,n,r){var i=[],s=e[n];while(s&&s.nodeType!==9&&(r===t||s.nodeType!==1||!v(s).is(r)))s.nodeType===1&&i.push(s),s=s[n];return i},sibling:function(e,t){var n=[];for(;e;e=e.nextSibling)e.nodeType===1&&e!==t&&n.push(e);return n}});var ct="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",ht=/ jQuery\d+="(?:null|\d+)"/g,pt=/^\s+/,dt=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,vt=/<([\w:]+)/,mt=/]","i"),Et=/^(?:checkbox|radio)$/,St=/checked\s*(?:[^=]|=\s*.checked.)/i,xt=/\/(java|ecma)script/i,Tt=/^\s*\s*$/g,Nt={option:[1,""],legend:[1,"
","
"],thead:[1,"","
"],tr:[2,"","
"],td:[3,"","
"],col:[2,"","
"],area:[1,"",""],_default:[0,"",""]},Ct=lt(i),kt=Ct.appendChild(i.createElement("div"));Nt.optgroup=Nt.option,Nt.tbody=Nt.tfoot=Nt.colgroup=Nt.caption=Nt.thead,Nt.th=Nt.td,v.support.htmlSerialize||(Nt._default=[1,"X
","
"]),v.fn.extend({text:function(e){return v.access(this,function(e){return e===t?v.text(this):this.empty().append((this[0]&&this[0].ownerDocument||i).createTextNode(e))},null,e,arguments.length)},wrapAll:function(e){if(v.isFunction(e))return this.each(function(t){v(this).wrapAll(e.call(this,t))});if(this[0]){var t=v(e,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&t.insertBefore(this[0]),t.map(function(){var e=this;while(e.firstChild&&e.firstChild.nodeType===1)e=e.firstChild;return e}).append(this)}return this},wrapInner:function(e){return v.isFunction(e)?this.each(function(t){v(this).wrapInner(e.call(this,t))}):this.each(function(){var t=v(this),n=t.contents();n.length?n.wrapAll(e):t.append(e)})},wrap:function(e){var t=v.isFunction(e);return this.each(function(n){v(this).wrapAll(t?e.call(this,n):e)})},unwrap:function(){return this.parent().each(function(){v.nodeName(this,"body")||v(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(e){(this.nodeType===1||this.nodeType===11)&&this.appendChild(e)})},prepend:function(){return this.domManip(arguments,!0,function(e){(this.nodeType===1||this.nodeType===11)&&this.insertBefore(e,this.firstChild)})},before:function(){if(!ut(this[0]))return this.domManip(arguments,!1,function(e){this.parentNode.insertBefore(e,this)});if(arguments.length){var e=v.clean(arguments);return this.pushStack(v.merge(e,this),"before",this.selector)}},after:function(){if(!ut(this[0]))return this.domManip(arguments,!1,function(e){this.parentNode.insertBefore(e,this.nextSibling)});if(arguments.length){var e=v.clean(arguments);return this.pushStack(v.merge(this,e),"after",this.selector)}},remove:function(e,t){var n,r=0;for(;(n=this[r])!=null;r++)if(!e||v.filter(e,[n]).length)!t&&n.nodeType===1&&(v.cleanData(n.getElementsByTagName("*")),v.cleanData([n])),n.parentNode&&n.parentNode.removeChild(n);return this},empty:function(){var e,t=0;for(;(e=this[t])!=null;t++){e.nodeType===1&&v.cleanData(e.getElementsByTagName("*"));while(e.firstChild)e.removeChild(e.firstChild)}return this},clone:function(e,t){return e=e==null?!1:e,t=t==null?e:t,this.map(function(){return v.clone(this,e,t)})},html:function(e){return v.access(this,function(e){var n=this[0]||{},r=0,i=this.length;if(e===t)return n.nodeType===1?n.innerHTML.replace(ht,""):t;if(typeof e=="string"&&!yt.test(e)&&(v.support.htmlSerialize||!wt.test(e))&&(v.support.leadingWhitespace||!pt.test(e))&&!Nt[(vt.exec(e)||["",""])[1].toLowerCase()]){e=e.replace(dt,"<$1>");try{for(;r1&&typeof f=="string"&&St.test(f))return this.each(function(){v(this).domManip(e,n,r)});if(v.isFunction(f))return this.each(function(i){var s=v(this);e[0]=f.call(this,i,n?s.html():t),s.domManip(e,n,r)});if(this[0]){i=v.buildFragment(e,this,l),o=i.fragment,s=o.firstChild,o.childNodes.length===1&&(o=s);if(s){n=n&&v.nodeName(s,"tr");for(u=i.cacheable||c-1;a0?this.clone(!0):this).get(),v(o[i])[t](r),s=s.concat(r);return this.pushStack(s,e,o.selector)}}),v.extend({clone:function(e,t,n){var r,i,s,o;v.support.html5Clone||v.isXMLDoc(e)||!wt.test("<"+e.nodeName+">")?o=e.cloneNode(!0):(kt.innerHTML=e.outerHTML,kt.removeChild(o=kt.firstChild));if((!v.support.noCloneEvent||!v.support.noCloneChecked)&&(e.nodeType===1||e.nodeType===11)&&!v.isXMLDoc(e)){Ot(e,o),r=Mt(e),i=Mt(o);for(s=0;r[s];++s)i[s]&&Ot(r[s],i[s])}if(t){At(e,o);if(n){r=Mt(e),i=Mt(o);for(s=0;r[s];++s)At(r[s],i[s])}}return r=i=null,o},clean:function(e,t,n,r){var s,o,u,a,f,l,c,h,p,d,m,g,y=t===i&&Ct,b=[];if(!t||typeof t.createDocumentFragment=="undefined")t=i;for(s=0;(u=e[s])!=null;s++){typeof u=="number"&&(u+="");if(!u)continue;if(typeof u=="string")if(!gt.test(u))u=t.createTextNode(u);else{y=y||lt(t),c=t.createElement("div"),y.appendChild(c),u=u.replace(dt,"<$1>"),a=(vt.exec(u)||["",""])[1].toLowerCase(),f=Nt[a]||Nt._default,l=f[0],c.innerHTML=f[1]+u+f[2];while(l--)c=c.lastChild;if(!v.support.tbody){h=mt.test(u),p=a==="table"&&!h?c.firstChild&&c.firstChild.childNodes:f[1]===""&&!h?c.childNodes:[];for(o=p.length-1;o>=0;--o)v.nodeName(p[o],"tbody")&&!p[o].childNodes.length&&p[o].parentNode.removeChild(p[o])}!v.support.leadingWhitespace&&pt.test(u)&&c.insertBefore(t.createTextNode(pt.exec(u)[0]),c.firstChild),u=c.childNodes,c.parentNode.removeChild(c)}u.nodeType?b.push(u):v.merge(b,u)}c&&(u=c=y=null);if(!v.support.appendChecked)for(s=0;(u=b[s])!=null;s++)v.nodeName(u,"input")?_t(u):typeof u.getElementsByTagName!="undefined"&&v.grep(u.getElementsByTagName("input"),_t);if(n){m=function(e){if(!e.type||xt.test(e.type))return r?r.push(e.parentNode?e.parentNode.removeChild(e):e):n.appendChild(e)};for(s=0;(u=b[s])!=null;s++)if(!v.nodeName(u,"script")||!m(u))n.appendChild(u),typeof u.getElementsByTagName!="undefined"&&(g=v.grep(v.merge([],u.getElementsByTagName("script")),m),b.splice.apply(b,[s+1,0].concat(g)),s+=g.length)}return b},cleanData:function(e,t){var n,r,i,s,o=0,u=v.expando,a=v.cache,f=v.support.deleteExpando,l=v.event.special;for(;(i=e[o])!=null;o++)if(t||v.acceptData(i)){r=i[u],n=r&&a[r];if(n){if(n.events)for(s in n.events)l[s]?v.event.remove(i,s):v.removeEvent(i,s,n.handle);a[r]&&(delete a[r],f?delete i[u]:i.removeAttribute?i.removeAttribute(u):i[u]=null,v.deletedIds.push(r))}}}}),function(){var e,t;v.uaMatch=function(e){e=e.toLowerCase();var t=/(chrome)[ \/]([\w.]+)/.exec(e)||/(webkit)[ \/]([\w.]+)/.exec(e)||/(opera)(?:.*version|)[ \/]([\w.]+)/.exec(e)||/(msie) ([\w.]+)/.exec(e)||e.indexOf("compatible")<0&&/(mozilla)(?:.*? rv:([\w.]+)|)/.exec(e)||[];return{browser:t[1]||"",version:t[2]||"0"}},e=v.uaMatch(o.userAgent),t={},e.browser&&(t[e.browser]=!0,t.version=e.version),t.chrome?t.webkit=!0:t.webkit&&(t.safari=!0),v.browser=t,v.sub=function(){function e(t,n){return new e.fn.init(t,n)}v.extend(!0,e,this),e.superclass=this,e.fn=e.prototype=this(),e.fn.constructor=e,e.sub=this.sub,e.fn.init=function(r,i){return i&&i instanceof v&&!(i instanceof e)&&(i=e(i)),v.fn.init.call(this,r,i,t)},e.fn.init.prototype=e.fn;var t=e(i);return e}}();var Dt,Pt,Ht,Bt=/alpha\([^)]*\)/i,jt=/opacity=([^)]*)/,Ft=/^(top|right|bottom|left)$/,It=/^(none|table(?!-c[ea]).+)/,qt=/^margin/,Rt=new RegExp("^("+m+")(.*)$","i"),Ut=new RegExp("^("+m+")(?!px)[a-z%]+$","i"),zt=new RegExp("^([-+])=("+m+")","i"),Wt={BODY:"block"},Xt={position:"absolute",visibility:"hidden",display:"block"},Vt={letterSpacing:0,fontWeight:400},$t=["Top","Right","Bottom","Left"],Jt=["Webkit","O","Moz","ms"],Kt=v.fn.toggle;v.fn.extend({css:function(e,n){return v.access(this,function(e,n,r){return r!==t?v.style(e,n,r):v.css(e,n)},e,n,arguments.length>1)},show:function(){return Yt(this,!0)},hide:function(){return Yt(this)},toggle:function(e,t){var n=typeof e=="boolean";return v.isFunction(e)&&v.isFunction(t)?Kt.apply(this,arguments):this.each(function(){(n?e:Gt(this))?v(this).show():v(this).hide()})}}),v.extend({cssHooks:{opacity:{get:function(e,t){if(t){var n=Dt(e,"opacity");return n===""?"1":n}}}},cssNumber:{fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":v.support.cssFloat?"cssFloat":"styleFloat"},style:function(e,n,r,i){if(!e||e.nodeType===3||e.nodeType===8||!e.style)return;var s,o,u,a=v.camelCase(n),f=e.style;n=v.cssProps[a]||(v.cssProps[a]=Qt(f,a)),u=v.cssHooks[n]||v.cssHooks[a];if(r===t)return u&&"get"in u&&(s=u.get(e,!1,i))!==t?s:f[n];o=typeof r,o==="string"&&(s=zt.exec(r))&&(r=(s[1]+1)*s[2]+parseFloat(v.css(e,n)),o="number");if(r==null||o==="number"&&isNaN(r))return;o==="number"&&!v.cssNumber[a]&&(r+="px");if(!u||!("set"in u)||(r=u.set(e,r,i))!==t)try{f[n]=r}catch(l){}},css:function(e,n,r,i){var s,o,u,a=v.camelCase(n);return n=v.cssProps[a]||(v.cssProps[a]=Qt(e.style,a)),u=v.cssHooks[n]||v.cssHooks[a],u&&"get"in u&&(s=u.get(e,!0,i)),s===t&&(s=Dt(e,n)),s==="normal"&&n in Vt&&(s=Vt[n]),r||i!==t?(o=parseFloat(s),r||v.isNumeric(o)?o||0:s):s},swap:function(e,t,n){var r,i,s={};for(i in t)s[i]=e.style[i],e.style[i]=t[i];r=n.call(e);for(i in t)e.style[i]=s[i];return r}}),e.getComputedStyle?Dt=function(t,n){var r,i,s,o,u=e.getComputedStyle(t,null),a=t.style;return u&&(r=u.getPropertyValue(n)||u[n],r===""&&!v.contains(t.ownerDocument,t)&&(r=v.style(t,n)),Ut.test(r)&&qt.test(n)&&(i=a.width,s=a.minWidth,o=a.maxWidth,a.minWidth=a.maxWidth=a.width=r,r=u.width,a.width=i,a.minWidth=s,a.maxWidth=o)),r}:i.documentElement.currentStyle&&(Dt=function(e,t){var n,r,i=e.currentStyle&&e.currentStyle[t],s=e.style;return i==null&&s&&s[t]&&(i=s[t]),Ut.test(i)&&!Ft.test(t)&&(n=s.left,r=e.runtimeStyle&&e.runtimeStyle.left,r&&(e.runtimeStyle.left=e.currentStyle.left),s.left=t==="fontSize"?"1em":i,i=s.pixelLeft+"px",s.left=n,r&&(e.runtimeStyle.left=r)),i===""?"auto":i}),v.each(["height","width"],function(e,t){v.cssHooks[t]={get:function(e,n,r){if(n)return e.offsetWidth===0&&It.test(Dt(e,"display"))?v.swap(e,Xt,function(){return tn(e,t,r)}):tn(e,t,r)},set:function(e,n,r){return Zt(e,n,r?en(e,t,r,v.support.boxSizing&&v.css(e,"boxSizing")==="border-box"):0)}}}),v.support.opacity||(v.cssHooks.opacity={get:function(e,t){return jt.test((t&&e.currentStyle?e.currentStyle.filter:e.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":t?"1":""},set:function(e,t){var n=e.style,r=e.currentStyle,i=v.isNumeric(t)?"alpha(opacity="+t*100+")":"",s=r&&r.filter||n.filter||"";n.zoom=1;if(t>=1&&v.trim(s.replace(Bt,""))===""&&n.removeAttribute){n.removeAttribute("filter");if(r&&!r.filter)return}n.filter=Bt.test(s)?s.replace(Bt,i):s+" "+i}}),v(function(){v.support.reliableMarginRight||(v.cssHooks.marginRight={get:function(e,t){return v.swap(e,{display:"inline-block"},function(){if(t)return Dt(e,"marginRight")})}}),!v.support.pixelPosition&&v.fn.position&&v.each(["top","left"],function(e,t){v.cssHooks[t]={get:function(e,n){if(n){var r=Dt(e,t);return Ut.test(r)?v(e).position()[t]+"px":r}}}})}),v.expr&&v.expr.filters&&(v.expr.filters.hidden=function(e){return e.offsetWidth===0&&e.offsetHeight===0||!v.support.reliableHiddenOffsets&&(e.style&&e.style.display||Dt(e,"display"))==="none"},v.expr.filters.visible=function(e){return!v.expr.filters.hidden(e)}),v.each({margin:"",padding:"",border:"Width"},function(e,t){v.cssHooks[e+t]={expand:function(n){var r,i=typeof n=="string"?n.split(" "):[n],s={};for(r=0;r<4;r++)s[e+$t[r]+t]=i[r]||i[r-2]||i[0];return s}},qt.test(e)||(v.cssHooks[e+t].set=Zt)});var rn=/%20/g,sn=/\[\]$/,on=/\r?\n/g,un=/^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,an=/^(?:select|textarea)/i;v.fn.extend({serialize:function(){return v.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?v.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||an.test(this.nodeName)||un.test(this.type))}).map(function(e,t){var n=v(this).val();return n==null?null:v.isArray(n)?v.map(n,function(e,n){return{name:t.name,value:e.replace(on,"\r\n")}}):{name:t.name,value:n.replace(on,"\r\n")}}).get()}}),v.param=function(e,n){var r,i=[],s=function(e,t){t=v.isFunction(t)?t():t==null?"":t,i[i.length]=encodeURIComponent(e)+"="+encodeURIComponent(t)};n===t&&(n=v.ajaxSettings&&v.ajaxSettings.traditional);if(v.isArray(e)||e.jquery&&!v.isPlainObject(e))v.each(e,function(){s(this.name,this.value)});else for(r in e)fn(r,e[r],n,s);return i.join("&").replace(rn,"+")};var ln,cn,hn=/#.*$/,pn=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,dn=/^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,vn=/^(?:GET|HEAD)$/,mn=/^\/\//,gn=/\?/,yn=/)<[^<]*)*<\/script>/gi,bn=/([?&])_=[^&]*/,wn=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,En=v.fn.load,Sn={},xn={},Tn=["*/"]+["*"];try{cn=s.href}catch(Nn){cn=i.createElement("a"),cn.href="",cn=cn.href}ln=wn.exec(cn.toLowerCase())||[],v.fn.load=function(e,n,r){if(typeof e!="string"&&En)return En.apply(this,arguments);if(!this.length)return this;var i,s,o,u=this,a=e.indexOf(" ");return a>=0&&(i=e.slice(a,e.length),e=e.slice(0,a)),v.isFunction(n)?(r=n,n=t):n&&typeof n=="object"&&(s="POST"),v.ajax({url:e,type:s,dataType:"html",data:n,complete:function(e,t){r&&u.each(r,o||[e.responseText,t,e])}}).done(function(e){o=arguments,u.html(i?v("
").append(e.replace(yn,"")).find(i):e)}),this},v.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(e,t){v.fn[t]=function(e){return this.on(t,e)}}),v.each(["get","post"],function(e,n){v[n]=function(e,r,i,s){return v.isFunction(r)&&(s=s||i,i=r,r=t),v.ajax({type:n,url:e,data:r,success:i,dataType:s})}}),v.extend({getScript:function(e,n){return v.get(e,t,n,"script")},getJSON:function(e,t,n){return v.get(e,t,n,"json")},ajaxSetup:function(e,t){return t?Ln(e,v.ajaxSettings):(t=e,e=v.ajaxSettings),Ln(e,t),e},ajaxSettings:{url:cn,isLocal:dn.test(ln[1]),global:!0,type:"GET",contentType:"application/x-www-form-urlencoded; charset=UTF-8",processData:!0,async:!0,accepts:{xml:"application/xml, text/xml",html:"text/html",text:"text/plain",json:"application/json, text/javascript","*":Tn},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":e.String,"text html":!0,"text json":v.parseJSON,"text xml":v.parseXML},flatOptions:{context:!0,url:!0}},ajaxPrefilter:Cn(Sn),ajaxTransport:Cn(xn),ajax:function(e,n){function T(e,n,s,a){var l,y,b,w,S,T=n;if(E===2)return;E=2,u&&clearTimeout(u),o=t,i=a||"",x.readyState=e>0?4:0,s&&(w=An(c,x,s));if(e>=200&&e<300||e===304)c.ifModified&&(S=x.getResponseHeader("Last-Modified"),S&&(v.lastModified[r]=S),S=x.getResponseHeader("Etag"),S&&(v.etag[r]=S)),e===304?(T="notmodified",l=!0):(l=On(c,w),T=l.state,y=l.data,b=l.error,l=!b);else{b=T;if(!T||e)T="error",e<0&&(e=0)}x.status=e,x.statusText=(n||T)+"",l?d.resolveWith(h,[y,T,x]):d.rejectWith(h,[x,T,b]),x.statusCode(g),g=t,f&&p.trigger("ajax"+(l?"Success":"Error"),[x,c,l?y:b]),m.fireWith(h,[x,T]),f&&(p.trigger("ajaxComplete",[x,c]),--v.active||v.event.trigger("ajaxStop"))}typeof e=="object"&&(n=e,e=t),n=n||{};var r,i,s,o,u,a,f,l,c=v.ajaxSetup({},n),h=c.context||c,p=h!==c&&(h.nodeType||h instanceof v)?v(h):v.event,d=v.Deferred(),m=v.Callbacks("once memory"),g=c.statusCode||{},b={},w={},E=0,S="canceled",x={readyState:0,setRequestHeader:function(e,t){if(!E){var n=e.toLowerCase();e=w[n]=w[n]||e,b[e]=t}return this},getAllResponseHeaders:function(){return E===2?i:null},getResponseHeader:function(e){var n;if(E===2){if(!s){s={};while(n=pn.exec(i))s[n[1].toLowerCase()]=n[2]}n=s[e.toLowerCase()]}return n===t?null:n},overrideMimeType:function(e){return E||(c.mimeType=e),this},abort:function(e){return e=e||S,o&&o.abort(e),T(0,e),this}};d.promise(x),x.success=x.done,x.error=x.fail,x.complete=m.add,x.statusCode=function(e){if(e){var t;if(E<2)for(t in e)g[t]=[g[t],e[t]];else t=e[x.status],x.always(t)}return this},c.url=((e||c.url)+"").replace(hn,"").replace(mn,ln[1]+"//"),c.dataTypes=v.trim(c.dataType||"*").toLowerCase().split(y),c.crossDomain==null&&(a=wn.exec(c.url.toLowerCase()),c.crossDomain=!(!a||a[1]===ln[1]&&a[2]===ln[2]&&(a[3]||(a[1]==="http:"?80:443))==(ln[3]||(ln[1]==="http:"?80:443)))),c.data&&c.processData&&typeof c.data!="string"&&(c.data=v.param(c.data,c.traditional)),kn(Sn,c,n,x);if(E===2)return x;f=c.global,c.type=c.type.toUpperCase(),c.hasContent=!vn.test(c.type),f&&v.active++===0&&v.event.trigger("ajaxStart");if(!c.hasContent){c.data&&(c.url+=(gn.test(c.url)?"&":"?")+c.data,delete c.data),r=c.url;if(c.cache===!1){var N=v.now(),C=c.url.replace(bn,"$1_="+N);c.url=C+(C===c.url?(gn.test(c.url)?"&":"?")+"_="+N:"")}}(c.data&&c.hasContent&&c.contentType!==!1||n.contentType)&&x.setRequestHeader("Content-Type",c.contentType),c.ifModified&&(r=r||c.url,v.lastModified[r]&&x.setRequestHeader("If-Modified-Since",v.lastModified[r]),v.etag[r]&&x.setRequestHeader("If-None-Match",v.etag[r])),x.setRequestHeader("Accept",c.dataTypes[0]&&c.accepts[c.dataTypes[0]]?c.accepts[c.dataTypes[0]]+(c.dataTypes[0]!=="*"?", "+Tn+"; q=0.01":""):c.accepts["*"]);for(l in c.headers)x.setRequestHeader(l,c.headers[l]);if(!c.beforeSend||c.beforeSend.call(h,x,c)!==!1&&E!==2){S="abort";for(l in{success:1,error:1,complete:1})x[l](c[l]);o=kn(xn,c,n,x);if(!o)T(-1,"No Transport");else{x.readyState=1,f&&p.trigger("ajaxSend",[x,c]),c.async&&c.timeout>0&&(u=setTimeout(function(){x.abort("timeout")},c.timeout));try{E=1,o.send(b,T)}catch(k){if(!(E<2))throw k;T(-1,k)}}return x}return x.abort()},active:0,lastModified:{},etag:{}});var Mn=[],_n=/\?/,Dn=/(=)\?(?=&|$)|\?\?/,Pn=v.now();v.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=Mn.pop()||v.expando+"_"+Pn++;return this[e]=!0,e}}),v.ajaxPrefilter("json jsonp",function(n,r,i){var s,o,u,a=n.data,f=n.url,l=n.jsonp!==!1,c=l&&Dn.test(f),h=l&&!c&&typeof a=="string"&&!(n.contentType||"").indexOf("application/x-www-form-urlencoded")&&Dn.test(a);if(n.dataTypes[0]==="jsonp"||c||h)return s=n.jsonpCallback=v.isFunction(n.jsonpCallback)?n.jsonpCallback():n.jsonpCallback,o=e[s],c?n.url=f.replace(Dn,"$1"+s):h?n.data=a.replace(Dn,"$1"+s):l&&(n.url+=(_n.test(f)?"&":"?")+n.jsonp+"="+s),n.converters["script json"]=function(){return u||v.error(s+" was not called"),u[0]},n.dataTypes[0]="json",e[s]=function(){u=arguments},i.always(function(){e[s]=o,n[s]&&(n.jsonpCallback=r.jsonpCallback,Mn.push(s)),u&&v.isFunction(o)&&o(u[0]),u=o=t}),"script"}),v.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/javascript|ecmascript/},converters:{"text script":function(e){return v.globalEval(e),e}}}),v.ajaxPrefilter("script",function(e){e.cache===t&&(e.cache=!1),e.crossDomain&&(e.type="GET",e.global=!1)}),v.ajaxTransport("script",function(e){if(e.crossDomain){var n,r=i.head||i.getElementsByTagName("head")[0]||i.documentElement;return{send:function(s,o){n=i.createElement("script"),n.async="async",e.scriptCharset&&(n.charset=e.scriptCharset),n.src=e.url,n.onload=n.onreadystatechange=function(e,i){if(i||!n.readyState||/loaded|complete/.test(n.readyState))n.onload=n.onreadystatechange=null,r&&n.parentNode&&r.removeChild(n),n=t,i||o(200,"success")},r.insertBefore(n,r.firstChild)},abort:function(){n&&n.onload(0,1)}}}});var Hn,Bn=e.ActiveXObject?function(){for(var e in Hn)Hn[e](0,1)}:!1,jn=0;v.ajaxSettings.xhr=e.ActiveXObject?function(){return!this.isLocal&&Fn()||In()}:Fn,function(e){v.extend(v.support,{ajax:!!e,cors:!!e&&"withCredentials"in e})}(v.ajaxSettings.xhr()),v.support.ajax&&v.ajaxTransport(function(n){if(!n.crossDomain||v.support.cors){var r;return{send:function(i,s){var o,u,a=n.xhr();n.username?a.open(n.type,n.url,n.async,n.username,n.password):a.open(n.type,n.url,n.async);if(n.xhrFields)for(u in n.xhrFields)a[u]=n.xhrFields[u];n.mimeType&&a.overrideMimeType&&a.overrideMimeType(n.mimeType),!n.crossDomain&&!i["X-Requested-With"]&&(i["X-Requested-With"]="XMLHttpRequest");try{for(u in i)a.setRequestHeader(u,i[u])}catch(f){}a.send(n.hasContent&&n.data||null),r=function(e,i){var u,f,l,c,h;try{if(r&&(i||a.readyState===4)){r=t,o&&(a.onreadystatechange=v.noop,Bn&&delete Hn[o]);if(i)a.readyState!==4&&a.abort();else{u=a.status,l=a.getAllResponseHeaders(),c={},h=a.responseXML,h&&h.documentElement&&(c.xml=h);try{c.text=a.responseText}catch(p){}try{f=a.statusText}catch(p){f=""}!u&&n.isLocal&&!n.crossDomain?u=c.text?200:404:u===1223&&(u=204)}}}catch(d){i||s(-1,d)}c&&s(u,f,c,l)},n.async?a.readyState===4?setTimeout(r,0):(o=++jn,Bn&&(Hn||(Hn={},v(e).unload(Bn)),Hn[o]=r),a.onreadystatechange=r):r()},abort:function(){r&&r(0,1)}}}});var qn,Rn,Un=/^(?:toggle|show|hide)$/,zn=new RegExp("^(?:([-+])=|)("+m+")([a-z%]*)$","i"),Wn=/queueHooks$/,Xn=[Gn],Vn={"*":[function(e,t){var n,r,i=this.createTween(e,t),s=zn.exec(t),o=i.cur(),u=+o||0,a=1,f=20;if(s){n=+s[2],r=s[3]||(v.cssNumber[e]?"":"px");if(r!=="px"&&u){u=v.css(i.elem,e,!0)||n||1;do a=a||".5",u/=a,v.style(i.elem,e,u+r);while(a!==(a=i.cur()/o)&&a!==1&&--f)}i.unit=r,i.start=u,i.end=s[1]?u+(s[1]+1)*n:n}return i}]};v.Animation=v.extend(Kn,{tweener:function(e,t){v.isFunction(e)?(t=e,e=["*"]):e=e.split(" ");var n,r=0,i=e.length;for(;r-1,f={},l={},c,h;a?(l=i.position(),c=l.top,h=l.left):(c=parseFloat(o)||0,h=parseFloat(u)||0),v.isFunction(t)&&(t=t.call(e,n,s)),t.top!=null&&(f.top=t.top-s.top+c),t.left!=null&&(f.left=t.left-s.left+h),"using"in t?t.using.call(e,f):i.css(f)}},v.fn.extend({position:function(){if(!this[0])return;var e=this[0],t=this.offsetParent(),n=this.offset(),r=er.test(t[0].nodeName)?{top:0,left:0}:t.offset();return n.top-=parseFloat(v.css(e,"marginTop"))||0,n.left-=parseFloat(v.css(e,"marginLeft"))||0,r.top+=parseFloat(v.css(t[0],"borderTopWidth"))||0,r.left+=parseFloat(v.css(t[0],"borderLeftWidth"))||0,{top:n.top-r.top,left:n.left-r.left}},offsetParent:function(){return this.map(function(){var e=this.offsetParent||i.body;while(e&&!er.test(e.nodeName)&&v.css(e,"position")==="static")e=e.offsetParent;return e||i.body})}}),v.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(e,n){var r=/Y/.test(n);v.fn[e]=function(i){return v.access(this,function(e,i,s){var o=tr(e);if(s===t)return o?n in o?o[n]:o.document.documentElement[i]:e[i];o?o.scrollTo(r?v(o).scrollLeft():s,r?s:v(o).scrollTop()):e[i]=s},e,i,arguments.length,null)}}),v.each({Height:"height",Width:"width"},function(e,n){v.each({padding:"inner"+e,content:n,"":"outer"+e},function(r,i){v.fn[i]=function(i,s){var o=arguments.length&&(r||typeof i!="boolean"),u=r||(i===!0||s===!0?"margin":"border");return v.access(this,function(n,r,i){var s;return v.isWindow(n)?n.document.documentElement["client"+e]:n.nodeType===9?(s=n.documentElement,Math.max(n.body["scroll"+e],s["scroll"+e],n.body["offset"+e],s["offset"+e],s["client"+e])):i===t?v.css(n,r,i,u):v.style(n,r,i,u)},n,o?i:t,o,null)}})}),e.jQuery=e.$=v,typeof define=="function"&&define.amd&&define.amd.jQuery&&define("jquery",[],function(){return v})})(window); \ No newline at end of file diff --git a/Chapter08/02_create_album/static/content/mustache.js b/Chapter08/02_create_album/static/content/mustache.js new file mode 100644 index 0000000..0148d29 --- /dev/null +++ b/Chapter08/02_create_album/static/content/mustache.js @@ -0,0 +1,625 @@ +/*! + * mustache.js - Logic-less {{mustache}} templates with JavaScript + * http://github.com/janl/mustache.js + */ + +/*global define: false*/ + +var Mustache; + +(function (exports) { + if (typeof module !== "undefined" && module.exports) { + module.exports = exports; // CommonJS + } else if (typeof define === "function") { + define(exports); // AMD + } else { + Mustache = exports; // diff --git a/Chapter08/02_create_album/static/templates/admin_add_photos.html b/Chapter08/02_create_album/static/templates/admin_add_photos.html new file mode 100644 index 0000000..d9cbe8d --- /dev/null +++ b/Chapter08/02_create_album/static/templates/admin_add_photos.html @@ -0,0 +1,86 @@ +
+ +
+
Add to Album:
+
+ +
+
Image:
+
+
Description
+
+
+ + + + + +
+ + diff --git a/Chapter08/02_create_album/static/templates/admin_home.html b/Chapter08/02_create_album/static/templates/admin_home.html new file mode 100644 index 0000000..4db4cf1 --- /dev/null +++ b/Chapter08/02_create_album/static/templates/admin_home.html @@ -0,0 +1,7 @@ + +

Admin Operations

+ + diff --git a/Chapter08/02_create_album/static/templates/album.html b/Chapter08/02_create_album/static/templates/album.html new file mode 100644 index 0000000..520560a --- /dev/null +++ b/Chapter08/02_create_album/static/templates/album.html @@ -0,0 +1,19 @@ +
+ {{#has_photos}} +

There are {{ has_photos }} photos in this album

+ {{/has_photos}} + {{#photos}} +
+
+
+
+

{{ desc }}

+
+
+ {{/photos}} +
+ {{^photos}} +

This album does't have any photos in it, sorry.

+ {{/photos}} +

diff --git a/Chapter08/02_create_album/static/templates/home.html b/Chapter08/02_create_album/static/templates/home.html new file mode 100644 index 0000000..a7d1436 --- /dev/null +++ b/Chapter08/02_create_album/static/templates/home.html @@ -0,0 +1,16 @@ +
+ Admin +
+
+

There are {{ albums.length }} albums

+
    + {{#albums}} +
  • + {{name}} +
  • + {{/albums}} + {{^albums}} +
  • Sorry, there are currently no albums
  • + {{/albums}} +
+
diff --git a/Chapter08/0x_with_user_auth/app/basic.html b/Chapter08/0x_with_user_auth/app/basic.html new file mode 100644 index 0000000..0d966da --- /dev/null +++ b/Chapter08/0x_with_user_auth/app/basic.html @@ -0,0 +1,25 @@ + + + + Photo Album + + + + + + + + + + + + + + + + + diff --git a/Chapter08/0x_with_user_auth/app/data/album.js b/Chapter08/0x_with_user_auth/app/data/album.js new file mode 100644 index 0000000..f423c24 --- /dev/null +++ b/Chapter08/0x_with_user_auth/app/data/album.js @@ -0,0 +1,169 @@ + +var fs = require('fs'), + crypto = require("crypto"), + local = require('../local.config.js'), + db = require('./db.js'), + path = require("path"), + async = require('async'), + backhelp = require("./backend_helpers.js"); + +exports.version = "0.1.0"; + + +exports.create_album = function (data, callback) { + var final_album; + var write_succeeded = false; + async.waterfall([ + // validate data. + function (cb) { + try { + backhelp.verify(data, + [ "name", + "title", + "date", + "description" ]); + if (!backhelp.valid_filename(data.name)) + throw invalid_album_name(); + } catch (e) { + cb(e); + } + cb(null, data); + }, + + // create the album in mongo. + function (album_data, cb) { + var write = JSON.parse(JSON.stringify(album_data)); + write._id = album_data.name; + db.albums.insert(write, { w: 1, safe: true }, cb); + }, + + // make sure the folder exists. + function (new_album, cb) { + write_succeeded = true; + final_album = new_album[0]; + fs.mkdir(local.config.static_content + + "albums/" + data.name, cb); + } + ], + function (err, results) { + // convert file errors to something we like. + if (err) { + if (write_succeeded) + db.albums.remove({ _id: data.name }, function () {}); + + if (err instanceof Error && err.code == 11000) + callback(backhelp.album_already_exists()); + else if (err instanceof Error && err.errno != undefined) + callback(backhelp.file_error(err)); + else + callback(err); + } else { + callback(err, err ? null : final_album); + } + }); +}; + + +exports.album_by_name = function (name, callback) { + db.albums.find({ _id: name }).toArray(function (err, results) { + if (err) { + callback(err); + return; + } + + if (results.length == 0) { + callback(null, null); + } else if (results.length == 1) { + callback(null, results[0]); + } else { + console.error("More than one album named: " + name); + console.error(results); + callback(backutils.db_error()); + } + }); +}; + + +exports.photos_for_album = function (album_name, pn, ps, callback) { + var sort = { date: -1 }; + db.photos.find({ albumid: album_name }) + .skip(pn) + .limit(ps) + .sort("date") + .toArray(callback); +}; + + + +exports.all_albums = function (sort_field, sort_desc, skip, count, callback) { + var sort = {}; + sort[sort_field] = sort_desc ? -1 : 1; + db.albums.find() + .sort(sort) + .limit(count) + .skip(skip) + .toArray(callback); +}; + + + +exports.add_photo = function (photo_data, path_to_photo, callback) { + var final_photo; + var base_fn = path.basename(path_to_photo).toLowerCase(); + async.waterfall([ + // validate data + function (cb) { + try { + backhelp.verify(photo_data, + [ "albumid", + "description", + "date" ]); + + photo_data.filename = base_fn; + + if (!backhelp.valid_filename(photo_data.albumid)) + throw invalid_album_name(); + } catch (e) { + cb(e); + } + + cb(null, photo_data); + }, + + // add the photo to the collection + function (pd, cb) { + pd._id = pd.albumid + "_" + pd.filename; + db.photos.insert(pd, { w: 1, safe: true }, cb); + }, + + // now copy the temp file to static content + function (new_photo, cb) { + final_photo = new_photo[0]; + + var save_path = local.config.static_content + "albums/" + + photo_data.albumid + "/" + base_fn; + + backhelp.file_copy(path_to_photo, save_path, true, cb); + } + ], + function (err, results) { + // convert file errors to something we like. + if (err && err instanceof Error && err.errno != undefined) + callback(backhelp.file_error(err)); + else + callback(err, err ? null : final_photo); + }); + +}; + + + +function invalid_album_name() { + return backhelp.error("invalid_album_name", + "Album names can have letters, #s, _ and, -"); +} +function invalid_filename() { + return backhelp.error("invalid_filename", + "Filenames can have letters, #s, _ and, -"); +} + diff --git a/Chapter08/0x_with_user_auth/app/data/backend_helpers.js b/Chapter08/0x_with_user_auth/app/data/backend_helpers.js new file mode 100644 index 0000000..35991f6 --- /dev/null +++ b/Chapter08/0x_with_user_auth/app/data/backend_helpers.js @@ -0,0 +1,106 @@ + +var fs = require('fs'); + + +exports.verify = function (data, field_names) { + for (var i = 0; i < field_names.length; i++) { + if (!data[field_names[i]]) { + throw exports.error("missing_data", + field_names[i] + " not optional"); + } + } + + return true; +} + +exports.error = function (code, message) { + var e = new Error(message); + e.code = code; + return e; +}; + +exports.file_error = function (err) { + return exports.error("file_error", JSON.stringify(err.message)); +} + + + +/** + * Possible signatures: + * src, dst, callback + * src, dst, can_overwrite, callback + */ +exports.file_copy = function () { + + var src, dst, callback; + var can_overwrite = false; + + if (arguments.length == 3) { + src = arguments[0]; + dst = arguments[1]; + callback = arguments[2]; + } else if (arguments.length == 4) { + src = arguments[0]; + dst = arguments[1]; + callback = arguments[3]; + can_overwrite = arguments[2] + } + + function copy(err) { + var is, os; + + if (!err && !can_overwrite) { + return callback(backhelp.error("file_exists", + "File " + dst + " exists.")); + } + + fs.stat(src, function (err) { + if (err) { + return callback(err); + } + + is = fs.createReadStream(src); + os = fs.createWriteStream(dst); + is.on('end', function () { callback(null); }); + is.on('error', function (e) { callback(e); }); + is.pipe(os); + }); + } + + fs.stat(dst, copy); +}; + + + +exports.valid_filename = function (fn) { + var re = /[^\.a-zA-Z0-9_-]/; + return typeof fn == 'string' && fn.length > 0 && !(fn.match(re)); +}; + + +exports.db_error = function () { + return exports.error("server_error", + "Something horrible has happened with our database!"); +}; + +exports.album_already_exists = function () { + return exports.error("album_already_exists", + "An album with this name already exists."); +}; + +exports.missing_data = function (field) { + return exports.error("missing_data", "You must provide: " + field); +}; + +exports.no_such_user = function () { + return exports.error("no_such_user", + "The specified user does not exist"); +}; + + +exports.user_already_registered = function () { + return exports.error("user_already_registered", + "This user appears to exist already!"); +}; + + diff --git a/Chapter08/0x_with_user_auth/app/data/db.js b/Chapter08/0x_with_user_auth/app/data/db.js new file mode 100644 index 0000000..76749e2 --- /dev/null +++ b/Chapter08/0x_with_user_auth/app/data/db.js @@ -0,0 +1,63 @@ +var Db = require('mongodb').Db, + Connection = require('mongodb').Connection, + Server = require('mongodb').Server, + async = require('async'), + local = require("../local.config.js"); + +var host = local.config.db_config.host + ? local.config.db_config.host + : 'localhost'; +var port = local.config.db_config.port + ? local.config.db_config.port + : Connection.DEFAULT_PORT; +var ps = local.config.db_config.poolSize + ? local.config.db_config.poolSize : 5; + +var db = new Db('PhotoAlbums', + new Server(host, port, + { auto_reconnect: true, + poolSize: ps}), + { w: 1 }); + +/** + * Currently for initialisation, we just want to open + * the database. We won't even attempt to start up + * if this fails, as it's pretty pointless. + */ +exports.init = function (callback) { + async.waterfall([ + // 1. open database connection + function (cb) { + console.log("** 1. open db"); + db.open(cb); + }, + + // 2. create collections for our albums and photos. if + // they already exist, then we're good. + function (db_conn, cb) { + console.log("** 2. create albums and photos collections."); + db.collection("albums", cb); + }, + + function (albums_coll, cb) { + exports.albums = albums_coll; + db.collection("photos", cb); + }, + + function (photos_coll, cb) { + exports.photos = photos_coll; + db.collection("users", cb); + }, + + function (users_coll, cb) { + exports.users = users_coll; + cb(null); + } + ], callback); +}; + + +exports.albums = null; +exports.photos = null; +exports.users = null; + diff --git a/Chapter08/0x_with_user_auth/app/data/user.js b/Chapter08/0x_with_user_auth/app/data/user.js new file mode 100644 index 0000000..d3a80ab --- /dev/null +++ b/Chapter08/0x_with_user_auth/app/data/user.js @@ -0,0 +1,109 @@ + +var async = require('async'), + bcrypt = require('bcrypt'), + db = require("./db.js"), + uuid = require('node-uuid'), + backhelp = require("./backend_helpers.js"); + + +exports.version = "0.1.0"; + +exports.user_by_uuid = function (uuid, callback) { + if (!uuid) + callback(backhelp.missing_data("uuid")); + else + user_by_field("user_uuid", uuid, callback); +}; + +exports.user_by_display_name = function (dn, callback) { + if (!dn) + callback(backhelp.missing_data("display_name")); + else + user_by_field("display_name", dn, callback); +} + +exports.user_by_email_address = function (email, callback) { + if (!email) + callback(backhelp.missing_data("email")); + else + user_by_field("email_address", email, callback); +}; + + +exports.register = function (email, display_name, password, callback) { + async.waterfall([ + // validate ze params + function (cb) { + if (!email || email.indexOf("@") == -1) + cb(backhelp.missing_data("email")); + else if (!display_name) + cb(backhelp.missing_data("display_name")); + else if (!password) + cb(backhelp.missing_data("password")); + else + // generate a password hash + bcrypt.hash(password, 10, cb); + }, + + // create the album in mongo. + function (hash, cb) { + var userid = uuid(); + // email must be unique, so use it as id + var write = { + _id: email_address, + userid: userid, + email_address: email, + display_name: display_name, + password: hash, + first_seen_date: now_in_s(), + last_modified_date: now_in_s(), + deleted: false + }; + db.users.insert(write, { w: 1, safe: true }, cb); + }, + + // fetch and return the new user. + function (results, cb) { + cb(null, results[0]); + } + ], + function (err, user_data) { + if (err) { + if (err instanceof Error && err.code == 11000) + callback(backhelp.user_already_registered()); + else + callback (err); + } else { + callback(null, user_data); + } + }); +}; + + + +function user_by_field (field, value, callback) { + var o = {}; + o[field] = value; + + db.albums.find( o ).toArray(function (err, results) { + if (err) { + callback(err); + return; + } + if (results.length == 0) { + callback(null, null); + } else if (results.length == 1) { + callback(null, results[0]); + } else { + console.error("More than one user matching field: " + value); + console.error(results); + callback(backutils.db_error()); + } + }); +} + + +function now_in_s() { + return Math.round((new Date()).getTime() / 1000); +} + diff --git a/Chapter08/0x_with_user_auth/app/handlers/albums.js b/Chapter08/0x_with_user_auth/app/handlers/albums.js new file mode 100644 index 0000000..ac2da86 --- /dev/null +++ b/Chapter08/0x_with_user_auth/app/handlers/albums.js @@ -0,0 +1,259 @@ + +var helpers = require('./helpers.js'), + album_data = require("../data/album.js"), + async = require('async'), + fs = require('fs'); + +exports.version = "0.1.0"; + + +/** + * Album class. + */ +function Album (album_data) { + this.name = album_data.name; + this.date = album_data.date; + this.title = album_data.title; + this.description = album_data.description; + this._id = album_data._id; +} + +Album.prototype.name = null; +Album.prototype.date = null; +Album.prototype.title = null; +Album.prototype.description = null; + +Album.prototype.response_obj = function () { + return { name: this.name, + date: this.date, + title: this.title, + description: this.description }; +}; +Album.prototype.photos = function (pn, ps, callback) { + if (this.album_photos != undefined) { + callback(null, this.album_photos); + return; + } + + album_data.photos_for_album( + this.name, + pn, ps, + function (err, results) { + if (err) { + callback(err); + return; + } + + var out = []; + for (var i = 0; i < results.length; i++) { + out.push(new Photo(results[i])); + } + + this.album_photos = out; + callback(null, this.album_photos); + } + ); +}; +Album.prototype.add_photo = function (data, path, callback) { + album_data.add_photo(data, path, function (err, photo_data) { + if (err) + callback(err); + else { + var p = new Photo(photo_data); + if (this.all_photos) + this.all_photos.push(p); + else + this.app_photos = [ p ]; + + callback(null, p); + } + }); +}; + + + + +/** + * Photo class. + */ +function Photo (photo_data) { + this.filename = photo_data.filename; + this.date = photo_data.date; + this.albumid = photo_data.albumid; + this.description = photo_data.description; + this._id = photo_data._id; +} +Photo.prototype._id = null; +Photo.prototype.filename = null; +Photo.prototype.date = null; +Photo.prototype.albumid = null; +Photo.prototype.description = null; +Photo.prototype.response_obj = function() { + return { + filename: this.filename, + date: this.date, + albumid: this.albumid, + description: this.description + }; +}; + + +/** + * Album module methods. + */ +exports.create_album = function (req, res) { + async.waterfall([ + // make sure the albumid is valid + function (cb) { + if (!req.body || !req.body.name) { + cb(helpers.no_such_album()); + return; + } + + // UNDONE: we should add some code to make sure the album + // doesn't already exist! + cb(null); + }, + + function (cb) { + album_data.create_album(req.body, cb); + } + ], + function (err, results) { + if (err) { + helpers.send_failure(res, err); + } else { + var a = new Album(results); + helpers.send_success(res, {album: a.response_obj() }); + } + }); +}; + + +exports.album_by_name = function (req, res) { + async.waterfall([ + // get the album + function (cb) { + if (!req.params || !req.params.album_name) + cb(helpers.no_such_album()); + else + album_data.album_by_name(req.params.album_name, cb); + } + ], + function (err, results) { + if (err) { + helpers.send_failure(res, err); + } else if (!results) { + helpers.send_failure(res, helpers.no_such_album()); + } else { + var a = new Album(album_data); + helpers.send_success(res, { album: a.response_obj() }); + } + }); +}; + + + +exports.list_all = function (req, res) { + album_data.all_albums("date", true, 0, 25, function (err, results) { + if (err) { + helpers.send_failure(res, err); + } else { + var out = []; + if (results) { + for (var i = 0; i < results.length; i++) { + out.push(new Album(results[i]).response_obj()); + } + } + helpers.send_success(res, { albums: out }); + } + }); +}; + + +exports.photos_for_album = function(req, res) { + var page_num = req.query.page ? req.query.page : 0; + var page_size = req.query.page_size ? req.query.page_size : 1000; + + page_num = parseInt(page_num); + page_size = parseInt(page_size); + if (isNaN(page_num)) page_num = 0; + if (isNaN(page_size)) page_size = 1000; + + var album; + async.waterfall([ + function (cb) { + // first get the album. + if (!req.params || !req.params.album_name) + cb(helpers.no_such_album()); + else + album_data.album_by_name(req.params.album_name, cb); + }, + + function (album_data, cb) { + if (!album_data) { + cb(helpers.no_such_album()); + return; + } + album = new Album(album_data); + album.photos(page_num, page_size, cb); + }, + function (photos, cb) { + var out = []; + for (var i = 0; i < photos.length; i++) { + out.push(photos[i].response_obj()); + } + cb(null, out); + } + ], + function (err, results) { + if (err) { + helpers.send_failure(res, err); + return; + } + if (!results) results = []; + var out = { photos: results, + album_data: album.response_obj() }; + helpers.send_success(res, out); + }); +}; + + +exports.add_photo_to_album = function (req, res) { + var album; + async.waterfall([ + // make sure we have everything we need. + function (cb) { + if (!req.body) + cb(helpers.missing_data("POST data")); + else if (!req.files || !req.files.photo_file) + cb(helpers.missing_data("a file")); + else if (!helpers.is_image(req.files.photo_file.name)) + cb(helpers.not_image()); + else + // get the album + album_data.album_by_name(req.params.album_name, cb); + }, + + function (album_data, cb) { + if (!album_data) { + cb(helpers.no_such_album()); + return; + } + + album = new Album(album_data); + req.body.filename = req.files.photo_file.name; + album.add_photo(req.body, req.files.photo_file.path, cb); + } + ], + function (err, p) { + if (err) { + helpers.send_failure(res, err); + return; + } + var out = { photo: p.response_obj(), + album_data: album.response_obj() }; + helpers.send_success(res, out); + }); +}; + diff --git a/Chapter08/0x_with_user_auth/app/handlers/helpers.js b/Chapter08/0x_with_user_auth/app/handlers/helpers.js new file mode 100644 index 0000000..e6f0a13 --- /dev/null +++ b/Chapter08/0x_with_user_auth/app/handlers/helpers.js @@ -0,0 +1,114 @@ + +var path = require('path'); + + +exports.version = '0.1.0'; + + + + +exports.send_success = function(res, data) { + res.writeHead(200, {"Content-Type": "application/json"}); + var output = { error: null, data: data }; + res.end(JSON.stringify(output) + "\n"); +} + + +exports.send_failure = function(res, err) { + console.log(err); + var code = (err.code) ? err.code : err.name; + res.writeHead(code, { "Content-Type" : "application/json" }); + res.end(JSON.stringify({ error: code, message: err.message }) + "\n"); +} + + +exports.error_for_resp = function (err) { + if (!err instanceof Error) { + console.error("** Unexpected error type! :" + + err.constructor.name); + return JSON.stringify(err); + } else { + var code = err.code ? err.code : err.name; + return JSON.stringify({ error: code, + message: err.message }); + } +} + +exports.error = function (code, message) { + var e = new Error(message); + e.code = code; + return e; +}; + +exports.file_error = function (err) { + return exports.error("file_error", JSON.stringify(err)); +}; + + +exports.is_image = function (filename) { + switch (path.extname(filename).toLowerCase()) { + case '.jpg': case '.jpeg': case '.png': case '.bmp': + case '.gif': case '.tif': case '.tiff': + return true; + } + + return false; +}; + + +exports.invalid_resource = function () { + return exports.error("invalid_resource", + "The requested resource does not exist."); +}; + + +exports.missing_data = function (what) { + return exports.error("missing_data", + "You must include " + what); +} + + +exports.not_image = function () { + return exports.error("not_image_file", + "The uploaded file must be an image file."); +}; + + +exports.no_such_album = function () { + return exports.error("no_such_album", + "The specified album does not exist"); +}; + + +exports.http_code_for_error = function (err) { + switch (err.message) { + case "no_such_album": + return 403; + case "invalid_resource": + return 404; + case "invalid_email_address": + return 403; + case "no_such_user": + return 403; + } + + console.log("*** Error needs HTTP response code: " + err.message); + return 503; +} + + +exports.valid_filename = function (fn) { + var re = /[^\.a-zA-Z0-9_-]/; + return typeof fn == 'string' && fn.length > 0 && !(fn.match(re)); +}; + + +exports.invalid_email_address = function () { + return exports.error("invalid_email_address", + "That's not a valid email address, sorry"); +}; + +exports.auth_failed = function () { + return exports.error("auth_failure", + "Invalid email address / password combination."); +}; \ No newline at end of file diff --git a/Chapter08/0x_with_user_auth/app/handlers/pages.js b/Chapter08/0x_with_user_auth/app/handlers/pages.js new file mode 100644 index 0000000..3e9baae --- /dev/null +++ b/Chapter08/0x_with_user_auth/app/handlers/pages.js @@ -0,0 +1,42 @@ + +var helpers = require('./helpers.js'), + fs = require('fs'); + + +exports.version = "0.1.0"; + + +exports.generateAdmin = function (req, res) { + req.params.page_name = 'admin'; + exports.generate(req, res); +}; + +exports.generate = function (req, res) { + + var page = req.params.page_name; + if (req.params.sub_page && req.params.page_name == 'admin') + page = req.params.page_name + "_" + req.params.sub_page; + + fs.readFile( + 'basic.html', + function (err, contents) { + if (err) { + send_failure(res, 500, err); + return; + } + + contents = contents.toString('utf8'); + + // replace page name, and then dump to output. + contents = contents.replace('{{PAGE_NAME}}', page); + res.writeHead(200, { "Content-Type": "text/html" }); + res.end(contents); + } + ); +}; + +// if we made it here, then we're logged in. redirect to admin home +exports.login = function (req, res) { + res.redirect("/pages/admin/home"); + res.end(); +}; diff --git a/Chapter08/0x_with_user_auth/app/handlers/users.js b/Chapter08/0x_with_user_auth/app/handlers/users.js new file mode 100644 index 0000000..cfadfbb --- /dev/null +++ b/Chapter08/0x_with_user_auth/app/handlers/users.js @@ -0,0 +1,170 @@ +var helpers = require('./helpers.js'), + user_data = require("../data/user.js"), + async = require('async'), + bcrypt = require('bcrypt'), + fs = require('fs'); + +exports.version = "0.1.0"; + + +function User (user_data) { + this.uuid = user_data["user_uuid"]; + this.email_address = user_data["email_address"]; + this.display_name = user_data["display_name"]; + this.password = user_data["password"]; + this.first_seen_date = user_data["first_seen_date"]; + this.last_modified_date = user_data["last_modified_date"]; + this.deleted = user_data["deleted"]; +} + +User.prototype.uuid = null; +User.prototype.email_address = null; +User.prototype.display_name = null; +User.prototype.password = null; +User.prototype.first_seen_date = null; +User.prototype.last_modified_date = null; +User.prototype.deleted = false; +User.prototype.check_password = function (pw, callback) { + bcrypt.compare(pw, this.password, callback); +}; +User.prototype.response_obj = function () { + return { + uuid: this.uuid, + email_address: this.email_address, + display_name: this.display_name, + first_seen_date: this.first_seen_date, + last_modified_date: this.last_modified_date + }; +}; + + + +exports.register = function (req, res) { + async.waterfall([ + function (cb) { + var em = req.body.email_address; + if (!em || em.indexOf("@") == -1) + cb(helpers.invalid_email_address()); + else if (!req.body.display_name) + cb(helpers.missing_data("display_name")); + else if (!req.body.password) + cb(helpers.missing_data("password")); + else + cb(null); + }, + + // register da user. + function (cb) { + user_data.register( + req.body.email_address, + req.body.display_name, + req.body.password, + cb); + }, + + // mark user as logged in + function (user_data, cb) { + req.session.logged_in = true; + req.session.logged_in_display_name = req.body.display_name; + req.session.logged_in_date = new Date(); + cb(null, user_data); + } + ], + function (err, user_data) { + if (err) { + helpers.send_failure(res, err); + } else { + var u = new User(user_data); + helpers.send_success(res, {user: u.response_obj() }); + } + }); +}; + + +exports.login = function (req, res) { + var em = req.body.email_address + ? req.body.email_address.trim().toLowerCase() + : ""; + + async.waterfall([ + function (cb) { + if (!em) + cb(helpers.missing_data("email_address")); + else if (req.session + && req.session.logged_in_email_address == em) + cb(helpers.error("already_logged_in", "")); + else if (!req.body.password) + cb(helpers.missing_data("password")); + else + cb(null); + }, + + // first get the user by the email address. + function (cb) { + user_data.user_by_email_address(em, cb); + }, + + // check the password + function (user_data, cb) { + var u = new User(user_data); + u.check_password(req.body.password, cb); + }, + + function (auth_ok, cb) { + if (!auth_ok) { + cb(helpers.auth_failed()); + return; + } + + req.session.logged_in = true; + req.session.logged_in_email_address = req.body.email_address; + req.session.logged_in_date = new Date(); + cb(null); + } + ], + function (err, results) { + if (!err || err.message == "already_logged_in") { + helpers.send_success(res, { logged_in: true }); + } else { + helpers.send_failure(res, err); + } + }); +}; + + +exports.user_by_display_name = function (req, res) { + async.waterfall([ + // first get the user by the email address. + function (cb) { + user_data.user_by_display_name(req.body.email_address, cb); + } + ], + function (err, u) { + if (!err) { + helpers.send_success(res, { user: u.response_obj() }); + } else { + helpers.send_failure(res, err); + } + }); +}; + + +exports.authenticate_API = function (un, pw, callback) { + async.waterfall([ + function (cb) { + user_data.user_by_email_address(un, cb); + }, + + function (user_data, cb) { + var u = new User(user_data); + u.check_password(pw, cb); + } + ], + function (err, results) { + if (!err) { + callback(null, un); + } else { + callback(new Error("bogus credentials")); + } + }); +}; diff --git a/Chapter08/0x_with_user_auth/app/local.config.js b/Chapter08/0x_with_user_auth/app/local.config.js new file mode 100644 index 0000000..85e0a8d --- /dev/null +++ b/Chapter08/0x_with_user_auth/app/local.config.js @@ -0,0 +1,16 @@ + + +exports.config = { + db_config: { + host: "localhost", + user: "root", + password: "", + database: "PhotoAlbums", + + pooled_connections: 125, + idle_timeout_millis: 30000 + }, + + static_content: "../static/" +}; + diff --git a/Chapter08/0x_with_user_auth/app/package.json b/Chapter08/0x_with_user_auth/app/package.json new file mode 100644 index 0000000..b1a3a50 --- /dev/null +++ b/Chapter08/0x_with_user_auth/app/package.json @@ -0,0 +1,13 @@ +{ + "name": "Photo-Sharing", + "description": "Our Photo Sharing Application with static middleware", + "version": "0.0.2", + "private": true, + "dependencies": { + "express": "3.x", + "async": "0.1.x", + "mongodb": "1.2.x", + "bcrypt": "0.x", + "node-uuid": "1.x" + } +} diff --git a/Chapter08/0x_with_user_auth/app/server.js b/Chapter08/0x_with_user_auth/app/server.js new file mode 100644 index 0000000..beacbbc --- /dev/null +++ b/Chapter08/0x_with_user_auth/app/server.js @@ -0,0 +1,113 @@ + +var express = require('express'); +var app = express(); + +var db = require('./data/db.js'), + album_hdlr = require('./handlers/albums.js'), + page_hdlr = require('./handlers/pages.js'), + user_hdlr = require('./handlers/users.js'), + helpers = require('./handlers/helpers.js'); + +app.use(express.logger('dev')); +app.use(express.bodyParser({ keepExtensions: true })); +app.use(express.static(__dirname + "/../static")); +app.use(express.cookieParser("kitten on keyboard")); +app.use(express.cookieSession({ + secret: "FLUFFY BUNNIES", + maxAge: 86400000 +})); + +app.get('/v1/albums.json', album_hdlr.list_all); +app.get('/v1/albums/:album_name.json', album_hdlr.album_by_name); +app.put('/v1/albums.json', requireAPILogin, album_hdlr.create_album); + +app.get('/v1/albums/:album_name/photos.json', album_hdlr.photos_for_album); +app.put('/v1/albums/:album_name/photos.json', + requireAPILogin, album_hdlr.add_photo_to_album); + + +// add-on requests we support for the purposes of the web interface +// to the server. +app.get('/pages/admin/:sub_page', + requirePageLogin, page_hdlr.generateAdmin); +app.get('/pages/:page_name', page_hdlr.generate); +app.get('/pages/:page_name/:sub_page', page_hdlr.generate); +app.post('/service/login', user_hdlr.login); + +app.put('/v1/users.json', user_hdlr.register); +app.get('/v1/users/:display_name.json', user_hdlr.user_by_display_name); + + +app.get("/", function (req, res) { + res.redirect("/pages/home"); + res.end(); +}); + +app.get('*', four_oh_four); + +function four_oh_four(req, res) { + res.writeHead(404, { "Content-Type" : "application/json" }); + res.end(JSON.stringify(helpers.invalid_resource()) + "\n"); +} + + +function requireAPILogin(req, res, next) { + // if they're using the API from the browser, then they'll be auth'd + if (req.session && req.session.logged_in) { + next(); + return; + } + var rha = req.headers.authorization; + if (rha && rha.search('Basic ') === 0) { + var creds = new Buffer(rha.split(' ')[1], 'base64').toString(); + var parts = creds.split(":"); + user_hdlr.authenticate_API( + parts[0], + parts[1], + function (err, resp) { + if (!err && resp) { + next(); + } else + need_auth(req, res); + } + ); + } else + need_auth(req, res); +} + + +function requirePageLogin(req, res, next) { + if (req.session && req.session.logged_in) { + next(); + } else { + res.redirect("/pages/login"); + } +} + +function need_auth(req, res) { + res.header('WWW-Authenticate', + 'Basic realm="Authorization required"'); + if (req.headers.authorization) { + // no more than 1 failure / 5s + setTimeout(function () { + res.send('Authentication required\n', 401); + }, 5000); + } else { + res.send('Authentication required\n', 401); + } +} + + + +db.init(function (err, results) { + if (err) { + console.error("** FATAL ERROR ON STARTUP: "); + console.error(err); + process.exit(-1); + } + + console.log("Initialisation complete. Running Server."); + app.listen(8080); +}); + + diff --git a/Chapter08/0x_with_user_auth/static/albums/australia2010/aus_01.jpg b/Chapter08/0x_with_user_auth/static/albums/australia2010/aus_01.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter08/0x_with_user_auth/static/albums/australia2010/aus_02.jpg b/Chapter08/0x_with_user_auth/static/albums/australia2010/aus_02.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter08/0x_with_user_auth/static/albums/australia2010/aus_03.jpg b/Chapter08/0x_with_user_auth/static/albums/australia2010/aus_03.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter08/0x_with_user_auth/static/albums/australia2010/aus_04.jpg b/Chapter08/0x_with_user_auth/static/albums/australia2010/aus_04.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter08/0x_with_user_auth/static/albums/australia2010/aus_05.jpg b/Chapter08/0x_with_user_auth/static/albums/australia2010/aus_05.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter08/0x_with_user_auth/static/albums/australia2010/aus_06.jpg b/Chapter08/0x_with_user_auth/static/albums/australia2010/aus_06.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter08/0x_with_user_auth/static/albums/australia2010/aus_07.jpg b/Chapter08/0x_with_user_auth/static/albums/australia2010/aus_07.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter08/0x_with_user_auth/static/albums/australia2010/aus_08.jpg b/Chapter08/0x_with_user_auth/static/albums/australia2010/aus_08.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter08/0x_with_user_auth/static/albums/australia2010/aus_09.jpg b/Chapter08/0x_with_user_auth/static/albums/australia2010/aus_09.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter08/0x_with_user_auth/static/albums/italy2012/picture_01.jpg b/Chapter08/0x_with_user_auth/static/albums/italy2012/picture_01.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter08/0x_with_user_auth/static/albums/italy2012/picture_02.jpg b/Chapter08/0x_with_user_auth/static/albums/italy2012/picture_02.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter08/0x_with_user_auth/static/albums/italy2012/picture_03.jpg b/Chapter08/0x_with_user_auth/static/albums/italy2012/picture_03.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter08/0x_with_user_auth/static/albums/italy2012/picture_04.jpg b/Chapter08/0x_with_user_auth/static/albums/italy2012/picture_04.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter08/0x_with_user_auth/static/albums/italy2012/picture_05.jpg b/Chapter08/0x_with_user_auth/static/albums/italy2012/picture_05.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter08/0x_with_user_auth/static/albums/japan2010/picture_001.jpg b/Chapter08/0x_with_user_auth/static/albums/japan2010/picture_001.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter08/0x_with_user_auth/static/albums/japan2010/picture_002.jpg b/Chapter08/0x_with_user_auth/static/albums/japan2010/picture_002.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter08/0x_with_user_auth/static/albums/japan2010/picture_003.jpg b/Chapter08/0x_with_user_auth/static/albums/japan2010/picture_003.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter08/0x_with_user_auth/static/albums/japan2010/picture_004.jpg b/Chapter08/0x_with_user_auth/static/albums/japan2010/picture_004.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter08/0x_with_user_auth/static/albums/japan2010/picture_005.jpg b/Chapter08/0x_with_user_auth/static/albums/japan2010/picture_005.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter08/0x_with_user_auth/static/albums/japan2010/picture_006.jpg b/Chapter08/0x_with_user_auth/static/albums/japan2010/picture_006.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter08/0x_with_user_auth/static/albums/japan2010/picture_007.jpg b/Chapter08/0x_with_user_auth/static/albums/japan2010/picture_007.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter08/0x_with_user_auth/static/content/#album.js# b/Chapter08/0x_with_user_auth/static/content/#album.js# new file mode 100644 index 0000000..442c047 --- /dev/null +++ b/Chapter08/0x_with_user_auth/static/content/#album.js# @@ -0,0 +1,60 @@ +$(function(){ + + var tmpl, // Main template HTML + tdata = {}; // JSON data object that feeds the template + + // Initialise page + var initPage = function() { + + // get our album name. + var re = "/pages/album/([a-zA-Z0-9_-]+)"; + var results = new RegExp(re).exec(window.location.href); + var album_name = results[1]; + + // Load the HTML template + $.get("/templates/album.html", function(d){ + tmpl = d; + }); + + var p = $.urlParam("page"); + var ps = $.urlParam("page_size"); + if (p < 0) p = 0; + if (ps <= 0) ps = 1000; + + var qs = "?page=" + p + "&page_size=" + ps; + var url = "/v1/albums/" + album_name + "/photos.json" + qs; + + // Retrieve the server data and then initialise the page + $.getJSON(url, function (d) { + var photo_d = massage_album(d); + $.extend(tdata, photo_d); + }); + + // When AJAX calls are complete parse the template + // replacing mustache tags with vars + $(document).ajaxStop(function () { + var renderedPage = Mustache.to_html( tmpl, tdata ); + $("body").html( renderedPage ); + }) + }(); +}); + + +function massage_album(d) { + if (d.error != null) return d; + var obj = { photos: [] }; + + var p = d.data.photos; + var a = d.data.album_data; + + for (var i = 0; i < p.length; i++) { + var url = "/albums/" + a.name + "/" + p[i].filename; + obj.photos.push({ url: url, desc: p[i].description }); + } + + if (obj.photos.length > 0) obj.has_photos = obj.photos.length; + return obj; +} + + +xundo \ No newline at end of file diff --git a/Chapter08/0x_with_user_auth/static/content/admin_add_album.js b/Chapter08/0x_with_user_auth/static/content/admin_add_album.js new file mode 100644 index 0000000..f2987d6 --- /dev/null +++ b/Chapter08/0x_with_user_auth/static/content/admin_add_album.js @@ -0,0 +1,22 @@ +$(function(){ + + var tmpl, // Main template HTML + tdata = {}; // JSON data object that feeds the template + + // Initialise page + var initPage = function() { + + // Load the HTML template + $.get("/templates/admin_add_album.html", function(d){ + tmpl = d; + }); + + // When AJAX calls are complete parse the template + // replacing mustache tags with vars + $(document).ajaxStop(function () { + var renderedPage = Mustache.to_html( tmpl, tdata ); + $("body").html( renderedPage ); + }) + }(); +}); + diff --git a/Chapter08/0x_with_user_auth/static/content/admin_add_photos.js b/Chapter08/0x_with_user_auth/static/content/admin_add_photos.js new file mode 100644 index 0000000..350e536 --- /dev/null +++ b/Chapter08/0x_with_user_auth/static/content/admin_add_photos.js @@ -0,0 +1,27 @@ +$(function(){ + + var tmpl, // Main template HTML + tdata = {}; // JSON data object that feeds the template + + // Initialise page + var initPage = function() { + + // Load the HTML template + $.get("/templates/admin_add_photos.html", function(d){ + tmpl = d; + }); + + // Retrieve the server data and then initialise the page + $.getJSON("/v1/albums.json", function (d) { + $.extend(tdata, d.data); + }); + + // When AJAX calls are complete parse the template + // replacing mustache tags with vars + $(document).ajaxStop(function () { + var renderedPage = Mustache.to_html( tmpl, tdata ); + $("body").html( renderedPage ); + }) + }(); +}); + diff --git a/Chapter08/0x_with_user_auth/static/content/admin_home.js b/Chapter08/0x_with_user_auth/static/content/admin_home.js new file mode 100644 index 0000000..820f7fd --- /dev/null +++ b/Chapter08/0x_with_user_auth/static/content/admin_home.js @@ -0,0 +1,22 @@ +$(function(){ + + var tmpl, // Main template HTML + tdata = {}; // JSON data object that feeds the template + + // Initialise page + var initPage = function() { + + // Load the HTML template + $.get("/templates/admin_home.html", function(d){ + tmpl = d; + }); + + // When AJAX calls are complete parse the template + // replacing mustache tags with vars + $(document).ajaxStop(function () { + var renderedPage = Mustache.to_html( tmpl, tdata ); + $("body").html( renderedPage ); + }) + }(); +}); + diff --git a/Chapter08/0x_with_user_auth/static/content/album.js b/Chapter08/0x_with_user_auth/static/content/album.js new file mode 100644 index 0000000..c4d918e --- /dev/null +++ b/Chapter08/0x_with_user_auth/static/content/album.js @@ -0,0 +1,67 @@ +$(function(){ + + var tmpl, // Main template HTML + tdata = {}; // JSON data object that feeds the template + + // Initialise page + var initPage = function() { + + // get our album name. + var re = "/pages/album/([a-zA-Z0-9_-]+)"; + var results = new RegExp(re).exec(window.location.href); + var album_name = results[1]; + + // Load the HTML template + $.get("/templates/album.html", function(d){ + tmpl = d; + }); + + var p = $.urlParam("page"); + var ps = $.urlParam("page_size"); + if (p < 0) p = 0; + if (ps <= 0) ps = 1000; + + var qs = "?page=" + p + "&page_size=" + ps; + var url = "/v1/albums/" + album_name + "/photos.json" + qs; + + // Retrieve the server data and then initialise the page + $.getJSON(url, function (d) { + var photo_d = massage_album(d); + $.extend(tdata, photo_d); + }); + + // When AJAX calls are complete parse the template + // replacing mustache tags with vars + $(document).ajaxStop(function () { + var renderedPage = Mustache.to_html( tmpl, tdata ); + $("body").html( renderedPage ); + }) + }(); +}); + + +function massage_album(d) { + if (d.error != null) return d; + var obj = { photos: [] }; + + var p = d.data.photos; + var a = d.data.album_data; + + for (var i = 0; i < p.length; i++) { + var url = "/albums/" + a.name + "/" + p[i].filename; + obj.photos.push({ url: url, desc: p[i].description }); + } + + if (obj.photos.length > 0) obj.has_photos = obj.photos.length; + return obj; +} + + +$.urlParam = function(name){ + var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href); + if (!results) + { + return 0; + } + return results[1] || 0; +} \ No newline at end of file diff --git a/Chapter08/0x_with_user_auth/static/content/home.js b/Chapter08/0x_with_user_auth/static/content/home.js new file mode 100644 index 0000000..fa7010b --- /dev/null +++ b/Chapter08/0x_with_user_auth/static/content/home.js @@ -0,0 +1,28 @@ +$(function(){ + + var tmpl, // Main template HTML + tdata = {}; // JSON data object that feeds the template + + // Initialise page + var initPage = function() { + + // Load the HTML template + $.get("/templates/home.html", function(d){ + tmpl = d; + }); + + + // Retrieve the server data and then initialise the page + $.getJSON("/v1/albums.json", function (d) { + $.extend(tdata, d.data); + }); + + // When AJAX calls are complete parse the template + // replacing mustache tags with vars + $(document).ajaxStop(function () { + var renderedPage = Mustache.to_html( tmpl, tdata ); + $("body").html( renderedPage ); + }) + }(); +}); + diff --git a/Chapter08/0x_with_user_auth/static/content/jquery-1.8.3.min.js b/Chapter08/0x_with_user_auth/static/content/jquery-1.8.3.min.js new file mode 100644 index 0000000..83589da --- /dev/null +++ b/Chapter08/0x_with_user_auth/static/content/jquery-1.8.3.min.js @@ -0,0 +1,2 @@ +/*! jQuery v1.8.3 jquery.com | jquery.org/license */ +(function(e,t){function _(e){var t=M[e]={};return v.each(e.split(y),function(e,n){t[n]=!0}),t}function H(e,n,r){if(r===t&&e.nodeType===1){var i="data-"+n.replace(P,"-$1").toLowerCase();r=e.getAttribute(i);if(typeof r=="string"){try{r=r==="true"?!0:r==="false"?!1:r==="null"?null:+r+""===r?+r:D.test(r)?v.parseJSON(r):r}catch(s){}v.data(e,n,r)}else r=t}return r}function B(e){var t;for(t in e){if(t==="data"&&v.isEmptyObject(e[t]))continue;if(t!=="toJSON")return!1}return!0}function et(){return!1}function tt(){return!0}function ut(e){return!e||!e.parentNode||e.parentNode.nodeType===11}function at(e,t){do e=e[t];while(e&&e.nodeType!==1);return e}function ft(e,t,n){t=t||0;if(v.isFunction(t))return v.grep(e,function(e,r){var i=!!t.call(e,r,e);return i===n});if(t.nodeType)return v.grep(e,function(e,r){return e===t===n});if(typeof t=="string"){var r=v.grep(e,function(e){return e.nodeType===1});if(it.test(t))return v.filter(t,r,!n);t=v.filter(t,r)}return v.grep(e,function(e,r){return v.inArray(e,t)>=0===n})}function lt(e){var t=ct.split("|"),n=e.createDocumentFragment();if(n.createElement)while(t.length)n.createElement(t.pop());return n}function Lt(e,t){return e.getElementsByTagName(t)[0]||e.appendChild(e.ownerDocument.createElement(t))}function At(e,t){if(t.nodeType!==1||!v.hasData(e))return;var n,r,i,s=v._data(e),o=v._data(t,s),u=s.events;if(u){delete o.handle,o.events={};for(n in u)for(r=0,i=u[n].length;r").appendTo(i.body),n=t.css("display");t.remove();if(n==="none"||n===""){Pt=i.body.appendChild(Pt||v.extend(i.createElement("iframe"),{frameBorder:0,width:0,height:0}));if(!Ht||!Pt.createElement)Ht=(Pt.contentWindow||Pt.contentDocument).document,Ht.write(""),Ht.close();t=Ht.body.appendChild(Ht.createElement(e)),n=Dt(t,"display"),i.body.removeChild(Pt)}return Wt[e]=n,n}function fn(e,t,n,r){var i;if(v.isArray(t))v.each(t,function(t,i){n||sn.test(e)?r(e,i):fn(e+"["+(typeof i=="object"?t:"")+"]",i,n,r)});else if(!n&&v.type(t)==="object")for(i in t)fn(e+"["+i+"]",t[i],n,r);else r(e,t)}function Cn(e){return function(t,n){typeof t!="string"&&(n=t,t="*");var r,i,s,o=t.toLowerCase().split(y),u=0,a=o.length;if(v.isFunction(n))for(;u)[^>]*$|#([\w\-]*)$)/,E=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,S=/^[\],:{}\s]*$/,x=/(?:^|:|,)(?:\s*\[)+/g,T=/\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,N=/"[^"\\\r\n]*"|true|false|null|-?(?:\d\d*\.|)\d+(?:[eE][\-+]?\d+|)/g,C=/^-ms-/,k=/-([\da-z])/gi,L=function(e,t){return(t+"").toUpperCase()},A=function(){i.addEventListener?(i.removeEventListener("DOMContentLoaded",A,!1),v.ready()):i.readyState==="complete"&&(i.detachEvent("onreadystatechange",A),v.ready())},O={};v.fn=v.prototype={constructor:v,init:function(e,n,r){var s,o,u,a;if(!e)return this;if(e.nodeType)return this.context=this[0]=e,this.length=1,this;if(typeof e=="string"){e.charAt(0)==="<"&&e.charAt(e.length-1)===">"&&e.length>=3?s=[null,e,null]:s=w.exec(e);if(s&&(s[1]||!n)){if(s[1])return n=n instanceof v?n[0]:n,a=n&&n.nodeType?n.ownerDocument||n:i,e=v.parseHTML(s[1],a,!0),E.test(s[1])&&v.isPlainObject(n)&&this.attr.call(e,n,!0),v.merge(this,e);o=i.getElementById(s[2]);if(o&&o.parentNode){if(o.id!==s[2])return r.find(e);this.length=1,this[0]=o}return this.context=i,this.selector=e,this}return!n||n.jquery?(n||r).find(e):this.constructor(n).find(e)}return v.isFunction(e)?r.ready(e):(e.selector!==t&&(this.selector=e.selector,this.context=e.context),v.makeArray(e,this))},selector:"",jquery:"1.8.3",length:0,size:function(){return this.length},toArray:function(){return l.call(this)},get:function(e){return e==null?this.toArray():e<0?this[this.length+e]:this[e]},pushStack:function(e,t,n){var r=v.merge(this.constructor(),e);return r.prevObject=this,r.context=this.context,t==="find"?r.selector=this.selector+(this.selector?" ":"")+n:t&&(r.selector=this.selector+"."+t+"("+n+")"),r},each:function(e,t){return v.each(this,e,t)},ready:function(e){return v.ready.promise().done(e),this},eq:function(e){return e=+e,e===-1?this.slice(e):this.slice(e,e+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(l.apply(this,arguments),"slice",l.call(arguments).join(","))},map:function(e){return this.pushStack(v.map(this,function(t,n){return e.call(t,n,t)}))},end:function(){return this.prevObject||this.constructor(null)},push:f,sort:[].sort,splice:[].splice},v.fn.init.prototype=v.fn,v.extend=v.fn.extend=function(){var e,n,r,i,s,o,u=arguments[0]||{},a=1,f=arguments.length,l=!1;typeof u=="boolean"&&(l=u,u=arguments[1]||{},a=2),typeof u!="object"&&!v.isFunction(u)&&(u={}),f===a&&(u=this,--a);for(;a0)return;r.resolveWith(i,[v]),v.fn.trigger&&v(i).trigger("ready").off("ready")},isFunction:function(e){return v.type(e)==="function"},isArray:Array.isArray||function(e){return v.type(e)==="array"},isWindow:function(e){return e!=null&&e==e.window},isNumeric:function(e){return!isNaN(parseFloat(e))&&isFinite(e)},type:function(e){return e==null?String(e):O[h.call(e)]||"object"},isPlainObject:function(e){if(!e||v.type(e)!=="object"||e.nodeType||v.isWindow(e))return!1;try{if(e.constructor&&!p.call(e,"constructor")&&!p.call(e.constructor.prototype,"isPrototypeOf"))return!1}catch(n){return!1}var r;for(r in e);return r===t||p.call(e,r)},isEmptyObject:function(e){var t;for(t in e)return!1;return!0},error:function(e){throw new Error(e)},parseHTML:function(e,t,n){var r;return!e||typeof e!="string"?null:(typeof t=="boolean"&&(n=t,t=0),t=t||i,(r=E.exec(e))?[t.createElement(r[1])]:(r=v.buildFragment([e],t,n?null:[]),v.merge([],(r.cacheable?v.clone(r.fragment):r.fragment).childNodes)))},parseJSON:function(t){if(!t||typeof t!="string")return null;t=v.trim(t);if(e.JSON&&e.JSON.parse)return e.JSON.parse(t);if(S.test(t.replace(T,"@").replace(N,"]").replace(x,"")))return(new Function("return "+t))();v.error("Invalid JSON: "+t)},parseXML:function(n){var r,i;if(!n||typeof n!="string")return null;try{e.DOMParser?(i=new DOMParser,r=i.parseFromString(n,"text/xml")):(r=new ActiveXObject("Microsoft.XMLDOM"),r.async="false",r.loadXML(n))}catch(s){r=t}return(!r||!r.documentElement||r.getElementsByTagName("parsererror").length)&&v.error("Invalid XML: "+n),r},noop:function(){},globalEval:function(t){t&&g.test(t)&&(e.execScript||function(t){e.eval.call(e,t)})(t)},camelCase:function(e){return e.replace(C,"ms-").replace(k,L)},nodeName:function(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()},each:function(e,n,r){var i,s=0,o=e.length,u=o===t||v.isFunction(e);if(r){if(u){for(i in e)if(n.apply(e[i],r)===!1)break}else for(;s0&&e[0]&&e[a-1]||a===0||v.isArray(e));if(f)for(;u-1)a.splice(n,1),i&&(n<=o&&o--,n<=u&&u--)}),this},has:function(e){return v.inArray(e,a)>-1},empty:function(){return a=[],this},disable:function(){return a=f=n=t,this},disabled:function(){return!a},lock:function(){return f=t,n||c.disable(),this},locked:function(){return!f},fireWith:function(e,t){return t=t||[],t=[e,t.slice?t.slice():t],a&&(!r||f)&&(i?f.push(t):l(t)),this},fire:function(){return c.fireWith(this,arguments),this},fired:function(){return!!r}};return c},v.extend({Deferred:function(e){var t=[["resolve","done",v.Callbacks("once memory"),"resolved"],["reject","fail",v.Callbacks("once memory"),"rejected"],["notify","progress",v.Callbacks("memory")]],n="pending",r={state:function(){return n},always:function(){return i.done(arguments).fail(arguments),this},then:function(){var e=arguments;return v.Deferred(function(n){v.each(t,function(t,r){var s=r[0],o=e[t];i[r[1]](v.isFunction(o)?function(){var e=o.apply(this,arguments);e&&v.isFunction(e.promise)?e.promise().done(n.resolve).fail(n.reject).progress(n.notify):n[s+"With"](this===i?n:this,[e])}:n[s])}),e=null}).promise()},promise:function(e){return e!=null?v.extend(e,r):r}},i={};return r.pipe=r.then,v.each(t,function(e,s){var o=s[2],u=s[3];r[s[1]]=o.add,u&&o.add(function(){n=u},t[e^1][2].disable,t[2][2].lock),i[s[0]]=o.fire,i[s[0]+"With"]=o.fireWith}),r.promise(i),e&&e.call(i,i),i},when:function(e){var t=0,n=l.call(arguments),r=n.length,i=r!==1||e&&v.isFunction(e.promise)?r:0,s=i===1?e:v.Deferred(),o=function(e,t,n){return function(r){t[e]=this,n[e]=arguments.length>1?l.call(arguments):r,n===u?s.notifyWith(t,n):--i||s.resolveWith(t,n)}},u,a,f;if(r>1){u=new Array(r),a=new Array(r),f=new Array(r);for(;t
a",n=p.getElementsByTagName("*"),r=p.getElementsByTagName("a")[0];if(!n||!r||!n.length)return{};s=i.createElement("select"),o=s.appendChild(i.createElement("option")),u=p.getElementsByTagName("input")[0],r.style.cssText="top:1px;float:left;opacity:.5",t={leadingWhitespace:p.firstChild.nodeType===3,tbody:!p.getElementsByTagName("tbody").length,htmlSerialize:!!p.getElementsByTagName("link").length,style:/top/.test(r.getAttribute("style")),hrefNormalized:r.getAttribute("href")==="/a",opacity:/^0.5/.test(r.style.opacity),cssFloat:!!r.style.cssFloat,checkOn:u.value==="on",optSelected:o.selected,getSetAttribute:p.className!=="t",enctype:!!i.createElement("form").enctype,html5Clone:i.createElement("nav").cloneNode(!0).outerHTML!=="<:nav>",boxModel:i.compatMode==="CSS1Compat",submitBubbles:!0,changeBubbles:!0,focusinBubbles:!1,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0,boxSizingReliable:!0,pixelPosition:!1},u.checked=!0,t.noCloneChecked=u.cloneNode(!0).checked,s.disabled=!0,t.optDisabled=!o.disabled;try{delete p.test}catch(d){t.deleteExpando=!1}!p.addEventListener&&p.attachEvent&&p.fireEvent&&(p.attachEvent("onclick",h=function(){t.noCloneEvent=!1}),p.cloneNode(!0).fireEvent("onclick"),p.detachEvent("onclick",h)),u=i.createElement("input"),u.value="t",u.setAttribute("type","radio"),t.radioValue=u.value==="t",u.setAttribute("checked","checked"),u.setAttribute("name","t"),p.appendChild(u),a=i.createDocumentFragment(),a.appendChild(p.lastChild),t.checkClone=a.cloneNode(!0).cloneNode(!0).lastChild.checked,t.appendChecked=u.checked,a.removeChild(u),a.appendChild(p);if(p.attachEvent)for(l in{submit:!0,change:!0,focusin:!0})f="on"+l,c=f in p,c||(p.setAttribute(f,"return;"),c=typeof p[f]=="function"),t[l+"Bubbles"]=c;return v(function(){var n,r,s,o,u="padding:0;margin:0;border:0;display:block;overflow:hidden;",a=i.getElementsByTagName("body")[0];if(!a)return;n=i.createElement("div"),n.style.cssText="visibility:hidden;border:0;width:0;height:0;position:static;top:0;margin-top:1px",a.insertBefore(n,a.firstChild),r=i.createElement("div"),n.appendChild(r),r.innerHTML="
t
",s=r.getElementsByTagName("td"),s[0].style.cssText="padding:0;margin:0;border:0;display:none",c=s[0].offsetHeight===0,s[0].style.display="",s[1].style.display="none",t.reliableHiddenOffsets=c&&s[0].offsetHeight===0,r.innerHTML="",r.style.cssText="box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;",t.boxSizing=r.offsetWidth===4,t.doesNotIncludeMarginInBodyOffset=a.offsetTop!==1,e.getComputedStyle&&(t.pixelPosition=(e.getComputedStyle(r,null)||{}).top!=="1%",t.boxSizingReliable=(e.getComputedStyle(r,null)||{width:"4px"}).width==="4px",o=i.createElement("div"),o.style.cssText=r.style.cssText=u,o.style.marginRight=o.style.width="0",r.style.width="1px",r.appendChild(o),t.reliableMarginRight=!parseFloat((e.getComputedStyle(o,null)||{}).marginRight)),typeof r.style.zoom!="undefined"&&(r.innerHTML="",r.style.cssText=u+"width:1px;padding:1px;display:inline;zoom:1",t.inlineBlockNeedsLayout=r.offsetWidth===3,r.style.display="block",r.style.overflow="visible",r.innerHTML="
",r.firstChild.style.width="5px",t.shrinkWrapBlocks=r.offsetWidth!==3,n.style.zoom=1),a.removeChild(n),n=r=s=o=null}),a.removeChild(p),n=r=s=o=u=a=p=null,t}();var D=/(?:\{[\s\S]*\}|\[[\s\S]*\])$/,P=/([A-Z])/g;v.extend({cache:{},deletedIds:[],uuid:0,expando:"jQuery"+(v.fn.jquery+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(e){return e=e.nodeType?v.cache[e[v.expando]]:e[v.expando],!!e&&!B(e)},data:function(e,n,r,i){if(!v.acceptData(e))return;var s,o,u=v.expando,a=typeof n=="string",f=e.nodeType,l=f?v.cache:e,c=f?e[u]:e[u]&&u;if((!c||!l[c]||!i&&!l[c].data)&&a&&r===t)return;c||(f?e[u]=c=v.deletedIds.pop()||v.guid++:c=u),l[c]||(l[c]={},f||(l[c].toJSON=v.noop));if(typeof n=="object"||typeof n=="function")i?l[c]=v.extend(l[c],n):l[c].data=v.extend(l[c].data,n);return s=l[c],i||(s.data||(s.data={}),s=s.data),r!==t&&(s[v.camelCase(n)]=r),a?(o=s[n],o==null&&(o=s[v.camelCase(n)])):o=s,o},removeData:function(e,t,n){if(!v.acceptData(e))return;var r,i,s,o=e.nodeType,u=o?v.cache:e,a=o?e[v.expando]:v.expando;if(!u[a])return;if(t){r=n?u[a]:u[a].data;if(r){v.isArray(t)||(t in r?t=[t]:(t=v.camelCase(t),t in r?t=[t]:t=t.split(" ")));for(i=0,s=t.length;i1,null,!1))},removeData:function(e){return this.each(function(){v.removeData(this,e)})}}),v.extend({queue:function(e,t,n){var r;if(e)return t=(t||"fx")+"queue",r=v._data(e,t),n&&(!r||v.isArray(n)?r=v._data(e,t,v.makeArray(n)):r.push(n)),r||[]},dequeue:function(e,t){t=t||"fx";var n=v.queue(e,t),r=n.length,i=n.shift(),s=v._queueHooks(e,t),o=function(){v.dequeue(e,t)};i==="inprogress"&&(i=n.shift(),r--),i&&(t==="fx"&&n.unshift("inprogress"),delete s.stop,i.call(e,o,s)),!r&&s&&s.empty.fire()},_queueHooks:function(e,t){var n=t+"queueHooks";return v._data(e,n)||v._data(e,n,{empty:v.Callbacks("once memory").add(function(){v.removeData(e,t+"queue",!0),v.removeData(e,n,!0)})})}}),v.fn.extend({queue:function(e,n){var r=2;return typeof e!="string"&&(n=e,e="fx",r--),arguments.length1)},removeAttr:function(e){return this.each(function(){v.removeAttr(this,e)})},prop:function(e,t){return v.access(this,v.prop,e,t,arguments.length>1)},removeProp:function(e){return e=v.propFix[e]||e,this.each(function(){try{this[e]=t,delete this[e]}catch(n){}})},addClass:function(e){var t,n,r,i,s,o,u;if(v.isFunction(e))return this.each(function(t){v(this).addClass(e.call(this,t,this.className))});if(e&&typeof e=="string"){t=e.split(y);for(n=0,r=this.length;n=0)r=r.replace(" "+n[s]+" "," ");i.className=e?v.trim(r):""}}}return this},toggleClass:function(e,t){var n=typeof e,r=typeof t=="boolean";return v.isFunction(e)?this.each(function(n){v(this).toggleClass(e.call(this,n,this.className,t),t)}):this.each(function(){if(n==="string"){var i,s=0,o=v(this),u=t,a=e.split(y);while(i=a[s++])u=r?u:!o.hasClass(i),o[u?"addClass":"removeClass"](i)}else if(n==="undefined"||n==="boolean")this.className&&v._data(this,"__className__",this.className),this.className=this.className||e===!1?"":v._data(this,"__className__")||""})},hasClass:function(e){var t=" "+e+" ",n=0,r=this.length;for(;n=0)return!0;return!1},val:function(e){var n,r,i,s=this[0];if(!arguments.length){if(s)return n=v.valHooks[s.type]||v.valHooks[s.nodeName.toLowerCase()],n&&"get"in n&&(r=n.get(s,"value"))!==t?r:(r=s.value,typeof r=="string"?r.replace(R,""):r==null?"":r);return}return i=v.isFunction(e),this.each(function(r){var s,o=v(this);if(this.nodeType!==1)return;i?s=e.call(this,r,o.val()):s=e,s==null?s="":typeof s=="number"?s+="":v.isArray(s)&&(s=v.map(s,function(e){return e==null?"":e+""})),n=v.valHooks[this.type]||v.valHooks[this.nodeName.toLowerCase()];if(!n||!("set"in n)||n.set(this,s,"value")===t)this.value=s})}}),v.extend({valHooks:{option:{get:function(e){var t=e.attributes.value;return!t||t.specified?e.value:e.text}},select:{get:function(e){var t,n,r=e.options,i=e.selectedIndex,s=e.type==="select-one"||i<0,o=s?null:[],u=s?i+1:r.length,a=i<0?u:s?i:0;for(;a=0}),n.length||(e.selectedIndex=-1),n}}},attrFn:{},attr:function(e,n,r,i){var s,o,u,a=e.nodeType;if(!e||a===3||a===8||a===2)return;if(i&&v.isFunction(v.fn[n]))return v(e)[n](r);if(typeof e.getAttribute=="undefined")return v.prop(e,n,r);u=a!==1||!v.isXMLDoc(e),u&&(n=n.toLowerCase(),o=v.attrHooks[n]||(X.test(n)?F:j));if(r!==t){if(r===null){v.removeAttr(e,n);return}return o&&"set"in o&&u&&(s=o.set(e,r,n))!==t?s:(e.setAttribute(n,r+""),r)}return o&&"get"in o&&u&&(s=o.get(e,n))!==null?s:(s=e.getAttribute(n),s===null?t:s)},removeAttr:function(e,t){var n,r,i,s,o=0;if(t&&e.nodeType===1){r=t.split(y);for(;o=0}})});var $=/^(?:textarea|input|select)$/i,J=/^([^\.]*|)(?:\.(.+)|)$/,K=/(?:^|\s)hover(\.\S+|)\b/,Q=/^key/,G=/^(?:mouse|contextmenu)|click/,Y=/^(?:focusinfocus|focusoutblur)$/,Z=function(e){return v.event.special.hover?e:e.replace(K,"mouseenter$1 mouseleave$1")};v.event={add:function(e,n,r,i,s){var o,u,a,f,l,c,h,p,d,m,g;if(e.nodeType===3||e.nodeType===8||!n||!r||!(o=v._data(e)))return;r.handler&&(d=r,r=d.handler,s=d.selector),r.guid||(r.guid=v.guid++),a=o.events,a||(o.events=a={}),u=o.handle,u||(o.handle=u=function(e){return typeof v=="undefined"||!!e&&v.event.triggered===e.type?t:v.event.dispatch.apply(u.elem,arguments)},u.elem=e),n=v.trim(Z(n)).split(" ");for(f=0;f=0&&(y=y.slice(0,-1),a=!0),y.indexOf(".")>=0&&(b=y.split("."),y=b.shift(),b.sort());if((!s||v.event.customEvent[y])&&!v.event.global[y])return;n=typeof n=="object"?n[v.expando]?n:new v.Event(y,n):new v.Event(y),n.type=y,n.isTrigger=!0,n.exclusive=a,n.namespace=b.join("."),n.namespace_re=n.namespace?new RegExp("(^|\\.)"+b.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,h=y.indexOf(":")<0?"on"+y:"";if(!s){u=v.cache;for(f in u)u[f].events&&u[f].events[y]&&v.event.trigger(n,r,u[f].handle.elem,!0);return}n.result=t,n.target||(n.target=s),r=r!=null?v.makeArray(r):[],r.unshift(n),p=v.event.special[y]||{};if(p.trigger&&p.trigger.apply(s,r)===!1)return;m=[[s,p.bindType||y]];if(!o&&!p.noBubble&&!v.isWindow(s)){g=p.delegateType||y,l=Y.test(g+y)?s:s.parentNode;for(c=s;l;l=l.parentNode)m.push([l,g]),c=l;c===(s.ownerDocument||i)&&m.push([c.defaultView||c.parentWindow||e,g])}for(f=0;f=0:v.find(h,this,null,[s]).length),u[h]&&f.push(c);f.length&&w.push({elem:s,matches:f})}d.length>m&&w.push({elem:this,matches:d.slice(m)});for(r=0;r0?this.on(t,null,e,n):this.trigger(t)},Q.test(t)&&(v.event.fixHooks[t]=v.event.keyHooks),G.test(t)&&(v.event.fixHooks[t]=v.event.mouseHooks)}),function(e,t){function nt(e,t,n,r){n=n||[],t=t||g;var i,s,a,f,l=t.nodeType;if(!e||typeof e!="string")return n;if(l!==1&&l!==9)return[];a=o(t);if(!a&&!r)if(i=R.exec(e))if(f=i[1]){if(l===9){s=t.getElementById(f);if(!s||!s.parentNode)return n;if(s.id===f)return n.push(s),n}else if(t.ownerDocument&&(s=t.ownerDocument.getElementById(f))&&u(t,s)&&s.id===f)return n.push(s),n}else{if(i[2])return S.apply(n,x.call(t.getElementsByTagName(e),0)),n;if((f=i[3])&&Z&&t.getElementsByClassName)return S.apply(n,x.call(t.getElementsByClassName(f),0)),n}return vt(e.replace(j,"$1"),t,n,r,a)}function rt(e){return function(t){var n=t.nodeName.toLowerCase();return n==="input"&&t.type===e}}function it(e){return function(t){var n=t.nodeName.toLowerCase();return(n==="input"||n==="button")&&t.type===e}}function st(e){return N(function(t){return t=+t,N(function(n,r){var i,s=e([],n.length,t),o=s.length;while(o--)n[i=s[o]]&&(n[i]=!(r[i]=n[i]))})})}function ot(e,t,n){if(e===t)return n;var r=e.nextSibling;while(r){if(r===t)return-1;r=r.nextSibling}return 1}function ut(e,t){var n,r,s,o,u,a,f,l=L[d][e+" "];if(l)return t?0:l.slice(0);u=e,a=[],f=i.preFilter;while(u){if(!n||(r=F.exec(u)))r&&(u=u.slice(r[0].length)||u),a.push(s=[]);n=!1;if(r=I.exec(u))s.push(n=new m(r.shift())),u=u.slice(n.length),n.type=r[0].replace(j," ");for(o in i.filter)(r=J[o].exec(u))&&(!f[o]||(r=f[o](r)))&&(s.push(n=new m(r.shift())),u=u.slice(n.length),n.type=o,n.matches=r);if(!n)break}return t?u.length:u?nt.error(e):L(e,a).slice(0)}function at(e,t,r){var i=t.dir,s=r&&t.dir==="parentNode",o=w++;return t.first?function(t,n,r){while(t=t[i])if(s||t.nodeType===1)return e(t,n,r)}:function(t,r,u){if(!u){var a,f=b+" "+o+" ",l=f+n;while(t=t[i])if(s||t.nodeType===1){if((a=t[d])===l)return t.sizset;if(typeof a=="string"&&a.indexOf(f)===0){if(t.sizset)return t}else{t[d]=l;if(e(t,r,u))return t.sizset=!0,t;t.sizset=!1}}}else while(t=t[i])if(s||t.nodeType===1)if(e(t,r,u))return t}}function ft(e){return e.length>1?function(t,n,r){var i=e.length;while(i--)if(!e[i](t,n,r))return!1;return!0}:e[0]}function lt(e,t,n,r,i){var s,o=[],u=0,a=e.length,f=t!=null;for(;u-1&&(s[f]=!(o[f]=c))}}else g=lt(g===o?g.splice(d,g.length):g),i?i(null,o,g,a):S.apply(o,g)})}function ht(e){var t,n,r,s=e.length,o=i.relative[e[0].type],u=o||i.relative[" "],a=o?1:0,f=at(function(e){return e===t},u,!0),l=at(function(e){return T.call(t,e)>-1},u,!0),h=[function(e,n,r){return!o&&(r||n!==c)||((t=n).nodeType?f(e,n,r):l(e,n,r))}];for(;a1&&ft(h),a>1&&e.slice(0,a-1).join("").replace(j,"$1"),n,a0,s=e.length>0,o=function(u,a,f,l,h){var p,d,v,m=[],y=0,w="0",x=u&&[],T=h!=null,N=c,C=u||s&&i.find.TAG("*",h&&a.parentNode||a),k=b+=N==null?1:Math.E;T&&(c=a!==g&&a,n=o.el);for(;(p=C[w])!=null;w++){if(s&&p){for(d=0;v=e[d];d++)if(v(p,a,f)){l.push(p);break}T&&(b=k,n=++o.el)}r&&((p=!v&&p)&&y--,u&&x.push(p))}y+=w;if(r&&w!==y){for(d=0;v=t[d];d++)v(x,m,a,f);if(u){if(y>0)while(w--)!x[w]&&!m[w]&&(m[w]=E.call(l));m=lt(m)}S.apply(l,m),T&&!u&&m.length>0&&y+t.length>1&&nt.uniqueSort(l)}return T&&(b=k,c=N),x};return o.el=0,r?N(o):o}function dt(e,t,n){var r=0,i=t.length;for(;r2&&(f=u[0]).type==="ID"&&t.nodeType===9&&!s&&i.relative[u[1].type]){t=i.find.ID(f.matches[0].replace($,""),t,s)[0];if(!t)return n;e=e.slice(u.shift().length)}for(o=J.POS.test(e)?-1:u.length-1;o>=0;o--){f=u[o];if(i.relative[l=f.type])break;if(c=i.find[l])if(r=c(f.matches[0].replace($,""),z.test(u[0].type)&&t.parentNode||t,s)){u.splice(o,1),e=r.length&&u.join("");if(!e)return S.apply(n,x.call(r,0)),n;break}}}return a(e,h)(r,t,s,n,z.test(e)),n}function mt(){}var n,r,i,s,o,u,a,f,l,c,h=!0,p="undefined",d=("sizcache"+Math.random()).replace(".",""),m=String,g=e.document,y=g.documentElement,b=0,w=0,E=[].pop,S=[].push,x=[].slice,T=[].indexOf||function(e){var t=0,n=this.length;for(;ti.cacheLength&&delete e[t.shift()],e[n+" "]=r},e)},k=C(),L=C(),A=C(),O="[\\x20\\t\\r\\n\\f]",M="(?:\\\\.|[-\\w]|[^\\x00-\\xa0])+",_=M.replace("w","w#"),D="([*^$|!~]?=)",P="\\["+O+"*("+M+")"+O+"*(?:"+D+O+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+_+")|)|)"+O+"*\\]",H=":("+M+")(?:\\((?:(['\"])((?:\\\\.|[^\\\\])*?)\\2|([^()[\\]]*|(?:(?:"+P+")|[^:]|\\\\.)*|.*))\\)|)",B=":(even|odd|eq|gt|lt|nth|first|last)(?:\\("+O+"*((?:-\\d)?\\d*)"+O+"*\\)|)(?=[^-]|$)",j=new RegExp("^"+O+"+|((?:^|[^\\\\])(?:\\\\.)*)"+O+"+$","g"),F=new RegExp("^"+O+"*,"+O+"*"),I=new RegExp("^"+O+"*([\\x20\\t\\r\\n\\f>+~])"+O+"*"),q=new RegExp(H),R=/^(?:#([\w\-]+)|(\w+)|\.([\w\-]+))$/,U=/^:not/,z=/[\x20\t\r\n\f]*[+~]/,W=/:not\($/,X=/h\d/i,V=/input|select|textarea|button/i,$=/\\(?!\\)/g,J={ID:new RegExp("^#("+M+")"),CLASS:new RegExp("^\\.("+M+")"),NAME:new RegExp("^\\[name=['\"]?("+M+")['\"]?\\]"),TAG:new RegExp("^("+M.replace("w","w*")+")"),ATTR:new RegExp("^"+P),PSEUDO:new RegExp("^"+H),POS:new RegExp(B,"i"),CHILD:new RegExp("^:(only|nth|first|last)-child(?:\\("+O+"*(even|odd|(([+-]|)(\\d*)n|)"+O+"*(?:([+-]|)"+O+"*(\\d+)|))"+O+"*\\)|)","i"),needsContext:new RegExp("^"+O+"*[>+~]|"+B,"i")},K=function(e){var t=g.createElement("div");try{return e(t)}catch(n){return!1}finally{t=null}},Q=K(function(e){return e.appendChild(g.createComment("")),!e.getElementsByTagName("*").length}),G=K(function(e){return e.innerHTML="",e.firstChild&&typeof e.firstChild.getAttribute!==p&&e.firstChild.getAttribute("href")==="#"}),Y=K(function(e){e.innerHTML="";var t=typeof e.lastChild.getAttribute("multiple");return t!=="boolean"&&t!=="string"}),Z=K(function(e){return e.innerHTML="",!e.getElementsByClassName||!e.getElementsByClassName("e").length?!1:(e.lastChild.className="e",e.getElementsByClassName("e").length===2)}),et=K(function(e){e.id=d+0,e.innerHTML="
",y.insertBefore(e,y.firstChild);var t=g.getElementsByName&&g.getElementsByName(d).length===2+g.getElementsByName(d+0).length;return r=!g.getElementById(d),y.removeChild(e),t});try{x.call(y.childNodes,0)[0].nodeType}catch(tt){x=function(e){var t,n=[];for(;t=this[e];e++)n.push(t);return n}}nt.matches=function(e,t){return nt(e,null,null,t)},nt.matchesSelector=function(e,t){return nt(t,null,null,[e]).length>0},s=nt.getText=function(e){var t,n="",r=0,i=e.nodeType;if(i){if(i===1||i===9||i===11){if(typeof e.textContent=="string")return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=s(e)}else if(i===3||i===4)return e.nodeValue}else for(;t=e[r];r++)n+=s(t);return n},o=nt.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return t?t.nodeName!=="HTML":!1},u=nt.contains=y.contains?function(e,t){var n=e.nodeType===9?e.documentElement:e,r=t&&t.parentNode;return e===r||!!(r&&r.nodeType===1&&n.contains&&n.contains(r))}:y.compareDocumentPosition?function(e,t){return t&&!!(e.compareDocumentPosition(t)&16)}:function(e,t){while(t=t.parentNode)if(t===e)return!0;return!1},nt.attr=function(e,t){var n,r=o(e);return r||(t=t.toLowerCase()),(n=i.attrHandle[t])?n(e):r||Y?e.getAttribute(t):(n=e.getAttributeNode(t),n?typeof e[t]=="boolean"?e[t]?t:null:n.specified?n.value:null:null)},i=nt.selectors={cacheLength:50,createPseudo:N,match:J,attrHandle:G?{}:{href:function(e){return e.getAttribute("href",2)},type:function(e){return e.getAttribute("type")}},find:{ID:r?function(e,t,n){if(typeof t.getElementById!==p&&!n){var r=t.getElementById(e);return r&&r.parentNode?[r]:[]}}:function(e,n,r){if(typeof n.getElementById!==p&&!r){var i=n.getElementById(e);return i?i.id===e||typeof i.getAttributeNode!==p&&i.getAttributeNode("id").value===e?[i]:t:[]}},TAG:Q?function(e,t){if(typeof t.getElementsByTagName!==p)return t.getElementsByTagName(e)}:function(e,t){var n=t.getElementsByTagName(e);if(e==="*"){var r,i=[],s=0;for(;r=n[s];s++)r.nodeType===1&&i.push(r);return i}return n},NAME:et&&function(e,t){if(typeof t.getElementsByName!==p)return t.getElementsByName(name)},CLASS:Z&&function(e,t,n){if(typeof t.getElementsByClassName!==p&&!n)return t.getElementsByClassName(e)}},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace($,""),e[3]=(e[4]||e[5]||"").replace($,""),e[2]==="~="&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),e[1]==="nth"?(e[2]||nt.error(e[0]),e[3]=+(e[3]?e[4]+(e[5]||1):2*(e[2]==="even"||e[2]==="odd")),e[4]=+(e[6]+e[7]||e[2]==="odd")):e[2]&&nt.error(e[0]),e},PSEUDO:function(e){var t,n;if(J.CHILD.test(e[0]))return null;if(e[3])e[2]=e[3];else if(t=e[4])q.test(t)&&(n=ut(t,!0))&&(n=t.indexOf(")",t.length-n)-t.length)&&(t=t.slice(0,n),e[0]=e[0].slice(0,n)),e[2]=t;return e.slice(0,3)}},filter:{ID:r?function(e){return e=e.replace($,""),function(t){return t.getAttribute("id")===e}}:function(e){return e=e.replace($,""),function(t){var n=typeof t.getAttributeNode!==p&&t.getAttributeNode("id");return n&&n.value===e}},TAG:function(e){return e==="*"?function(){return!0}:(e=e.replace($,"").toLowerCase(),function(t){return t.nodeName&&t.nodeName.toLowerCase()===e})},CLASS:function(e){var t=k[d][e+" "];return t||(t=new RegExp("(^|"+O+")"+e+"("+O+"|$)"))&&k(e,function(e){return t.test(e.className||typeof e.getAttribute!==p&&e.getAttribute("class")||"")})},ATTR:function(e,t,n){return function(r,i){var s=nt.attr(r,e);return s==null?t==="!=":t?(s+="",t==="="?s===n:t==="!="?s!==n:t==="^="?n&&s.indexOf(n)===0:t==="*="?n&&s.indexOf(n)>-1:t==="$="?n&&s.substr(s.length-n.length)===n:t==="~="?(" "+s+" ").indexOf(n)>-1:t==="|="?s===n||s.substr(0,n.length+1)===n+"-":!1):!0}},CHILD:function(e,t,n,r){return e==="nth"?function(e){var t,i,s=e.parentNode;if(n===1&&r===0)return!0;if(s){i=0;for(t=s.firstChild;t;t=t.nextSibling)if(t.nodeType===1){i++;if(e===t)break}}return i-=r,i===n||i%n===0&&i/n>=0}:function(t){var n=t;switch(e){case"only":case"first":while(n=n.previousSibling)if(n.nodeType===1)return!1;if(e==="first")return!0;n=t;case"last":while(n=n.nextSibling)if(n.nodeType===1)return!1;return!0}}},PSEUDO:function(e,t){var n,r=i.pseudos[e]||i.setFilters[e.toLowerCase()]||nt.error("unsupported pseudo: "+e);return r[d]?r(t):r.length>1?(n=[e,e,"",t],i.setFilters.hasOwnProperty(e.toLowerCase())?N(function(e,n){var i,s=r(e,t),o=s.length;while(o--)i=T.call(e,s[o]),e[i]=!(n[i]=s[o])}):function(e){return r(e,0,n)}):r}},pseudos:{not:N(function(e){var t=[],n=[],r=a(e.replace(j,"$1"));return r[d]?N(function(e,t,n,i){var s,o=r(e,null,i,[]),u=e.length;while(u--)if(s=o[u])e[u]=!(t[u]=s)}):function(e,i,s){return t[0]=e,r(t,null,s,n),!n.pop()}}),has:N(function(e){return function(t){return nt(e,t).length>0}}),contains:N(function(e){return function(t){return(t.textContent||t.innerText||s(t)).indexOf(e)>-1}}),enabled:function(e){return e.disabled===!1},disabled:function(e){return e.disabled===!0},checked:function(e){var t=e.nodeName.toLowerCase();return t==="input"&&!!e.checked||t==="option"&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,e.selected===!0},parent:function(e){return!i.pseudos.empty(e)},empty:function(e){var t;e=e.firstChild;while(e){if(e.nodeName>"@"||(t=e.nodeType)===3||t===4)return!1;e=e.nextSibling}return!0},header:function(e){return X.test(e.nodeName)},text:function(e){var t,n;return e.nodeName.toLowerCase()==="input"&&(t=e.type)==="text"&&((n=e.getAttribute("type"))==null||n.toLowerCase()===t)},radio:rt("radio"),checkbox:rt("checkbox"),file:rt("file"),password:rt("password"),image:rt("image"),submit:it("submit"),reset:it("reset"),button:function(e){var t=e.nodeName.toLowerCase();return t==="input"&&e.type==="button"||t==="button"},input:function(e){return V.test(e.nodeName)},focus:function(e){var t=e.ownerDocument;return e===t.activeElement&&(!t.hasFocus||t.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},active:function(e){return e===e.ownerDocument.activeElement},first:st(function(){return[0]}),last:st(function(e,t){return[t-1]}),eq:st(function(e,t,n){return[n<0?n+t:n]}),even:st(function(e,t){for(var n=0;n=0;)e.push(r);return e}),gt:st(function(e,t,n){for(var r=n<0?n+t:n;++r",e.querySelectorAll("[selected]").length||i.push("\\["+O+"*(?:checked|disabled|ismap|multiple|readonly|selected|value)"),e.querySelectorAll(":checked").length||i.push(":checked")}),K(function(e){e.innerHTML="

",e.querySelectorAll("[test^='']").length&&i.push("[*^$]="+O+"*(?:\"\"|'')"),e.innerHTML="",e.querySelectorAll(":enabled").length||i.push(":enabled",":disabled")}),i=new RegExp(i.join("|")),vt=function(e,r,s,o,u){if(!o&&!u&&!i.test(e)){var a,f,l=!0,c=d,h=r,p=r.nodeType===9&&e;if(r.nodeType===1&&r.nodeName.toLowerCase()!=="object"){a=ut(e),(l=r.getAttribute("id"))?c=l.replace(n,"\\$&"):r.setAttribute("id",c),c="[id='"+c+"'] ",f=a.length;while(f--)a[f]=c+a[f].join("");h=z.test(e)&&r.parentNode||r,p=a.join(",")}if(p)try{return S.apply(s,x.call(h.querySelectorAll(p),0)),s}catch(v){}finally{l||r.removeAttribute("id")}}return t(e,r,s,o,u)},u&&(K(function(t){e=u.call(t,"div");try{u.call(t,"[test!='']:sizzle"),s.push("!=",H)}catch(n){}}),s=new RegExp(s.join("|")),nt.matchesSelector=function(t,n){n=n.replace(r,"='$1']");if(!o(t)&&!s.test(n)&&!i.test(n))try{var a=u.call(t,n);if(a||e||t.document&&t.document.nodeType!==11)return a}catch(f){}return nt(n,null,null,[t]).length>0})}(),i.pseudos.nth=i.pseudos.eq,i.filters=mt.prototype=i.pseudos,i.setFilters=new mt,nt.attr=v.attr,v.find=nt,v.expr=nt.selectors,v.expr[":"]=v.expr.pseudos,v.unique=nt.uniqueSort,v.text=nt.getText,v.isXMLDoc=nt.isXML,v.contains=nt.contains}(e);var nt=/Until$/,rt=/^(?:parents|prev(?:Until|All))/,it=/^.[^:#\[\.,]*$/,st=v.expr.match.needsContext,ot={children:!0,contents:!0,next:!0,prev:!0};v.fn.extend({find:function(e){var t,n,r,i,s,o,u=this;if(typeof e!="string")return v(e).filter(function(){for(t=0,n=u.length;t0)for(i=r;i=0:v.filter(e,this).length>0:this.filter(e).length>0)},closest:function(e,t){var n,r=0,i=this.length,s=[],o=st.test(e)||typeof e!="string"?v(e,t||this.context):0;for(;r-1:v.find.matchesSelector(n,e)){s.push(n);break}n=n.parentNode}}return s=s.length>1?v.unique(s):s,this.pushStack(s,"closest",e)},index:function(e){return e?typeof e=="string"?v.inArray(this[0],v(e)):v.inArray(e.jquery?e[0]:e,this):this[0]&&this[0].parentNode?this.prevAll().length:-1},add:function(e,t){var n=typeof e=="string"?v(e,t):v.makeArray(e&&e.nodeType?[e]:e),r=v.merge(this.get(),n);return this.pushStack(ut(n[0])||ut(r[0])?r:v.unique(r))},addBack:function(e){return this.add(e==null?this.prevObject:this.prevObject.filter(e))}}),v.fn.andSelf=v.fn.addBack,v.each({parent:function(e){var t=e.parentNode;return t&&t.nodeType!==11?t:null},parents:function(e){return v.dir(e,"parentNode")},parentsUntil:function(e,t,n){return v.dir(e,"parentNode",n)},next:function(e){return at(e,"nextSibling")},prev:function(e){return at(e,"previousSibling")},nextAll:function(e){return v.dir(e,"nextSibling")},prevAll:function(e){return v.dir(e,"previousSibling")},nextUntil:function(e,t,n){return v.dir(e,"nextSibling",n)},prevUntil:function(e,t,n){return v.dir(e,"previousSibling",n)},siblings:function(e){return v.sibling((e.parentNode||{}).firstChild,e)},children:function(e){return v.sibling(e.firstChild)},contents:function(e){return v.nodeName(e,"iframe")?e.contentDocument||e.contentWindow.document:v.merge([],e.childNodes)}},function(e,t){v.fn[e]=function(n,r){var i=v.map(this,t,n);return nt.test(e)||(r=n),r&&typeof r=="string"&&(i=v.filter(r,i)),i=this.length>1&&!ot[e]?v.unique(i):i,this.length>1&&rt.test(e)&&(i=i.reverse()),this.pushStack(i,e,l.call(arguments).join(","))}}),v.extend({filter:function(e,t,n){return n&&(e=":not("+e+")"),t.length===1?v.find.matchesSelector(t[0],e)?[t[0]]:[]:v.find.matches(e,t)},dir:function(e,n,r){var i=[],s=e[n];while(s&&s.nodeType!==9&&(r===t||s.nodeType!==1||!v(s).is(r)))s.nodeType===1&&i.push(s),s=s[n];return i},sibling:function(e,t){var n=[];for(;e;e=e.nextSibling)e.nodeType===1&&e!==t&&n.push(e);return n}});var ct="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",ht=/ jQuery\d+="(?:null|\d+)"/g,pt=/^\s+/,dt=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,vt=/<([\w:]+)/,mt=/]","i"),Et=/^(?:checkbox|radio)$/,St=/checked\s*(?:[^=]|=\s*.checked.)/i,xt=/\/(java|ecma)script/i,Tt=/^\s*\s*$/g,Nt={option:[1,""],legend:[1,"
","
"],thead:[1,"","
"],tr:[2,"","
"],td:[3,"","
"],col:[2,"","
"],area:[1,"",""],_default:[0,"",""]},Ct=lt(i),kt=Ct.appendChild(i.createElement("div"));Nt.optgroup=Nt.option,Nt.tbody=Nt.tfoot=Nt.colgroup=Nt.caption=Nt.thead,Nt.th=Nt.td,v.support.htmlSerialize||(Nt._default=[1,"X
","
"]),v.fn.extend({text:function(e){return v.access(this,function(e){return e===t?v.text(this):this.empty().append((this[0]&&this[0].ownerDocument||i).createTextNode(e))},null,e,arguments.length)},wrapAll:function(e){if(v.isFunction(e))return this.each(function(t){v(this).wrapAll(e.call(this,t))});if(this[0]){var t=v(e,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&t.insertBefore(this[0]),t.map(function(){var e=this;while(e.firstChild&&e.firstChild.nodeType===1)e=e.firstChild;return e}).append(this)}return this},wrapInner:function(e){return v.isFunction(e)?this.each(function(t){v(this).wrapInner(e.call(this,t))}):this.each(function(){var t=v(this),n=t.contents();n.length?n.wrapAll(e):t.append(e)})},wrap:function(e){var t=v.isFunction(e);return this.each(function(n){v(this).wrapAll(t?e.call(this,n):e)})},unwrap:function(){return this.parent().each(function(){v.nodeName(this,"body")||v(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(e){(this.nodeType===1||this.nodeType===11)&&this.appendChild(e)})},prepend:function(){return this.domManip(arguments,!0,function(e){(this.nodeType===1||this.nodeType===11)&&this.insertBefore(e,this.firstChild)})},before:function(){if(!ut(this[0]))return this.domManip(arguments,!1,function(e){this.parentNode.insertBefore(e,this)});if(arguments.length){var e=v.clean(arguments);return this.pushStack(v.merge(e,this),"before",this.selector)}},after:function(){if(!ut(this[0]))return this.domManip(arguments,!1,function(e){this.parentNode.insertBefore(e,this.nextSibling)});if(arguments.length){var e=v.clean(arguments);return this.pushStack(v.merge(this,e),"after",this.selector)}},remove:function(e,t){var n,r=0;for(;(n=this[r])!=null;r++)if(!e||v.filter(e,[n]).length)!t&&n.nodeType===1&&(v.cleanData(n.getElementsByTagName("*")),v.cleanData([n])),n.parentNode&&n.parentNode.removeChild(n);return this},empty:function(){var e,t=0;for(;(e=this[t])!=null;t++){e.nodeType===1&&v.cleanData(e.getElementsByTagName("*"));while(e.firstChild)e.removeChild(e.firstChild)}return this},clone:function(e,t){return e=e==null?!1:e,t=t==null?e:t,this.map(function(){return v.clone(this,e,t)})},html:function(e){return v.access(this,function(e){var n=this[0]||{},r=0,i=this.length;if(e===t)return n.nodeType===1?n.innerHTML.replace(ht,""):t;if(typeof e=="string"&&!yt.test(e)&&(v.support.htmlSerialize||!wt.test(e))&&(v.support.leadingWhitespace||!pt.test(e))&&!Nt[(vt.exec(e)||["",""])[1].toLowerCase()]){e=e.replace(dt,"<$1>");try{for(;r1&&typeof f=="string"&&St.test(f))return this.each(function(){v(this).domManip(e,n,r)});if(v.isFunction(f))return this.each(function(i){var s=v(this);e[0]=f.call(this,i,n?s.html():t),s.domManip(e,n,r)});if(this[0]){i=v.buildFragment(e,this,l),o=i.fragment,s=o.firstChild,o.childNodes.length===1&&(o=s);if(s){n=n&&v.nodeName(s,"tr");for(u=i.cacheable||c-1;a0?this.clone(!0):this).get(),v(o[i])[t](r),s=s.concat(r);return this.pushStack(s,e,o.selector)}}),v.extend({clone:function(e,t,n){var r,i,s,o;v.support.html5Clone||v.isXMLDoc(e)||!wt.test("<"+e.nodeName+">")?o=e.cloneNode(!0):(kt.innerHTML=e.outerHTML,kt.removeChild(o=kt.firstChild));if((!v.support.noCloneEvent||!v.support.noCloneChecked)&&(e.nodeType===1||e.nodeType===11)&&!v.isXMLDoc(e)){Ot(e,o),r=Mt(e),i=Mt(o);for(s=0;r[s];++s)i[s]&&Ot(r[s],i[s])}if(t){At(e,o);if(n){r=Mt(e),i=Mt(o);for(s=0;r[s];++s)At(r[s],i[s])}}return r=i=null,o},clean:function(e,t,n,r){var s,o,u,a,f,l,c,h,p,d,m,g,y=t===i&&Ct,b=[];if(!t||typeof t.createDocumentFragment=="undefined")t=i;for(s=0;(u=e[s])!=null;s++){typeof u=="number"&&(u+="");if(!u)continue;if(typeof u=="string")if(!gt.test(u))u=t.createTextNode(u);else{y=y||lt(t),c=t.createElement("div"),y.appendChild(c),u=u.replace(dt,"<$1>"),a=(vt.exec(u)||["",""])[1].toLowerCase(),f=Nt[a]||Nt._default,l=f[0],c.innerHTML=f[1]+u+f[2];while(l--)c=c.lastChild;if(!v.support.tbody){h=mt.test(u),p=a==="table"&&!h?c.firstChild&&c.firstChild.childNodes:f[1]===""&&!h?c.childNodes:[];for(o=p.length-1;o>=0;--o)v.nodeName(p[o],"tbody")&&!p[o].childNodes.length&&p[o].parentNode.removeChild(p[o])}!v.support.leadingWhitespace&&pt.test(u)&&c.insertBefore(t.createTextNode(pt.exec(u)[0]),c.firstChild),u=c.childNodes,c.parentNode.removeChild(c)}u.nodeType?b.push(u):v.merge(b,u)}c&&(u=c=y=null);if(!v.support.appendChecked)for(s=0;(u=b[s])!=null;s++)v.nodeName(u,"input")?_t(u):typeof u.getElementsByTagName!="undefined"&&v.grep(u.getElementsByTagName("input"),_t);if(n){m=function(e){if(!e.type||xt.test(e.type))return r?r.push(e.parentNode?e.parentNode.removeChild(e):e):n.appendChild(e)};for(s=0;(u=b[s])!=null;s++)if(!v.nodeName(u,"script")||!m(u))n.appendChild(u),typeof u.getElementsByTagName!="undefined"&&(g=v.grep(v.merge([],u.getElementsByTagName("script")),m),b.splice.apply(b,[s+1,0].concat(g)),s+=g.length)}return b},cleanData:function(e,t){var n,r,i,s,o=0,u=v.expando,a=v.cache,f=v.support.deleteExpando,l=v.event.special;for(;(i=e[o])!=null;o++)if(t||v.acceptData(i)){r=i[u],n=r&&a[r];if(n){if(n.events)for(s in n.events)l[s]?v.event.remove(i,s):v.removeEvent(i,s,n.handle);a[r]&&(delete a[r],f?delete i[u]:i.removeAttribute?i.removeAttribute(u):i[u]=null,v.deletedIds.push(r))}}}}),function(){var e,t;v.uaMatch=function(e){e=e.toLowerCase();var t=/(chrome)[ \/]([\w.]+)/.exec(e)||/(webkit)[ \/]([\w.]+)/.exec(e)||/(opera)(?:.*version|)[ \/]([\w.]+)/.exec(e)||/(msie) ([\w.]+)/.exec(e)||e.indexOf("compatible")<0&&/(mozilla)(?:.*? rv:([\w.]+)|)/.exec(e)||[];return{browser:t[1]||"",version:t[2]||"0"}},e=v.uaMatch(o.userAgent),t={},e.browser&&(t[e.browser]=!0,t.version=e.version),t.chrome?t.webkit=!0:t.webkit&&(t.safari=!0),v.browser=t,v.sub=function(){function e(t,n){return new e.fn.init(t,n)}v.extend(!0,e,this),e.superclass=this,e.fn=e.prototype=this(),e.fn.constructor=e,e.sub=this.sub,e.fn.init=function(r,i){return i&&i instanceof v&&!(i instanceof e)&&(i=e(i)),v.fn.init.call(this,r,i,t)},e.fn.init.prototype=e.fn;var t=e(i);return e}}();var Dt,Pt,Ht,Bt=/alpha\([^)]*\)/i,jt=/opacity=([^)]*)/,Ft=/^(top|right|bottom|left)$/,It=/^(none|table(?!-c[ea]).+)/,qt=/^margin/,Rt=new RegExp("^("+m+")(.*)$","i"),Ut=new RegExp("^("+m+")(?!px)[a-z%]+$","i"),zt=new RegExp("^([-+])=("+m+")","i"),Wt={BODY:"block"},Xt={position:"absolute",visibility:"hidden",display:"block"},Vt={letterSpacing:0,fontWeight:400},$t=["Top","Right","Bottom","Left"],Jt=["Webkit","O","Moz","ms"],Kt=v.fn.toggle;v.fn.extend({css:function(e,n){return v.access(this,function(e,n,r){return r!==t?v.style(e,n,r):v.css(e,n)},e,n,arguments.length>1)},show:function(){return Yt(this,!0)},hide:function(){return Yt(this)},toggle:function(e,t){var n=typeof e=="boolean";return v.isFunction(e)&&v.isFunction(t)?Kt.apply(this,arguments):this.each(function(){(n?e:Gt(this))?v(this).show():v(this).hide()})}}),v.extend({cssHooks:{opacity:{get:function(e,t){if(t){var n=Dt(e,"opacity");return n===""?"1":n}}}},cssNumber:{fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":v.support.cssFloat?"cssFloat":"styleFloat"},style:function(e,n,r,i){if(!e||e.nodeType===3||e.nodeType===8||!e.style)return;var s,o,u,a=v.camelCase(n),f=e.style;n=v.cssProps[a]||(v.cssProps[a]=Qt(f,a)),u=v.cssHooks[n]||v.cssHooks[a];if(r===t)return u&&"get"in u&&(s=u.get(e,!1,i))!==t?s:f[n];o=typeof r,o==="string"&&(s=zt.exec(r))&&(r=(s[1]+1)*s[2]+parseFloat(v.css(e,n)),o="number");if(r==null||o==="number"&&isNaN(r))return;o==="number"&&!v.cssNumber[a]&&(r+="px");if(!u||!("set"in u)||(r=u.set(e,r,i))!==t)try{f[n]=r}catch(l){}},css:function(e,n,r,i){var s,o,u,a=v.camelCase(n);return n=v.cssProps[a]||(v.cssProps[a]=Qt(e.style,a)),u=v.cssHooks[n]||v.cssHooks[a],u&&"get"in u&&(s=u.get(e,!0,i)),s===t&&(s=Dt(e,n)),s==="normal"&&n in Vt&&(s=Vt[n]),r||i!==t?(o=parseFloat(s),r||v.isNumeric(o)?o||0:s):s},swap:function(e,t,n){var r,i,s={};for(i in t)s[i]=e.style[i],e.style[i]=t[i];r=n.call(e);for(i in t)e.style[i]=s[i];return r}}),e.getComputedStyle?Dt=function(t,n){var r,i,s,o,u=e.getComputedStyle(t,null),a=t.style;return u&&(r=u.getPropertyValue(n)||u[n],r===""&&!v.contains(t.ownerDocument,t)&&(r=v.style(t,n)),Ut.test(r)&&qt.test(n)&&(i=a.width,s=a.minWidth,o=a.maxWidth,a.minWidth=a.maxWidth=a.width=r,r=u.width,a.width=i,a.minWidth=s,a.maxWidth=o)),r}:i.documentElement.currentStyle&&(Dt=function(e,t){var n,r,i=e.currentStyle&&e.currentStyle[t],s=e.style;return i==null&&s&&s[t]&&(i=s[t]),Ut.test(i)&&!Ft.test(t)&&(n=s.left,r=e.runtimeStyle&&e.runtimeStyle.left,r&&(e.runtimeStyle.left=e.currentStyle.left),s.left=t==="fontSize"?"1em":i,i=s.pixelLeft+"px",s.left=n,r&&(e.runtimeStyle.left=r)),i===""?"auto":i}),v.each(["height","width"],function(e,t){v.cssHooks[t]={get:function(e,n,r){if(n)return e.offsetWidth===0&&It.test(Dt(e,"display"))?v.swap(e,Xt,function(){return tn(e,t,r)}):tn(e,t,r)},set:function(e,n,r){return Zt(e,n,r?en(e,t,r,v.support.boxSizing&&v.css(e,"boxSizing")==="border-box"):0)}}}),v.support.opacity||(v.cssHooks.opacity={get:function(e,t){return jt.test((t&&e.currentStyle?e.currentStyle.filter:e.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":t?"1":""},set:function(e,t){var n=e.style,r=e.currentStyle,i=v.isNumeric(t)?"alpha(opacity="+t*100+")":"",s=r&&r.filter||n.filter||"";n.zoom=1;if(t>=1&&v.trim(s.replace(Bt,""))===""&&n.removeAttribute){n.removeAttribute("filter");if(r&&!r.filter)return}n.filter=Bt.test(s)?s.replace(Bt,i):s+" "+i}}),v(function(){v.support.reliableMarginRight||(v.cssHooks.marginRight={get:function(e,t){return v.swap(e,{display:"inline-block"},function(){if(t)return Dt(e,"marginRight")})}}),!v.support.pixelPosition&&v.fn.position&&v.each(["top","left"],function(e,t){v.cssHooks[t]={get:function(e,n){if(n){var r=Dt(e,t);return Ut.test(r)?v(e).position()[t]+"px":r}}}})}),v.expr&&v.expr.filters&&(v.expr.filters.hidden=function(e){return e.offsetWidth===0&&e.offsetHeight===0||!v.support.reliableHiddenOffsets&&(e.style&&e.style.display||Dt(e,"display"))==="none"},v.expr.filters.visible=function(e){return!v.expr.filters.hidden(e)}),v.each({margin:"",padding:"",border:"Width"},function(e,t){v.cssHooks[e+t]={expand:function(n){var r,i=typeof n=="string"?n.split(" "):[n],s={};for(r=0;r<4;r++)s[e+$t[r]+t]=i[r]||i[r-2]||i[0];return s}},qt.test(e)||(v.cssHooks[e+t].set=Zt)});var rn=/%20/g,sn=/\[\]$/,on=/\r?\n/g,un=/^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,an=/^(?:select|textarea)/i;v.fn.extend({serialize:function(){return v.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?v.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||an.test(this.nodeName)||un.test(this.type))}).map(function(e,t){var n=v(this).val();return n==null?null:v.isArray(n)?v.map(n,function(e,n){return{name:t.name,value:e.replace(on,"\r\n")}}):{name:t.name,value:n.replace(on,"\r\n")}}).get()}}),v.param=function(e,n){var r,i=[],s=function(e,t){t=v.isFunction(t)?t():t==null?"":t,i[i.length]=encodeURIComponent(e)+"="+encodeURIComponent(t)};n===t&&(n=v.ajaxSettings&&v.ajaxSettings.traditional);if(v.isArray(e)||e.jquery&&!v.isPlainObject(e))v.each(e,function(){s(this.name,this.value)});else for(r in e)fn(r,e[r],n,s);return i.join("&").replace(rn,"+")};var ln,cn,hn=/#.*$/,pn=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,dn=/^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,vn=/^(?:GET|HEAD)$/,mn=/^\/\//,gn=/\?/,yn=/)<[^<]*)*<\/script>/gi,bn=/([?&])_=[^&]*/,wn=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,En=v.fn.load,Sn={},xn={},Tn=["*/"]+["*"];try{cn=s.href}catch(Nn){cn=i.createElement("a"),cn.href="",cn=cn.href}ln=wn.exec(cn.toLowerCase())||[],v.fn.load=function(e,n,r){if(typeof e!="string"&&En)return En.apply(this,arguments);if(!this.length)return this;var i,s,o,u=this,a=e.indexOf(" ");return a>=0&&(i=e.slice(a,e.length),e=e.slice(0,a)),v.isFunction(n)?(r=n,n=t):n&&typeof n=="object"&&(s="POST"),v.ajax({url:e,type:s,dataType:"html",data:n,complete:function(e,t){r&&u.each(r,o||[e.responseText,t,e])}}).done(function(e){o=arguments,u.html(i?v("
").append(e.replace(yn,"")).find(i):e)}),this},v.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(e,t){v.fn[t]=function(e){return this.on(t,e)}}),v.each(["get","post"],function(e,n){v[n]=function(e,r,i,s){return v.isFunction(r)&&(s=s||i,i=r,r=t),v.ajax({type:n,url:e,data:r,success:i,dataType:s})}}),v.extend({getScript:function(e,n){return v.get(e,t,n,"script")},getJSON:function(e,t,n){return v.get(e,t,n,"json")},ajaxSetup:function(e,t){return t?Ln(e,v.ajaxSettings):(t=e,e=v.ajaxSettings),Ln(e,t),e},ajaxSettings:{url:cn,isLocal:dn.test(ln[1]),global:!0,type:"GET",contentType:"application/x-www-form-urlencoded; charset=UTF-8",processData:!0,async:!0,accepts:{xml:"application/xml, text/xml",html:"text/html",text:"text/plain",json:"application/json, text/javascript","*":Tn},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":e.String,"text html":!0,"text json":v.parseJSON,"text xml":v.parseXML},flatOptions:{context:!0,url:!0}},ajaxPrefilter:Cn(Sn),ajaxTransport:Cn(xn),ajax:function(e,n){function T(e,n,s,a){var l,y,b,w,S,T=n;if(E===2)return;E=2,u&&clearTimeout(u),o=t,i=a||"",x.readyState=e>0?4:0,s&&(w=An(c,x,s));if(e>=200&&e<300||e===304)c.ifModified&&(S=x.getResponseHeader("Last-Modified"),S&&(v.lastModified[r]=S),S=x.getResponseHeader("Etag"),S&&(v.etag[r]=S)),e===304?(T="notmodified",l=!0):(l=On(c,w),T=l.state,y=l.data,b=l.error,l=!b);else{b=T;if(!T||e)T="error",e<0&&(e=0)}x.status=e,x.statusText=(n||T)+"",l?d.resolveWith(h,[y,T,x]):d.rejectWith(h,[x,T,b]),x.statusCode(g),g=t,f&&p.trigger("ajax"+(l?"Success":"Error"),[x,c,l?y:b]),m.fireWith(h,[x,T]),f&&(p.trigger("ajaxComplete",[x,c]),--v.active||v.event.trigger("ajaxStop"))}typeof e=="object"&&(n=e,e=t),n=n||{};var r,i,s,o,u,a,f,l,c=v.ajaxSetup({},n),h=c.context||c,p=h!==c&&(h.nodeType||h instanceof v)?v(h):v.event,d=v.Deferred(),m=v.Callbacks("once memory"),g=c.statusCode||{},b={},w={},E=0,S="canceled",x={readyState:0,setRequestHeader:function(e,t){if(!E){var n=e.toLowerCase();e=w[n]=w[n]||e,b[e]=t}return this},getAllResponseHeaders:function(){return E===2?i:null},getResponseHeader:function(e){var n;if(E===2){if(!s){s={};while(n=pn.exec(i))s[n[1].toLowerCase()]=n[2]}n=s[e.toLowerCase()]}return n===t?null:n},overrideMimeType:function(e){return E||(c.mimeType=e),this},abort:function(e){return e=e||S,o&&o.abort(e),T(0,e),this}};d.promise(x),x.success=x.done,x.error=x.fail,x.complete=m.add,x.statusCode=function(e){if(e){var t;if(E<2)for(t in e)g[t]=[g[t],e[t]];else t=e[x.status],x.always(t)}return this},c.url=((e||c.url)+"").replace(hn,"").replace(mn,ln[1]+"//"),c.dataTypes=v.trim(c.dataType||"*").toLowerCase().split(y),c.crossDomain==null&&(a=wn.exec(c.url.toLowerCase()),c.crossDomain=!(!a||a[1]===ln[1]&&a[2]===ln[2]&&(a[3]||(a[1]==="http:"?80:443))==(ln[3]||(ln[1]==="http:"?80:443)))),c.data&&c.processData&&typeof c.data!="string"&&(c.data=v.param(c.data,c.traditional)),kn(Sn,c,n,x);if(E===2)return x;f=c.global,c.type=c.type.toUpperCase(),c.hasContent=!vn.test(c.type),f&&v.active++===0&&v.event.trigger("ajaxStart");if(!c.hasContent){c.data&&(c.url+=(gn.test(c.url)?"&":"?")+c.data,delete c.data),r=c.url;if(c.cache===!1){var N=v.now(),C=c.url.replace(bn,"$1_="+N);c.url=C+(C===c.url?(gn.test(c.url)?"&":"?")+"_="+N:"")}}(c.data&&c.hasContent&&c.contentType!==!1||n.contentType)&&x.setRequestHeader("Content-Type",c.contentType),c.ifModified&&(r=r||c.url,v.lastModified[r]&&x.setRequestHeader("If-Modified-Since",v.lastModified[r]),v.etag[r]&&x.setRequestHeader("If-None-Match",v.etag[r])),x.setRequestHeader("Accept",c.dataTypes[0]&&c.accepts[c.dataTypes[0]]?c.accepts[c.dataTypes[0]]+(c.dataTypes[0]!=="*"?", "+Tn+"; q=0.01":""):c.accepts["*"]);for(l in c.headers)x.setRequestHeader(l,c.headers[l]);if(!c.beforeSend||c.beforeSend.call(h,x,c)!==!1&&E!==2){S="abort";for(l in{success:1,error:1,complete:1})x[l](c[l]);o=kn(xn,c,n,x);if(!o)T(-1,"No Transport");else{x.readyState=1,f&&p.trigger("ajaxSend",[x,c]),c.async&&c.timeout>0&&(u=setTimeout(function(){x.abort("timeout")},c.timeout));try{E=1,o.send(b,T)}catch(k){if(!(E<2))throw k;T(-1,k)}}return x}return x.abort()},active:0,lastModified:{},etag:{}});var Mn=[],_n=/\?/,Dn=/(=)\?(?=&|$)|\?\?/,Pn=v.now();v.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=Mn.pop()||v.expando+"_"+Pn++;return this[e]=!0,e}}),v.ajaxPrefilter("json jsonp",function(n,r,i){var s,o,u,a=n.data,f=n.url,l=n.jsonp!==!1,c=l&&Dn.test(f),h=l&&!c&&typeof a=="string"&&!(n.contentType||"").indexOf("application/x-www-form-urlencoded")&&Dn.test(a);if(n.dataTypes[0]==="jsonp"||c||h)return s=n.jsonpCallback=v.isFunction(n.jsonpCallback)?n.jsonpCallback():n.jsonpCallback,o=e[s],c?n.url=f.replace(Dn,"$1"+s):h?n.data=a.replace(Dn,"$1"+s):l&&(n.url+=(_n.test(f)?"&":"?")+n.jsonp+"="+s),n.converters["script json"]=function(){return u||v.error(s+" was not called"),u[0]},n.dataTypes[0]="json",e[s]=function(){u=arguments},i.always(function(){e[s]=o,n[s]&&(n.jsonpCallback=r.jsonpCallback,Mn.push(s)),u&&v.isFunction(o)&&o(u[0]),u=o=t}),"script"}),v.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/javascript|ecmascript/},converters:{"text script":function(e){return v.globalEval(e),e}}}),v.ajaxPrefilter("script",function(e){e.cache===t&&(e.cache=!1),e.crossDomain&&(e.type="GET",e.global=!1)}),v.ajaxTransport("script",function(e){if(e.crossDomain){var n,r=i.head||i.getElementsByTagName("head")[0]||i.documentElement;return{send:function(s,o){n=i.createElement("script"),n.async="async",e.scriptCharset&&(n.charset=e.scriptCharset),n.src=e.url,n.onload=n.onreadystatechange=function(e,i){if(i||!n.readyState||/loaded|complete/.test(n.readyState))n.onload=n.onreadystatechange=null,r&&n.parentNode&&r.removeChild(n),n=t,i||o(200,"success")},r.insertBefore(n,r.firstChild)},abort:function(){n&&n.onload(0,1)}}}});var Hn,Bn=e.ActiveXObject?function(){for(var e in Hn)Hn[e](0,1)}:!1,jn=0;v.ajaxSettings.xhr=e.ActiveXObject?function(){return!this.isLocal&&Fn()||In()}:Fn,function(e){v.extend(v.support,{ajax:!!e,cors:!!e&&"withCredentials"in e})}(v.ajaxSettings.xhr()),v.support.ajax&&v.ajaxTransport(function(n){if(!n.crossDomain||v.support.cors){var r;return{send:function(i,s){var o,u,a=n.xhr();n.username?a.open(n.type,n.url,n.async,n.username,n.password):a.open(n.type,n.url,n.async);if(n.xhrFields)for(u in n.xhrFields)a[u]=n.xhrFields[u];n.mimeType&&a.overrideMimeType&&a.overrideMimeType(n.mimeType),!n.crossDomain&&!i["X-Requested-With"]&&(i["X-Requested-With"]="XMLHttpRequest");try{for(u in i)a.setRequestHeader(u,i[u])}catch(f){}a.send(n.hasContent&&n.data||null),r=function(e,i){var u,f,l,c,h;try{if(r&&(i||a.readyState===4)){r=t,o&&(a.onreadystatechange=v.noop,Bn&&delete Hn[o]);if(i)a.readyState!==4&&a.abort();else{u=a.status,l=a.getAllResponseHeaders(),c={},h=a.responseXML,h&&h.documentElement&&(c.xml=h);try{c.text=a.responseText}catch(p){}try{f=a.statusText}catch(p){f=""}!u&&n.isLocal&&!n.crossDomain?u=c.text?200:404:u===1223&&(u=204)}}}catch(d){i||s(-1,d)}c&&s(u,f,c,l)},n.async?a.readyState===4?setTimeout(r,0):(o=++jn,Bn&&(Hn||(Hn={},v(e).unload(Bn)),Hn[o]=r),a.onreadystatechange=r):r()},abort:function(){r&&r(0,1)}}}});var qn,Rn,Un=/^(?:toggle|show|hide)$/,zn=new RegExp("^(?:([-+])=|)("+m+")([a-z%]*)$","i"),Wn=/queueHooks$/,Xn=[Gn],Vn={"*":[function(e,t){var n,r,i=this.createTween(e,t),s=zn.exec(t),o=i.cur(),u=+o||0,a=1,f=20;if(s){n=+s[2],r=s[3]||(v.cssNumber[e]?"":"px");if(r!=="px"&&u){u=v.css(i.elem,e,!0)||n||1;do a=a||".5",u/=a,v.style(i.elem,e,u+r);while(a!==(a=i.cur()/o)&&a!==1&&--f)}i.unit=r,i.start=u,i.end=s[1]?u+(s[1]+1)*n:n}return i}]};v.Animation=v.extend(Kn,{tweener:function(e,t){v.isFunction(e)?(t=e,e=["*"]):e=e.split(" ");var n,r=0,i=e.length;for(;r-1,f={},l={},c,h;a?(l=i.position(),c=l.top,h=l.left):(c=parseFloat(o)||0,h=parseFloat(u)||0),v.isFunction(t)&&(t=t.call(e,n,s)),t.top!=null&&(f.top=t.top-s.top+c),t.left!=null&&(f.left=t.left-s.left+h),"using"in t?t.using.call(e,f):i.css(f)}},v.fn.extend({position:function(){if(!this[0])return;var e=this[0],t=this.offsetParent(),n=this.offset(),r=er.test(t[0].nodeName)?{top:0,left:0}:t.offset();return n.top-=parseFloat(v.css(e,"marginTop"))||0,n.left-=parseFloat(v.css(e,"marginLeft"))||0,r.top+=parseFloat(v.css(t[0],"borderTopWidth"))||0,r.left+=parseFloat(v.css(t[0],"borderLeftWidth"))||0,{top:n.top-r.top,left:n.left-r.left}},offsetParent:function(){return this.map(function(){var e=this.offsetParent||i.body;while(e&&!er.test(e.nodeName)&&v.css(e,"position")==="static")e=e.offsetParent;return e||i.body})}}),v.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(e,n){var r=/Y/.test(n);v.fn[e]=function(i){return v.access(this,function(e,i,s){var o=tr(e);if(s===t)return o?n in o?o[n]:o.document.documentElement[i]:e[i];o?o.scrollTo(r?v(o).scrollLeft():s,r?s:v(o).scrollTop()):e[i]=s},e,i,arguments.length,null)}}),v.each({Height:"height",Width:"width"},function(e,n){v.each({padding:"inner"+e,content:n,"":"outer"+e},function(r,i){v.fn[i]=function(i,s){var o=arguments.length&&(r||typeof i!="boolean"),u=r||(i===!0||s===!0?"margin":"border");return v.access(this,function(n,r,i){var s;return v.isWindow(n)?n.document.documentElement["client"+e]:n.nodeType===9?(s=n.documentElement,Math.max(n.body["scroll"+e],s["scroll"+e],n.body["offset"+e],s["offset"+e],s["client"+e])):i===t?v.css(n,r,i,u):v.style(n,r,i,u)},n,o?i:t,o,null)}})}),e.jQuery=e.$=v,typeof define=="function"&&define.amd&&define.amd.jQuery&&define("jquery",[],function(){return v})})(window); \ No newline at end of file diff --git a/Chapter08/0x_with_user_auth/static/content/login.js b/Chapter08/0x_with_user_auth/static/content/login.js new file mode 100644 index 0000000..fd52f1d --- /dev/null +++ b/Chapter08/0x_with_user_auth/static/content/login.js @@ -0,0 +1,30 @@ +$(function(){ + + var tmpl, // Main template HTML + tdata = {}; // JSON data object that feeds the template + + // Initialise page + var initPage = function() { + + // Load the HTML template + $.get("/templates/login.html", function(d){ + tmpl = d; + }); + + // Retrieve the server data and then initialise the page +// $.getJSON("/v1/users/logged_in.json", function (d) { +// $.extend(tdata, d); +// }); + + // When AJAX calls are complete parse the template + // replacing mustache tags with vars + $(document).ajaxStop(function () { +// if (tdata.data.logged_in) +// window.location = "/pages/admin/home"; +// else { + var renderedPage = Mustache.to_html( tmpl, tdata ); + $("body").html( renderedPage ); +// } + }); + }(); +}); diff --git a/Chapter08/0x_with_user_auth/static/content/mustache.js b/Chapter08/0x_with_user_auth/static/content/mustache.js new file mode 100644 index 0000000..0148d29 --- /dev/null +++ b/Chapter08/0x_with_user_auth/static/content/mustache.js @@ -0,0 +1,625 @@ +/*! + * mustache.js - Logic-less {{mustache}} templates with JavaScript + * http://github.com/janl/mustache.js + */ + +/*global define: false*/ + +var Mustache; + +(function (exports) { + if (typeof module !== "undefined" && module.exports) { + module.exports = exports; // CommonJS + } else if (typeof define === "function") { + define(exports); // AMD + } else { + Mustache = exports; // diff --git a/Chapter08/0x_with_user_auth/static/templates/admin_add_photos.html b/Chapter08/0x_with_user_auth/static/templates/admin_add_photos.html new file mode 100644 index 0000000..d9cbe8d --- /dev/null +++ b/Chapter08/0x_with_user_auth/static/templates/admin_add_photos.html @@ -0,0 +1,86 @@ +
+ +
+
Add to Album:
+
+ +
+
Image:
+
+
Description
+
+
+ + + + + +
+ + diff --git a/Chapter08/0x_with_user_auth/static/templates/admin_home.html b/Chapter08/0x_with_user_auth/static/templates/admin_home.html new file mode 100644 index 0000000..4db4cf1 --- /dev/null +++ b/Chapter08/0x_with_user_auth/static/templates/admin_home.html @@ -0,0 +1,7 @@ + +

Admin Operations

+ + diff --git a/Chapter08/0x_with_user_auth/static/templates/album.html b/Chapter08/0x_with_user_auth/static/templates/album.html new file mode 100644 index 0000000..fbcbda2 --- /dev/null +++ b/Chapter08/0x_with_user_auth/static/templates/album.html @@ -0,0 +1,20 @@ + +
+ {{#has_photos}} +

There are {{ has_photos }} photos in this album

+ {{/has_photos}} + {{#photos}} +
+
+
+
+

{{ desc }}

+
+
+ {{/photos}} +
+ {{^photos}} +

This album does't have any photos in it, sorry.

+ {{/photos}} +

diff --git a/Chapter08/0x_with_user_auth/static/templates/home.html b/Chapter08/0x_with_user_auth/static/templates/home.html new file mode 100644 index 0000000..90ff5fc --- /dev/null +++ b/Chapter08/0x_with_user_auth/static/templates/home.html @@ -0,0 +1,17 @@ +
+ Register | + Admin +
+
+

There are {{ albums.length }} albums

+
    + {{#albums}} +
  • + {{name}} +
  • + {{/albums}} + {{^albums}} +
  • Sorry, there are currently no albums
  • + {{/albums}} +
+
diff --git a/Chapter08/0x_with_user_auth/static/templates/login.html b/Chapter08/0x_with_user_auth/static/templates/login.html new file mode 100644 index 0000000..7bbcc3f --- /dev/null +++ b/Chapter08/0x_with_user_auth/static/templates/login.html @@ -0,0 +1,49 @@ + +
+
+
+
Email address:
+
+
Password:
+
+
+
+ + + + diff --git a/Chapter08/0x_with_user_auth/static/templates/register.html b/Chapter08/0x_with_user_auth/static/templates/register.html new file mode 100644 index 0000000..2934caa --- /dev/null +++ b/Chapter08/0x_with_user_auth/static/templates/register.html @@ -0,0 +1,56 @@ + + +
+
+
+
Email address:
+
+
Display Name:
+
+
Password:
+
+
Password (confirm):
+
+
+
+ + + + diff --git a/Chapter08/0x_with_user_auth/test.jpg b/Chapter08/0x_with_user_auth/test.jpg new file mode 100644 index 0000000..6e4250a Binary files /dev/null and b/Chapter08/0x_with_user_auth/test.jpg differ diff --git a/Chapter09/01_mysql_demos/01_mysql_testing.js b/Chapter09/01_mysql_demos/01_mysql_testing.js new file mode 100644 index 0000000..05a352e --- /dev/null +++ b/Chapter09/01_mysql_demos/01_mysql_testing.js @@ -0,0 +1,309 @@ + +var pool = require('generic-pool'), + mysql = require('mysql'), + async = require('async'); + +var host = "localhost"; +var database = "PhotoAlbums"; +var user = "root"; +var password = ""; + + + + +/** + * Don't forget that for waterfall, it will stop and call the final + * "cleanup" function whenever it sees an error has been passed to + * one of the callback functions. + * + * Also, if a parameter is given to the callback, it will include + * those in the next function called in the waterfall. + */ +var dbclient; + +async.waterfall([ + + // 1. create database connection + function (cb) { + console.log("\n** 1. create connection."); + dbclient = mysql.createConnection({ + host: "localhost", + user: "root", + password: "", + database: "PhotoAlbums" + }); + + dbclient.connect(cb); + }, + + // 2. let's add a couple of albums. we will run them as separate + // queries. + function (results, cb) { + console.log("\n** 2. create albums."); + dbclient.query( + "INSERT INTO Albums VALUES (?, ?, ?, ?)", + [ "italy2012", "Spring Festival in Italy", "2012-02-15", + "I went to Italy for Spring Festival" ], + cb); + }, + + function (results, fields, cb) { + console.log(arguments); + console.log(fields); + console.log("\n** 2b. create albums."); + dbclient.query( + "INSERT INTO Albums VALUES (?, ?, ?, ?)", + [ "australia2010", "Vacation Down Under", "2010-10-20", + "Spent some time in Australia visiting Friends" ], + cb); + }, + + function (results, fields, cb) { + console.log(fields); + console.log("\n** 2c. create albums."); + dbclient.query( + "INSERT INTO Albums VALUES (?, ?, ?, ?)", + [ "japan2010", "Programming in Tokyo", "2010/06/10", + "I worked in Tokyo for a while." ], + cb); + }, + + // 3. let's add some photos to albums + function (results, fields, cb) { + console.log(fields); + // mysql is cool with this date format. + var pix = [ + { filename: "picture_01.jpg", + albumid: "italy2012", + description: "rome!", + date: "2012/02/15 16:20:40" }, + { filename: "picture_04.jpg", + albumid: "italy2012", + description: "fontana di trevi", + date: "2012/02/19 16:20:40" }, + { filename: "picture_02.jpg", + albumid: "italy2012", + description: "it's the vatican!", + date: "2012/02/17 16:35:04" }, + { filename: "picture_05.jpg", + albumid: "italy2012", + description: "rome!", + date: "2012/02/19 16:20:40" }, + { filename: "picture_03.jpg", + albumid: "italy2012", + description: "spanish steps", + date: "2012/02/18 16:20:40" }, + + { filename: "photo_05.jpg", + albumid: "japan2010", + description: "something nice", + date: "2010/06/14 12:21:40" }, + { filename: "photo_01.jpg", + albumid: "japan2010", + description: "tokyo tower!", + date: "2010/06/11 12:20:40" }, + { filename: "photo_06.jpg", + albumid: "japan2010", + description: "kitty cats", + date: "2010/06/14 12:23:40" }, + { filename: "photo_03.jpg", + albumid: "japan2010", + description: "shinjuku is nice", + date: "2010/06/12 08:80:40" }, + { filename: "photo_04.jpg", + albumid: "japan2010", + description: "eating sushi", + date: "2010/06/12 08:34:40" }, + { filename: "photo_02.jpg", + albumid: "japan2010", + description: "roppongi!", + date: "2010/06/12 07:44:40" }, + { filename: "photo_07.jpg", + albumid: "japan2010", + description: "moo cow oink pig woo!!", + date: "2010/06/15 12:55:40" }, + + { filename: "photo_001.jpg", + albumid: "australia2010", + description: "sydney!", + date: "2010/10/20 07:44:40" }, + { filename: "photo_002.jpg", + albumid: "australia2010", + description: "asdfasdf!", + date: "2010/10/20 08:24:40" }, + { filename: "photo_003.jpg", + albumid: "australia2010", + description: "qwerqwr!", + date: "2010/10/20 08:55:40" }, + { filename: "photo_004.jpg", + albumid: "australia2010", + description: "zzzxcv zxcv", + date: "2010/10/21 14:29:40" }, + { filename: "photo_005.jpg", + albumid: "australia2010", + description: "ipuoip", + date: "2010/10/22 19:08:40" }, + { filename: "photo_006.jpg", + albumid: "australia2010", + description: "asdufio", + date: "2010/10/22 22:15:40" } + ]; + + var q = "\ +INSERT INTO Photos (filename, album_name, description, date) \ + VALUES (?, ?, ?, ?)"; + + console.log("\n** 3. Add pictures."); + async.forEachSeries( + pix, + // run the query and call clbk to do next in array + // we do in serial because connection only does + // one thing at a time. + function (item, clbk) { + dbclient.query( + q, + [ item.filename, item.albumid, + item.description, item.date ], + clbk); + }, + cb); + }, + + function (cb) { + console.log(arguments); + // 4. list all albums + console.log("\n** 4. list albums"); + dbclient.query("SELECT * FROM Albums ORDER BY date DESC", cb); + }, + + function (rows, fields, cb) { + console.log(fields); + console.log(" -> dumping albums:"); + for (var i = 0; i < rows.length; i++) { + console.log(" -> Album: " + rows[i].name + + " (" + rows[i].date + ")"); + } + + // 5. find italy2012 album. + console.log("\n** 5. Find album."); + dbclient.query( + "SELECT * FROM Albums WHERE name = ?", + [ "italy2012" ], + cb); + }, + + function (rows, fields, cb) { + console.log(fields); + console.log(" -> dumping italy2012:"); + for (var i = 0; i < rows.length; i++) { + console.log(" -> Album: " + rows[i].name + + " (" + rows[i].date + ")"); + } + + // 6. find all photos in italy2012 album. sort by date, + // and return subset + console.log("\n** 6. Photos for albums."); + var q = "\ +SELECT * FROM Photos WHERE album_name = ?\ + ORDER BY date DESC LIMIT ?, ?"; + + dbclient.query(q, ["italy2012", 2, 5 ], cb); + }, + + function (rows, fields, cb) { + console.log(fields); + console.log(" -> dumping italy2012 photos:"); + for (var i = 0; i < rows.length; i++) { + console.log("Photo: " + rows[i].filename + + " (" + rows[i].date + ")"); + } + + // 7. replace the description in a photo + console.log("\n** 7. update photo."); + dbclient.query( + "UPDATE Photos SET description = ? \ + WHERE album_name = ? AND filename = ?", + [ "NO SHINJUKU! BAD!", "italy2012", "picture_03.jpg" ], + cb); + }, + + function (results, fields, cb) { + console.log(fields); + console.log(results); + console.log(" -> updated rows: " + results.affectedRows); + if (results.affectedRows != 1) { + cb(new Error("CRAP TEST 7 didn't affect 1 row!")); + return; + } + + // 8. delete a photo + console.log("\n** 8. delete photo."); + dbclient.query( + "DELETE FROM Photos WHERE filename = ? AND album_name = ?", + [ "photo_04.jpg", "japan2010" ], + cb); + }, + + function (results, fields, cb) { + console.log(fields); + console.log(results); + console.log(" -> deleted rows: " + results.affectedRows); + if (results.affectedRows != 1) { + cb(new Error("CRAP TEST 8 didn't affect 1 row!")); + return; + } + + // 9. delete an entire album and its photos. + // a. delete photos + console.log("\n** 9. delete entire album and photos"); + dbclient.query( + "DELETE FROM Photos WHERE album_name = ?", + [ "australia2012" ], + cb); + }, + + function (results, fields, cb) { + console.log(fields); + console.log(" -> delete photos rows: " + results.affectedRows); + console.log(results); + + // b. delete the album + dbclient.query( + "DELETE FROM Albums WHERE name = ?", + [ "australia2012" ], + cb); + }, + + function (results, fields, cb) { + console.log(fields); + console.log(" -> delete album rows: " + results.affectedRows); + console.log(results); + + // 10. ask for an album that doesn't exist. + console.log("\n** 10. Search for non-existant album."); + dbclient.query( + "SELECT * FROM Albums WHERE name = ?", + [ "asdfasdf" ], + cb); + }, + + function (rows, fields, cb) { + console.log(fields); + console.log(" -> asked for bogus, got " + rows.length + " rows"); + cb(null); + } +], +// waterfall cleanup function +function (err, results) { + if (err) { + console.log("Aw, there was an error: "); + console.log(err); + } else { + console.log("All operations completed without error."); + } + + dbclient.end(); +}); + + + diff --git a/Chapter09/01_mysql_demos/01_mysql_testing.js.bak b/Chapter09/01_mysql_demos/01_mysql_testing.js.bak new file mode 100644 index 0000000..481be7a --- /dev/null +++ b/Chapter09/01_mysql_demos/01_mysql_testing.js.bak @@ -0,0 +1,309 @@ + +var pool = require('generic-pool'), + mysql = require('mysql'), + async = require('async'); + +var host = "localhost"; +var database = "PhotoAlbums"; +var user = "root"; +var password = ""; + + +/** + * node-mysql sometimes adds extra data to callbacks to be helpful. + * this can mess up our waterfall, however, so we'll strip those + * out. + */ +function mscb(cb) { + return function (err, results) { + cb(err, results); + } +} + + + +/** + * Don't forget that for waterfall, it will stop and call the final + * "cleanup" function whenever it sees an error has been passed to + * one of the callback functions. + * + * Also, if a parameter is given to the callback, it will include + * those in the next function called in the waterfall. + */ +var dbclient; + +async.waterfall([ + + // 1. create database connection + function (cb) { + console.log("\n** 1. create connection."); + dbclient = mysql.createConnection({ + host: "localhost", + user: "root", + password: "", + database: "PhotoAlbums" + }); + + dbclient.connect(cb); + }, + + // 2. let's add a couple of albums. we will run them as separate + // queries. + function (results, cb) { + console.log("\n** 2. create albums."); + dbclient.query( + "INSERT INTO Albums VALUES (?, ?, ?, ?)", + [ "italy2012", "Spring Festival in Italy", "2012-02-15", + "I went to Italy for Spring Festival" ], + mscb(cb)); + }, + + function (results, cb) { + console.log(arguments); + console.log("\n** 2b. create albums."); + dbclient.query( + "INSERT INTO Albums VALUES (?, ?, ?, ?)", + [ "australia2010", "Vacation Down Under", "2010-10-20", + "Spent some time in Australia visiting Friends" ], + mscb(cb)); + }, + + function (results, cb) { + console.log("\n** 2c. create albums."); + dbclient.query( + "INSERT INTO Albums VALUES (?, ?, ?, ?)", + [ "japan2010", "Programming in Tokyo", "2010/06/10", + "I worked in Tokyo for a while." ], + mscb(cb)); + }, + + // 3. let's add some photos to albums + function (results, cb) { + // mysql is cool with this date format. + var pix = [ + { filename: "picture_01.jpg", + albumid: "italy2012", + description: "rome!", + date: "2012/02/15 16:20:40" }, + { filename: "picture_04.jpg", + albumid: "italy2012", + description: "fontana di trevi", + date: "2012/02/19 16:20:40" }, + { filename: "picture_02.jpg", + albumid: "italy2012", + description: "it's the vatican!", + date: "2012/02/17 16:35:04" }, + { filename: "picture_05.jpg", + albumid: "italy2012", + description: "rome!", + date: "2012/02/19 16:20:40" }, + { filename: "picture_03.jpg", + albumid: "italy2012", + description: "spanish steps", + date: "2012/02/18 16:20:40" }, + + { filename: "photo_05.jpg", + albumid: "japan2010", + description: "something nice", + date: "2010/06/14 12:21:40" }, + { filename: "photo_01.jpg", + albumid: "japan2010", + description: "tokyo tower!", + date: "2010/06/11 12:20:40" }, + { filename: "photo_06.jpg", + albumid: "japan2010", + description: "kitty cats", + date: "2010/06/14 12:23:40" }, + { filename: "photo_03.jpg", + albumid: "japan2010", + description: "shinjuku is nice", + date: "2010/06/12 08:80:40" }, + { filename: "photo_04.jpg", + albumid: "japan2010", + description: "eating sushi", + date: "2010/06/12 08:34:40" }, + { filename: "photo_02.jpg", + albumid: "japan2010", + description: "roppongi!", + date: "2010/06/12 07:44:40" }, + { filename: "photo_07.jpg", + albumid: "japan2010", + description: "moo cow oink pig woo!!", + date: "2010/06/15 12:55:40" }, + + { filename: "photo_001.jpg", + albumid: "australia2010", + description: "sydney!", + date: "2010/10/20 07:44:40" }, + { filename: "photo_002.jpg", + albumid: "australia2010", + description: "asdfasdf!", + date: "2010/10/20 08:24:40" }, + { filename: "photo_003.jpg", + albumid: "australia2010", + description: "qwerqwr!", + date: "2010/10/20 08:55:40" }, + { filename: "photo_004.jpg", + albumid: "australia2010", + description: "zzzxcv zxcv", + date: "2010/10/21 14:29:40" }, + { filename: "photo_005.jpg", + albumid: "australia2010", + description: "ipuoip", + date: "2010/10/22 19:08:40" }, + { filename: "photo_006.jpg", + albumid: "australia2010", + description: "asdufio", + date: "2010/10/22 22:15:40" } + ]; + + var q = "\ +INSERT INTO Photos (filename, album_name, description, date) \ + VALUES (?, ?, ?, ?)"; + + console.log("\n** 3. Add pictures."); + async.forEachSeries( + pix, + // run the query and call clbk to do next in array + // we do in serial because connection only does + // one thing at a time. + function (item, clbk) { + dbclient.query( + q, + [ item.filename, item.albumid, + item.description, item.date ], + clbk); + }, + cb); + }, + + function (cb) { + console.log(arguments); + // 4. list all albums + console.log("\n** 4. list albums"); + dbclient.query("SELECT * FROM Albums ORDER BY date DESC", mscb(cb)); + }, + + function (rows, cb) { + console.log(" -> dumping albums:"); + for (var i = 0; i < rows.length; i++) { + console.log(" -> Album: " + rows[i].name + + " (" + rows[i].date + ")"); + } + + // 5. find italy2012 album. + console.log("\n** 5. Find album."); + dbclient.query( + "SELECT * FROM Albums WHERE name = ?", + [ "italy2012" ], + mscb(cb)); + }, + + function (rows, cb) { + console.log(" -> dumping italy2012:"); + for (var i = 0; i < rows.length; i++) { + console.log(" -> Album: " + rows[i].name + + " (" + rows[i].date + ")"); + } + + // 6. find all photos in italy2012 album. sort by date, + // and return subset + console.log("\n** 6. Photos for albums."); + var q = "\ +SELECT * FROM Photos WHERE album_name = ?\ + ORDER BY date DESC LIMIT ?, ?"; + + dbclient.query(q, ["italy2012", 2, 5 ], mscb(cb)); + }, + + function (rows, cb) { + console.log(" -> dumping italy2012 photos:"); + for (var i = 0; i < rows.length; i++) { + console.log("Photo: " + rows[i].filename + + " (" + rows[i].date + ")"); + } + + // 7. replace the description in a photo + console.log("\n** 7. update photo."); + dbclient.query( + "UPDATE Photos SET description = ? \ + WHERE album_name = ? AND filename = ?", + [ "NO SHINJUKU! BAD!", "italy2012", "picture_03.jpg" ], + mscb(cb)); + }, + + function (results, cb) { + console.log(results); + console.log(" -> updated rows: " + results.affectedRows); + if (results.affectedRows != 1) { + cb(new Error("CRAP TEST 7 didn't affect 1 row!")); + return; + } + + // 8. delete a photo + console.log("\n** 8. delete photo."); + dbclient.query( + "DELETE FROM Photos WHERE filename = ? AND album_name = ?", + [ "photo_04.jpg", "japan2010" ], + mscb(cb)); + }, + + function (results, cb) { + console.log(results); + console.log(" -> deleted rows: " + results.affectedRows); + if (results.affectedRows != 1) { + cb(new Error("CRAP TEST 8 didn't affect 1 row!")); + return; + } + + // 9. delete an entire album and its photos. + // a. delete photos + console.log("\n** 9. delete entire album and photos"); + dbclient.query( + "DELETE FROM Photos WHERE album_name = ?", + [ "australia2012" ], + mscb(cb)); + }, + + function (results, cb) { + console.log(" -> delete photos rows: " + results.affectedRows); + console.log(results); + + // b. delete the album + dbclient.query( + "DELETE FROM Albums WHERE name = ?", + [ "australia2012" ], + mscb(cb)); + }, + + function (results, cb) { + console.log(" -> delete album rows: " + results.affectedRows); + console.log(results); + + // 10. ask for an album that doesn't exist. + console.log("\n** 10. Search for non-existant album."); + dbclient.query( + "SELECT * FROM Albums WHERE name = ?", + [ "asdfasdf" ], + mscb(cb)); + }, + + function (rows, cb) { + console.log(" -> asked for bogus, got " + rows.length + " rows"); + cb(null); + } +], +// waterfall cleanup function +function (err, results) { + if (err) { + console.log("Aw, there was an error: "); + console.log(err); + } else { + console.log("All operations completed without error."); + } + + dbclient.end(); +}); + + + diff --git a/Chapter09/01_mysql_demos/package.json b/Chapter09/01_mysql_demos/package.json new file mode 100644 index 0000000..00536fb --- /dev/null +++ b/Chapter09/01_mysql_demos/package.json @@ -0,0 +1,11 @@ +{ + "name": "MySQL-Demo", + "description": "Demonstrates Using MySQL Database connectivity", + "version": "0.0.1", + "private": true, + "dependencies": { + "async": "0.1.x", + "generic-pool": "2.x", + "mysql": "2.x" + } +} diff --git a/Chapter09/01_mysql_demos/schema.sql b/Chapter09/01_mysql_demos/schema.sql new file mode 100644 index 0000000..7b58014 --- /dev/null +++ b/Chapter09/01_mysql_demos/schema.sql @@ -0,0 +1,53 @@ +DROP DATABASE IF EXISTS PhotoAlbums; + + +CREATE DATABASE PhotoAlbums + DEFAULT CHARACTER SET utf8 + DEFAULT COLLATE utf8_general_ci; + +USE PhotoAlbums; + + +CREATE TABLE Albums +( + name VARCHAR(50) UNIQUE PRIMARY KEY, + title VARCHAR(100), + date DATETIME, + description VARCHAR(500), + + -- allow for sorting on date. + INDEX(date) +) +ENGINE = InnoDB; + +CREATE TABLE Photos +( + album_name VARCHAR(50), + filename VARCHAR(50), + description VARCHAR(500), + date DATETIME, + + FOREIGN KEY (album_name) REFERENCES Albums (name), + INDEX (album_name, date) +) +ENGINE = InnoDB; + + +CREATE TABLE Users +( + user_uuid VARCHAR(50) UNIQUE PRIMARY KEY, + email_address VARCHAR(150) UNIQUE, + + display_name VARCHAR(100) NOT NULL, + password VARCHAR(100), + + first_seen_date BIGINT, + last_modified_date BIGINT, + deleted BOOL DEFAULT false, + + INDEX(email_address), + INDEX(user_uuid) +) +ENGINE = InnoDB; + + diff --git a/Chapter09/02_user_auth/app/basic.html b/Chapter09/02_user_auth/app/basic.html new file mode 100644 index 0000000..0d966da --- /dev/null +++ b/Chapter09/02_user_auth/app/basic.html @@ -0,0 +1,25 @@ + + + + Photo Album + + + + + + + + + + + + + + + + + diff --git a/Chapter09/02_user_auth/app/data/album.js b/Chapter09/02_user_auth/app/data/album.js new file mode 100644 index 0000000..d28fa6a --- /dev/null +++ b/Chapter09/02_user_auth/app/data/album.js @@ -0,0 +1,237 @@ + +var fs = require('fs'), + local = require('../local.config.js'), + db = require('./db.js'), + path = require("path"), + async = require('async'), + backhelp = require("./backend_helpers.js"); + +exports.version = "0.1.0"; + + +exports.create_album = function (data, callback) { + var write_succeeded = false; + var dbc; + + async.waterfall([ + // validate data. + function (cb) { + try { + backhelp.verify(data, + [ "name", + "title", + "date", + "description" ]); + if (!backhelp.valid_filename(data.name)) + throw invalid_album_name(); + } catch (e) { + cb(e); + } + + db.db(cb); + }, + + function (dbclient, cb) { + dbc = dbclient; + dbc.query( + "INSERT INTO Albums VALUES (?, ?, ?, ?)", + [ data.name, data.title, data.date, data.description ], + cb); + }, + + // make sure the folder exists. + function (results, fields, cb) { + write_succeeded = true; + fs.mkdir(local.config.static_content + + "albums/" + data.name, cb); + } + ], + function (err, results) { + // convert file errors to something we like. + if (err) { + if (write_succeeded) delete_album(dbc, data.name); + if (err instanceof Error && err.code == 'ER_EXISTS') + callback(backhelp.album_already_exists()); + else if (err instanceof Error && err.errno != undefined) + callback(backhelp.file_error(err)); + else + callback(err); + } else { + callback(err, err ? null : data); + } + + if (dbc) dbc.end(); + }); +}; + + +exports.album_by_name = function (name, callback) { + var dbc; + + async.waterfall([ + function (cb) { + if (!name) + cb(backhelp.missing_data("album name")); + else + db.db(cb); + }, + + function (dbclient, cb) { + dbc = dbclient; + dbc.query( + "SELECT * FROM Albums WHERE name = ?", + [ name ], + cb); + } + + ], + function (err, results) { + if (dbc) dbc.end(); + if (err) { + callback (err); + } else if (!results || results.length == 0) { + callback(backhelp.no_such_album()); + } else { + callback(null, results[0]); + } + }); +}; + + +exports.photos_for_album = function (album_name, skip, limit, callback) { + var dbc; + + async.waterfall([ + function (cb) { + if (!album_name) + cb(backhelp.missing_data("album name")); + else + db.db(cb); + }, + + function (dbclient, cb) { + dbc = dbclient; + dbc.query( + "SELECT * FROM Photos WHERE album_name = ? LIMIT ?, ?", + [ album_name, skip, limit ], + cb); + }, + + ], + function (err, results) { + if (dbc) dbc.end(); + if (err) { + callback (err); + } else { + callback(null, results); + } + }); +}; + + +exports.all_albums = function (sort_by, desc, skip, count, callback) { + var dbc; + async.waterfall([ + function (cb) { + db.db(cb); + }, + function (dbclient, cb) { + dbc = dbclient; + dbc.query( + "SELECT * FROM Albums ORDER BY ? " + + (desc ? "DESC" : "ASC") + + " LIMIT ?, ?", + [ sort_by, skip, count ], + cb); + } + ], + function (err, results) { + if (dbc) dbc.end(); + if (err) { + callback (err); + } else { + callback(null, results); + } + }); +}; + + +exports.add_photo = function (photo_data, path_to_photo, callback) { + var base_fn = path.basename(path_to_photo).toLowerCase(); + var write_succeeded = false; + var dbc; + + async.waterfall([ + // validate data + function (cb) { + try { + backhelp.verify(photo_data, + [ "albumid", "description", "date" ]); + photo_data.filename = base_fn; + if (!backhelp.valid_filename(photo_data.albumid)) + throw invalid_album_name(); + } catch (e) { + cb(e); + return; + } + db.db(cb); + }, + + function (dbclient, cb) { + dbc = dbclient; + dbc.query( + "INSERT INTO Photos VALUES (?, ?, ?, ?)", + [ photo_data.albumid, base_fn, photo_data.description, + photo_data.date ], + cb); + }, + + // now copy the temp file to static content + function (results, cb) { + write_succeeded = true; + var save_path = local.config.static_content + "albums/" + + photo_data.albumid + "/" + base_fn; + backhelp.file_copy(path_to_photo, save_path, true, cb); + }, + + ], + function (err, results) { + if (err && write_succeeded) + delete_photo(dbc, photo_data.albumid, base_fn); + if (err) { + callback (err); + } else { + // clone the object + var pd = JSON.parse(JSON.stringify(photo_data)); + pd.filename = base_fn; + callback(null, pd); + } + if (dbc) dbc.end(); + }); +}; + + +function invalid_album_name() { + return backhelp.error("invalid_album_name", + "Album names can have letters, #s, _ and, -"); +} +function invalid_filename() { + return backhelp.error("invalid_filename", + "Filenames can have letters, #s, _ and, -"); +} + + +function delete_album(dbc, name) { + dbc.query( + "DELETE FROM Albums WHERE name = ?", + [ name ], + function (err, results) {}); +} + +function delete_photo(dbc, albumid, fn) { + dbc.query( + "DELETE FROM Photos WHERE albumid = ? AND filename = ?", + [ albumid, fn ], + function (err, results) { }); +} + diff --git a/Chapter09/02_user_auth/app/data/backend_helpers.js b/Chapter09/02_user_auth/app/data/backend_helpers.js new file mode 100644 index 0000000..f43d753 --- /dev/null +++ b/Chapter09/02_user_auth/app/data/backend_helpers.js @@ -0,0 +1,111 @@ + +var fs = require('fs'); + + +exports.verify = function (data, field_names) { + for (var i = 0; i < field_names.length; i++) { + if (!data[field_names[i]]) { + throw exports.error("missing_data", + field_names[i] + " not optional"); + } + } + + return true; +} + +exports.error = function (code, message) { + var e = new Error(message); + e.code = code; + return e; +}; + +exports.file_error = function (err) { + return exports.error("file_error", JSON.stringify(err.message)); +} + + + +/** + * Possible signatures: + * src, dst, callback + * src, dst, can_overwrite, callback + */ +exports.file_copy = function () { + + var src, dst, callback; + var can_overwrite = false; + + if (arguments.length == 3) { + src = arguments[0]; + dst = arguments[1]; + callback = arguments[2]; + } else if (arguments.length == 4) { + src = arguments[0]; + dst = arguments[1]; + callback = arguments[3]; + can_overwrite = arguments[2] + } + + function copy(err) { + var is, os; + + if (!err && !can_overwrite) { + return callback(backhelp.error("file_exists", + "File " + dst + " exists.")); + } + + fs.stat(src, function (err) { + if (err) { + return callback(err); + } + + is = fs.createReadStream(src); + os = fs.createWriteStream(dst); + is.on('end', function () { callback(null); }); + is.on('error', function (e) { callback(e); }); + is.pipe(os); + }); + } + + fs.stat(dst, copy); +}; + + + +exports.valid_filename = function (fn) { + var re = /[^\.a-zA-Z0-9_-]/; + return typeof fn == 'string' && fn.length > 0 && !(fn.match(re)); +}; + + +exports.db_error = function () { + return exports.error("server_error", + "Something horrible has happened with our database!"); +}; + +exports.album_already_exists = function () { + return exports.error("album_already_exists", + "An album with this name already exists."); +}; + +exports.missing_data = function (field) { + return exports.error("missing_data", "You must provide: " + field); +}; + +exports.no_such_user = function () { + return exports.error("no_such_user", + "The specified user does not exist"); +}; + + +exports.user_already_registered = function () { + return exports.error("user_already_registered", + "This user appears to exist already!"); +}; + +exports.no_such_album = function () { + return exports.error("no_such_album", + "The specified album does not exist"); +}; + + diff --git a/Chapter09/02_user_auth/app/data/db.js b/Chapter09/02_user_auth/app/data/db.js new file mode 100644 index 0000000..b929d03 --- /dev/null +++ b/Chapter09/02_user_auth/app/data/db.js @@ -0,0 +1,14 @@ +var mysql = require('mysql'), + local = require("../local.config.js"); + +exports.db = function (callback) { + + conn_props = local.config.db_config; + var c = mysql.createConnection({ + host: conn_props.host, + user: conn_props.user, + password: conn_props.password, + database: conn_props.database + }); + callback(null, c); +}; diff --git a/Chapter09/02_user_auth/app/data/user.js b/Chapter09/02_user_auth/app/data/user.js new file mode 100644 index 0000000..29fe49c --- /dev/null +++ b/Chapter09/02_user_auth/app/data/user.js @@ -0,0 +1,127 @@ + +var async = require('async'), + bcrypt = require('bcrypt'), + db = require("./db.js"), + uuid = require('node-uuid'), + backhelp = require("./backend_helpers.js"); + + +exports.version = "0.1.0"; + +exports.user_by_uuid = function (uuid, callback) { + if (!uuid) + callback(backhelp.missing_data("uuid")); + else + user_by_field("user_uuid", uuid, callback); +}; + +exports.user_by_display_name = function (dn, callback) { + if (!dn) + callback(backhelp.missing_data("display_name")); + else + user_by_field("display_name", dn, callback); +} + +exports.user_by_email_address = function (email, callback) { + if (!email) + callback(backhelp.missing_data("email")); + else + user_by_field("email_address", email, callback); +}; + +exports.register = function (email, display_name, password, callback) { + var dbc; + var userid; + async.waterfall([ + // validate ze params + function (cb) { + if (!email || email.indexOf("@") == -1) + cb(backhelp.missing_data("email")); + else if (!display_name) + cb(backhelp.missing_data("display_name")); + else if (!password) + cb(backhelp.missing_data("password")); + else + cb(null); + }, + + // get a connection + function (cb) { + db.db(cb); + }, + + // generate a password hash + function (dbclient, cb) { + dbc = dbclient; + bcrypt.hash(password, 10, cb); + }, + + // register the account. + function (hash, cb) { + userid = uuid(); + var now = Math.round((new Date()).getTime() / 1000); + dbc.query( + "INSERT INTO Users VALUES (?, ?, ?, ?, ?, NULL, 0)", + [ userid, email.trim(), display_name.trim(), hash, now ], + cb); + }, + + // fetch and return the new user. + function (results, fields, cb) { + exports.user_by_uuid(userid, cb); + } + ], + function (err, user_data) { + if (dbc) dbc.end(); + if (err) { + if (err.code + && (err.code == 'ER_DUP_KEYNAME' + || err.code == 'ER_EXISTS' + || err.code == 'ER_DUP_ENTRY')) + callback(backhelp.user_already_registered()); + else + callback (err); + } else { + callback(null, user_data); + } + }); +}; + + + + +function user_by_field (field, value, callback) { + var dbc; + async.waterfall([ + // get a connection + function (cb) { + db.db(cb); + }, + + // fetch the user. + function (dbclient, cb) { + dbc = dbclient; + dbc.query( + "SELECT * FROM Users WHERE " + field + + " = ? AND deleted = false", + [ value ], + cb); + }, + + function (rows, fields, cb) { + if (!rows || rows.length == 0) + cb(backhelp.no_such_user()); + else + cb(null, rows[0]); + } + ], + function (err, user_data) { + if (dbc) dbc.end(); + if (err) { + callback (err); + } else { + console.log(user_data); + callback(null, user_data); + } + }); +} \ No newline at end of file diff --git a/Chapter09/02_user_auth/app/handlers/albums.js b/Chapter09/02_user_auth/app/handlers/albums.js new file mode 100644 index 0000000..ac2da86 --- /dev/null +++ b/Chapter09/02_user_auth/app/handlers/albums.js @@ -0,0 +1,259 @@ + +var helpers = require('./helpers.js'), + album_data = require("../data/album.js"), + async = require('async'), + fs = require('fs'); + +exports.version = "0.1.0"; + + +/** + * Album class. + */ +function Album (album_data) { + this.name = album_data.name; + this.date = album_data.date; + this.title = album_data.title; + this.description = album_data.description; + this._id = album_data._id; +} + +Album.prototype.name = null; +Album.prototype.date = null; +Album.prototype.title = null; +Album.prototype.description = null; + +Album.prototype.response_obj = function () { + return { name: this.name, + date: this.date, + title: this.title, + description: this.description }; +}; +Album.prototype.photos = function (pn, ps, callback) { + if (this.album_photos != undefined) { + callback(null, this.album_photos); + return; + } + + album_data.photos_for_album( + this.name, + pn, ps, + function (err, results) { + if (err) { + callback(err); + return; + } + + var out = []; + for (var i = 0; i < results.length; i++) { + out.push(new Photo(results[i])); + } + + this.album_photos = out; + callback(null, this.album_photos); + } + ); +}; +Album.prototype.add_photo = function (data, path, callback) { + album_data.add_photo(data, path, function (err, photo_data) { + if (err) + callback(err); + else { + var p = new Photo(photo_data); + if (this.all_photos) + this.all_photos.push(p); + else + this.app_photos = [ p ]; + + callback(null, p); + } + }); +}; + + + + +/** + * Photo class. + */ +function Photo (photo_data) { + this.filename = photo_data.filename; + this.date = photo_data.date; + this.albumid = photo_data.albumid; + this.description = photo_data.description; + this._id = photo_data._id; +} +Photo.prototype._id = null; +Photo.prototype.filename = null; +Photo.prototype.date = null; +Photo.prototype.albumid = null; +Photo.prototype.description = null; +Photo.prototype.response_obj = function() { + return { + filename: this.filename, + date: this.date, + albumid: this.albumid, + description: this.description + }; +}; + + +/** + * Album module methods. + */ +exports.create_album = function (req, res) { + async.waterfall([ + // make sure the albumid is valid + function (cb) { + if (!req.body || !req.body.name) { + cb(helpers.no_such_album()); + return; + } + + // UNDONE: we should add some code to make sure the album + // doesn't already exist! + cb(null); + }, + + function (cb) { + album_data.create_album(req.body, cb); + } + ], + function (err, results) { + if (err) { + helpers.send_failure(res, err); + } else { + var a = new Album(results); + helpers.send_success(res, {album: a.response_obj() }); + } + }); +}; + + +exports.album_by_name = function (req, res) { + async.waterfall([ + // get the album + function (cb) { + if (!req.params || !req.params.album_name) + cb(helpers.no_such_album()); + else + album_data.album_by_name(req.params.album_name, cb); + } + ], + function (err, results) { + if (err) { + helpers.send_failure(res, err); + } else if (!results) { + helpers.send_failure(res, helpers.no_such_album()); + } else { + var a = new Album(album_data); + helpers.send_success(res, { album: a.response_obj() }); + } + }); +}; + + + +exports.list_all = function (req, res) { + album_data.all_albums("date", true, 0, 25, function (err, results) { + if (err) { + helpers.send_failure(res, err); + } else { + var out = []; + if (results) { + for (var i = 0; i < results.length; i++) { + out.push(new Album(results[i]).response_obj()); + } + } + helpers.send_success(res, { albums: out }); + } + }); +}; + + +exports.photos_for_album = function(req, res) { + var page_num = req.query.page ? req.query.page : 0; + var page_size = req.query.page_size ? req.query.page_size : 1000; + + page_num = parseInt(page_num); + page_size = parseInt(page_size); + if (isNaN(page_num)) page_num = 0; + if (isNaN(page_size)) page_size = 1000; + + var album; + async.waterfall([ + function (cb) { + // first get the album. + if (!req.params || !req.params.album_name) + cb(helpers.no_such_album()); + else + album_data.album_by_name(req.params.album_name, cb); + }, + + function (album_data, cb) { + if (!album_data) { + cb(helpers.no_such_album()); + return; + } + album = new Album(album_data); + album.photos(page_num, page_size, cb); + }, + function (photos, cb) { + var out = []; + for (var i = 0; i < photos.length; i++) { + out.push(photos[i].response_obj()); + } + cb(null, out); + } + ], + function (err, results) { + if (err) { + helpers.send_failure(res, err); + return; + } + if (!results) results = []; + var out = { photos: results, + album_data: album.response_obj() }; + helpers.send_success(res, out); + }); +}; + + +exports.add_photo_to_album = function (req, res) { + var album; + async.waterfall([ + // make sure we have everything we need. + function (cb) { + if (!req.body) + cb(helpers.missing_data("POST data")); + else if (!req.files || !req.files.photo_file) + cb(helpers.missing_data("a file")); + else if (!helpers.is_image(req.files.photo_file.name)) + cb(helpers.not_image()); + else + // get the album + album_data.album_by_name(req.params.album_name, cb); + }, + + function (album_data, cb) { + if (!album_data) { + cb(helpers.no_such_album()); + return; + } + + album = new Album(album_data); + req.body.filename = req.files.photo_file.name; + album.add_photo(req.body, req.files.photo_file.path, cb); + } + ], + function (err, p) { + if (err) { + helpers.send_failure(res, err); + return; + } + var out = { photo: p.response_obj(), + album_data: album.response_obj() }; + helpers.send_success(res, out); + }); +}; + diff --git a/Chapter09/02_user_auth/app/handlers/helpers.js b/Chapter09/02_user_auth/app/handlers/helpers.js new file mode 100644 index 0000000..e6f0a13 --- /dev/null +++ b/Chapter09/02_user_auth/app/handlers/helpers.js @@ -0,0 +1,114 @@ + +var path = require('path'); + + +exports.version = '0.1.0'; + + + + +exports.send_success = function(res, data) { + res.writeHead(200, {"Content-Type": "application/json"}); + var output = { error: null, data: data }; + res.end(JSON.stringify(output) + "\n"); +} + + +exports.send_failure = function(res, err) { + console.log(err); + var code = (err.code) ? err.code : err.name; + res.writeHead(code, { "Content-Type" : "application/json" }); + res.end(JSON.stringify({ error: code, message: err.message }) + "\n"); +} + + +exports.error_for_resp = function (err) { + if (!err instanceof Error) { + console.error("** Unexpected error type! :" + + err.constructor.name); + return JSON.stringify(err); + } else { + var code = err.code ? err.code : err.name; + return JSON.stringify({ error: code, + message: err.message }); + } +} + +exports.error = function (code, message) { + var e = new Error(message); + e.code = code; + return e; +}; + +exports.file_error = function (err) { + return exports.error("file_error", JSON.stringify(err)); +}; + + +exports.is_image = function (filename) { + switch (path.extname(filename).toLowerCase()) { + case '.jpg': case '.jpeg': case '.png': case '.bmp': + case '.gif': case '.tif': case '.tiff': + return true; + } + + return false; +}; + + +exports.invalid_resource = function () { + return exports.error("invalid_resource", + "The requested resource does not exist."); +}; + + +exports.missing_data = function (what) { + return exports.error("missing_data", + "You must include " + what); +} + + +exports.not_image = function () { + return exports.error("not_image_file", + "The uploaded file must be an image file."); +}; + + +exports.no_such_album = function () { + return exports.error("no_such_album", + "The specified album does not exist"); +}; + + +exports.http_code_for_error = function (err) { + switch (err.message) { + case "no_such_album": + return 403; + case "invalid_resource": + return 404; + case "invalid_email_address": + return 403; + case "no_such_user": + return 403; + } + + console.log("*** Error needs HTTP response code: " + err.message); + return 503; +} + + +exports.valid_filename = function (fn) { + var re = /[^\.a-zA-Z0-9_-]/; + return typeof fn == 'string' && fn.length > 0 && !(fn.match(re)); +}; + + +exports.invalid_email_address = function () { + return exports.error("invalid_email_address", + "That's not a valid email address, sorry"); +}; + +exports.auth_failed = function () { + return exports.error("auth_failure", + "Invalid email address / password combination."); +}; \ No newline at end of file diff --git a/Chapter09/02_user_auth/app/handlers/pages.js b/Chapter09/02_user_auth/app/handlers/pages.js new file mode 100644 index 0000000..d80a263 --- /dev/null +++ b/Chapter09/02_user_auth/app/handlers/pages.js @@ -0,0 +1,37 @@ + +var helpers = require('./helpers.js'), + fs = require('fs'); + + +exports.version = "0.1.0"; + + +exports.generate = function (req, res) { + + var page = req.params.page_name; + if (req.params.sub_page && req.params.page_name == 'admin') + page = req.params.page_name + "_" + req.params.sub_page; + + fs.readFile( + 'basic.html', + function (err, contents) { + if (err) { + send_failure(res, 500, err); + return; + } + + contents = contents.toString('utf8'); + + // replace page name, and then dump to output. + contents = contents.replace('{{PAGE_NAME}}', page); + res.writeHead(200, { "Content-Type": "text/html" }); + res.end(contents); + } + ); +}; + +// if we made it here, then we're logged in. redirect to admin home +exports.login = function (req, res) { + res.redirect("/pages/admin/home"); + res.end(); +}; diff --git a/Chapter09/02_user_auth/app/handlers/users.js b/Chapter09/02_user_auth/app/handlers/users.js new file mode 100644 index 0000000..9668cdd --- /dev/null +++ b/Chapter09/02_user_auth/app/handlers/users.js @@ -0,0 +1,186 @@ +var helpers = require('./helpers.js'), + user_data = require("../data/user.js"), + async = require('async'), + bcrypt = require('bcrypt'), + fs = require('fs'); + +exports.version = "0.1.0"; + + +function User (user_data) { + this.uuid = user_data["user_uuid"]; + this.email_address = user_data["email_address"]; + this.display_name = user_data["display_name"]; + this.password = user_data["password"]; + this.first_seen_date = user_data["first_seen_date"]; + this.last_modified_date = user_data["last_modified_date"]; + this.deleted = user_data["deleted"]; +} + +User.prototype.uuid = null; +User.prototype.email_address = null; +User.prototype.display_name = null; +User.prototype.password = null; +User.prototype.first_seen_date = null; +User.prototype.last_modified_date = null; +User.prototype.deleted = false; +User.prototype.check_password = function (pw, callback) { + bcrypt.compare(pw, this.password, callback); +}; +User.prototype.response_obj = function () { + return { + uuid: this.uuid, + email_address: this.email_address, + display_name: this.display_name, + first_seen_date: this.first_seen_date, + last_modified_date: this.last_modified_date + }; +}; + + + +exports.register = function (req, res) { + async.waterfall([ + function (cb) { + var em = req.body.email_address; + if (!em || em.indexOf("@") == -1) + cb(helpers.invalid_email_address()); + else if (!req.body.display_name) + cb(helpers.missing_data("display_name")); + else if (!req.body.password) + cb(helpers.missing_data("password")); + else + cb(null); + }, + + // register da user. + function (cb) { + user_data.register( + req.body.email_address, + req.body.display_name, + req.body.password, + cb); + }, + + // mark user as logged in + function (user_data, cb) { + req.session.logged_in = true; + req.session.logged_in_display_name = req.body.display_name; + req.session.logged_in_date = new Date(); + cb(null, user_data); + } + ], + function (err, user_data) { + if (err) { + helpers.send_failure(res, err); + } else { + var u = new User(user_data); + helpers.send_success(res, {user: u.response_obj() }); + } + }); +}; + + +exports.login = function (req, res) { + var em = req.body.email_address + ? req.body.email_address.trim().toLowerCase() + : ""; + + async.waterfall([ + function (cb) { + if (!em) + cb(helpers.missing_data("email_address")); + else if (req.session + && req.session.logged_in_email_address == em) + cb(helpers.error("already_logged_in", "")); + else if (!req.body.password) + cb(helpers.missing_data("password")); + else + cb(null); + }, + + // first get the user by the email address. + function (cb) { + user_data.user_by_email_address(em, cb); + }, + + // check the password + function (user_data, cb) { + var u = new User(user_data); + u.check_password(req.body.password, cb); + }, + + function (auth_ok, cb) { + if (!auth_ok) { + cb(helpers.auth_failed()); + return; + } + + req.session.logged_in = true; + req.session.logged_in_email_address = req.body.email_address; + req.session.logged_in_date = new Date(); + cb(null); + } + ], + function (err, results) { + if (!err || err.message == "already_logged_in") { + helpers.send_success(res, { logged_in: true }); + } else { + helpers.send_failure(res, err); + } + }); +}; + + +exports.user_by_display_name = function (req, res) { + async.waterfall([ + // first get the user by the email address. + function (cb) { + user_data.user_by_display_name(req.body.email_address, cb); + } + ], + function (err, u) { + if (!err) { + helpers.send_success(res, { user: u.response_obj() }); + } else { + helpers.send_failure(res, err); + } + }); +}; + + +exports.authenticate_API = function (un, pw, callback) { + if (req.session && req.session.logged_in + && req.session.logged_in_email_address == un) { + callback(null, un); + return; + } + + async.waterfall([ + function (cb) { + user_data.user_by_email_address(un, cb); + }, + + function (user_data, cb) { + var u = new User(user_data); + u.check_password(pw, cb); + } + ], + function (err, results) { + if (!err) { + callback(null, un); + } else { + callback(new Error("bogus credentials")); + } + }); +}; + +exports.logged_in = function (req, res) { + var li = (req.session && req.session.logged_in_email_address); + helpers.send_success(res, { logged_in: li }); +}; + +exports.logout = function (req, res) { + req.session = null; + helpers.send_success(res, { logged_out: true }); +}; diff --git a/Chapter09/02_user_auth/app/local.config.js b/Chapter09/02_user_auth/app/local.config.js new file mode 100644 index 0000000..85e0a8d --- /dev/null +++ b/Chapter09/02_user_auth/app/local.config.js @@ -0,0 +1,16 @@ + + +exports.config = { + db_config: { + host: "localhost", + user: "root", + password: "", + database: "PhotoAlbums", + + pooled_connections: 125, + idle_timeout_millis: 30000 + }, + + static_content: "../static/" +}; + diff --git a/Chapter09/02_user_auth/app/package.json b/Chapter09/02_user_auth/app/package.json new file mode 100644 index 0000000..dddffd9 --- /dev/null +++ b/Chapter09/02_user_auth/app/package.json @@ -0,0 +1,13 @@ +{ + "name": "MySQL-Demo", + "description": "Demonstrates Using MySQL Database connectivity", + "version": "0.0.1", + "private": true, + "dependencies": { + "express": "3.x", + "async": "0.1.x", + "mysql": "2.x", + "bcrypt": "0.x", + "node-uuid": "1.x" + } +} diff --git a/Chapter09/02_user_auth/app/server.js b/Chapter09/02_user_auth/app/server.js new file mode 100644 index 0000000..6f20cb3 --- /dev/null +++ b/Chapter09/02_user_auth/app/server.js @@ -0,0 +1,68 @@ + +var express = require('express'); +var app = express(); + +var db = require('./data/db.js'), + album_hdlr = require('./handlers/albums.js'), + page_hdlr = require('./handlers/pages.js'), + user_hdlr = require('./handlers/users.js'), + helpers = require('./handlers/helpers.js'); + +app.use(express.logger('dev')); +app.use(express.bodyParser({ keepExtensions: true })); +app.use(express.static(__dirname + "/../static")); +app.use(express.cookieParser()); +app.use(express.cookieSession({ + secret: "FLUFFY BUNNIES", + maxAge: 86400000, + store: new express.session.MemoryStore() +})); + +/** + * API Server requests. + */ +app.get('/v1/albums.json', album_hdlr.list_all); +app.get('/v1/albums/:album_name.json', album_hdlr.album_by_name); +app.put('/v1/albums.json', album_hdlr.create_album); + +app.get('/v1/albums/:album_name/photos.json', album_hdlr.photos_for_album); +app.put('/v1/albums/:album_name/photos.json', album_hdlr.add_photo_to_album); + +app.put('/v1/users.json', user_hdlr.register); + + +/** + * add-on requests we support for the purposes of the web interface + * to the server. + */ +app.get('/pages/:page_name', requirePageLogin, page_hdlr.generate); +app.get('/pages/:page_name/:sub_page', requirePageLogin, page_hdlr.generate); +app.post('/service/login', user_hdlr.login); + + +app.get("/", function (req, res) { + res.redirect("/pages/home"); + res.end(); +}); + +app.get('*', four_oh_four); + +function four_oh_four(req, res) { + res.writeHead(404, { "Content-Type" : "application/json" }); + res.end(JSON.stringify(helpers.invalid_resource()) + "\n"); +} + +function requirePageLogin(req, res, next) { + if (req.params && req.params.page_name == 'admin') { + if (req.session && req.session.logged_in) { + next(); + } else { + res.redirect("/pages/login"); + } + } else + next(); +} + +app.listen(8080); + + diff --git a/Chapter09/02_user_auth/schema.sql b/Chapter09/02_user_auth/schema.sql new file mode 100644 index 0000000..61ab5c3 --- /dev/null +++ b/Chapter09/02_user_auth/schema.sql @@ -0,0 +1,53 @@ +DROP DATABASE IF EXISTS PhotoAlbums; + + +CREATE DATABASE PhotoAlbums + DEFAULT CHARACTER SET utf8 + DEFAULT COLLATE utf8_general_ci; + +USE PhotoAlbums; + + +CREATE TABLE Albums +( + name VARCHAR(50) UNIQUE PRIMARY KEY, + title VARCHAR(100), + date DATETIME, + description VARCHAR(500), + + -- allow for sorting on date. + INDEX(date) +) +ENGINE = InnoDB; + +CREATE TABLE Photos +( + album_name VARCHAR(50), + filename VARCHAR(50), + description VARCHAR(500), + date DATETIME, + + FOREIGN KEY (album_name) REFERENCES Albums (name), + INDEX (album_name, date) +) +ENGINE = InnoDB; + + +CREATE TABLE Users +( + user_uuid VARCHAR(50) UNIQUE PRIMARY KEY, + email_address VARCHAR(150) UNIQUE, + + display_name VARCHAR(100) UNIQUE, + password VARCHAR(100), + + first_seen_date BIGINT, + last_modified_date BIGINT, + deleted BOOL DEFAULT false, + + INDEX(email_address, deleted), + INDEX(user_uuid, deleted) +) +ENGINE = InnoDB; + + diff --git a/Chapter09/02_user_auth/static/albums/australia2010/aus_01.jpg b/Chapter09/02_user_auth/static/albums/australia2010/aus_01.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter09/02_user_auth/static/albums/australia2010/aus_02.jpg b/Chapter09/02_user_auth/static/albums/australia2010/aus_02.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter09/02_user_auth/static/albums/australia2010/aus_03.jpg b/Chapter09/02_user_auth/static/albums/australia2010/aus_03.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter09/02_user_auth/static/albums/australia2010/aus_04.jpg b/Chapter09/02_user_auth/static/albums/australia2010/aus_04.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter09/02_user_auth/static/albums/australia2010/aus_05.jpg b/Chapter09/02_user_auth/static/albums/australia2010/aus_05.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter09/02_user_auth/static/albums/australia2010/aus_06.jpg b/Chapter09/02_user_auth/static/albums/australia2010/aus_06.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter09/02_user_auth/static/albums/australia2010/aus_07.jpg b/Chapter09/02_user_auth/static/albums/australia2010/aus_07.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter09/02_user_auth/static/albums/australia2010/aus_08.jpg b/Chapter09/02_user_auth/static/albums/australia2010/aus_08.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter09/02_user_auth/static/albums/australia2010/aus_09.jpg b/Chapter09/02_user_auth/static/albums/australia2010/aus_09.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter09/02_user_auth/static/albums/italy2012/picture_01.jpg b/Chapter09/02_user_auth/static/albums/italy2012/picture_01.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter09/02_user_auth/static/albums/italy2012/picture_02.jpg b/Chapter09/02_user_auth/static/albums/italy2012/picture_02.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter09/02_user_auth/static/albums/italy2012/picture_03.jpg b/Chapter09/02_user_auth/static/albums/italy2012/picture_03.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter09/02_user_auth/static/albums/italy2012/picture_04.jpg b/Chapter09/02_user_auth/static/albums/italy2012/picture_04.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter09/02_user_auth/static/albums/italy2012/picture_05.jpg b/Chapter09/02_user_auth/static/albums/italy2012/picture_05.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter09/02_user_auth/static/albums/japan2010/picture_001.jpg b/Chapter09/02_user_auth/static/albums/japan2010/picture_001.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter09/02_user_auth/static/albums/japan2010/picture_002.jpg b/Chapter09/02_user_auth/static/albums/japan2010/picture_002.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter09/02_user_auth/static/albums/japan2010/picture_003.jpg b/Chapter09/02_user_auth/static/albums/japan2010/picture_003.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter09/02_user_auth/static/albums/japan2010/picture_004.jpg b/Chapter09/02_user_auth/static/albums/japan2010/picture_004.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter09/02_user_auth/static/albums/japan2010/picture_005.jpg b/Chapter09/02_user_auth/static/albums/japan2010/picture_005.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter09/02_user_auth/static/albums/japan2010/picture_006.jpg b/Chapter09/02_user_auth/static/albums/japan2010/picture_006.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter09/02_user_auth/static/albums/japan2010/picture_007.jpg b/Chapter09/02_user_auth/static/albums/japan2010/picture_007.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter09/02_user_auth/static/content/#album.js# b/Chapter09/02_user_auth/static/content/#album.js# new file mode 100644 index 0000000..442c047 --- /dev/null +++ b/Chapter09/02_user_auth/static/content/#album.js# @@ -0,0 +1,60 @@ +$(function(){ + + var tmpl, // Main template HTML + tdata = {}; // JSON data object that feeds the template + + // Initialise page + var initPage = function() { + + // get our album name. + var re = "/pages/album/([a-zA-Z0-9_-]+)"; + var results = new RegExp(re).exec(window.location.href); + var album_name = results[1]; + + // Load the HTML template + $.get("/templates/album.html", function(d){ + tmpl = d; + }); + + var p = $.urlParam("page"); + var ps = $.urlParam("page_size"); + if (p < 0) p = 0; + if (ps <= 0) ps = 1000; + + var qs = "?page=" + p + "&page_size=" + ps; + var url = "/v1/albums/" + album_name + "/photos.json" + qs; + + // Retrieve the server data and then initialise the page + $.getJSON(url, function (d) { + var photo_d = massage_album(d); + $.extend(tdata, photo_d); + }); + + // When AJAX calls are complete parse the template + // replacing mustache tags with vars + $(document).ajaxStop(function () { + var renderedPage = Mustache.to_html( tmpl, tdata ); + $("body").html( renderedPage ); + }) + }(); +}); + + +function massage_album(d) { + if (d.error != null) return d; + var obj = { photos: [] }; + + var p = d.data.photos; + var a = d.data.album_data; + + for (var i = 0; i < p.length; i++) { + var url = "/albums/" + a.name + "/" + p[i].filename; + obj.photos.push({ url: url, desc: p[i].description }); + } + + if (obj.photos.length > 0) obj.has_photos = obj.photos.length; + return obj; +} + + +xundo \ No newline at end of file diff --git a/Chapter09/02_user_auth/static/content/admin_add_album.js b/Chapter09/02_user_auth/static/content/admin_add_album.js new file mode 100644 index 0000000..f2987d6 --- /dev/null +++ b/Chapter09/02_user_auth/static/content/admin_add_album.js @@ -0,0 +1,22 @@ +$(function(){ + + var tmpl, // Main template HTML + tdata = {}; // JSON data object that feeds the template + + // Initialise page + var initPage = function() { + + // Load the HTML template + $.get("/templates/admin_add_album.html", function(d){ + tmpl = d; + }); + + // When AJAX calls are complete parse the template + // replacing mustache tags with vars + $(document).ajaxStop(function () { + var renderedPage = Mustache.to_html( tmpl, tdata ); + $("body").html( renderedPage ); + }) + }(); +}); + diff --git a/Chapter09/02_user_auth/static/content/admin_add_photos.js b/Chapter09/02_user_auth/static/content/admin_add_photos.js new file mode 100644 index 0000000..350e536 --- /dev/null +++ b/Chapter09/02_user_auth/static/content/admin_add_photos.js @@ -0,0 +1,27 @@ +$(function(){ + + var tmpl, // Main template HTML + tdata = {}; // JSON data object that feeds the template + + // Initialise page + var initPage = function() { + + // Load the HTML template + $.get("/templates/admin_add_photos.html", function(d){ + tmpl = d; + }); + + // Retrieve the server data and then initialise the page + $.getJSON("/v1/albums.json", function (d) { + $.extend(tdata, d.data); + }); + + // When AJAX calls are complete parse the template + // replacing mustache tags with vars + $(document).ajaxStop(function () { + var renderedPage = Mustache.to_html( tmpl, tdata ); + $("body").html( renderedPage ); + }) + }(); +}); + diff --git a/Chapter09/02_user_auth/static/content/admin_home.js b/Chapter09/02_user_auth/static/content/admin_home.js new file mode 100644 index 0000000..820f7fd --- /dev/null +++ b/Chapter09/02_user_auth/static/content/admin_home.js @@ -0,0 +1,22 @@ +$(function(){ + + var tmpl, // Main template HTML + tdata = {}; // JSON data object that feeds the template + + // Initialise page + var initPage = function() { + + // Load the HTML template + $.get("/templates/admin_home.html", function(d){ + tmpl = d; + }); + + // When AJAX calls are complete parse the template + // replacing mustache tags with vars + $(document).ajaxStop(function () { + var renderedPage = Mustache.to_html( tmpl, tdata ); + $("body").html( renderedPage ); + }) + }(); +}); + diff --git a/Chapter09/02_user_auth/static/content/album.js b/Chapter09/02_user_auth/static/content/album.js new file mode 100644 index 0000000..c4d918e --- /dev/null +++ b/Chapter09/02_user_auth/static/content/album.js @@ -0,0 +1,67 @@ +$(function(){ + + var tmpl, // Main template HTML + tdata = {}; // JSON data object that feeds the template + + // Initialise page + var initPage = function() { + + // get our album name. + var re = "/pages/album/([a-zA-Z0-9_-]+)"; + var results = new RegExp(re).exec(window.location.href); + var album_name = results[1]; + + // Load the HTML template + $.get("/templates/album.html", function(d){ + tmpl = d; + }); + + var p = $.urlParam("page"); + var ps = $.urlParam("page_size"); + if (p < 0) p = 0; + if (ps <= 0) ps = 1000; + + var qs = "?page=" + p + "&page_size=" + ps; + var url = "/v1/albums/" + album_name + "/photos.json" + qs; + + // Retrieve the server data and then initialise the page + $.getJSON(url, function (d) { + var photo_d = massage_album(d); + $.extend(tdata, photo_d); + }); + + // When AJAX calls are complete parse the template + // replacing mustache tags with vars + $(document).ajaxStop(function () { + var renderedPage = Mustache.to_html( tmpl, tdata ); + $("body").html( renderedPage ); + }) + }(); +}); + + +function massage_album(d) { + if (d.error != null) return d; + var obj = { photos: [] }; + + var p = d.data.photos; + var a = d.data.album_data; + + for (var i = 0; i < p.length; i++) { + var url = "/albums/" + a.name + "/" + p[i].filename; + obj.photos.push({ url: url, desc: p[i].description }); + } + + if (obj.photos.length > 0) obj.has_photos = obj.photos.length; + return obj; +} + + +$.urlParam = function(name){ + var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href); + if (!results) + { + return 0; + } + return results[1] || 0; +} \ No newline at end of file diff --git a/Chapter09/02_user_auth/static/content/home.js b/Chapter09/02_user_auth/static/content/home.js new file mode 100644 index 0000000..fa7010b --- /dev/null +++ b/Chapter09/02_user_auth/static/content/home.js @@ -0,0 +1,28 @@ +$(function(){ + + var tmpl, // Main template HTML + tdata = {}; // JSON data object that feeds the template + + // Initialise page + var initPage = function() { + + // Load the HTML template + $.get("/templates/home.html", function(d){ + tmpl = d; + }); + + + // Retrieve the server data and then initialise the page + $.getJSON("/v1/albums.json", function (d) { + $.extend(tdata, d.data); + }); + + // When AJAX calls are complete parse the template + // replacing mustache tags with vars + $(document).ajaxStop(function () { + var renderedPage = Mustache.to_html( tmpl, tdata ); + $("body").html( renderedPage ); + }) + }(); +}); + diff --git a/Chapter09/02_user_auth/static/content/jquery-1.8.3.min.js b/Chapter09/02_user_auth/static/content/jquery-1.8.3.min.js new file mode 100644 index 0000000..83589da --- /dev/null +++ b/Chapter09/02_user_auth/static/content/jquery-1.8.3.min.js @@ -0,0 +1,2 @@ +/*! jQuery v1.8.3 jquery.com | jquery.org/license */ +(function(e,t){function _(e){var t=M[e]={};return v.each(e.split(y),function(e,n){t[n]=!0}),t}function H(e,n,r){if(r===t&&e.nodeType===1){var i="data-"+n.replace(P,"-$1").toLowerCase();r=e.getAttribute(i);if(typeof r=="string"){try{r=r==="true"?!0:r==="false"?!1:r==="null"?null:+r+""===r?+r:D.test(r)?v.parseJSON(r):r}catch(s){}v.data(e,n,r)}else r=t}return r}function B(e){var t;for(t in e){if(t==="data"&&v.isEmptyObject(e[t]))continue;if(t!=="toJSON")return!1}return!0}function et(){return!1}function tt(){return!0}function ut(e){return!e||!e.parentNode||e.parentNode.nodeType===11}function at(e,t){do e=e[t];while(e&&e.nodeType!==1);return e}function ft(e,t,n){t=t||0;if(v.isFunction(t))return v.grep(e,function(e,r){var i=!!t.call(e,r,e);return i===n});if(t.nodeType)return v.grep(e,function(e,r){return e===t===n});if(typeof t=="string"){var r=v.grep(e,function(e){return e.nodeType===1});if(it.test(t))return v.filter(t,r,!n);t=v.filter(t,r)}return v.grep(e,function(e,r){return v.inArray(e,t)>=0===n})}function lt(e){var t=ct.split("|"),n=e.createDocumentFragment();if(n.createElement)while(t.length)n.createElement(t.pop());return n}function Lt(e,t){return e.getElementsByTagName(t)[0]||e.appendChild(e.ownerDocument.createElement(t))}function At(e,t){if(t.nodeType!==1||!v.hasData(e))return;var n,r,i,s=v._data(e),o=v._data(t,s),u=s.events;if(u){delete o.handle,o.events={};for(n in u)for(r=0,i=u[n].length;r").appendTo(i.body),n=t.css("display");t.remove();if(n==="none"||n===""){Pt=i.body.appendChild(Pt||v.extend(i.createElement("iframe"),{frameBorder:0,width:0,height:0}));if(!Ht||!Pt.createElement)Ht=(Pt.contentWindow||Pt.contentDocument).document,Ht.write(""),Ht.close();t=Ht.body.appendChild(Ht.createElement(e)),n=Dt(t,"display"),i.body.removeChild(Pt)}return Wt[e]=n,n}function fn(e,t,n,r){var i;if(v.isArray(t))v.each(t,function(t,i){n||sn.test(e)?r(e,i):fn(e+"["+(typeof i=="object"?t:"")+"]",i,n,r)});else if(!n&&v.type(t)==="object")for(i in t)fn(e+"["+i+"]",t[i],n,r);else r(e,t)}function Cn(e){return function(t,n){typeof t!="string"&&(n=t,t="*");var r,i,s,o=t.toLowerCase().split(y),u=0,a=o.length;if(v.isFunction(n))for(;u)[^>]*$|#([\w\-]*)$)/,E=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,S=/^[\],:{}\s]*$/,x=/(?:^|:|,)(?:\s*\[)+/g,T=/\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,N=/"[^"\\\r\n]*"|true|false|null|-?(?:\d\d*\.|)\d+(?:[eE][\-+]?\d+|)/g,C=/^-ms-/,k=/-([\da-z])/gi,L=function(e,t){return(t+"").toUpperCase()},A=function(){i.addEventListener?(i.removeEventListener("DOMContentLoaded",A,!1),v.ready()):i.readyState==="complete"&&(i.detachEvent("onreadystatechange",A),v.ready())},O={};v.fn=v.prototype={constructor:v,init:function(e,n,r){var s,o,u,a;if(!e)return this;if(e.nodeType)return this.context=this[0]=e,this.length=1,this;if(typeof e=="string"){e.charAt(0)==="<"&&e.charAt(e.length-1)===">"&&e.length>=3?s=[null,e,null]:s=w.exec(e);if(s&&(s[1]||!n)){if(s[1])return n=n instanceof v?n[0]:n,a=n&&n.nodeType?n.ownerDocument||n:i,e=v.parseHTML(s[1],a,!0),E.test(s[1])&&v.isPlainObject(n)&&this.attr.call(e,n,!0),v.merge(this,e);o=i.getElementById(s[2]);if(o&&o.parentNode){if(o.id!==s[2])return r.find(e);this.length=1,this[0]=o}return this.context=i,this.selector=e,this}return!n||n.jquery?(n||r).find(e):this.constructor(n).find(e)}return v.isFunction(e)?r.ready(e):(e.selector!==t&&(this.selector=e.selector,this.context=e.context),v.makeArray(e,this))},selector:"",jquery:"1.8.3",length:0,size:function(){return this.length},toArray:function(){return l.call(this)},get:function(e){return e==null?this.toArray():e<0?this[this.length+e]:this[e]},pushStack:function(e,t,n){var r=v.merge(this.constructor(),e);return r.prevObject=this,r.context=this.context,t==="find"?r.selector=this.selector+(this.selector?" ":"")+n:t&&(r.selector=this.selector+"."+t+"("+n+")"),r},each:function(e,t){return v.each(this,e,t)},ready:function(e){return v.ready.promise().done(e),this},eq:function(e){return e=+e,e===-1?this.slice(e):this.slice(e,e+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(l.apply(this,arguments),"slice",l.call(arguments).join(","))},map:function(e){return this.pushStack(v.map(this,function(t,n){return e.call(t,n,t)}))},end:function(){return this.prevObject||this.constructor(null)},push:f,sort:[].sort,splice:[].splice},v.fn.init.prototype=v.fn,v.extend=v.fn.extend=function(){var e,n,r,i,s,o,u=arguments[0]||{},a=1,f=arguments.length,l=!1;typeof u=="boolean"&&(l=u,u=arguments[1]||{},a=2),typeof u!="object"&&!v.isFunction(u)&&(u={}),f===a&&(u=this,--a);for(;a0)return;r.resolveWith(i,[v]),v.fn.trigger&&v(i).trigger("ready").off("ready")},isFunction:function(e){return v.type(e)==="function"},isArray:Array.isArray||function(e){return v.type(e)==="array"},isWindow:function(e){return e!=null&&e==e.window},isNumeric:function(e){return!isNaN(parseFloat(e))&&isFinite(e)},type:function(e){return e==null?String(e):O[h.call(e)]||"object"},isPlainObject:function(e){if(!e||v.type(e)!=="object"||e.nodeType||v.isWindow(e))return!1;try{if(e.constructor&&!p.call(e,"constructor")&&!p.call(e.constructor.prototype,"isPrototypeOf"))return!1}catch(n){return!1}var r;for(r in e);return r===t||p.call(e,r)},isEmptyObject:function(e){var t;for(t in e)return!1;return!0},error:function(e){throw new Error(e)},parseHTML:function(e,t,n){var r;return!e||typeof e!="string"?null:(typeof t=="boolean"&&(n=t,t=0),t=t||i,(r=E.exec(e))?[t.createElement(r[1])]:(r=v.buildFragment([e],t,n?null:[]),v.merge([],(r.cacheable?v.clone(r.fragment):r.fragment).childNodes)))},parseJSON:function(t){if(!t||typeof t!="string")return null;t=v.trim(t);if(e.JSON&&e.JSON.parse)return e.JSON.parse(t);if(S.test(t.replace(T,"@").replace(N,"]").replace(x,"")))return(new Function("return "+t))();v.error("Invalid JSON: "+t)},parseXML:function(n){var r,i;if(!n||typeof n!="string")return null;try{e.DOMParser?(i=new DOMParser,r=i.parseFromString(n,"text/xml")):(r=new ActiveXObject("Microsoft.XMLDOM"),r.async="false",r.loadXML(n))}catch(s){r=t}return(!r||!r.documentElement||r.getElementsByTagName("parsererror").length)&&v.error("Invalid XML: "+n),r},noop:function(){},globalEval:function(t){t&&g.test(t)&&(e.execScript||function(t){e.eval.call(e,t)})(t)},camelCase:function(e){return e.replace(C,"ms-").replace(k,L)},nodeName:function(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()},each:function(e,n,r){var i,s=0,o=e.length,u=o===t||v.isFunction(e);if(r){if(u){for(i in e)if(n.apply(e[i],r)===!1)break}else for(;s0&&e[0]&&e[a-1]||a===0||v.isArray(e));if(f)for(;u-1)a.splice(n,1),i&&(n<=o&&o--,n<=u&&u--)}),this},has:function(e){return v.inArray(e,a)>-1},empty:function(){return a=[],this},disable:function(){return a=f=n=t,this},disabled:function(){return!a},lock:function(){return f=t,n||c.disable(),this},locked:function(){return!f},fireWith:function(e,t){return t=t||[],t=[e,t.slice?t.slice():t],a&&(!r||f)&&(i?f.push(t):l(t)),this},fire:function(){return c.fireWith(this,arguments),this},fired:function(){return!!r}};return c},v.extend({Deferred:function(e){var t=[["resolve","done",v.Callbacks("once memory"),"resolved"],["reject","fail",v.Callbacks("once memory"),"rejected"],["notify","progress",v.Callbacks("memory")]],n="pending",r={state:function(){return n},always:function(){return i.done(arguments).fail(arguments),this},then:function(){var e=arguments;return v.Deferred(function(n){v.each(t,function(t,r){var s=r[0],o=e[t];i[r[1]](v.isFunction(o)?function(){var e=o.apply(this,arguments);e&&v.isFunction(e.promise)?e.promise().done(n.resolve).fail(n.reject).progress(n.notify):n[s+"With"](this===i?n:this,[e])}:n[s])}),e=null}).promise()},promise:function(e){return e!=null?v.extend(e,r):r}},i={};return r.pipe=r.then,v.each(t,function(e,s){var o=s[2],u=s[3];r[s[1]]=o.add,u&&o.add(function(){n=u},t[e^1][2].disable,t[2][2].lock),i[s[0]]=o.fire,i[s[0]+"With"]=o.fireWith}),r.promise(i),e&&e.call(i,i),i},when:function(e){var t=0,n=l.call(arguments),r=n.length,i=r!==1||e&&v.isFunction(e.promise)?r:0,s=i===1?e:v.Deferred(),o=function(e,t,n){return function(r){t[e]=this,n[e]=arguments.length>1?l.call(arguments):r,n===u?s.notifyWith(t,n):--i||s.resolveWith(t,n)}},u,a,f;if(r>1){u=new Array(r),a=new Array(r),f=new Array(r);for(;t
a",n=p.getElementsByTagName("*"),r=p.getElementsByTagName("a")[0];if(!n||!r||!n.length)return{};s=i.createElement("select"),o=s.appendChild(i.createElement("option")),u=p.getElementsByTagName("input")[0],r.style.cssText="top:1px;float:left;opacity:.5",t={leadingWhitespace:p.firstChild.nodeType===3,tbody:!p.getElementsByTagName("tbody").length,htmlSerialize:!!p.getElementsByTagName("link").length,style:/top/.test(r.getAttribute("style")),hrefNormalized:r.getAttribute("href")==="/a",opacity:/^0.5/.test(r.style.opacity),cssFloat:!!r.style.cssFloat,checkOn:u.value==="on",optSelected:o.selected,getSetAttribute:p.className!=="t",enctype:!!i.createElement("form").enctype,html5Clone:i.createElement("nav").cloneNode(!0).outerHTML!=="<:nav>",boxModel:i.compatMode==="CSS1Compat",submitBubbles:!0,changeBubbles:!0,focusinBubbles:!1,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0,boxSizingReliable:!0,pixelPosition:!1},u.checked=!0,t.noCloneChecked=u.cloneNode(!0).checked,s.disabled=!0,t.optDisabled=!o.disabled;try{delete p.test}catch(d){t.deleteExpando=!1}!p.addEventListener&&p.attachEvent&&p.fireEvent&&(p.attachEvent("onclick",h=function(){t.noCloneEvent=!1}),p.cloneNode(!0).fireEvent("onclick"),p.detachEvent("onclick",h)),u=i.createElement("input"),u.value="t",u.setAttribute("type","radio"),t.radioValue=u.value==="t",u.setAttribute("checked","checked"),u.setAttribute("name","t"),p.appendChild(u),a=i.createDocumentFragment(),a.appendChild(p.lastChild),t.checkClone=a.cloneNode(!0).cloneNode(!0).lastChild.checked,t.appendChecked=u.checked,a.removeChild(u),a.appendChild(p);if(p.attachEvent)for(l in{submit:!0,change:!0,focusin:!0})f="on"+l,c=f in p,c||(p.setAttribute(f,"return;"),c=typeof p[f]=="function"),t[l+"Bubbles"]=c;return v(function(){var n,r,s,o,u="padding:0;margin:0;border:0;display:block;overflow:hidden;",a=i.getElementsByTagName("body")[0];if(!a)return;n=i.createElement("div"),n.style.cssText="visibility:hidden;border:0;width:0;height:0;position:static;top:0;margin-top:1px",a.insertBefore(n,a.firstChild),r=i.createElement("div"),n.appendChild(r),r.innerHTML="
t
",s=r.getElementsByTagName("td"),s[0].style.cssText="padding:0;margin:0;border:0;display:none",c=s[0].offsetHeight===0,s[0].style.display="",s[1].style.display="none",t.reliableHiddenOffsets=c&&s[0].offsetHeight===0,r.innerHTML="",r.style.cssText="box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;",t.boxSizing=r.offsetWidth===4,t.doesNotIncludeMarginInBodyOffset=a.offsetTop!==1,e.getComputedStyle&&(t.pixelPosition=(e.getComputedStyle(r,null)||{}).top!=="1%",t.boxSizingReliable=(e.getComputedStyle(r,null)||{width:"4px"}).width==="4px",o=i.createElement("div"),o.style.cssText=r.style.cssText=u,o.style.marginRight=o.style.width="0",r.style.width="1px",r.appendChild(o),t.reliableMarginRight=!parseFloat((e.getComputedStyle(o,null)||{}).marginRight)),typeof r.style.zoom!="undefined"&&(r.innerHTML="",r.style.cssText=u+"width:1px;padding:1px;display:inline;zoom:1",t.inlineBlockNeedsLayout=r.offsetWidth===3,r.style.display="block",r.style.overflow="visible",r.innerHTML="
",r.firstChild.style.width="5px",t.shrinkWrapBlocks=r.offsetWidth!==3,n.style.zoom=1),a.removeChild(n),n=r=s=o=null}),a.removeChild(p),n=r=s=o=u=a=p=null,t}();var D=/(?:\{[\s\S]*\}|\[[\s\S]*\])$/,P=/([A-Z])/g;v.extend({cache:{},deletedIds:[],uuid:0,expando:"jQuery"+(v.fn.jquery+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(e){return e=e.nodeType?v.cache[e[v.expando]]:e[v.expando],!!e&&!B(e)},data:function(e,n,r,i){if(!v.acceptData(e))return;var s,o,u=v.expando,a=typeof n=="string",f=e.nodeType,l=f?v.cache:e,c=f?e[u]:e[u]&&u;if((!c||!l[c]||!i&&!l[c].data)&&a&&r===t)return;c||(f?e[u]=c=v.deletedIds.pop()||v.guid++:c=u),l[c]||(l[c]={},f||(l[c].toJSON=v.noop));if(typeof n=="object"||typeof n=="function")i?l[c]=v.extend(l[c],n):l[c].data=v.extend(l[c].data,n);return s=l[c],i||(s.data||(s.data={}),s=s.data),r!==t&&(s[v.camelCase(n)]=r),a?(o=s[n],o==null&&(o=s[v.camelCase(n)])):o=s,o},removeData:function(e,t,n){if(!v.acceptData(e))return;var r,i,s,o=e.nodeType,u=o?v.cache:e,a=o?e[v.expando]:v.expando;if(!u[a])return;if(t){r=n?u[a]:u[a].data;if(r){v.isArray(t)||(t in r?t=[t]:(t=v.camelCase(t),t in r?t=[t]:t=t.split(" ")));for(i=0,s=t.length;i1,null,!1))},removeData:function(e){return this.each(function(){v.removeData(this,e)})}}),v.extend({queue:function(e,t,n){var r;if(e)return t=(t||"fx")+"queue",r=v._data(e,t),n&&(!r||v.isArray(n)?r=v._data(e,t,v.makeArray(n)):r.push(n)),r||[]},dequeue:function(e,t){t=t||"fx";var n=v.queue(e,t),r=n.length,i=n.shift(),s=v._queueHooks(e,t),o=function(){v.dequeue(e,t)};i==="inprogress"&&(i=n.shift(),r--),i&&(t==="fx"&&n.unshift("inprogress"),delete s.stop,i.call(e,o,s)),!r&&s&&s.empty.fire()},_queueHooks:function(e,t){var n=t+"queueHooks";return v._data(e,n)||v._data(e,n,{empty:v.Callbacks("once memory").add(function(){v.removeData(e,t+"queue",!0),v.removeData(e,n,!0)})})}}),v.fn.extend({queue:function(e,n){var r=2;return typeof e!="string"&&(n=e,e="fx",r--),arguments.length1)},removeAttr:function(e){return this.each(function(){v.removeAttr(this,e)})},prop:function(e,t){return v.access(this,v.prop,e,t,arguments.length>1)},removeProp:function(e){return e=v.propFix[e]||e,this.each(function(){try{this[e]=t,delete this[e]}catch(n){}})},addClass:function(e){var t,n,r,i,s,o,u;if(v.isFunction(e))return this.each(function(t){v(this).addClass(e.call(this,t,this.className))});if(e&&typeof e=="string"){t=e.split(y);for(n=0,r=this.length;n=0)r=r.replace(" "+n[s]+" "," ");i.className=e?v.trim(r):""}}}return this},toggleClass:function(e,t){var n=typeof e,r=typeof t=="boolean";return v.isFunction(e)?this.each(function(n){v(this).toggleClass(e.call(this,n,this.className,t),t)}):this.each(function(){if(n==="string"){var i,s=0,o=v(this),u=t,a=e.split(y);while(i=a[s++])u=r?u:!o.hasClass(i),o[u?"addClass":"removeClass"](i)}else if(n==="undefined"||n==="boolean")this.className&&v._data(this,"__className__",this.className),this.className=this.className||e===!1?"":v._data(this,"__className__")||""})},hasClass:function(e){var t=" "+e+" ",n=0,r=this.length;for(;n=0)return!0;return!1},val:function(e){var n,r,i,s=this[0];if(!arguments.length){if(s)return n=v.valHooks[s.type]||v.valHooks[s.nodeName.toLowerCase()],n&&"get"in n&&(r=n.get(s,"value"))!==t?r:(r=s.value,typeof r=="string"?r.replace(R,""):r==null?"":r);return}return i=v.isFunction(e),this.each(function(r){var s,o=v(this);if(this.nodeType!==1)return;i?s=e.call(this,r,o.val()):s=e,s==null?s="":typeof s=="number"?s+="":v.isArray(s)&&(s=v.map(s,function(e){return e==null?"":e+""})),n=v.valHooks[this.type]||v.valHooks[this.nodeName.toLowerCase()];if(!n||!("set"in n)||n.set(this,s,"value")===t)this.value=s})}}),v.extend({valHooks:{option:{get:function(e){var t=e.attributes.value;return!t||t.specified?e.value:e.text}},select:{get:function(e){var t,n,r=e.options,i=e.selectedIndex,s=e.type==="select-one"||i<0,o=s?null:[],u=s?i+1:r.length,a=i<0?u:s?i:0;for(;a=0}),n.length||(e.selectedIndex=-1),n}}},attrFn:{},attr:function(e,n,r,i){var s,o,u,a=e.nodeType;if(!e||a===3||a===8||a===2)return;if(i&&v.isFunction(v.fn[n]))return v(e)[n](r);if(typeof e.getAttribute=="undefined")return v.prop(e,n,r);u=a!==1||!v.isXMLDoc(e),u&&(n=n.toLowerCase(),o=v.attrHooks[n]||(X.test(n)?F:j));if(r!==t){if(r===null){v.removeAttr(e,n);return}return o&&"set"in o&&u&&(s=o.set(e,r,n))!==t?s:(e.setAttribute(n,r+""),r)}return o&&"get"in o&&u&&(s=o.get(e,n))!==null?s:(s=e.getAttribute(n),s===null?t:s)},removeAttr:function(e,t){var n,r,i,s,o=0;if(t&&e.nodeType===1){r=t.split(y);for(;o=0}})});var $=/^(?:textarea|input|select)$/i,J=/^([^\.]*|)(?:\.(.+)|)$/,K=/(?:^|\s)hover(\.\S+|)\b/,Q=/^key/,G=/^(?:mouse|contextmenu)|click/,Y=/^(?:focusinfocus|focusoutblur)$/,Z=function(e){return v.event.special.hover?e:e.replace(K,"mouseenter$1 mouseleave$1")};v.event={add:function(e,n,r,i,s){var o,u,a,f,l,c,h,p,d,m,g;if(e.nodeType===3||e.nodeType===8||!n||!r||!(o=v._data(e)))return;r.handler&&(d=r,r=d.handler,s=d.selector),r.guid||(r.guid=v.guid++),a=o.events,a||(o.events=a={}),u=o.handle,u||(o.handle=u=function(e){return typeof v=="undefined"||!!e&&v.event.triggered===e.type?t:v.event.dispatch.apply(u.elem,arguments)},u.elem=e),n=v.trim(Z(n)).split(" ");for(f=0;f=0&&(y=y.slice(0,-1),a=!0),y.indexOf(".")>=0&&(b=y.split("."),y=b.shift(),b.sort());if((!s||v.event.customEvent[y])&&!v.event.global[y])return;n=typeof n=="object"?n[v.expando]?n:new v.Event(y,n):new v.Event(y),n.type=y,n.isTrigger=!0,n.exclusive=a,n.namespace=b.join("."),n.namespace_re=n.namespace?new RegExp("(^|\\.)"+b.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,h=y.indexOf(":")<0?"on"+y:"";if(!s){u=v.cache;for(f in u)u[f].events&&u[f].events[y]&&v.event.trigger(n,r,u[f].handle.elem,!0);return}n.result=t,n.target||(n.target=s),r=r!=null?v.makeArray(r):[],r.unshift(n),p=v.event.special[y]||{};if(p.trigger&&p.trigger.apply(s,r)===!1)return;m=[[s,p.bindType||y]];if(!o&&!p.noBubble&&!v.isWindow(s)){g=p.delegateType||y,l=Y.test(g+y)?s:s.parentNode;for(c=s;l;l=l.parentNode)m.push([l,g]),c=l;c===(s.ownerDocument||i)&&m.push([c.defaultView||c.parentWindow||e,g])}for(f=0;f=0:v.find(h,this,null,[s]).length),u[h]&&f.push(c);f.length&&w.push({elem:s,matches:f})}d.length>m&&w.push({elem:this,matches:d.slice(m)});for(r=0;r0?this.on(t,null,e,n):this.trigger(t)},Q.test(t)&&(v.event.fixHooks[t]=v.event.keyHooks),G.test(t)&&(v.event.fixHooks[t]=v.event.mouseHooks)}),function(e,t){function nt(e,t,n,r){n=n||[],t=t||g;var i,s,a,f,l=t.nodeType;if(!e||typeof e!="string")return n;if(l!==1&&l!==9)return[];a=o(t);if(!a&&!r)if(i=R.exec(e))if(f=i[1]){if(l===9){s=t.getElementById(f);if(!s||!s.parentNode)return n;if(s.id===f)return n.push(s),n}else if(t.ownerDocument&&(s=t.ownerDocument.getElementById(f))&&u(t,s)&&s.id===f)return n.push(s),n}else{if(i[2])return S.apply(n,x.call(t.getElementsByTagName(e),0)),n;if((f=i[3])&&Z&&t.getElementsByClassName)return S.apply(n,x.call(t.getElementsByClassName(f),0)),n}return vt(e.replace(j,"$1"),t,n,r,a)}function rt(e){return function(t){var n=t.nodeName.toLowerCase();return n==="input"&&t.type===e}}function it(e){return function(t){var n=t.nodeName.toLowerCase();return(n==="input"||n==="button")&&t.type===e}}function st(e){return N(function(t){return t=+t,N(function(n,r){var i,s=e([],n.length,t),o=s.length;while(o--)n[i=s[o]]&&(n[i]=!(r[i]=n[i]))})})}function ot(e,t,n){if(e===t)return n;var r=e.nextSibling;while(r){if(r===t)return-1;r=r.nextSibling}return 1}function ut(e,t){var n,r,s,o,u,a,f,l=L[d][e+" "];if(l)return t?0:l.slice(0);u=e,a=[],f=i.preFilter;while(u){if(!n||(r=F.exec(u)))r&&(u=u.slice(r[0].length)||u),a.push(s=[]);n=!1;if(r=I.exec(u))s.push(n=new m(r.shift())),u=u.slice(n.length),n.type=r[0].replace(j," ");for(o in i.filter)(r=J[o].exec(u))&&(!f[o]||(r=f[o](r)))&&(s.push(n=new m(r.shift())),u=u.slice(n.length),n.type=o,n.matches=r);if(!n)break}return t?u.length:u?nt.error(e):L(e,a).slice(0)}function at(e,t,r){var i=t.dir,s=r&&t.dir==="parentNode",o=w++;return t.first?function(t,n,r){while(t=t[i])if(s||t.nodeType===1)return e(t,n,r)}:function(t,r,u){if(!u){var a,f=b+" "+o+" ",l=f+n;while(t=t[i])if(s||t.nodeType===1){if((a=t[d])===l)return t.sizset;if(typeof a=="string"&&a.indexOf(f)===0){if(t.sizset)return t}else{t[d]=l;if(e(t,r,u))return t.sizset=!0,t;t.sizset=!1}}}else while(t=t[i])if(s||t.nodeType===1)if(e(t,r,u))return t}}function ft(e){return e.length>1?function(t,n,r){var i=e.length;while(i--)if(!e[i](t,n,r))return!1;return!0}:e[0]}function lt(e,t,n,r,i){var s,o=[],u=0,a=e.length,f=t!=null;for(;u-1&&(s[f]=!(o[f]=c))}}else g=lt(g===o?g.splice(d,g.length):g),i?i(null,o,g,a):S.apply(o,g)})}function ht(e){var t,n,r,s=e.length,o=i.relative[e[0].type],u=o||i.relative[" "],a=o?1:0,f=at(function(e){return e===t},u,!0),l=at(function(e){return T.call(t,e)>-1},u,!0),h=[function(e,n,r){return!o&&(r||n!==c)||((t=n).nodeType?f(e,n,r):l(e,n,r))}];for(;a1&&ft(h),a>1&&e.slice(0,a-1).join("").replace(j,"$1"),n,a0,s=e.length>0,o=function(u,a,f,l,h){var p,d,v,m=[],y=0,w="0",x=u&&[],T=h!=null,N=c,C=u||s&&i.find.TAG("*",h&&a.parentNode||a),k=b+=N==null?1:Math.E;T&&(c=a!==g&&a,n=o.el);for(;(p=C[w])!=null;w++){if(s&&p){for(d=0;v=e[d];d++)if(v(p,a,f)){l.push(p);break}T&&(b=k,n=++o.el)}r&&((p=!v&&p)&&y--,u&&x.push(p))}y+=w;if(r&&w!==y){for(d=0;v=t[d];d++)v(x,m,a,f);if(u){if(y>0)while(w--)!x[w]&&!m[w]&&(m[w]=E.call(l));m=lt(m)}S.apply(l,m),T&&!u&&m.length>0&&y+t.length>1&&nt.uniqueSort(l)}return T&&(b=k,c=N),x};return o.el=0,r?N(o):o}function dt(e,t,n){var r=0,i=t.length;for(;r2&&(f=u[0]).type==="ID"&&t.nodeType===9&&!s&&i.relative[u[1].type]){t=i.find.ID(f.matches[0].replace($,""),t,s)[0];if(!t)return n;e=e.slice(u.shift().length)}for(o=J.POS.test(e)?-1:u.length-1;o>=0;o--){f=u[o];if(i.relative[l=f.type])break;if(c=i.find[l])if(r=c(f.matches[0].replace($,""),z.test(u[0].type)&&t.parentNode||t,s)){u.splice(o,1),e=r.length&&u.join("");if(!e)return S.apply(n,x.call(r,0)),n;break}}}return a(e,h)(r,t,s,n,z.test(e)),n}function mt(){}var n,r,i,s,o,u,a,f,l,c,h=!0,p="undefined",d=("sizcache"+Math.random()).replace(".",""),m=String,g=e.document,y=g.documentElement,b=0,w=0,E=[].pop,S=[].push,x=[].slice,T=[].indexOf||function(e){var t=0,n=this.length;for(;ti.cacheLength&&delete e[t.shift()],e[n+" "]=r},e)},k=C(),L=C(),A=C(),O="[\\x20\\t\\r\\n\\f]",M="(?:\\\\.|[-\\w]|[^\\x00-\\xa0])+",_=M.replace("w","w#"),D="([*^$|!~]?=)",P="\\["+O+"*("+M+")"+O+"*(?:"+D+O+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+_+")|)|)"+O+"*\\]",H=":("+M+")(?:\\((?:(['\"])((?:\\\\.|[^\\\\])*?)\\2|([^()[\\]]*|(?:(?:"+P+")|[^:]|\\\\.)*|.*))\\)|)",B=":(even|odd|eq|gt|lt|nth|first|last)(?:\\("+O+"*((?:-\\d)?\\d*)"+O+"*\\)|)(?=[^-]|$)",j=new RegExp("^"+O+"+|((?:^|[^\\\\])(?:\\\\.)*)"+O+"+$","g"),F=new RegExp("^"+O+"*,"+O+"*"),I=new RegExp("^"+O+"*([\\x20\\t\\r\\n\\f>+~])"+O+"*"),q=new RegExp(H),R=/^(?:#([\w\-]+)|(\w+)|\.([\w\-]+))$/,U=/^:not/,z=/[\x20\t\r\n\f]*[+~]/,W=/:not\($/,X=/h\d/i,V=/input|select|textarea|button/i,$=/\\(?!\\)/g,J={ID:new RegExp("^#("+M+")"),CLASS:new RegExp("^\\.("+M+")"),NAME:new RegExp("^\\[name=['\"]?("+M+")['\"]?\\]"),TAG:new RegExp("^("+M.replace("w","w*")+")"),ATTR:new RegExp("^"+P),PSEUDO:new RegExp("^"+H),POS:new RegExp(B,"i"),CHILD:new RegExp("^:(only|nth|first|last)-child(?:\\("+O+"*(even|odd|(([+-]|)(\\d*)n|)"+O+"*(?:([+-]|)"+O+"*(\\d+)|))"+O+"*\\)|)","i"),needsContext:new RegExp("^"+O+"*[>+~]|"+B,"i")},K=function(e){var t=g.createElement("div");try{return e(t)}catch(n){return!1}finally{t=null}},Q=K(function(e){return e.appendChild(g.createComment("")),!e.getElementsByTagName("*").length}),G=K(function(e){return e.innerHTML="",e.firstChild&&typeof e.firstChild.getAttribute!==p&&e.firstChild.getAttribute("href")==="#"}),Y=K(function(e){e.innerHTML="";var t=typeof e.lastChild.getAttribute("multiple");return t!=="boolean"&&t!=="string"}),Z=K(function(e){return e.innerHTML="",!e.getElementsByClassName||!e.getElementsByClassName("e").length?!1:(e.lastChild.className="e",e.getElementsByClassName("e").length===2)}),et=K(function(e){e.id=d+0,e.innerHTML="
",y.insertBefore(e,y.firstChild);var t=g.getElementsByName&&g.getElementsByName(d).length===2+g.getElementsByName(d+0).length;return r=!g.getElementById(d),y.removeChild(e),t});try{x.call(y.childNodes,0)[0].nodeType}catch(tt){x=function(e){var t,n=[];for(;t=this[e];e++)n.push(t);return n}}nt.matches=function(e,t){return nt(e,null,null,t)},nt.matchesSelector=function(e,t){return nt(t,null,null,[e]).length>0},s=nt.getText=function(e){var t,n="",r=0,i=e.nodeType;if(i){if(i===1||i===9||i===11){if(typeof e.textContent=="string")return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=s(e)}else if(i===3||i===4)return e.nodeValue}else for(;t=e[r];r++)n+=s(t);return n},o=nt.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return t?t.nodeName!=="HTML":!1},u=nt.contains=y.contains?function(e,t){var n=e.nodeType===9?e.documentElement:e,r=t&&t.parentNode;return e===r||!!(r&&r.nodeType===1&&n.contains&&n.contains(r))}:y.compareDocumentPosition?function(e,t){return t&&!!(e.compareDocumentPosition(t)&16)}:function(e,t){while(t=t.parentNode)if(t===e)return!0;return!1},nt.attr=function(e,t){var n,r=o(e);return r||(t=t.toLowerCase()),(n=i.attrHandle[t])?n(e):r||Y?e.getAttribute(t):(n=e.getAttributeNode(t),n?typeof e[t]=="boolean"?e[t]?t:null:n.specified?n.value:null:null)},i=nt.selectors={cacheLength:50,createPseudo:N,match:J,attrHandle:G?{}:{href:function(e){return e.getAttribute("href",2)},type:function(e){return e.getAttribute("type")}},find:{ID:r?function(e,t,n){if(typeof t.getElementById!==p&&!n){var r=t.getElementById(e);return r&&r.parentNode?[r]:[]}}:function(e,n,r){if(typeof n.getElementById!==p&&!r){var i=n.getElementById(e);return i?i.id===e||typeof i.getAttributeNode!==p&&i.getAttributeNode("id").value===e?[i]:t:[]}},TAG:Q?function(e,t){if(typeof t.getElementsByTagName!==p)return t.getElementsByTagName(e)}:function(e,t){var n=t.getElementsByTagName(e);if(e==="*"){var r,i=[],s=0;for(;r=n[s];s++)r.nodeType===1&&i.push(r);return i}return n},NAME:et&&function(e,t){if(typeof t.getElementsByName!==p)return t.getElementsByName(name)},CLASS:Z&&function(e,t,n){if(typeof t.getElementsByClassName!==p&&!n)return t.getElementsByClassName(e)}},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace($,""),e[3]=(e[4]||e[5]||"").replace($,""),e[2]==="~="&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),e[1]==="nth"?(e[2]||nt.error(e[0]),e[3]=+(e[3]?e[4]+(e[5]||1):2*(e[2]==="even"||e[2]==="odd")),e[4]=+(e[6]+e[7]||e[2]==="odd")):e[2]&&nt.error(e[0]),e},PSEUDO:function(e){var t,n;if(J.CHILD.test(e[0]))return null;if(e[3])e[2]=e[3];else if(t=e[4])q.test(t)&&(n=ut(t,!0))&&(n=t.indexOf(")",t.length-n)-t.length)&&(t=t.slice(0,n),e[0]=e[0].slice(0,n)),e[2]=t;return e.slice(0,3)}},filter:{ID:r?function(e){return e=e.replace($,""),function(t){return t.getAttribute("id")===e}}:function(e){return e=e.replace($,""),function(t){var n=typeof t.getAttributeNode!==p&&t.getAttributeNode("id");return n&&n.value===e}},TAG:function(e){return e==="*"?function(){return!0}:(e=e.replace($,"").toLowerCase(),function(t){return t.nodeName&&t.nodeName.toLowerCase()===e})},CLASS:function(e){var t=k[d][e+" "];return t||(t=new RegExp("(^|"+O+")"+e+"("+O+"|$)"))&&k(e,function(e){return t.test(e.className||typeof e.getAttribute!==p&&e.getAttribute("class")||"")})},ATTR:function(e,t,n){return function(r,i){var s=nt.attr(r,e);return s==null?t==="!=":t?(s+="",t==="="?s===n:t==="!="?s!==n:t==="^="?n&&s.indexOf(n)===0:t==="*="?n&&s.indexOf(n)>-1:t==="$="?n&&s.substr(s.length-n.length)===n:t==="~="?(" "+s+" ").indexOf(n)>-1:t==="|="?s===n||s.substr(0,n.length+1)===n+"-":!1):!0}},CHILD:function(e,t,n,r){return e==="nth"?function(e){var t,i,s=e.parentNode;if(n===1&&r===0)return!0;if(s){i=0;for(t=s.firstChild;t;t=t.nextSibling)if(t.nodeType===1){i++;if(e===t)break}}return i-=r,i===n||i%n===0&&i/n>=0}:function(t){var n=t;switch(e){case"only":case"first":while(n=n.previousSibling)if(n.nodeType===1)return!1;if(e==="first")return!0;n=t;case"last":while(n=n.nextSibling)if(n.nodeType===1)return!1;return!0}}},PSEUDO:function(e,t){var n,r=i.pseudos[e]||i.setFilters[e.toLowerCase()]||nt.error("unsupported pseudo: "+e);return r[d]?r(t):r.length>1?(n=[e,e,"",t],i.setFilters.hasOwnProperty(e.toLowerCase())?N(function(e,n){var i,s=r(e,t),o=s.length;while(o--)i=T.call(e,s[o]),e[i]=!(n[i]=s[o])}):function(e){return r(e,0,n)}):r}},pseudos:{not:N(function(e){var t=[],n=[],r=a(e.replace(j,"$1"));return r[d]?N(function(e,t,n,i){var s,o=r(e,null,i,[]),u=e.length;while(u--)if(s=o[u])e[u]=!(t[u]=s)}):function(e,i,s){return t[0]=e,r(t,null,s,n),!n.pop()}}),has:N(function(e){return function(t){return nt(e,t).length>0}}),contains:N(function(e){return function(t){return(t.textContent||t.innerText||s(t)).indexOf(e)>-1}}),enabled:function(e){return e.disabled===!1},disabled:function(e){return e.disabled===!0},checked:function(e){var t=e.nodeName.toLowerCase();return t==="input"&&!!e.checked||t==="option"&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,e.selected===!0},parent:function(e){return!i.pseudos.empty(e)},empty:function(e){var t;e=e.firstChild;while(e){if(e.nodeName>"@"||(t=e.nodeType)===3||t===4)return!1;e=e.nextSibling}return!0},header:function(e){return X.test(e.nodeName)},text:function(e){var t,n;return e.nodeName.toLowerCase()==="input"&&(t=e.type)==="text"&&((n=e.getAttribute("type"))==null||n.toLowerCase()===t)},radio:rt("radio"),checkbox:rt("checkbox"),file:rt("file"),password:rt("password"),image:rt("image"),submit:it("submit"),reset:it("reset"),button:function(e){var t=e.nodeName.toLowerCase();return t==="input"&&e.type==="button"||t==="button"},input:function(e){return V.test(e.nodeName)},focus:function(e){var t=e.ownerDocument;return e===t.activeElement&&(!t.hasFocus||t.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},active:function(e){return e===e.ownerDocument.activeElement},first:st(function(){return[0]}),last:st(function(e,t){return[t-1]}),eq:st(function(e,t,n){return[n<0?n+t:n]}),even:st(function(e,t){for(var n=0;n=0;)e.push(r);return e}),gt:st(function(e,t,n){for(var r=n<0?n+t:n;++r",e.querySelectorAll("[selected]").length||i.push("\\["+O+"*(?:checked|disabled|ismap|multiple|readonly|selected|value)"),e.querySelectorAll(":checked").length||i.push(":checked")}),K(function(e){e.innerHTML="

",e.querySelectorAll("[test^='']").length&&i.push("[*^$]="+O+"*(?:\"\"|'')"),e.innerHTML="",e.querySelectorAll(":enabled").length||i.push(":enabled",":disabled")}),i=new RegExp(i.join("|")),vt=function(e,r,s,o,u){if(!o&&!u&&!i.test(e)){var a,f,l=!0,c=d,h=r,p=r.nodeType===9&&e;if(r.nodeType===1&&r.nodeName.toLowerCase()!=="object"){a=ut(e),(l=r.getAttribute("id"))?c=l.replace(n,"\\$&"):r.setAttribute("id",c),c="[id='"+c+"'] ",f=a.length;while(f--)a[f]=c+a[f].join("");h=z.test(e)&&r.parentNode||r,p=a.join(",")}if(p)try{return S.apply(s,x.call(h.querySelectorAll(p),0)),s}catch(v){}finally{l||r.removeAttribute("id")}}return t(e,r,s,o,u)},u&&(K(function(t){e=u.call(t,"div");try{u.call(t,"[test!='']:sizzle"),s.push("!=",H)}catch(n){}}),s=new RegExp(s.join("|")),nt.matchesSelector=function(t,n){n=n.replace(r,"='$1']");if(!o(t)&&!s.test(n)&&!i.test(n))try{var a=u.call(t,n);if(a||e||t.document&&t.document.nodeType!==11)return a}catch(f){}return nt(n,null,null,[t]).length>0})}(),i.pseudos.nth=i.pseudos.eq,i.filters=mt.prototype=i.pseudos,i.setFilters=new mt,nt.attr=v.attr,v.find=nt,v.expr=nt.selectors,v.expr[":"]=v.expr.pseudos,v.unique=nt.uniqueSort,v.text=nt.getText,v.isXMLDoc=nt.isXML,v.contains=nt.contains}(e);var nt=/Until$/,rt=/^(?:parents|prev(?:Until|All))/,it=/^.[^:#\[\.,]*$/,st=v.expr.match.needsContext,ot={children:!0,contents:!0,next:!0,prev:!0};v.fn.extend({find:function(e){var t,n,r,i,s,o,u=this;if(typeof e!="string")return v(e).filter(function(){for(t=0,n=u.length;t0)for(i=r;i=0:v.filter(e,this).length>0:this.filter(e).length>0)},closest:function(e,t){var n,r=0,i=this.length,s=[],o=st.test(e)||typeof e!="string"?v(e,t||this.context):0;for(;r-1:v.find.matchesSelector(n,e)){s.push(n);break}n=n.parentNode}}return s=s.length>1?v.unique(s):s,this.pushStack(s,"closest",e)},index:function(e){return e?typeof e=="string"?v.inArray(this[0],v(e)):v.inArray(e.jquery?e[0]:e,this):this[0]&&this[0].parentNode?this.prevAll().length:-1},add:function(e,t){var n=typeof e=="string"?v(e,t):v.makeArray(e&&e.nodeType?[e]:e),r=v.merge(this.get(),n);return this.pushStack(ut(n[0])||ut(r[0])?r:v.unique(r))},addBack:function(e){return this.add(e==null?this.prevObject:this.prevObject.filter(e))}}),v.fn.andSelf=v.fn.addBack,v.each({parent:function(e){var t=e.parentNode;return t&&t.nodeType!==11?t:null},parents:function(e){return v.dir(e,"parentNode")},parentsUntil:function(e,t,n){return v.dir(e,"parentNode",n)},next:function(e){return at(e,"nextSibling")},prev:function(e){return at(e,"previousSibling")},nextAll:function(e){return v.dir(e,"nextSibling")},prevAll:function(e){return v.dir(e,"previousSibling")},nextUntil:function(e,t,n){return v.dir(e,"nextSibling",n)},prevUntil:function(e,t,n){return v.dir(e,"previousSibling",n)},siblings:function(e){return v.sibling((e.parentNode||{}).firstChild,e)},children:function(e){return v.sibling(e.firstChild)},contents:function(e){return v.nodeName(e,"iframe")?e.contentDocument||e.contentWindow.document:v.merge([],e.childNodes)}},function(e,t){v.fn[e]=function(n,r){var i=v.map(this,t,n);return nt.test(e)||(r=n),r&&typeof r=="string"&&(i=v.filter(r,i)),i=this.length>1&&!ot[e]?v.unique(i):i,this.length>1&&rt.test(e)&&(i=i.reverse()),this.pushStack(i,e,l.call(arguments).join(","))}}),v.extend({filter:function(e,t,n){return n&&(e=":not("+e+")"),t.length===1?v.find.matchesSelector(t[0],e)?[t[0]]:[]:v.find.matches(e,t)},dir:function(e,n,r){var i=[],s=e[n];while(s&&s.nodeType!==9&&(r===t||s.nodeType!==1||!v(s).is(r)))s.nodeType===1&&i.push(s),s=s[n];return i},sibling:function(e,t){var n=[];for(;e;e=e.nextSibling)e.nodeType===1&&e!==t&&n.push(e);return n}});var ct="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",ht=/ jQuery\d+="(?:null|\d+)"/g,pt=/^\s+/,dt=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,vt=/<([\w:]+)/,mt=/]","i"),Et=/^(?:checkbox|radio)$/,St=/checked\s*(?:[^=]|=\s*.checked.)/i,xt=/\/(java|ecma)script/i,Tt=/^\s*\s*$/g,Nt={option:[1,""],legend:[1,"
","
"],thead:[1,"","
"],tr:[2,"","
"],td:[3,"","
"],col:[2,"","
"],area:[1,"",""],_default:[0,"",""]},Ct=lt(i),kt=Ct.appendChild(i.createElement("div"));Nt.optgroup=Nt.option,Nt.tbody=Nt.tfoot=Nt.colgroup=Nt.caption=Nt.thead,Nt.th=Nt.td,v.support.htmlSerialize||(Nt._default=[1,"X
","
"]),v.fn.extend({text:function(e){return v.access(this,function(e){return e===t?v.text(this):this.empty().append((this[0]&&this[0].ownerDocument||i).createTextNode(e))},null,e,arguments.length)},wrapAll:function(e){if(v.isFunction(e))return this.each(function(t){v(this).wrapAll(e.call(this,t))});if(this[0]){var t=v(e,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&t.insertBefore(this[0]),t.map(function(){var e=this;while(e.firstChild&&e.firstChild.nodeType===1)e=e.firstChild;return e}).append(this)}return this},wrapInner:function(e){return v.isFunction(e)?this.each(function(t){v(this).wrapInner(e.call(this,t))}):this.each(function(){var t=v(this),n=t.contents();n.length?n.wrapAll(e):t.append(e)})},wrap:function(e){var t=v.isFunction(e);return this.each(function(n){v(this).wrapAll(t?e.call(this,n):e)})},unwrap:function(){return this.parent().each(function(){v.nodeName(this,"body")||v(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(e){(this.nodeType===1||this.nodeType===11)&&this.appendChild(e)})},prepend:function(){return this.domManip(arguments,!0,function(e){(this.nodeType===1||this.nodeType===11)&&this.insertBefore(e,this.firstChild)})},before:function(){if(!ut(this[0]))return this.domManip(arguments,!1,function(e){this.parentNode.insertBefore(e,this)});if(arguments.length){var e=v.clean(arguments);return this.pushStack(v.merge(e,this),"before",this.selector)}},after:function(){if(!ut(this[0]))return this.domManip(arguments,!1,function(e){this.parentNode.insertBefore(e,this.nextSibling)});if(arguments.length){var e=v.clean(arguments);return this.pushStack(v.merge(this,e),"after",this.selector)}},remove:function(e,t){var n,r=0;for(;(n=this[r])!=null;r++)if(!e||v.filter(e,[n]).length)!t&&n.nodeType===1&&(v.cleanData(n.getElementsByTagName("*")),v.cleanData([n])),n.parentNode&&n.parentNode.removeChild(n);return this},empty:function(){var e,t=0;for(;(e=this[t])!=null;t++){e.nodeType===1&&v.cleanData(e.getElementsByTagName("*"));while(e.firstChild)e.removeChild(e.firstChild)}return this},clone:function(e,t){return e=e==null?!1:e,t=t==null?e:t,this.map(function(){return v.clone(this,e,t)})},html:function(e){return v.access(this,function(e){var n=this[0]||{},r=0,i=this.length;if(e===t)return n.nodeType===1?n.innerHTML.replace(ht,""):t;if(typeof e=="string"&&!yt.test(e)&&(v.support.htmlSerialize||!wt.test(e))&&(v.support.leadingWhitespace||!pt.test(e))&&!Nt[(vt.exec(e)||["",""])[1].toLowerCase()]){e=e.replace(dt,"<$1>");try{for(;r1&&typeof f=="string"&&St.test(f))return this.each(function(){v(this).domManip(e,n,r)});if(v.isFunction(f))return this.each(function(i){var s=v(this);e[0]=f.call(this,i,n?s.html():t),s.domManip(e,n,r)});if(this[0]){i=v.buildFragment(e,this,l),o=i.fragment,s=o.firstChild,o.childNodes.length===1&&(o=s);if(s){n=n&&v.nodeName(s,"tr");for(u=i.cacheable||c-1;a0?this.clone(!0):this).get(),v(o[i])[t](r),s=s.concat(r);return this.pushStack(s,e,o.selector)}}),v.extend({clone:function(e,t,n){var r,i,s,o;v.support.html5Clone||v.isXMLDoc(e)||!wt.test("<"+e.nodeName+">")?o=e.cloneNode(!0):(kt.innerHTML=e.outerHTML,kt.removeChild(o=kt.firstChild));if((!v.support.noCloneEvent||!v.support.noCloneChecked)&&(e.nodeType===1||e.nodeType===11)&&!v.isXMLDoc(e)){Ot(e,o),r=Mt(e),i=Mt(o);for(s=0;r[s];++s)i[s]&&Ot(r[s],i[s])}if(t){At(e,o);if(n){r=Mt(e),i=Mt(o);for(s=0;r[s];++s)At(r[s],i[s])}}return r=i=null,o},clean:function(e,t,n,r){var s,o,u,a,f,l,c,h,p,d,m,g,y=t===i&&Ct,b=[];if(!t||typeof t.createDocumentFragment=="undefined")t=i;for(s=0;(u=e[s])!=null;s++){typeof u=="number"&&(u+="");if(!u)continue;if(typeof u=="string")if(!gt.test(u))u=t.createTextNode(u);else{y=y||lt(t),c=t.createElement("div"),y.appendChild(c),u=u.replace(dt,"<$1>"),a=(vt.exec(u)||["",""])[1].toLowerCase(),f=Nt[a]||Nt._default,l=f[0],c.innerHTML=f[1]+u+f[2];while(l--)c=c.lastChild;if(!v.support.tbody){h=mt.test(u),p=a==="table"&&!h?c.firstChild&&c.firstChild.childNodes:f[1]===""&&!h?c.childNodes:[];for(o=p.length-1;o>=0;--o)v.nodeName(p[o],"tbody")&&!p[o].childNodes.length&&p[o].parentNode.removeChild(p[o])}!v.support.leadingWhitespace&&pt.test(u)&&c.insertBefore(t.createTextNode(pt.exec(u)[0]),c.firstChild),u=c.childNodes,c.parentNode.removeChild(c)}u.nodeType?b.push(u):v.merge(b,u)}c&&(u=c=y=null);if(!v.support.appendChecked)for(s=0;(u=b[s])!=null;s++)v.nodeName(u,"input")?_t(u):typeof u.getElementsByTagName!="undefined"&&v.grep(u.getElementsByTagName("input"),_t);if(n){m=function(e){if(!e.type||xt.test(e.type))return r?r.push(e.parentNode?e.parentNode.removeChild(e):e):n.appendChild(e)};for(s=0;(u=b[s])!=null;s++)if(!v.nodeName(u,"script")||!m(u))n.appendChild(u),typeof u.getElementsByTagName!="undefined"&&(g=v.grep(v.merge([],u.getElementsByTagName("script")),m),b.splice.apply(b,[s+1,0].concat(g)),s+=g.length)}return b},cleanData:function(e,t){var n,r,i,s,o=0,u=v.expando,a=v.cache,f=v.support.deleteExpando,l=v.event.special;for(;(i=e[o])!=null;o++)if(t||v.acceptData(i)){r=i[u],n=r&&a[r];if(n){if(n.events)for(s in n.events)l[s]?v.event.remove(i,s):v.removeEvent(i,s,n.handle);a[r]&&(delete a[r],f?delete i[u]:i.removeAttribute?i.removeAttribute(u):i[u]=null,v.deletedIds.push(r))}}}}),function(){var e,t;v.uaMatch=function(e){e=e.toLowerCase();var t=/(chrome)[ \/]([\w.]+)/.exec(e)||/(webkit)[ \/]([\w.]+)/.exec(e)||/(opera)(?:.*version|)[ \/]([\w.]+)/.exec(e)||/(msie) ([\w.]+)/.exec(e)||e.indexOf("compatible")<0&&/(mozilla)(?:.*? rv:([\w.]+)|)/.exec(e)||[];return{browser:t[1]||"",version:t[2]||"0"}},e=v.uaMatch(o.userAgent),t={},e.browser&&(t[e.browser]=!0,t.version=e.version),t.chrome?t.webkit=!0:t.webkit&&(t.safari=!0),v.browser=t,v.sub=function(){function e(t,n){return new e.fn.init(t,n)}v.extend(!0,e,this),e.superclass=this,e.fn=e.prototype=this(),e.fn.constructor=e,e.sub=this.sub,e.fn.init=function(r,i){return i&&i instanceof v&&!(i instanceof e)&&(i=e(i)),v.fn.init.call(this,r,i,t)},e.fn.init.prototype=e.fn;var t=e(i);return e}}();var Dt,Pt,Ht,Bt=/alpha\([^)]*\)/i,jt=/opacity=([^)]*)/,Ft=/^(top|right|bottom|left)$/,It=/^(none|table(?!-c[ea]).+)/,qt=/^margin/,Rt=new RegExp("^("+m+")(.*)$","i"),Ut=new RegExp("^("+m+")(?!px)[a-z%]+$","i"),zt=new RegExp("^([-+])=("+m+")","i"),Wt={BODY:"block"},Xt={position:"absolute",visibility:"hidden",display:"block"},Vt={letterSpacing:0,fontWeight:400},$t=["Top","Right","Bottom","Left"],Jt=["Webkit","O","Moz","ms"],Kt=v.fn.toggle;v.fn.extend({css:function(e,n){return v.access(this,function(e,n,r){return r!==t?v.style(e,n,r):v.css(e,n)},e,n,arguments.length>1)},show:function(){return Yt(this,!0)},hide:function(){return Yt(this)},toggle:function(e,t){var n=typeof e=="boolean";return v.isFunction(e)&&v.isFunction(t)?Kt.apply(this,arguments):this.each(function(){(n?e:Gt(this))?v(this).show():v(this).hide()})}}),v.extend({cssHooks:{opacity:{get:function(e,t){if(t){var n=Dt(e,"opacity");return n===""?"1":n}}}},cssNumber:{fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":v.support.cssFloat?"cssFloat":"styleFloat"},style:function(e,n,r,i){if(!e||e.nodeType===3||e.nodeType===8||!e.style)return;var s,o,u,a=v.camelCase(n),f=e.style;n=v.cssProps[a]||(v.cssProps[a]=Qt(f,a)),u=v.cssHooks[n]||v.cssHooks[a];if(r===t)return u&&"get"in u&&(s=u.get(e,!1,i))!==t?s:f[n];o=typeof r,o==="string"&&(s=zt.exec(r))&&(r=(s[1]+1)*s[2]+parseFloat(v.css(e,n)),o="number");if(r==null||o==="number"&&isNaN(r))return;o==="number"&&!v.cssNumber[a]&&(r+="px");if(!u||!("set"in u)||(r=u.set(e,r,i))!==t)try{f[n]=r}catch(l){}},css:function(e,n,r,i){var s,o,u,a=v.camelCase(n);return n=v.cssProps[a]||(v.cssProps[a]=Qt(e.style,a)),u=v.cssHooks[n]||v.cssHooks[a],u&&"get"in u&&(s=u.get(e,!0,i)),s===t&&(s=Dt(e,n)),s==="normal"&&n in Vt&&(s=Vt[n]),r||i!==t?(o=parseFloat(s),r||v.isNumeric(o)?o||0:s):s},swap:function(e,t,n){var r,i,s={};for(i in t)s[i]=e.style[i],e.style[i]=t[i];r=n.call(e);for(i in t)e.style[i]=s[i];return r}}),e.getComputedStyle?Dt=function(t,n){var r,i,s,o,u=e.getComputedStyle(t,null),a=t.style;return u&&(r=u.getPropertyValue(n)||u[n],r===""&&!v.contains(t.ownerDocument,t)&&(r=v.style(t,n)),Ut.test(r)&&qt.test(n)&&(i=a.width,s=a.minWidth,o=a.maxWidth,a.minWidth=a.maxWidth=a.width=r,r=u.width,a.width=i,a.minWidth=s,a.maxWidth=o)),r}:i.documentElement.currentStyle&&(Dt=function(e,t){var n,r,i=e.currentStyle&&e.currentStyle[t],s=e.style;return i==null&&s&&s[t]&&(i=s[t]),Ut.test(i)&&!Ft.test(t)&&(n=s.left,r=e.runtimeStyle&&e.runtimeStyle.left,r&&(e.runtimeStyle.left=e.currentStyle.left),s.left=t==="fontSize"?"1em":i,i=s.pixelLeft+"px",s.left=n,r&&(e.runtimeStyle.left=r)),i===""?"auto":i}),v.each(["height","width"],function(e,t){v.cssHooks[t]={get:function(e,n,r){if(n)return e.offsetWidth===0&&It.test(Dt(e,"display"))?v.swap(e,Xt,function(){return tn(e,t,r)}):tn(e,t,r)},set:function(e,n,r){return Zt(e,n,r?en(e,t,r,v.support.boxSizing&&v.css(e,"boxSizing")==="border-box"):0)}}}),v.support.opacity||(v.cssHooks.opacity={get:function(e,t){return jt.test((t&&e.currentStyle?e.currentStyle.filter:e.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":t?"1":""},set:function(e,t){var n=e.style,r=e.currentStyle,i=v.isNumeric(t)?"alpha(opacity="+t*100+")":"",s=r&&r.filter||n.filter||"";n.zoom=1;if(t>=1&&v.trim(s.replace(Bt,""))===""&&n.removeAttribute){n.removeAttribute("filter");if(r&&!r.filter)return}n.filter=Bt.test(s)?s.replace(Bt,i):s+" "+i}}),v(function(){v.support.reliableMarginRight||(v.cssHooks.marginRight={get:function(e,t){return v.swap(e,{display:"inline-block"},function(){if(t)return Dt(e,"marginRight")})}}),!v.support.pixelPosition&&v.fn.position&&v.each(["top","left"],function(e,t){v.cssHooks[t]={get:function(e,n){if(n){var r=Dt(e,t);return Ut.test(r)?v(e).position()[t]+"px":r}}}})}),v.expr&&v.expr.filters&&(v.expr.filters.hidden=function(e){return e.offsetWidth===0&&e.offsetHeight===0||!v.support.reliableHiddenOffsets&&(e.style&&e.style.display||Dt(e,"display"))==="none"},v.expr.filters.visible=function(e){return!v.expr.filters.hidden(e)}),v.each({margin:"",padding:"",border:"Width"},function(e,t){v.cssHooks[e+t]={expand:function(n){var r,i=typeof n=="string"?n.split(" "):[n],s={};for(r=0;r<4;r++)s[e+$t[r]+t]=i[r]||i[r-2]||i[0];return s}},qt.test(e)||(v.cssHooks[e+t].set=Zt)});var rn=/%20/g,sn=/\[\]$/,on=/\r?\n/g,un=/^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,an=/^(?:select|textarea)/i;v.fn.extend({serialize:function(){return v.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?v.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||an.test(this.nodeName)||un.test(this.type))}).map(function(e,t){var n=v(this).val();return n==null?null:v.isArray(n)?v.map(n,function(e,n){return{name:t.name,value:e.replace(on,"\r\n")}}):{name:t.name,value:n.replace(on,"\r\n")}}).get()}}),v.param=function(e,n){var r,i=[],s=function(e,t){t=v.isFunction(t)?t():t==null?"":t,i[i.length]=encodeURIComponent(e)+"="+encodeURIComponent(t)};n===t&&(n=v.ajaxSettings&&v.ajaxSettings.traditional);if(v.isArray(e)||e.jquery&&!v.isPlainObject(e))v.each(e,function(){s(this.name,this.value)});else for(r in e)fn(r,e[r],n,s);return i.join("&").replace(rn,"+")};var ln,cn,hn=/#.*$/,pn=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,dn=/^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,vn=/^(?:GET|HEAD)$/,mn=/^\/\//,gn=/\?/,yn=/)<[^<]*)*<\/script>/gi,bn=/([?&])_=[^&]*/,wn=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,En=v.fn.load,Sn={},xn={},Tn=["*/"]+["*"];try{cn=s.href}catch(Nn){cn=i.createElement("a"),cn.href="",cn=cn.href}ln=wn.exec(cn.toLowerCase())||[],v.fn.load=function(e,n,r){if(typeof e!="string"&&En)return En.apply(this,arguments);if(!this.length)return this;var i,s,o,u=this,a=e.indexOf(" ");return a>=0&&(i=e.slice(a,e.length),e=e.slice(0,a)),v.isFunction(n)?(r=n,n=t):n&&typeof n=="object"&&(s="POST"),v.ajax({url:e,type:s,dataType:"html",data:n,complete:function(e,t){r&&u.each(r,o||[e.responseText,t,e])}}).done(function(e){o=arguments,u.html(i?v("
").append(e.replace(yn,"")).find(i):e)}),this},v.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(e,t){v.fn[t]=function(e){return this.on(t,e)}}),v.each(["get","post"],function(e,n){v[n]=function(e,r,i,s){return v.isFunction(r)&&(s=s||i,i=r,r=t),v.ajax({type:n,url:e,data:r,success:i,dataType:s})}}),v.extend({getScript:function(e,n){return v.get(e,t,n,"script")},getJSON:function(e,t,n){return v.get(e,t,n,"json")},ajaxSetup:function(e,t){return t?Ln(e,v.ajaxSettings):(t=e,e=v.ajaxSettings),Ln(e,t),e},ajaxSettings:{url:cn,isLocal:dn.test(ln[1]),global:!0,type:"GET",contentType:"application/x-www-form-urlencoded; charset=UTF-8",processData:!0,async:!0,accepts:{xml:"application/xml, text/xml",html:"text/html",text:"text/plain",json:"application/json, text/javascript","*":Tn},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":e.String,"text html":!0,"text json":v.parseJSON,"text xml":v.parseXML},flatOptions:{context:!0,url:!0}},ajaxPrefilter:Cn(Sn),ajaxTransport:Cn(xn),ajax:function(e,n){function T(e,n,s,a){var l,y,b,w,S,T=n;if(E===2)return;E=2,u&&clearTimeout(u),o=t,i=a||"",x.readyState=e>0?4:0,s&&(w=An(c,x,s));if(e>=200&&e<300||e===304)c.ifModified&&(S=x.getResponseHeader("Last-Modified"),S&&(v.lastModified[r]=S),S=x.getResponseHeader("Etag"),S&&(v.etag[r]=S)),e===304?(T="notmodified",l=!0):(l=On(c,w),T=l.state,y=l.data,b=l.error,l=!b);else{b=T;if(!T||e)T="error",e<0&&(e=0)}x.status=e,x.statusText=(n||T)+"",l?d.resolveWith(h,[y,T,x]):d.rejectWith(h,[x,T,b]),x.statusCode(g),g=t,f&&p.trigger("ajax"+(l?"Success":"Error"),[x,c,l?y:b]),m.fireWith(h,[x,T]),f&&(p.trigger("ajaxComplete",[x,c]),--v.active||v.event.trigger("ajaxStop"))}typeof e=="object"&&(n=e,e=t),n=n||{};var r,i,s,o,u,a,f,l,c=v.ajaxSetup({},n),h=c.context||c,p=h!==c&&(h.nodeType||h instanceof v)?v(h):v.event,d=v.Deferred(),m=v.Callbacks("once memory"),g=c.statusCode||{},b={},w={},E=0,S="canceled",x={readyState:0,setRequestHeader:function(e,t){if(!E){var n=e.toLowerCase();e=w[n]=w[n]||e,b[e]=t}return this},getAllResponseHeaders:function(){return E===2?i:null},getResponseHeader:function(e){var n;if(E===2){if(!s){s={};while(n=pn.exec(i))s[n[1].toLowerCase()]=n[2]}n=s[e.toLowerCase()]}return n===t?null:n},overrideMimeType:function(e){return E||(c.mimeType=e),this},abort:function(e){return e=e||S,o&&o.abort(e),T(0,e),this}};d.promise(x),x.success=x.done,x.error=x.fail,x.complete=m.add,x.statusCode=function(e){if(e){var t;if(E<2)for(t in e)g[t]=[g[t],e[t]];else t=e[x.status],x.always(t)}return this},c.url=((e||c.url)+"").replace(hn,"").replace(mn,ln[1]+"//"),c.dataTypes=v.trim(c.dataType||"*").toLowerCase().split(y),c.crossDomain==null&&(a=wn.exec(c.url.toLowerCase()),c.crossDomain=!(!a||a[1]===ln[1]&&a[2]===ln[2]&&(a[3]||(a[1]==="http:"?80:443))==(ln[3]||(ln[1]==="http:"?80:443)))),c.data&&c.processData&&typeof c.data!="string"&&(c.data=v.param(c.data,c.traditional)),kn(Sn,c,n,x);if(E===2)return x;f=c.global,c.type=c.type.toUpperCase(),c.hasContent=!vn.test(c.type),f&&v.active++===0&&v.event.trigger("ajaxStart");if(!c.hasContent){c.data&&(c.url+=(gn.test(c.url)?"&":"?")+c.data,delete c.data),r=c.url;if(c.cache===!1){var N=v.now(),C=c.url.replace(bn,"$1_="+N);c.url=C+(C===c.url?(gn.test(c.url)?"&":"?")+"_="+N:"")}}(c.data&&c.hasContent&&c.contentType!==!1||n.contentType)&&x.setRequestHeader("Content-Type",c.contentType),c.ifModified&&(r=r||c.url,v.lastModified[r]&&x.setRequestHeader("If-Modified-Since",v.lastModified[r]),v.etag[r]&&x.setRequestHeader("If-None-Match",v.etag[r])),x.setRequestHeader("Accept",c.dataTypes[0]&&c.accepts[c.dataTypes[0]]?c.accepts[c.dataTypes[0]]+(c.dataTypes[0]!=="*"?", "+Tn+"; q=0.01":""):c.accepts["*"]);for(l in c.headers)x.setRequestHeader(l,c.headers[l]);if(!c.beforeSend||c.beforeSend.call(h,x,c)!==!1&&E!==2){S="abort";for(l in{success:1,error:1,complete:1})x[l](c[l]);o=kn(xn,c,n,x);if(!o)T(-1,"No Transport");else{x.readyState=1,f&&p.trigger("ajaxSend",[x,c]),c.async&&c.timeout>0&&(u=setTimeout(function(){x.abort("timeout")},c.timeout));try{E=1,o.send(b,T)}catch(k){if(!(E<2))throw k;T(-1,k)}}return x}return x.abort()},active:0,lastModified:{},etag:{}});var Mn=[],_n=/\?/,Dn=/(=)\?(?=&|$)|\?\?/,Pn=v.now();v.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=Mn.pop()||v.expando+"_"+Pn++;return this[e]=!0,e}}),v.ajaxPrefilter("json jsonp",function(n,r,i){var s,o,u,a=n.data,f=n.url,l=n.jsonp!==!1,c=l&&Dn.test(f),h=l&&!c&&typeof a=="string"&&!(n.contentType||"").indexOf("application/x-www-form-urlencoded")&&Dn.test(a);if(n.dataTypes[0]==="jsonp"||c||h)return s=n.jsonpCallback=v.isFunction(n.jsonpCallback)?n.jsonpCallback():n.jsonpCallback,o=e[s],c?n.url=f.replace(Dn,"$1"+s):h?n.data=a.replace(Dn,"$1"+s):l&&(n.url+=(_n.test(f)?"&":"?")+n.jsonp+"="+s),n.converters["script json"]=function(){return u||v.error(s+" was not called"),u[0]},n.dataTypes[0]="json",e[s]=function(){u=arguments},i.always(function(){e[s]=o,n[s]&&(n.jsonpCallback=r.jsonpCallback,Mn.push(s)),u&&v.isFunction(o)&&o(u[0]),u=o=t}),"script"}),v.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/javascript|ecmascript/},converters:{"text script":function(e){return v.globalEval(e),e}}}),v.ajaxPrefilter("script",function(e){e.cache===t&&(e.cache=!1),e.crossDomain&&(e.type="GET",e.global=!1)}),v.ajaxTransport("script",function(e){if(e.crossDomain){var n,r=i.head||i.getElementsByTagName("head")[0]||i.documentElement;return{send:function(s,o){n=i.createElement("script"),n.async="async",e.scriptCharset&&(n.charset=e.scriptCharset),n.src=e.url,n.onload=n.onreadystatechange=function(e,i){if(i||!n.readyState||/loaded|complete/.test(n.readyState))n.onload=n.onreadystatechange=null,r&&n.parentNode&&r.removeChild(n),n=t,i||o(200,"success")},r.insertBefore(n,r.firstChild)},abort:function(){n&&n.onload(0,1)}}}});var Hn,Bn=e.ActiveXObject?function(){for(var e in Hn)Hn[e](0,1)}:!1,jn=0;v.ajaxSettings.xhr=e.ActiveXObject?function(){return!this.isLocal&&Fn()||In()}:Fn,function(e){v.extend(v.support,{ajax:!!e,cors:!!e&&"withCredentials"in e})}(v.ajaxSettings.xhr()),v.support.ajax&&v.ajaxTransport(function(n){if(!n.crossDomain||v.support.cors){var r;return{send:function(i,s){var o,u,a=n.xhr();n.username?a.open(n.type,n.url,n.async,n.username,n.password):a.open(n.type,n.url,n.async);if(n.xhrFields)for(u in n.xhrFields)a[u]=n.xhrFields[u];n.mimeType&&a.overrideMimeType&&a.overrideMimeType(n.mimeType),!n.crossDomain&&!i["X-Requested-With"]&&(i["X-Requested-With"]="XMLHttpRequest");try{for(u in i)a.setRequestHeader(u,i[u])}catch(f){}a.send(n.hasContent&&n.data||null),r=function(e,i){var u,f,l,c,h;try{if(r&&(i||a.readyState===4)){r=t,o&&(a.onreadystatechange=v.noop,Bn&&delete Hn[o]);if(i)a.readyState!==4&&a.abort();else{u=a.status,l=a.getAllResponseHeaders(),c={},h=a.responseXML,h&&h.documentElement&&(c.xml=h);try{c.text=a.responseText}catch(p){}try{f=a.statusText}catch(p){f=""}!u&&n.isLocal&&!n.crossDomain?u=c.text?200:404:u===1223&&(u=204)}}}catch(d){i||s(-1,d)}c&&s(u,f,c,l)},n.async?a.readyState===4?setTimeout(r,0):(o=++jn,Bn&&(Hn||(Hn={},v(e).unload(Bn)),Hn[o]=r),a.onreadystatechange=r):r()},abort:function(){r&&r(0,1)}}}});var qn,Rn,Un=/^(?:toggle|show|hide)$/,zn=new RegExp("^(?:([-+])=|)("+m+")([a-z%]*)$","i"),Wn=/queueHooks$/,Xn=[Gn],Vn={"*":[function(e,t){var n,r,i=this.createTween(e,t),s=zn.exec(t),o=i.cur(),u=+o||0,a=1,f=20;if(s){n=+s[2],r=s[3]||(v.cssNumber[e]?"":"px");if(r!=="px"&&u){u=v.css(i.elem,e,!0)||n||1;do a=a||".5",u/=a,v.style(i.elem,e,u+r);while(a!==(a=i.cur()/o)&&a!==1&&--f)}i.unit=r,i.start=u,i.end=s[1]?u+(s[1]+1)*n:n}return i}]};v.Animation=v.extend(Kn,{tweener:function(e,t){v.isFunction(e)?(t=e,e=["*"]):e=e.split(" ");var n,r=0,i=e.length;for(;r-1,f={},l={},c,h;a?(l=i.position(),c=l.top,h=l.left):(c=parseFloat(o)||0,h=parseFloat(u)||0),v.isFunction(t)&&(t=t.call(e,n,s)),t.top!=null&&(f.top=t.top-s.top+c),t.left!=null&&(f.left=t.left-s.left+h),"using"in t?t.using.call(e,f):i.css(f)}},v.fn.extend({position:function(){if(!this[0])return;var e=this[0],t=this.offsetParent(),n=this.offset(),r=er.test(t[0].nodeName)?{top:0,left:0}:t.offset();return n.top-=parseFloat(v.css(e,"marginTop"))||0,n.left-=parseFloat(v.css(e,"marginLeft"))||0,r.top+=parseFloat(v.css(t[0],"borderTopWidth"))||0,r.left+=parseFloat(v.css(t[0],"borderLeftWidth"))||0,{top:n.top-r.top,left:n.left-r.left}},offsetParent:function(){return this.map(function(){var e=this.offsetParent||i.body;while(e&&!er.test(e.nodeName)&&v.css(e,"position")==="static")e=e.offsetParent;return e||i.body})}}),v.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(e,n){var r=/Y/.test(n);v.fn[e]=function(i){return v.access(this,function(e,i,s){var o=tr(e);if(s===t)return o?n in o?o[n]:o.document.documentElement[i]:e[i];o?o.scrollTo(r?v(o).scrollLeft():s,r?s:v(o).scrollTop()):e[i]=s},e,i,arguments.length,null)}}),v.each({Height:"height",Width:"width"},function(e,n){v.each({padding:"inner"+e,content:n,"":"outer"+e},function(r,i){v.fn[i]=function(i,s){var o=arguments.length&&(r||typeof i!="boolean"),u=r||(i===!0||s===!0?"margin":"border");return v.access(this,function(n,r,i){var s;return v.isWindow(n)?n.document.documentElement["client"+e]:n.nodeType===9?(s=n.documentElement,Math.max(n.body["scroll"+e],s["scroll"+e],n.body["offset"+e],s["offset"+e],s["client"+e])):i===t?v.css(n,r,i,u):v.style(n,r,i,u)},n,o?i:t,o,null)}})}),e.jQuery=e.$=v,typeof define=="function"&&define.amd&&define.amd.jQuery&&define("jquery",[],function(){return v})})(window); \ No newline at end of file diff --git a/Chapter09/02_user_auth/static/content/login.js b/Chapter09/02_user_auth/static/content/login.js new file mode 100644 index 0000000..fd52f1d --- /dev/null +++ b/Chapter09/02_user_auth/static/content/login.js @@ -0,0 +1,30 @@ +$(function(){ + + var tmpl, // Main template HTML + tdata = {}; // JSON data object that feeds the template + + // Initialise page + var initPage = function() { + + // Load the HTML template + $.get("/templates/login.html", function(d){ + tmpl = d; + }); + + // Retrieve the server data and then initialise the page +// $.getJSON("/v1/users/logged_in.json", function (d) { +// $.extend(tdata, d); +// }); + + // When AJAX calls are complete parse the template + // replacing mustache tags with vars + $(document).ajaxStop(function () { +// if (tdata.data.logged_in) +// window.location = "/pages/admin/home"; +// else { + var renderedPage = Mustache.to_html( tmpl, tdata ); + $("body").html( renderedPage ); +// } + }); + }(); +}); diff --git a/Chapter09/02_user_auth/static/content/mustache.js b/Chapter09/02_user_auth/static/content/mustache.js new file mode 100644 index 0000000..0148d29 --- /dev/null +++ b/Chapter09/02_user_auth/static/content/mustache.js @@ -0,0 +1,625 @@ +/*! + * mustache.js - Logic-less {{mustache}} templates with JavaScript + * http://github.com/janl/mustache.js + */ + +/*global define: false*/ + +var Mustache; + +(function (exports) { + if (typeof module !== "undefined" && module.exports) { + module.exports = exports; // CommonJS + } else if (typeof define === "function") { + define(exports); // AMD + } else { + Mustache = exports; // diff --git a/Chapter09/02_user_auth/static/templates/admin_add_photos.html b/Chapter09/02_user_auth/static/templates/admin_add_photos.html new file mode 100644 index 0000000..d9cbe8d --- /dev/null +++ b/Chapter09/02_user_auth/static/templates/admin_add_photos.html @@ -0,0 +1,86 @@ +
+ +
+
Add to Album:
+
+ +
+
Image:
+
+
Description
+
+
+ + + + + +
+ + diff --git a/Chapter09/02_user_auth/static/templates/admin_home.html b/Chapter09/02_user_auth/static/templates/admin_home.html new file mode 100644 index 0000000..4db4cf1 --- /dev/null +++ b/Chapter09/02_user_auth/static/templates/admin_home.html @@ -0,0 +1,7 @@ + +

Admin Operations

+ + diff --git a/Chapter09/02_user_auth/static/templates/album.html b/Chapter09/02_user_auth/static/templates/album.html new file mode 100644 index 0000000..fbcbda2 --- /dev/null +++ b/Chapter09/02_user_auth/static/templates/album.html @@ -0,0 +1,20 @@ + +
+ {{#has_photos}} +

There are {{ has_photos }} photos in this album

+ {{/has_photos}} + {{#photos}} +
+
+
+
+

{{ desc }}

+
+
+ {{/photos}} +
+ {{^photos}} +

This album does't have any photos in it, sorry.

+ {{/photos}} +

diff --git a/Chapter09/02_user_auth/static/templates/home.html b/Chapter09/02_user_auth/static/templates/home.html new file mode 100644 index 0000000..90ff5fc --- /dev/null +++ b/Chapter09/02_user_auth/static/templates/home.html @@ -0,0 +1,17 @@ +
+ Register | + Admin +
+
+

There are {{ albums.length }} albums

+
    + {{#albums}} +
  • + {{name}} +
  • + {{/albums}} + {{^albums}} +
  • Sorry, there are currently no albums
  • + {{/albums}} +
+
diff --git a/Chapter09/02_user_auth/static/templates/login.html b/Chapter09/02_user_auth/static/templates/login.html new file mode 100644 index 0000000..7bbcc3f --- /dev/null +++ b/Chapter09/02_user_auth/static/templates/login.html @@ -0,0 +1,49 @@ + +
+
+
+
Email address:
+
+
Password:
+
+
+
+ + + + diff --git a/Chapter09/02_user_auth/static/templates/register.html b/Chapter09/02_user_auth/static/templates/register.html new file mode 100644 index 0000000..2934caa --- /dev/null +++ b/Chapter09/02_user_auth/static/templates/register.html @@ -0,0 +1,56 @@ + + +
+
+
+
Email address:
+
+
Display Name:
+
+
Password:
+
+
Password (confirm):
+
+
+
+ + + + diff --git a/Chapter09/02_user_auth/test.jpg b/Chapter09/02_user_auth/test.jpg new file mode 100644 index 0000000..6e4250a Binary files /dev/null and b/Chapter09/02_user_auth/test.jpg differ diff --git a/Chapter09/03_connection_pools/app/basic.html b/Chapter09/03_connection_pools/app/basic.html new file mode 100644 index 0000000..0d966da --- /dev/null +++ b/Chapter09/03_connection_pools/app/basic.html @@ -0,0 +1,25 @@ + + + + Photo Album + + + + + + + + + + + + + + + + + diff --git a/Chapter09/03_connection_pools/app/data/album.js b/Chapter09/03_connection_pools/app/data/album.js new file mode 100644 index 0000000..d28fa6a --- /dev/null +++ b/Chapter09/03_connection_pools/app/data/album.js @@ -0,0 +1,237 @@ + +var fs = require('fs'), + local = require('../local.config.js'), + db = require('./db.js'), + path = require("path"), + async = require('async'), + backhelp = require("./backend_helpers.js"); + +exports.version = "0.1.0"; + + +exports.create_album = function (data, callback) { + var write_succeeded = false; + var dbc; + + async.waterfall([ + // validate data. + function (cb) { + try { + backhelp.verify(data, + [ "name", + "title", + "date", + "description" ]); + if (!backhelp.valid_filename(data.name)) + throw invalid_album_name(); + } catch (e) { + cb(e); + } + + db.db(cb); + }, + + function (dbclient, cb) { + dbc = dbclient; + dbc.query( + "INSERT INTO Albums VALUES (?, ?, ?, ?)", + [ data.name, data.title, data.date, data.description ], + cb); + }, + + // make sure the folder exists. + function (results, fields, cb) { + write_succeeded = true; + fs.mkdir(local.config.static_content + + "albums/" + data.name, cb); + } + ], + function (err, results) { + // convert file errors to something we like. + if (err) { + if (write_succeeded) delete_album(dbc, data.name); + if (err instanceof Error && err.code == 'ER_EXISTS') + callback(backhelp.album_already_exists()); + else if (err instanceof Error && err.errno != undefined) + callback(backhelp.file_error(err)); + else + callback(err); + } else { + callback(err, err ? null : data); + } + + if (dbc) dbc.end(); + }); +}; + + +exports.album_by_name = function (name, callback) { + var dbc; + + async.waterfall([ + function (cb) { + if (!name) + cb(backhelp.missing_data("album name")); + else + db.db(cb); + }, + + function (dbclient, cb) { + dbc = dbclient; + dbc.query( + "SELECT * FROM Albums WHERE name = ?", + [ name ], + cb); + } + + ], + function (err, results) { + if (dbc) dbc.end(); + if (err) { + callback (err); + } else if (!results || results.length == 0) { + callback(backhelp.no_such_album()); + } else { + callback(null, results[0]); + } + }); +}; + + +exports.photos_for_album = function (album_name, skip, limit, callback) { + var dbc; + + async.waterfall([ + function (cb) { + if (!album_name) + cb(backhelp.missing_data("album name")); + else + db.db(cb); + }, + + function (dbclient, cb) { + dbc = dbclient; + dbc.query( + "SELECT * FROM Photos WHERE album_name = ? LIMIT ?, ?", + [ album_name, skip, limit ], + cb); + }, + + ], + function (err, results) { + if (dbc) dbc.end(); + if (err) { + callback (err); + } else { + callback(null, results); + } + }); +}; + + +exports.all_albums = function (sort_by, desc, skip, count, callback) { + var dbc; + async.waterfall([ + function (cb) { + db.db(cb); + }, + function (dbclient, cb) { + dbc = dbclient; + dbc.query( + "SELECT * FROM Albums ORDER BY ? " + + (desc ? "DESC" : "ASC") + + " LIMIT ?, ?", + [ sort_by, skip, count ], + cb); + } + ], + function (err, results) { + if (dbc) dbc.end(); + if (err) { + callback (err); + } else { + callback(null, results); + } + }); +}; + + +exports.add_photo = function (photo_data, path_to_photo, callback) { + var base_fn = path.basename(path_to_photo).toLowerCase(); + var write_succeeded = false; + var dbc; + + async.waterfall([ + // validate data + function (cb) { + try { + backhelp.verify(photo_data, + [ "albumid", "description", "date" ]); + photo_data.filename = base_fn; + if (!backhelp.valid_filename(photo_data.albumid)) + throw invalid_album_name(); + } catch (e) { + cb(e); + return; + } + db.db(cb); + }, + + function (dbclient, cb) { + dbc = dbclient; + dbc.query( + "INSERT INTO Photos VALUES (?, ?, ?, ?)", + [ photo_data.albumid, base_fn, photo_data.description, + photo_data.date ], + cb); + }, + + // now copy the temp file to static content + function (results, cb) { + write_succeeded = true; + var save_path = local.config.static_content + "albums/" + + photo_data.albumid + "/" + base_fn; + backhelp.file_copy(path_to_photo, save_path, true, cb); + }, + + ], + function (err, results) { + if (err && write_succeeded) + delete_photo(dbc, photo_data.albumid, base_fn); + if (err) { + callback (err); + } else { + // clone the object + var pd = JSON.parse(JSON.stringify(photo_data)); + pd.filename = base_fn; + callback(null, pd); + } + if (dbc) dbc.end(); + }); +}; + + +function invalid_album_name() { + return backhelp.error("invalid_album_name", + "Album names can have letters, #s, _ and, -"); +} +function invalid_filename() { + return backhelp.error("invalid_filename", + "Filenames can have letters, #s, _ and, -"); +} + + +function delete_album(dbc, name) { + dbc.query( + "DELETE FROM Albums WHERE name = ?", + [ name ], + function (err, results) {}); +} + +function delete_photo(dbc, albumid, fn) { + dbc.query( + "DELETE FROM Photos WHERE albumid = ? AND filename = ?", + [ albumid, fn ], + function (err, results) { }); +} + diff --git a/Chapter09/03_connection_pools/app/data/backend_helpers.js b/Chapter09/03_connection_pools/app/data/backend_helpers.js new file mode 100644 index 0000000..2df8e6b --- /dev/null +++ b/Chapter09/03_connection_pools/app/data/backend_helpers.js @@ -0,0 +1,117 @@ + +var fs = require('fs'); + + +exports.verify = function (data, field_names) { + for (var i = 0; i < field_names.length; i++) { + if (!data[field_names[i]]) { + throw exports.error("missing_data", + field_names[i] + " not optional"); + } + } + + return true; +} + +exports.error = function (code, message) { + var e = new Error(message); + e.code = code; + return e; +}; + +exports.file_error = function (err) { + return exports.error("file_error", JSON.stringify(err.message)); +} + + + +/** + * Possible signatures: + * src, dst, callback + * src, dst, can_overwrite, callback + */ +exports.file_copy = function () { + + var src, dst, callback; + var can_overwrite = false; + + if (arguments.length == 3) { + src = arguments[0]; + dst = arguments[1]; + callback = arguments[2]; + } else if (arguments.length == 4) { + src = arguments[0]; + dst = arguments[1]; + callback = arguments[3]; + can_overwrite = arguments[2] + } + + function copy(err) { + var is, os; + + if (!err && !can_overwrite) { + return callback(backhelp.error("file_exists", + "File " + dst + " exists.")); + } + + fs.stat(src, function (err) { + if (err) { + return callback(err); + } + + is = fs.createReadStream(src); + os = fs.createWriteStream(dst); + is.on('end', function () { callback(null); }); + is.on('error', function (e) { callback(e); }); + is.pipe(os); + }); + } + + fs.stat(dst, copy); +}; + + + +exports.valid_filename = function (fn) { + var re = /[^\.a-zA-Z0-9_-]/; + return typeof fn == 'string' && fn.length > 0 && !(fn.match(re)); +}; + + +exports.db_error = function () { + return exports.error("server_error", + "Something horrible has happened with our database!"); +}; + +exports.album_already_exists = function () { + return exports.error("album_already_exists", + "An album with this name already exists."); +}; + +exports.missing_data = function (field) { + return exports.error("missing_data", "You must provide: " + field); +}; + +exports.no_such_user = function () { + return exports.error("no_such_user", + "The specified user does not exist"); +}; + + +exports.user_already_registered = function () { + return exports.error("user_already_registered", + "This user appears to exist already!"); +}; + + + +/** + * node-mysql sometimes adds extra data to callbacks to be helpful. + * this can mess up our waterfall, however, so we'll strip those + * out. + */ +exports.mscb = function (cb) { + return function (err, results) { + cb(err, results); + } +} diff --git a/Chapter09/03_connection_pools/app/data/db.js b/Chapter09/03_connection_pools/app/data/db.js new file mode 100644 index 0000000..8bab0f1 --- /dev/null +++ b/Chapter09/03_connection_pools/app/data/db.js @@ -0,0 +1,62 @@ +var mysql = require('mysql'), + pool = require('generic-pool'), + async = require('async'), + local = require("../local.config.js"); + + +var mysql_pool; + + +/** + * Currently for initialisation, we + * the database. We won't even attempt to start up + * if this fails, as it's pretty pointless. + */ +exports.init = function (callback) { + + conn_props = local.config.db_config; + + mysql_pool = pool.Pool({ + name : 'mysql', + create : function (callback) { + var c = mysql.createConnection({ + host: conn_props.host, + user: conn_props.user, + password: conn_props.password, + database: conn_props.database + }); + callback(null, c); + }, + destroy : function(client) { client.end(); }, + max : conn_props.pooled_connections, + idleTimeoutMillis : conn_props.idle_timeout_millis, + log : false + }); + + // run a test query to make sure it's working. + exports.run_mysql_query("SELECT 1", [], function (err, results) { + if (err != null) { + callback(err); + console.error("Unable to connect to database server. Aborting."); + } else { + console.log("Database initialised and connected."); + callback(null); + } + }); + +}; + + +exports.run_mysql_query = function (query, values, callback) { + mysql_pool.acquire(function(err, mysqlconn) { + mysqlconn.query(query, values, function (mysqlerr, mysqlresults) { + mysql_pool.release(mysqlconn); + callback(mysqlerr, mysqlresults); + }); + }); +}; + + +exports.db = function (callback) { + mysql_pool.acquire(callback); +}; diff --git a/Chapter09/03_connection_pools/app/data/user.js b/Chapter09/03_connection_pools/app/data/user.js new file mode 100644 index 0000000..29fe49c --- /dev/null +++ b/Chapter09/03_connection_pools/app/data/user.js @@ -0,0 +1,127 @@ + +var async = require('async'), + bcrypt = require('bcrypt'), + db = require("./db.js"), + uuid = require('node-uuid'), + backhelp = require("./backend_helpers.js"); + + +exports.version = "0.1.0"; + +exports.user_by_uuid = function (uuid, callback) { + if (!uuid) + callback(backhelp.missing_data("uuid")); + else + user_by_field("user_uuid", uuid, callback); +}; + +exports.user_by_display_name = function (dn, callback) { + if (!dn) + callback(backhelp.missing_data("display_name")); + else + user_by_field("display_name", dn, callback); +} + +exports.user_by_email_address = function (email, callback) { + if (!email) + callback(backhelp.missing_data("email")); + else + user_by_field("email_address", email, callback); +}; + +exports.register = function (email, display_name, password, callback) { + var dbc; + var userid; + async.waterfall([ + // validate ze params + function (cb) { + if (!email || email.indexOf("@") == -1) + cb(backhelp.missing_data("email")); + else if (!display_name) + cb(backhelp.missing_data("display_name")); + else if (!password) + cb(backhelp.missing_data("password")); + else + cb(null); + }, + + // get a connection + function (cb) { + db.db(cb); + }, + + // generate a password hash + function (dbclient, cb) { + dbc = dbclient; + bcrypt.hash(password, 10, cb); + }, + + // register the account. + function (hash, cb) { + userid = uuid(); + var now = Math.round((new Date()).getTime() / 1000); + dbc.query( + "INSERT INTO Users VALUES (?, ?, ?, ?, ?, NULL, 0)", + [ userid, email.trim(), display_name.trim(), hash, now ], + cb); + }, + + // fetch and return the new user. + function (results, fields, cb) { + exports.user_by_uuid(userid, cb); + } + ], + function (err, user_data) { + if (dbc) dbc.end(); + if (err) { + if (err.code + && (err.code == 'ER_DUP_KEYNAME' + || err.code == 'ER_EXISTS' + || err.code == 'ER_DUP_ENTRY')) + callback(backhelp.user_already_registered()); + else + callback (err); + } else { + callback(null, user_data); + } + }); +}; + + + + +function user_by_field (field, value, callback) { + var dbc; + async.waterfall([ + // get a connection + function (cb) { + db.db(cb); + }, + + // fetch the user. + function (dbclient, cb) { + dbc = dbclient; + dbc.query( + "SELECT * FROM Users WHERE " + field + + " = ? AND deleted = false", + [ value ], + cb); + }, + + function (rows, fields, cb) { + if (!rows || rows.length == 0) + cb(backhelp.no_such_user()); + else + cb(null, rows[0]); + } + ], + function (err, user_data) { + if (dbc) dbc.end(); + if (err) { + callback (err); + } else { + console.log(user_data); + callback(null, user_data); + } + }); +} \ No newline at end of file diff --git a/Chapter09/03_connection_pools/app/handlers/albums.js b/Chapter09/03_connection_pools/app/handlers/albums.js new file mode 100644 index 0000000..ac2da86 --- /dev/null +++ b/Chapter09/03_connection_pools/app/handlers/albums.js @@ -0,0 +1,259 @@ + +var helpers = require('./helpers.js'), + album_data = require("../data/album.js"), + async = require('async'), + fs = require('fs'); + +exports.version = "0.1.0"; + + +/** + * Album class. + */ +function Album (album_data) { + this.name = album_data.name; + this.date = album_data.date; + this.title = album_data.title; + this.description = album_data.description; + this._id = album_data._id; +} + +Album.prototype.name = null; +Album.prototype.date = null; +Album.prototype.title = null; +Album.prototype.description = null; + +Album.prototype.response_obj = function () { + return { name: this.name, + date: this.date, + title: this.title, + description: this.description }; +}; +Album.prototype.photos = function (pn, ps, callback) { + if (this.album_photos != undefined) { + callback(null, this.album_photos); + return; + } + + album_data.photos_for_album( + this.name, + pn, ps, + function (err, results) { + if (err) { + callback(err); + return; + } + + var out = []; + for (var i = 0; i < results.length; i++) { + out.push(new Photo(results[i])); + } + + this.album_photos = out; + callback(null, this.album_photos); + } + ); +}; +Album.prototype.add_photo = function (data, path, callback) { + album_data.add_photo(data, path, function (err, photo_data) { + if (err) + callback(err); + else { + var p = new Photo(photo_data); + if (this.all_photos) + this.all_photos.push(p); + else + this.app_photos = [ p ]; + + callback(null, p); + } + }); +}; + + + + +/** + * Photo class. + */ +function Photo (photo_data) { + this.filename = photo_data.filename; + this.date = photo_data.date; + this.albumid = photo_data.albumid; + this.description = photo_data.description; + this._id = photo_data._id; +} +Photo.prototype._id = null; +Photo.prototype.filename = null; +Photo.prototype.date = null; +Photo.prototype.albumid = null; +Photo.prototype.description = null; +Photo.prototype.response_obj = function() { + return { + filename: this.filename, + date: this.date, + albumid: this.albumid, + description: this.description + }; +}; + + +/** + * Album module methods. + */ +exports.create_album = function (req, res) { + async.waterfall([ + // make sure the albumid is valid + function (cb) { + if (!req.body || !req.body.name) { + cb(helpers.no_such_album()); + return; + } + + // UNDONE: we should add some code to make sure the album + // doesn't already exist! + cb(null); + }, + + function (cb) { + album_data.create_album(req.body, cb); + } + ], + function (err, results) { + if (err) { + helpers.send_failure(res, err); + } else { + var a = new Album(results); + helpers.send_success(res, {album: a.response_obj() }); + } + }); +}; + + +exports.album_by_name = function (req, res) { + async.waterfall([ + // get the album + function (cb) { + if (!req.params || !req.params.album_name) + cb(helpers.no_such_album()); + else + album_data.album_by_name(req.params.album_name, cb); + } + ], + function (err, results) { + if (err) { + helpers.send_failure(res, err); + } else if (!results) { + helpers.send_failure(res, helpers.no_such_album()); + } else { + var a = new Album(album_data); + helpers.send_success(res, { album: a.response_obj() }); + } + }); +}; + + + +exports.list_all = function (req, res) { + album_data.all_albums("date", true, 0, 25, function (err, results) { + if (err) { + helpers.send_failure(res, err); + } else { + var out = []; + if (results) { + for (var i = 0; i < results.length; i++) { + out.push(new Album(results[i]).response_obj()); + } + } + helpers.send_success(res, { albums: out }); + } + }); +}; + + +exports.photos_for_album = function(req, res) { + var page_num = req.query.page ? req.query.page : 0; + var page_size = req.query.page_size ? req.query.page_size : 1000; + + page_num = parseInt(page_num); + page_size = parseInt(page_size); + if (isNaN(page_num)) page_num = 0; + if (isNaN(page_size)) page_size = 1000; + + var album; + async.waterfall([ + function (cb) { + // first get the album. + if (!req.params || !req.params.album_name) + cb(helpers.no_such_album()); + else + album_data.album_by_name(req.params.album_name, cb); + }, + + function (album_data, cb) { + if (!album_data) { + cb(helpers.no_such_album()); + return; + } + album = new Album(album_data); + album.photos(page_num, page_size, cb); + }, + function (photos, cb) { + var out = []; + for (var i = 0; i < photos.length; i++) { + out.push(photos[i].response_obj()); + } + cb(null, out); + } + ], + function (err, results) { + if (err) { + helpers.send_failure(res, err); + return; + } + if (!results) results = []; + var out = { photos: results, + album_data: album.response_obj() }; + helpers.send_success(res, out); + }); +}; + + +exports.add_photo_to_album = function (req, res) { + var album; + async.waterfall([ + // make sure we have everything we need. + function (cb) { + if (!req.body) + cb(helpers.missing_data("POST data")); + else if (!req.files || !req.files.photo_file) + cb(helpers.missing_data("a file")); + else if (!helpers.is_image(req.files.photo_file.name)) + cb(helpers.not_image()); + else + // get the album + album_data.album_by_name(req.params.album_name, cb); + }, + + function (album_data, cb) { + if (!album_data) { + cb(helpers.no_such_album()); + return; + } + + album = new Album(album_data); + req.body.filename = req.files.photo_file.name; + album.add_photo(req.body, req.files.photo_file.path, cb); + } + ], + function (err, p) { + if (err) { + helpers.send_failure(res, err); + return; + } + var out = { photo: p.response_obj(), + album_data: album.response_obj() }; + helpers.send_success(res, out); + }); +}; + diff --git a/Chapter09/03_connection_pools/app/handlers/helpers.js b/Chapter09/03_connection_pools/app/handlers/helpers.js new file mode 100644 index 0000000..e6f0a13 --- /dev/null +++ b/Chapter09/03_connection_pools/app/handlers/helpers.js @@ -0,0 +1,114 @@ + +var path = require('path'); + + +exports.version = '0.1.0'; + + + + +exports.send_success = function(res, data) { + res.writeHead(200, {"Content-Type": "application/json"}); + var output = { error: null, data: data }; + res.end(JSON.stringify(output) + "\n"); +} + + +exports.send_failure = function(res, err) { + console.log(err); + var code = (err.code) ? err.code : err.name; + res.writeHead(code, { "Content-Type" : "application/json" }); + res.end(JSON.stringify({ error: code, message: err.message }) + "\n"); +} + + +exports.error_for_resp = function (err) { + if (!err instanceof Error) { + console.error("** Unexpected error type! :" + + err.constructor.name); + return JSON.stringify(err); + } else { + var code = err.code ? err.code : err.name; + return JSON.stringify({ error: code, + message: err.message }); + } +} + +exports.error = function (code, message) { + var e = new Error(message); + e.code = code; + return e; +}; + +exports.file_error = function (err) { + return exports.error("file_error", JSON.stringify(err)); +}; + + +exports.is_image = function (filename) { + switch (path.extname(filename).toLowerCase()) { + case '.jpg': case '.jpeg': case '.png': case '.bmp': + case '.gif': case '.tif': case '.tiff': + return true; + } + + return false; +}; + + +exports.invalid_resource = function () { + return exports.error("invalid_resource", + "The requested resource does not exist."); +}; + + +exports.missing_data = function (what) { + return exports.error("missing_data", + "You must include " + what); +} + + +exports.not_image = function () { + return exports.error("not_image_file", + "The uploaded file must be an image file."); +}; + + +exports.no_such_album = function () { + return exports.error("no_such_album", + "The specified album does not exist"); +}; + + +exports.http_code_for_error = function (err) { + switch (err.message) { + case "no_such_album": + return 403; + case "invalid_resource": + return 404; + case "invalid_email_address": + return 403; + case "no_such_user": + return 403; + } + + console.log("*** Error needs HTTP response code: " + err.message); + return 503; +} + + +exports.valid_filename = function (fn) { + var re = /[^\.a-zA-Z0-9_-]/; + return typeof fn == 'string' && fn.length > 0 && !(fn.match(re)); +}; + + +exports.invalid_email_address = function () { + return exports.error("invalid_email_address", + "That's not a valid email address, sorry"); +}; + +exports.auth_failed = function () { + return exports.error("auth_failure", + "Invalid email address / password combination."); +}; \ No newline at end of file diff --git a/Chapter09/03_connection_pools/app/handlers/pages.js b/Chapter09/03_connection_pools/app/handlers/pages.js new file mode 100644 index 0000000..d80a263 --- /dev/null +++ b/Chapter09/03_connection_pools/app/handlers/pages.js @@ -0,0 +1,37 @@ + +var helpers = require('./helpers.js'), + fs = require('fs'); + + +exports.version = "0.1.0"; + + +exports.generate = function (req, res) { + + var page = req.params.page_name; + if (req.params.sub_page && req.params.page_name == 'admin') + page = req.params.page_name + "_" + req.params.sub_page; + + fs.readFile( + 'basic.html', + function (err, contents) { + if (err) { + send_failure(res, 500, err); + return; + } + + contents = contents.toString('utf8'); + + // replace page name, and then dump to output. + contents = contents.replace('{{PAGE_NAME}}', page); + res.writeHead(200, { "Content-Type": "text/html" }); + res.end(contents); + } + ); +}; + +// if we made it here, then we're logged in. redirect to admin home +exports.login = function (req, res) { + res.redirect("/pages/admin/home"); + res.end(); +}; diff --git a/Chapter09/03_connection_pools/app/handlers/users.js b/Chapter09/03_connection_pools/app/handlers/users.js new file mode 100644 index 0000000..9668cdd --- /dev/null +++ b/Chapter09/03_connection_pools/app/handlers/users.js @@ -0,0 +1,186 @@ +var helpers = require('./helpers.js'), + user_data = require("../data/user.js"), + async = require('async'), + bcrypt = require('bcrypt'), + fs = require('fs'); + +exports.version = "0.1.0"; + + +function User (user_data) { + this.uuid = user_data["user_uuid"]; + this.email_address = user_data["email_address"]; + this.display_name = user_data["display_name"]; + this.password = user_data["password"]; + this.first_seen_date = user_data["first_seen_date"]; + this.last_modified_date = user_data["last_modified_date"]; + this.deleted = user_data["deleted"]; +} + +User.prototype.uuid = null; +User.prototype.email_address = null; +User.prototype.display_name = null; +User.prototype.password = null; +User.prototype.first_seen_date = null; +User.prototype.last_modified_date = null; +User.prototype.deleted = false; +User.prototype.check_password = function (pw, callback) { + bcrypt.compare(pw, this.password, callback); +}; +User.prototype.response_obj = function () { + return { + uuid: this.uuid, + email_address: this.email_address, + display_name: this.display_name, + first_seen_date: this.first_seen_date, + last_modified_date: this.last_modified_date + }; +}; + + + +exports.register = function (req, res) { + async.waterfall([ + function (cb) { + var em = req.body.email_address; + if (!em || em.indexOf("@") == -1) + cb(helpers.invalid_email_address()); + else if (!req.body.display_name) + cb(helpers.missing_data("display_name")); + else if (!req.body.password) + cb(helpers.missing_data("password")); + else + cb(null); + }, + + // register da user. + function (cb) { + user_data.register( + req.body.email_address, + req.body.display_name, + req.body.password, + cb); + }, + + // mark user as logged in + function (user_data, cb) { + req.session.logged_in = true; + req.session.logged_in_display_name = req.body.display_name; + req.session.logged_in_date = new Date(); + cb(null, user_data); + } + ], + function (err, user_data) { + if (err) { + helpers.send_failure(res, err); + } else { + var u = new User(user_data); + helpers.send_success(res, {user: u.response_obj() }); + } + }); +}; + + +exports.login = function (req, res) { + var em = req.body.email_address + ? req.body.email_address.trim().toLowerCase() + : ""; + + async.waterfall([ + function (cb) { + if (!em) + cb(helpers.missing_data("email_address")); + else if (req.session + && req.session.logged_in_email_address == em) + cb(helpers.error("already_logged_in", "")); + else if (!req.body.password) + cb(helpers.missing_data("password")); + else + cb(null); + }, + + // first get the user by the email address. + function (cb) { + user_data.user_by_email_address(em, cb); + }, + + // check the password + function (user_data, cb) { + var u = new User(user_data); + u.check_password(req.body.password, cb); + }, + + function (auth_ok, cb) { + if (!auth_ok) { + cb(helpers.auth_failed()); + return; + } + + req.session.logged_in = true; + req.session.logged_in_email_address = req.body.email_address; + req.session.logged_in_date = new Date(); + cb(null); + } + ], + function (err, results) { + if (!err || err.message == "already_logged_in") { + helpers.send_success(res, { logged_in: true }); + } else { + helpers.send_failure(res, err); + } + }); +}; + + +exports.user_by_display_name = function (req, res) { + async.waterfall([ + // first get the user by the email address. + function (cb) { + user_data.user_by_display_name(req.body.email_address, cb); + } + ], + function (err, u) { + if (!err) { + helpers.send_success(res, { user: u.response_obj() }); + } else { + helpers.send_failure(res, err); + } + }); +}; + + +exports.authenticate_API = function (un, pw, callback) { + if (req.session && req.session.logged_in + && req.session.logged_in_email_address == un) { + callback(null, un); + return; + } + + async.waterfall([ + function (cb) { + user_data.user_by_email_address(un, cb); + }, + + function (user_data, cb) { + var u = new User(user_data); + u.check_password(pw, cb); + } + ], + function (err, results) { + if (!err) { + callback(null, un); + } else { + callback(new Error("bogus credentials")); + } + }); +}; + +exports.logged_in = function (req, res) { + var li = (req.session && req.session.logged_in_email_address); + helpers.send_success(res, { logged_in: li }); +}; + +exports.logout = function (req, res) { + req.session = null; + helpers.send_success(res, { logged_out: true }); +}; diff --git a/Chapter09/03_connection_pools/app/local.config.js b/Chapter09/03_connection_pools/app/local.config.js new file mode 100644 index 0000000..85e0a8d --- /dev/null +++ b/Chapter09/03_connection_pools/app/local.config.js @@ -0,0 +1,16 @@ + + +exports.config = { + db_config: { + host: "localhost", + user: "root", + password: "", + database: "PhotoAlbums", + + pooled_connections: 125, + idle_timeout_millis: 30000 + }, + + static_content: "../static/" +}; + diff --git a/Chapter09/03_connection_pools/app/package.json b/Chapter09/03_connection_pools/app/package.json new file mode 100644 index 0000000..a6f903b --- /dev/null +++ b/Chapter09/03_connection_pools/app/package.json @@ -0,0 +1,14 @@ +{ + "name": "MySQL-Demo", + "description": "Demonstrates Using MySQL Database connectivity", + "version": "0.0.1", + "private": true, + "dependencies": { + "express": "3.x", + "async": "0.1.x", + "generic-pool": "2.x", + "mysql": "2.x", + "bcrypt": "0.x", + "node-uuid": "1.x" + } +} diff --git a/Chapter09/03_connection_pools/app/server.js b/Chapter09/03_connection_pools/app/server.js new file mode 100644 index 0000000..6e2b17c --- /dev/null +++ b/Chapter09/03_connection_pools/app/server.js @@ -0,0 +1,73 @@ + +var express = require('express'); +var app = express(); + +var db = require('./data/db.js'), + album_hdlr = require('./handlers/albums.js'), + page_hdlr = require('./handlers/pages.js'), + user_hdlr = require('./handlers/users.js'), + helpers = require('./handlers/helpers.js'); + +app.use(express.logger('dev')); +app.use(express.bodyParser({ keepExtensions: true })); +app.use(express.static(__dirname + "/../static")); +app.use(express.cookieParser("kitten on keyboard")); +app.use(express.cookieSession({ + secret: "FLUFFY BUNNIES", + maxAge: 86400000 +})); + +/** + * API Server requests. + */ +app.get('/v1/albums.json', album_hdlr.list_all); +app.get('/v1/albums/:album_name.json', album_hdlr.album_by_name); +app.put('/v1/albums.json', album_hdlr.create_album); + +app.get('/v1/albums/:album_name/photos.json', album_hdlr.photos_for_album); +app.put('/v1/albums/:album_name/photos.json', album_hdlr.add_photo_to_album); + +app.put('/v1/users.json', user_hdlr.register); + + +/** + * add-on requests we support for the purposes of the web interface + * to the server. + */ +app.get('/pages/:page_name', requirePageLogin, page_hdlr.generate); +app.get('/pages/:page_name/:sub_page', requirePageLogin, page_hdlr.generate); +app.post('/service/login', user_hdlr.login); + + +app.get("/", function (req, res) { + res.redirect("/pages/home"); + res.end(); +}); + +app.get('*', four_oh_four); + +function four_oh_four(req, res) { + res.writeHead(404, { "Content-Type" : "application/json" }); + res.end(JSON.stringify(helpers.invalid_resource()) + "\n"); +} + +function requirePageLogin(req, res, next) { + if (req.params && req.params.page_name == 'admin') { + if (req.session && req.session.logged_in) { + next(); + } else { + res.redirect("/pages/login"); + } + } else + next(); +} + +require('./data/db.js').init(function (err) { + if (err) { + console.log("\nFATAL ERROR INITIALISING DATABASE:"); + console.log(err); + } else { + app.listen(8080); + } +}); + diff --git a/Chapter09/03_connection_pools/schema.sql b/Chapter09/03_connection_pools/schema.sql new file mode 100644 index 0000000..61ab5c3 --- /dev/null +++ b/Chapter09/03_connection_pools/schema.sql @@ -0,0 +1,53 @@ +DROP DATABASE IF EXISTS PhotoAlbums; + + +CREATE DATABASE PhotoAlbums + DEFAULT CHARACTER SET utf8 + DEFAULT COLLATE utf8_general_ci; + +USE PhotoAlbums; + + +CREATE TABLE Albums +( + name VARCHAR(50) UNIQUE PRIMARY KEY, + title VARCHAR(100), + date DATETIME, + description VARCHAR(500), + + -- allow for sorting on date. + INDEX(date) +) +ENGINE = InnoDB; + +CREATE TABLE Photos +( + album_name VARCHAR(50), + filename VARCHAR(50), + description VARCHAR(500), + date DATETIME, + + FOREIGN KEY (album_name) REFERENCES Albums (name), + INDEX (album_name, date) +) +ENGINE = InnoDB; + + +CREATE TABLE Users +( + user_uuid VARCHAR(50) UNIQUE PRIMARY KEY, + email_address VARCHAR(150) UNIQUE, + + display_name VARCHAR(100) UNIQUE, + password VARCHAR(100), + + first_seen_date BIGINT, + last_modified_date BIGINT, + deleted BOOL DEFAULT false, + + INDEX(email_address, deleted), + INDEX(user_uuid, deleted) +) +ENGINE = InnoDB; + + diff --git a/Chapter09/03_connection_pools/static/albums/australia2010/aus_01.jpg b/Chapter09/03_connection_pools/static/albums/australia2010/aus_01.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter09/03_connection_pools/static/albums/australia2010/aus_02.jpg b/Chapter09/03_connection_pools/static/albums/australia2010/aus_02.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter09/03_connection_pools/static/albums/australia2010/aus_03.jpg b/Chapter09/03_connection_pools/static/albums/australia2010/aus_03.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter09/03_connection_pools/static/albums/australia2010/aus_04.jpg b/Chapter09/03_connection_pools/static/albums/australia2010/aus_04.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter09/03_connection_pools/static/albums/australia2010/aus_05.jpg b/Chapter09/03_connection_pools/static/albums/australia2010/aus_05.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter09/03_connection_pools/static/albums/australia2010/aus_06.jpg b/Chapter09/03_connection_pools/static/albums/australia2010/aus_06.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter09/03_connection_pools/static/albums/australia2010/aus_07.jpg b/Chapter09/03_connection_pools/static/albums/australia2010/aus_07.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter09/03_connection_pools/static/albums/australia2010/aus_08.jpg b/Chapter09/03_connection_pools/static/albums/australia2010/aus_08.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter09/03_connection_pools/static/albums/australia2010/aus_09.jpg b/Chapter09/03_connection_pools/static/albums/australia2010/aus_09.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter09/03_connection_pools/static/albums/italy2012/picture_01.jpg b/Chapter09/03_connection_pools/static/albums/italy2012/picture_01.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter09/03_connection_pools/static/albums/italy2012/picture_02.jpg b/Chapter09/03_connection_pools/static/albums/italy2012/picture_02.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter09/03_connection_pools/static/albums/italy2012/picture_03.jpg b/Chapter09/03_connection_pools/static/albums/italy2012/picture_03.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter09/03_connection_pools/static/albums/italy2012/picture_04.jpg b/Chapter09/03_connection_pools/static/albums/italy2012/picture_04.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter09/03_connection_pools/static/albums/italy2012/picture_05.jpg b/Chapter09/03_connection_pools/static/albums/italy2012/picture_05.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter09/03_connection_pools/static/albums/japan2010/picture_001.jpg b/Chapter09/03_connection_pools/static/albums/japan2010/picture_001.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter09/03_connection_pools/static/albums/japan2010/picture_002.jpg b/Chapter09/03_connection_pools/static/albums/japan2010/picture_002.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter09/03_connection_pools/static/albums/japan2010/picture_003.jpg b/Chapter09/03_connection_pools/static/albums/japan2010/picture_003.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter09/03_connection_pools/static/albums/japan2010/picture_004.jpg b/Chapter09/03_connection_pools/static/albums/japan2010/picture_004.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter09/03_connection_pools/static/albums/japan2010/picture_005.jpg b/Chapter09/03_connection_pools/static/albums/japan2010/picture_005.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter09/03_connection_pools/static/albums/japan2010/picture_006.jpg b/Chapter09/03_connection_pools/static/albums/japan2010/picture_006.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter09/03_connection_pools/static/albums/japan2010/picture_007.jpg b/Chapter09/03_connection_pools/static/albums/japan2010/picture_007.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter09/03_connection_pools/static/content/#album.js# b/Chapter09/03_connection_pools/static/content/#album.js# new file mode 100644 index 0000000..442c047 --- /dev/null +++ b/Chapter09/03_connection_pools/static/content/#album.js# @@ -0,0 +1,60 @@ +$(function(){ + + var tmpl, // Main template HTML + tdata = {}; // JSON data object that feeds the template + + // Initialise page + var initPage = function() { + + // get our album name. + var re = "/pages/album/([a-zA-Z0-9_-]+)"; + var results = new RegExp(re).exec(window.location.href); + var album_name = results[1]; + + // Load the HTML template + $.get("/templates/album.html", function(d){ + tmpl = d; + }); + + var p = $.urlParam("page"); + var ps = $.urlParam("page_size"); + if (p < 0) p = 0; + if (ps <= 0) ps = 1000; + + var qs = "?page=" + p + "&page_size=" + ps; + var url = "/v1/albums/" + album_name + "/photos.json" + qs; + + // Retrieve the server data and then initialise the page + $.getJSON(url, function (d) { + var photo_d = massage_album(d); + $.extend(tdata, photo_d); + }); + + // When AJAX calls are complete parse the template + // replacing mustache tags with vars + $(document).ajaxStop(function () { + var renderedPage = Mustache.to_html( tmpl, tdata ); + $("body").html( renderedPage ); + }) + }(); +}); + + +function massage_album(d) { + if (d.error != null) return d; + var obj = { photos: [] }; + + var p = d.data.photos; + var a = d.data.album_data; + + for (var i = 0; i < p.length; i++) { + var url = "/albums/" + a.name + "/" + p[i].filename; + obj.photos.push({ url: url, desc: p[i].description }); + } + + if (obj.photos.length > 0) obj.has_photos = obj.photos.length; + return obj; +} + + +xundo \ No newline at end of file diff --git a/Chapter09/03_connection_pools/static/content/admin_add_album.js b/Chapter09/03_connection_pools/static/content/admin_add_album.js new file mode 100644 index 0000000..f2987d6 --- /dev/null +++ b/Chapter09/03_connection_pools/static/content/admin_add_album.js @@ -0,0 +1,22 @@ +$(function(){ + + var tmpl, // Main template HTML + tdata = {}; // JSON data object that feeds the template + + // Initialise page + var initPage = function() { + + // Load the HTML template + $.get("/templates/admin_add_album.html", function(d){ + tmpl = d; + }); + + // When AJAX calls are complete parse the template + // replacing mustache tags with vars + $(document).ajaxStop(function () { + var renderedPage = Mustache.to_html( tmpl, tdata ); + $("body").html( renderedPage ); + }) + }(); +}); + diff --git a/Chapter09/03_connection_pools/static/content/admin_add_photos.js b/Chapter09/03_connection_pools/static/content/admin_add_photos.js new file mode 100644 index 0000000..350e536 --- /dev/null +++ b/Chapter09/03_connection_pools/static/content/admin_add_photos.js @@ -0,0 +1,27 @@ +$(function(){ + + var tmpl, // Main template HTML + tdata = {}; // JSON data object that feeds the template + + // Initialise page + var initPage = function() { + + // Load the HTML template + $.get("/templates/admin_add_photos.html", function(d){ + tmpl = d; + }); + + // Retrieve the server data and then initialise the page + $.getJSON("/v1/albums.json", function (d) { + $.extend(tdata, d.data); + }); + + // When AJAX calls are complete parse the template + // replacing mustache tags with vars + $(document).ajaxStop(function () { + var renderedPage = Mustache.to_html( tmpl, tdata ); + $("body").html( renderedPage ); + }) + }(); +}); + diff --git a/Chapter09/03_connection_pools/static/content/admin_home.js b/Chapter09/03_connection_pools/static/content/admin_home.js new file mode 100644 index 0000000..820f7fd --- /dev/null +++ b/Chapter09/03_connection_pools/static/content/admin_home.js @@ -0,0 +1,22 @@ +$(function(){ + + var tmpl, // Main template HTML + tdata = {}; // JSON data object that feeds the template + + // Initialise page + var initPage = function() { + + // Load the HTML template + $.get("/templates/admin_home.html", function(d){ + tmpl = d; + }); + + // When AJAX calls are complete parse the template + // replacing mustache tags with vars + $(document).ajaxStop(function () { + var renderedPage = Mustache.to_html( tmpl, tdata ); + $("body").html( renderedPage ); + }) + }(); +}); + diff --git a/Chapter09/03_connection_pools/static/content/album.js b/Chapter09/03_connection_pools/static/content/album.js new file mode 100644 index 0000000..c4d918e --- /dev/null +++ b/Chapter09/03_connection_pools/static/content/album.js @@ -0,0 +1,67 @@ +$(function(){ + + var tmpl, // Main template HTML + tdata = {}; // JSON data object that feeds the template + + // Initialise page + var initPage = function() { + + // get our album name. + var re = "/pages/album/([a-zA-Z0-9_-]+)"; + var results = new RegExp(re).exec(window.location.href); + var album_name = results[1]; + + // Load the HTML template + $.get("/templates/album.html", function(d){ + tmpl = d; + }); + + var p = $.urlParam("page"); + var ps = $.urlParam("page_size"); + if (p < 0) p = 0; + if (ps <= 0) ps = 1000; + + var qs = "?page=" + p + "&page_size=" + ps; + var url = "/v1/albums/" + album_name + "/photos.json" + qs; + + // Retrieve the server data and then initialise the page + $.getJSON(url, function (d) { + var photo_d = massage_album(d); + $.extend(tdata, photo_d); + }); + + // When AJAX calls are complete parse the template + // replacing mustache tags with vars + $(document).ajaxStop(function () { + var renderedPage = Mustache.to_html( tmpl, tdata ); + $("body").html( renderedPage ); + }) + }(); +}); + + +function massage_album(d) { + if (d.error != null) return d; + var obj = { photos: [] }; + + var p = d.data.photos; + var a = d.data.album_data; + + for (var i = 0; i < p.length; i++) { + var url = "/albums/" + a.name + "/" + p[i].filename; + obj.photos.push({ url: url, desc: p[i].description }); + } + + if (obj.photos.length > 0) obj.has_photos = obj.photos.length; + return obj; +} + + +$.urlParam = function(name){ + var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href); + if (!results) + { + return 0; + } + return results[1] || 0; +} \ No newline at end of file diff --git a/Chapter09/03_connection_pools/static/content/home.js b/Chapter09/03_connection_pools/static/content/home.js new file mode 100644 index 0000000..fa7010b --- /dev/null +++ b/Chapter09/03_connection_pools/static/content/home.js @@ -0,0 +1,28 @@ +$(function(){ + + var tmpl, // Main template HTML + tdata = {}; // JSON data object that feeds the template + + // Initialise page + var initPage = function() { + + // Load the HTML template + $.get("/templates/home.html", function(d){ + tmpl = d; + }); + + + // Retrieve the server data and then initialise the page + $.getJSON("/v1/albums.json", function (d) { + $.extend(tdata, d.data); + }); + + // When AJAX calls are complete parse the template + // replacing mustache tags with vars + $(document).ajaxStop(function () { + var renderedPage = Mustache.to_html( tmpl, tdata ); + $("body").html( renderedPage ); + }) + }(); +}); + diff --git a/Chapter09/03_connection_pools/static/content/jquery-1.8.3.min.js b/Chapter09/03_connection_pools/static/content/jquery-1.8.3.min.js new file mode 100644 index 0000000..83589da --- /dev/null +++ b/Chapter09/03_connection_pools/static/content/jquery-1.8.3.min.js @@ -0,0 +1,2 @@ +/*! jQuery v1.8.3 jquery.com | jquery.org/license */ +(function(e,t){function _(e){var t=M[e]={};return v.each(e.split(y),function(e,n){t[n]=!0}),t}function H(e,n,r){if(r===t&&e.nodeType===1){var i="data-"+n.replace(P,"-$1").toLowerCase();r=e.getAttribute(i);if(typeof r=="string"){try{r=r==="true"?!0:r==="false"?!1:r==="null"?null:+r+""===r?+r:D.test(r)?v.parseJSON(r):r}catch(s){}v.data(e,n,r)}else r=t}return r}function B(e){var t;for(t in e){if(t==="data"&&v.isEmptyObject(e[t]))continue;if(t!=="toJSON")return!1}return!0}function et(){return!1}function tt(){return!0}function ut(e){return!e||!e.parentNode||e.parentNode.nodeType===11}function at(e,t){do e=e[t];while(e&&e.nodeType!==1);return e}function ft(e,t,n){t=t||0;if(v.isFunction(t))return v.grep(e,function(e,r){var i=!!t.call(e,r,e);return i===n});if(t.nodeType)return v.grep(e,function(e,r){return e===t===n});if(typeof t=="string"){var r=v.grep(e,function(e){return e.nodeType===1});if(it.test(t))return v.filter(t,r,!n);t=v.filter(t,r)}return v.grep(e,function(e,r){return v.inArray(e,t)>=0===n})}function lt(e){var t=ct.split("|"),n=e.createDocumentFragment();if(n.createElement)while(t.length)n.createElement(t.pop());return n}function Lt(e,t){return e.getElementsByTagName(t)[0]||e.appendChild(e.ownerDocument.createElement(t))}function At(e,t){if(t.nodeType!==1||!v.hasData(e))return;var n,r,i,s=v._data(e),o=v._data(t,s),u=s.events;if(u){delete o.handle,o.events={};for(n in u)for(r=0,i=u[n].length;r").appendTo(i.body),n=t.css("display");t.remove();if(n==="none"||n===""){Pt=i.body.appendChild(Pt||v.extend(i.createElement("iframe"),{frameBorder:0,width:0,height:0}));if(!Ht||!Pt.createElement)Ht=(Pt.contentWindow||Pt.contentDocument).document,Ht.write(""),Ht.close();t=Ht.body.appendChild(Ht.createElement(e)),n=Dt(t,"display"),i.body.removeChild(Pt)}return Wt[e]=n,n}function fn(e,t,n,r){var i;if(v.isArray(t))v.each(t,function(t,i){n||sn.test(e)?r(e,i):fn(e+"["+(typeof i=="object"?t:"")+"]",i,n,r)});else if(!n&&v.type(t)==="object")for(i in t)fn(e+"["+i+"]",t[i],n,r);else r(e,t)}function Cn(e){return function(t,n){typeof t!="string"&&(n=t,t="*");var r,i,s,o=t.toLowerCase().split(y),u=0,a=o.length;if(v.isFunction(n))for(;u)[^>]*$|#([\w\-]*)$)/,E=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,S=/^[\],:{}\s]*$/,x=/(?:^|:|,)(?:\s*\[)+/g,T=/\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,N=/"[^"\\\r\n]*"|true|false|null|-?(?:\d\d*\.|)\d+(?:[eE][\-+]?\d+|)/g,C=/^-ms-/,k=/-([\da-z])/gi,L=function(e,t){return(t+"").toUpperCase()},A=function(){i.addEventListener?(i.removeEventListener("DOMContentLoaded",A,!1),v.ready()):i.readyState==="complete"&&(i.detachEvent("onreadystatechange",A),v.ready())},O={};v.fn=v.prototype={constructor:v,init:function(e,n,r){var s,o,u,a;if(!e)return this;if(e.nodeType)return this.context=this[0]=e,this.length=1,this;if(typeof e=="string"){e.charAt(0)==="<"&&e.charAt(e.length-1)===">"&&e.length>=3?s=[null,e,null]:s=w.exec(e);if(s&&(s[1]||!n)){if(s[1])return n=n instanceof v?n[0]:n,a=n&&n.nodeType?n.ownerDocument||n:i,e=v.parseHTML(s[1],a,!0),E.test(s[1])&&v.isPlainObject(n)&&this.attr.call(e,n,!0),v.merge(this,e);o=i.getElementById(s[2]);if(o&&o.parentNode){if(o.id!==s[2])return r.find(e);this.length=1,this[0]=o}return this.context=i,this.selector=e,this}return!n||n.jquery?(n||r).find(e):this.constructor(n).find(e)}return v.isFunction(e)?r.ready(e):(e.selector!==t&&(this.selector=e.selector,this.context=e.context),v.makeArray(e,this))},selector:"",jquery:"1.8.3",length:0,size:function(){return this.length},toArray:function(){return l.call(this)},get:function(e){return e==null?this.toArray():e<0?this[this.length+e]:this[e]},pushStack:function(e,t,n){var r=v.merge(this.constructor(),e);return r.prevObject=this,r.context=this.context,t==="find"?r.selector=this.selector+(this.selector?" ":"")+n:t&&(r.selector=this.selector+"."+t+"("+n+")"),r},each:function(e,t){return v.each(this,e,t)},ready:function(e){return v.ready.promise().done(e),this},eq:function(e){return e=+e,e===-1?this.slice(e):this.slice(e,e+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(l.apply(this,arguments),"slice",l.call(arguments).join(","))},map:function(e){return this.pushStack(v.map(this,function(t,n){return e.call(t,n,t)}))},end:function(){return this.prevObject||this.constructor(null)},push:f,sort:[].sort,splice:[].splice},v.fn.init.prototype=v.fn,v.extend=v.fn.extend=function(){var e,n,r,i,s,o,u=arguments[0]||{},a=1,f=arguments.length,l=!1;typeof u=="boolean"&&(l=u,u=arguments[1]||{},a=2),typeof u!="object"&&!v.isFunction(u)&&(u={}),f===a&&(u=this,--a);for(;a0)return;r.resolveWith(i,[v]),v.fn.trigger&&v(i).trigger("ready").off("ready")},isFunction:function(e){return v.type(e)==="function"},isArray:Array.isArray||function(e){return v.type(e)==="array"},isWindow:function(e){return e!=null&&e==e.window},isNumeric:function(e){return!isNaN(parseFloat(e))&&isFinite(e)},type:function(e){return e==null?String(e):O[h.call(e)]||"object"},isPlainObject:function(e){if(!e||v.type(e)!=="object"||e.nodeType||v.isWindow(e))return!1;try{if(e.constructor&&!p.call(e,"constructor")&&!p.call(e.constructor.prototype,"isPrototypeOf"))return!1}catch(n){return!1}var r;for(r in e);return r===t||p.call(e,r)},isEmptyObject:function(e){var t;for(t in e)return!1;return!0},error:function(e){throw new Error(e)},parseHTML:function(e,t,n){var r;return!e||typeof e!="string"?null:(typeof t=="boolean"&&(n=t,t=0),t=t||i,(r=E.exec(e))?[t.createElement(r[1])]:(r=v.buildFragment([e],t,n?null:[]),v.merge([],(r.cacheable?v.clone(r.fragment):r.fragment).childNodes)))},parseJSON:function(t){if(!t||typeof t!="string")return null;t=v.trim(t);if(e.JSON&&e.JSON.parse)return e.JSON.parse(t);if(S.test(t.replace(T,"@").replace(N,"]").replace(x,"")))return(new Function("return "+t))();v.error("Invalid JSON: "+t)},parseXML:function(n){var r,i;if(!n||typeof n!="string")return null;try{e.DOMParser?(i=new DOMParser,r=i.parseFromString(n,"text/xml")):(r=new ActiveXObject("Microsoft.XMLDOM"),r.async="false",r.loadXML(n))}catch(s){r=t}return(!r||!r.documentElement||r.getElementsByTagName("parsererror").length)&&v.error("Invalid XML: "+n),r},noop:function(){},globalEval:function(t){t&&g.test(t)&&(e.execScript||function(t){e.eval.call(e,t)})(t)},camelCase:function(e){return e.replace(C,"ms-").replace(k,L)},nodeName:function(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()},each:function(e,n,r){var i,s=0,o=e.length,u=o===t||v.isFunction(e);if(r){if(u){for(i in e)if(n.apply(e[i],r)===!1)break}else for(;s0&&e[0]&&e[a-1]||a===0||v.isArray(e));if(f)for(;u-1)a.splice(n,1),i&&(n<=o&&o--,n<=u&&u--)}),this},has:function(e){return v.inArray(e,a)>-1},empty:function(){return a=[],this},disable:function(){return a=f=n=t,this},disabled:function(){return!a},lock:function(){return f=t,n||c.disable(),this},locked:function(){return!f},fireWith:function(e,t){return t=t||[],t=[e,t.slice?t.slice():t],a&&(!r||f)&&(i?f.push(t):l(t)),this},fire:function(){return c.fireWith(this,arguments),this},fired:function(){return!!r}};return c},v.extend({Deferred:function(e){var t=[["resolve","done",v.Callbacks("once memory"),"resolved"],["reject","fail",v.Callbacks("once memory"),"rejected"],["notify","progress",v.Callbacks("memory")]],n="pending",r={state:function(){return n},always:function(){return i.done(arguments).fail(arguments),this},then:function(){var e=arguments;return v.Deferred(function(n){v.each(t,function(t,r){var s=r[0],o=e[t];i[r[1]](v.isFunction(o)?function(){var e=o.apply(this,arguments);e&&v.isFunction(e.promise)?e.promise().done(n.resolve).fail(n.reject).progress(n.notify):n[s+"With"](this===i?n:this,[e])}:n[s])}),e=null}).promise()},promise:function(e){return e!=null?v.extend(e,r):r}},i={};return r.pipe=r.then,v.each(t,function(e,s){var o=s[2],u=s[3];r[s[1]]=o.add,u&&o.add(function(){n=u},t[e^1][2].disable,t[2][2].lock),i[s[0]]=o.fire,i[s[0]+"With"]=o.fireWith}),r.promise(i),e&&e.call(i,i),i},when:function(e){var t=0,n=l.call(arguments),r=n.length,i=r!==1||e&&v.isFunction(e.promise)?r:0,s=i===1?e:v.Deferred(),o=function(e,t,n){return function(r){t[e]=this,n[e]=arguments.length>1?l.call(arguments):r,n===u?s.notifyWith(t,n):--i||s.resolveWith(t,n)}},u,a,f;if(r>1){u=new Array(r),a=new Array(r),f=new Array(r);for(;t
a",n=p.getElementsByTagName("*"),r=p.getElementsByTagName("a")[0];if(!n||!r||!n.length)return{};s=i.createElement("select"),o=s.appendChild(i.createElement("option")),u=p.getElementsByTagName("input")[0],r.style.cssText="top:1px;float:left;opacity:.5",t={leadingWhitespace:p.firstChild.nodeType===3,tbody:!p.getElementsByTagName("tbody").length,htmlSerialize:!!p.getElementsByTagName("link").length,style:/top/.test(r.getAttribute("style")),hrefNormalized:r.getAttribute("href")==="/a",opacity:/^0.5/.test(r.style.opacity),cssFloat:!!r.style.cssFloat,checkOn:u.value==="on",optSelected:o.selected,getSetAttribute:p.className!=="t",enctype:!!i.createElement("form").enctype,html5Clone:i.createElement("nav").cloneNode(!0).outerHTML!=="<:nav>",boxModel:i.compatMode==="CSS1Compat",submitBubbles:!0,changeBubbles:!0,focusinBubbles:!1,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0,boxSizingReliable:!0,pixelPosition:!1},u.checked=!0,t.noCloneChecked=u.cloneNode(!0).checked,s.disabled=!0,t.optDisabled=!o.disabled;try{delete p.test}catch(d){t.deleteExpando=!1}!p.addEventListener&&p.attachEvent&&p.fireEvent&&(p.attachEvent("onclick",h=function(){t.noCloneEvent=!1}),p.cloneNode(!0).fireEvent("onclick"),p.detachEvent("onclick",h)),u=i.createElement("input"),u.value="t",u.setAttribute("type","radio"),t.radioValue=u.value==="t",u.setAttribute("checked","checked"),u.setAttribute("name","t"),p.appendChild(u),a=i.createDocumentFragment(),a.appendChild(p.lastChild),t.checkClone=a.cloneNode(!0).cloneNode(!0).lastChild.checked,t.appendChecked=u.checked,a.removeChild(u),a.appendChild(p);if(p.attachEvent)for(l in{submit:!0,change:!0,focusin:!0})f="on"+l,c=f in p,c||(p.setAttribute(f,"return;"),c=typeof p[f]=="function"),t[l+"Bubbles"]=c;return v(function(){var n,r,s,o,u="padding:0;margin:0;border:0;display:block;overflow:hidden;",a=i.getElementsByTagName("body")[0];if(!a)return;n=i.createElement("div"),n.style.cssText="visibility:hidden;border:0;width:0;height:0;position:static;top:0;margin-top:1px",a.insertBefore(n,a.firstChild),r=i.createElement("div"),n.appendChild(r),r.innerHTML="
t
",s=r.getElementsByTagName("td"),s[0].style.cssText="padding:0;margin:0;border:0;display:none",c=s[0].offsetHeight===0,s[0].style.display="",s[1].style.display="none",t.reliableHiddenOffsets=c&&s[0].offsetHeight===0,r.innerHTML="",r.style.cssText="box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;",t.boxSizing=r.offsetWidth===4,t.doesNotIncludeMarginInBodyOffset=a.offsetTop!==1,e.getComputedStyle&&(t.pixelPosition=(e.getComputedStyle(r,null)||{}).top!=="1%",t.boxSizingReliable=(e.getComputedStyle(r,null)||{width:"4px"}).width==="4px",o=i.createElement("div"),o.style.cssText=r.style.cssText=u,o.style.marginRight=o.style.width="0",r.style.width="1px",r.appendChild(o),t.reliableMarginRight=!parseFloat((e.getComputedStyle(o,null)||{}).marginRight)),typeof r.style.zoom!="undefined"&&(r.innerHTML="",r.style.cssText=u+"width:1px;padding:1px;display:inline;zoom:1",t.inlineBlockNeedsLayout=r.offsetWidth===3,r.style.display="block",r.style.overflow="visible",r.innerHTML="
",r.firstChild.style.width="5px",t.shrinkWrapBlocks=r.offsetWidth!==3,n.style.zoom=1),a.removeChild(n),n=r=s=o=null}),a.removeChild(p),n=r=s=o=u=a=p=null,t}();var D=/(?:\{[\s\S]*\}|\[[\s\S]*\])$/,P=/([A-Z])/g;v.extend({cache:{},deletedIds:[],uuid:0,expando:"jQuery"+(v.fn.jquery+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(e){return e=e.nodeType?v.cache[e[v.expando]]:e[v.expando],!!e&&!B(e)},data:function(e,n,r,i){if(!v.acceptData(e))return;var s,o,u=v.expando,a=typeof n=="string",f=e.nodeType,l=f?v.cache:e,c=f?e[u]:e[u]&&u;if((!c||!l[c]||!i&&!l[c].data)&&a&&r===t)return;c||(f?e[u]=c=v.deletedIds.pop()||v.guid++:c=u),l[c]||(l[c]={},f||(l[c].toJSON=v.noop));if(typeof n=="object"||typeof n=="function")i?l[c]=v.extend(l[c],n):l[c].data=v.extend(l[c].data,n);return s=l[c],i||(s.data||(s.data={}),s=s.data),r!==t&&(s[v.camelCase(n)]=r),a?(o=s[n],o==null&&(o=s[v.camelCase(n)])):o=s,o},removeData:function(e,t,n){if(!v.acceptData(e))return;var r,i,s,o=e.nodeType,u=o?v.cache:e,a=o?e[v.expando]:v.expando;if(!u[a])return;if(t){r=n?u[a]:u[a].data;if(r){v.isArray(t)||(t in r?t=[t]:(t=v.camelCase(t),t in r?t=[t]:t=t.split(" ")));for(i=0,s=t.length;i1,null,!1))},removeData:function(e){return this.each(function(){v.removeData(this,e)})}}),v.extend({queue:function(e,t,n){var r;if(e)return t=(t||"fx")+"queue",r=v._data(e,t),n&&(!r||v.isArray(n)?r=v._data(e,t,v.makeArray(n)):r.push(n)),r||[]},dequeue:function(e,t){t=t||"fx";var n=v.queue(e,t),r=n.length,i=n.shift(),s=v._queueHooks(e,t),o=function(){v.dequeue(e,t)};i==="inprogress"&&(i=n.shift(),r--),i&&(t==="fx"&&n.unshift("inprogress"),delete s.stop,i.call(e,o,s)),!r&&s&&s.empty.fire()},_queueHooks:function(e,t){var n=t+"queueHooks";return v._data(e,n)||v._data(e,n,{empty:v.Callbacks("once memory").add(function(){v.removeData(e,t+"queue",!0),v.removeData(e,n,!0)})})}}),v.fn.extend({queue:function(e,n){var r=2;return typeof e!="string"&&(n=e,e="fx",r--),arguments.length1)},removeAttr:function(e){return this.each(function(){v.removeAttr(this,e)})},prop:function(e,t){return v.access(this,v.prop,e,t,arguments.length>1)},removeProp:function(e){return e=v.propFix[e]||e,this.each(function(){try{this[e]=t,delete this[e]}catch(n){}})},addClass:function(e){var t,n,r,i,s,o,u;if(v.isFunction(e))return this.each(function(t){v(this).addClass(e.call(this,t,this.className))});if(e&&typeof e=="string"){t=e.split(y);for(n=0,r=this.length;n=0)r=r.replace(" "+n[s]+" "," ");i.className=e?v.trim(r):""}}}return this},toggleClass:function(e,t){var n=typeof e,r=typeof t=="boolean";return v.isFunction(e)?this.each(function(n){v(this).toggleClass(e.call(this,n,this.className,t),t)}):this.each(function(){if(n==="string"){var i,s=0,o=v(this),u=t,a=e.split(y);while(i=a[s++])u=r?u:!o.hasClass(i),o[u?"addClass":"removeClass"](i)}else if(n==="undefined"||n==="boolean")this.className&&v._data(this,"__className__",this.className),this.className=this.className||e===!1?"":v._data(this,"__className__")||""})},hasClass:function(e){var t=" "+e+" ",n=0,r=this.length;for(;n=0)return!0;return!1},val:function(e){var n,r,i,s=this[0];if(!arguments.length){if(s)return n=v.valHooks[s.type]||v.valHooks[s.nodeName.toLowerCase()],n&&"get"in n&&(r=n.get(s,"value"))!==t?r:(r=s.value,typeof r=="string"?r.replace(R,""):r==null?"":r);return}return i=v.isFunction(e),this.each(function(r){var s,o=v(this);if(this.nodeType!==1)return;i?s=e.call(this,r,o.val()):s=e,s==null?s="":typeof s=="number"?s+="":v.isArray(s)&&(s=v.map(s,function(e){return e==null?"":e+""})),n=v.valHooks[this.type]||v.valHooks[this.nodeName.toLowerCase()];if(!n||!("set"in n)||n.set(this,s,"value")===t)this.value=s})}}),v.extend({valHooks:{option:{get:function(e){var t=e.attributes.value;return!t||t.specified?e.value:e.text}},select:{get:function(e){var t,n,r=e.options,i=e.selectedIndex,s=e.type==="select-one"||i<0,o=s?null:[],u=s?i+1:r.length,a=i<0?u:s?i:0;for(;a=0}),n.length||(e.selectedIndex=-1),n}}},attrFn:{},attr:function(e,n,r,i){var s,o,u,a=e.nodeType;if(!e||a===3||a===8||a===2)return;if(i&&v.isFunction(v.fn[n]))return v(e)[n](r);if(typeof e.getAttribute=="undefined")return v.prop(e,n,r);u=a!==1||!v.isXMLDoc(e),u&&(n=n.toLowerCase(),o=v.attrHooks[n]||(X.test(n)?F:j));if(r!==t){if(r===null){v.removeAttr(e,n);return}return o&&"set"in o&&u&&(s=o.set(e,r,n))!==t?s:(e.setAttribute(n,r+""),r)}return o&&"get"in o&&u&&(s=o.get(e,n))!==null?s:(s=e.getAttribute(n),s===null?t:s)},removeAttr:function(e,t){var n,r,i,s,o=0;if(t&&e.nodeType===1){r=t.split(y);for(;o=0}})});var $=/^(?:textarea|input|select)$/i,J=/^([^\.]*|)(?:\.(.+)|)$/,K=/(?:^|\s)hover(\.\S+|)\b/,Q=/^key/,G=/^(?:mouse|contextmenu)|click/,Y=/^(?:focusinfocus|focusoutblur)$/,Z=function(e){return v.event.special.hover?e:e.replace(K,"mouseenter$1 mouseleave$1")};v.event={add:function(e,n,r,i,s){var o,u,a,f,l,c,h,p,d,m,g;if(e.nodeType===3||e.nodeType===8||!n||!r||!(o=v._data(e)))return;r.handler&&(d=r,r=d.handler,s=d.selector),r.guid||(r.guid=v.guid++),a=o.events,a||(o.events=a={}),u=o.handle,u||(o.handle=u=function(e){return typeof v=="undefined"||!!e&&v.event.triggered===e.type?t:v.event.dispatch.apply(u.elem,arguments)},u.elem=e),n=v.trim(Z(n)).split(" ");for(f=0;f=0&&(y=y.slice(0,-1),a=!0),y.indexOf(".")>=0&&(b=y.split("."),y=b.shift(),b.sort());if((!s||v.event.customEvent[y])&&!v.event.global[y])return;n=typeof n=="object"?n[v.expando]?n:new v.Event(y,n):new v.Event(y),n.type=y,n.isTrigger=!0,n.exclusive=a,n.namespace=b.join("."),n.namespace_re=n.namespace?new RegExp("(^|\\.)"+b.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,h=y.indexOf(":")<0?"on"+y:"";if(!s){u=v.cache;for(f in u)u[f].events&&u[f].events[y]&&v.event.trigger(n,r,u[f].handle.elem,!0);return}n.result=t,n.target||(n.target=s),r=r!=null?v.makeArray(r):[],r.unshift(n),p=v.event.special[y]||{};if(p.trigger&&p.trigger.apply(s,r)===!1)return;m=[[s,p.bindType||y]];if(!o&&!p.noBubble&&!v.isWindow(s)){g=p.delegateType||y,l=Y.test(g+y)?s:s.parentNode;for(c=s;l;l=l.parentNode)m.push([l,g]),c=l;c===(s.ownerDocument||i)&&m.push([c.defaultView||c.parentWindow||e,g])}for(f=0;f=0:v.find(h,this,null,[s]).length),u[h]&&f.push(c);f.length&&w.push({elem:s,matches:f})}d.length>m&&w.push({elem:this,matches:d.slice(m)});for(r=0;r0?this.on(t,null,e,n):this.trigger(t)},Q.test(t)&&(v.event.fixHooks[t]=v.event.keyHooks),G.test(t)&&(v.event.fixHooks[t]=v.event.mouseHooks)}),function(e,t){function nt(e,t,n,r){n=n||[],t=t||g;var i,s,a,f,l=t.nodeType;if(!e||typeof e!="string")return n;if(l!==1&&l!==9)return[];a=o(t);if(!a&&!r)if(i=R.exec(e))if(f=i[1]){if(l===9){s=t.getElementById(f);if(!s||!s.parentNode)return n;if(s.id===f)return n.push(s),n}else if(t.ownerDocument&&(s=t.ownerDocument.getElementById(f))&&u(t,s)&&s.id===f)return n.push(s),n}else{if(i[2])return S.apply(n,x.call(t.getElementsByTagName(e),0)),n;if((f=i[3])&&Z&&t.getElementsByClassName)return S.apply(n,x.call(t.getElementsByClassName(f),0)),n}return vt(e.replace(j,"$1"),t,n,r,a)}function rt(e){return function(t){var n=t.nodeName.toLowerCase();return n==="input"&&t.type===e}}function it(e){return function(t){var n=t.nodeName.toLowerCase();return(n==="input"||n==="button")&&t.type===e}}function st(e){return N(function(t){return t=+t,N(function(n,r){var i,s=e([],n.length,t),o=s.length;while(o--)n[i=s[o]]&&(n[i]=!(r[i]=n[i]))})})}function ot(e,t,n){if(e===t)return n;var r=e.nextSibling;while(r){if(r===t)return-1;r=r.nextSibling}return 1}function ut(e,t){var n,r,s,o,u,a,f,l=L[d][e+" "];if(l)return t?0:l.slice(0);u=e,a=[],f=i.preFilter;while(u){if(!n||(r=F.exec(u)))r&&(u=u.slice(r[0].length)||u),a.push(s=[]);n=!1;if(r=I.exec(u))s.push(n=new m(r.shift())),u=u.slice(n.length),n.type=r[0].replace(j," ");for(o in i.filter)(r=J[o].exec(u))&&(!f[o]||(r=f[o](r)))&&(s.push(n=new m(r.shift())),u=u.slice(n.length),n.type=o,n.matches=r);if(!n)break}return t?u.length:u?nt.error(e):L(e,a).slice(0)}function at(e,t,r){var i=t.dir,s=r&&t.dir==="parentNode",o=w++;return t.first?function(t,n,r){while(t=t[i])if(s||t.nodeType===1)return e(t,n,r)}:function(t,r,u){if(!u){var a,f=b+" "+o+" ",l=f+n;while(t=t[i])if(s||t.nodeType===1){if((a=t[d])===l)return t.sizset;if(typeof a=="string"&&a.indexOf(f)===0){if(t.sizset)return t}else{t[d]=l;if(e(t,r,u))return t.sizset=!0,t;t.sizset=!1}}}else while(t=t[i])if(s||t.nodeType===1)if(e(t,r,u))return t}}function ft(e){return e.length>1?function(t,n,r){var i=e.length;while(i--)if(!e[i](t,n,r))return!1;return!0}:e[0]}function lt(e,t,n,r,i){var s,o=[],u=0,a=e.length,f=t!=null;for(;u-1&&(s[f]=!(o[f]=c))}}else g=lt(g===o?g.splice(d,g.length):g),i?i(null,o,g,a):S.apply(o,g)})}function ht(e){var t,n,r,s=e.length,o=i.relative[e[0].type],u=o||i.relative[" "],a=o?1:0,f=at(function(e){return e===t},u,!0),l=at(function(e){return T.call(t,e)>-1},u,!0),h=[function(e,n,r){return!o&&(r||n!==c)||((t=n).nodeType?f(e,n,r):l(e,n,r))}];for(;a1&&ft(h),a>1&&e.slice(0,a-1).join("").replace(j,"$1"),n,a0,s=e.length>0,o=function(u,a,f,l,h){var p,d,v,m=[],y=0,w="0",x=u&&[],T=h!=null,N=c,C=u||s&&i.find.TAG("*",h&&a.parentNode||a),k=b+=N==null?1:Math.E;T&&(c=a!==g&&a,n=o.el);for(;(p=C[w])!=null;w++){if(s&&p){for(d=0;v=e[d];d++)if(v(p,a,f)){l.push(p);break}T&&(b=k,n=++o.el)}r&&((p=!v&&p)&&y--,u&&x.push(p))}y+=w;if(r&&w!==y){for(d=0;v=t[d];d++)v(x,m,a,f);if(u){if(y>0)while(w--)!x[w]&&!m[w]&&(m[w]=E.call(l));m=lt(m)}S.apply(l,m),T&&!u&&m.length>0&&y+t.length>1&&nt.uniqueSort(l)}return T&&(b=k,c=N),x};return o.el=0,r?N(o):o}function dt(e,t,n){var r=0,i=t.length;for(;r2&&(f=u[0]).type==="ID"&&t.nodeType===9&&!s&&i.relative[u[1].type]){t=i.find.ID(f.matches[0].replace($,""),t,s)[0];if(!t)return n;e=e.slice(u.shift().length)}for(o=J.POS.test(e)?-1:u.length-1;o>=0;o--){f=u[o];if(i.relative[l=f.type])break;if(c=i.find[l])if(r=c(f.matches[0].replace($,""),z.test(u[0].type)&&t.parentNode||t,s)){u.splice(o,1),e=r.length&&u.join("");if(!e)return S.apply(n,x.call(r,0)),n;break}}}return a(e,h)(r,t,s,n,z.test(e)),n}function mt(){}var n,r,i,s,o,u,a,f,l,c,h=!0,p="undefined",d=("sizcache"+Math.random()).replace(".",""),m=String,g=e.document,y=g.documentElement,b=0,w=0,E=[].pop,S=[].push,x=[].slice,T=[].indexOf||function(e){var t=0,n=this.length;for(;ti.cacheLength&&delete e[t.shift()],e[n+" "]=r},e)},k=C(),L=C(),A=C(),O="[\\x20\\t\\r\\n\\f]",M="(?:\\\\.|[-\\w]|[^\\x00-\\xa0])+",_=M.replace("w","w#"),D="([*^$|!~]?=)",P="\\["+O+"*("+M+")"+O+"*(?:"+D+O+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+_+")|)|)"+O+"*\\]",H=":("+M+")(?:\\((?:(['\"])((?:\\\\.|[^\\\\])*?)\\2|([^()[\\]]*|(?:(?:"+P+")|[^:]|\\\\.)*|.*))\\)|)",B=":(even|odd|eq|gt|lt|nth|first|last)(?:\\("+O+"*((?:-\\d)?\\d*)"+O+"*\\)|)(?=[^-]|$)",j=new RegExp("^"+O+"+|((?:^|[^\\\\])(?:\\\\.)*)"+O+"+$","g"),F=new RegExp("^"+O+"*,"+O+"*"),I=new RegExp("^"+O+"*([\\x20\\t\\r\\n\\f>+~])"+O+"*"),q=new RegExp(H),R=/^(?:#([\w\-]+)|(\w+)|\.([\w\-]+))$/,U=/^:not/,z=/[\x20\t\r\n\f]*[+~]/,W=/:not\($/,X=/h\d/i,V=/input|select|textarea|button/i,$=/\\(?!\\)/g,J={ID:new RegExp("^#("+M+")"),CLASS:new RegExp("^\\.("+M+")"),NAME:new RegExp("^\\[name=['\"]?("+M+")['\"]?\\]"),TAG:new RegExp("^("+M.replace("w","w*")+")"),ATTR:new RegExp("^"+P),PSEUDO:new RegExp("^"+H),POS:new RegExp(B,"i"),CHILD:new RegExp("^:(only|nth|first|last)-child(?:\\("+O+"*(even|odd|(([+-]|)(\\d*)n|)"+O+"*(?:([+-]|)"+O+"*(\\d+)|))"+O+"*\\)|)","i"),needsContext:new RegExp("^"+O+"*[>+~]|"+B,"i")},K=function(e){var t=g.createElement("div");try{return e(t)}catch(n){return!1}finally{t=null}},Q=K(function(e){return e.appendChild(g.createComment("")),!e.getElementsByTagName("*").length}),G=K(function(e){return e.innerHTML="",e.firstChild&&typeof e.firstChild.getAttribute!==p&&e.firstChild.getAttribute("href")==="#"}),Y=K(function(e){e.innerHTML="";var t=typeof e.lastChild.getAttribute("multiple");return t!=="boolean"&&t!=="string"}),Z=K(function(e){return e.innerHTML="",!e.getElementsByClassName||!e.getElementsByClassName("e").length?!1:(e.lastChild.className="e",e.getElementsByClassName("e").length===2)}),et=K(function(e){e.id=d+0,e.innerHTML="
",y.insertBefore(e,y.firstChild);var t=g.getElementsByName&&g.getElementsByName(d).length===2+g.getElementsByName(d+0).length;return r=!g.getElementById(d),y.removeChild(e),t});try{x.call(y.childNodes,0)[0].nodeType}catch(tt){x=function(e){var t,n=[];for(;t=this[e];e++)n.push(t);return n}}nt.matches=function(e,t){return nt(e,null,null,t)},nt.matchesSelector=function(e,t){return nt(t,null,null,[e]).length>0},s=nt.getText=function(e){var t,n="",r=0,i=e.nodeType;if(i){if(i===1||i===9||i===11){if(typeof e.textContent=="string")return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=s(e)}else if(i===3||i===4)return e.nodeValue}else for(;t=e[r];r++)n+=s(t);return n},o=nt.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return t?t.nodeName!=="HTML":!1},u=nt.contains=y.contains?function(e,t){var n=e.nodeType===9?e.documentElement:e,r=t&&t.parentNode;return e===r||!!(r&&r.nodeType===1&&n.contains&&n.contains(r))}:y.compareDocumentPosition?function(e,t){return t&&!!(e.compareDocumentPosition(t)&16)}:function(e,t){while(t=t.parentNode)if(t===e)return!0;return!1},nt.attr=function(e,t){var n,r=o(e);return r||(t=t.toLowerCase()),(n=i.attrHandle[t])?n(e):r||Y?e.getAttribute(t):(n=e.getAttributeNode(t),n?typeof e[t]=="boolean"?e[t]?t:null:n.specified?n.value:null:null)},i=nt.selectors={cacheLength:50,createPseudo:N,match:J,attrHandle:G?{}:{href:function(e){return e.getAttribute("href",2)},type:function(e){return e.getAttribute("type")}},find:{ID:r?function(e,t,n){if(typeof t.getElementById!==p&&!n){var r=t.getElementById(e);return r&&r.parentNode?[r]:[]}}:function(e,n,r){if(typeof n.getElementById!==p&&!r){var i=n.getElementById(e);return i?i.id===e||typeof i.getAttributeNode!==p&&i.getAttributeNode("id").value===e?[i]:t:[]}},TAG:Q?function(e,t){if(typeof t.getElementsByTagName!==p)return t.getElementsByTagName(e)}:function(e,t){var n=t.getElementsByTagName(e);if(e==="*"){var r,i=[],s=0;for(;r=n[s];s++)r.nodeType===1&&i.push(r);return i}return n},NAME:et&&function(e,t){if(typeof t.getElementsByName!==p)return t.getElementsByName(name)},CLASS:Z&&function(e,t,n){if(typeof t.getElementsByClassName!==p&&!n)return t.getElementsByClassName(e)}},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace($,""),e[3]=(e[4]||e[5]||"").replace($,""),e[2]==="~="&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),e[1]==="nth"?(e[2]||nt.error(e[0]),e[3]=+(e[3]?e[4]+(e[5]||1):2*(e[2]==="even"||e[2]==="odd")),e[4]=+(e[6]+e[7]||e[2]==="odd")):e[2]&&nt.error(e[0]),e},PSEUDO:function(e){var t,n;if(J.CHILD.test(e[0]))return null;if(e[3])e[2]=e[3];else if(t=e[4])q.test(t)&&(n=ut(t,!0))&&(n=t.indexOf(")",t.length-n)-t.length)&&(t=t.slice(0,n),e[0]=e[0].slice(0,n)),e[2]=t;return e.slice(0,3)}},filter:{ID:r?function(e){return e=e.replace($,""),function(t){return t.getAttribute("id")===e}}:function(e){return e=e.replace($,""),function(t){var n=typeof t.getAttributeNode!==p&&t.getAttributeNode("id");return n&&n.value===e}},TAG:function(e){return e==="*"?function(){return!0}:(e=e.replace($,"").toLowerCase(),function(t){return t.nodeName&&t.nodeName.toLowerCase()===e})},CLASS:function(e){var t=k[d][e+" "];return t||(t=new RegExp("(^|"+O+")"+e+"("+O+"|$)"))&&k(e,function(e){return t.test(e.className||typeof e.getAttribute!==p&&e.getAttribute("class")||"")})},ATTR:function(e,t,n){return function(r,i){var s=nt.attr(r,e);return s==null?t==="!=":t?(s+="",t==="="?s===n:t==="!="?s!==n:t==="^="?n&&s.indexOf(n)===0:t==="*="?n&&s.indexOf(n)>-1:t==="$="?n&&s.substr(s.length-n.length)===n:t==="~="?(" "+s+" ").indexOf(n)>-1:t==="|="?s===n||s.substr(0,n.length+1)===n+"-":!1):!0}},CHILD:function(e,t,n,r){return e==="nth"?function(e){var t,i,s=e.parentNode;if(n===1&&r===0)return!0;if(s){i=0;for(t=s.firstChild;t;t=t.nextSibling)if(t.nodeType===1){i++;if(e===t)break}}return i-=r,i===n||i%n===0&&i/n>=0}:function(t){var n=t;switch(e){case"only":case"first":while(n=n.previousSibling)if(n.nodeType===1)return!1;if(e==="first")return!0;n=t;case"last":while(n=n.nextSibling)if(n.nodeType===1)return!1;return!0}}},PSEUDO:function(e,t){var n,r=i.pseudos[e]||i.setFilters[e.toLowerCase()]||nt.error("unsupported pseudo: "+e);return r[d]?r(t):r.length>1?(n=[e,e,"",t],i.setFilters.hasOwnProperty(e.toLowerCase())?N(function(e,n){var i,s=r(e,t),o=s.length;while(o--)i=T.call(e,s[o]),e[i]=!(n[i]=s[o])}):function(e){return r(e,0,n)}):r}},pseudos:{not:N(function(e){var t=[],n=[],r=a(e.replace(j,"$1"));return r[d]?N(function(e,t,n,i){var s,o=r(e,null,i,[]),u=e.length;while(u--)if(s=o[u])e[u]=!(t[u]=s)}):function(e,i,s){return t[0]=e,r(t,null,s,n),!n.pop()}}),has:N(function(e){return function(t){return nt(e,t).length>0}}),contains:N(function(e){return function(t){return(t.textContent||t.innerText||s(t)).indexOf(e)>-1}}),enabled:function(e){return e.disabled===!1},disabled:function(e){return e.disabled===!0},checked:function(e){var t=e.nodeName.toLowerCase();return t==="input"&&!!e.checked||t==="option"&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,e.selected===!0},parent:function(e){return!i.pseudos.empty(e)},empty:function(e){var t;e=e.firstChild;while(e){if(e.nodeName>"@"||(t=e.nodeType)===3||t===4)return!1;e=e.nextSibling}return!0},header:function(e){return X.test(e.nodeName)},text:function(e){var t,n;return e.nodeName.toLowerCase()==="input"&&(t=e.type)==="text"&&((n=e.getAttribute("type"))==null||n.toLowerCase()===t)},radio:rt("radio"),checkbox:rt("checkbox"),file:rt("file"),password:rt("password"),image:rt("image"),submit:it("submit"),reset:it("reset"),button:function(e){var t=e.nodeName.toLowerCase();return t==="input"&&e.type==="button"||t==="button"},input:function(e){return V.test(e.nodeName)},focus:function(e){var t=e.ownerDocument;return e===t.activeElement&&(!t.hasFocus||t.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},active:function(e){return e===e.ownerDocument.activeElement},first:st(function(){return[0]}),last:st(function(e,t){return[t-1]}),eq:st(function(e,t,n){return[n<0?n+t:n]}),even:st(function(e,t){for(var n=0;n=0;)e.push(r);return e}),gt:st(function(e,t,n){for(var r=n<0?n+t:n;++r",e.querySelectorAll("[selected]").length||i.push("\\["+O+"*(?:checked|disabled|ismap|multiple|readonly|selected|value)"),e.querySelectorAll(":checked").length||i.push(":checked")}),K(function(e){e.innerHTML="

",e.querySelectorAll("[test^='']").length&&i.push("[*^$]="+O+"*(?:\"\"|'')"),e.innerHTML="",e.querySelectorAll(":enabled").length||i.push(":enabled",":disabled")}),i=new RegExp(i.join("|")),vt=function(e,r,s,o,u){if(!o&&!u&&!i.test(e)){var a,f,l=!0,c=d,h=r,p=r.nodeType===9&&e;if(r.nodeType===1&&r.nodeName.toLowerCase()!=="object"){a=ut(e),(l=r.getAttribute("id"))?c=l.replace(n,"\\$&"):r.setAttribute("id",c),c="[id='"+c+"'] ",f=a.length;while(f--)a[f]=c+a[f].join("");h=z.test(e)&&r.parentNode||r,p=a.join(",")}if(p)try{return S.apply(s,x.call(h.querySelectorAll(p),0)),s}catch(v){}finally{l||r.removeAttribute("id")}}return t(e,r,s,o,u)},u&&(K(function(t){e=u.call(t,"div");try{u.call(t,"[test!='']:sizzle"),s.push("!=",H)}catch(n){}}),s=new RegExp(s.join("|")),nt.matchesSelector=function(t,n){n=n.replace(r,"='$1']");if(!o(t)&&!s.test(n)&&!i.test(n))try{var a=u.call(t,n);if(a||e||t.document&&t.document.nodeType!==11)return a}catch(f){}return nt(n,null,null,[t]).length>0})}(),i.pseudos.nth=i.pseudos.eq,i.filters=mt.prototype=i.pseudos,i.setFilters=new mt,nt.attr=v.attr,v.find=nt,v.expr=nt.selectors,v.expr[":"]=v.expr.pseudos,v.unique=nt.uniqueSort,v.text=nt.getText,v.isXMLDoc=nt.isXML,v.contains=nt.contains}(e);var nt=/Until$/,rt=/^(?:parents|prev(?:Until|All))/,it=/^.[^:#\[\.,]*$/,st=v.expr.match.needsContext,ot={children:!0,contents:!0,next:!0,prev:!0};v.fn.extend({find:function(e){var t,n,r,i,s,o,u=this;if(typeof e!="string")return v(e).filter(function(){for(t=0,n=u.length;t0)for(i=r;i=0:v.filter(e,this).length>0:this.filter(e).length>0)},closest:function(e,t){var n,r=0,i=this.length,s=[],o=st.test(e)||typeof e!="string"?v(e,t||this.context):0;for(;r-1:v.find.matchesSelector(n,e)){s.push(n);break}n=n.parentNode}}return s=s.length>1?v.unique(s):s,this.pushStack(s,"closest",e)},index:function(e){return e?typeof e=="string"?v.inArray(this[0],v(e)):v.inArray(e.jquery?e[0]:e,this):this[0]&&this[0].parentNode?this.prevAll().length:-1},add:function(e,t){var n=typeof e=="string"?v(e,t):v.makeArray(e&&e.nodeType?[e]:e),r=v.merge(this.get(),n);return this.pushStack(ut(n[0])||ut(r[0])?r:v.unique(r))},addBack:function(e){return this.add(e==null?this.prevObject:this.prevObject.filter(e))}}),v.fn.andSelf=v.fn.addBack,v.each({parent:function(e){var t=e.parentNode;return t&&t.nodeType!==11?t:null},parents:function(e){return v.dir(e,"parentNode")},parentsUntil:function(e,t,n){return v.dir(e,"parentNode",n)},next:function(e){return at(e,"nextSibling")},prev:function(e){return at(e,"previousSibling")},nextAll:function(e){return v.dir(e,"nextSibling")},prevAll:function(e){return v.dir(e,"previousSibling")},nextUntil:function(e,t,n){return v.dir(e,"nextSibling",n)},prevUntil:function(e,t,n){return v.dir(e,"previousSibling",n)},siblings:function(e){return v.sibling((e.parentNode||{}).firstChild,e)},children:function(e){return v.sibling(e.firstChild)},contents:function(e){return v.nodeName(e,"iframe")?e.contentDocument||e.contentWindow.document:v.merge([],e.childNodes)}},function(e,t){v.fn[e]=function(n,r){var i=v.map(this,t,n);return nt.test(e)||(r=n),r&&typeof r=="string"&&(i=v.filter(r,i)),i=this.length>1&&!ot[e]?v.unique(i):i,this.length>1&&rt.test(e)&&(i=i.reverse()),this.pushStack(i,e,l.call(arguments).join(","))}}),v.extend({filter:function(e,t,n){return n&&(e=":not("+e+")"),t.length===1?v.find.matchesSelector(t[0],e)?[t[0]]:[]:v.find.matches(e,t)},dir:function(e,n,r){var i=[],s=e[n];while(s&&s.nodeType!==9&&(r===t||s.nodeType!==1||!v(s).is(r)))s.nodeType===1&&i.push(s),s=s[n];return i},sibling:function(e,t){var n=[];for(;e;e=e.nextSibling)e.nodeType===1&&e!==t&&n.push(e);return n}});var ct="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",ht=/ jQuery\d+="(?:null|\d+)"/g,pt=/^\s+/,dt=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,vt=/<([\w:]+)/,mt=/]","i"),Et=/^(?:checkbox|radio)$/,St=/checked\s*(?:[^=]|=\s*.checked.)/i,xt=/\/(java|ecma)script/i,Tt=/^\s*\s*$/g,Nt={option:[1,""],legend:[1,"
","
"],thead:[1,"","
"],tr:[2,"","
"],td:[3,"","
"],col:[2,"","
"],area:[1,"",""],_default:[0,"",""]},Ct=lt(i),kt=Ct.appendChild(i.createElement("div"));Nt.optgroup=Nt.option,Nt.tbody=Nt.tfoot=Nt.colgroup=Nt.caption=Nt.thead,Nt.th=Nt.td,v.support.htmlSerialize||(Nt._default=[1,"X
","
"]),v.fn.extend({text:function(e){return v.access(this,function(e){return e===t?v.text(this):this.empty().append((this[0]&&this[0].ownerDocument||i).createTextNode(e))},null,e,arguments.length)},wrapAll:function(e){if(v.isFunction(e))return this.each(function(t){v(this).wrapAll(e.call(this,t))});if(this[0]){var t=v(e,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&t.insertBefore(this[0]),t.map(function(){var e=this;while(e.firstChild&&e.firstChild.nodeType===1)e=e.firstChild;return e}).append(this)}return this},wrapInner:function(e){return v.isFunction(e)?this.each(function(t){v(this).wrapInner(e.call(this,t))}):this.each(function(){var t=v(this),n=t.contents();n.length?n.wrapAll(e):t.append(e)})},wrap:function(e){var t=v.isFunction(e);return this.each(function(n){v(this).wrapAll(t?e.call(this,n):e)})},unwrap:function(){return this.parent().each(function(){v.nodeName(this,"body")||v(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(e){(this.nodeType===1||this.nodeType===11)&&this.appendChild(e)})},prepend:function(){return this.domManip(arguments,!0,function(e){(this.nodeType===1||this.nodeType===11)&&this.insertBefore(e,this.firstChild)})},before:function(){if(!ut(this[0]))return this.domManip(arguments,!1,function(e){this.parentNode.insertBefore(e,this)});if(arguments.length){var e=v.clean(arguments);return this.pushStack(v.merge(e,this),"before",this.selector)}},after:function(){if(!ut(this[0]))return this.domManip(arguments,!1,function(e){this.parentNode.insertBefore(e,this.nextSibling)});if(arguments.length){var e=v.clean(arguments);return this.pushStack(v.merge(this,e),"after",this.selector)}},remove:function(e,t){var n,r=0;for(;(n=this[r])!=null;r++)if(!e||v.filter(e,[n]).length)!t&&n.nodeType===1&&(v.cleanData(n.getElementsByTagName("*")),v.cleanData([n])),n.parentNode&&n.parentNode.removeChild(n);return this},empty:function(){var e,t=0;for(;(e=this[t])!=null;t++){e.nodeType===1&&v.cleanData(e.getElementsByTagName("*"));while(e.firstChild)e.removeChild(e.firstChild)}return this},clone:function(e,t){return e=e==null?!1:e,t=t==null?e:t,this.map(function(){return v.clone(this,e,t)})},html:function(e){return v.access(this,function(e){var n=this[0]||{},r=0,i=this.length;if(e===t)return n.nodeType===1?n.innerHTML.replace(ht,""):t;if(typeof e=="string"&&!yt.test(e)&&(v.support.htmlSerialize||!wt.test(e))&&(v.support.leadingWhitespace||!pt.test(e))&&!Nt[(vt.exec(e)||["",""])[1].toLowerCase()]){e=e.replace(dt,"<$1>");try{for(;r1&&typeof f=="string"&&St.test(f))return this.each(function(){v(this).domManip(e,n,r)});if(v.isFunction(f))return this.each(function(i){var s=v(this);e[0]=f.call(this,i,n?s.html():t),s.domManip(e,n,r)});if(this[0]){i=v.buildFragment(e,this,l),o=i.fragment,s=o.firstChild,o.childNodes.length===1&&(o=s);if(s){n=n&&v.nodeName(s,"tr");for(u=i.cacheable||c-1;a0?this.clone(!0):this).get(),v(o[i])[t](r),s=s.concat(r);return this.pushStack(s,e,o.selector)}}),v.extend({clone:function(e,t,n){var r,i,s,o;v.support.html5Clone||v.isXMLDoc(e)||!wt.test("<"+e.nodeName+">")?o=e.cloneNode(!0):(kt.innerHTML=e.outerHTML,kt.removeChild(o=kt.firstChild));if((!v.support.noCloneEvent||!v.support.noCloneChecked)&&(e.nodeType===1||e.nodeType===11)&&!v.isXMLDoc(e)){Ot(e,o),r=Mt(e),i=Mt(o);for(s=0;r[s];++s)i[s]&&Ot(r[s],i[s])}if(t){At(e,o);if(n){r=Mt(e),i=Mt(o);for(s=0;r[s];++s)At(r[s],i[s])}}return r=i=null,o},clean:function(e,t,n,r){var s,o,u,a,f,l,c,h,p,d,m,g,y=t===i&&Ct,b=[];if(!t||typeof t.createDocumentFragment=="undefined")t=i;for(s=0;(u=e[s])!=null;s++){typeof u=="number"&&(u+="");if(!u)continue;if(typeof u=="string")if(!gt.test(u))u=t.createTextNode(u);else{y=y||lt(t),c=t.createElement("div"),y.appendChild(c),u=u.replace(dt,"<$1>"),a=(vt.exec(u)||["",""])[1].toLowerCase(),f=Nt[a]||Nt._default,l=f[0],c.innerHTML=f[1]+u+f[2];while(l--)c=c.lastChild;if(!v.support.tbody){h=mt.test(u),p=a==="table"&&!h?c.firstChild&&c.firstChild.childNodes:f[1]===""&&!h?c.childNodes:[];for(o=p.length-1;o>=0;--o)v.nodeName(p[o],"tbody")&&!p[o].childNodes.length&&p[o].parentNode.removeChild(p[o])}!v.support.leadingWhitespace&&pt.test(u)&&c.insertBefore(t.createTextNode(pt.exec(u)[0]),c.firstChild),u=c.childNodes,c.parentNode.removeChild(c)}u.nodeType?b.push(u):v.merge(b,u)}c&&(u=c=y=null);if(!v.support.appendChecked)for(s=0;(u=b[s])!=null;s++)v.nodeName(u,"input")?_t(u):typeof u.getElementsByTagName!="undefined"&&v.grep(u.getElementsByTagName("input"),_t);if(n){m=function(e){if(!e.type||xt.test(e.type))return r?r.push(e.parentNode?e.parentNode.removeChild(e):e):n.appendChild(e)};for(s=0;(u=b[s])!=null;s++)if(!v.nodeName(u,"script")||!m(u))n.appendChild(u),typeof u.getElementsByTagName!="undefined"&&(g=v.grep(v.merge([],u.getElementsByTagName("script")),m),b.splice.apply(b,[s+1,0].concat(g)),s+=g.length)}return b},cleanData:function(e,t){var n,r,i,s,o=0,u=v.expando,a=v.cache,f=v.support.deleteExpando,l=v.event.special;for(;(i=e[o])!=null;o++)if(t||v.acceptData(i)){r=i[u],n=r&&a[r];if(n){if(n.events)for(s in n.events)l[s]?v.event.remove(i,s):v.removeEvent(i,s,n.handle);a[r]&&(delete a[r],f?delete i[u]:i.removeAttribute?i.removeAttribute(u):i[u]=null,v.deletedIds.push(r))}}}}),function(){var e,t;v.uaMatch=function(e){e=e.toLowerCase();var t=/(chrome)[ \/]([\w.]+)/.exec(e)||/(webkit)[ \/]([\w.]+)/.exec(e)||/(opera)(?:.*version|)[ \/]([\w.]+)/.exec(e)||/(msie) ([\w.]+)/.exec(e)||e.indexOf("compatible")<0&&/(mozilla)(?:.*? rv:([\w.]+)|)/.exec(e)||[];return{browser:t[1]||"",version:t[2]||"0"}},e=v.uaMatch(o.userAgent),t={},e.browser&&(t[e.browser]=!0,t.version=e.version),t.chrome?t.webkit=!0:t.webkit&&(t.safari=!0),v.browser=t,v.sub=function(){function e(t,n){return new e.fn.init(t,n)}v.extend(!0,e,this),e.superclass=this,e.fn=e.prototype=this(),e.fn.constructor=e,e.sub=this.sub,e.fn.init=function(r,i){return i&&i instanceof v&&!(i instanceof e)&&(i=e(i)),v.fn.init.call(this,r,i,t)},e.fn.init.prototype=e.fn;var t=e(i);return e}}();var Dt,Pt,Ht,Bt=/alpha\([^)]*\)/i,jt=/opacity=([^)]*)/,Ft=/^(top|right|bottom|left)$/,It=/^(none|table(?!-c[ea]).+)/,qt=/^margin/,Rt=new RegExp("^("+m+")(.*)$","i"),Ut=new RegExp("^("+m+")(?!px)[a-z%]+$","i"),zt=new RegExp("^([-+])=("+m+")","i"),Wt={BODY:"block"},Xt={position:"absolute",visibility:"hidden",display:"block"},Vt={letterSpacing:0,fontWeight:400},$t=["Top","Right","Bottom","Left"],Jt=["Webkit","O","Moz","ms"],Kt=v.fn.toggle;v.fn.extend({css:function(e,n){return v.access(this,function(e,n,r){return r!==t?v.style(e,n,r):v.css(e,n)},e,n,arguments.length>1)},show:function(){return Yt(this,!0)},hide:function(){return Yt(this)},toggle:function(e,t){var n=typeof e=="boolean";return v.isFunction(e)&&v.isFunction(t)?Kt.apply(this,arguments):this.each(function(){(n?e:Gt(this))?v(this).show():v(this).hide()})}}),v.extend({cssHooks:{opacity:{get:function(e,t){if(t){var n=Dt(e,"opacity");return n===""?"1":n}}}},cssNumber:{fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":v.support.cssFloat?"cssFloat":"styleFloat"},style:function(e,n,r,i){if(!e||e.nodeType===3||e.nodeType===8||!e.style)return;var s,o,u,a=v.camelCase(n),f=e.style;n=v.cssProps[a]||(v.cssProps[a]=Qt(f,a)),u=v.cssHooks[n]||v.cssHooks[a];if(r===t)return u&&"get"in u&&(s=u.get(e,!1,i))!==t?s:f[n];o=typeof r,o==="string"&&(s=zt.exec(r))&&(r=(s[1]+1)*s[2]+parseFloat(v.css(e,n)),o="number");if(r==null||o==="number"&&isNaN(r))return;o==="number"&&!v.cssNumber[a]&&(r+="px");if(!u||!("set"in u)||(r=u.set(e,r,i))!==t)try{f[n]=r}catch(l){}},css:function(e,n,r,i){var s,o,u,a=v.camelCase(n);return n=v.cssProps[a]||(v.cssProps[a]=Qt(e.style,a)),u=v.cssHooks[n]||v.cssHooks[a],u&&"get"in u&&(s=u.get(e,!0,i)),s===t&&(s=Dt(e,n)),s==="normal"&&n in Vt&&(s=Vt[n]),r||i!==t?(o=parseFloat(s),r||v.isNumeric(o)?o||0:s):s},swap:function(e,t,n){var r,i,s={};for(i in t)s[i]=e.style[i],e.style[i]=t[i];r=n.call(e);for(i in t)e.style[i]=s[i];return r}}),e.getComputedStyle?Dt=function(t,n){var r,i,s,o,u=e.getComputedStyle(t,null),a=t.style;return u&&(r=u.getPropertyValue(n)||u[n],r===""&&!v.contains(t.ownerDocument,t)&&(r=v.style(t,n)),Ut.test(r)&&qt.test(n)&&(i=a.width,s=a.minWidth,o=a.maxWidth,a.minWidth=a.maxWidth=a.width=r,r=u.width,a.width=i,a.minWidth=s,a.maxWidth=o)),r}:i.documentElement.currentStyle&&(Dt=function(e,t){var n,r,i=e.currentStyle&&e.currentStyle[t],s=e.style;return i==null&&s&&s[t]&&(i=s[t]),Ut.test(i)&&!Ft.test(t)&&(n=s.left,r=e.runtimeStyle&&e.runtimeStyle.left,r&&(e.runtimeStyle.left=e.currentStyle.left),s.left=t==="fontSize"?"1em":i,i=s.pixelLeft+"px",s.left=n,r&&(e.runtimeStyle.left=r)),i===""?"auto":i}),v.each(["height","width"],function(e,t){v.cssHooks[t]={get:function(e,n,r){if(n)return e.offsetWidth===0&&It.test(Dt(e,"display"))?v.swap(e,Xt,function(){return tn(e,t,r)}):tn(e,t,r)},set:function(e,n,r){return Zt(e,n,r?en(e,t,r,v.support.boxSizing&&v.css(e,"boxSizing")==="border-box"):0)}}}),v.support.opacity||(v.cssHooks.opacity={get:function(e,t){return jt.test((t&&e.currentStyle?e.currentStyle.filter:e.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":t?"1":""},set:function(e,t){var n=e.style,r=e.currentStyle,i=v.isNumeric(t)?"alpha(opacity="+t*100+")":"",s=r&&r.filter||n.filter||"";n.zoom=1;if(t>=1&&v.trim(s.replace(Bt,""))===""&&n.removeAttribute){n.removeAttribute("filter");if(r&&!r.filter)return}n.filter=Bt.test(s)?s.replace(Bt,i):s+" "+i}}),v(function(){v.support.reliableMarginRight||(v.cssHooks.marginRight={get:function(e,t){return v.swap(e,{display:"inline-block"},function(){if(t)return Dt(e,"marginRight")})}}),!v.support.pixelPosition&&v.fn.position&&v.each(["top","left"],function(e,t){v.cssHooks[t]={get:function(e,n){if(n){var r=Dt(e,t);return Ut.test(r)?v(e).position()[t]+"px":r}}}})}),v.expr&&v.expr.filters&&(v.expr.filters.hidden=function(e){return e.offsetWidth===0&&e.offsetHeight===0||!v.support.reliableHiddenOffsets&&(e.style&&e.style.display||Dt(e,"display"))==="none"},v.expr.filters.visible=function(e){return!v.expr.filters.hidden(e)}),v.each({margin:"",padding:"",border:"Width"},function(e,t){v.cssHooks[e+t]={expand:function(n){var r,i=typeof n=="string"?n.split(" "):[n],s={};for(r=0;r<4;r++)s[e+$t[r]+t]=i[r]||i[r-2]||i[0];return s}},qt.test(e)||(v.cssHooks[e+t].set=Zt)});var rn=/%20/g,sn=/\[\]$/,on=/\r?\n/g,un=/^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,an=/^(?:select|textarea)/i;v.fn.extend({serialize:function(){return v.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?v.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||an.test(this.nodeName)||un.test(this.type))}).map(function(e,t){var n=v(this).val();return n==null?null:v.isArray(n)?v.map(n,function(e,n){return{name:t.name,value:e.replace(on,"\r\n")}}):{name:t.name,value:n.replace(on,"\r\n")}}).get()}}),v.param=function(e,n){var r,i=[],s=function(e,t){t=v.isFunction(t)?t():t==null?"":t,i[i.length]=encodeURIComponent(e)+"="+encodeURIComponent(t)};n===t&&(n=v.ajaxSettings&&v.ajaxSettings.traditional);if(v.isArray(e)||e.jquery&&!v.isPlainObject(e))v.each(e,function(){s(this.name,this.value)});else for(r in e)fn(r,e[r],n,s);return i.join("&").replace(rn,"+")};var ln,cn,hn=/#.*$/,pn=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,dn=/^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,vn=/^(?:GET|HEAD)$/,mn=/^\/\//,gn=/\?/,yn=/)<[^<]*)*<\/script>/gi,bn=/([?&])_=[^&]*/,wn=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,En=v.fn.load,Sn={},xn={},Tn=["*/"]+["*"];try{cn=s.href}catch(Nn){cn=i.createElement("a"),cn.href="",cn=cn.href}ln=wn.exec(cn.toLowerCase())||[],v.fn.load=function(e,n,r){if(typeof e!="string"&&En)return En.apply(this,arguments);if(!this.length)return this;var i,s,o,u=this,a=e.indexOf(" ");return a>=0&&(i=e.slice(a,e.length),e=e.slice(0,a)),v.isFunction(n)?(r=n,n=t):n&&typeof n=="object"&&(s="POST"),v.ajax({url:e,type:s,dataType:"html",data:n,complete:function(e,t){r&&u.each(r,o||[e.responseText,t,e])}}).done(function(e){o=arguments,u.html(i?v("
").append(e.replace(yn,"")).find(i):e)}),this},v.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(e,t){v.fn[t]=function(e){return this.on(t,e)}}),v.each(["get","post"],function(e,n){v[n]=function(e,r,i,s){return v.isFunction(r)&&(s=s||i,i=r,r=t),v.ajax({type:n,url:e,data:r,success:i,dataType:s})}}),v.extend({getScript:function(e,n){return v.get(e,t,n,"script")},getJSON:function(e,t,n){return v.get(e,t,n,"json")},ajaxSetup:function(e,t){return t?Ln(e,v.ajaxSettings):(t=e,e=v.ajaxSettings),Ln(e,t),e},ajaxSettings:{url:cn,isLocal:dn.test(ln[1]),global:!0,type:"GET",contentType:"application/x-www-form-urlencoded; charset=UTF-8",processData:!0,async:!0,accepts:{xml:"application/xml, text/xml",html:"text/html",text:"text/plain",json:"application/json, text/javascript","*":Tn},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":e.String,"text html":!0,"text json":v.parseJSON,"text xml":v.parseXML},flatOptions:{context:!0,url:!0}},ajaxPrefilter:Cn(Sn),ajaxTransport:Cn(xn),ajax:function(e,n){function T(e,n,s,a){var l,y,b,w,S,T=n;if(E===2)return;E=2,u&&clearTimeout(u),o=t,i=a||"",x.readyState=e>0?4:0,s&&(w=An(c,x,s));if(e>=200&&e<300||e===304)c.ifModified&&(S=x.getResponseHeader("Last-Modified"),S&&(v.lastModified[r]=S),S=x.getResponseHeader("Etag"),S&&(v.etag[r]=S)),e===304?(T="notmodified",l=!0):(l=On(c,w),T=l.state,y=l.data,b=l.error,l=!b);else{b=T;if(!T||e)T="error",e<0&&(e=0)}x.status=e,x.statusText=(n||T)+"",l?d.resolveWith(h,[y,T,x]):d.rejectWith(h,[x,T,b]),x.statusCode(g),g=t,f&&p.trigger("ajax"+(l?"Success":"Error"),[x,c,l?y:b]),m.fireWith(h,[x,T]),f&&(p.trigger("ajaxComplete",[x,c]),--v.active||v.event.trigger("ajaxStop"))}typeof e=="object"&&(n=e,e=t),n=n||{};var r,i,s,o,u,a,f,l,c=v.ajaxSetup({},n),h=c.context||c,p=h!==c&&(h.nodeType||h instanceof v)?v(h):v.event,d=v.Deferred(),m=v.Callbacks("once memory"),g=c.statusCode||{},b={},w={},E=0,S="canceled",x={readyState:0,setRequestHeader:function(e,t){if(!E){var n=e.toLowerCase();e=w[n]=w[n]||e,b[e]=t}return this},getAllResponseHeaders:function(){return E===2?i:null},getResponseHeader:function(e){var n;if(E===2){if(!s){s={};while(n=pn.exec(i))s[n[1].toLowerCase()]=n[2]}n=s[e.toLowerCase()]}return n===t?null:n},overrideMimeType:function(e){return E||(c.mimeType=e),this},abort:function(e){return e=e||S,o&&o.abort(e),T(0,e),this}};d.promise(x),x.success=x.done,x.error=x.fail,x.complete=m.add,x.statusCode=function(e){if(e){var t;if(E<2)for(t in e)g[t]=[g[t],e[t]];else t=e[x.status],x.always(t)}return this},c.url=((e||c.url)+"").replace(hn,"").replace(mn,ln[1]+"//"),c.dataTypes=v.trim(c.dataType||"*").toLowerCase().split(y),c.crossDomain==null&&(a=wn.exec(c.url.toLowerCase()),c.crossDomain=!(!a||a[1]===ln[1]&&a[2]===ln[2]&&(a[3]||(a[1]==="http:"?80:443))==(ln[3]||(ln[1]==="http:"?80:443)))),c.data&&c.processData&&typeof c.data!="string"&&(c.data=v.param(c.data,c.traditional)),kn(Sn,c,n,x);if(E===2)return x;f=c.global,c.type=c.type.toUpperCase(),c.hasContent=!vn.test(c.type),f&&v.active++===0&&v.event.trigger("ajaxStart");if(!c.hasContent){c.data&&(c.url+=(gn.test(c.url)?"&":"?")+c.data,delete c.data),r=c.url;if(c.cache===!1){var N=v.now(),C=c.url.replace(bn,"$1_="+N);c.url=C+(C===c.url?(gn.test(c.url)?"&":"?")+"_="+N:"")}}(c.data&&c.hasContent&&c.contentType!==!1||n.contentType)&&x.setRequestHeader("Content-Type",c.contentType),c.ifModified&&(r=r||c.url,v.lastModified[r]&&x.setRequestHeader("If-Modified-Since",v.lastModified[r]),v.etag[r]&&x.setRequestHeader("If-None-Match",v.etag[r])),x.setRequestHeader("Accept",c.dataTypes[0]&&c.accepts[c.dataTypes[0]]?c.accepts[c.dataTypes[0]]+(c.dataTypes[0]!=="*"?", "+Tn+"; q=0.01":""):c.accepts["*"]);for(l in c.headers)x.setRequestHeader(l,c.headers[l]);if(!c.beforeSend||c.beforeSend.call(h,x,c)!==!1&&E!==2){S="abort";for(l in{success:1,error:1,complete:1})x[l](c[l]);o=kn(xn,c,n,x);if(!o)T(-1,"No Transport");else{x.readyState=1,f&&p.trigger("ajaxSend",[x,c]),c.async&&c.timeout>0&&(u=setTimeout(function(){x.abort("timeout")},c.timeout));try{E=1,o.send(b,T)}catch(k){if(!(E<2))throw k;T(-1,k)}}return x}return x.abort()},active:0,lastModified:{},etag:{}});var Mn=[],_n=/\?/,Dn=/(=)\?(?=&|$)|\?\?/,Pn=v.now();v.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=Mn.pop()||v.expando+"_"+Pn++;return this[e]=!0,e}}),v.ajaxPrefilter("json jsonp",function(n,r,i){var s,o,u,a=n.data,f=n.url,l=n.jsonp!==!1,c=l&&Dn.test(f),h=l&&!c&&typeof a=="string"&&!(n.contentType||"").indexOf("application/x-www-form-urlencoded")&&Dn.test(a);if(n.dataTypes[0]==="jsonp"||c||h)return s=n.jsonpCallback=v.isFunction(n.jsonpCallback)?n.jsonpCallback():n.jsonpCallback,o=e[s],c?n.url=f.replace(Dn,"$1"+s):h?n.data=a.replace(Dn,"$1"+s):l&&(n.url+=(_n.test(f)?"&":"?")+n.jsonp+"="+s),n.converters["script json"]=function(){return u||v.error(s+" was not called"),u[0]},n.dataTypes[0]="json",e[s]=function(){u=arguments},i.always(function(){e[s]=o,n[s]&&(n.jsonpCallback=r.jsonpCallback,Mn.push(s)),u&&v.isFunction(o)&&o(u[0]),u=o=t}),"script"}),v.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/javascript|ecmascript/},converters:{"text script":function(e){return v.globalEval(e),e}}}),v.ajaxPrefilter("script",function(e){e.cache===t&&(e.cache=!1),e.crossDomain&&(e.type="GET",e.global=!1)}),v.ajaxTransport("script",function(e){if(e.crossDomain){var n,r=i.head||i.getElementsByTagName("head")[0]||i.documentElement;return{send:function(s,o){n=i.createElement("script"),n.async="async",e.scriptCharset&&(n.charset=e.scriptCharset),n.src=e.url,n.onload=n.onreadystatechange=function(e,i){if(i||!n.readyState||/loaded|complete/.test(n.readyState))n.onload=n.onreadystatechange=null,r&&n.parentNode&&r.removeChild(n),n=t,i||o(200,"success")},r.insertBefore(n,r.firstChild)},abort:function(){n&&n.onload(0,1)}}}});var Hn,Bn=e.ActiveXObject?function(){for(var e in Hn)Hn[e](0,1)}:!1,jn=0;v.ajaxSettings.xhr=e.ActiveXObject?function(){return!this.isLocal&&Fn()||In()}:Fn,function(e){v.extend(v.support,{ajax:!!e,cors:!!e&&"withCredentials"in e})}(v.ajaxSettings.xhr()),v.support.ajax&&v.ajaxTransport(function(n){if(!n.crossDomain||v.support.cors){var r;return{send:function(i,s){var o,u,a=n.xhr();n.username?a.open(n.type,n.url,n.async,n.username,n.password):a.open(n.type,n.url,n.async);if(n.xhrFields)for(u in n.xhrFields)a[u]=n.xhrFields[u];n.mimeType&&a.overrideMimeType&&a.overrideMimeType(n.mimeType),!n.crossDomain&&!i["X-Requested-With"]&&(i["X-Requested-With"]="XMLHttpRequest");try{for(u in i)a.setRequestHeader(u,i[u])}catch(f){}a.send(n.hasContent&&n.data||null),r=function(e,i){var u,f,l,c,h;try{if(r&&(i||a.readyState===4)){r=t,o&&(a.onreadystatechange=v.noop,Bn&&delete Hn[o]);if(i)a.readyState!==4&&a.abort();else{u=a.status,l=a.getAllResponseHeaders(),c={},h=a.responseXML,h&&h.documentElement&&(c.xml=h);try{c.text=a.responseText}catch(p){}try{f=a.statusText}catch(p){f=""}!u&&n.isLocal&&!n.crossDomain?u=c.text?200:404:u===1223&&(u=204)}}}catch(d){i||s(-1,d)}c&&s(u,f,c,l)},n.async?a.readyState===4?setTimeout(r,0):(o=++jn,Bn&&(Hn||(Hn={},v(e).unload(Bn)),Hn[o]=r),a.onreadystatechange=r):r()},abort:function(){r&&r(0,1)}}}});var qn,Rn,Un=/^(?:toggle|show|hide)$/,zn=new RegExp("^(?:([-+])=|)("+m+")([a-z%]*)$","i"),Wn=/queueHooks$/,Xn=[Gn],Vn={"*":[function(e,t){var n,r,i=this.createTween(e,t),s=zn.exec(t),o=i.cur(),u=+o||0,a=1,f=20;if(s){n=+s[2],r=s[3]||(v.cssNumber[e]?"":"px");if(r!=="px"&&u){u=v.css(i.elem,e,!0)||n||1;do a=a||".5",u/=a,v.style(i.elem,e,u+r);while(a!==(a=i.cur()/o)&&a!==1&&--f)}i.unit=r,i.start=u,i.end=s[1]?u+(s[1]+1)*n:n}return i}]};v.Animation=v.extend(Kn,{tweener:function(e,t){v.isFunction(e)?(t=e,e=["*"]):e=e.split(" ");var n,r=0,i=e.length;for(;r-1,f={},l={},c,h;a?(l=i.position(),c=l.top,h=l.left):(c=parseFloat(o)||0,h=parseFloat(u)||0),v.isFunction(t)&&(t=t.call(e,n,s)),t.top!=null&&(f.top=t.top-s.top+c),t.left!=null&&(f.left=t.left-s.left+h),"using"in t?t.using.call(e,f):i.css(f)}},v.fn.extend({position:function(){if(!this[0])return;var e=this[0],t=this.offsetParent(),n=this.offset(),r=er.test(t[0].nodeName)?{top:0,left:0}:t.offset();return n.top-=parseFloat(v.css(e,"marginTop"))||0,n.left-=parseFloat(v.css(e,"marginLeft"))||0,r.top+=parseFloat(v.css(t[0],"borderTopWidth"))||0,r.left+=parseFloat(v.css(t[0],"borderLeftWidth"))||0,{top:n.top-r.top,left:n.left-r.left}},offsetParent:function(){return this.map(function(){var e=this.offsetParent||i.body;while(e&&!er.test(e.nodeName)&&v.css(e,"position")==="static")e=e.offsetParent;return e||i.body})}}),v.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(e,n){var r=/Y/.test(n);v.fn[e]=function(i){return v.access(this,function(e,i,s){var o=tr(e);if(s===t)return o?n in o?o[n]:o.document.documentElement[i]:e[i];o?o.scrollTo(r?v(o).scrollLeft():s,r?s:v(o).scrollTop()):e[i]=s},e,i,arguments.length,null)}}),v.each({Height:"height",Width:"width"},function(e,n){v.each({padding:"inner"+e,content:n,"":"outer"+e},function(r,i){v.fn[i]=function(i,s){var o=arguments.length&&(r||typeof i!="boolean"),u=r||(i===!0||s===!0?"margin":"border");return v.access(this,function(n,r,i){var s;return v.isWindow(n)?n.document.documentElement["client"+e]:n.nodeType===9?(s=n.documentElement,Math.max(n.body["scroll"+e],s["scroll"+e],n.body["offset"+e],s["offset"+e],s["client"+e])):i===t?v.css(n,r,i,u):v.style(n,r,i,u)},n,o?i:t,o,null)}})}),e.jQuery=e.$=v,typeof define=="function"&&define.amd&&define.amd.jQuery&&define("jquery",[],function(){return v})})(window); \ No newline at end of file diff --git a/Chapter09/03_connection_pools/static/content/login.js b/Chapter09/03_connection_pools/static/content/login.js new file mode 100644 index 0000000..fd52f1d --- /dev/null +++ b/Chapter09/03_connection_pools/static/content/login.js @@ -0,0 +1,30 @@ +$(function(){ + + var tmpl, // Main template HTML + tdata = {}; // JSON data object that feeds the template + + // Initialise page + var initPage = function() { + + // Load the HTML template + $.get("/templates/login.html", function(d){ + tmpl = d; + }); + + // Retrieve the server data and then initialise the page +// $.getJSON("/v1/users/logged_in.json", function (d) { +// $.extend(tdata, d); +// }); + + // When AJAX calls are complete parse the template + // replacing mustache tags with vars + $(document).ajaxStop(function () { +// if (tdata.data.logged_in) +// window.location = "/pages/admin/home"; +// else { + var renderedPage = Mustache.to_html( tmpl, tdata ); + $("body").html( renderedPage ); +// } + }); + }(); +}); diff --git a/Chapter09/03_connection_pools/static/content/mustache.js b/Chapter09/03_connection_pools/static/content/mustache.js new file mode 100644 index 0000000..0148d29 --- /dev/null +++ b/Chapter09/03_connection_pools/static/content/mustache.js @@ -0,0 +1,625 @@ +/*! + * mustache.js - Logic-less {{mustache}} templates with JavaScript + * http://github.com/janl/mustache.js + */ + +/*global define: false*/ + +var Mustache; + +(function (exports) { + if (typeof module !== "undefined" && module.exports) { + module.exports = exports; // CommonJS + } else if (typeof define === "function") { + define(exports); // AMD + } else { + Mustache = exports; // diff --git a/Chapter09/03_connection_pools/static/templates/admin_add_photos.html b/Chapter09/03_connection_pools/static/templates/admin_add_photos.html new file mode 100644 index 0000000..d9cbe8d --- /dev/null +++ b/Chapter09/03_connection_pools/static/templates/admin_add_photos.html @@ -0,0 +1,86 @@ +
+ +
+
Add to Album:
+
+ +
+
Image:
+
+
Description
+
+
+ + + + + +
+ + diff --git a/Chapter09/03_connection_pools/static/templates/admin_home.html b/Chapter09/03_connection_pools/static/templates/admin_home.html new file mode 100644 index 0000000..4db4cf1 --- /dev/null +++ b/Chapter09/03_connection_pools/static/templates/admin_home.html @@ -0,0 +1,7 @@ + +

Admin Operations

+ + diff --git a/Chapter09/03_connection_pools/static/templates/album.html b/Chapter09/03_connection_pools/static/templates/album.html new file mode 100644 index 0000000..fbcbda2 --- /dev/null +++ b/Chapter09/03_connection_pools/static/templates/album.html @@ -0,0 +1,20 @@ + +
+ {{#has_photos}} +

There are {{ has_photos }} photos in this album

+ {{/has_photos}} + {{#photos}} +
+
+
+
+

{{ desc }}

+
+
+ {{/photos}} +
+ {{^photos}} +

This album does't have any photos in it, sorry.

+ {{/photos}} +

diff --git a/Chapter09/03_connection_pools/static/templates/home.html b/Chapter09/03_connection_pools/static/templates/home.html new file mode 100644 index 0000000..90ff5fc --- /dev/null +++ b/Chapter09/03_connection_pools/static/templates/home.html @@ -0,0 +1,17 @@ +
+ Register | + Admin +
+
+

There are {{ albums.length }} albums

+
    + {{#albums}} +
  • + {{name}} +
  • + {{/albums}} + {{^albums}} +
  • Sorry, there are currently no albums
  • + {{/albums}} +
+
diff --git a/Chapter09/03_connection_pools/static/templates/login.html b/Chapter09/03_connection_pools/static/templates/login.html new file mode 100644 index 0000000..7bbcc3f --- /dev/null +++ b/Chapter09/03_connection_pools/static/templates/login.html @@ -0,0 +1,49 @@ + +
+
+
+
Email address:
+
+
Password:
+
+
+
+ + + + diff --git a/Chapter09/03_connection_pools/static/templates/register.html b/Chapter09/03_connection_pools/static/templates/register.html new file mode 100644 index 0000000..2934caa --- /dev/null +++ b/Chapter09/03_connection_pools/static/templates/register.html @@ -0,0 +1,56 @@ + + +
+
+
+
Email address:
+
+
Display Name:
+
+
Password:
+
+
Password (confirm):
+
+
+
+ + + + diff --git a/Chapter09/03_connection_pools/test.jpg b/Chapter09/03_connection_pools/test.jpg new file mode 100644 index 0000000..6e4250a Binary files /dev/null and b/Chapter09/03_connection_pools/test.jpg differ diff --git a/Chapter09/04_api_auth_added/app/basic.html b/Chapter09/04_api_auth_added/app/basic.html new file mode 100644 index 0000000..0d966da --- /dev/null +++ b/Chapter09/04_api_auth_added/app/basic.html @@ -0,0 +1,25 @@ + + + + Photo Album + + + + + + + + + + + + + + + + + diff --git a/Chapter09/04_api_auth_added/app/data/album.js b/Chapter09/04_api_auth_added/app/data/album.js new file mode 100644 index 0000000..d28fa6a --- /dev/null +++ b/Chapter09/04_api_auth_added/app/data/album.js @@ -0,0 +1,237 @@ + +var fs = require('fs'), + local = require('../local.config.js'), + db = require('./db.js'), + path = require("path"), + async = require('async'), + backhelp = require("./backend_helpers.js"); + +exports.version = "0.1.0"; + + +exports.create_album = function (data, callback) { + var write_succeeded = false; + var dbc; + + async.waterfall([ + // validate data. + function (cb) { + try { + backhelp.verify(data, + [ "name", + "title", + "date", + "description" ]); + if (!backhelp.valid_filename(data.name)) + throw invalid_album_name(); + } catch (e) { + cb(e); + } + + db.db(cb); + }, + + function (dbclient, cb) { + dbc = dbclient; + dbc.query( + "INSERT INTO Albums VALUES (?, ?, ?, ?)", + [ data.name, data.title, data.date, data.description ], + cb); + }, + + // make sure the folder exists. + function (results, fields, cb) { + write_succeeded = true; + fs.mkdir(local.config.static_content + + "albums/" + data.name, cb); + } + ], + function (err, results) { + // convert file errors to something we like. + if (err) { + if (write_succeeded) delete_album(dbc, data.name); + if (err instanceof Error && err.code == 'ER_EXISTS') + callback(backhelp.album_already_exists()); + else if (err instanceof Error && err.errno != undefined) + callback(backhelp.file_error(err)); + else + callback(err); + } else { + callback(err, err ? null : data); + } + + if (dbc) dbc.end(); + }); +}; + + +exports.album_by_name = function (name, callback) { + var dbc; + + async.waterfall([ + function (cb) { + if (!name) + cb(backhelp.missing_data("album name")); + else + db.db(cb); + }, + + function (dbclient, cb) { + dbc = dbclient; + dbc.query( + "SELECT * FROM Albums WHERE name = ?", + [ name ], + cb); + } + + ], + function (err, results) { + if (dbc) dbc.end(); + if (err) { + callback (err); + } else if (!results || results.length == 0) { + callback(backhelp.no_such_album()); + } else { + callback(null, results[0]); + } + }); +}; + + +exports.photos_for_album = function (album_name, skip, limit, callback) { + var dbc; + + async.waterfall([ + function (cb) { + if (!album_name) + cb(backhelp.missing_data("album name")); + else + db.db(cb); + }, + + function (dbclient, cb) { + dbc = dbclient; + dbc.query( + "SELECT * FROM Photos WHERE album_name = ? LIMIT ?, ?", + [ album_name, skip, limit ], + cb); + }, + + ], + function (err, results) { + if (dbc) dbc.end(); + if (err) { + callback (err); + } else { + callback(null, results); + } + }); +}; + + +exports.all_albums = function (sort_by, desc, skip, count, callback) { + var dbc; + async.waterfall([ + function (cb) { + db.db(cb); + }, + function (dbclient, cb) { + dbc = dbclient; + dbc.query( + "SELECT * FROM Albums ORDER BY ? " + + (desc ? "DESC" : "ASC") + + " LIMIT ?, ?", + [ sort_by, skip, count ], + cb); + } + ], + function (err, results) { + if (dbc) dbc.end(); + if (err) { + callback (err); + } else { + callback(null, results); + } + }); +}; + + +exports.add_photo = function (photo_data, path_to_photo, callback) { + var base_fn = path.basename(path_to_photo).toLowerCase(); + var write_succeeded = false; + var dbc; + + async.waterfall([ + // validate data + function (cb) { + try { + backhelp.verify(photo_data, + [ "albumid", "description", "date" ]); + photo_data.filename = base_fn; + if (!backhelp.valid_filename(photo_data.albumid)) + throw invalid_album_name(); + } catch (e) { + cb(e); + return; + } + db.db(cb); + }, + + function (dbclient, cb) { + dbc = dbclient; + dbc.query( + "INSERT INTO Photos VALUES (?, ?, ?, ?)", + [ photo_data.albumid, base_fn, photo_data.description, + photo_data.date ], + cb); + }, + + // now copy the temp file to static content + function (results, cb) { + write_succeeded = true; + var save_path = local.config.static_content + "albums/" + + photo_data.albumid + "/" + base_fn; + backhelp.file_copy(path_to_photo, save_path, true, cb); + }, + + ], + function (err, results) { + if (err && write_succeeded) + delete_photo(dbc, photo_data.albumid, base_fn); + if (err) { + callback (err); + } else { + // clone the object + var pd = JSON.parse(JSON.stringify(photo_data)); + pd.filename = base_fn; + callback(null, pd); + } + if (dbc) dbc.end(); + }); +}; + + +function invalid_album_name() { + return backhelp.error("invalid_album_name", + "Album names can have letters, #s, _ and, -"); +} +function invalid_filename() { + return backhelp.error("invalid_filename", + "Filenames can have letters, #s, _ and, -"); +} + + +function delete_album(dbc, name) { + dbc.query( + "DELETE FROM Albums WHERE name = ?", + [ name ], + function (err, results) {}); +} + +function delete_photo(dbc, albumid, fn) { + dbc.query( + "DELETE FROM Photos WHERE albumid = ? AND filename = ?", + [ albumid, fn ], + function (err, results) { }); +} + diff --git a/Chapter09/04_api_auth_added/app/data/backend_helpers.js b/Chapter09/04_api_auth_added/app/data/backend_helpers.js new file mode 100644 index 0000000..2df8e6b --- /dev/null +++ b/Chapter09/04_api_auth_added/app/data/backend_helpers.js @@ -0,0 +1,117 @@ + +var fs = require('fs'); + + +exports.verify = function (data, field_names) { + for (var i = 0; i < field_names.length; i++) { + if (!data[field_names[i]]) { + throw exports.error("missing_data", + field_names[i] + " not optional"); + } + } + + return true; +} + +exports.error = function (code, message) { + var e = new Error(message); + e.code = code; + return e; +}; + +exports.file_error = function (err) { + return exports.error("file_error", JSON.stringify(err.message)); +} + + + +/** + * Possible signatures: + * src, dst, callback + * src, dst, can_overwrite, callback + */ +exports.file_copy = function () { + + var src, dst, callback; + var can_overwrite = false; + + if (arguments.length == 3) { + src = arguments[0]; + dst = arguments[1]; + callback = arguments[2]; + } else if (arguments.length == 4) { + src = arguments[0]; + dst = arguments[1]; + callback = arguments[3]; + can_overwrite = arguments[2] + } + + function copy(err) { + var is, os; + + if (!err && !can_overwrite) { + return callback(backhelp.error("file_exists", + "File " + dst + " exists.")); + } + + fs.stat(src, function (err) { + if (err) { + return callback(err); + } + + is = fs.createReadStream(src); + os = fs.createWriteStream(dst); + is.on('end', function () { callback(null); }); + is.on('error', function (e) { callback(e); }); + is.pipe(os); + }); + } + + fs.stat(dst, copy); +}; + + + +exports.valid_filename = function (fn) { + var re = /[^\.a-zA-Z0-9_-]/; + return typeof fn == 'string' && fn.length > 0 && !(fn.match(re)); +}; + + +exports.db_error = function () { + return exports.error("server_error", + "Something horrible has happened with our database!"); +}; + +exports.album_already_exists = function () { + return exports.error("album_already_exists", + "An album with this name already exists."); +}; + +exports.missing_data = function (field) { + return exports.error("missing_data", "You must provide: " + field); +}; + +exports.no_such_user = function () { + return exports.error("no_such_user", + "The specified user does not exist"); +}; + + +exports.user_already_registered = function () { + return exports.error("user_already_registered", + "This user appears to exist already!"); +}; + + + +/** + * node-mysql sometimes adds extra data to callbacks to be helpful. + * this can mess up our waterfall, however, so we'll strip those + * out. + */ +exports.mscb = function (cb) { + return function (err, results) { + cb(err, results); + } +} diff --git a/Chapter09/04_api_auth_added/app/data/db.js b/Chapter09/04_api_auth_added/app/data/db.js new file mode 100644 index 0000000..b929d03 --- /dev/null +++ b/Chapter09/04_api_auth_added/app/data/db.js @@ -0,0 +1,14 @@ +var mysql = require('mysql'), + local = require("../local.config.js"); + +exports.db = function (callback) { + + conn_props = local.config.db_config; + var c = mysql.createConnection({ + host: conn_props.host, + user: conn_props.user, + password: conn_props.password, + database: conn_props.database + }); + callback(null, c); +}; diff --git a/Chapter09/04_api_auth_added/app/data/user.js b/Chapter09/04_api_auth_added/app/data/user.js new file mode 100644 index 0000000..29fe49c --- /dev/null +++ b/Chapter09/04_api_auth_added/app/data/user.js @@ -0,0 +1,127 @@ + +var async = require('async'), + bcrypt = require('bcrypt'), + db = require("./db.js"), + uuid = require('node-uuid'), + backhelp = require("./backend_helpers.js"); + + +exports.version = "0.1.0"; + +exports.user_by_uuid = function (uuid, callback) { + if (!uuid) + callback(backhelp.missing_data("uuid")); + else + user_by_field("user_uuid", uuid, callback); +}; + +exports.user_by_display_name = function (dn, callback) { + if (!dn) + callback(backhelp.missing_data("display_name")); + else + user_by_field("display_name", dn, callback); +} + +exports.user_by_email_address = function (email, callback) { + if (!email) + callback(backhelp.missing_data("email")); + else + user_by_field("email_address", email, callback); +}; + +exports.register = function (email, display_name, password, callback) { + var dbc; + var userid; + async.waterfall([ + // validate ze params + function (cb) { + if (!email || email.indexOf("@") == -1) + cb(backhelp.missing_data("email")); + else if (!display_name) + cb(backhelp.missing_data("display_name")); + else if (!password) + cb(backhelp.missing_data("password")); + else + cb(null); + }, + + // get a connection + function (cb) { + db.db(cb); + }, + + // generate a password hash + function (dbclient, cb) { + dbc = dbclient; + bcrypt.hash(password, 10, cb); + }, + + // register the account. + function (hash, cb) { + userid = uuid(); + var now = Math.round((new Date()).getTime() / 1000); + dbc.query( + "INSERT INTO Users VALUES (?, ?, ?, ?, ?, NULL, 0)", + [ userid, email.trim(), display_name.trim(), hash, now ], + cb); + }, + + // fetch and return the new user. + function (results, fields, cb) { + exports.user_by_uuid(userid, cb); + } + ], + function (err, user_data) { + if (dbc) dbc.end(); + if (err) { + if (err.code + && (err.code == 'ER_DUP_KEYNAME' + || err.code == 'ER_EXISTS' + || err.code == 'ER_DUP_ENTRY')) + callback(backhelp.user_already_registered()); + else + callback (err); + } else { + callback(null, user_data); + } + }); +}; + + + + +function user_by_field (field, value, callback) { + var dbc; + async.waterfall([ + // get a connection + function (cb) { + db.db(cb); + }, + + // fetch the user. + function (dbclient, cb) { + dbc = dbclient; + dbc.query( + "SELECT * FROM Users WHERE " + field + + " = ? AND deleted = false", + [ value ], + cb); + }, + + function (rows, fields, cb) { + if (!rows || rows.length == 0) + cb(backhelp.no_such_user()); + else + cb(null, rows[0]); + } + ], + function (err, user_data) { + if (dbc) dbc.end(); + if (err) { + callback (err); + } else { + console.log(user_data); + callback(null, user_data); + } + }); +} \ No newline at end of file diff --git a/Chapter09/04_api_auth_added/app/handlers/albums.js b/Chapter09/04_api_auth_added/app/handlers/albums.js new file mode 100644 index 0000000..ac2da86 --- /dev/null +++ b/Chapter09/04_api_auth_added/app/handlers/albums.js @@ -0,0 +1,259 @@ + +var helpers = require('./helpers.js'), + album_data = require("../data/album.js"), + async = require('async'), + fs = require('fs'); + +exports.version = "0.1.0"; + + +/** + * Album class. + */ +function Album (album_data) { + this.name = album_data.name; + this.date = album_data.date; + this.title = album_data.title; + this.description = album_data.description; + this._id = album_data._id; +} + +Album.prototype.name = null; +Album.prototype.date = null; +Album.prototype.title = null; +Album.prototype.description = null; + +Album.prototype.response_obj = function () { + return { name: this.name, + date: this.date, + title: this.title, + description: this.description }; +}; +Album.prototype.photos = function (pn, ps, callback) { + if (this.album_photos != undefined) { + callback(null, this.album_photos); + return; + } + + album_data.photos_for_album( + this.name, + pn, ps, + function (err, results) { + if (err) { + callback(err); + return; + } + + var out = []; + for (var i = 0; i < results.length; i++) { + out.push(new Photo(results[i])); + } + + this.album_photos = out; + callback(null, this.album_photos); + } + ); +}; +Album.prototype.add_photo = function (data, path, callback) { + album_data.add_photo(data, path, function (err, photo_data) { + if (err) + callback(err); + else { + var p = new Photo(photo_data); + if (this.all_photos) + this.all_photos.push(p); + else + this.app_photos = [ p ]; + + callback(null, p); + } + }); +}; + + + + +/** + * Photo class. + */ +function Photo (photo_data) { + this.filename = photo_data.filename; + this.date = photo_data.date; + this.albumid = photo_data.albumid; + this.description = photo_data.description; + this._id = photo_data._id; +} +Photo.prototype._id = null; +Photo.prototype.filename = null; +Photo.prototype.date = null; +Photo.prototype.albumid = null; +Photo.prototype.description = null; +Photo.prototype.response_obj = function() { + return { + filename: this.filename, + date: this.date, + albumid: this.albumid, + description: this.description + }; +}; + + +/** + * Album module methods. + */ +exports.create_album = function (req, res) { + async.waterfall([ + // make sure the albumid is valid + function (cb) { + if (!req.body || !req.body.name) { + cb(helpers.no_such_album()); + return; + } + + // UNDONE: we should add some code to make sure the album + // doesn't already exist! + cb(null); + }, + + function (cb) { + album_data.create_album(req.body, cb); + } + ], + function (err, results) { + if (err) { + helpers.send_failure(res, err); + } else { + var a = new Album(results); + helpers.send_success(res, {album: a.response_obj() }); + } + }); +}; + + +exports.album_by_name = function (req, res) { + async.waterfall([ + // get the album + function (cb) { + if (!req.params || !req.params.album_name) + cb(helpers.no_such_album()); + else + album_data.album_by_name(req.params.album_name, cb); + } + ], + function (err, results) { + if (err) { + helpers.send_failure(res, err); + } else if (!results) { + helpers.send_failure(res, helpers.no_such_album()); + } else { + var a = new Album(album_data); + helpers.send_success(res, { album: a.response_obj() }); + } + }); +}; + + + +exports.list_all = function (req, res) { + album_data.all_albums("date", true, 0, 25, function (err, results) { + if (err) { + helpers.send_failure(res, err); + } else { + var out = []; + if (results) { + for (var i = 0; i < results.length; i++) { + out.push(new Album(results[i]).response_obj()); + } + } + helpers.send_success(res, { albums: out }); + } + }); +}; + + +exports.photos_for_album = function(req, res) { + var page_num = req.query.page ? req.query.page : 0; + var page_size = req.query.page_size ? req.query.page_size : 1000; + + page_num = parseInt(page_num); + page_size = parseInt(page_size); + if (isNaN(page_num)) page_num = 0; + if (isNaN(page_size)) page_size = 1000; + + var album; + async.waterfall([ + function (cb) { + // first get the album. + if (!req.params || !req.params.album_name) + cb(helpers.no_such_album()); + else + album_data.album_by_name(req.params.album_name, cb); + }, + + function (album_data, cb) { + if (!album_data) { + cb(helpers.no_such_album()); + return; + } + album = new Album(album_data); + album.photos(page_num, page_size, cb); + }, + function (photos, cb) { + var out = []; + for (var i = 0; i < photos.length; i++) { + out.push(photos[i].response_obj()); + } + cb(null, out); + } + ], + function (err, results) { + if (err) { + helpers.send_failure(res, err); + return; + } + if (!results) results = []; + var out = { photos: results, + album_data: album.response_obj() }; + helpers.send_success(res, out); + }); +}; + + +exports.add_photo_to_album = function (req, res) { + var album; + async.waterfall([ + // make sure we have everything we need. + function (cb) { + if (!req.body) + cb(helpers.missing_data("POST data")); + else if (!req.files || !req.files.photo_file) + cb(helpers.missing_data("a file")); + else if (!helpers.is_image(req.files.photo_file.name)) + cb(helpers.not_image()); + else + // get the album + album_data.album_by_name(req.params.album_name, cb); + }, + + function (album_data, cb) { + if (!album_data) { + cb(helpers.no_such_album()); + return; + } + + album = new Album(album_data); + req.body.filename = req.files.photo_file.name; + album.add_photo(req.body, req.files.photo_file.path, cb); + } + ], + function (err, p) { + if (err) { + helpers.send_failure(res, err); + return; + } + var out = { photo: p.response_obj(), + album_data: album.response_obj() }; + helpers.send_success(res, out); + }); +}; + diff --git a/Chapter09/04_api_auth_added/app/handlers/helpers.js b/Chapter09/04_api_auth_added/app/handlers/helpers.js new file mode 100644 index 0000000..e6f0a13 --- /dev/null +++ b/Chapter09/04_api_auth_added/app/handlers/helpers.js @@ -0,0 +1,114 @@ + +var path = require('path'); + + +exports.version = '0.1.0'; + + + + +exports.send_success = function(res, data) { + res.writeHead(200, {"Content-Type": "application/json"}); + var output = { error: null, data: data }; + res.end(JSON.stringify(output) + "\n"); +} + + +exports.send_failure = function(res, err) { + console.log(err); + var code = (err.code) ? err.code : err.name; + res.writeHead(code, { "Content-Type" : "application/json" }); + res.end(JSON.stringify({ error: code, message: err.message }) + "\n"); +} + + +exports.error_for_resp = function (err) { + if (!err instanceof Error) { + console.error("** Unexpected error type! :" + + err.constructor.name); + return JSON.stringify(err); + } else { + var code = err.code ? err.code : err.name; + return JSON.stringify({ error: code, + message: err.message }); + } +} + +exports.error = function (code, message) { + var e = new Error(message); + e.code = code; + return e; +}; + +exports.file_error = function (err) { + return exports.error("file_error", JSON.stringify(err)); +}; + + +exports.is_image = function (filename) { + switch (path.extname(filename).toLowerCase()) { + case '.jpg': case '.jpeg': case '.png': case '.bmp': + case '.gif': case '.tif': case '.tiff': + return true; + } + + return false; +}; + + +exports.invalid_resource = function () { + return exports.error("invalid_resource", + "The requested resource does not exist."); +}; + + +exports.missing_data = function (what) { + return exports.error("missing_data", + "You must include " + what); +} + + +exports.not_image = function () { + return exports.error("not_image_file", + "The uploaded file must be an image file."); +}; + + +exports.no_such_album = function () { + return exports.error("no_such_album", + "The specified album does not exist"); +}; + + +exports.http_code_for_error = function (err) { + switch (err.message) { + case "no_such_album": + return 403; + case "invalid_resource": + return 404; + case "invalid_email_address": + return 403; + case "no_such_user": + return 403; + } + + console.log("*** Error needs HTTP response code: " + err.message); + return 503; +} + + +exports.valid_filename = function (fn) { + var re = /[^\.a-zA-Z0-9_-]/; + return typeof fn == 'string' && fn.length > 0 && !(fn.match(re)); +}; + + +exports.invalid_email_address = function () { + return exports.error("invalid_email_address", + "That's not a valid email address, sorry"); +}; + +exports.auth_failed = function () { + return exports.error("auth_failure", + "Invalid email address / password combination."); +}; \ No newline at end of file diff --git a/Chapter09/04_api_auth_added/app/handlers/pages.js b/Chapter09/04_api_auth_added/app/handlers/pages.js new file mode 100644 index 0000000..3e9baae --- /dev/null +++ b/Chapter09/04_api_auth_added/app/handlers/pages.js @@ -0,0 +1,42 @@ + +var helpers = require('./helpers.js'), + fs = require('fs'); + + +exports.version = "0.1.0"; + + +exports.generateAdmin = function (req, res) { + req.params.page_name = 'admin'; + exports.generate(req, res); +}; + +exports.generate = function (req, res) { + + var page = req.params.page_name; + if (req.params.sub_page && req.params.page_name == 'admin') + page = req.params.page_name + "_" + req.params.sub_page; + + fs.readFile( + 'basic.html', + function (err, contents) { + if (err) { + send_failure(res, 500, err); + return; + } + + contents = contents.toString('utf8'); + + // replace page name, and then dump to output. + contents = contents.replace('{{PAGE_NAME}}', page); + res.writeHead(200, { "Content-Type": "text/html" }); + res.end(contents); + } + ); +}; + +// if we made it here, then we're logged in. redirect to admin home +exports.login = function (req, res) { + res.redirect("/pages/admin/home"); + res.end(); +}; diff --git a/Chapter09/04_api_auth_added/app/handlers/users.js b/Chapter09/04_api_auth_added/app/handlers/users.js new file mode 100644 index 0000000..cfadfbb --- /dev/null +++ b/Chapter09/04_api_auth_added/app/handlers/users.js @@ -0,0 +1,170 @@ +var helpers = require('./helpers.js'), + user_data = require("../data/user.js"), + async = require('async'), + bcrypt = require('bcrypt'), + fs = require('fs'); + +exports.version = "0.1.0"; + + +function User (user_data) { + this.uuid = user_data["user_uuid"]; + this.email_address = user_data["email_address"]; + this.display_name = user_data["display_name"]; + this.password = user_data["password"]; + this.first_seen_date = user_data["first_seen_date"]; + this.last_modified_date = user_data["last_modified_date"]; + this.deleted = user_data["deleted"]; +} + +User.prototype.uuid = null; +User.prototype.email_address = null; +User.prototype.display_name = null; +User.prototype.password = null; +User.prototype.first_seen_date = null; +User.prototype.last_modified_date = null; +User.prototype.deleted = false; +User.prototype.check_password = function (pw, callback) { + bcrypt.compare(pw, this.password, callback); +}; +User.prototype.response_obj = function () { + return { + uuid: this.uuid, + email_address: this.email_address, + display_name: this.display_name, + first_seen_date: this.first_seen_date, + last_modified_date: this.last_modified_date + }; +}; + + + +exports.register = function (req, res) { + async.waterfall([ + function (cb) { + var em = req.body.email_address; + if (!em || em.indexOf("@") == -1) + cb(helpers.invalid_email_address()); + else if (!req.body.display_name) + cb(helpers.missing_data("display_name")); + else if (!req.body.password) + cb(helpers.missing_data("password")); + else + cb(null); + }, + + // register da user. + function (cb) { + user_data.register( + req.body.email_address, + req.body.display_name, + req.body.password, + cb); + }, + + // mark user as logged in + function (user_data, cb) { + req.session.logged_in = true; + req.session.logged_in_display_name = req.body.display_name; + req.session.logged_in_date = new Date(); + cb(null, user_data); + } + ], + function (err, user_data) { + if (err) { + helpers.send_failure(res, err); + } else { + var u = new User(user_data); + helpers.send_success(res, {user: u.response_obj() }); + } + }); +}; + + +exports.login = function (req, res) { + var em = req.body.email_address + ? req.body.email_address.trim().toLowerCase() + : ""; + + async.waterfall([ + function (cb) { + if (!em) + cb(helpers.missing_data("email_address")); + else if (req.session + && req.session.logged_in_email_address == em) + cb(helpers.error("already_logged_in", "")); + else if (!req.body.password) + cb(helpers.missing_data("password")); + else + cb(null); + }, + + // first get the user by the email address. + function (cb) { + user_data.user_by_email_address(em, cb); + }, + + // check the password + function (user_data, cb) { + var u = new User(user_data); + u.check_password(req.body.password, cb); + }, + + function (auth_ok, cb) { + if (!auth_ok) { + cb(helpers.auth_failed()); + return; + } + + req.session.logged_in = true; + req.session.logged_in_email_address = req.body.email_address; + req.session.logged_in_date = new Date(); + cb(null); + } + ], + function (err, results) { + if (!err || err.message == "already_logged_in") { + helpers.send_success(res, { logged_in: true }); + } else { + helpers.send_failure(res, err); + } + }); +}; + + +exports.user_by_display_name = function (req, res) { + async.waterfall([ + // first get the user by the email address. + function (cb) { + user_data.user_by_display_name(req.body.email_address, cb); + } + ], + function (err, u) { + if (!err) { + helpers.send_success(res, { user: u.response_obj() }); + } else { + helpers.send_failure(res, err); + } + }); +}; + + +exports.authenticate_API = function (un, pw, callback) { + async.waterfall([ + function (cb) { + user_data.user_by_email_address(un, cb); + }, + + function (user_data, cb) { + var u = new User(user_data); + u.check_password(pw, cb); + } + ], + function (err, results) { + if (!err) { + callback(null, un); + } else { + callback(new Error("bogus credentials")); + } + }); +}; diff --git a/Chapter09/04_api_auth_added/app/local.config.js b/Chapter09/04_api_auth_added/app/local.config.js new file mode 100644 index 0000000..85e0a8d --- /dev/null +++ b/Chapter09/04_api_auth_added/app/local.config.js @@ -0,0 +1,16 @@ + + +exports.config = { + db_config: { + host: "localhost", + user: "root", + password: "", + database: "PhotoAlbums", + + pooled_connections: 125, + idle_timeout_millis: 30000 + }, + + static_content: "../static/" +}; + diff --git a/Chapter09/04_api_auth_added/app/package.json b/Chapter09/04_api_auth_added/app/package.json new file mode 100644 index 0000000..a6f903b --- /dev/null +++ b/Chapter09/04_api_auth_added/app/package.json @@ -0,0 +1,14 @@ +{ + "name": "MySQL-Demo", + "description": "Demonstrates Using MySQL Database connectivity", + "version": "0.0.1", + "private": true, + "dependencies": { + "express": "3.x", + "async": "0.1.x", + "generic-pool": "2.x", + "mysql": "2.x", + "bcrypt": "0.x", + "node-uuid": "1.x" + } +} diff --git a/Chapter09/04_api_auth_added/app/server.js b/Chapter09/04_api_auth_added/app/server.js new file mode 100644 index 0000000..c5061f2 --- /dev/null +++ b/Chapter09/04_api_auth_added/app/server.js @@ -0,0 +1,103 @@ + +var express = require('express'); +var app = express(); + +var db = require('./data/db.js'), + album_hdlr = require('./handlers/albums.js'), + page_hdlr = require('./handlers/pages.js'), + user_hdlr = require('./handlers/users.js'), + helpers = require('./handlers/helpers.js'); + +app.use(express.logger('dev')); +app.use(express.bodyParser({ keepExtensions: true })); +app.use(express.static(__dirname + "/../static")); +app.use(express.cookieParser("kitten on keyboard")); +app.use(express.cookieSession({ + secret: "FLUFFY BUNNIES", + maxAge: 86400000 +})); + +app.get('/v1/albums.json', album_hdlr.list_all); +app.get('/v1/albums/:album_name.json', album_hdlr.album_by_name); +app.put('/v1/albums.json', requireAPILogin, album_hdlr.create_album); + +app.get('/v1/albums/:album_name/photos.json', album_hdlr.photos_for_album); +app.put('/v1/albums/:album_name/photos.json', + requireAPILogin, album_hdlr.add_photo_to_album); + + +// add-on requests we support for the purposes of the web interface +// to the server. +app.get('/pages/admin/:sub_page', + requirePageLogin, page_hdlr.generateAdmin); +app.get('/pages/:page_name', page_hdlr.generate); +app.get('/pages/:page_name/:sub_page', page_hdlr.generate); +app.post('/service/login', user_hdlr.login); + +app.put('/v1/users.json', user_hdlr.register); +app.get('/v1/users/:display_name.json', user_hdlr.user_by_display_name); + + +app.get("/", function (req, res) { + res.redirect("/pages/home"); + res.end(); +}); + +app.get('*', four_oh_four); + +function four_oh_four(req, res) { + res.writeHead(404, { "Content-Type" : "application/json" }); + res.end(JSON.stringify(helpers.invalid_resource()) + "\n"); +} + + +function requireAPILogin(req, res, next) { + // if they're using the API from the browser, then they'll be auth'd + if (req.session && req.session.logged_in) { + next(); + return; + } + var rha = req.headers.authorization; + if (rha && rha.search('Basic ') === 0) { + var creds = new Buffer(rha.split(' ')[1], 'base64').toString(); + var parts = creds.split(":"); + user_hdlr.authenticate_API( + parts[0], + parts[1], + function (err, resp) { + if (!err && resp) { + next(); + } else + need_auth(req, res); + } + ); + } else + need_auth(req, res); +} + + +function requirePageLogin(req, res, next) { + if (req.session && req.session.logged_in) { + next(); + } else { + res.redirect("/pages/login"); + } +} + +function need_auth(req, res) { + res.header('WWW-Authenticate', + 'Basic realm="Authorization required"'); + if (req.headers.authorization) { + // no more than 1 failure / 5s + setTimeout(function () { + res.send('Authentication required\n', 401); + }, 5000); + } else { + res.send('Authentication required\n', 401); + } +} + + +app.listen(8080); + + diff --git a/Chapter09/04_api_auth_added/app/user.js b/Chapter09/04_api_auth_added/app/user.js new file mode 100644 index 0000000..fd79c87 --- /dev/null +++ b/Chapter09/04_api_auth_added/app/user.js @@ -0,0 +1,129 @@ + +var async = require('async'), + bcrypt = require('bcrypt'), + db = require("./db.js"), + uuid = require('node-uuid'), + backhelp = require("./backend_helpers.js"); + + +exports.version = "0.1.0"; + +exports.user_by_uuid = function (uuid, callback) { + if (!uuid) + callback(backhelp.missing_data("uuid")); + else + user_by_field("user_uuid", uuid, callback); +}; + +exports.user_by_display_name = function (dn, callback) { + if (!dn) + callback(backhelp.missing_data("display_name")); + else + user_by_field("display_name", dn, callback); +} + +exports.user_by_email_address = function (email, callback) { + if (!email) + callback(backhelp.missing_data("email")); + else + user_by_field("email_address", email, callback); +}; + + + + +exports.register = function (email, display_name, password, callback) { + var dbc; + var userid; + async.waterfall([ + // validate ze params + function (cb) { + if (!email || email.indexOf("@") == -1) + cb(backhelp.missing_data("email")); + else if (!display_name) + cb(backhelp.missing_data("display_name")); + else if (!password) + cb(backhelp.missing_data("password")); + else + cb(null); + }, + + // get a connection + function (cb) { + db.db(cb); + }, + + // generate a password hash + function (dbclient, cb) { + dbc = dbclient; + bcrypt.hash(password, 10, cb); + }, + + // register the account. + function (hash, cb) { + userid = uuid(); + var now = Math.round((new Date()).getTime() / 1000); + dbc.query( + "INSERT INTO Users VALUES (?, ?, ?, ?, ?, NULL, 0)", + [ userid, email.trim(), display_name.trim(), hash, now ], + backhelp.mscb(cb)); + }, + + // fetch and return the new user. + function (results, cb) { + exports.user_by_uuid(userid, cb); + } + ], + function (err, user_data) { + if (dbc) dbc.end(); + if (err) { + if (err.code + && (err.code == 'ER_DUP_KEYNAME' + || err.code == 'ER_EXISTS' + || err.code == 'ER_DUP_ENTRY')) + callback(backhelp.user_already_registered()); + else + callback (err); + } else { + callback(null, user_data); + } + }); +}; + + + +function user_by_field (field, value, callback) { + var dbc; + async.waterfall([ + // get a connection + function (cb) { + db.db(cb); + }, + + // fetch the user. + function (dbclient, cb) { + dbc = dbclient; + dbc.query( + "SELECT * FROM Users WHERE " + field + + " = ? AND deleted = false", + [ value ], + backhelp.mscb(cb)); + }, + + function (rows, cb) { + if (!rows || rows.length == 0) + cb(backhelp.no_such_user()); + else + cb(null, rows[0]); + } + ], + function (err, user_data) { + if (dbc) dbc.end(); + if (err) { + callback (err); + } else { + console.log(user_data); + callback(null, user_data); + } + }); +} \ No newline at end of file diff --git a/Chapter09/04_api_auth_added/schema.sql b/Chapter09/04_api_auth_added/schema.sql new file mode 100644 index 0000000..61ab5c3 --- /dev/null +++ b/Chapter09/04_api_auth_added/schema.sql @@ -0,0 +1,53 @@ +DROP DATABASE IF EXISTS PhotoAlbums; + + +CREATE DATABASE PhotoAlbums + DEFAULT CHARACTER SET utf8 + DEFAULT COLLATE utf8_general_ci; + +USE PhotoAlbums; + + +CREATE TABLE Albums +( + name VARCHAR(50) UNIQUE PRIMARY KEY, + title VARCHAR(100), + date DATETIME, + description VARCHAR(500), + + -- allow for sorting on date. + INDEX(date) +) +ENGINE = InnoDB; + +CREATE TABLE Photos +( + album_name VARCHAR(50), + filename VARCHAR(50), + description VARCHAR(500), + date DATETIME, + + FOREIGN KEY (album_name) REFERENCES Albums (name), + INDEX (album_name, date) +) +ENGINE = InnoDB; + + +CREATE TABLE Users +( + user_uuid VARCHAR(50) UNIQUE PRIMARY KEY, + email_address VARCHAR(150) UNIQUE, + + display_name VARCHAR(100) UNIQUE, + password VARCHAR(100), + + first_seen_date BIGINT, + last_modified_date BIGINT, + deleted BOOL DEFAULT false, + + INDEX(email_address, deleted), + INDEX(user_uuid, deleted) +) +ENGINE = InnoDB; + + diff --git a/Chapter09/04_api_auth_added/static/albums/australia2010/aus_01.jpg b/Chapter09/04_api_auth_added/static/albums/australia2010/aus_01.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter09/04_api_auth_added/static/albums/australia2010/aus_02.jpg b/Chapter09/04_api_auth_added/static/albums/australia2010/aus_02.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter09/04_api_auth_added/static/albums/australia2010/aus_03.jpg b/Chapter09/04_api_auth_added/static/albums/australia2010/aus_03.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter09/04_api_auth_added/static/albums/australia2010/aus_04.jpg b/Chapter09/04_api_auth_added/static/albums/australia2010/aus_04.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter09/04_api_auth_added/static/albums/australia2010/aus_05.jpg b/Chapter09/04_api_auth_added/static/albums/australia2010/aus_05.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter09/04_api_auth_added/static/albums/australia2010/aus_06.jpg b/Chapter09/04_api_auth_added/static/albums/australia2010/aus_06.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter09/04_api_auth_added/static/albums/australia2010/aus_07.jpg b/Chapter09/04_api_auth_added/static/albums/australia2010/aus_07.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter09/04_api_auth_added/static/albums/australia2010/aus_08.jpg b/Chapter09/04_api_auth_added/static/albums/australia2010/aus_08.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter09/04_api_auth_added/static/albums/australia2010/aus_09.jpg b/Chapter09/04_api_auth_added/static/albums/australia2010/aus_09.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter09/04_api_auth_added/static/albums/italy2012/picture_01.jpg b/Chapter09/04_api_auth_added/static/albums/italy2012/picture_01.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter09/04_api_auth_added/static/albums/italy2012/picture_02.jpg b/Chapter09/04_api_auth_added/static/albums/italy2012/picture_02.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter09/04_api_auth_added/static/albums/italy2012/picture_03.jpg b/Chapter09/04_api_auth_added/static/albums/italy2012/picture_03.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter09/04_api_auth_added/static/albums/italy2012/picture_04.jpg b/Chapter09/04_api_auth_added/static/albums/italy2012/picture_04.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter09/04_api_auth_added/static/albums/italy2012/picture_05.jpg b/Chapter09/04_api_auth_added/static/albums/italy2012/picture_05.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter09/04_api_auth_added/static/albums/japan2010/picture_001.jpg b/Chapter09/04_api_auth_added/static/albums/japan2010/picture_001.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter09/04_api_auth_added/static/albums/japan2010/picture_002.jpg b/Chapter09/04_api_auth_added/static/albums/japan2010/picture_002.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter09/04_api_auth_added/static/albums/japan2010/picture_003.jpg b/Chapter09/04_api_auth_added/static/albums/japan2010/picture_003.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter09/04_api_auth_added/static/albums/japan2010/picture_004.jpg b/Chapter09/04_api_auth_added/static/albums/japan2010/picture_004.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter09/04_api_auth_added/static/albums/japan2010/picture_005.jpg b/Chapter09/04_api_auth_added/static/albums/japan2010/picture_005.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter09/04_api_auth_added/static/albums/japan2010/picture_006.jpg b/Chapter09/04_api_auth_added/static/albums/japan2010/picture_006.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter09/04_api_auth_added/static/albums/japan2010/picture_007.jpg b/Chapter09/04_api_auth_added/static/albums/japan2010/picture_007.jpg new file mode 100644 index 0000000..e69de29 diff --git a/Chapter09/04_api_auth_added/static/content/#album.js# b/Chapter09/04_api_auth_added/static/content/#album.js# new file mode 100644 index 0000000..442c047 --- /dev/null +++ b/Chapter09/04_api_auth_added/static/content/#album.js# @@ -0,0 +1,60 @@ +$(function(){ + + var tmpl, // Main template HTML + tdata = {}; // JSON data object that feeds the template + + // Initialise page + var initPage = function() { + + // get our album name. + var re = "/pages/album/([a-zA-Z0-9_-]+)"; + var results = new RegExp(re).exec(window.location.href); + var album_name = results[1]; + + // Load the HTML template + $.get("/templates/album.html", function(d){ + tmpl = d; + }); + + var p = $.urlParam("page"); + var ps = $.urlParam("page_size"); + if (p < 0) p = 0; + if (ps <= 0) ps = 1000; + + var qs = "?page=" + p + "&page_size=" + ps; + var url = "/v1/albums/" + album_name + "/photos.json" + qs; + + // Retrieve the server data and then initialise the page + $.getJSON(url, function (d) { + var photo_d = massage_album(d); + $.extend(tdata, photo_d); + }); + + // When AJAX calls are complete parse the template + // replacing mustache tags with vars + $(document).ajaxStop(function () { + var renderedPage = Mustache.to_html( tmpl, tdata ); + $("body").html( renderedPage ); + }) + }(); +}); + + +function massage_album(d) { + if (d.error != null) return d; + var obj = { photos: [] }; + + var p = d.data.photos; + var a = d.data.album_data; + + for (var i = 0; i < p.length; i++) { + var url = "/albums/" + a.name + "/" + p[i].filename; + obj.photos.push({ url: url, desc: p[i].description }); + } + + if (obj.photos.length > 0) obj.has_photos = obj.photos.length; + return obj; +} + + +xundo \ No newline at end of file diff --git a/Chapter09/04_api_auth_added/static/content/admin_add_album.js b/Chapter09/04_api_auth_added/static/content/admin_add_album.js new file mode 100644 index 0000000..f2987d6 --- /dev/null +++ b/Chapter09/04_api_auth_added/static/content/admin_add_album.js @@ -0,0 +1,22 @@ +$(function(){ + + var tmpl, // Main template HTML + tdata = {}; // JSON data object that feeds the template + + // Initialise page + var initPage = function() { + + // Load the HTML template + $.get("/templates/admin_add_album.html", function(d){ + tmpl = d; + }); + + // When AJAX calls are complete parse the template + // replacing mustache tags with vars + $(document).ajaxStop(function () { + var renderedPage = Mustache.to_html( tmpl, tdata ); + $("body").html( renderedPage ); + }) + }(); +}); + diff --git a/Chapter09/04_api_auth_added/static/content/admin_add_photos.js b/Chapter09/04_api_auth_added/static/content/admin_add_photos.js new file mode 100644 index 0000000..350e536 --- /dev/null +++ b/Chapter09/04_api_auth_added/static/content/admin_add_photos.js @@ -0,0 +1,27 @@ +$(function(){ + + var tmpl, // Main template HTML + tdata = {}; // JSON data object that feeds the template + + // Initialise page + var initPage = function() { + + // Load the HTML template + $.get("/templates/admin_add_photos.html", function(d){ + tmpl = d; + }); + + // Retrieve the server data and then initialise the page + $.getJSON("/v1/albums.json", function (d) { + $.extend(tdata, d.data); + }); + + // When AJAX calls are complete parse the template + // replacing mustache tags with vars + $(document).ajaxStop(function () { + var renderedPage = Mustache.to_html( tmpl, tdata ); + $("body").html( renderedPage ); + }) + }(); +}); + diff --git a/Chapter09/04_api_auth_added/static/content/admin_home.js b/Chapter09/04_api_auth_added/static/content/admin_home.js new file mode 100644 index 0000000..820f7fd --- /dev/null +++ b/Chapter09/04_api_auth_added/static/content/admin_home.js @@ -0,0 +1,22 @@ +$(function(){ + + var tmpl, // Main template HTML + tdata = {}; // JSON data object that feeds the template + + // Initialise page + var initPage = function() { + + // Load the HTML template + $.get("/templates/admin_home.html", function(d){ + tmpl = d; + }); + + // When AJAX calls are complete parse the template + // replacing mustache tags with vars + $(document).ajaxStop(function () { + var renderedPage = Mustache.to_html( tmpl, tdata ); + $("body").html( renderedPage ); + }) + }(); +}); + diff --git a/Chapter09/04_api_auth_added/static/content/album.js b/Chapter09/04_api_auth_added/static/content/album.js new file mode 100644 index 0000000..c4d918e --- /dev/null +++ b/Chapter09/04_api_auth_added/static/content/album.js @@ -0,0 +1,67 @@ +$(function(){ + + var tmpl, // Main template HTML + tdata = {}; // JSON data object that feeds the template + + // Initialise page + var initPage = function() { + + // get our album name. + var re = "/pages/album/([a-zA-Z0-9_-]+)"; + var results = new RegExp(re).exec(window.location.href); + var album_name = results[1]; + + // Load the HTML template + $.get("/templates/album.html", function(d){ + tmpl = d; + }); + + var p = $.urlParam("page"); + var ps = $.urlParam("page_size"); + if (p < 0) p = 0; + if (ps <= 0) ps = 1000; + + var qs = "?page=" + p + "&page_size=" + ps; + var url = "/v1/albums/" + album_name + "/photos.json" + qs; + + // Retrieve the server data and then initialise the page + $.getJSON(url, function (d) { + var photo_d = massage_album(d); + $.extend(tdata, photo_d); + }); + + // When AJAX calls are complete parse the template + // replacing mustache tags with vars + $(document).ajaxStop(function () { + var renderedPage = Mustache.to_html( tmpl, tdata ); + $("body").html( renderedPage ); + }) + }(); +}); + + +function massage_album(d) { + if (d.error != null) return d; + var obj = { photos: [] }; + + var p = d.data.photos; + var a = d.data.album_data; + + for (var i = 0; i < p.length; i++) { + var url = "/albums/" + a.name + "/" + p[i].filename; + obj.photos.push({ url: url, desc: p[i].description }); + } + + if (obj.photos.length > 0) obj.has_photos = obj.photos.length; + return obj; +} + + +$.urlParam = function(name){ + var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href); + if (!results) + { + return 0; + } + return results[1] || 0; +} \ No newline at end of file diff --git a/Chapter09/04_api_auth_added/static/content/home.js b/Chapter09/04_api_auth_added/static/content/home.js new file mode 100644 index 0000000..fa7010b --- /dev/null +++ b/Chapter09/04_api_auth_added/static/content/home.js @@ -0,0 +1,28 @@ +$(function(){ + + var tmpl, // Main template HTML + tdata = {}; // JSON data object that feeds the template + + // Initialise page + var initPage = function() { + + // Load the HTML template + $.get("/templates/home.html", function(d){ + tmpl = d; + }); + + + // Retrieve the server data and then initialise the page + $.getJSON("/v1/albums.json", function (d) { + $.extend(tdata, d.data); + }); + + // When AJAX calls are complete parse the template + // replacing mustache tags with vars + $(document).ajaxStop(function () { + var renderedPage = Mustache.to_html( tmpl, tdata ); + $("body").html( renderedPage ); + }) + }(); +}); + diff --git a/Chapter09/04_api_auth_added/static/content/jquery-1.8.3.min.js b/Chapter09/04_api_auth_added/static/content/jquery-1.8.3.min.js new file mode 100644 index 0000000..83589da --- /dev/null +++ b/Chapter09/04_api_auth_added/static/content/jquery-1.8.3.min.js @@ -0,0 +1,2 @@ +/*! jQuery v1.8.3 jquery.com | jquery.org/license */ +(function(e,t){function _(e){var t=M[e]={};return v.each(e.split(y),function(e,n){t[n]=!0}),t}function H(e,n,r){if(r===t&&e.nodeType===1){var i="data-"+n.replace(P,"-$1").toLowerCase();r=e.getAttribute(i);if(typeof r=="string"){try{r=r==="true"?!0:r==="false"?!1:r==="null"?null:+r+""===r?+r:D.test(r)?v.parseJSON(r):r}catch(s){}v.data(e,n,r)}else r=t}return r}function B(e){var t;for(t in e){if(t==="data"&&v.isEmptyObject(e[t]))continue;if(t!=="toJSON")return!1}return!0}function et(){return!1}function tt(){return!0}function ut(e){return!e||!e.parentNode||e.parentNode.nodeType===11}function at(e,t){do e=e[t];while(e&&e.nodeType!==1);return e}function ft(e,t,n){t=t||0;if(v.isFunction(t))return v.grep(e,function(e,r){var i=!!t.call(e,r,e);return i===n});if(t.nodeType)return v.grep(e,function(e,r){return e===t===n});if(typeof t=="string"){var r=v.grep(e,function(e){return e.nodeType===1});if(it.test(t))return v.filter(t,r,!n);t=v.filter(t,r)}return v.grep(e,function(e,r){return v.inArray(e,t)>=0===n})}function lt(e){var t=ct.split("|"),n=e.createDocumentFragment();if(n.createElement)while(t.length)n.createElement(t.pop());return n}function Lt(e,t){return e.getElementsByTagName(t)[0]||e.appendChild(e.ownerDocument.createElement(t))}function At(e,t){if(t.nodeType!==1||!v.hasData(e))return;var n,r,i,s=v._data(e),o=v._data(t,s),u=s.events;if(u){delete o.handle,o.events={};for(n in u)for(r=0,i=u[n].length;r").appendTo(i.body),n=t.css("display");t.remove();if(n==="none"||n===""){Pt=i.body.appendChild(Pt||v.extend(i.createElement("iframe"),{frameBorder:0,width:0,height:0}));if(!Ht||!Pt.createElement)Ht=(Pt.contentWindow||Pt.contentDocument).document,Ht.write(""),Ht.close();t=Ht.body.appendChild(Ht.createElement(e)),n=Dt(t,"display"),i.body.removeChild(Pt)}return Wt[e]=n,n}function fn(e,t,n,r){var i;if(v.isArray(t))v.each(t,function(t,i){n||sn.test(e)?r(e,i):fn(e+"["+(typeof i=="object"?t:"")+"]",i,n,r)});else if(!n&&v.type(t)==="object")for(i in t)fn(e+"["+i+"]",t[i],n,r);else r(e,t)}function Cn(e){return function(t,n){typeof t!="string"&&(n=t,t="*");var r,i,s,o=t.toLowerCase().split(y),u=0,a=o.length;if(v.isFunction(n))for(;u)[^>]*$|#([\w\-]*)$)/,E=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,S=/^[\],:{}\s]*$/,x=/(?:^|:|,)(?:\s*\[)+/g,T=/\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,N=/"[^"\\\r\n]*"|true|false|null|-?(?:\d\d*\.|)\d+(?:[eE][\-+]?\d+|)/g,C=/^-ms-/,k=/-([\da-z])/gi,L=function(e,t){return(t+"").toUpperCase()},A=function(){i.addEventListener?(i.removeEventListener("DOMContentLoaded",A,!1),v.ready()):i.readyState==="complete"&&(i.detachEvent("onreadystatechange",A),v.ready())},O={};v.fn=v.prototype={constructor:v,init:function(e,n,r){var s,o,u,a;if(!e)return this;if(e.nodeType)return this.context=this[0]=e,this.length=1,this;if(typeof e=="string"){e.charAt(0)==="<"&&e.charAt(e.length-1)===">"&&e.length>=3?s=[null,e,null]:s=w.exec(e);if(s&&(s[1]||!n)){if(s[1])return n=n instanceof v?n[0]:n,a=n&&n.nodeType?n.ownerDocument||n:i,e=v.parseHTML(s[1],a,!0),E.test(s[1])&&v.isPlainObject(n)&&this.attr.call(e,n,!0),v.merge(this,e);o=i.getElementById(s[2]);if(o&&o.parentNode){if(o.id!==s[2])return r.find(e);this.length=1,this[0]=o}return this.context=i,this.selector=e,this}return!n||n.jquery?(n||r).find(e):this.constructor(n).find(e)}return v.isFunction(e)?r.ready(e):(e.selector!==t&&(this.selector=e.selector,this.context=e.context),v.makeArray(e,this))},selector:"",jquery:"1.8.3",length:0,size:function(){return this.length},toArray:function(){return l.call(this)},get:function(e){return e==null?this.toArray():e<0?this[this.length+e]:this[e]},pushStack:function(e,t,n){var r=v.merge(this.constructor(),e);return r.prevObject=this,r.context=this.context,t==="find"?r.selector=this.selector+(this.selector?" ":"")+n:t&&(r.selector=this.selector+"."+t+"("+n+")"),r},each:function(e,t){return v.each(this,e,t)},ready:function(e){return v.ready.promise().done(e),this},eq:function(e){return e=+e,e===-1?this.slice(e):this.slice(e,e+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(l.apply(this,arguments),"slice",l.call(arguments).join(","))},map:function(e){return this.pushStack(v.map(this,function(t,n){return e.call(t,n,t)}))},end:function(){return this.prevObject||this.constructor(null)},push:f,sort:[].sort,splice:[].splice},v.fn.init.prototype=v.fn,v.extend=v.fn.extend=function(){var e,n,r,i,s,o,u=arguments[0]||{},a=1,f=arguments.length,l=!1;typeof u=="boolean"&&(l=u,u=arguments[1]||{},a=2),typeof u!="object"&&!v.isFunction(u)&&(u={}),f===a&&(u=this,--a);for(;a0)return;r.resolveWith(i,[v]),v.fn.trigger&&v(i).trigger("ready").off("ready")},isFunction:function(e){return v.type(e)==="function"},isArray:Array.isArray||function(e){return v.type(e)==="array"},isWindow:function(e){return e!=null&&e==e.window},isNumeric:function(e){return!isNaN(parseFloat(e))&&isFinite(e)},type:function(e){return e==null?String(e):O[h.call(e)]||"object"},isPlainObject:function(e){if(!e||v.type(e)!=="object"||e.nodeType||v.isWindow(e))return!1;try{if(e.constructor&&!p.call(e,"constructor")&&!p.call(e.constructor.prototype,"isPrototypeOf"))return!1}catch(n){return!1}var r;for(r in e);return r===t||p.call(e,r)},isEmptyObject:function(e){var t;for(t in e)return!1;return!0},error:function(e){throw new Error(e)},parseHTML:function(e,t,n){var r;return!e||typeof e!="string"?null:(typeof t=="boolean"&&(n=t,t=0),t=t||i,(r=E.exec(e))?[t.createElement(r[1])]:(r=v.buildFragment([e],t,n?null:[]),v.merge([],(r.cacheable?v.clone(r.fragment):r.fragment).childNodes)))},parseJSON:function(t){if(!t||typeof t!="string")return null;t=v.trim(t);if(e.JSON&&e.JSON.parse)return e.JSON.parse(t);if(S.test(t.replace(T,"@").replace(N,"]").replace(x,"")))return(new Function("return "+t))();v.error("Invalid JSON: "+t)},parseXML:function(n){var r,i;if(!n||typeof n!="string")return null;try{e.DOMParser?(i=new DOMParser,r=i.parseFromString(n,"text/xml")):(r=new ActiveXObject("Microsoft.XMLDOM"),r.async="false",r.loadXML(n))}catch(s){r=t}return(!r||!r.documentElement||r.getElementsByTagName("parsererror").length)&&v.error("Invalid XML: "+n),r},noop:function(){},globalEval:function(t){t&&g.test(t)&&(e.execScript||function(t){e.eval.call(e,t)})(t)},camelCase:function(e){return e.replace(C,"ms-").replace(k,L)},nodeName:function(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()},each:function(e,n,r){var i,s=0,o=e.length,u=o===t||v.isFunction(e);if(r){if(u){for(i in e)if(n.apply(e[i],r)===!1)break}else for(;s0&&e[0]&&e[a-1]||a===0||v.isArray(e));if(f)for(;u-1)a.splice(n,1),i&&(n<=o&&o--,n<=u&&u--)}),this},has:function(e){return v.inArray(e,a)>-1},empty:function(){return a=[],this},disable:function(){return a=f=n=t,this},disabled:function(){return!a},lock:function(){return f=t,n||c.disable(),this},locked:function(){return!f},fireWith:function(e,t){return t=t||[],t=[e,t.slice?t.slice():t],a&&(!r||f)&&(i?f.push(t):l(t)),this},fire:function(){return c.fireWith(this,arguments),this},fired:function(){return!!r}};return c},v.extend({Deferred:function(e){var t=[["resolve","done",v.Callbacks("once memory"),"resolved"],["reject","fail",v.Callbacks("once memory"),"rejected"],["notify","progress",v.Callbacks("memory")]],n="pending",r={state:function(){return n},always:function(){return i.done(arguments).fail(arguments),this},then:function(){var e=arguments;return v.Deferred(function(n){v.each(t,function(t,r){var s=r[0],o=e[t];i[r[1]](v.isFunction(o)?function(){var e=o.apply(this,arguments);e&&v.isFunction(e.promise)?e.promise().done(n.resolve).fail(n.reject).progress(n.notify):n[s+"With"](this===i?n:this,[e])}:n[s])}),e=null}).promise()},promise:function(e){return e!=null?v.extend(e,r):r}},i={};return r.pipe=r.then,v.each(t,function(e,s){var o=s[2],u=s[3];r[s[1]]=o.add,u&&o.add(function(){n=u},t[e^1][2].disable,t[2][2].lock),i[s[0]]=o.fire,i[s[0]+"With"]=o.fireWith}),r.promise(i),e&&e.call(i,i),i},when:function(e){var t=0,n=l.call(arguments),r=n.length,i=r!==1||e&&v.isFunction(e.promise)?r:0,s=i===1?e:v.Deferred(),o=function(e,t,n){return function(r){t[e]=this,n[e]=arguments.length>1?l.call(arguments):r,n===u?s.notifyWith(t,n):--i||s.resolveWith(t,n)}},u,a,f;if(r>1){u=new Array(r),a=new Array(r),f=new Array(r);for(;t
a",n=p.getElementsByTagName("*"),r=p.getElementsByTagName("a")[0];if(!n||!r||!n.length)return{};s=i.createElement("select"),o=s.appendChild(i.createElement("option")),u=p.getElementsByTagName("input")[0],r.style.cssText="top:1px;float:left;opacity:.5",t={leadingWhitespace:p.firstChild.nodeType===3,tbody:!p.getElementsByTagName("tbody").length,htmlSerialize:!!p.getElementsByTagName("link").length,style:/top/.test(r.getAttribute("style")),hrefNormalized:r.getAttribute("href")==="/a",opacity:/^0.5/.test(r.style.opacity),cssFloat:!!r.style.cssFloat,checkOn:u.value==="on",optSelected:o.selected,getSetAttribute:p.className!=="t",enctype:!!i.createElement("form").enctype,html5Clone:i.createElement("nav").cloneNode(!0).outerHTML!=="<:nav>",boxModel:i.compatMode==="CSS1Compat",submitBubbles:!0,changeBubbles:!0,focusinBubbles:!1,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0,boxSizingReliable:!0,pixelPosition:!1},u.checked=!0,t.noCloneChecked=u.cloneNode(!0).checked,s.disabled=!0,t.optDisabled=!o.disabled;try{delete p.test}catch(d){t.deleteExpando=!1}!p.addEventListener&&p.attachEvent&&p.fireEvent&&(p.attachEvent("onclick",h=function(){t.noCloneEvent=!1}),p.cloneNode(!0).fireEvent("onclick"),p.detachEvent("onclick",h)),u=i.createElement("input"),u.value="t",u.setAttribute("type","radio"),t.radioValue=u.value==="t",u.setAttribute("checked","checked"),u.setAttribute("name","t"),p.appendChild(u),a=i.createDocumentFragment(),a.appendChild(p.lastChild),t.checkClone=a.cloneNode(!0).cloneNode(!0).lastChild.checked,t.appendChecked=u.checked,a.removeChild(u),a.appendChild(p);if(p.attachEvent)for(l in{submit:!0,change:!0,focusin:!0})f="on"+l,c=f in p,c||(p.setAttribute(f,"return;"),c=typeof p[f]=="function"),t[l+"Bubbles"]=c;return v(function(){var n,r,s,o,u="padding:0;margin:0;border:0;display:block;overflow:hidden;",a=i.getElementsByTagName("body")[0];if(!a)return;n=i.createElement("div"),n.style.cssText="visibility:hidden;border:0;width:0;height:0;position:static;top:0;margin-top:1px",a.insertBefore(n,a.firstChild),r=i.createElement("div"),n.appendChild(r),r.innerHTML="
t
",s=r.getElementsByTagName("td"),s[0].style.cssText="padding:0;margin:0;border:0;display:none",c=s[0].offsetHeight===0,s[0].style.display="",s[1].style.display="none",t.reliableHiddenOffsets=c&&s[0].offsetHeight===0,r.innerHTML="",r.style.cssText="box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;",t.boxSizing=r.offsetWidth===4,t.doesNotIncludeMarginInBodyOffset=a.offsetTop!==1,e.getComputedStyle&&(t.pixelPosition=(e.getComputedStyle(r,null)||{}).top!=="1%",t.boxSizingReliable=(e.getComputedStyle(r,null)||{width:"4px"}).width==="4px",o=i.createElement("div"),o.style.cssText=r.style.cssText=u,o.style.marginRight=o.style.width="0",r.style.width="1px",r.appendChild(o),t.reliableMarginRight=!parseFloat((e.getComputedStyle(o,null)||{}).marginRight)),typeof r.style.zoom!="undefined"&&(r.innerHTML="",r.style.cssText=u+"width:1px;padding:1px;display:inline;zoom:1",t.inlineBlockNeedsLayout=r.offsetWidth===3,r.style.display="block",r.style.overflow="visible",r.innerHTML="
",r.firstChild.style.width="5px",t.shrinkWrapBlocks=r.offsetWidth!==3,n.style.zoom=1),a.removeChild(n),n=r=s=o=null}),a.removeChild(p),n=r=s=o=u=a=p=null,t}();var D=/(?:\{[\s\S]*\}|\[[\s\S]*\])$/,P=/([A-Z])/g;v.extend({cache:{},deletedIds:[],uuid:0,expando:"jQuery"+(v.fn.jquery+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(e){return e=e.nodeType?v.cache[e[v.expando]]:e[v.expando],!!e&&!B(e)},data:function(e,n,r,i){if(!v.acceptData(e))return;var s,o,u=v.expando,a=typeof n=="string",f=e.nodeType,l=f?v.cache:e,c=f?e[u]:e[u]&&u;if((!c||!l[c]||!i&&!l[c].data)&&a&&r===t)return;c||(f?e[u]=c=v.deletedIds.pop()||v.guid++:c=u),l[c]||(l[c]={},f||(l[c].toJSON=v.noop));if(typeof n=="object"||typeof n=="function")i?l[c]=v.extend(l[c],n):l[c].data=v.extend(l[c].data,n);return s=l[c],i||(s.data||(s.data={}),s=s.data),r!==t&&(s[v.camelCase(n)]=r),a?(o=s[n],o==null&&(o=s[v.camelCase(n)])):o=s,o},removeData:function(e,t,n){if(!v.acceptData(e))return;var r,i,s,o=e.nodeType,u=o?v.cache:e,a=o?e[v.expando]:v.expando;if(!u[a])return;if(t){r=n?u[a]:u[a].data;if(r){v.isArray(t)||(t in r?t=[t]:(t=v.camelCase(t),t in r?t=[t]:t=t.split(" ")));for(i=0,s=t.length;i1,null,!1))},removeData:function(e){return this.each(function(){v.removeData(this,e)})}}),v.extend({queue:function(e,t,n){var r;if(e)return t=(t||"fx")+"queue",r=v._data(e,t),n&&(!r||v.isArray(n)?r=v._data(e,t,v.makeArray(n)):r.push(n)),r||[]},dequeue:function(e,t){t=t||"fx";var n=v.queue(e,t),r=n.length,i=n.shift(),s=v._queueHooks(e,t),o=function(){v.dequeue(e,t)};i==="inprogress"&&(i=n.shift(),r--),i&&(t==="fx"&&n.unshift("inprogress"),delete s.stop,i.call(e,o,s)),!r&&s&&s.empty.fire()},_queueHooks:function(e,t){var n=t+"queueHooks";return v._data(e,n)||v._data(e,n,{empty:v.Callbacks("once memory").add(function(){v.removeData(e,t+"queue",!0),v.removeData(e,n,!0)})})}}),v.fn.extend({queue:function(e,n){var r=2;return typeof e!="string"&&(n=e,e="fx",r--),arguments.length1)},removeAttr:function(e){return this.each(function(){v.removeAttr(this,e)})},prop:function(e,t){return v.access(this,v.prop,e,t,arguments.length>1)},removeProp:function(e){return e=v.propFix[e]||e,this.each(function(){try{this[e]=t,delete this[e]}catch(n){}})},addClass:function(e){var t,n,r,i,s,o,u;if(v.isFunction(e))return this.each(function(t){v(this).addClass(e.call(this,t,this.className))});if(e&&typeof e=="string"){t=e.split(y);for(n=0,r=this.length;n=0)r=r.replace(" "+n[s]+" "," ");i.className=e?v.trim(r):""}}}return this},toggleClass:function(e,t){var n=typeof e,r=typeof t=="boolean";return v.isFunction(e)?this.each(function(n){v(this).toggleClass(e.call(this,n,this.className,t),t)}):this.each(function(){if(n==="string"){var i,s=0,o=v(this),u=t,a=e.split(y);while(i=a[s++])u=r?u:!o.hasClass(i),o[u?"addClass":"removeClass"](i)}else if(n==="undefined"||n==="boolean")this.className&&v._data(this,"__className__",this.className),this.className=this.className||e===!1?"":v._data(this,"__className__")||""})},hasClass:function(e){var t=" "+e+" ",n=0,r=this.length;for(;n=0)return!0;return!1},val:function(e){var n,r,i,s=this[0];if(!arguments.length){if(s)return n=v.valHooks[s.type]||v.valHooks[s.nodeName.toLowerCase()],n&&"get"in n&&(r=n.get(s,"value"))!==t?r:(r=s.value,typeof r=="string"?r.replace(R,""):r==null?"":r);return}return i=v.isFunction(e),this.each(function(r){var s,o=v(this);if(this.nodeType!==1)return;i?s=e.call(this,r,o.val()):s=e,s==null?s="":typeof s=="number"?s+="":v.isArray(s)&&(s=v.map(s,function(e){return e==null?"":e+""})),n=v.valHooks[this.type]||v.valHooks[this.nodeName.toLowerCase()];if(!n||!("set"in n)||n.set(this,s,"value")===t)this.value=s})}}),v.extend({valHooks:{option:{get:function(e){var t=e.attributes.value;return!t||t.specified?e.value:e.text}},select:{get:function(e){var t,n,r=e.options,i=e.selectedIndex,s=e.type==="select-one"||i<0,o=s?null:[],u=s?i+1:r.length,a=i<0?u:s?i:0;for(;a=0}),n.length||(e.selectedIndex=-1),n}}},attrFn:{},attr:function(e,n,r,i){var s,o,u,a=e.nodeType;if(!e||a===3||a===8||a===2)return;if(i&&v.isFunction(v.fn[n]))return v(e)[n](r);if(typeof e.getAttribute=="undefined")return v.prop(e,n,r);u=a!==1||!v.isXMLDoc(e),u&&(n=n.toLowerCase(),o=v.attrHooks[n]||(X.test(n)?F:j));if(r!==t){if(r===null){v.removeAttr(e,n);return}return o&&"set"in o&&u&&(s=o.set(e,r,n))!==t?s:(e.setAttribute(n,r+""),r)}return o&&"get"in o&&u&&(s=o.get(e,n))!==null?s:(s=e.getAttribute(n),s===null?t:s)},removeAttr:function(e,t){var n,r,i,s,o=0;if(t&&e.nodeType===1){r=t.split(y);for(;o=0}})});var $=/^(?:textarea|input|select)$/i,J=/^([^\.]*|)(?:\.(.+)|)$/,K=/(?:^|\s)hover(\.\S+|)\b/,Q=/^key/,G=/^(?:mouse|contextmenu)|click/,Y=/^(?:focusinfocus|focusoutblur)$/,Z=function(e){return v.event.special.hover?e:e.replace(K,"mouseenter$1 mouseleave$1")};v.event={add:function(e,n,r,i,s){var o,u,a,f,l,c,h,p,d,m,g;if(e.nodeType===3||e.nodeType===8||!n||!r||!(o=v._data(e)))return;r.handler&&(d=r,r=d.handler,s=d.selector),r.guid||(r.guid=v.guid++),a=o.events,a||(o.events=a={}),u=o.handle,u||(o.handle=u=function(e){return typeof v=="undefined"||!!e&&v.event.triggered===e.type?t:v.event.dispatch.apply(u.elem,arguments)},u.elem=e),n=v.trim(Z(n)).split(" ");for(f=0;f=0&&(y=y.slice(0,-1),a=!0),y.indexOf(".")>=0&&(b=y.split("."),y=b.shift(),b.sort());if((!s||v.event.customEvent[y])&&!v.event.global[y])return;n=typeof n=="object"?n[v.expando]?n:new v.Event(y,n):new v.Event(y),n.type=y,n.isTrigger=!0,n.exclusive=a,n.namespace=b.join("."),n.namespace_re=n.namespace?new RegExp("(^|\\.)"+b.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,h=y.indexOf(":")<0?"on"+y:"";if(!s){u=v.cache;for(f in u)u[f].events&&u[f].events[y]&&v.event.trigger(n,r,u[f].handle.elem,!0);return}n.result=t,n.target||(n.target=s),r=r!=null?v.makeArray(r):[],r.unshift(n),p=v.event.special[y]||{};if(p.trigger&&p.trigger.apply(s,r)===!1)return;m=[[s,p.bindType||y]];if(!o&&!p.noBubble&&!v.isWindow(s)){g=p.delegateType||y,l=Y.test(g+y)?s:s.parentNode;for(c=s;l;l=l.parentNode)m.push([l,g]),c=l;c===(s.ownerDocument||i)&&m.push([c.defaultView||c.parentWindow||e,g])}for(f=0;f=0:v.find(h,this,null,[s]).length),u[h]&&f.push(c);f.length&&w.push({elem:s,matches:f})}d.length>m&&w.push({elem:this,matches:d.slice(m)});for(r=0;r0?this.on(t,null,e,n):this.trigger(t)},Q.test(t)&&(v.event.fixHooks[t]=v.event.keyHooks),G.test(t)&&(v.event.fixHooks[t]=v.event.mouseHooks)}),function(e,t){function nt(e,t,n,r){n=n||[],t=t||g;var i,s,a,f,l=t.nodeType;if(!e||typeof e!="string")return n;if(l!==1&&l!==9)return[];a=o(t);if(!a&&!r)if(i=R.exec(e))if(f=i[1]){if(l===9){s=t.getElementById(f);if(!s||!s.parentNode)return n;if(s.id===f)return n.push(s),n}else if(t.ownerDocument&&(s=t.ownerDocument.getElementById(f))&&u(t,s)&&s.id===f)return n.push(s),n}else{if(i[2])return S.apply(n,x.call(t.getElementsByTagName(e),0)),n;if((f=i[3])&&Z&&t.getElementsByClassName)return S.apply(n,x.call(t.getElementsByClassName(f),0)),n}return vt(e.replace(j,"$1"),t,n,r,a)}function rt(e){return function(t){var n=t.nodeName.toLowerCase();return n==="input"&&t.type===e}}function it(e){return function(t){var n=t.nodeName.toLowerCase();return(n==="input"||n==="button")&&t.type===e}}function st(e){return N(function(t){return t=+t,N(function(n,r){var i,s=e([],n.length,t),o=s.length;while(o--)n[i=s[o]]&&(n[i]=!(r[i]=n[i]))})})}function ot(e,t,n){if(e===t)return n;var r=e.nextSibling;while(r){if(r===t)return-1;r=r.nextSibling}return 1}function ut(e,t){var n,r,s,o,u,a,f,l=L[d][e+" "];if(l)return t?0:l.slice(0);u=e,a=[],f=i.preFilter;while(u){if(!n||(r=F.exec(u)))r&&(u=u.slice(r[0].length)||u),a.push(s=[]);n=!1;if(r=I.exec(u))s.push(n=new m(r.shift())),u=u.slice(n.length),n.type=r[0].replace(j," ");for(o in i.filter)(r=J[o].exec(u))&&(!f[o]||(r=f[o](r)))&&(s.push(n=new m(r.shift())),u=u.slice(n.length),n.type=o,n.matches=r);if(!n)break}return t?u.length:u?nt.error(e):L(e,a).slice(0)}function at(e,t,r){var i=t.dir,s=r&&t.dir==="parentNode",o=w++;return t.first?function(t,n,r){while(t=t[i])if(s||t.nodeType===1)return e(t,n,r)}:function(t,r,u){if(!u){var a,f=b+" "+o+" ",l=f+n;while(t=t[i])if(s||t.nodeType===1){if((a=t[d])===l)return t.sizset;if(typeof a=="string"&&a.indexOf(f)===0){if(t.sizset)return t}else{t[d]=l;if(e(t,r,u))return t.sizset=!0,t;t.sizset=!1}}}else while(t=t[i])if(s||t.nodeType===1)if(e(t,r,u))return t}}function ft(e){return e.length>1?function(t,n,r){var i=e.length;while(i--)if(!e[i](t,n,r))return!1;return!0}:e[0]}function lt(e,t,n,r,i){var s,o=[],u=0,a=e.length,f=t!=null;for(;u-1&&(s[f]=!(o[f]=c))}}else g=lt(g===o?g.splice(d,g.length):g),i?i(null,o,g,a):S.apply(o,g)})}function ht(e){var t,n,r,s=e.length,o=i.relative[e[0].type],u=o||i.relative[" "],a=o?1:0,f=at(function(e){return e===t},u,!0),l=at(function(e){return T.call(t,e)>-1},u,!0),h=[function(e,n,r){return!o&&(r||n!==c)||((t=n).nodeType?f(e,n,r):l(e,n,r))}];for(;a1&&ft(h),a>1&&e.slice(0,a-1).join("").replace(j,"$1"),n,a0,s=e.length>0,o=function(u,a,f,l,h){var p,d,v,m=[],y=0,w="0",x=u&&[],T=h!=null,N=c,C=u||s&&i.find.TAG("*",h&&a.parentNode||a),k=b+=N==null?1:Math.E;T&&(c=a!==g&&a,n=o.el);for(;(p=C[w])!=null;w++){if(s&&p){for(d=0;v=e[d];d++)if(v(p,a,f)){l.push(p);break}T&&(b=k,n=++o.el)}r&&((p=!v&&p)&&y--,u&&x.push(p))}y+=w;if(r&&w!==y){for(d=0;v=t[d];d++)v(x,m,a,f);if(u){if(y>0)while(w--)!x[w]&&!m[w]&&(m[w]=E.call(l));m=lt(m)}S.apply(l,m),T&&!u&&m.length>0&&y+t.length>1&&nt.uniqueSort(l)}return T&&(b=k,c=N),x};return o.el=0,r?N(o):o}function dt(e,t,n){var r=0,i=t.length;for(;r2&&(f=u[0]).type==="ID"&&t.nodeType===9&&!s&&i.relative[u[1].type]){t=i.find.ID(f.matches[0].replace($,""),t,s)[0];if(!t)return n;e=e.slice(u.shift().length)}for(o=J.POS.test(e)?-1:u.length-1;o>=0;o--){f=u[o];if(i.relative[l=f.type])break;if(c=i.find[l])if(r=c(f.matches[0].replace($,""),z.test(u[0].type)&&t.parentNode||t,s)){u.splice(o,1),e=r.length&&u.join("");if(!e)return S.apply(n,x.call(r,0)),n;break}}}return a(e,h)(r,t,s,n,z.test(e)),n}function mt(){}var n,r,i,s,o,u,a,f,l,c,h=!0,p="undefined",d=("sizcache"+Math.random()).replace(".",""),m=String,g=e.document,y=g.documentElement,b=0,w=0,E=[].pop,S=[].push,x=[].slice,T=[].indexOf||function(e){var t=0,n=this.length;for(;ti.cacheLength&&delete e[t.shift()],e[n+" "]=r},e)},k=C(),L=C(),A=C(),O="[\\x20\\t\\r\\n\\f]",M="(?:\\\\.|[-\\w]|[^\\x00-\\xa0])+",_=M.replace("w","w#"),D="([*^$|!~]?=)",P="\\["+O+"*("+M+")"+O+"*(?:"+D+O+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+_+")|)|)"+O+"*\\]",H=":("+M+")(?:\\((?:(['\"])((?:\\\\.|[^\\\\])*?)\\2|([^()[\\]]*|(?:(?:"+P+")|[^:]|\\\\.)*|.*))\\)|)",B=":(even|odd|eq|gt|lt|nth|first|last)(?:\\("+O+"*((?:-\\d)?\\d*)"+O+"*\\)|)(?=[^-]|$)",j=new RegExp("^"+O+"+|((?:^|[^\\\\])(?:\\\\.)*)"+O+"+$","g"),F=new RegExp("^"+O+"*,"+O+"*"),I=new RegExp("^"+O+"*([\\x20\\t\\r\\n\\f>+~])"+O+"*"),q=new RegExp(H),R=/^(?:#([\w\-]+)|(\w+)|\.([\w\-]+))$/,U=/^:not/,z=/[\x20\t\r\n\f]*[+~]/,W=/:not\($/,X=/h\d/i,V=/input|select|textarea|button/i,$=/\\(?!\\)/g,J={ID:new RegExp("^#("+M+")"),CLASS:new RegExp("^\\.("+M+")"),NAME:new RegExp("^\\[name=['\"]?("+M+")['\"]?\\]"),TAG:new RegExp("^("+M.replace("w","w*")+")"),ATTR:new RegExp("^"+P),PSEUDO:new RegExp("^"+H),POS:new RegExp(B,"i"),CHILD:new RegExp("^:(only|nth|first|last)-child(?:\\("+O+"*(even|odd|(([+-]|)(\\d*)n|)"+O+"*(?:([+-]|)"+O+"*(\\d+)|))"+O+"*\\)|)","i"),needsContext:new RegExp("^"+O+"*[>+~]|"+B,"i")},K=function(e){var t=g.createElement("div");try{return e(t)}catch(n){return!1}finally{t=null}},Q=K(function(e){return e.appendChild(g.createComment("")),!e.getElementsByTagName("*").length}),G=K(function(e){return e.innerHTML="",e.firstChild&&typeof e.firstChild.getAttribute!==p&&e.firstChild.getAttribute("href")==="#"}),Y=K(function(e){e.innerHTML="";var t=typeof e.lastChild.getAttribute("multiple");return t!=="boolean"&&t!=="string"}),Z=K(function(e){return e.innerHTML="",!e.getElementsByClassName||!e.getElementsByClassName("e").length?!1:(e.lastChild.className="e",e.getElementsByClassName("e").length===2)}),et=K(function(e){e.id=d+0,e.innerHTML="
",y.insertBefore(e,y.firstChild);var t=g.getElementsByName&&g.getElementsByName(d).length===2+g.getElementsByName(d+0).length;return r=!g.getElementById(d),y.removeChild(e),t});try{x.call(y.childNodes,0)[0].nodeType}catch(tt){x=function(e){var t,n=[];for(;t=this[e];e++)n.push(t);return n}}nt.matches=function(e,t){return nt(e,null,null,t)},nt.matchesSelector=function(e,t){return nt(t,null,null,[e]).length>0},s=nt.getText=function(e){var t,n="",r=0,i=e.nodeType;if(i){if(i===1||i===9||i===11){if(typeof e.textContent=="string")return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=s(e)}else if(i===3||i===4)return e.nodeValue}else for(;t=e[r];r++)n+=s(t);return n},o=nt.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return t?t.nodeName!=="HTML":!1},u=nt.contains=y.contains?function(e,t){var n=e.nodeType===9?e.documentElement:e,r=t&&t.parentNode;return e===r||!!(r&&r.nodeType===1&&n.contains&&n.contains(r))}:y.compareDocumentPosition?function(e,t){return t&&!!(e.compareDocumentPosition(t)&16)}:function(e,t){while(t=t.parentNode)if(t===e)return!0;return!1},nt.attr=function(e,t){var n,r=o(e);return r||(t=t.toLowerCase()),(n=i.attrHandle[t])?n(e):r||Y?e.getAttribute(t):(n=e.getAttributeNode(t),n?typeof e[t]=="boolean"?e[t]?t:null:n.specified?n.value:null:null)},i=nt.selectors={cacheLength:50,createPseudo:N,match:J,attrHandle:G?{}:{href:function(e){return e.getAttribute("href",2)},type:function(e){return e.getAttribute("type")}},find:{ID:r?function(e,t,n){if(typeof t.getElementById!==p&&!n){var r=t.getElementById(e);return r&&r.parentNode?[r]:[]}}:function(e,n,r){if(typeof n.getElementById!==p&&!r){var i=n.getElementById(e);return i?i.id===e||typeof i.getAttributeNode!==p&&i.getAttributeNode("id").value===e?[i]:t:[]}},TAG:Q?function(e,t){if(typeof t.getElementsByTagName!==p)return t.getElementsByTagName(e)}:function(e,t){var n=t.getElementsByTagName(e);if(e==="*"){var r,i=[],s=0;for(;r=n[s];s++)r.nodeType===1&&i.push(r);return i}return n},NAME:et&&function(e,t){if(typeof t.getElementsByName!==p)return t.getElementsByName(name)},CLASS:Z&&function(e,t,n){if(typeof t.getElementsByClassName!==p&&!n)return t.getElementsByClassName(e)}},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace($,""),e[3]=(e[4]||e[5]||"").replace($,""),e[2]==="~="&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),e[1]==="nth"?(e[2]||nt.error(e[0]),e[3]=+(e[3]?e[4]+(e[5]||1):2*(e[2]==="even"||e[2]==="odd")),e[4]=+(e[6]+e[7]||e[2]==="odd")):e[2]&&nt.error(e[0]),e},PSEUDO:function(e){var t,n;if(J.CHILD.test(e[0]))return null;if(e[3])e[2]=e[3];else if(t=e[4])q.test(t)&&(n=ut(t,!0))&&(n=t.indexOf(")",t.length-n)-t.length)&&(t=t.slice(0,n),e[0]=e[0].slice(0,n)),e[2]=t;return e.slice(0,3)}},filter:{ID:r?function(e){return e=e.replace($,""),function(t){return t.getAttribute("id")===e}}:function(e){return e=e.replace($,""),function(t){var n=typeof t.getAttributeNode!==p&&t.getAttributeNode("id");return n&&n.value===e}},TAG:function(e){return e==="*"?function(){return!0}:(e=e.replace($,"").toLowerCase(),function(t){return t.nodeName&&t.nodeName.toLowerCase()===e})},CLASS:function(e){var t=k[d][e+" "];return t||(t=new RegExp("(^|"+O+")"+e+"("+O+"|$)"))&&k(e,function(e){return t.test(e.className||typeof e.getAttribute!==p&&e.getAttribute("class")||"")})},ATTR:function(e,t,n){return function(r,i){var s=nt.attr(r,e);return s==null?t==="!=":t?(s+="",t==="="?s===n:t==="!="?s!==n:t==="^="?n&&s.indexOf(n)===0:t==="*="?n&&s.indexOf(n)>-1:t==="$="?n&&s.substr(s.length-n.length)===n:t==="~="?(" "+s+" ").indexOf(n)>-1:t==="|="?s===n||s.substr(0,n.length+1)===n+"-":!1):!0}},CHILD:function(e,t,n,r){return e==="nth"?function(e){var t,i,s=e.parentNode;if(n===1&&r===0)return!0;if(s){i=0;for(t=s.firstChild;t;t=t.nextSibling)if(t.nodeType===1){i++;if(e===t)break}}return i-=r,i===n||i%n===0&&i/n>=0}:function(t){var n=t;switch(e){case"only":case"first":while(n=n.previousSibling)if(n.nodeType===1)return!1;if(e==="first")return!0;n=t;case"last":while(n=n.nextSibling)if(n.nodeType===1)return!1;return!0}}},PSEUDO:function(e,t){var n,r=i.pseudos[e]||i.setFilters[e.toLowerCase()]||nt.error("unsupported pseudo: "+e);return r[d]?r(t):r.length>1?(n=[e,e,"",t],i.setFilters.hasOwnProperty(e.toLowerCase())?N(function(e,n){var i,s=r(e,t),o=s.length;while(o--)i=T.call(e,s[o]),e[i]=!(n[i]=s[o])}):function(e){return r(e,0,n)}):r}},pseudos:{not:N(function(e){var t=[],n=[],r=a(e.replace(j,"$1"));return r[d]?N(function(e,t,n,i){var s,o=r(e,null,i,[]),u=e.length;while(u--)if(s=o[u])e[u]=!(t[u]=s)}):function(e,i,s){return t[0]=e,r(t,null,s,n),!n.pop()}}),has:N(function(e){return function(t){return nt(e,t).length>0}}),contains:N(function(e){return function(t){return(t.textContent||t.innerText||s(t)).indexOf(e)>-1}}),enabled:function(e){return e.disabled===!1},disabled:function(e){return e.disabled===!0},checked:function(e){var t=e.nodeName.toLowerCase();return t==="input"&&!!e.checked||t==="option"&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,e.selected===!0},parent:function(e){return!i.pseudos.empty(e)},empty:function(e){var t;e=e.firstChild;while(e){if(e.nodeName>"@"||(t=e.nodeType)===3||t===4)return!1;e=e.nextSibling}return!0},header:function(e){return X.test(e.nodeName)},text:function(e){var t,n;return e.nodeName.toLowerCase()==="input"&&(t=e.type)==="text"&&((n=e.getAttribute("type"))==null||n.toLowerCase()===t)},radio:rt("radio"),checkbox:rt("checkbox"),file:rt("file"),password:rt("password"),image:rt("image"),submit:it("submit"),reset:it("reset"),button:function(e){var t=e.nodeName.toLowerCase();return t==="input"&&e.type==="button"||t==="button"},input:function(e){return V.test(e.nodeName)},focus:function(e){var t=e.ownerDocument;return e===t.activeElement&&(!t.hasFocus||t.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},active:function(e){return e===e.ownerDocument.activeElement},first:st(function(){return[0]}),last:st(function(e,t){return[t-1]}),eq:st(function(e,t,n){return[n<0?n+t:n]}),even:st(function(e,t){for(var n=0;n=0;)e.push(r);return e}),gt:st(function(e,t,n){for(var r=n<0?n+t:n;++r",e.querySelectorAll("[selected]").length||i.push("\\["+O+"*(?:checked|disabled|ismap|multiple|readonly|selected|value)"),e.querySelectorAll(":checked").length||i.push(":checked")}),K(function(e){e.innerHTML="

",e.querySelectorAll("[test^='']").length&&i.push("[*^$]="+O+"*(?:\"\"|'')"),e.innerHTML="",e.querySelectorAll(":enabled").length||i.push(":enabled",":disabled")}),i=new RegExp(i.join("|")),vt=function(e,r,s,o,u){if(!o&&!u&&!i.test(e)){var a,f,l=!0,c=d,h=r,p=r.nodeType===9&&e;if(r.nodeType===1&&r.nodeName.toLowerCase()!=="object"){a=ut(e),(l=r.getAttribute("id"))?c=l.replace(n,"\\$&"):r.setAttribute("id",c),c="[id='"+c+"'] ",f=a.length;while(f--)a[f]=c+a[f].join("");h=z.test(e)&&r.parentNode||r,p=a.join(",")}if(p)try{return S.apply(s,x.call(h.querySelectorAll(p),0)),s}catch(v){}finally{l||r.removeAttribute("id")}}return t(e,r,s,o,u)},u&&(K(function(t){e=u.call(t,"div");try{u.call(t,"[test!='']:sizzle"),s.push("!=",H)}catch(n){}}),s=new RegExp(s.join("|")),nt.matchesSelector=function(t,n){n=n.replace(r,"='$1']");if(!o(t)&&!s.test(n)&&!i.test(n))try{var a=u.call(t,n);if(a||e||t.document&&t.document.nodeType!==11)return a}catch(f){}return nt(n,null,null,[t]).length>0})}(),i.pseudos.nth=i.pseudos.eq,i.filters=mt.prototype=i.pseudos,i.setFilters=new mt,nt.attr=v.attr,v.find=nt,v.expr=nt.selectors,v.expr[":"]=v.expr.pseudos,v.unique=nt.uniqueSort,v.text=nt.getText,v.isXMLDoc=nt.isXML,v.contains=nt.contains}(e);var nt=/Until$/,rt=/^(?:parents|prev(?:Until|All))/,it=/^.[^:#\[\.,]*$/,st=v.expr.match.needsContext,ot={children:!0,contents:!0,next:!0,prev:!0};v.fn.extend({find:function(e){var t,n,r,i,s,o,u=this;if(typeof e!="string")return v(e).filter(function(){for(t=0,n=u.length;t0)for(i=r;i=0:v.filter(e,this).length>0:this.filter(e).length>0)},closest:function(e,t){var n,r=0,i=this.length,s=[],o=st.test(e)||typeof e!="string"?v(e,t||this.context):0;for(;r-1:v.find.matchesSelector(n,e)){s.push(n);break}n=n.parentNode}}return s=s.length>1?v.unique(s):s,this.pushStack(s,"closest",e)},index:function(e){return e?typeof e=="string"?v.inArray(this[0],v(e)):v.inArray(e.jquery?e[0]:e,this):this[0]&&this[0].parentNode?this.prevAll().length:-1},add:function(e,t){var n=typeof e=="string"?v(e,t):v.makeArray(e&&e.nodeType?[e]:e),r=v.merge(this.get(),n);return this.pushStack(ut(n[0])||ut(r[0])?r:v.unique(r))},addBack:function(e){return this.add(e==null?this.prevObject:this.prevObject.filter(e))}}),v.fn.andSelf=v.fn.addBack,v.each({parent:function(e){var t=e.parentNode;return t&&t.nodeType!==11?t:null},parents:function(e){return v.dir(e,"parentNode")},parentsUntil:function(e,t,n){return v.dir(e,"parentNode",n)},next:function(e){return at(e,"nextSibling")},prev:function(e){return at(e,"previousSibling")},nextAll:function(e){return v.dir(e,"nextSibling")},prevAll:function(e){return v.dir(e,"previousSibling")},nextUntil:function(e,t,n){return v.dir(e,"nextSibling",n)},prevUntil:function(e,t,n){return v.dir(e,"previousSibling",n)},siblings:function(e){return v.sibling((e.parentNode||{}).firstChild,e)},children:function(e){return v.sibling(e.firstChild)},contents:function(e){return v.nodeName(e,"iframe")?e.contentDocument||e.contentWindow.document:v.merge([],e.childNodes)}},function(e,t){v.fn[e]=function(n,r){var i=v.map(this,t,n);return nt.test(e)||(r=n),r&&typeof r=="string"&&(i=v.filter(r,i)),i=this.length>1&&!ot[e]?v.unique(i):i,this.length>1&&rt.test(e)&&(i=i.reverse()),this.pushStack(i,e,l.call(arguments).join(","))}}),v.extend({filter:function(e,t,n){return n&&(e=":not("+e+")"),t.length===1?v.find.matchesSelector(t[0],e)?[t[0]]:[]:v.find.matches(e,t)},dir:function(e,n,r){var i=[],s=e[n];while(s&&s.nodeType!==9&&(r===t||s.nodeType!==1||!v(s).is(r)))s.nodeType===1&&i.push(s),s=s[n];return i},sibling:function(e,t){var n=[];for(;e;e=e.nextSibling)e.nodeType===1&&e!==t&&n.push(e);return n}});var ct="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",ht=/ jQuery\d+="(?:null|\d+)"/g,pt=/^\s+/,dt=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,vt=/<([\w:]+)/,mt=/]","i"),Et=/^(?:checkbox|radio)$/,St=/checked\s*(?:[^=]|=\s*.checked.)/i,xt=/\/(java|ecma)script/i,Tt=/^\s*\s*$/g,Nt={option:[1,""],legend:[1,"
","
"],thead:[1,"","
"],tr:[2,"","
"],td:[3,"","
"],col:[2,"","
"],area:[1,"",""],_default:[0,"",""]},Ct=lt(i),kt=Ct.appendChild(i.createElement("div"));Nt.optgroup=Nt.option,Nt.tbody=Nt.tfoot=Nt.colgroup=Nt.caption=Nt.thead,Nt.th=Nt.td,v.support.htmlSerialize||(Nt._default=[1,"X
","
"]),v.fn.extend({text:function(e){return v.access(this,function(e){return e===t?v.text(this):this.empty().append((this[0]&&this[0].ownerDocument||i).createTextNode(e))},null,e,arguments.length)},wrapAll:function(e){if(v.isFunction(e))return this.each(function(t){v(this).wrapAll(e.call(this,t))});if(this[0]){var t=v(e,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&t.insertBefore(this[0]),t.map(function(){var e=this;while(e.firstChild&&e.firstChild.nodeType===1)e=e.firstChild;return e}).append(this)}return this},wrapInner:function(e){return v.isFunction(e)?this.each(function(t){v(this).wrapInner(e.call(this,t))}):this.each(function(){var t=v(this),n=t.contents();n.length?n.wrapAll(e):t.append(e)})},wrap:function(e){var t=v.isFunction(e);return this.each(function(n){v(this).wrapAll(t?e.call(this,n):e)})},unwrap:function(){return this.parent().each(function(){v.nodeName(this,"body")||v(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(e){(this.nodeType===1||this.nodeType===11)&&this.appendChild(e)})},prepend:function(){return this.domManip(arguments,!0,function(e){(this.nodeType===1||this.nodeType===11)&&this.insertBefore(e,this.firstChild)})},before:function(){if(!ut(this[0]))return this.domManip(arguments,!1,function(e){this.parentNode.insertBefore(e,this)});if(arguments.length){var e=v.clean(arguments);return this.pushStack(v.merge(e,this),"before",this.selector)}},after:function(){if(!ut(this[0]))return this.domManip(arguments,!1,function(e){this.parentNode.insertBefore(e,this.nextSibling)});if(arguments.length){var e=v.clean(arguments);return this.pushStack(v.merge(this,e),"after",this.selector)}},remove:function(e,t){var n,r=0;for(;(n=this[r])!=null;r++)if(!e||v.filter(e,[n]).length)!t&&n.nodeType===1&&(v.cleanData(n.getElementsByTagName("*")),v.cleanData([n])),n.parentNode&&n.parentNode.removeChild(n);return this},empty:function(){var e,t=0;for(;(e=this[t])!=null;t++){e.nodeType===1&&v.cleanData(e.getElementsByTagName("*"));while(e.firstChild)e.removeChild(e.firstChild)}return this},clone:function(e,t){return e=e==null?!1:e,t=t==null?e:t,this.map(function(){return v.clone(this,e,t)})},html:function(e){return v.access(this,function(e){var n=this[0]||{},r=0,i=this.length;if(e===t)return n.nodeType===1?n.innerHTML.replace(ht,""):t;if(typeof e=="string"&&!yt.test(e)&&(v.support.htmlSerialize||!wt.test(e))&&(v.support.leadingWhitespace||!pt.test(e))&&!Nt[(vt.exec(e)||["",""])[1].toLowerCase()]){e=e.replace(dt,"<$1>");try{for(;r1&&typeof f=="string"&&St.test(f))return this.each(function(){v(this).domManip(e,n,r)});if(v.isFunction(f))return this.each(function(i){var s=v(this);e[0]=f.call(this,i,n?s.html():t),s.domManip(e,n,r)});if(this[0]){i=v.buildFragment(e,this,l),o=i.fragment,s=o.firstChild,o.childNodes.length===1&&(o=s);if(s){n=n&&v.nodeName(s,"tr");for(u=i.cacheable||c-1;a0?this.clone(!0):this).get(),v(o[i])[t](r),s=s.concat(r);return this.pushStack(s,e,o.selector)}}),v.extend({clone:function(e,t,n){var r,i,s,o;v.support.html5Clone||v.isXMLDoc(e)||!wt.test("<"+e.nodeName+">")?o=e.cloneNode(!0):(kt.innerHTML=e.outerHTML,kt.removeChild(o=kt.firstChild));if((!v.support.noCloneEvent||!v.support.noCloneChecked)&&(e.nodeType===1||e.nodeType===11)&&!v.isXMLDoc(e)){Ot(e,o),r=Mt(e),i=Mt(o);for(s=0;r[s];++s)i[s]&&Ot(r[s],i[s])}if(t){At(e,o);if(n){r=Mt(e),i=Mt(o);for(s=0;r[s];++s)At(r[s],i[s])}}return r=i=null,o},clean:function(e,t,n,r){var s,o,u,a,f,l,c,h,p,d,m,g,y=t===i&&Ct,b=[];if(!t||typeof t.createDocumentFragment=="undefined")t=i;for(s=0;(u=e[s])!=null;s++){typeof u=="number"&&(u+="");if(!u)continue;if(typeof u=="string")if(!gt.test(u))u=t.createTextNode(u);else{y=y||lt(t),c=t.createElement("div"),y.appendChild(c),u=u.replace(dt,"<$1>"),a=(vt.exec(u)||["",""])[1].toLowerCase(),f=Nt[a]||Nt._default,l=f[0],c.innerHTML=f[1]+u+f[2];while(l--)c=c.lastChild;if(!v.support.tbody){h=mt.test(u),p=a==="table"&&!h?c.firstChild&&c.firstChild.childNodes:f[1]===""&&!h?c.childNodes:[];for(o=p.length-1;o>=0;--o)v.nodeName(p[o],"tbody")&&!p[o].childNodes.length&&p[o].parentNode.removeChild(p[o])}!v.support.leadingWhitespace&&pt.test(u)&&c.insertBefore(t.createTextNode(pt.exec(u)[0]),c.firstChild),u=c.childNodes,c.parentNode.removeChild(c)}u.nodeType?b.push(u):v.merge(b,u)}c&&(u=c=y=null);if(!v.support.appendChecked)for(s=0;(u=b[s])!=null;s++)v.nodeName(u,"input")?_t(u):typeof u.getElementsByTagName!="undefined"&&v.grep(u.getElementsByTagName("input"),_t);if(n){m=function(e){if(!e.type||xt.test(e.type))return r?r.push(e.parentNode?e.parentNode.removeChild(e):e):n.appendChild(e)};for(s=0;(u=b[s])!=null;s++)if(!v.nodeName(u,"script")||!m(u))n.appendChild(u),typeof u.getElementsByTagName!="undefined"&&(g=v.grep(v.merge([],u.getElementsByTagName("script")),m),b.splice.apply(b,[s+1,0].concat(g)),s+=g.length)}return b},cleanData:function(e,t){var n,r,i,s,o=0,u=v.expando,a=v.cache,f=v.support.deleteExpando,l=v.event.special;for(;(i=e[o])!=null;o++)if(t||v.acceptData(i)){r=i[u],n=r&&a[r];if(n){if(n.events)for(s in n.events)l[s]?v.event.remove(i,s):v.removeEvent(i,s,n.handle);a[r]&&(delete a[r],f?delete i[u]:i.removeAttribute?i.removeAttribute(u):i[u]=null,v.deletedIds.push(r))}}}}),function(){var e,t;v.uaMatch=function(e){e=e.toLowerCase();var t=/(chrome)[ \/]([\w.]+)/.exec(e)||/(webkit)[ \/]([\w.]+)/.exec(e)||/(opera)(?:.*version|)[ \/]([\w.]+)/.exec(e)||/(msie) ([\w.]+)/.exec(e)||e.indexOf("compatible")<0&&/(mozilla)(?:.*? rv:([\w.]+)|)/.exec(e)||[];return{browser:t[1]||"",version:t[2]||"0"}},e=v.uaMatch(o.userAgent),t={},e.browser&&(t[e.browser]=!0,t.version=e.version),t.chrome?t.webkit=!0:t.webkit&&(t.safari=!0),v.browser=t,v.sub=function(){function e(t,n){return new e.fn.init(t,n)}v.extend(!0,e,this),e.superclass=this,e.fn=e.prototype=this(),e.fn.constructor=e,e.sub=this.sub,e.fn.init=function(r,i){return i&&i instanceof v&&!(i instanceof e)&&(i=e(i)),v.fn.init.call(this,r,i,t)},e.fn.init.prototype=e.fn;var t=e(i);return e}}();var Dt,Pt,Ht,Bt=/alpha\([^)]*\)/i,jt=/opacity=([^)]*)/,Ft=/^(top|right|bottom|left)$/,It=/^(none|table(?!-c[ea]).+)/,qt=/^margin/,Rt=new RegExp("^("+m+")(.*)$","i"),Ut=new RegExp("^("+m+")(?!px)[a-z%]+$","i"),zt=new RegExp("^([-+])=("+m+")","i"),Wt={BODY:"block"},Xt={position:"absolute",visibility:"hidden",display:"block"},Vt={letterSpacing:0,fontWeight:400},$t=["Top","Right","Bottom","Left"],Jt=["Webkit","O","Moz","ms"],Kt=v.fn.toggle;v.fn.extend({css:function(e,n){return v.access(this,function(e,n,r){return r!==t?v.style(e,n,r):v.css(e,n)},e,n,arguments.length>1)},show:function(){return Yt(this,!0)},hide:function(){return Yt(this)},toggle:function(e,t){var n=typeof e=="boolean";return v.isFunction(e)&&v.isFunction(t)?Kt.apply(this,arguments):this.each(function(){(n?e:Gt(this))?v(this).show():v(this).hide()})}}),v.extend({cssHooks:{opacity:{get:function(e,t){if(t){var n=Dt(e,"opacity");return n===""?"1":n}}}},cssNumber:{fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":v.support.cssFloat?"cssFloat":"styleFloat"},style:function(e,n,r,i){if(!e||e.nodeType===3||e.nodeType===8||!e.style)return;var s,o,u,a=v.camelCase(n),f=e.style;n=v.cssProps[a]||(v.cssProps[a]=Qt(f,a)),u=v.cssHooks[n]||v.cssHooks[a];if(r===t)return u&&"get"in u&&(s=u.get(e,!1,i))!==t?s:f[n];o=typeof r,o==="string"&&(s=zt.exec(r))&&(r=(s[1]+1)*s[2]+parseFloat(v.css(e,n)),o="number");if(r==null||o==="number"&&isNaN(r))return;o==="number"&&!v.cssNumber[a]&&(r+="px");if(!u||!("set"in u)||(r=u.set(e,r,i))!==t)try{f[n]=r}catch(l){}},css:function(e,n,r,i){var s,o,u,a=v.camelCase(n);return n=v.cssProps[a]||(v.cssProps[a]=Qt(e.style,a)),u=v.cssHooks[n]||v.cssHooks[a],u&&"get"in u&&(s=u.get(e,!0,i)),s===t&&(s=Dt(e,n)),s==="normal"&&n in Vt&&(s=Vt[n]),r||i!==t?(o=parseFloat(s),r||v.isNumeric(o)?o||0:s):s},swap:function(e,t,n){var r,i,s={};for(i in t)s[i]=e.style[i],e.style[i]=t[i];r=n.call(e);for(i in t)e.style[i]=s[i];return r}}),e.getComputedStyle?Dt=function(t,n){var r,i,s,o,u=e.getComputedStyle(t,null),a=t.style;return u&&(r=u.getPropertyValue(n)||u[n],r===""&&!v.contains(t.ownerDocument,t)&&(r=v.style(t,n)),Ut.test(r)&&qt.test(n)&&(i=a.width,s=a.minWidth,o=a.maxWidth,a.minWidth=a.maxWidth=a.width=r,r=u.width,a.width=i,a.minWidth=s,a.maxWidth=o)),r}:i.documentElement.currentStyle&&(Dt=function(e,t){var n,r,i=e.currentStyle&&e.currentStyle[t],s=e.style;return i==null&&s&&s[t]&&(i=s[t]),Ut.test(i)&&!Ft.test(t)&&(n=s.left,r=e.runtimeStyle&&e.runtimeStyle.left,r&&(e.runtimeStyle.left=e.currentStyle.left),s.left=t==="fontSize"?"1em":i,i=s.pixelLeft+"px",s.left=n,r&&(e.runtimeStyle.left=r)),i===""?"auto":i}),v.each(["height","width"],function(e,t){v.cssHooks[t]={get:function(e,n,r){if(n)return e.offsetWidth===0&&It.test(Dt(e,"display"))?v.swap(e,Xt,function(){return tn(e,t,r)}):tn(e,t,r)},set:function(e,n,r){return Zt(e,n,r?en(e,t,r,v.support.boxSizing&&v.css(e,"boxSizing")==="border-box"):0)}}}),v.support.opacity||(v.cssHooks.opacity={get:function(e,t){return jt.test((t&&e.currentStyle?e.currentStyle.filter:e.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":t?"1":""},set:function(e,t){var n=e.style,r=e.currentStyle,i=v.isNumeric(t)?"alpha(opacity="+t*100+")":"",s=r&&r.filter||n.filter||"";n.zoom=1;if(t>=1&&v.trim(s.replace(Bt,""))===""&&n.removeAttribute){n.removeAttribute("filter");if(r&&!r.filter)return}n.filter=Bt.test(s)?s.replace(Bt,i):s+" "+i}}),v(function(){v.support.reliableMarginRight||(v.cssHooks.marginRight={get:function(e,t){return v.swap(e,{display:"inline-block"},function(){if(t)return Dt(e,"marginRight")})}}),!v.support.pixelPosition&&v.fn.position&&v.each(["top","left"],function(e,t){v.cssHooks[t]={get:function(e,n){if(n){var r=Dt(e,t);return Ut.test(r)?v(e).position()[t]+"px":r}}}})}),v.expr&&v.expr.filters&&(v.expr.filters.hidden=function(e){return e.offsetWidth===0&&e.offsetHeight===0||!v.support.reliableHiddenOffsets&&(e.style&&e.style.display||Dt(e,"display"))==="none"},v.expr.filters.visible=function(e){return!v.expr.filters.hidden(e)}),v.each({margin:"",padding:"",border:"Width"},function(e,t){v.cssHooks[e+t]={expand:function(n){var r,i=typeof n=="string"?n.split(" "):[n],s={};for(r=0;r<4;r++)s[e+$t[r]+t]=i[r]||i[r-2]||i[0];return s}},qt.test(e)||(v.cssHooks[e+t].set=Zt)});var rn=/%20/g,sn=/\[\]$/,on=/\r?\n/g,un=/^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,an=/^(?:select|textarea)/i;v.fn.extend({serialize:function(){return v.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?v.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||an.test(this.nodeName)||un.test(this.type))}).map(function(e,t){var n=v(this).val();return n==null?null:v.isArray(n)?v.map(n,function(e,n){return{name:t.name,value:e.replace(on,"\r\n")}}):{name:t.name,value:n.replace(on,"\r\n")}}).get()}}),v.param=function(e,n){var r,i=[],s=function(e,t){t=v.isFunction(t)?t():t==null?"":t,i[i.length]=encodeURIComponent(e)+"="+encodeURIComponent(t)};n===t&&(n=v.ajaxSettings&&v.ajaxSettings.traditional);if(v.isArray(e)||e.jquery&&!v.isPlainObject(e))v.each(e,function(){s(this.name,this.value)});else for(r in e)fn(r,e[r],n,s);return i.join("&").replace(rn,"+")};var ln,cn,hn=/#.*$/,pn=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,dn=/^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,vn=/^(?:GET|HEAD)$/,mn=/^\/\//,gn=/\?/,yn=/)<[^<]*)*<\/script>/gi,bn=/([?&])_=[^&]*/,wn=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,En=v.fn.load,Sn={},xn={},Tn=["*/"]+["*"];try{cn=s.href}catch(Nn){cn=i.createElement("a"),cn.href="",cn=cn.href}ln=wn.exec(cn.toLowerCase())||[],v.fn.load=function(e,n,r){if(typeof e!="string"&&En)return En.apply(this,arguments);if(!this.length)return this;var i,s,o,u=this,a=e.indexOf(" ");return a>=0&&(i=e.slice(a,e.length),e=e.slice(0,a)),v.isFunction(n)?(r=n,n=t):n&&typeof n=="object"&&(s="POST"),v.ajax({url:e,type:s,dataType:"html",data:n,complete:function(e,t){r&&u.each(r,o||[e.responseText,t,e])}}).done(function(e){o=arguments,u.html(i?v("
").append(e.replace(yn,"")).find(i):e)}),this},v.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(e,t){v.fn[t]=function(e){return this.on(t,e)}}),v.each(["get","post"],function(e,n){v[n]=function(e,r,i,s){return v.isFunction(r)&&(s=s||i,i=r,r=t),v.ajax({type:n,url:e,data:r,success:i,dataType:s})}}),v.extend({getScript:function(e,n){return v.get(e,t,n,"script")},getJSON:function(e,t,n){return v.get(e,t,n,"json")},ajaxSetup:function(e,t){return t?Ln(e,v.ajaxSettings):(t=e,e=v.ajaxSettings),Ln(e,t),e},ajaxSettings:{url:cn,isLocal:dn.test(ln[1]),global:!0,type:"GET",contentType:"application/x-www-form-urlencoded; charset=UTF-8",processData:!0,async:!0,accepts:{xml:"application/xml, text/xml",html:"text/html",text:"text/plain",json:"application/json, text/javascript","*":Tn},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":e.String,"text html":!0,"text json":v.parseJSON,"text xml":v.parseXML},flatOptions:{context:!0,url:!0}},ajaxPrefilter:Cn(Sn),ajaxTransport:Cn(xn),ajax:function(e,n){function T(e,n,s,a){var l,y,b,w,S,T=n;if(E===2)return;E=2,u&&clearTimeout(u),o=t,i=a||"",x.readyState=e>0?4:0,s&&(w=An(c,x,s));if(e>=200&&e<300||e===304)c.ifModified&&(S=x.getResponseHeader("Last-Modified"),S&&(v.lastModified[r]=S),S=x.getResponseHeader("Etag"),S&&(v.etag[r]=S)),e===304?(T="notmodified",l=!0):(l=On(c,w),T=l.state,y=l.data,b=l.error,l=!b);else{b=T;if(!T||e)T="error",e<0&&(e=0)}x.status=e,x.statusText=(n||T)+"",l?d.resolveWith(h,[y,T,x]):d.rejectWith(h,[x,T,b]),x.statusCode(g),g=t,f&&p.trigger("ajax"+(l?"Success":"Error"),[x,c,l?y:b]),m.fireWith(h,[x,T]),f&&(p.trigger("ajaxComplete",[x,c]),--v.active||v.event.trigger("ajaxStop"))}typeof e=="object"&&(n=e,e=t),n=n||{};var r,i,s,o,u,a,f,l,c=v.ajaxSetup({},n),h=c.context||c,p=h!==c&&(h.nodeType||h instanceof v)?v(h):v.event,d=v.Deferred(),m=v.Callbacks("once memory"),g=c.statusCode||{},b={},w={},E=0,S="canceled",x={readyState:0,setRequestHeader:function(e,t){if(!E){var n=e.toLowerCase();e=w[n]=w[n]||e,b[e]=t}return this},getAllResponseHeaders:function(){return E===2?i:null},getResponseHeader:function(e){var n;if(E===2){if(!s){s={};while(n=pn.exec(i))s[n[1].toLowerCase()]=n[2]}n=s[e.toLowerCase()]}return n===t?null:n},overrideMimeType:function(e){return E||(c.mimeType=e),this},abort:function(e){return e=e||S,o&&o.abort(e),T(0,e),this}};d.promise(x),x.success=x.done,x.error=x.fail,x.complete=m.add,x.statusCode=function(e){if(e){var t;if(E<2)for(t in e)g[t]=[g[t],e[t]];else t=e[x.status],x.always(t)}return this},c.url=((e||c.url)+"").replace(hn,"").replace(mn,ln[1]+"//"),c.dataTypes=v.trim(c.dataType||"*").toLowerCase().split(y),c.crossDomain==null&&(a=wn.exec(c.url.toLowerCase()),c.crossDomain=!(!a||a[1]===ln[1]&&a[2]===ln[2]&&(a[3]||(a[1]==="http:"?80:443))==(ln[3]||(ln[1]==="http:"?80:443)))),c.data&&c.processData&&typeof c.data!="string"&&(c.data=v.param(c.data,c.traditional)),kn(Sn,c,n,x);if(E===2)return x;f=c.global,c.type=c.type.toUpperCase(),c.hasContent=!vn.test(c.type),f&&v.active++===0&&v.event.trigger("ajaxStart");if(!c.hasContent){c.data&&(c.url+=(gn.test(c.url)?"&":"?")+c.data,delete c.data),r=c.url;if(c.cache===!1){var N=v.now(),C=c.url.replace(bn,"$1_="+N);c.url=C+(C===c.url?(gn.test(c.url)?"&":"?")+"_="+N:"")}}(c.data&&c.hasContent&&c.contentType!==!1||n.contentType)&&x.setRequestHeader("Content-Type",c.contentType),c.ifModified&&(r=r||c.url,v.lastModified[r]&&x.setRequestHeader("If-Modified-Since",v.lastModified[r]),v.etag[r]&&x.setRequestHeader("If-None-Match",v.etag[r])),x.setRequestHeader("Accept",c.dataTypes[0]&&c.accepts[c.dataTypes[0]]?c.accepts[c.dataTypes[0]]+(c.dataTypes[0]!=="*"?", "+Tn+"; q=0.01":""):c.accepts["*"]);for(l in c.headers)x.setRequestHeader(l,c.headers[l]);if(!c.beforeSend||c.beforeSend.call(h,x,c)!==!1&&E!==2){S="abort";for(l in{success:1,error:1,complete:1})x[l](c[l]);o=kn(xn,c,n,x);if(!o)T(-1,"No Transport");else{x.readyState=1,f&&p.trigger("ajaxSend",[x,c]),c.async&&c.timeout>0&&(u=setTimeout(function(){x.abort("timeout")},c.timeout));try{E=1,o.send(b,T)}catch(k){if(!(E<2))throw k;T(-1,k)}}return x}return x.abort()},active:0,lastModified:{},etag:{}});var Mn=[],_n=/\?/,Dn=/(=)\?(?=&|$)|\?\?/,Pn=v.now();v.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=Mn.pop()||v.expando+"_"+Pn++;return this[e]=!0,e}}),v.ajaxPrefilter("json jsonp",function(n,r,i){var s,o,u,a=n.data,f=n.url,l=n.jsonp!==!1,c=l&&Dn.test(f),h=l&&!c&&typeof a=="string"&&!(n.contentType||"").indexOf("application/x-www-form-urlencoded")&&Dn.test(a);if(n.dataTypes[0]==="jsonp"||c||h)return s=n.jsonpCallback=v.isFunction(n.jsonpCallback)?n.jsonpCallback():n.jsonpCallback,o=e[s],c?n.url=f.replace(Dn,"$1"+s):h?n.data=a.replace(Dn,"$1"+s):l&&(n.url+=(_n.test(f)?"&":"?")+n.jsonp+"="+s),n.converters["script json"]=function(){return u||v.error(s+" was not called"),u[0]},n.dataTypes[0]="json",e[s]=function(){u=arguments},i.always(function(){e[s]=o,n[s]&&(n.jsonpCallback=r.jsonpCallback,Mn.push(s)),u&&v.isFunction(o)&&o(u[0]),u=o=t}),"script"}),v.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/javascript|ecmascript/},converters:{"text script":function(e){return v.globalEval(e),e}}}),v.ajaxPrefilter("script",function(e){e.cache===t&&(e.cache=!1),e.crossDomain&&(e.type="GET",e.global=!1)}),v.ajaxTransport("script",function(e){if(e.crossDomain){var n,r=i.head||i.getElementsByTagName("head")[0]||i.documentElement;return{send:function(s,o){n=i.createElement("script"),n.async="async",e.scriptCharset&&(n.charset=e.scriptCharset),n.src=e.url,n.onload=n.onreadystatechange=function(e,i){if(i||!n.readyState||/loaded|complete/.test(n.readyState))n.onload=n.onreadystatechange=null,r&&n.parentNode&&r.removeChild(n),n=t,i||o(200,"success")},r.insertBefore(n,r.firstChild)},abort:function(){n&&n.onload(0,1)}}}});var Hn,Bn=e.ActiveXObject?function(){for(var e in Hn)Hn[e](0,1)}:!1,jn=0;v.ajaxSettings.xhr=e.ActiveXObject?function(){return!this.isLocal&&Fn()||In()}:Fn,function(e){v.extend(v.support,{ajax:!!e,cors:!!e&&"withCredentials"in e})}(v.ajaxSettings.xhr()),v.support.ajax&&v.ajaxTransport(function(n){if(!n.crossDomain||v.support.cors){var r;return{send:function(i,s){var o,u,a=n.xhr();n.username?a.open(n.type,n.url,n.async,n.username,n.password):a.open(n.type,n.url,n.async);if(n.xhrFields)for(u in n.xhrFields)a[u]=n.xhrFields[u];n.mimeType&&a.overrideMimeType&&a.overrideMimeType(n.mimeType),!n.crossDomain&&!i["X-Requested-With"]&&(i["X-Requested-With"]="XMLHttpRequest");try{for(u in i)a.setRequestHeader(u,i[u])}catch(f){}a.send(n.hasContent&&n.data||null),r=function(e,i){var u,f,l,c,h;try{if(r&&(i||a.readyState===4)){r=t,o&&(a.onreadystatechange=v.noop,Bn&&delete Hn[o]);if(i)a.readyState!==4&&a.abort();else{u=a.status,l=a.getAllResponseHeaders(),c={},h=a.responseXML,h&&h.documentElement&&(c.xml=h);try{c.text=a.responseText}catch(p){}try{f=a.statusText}catch(p){f=""}!u&&n.isLocal&&!n.crossDomain?u=c.text?200:404:u===1223&&(u=204)}}}catch(d){i||s(-1,d)}c&&s(u,f,c,l)},n.async?a.readyState===4?setTimeout(r,0):(o=++jn,Bn&&(Hn||(Hn={},v(e).unload(Bn)),Hn[o]=r),a.onreadystatechange=r):r()},abort:function(){r&&r(0,1)}}}});var qn,Rn,Un=/^(?:toggle|show|hide)$/,zn=new RegExp("^(?:([-+])=|)("+m+")([a-z%]*)$","i"),Wn=/queueHooks$/,Xn=[Gn],Vn={"*":[function(e,t){var n,r,i=this.createTween(e,t),s=zn.exec(t),o=i.cur(),u=+o||0,a=1,f=20;if(s){n=+s[2],r=s[3]||(v.cssNumber[e]?"":"px");if(r!=="px"&&u){u=v.css(i.elem,e,!0)||n||1;do a=a||".5",u/=a,v.style(i.elem,e,u+r);while(a!==(a=i.cur()/o)&&a!==1&&--f)}i.unit=r,i.start=u,i.end=s[1]?u+(s[1]+1)*n:n}return i}]};v.Animation=v.extend(Kn,{tweener:function(e,t){v.isFunction(e)?(t=e,e=["*"]):e=e.split(" ");var n,r=0,i=e.length;for(;r-1,f={},l={},c,h;a?(l=i.position(),c=l.top,h=l.left):(c=parseFloat(o)||0,h=parseFloat(u)||0),v.isFunction(t)&&(t=t.call(e,n,s)),t.top!=null&&(f.top=t.top-s.top+c),t.left!=null&&(f.left=t.left-s.left+h),"using"in t?t.using.call(e,f):i.css(f)}},v.fn.extend({position:function(){if(!this[0])return;var e=this[0],t=this.offsetParent(),n=this.offset(),r=er.test(t[0].nodeName)?{top:0,left:0}:t.offset();return n.top-=parseFloat(v.css(e,"marginTop"))||0,n.left-=parseFloat(v.css(e,"marginLeft"))||0,r.top+=parseFloat(v.css(t[0],"borderTopWidth"))||0,r.left+=parseFloat(v.css(t[0],"borderLeftWidth"))||0,{top:n.top-r.top,left:n.left-r.left}},offsetParent:function(){return this.map(function(){var e=this.offsetParent||i.body;while(e&&!er.test(e.nodeName)&&v.css(e,"position")==="static")e=e.offsetParent;return e||i.body})}}),v.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(e,n){var r=/Y/.test(n);v.fn[e]=function(i){return v.access(this,function(e,i,s){var o=tr(e);if(s===t)return o?n in o?o[n]:o.document.documentElement[i]:e[i];o?o.scrollTo(r?v(o).scrollLeft():s,r?s:v(o).scrollTop()):e[i]=s},e,i,arguments.length,null)}}),v.each({Height:"height",Width:"width"},function(e,n){v.each({padding:"inner"+e,content:n,"":"outer"+e},function(r,i){v.fn[i]=function(i,s){var o=arguments.length&&(r||typeof i!="boolean"),u=r||(i===!0||s===!0?"margin":"border");return v.access(this,function(n,r,i){var s;return v.isWindow(n)?n.document.documentElement["client"+e]:n.nodeType===9?(s=n.documentElement,Math.max(n.body["scroll"+e],s["scroll"+e],n.body["offset"+e],s["offset"+e],s["client"+e])):i===t?v.css(n,r,i,u):v.style(n,r,i,u)},n,o?i:t,o,null)}})}),e.jQuery=e.$=v,typeof define=="function"&&define.amd&&define.amd.jQuery&&define("jquery",[],function(){return v})})(window); \ No newline at end of file diff --git a/Chapter09/04_api_auth_added/static/content/login.js b/Chapter09/04_api_auth_added/static/content/login.js new file mode 100644 index 0000000..fd52f1d --- /dev/null +++ b/Chapter09/04_api_auth_added/static/content/login.js @@ -0,0 +1,30 @@ +$(function(){ + + var tmpl, // Main template HTML + tdata = {}; // JSON data object that feeds the template + + // Initialise page + var initPage = function() { + + // Load the HTML template + $.get("/templates/login.html", function(d){ + tmpl = d; + }); + + // Retrieve the server data and then initialise the page +// $.getJSON("/v1/users/logged_in.json", function (d) { +// $.extend(tdata, d); +// }); + + // When AJAX calls are complete parse the template + // replacing mustache tags with vars + $(document).ajaxStop(function () { +// if (tdata.data.logged_in) +// window.location = "/pages/admin/home"; +// else { + var renderedPage = Mustache.to_html( tmpl, tdata ); + $("body").html( renderedPage ); +// } + }); + }(); +}); diff --git a/Chapter09/04_api_auth_added/static/content/mustache.js b/Chapter09/04_api_auth_added/static/content/mustache.js new file mode 100644 index 0000000..0148d29 --- /dev/null +++ b/Chapter09/04_api_auth_added/static/content/mustache.js @@ -0,0 +1,625 @@ +/*! + * mustache.js - Logic-less {{mustache}} templates with JavaScript + * http://github.com/janl/mustache.js + */ + +/*global define: false*/ + +var Mustache; + +(function (exports) { + if (typeof module !== "undefined" && module.exports) { + module.exports = exports; // CommonJS + } else if (typeof define === "function") { + define(exports); // AMD + } else { + Mustache = exports; // diff --git a/Chapter09/04_api_auth_added/static/templates/admin_add_photos.html b/Chapter09/04_api_auth_added/static/templates/admin_add_photos.html new file mode 100644 index 0000000..d9cbe8d --- /dev/null +++ b/Chapter09/04_api_auth_added/static/templates/admin_add_photos.html @@ -0,0 +1,86 @@ +
+ +
+
Add to Album:
+
+ +
+
Image:
+
+
Description
+
+
+ + + + + +
+ + diff --git a/Chapter09/04_api_auth_added/static/templates/admin_home.html b/Chapter09/04_api_auth_added/static/templates/admin_home.html new file mode 100644 index 0000000..4db4cf1 --- /dev/null +++ b/Chapter09/04_api_auth_added/static/templates/admin_home.html @@ -0,0 +1,7 @@ + +

Admin Operations

+ + diff --git a/Chapter09/04_api_auth_added/static/templates/album.html b/Chapter09/04_api_auth_added/static/templates/album.html new file mode 100644 index 0000000..fbcbda2 --- /dev/null +++ b/Chapter09/04_api_auth_added/static/templates/album.html @@ -0,0 +1,20 @@ + +
+ {{#has_photos}} +

There are {{ has_photos }} photos in this album

+ {{/has_photos}} + {{#photos}} +
+
+
+
+

{{ desc }}

+
+
+ {{/photos}} +
+ {{^photos}} +

This album does't have any photos in it, sorry.

+ {{/photos}} +

diff --git a/Chapter09/04_api_auth_added/static/templates/home.html b/Chapter09/04_api_auth_added/static/templates/home.html new file mode 100644 index 0000000..90ff5fc --- /dev/null +++ b/Chapter09/04_api_auth_added/static/templates/home.html @@ -0,0 +1,17 @@ +
+ Register | + Admin +
+
+

There are {{ albums.length }} albums

+
    + {{#albums}} +
  • + {{name}} +
  • + {{/albums}} + {{^albums}} +
  • Sorry, there are currently no albums
  • + {{/albums}} +
+
diff --git a/Chapter09/04_api_auth_added/static/templates/login.html b/Chapter09/04_api_auth_added/static/templates/login.html new file mode 100644 index 0000000..7bbcc3f --- /dev/null +++ b/Chapter09/04_api_auth_added/static/templates/login.html @@ -0,0 +1,49 @@ + +
+
+
+
Email address:
+
+
Password:
+
+
+
+ + + + diff --git a/Chapter09/04_api_auth_added/static/templates/register.html b/Chapter09/04_api_auth_added/static/templates/register.html new file mode 100644 index 0000000..2934caa --- /dev/null +++ b/Chapter09/04_api_auth_added/static/templates/register.html @@ -0,0 +1,56 @@ + + +
+
+
+
Email address:
+
+
Display Name:
+
+
Password:
+
+
Password (confirm):
+
+
+
+ + + + diff --git a/Chapter09/04_api_auth_added/test.jpg b/Chapter09/04_api_auth_added/test.jpg new file mode 100644 index 0000000..6e4250a Binary files /dev/null and b/Chapter09/04_api_auth_added/test.jpg differ diff --git a/Chapter10/01_simple/01_behaves.js b/Chapter10/01_simple/01_behaves.js new file mode 100644 index 0000000..f08f7b2 --- /dev/null +++ b/Chapter10/01_simple/01_behaves.js @@ -0,0 +1,7 @@ + + +// simulate a request coming in every 5s +setInterval(function () { + console.log("got request"); +}, 2000); + diff --git a/Chapter10/01_simple/02_occasional_crash.js b/Chapter10/01_simple/02_occasional_crash.js new file mode 100644 index 0000000..839afc4 --- /dev/null +++ b/Chapter10/01_simple/02_occasional_crash.js @@ -0,0 +1,9 @@ + +// simulate a request coming in every 5s, 1/10 chance of a crash +// while processing it +setInterval(function () { + console.log("got request"); + if (Math.round(Math.random() * 10) == 0) + throw new Error("SIMULATED CRASH!"); +}, 2000); + diff --git a/Chapter10/01_simple/02_run.bat b/Chapter10/01_simple/02_run.bat new file mode 100644 index 0000000..70a0122 --- /dev/null +++ b/Chapter10/01_simple/02_run.bat @@ -0,0 +1,6 @@ + +: loop +node 02_occasional_crash +goto loop +: end + diff --git a/Chapter10/01_simple/02_run.sh b/Chapter10/01_simple/02_run.sh new file mode 100644 index 0000000..5606bd1 --- /dev/null +++ b/Chapter10/01_simple/02_run.sh @@ -0,0 +1,6 @@ +#!/bin/bash + +while true +do + node 02_occasional_crash.js +done diff --git a/Chapter10/02_ninja/02_memory_hog.js b/Chapter10/02_ninja/02_memory_hog.js new file mode 100644 index 0000000..1b952ad --- /dev/null +++ b/Chapter10/02_ninja/02_memory_hog.js @@ -0,0 +1,13 @@ + + + +var waste_bin = []; + + + +setInterval(function () { + var b = new Buffer(1000000); + b.fill("x"); + waste_bin.push(b); +}, +1000); diff --git a/Chapter10/02_ninja/03_crashy_crashy.js b/Chapter10/02_ninja/03_crashy_crashy.js new file mode 100644 index 0000000..1c40745 --- /dev/null +++ b/Chapter10/02_ninja/03_crashy_crashy.js @@ -0,0 +1,4 @@ + +setTimeout(function () { + throw new Error("Crashy Crashy McCrasherson"); +}, 2000); diff --git a/Chapter10/02_ninja/node_ninja_runner.sh b/Chapter10/02_ninja/node_ninja_runner.sh new file mode 100644 index 0000000..0f3993e --- /dev/null +++ b/Chapter10/02_ninja/node_ninja_runner.sh @@ -0,0 +1,116 @@ +#!/bin/bash + +# +# !!! IMPORTANT !!!! +# MAKE SURE THESE ARE CORRECT FOR YOUR SYSTEM +# +PGREP=/usr/bin/pgrep +AWK=/usr/bin/awk +NODE=/usr/local/bin/node +PS=/bin/ps +PS_FLAGS=wux # some linux use "ps wup" instead -- check!!! +AWK_PROG='{print $6}' # on OS X and many linux, res mem size is $6 in "$PS_FLAGS" +PAUSE_TIME=4 + + + +txtund=$(tput sgr 0 1) # Underline +txtbld=$(tput bold) # Bold +bldred=${txtbld}$(tput setaf 1) # red +bldylw=${txtbld}$(tput setaf 3) # yellow +bldgrn=${txtbld}$(tput setaf 2) # green +txtrst=$(tput sgr0) # Reset +INFO=${bldgrn}INFO:${txtrst} +ERROR=${bldred}ERROR:${txtrst} +WARN=${bldylw}WARNING:${txtrst} + +app_name=`basename $0` + + +function usage () +{ + echo "usage: $app_name max_memory n_crashes n_minutes script.js [...]" + echo " - max_memory in MB" + echo " - permit no more than 'n_crashes' per 'n_minutes'" + exit 1; +} + +function check_progs +{ + if [ ! -f $NODE ]; then echo "$ERROR Missing $NODE, aborting"; exit 1; fi + if [ ! -f $PGREP ]; then echo "$ERROR Missing $PGREP, aborting"; exit 1; fi + if [ ! -f $AWK ]; then echo "$ERROR Missing $AWK, aborting"; exit 1; fi + if [ ! -f $PS ]; then echo "$ERROR Missing $PS, aborting"; exit 1; fi +} + +function already_running +{ + echo "'node $1' already be running. Cowardly refusing to start another." + exit 1 +} + + +check_progs + +if [ $# -lt 4 ]; +then + usage +fi + +# bash only does integer arithmetic, so we'll mult by 100 +# to avoid decimals +RESTART_WEIGHT=0 +MAX_WEIGHT=$(( $3 * 6000 )) +WEIGHT_TIME_CHUNK=$(( (6000 * $3) / $2 )) +FADE_TIME_CHUNK=$(( ($MAX_WEIGHT / $2) / (600 / ($PAUSE_TIME * 10)) )) +#echo $WEIGHT_TIME_CHUNK $MAX_WEIGHT $FADE_TIME_CHUNK + +# first make sure it's not running. +PID=`$PGREP -n -f "$NODE $4"` +if [ "$PID" != "" ]; then + already_running $4 +fi + +# now launch it and start monitoring +echo "$INFO Launching node..." +$NODE $4 $5 $6 $7 $8 $9 $10 $11 $12 $13 $14 & + +while true +do + sleep $PAUSE_TIME + + PID=`$PGREP -n -f "$NODE $4"` + NEED_RESTART=no + if [ "$PID" == "" ]; then + echo + echo "$WARN Node appears to have crashed." + NEED_RESTART=yes + else + # check memory usage + MEM_USAGE=`$PS $PS_FLAGS $PID | $AWK 'NR>1' | $AWK "$AWK_PROG"` + MEM_USAGE=$(( $MEM_USAGE / 1024 )) + if [ $MEM_USAGE -gt $1 ]; + then + echo "$ERROR node has exceed permitted memory of $1 mb, restarting." + kill $PID + NEED_RESTART=yes + fi + fi + RESTART_WEIGHT=$(($RESTART_WEIGHT - $FADE_TIME_CHUNK)) + if [ "$RESTART_WEIGHT" -lt "0" ]; + then + RESTART_WEIGHT=0 + fi + if [ "$NEED_RESTART" == "yes" ]; + then + if [ "$RESTART_WEIGHT" -le "$MAX_WEIGHT" ]; + then + echo "$INFO Restarting..." + $NODE $4 $5 $6 $7 $8 $9 $10 $11 $12 $13 $14 & + RESTART_WEIGHT=$(( $RESTART_WEIGHT + $WEIGHT_TIME_CHUNK )) + else + echo "$ERROR Too many restarts. Aborting." + exit -1 + fi + fi +done diff --git a/Chapter10/02_ninja/test.js b/Chapter10/02_ninja/test.js new file mode 100644 index 0000000..7741f12 --- /dev/null +++ b/Chapter10/02_ninja/test.js @@ -0,0 +1,5 @@ + + +setInterval(function() { console.log("hello"); }, 1000); + + diff --git a/Chapter10/03_roundrobin/package.json b/Chapter10/03_roundrobin/package.json new file mode 100644 index 0000000..9abe672 --- /dev/null +++ b/Chapter10/03_roundrobin/package.json @@ -0,0 +1,9 @@ +{ + "name": "Round-Robin-Demo", + "description": "A little proxy server to round-robin requests", + "version": "0.0.1", + "private": true, + "dependencies": { + "http-proxy": "0.8.x" + } +} diff --git a/Chapter10/03_roundrobin/roundrobin.js b/Chapter10/03_roundrobin/roundrobin.js new file mode 100644 index 0000000..1ea2fc7 --- /dev/null +++ b/Chapter10/03_roundrobin/roundrobin.js @@ -0,0 +1,13 @@ +var httpProxy = require('http-proxy'), + fs = require('fs'); + +var servers = JSON.parse(fs.readFileSync('server_list.json')).servers; + +var s = httpProxy.createServer(function (req, res, proxy) { + var target = servers.shift(); // 1. Remove first server + proxy.proxyRequest(req, res, target); // 2. Re-route to that server + servers.push(target); // 3. Add back to end of list +}); + + +s.listen(8080); \ No newline at end of file diff --git a/Chapter10/03_roundrobin/server_list.json b/Chapter10/03_roundrobin/server_list.json new file mode 100644 index 0000000..99de2f2 --- /dev/null +++ b/Chapter10/03_roundrobin/server_list.json @@ -0,0 +1,16 @@ +{ + "servers": [ + { + "host": "localhost", + "port": "8081" + }, + { + "host": "localhost", + "port": "8082" + }, + { + "host": "localhost", + "port": "8083" + } + ] +} diff --git a/Chapter10/03_roundrobin/simple.js b/Chapter10/03_roundrobin/simple.js new file mode 100644 index 0000000..f26857d --- /dev/null +++ b/Chapter10/03_roundrobin/simple.js @@ -0,0 +1,15 @@ + +var http = require('http'); + +console.log(process.argv); + +if (process.argv.length != 3) { + console.log("Need a port number"); + process.exit(-1); +} + +var s = http.createServer(function (req, res) { + res.end("I listened on port " + process.argv[2] + "\n"); +}); + +s.listen(process.argv[2]); diff --git a/Chapter10/03b_roundrobin_sessions/01_memecached_sessions.js b/Chapter10/03b_roundrobin_sessions/01_memecached_sessions.js new file mode 100644 index 0000000..e32d1bd --- /dev/null +++ b/Chapter10/03b_roundrobin_sessions/01_memecached_sessions.js @@ -0,0 +1,18 @@ +var express = require('express'); + +// pass the express object so it can inherit from MemoryStore +var MemcachedStore = require('connect-memcached')(express); +var mcds = new MemcachedStore({ hosts: "localhost:11211" }); + +var app = express() + .use(express.logger('dev')) + .use(express.cookieParser()) + .use(express.session({ secret: "cat on keyboard", + cookie: { maxAge: 1800000 }, + store: mcds})) + .use(function(req, res){ + var x = req.session.last_access; + req.session.last_access = new Date(); + res.end("You last asked for this page at: " + x); + }) + .listen(8080); diff --git a/Chapter10/03b_roundrobin_sessions/Readme.md b/Chapter10/03b_roundrobin_sessions/Readme.md new file mode 100644 index 0000000..4d98bf9 --- /dev/null +++ b/Chapter10/03b_roundrobin_sessions/Readme.md @@ -0,0 +1,7 @@ + +# Running this Sample + + +To run this sample, you need memcached installed. + + diff --git a/Chapter10/03b_roundrobin_sessions/package.json b/Chapter10/03b_roundrobin_sessions/package.json new file mode 100644 index 0000000..9abe672 --- /dev/null +++ b/Chapter10/03b_roundrobin_sessions/package.json @@ -0,0 +1,9 @@ +{ + "name": "Round-Robin-Demo", + "description": "A little proxy server to round-robin requests", + "version": "0.0.1", + "private": true, + "dependencies": { + "http-proxy": "0.8.x" + } +} diff --git a/Chapter10/04a_vhosting_builtin/Readme.md b/Chapter10/04a_vhosting_builtin/Readme.md new file mode 100644 index 0000000..df5d087 --- /dev/null +++ b/Chapter10/04a_vhosting_builtin/Readme.md @@ -0,0 +1,48 @@ + +# Virtual Hosts using express + +To get this sample running, you first need to do a bit of setup. + +## 1. Set up the host names + +### Mac / Unix + +Launch /Applications/Utilities/Terminal.app/ +type: +sudo emacs (or vi) /etc/hosts + +Add the following entries: + +127.0.0.1 app1 +127.0.0.1 app2 +127.0.0.1 app3 + +Save and exit + +### Windows + +notepad c:\windows\system32\drivers\etc\hosts.txt + +Add the following entries: + +127.0.0.1 app1 +127.0.0.1 app2 +127.0.0.1 app3 + +Save and exit. + + +## 2. Run the sample + + node server.js + +## 3. Test it out + +1. You can either use `curl` to download the page content: + + curl http://app1:8080/ + curl http://app2:8080/ + curl http://app3:8080/ + +1. Or you can just view the page in the browser, as _http://app1:8080_, _http://app1:8080_, _http://app1:8080_ . + diff --git a/Chapter10/04a_vhosting_builtin/package.json b/Chapter10/04a_vhosting_builtin/package.json new file mode 100644 index 0000000..8659420 --- /dev/null +++ b/Chapter10/04a_vhosting_builtin/package.json @@ -0,0 +1,10 @@ +{ + "name": "Virtual-Hosts-Demo", + "description": "Demonstrates virtual hosts and expressjs", + "version": "0.0.1", + "private": true, + "dependencies": { + "express": "3.x", + "async": "0.1.x" + } +} diff --git a/Chapter10/04a_vhosting_builtin/vhost_server.js b/Chapter10/04a_vhosting_builtin/vhost_server.js new file mode 100644 index 0000000..5e54568 --- /dev/null +++ b/Chapter10/04a_vhosting_builtin/vhost_server.js @@ -0,0 +1,32 @@ + +var express = require('express'); + +var one = express(); +one.get("/", function(req, res){ + res.send("This is app one!") +}); + + +// App two +var two = express(); +two.get("/", function(req, res){ + res.send("This is app two!") +}); + +// App three +var three = express(); +three.get("/", function(req, res){ + res.send("This is app three!") +}); + + +// controlling app +var master_app = express(); + +master_app.use(express.logger('dev')); +master_app.use(express.vhost('app1', one)) +master_app.use(express.vhost('app2', two)); +master_app.use(express.vhost('app3', three)); + +master_app.listen(8080); +console.log('Listening on 8080 for three different hosts'); diff --git a/Chapter10/04b_vhosting_proxy/app1.js b/Chapter10/04b_vhosting_proxy/app1.js new file mode 100644 index 0000000..dbc3d36 --- /dev/null +++ b/Chapter10/04b_vhosting_proxy/app1.js @@ -0,0 +1,10 @@ + +var express = require('express'); + +var one = express(); +one.use(express.logger('dev')); +one.get("/", function(req, res){ + res.send("This is app one!") +}); + +one.listen(8081); diff --git a/Chapter10/04b_vhosting_proxy/app2.js b/Chapter10/04b_vhosting_proxy/app2.js new file mode 100644 index 0000000..182d959 --- /dev/null +++ b/Chapter10/04b_vhosting_proxy/app2.js @@ -0,0 +1,10 @@ + +var express = require('express'); + +var two = express(); +two.use(express.logger('dev')); +two.get("/", function(req, res){ + res.send("This is app two!") +}); + +two.listen(8082); diff --git a/Chapter10/04b_vhosting_proxy/app3.js b/Chapter10/04b_vhosting_proxy/app3.js new file mode 100644 index 0000000..dc9a609 --- /dev/null +++ b/Chapter10/04b_vhosting_proxy/app3.js @@ -0,0 +1,10 @@ + +var express = require('express'); + +var three = express(); +three.use(express.logger('dev')); +three.get("/", function(req, res){ + res.send("This is app three!") +}); + +three.listen(8083); diff --git a/Chapter10/04b_vhosting_proxy/package.json b/Chapter10/04b_vhosting_proxy/package.json new file mode 100644 index 0000000..7b683d0 --- /dev/null +++ b/Chapter10/04b_vhosting_proxy/package.json @@ -0,0 +1,10 @@ +{ + "name": "Virtual-Hosts-Demo", + "description": "Demonstrates virtual hosts and expressjs", + "version": "0.0.1", + "private": true, + "dependencies": { + "express": "3.x", + "http-proxy": "0.8.x" + } +} diff --git a/Chapter10/04b_vhosting_proxy/proxy_vhost_server.js b/Chapter10/04b_vhosting_proxy/proxy_vhost_server.js new file mode 100644 index 0000000..e752816 --- /dev/null +++ b/Chapter10/04b_vhosting_proxy/proxy_vhost_server.js @@ -0,0 +1,14 @@ + +var httpProxy = require('http-proxy'); + +var options = { + hostnameOnly: true, + router: { + 'app1': '127.0.0.1:8081', + 'app2': '127.0.0.1:8082', + 'app3': '127.0.0.1:8083' + } +} + +var proxyServer = httpProxy.createServer(options); +proxyServer.listen(8080); diff --git a/Chapter10/05a_https_builtin/certreq.csr b/Chapter10/05a_https_builtin/certreq.csr new file mode 100644 index 0000000..4b66cb0 --- /dev/null +++ b/Chapter10/05a_https_builtin/certreq.csr @@ -0,0 +1,10 @@ +-----BEGIN CERTIFICATE REQUEST----- +MIIBejCB5AIBADA7MQswCQYDVQQGEwJVUzELMAkGA1UECBMCV0ExEDAOBgNVBAcT +B1NlYXR0bGUxDTALBgNVBAoTBFRlc3QwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJ +AoGBANrhN9YKw0P6Oz5RoYRiyh0if3FosI5A3NqZSdvQSKxzzUMLOxT2UJ8qAXqy +4BOIbwwlu6tv5tayqWurTcNg5n6seNGAZex2TRqeoNpHYI3BGcaaE6C/Q4sMzfSZ +VESdZGr1P557SH06DZlwvjZut/d5PpqYXNoHUwoJUFe60XxbAgMBAAGgADANBgkq +hkiG9w0BAQUFAAOBgQBpsF3SutkgYnxTjw12BqlCcX2JGLOS4vnPICHh3iaujvdZ +9MMNsx+ZoZiqGxGBJghNbYBMJVLy/QMQQdhGKUimgb6Z9JXbbbHxzrwOFO5MWbxo +WK/9VQYRoz/VCbG1W2LJ4w6qR0INuLTN55mdHNpPaQaVEMvs81fNwk0etMvPkg== +-----END CERTIFICATE REQUEST----- diff --git a/Chapter10/05a_https_builtin/https_express_server.js b/Chapter10/05a_https_builtin/https_express_server.js new file mode 100644 index 0000000..8c003f0 --- /dev/null +++ b/Chapter10/05a_https_builtin/https_express_server.js @@ -0,0 +1,22 @@ +var express = require('express'), + https = require('https'), + fs = require('fs'); + +var privateKey = fs.readFileSync('privkey.pem').toString(); +var certificate = fs.readFileSync('newcert.pem').toString(); + +var options = { + key : privateKey, + cert : certificate +} +var app = express(); + +app.get("*", function (req, res) { + res.end("Thanks for calling securely!\n"); +}); + + +// start server +https.createServer(options, app).listen(443, function(){ + console.log("Express server listening on port " + 443); +}); diff --git a/Chapter10/05a_https_builtin/newcert.pem b/Chapter10/05a_https_builtin/newcert.pem new file mode 100644 index 0000000..a60f9e5 --- /dev/null +++ b/Chapter10/05a_https_builtin/newcert.pem @@ -0,0 +1,13 @@ +-----BEGIN CERTIFICATE----- +MIIB7TCCAVYCCQCrAS8mJkbZ+TANBgkqhkiG9w0BAQUFADA7MQswCQYDVQQGEwJV +UzELMAkGA1UECBMCV0ExEDAOBgNVBAcTB1NlYXR0bGUxDTALBgNVBAoTBFRlc3Qw +HhcNMTMwMTA1MTQzMjQxWhcNMjMwMTAzMTQzMjQxWjA7MQswCQYDVQQGEwJVUzEL +MAkGA1UECBMCV0ExEDAOBgNVBAcTB1NlYXR0bGUxDTALBgNVBAoTBFRlc3QwgZ8w +DQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBANrhN9YKw0P6Oz5RoYRiyh0if3FosI5A +3NqZSdvQSKxzzUMLOxT2UJ8qAXqy4BOIbwwlu6tv5tayqWurTcNg5n6seNGAZex2 +TRqeoNpHYI3BGcaaE6C/Q4sMzfSZVESdZGr1P557SH06DZlwvjZut/d5PpqYXNoH +UwoJUFe60XxbAgMBAAEwDQYJKoZIhvcNAQEFBQADgYEAp03fWV/ZlTxh5ZFnet7f +9BE/VUBRtKFKyTVmjeQDs400NC2MrxXdkWs/hLMjfaWV5HleqaQ/kKUmwqw+Enie +aOh5Lk1C4iOv8sbOScOCIbe7aphzk52lT3QuC2JYspT/BXUz7KlaKDmsW12guGds +8VGcLDStAGjCFgEMHo9vECc= +-----END CERTIFICATE----- diff --git a/Chapter10/05a_https_builtin/package.json b/Chapter10/05a_https_builtin/package.json new file mode 100644 index 0000000..8659420 --- /dev/null +++ b/Chapter10/05a_https_builtin/package.json @@ -0,0 +1,10 @@ +{ + "name": "Virtual-Hosts-Demo", + "description": "Demonstrates virtual hosts and expressjs", + "version": "0.0.1", + "private": true, + "dependencies": { + "express": "3.x", + "async": "0.1.x" + } +} diff --git a/Chapter10/05a_https_builtin/privkey.pem b/Chapter10/05a_https_builtin/privkey.pem new file mode 100644 index 0000000..292f898 --- /dev/null +++ b/Chapter10/05a_https_builtin/privkey.pem @@ -0,0 +1,15 @@ +-----BEGIN RSA PRIVATE KEY----- +MIICXAIBAAKBgQDa4TfWCsND+js+UaGEYsodIn9xaLCOQNzamUnb0Eisc81DCzsU +9lCfKgF6suATiG8MJburb+bWsqlrq03DYOZ+rHjRgGXsdk0anqDaR2CNwRnGmhOg +v0OLDM30mVREnWRq9T+ee0h9Og2ZcL42brf3eT6amFzaB1MKCVBXutF8WwIDAQAB +AoGAcpCVyDwD7s3IOptBnmiS/+Lxr+urFhpPP0Aiz6Jal6FZW/FB8HvowRachZug ++7ha35HUhCxjOBd15DxazJwoqEdImCtSr03u0PYET6U55YOSxI1BQCRjcybpydOc +ZHpdOVeQjQesfOKeQpIMHjgzKFhUlxrGoY5e6BDtHqpdDTECQQDxB89FTuIV1PbK +TkFR6HLrdQh7hLgb+V+EftNVAkyQjPdaPgYFi5rMFqfvIzVG93hiaVnaxh8Ks6uM +6cbxsaijAkEA6Hk6vZR465OxnGLarj8ijDTZs7xXBjxniBAyfP/S+APOSfAARGlg +vQhzL9Y2lHBZJs/DsH5NRk7L2yX2VlUA6QJADDAq6QROJnB4ck52ux+YABQQ874I +WVHI5LhNE3VkTcLzFxsfztP6ZeuXXl5XaVlGOyO8qXVvSGlBeYSwzLQBJQJAWfbg +RpF4oiIL7+tJmXkRU5T4UtgmDWG+5ybtgvY1nIlMgcyBLfhh2YW1neOWR6eauKxa +nKikGvtPZMWyKQLIUQJBAIbQCmsyX944TmmRLJ5g7Ur77Rj6ANTAWYL8v7zEcHJi +oZ2mxF4Asdggu2Kavc8SVitQ8HZAOTtiFjQriG3+GjI= +-----END RSA PRIVATE KEY----- diff --git a/Chapter10/05b_https_proxy/app1.js b/Chapter10/05b_https_proxy/app1.js new file mode 100644 index 0000000..8b18152 --- /dev/null +++ b/Chapter10/05b_https_proxy/app1.js @@ -0,0 +1,10 @@ +var express = require('express'); + +var one = express(); +one.use(express.logger('dev')); +one.get("/", function(req, res){ + console.log(req); + res.send("\nWhat part of 'highly classified' do you not understand?!!\n") +}); + +one.listen(8081); diff --git a/Chapter10/05b_https_proxy/certreq.csr b/Chapter10/05b_https_proxy/certreq.csr new file mode 100644 index 0000000..4b66cb0 --- /dev/null +++ b/Chapter10/05b_https_proxy/certreq.csr @@ -0,0 +1,10 @@ +-----BEGIN CERTIFICATE REQUEST----- +MIIBejCB5AIBADA7MQswCQYDVQQGEwJVUzELMAkGA1UECBMCV0ExEDAOBgNVBAcT +B1NlYXR0bGUxDTALBgNVBAoTBFRlc3QwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJ +AoGBANrhN9YKw0P6Oz5RoYRiyh0if3FosI5A3NqZSdvQSKxzzUMLOxT2UJ8qAXqy +4BOIbwwlu6tv5tayqWurTcNg5n6seNGAZex2TRqeoNpHYI3BGcaaE6C/Q4sMzfSZ +VESdZGr1P557SH06DZlwvjZut/d5PpqYXNoHUwoJUFe60XxbAgMBAAGgADANBgkq +hkiG9w0BAQUFAAOBgQBpsF3SutkgYnxTjw12BqlCcX2JGLOS4vnPICHh3iaujvdZ +9MMNsx+ZoZiqGxGBJghNbYBMJVLy/QMQQdhGKUimgb6Z9JXbbbHxzrwOFO5MWbxo +WK/9VQYRoz/VCbG1W2LJ4w6qR0INuLTN55mdHNpPaQaVEMvs81fNwk0etMvPkg== +-----END CERTIFICATE REQUEST----- diff --git a/Chapter10/05b_https_proxy/https_proxy_server.js b/Chapter10/05b_https_proxy/https_proxy_server.js new file mode 100644 index 0000000..a750cf6 --- /dev/null +++ b/Chapter10/05b_https_proxy/https_proxy_server.js @@ -0,0 +1,34 @@ +var fs = require('fs'), + http = require('http'), + https = require('https'), + httpProxy = require('http-proxy'); + + +var options = { + https: { + key: fs.readFileSync('privkey.pem', 'utf8'), + cert: fs.readFileSync('newcert.pem', 'utf8') + } +}; + + +// +// Create a standalone HTTPS proxy server +// +//httpProxy.createServer(8000, 'localhost', options).listen(8001); + + +// +// Create an instance of HttpProxy to use with another HTTPS server +// +var proxy = new httpProxy.HttpProxy({ + target: { + host: 'localhost', + port: 8081 + } +}); + +https.createServer(options.https, function (req, res) { + proxy.proxyRequest(req, res) +}).listen(443); + diff --git a/Chapter10/05b_https_proxy/newcert.pem b/Chapter10/05b_https_proxy/newcert.pem new file mode 100644 index 0000000..a60f9e5 --- /dev/null +++ b/Chapter10/05b_https_proxy/newcert.pem @@ -0,0 +1,13 @@ +-----BEGIN CERTIFICATE----- +MIIB7TCCAVYCCQCrAS8mJkbZ+TANBgkqhkiG9w0BAQUFADA7MQswCQYDVQQGEwJV +UzELMAkGA1UECBMCV0ExEDAOBgNVBAcTB1NlYXR0bGUxDTALBgNVBAoTBFRlc3Qw +HhcNMTMwMTA1MTQzMjQxWhcNMjMwMTAzMTQzMjQxWjA7MQswCQYDVQQGEwJVUzEL +MAkGA1UECBMCV0ExEDAOBgNVBAcTB1NlYXR0bGUxDTALBgNVBAoTBFRlc3QwgZ8w +DQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBANrhN9YKw0P6Oz5RoYRiyh0if3FosI5A +3NqZSdvQSKxzzUMLOxT2UJ8qAXqy4BOIbwwlu6tv5tayqWurTcNg5n6seNGAZex2 +TRqeoNpHYI3BGcaaE6C/Q4sMzfSZVESdZGr1P557SH06DZlwvjZut/d5PpqYXNoH +UwoJUFe60XxbAgMBAAEwDQYJKoZIhvcNAQEFBQADgYEAp03fWV/ZlTxh5ZFnet7f +9BE/VUBRtKFKyTVmjeQDs400NC2MrxXdkWs/hLMjfaWV5HleqaQ/kKUmwqw+Enie +aOh5Lk1C4iOv8sbOScOCIbe7aphzk52lT3QuC2JYspT/BXUz7KlaKDmsW12guGds +8VGcLDStAGjCFgEMHo9vECc= +-----END CERTIFICATE----- diff --git a/Chapter10/05b_https_proxy/package.json b/Chapter10/05b_https_proxy/package.json new file mode 100644 index 0000000..770aae2 --- /dev/null +++ b/Chapter10/05b_https_proxy/package.json @@ -0,0 +1,11 @@ +{ + "name": "Virtual-Hosts-Demo", + "description": "Demonstrates virtual hosts and expressjs", + "version": "0.0.1", + "private": true, + "dependencies": { + "express": "3.x", + "http-proxy": "0.8.x", + "async": "0.1.x" + } +} diff --git a/Chapter10/05b_https_proxy/privkey.pem b/Chapter10/05b_https_proxy/privkey.pem new file mode 100644 index 0000000..292f898 --- /dev/null +++ b/Chapter10/05b_https_proxy/privkey.pem @@ -0,0 +1,15 @@ +-----BEGIN RSA PRIVATE KEY----- +MIICXAIBAAKBgQDa4TfWCsND+js+UaGEYsodIn9xaLCOQNzamUnb0Eisc81DCzsU +9lCfKgF6suATiG8MJburb+bWsqlrq03DYOZ+rHjRgGXsdk0anqDaR2CNwRnGmhOg +v0OLDM30mVREnWRq9T+ee0h9Og2ZcL42brf3eT6amFzaB1MKCVBXutF8WwIDAQAB +AoGAcpCVyDwD7s3IOptBnmiS/+Lxr+urFhpPP0Aiz6Jal6FZW/FB8HvowRachZug ++7ha35HUhCxjOBd15DxazJwoqEdImCtSr03u0PYET6U55YOSxI1BQCRjcybpydOc +ZHpdOVeQjQesfOKeQpIMHjgzKFhUlxrGoY5e6BDtHqpdDTECQQDxB89FTuIV1PbK +TkFR6HLrdQh7hLgb+V+EftNVAkyQjPdaPgYFi5rMFqfvIzVG93hiaVnaxh8Ks6uM +6cbxsaijAkEA6Hk6vZR465OxnGLarj8ijDTZs7xXBjxniBAyfP/S+APOSfAARGlg +vQhzL9Y2lHBZJs/DsH5NRk7L2yX2VlUA6QJADDAq6QROJnB4ck52ux+YABQQ874I +WVHI5LhNE3VkTcLzFxsfztP6ZeuXXl5XaVlGOyO8qXVvSGlBeYSwzLQBJQJAWfbg +RpF4oiIL7+tJmXkRU5T4UtgmDWG+5ybtgvY1nIlMgcyBLfhh2YW1neOWR6eauKxa +nKikGvtPZMWyKQLIUQJBAIbQCmsyX944TmmRLJ5g7Ur77Rj6ANTAWYL8v7zEcHJi +oZ2mxF4Asdggu2Kavc8SVitQ8HZAOTtiFjQriG3+GjI= +-----END RSA PRIVATE KEY----- diff --git a/Chapter10/06_path/path.js b/Chapter10/06_path/path.js new file mode 100644 index 0000000..b92108e --- /dev/null +++ b/Chapter10/06_path/path.js @@ -0,0 +1,4 @@ +var path = require('path'); + +var comps = [ '..', 'static', 'photos' ]; +console.log(comps.join(path.sep)); diff --git a/Chapter11/01_running/arguments.js b/Chapter11/01_running/arguments.js new file mode 100755 index 0000000..c62f484 --- /dev/null +++ b/Chapter11/01_running/arguments.js @@ -0,0 +1,12 @@ +#!/usr/local/bin/node + + +console.log("argv[0] is always the interpreter: " + process.argv[0]); +console.log("argv[0] is always the running script: " + process.argv[1]); +console.log("The rest are additional arguments you gave on the command line."); + +for (var i = 2; i < process.argv.length; i++) { + console.log("program parameter " + (i - 2) + " : " + + process.argv[i]); +} + diff --git a/Chapter11/01_running/env.js b/Chapter11/01_running/env.js new file mode 100644 index 0000000..348e09d --- /dev/null +++ b/Chapter11/01_running/env.js @@ -0,0 +1,4 @@ +#!/usr/local/bin/node + +console.log("process environment:"); +console.log(process.env); diff --git a/Chapter11/01_running/params.js b/Chapter11/01_running/params.js new file mode 100755 index 0000000..2aa1f91 --- /dev/null +++ b/Chapter11/01_running/params.js @@ -0,0 +1,3 @@ +#!/usr/local/bin/node + +console.log(process.argv); diff --git a/Chapter11/01_running/unix.js b/Chapter11/01_running/unix.js new file mode 100755 index 0000000..844b85b --- /dev/null +++ b/Chapter11/01_running/unix.js @@ -0,0 +1,6 @@ +#!/usr/local/bin/node + +console.log("Very sweet -- you can run node as a #!'d executable on Unix"); +console.log("You ran me with the following parameters:"); +console.log(process.argv); + diff --git a/Chapter11/01_running/windows.bat b/Chapter11/01_running/windows.bat new file mode 100755 index 0000000..b0c299a --- /dev/null +++ b/Chapter11/01_running/windows.bat @@ -0,0 +1,2 @@ + +node test.js %1 %2 %3 %4 %5 %6 %7 %8 %9 \ No newline at end of file diff --git a/Chapter11/01_running/windows.js b/Chapter11/01_running/windows.js new file mode 100755 index 0000000..8817e8c --- /dev/null +++ b/Chapter11/01_running/windows.js @@ -0,0 +1,3 @@ + +console.log(process.argv); + diff --git a/Chapter11/02_fs_sync/file_copy.js b/Chapter11/02_fs_sync/file_copy.js new file mode 100755 index 0000000..f8091fe --- /dev/null +++ b/Chapter11/02_fs_sync/file_copy.js @@ -0,0 +1,39 @@ +#!/usr/local/bin/node +var fs = require('fs'), + path = require('path'); + +var BUFFER_SIZE = 1000000; + +function copy_file_sync (src, dest) { + var read_so_far, fdsrc, fddest, read; + var buff = new Buffer(BUFFER_SIZE); + + fdsrc = fs.openSync(src, 'r'); + fddest = fs.openSync(dest, 'w'); + read_so_far = 0; + + do { + read = fs.readSync(fdsrc, buff, 0, BUFFER_SIZE, read_so_far); + fs.writeSync(fddest, buff, 0, read); + read_so_far += read; + } while (read > 0); + + fs.closeSync(fdsrc); + return fs.closeSync(fddest); +} + + +if (process.argv.length != 4) { + console.log("Usage: " + path.basename(process.argv[1], '.js') + + " [src_file] [dest_file]"); +} else { + try { + copy_file_sync(process.argv[2], process.argv[3]); + } catch (e) { + console.log("Error copying file:"); + console.log(e); + process.exit(-1); + } + + console.log("1 file copied."); +} diff --git a/Chapter11/02_fs_sync/file_move.js b/Chapter11/02_fs_sync/file_move.js new file mode 100755 index 0000000..a6e9ff2 --- /dev/null +++ b/Chapter11/02_fs_sync/file_move.js @@ -0,0 +1,40 @@ +#!/usr/local/bin/node +var fs = require('fs'), + path = require('path'); + +var BUFFER_SIZE = 1000000; + +function move_file_sync (src, dest) { + var read_so_far, fdsrc, fddest, read; + var buff = new Buffer(BUFFER_SIZE); + + fdsrc = fs.openSync(src, 'r'); + fddest = fs.openSync(dest, 'w'); + read_so_far = 0; + + do { + read = fs.readSync(fdsrc, buff, 0, BUFFER_SIZE, read_so_far); + fs.writeSync(fddest, buff, 0, read); + read_so_far += read; + } while (read > 0); + + fs.closeSync(fdsrc); + fs.closeSync(fddest); + return fs.unlinkSync(src); +} + + +if (process.argv.length != 4) { + console.log("Usage: " + path.basename(process.argv[1], '.js') + + " [src_file] [dest_file]"); +} else { + try { + move_file_sync(process.argv[2], process.argv[3]); + } catch (e) { + console.log("Error moving file:"); + console.log(e); + process.exit(-1); + } + + console.log("1 file moved."); +} diff --git a/Chapter11/02_fs_sync/mkdirs.js b/Chapter11/02_fs_sync/mkdirs.js new file mode 100755 index 0000000..3438d81 --- /dev/null +++ b/Chapter11/02_fs_sync/mkdirs.js @@ -0,0 +1,45 @@ +#!/usr/local/bin/node +var fs = require('fs'), + path = require('path'); + +function mkdirs (path_to_create, mode) { + if (mode == undefined) + mode = 0777 & (~process.umask()); + + var parts = path_to_create.split(path.sep); + var i; + for (i = 0; i < parts.length; i++) { + var search; + search = parts.slice(0, i + 1).join(path.sep); + if (fs.existsSync(search)) { + var st; + if ((st = fs.statSync(search))){ + if (!st.isDirectory()) { + throw new Error("Intermediate exists, is not a dir!"); + } + } + } else { + // doesn't exist. We can start creating now + break; + } + } + + for (var j = i; j < parts.length; j++) { + var build = parts.slice(0, j + 1).join(path.sep); + fs.mkdirSync(build); + } +} + +if (process.argv.length != 3) { + console.log("Usage: " + path.basename(process.argv[1], '.js') + + " path_to_create"); +} else { + try { + mkdirs(process.argv[2]); + } catch (e) { + console.log("Error creating folder:"); + console.log(e); + process.exit(-1); + } + console.log("done"); +} diff --git a/Chapter11/02_fs_sync/read_dir.js b/Chapter11/02_fs_sync/read_dir.js new file mode 100755 index 0000000..58c0515 --- /dev/null +++ b/Chapter11/02_fs_sync/read_dir.js @@ -0,0 +1,7 @@ +#!/usr/local/bin/node + +var fs = require('fs'); + +var files = fs.readdirSync("."); +console.log(files); + diff --git a/Chapter11/03_stdinout/01_simple_hasher.js b/Chapter11/03_stdinout/01_simple_hasher.js new file mode 100644 index 0000000..efd9f3b --- /dev/null +++ b/Chapter11/03_stdinout/01_simple_hasher.js @@ -0,0 +1,18 @@ +process.stdout.write("Hash-o-tron 3000\n"); +process.stdout.write("(Ctrl+D or Empty line quits)\n"); +process.stdout.write("data to hash > "); + +process.stdin.on('readable', function () { + var data = process.stdin.read(); + if (data == null) return; + if (data == "\n") process.exit(0); + + var hash = require('crypto').createHash('md5'); + hash.update(data); + process.stdout.write("Hashed to: " + hash.digest('hex') + "\n"); + process.stdout.write("data to hash > "); +}); + + +process.stdin.setEncoding('utf8'); +process.stdin.resume(); diff --git a/Chapter11/03_stdinout/02_raw_mode.js b/Chapter11/03_stdinout/02_raw_mode.js new file mode 100644 index 0000000..bdf8e24 --- /dev/null +++ b/Chapter11/03_stdinout/02_raw_mode.js @@ -0,0 +1,46 @@ +process.stdout.write("Hash-o-tron 3000\n"); +process.stdout.write("(Ctrl+D or Empty line quits)\n"); +process.stdout.write("data to hash > "); + +var last_read; + +process.stdin.on('readable', function () { + data = process.stdin.read(); + if (!data) return; + if (!process.stdin.isRaw) { + last_read = data; + if (data == "\n") process.exit(0); + process.stdout.write("Please select type of hash:\n"); + process.stdout.write("(1 – md5, 2 – sha1, 3 – sha256, 4 – sha512)\n"); + process.stdout.write("[1-4] > "); + process.stdin.setRawMode(true); + } else { + var alg; + if (data != '') { + var c = parseInt(data); + switch (c) { + case 1: alg = 'md5'; break; + case 2: alg = 'sha1'; break; + case 3: alg = 'sha256'; break; + case 4: alg = 'sha512'; break; + } + if (alg) { + var hash = require('crypto').createHash(alg); + hash.update(last_read); + process.stdout.write("\nHashed to: " + hash.digest('hex')); + process.stdout.write("\ndata to hash > "); + process.stdin.setRawMode(false); + } else { + process.stdout.write("\nPlease select type of hash:\n"); + process.stdout.write("[1-4] > "); + } + } else { + process.stdout.write("\ndata to hash > "); + process.stdin.setRawMode(false); + } + } +}); + +process.stdin.setEncoding('utf8') +process.stdin.resume() + diff --git a/Chapter11/03_stdinout/03_readline.js b/Chapter11/03_stdinout/03_readline.js new file mode 100644 index 0000000..fe168fe --- /dev/null +++ b/Chapter11/03_stdinout/03_readline.js @@ -0,0 +1,66 @@ +var readline = require('readline'); + +var rl = readline.createInterface({ + input: process.stdin, + output: process.stdout +}); + +var p = "rpn expression > " +rl.setPrompt(p, p.length); +rl.prompt(); + +rl.on("line", function (line) { + if (line == "\n") { + rl.close(); + return; + } + + var parts = line.trim().split(new RegExp("[ ]+")); + var r = rpn_compute(parts); + if (r !== false) { + process.stdout.write("Result: " + r + "\n"); + } else { + process.stdout.write("Invalid expression.\n"); + } + rl.prompt(); +}); + +rl.on("SIGINT", function () { + process.stdout.write("\n"); + rl.close(); +}); + + +// push numbers onto a stack, pop when we see an operator. +function rpn_compute(parts) { + var stack = []; + for (var i = 0; i < parts.length; i++) { + switch (parts[i]) { + case '+': case '-': case '*': case '/': + if (stack.length < 2) return false; + do_op(stack, parts[i]); + break; + default: + var num = parseFloat(parts[i]); + if (isNaN(num)) return false; + stack.push(num); + break; + } + } + if (stack.length != 1) return false; + return stack.pop(); +} + + +function do_op(stack, operator) { + var b = stack.pop(); + var a = stack.pop(); + switch (operator) { + case '+': stack.push(a + b); break; + case '-': stack.push(a - b); break; + case '*': stack.push(a * b); break; + case '/': stack.push(a / b); break; + default: throw new Error("Unexpected operator"); + } +} + diff --git a/Chapter11/03_stdinout/04_questions.js b/Chapter11/03_stdinout/04_questions.js new file mode 100644 index 0000000..cf4382b --- /dev/null +++ b/Chapter11/03_stdinout/04_questions.js @@ -0,0 +1,37 @@ +var readline = require('readline'), + async = require("async"), + fs = require('fs'); + +var questions = [ "What's your favourite colour? ", + "What's your shoe size? ", + "Cats or dogs? ", + "Doctor Who or Doctor House? " ]; + +var rl = readline.createInterface({ // 1. + input: process.stdin, + output: process.stdout +}); + +var output = []; +async.forEachSeries( + questions, + function (item, cb) { // 2. + rl.question(item, function (answer) { + output.push(answer); + cb(null); + }); + }, + function (err) { // 3. + if (err) { + console.log("Hunh, couldn't get answers"); + console.log(err); + return; + } + fs.appendFileSync("answers.txt", JSON.stringify(output) + "\n"); + console.log("\nThanks for your answers!"); + console.log("We'll sell them to some telemarketer immediately!"); + rl.close(); + } +); + + diff --git a/Chapter11/03_stdinout/package.json b/Chapter11/03_stdinout/package.json new file mode 100644 index 0000000..ed249e2 --- /dev/null +++ b/Chapter11/03_stdinout/package.json @@ -0,0 +1,9 @@ +{ + "name": "Readline-questions-demo", + "description": "Demonstrates questions in readline", + "version": "0.0.1", + "private": true, + "dependencies": { + "async": "0.1.x" + } +} diff --git a/Chapter11/04_create_processes/01_simple_exec.js b/Chapter11/04_create_processes/01_simple_exec.js new file mode 100644 index 0000000..4e5c79e --- /dev/null +++ b/Chapter11/04_create_processes/01_simple_exec.js @@ -0,0 +1,20 @@ +var exec = require('child_process').exec, + child; + +if (process.argv.length != 3) { + console.log("I need a file name"); + process.exit(-1); +} + +var file_name = process.argv[2]; +var cmd = process.platform == 'win32' ? 'type' : "cat"; +child = exec(cmd + " " + file_name, function (error, stdout, stderr) { + console.log('stdout: ' + stdout); + console.log('stderr: ' + stderr); + + if (error) { + console.log("Error exec'ing the file"); + console.log(error); + process.exit(1); + } +}); diff --git a/Chapter11/04_create_processes/02_spawn.js b/Chapter11/04_create_processes/02_spawn.js new file mode 100644 index 0000000..a788071 --- /dev/null +++ b/Chapter11/04_create_processes/02_spawn.js @@ -0,0 +1,23 @@ + +var spawn = require("child_process").spawn; +var node; + +if (process.argv.length != 3) { + console.log("I need a script to run"); + process.exit(-1); +} + +var node = spawn("node", [ process.argv[2] ]); +node.stdout.on('data', print_stdout); +node.stderr.on('data', print_stderr); +node.on('exit', exited); + +function print_stdout(data) { + console.log("stdout: " + data.toString('utf8')); +} +function print_stderr(data) { + console.log("stderr: " + data.toString('utf8')); +} +function exited(code) { + console.error("--> Node exited with code: " + code); +} diff --git a/Chapter11/04_create_processes/03_node_runner.js b/Chapter11/04_create_processes/03_node_runner.js new file mode 100644 index 0000000..2a80735 --- /dev/null +++ b/Chapter11/04_create_processes/03_node_runner.js @@ -0,0 +1,28 @@ + +var spawn = require("child_process").spawn; +var node; + +if (process.argv.length < 3) { + console.log("I need a script to run"); + process.exit(-1); +} + +function spawn_node() { + var node = spawn("node", process.argv.slice(2)); + node.stdout.on('data', print_stdout); + node.stderr.on('data', print_stderr); + node.on('exit', exited); +} + +function print_stdout(data) { + console.log(data.toString('utf8')); +} +function print_stderr(data) { + console.log("stderr: " + data.toString('utf8')); +} +function exited(code) { + console.error("--> Node exited with code: " + code + ". Restarting"); + spawn_node(); +} + +spawn_node(); diff --git a/Chapter11/04_create_processes/hello.js b/Chapter11/04_create_processes/hello.js new file mode 100644 index 0000000..c36e70f --- /dev/null +++ b/Chapter11/04_create_processes/hello.js @@ -0,0 +1,2 @@ + +console.log("hello world"); diff --git a/Chapter11/04_create_processes/simulate_crash.js b/Chapter11/04_create_processes/simulate_crash.js new file mode 100644 index 0000000..c7c9695 --- /dev/null +++ b/Chapter11/04_create_processes/simulate_crash.js @@ -0,0 +1,8 @@ + +console.log("Starting Server woo!"); + +setTimeout(function () { + console.error("OH noes, I'm dying!"); +}, 5000); + + diff --git a/Chapter12/01_functional_tests/01_functional.js b/Chapter12/01_functional_tests/01_functional.js new file mode 100644 index 0000000..aa6c35f --- /dev/null +++ b/Chapter12/01_functional_tests/01_functional.js @@ -0,0 +1,55 @@ +var rpn = require('./rpn.js'); + + +exports.addition = function (test) { + test.expect(4); + test.equals(rpn.compute(prep("1 2 +")), 3); + test.equals(rpn.compute(prep("1 2 3 + +")), 6); + test.equals(rpn.compute(prep("1 2 + 5 6 + +")), 14); + test.equals(rpn.compute(prep("1 2 3 4 5 6 7 + + + + + +")), 28); + test.done(); +}; + +exports.subtraction = function (test) { + test.expect(4); + test.equals(rpn.compute(prep("7 2 -")), 5); + test.equals(rpn.compute(prep("7 2 5 - -")), 10); + test.equals(rpn.compute(prep("7 2 - 10 2 - -")), -3); + test.equals(rpn.compute(prep("100 50 20 15 5 5 - - - - -")), 55); + test.done(); +}; + +exports.multiplication = function (test) { + test.expect(3); + test.equals(rpn.compute(prep("4 5 *")), 20); + test.equals(rpn.compute(prep("4 5 8 * *")), 160); + test.equals(rpn.compute(prep("4 5 * 2 3 * *")), 120); + test.done(); +}; + +exports.division = function (test) { + test.expect(3) + test.equals(rpn.compute(prep("39 13 /")), 3); + test.equals(rpn.compute(prep("9 39 13 / /")), 3); + test.equals(rpn.compute(prep("18 27 39 13 / / /")), 2); + test.done(); +}; + +exports.decimals = function (test) { + test.expect(2); + test.equals(rpn.compute(prep("3.14159 5 *")), 15.70795); + test.equals(rpn.compute(prep("100 3 /")), 33.333333333333336); + test.done(); +}; + +exports.empty = function (test) { + test.expect(1); + test.throws(rpn.compute([])); + test.done(); +}; + + +function prep(str) { + return str.trim().split(/[ ]+/); +} + diff --git a/Chapter12/01_functional_tests/02_async.js b/Chapter12/01_functional_tests/02_async.js new file mode 100644 index 0000000..75092e9 --- /dev/null +++ b/Chapter12/01_functional_tests/02_async.js @@ -0,0 +1,18 @@ + + +exports.async1 = function (test) { + setTimeout(function () { + test.equal(true, true); + test.done(); + }, 2000); +}; + + +exports.async2 = function (test) { + setTimeout(function () { + test.equal(true, true); + test.done(); + }, 1400); +}; + + diff --git a/Chapter12/01_functional_tests/03_group.js b/Chapter12/01_functional_tests/03_group.js new file mode 100644 index 0000000..6066fff --- /dev/null +++ b/Chapter12/01_functional_tests/03_group.js @@ -0,0 +1,18 @@ + + +exports.group1 = { + setUp: function (callback) { + // do something + callback(); + }, + tearDown: function (callback) { + // do something + callback(); + }, + test1: function (test) { + test.done(); + }, + test2: function (test) { + test.done(); + } +}; diff --git a/Chapter12/01_functional_tests/package.json b/Chapter12/01_functional_tests/package.json new file mode 100644 index 0000000..b7d84d2 --- /dev/null +++ b/Chapter12/01_functional_tests/package.json @@ -0,0 +1,9 @@ +{ + "name": "Functional-testing-demo", + "description": "Some simple functional tests", + "version": "0.0.1", + "private": true, + "dependencies": { + "nodeunit": "0.7.x" + } +} diff --git a/Chapter12/01_functional_tests/rpn.js b/Chapter12/01_functional_tests/rpn.js new file mode 100644 index 0000000..569b6f6 --- /dev/null +++ b/Chapter12/01_functional_tests/rpn.js @@ -0,0 +1,35 @@ + +exports.version = "1.0.0"; + +// push numbers onto a stack, pop when we see an operator. +exports.compute = function (parts) { + var stack = []; + for (var i = 0; i < parts.length; i++) { + switch (parts[i]) { + case '+': case '-': case '*': case '/': + if (stack.length < 2) return false; + do_op(stack, parts[i]); + break; + default: + var num = parseFloat(parts[i]); + if (isNaN(num)) return false; + stack.push(num); + break; + } + } + if (stack.length != 1) return false; + return stack.pop(); +} + + +function do_op(stack, operator) { + var b = stack.pop(); + var a = stack.pop(); + switch (operator) { + case '+': stack.push(a + b); break; + case '-': stack.push(a - b); break; + case '*': stack.push(a * b); break; + case '/': stack.push(a / b); break; + default: throw new Error("Unexpected operator"); + } +} diff --git a/Chapter12/02_api_testing/app/basic.html b/Chapter12/02_api_testing/app/basic.html new file mode 100644 index 0000000..0d966da --- /dev/null +++ b/Chapter12/02_api_testing/app/basic.html @@ -0,0 +1,25 @@ + + + + Photo Album + + + + + + + + + + + + + + + + + diff --git a/Chapter12/02_api_testing/app/data/album.js b/Chapter12/02_api_testing/app/data/album.js new file mode 100644 index 0000000..22fe780 --- /dev/null +++ b/Chapter12/02_api_testing/app/data/album.js @@ -0,0 +1,237 @@ + +var fs = require('fs'), + local = require('../local.config.js'), + db = require('./db.js'), + path = require("path"), + async = require('async'), + backhelp = require("./backend_helpers.js"); + +exports.version = "0.1.0"; + + +exports.create_album = function (data, callback) { + var write_succeeded = false; + var dbc; + + async.waterfall([ + // validate data. + function (cb) { + try { + backhelp.verify(data, + [ "name", + "title", + "date", + "description" ]); + if (!backhelp.valid_filename(data.name)) + throw invalid_album_name(); + } catch (e) { + cb(e); + return; + } + + db.db(cb); + }, + + function (dbclient, cb) { + dbc = dbclient; + dbc.query( + "INSERT INTO Albums VALUES (?, ?, ?, ?)", + [ data.name, data.title, data.date, data.description ], + backhelp.mscb(cb)); + }, + + // make sure the folder exists. + function (results, cb) { + write_succeeded = true; + fs.mkdir(local.config.static_content + + "albums/" + data.name, cb); + } + ], + function (err, results) { + // convert file errors to something we like. + if (err) { + if (write_succeeded) delete_album(dbc, data.name); + if (err instanceof Error && err.code == 'ER_EXISTS') + callback(backhelp.album_already_exists()); + else if (err instanceof Error && err.errno != undefined) + callback(backhelp.file_error(err)); + else + callback(err); + } else { + callback(err, err ? null : data); + } + + if (dbc) dbc.end(); + }); +}; + + +exports.album_by_name = function (name, callback) { + var dbc; + + async.waterfall([ + function (cb) { + if (!name) + cb(backhelp.missing_data("album name")); + else + db.db(cb); + }, + + function (dbclient, cb) { + dbc = dbclient; + dbc.query( + "SELECT * FROM Albums WHERE name = ?", + [ name ], + backhelp.mscb(cb)); + } + ], + function (err, results) { + if (dbc) dbc.end(); + if (err) { + callback (err); + } else if (!results || results.length == 0) { + callback(backhelp.no_such_album()); + } else { + callback(null, results[0]); + } + }); +}; + + +exports.photos_for_album = function (album_name, skip, limit, callback) { + var dbc; + + async.waterfall([ + function (cb) { + if (!album_name) + cb(backhelp.missing_data("album name")); + else + db.db(cb); + }, + + function (dbclient, cb) { + dbc = dbclient; + dbc.query( + "SELECT * FROM Photos WHERE album_name = ? LIMIT ?, ?", + [ album_name, skip, limit ], + backhelp.mscb(cb)); + }, + + ], + function (err, results) { + if (dbc) dbc.end(); + if (err) { + callback (err); + } else { + callback(null, results); + } + }); +}; + + +exports.all_albums = function (sort_by, desc, skip, count, callback) { + var dbc; + async.waterfall([ + function (cb) { + db.db(cb); + }, + function (dbclient, cb) { + dbc = dbclient; + dbc.query( + "SELECT * FROM Albums ORDER BY ? " + + (desc ? "DESC" : "ASC") + + " LIMIT ?, ?", + [ sort_by, skip, count ], + backhelp.mscb(cb)); + } + ], + function (err, results) { + if (dbc) dbc.end(); + if (err) { + callback (err); + } else { + callback(null, results); + } + }); +}; + + +exports.add_photo = function (photo_data, path_to_photo, callback) { + var base_fn = path.basename(path_to_photo).toLowerCase(); + var write_succeeded = false; + var dbc; + + async.waterfall([ + // validate data + function (cb) { + try { + backhelp.verify(photo_data, + [ "albumid", "description", "date" ]); + photo_data.filename = base_fn; + if (!backhelp.valid_filename(photo_data.albumid)) + throw invalid_album_name(); + } catch (e) { + cb(e); + return; + } + db.db(cb); + }, + + function (dbclient, cb) { + dbc = dbclient; + dbc.query( + "INSERT INTO Photos VALUES (?, ?, ?, ?)", + [ photo_data.albumid, base_fn, photo_data.description, + photo_data.date ], + backhelp.mscb(cb)); + }, + + // now copy the temp file to static content + function (results, cb) { + write_succeeded = true; + var save_path = local.config.static_content + "albums/" + + photo_data.albumid + "/" + base_fn; + backhelp.file_copy(path_to_photo, save_path, true, cb); + }, + + ], + function (err, results) { + if (err && write_succeeded) + delete_photo(dbc, photo_data.albumid, base_fn); + if (err) { + callback (err); + } else { + // clone the object + var pd = JSON.parse(JSON.stringify(photo_data)); + pd.filename = base_fn; + callback(null, pd); + } + if (dbc) dbc.end(); + }); +}; + + +function invalid_album_name() { + return backhelp.error("invalid_album_name", + "Album names can have letters, #s, _ and, -"); +} +function invalid_filename() { + return backhelp.error("invalid_filename", + "Filenames can have letters, #s, _ and, -"); +} + + +function delete_album(dbc, name) { + dbc.query( + "DELETE FROM Albums WHERE name = ?", + [ name ], + function (err, results) {}); +} + +function delete_photo(dbc, albumid, fn) { + dbc.query( + "DELETE FROM Photos WHERE albumid = ? AND filename = ?", + [ albumid, fn ], + function (err, results) { }); +} + diff --git a/Chapter12/02_api_testing/app/data/backend_helpers.js b/Chapter12/02_api_testing/app/data/backend_helpers.js new file mode 100644 index 0000000..d2eb70b --- /dev/null +++ b/Chapter12/02_api_testing/app/data/backend_helpers.js @@ -0,0 +1,118 @@ + +var fs = require('fs'); + + +exports.verify = function (data, field_names) { + for (var i = 0; i < field_names.length; i++) { + if (!data[field_names[i]]) { + throw exports.error("missing_data", + field_names[i] + " not optional"); + } + } + + return true; +} + +exports.error = function (code, message) { + var e = new Error(code); + e.description = message; + return e; +}; + +exports.file_error = function (err) { + err.description = err.message; + err.message = "file_error"; + return err; +} + + +/** + * Possible signatures: + * src, dst, callback + * src, dst, can_overwrite, callback + */ +exports.file_copy = function () { + + var src, dst, callback; + var can_overwrite = false; + + if (arguments.length == 3) { + src = arguments[0]; + dst = arguments[1]; + callback = arguments[2]; + } else if (arguments.length == 4) { + src = arguments[0]; + dst = arguments[1]; + callback = arguments[3]; + can_overwrite = arguments[2] + } + + function copy(err) { + var is, os; + + if (!err && !can_overwrite) { + return callback(backhelp.error("file_exists", + "File " + dst + " exists.")); + } + + fs.stat(src, function (err) { + if (err) { + return callback(err); + } + + is = fs.createReadStream(src); + os = fs.createWriteStream(dst); + is.on('end', function () { callback(null); }); + is.on('error', function (e) { callback(e); }); + is.pipe(os); + }); + } + + fs.stat(dst, copy); +}; + + + +exports.valid_filename = function (fn) { + var re = /[^\.a-zA-Z0-9_-]/; + return typeof fn == 'string' && fn.length > 0 && !(fn.match(re)); +}; + + +exports.db_error = function () { + return exports.error("server_error", + "Something horrible has happened with our database!"); +}; + +exports.album_already_exists = function () { + return exports.error("album_already_exists", + "An album with this name already exists."); +}; + +exports.missing_data = function (field) { + return exports.error("missing_data", "You must provide: " + field); +}; + +exports.no_such_user = function () { + return exports.error("no_such_user", + "The specified user does not exist"); +}; + + +exports.user_already_registered = function () { + return exprots.error("user_already_registered", + "This user appears to exist already!"); +}; + + + +/** + * node-mysql sometimes adds extra data to callbacks to be helpful. + * this can mess up our waterfall, however, so we'll strip those + * out. + */ +exports.mscb = function (cb) { + return function (err, results) { + cb(err, results); + } +} diff --git a/Chapter12/02_api_testing/app/data/db.js b/Chapter12/02_api_testing/app/data/db.js new file mode 100644 index 0000000..8bab0f1 --- /dev/null +++ b/Chapter12/02_api_testing/app/data/db.js @@ -0,0 +1,62 @@ +var mysql = require('mysql'), + pool = require('generic-pool'), + async = require('async'), + local = require("../local.config.js"); + + +var mysql_pool; + + +/** + * Currently for initialisation, we + * the database. We won't even attempt to start up + * if this fails, as it's pretty pointless. + */ +exports.init = function (callback) { + + conn_props = local.config.db_config; + + mysql_pool = pool.Pool({ + name : 'mysql', + create : function (callback) { + var c = mysql.createConnection({ + host: conn_props.host, + user: conn_props.user, + password: conn_props.password, + database: conn_props.database + }); + callback(null, c); + }, + destroy : function(client) { client.end(); }, + max : conn_props.pooled_connections, + idleTimeoutMillis : conn_props.idle_timeout_millis, + log : false + }); + + // run a test query to make sure it's working. + exports.run_mysql_query("SELECT 1", [], function (err, results) { + if (err != null) { + callback(err); + console.error("Unable to connect to database server. Aborting."); + } else { + console.log("Database initialised and connected."); + callback(null); + } + }); + +}; + + +exports.run_mysql_query = function (query, values, callback) { + mysql_pool.acquire(function(err, mysqlconn) { + mysqlconn.query(query, values, function (mysqlerr, mysqlresults) { + mysql_pool.release(mysqlconn); + callback(mysqlerr, mysqlresults); + }); + }); +}; + + +exports.db = function (callback) { + mysql_pool.acquire(callback); +}; diff --git a/Chapter12/02_api_testing/app/data/user.js b/Chapter12/02_api_testing/app/data/user.js new file mode 100644 index 0000000..cb724cb --- /dev/null +++ b/Chapter12/02_api_testing/app/data/user.js @@ -0,0 +1,120 @@ + +var async = require('async'), + bcrypt = require('bcrypt'), + db = require("./db.js"), + uuid = require('node-uuid'), + backhelp = require("./backend_helpers.js"); + + +exports.version = "0.1.0"; + +exports.user_by_uuid = function (uuid, callback) { + if (!uuid) + cb(backend.missing_data("uuid")); + else + user_by_field("user_uuid", uuid, callback); +}; + +exports.user_by_email = function (email, callback) { + if (!email) + cb(backend.missing_data("email")); + else + user_by_field("email_address", email, callback); +}; + + + + +exports.register = function (email, display_name, password, callback) { + var dbc; + var userid; + async.waterfall([ + // validate ze params + function (cb) { + if (!email || email.indexOf("@") == -1) + cb(backend.missing_data("email")); + else if (!display_name) + cb(backend.missing_data("display_name")); + else if (!password) + cb(backend.missing_data("password")); + else + cb(null); + }, + + // get a connection + function (cb) { + db.db(cb); + }, + + // generate a password hash + function (dbclient, cb) { + dbc = dbclient; + bcrypt.hash(password, 10, cb); + }, + + // register the account. + function (hash, cb) { + userid = uuid(); + var now = Math.round((new Date()).getTime() / 1000); + dbc.query( + "INSERT INTO Users VALUES (?, ?, ?, ?, ?, NULL, 0)", + [ userid, email, display_name, hash, now ], + backhelp.mscb(cb)); + }, + + // fetch and return the new user. + function (results, cb) { + exports.user_by_uuid(userid, cb); + } + ], + function (err, user_data) { + if (err) { + if (err.code + && (err.code == 'ER_DUP_KEYNAME' + || err.code == 'ER_EXISTS' + || err.code == 'ER_DUP_ENTRY')) + callback(backhelp.user_already_registered()); + else + callback (err); + } else { + callback(null, user_data); + } + }); +}; + + + +function user_by_field (field, value, callback) { + var dbc; + async.waterfall([ + // get a connection + function (cb) { + db.db(cb); + }, + + // fetch the user. + function (dbclient, cb) { + dbc = dbclient; + dbc.query( + "SELECT * FROM Users WHERE " + field + + " = ? AND deleted = false", + [ value ], + backhelp.mscb(cb)); + }, + + function (rows, cb) { + if (!rows || rows.length == 0) + cb(backhelp.no_such_user()); + else + cb(null, rows[0]); + } + ], + function (err, user_data) { + if (err) { + callback (err); + } else { + console.log(user_data); + callback(null, user_data); + } + }); +} \ No newline at end of file diff --git a/Chapter12/02_api_testing/app/handlers/albums.js b/Chapter12/02_api_testing/app/handlers/albums.js new file mode 100644 index 0000000..ac2da86 --- /dev/null +++ b/Chapter12/02_api_testing/app/handlers/albums.js @@ -0,0 +1,259 @@ + +var helpers = require('./helpers.js'), + album_data = require("../data/album.js"), + async = require('async'), + fs = require('fs'); + +exports.version = "0.1.0"; + + +/** + * Album class. + */ +function Album (album_data) { + this.name = album_data.name; + this.date = album_data.date; + this.title = album_data.title; + this.description = album_data.description; + this._id = album_data._id; +} + +Album.prototype.name = null; +Album.prototype.date = null; +Album.prototype.title = null; +Album.prototype.description = null; + +Album.prototype.response_obj = function () { + return { name: this.name, + date: this.date, + title: this.title, + description: this.description }; +}; +Album.prototype.photos = function (pn, ps, callback) { + if (this.album_photos != undefined) { + callback(null, this.album_photos); + return; + } + + album_data.photos_for_album( + this.name, + pn, ps, + function (err, results) { + if (err) { + callback(err); + return; + } + + var out = []; + for (var i = 0; i < results.length; i++) { + out.push(new Photo(results[i])); + } + + this.album_photos = out; + callback(null, this.album_photos); + } + ); +}; +Album.prototype.add_photo = function (data, path, callback) { + album_data.add_photo(data, path, function (err, photo_data) { + if (err) + callback(err); + else { + var p = new Photo(photo_data); + if (this.all_photos) + this.all_photos.push(p); + else + this.app_photos = [ p ]; + + callback(null, p); + } + }); +}; + + + + +/** + * Photo class. + */ +function Photo (photo_data) { + this.filename = photo_data.filename; + this.date = photo_data.date; + this.albumid = photo_data.albumid; + this.description = photo_data.description; + this._id = photo_data._id; +} +Photo.prototype._id = null; +Photo.prototype.filename = null; +Photo.prototype.date = null; +Photo.prototype.albumid = null; +Photo.prototype.description = null; +Photo.prototype.response_obj = function() { + return { + filename: this.filename, + date: this.date, + albumid: this.albumid, + description: this.description + }; +}; + + +/** + * Album module methods. + */ +exports.create_album = function (req, res) { + async.waterfall([ + // make sure the albumid is valid + function (cb) { + if (!req.body || !req.body.name) { + cb(helpers.no_such_album()); + return; + } + + // UNDONE: we should add some code to make sure the album + // doesn't already exist! + cb(null); + }, + + function (cb) { + album_data.create_album(req.body, cb); + } + ], + function (err, results) { + if (err) { + helpers.send_failure(res, err); + } else { + var a = new Album(results); + helpers.send_success(res, {album: a.response_obj() }); + } + }); +}; + + +exports.album_by_name = function (req, res) { + async.waterfall([ + // get the album + function (cb) { + if (!req.params || !req.params.album_name) + cb(helpers.no_such_album()); + else + album_data.album_by_name(req.params.album_name, cb); + } + ], + function (err, results) { + if (err) { + helpers.send_failure(res, err); + } else if (!results) { + helpers.send_failure(res, helpers.no_such_album()); + } else { + var a = new Album(album_data); + helpers.send_success(res, { album: a.response_obj() }); + } + }); +}; + + + +exports.list_all = function (req, res) { + album_data.all_albums("date", true, 0, 25, function (err, results) { + if (err) { + helpers.send_failure(res, err); + } else { + var out = []; + if (results) { + for (var i = 0; i < results.length; i++) { + out.push(new Album(results[i]).response_obj()); + } + } + helpers.send_success(res, { albums: out }); + } + }); +}; + + +exports.photos_for_album = function(req, res) { + var page_num = req.query.page ? req.query.page : 0; + var page_size = req.query.page_size ? req.query.page_size : 1000; + + page_num = parseInt(page_num); + page_size = parseInt(page_size); + if (isNaN(page_num)) page_num = 0; + if (isNaN(page_size)) page_size = 1000; + + var album; + async.waterfall([ + function (cb) { + // first get the album. + if (!req.params || !req.params.album_name) + cb(helpers.no_such_album()); + else + album_data.album_by_name(req.params.album_name, cb); + }, + + function (album_data, cb) { + if (!album_data) { + cb(helpers.no_such_album()); + return; + } + album = new Album(album_data); + album.photos(page_num, page_size, cb); + }, + function (photos, cb) { + var out = []; + for (var i = 0; i < photos.length; i++) { + out.push(photos[i].response_obj()); + } + cb(null, out); + } + ], + function (err, results) { + if (err) { + helpers.send_failure(res, err); + return; + } + if (!results) results = []; + var out = { photos: results, + album_data: album.response_obj() }; + helpers.send_success(res, out); + }); +}; + + +exports.add_photo_to_album = function (req, res) { + var album; + async.waterfall([ + // make sure we have everything we need. + function (cb) { + if (!req.body) + cb(helpers.missing_data("POST data")); + else if (!req.files || !req.files.photo_file) + cb(helpers.missing_data("a file")); + else if (!helpers.is_image(req.files.photo_file.name)) + cb(helpers.not_image()); + else + // get the album + album_data.album_by_name(req.params.album_name, cb); + }, + + function (album_data, cb) { + if (!album_data) { + cb(helpers.no_such_album()); + return; + } + + album = new Album(album_data); + req.body.filename = req.files.photo_file.name; + album.add_photo(req.body, req.files.photo_file.path, cb); + } + ], + function (err, p) { + if (err) { + helpers.send_failure(res, err); + return; + } + var out = { photo: p.response_obj(), + album_data: album.response_obj() }; + helpers.send_success(res, out); + }); +}; + diff --git a/Chapter12/02_api_testing/app/handlers/helpers.js b/Chapter12/02_api_testing/app/handlers/helpers.js new file mode 100644 index 0000000..ab0287f --- /dev/null +++ b/Chapter12/02_api_testing/app/handlers/helpers.js @@ -0,0 +1,107 @@ + +var path = require('path'); + + +exports.version = '0.1.0'; + + +exports.send_success = function (res, data) { + res.writeHead(200, {"Content-Type": "application/json"}); + var output = { error: null, data: data }; + res.end(JSON.stringify(output) + "\n"); +}; + +exports.send_failure = function (res, err) { + var code = exports.http_code_for_error(err); + res.writeHead(code, { "Content-Type" : "application/json" }); + res.end(exports.error_for_resp(err) + "\n"); +}; + +exports.error_for_resp = function (err) { + if (!err instanceof Error) { + console.error("** Unexpected error type! :" + + err.constructor.name); + return JSON.stringify(err); + } else { + return JSON.stringify({ error: err.message, + message: err.description }); + } +} + +exports.error = function (code, message) { + var e = new Error(code); + e.description = message; + return e; +}; + +exports.file_error = function (err) { + err.description = err.message; + err.message = "file_error"; + return e; +}; + + +exports.is_image = function (filename) { + switch (path.extname(filename).toLowerCase()) { + case '.jpg': case '.jpeg': case '.png': case '.bmp': + case '.gif': case '.tif': case '.tiff': + return true; + } + + return false; +}; + + +exports.invalid_resource = function () { + return exports.error("invalid_resource", + "The requested resource does not exist."); +}; + + +exports.missing_data = function (what) { + return exports.error("missing_data", + "You must include " + what); +} + + +exports.not_image = function () { + return exports.error("not_image_file", + "The uploaded file must be an image file."); +}; + + +exports.no_such_album = function () { + return exports.error("no_such_album", + "The specified album does not exist"); +}; + + +exports.http_code_for_error = function (err) { + switch (err.message) { + case "no_such_album": return 403; + case "invalid_resource": return 404; + case "invalid_email_address": return 403; + case 'invalid_album_name': return 403; + case "no_such_user": return 403; + } + + console.log("*** Error needs HTTP response code: " + err.message); + return 503; +} + + +exports.valid_filename = function (fn) { + var re = /[^\.a-zA-Z0-9_-]/; + return typeof fn == 'string' && fn.length > 0 && !(fn.match(re)); +}; + + +exports.invalid_email_address = function () { + return exports.error("invalid_email_address", + "That's not a valid email address, sorry"); +}; + +exports.auth_failed = function () { + return exports.error("auth_failure", + "Invalid email address / password combination."); +}; \ No newline at end of file diff --git a/Chapter12/02_api_testing/app/handlers/pages.js b/Chapter12/02_api_testing/app/handlers/pages.js new file mode 100644 index 0000000..77bf239 --- /dev/null +++ b/Chapter12/02_api_testing/app/handlers/pages.js @@ -0,0 +1,31 @@ + +var helpers = require('./helpers.js'), + fs = require('fs'); + + +exports.version = "0.1.0"; + + +exports.generate = function (req, res) { + + var page = req.params.page_name; + if (req.params.sub_page && req.params.page_name == 'admin') + page = req.params.page_name + "_" + req.params.sub_page; + + fs.readFile( + 'basic.html', + function (err, contents) { + if (err) { + send_failure(res, 500, err); + return; + } + + contents = contents.toString('utf8'); + + // replace page name, and then dump to output. + contents = contents.replace('{{PAGE_NAME}}', page); + res.writeHead(200, { "Content-Type": "text/html" }); + res.end(contents); + } + ); +}; diff --git a/Chapter12/02_api_testing/app/handlers/users.js b/Chapter12/02_api_testing/app/handlers/users.js new file mode 100644 index 0000000..18fba21 --- /dev/null +++ b/Chapter12/02_api_testing/app/handlers/users.js @@ -0,0 +1,138 @@ +var helpers = require('./helpers.js'), + user_data = require("../data/user.js"), + async = require('async'), + bcrypt = require('bcrypt'), + fs = require('fs'); + +exports.version = "0.1.0"; + + +function User (user_data) { + this.uuid = user_data["user_uuid"]; + this.email_address = user_data["email_address"]; + this.display_name = user_data["display_name"]; + this.password = user_data["password"]; + this.first_seen_date = user_data["first_seen_date"]; + this.last_modified_date = user_data["last_modified_date"]; + this.deleted = user_data["deleted"]; +} + +User.prototype.uuid = null; +User.prototype.email_address = null; +User.prototype.display_name = null; +User.prototype.password = null; +User.prototype.first_seen_date = null; +User.prototype.last_modified_date = null; +User.prototype.deleted = false; +User.prototype.check_password = function (pw, callback) { + bcrypt.compare(pw, this.password, callback); +}; +User.prototype.response_obj = function () { + return { + uuid: this.uuid, + email_address: this.email_address, + display_name: this.display_name, + first_seen_date: this.first_seen_date, + last_modified_date: this.last_modified_date + }; +}; + + + +exports.logged_in = function (req, res) { + var li = (req.session && req.session.logged_in_email_address); + helpers.send_success(res, { logged_in: li }); +}; + + +exports.register = function (req, res) { + async.waterfall([ + function (cb) { + var em = req.body.email_address; + if (!em || em.indexOf("@") == -1) + cb(helpers.invalid_email_address()); + else if (!req.body.display_name) + cb(helpers.missing_data("display_name")); + else if (!req.body.password) + cb(helpers.missing_data("password")); + else + cb(null); + }, + + // register da user. + function (cb) { + user_data.register( + req.body.email_address, + req.body.display_name, + req.body.password, + cb); + }, + + // mark user as logged in + function (user_data, cb) { + req.session.logged_in = true; + req.session.logged_in_email_address = req.body.email_address; + req.session.logged_in_date = new Date(); + cb(null, user_data); + } + + ], + function (err, user_data) { + if (err) { + helpers.send_failure(res, err); + } else { + var u = new User(user_data); + helpers.send_success(res, {user: u.response_obj() }); + } + }); +}; + + +exports.login = function (req, res) { + + async.waterfall([ + function (cb) { + var em = req.body.email_address + if (!em || em.indexOf('@') == -1) + cb(helpers.invalid_email_address()); + else if (req.session && req.session.logged_in_email_address + == em.toLowerCase()) + cb(helpers.error("already_logged_in", "")); + else if (!req.body.password) + cb(helpers.missing_data("password")); + else + cb(null); + }, + + // first get the user by the email address. + function (cb) { + user_data.user_by_email(req.body.email_address, cb); + }, + + // check the password + function (user_data, cb) { + var u = new User(user_data); + u.check_password(req.body.password, cb); + }, + + function (auth_ok, cb) { + if (!auth_ok) { + cb(helpers.auth_failed()); + return; + } + + req.session.logged_in = true; + req.session.logged_in_email_address = req.body.email_address; + req.session.logged_in_date = new Date(); + cb(null); + } + ], + function (err, results) { + if (!err || err.message == "already_logged_in") { + helpers.send_success(res, { logged_in: true }); + } else { + helpers.send_failure(res, err); + } + }); +}; + diff --git a/Chapter12/02_api_testing/app/local.config.js b/Chapter12/02_api_testing/app/local.config.js new file mode 100644 index 0000000..85e0a8d --- /dev/null +++ b/Chapter12/02_api_testing/app/local.config.js @@ -0,0 +1,16 @@ + + +exports.config = { + db_config: { + host: "localhost", + user: "root", + password: "", + database: "PhotoAlbums", + + pooled_connections: 125, + idle_timeout_millis: 30000 + }, + + static_content: "../static/" +}; + diff --git a/Chapter12/02_api_testing/app/package.json b/Chapter12/02_api_testing/app/package.json new file mode 100644 index 0000000..a6f903b --- /dev/null +++ b/Chapter12/02_api_testing/app/package.json @@ -0,0 +1,14 @@ +{ + "name": "MySQL-Demo", + "description": "Demonstrates Using MySQL Database connectivity", + "version": "0.0.1", + "private": true, + "dependencies": { + "express": "3.x", + "async": "0.1.x", + "generic-pool": "2.x", + "mysql": "2.x", + "bcrypt": "0.x", + "node-uuid": "1.x" + } +} diff --git a/Chapter12/02_api_testing/app/server.js b/Chapter12/02_api_testing/app/server.js new file mode 100644 index 0000000..d3cc515 --- /dev/null +++ b/Chapter12/02_api_testing/app/server.js @@ -0,0 +1,69 @@ + +var express = require('express'); +var app = express(); + +var db = require('./data/db.js'), + album_hdlr = require('./handlers/albums.js'), + page_hdlr = require('./handlers/pages.js'), + user_hdlr = require('./handlers/users.js'), + helpers = require('./handlers/helpers.js'); + +app.use(express.logger('dev')); +app.use(express.bodyParser({ keepExtensions: true })); +app.use(express.static(__dirname + "/../static")); +app.use(express.cookieParser("kitten on keyboard")); +app.use(express.cookieSession({ + maxAge: 86400000 +})); + +app.get('/v1/albums.json', album_hdlr.list_all); +app.put('/v1/albums.json', album_hdlr.create_album); +app.get('/v1/albums/:album_name.json', album_hdlr.album_by_name); + +app.get('/v1/albums/:album_name/photos.json', album_hdlr.photos_for_album); +app.put('/v1/albums/:album_name/photos.json', album_hdlr.add_photo_to_album); + +app.get('/pages/:page_name', page_hdlr.generate); +app.get('/pages/:page_name/:sub_page', requireLogin, page_hdlr.generate); + +app.put('/v1/users.json', user_hdlr.register); +app.post('/v1/users/login.json', user_hdlr.login); +app.get('/v1/users/logged_in.json', user_hdlr.logged_in); + + +app.get("/", function (req, res) { + res.redirect("/pages/home"); + res.end(); +}); + +app.get('*', four_oh_four); + +function four_oh_four(req, res) { + res.writeHead(404, { "Content-Type" : "application/json" }); + res.end(JSON.stringify(helpers.invalid_resource()) + "\n"); +} + + +function requireLogin(req, res, next) { + // all pages are always approved if you're logged in. + if (req.session && req.session.logged_in_email_address) + next(); // continue + else if (req.param.page_name == 'admin') { + res.redirect("/pages/login"); // force login for admin pages + res.end(); + } else + next(); // continue +} + + + +db.init(function (err, results) { + if (err) { + console.error("** FATAL ERROR ON STARTUP: "); + console.error(err); + process.exit(-1); + } + + app.listen(8080); +}); + diff --git a/Chapter12/02_api_testing/schema.sql b/Chapter12/02_api_testing/schema.sql new file mode 100644 index 0000000..61ab5c3 --- /dev/null +++ b/Chapter12/02_api_testing/schema.sql @@ -0,0 +1,53 @@ +DROP DATABASE IF EXISTS PhotoAlbums; + + +CREATE DATABASE PhotoAlbums + DEFAULT CHARACTER SET utf8 + DEFAULT COLLATE utf8_general_ci; + +USE PhotoAlbums; + + +CREATE TABLE Albums +( + name VARCHAR(50) UNIQUE PRIMARY KEY, + title VARCHAR(100), + date DATETIME, + description VARCHAR(500), + + -- allow for sorting on date. + INDEX(date) +) +ENGINE = InnoDB; + +CREATE TABLE Photos +( + album_name VARCHAR(50), + filename VARCHAR(50), + description VARCHAR(500), + date DATETIME, + + FOREIGN KEY (album_name) REFERENCES Albums (name), + INDEX (album_name, date) +) +ENGINE = InnoDB; + + +CREATE TABLE Users +( + user_uuid VARCHAR(50) UNIQUE PRIMARY KEY, + email_address VARCHAR(150) UNIQUE, + + display_name VARCHAR(100) UNIQUE, + password VARCHAR(100), + + first_seen_date BIGINT, + last_modified_date BIGINT, + deleted BOOL DEFAULT false, + + INDEX(email_address, deleted), + INDEX(user_uuid, deleted) +) +ENGINE = InnoDB; + + diff --git a/Chapter12/02_api_testing/static/content/#album.js# b/Chapter12/02_api_testing/static/content/#album.js# new file mode 100644 index 0000000..442c047 --- /dev/null +++ b/Chapter12/02_api_testing/static/content/#album.js# @@ -0,0 +1,60 @@ +$(function(){ + + var tmpl, // Main template HTML + tdata = {}; // JSON data object that feeds the template + + // Initialise page + var initPage = function() { + + // get our album name. + var re = "/pages/album/([a-zA-Z0-9_-]+)"; + var results = new RegExp(re).exec(window.location.href); + var album_name = results[1]; + + // Load the HTML template + $.get("/templates/album.html", function(d){ + tmpl = d; + }); + + var p = $.urlParam("page"); + var ps = $.urlParam("page_size"); + if (p < 0) p = 0; + if (ps <= 0) ps = 1000; + + var qs = "?page=" + p + "&page_size=" + ps; + var url = "/v1/albums/" + album_name + "/photos.json" + qs; + + // Retrieve the server data and then initialise the page + $.getJSON(url, function (d) { + var photo_d = massage_album(d); + $.extend(tdata, photo_d); + }); + + // When AJAX calls are complete parse the template + // replacing mustache tags with vars + $(document).ajaxStop(function () { + var renderedPage = Mustache.to_html( tmpl, tdata ); + $("body").html( renderedPage ); + }) + }(); +}); + + +function massage_album(d) { + if (d.error != null) return d; + var obj = { photos: [] }; + + var p = d.data.photos; + var a = d.data.album_data; + + for (var i = 0; i < p.length; i++) { + var url = "/albums/" + a.name + "/" + p[i].filename; + obj.photos.push({ url: url, desc: p[i].description }); + } + + if (obj.photos.length > 0) obj.has_photos = obj.photos.length; + return obj; +} + + +xundo \ No newline at end of file diff --git a/Chapter12/02_api_testing/static/content/admin_add_album.js b/Chapter12/02_api_testing/static/content/admin_add_album.js new file mode 100644 index 0000000..f2987d6 --- /dev/null +++ b/Chapter12/02_api_testing/static/content/admin_add_album.js @@ -0,0 +1,22 @@ +$(function(){ + + var tmpl, // Main template HTML + tdata = {}; // JSON data object that feeds the template + + // Initialise page + var initPage = function() { + + // Load the HTML template + $.get("/templates/admin_add_album.html", function(d){ + tmpl = d; + }); + + // When AJAX calls are complete parse the template + // replacing mustache tags with vars + $(document).ajaxStop(function () { + var renderedPage = Mustache.to_html( tmpl, tdata ); + $("body").html( renderedPage ); + }) + }(); +}); + diff --git a/Chapter12/02_api_testing/static/content/admin_add_photos.js b/Chapter12/02_api_testing/static/content/admin_add_photos.js new file mode 100644 index 0000000..350e536 --- /dev/null +++ b/Chapter12/02_api_testing/static/content/admin_add_photos.js @@ -0,0 +1,27 @@ +$(function(){ + + var tmpl, // Main template HTML + tdata = {}; // JSON data object that feeds the template + + // Initialise page + var initPage = function() { + + // Load the HTML template + $.get("/templates/admin_add_photos.html", function(d){ + tmpl = d; + }); + + // Retrieve the server data and then initialise the page + $.getJSON("/v1/albums.json", function (d) { + $.extend(tdata, d.data); + }); + + // When AJAX calls are complete parse the template + // replacing mustache tags with vars + $(document).ajaxStop(function () { + var renderedPage = Mustache.to_html( tmpl, tdata ); + $("body").html( renderedPage ); + }) + }(); +}); + diff --git a/Chapter12/02_api_testing/static/content/admin_home.js b/Chapter12/02_api_testing/static/content/admin_home.js new file mode 100644 index 0000000..65f31a2 --- /dev/null +++ b/Chapter12/02_api_testing/static/content/admin_home.js @@ -0,0 +1,27 @@ +$(function(){ + + var tmpl, // Main template HTML + tdata = {}; // JSON data object that feeds the template + + // Initialise page + var initPage = function() { + + // Load the HTML template + $.get("/templates/admin_home.html", function(d){ + tmpl = d; + }); + + // Retrieve the server data and then initialise the page +/* $.getJSON("/v1/albums.json", function (d) { + $.extend(tdata, d.data); + }); + */ + // When AJAX calls are complete parse the template + // replacing mustache tags with vars + $(document).ajaxStop(function () { + var renderedPage = Mustache.to_html( tmpl, tdata ); + $("body").html( renderedPage ); + }) + }(); +}); + diff --git a/Chapter12/02_api_testing/static/content/album.js b/Chapter12/02_api_testing/static/content/album.js new file mode 100644 index 0000000..c4d918e --- /dev/null +++ b/Chapter12/02_api_testing/static/content/album.js @@ -0,0 +1,67 @@ +$(function(){ + + var tmpl, // Main template HTML + tdata = {}; // JSON data object that feeds the template + + // Initialise page + var initPage = function() { + + // get our album name. + var re = "/pages/album/([a-zA-Z0-9_-]+)"; + var results = new RegExp(re).exec(window.location.href); + var album_name = results[1]; + + // Load the HTML template + $.get("/templates/album.html", function(d){ + tmpl = d; + }); + + var p = $.urlParam("page"); + var ps = $.urlParam("page_size"); + if (p < 0) p = 0; + if (ps <= 0) ps = 1000; + + var qs = "?page=" + p + "&page_size=" + ps; + var url = "/v1/albums/" + album_name + "/photos.json" + qs; + + // Retrieve the server data and then initialise the page + $.getJSON(url, function (d) { + var photo_d = massage_album(d); + $.extend(tdata, photo_d); + }); + + // When AJAX calls are complete parse the template + // replacing mustache tags with vars + $(document).ajaxStop(function () { + var renderedPage = Mustache.to_html( tmpl, tdata ); + $("body").html( renderedPage ); + }) + }(); +}); + + +function massage_album(d) { + if (d.error != null) return d; + var obj = { photos: [] }; + + var p = d.data.photos; + var a = d.data.album_data; + + for (var i = 0; i < p.length; i++) { + var url = "/albums/" + a.name + "/" + p[i].filename; + obj.photos.push({ url: url, desc: p[i].description }); + } + + if (obj.photos.length > 0) obj.has_photos = obj.photos.length; + return obj; +} + + +$.urlParam = function(name){ + var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href); + if (!results) + { + return 0; + } + return results[1] || 0; +} \ No newline at end of file diff --git a/Chapter12/02_api_testing/static/content/home.js b/Chapter12/02_api_testing/static/content/home.js new file mode 100644 index 0000000..fa7010b --- /dev/null +++ b/Chapter12/02_api_testing/static/content/home.js @@ -0,0 +1,28 @@ +$(function(){ + + var tmpl, // Main template HTML + tdata = {}; // JSON data object that feeds the template + + // Initialise page + var initPage = function() { + + // Load the HTML template + $.get("/templates/home.html", function(d){ + tmpl = d; + }); + + + // Retrieve the server data and then initialise the page + $.getJSON("/v1/albums.json", function (d) { + $.extend(tdata, d.data); + }); + + // When AJAX calls are complete parse the template + // replacing mustache tags with vars + $(document).ajaxStop(function () { + var renderedPage = Mustache.to_html( tmpl, tdata ); + $("body").html( renderedPage ); + }) + }(); +}); + diff --git a/Chapter12/02_api_testing/static/content/jquery-1.8.3.min.js b/Chapter12/02_api_testing/static/content/jquery-1.8.3.min.js new file mode 100644 index 0000000..83589da --- /dev/null +++ b/Chapter12/02_api_testing/static/content/jquery-1.8.3.min.js @@ -0,0 +1,2 @@ +/*! jQuery v1.8.3 jquery.com | jquery.org/license */ +(function(e,t){function _(e){var t=M[e]={};return v.each(e.split(y),function(e,n){t[n]=!0}),t}function H(e,n,r){if(r===t&&e.nodeType===1){var i="data-"+n.replace(P,"-$1").toLowerCase();r=e.getAttribute(i);if(typeof r=="string"){try{r=r==="true"?!0:r==="false"?!1:r==="null"?null:+r+""===r?+r:D.test(r)?v.parseJSON(r):r}catch(s){}v.data(e,n,r)}else r=t}return r}function B(e){var t;for(t in e){if(t==="data"&&v.isEmptyObject(e[t]))continue;if(t!=="toJSON")return!1}return!0}function et(){return!1}function tt(){return!0}function ut(e){return!e||!e.parentNode||e.parentNode.nodeType===11}function at(e,t){do e=e[t];while(e&&e.nodeType!==1);return e}function ft(e,t,n){t=t||0;if(v.isFunction(t))return v.grep(e,function(e,r){var i=!!t.call(e,r,e);return i===n});if(t.nodeType)return v.grep(e,function(e,r){return e===t===n});if(typeof t=="string"){var r=v.grep(e,function(e){return e.nodeType===1});if(it.test(t))return v.filter(t,r,!n);t=v.filter(t,r)}return v.grep(e,function(e,r){return v.inArray(e,t)>=0===n})}function lt(e){var t=ct.split("|"),n=e.createDocumentFragment();if(n.createElement)while(t.length)n.createElement(t.pop());return n}function Lt(e,t){return e.getElementsByTagName(t)[0]||e.appendChild(e.ownerDocument.createElement(t))}function At(e,t){if(t.nodeType!==1||!v.hasData(e))return;var n,r,i,s=v._data(e),o=v._data(t,s),u=s.events;if(u){delete o.handle,o.events={};for(n in u)for(r=0,i=u[n].length;r").appendTo(i.body),n=t.css("display");t.remove();if(n==="none"||n===""){Pt=i.body.appendChild(Pt||v.extend(i.createElement("iframe"),{frameBorder:0,width:0,height:0}));if(!Ht||!Pt.createElement)Ht=(Pt.contentWindow||Pt.contentDocument).document,Ht.write(""),Ht.close();t=Ht.body.appendChild(Ht.createElement(e)),n=Dt(t,"display"),i.body.removeChild(Pt)}return Wt[e]=n,n}function fn(e,t,n,r){var i;if(v.isArray(t))v.each(t,function(t,i){n||sn.test(e)?r(e,i):fn(e+"["+(typeof i=="object"?t:"")+"]",i,n,r)});else if(!n&&v.type(t)==="object")for(i in t)fn(e+"["+i+"]",t[i],n,r);else r(e,t)}function Cn(e){return function(t,n){typeof t!="string"&&(n=t,t="*");var r,i,s,o=t.toLowerCase().split(y),u=0,a=o.length;if(v.isFunction(n))for(;u)[^>]*$|#([\w\-]*)$)/,E=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,S=/^[\],:{}\s]*$/,x=/(?:^|:|,)(?:\s*\[)+/g,T=/\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,N=/"[^"\\\r\n]*"|true|false|null|-?(?:\d\d*\.|)\d+(?:[eE][\-+]?\d+|)/g,C=/^-ms-/,k=/-([\da-z])/gi,L=function(e,t){return(t+"").toUpperCase()},A=function(){i.addEventListener?(i.removeEventListener("DOMContentLoaded",A,!1),v.ready()):i.readyState==="complete"&&(i.detachEvent("onreadystatechange",A),v.ready())},O={};v.fn=v.prototype={constructor:v,init:function(e,n,r){var s,o,u,a;if(!e)return this;if(e.nodeType)return this.context=this[0]=e,this.length=1,this;if(typeof e=="string"){e.charAt(0)==="<"&&e.charAt(e.length-1)===">"&&e.length>=3?s=[null,e,null]:s=w.exec(e);if(s&&(s[1]||!n)){if(s[1])return n=n instanceof v?n[0]:n,a=n&&n.nodeType?n.ownerDocument||n:i,e=v.parseHTML(s[1],a,!0),E.test(s[1])&&v.isPlainObject(n)&&this.attr.call(e,n,!0),v.merge(this,e);o=i.getElementById(s[2]);if(o&&o.parentNode){if(o.id!==s[2])return r.find(e);this.length=1,this[0]=o}return this.context=i,this.selector=e,this}return!n||n.jquery?(n||r).find(e):this.constructor(n).find(e)}return v.isFunction(e)?r.ready(e):(e.selector!==t&&(this.selector=e.selector,this.context=e.context),v.makeArray(e,this))},selector:"",jquery:"1.8.3",length:0,size:function(){return this.length},toArray:function(){return l.call(this)},get:function(e){return e==null?this.toArray():e<0?this[this.length+e]:this[e]},pushStack:function(e,t,n){var r=v.merge(this.constructor(),e);return r.prevObject=this,r.context=this.context,t==="find"?r.selector=this.selector+(this.selector?" ":"")+n:t&&(r.selector=this.selector+"."+t+"("+n+")"),r},each:function(e,t){return v.each(this,e,t)},ready:function(e){return v.ready.promise().done(e),this},eq:function(e){return e=+e,e===-1?this.slice(e):this.slice(e,e+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(l.apply(this,arguments),"slice",l.call(arguments).join(","))},map:function(e){return this.pushStack(v.map(this,function(t,n){return e.call(t,n,t)}))},end:function(){return this.prevObject||this.constructor(null)},push:f,sort:[].sort,splice:[].splice},v.fn.init.prototype=v.fn,v.extend=v.fn.extend=function(){var e,n,r,i,s,o,u=arguments[0]||{},a=1,f=arguments.length,l=!1;typeof u=="boolean"&&(l=u,u=arguments[1]||{},a=2),typeof u!="object"&&!v.isFunction(u)&&(u={}),f===a&&(u=this,--a);for(;a0)return;r.resolveWith(i,[v]),v.fn.trigger&&v(i).trigger("ready").off("ready")},isFunction:function(e){return v.type(e)==="function"},isArray:Array.isArray||function(e){return v.type(e)==="array"},isWindow:function(e){return e!=null&&e==e.window},isNumeric:function(e){return!isNaN(parseFloat(e))&&isFinite(e)},type:function(e){return e==null?String(e):O[h.call(e)]||"object"},isPlainObject:function(e){if(!e||v.type(e)!=="object"||e.nodeType||v.isWindow(e))return!1;try{if(e.constructor&&!p.call(e,"constructor")&&!p.call(e.constructor.prototype,"isPrototypeOf"))return!1}catch(n){return!1}var r;for(r in e);return r===t||p.call(e,r)},isEmptyObject:function(e){var t;for(t in e)return!1;return!0},error:function(e){throw new Error(e)},parseHTML:function(e,t,n){var r;return!e||typeof e!="string"?null:(typeof t=="boolean"&&(n=t,t=0),t=t||i,(r=E.exec(e))?[t.createElement(r[1])]:(r=v.buildFragment([e],t,n?null:[]),v.merge([],(r.cacheable?v.clone(r.fragment):r.fragment).childNodes)))},parseJSON:function(t){if(!t||typeof t!="string")return null;t=v.trim(t);if(e.JSON&&e.JSON.parse)return e.JSON.parse(t);if(S.test(t.replace(T,"@").replace(N,"]").replace(x,"")))return(new Function("return "+t))();v.error("Invalid JSON: "+t)},parseXML:function(n){var r,i;if(!n||typeof n!="string")return null;try{e.DOMParser?(i=new DOMParser,r=i.parseFromString(n,"text/xml")):(r=new ActiveXObject("Microsoft.XMLDOM"),r.async="false",r.loadXML(n))}catch(s){r=t}return(!r||!r.documentElement||r.getElementsByTagName("parsererror").length)&&v.error("Invalid XML: "+n),r},noop:function(){},globalEval:function(t){t&&g.test(t)&&(e.execScript||function(t){e.eval.call(e,t)})(t)},camelCase:function(e){return e.replace(C,"ms-").replace(k,L)},nodeName:function(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()},each:function(e,n,r){var i,s=0,o=e.length,u=o===t||v.isFunction(e);if(r){if(u){for(i in e)if(n.apply(e[i],r)===!1)break}else for(;s0&&e[0]&&e[a-1]||a===0||v.isArray(e));if(f)for(;u-1)a.splice(n,1),i&&(n<=o&&o--,n<=u&&u--)}),this},has:function(e){return v.inArray(e,a)>-1},empty:function(){return a=[],this},disable:function(){return a=f=n=t,this},disabled:function(){return!a},lock:function(){return f=t,n||c.disable(),this},locked:function(){return!f},fireWith:function(e,t){return t=t||[],t=[e,t.slice?t.slice():t],a&&(!r||f)&&(i?f.push(t):l(t)),this},fire:function(){return c.fireWith(this,arguments),this},fired:function(){return!!r}};return c},v.extend({Deferred:function(e){var t=[["resolve","done",v.Callbacks("once memory"),"resolved"],["reject","fail",v.Callbacks("once memory"),"rejected"],["notify","progress",v.Callbacks("memory")]],n="pending",r={state:function(){return n},always:function(){return i.done(arguments).fail(arguments),this},then:function(){var e=arguments;return v.Deferred(function(n){v.each(t,function(t,r){var s=r[0],o=e[t];i[r[1]](v.isFunction(o)?function(){var e=o.apply(this,arguments);e&&v.isFunction(e.promise)?e.promise().done(n.resolve).fail(n.reject).progress(n.notify):n[s+"With"](this===i?n:this,[e])}:n[s])}),e=null}).promise()},promise:function(e){return e!=null?v.extend(e,r):r}},i={};return r.pipe=r.then,v.each(t,function(e,s){var o=s[2],u=s[3];r[s[1]]=o.add,u&&o.add(function(){n=u},t[e^1][2].disable,t[2][2].lock),i[s[0]]=o.fire,i[s[0]+"With"]=o.fireWith}),r.promise(i),e&&e.call(i,i),i},when:function(e){var t=0,n=l.call(arguments),r=n.length,i=r!==1||e&&v.isFunction(e.promise)?r:0,s=i===1?e:v.Deferred(),o=function(e,t,n){return function(r){t[e]=this,n[e]=arguments.length>1?l.call(arguments):r,n===u?s.notifyWith(t,n):--i||s.resolveWith(t,n)}},u,a,f;if(r>1){u=new Array(r),a=new Array(r),f=new Array(r);for(;t
a",n=p.getElementsByTagName("*"),r=p.getElementsByTagName("a")[0];if(!n||!r||!n.length)return{};s=i.createElement("select"),o=s.appendChild(i.createElement("option")),u=p.getElementsByTagName("input")[0],r.style.cssText="top:1px;float:left;opacity:.5",t={leadingWhitespace:p.firstChild.nodeType===3,tbody:!p.getElementsByTagName("tbody").length,htmlSerialize:!!p.getElementsByTagName("link").length,style:/top/.test(r.getAttribute("style")),hrefNormalized:r.getAttribute("href")==="/a",opacity:/^0.5/.test(r.style.opacity),cssFloat:!!r.style.cssFloat,checkOn:u.value==="on",optSelected:o.selected,getSetAttribute:p.className!=="t",enctype:!!i.createElement("form").enctype,html5Clone:i.createElement("nav").cloneNode(!0).outerHTML!=="<:nav>",boxModel:i.compatMode==="CSS1Compat",submitBubbles:!0,changeBubbles:!0,focusinBubbles:!1,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0,boxSizingReliable:!0,pixelPosition:!1},u.checked=!0,t.noCloneChecked=u.cloneNode(!0).checked,s.disabled=!0,t.optDisabled=!o.disabled;try{delete p.test}catch(d){t.deleteExpando=!1}!p.addEventListener&&p.attachEvent&&p.fireEvent&&(p.attachEvent("onclick",h=function(){t.noCloneEvent=!1}),p.cloneNode(!0).fireEvent("onclick"),p.detachEvent("onclick",h)),u=i.createElement("input"),u.value="t",u.setAttribute("type","radio"),t.radioValue=u.value==="t",u.setAttribute("checked","checked"),u.setAttribute("name","t"),p.appendChild(u),a=i.createDocumentFragment(),a.appendChild(p.lastChild),t.checkClone=a.cloneNode(!0).cloneNode(!0).lastChild.checked,t.appendChecked=u.checked,a.removeChild(u),a.appendChild(p);if(p.attachEvent)for(l in{submit:!0,change:!0,focusin:!0})f="on"+l,c=f in p,c||(p.setAttribute(f,"return;"),c=typeof p[f]=="function"),t[l+"Bubbles"]=c;return v(function(){var n,r,s,o,u="padding:0;margin:0;border:0;display:block;overflow:hidden;",a=i.getElementsByTagName("body")[0];if(!a)return;n=i.createElement("div"),n.style.cssText="visibility:hidden;border:0;width:0;height:0;position:static;top:0;margin-top:1px",a.insertBefore(n,a.firstChild),r=i.createElement("div"),n.appendChild(r),r.innerHTML="
t
",s=r.getElementsByTagName("td"),s[0].style.cssText="padding:0;margin:0;border:0;display:none",c=s[0].offsetHeight===0,s[0].style.display="",s[1].style.display="none",t.reliableHiddenOffsets=c&&s[0].offsetHeight===0,r.innerHTML="",r.style.cssText="box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;",t.boxSizing=r.offsetWidth===4,t.doesNotIncludeMarginInBodyOffset=a.offsetTop!==1,e.getComputedStyle&&(t.pixelPosition=(e.getComputedStyle(r,null)||{}).top!=="1%",t.boxSizingReliable=(e.getComputedStyle(r,null)||{width:"4px"}).width==="4px",o=i.createElement("div"),o.style.cssText=r.style.cssText=u,o.style.marginRight=o.style.width="0",r.style.width="1px",r.appendChild(o),t.reliableMarginRight=!parseFloat((e.getComputedStyle(o,null)||{}).marginRight)),typeof r.style.zoom!="undefined"&&(r.innerHTML="",r.style.cssText=u+"width:1px;padding:1px;display:inline;zoom:1",t.inlineBlockNeedsLayout=r.offsetWidth===3,r.style.display="block",r.style.overflow="visible",r.innerHTML="
",r.firstChild.style.width="5px",t.shrinkWrapBlocks=r.offsetWidth!==3,n.style.zoom=1),a.removeChild(n),n=r=s=o=null}),a.removeChild(p),n=r=s=o=u=a=p=null,t}();var D=/(?:\{[\s\S]*\}|\[[\s\S]*\])$/,P=/([A-Z])/g;v.extend({cache:{},deletedIds:[],uuid:0,expando:"jQuery"+(v.fn.jquery+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(e){return e=e.nodeType?v.cache[e[v.expando]]:e[v.expando],!!e&&!B(e)},data:function(e,n,r,i){if(!v.acceptData(e))return;var s,o,u=v.expando,a=typeof n=="string",f=e.nodeType,l=f?v.cache:e,c=f?e[u]:e[u]&&u;if((!c||!l[c]||!i&&!l[c].data)&&a&&r===t)return;c||(f?e[u]=c=v.deletedIds.pop()||v.guid++:c=u),l[c]||(l[c]={},f||(l[c].toJSON=v.noop));if(typeof n=="object"||typeof n=="function")i?l[c]=v.extend(l[c],n):l[c].data=v.extend(l[c].data,n);return s=l[c],i||(s.data||(s.data={}),s=s.data),r!==t&&(s[v.camelCase(n)]=r),a?(o=s[n],o==null&&(o=s[v.camelCase(n)])):o=s,o},removeData:function(e,t,n){if(!v.acceptData(e))return;var r,i,s,o=e.nodeType,u=o?v.cache:e,a=o?e[v.expando]:v.expando;if(!u[a])return;if(t){r=n?u[a]:u[a].data;if(r){v.isArray(t)||(t in r?t=[t]:(t=v.camelCase(t),t in r?t=[t]:t=t.split(" ")));for(i=0,s=t.length;i1,null,!1))},removeData:function(e){return this.each(function(){v.removeData(this,e)})}}),v.extend({queue:function(e,t,n){var r;if(e)return t=(t||"fx")+"queue",r=v._data(e,t),n&&(!r||v.isArray(n)?r=v._data(e,t,v.makeArray(n)):r.push(n)),r||[]},dequeue:function(e,t){t=t||"fx";var n=v.queue(e,t),r=n.length,i=n.shift(),s=v._queueHooks(e,t),o=function(){v.dequeue(e,t)};i==="inprogress"&&(i=n.shift(),r--),i&&(t==="fx"&&n.unshift("inprogress"),delete s.stop,i.call(e,o,s)),!r&&s&&s.empty.fire()},_queueHooks:function(e,t){var n=t+"queueHooks";return v._data(e,n)||v._data(e,n,{empty:v.Callbacks("once memory").add(function(){v.removeData(e,t+"queue",!0),v.removeData(e,n,!0)})})}}),v.fn.extend({queue:function(e,n){var r=2;return typeof e!="string"&&(n=e,e="fx",r--),arguments.length1)},removeAttr:function(e){return this.each(function(){v.removeAttr(this,e)})},prop:function(e,t){return v.access(this,v.prop,e,t,arguments.length>1)},removeProp:function(e){return e=v.propFix[e]||e,this.each(function(){try{this[e]=t,delete this[e]}catch(n){}})},addClass:function(e){var t,n,r,i,s,o,u;if(v.isFunction(e))return this.each(function(t){v(this).addClass(e.call(this,t,this.className))});if(e&&typeof e=="string"){t=e.split(y);for(n=0,r=this.length;n=0)r=r.replace(" "+n[s]+" "," ");i.className=e?v.trim(r):""}}}return this},toggleClass:function(e,t){var n=typeof e,r=typeof t=="boolean";return v.isFunction(e)?this.each(function(n){v(this).toggleClass(e.call(this,n,this.className,t),t)}):this.each(function(){if(n==="string"){var i,s=0,o=v(this),u=t,a=e.split(y);while(i=a[s++])u=r?u:!o.hasClass(i),o[u?"addClass":"removeClass"](i)}else if(n==="undefined"||n==="boolean")this.className&&v._data(this,"__className__",this.className),this.className=this.className||e===!1?"":v._data(this,"__className__")||""})},hasClass:function(e){var t=" "+e+" ",n=0,r=this.length;for(;n=0)return!0;return!1},val:function(e){var n,r,i,s=this[0];if(!arguments.length){if(s)return n=v.valHooks[s.type]||v.valHooks[s.nodeName.toLowerCase()],n&&"get"in n&&(r=n.get(s,"value"))!==t?r:(r=s.value,typeof r=="string"?r.replace(R,""):r==null?"":r);return}return i=v.isFunction(e),this.each(function(r){var s,o=v(this);if(this.nodeType!==1)return;i?s=e.call(this,r,o.val()):s=e,s==null?s="":typeof s=="number"?s+="":v.isArray(s)&&(s=v.map(s,function(e){return e==null?"":e+""})),n=v.valHooks[this.type]||v.valHooks[this.nodeName.toLowerCase()];if(!n||!("set"in n)||n.set(this,s,"value")===t)this.value=s})}}),v.extend({valHooks:{option:{get:function(e){var t=e.attributes.value;return!t||t.specified?e.value:e.text}},select:{get:function(e){var t,n,r=e.options,i=e.selectedIndex,s=e.type==="select-one"||i<0,o=s?null:[],u=s?i+1:r.length,a=i<0?u:s?i:0;for(;a=0}),n.length||(e.selectedIndex=-1),n}}},attrFn:{},attr:function(e,n,r,i){var s,o,u,a=e.nodeType;if(!e||a===3||a===8||a===2)return;if(i&&v.isFunction(v.fn[n]))return v(e)[n](r);if(typeof e.getAttribute=="undefined")return v.prop(e,n,r);u=a!==1||!v.isXMLDoc(e),u&&(n=n.toLowerCase(),o=v.attrHooks[n]||(X.test(n)?F:j));if(r!==t){if(r===null){v.removeAttr(e,n);return}return o&&"set"in o&&u&&(s=o.set(e,r,n))!==t?s:(e.setAttribute(n,r+""),r)}return o&&"get"in o&&u&&(s=o.get(e,n))!==null?s:(s=e.getAttribute(n),s===null?t:s)},removeAttr:function(e,t){var n,r,i,s,o=0;if(t&&e.nodeType===1){r=t.split(y);for(;o=0}})});var $=/^(?:textarea|input|select)$/i,J=/^([^\.]*|)(?:\.(.+)|)$/,K=/(?:^|\s)hover(\.\S+|)\b/,Q=/^key/,G=/^(?:mouse|contextmenu)|click/,Y=/^(?:focusinfocus|focusoutblur)$/,Z=function(e){return v.event.special.hover?e:e.replace(K,"mouseenter$1 mouseleave$1")};v.event={add:function(e,n,r,i,s){var o,u,a,f,l,c,h,p,d,m,g;if(e.nodeType===3||e.nodeType===8||!n||!r||!(o=v._data(e)))return;r.handler&&(d=r,r=d.handler,s=d.selector),r.guid||(r.guid=v.guid++),a=o.events,a||(o.events=a={}),u=o.handle,u||(o.handle=u=function(e){return typeof v=="undefined"||!!e&&v.event.triggered===e.type?t:v.event.dispatch.apply(u.elem,arguments)},u.elem=e),n=v.trim(Z(n)).split(" ");for(f=0;f=0&&(y=y.slice(0,-1),a=!0),y.indexOf(".")>=0&&(b=y.split("."),y=b.shift(),b.sort());if((!s||v.event.customEvent[y])&&!v.event.global[y])return;n=typeof n=="object"?n[v.expando]?n:new v.Event(y,n):new v.Event(y),n.type=y,n.isTrigger=!0,n.exclusive=a,n.namespace=b.join("."),n.namespace_re=n.namespace?new RegExp("(^|\\.)"+b.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,h=y.indexOf(":")<0?"on"+y:"";if(!s){u=v.cache;for(f in u)u[f].events&&u[f].events[y]&&v.event.trigger(n,r,u[f].handle.elem,!0);return}n.result=t,n.target||(n.target=s),r=r!=null?v.makeArray(r):[],r.unshift(n),p=v.event.special[y]||{};if(p.trigger&&p.trigger.apply(s,r)===!1)return;m=[[s,p.bindType||y]];if(!o&&!p.noBubble&&!v.isWindow(s)){g=p.delegateType||y,l=Y.test(g+y)?s:s.parentNode;for(c=s;l;l=l.parentNode)m.push([l,g]),c=l;c===(s.ownerDocument||i)&&m.push([c.defaultView||c.parentWindow||e,g])}for(f=0;f=0:v.find(h,this,null,[s]).length),u[h]&&f.push(c);f.length&&w.push({elem:s,matches:f})}d.length>m&&w.push({elem:this,matches:d.slice(m)});for(r=0;r0?this.on(t,null,e,n):this.trigger(t)},Q.test(t)&&(v.event.fixHooks[t]=v.event.keyHooks),G.test(t)&&(v.event.fixHooks[t]=v.event.mouseHooks)}),function(e,t){function nt(e,t,n,r){n=n||[],t=t||g;var i,s,a,f,l=t.nodeType;if(!e||typeof e!="string")return n;if(l!==1&&l!==9)return[];a=o(t);if(!a&&!r)if(i=R.exec(e))if(f=i[1]){if(l===9){s=t.getElementById(f);if(!s||!s.parentNode)return n;if(s.id===f)return n.push(s),n}else if(t.ownerDocument&&(s=t.ownerDocument.getElementById(f))&&u(t,s)&&s.id===f)return n.push(s),n}else{if(i[2])return S.apply(n,x.call(t.getElementsByTagName(e),0)),n;if((f=i[3])&&Z&&t.getElementsByClassName)return S.apply(n,x.call(t.getElementsByClassName(f),0)),n}return vt(e.replace(j,"$1"),t,n,r,a)}function rt(e){return function(t){var n=t.nodeName.toLowerCase();return n==="input"&&t.type===e}}function it(e){return function(t){var n=t.nodeName.toLowerCase();return(n==="input"||n==="button")&&t.type===e}}function st(e){return N(function(t){return t=+t,N(function(n,r){var i,s=e([],n.length,t),o=s.length;while(o--)n[i=s[o]]&&(n[i]=!(r[i]=n[i]))})})}function ot(e,t,n){if(e===t)return n;var r=e.nextSibling;while(r){if(r===t)return-1;r=r.nextSibling}return 1}function ut(e,t){var n,r,s,o,u,a,f,l=L[d][e+" "];if(l)return t?0:l.slice(0);u=e,a=[],f=i.preFilter;while(u){if(!n||(r=F.exec(u)))r&&(u=u.slice(r[0].length)||u),a.push(s=[]);n=!1;if(r=I.exec(u))s.push(n=new m(r.shift())),u=u.slice(n.length),n.type=r[0].replace(j," ");for(o in i.filter)(r=J[o].exec(u))&&(!f[o]||(r=f[o](r)))&&(s.push(n=new m(r.shift())),u=u.slice(n.length),n.type=o,n.matches=r);if(!n)break}return t?u.length:u?nt.error(e):L(e,a).slice(0)}function at(e,t,r){var i=t.dir,s=r&&t.dir==="parentNode",o=w++;return t.first?function(t,n,r){while(t=t[i])if(s||t.nodeType===1)return e(t,n,r)}:function(t,r,u){if(!u){var a,f=b+" "+o+" ",l=f+n;while(t=t[i])if(s||t.nodeType===1){if((a=t[d])===l)return t.sizset;if(typeof a=="string"&&a.indexOf(f)===0){if(t.sizset)return t}else{t[d]=l;if(e(t,r,u))return t.sizset=!0,t;t.sizset=!1}}}else while(t=t[i])if(s||t.nodeType===1)if(e(t,r,u))return t}}function ft(e){return e.length>1?function(t,n,r){var i=e.length;while(i--)if(!e[i](t,n,r))return!1;return!0}:e[0]}function lt(e,t,n,r,i){var s,o=[],u=0,a=e.length,f=t!=null;for(;u-1&&(s[f]=!(o[f]=c))}}else g=lt(g===o?g.splice(d,g.length):g),i?i(null,o,g,a):S.apply(o,g)})}function ht(e){var t,n,r,s=e.length,o=i.relative[e[0].type],u=o||i.relative[" "],a=o?1:0,f=at(function(e){return e===t},u,!0),l=at(function(e){return T.call(t,e)>-1},u,!0),h=[function(e,n,r){return!o&&(r||n!==c)||((t=n).nodeType?f(e,n,r):l(e,n,r))}];for(;a1&&ft(h),a>1&&e.slice(0,a-1).join("").replace(j,"$1"),n,a0,s=e.length>0,o=function(u,a,f,l,h){var p,d,v,m=[],y=0,w="0",x=u&&[],T=h!=null,N=c,C=u||s&&i.find.TAG("*",h&&a.parentNode||a),k=b+=N==null?1:Math.E;T&&(c=a!==g&&a,n=o.el);for(;(p=C[w])!=null;w++){if(s&&p){for(d=0;v=e[d];d++)if(v(p,a,f)){l.push(p);break}T&&(b=k,n=++o.el)}r&&((p=!v&&p)&&y--,u&&x.push(p))}y+=w;if(r&&w!==y){for(d=0;v=t[d];d++)v(x,m,a,f);if(u){if(y>0)while(w--)!x[w]&&!m[w]&&(m[w]=E.call(l));m=lt(m)}S.apply(l,m),T&&!u&&m.length>0&&y+t.length>1&&nt.uniqueSort(l)}return T&&(b=k,c=N),x};return o.el=0,r?N(o):o}function dt(e,t,n){var r=0,i=t.length;for(;r2&&(f=u[0]).type==="ID"&&t.nodeType===9&&!s&&i.relative[u[1].type]){t=i.find.ID(f.matches[0].replace($,""),t,s)[0];if(!t)return n;e=e.slice(u.shift().length)}for(o=J.POS.test(e)?-1:u.length-1;o>=0;o--){f=u[o];if(i.relative[l=f.type])break;if(c=i.find[l])if(r=c(f.matches[0].replace($,""),z.test(u[0].type)&&t.parentNode||t,s)){u.splice(o,1),e=r.length&&u.join("");if(!e)return S.apply(n,x.call(r,0)),n;break}}}return a(e,h)(r,t,s,n,z.test(e)),n}function mt(){}var n,r,i,s,o,u,a,f,l,c,h=!0,p="undefined",d=("sizcache"+Math.random()).replace(".",""),m=String,g=e.document,y=g.documentElement,b=0,w=0,E=[].pop,S=[].push,x=[].slice,T=[].indexOf||function(e){var t=0,n=this.length;for(;ti.cacheLength&&delete e[t.shift()],e[n+" "]=r},e)},k=C(),L=C(),A=C(),O="[\\x20\\t\\r\\n\\f]",M="(?:\\\\.|[-\\w]|[^\\x00-\\xa0])+",_=M.replace("w","w#"),D="([*^$|!~]?=)",P="\\["+O+"*("+M+")"+O+"*(?:"+D+O+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+_+")|)|)"+O+"*\\]",H=":("+M+")(?:\\((?:(['\"])((?:\\\\.|[^\\\\])*?)\\2|([^()[\\]]*|(?:(?:"+P+")|[^:]|\\\\.)*|.*))\\)|)",B=":(even|odd|eq|gt|lt|nth|first|last)(?:\\("+O+"*((?:-\\d)?\\d*)"+O+"*\\)|)(?=[^-]|$)",j=new RegExp("^"+O+"+|((?:^|[^\\\\])(?:\\\\.)*)"+O+"+$","g"),F=new RegExp("^"+O+"*,"+O+"*"),I=new RegExp("^"+O+"*([\\x20\\t\\r\\n\\f>+~])"+O+"*"),q=new RegExp(H),R=/^(?:#([\w\-]+)|(\w+)|\.([\w\-]+))$/,U=/^:not/,z=/[\x20\t\r\n\f]*[+~]/,W=/:not\($/,X=/h\d/i,V=/input|select|textarea|button/i,$=/\\(?!\\)/g,J={ID:new RegExp("^#("+M+")"),CLASS:new RegExp("^\\.("+M+")"),NAME:new RegExp("^\\[name=['\"]?("+M+")['\"]?\\]"),TAG:new RegExp("^("+M.replace("w","w*")+")"),ATTR:new RegExp("^"+P),PSEUDO:new RegExp("^"+H),POS:new RegExp(B,"i"),CHILD:new RegExp("^:(only|nth|first|last)-child(?:\\("+O+"*(even|odd|(([+-]|)(\\d*)n|)"+O+"*(?:([+-]|)"+O+"*(\\d+)|))"+O+"*\\)|)","i"),needsContext:new RegExp("^"+O+"*[>+~]|"+B,"i")},K=function(e){var t=g.createElement("div");try{return e(t)}catch(n){return!1}finally{t=null}},Q=K(function(e){return e.appendChild(g.createComment("")),!e.getElementsByTagName("*").length}),G=K(function(e){return e.innerHTML="",e.firstChild&&typeof e.firstChild.getAttribute!==p&&e.firstChild.getAttribute("href")==="#"}),Y=K(function(e){e.innerHTML="";var t=typeof e.lastChild.getAttribute("multiple");return t!=="boolean"&&t!=="string"}),Z=K(function(e){return e.innerHTML="",!e.getElementsByClassName||!e.getElementsByClassName("e").length?!1:(e.lastChild.className="e",e.getElementsByClassName("e").length===2)}),et=K(function(e){e.id=d+0,e.innerHTML="
",y.insertBefore(e,y.firstChild);var t=g.getElementsByName&&g.getElementsByName(d).length===2+g.getElementsByName(d+0).length;return r=!g.getElementById(d),y.removeChild(e),t});try{x.call(y.childNodes,0)[0].nodeType}catch(tt){x=function(e){var t,n=[];for(;t=this[e];e++)n.push(t);return n}}nt.matches=function(e,t){return nt(e,null,null,t)},nt.matchesSelector=function(e,t){return nt(t,null,null,[e]).length>0},s=nt.getText=function(e){var t,n="",r=0,i=e.nodeType;if(i){if(i===1||i===9||i===11){if(typeof e.textContent=="string")return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=s(e)}else if(i===3||i===4)return e.nodeValue}else for(;t=e[r];r++)n+=s(t);return n},o=nt.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return t?t.nodeName!=="HTML":!1},u=nt.contains=y.contains?function(e,t){var n=e.nodeType===9?e.documentElement:e,r=t&&t.parentNode;return e===r||!!(r&&r.nodeType===1&&n.contains&&n.contains(r))}:y.compareDocumentPosition?function(e,t){return t&&!!(e.compareDocumentPosition(t)&16)}:function(e,t){while(t=t.parentNode)if(t===e)return!0;return!1},nt.attr=function(e,t){var n,r=o(e);return r||(t=t.toLowerCase()),(n=i.attrHandle[t])?n(e):r||Y?e.getAttribute(t):(n=e.getAttributeNode(t),n?typeof e[t]=="boolean"?e[t]?t:null:n.specified?n.value:null:null)},i=nt.selectors={cacheLength:50,createPseudo:N,match:J,attrHandle:G?{}:{href:function(e){return e.getAttribute("href",2)},type:function(e){return e.getAttribute("type")}},find:{ID:r?function(e,t,n){if(typeof t.getElementById!==p&&!n){var r=t.getElementById(e);return r&&r.parentNode?[r]:[]}}:function(e,n,r){if(typeof n.getElementById!==p&&!r){var i=n.getElementById(e);return i?i.id===e||typeof i.getAttributeNode!==p&&i.getAttributeNode("id").value===e?[i]:t:[]}},TAG:Q?function(e,t){if(typeof t.getElementsByTagName!==p)return t.getElementsByTagName(e)}:function(e,t){var n=t.getElementsByTagName(e);if(e==="*"){var r,i=[],s=0;for(;r=n[s];s++)r.nodeType===1&&i.push(r);return i}return n},NAME:et&&function(e,t){if(typeof t.getElementsByName!==p)return t.getElementsByName(name)},CLASS:Z&&function(e,t,n){if(typeof t.getElementsByClassName!==p&&!n)return t.getElementsByClassName(e)}},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace($,""),e[3]=(e[4]||e[5]||"").replace($,""),e[2]==="~="&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),e[1]==="nth"?(e[2]||nt.error(e[0]),e[3]=+(e[3]?e[4]+(e[5]||1):2*(e[2]==="even"||e[2]==="odd")),e[4]=+(e[6]+e[7]||e[2]==="odd")):e[2]&&nt.error(e[0]),e},PSEUDO:function(e){var t,n;if(J.CHILD.test(e[0]))return null;if(e[3])e[2]=e[3];else if(t=e[4])q.test(t)&&(n=ut(t,!0))&&(n=t.indexOf(")",t.length-n)-t.length)&&(t=t.slice(0,n),e[0]=e[0].slice(0,n)),e[2]=t;return e.slice(0,3)}},filter:{ID:r?function(e){return e=e.replace($,""),function(t){return t.getAttribute("id")===e}}:function(e){return e=e.replace($,""),function(t){var n=typeof t.getAttributeNode!==p&&t.getAttributeNode("id");return n&&n.value===e}},TAG:function(e){return e==="*"?function(){return!0}:(e=e.replace($,"").toLowerCase(),function(t){return t.nodeName&&t.nodeName.toLowerCase()===e})},CLASS:function(e){var t=k[d][e+" "];return t||(t=new RegExp("(^|"+O+")"+e+"("+O+"|$)"))&&k(e,function(e){return t.test(e.className||typeof e.getAttribute!==p&&e.getAttribute("class")||"")})},ATTR:function(e,t,n){return function(r,i){var s=nt.attr(r,e);return s==null?t==="!=":t?(s+="",t==="="?s===n:t==="!="?s!==n:t==="^="?n&&s.indexOf(n)===0:t==="*="?n&&s.indexOf(n)>-1:t==="$="?n&&s.substr(s.length-n.length)===n:t==="~="?(" "+s+" ").indexOf(n)>-1:t==="|="?s===n||s.substr(0,n.length+1)===n+"-":!1):!0}},CHILD:function(e,t,n,r){return e==="nth"?function(e){var t,i,s=e.parentNode;if(n===1&&r===0)return!0;if(s){i=0;for(t=s.firstChild;t;t=t.nextSibling)if(t.nodeType===1){i++;if(e===t)break}}return i-=r,i===n||i%n===0&&i/n>=0}:function(t){var n=t;switch(e){case"only":case"first":while(n=n.previousSibling)if(n.nodeType===1)return!1;if(e==="first")return!0;n=t;case"last":while(n=n.nextSibling)if(n.nodeType===1)return!1;return!0}}},PSEUDO:function(e,t){var n,r=i.pseudos[e]||i.setFilters[e.toLowerCase()]||nt.error("unsupported pseudo: "+e);return r[d]?r(t):r.length>1?(n=[e,e,"",t],i.setFilters.hasOwnProperty(e.toLowerCase())?N(function(e,n){var i,s=r(e,t),o=s.length;while(o--)i=T.call(e,s[o]),e[i]=!(n[i]=s[o])}):function(e){return r(e,0,n)}):r}},pseudos:{not:N(function(e){var t=[],n=[],r=a(e.replace(j,"$1"));return r[d]?N(function(e,t,n,i){var s,o=r(e,null,i,[]),u=e.length;while(u--)if(s=o[u])e[u]=!(t[u]=s)}):function(e,i,s){return t[0]=e,r(t,null,s,n),!n.pop()}}),has:N(function(e){return function(t){return nt(e,t).length>0}}),contains:N(function(e){return function(t){return(t.textContent||t.innerText||s(t)).indexOf(e)>-1}}),enabled:function(e){return e.disabled===!1},disabled:function(e){return e.disabled===!0},checked:function(e){var t=e.nodeName.toLowerCase();return t==="input"&&!!e.checked||t==="option"&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,e.selected===!0},parent:function(e){return!i.pseudos.empty(e)},empty:function(e){var t;e=e.firstChild;while(e){if(e.nodeName>"@"||(t=e.nodeType)===3||t===4)return!1;e=e.nextSibling}return!0},header:function(e){return X.test(e.nodeName)},text:function(e){var t,n;return e.nodeName.toLowerCase()==="input"&&(t=e.type)==="text"&&((n=e.getAttribute("type"))==null||n.toLowerCase()===t)},radio:rt("radio"),checkbox:rt("checkbox"),file:rt("file"),password:rt("password"),image:rt("image"),submit:it("submit"),reset:it("reset"),button:function(e){var t=e.nodeName.toLowerCase();return t==="input"&&e.type==="button"||t==="button"},input:function(e){return V.test(e.nodeName)},focus:function(e){var t=e.ownerDocument;return e===t.activeElement&&(!t.hasFocus||t.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},active:function(e){return e===e.ownerDocument.activeElement},first:st(function(){return[0]}),last:st(function(e,t){return[t-1]}),eq:st(function(e,t,n){return[n<0?n+t:n]}),even:st(function(e,t){for(var n=0;n=0;)e.push(r);return e}),gt:st(function(e,t,n){for(var r=n<0?n+t:n;++r",e.querySelectorAll("[selected]").length||i.push("\\["+O+"*(?:checked|disabled|ismap|multiple|readonly|selected|value)"),e.querySelectorAll(":checked").length||i.push(":checked")}),K(function(e){e.innerHTML="

",e.querySelectorAll("[test^='']").length&&i.push("[*^$]="+O+"*(?:\"\"|'')"),e.innerHTML="",e.querySelectorAll(":enabled").length||i.push(":enabled",":disabled")}),i=new RegExp(i.join("|")),vt=function(e,r,s,o,u){if(!o&&!u&&!i.test(e)){var a,f,l=!0,c=d,h=r,p=r.nodeType===9&&e;if(r.nodeType===1&&r.nodeName.toLowerCase()!=="object"){a=ut(e),(l=r.getAttribute("id"))?c=l.replace(n,"\\$&"):r.setAttribute("id",c),c="[id='"+c+"'] ",f=a.length;while(f--)a[f]=c+a[f].join("");h=z.test(e)&&r.parentNode||r,p=a.join(",")}if(p)try{return S.apply(s,x.call(h.querySelectorAll(p),0)),s}catch(v){}finally{l||r.removeAttribute("id")}}return t(e,r,s,o,u)},u&&(K(function(t){e=u.call(t,"div");try{u.call(t,"[test!='']:sizzle"),s.push("!=",H)}catch(n){}}),s=new RegExp(s.join("|")),nt.matchesSelector=function(t,n){n=n.replace(r,"='$1']");if(!o(t)&&!s.test(n)&&!i.test(n))try{var a=u.call(t,n);if(a||e||t.document&&t.document.nodeType!==11)return a}catch(f){}return nt(n,null,null,[t]).length>0})}(),i.pseudos.nth=i.pseudos.eq,i.filters=mt.prototype=i.pseudos,i.setFilters=new mt,nt.attr=v.attr,v.find=nt,v.expr=nt.selectors,v.expr[":"]=v.expr.pseudos,v.unique=nt.uniqueSort,v.text=nt.getText,v.isXMLDoc=nt.isXML,v.contains=nt.contains}(e);var nt=/Until$/,rt=/^(?:parents|prev(?:Until|All))/,it=/^.[^:#\[\.,]*$/,st=v.expr.match.needsContext,ot={children:!0,contents:!0,next:!0,prev:!0};v.fn.extend({find:function(e){var t,n,r,i,s,o,u=this;if(typeof e!="string")return v(e).filter(function(){for(t=0,n=u.length;t0)for(i=r;i=0:v.filter(e,this).length>0:this.filter(e).length>0)},closest:function(e,t){var n,r=0,i=this.length,s=[],o=st.test(e)||typeof e!="string"?v(e,t||this.context):0;for(;r-1:v.find.matchesSelector(n,e)){s.push(n);break}n=n.parentNode}}return s=s.length>1?v.unique(s):s,this.pushStack(s,"closest",e)},index:function(e){return e?typeof e=="string"?v.inArray(this[0],v(e)):v.inArray(e.jquery?e[0]:e,this):this[0]&&this[0].parentNode?this.prevAll().length:-1},add:function(e,t){var n=typeof e=="string"?v(e,t):v.makeArray(e&&e.nodeType?[e]:e),r=v.merge(this.get(),n);return this.pushStack(ut(n[0])||ut(r[0])?r:v.unique(r))},addBack:function(e){return this.add(e==null?this.prevObject:this.prevObject.filter(e))}}),v.fn.andSelf=v.fn.addBack,v.each({parent:function(e){var t=e.parentNode;return t&&t.nodeType!==11?t:null},parents:function(e){return v.dir(e,"parentNode")},parentsUntil:function(e,t,n){return v.dir(e,"parentNode",n)},next:function(e){return at(e,"nextSibling")},prev:function(e){return at(e,"previousSibling")},nextAll:function(e){return v.dir(e,"nextSibling")},prevAll:function(e){return v.dir(e,"previousSibling")},nextUntil:function(e,t,n){return v.dir(e,"nextSibling",n)},prevUntil:function(e,t,n){return v.dir(e,"previousSibling",n)},siblings:function(e){return v.sibling((e.parentNode||{}).firstChild,e)},children:function(e){return v.sibling(e.firstChild)},contents:function(e){return v.nodeName(e,"iframe")?e.contentDocument||e.contentWindow.document:v.merge([],e.childNodes)}},function(e,t){v.fn[e]=function(n,r){var i=v.map(this,t,n);return nt.test(e)||(r=n),r&&typeof r=="string"&&(i=v.filter(r,i)),i=this.length>1&&!ot[e]?v.unique(i):i,this.length>1&&rt.test(e)&&(i=i.reverse()),this.pushStack(i,e,l.call(arguments).join(","))}}),v.extend({filter:function(e,t,n){return n&&(e=":not("+e+")"),t.length===1?v.find.matchesSelector(t[0],e)?[t[0]]:[]:v.find.matches(e,t)},dir:function(e,n,r){var i=[],s=e[n];while(s&&s.nodeType!==9&&(r===t||s.nodeType!==1||!v(s).is(r)))s.nodeType===1&&i.push(s),s=s[n];return i},sibling:function(e,t){var n=[];for(;e;e=e.nextSibling)e.nodeType===1&&e!==t&&n.push(e);return n}});var ct="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",ht=/ jQuery\d+="(?:null|\d+)"/g,pt=/^\s+/,dt=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,vt=/<([\w:]+)/,mt=/]","i"),Et=/^(?:checkbox|radio)$/,St=/checked\s*(?:[^=]|=\s*.checked.)/i,xt=/\/(java|ecma)script/i,Tt=/^\s*\s*$/g,Nt={option:[1,""],legend:[1,"
","
"],thead:[1,"","
"],tr:[2,"","
"],td:[3,"","
"],col:[2,"","
"],area:[1,"",""],_default:[0,"",""]},Ct=lt(i),kt=Ct.appendChild(i.createElement("div"));Nt.optgroup=Nt.option,Nt.tbody=Nt.tfoot=Nt.colgroup=Nt.caption=Nt.thead,Nt.th=Nt.td,v.support.htmlSerialize||(Nt._default=[1,"X
","
"]),v.fn.extend({text:function(e){return v.access(this,function(e){return e===t?v.text(this):this.empty().append((this[0]&&this[0].ownerDocument||i).createTextNode(e))},null,e,arguments.length)},wrapAll:function(e){if(v.isFunction(e))return this.each(function(t){v(this).wrapAll(e.call(this,t))});if(this[0]){var t=v(e,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&t.insertBefore(this[0]),t.map(function(){var e=this;while(e.firstChild&&e.firstChild.nodeType===1)e=e.firstChild;return e}).append(this)}return this},wrapInner:function(e){return v.isFunction(e)?this.each(function(t){v(this).wrapInner(e.call(this,t))}):this.each(function(){var t=v(this),n=t.contents();n.length?n.wrapAll(e):t.append(e)})},wrap:function(e){var t=v.isFunction(e);return this.each(function(n){v(this).wrapAll(t?e.call(this,n):e)})},unwrap:function(){return this.parent().each(function(){v.nodeName(this,"body")||v(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(e){(this.nodeType===1||this.nodeType===11)&&this.appendChild(e)})},prepend:function(){return this.domManip(arguments,!0,function(e){(this.nodeType===1||this.nodeType===11)&&this.insertBefore(e,this.firstChild)})},before:function(){if(!ut(this[0]))return this.domManip(arguments,!1,function(e){this.parentNode.insertBefore(e,this)});if(arguments.length){var e=v.clean(arguments);return this.pushStack(v.merge(e,this),"before",this.selector)}},after:function(){if(!ut(this[0]))return this.domManip(arguments,!1,function(e){this.parentNode.insertBefore(e,this.nextSibling)});if(arguments.length){var e=v.clean(arguments);return this.pushStack(v.merge(this,e),"after",this.selector)}},remove:function(e,t){var n,r=0;for(;(n=this[r])!=null;r++)if(!e||v.filter(e,[n]).length)!t&&n.nodeType===1&&(v.cleanData(n.getElementsByTagName("*")),v.cleanData([n])),n.parentNode&&n.parentNode.removeChild(n);return this},empty:function(){var e,t=0;for(;(e=this[t])!=null;t++){e.nodeType===1&&v.cleanData(e.getElementsByTagName("*"));while(e.firstChild)e.removeChild(e.firstChild)}return this},clone:function(e,t){return e=e==null?!1:e,t=t==null?e:t,this.map(function(){return v.clone(this,e,t)})},html:function(e){return v.access(this,function(e){var n=this[0]||{},r=0,i=this.length;if(e===t)return n.nodeType===1?n.innerHTML.replace(ht,""):t;if(typeof e=="string"&&!yt.test(e)&&(v.support.htmlSerialize||!wt.test(e))&&(v.support.leadingWhitespace||!pt.test(e))&&!Nt[(vt.exec(e)||["",""])[1].toLowerCase()]){e=e.replace(dt,"<$1>");try{for(;r1&&typeof f=="string"&&St.test(f))return this.each(function(){v(this).domManip(e,n,r)});if(v.isFunction(f))return this.each(function(i){var s=v(this);e[0]=f.call(this,i,n?s.html():t),s.domManip(e,n,r)});if(this[0]){i=v.buildFragment(e,this,l),o=i.fragment,s=o.firstChild,o.childNodes.length===1&&(o=s);if(s){n=n&&v.nodeName(s,"tr");for(u=i.cacheable||c-1;a0?this.clone(!0):this).get(),v(o[i])[t](r),s=s.concat(r);return this.pushStack(s,e,o.selector)}}),v.extend({clone:function(e,t,n){var r,i,s,o;v.support.html5Clone||v.isXMLDoc(e)||!wt.test("<"+e.nodeName+">")?o=e.cloneNode(!0):(kt.innerHTML=e.outerHTML,kt.removeChild(o=kt.firstChild));if((!v.support.noCloneEvent||!v.support.noCloneChecked)&&(e.nodeType===1||e.nodeType===11)&&!v.isXMLDoc(e)){Ot(e,o),r=Mt(e),i=Mt(o);for(s=0;r[s];++s)i[s]&&Ot(r[s],i[s])}if(t){At(e,o);if(n){r=Mt(e),i=Mt(o);for(s=0;r[s];++s)At(r[s],i[s])}}return r=i=null,o},clean:function(e,t,n,r){var s,o,u,a,f,l,c,h,p,d,m,g,y=t===i&&Ct,b=[];if(!t||typeof t.createDocumentFragment=="undefined")t=i;for(s=0;(u=e[s])!=null;s++){typeof u=="number"&&(u+="");if(!u)continue;if(typeof u=="string")if(!gt.test(u))u=t.createTextNode(u);else{y=y||lt(t),c=t.createElement("div"),y.appendChild(c),u=u.replace(dt,"<$1>"),a=(vt.exec(u)||["",""])[1].toLowerCase(),f=Nt[a]||Nt._default,l=f[0],c.innerHTML=f[1]+u+f[2];while(l--)c=c.lastChild;if(!v.support.tbody){h=mt.test(u),p=a==="table"&&!h?c.firstChild&&c.firstChild.childNodes:f[1]===""&&!h?c.childNodes:[];for(o=p.length-1;o>=0;--o)v.nodeName(p[o],"tbody")&&!p[o].childNodes.length&&p[o].parentNode.removeChild(p[o])}!v.support.leadingWhitespace&&pt.test(u)&&c.insertBefore(t.createTextNode(pt.exec(u)[0]),c.firstChild),u=c.childNodes,c.parentNode.removeChild(c)}u.nodeType?b.push(u):v.merge(b,u)}c&&(u=c=y=null);if(!v.support.appendChecked)for(s=0;(u=b[s])!=null;s++)v.nodeName(u,"input")?_t(u):typeof u.getElementsByTagName!="undefined"&&v.grep(u.getElementsByTagName("input"),_t);if(n){m=function(e){if(!e.type||xt.test(e.type))return r?r.push(e.parentNode?e.parentNode.removeChild(e):e):n.appendChild(e)};for(s=0;(u=b[s])!=null;s++)if(!v.nodeName(u,"script")||!m(u))n.appendChild(u),typeof u.getElementsByTagName!="undefined"&&(g=v.grep(v.merge([],u.getElementsByTagName("script")),m),b.splice.apply(b,[s+1,0].concat(g)),s+=g.length)}return b},cleanData:function(e,t){var n,r,i,s,o=0,u=v.expando,a=v.cache,f=v.support.deleteExpando,l=v.event.special;for(;(i=e[o])!=null;o++)if(t||v.acceptData(i)){r=i[u],n=r&&a[r];if(n){if(n.events)for(s in n.events)l[s]?v.event.remove(i,s):v.removeEvent(i,s,n.handle);a[r]&&(delete a[r],f?delete i[u]:i.removeAttribute?i.removeAttribute(u):i[u]=null,v.deletedIds.push(r))}}}}),function(){var e,t;v.uaMatch=function(e){e=e.toLowerCase();var t=/(chrome)[ \/]([\w.]+)/.exec(e)||/(webkit)[ \/]([\w.]+)/.exec(e)||/(opera)(?:.*version|)[ \/]([\w.]+)/.exec(e)||/(msie) ([\w.]+)/.exec(e)||e.indexOf("compatible")<0&&/(mozilla)(?:.*? rv:([\w.]+)|)/.exec(e)||[];return{browser:t[1]||"",version:t[2]||"0"}},e=v.uaMatch(o.userAgent),t={},e.browser&&(t[e.browser]=!0,t.version=e.version),t.chrome?t.webkit=!0:t.webkit&&(t.safari=!0),v.browser=t,v.sub=function(){function e(t,n){return new e.fn.init(t,n)}v.extend(!0,e,this),e.superclass=this,e.fn=e.prototype=this(),e.fn.constructor=e,e.sub=this.sub,e.fn.init=function(r,i){return i&&i instanceof v&&!(i instanceof e)&&(i=e(i)),v.fn.init.call(this,r,i,t)},e.fn.init.prototype=e.fn;var t=e(i);return e}}();var Dt,Pt,Ht,Bt=/alpha\([^)]*\)/i,jt=/opacity=([^)]*)/,Ft=/^(top|right|bottom|left)$/,It=/^(none|table(?!-c[ea]).+)/,qt=/^margin/,Rt=new RegExp("^("+m+")(.*)$","i"),Ut=new RegExp("^("+m+")(?!px)[a-z%]+$","i"),zt=new RegExp("^([-+])=("+m+")","i"),Wt={BODY:"block"},Xt={position:"absolute",visibility:"hidden",display:"block"},Vt={letterSpacing:0,fontWeight:400},$t=["Top","Right","Bottom","Left"],Jt=["Webkit","O","Moz","ms"],Kt=v.fn.toggle;v.fn.extend({css:function(e,n){return v.access(this,function(e,n,r){return r!==t?v.style(e,n,r):v.css(e,n)},e,n,arguments.length>1)},show:function(){return Yt(this,!0)},hide:function(){return Yt(this)},toggle:function(e,t){var n=typeof e=="boolean";return v.isFunction(e)&&v.isFunction(t)?Kt.apply(this,arguments):this.each(function(){(n?e:Gt(this))?v(this).show():v(this).hide()})}}),v.extend({cssHooks:{opacity:{get:function(e,t){if(t){var n=Dt(e,"opacity");return n===""?"1":n}}}},cssNumber:{fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":v.support.cssFloat?"cssFloat":"styleFloat"},style:function(e,n,r,i){if(!e||e.nodeType===3||e.nodeType===8||!e.style)return;var s,o,u,a=v.camelCase(n),f=e.style;n=v.cssProps[a]||(v.cssProps[a]=Qt(f,a)),u=v.cssHooks[n]||v.cssHooks[a];if(r===t)return u&&"get"in u&&(s=u.get(e,!1,i))!==t?s:f[n];o=typeof r,o==="string"&&(s=zt.exec(r))&&(r=(s[1]+1)*s[2]+parseFloat(v.css(e,n)),o="number");if(r==null||o==="number"&&isNaN(r))return;o==="number"&&!v.cssNumber[a]&&(r+="px");if(!u||!("set"in u)||(r=u.set(e,r,i))!==t)try{f[n]=r}catch(l){}},css:function(e,n,r,i){var s,o,u,a=v.camelCase(n);return n=v.cssProps[a]||(v.cssProps[a]=Qt(e.style,a)),u=v.cssHooks[n]||v.cssHooks[a],u&&"get"in u&&(s=u.get(e,!0,i)),s===t&&(s=Dt(e,n)),s==="normal"&&n in Vt&&(s=Vt[n]),r||i!==t?(o=parseFloat(s),r||v.isNumeric(o)?o||0:s):s},swap:function(e,t,n){var r,i,s={};for(i in t)s[i]=e.style[i],e.style[i]=t[i];r=n.call(e);for(i in t)e.style[i]=s[i];return r}}),e.getComputedStyle?Dt=function(t,n){var r,i,s,o,u=e.getComputedStyle(t,null),a=t.style;return u&&(r=u.getPropertyValue(n)||u[n],r===""&&!v.contains(t.ownerDocument,t)&&(r=v.style(t,n)),Ut.test(r)&&qt.test(n)&&(i=a.width,s=a.minWidth,o=a.maxWidth,a.minWidth=a.maxWidth=a.width=r,r=u.width,a.width=i,a.minWidth=s,a.maxWidth=o)),r}:i.documentElement.currentStyle&&(Dt=function(e,t){var n,r,i=e.currentStyle&&e.currentStyle[t],s=e.style;return i==null&&s&&s[t]&&(i=s[t]),Ut.test(i)&&!Ft.test(t)&&(n=s.left,r=e.runtimeStyle&&e.runtimeStyle.left,r&&(e.runtimeStyle.left=e.currentStyle.left),s.left=t==="fontSize"?"1em":i,i=s.pixelLeft+"px",s.left=n,r&&(e.runtimeStyle.left=r)),i===""?"auto":i}),v.each(["height","width"],function(e,t){v.cssHooks[t]={get:function(e,n,r){if(n)return e.offsetWidth===0&&It.test(Dt(e,"display"))?v.swap(e,Xt,function(){return tn(e,t,r)}):tn(e,t,r)},set:function(e,n,r){return Zt(e,n,r?en(e,t,r,v.support.boxSizing&&v.css(e,"boxSizing")==="border-box"):0)}}}),v.support.opacity||(v.cssHooks.opacity={get:function(e,t){return jt.test((t&&e.currentStyle?e.currentStyle.filter:e.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":t?"1":""},set:function(e,t){var n=e.style,r=e.currentStyle,i=v.isNumeric(t)?"alpha(opacity="+t*100+")":"",s=r&&r.filter||n.filter||"";n.zoom=1;if(t>=1&&v.trim(s.replace(Bt,""))===""&&n.removeAttribute){n.removeAttribute("filter");if(r&&!r.filter)return}n.filter=Bt.test(s)?s.replace(Bt,i):s+" "+i}}),v(function(){v.support.reliableMarginRight||(v.cssHooks.marginRight={get:function(e,t){return v.swap(e,{display:"inline-block"},function(){if(t)return Dt(e,"marginRight")})}}),!v.support.pixelPosition&&v.fn.position&&v.each(["top","left"],function(e,t){v.cssHooks[t]={get:function(e,n){if(n){var r=Dt(e,t);return Ut.test(r)?v(e).position()[t]+"px":r}}}})}),v.expr&&v.expr.filters&&(v.expr.filters.hidden=function(e){return e.offsetWidth===0&&e.offsetHeight===0||!v.support.reliableHiddenOffsets&&(e.style&&e.style.display||Dt(e,"display"))==="none"},v.expr.filters.visible=function(e){return!v.expr.filters.hidden(e)}),v.each({margin:"",padding:"",border:"Width"},function(e,t){v.cssHooks[e+t]={expand:function(n){var r,i=typeof n=="string"?n.split(" "):[n],s={};for(r=0;r<4;r++)s[e+$t[r]+t]=i[r]||i[r-2]||i[0];return s}},qt.test(e)||(v.cssHooks[e+t].set=Zt)});var rn=/%20/g,sn=/\[\]$/,on=/\r?\n/g,un=/^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,an=/^(?:select|textarea)/i;v.fn.extend({serialize:function(){return v.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?v.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||an.test(this.nodeName)||un.test(this.type))}).map(function(e,t){var n=v(this).val();return n==null?null:v.isArray(n)?v.map(n,function(e,n){return{name:t.name,value:e.replace(on,"\r\n")}}):{name:t.name,value:n.replace(on,"\r\n")}}).get()}}),v.param=function(e,n){var r,i=[],s=function(e,t){t=v.isFunction(t)?t():t==null?"":t,i[i.length]=encodeURIComponent(e)+"="+encodeURIComponent(t)};n===t&&(n=v.ajaxSettings&&v.ajaxSettings.traditional);if(v.isArray(e)||e.jquery&&!v.isPlainObject(e))v.each(e,function(){s(this.name,this.value)});else for(r in e)fn(r,e[r],n,s);return i.join("&").replace(rn,"+")};var ln,cn,hn=/#.*$/,pn=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,dn=/^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,vn=/^(?:GET|HEAD)$/,mn=/^\/\//,gn=/\?/,yn=/)<[^<]*)*<\/script>/gi,bn=/([?&])_=[^&]*/,wn=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,En=v.fn.load,Sn={},xn={},Tn=["*/"]+["*"];try{cn=s.href}catch(Nn){cn=i.createElement("a"),cn.href="",cn=cn.href}ln=wn.exec(cn.toLowerCase())||[],v.fn.load=function(e,n,r){if(typeof e!="string"&&En)return En.apply(this,arguments);if(!this.length)return this;var i,s,o,u=this,a=e.indexOf(" ");return a>=0&&(i=e.slice(a,e.length),e=e.slice(0,a)),v.isFunction(n)?(r=n,n=t):n&&typeof n=="object"&&(s="POST"),v.ajax({url:e,type:s,dataType:"html",data:n,complete:function(e,t){r&&u.each(r,o||[e.responseText,t,e])}}).done(function(e){o=arguments,u.html(i?v("
").append(e.replace(yn,"")).find(i):e)}),this},v.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(e,t){v.fn[t]=function(e){return this.on(t,e)}}),v.each(["get","post"],function(e,n){v[n]=function(e,r,i,s){return v.isFunction(r)&&(s=s||i,i=r,r=t),v.ajax({type:n,url:e,data:r,success:i,dataType:s})}}),v.extend({getScript:function(e,n){return v.get(e,t,n,"script")},getJSON:function(e,t,n){return v.get(e,t,n,"json")},ajaxSetup:function(e,t){return t?Ln(e,v.ajaxSettings):(t=e,e=v.ajaxSettings),Ln(e,t),e},ajaxSettings:{url:cn,isLocal:dn.test(ln[1]),global:!0,type:"GET",contentType:"application/x-www-form-urlencoded; charset=UTF-8",processData:!0,async:!0,accepts:{xml:"application/xml, text/xml",html:"text/html",text:"text/plain",json:"application/json, text/javascript","*":Tn},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":e.String,"text html":!0,"text json":v.parseJSON,"text xml":v.parseXML},flatOptions:{context:!0,url:!0}},ajaxPrefilter:Cn(Sn),ajaxTransport:Cn(xn),ajax:function(e,n){function T(e,n,s,a){var l,y,b,w,S,T=n;if(E===2)return;E=2,u&&clearTimeout(u),o=t,i=a||"",x.readyState=e>0?4:0,s&&(w=An(c,x,s));if(e>=200&&e<300||e===304)c.ifModified&&(S=x.getResponseHeader("Last-Modified"),S&&(v.lastModified[r]=S),S=x.getResponseHeader("Etag"),S&&(v.etag[r]=S)),e===304?(T="notmodified",l=!0):(l=On(c,w),T=l.state,y=l.data,b=l.error,l=!b);else{b=T;if(!T||e)T="error",e<0&&(e=0)}x.status=e,x.statusText=(n||T)+"",l?d.resolveWith(h,[y,T,x]):d.rejectWith(h,[x,T,b]),x.statusCode(g),g=t,f&&p.trigger("ajax"+(l?"Success":"Error"),[x,c,l?y:b]),m.fireWith(h,[x,T]),f&&(p.trigger("ajaxComplete",[x,c]),--v.active||v.event.trigger("ajaxStop"))}typeof e=="object"&&(n=e,e=t),n=n||{};var r,i,s,o,u,a,f,l,c=v.ajaxSetup({},n),h=c.context||c,p=h!==c&&(h.nodeType||h instanceof v)?v(h):v.event,d=v.Deferred(),m=v.Callbacks("once memory"),g=c.statusCode||{},b={},w={},E=0,S="canceled",x={readyState:0,setRequestHeader:function(e,t){if(!E){var n=e.toLowerCase();e=w[n]=w[n]||e,b[e]=t}return this},getAllResponseHeaders:function(){return E===2?i:null},getResponseHeader:function(e){var n;if(E===2){if(!s){s={};while(n=pn.exec(i))s[n[1].toLowerCase()]=n[2]}n=s[e.toLowerCase()]}return n===t?null:n},overrideMimeType:function(e){return E||(c.mimeType=e),this},abort:function(e){return e=e||S,o&&o.abort(e),T(0,e),this}};d.promise(x),x.success=x.done,x.error=x.fail,x.complete=m.add,x.statusCode=function(e){if(e){var t;if(E<2)for(t in e)g[t]=[g[t],e[t]];else t=e[x.status],x.always(t)}return this},c.url=((e||c.url)+"").replace(hn,"").replace(mn,ln[1]+"//"),c.dataTypes=v.trim(c.dataType||"*").toLowerCase().split(y),c.crossDomain==null&&(a=wn.exec(c.url.toLowerCase()),c.crossDomain=!(!a||a[1]===ln[1]&&a[2]===ln[2]&&(a[3]||(a[1]==="http:"?80:443))==(ln[3]||(ln[1]==="http:"?80:443)))),c.data&&c.processData&&typeof c.data!="string"&&(c.data=v.param(c.data,c.traditional)),kn(Sn,c,n,x);if(E===2)return x;f=c.global,c.type=c.type.toUpperCase(),c.hasContent=!vn.test(c.type),f&&v.active++===0&&v.event.trigger("ajaxStart");if(!c.hasContent){c.data&&(c.url+=(gn.test(c.url)?"&":"?")+c.data,delete c.data),r=c.url;if(c.cache===!1){var N=v.now(),C=c.url.replace(bn,"$1_="+N);c.url=C+(C===c.url?(gn.test(c.url)?"&":"?")+"_="+N:"")}}(c.data&&c.hasContent&&c.contentType!==!1||n.contentType)&&x.setRequestHeader("Content-Type",c.contentType),c.ifModified&&(r=r||c.url,v.lastModified[r]&&x.setRequestHeader("If-Modified-Since",v.lastModified[r]),v.etag[r]&&x.setRequestHeader("If-None-Match",v.etag[r])),x.setRequestHeader("Accept",c.dataTypes[0]&&c.accepts[c.dataTypes[0]]?c.accepts[c.dataTypes[0]]+(c.dataTypes[0]!=="*"?", "+Tn+"; q=0.01":""):c.accepts["*"]);for(l in c.headers)x.setRequestHeader(l,c.headers[l]);if(!c.beforeSend||c.beforeSend.call(h,x,c)!==!1&&E!==2){S="abort";for(l in{success:1,error:1,complete:1})x[l](c[l]);o=kn(xn,c,n,x);if(!o)T(-1,"No Transport");else{x.readyState=1,f&&p.trigger("ajaxSend",[x,c]),c.async&&c.timeout>0&&(u=setTimeout(function(){x.abort("timeout")},c.timeout));try{E=1,o.send(b,T)}catch(k){if(!(E<2))throw k;T(-1,k)}}return x}return x.abort()},active:0,lastModified:{},etag:{}});var Mn=[],_n=/\?/,Dn=/(=)\?(?=&|$)|\?\?/,Pn=v.now();v.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=Mn.pop()||v.expando+"_"+Pn++;return this[e]=!0,e}}),v.ajaxPrefilter("json jsonp",function(n,r,i){var s,o,u,a=n.data,f=n.url,l=n.jsonp!==!1,c=l&&Dn.test(f),h=l&&!c&&typeof a=="string"&&!(n.contentType||"").indexOf("application/x-www-form-urlencoded")&&Dn.test(a);if(n.dataTypes[0]==="jsonp"||c||h)return s=n.jsonpCallback=v.isFunction(n.jsonpCallback)?n.jsonpCallback():n.jsonpCallback,o=e[s],c?n.url=f.replace(Dn,"$1"+s):h?n.data=a.replace(Dn,"$1"+s):l&&(n.url+=(_n.test(f)?"&":"?")+n.jsonp+"="+s),n.converters["script json"]=function(){return u||v.error(s+" was not called"),u[0]},n.dataTypes[0]="json",e[s]=function(){u=arguments},i.always(function(){e[s]=o,n[s]&&(n.jsonpCallback=r.jsonpCallback,Mn.push(s)),u&&v.isFunction(o)&&o(u[0]),u=o=t}),"script"}),v.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/javascript|ecmascript/},converters:{"text script":function(e){return v.globalEval(e),e}}}),v.ajaxPrefilter("script",function(e){e.cache===t&&(e.cache=!1),e.crossDomain&&(e.type="GET",e.global=!1)}),v.ajaxTransport("script",function(e){if(e.crossDomain){var n,r=i.head||i.getElementsByTagName("head")[0]||i.documentElement;return{send:function(s,o){n=i.createElement("script"),n.async="async",e.scriptCharset&&(n.charset=e.scriptCharset),n.src=e.url,n.onload=n.onreadystatechange=function(e,i){if(i||!n.readyState||/loaded|complete/.test(n.readyState))n.onload=n.onreadystatechange=null,r&&n.parentNode&&r.removeChild(n),n=t,i||o(200,"success")},r.insertBefore(n,r.firstChild)},abort:function(){n&&n.onload(0,1)}}}});var Hn,Bn=e.ActiveXObject?function(){for(var e in Hn)Hn[e](0,1)}:!1,jn=0;v.ajaxSettings.xhr=e.ActiveXObject?function(){return!this.isLocal&&Fn()||In()}:Fn,function(e){v.extend(v.support,{ajax:!!e,cors:!!e&&"withCredentials"in e})}(v.ajaxSettings.xhr()),v.support.ajax&&v.ajaxTransport(function(n){if(!n.crossDomain||v.support.cors){var r;return{send:function(i,s){var o,u,a=n.xhr();n.username?a.open(n.type,n.url,n.async,n.username,n.password):a.open(n.type,n.url,n.async);if(n.xhrFields)for(u in n.xhrFields)a[u]=n.xhrFields[u];n.mimeType&&a.overrideMimeType&&a.overrideMimeType(n.mimeType),!n.crossDomain&&!i["X-Requested-With"]&&(i["X-Requested-With"]="XMLHttpRequest");try{for(u in i)a.setRequestHeader(u,i[u])}catch(f){}a.send(n.hasContent&&n.data||null),r=function(e,i){var u,f,l,c,h;try{if(r&&(i||a.readyState===4)){r=t,o&&(a.onreadystatechange=v.noop,Bn&&delete Hn[o]);if(i)a.readyState!==4&&a.abort();else{u=a.status,l=a.getAllResponseHeaders(),c={},h=a.responseXML,h&&h.documentElement&&(c.xml=h);try{c.text=a.responseText}catch(p){}try{f=a.statusText}catch(p){f=""}!u&&n.isLocal&&!n.crossDomain?u=c.text?200:404:u===1223&&(u=204)}}}catch(d){i||s(-1,d)}c&&s(u,f,c,l)},n.async?a.readyState===4?setTimeout(r,0):(o=++jn,Bn&&(Hn||(Hn={},v(e).unload(Bn)),Hn[o]=r),a.onreadystatechange=r):r()},abort:function(){r&&r(0,1)}}}});var qn,Rn,Un=/^(?:toggle|show|hide)$/,zn=new RegExp("^(?:([-+])=|)("+m+")([a-z%]*)$","i"),Wn=/queueHooks$/,Xn=[Gn],Vn={"*":[function(e,t){var n,r,i=this.createTween(e,t),s=zn.exec(t),o=i.cur(),u=+o||0,a=1,f=20;if(s){n=+s[2],r=s[3]||(v.cssNumber[e]?"":"px");if(r!=="px"&&u){u=v.css(i.elem,e,!0)||n||1;do a=a||".5",u/=a,v.style(i.elem,e,u+r);while(a!==(a=i.cur()/o)&&a!==1&&--f)}i.unit=r,i.start=u,i.end=s[1]?u+(s[1]+1)*n:n}return i}]};v.Animation=v.extend(Kn,{tweener:function(e,t){v.isFunction(e)?(t=e,e=["*"]):e=e.split(" ");var n,r=0,i=e.length;for(;r-1,f={},l={},c,h;a?(l=i.position(),c=l.top,h=l.left):(c=parseFloat(o)||0,h=parseFloat(u)||0),v.isFunction(t)&&(t=t.call(e,n,s)),t.top!=null&&(f.top=t.top-s.top+c),t.left!=null&&(f.left=t.left-s.left+h),"using"in t?t.using.call(e,f):i.css(f)}},v.fn.extend({position:function(){if(!this[0])return;var e=this[0],t=this.offsetParent(),n=this.offset(),r=er.test(t[0].nodeName)?{top:0,left:0}:t.offset();return n.top-=parseFloat(v.css(e,"marginTop"))||0,n.left-=parseFloat(v.css(e,"marginLeft"))||0,r.top+=parseFloat(v.css(t[0],"borderTopWidth"))||0,r.left+=parseFloat(v.css(t[0],"borderLeftWidth"))||0,{top:n.top-r.top,left:n.left-r.left}},offsetParent:function(){return this.map(function(){var e=this.offsetParent||i.body;while(e&&!er.test(e.nodeName)&&v.css(e,"position")==="static")e=e.offsetParent;return e||i.body})}}),v.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(e,n){var r=/Y/.test(n);v.fn[e]=function(i){return v.access(this,function(e,i,s){var o=tr(e);if(s===t)return o?n in o?o[n]:o.document.documentElement[i]:e[i];o?o.scrollTo(r?v(o).scrollLeft():s,r?s:v(o).scrollTop()):e[i]=s},e,i,arguments.length,null)}}),v.each({Height:"height",Width:"width"},function(e,n){v.each({padding:"inner"+e,content:n,"":"outer"+e},function(r,i){v.fn[i]=function(i,s){var o=arguments.length&&(r||typeof i!="boolean"),u=r||(i===!0||s===!0?"margin":"border");return v.access(this,function(n,r,i){var s;return v.isWindow(n)?n.document.documentElement["client"+e]:n.nodeType===9?(s=n.documentElement,Math.max(n.body["scroll"+e],s["scroll"+e],n.body["offset"+e],s["offset"+e],s["client"+e])):i===t?v.css(n,r,i,u):v.style(n,r,i,u)},n,o?i:t,o,null)}})}),e.jQuery=e.$=v,typeof define=="function"&&define.amd&&define.amd.jQuery&&define("jquery",[],function(){return v})})(window); \ No newline at end of file diff --git a/Chapter12/02_api_testing/static/content/login.js b/Chapter12/02_api_testing/static/content/login.js new file mode 100644 index 0000000..57840e2 --- /dev/null +++ b/Chapter12/02_api_testing/static/content/login.js @@ -0,0 +1,30 @@ +$(function(){ + + var tmpl, // Main template HTML + tdata = {}; // JSON data object that feeds the template + + // Initialise page + var initPage = function() { + + // Load the HTML template + $.get("/templates/login.html", function(d){ + tmpl = d; + }); + + // Retrieve the server data and then initialise the page + $.getJSON("/v1/users/logged_in.json", function (d) { + $.extend(tdata, d); + }); + + // When AJAX calls are complete parse the template + // replacing mustache tags with vars + $(document).ajaxStop(function () { + if (tdata.data.logged_in) + window.location = "/pages/admin/home"; + else { + var renderedPage = Mustache.to_html( tmpl, tdata ); + $("body").html( renderedPage ); + } + }); + }(); +}); diff --git a/Chapter12/02_api_testing/static/content/mustache.js b/Chapter12/02_api_testing/static/content/mustache.js new file mode 100644 index 0000000..0148d29 --- /dev/null +++ b/Chapter12/02_api_testing/static/content/mustache.js @@ -0,0 +1,625 @@ +/*! + * mustache.js - Logic-less {{mustache}} templates with JavaScript + * http://github.com/janl/mustache.js + */ + +/*global define: false*/ + +var Mustache; + +(function (exports) { + if (typeof module !== "undefined" && module.exports) { + module.exports = exports; // CommonJS + } else if (typeof define === "function") { + define(exports); // AMD + } else { + Mustache = exports; // diff --git a/Chapter12/02_api_testing/static/templates/admin_add_photos.html b/Chapter12/02_api_testing/static/templates/admin_add_photos.html new file mode 100644 index 0000000..d9cbe8d --- /dev/null +++ b/Chapter12/02_api_testing/static/templates/admin_add_photos.html @@ -0,0 +1,86 @@ +
+ +
+
Add to Album:
+
+ +
+
Image:
+
+
Description
+
+
+ + + + + +
+ + diff --git a/Chapter12/02_api_testing/static/templates/admin_home.html b/Chapter12/02_api_testing/static/templates/admin_home.html new file mode 100644 index 0000000..4db4cf1 --- /dev/null +++ b/Chapter12/02_api_testing/static/templates/admin_home.html @@ -0,0 +1,7 @@ + +

Admin Operations

+ + diff --git a/Chapter12/02_api_testing/static/templates/album.html b/Chapter12/02_api_testing/static/templates/album.html new file mode 100644 index 0000000..520560a --- /dev/null +++ b/Chapter12/02_api_testing/static/templates/album.html @@ -0,0 +1,19 @@ +
+ {{#has_photos}} +

There are {{ has_photos }} photos in this album

+ {{/has_photos}} + {{#photos}} +
+
+
+
+

{{ desc }}

+
+
+ {{/photos}} +
+ {{^photos}} +

This album does't have any photos in it, sorry.

+ {{/photos}} +

diff --git a/Chapter12/02_api_testing/static/templates/home.html b/Chapter12/02_api_testing/static/templates/home.html new file mode 100644 index 0000000..a7d1436 --- /dev/null +++ b/Chapter12/02_api_testing/static/templates/home.html @@ -0,0 +1,16 @@ +
+ Admin +
+
+

There are {{ albums.length }} albums

+
    + {{#albums}} +
  • + {{name}} +
  • + {{/albums}} + {{^albums}} +
  • Sorry, there are currently no albums
  • + {{/albums}} +
+
diff --git a/Chapter12/02_api_testing/static/templates/login.html b/Chapter12/02_api_testing/static/templates/login.html new file mode 100644 index 0000000..b24f910 --- /dev/null +++ b/Chapter12/02_api_testing/static/templates/login.html @@ -0,0 +1,49 @@ + +
+
+
+
Email address:
+
+
Password:
+
+
+
+ + + + diff --git a/Chapter12/02_api_testing/static/templates/register.html b/Chapter12/02_api_testing/static/templates/register.html new file mode 100644 index 0000000..491e4fd --- /dev/null +++ b/Chapter12/02_api_testing/static/templates/register.html @@ -0,0 +1,59 @@ + + +
+
+
+
Email address:
+
+
Display Name:
+
+
Password:
+
+
Password (confirm):
+
+
+
+ + + + + diff --git a/Chapter12/02_api_testing/test/01_api_albums.js b/Chapter12/02_api_testing/test/01_api_albums.js new file mode 100644 index 0000000..1268664 --- /dev/null +++ b/Chapter12/02_api_testing/test/01_api_albums.js @@ -0,0 +1,59 @@ + +var request = require('request'); + +var h = "http://localhost:8080"; + +exports.no_albums = function (test) { + test.expect(5); + request.get(h + "/v1/albums.json", function (err, resp, body) { + test.equal(err, null); + test.equal(resp.statusCode, 200); + var r = JSON.parse(body); + test.equal(r.error, null); + test.notEqual(r.data.albums, undefined); + test.equal(r.data.albums.length, 0); + test.done(); + }); +}; + +exports.create_album = function (test) { + var d = "We went to HK to do some shopping and spend new years. Nice!"; + var t = "New Years in Hong Kong"; + test.expect(7); + request.put( + { url: h + "/v1/albums.json", + json: { name: "hongkong2012", + title: t, + description: d, + date: "2012-12-28" } }, + function (err, resp, body) { + test.equal(err, null); + test.equal(resp.statusCode, 200); + test.notEqual(body.data.album, undefined); + test.equal(body.data.album.name, "hongkong2012"), + test.equal(body.data.album.date, "2012-12-28"); + test.equal(body.data.album.description, d); + test.equal(body.data.album.title, t); + test.done(); + } + ); +} + +exports.fail_create_album = function (test) { + test.expect(4); + request.put( + { url: h + "/v1/albums.json", + headers: { "Content-Type" : "application/json" }, + json: { name: "hong kong 2012", + title: "title", + description: "desc", + date: "2012-12-28" } }, + function (err, resp, body) { + test.equal(err, null); + test.equal(resp.statusCode, 403); + test.notEqual(body.error, null); + test.equal(body.error, "invalid_album_name"); + test.done(); + } + ); +}; diff --git a/Chapter12/02_api_testing/test/02_api_photos.js b/Chapter12/02_api_testing/test/02_api_photos.js new file mode 100644 index 0000000..e69de29 diff --git a/Chapter12/02_api_testing/test/Makefile b/Chapter12/02_api_testing/test/Makefile new file mode 100644 index 0000000..5fabd9a --- /dev/null +++ b/Chapter12/02_api_testing/test/Makefile @@ -0,0 +1,18 @@ + + +all: prepare run-tests + @echo "Done" + +prepare: + @-rm -fr ../static/albums/* + @echo "Preparing MySQL db for running" + @/usr/local/mysql/bin/mysql -u root < ../schema.sql + @echo "Launching app server" + @-killall node + @sh -c "pushd ../app && sh -c \"node server.js 2>&1 > ../test/output.txt &\" && popd && sleep 2" + +run-tests: + @echo "Starting to run tests..." + @node_modules/.bin/nodeunit 01_api_albums.js 02_api_photos.js + @echo "Tested! Shutting down app server" + @killall node diff --git a/Chapter12/02_api_testing/test/output.txt b/Chapter12/02_api_testing/test/output.txt new file mode 100644 index 0000000..d8f0e88 --- /dev/null +++ b/Chapter12/02_api_testing/test/output.txt @@ -0,0 +1,4 @@ +Database initialised and connected. +GET /v1/albums.json 200 4ms +PUT /v1/albums.json 200 5ms +PUT /v1/albums.json 403 1ms diff --git a/Chapter12/02_api_testing/test/package.json b/Chapter12/02_api_testing/test/package.json new file mode 100644 index 0000000..4d8f473 --- /dev/null +++ b/Chapter12/02_api_testing/test/package.json @@ -0,0 +1,10 @@ +{ + "name": "API-testing-demo", + "description": "Demonstrates API Testing with request and nodeunit", + "version": "0.0.1", + "private": true, + "dependencies": { + "nodeunit": "0.7.x", + "request": "2.x" + } +} diff --git a/mac_osx_from_source.rtf b/mac_osx_from_source.rtf new file mode 100644 index 0000000..415a021 --- /dev/null +++ b/mac_osx_from_source.rtf @@ -0,0 +1,144 @@ +{\rtf1\ansi\ansicpg1252\cocoartf1187\cocoasubrtf340 +{\fonttbl\f0\fswiss\fcharset0 ArialMT;\f1\fmodern\fcharset0 Courier;\f2\fnil\fcharset0 LucidaGrande; +} +{\colortbl;\red255\green255\blue255;} +\paperw11900\paperh16840\margl1440\margr1440\vieww17560\viewh12320\viewkind0 +\pard\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803 + +\f0\b\fs30 \cf0 Installing from Source on Mac OS X\ + +\b0\fs24 \ +If you have Xcode on your Mac, you can also build and install Node.js from the source code.\ +\ + +\b\fs26 0. Getting the Command-Line Compiler via Xcode\ +\ + +\b0\fs24 To build Node.js from source on your OS X\'96based computer, you first need to make sure that you have the command-line compiler tools installed. To do this, you can type\ +\ + +\f1 c++ +\f0 \ +\ +in a terminal window. If you don\'92t know what a terminal window is, you should probably use the PKG installer method described previously for installing Node.js onto your Mac.\ +\ +If you see something like\ +\ + +\f1 client:LearningNode marcw$ c++\ +clang: error: no input files +\f0 \ +\ +you have the compiler installed and will be able to build. If instead you see\ +\ + +\f1 client:LearningNode marcw$ c++\ +-bash: c++: No such file or directory +\f0 \ +\ +you need to do the following:\ +\ +1. Launch Xcode.\ +2. View Xcode Preferences ( +\f2 \uc0\u8984 + , +\f0 ).\ +3. Select the Downloads page and Components group, and then click on Install or Update next to Command Line Tools.\ +\ +After these command-line tools are installed, the c++ command should work, and you should be able to continue compiling.\ +\ + +\b\fs26 1. Building Node.js\ + +\b0\fs24 \ +Start by creating some scratch space to download and compile from:\ +\ + +\f1 cd\ +mkdir -p src/scratch\ +cd src/scratch\ + +\f0 \ +The next step is to download and unpack the Node sources. You can do this using +\f1 curl +\f0 or +\f1 wget +\f0 :\ +\ + +\f1 curl http://nodejs.org/dist/v0.10.1/node-v0.10.1.tar.gz -o node-v0.10.1.tar.gz\ +tar xfz node-v0.10.1.tar.gz\ +cd node-v0.10.1 +\f0 \ +\ +Next, run the configuration scripts to prepare for the build:\ +\ + +\f1 ./configure +\f0 \ +\ +You can let it use the default +\i /usr/local +\i0 as the installation point because it\'92s a good location from which to run this software. If you want to install it somewhere else, you can specify the +\f1 --prefix +\f0 switch to the configure script, as follows:\ +\ + +\f1 ./configure --prefix =/opt/nodejs +\f0 \ +\ +The configure script should print out some JavaScript Object Notation (JSON) similar to the following:\ +\ + +\f1 \{ 'target_defaults': \{ 'cflags': [],\ + 'default_configuration': 'Release',\ + 'defines': [],\ + 'include_dirs': [],\ + 'libraries': []\},\ + 'variables': \{ 'clang': 1,\ + 'host_arch': 'x64',\ + 'node_install_npm': 'true',\ + 'node_install_waf': 'true',\ + 'node_prefix': '',\ + 'node_shared_openssl': 'false',\ + 'node_shared_v8': 'false',\ + 'node_shared_zlib': 'false',\ + 'node_unsafe_optimizations': 0,\ + 'node_use_dtrace': 'false',\ + 'node_use_etw': 'false',\ + 'node_use_openssl': 'true',\ + 'target_arch': 'x64',\ + 'v8_no_strict_aliasing': 1,\ + 'v8_use_snapshot': 'true'\}\}\ +creating ./config.gypi\ +creating ./config.mk\ + +\f0 \ +Now you can build the product. Type in the following command and go get yourself a coffee (or two, depending on how fast your machine is):\ +\ + +\f1 make +\f0 \ +\ +After the make has completed successfully (if it fails, do a Google search on the problem because you will almost certainly not be the first to see it), you can then install the software to your chosen prefix (/usr/local if you did not choose one):\ +\ + +\f1 sudo make install +\f0 \ +\ +When you are done, you should be able to just enter\ +\ + +\f1 node --version\ +npm --version\ + +\f0 \ +and get output somewhat similar to\ +\ + +\f1 client:node-v0.10.3 marcw$ node --version\ +v0.10.3\ +client:node-v0.10.3 marcw$ npm --version\ +1.1.65 +\f0 \ +\ +} \ No newline at end of file