diff --git a/demo/.DS_Store b/demo/.DS_Store new file mode 100644 index 0000000..5008ddf Binary files /dev/null and b/demo/.DS_Store differ diff --git a/demo/README.md b/demo/README.md new file mode 100644 index 0000000..32ff1e5 --- /dev/null +++ b/demo/README.md @@ -0,0 +1,12 @@ +# DEMO + +1. First download and unzip the file from the following [link](https://docs.google.com/a/umich.edu/uc?id=0B_jnlzs7cGbjVWZvanVUejdVTG8&export=download) into your desired location + +2. Use the following to install the proper dependencies: +```luarocks install luasocket``` +```luarocks install json``` + +3. Type the following into a terminal: +```th kp_demo.lua ``` + +4. Direct your browser to `localhost:8080` \ No newline at end of file diff --git a/demo/index.html b/demo/index.html new file mode 100644 index 0000000..bb5d56a --- /dev/null +++ b/demo/index.html @@ -0,0 +1,71 @@ + + + + + + + + + + + + + + + +
+
+ + +
+ +
+ + +
+
+ + + + + + + + + + + +
+ + + +
+
+
+ + + +
+ + + + Show keypoints? + +
+
+ + + +
+
+
+
+
+ + diff --git a/demo/kp_demo.lua b/demo/kp_demo.lua new file mode 100644 index 0000000..e5dd48a --- /dev/null +++ b/demo/kp_demo.lua @@ -0,0 +1,130 @@ +local orbiter = require 'orbiter' + +local hello = orbiter.new() +local mime = require("mime") +local util = paths.dofile('../util.lua') +require('image') +require('nn') +require('nngraph') +require('image') +require('json') + +-- Fill in appropriate data path variable +if arg[1] == nil then + print('Please enter path to folder containing data') + else + DATA_PATH = arg[1] + end + +net_txt = torch.load(DATA_PATH .. 'lm_sje_nc4_cub_hybrid_gru18_a1_c512_0.00070_1_10_trainvalids.txt_iter30000.t7_cpu.t7') +net_txt:evaluate() +net_gen = torch.load(DATA_PATH .. 'cub_part_stn_kd16_bs16_ngf128_ndf128_600_net_G.t7_cpu.t7') +net_gen:evaluate() +net_kp = torch.load(DATA_PATH .. 'cub_kptxt2kp_large_bs64_ngf128_ndf128_200_net_G.t7_cpu.t7') +net_kp:evaluate() + +torch.setdefaulttensortype('torch.FloatTensor') + +local alphabet = "abcdefghijklmnopqrstuvwxyz0123456789-,;.!?:'\"/\\|_@#$%^&*~`+-=<>()[]{} " +local dict = {} +for i = 1,#alphabet do + dict[alphabet:sub(i,i)] = i + end + ivocab = {} + for k,v in pairs(dict) do + ivocab[v] = k + end + +opt = {} +opt.keypoint_dim = 16 +opt.num_elt = 15 +opt.doc_length = 201 +opt.batchSize = 1 +opt.nz = 100 +opt.txtSize = 1024 +opt.noisetype = 'normal' + +function hello:index(web) + local f = assert(io.open('index.html', 'r')) + local rtrn = f:read('*all') + f:close() + return rtrn + end + +function hello:request(web) + local data = json.decode(web.POST.data) + local desc = data.description + local showkps = data.showkps + -- prepare noise + noise = torch.Tensor(opt.batchSize, opt.nz) + if opt.noisetype == 'uniform' then + noise:uniform(-1, 1) + elseif opt.noisetype == 'normal' then + noise:normal(0, 1) + end + -- prepare text + local txt_mat = torch.zeros(1,opt.doc_length,#alphabet) + for t = 1,opt.doc_length do + local ch = desc:sub(t,t) + local on_ix = dict[ch] + if (on_ix ~= 0 and on_ix ~= nil) then + txt_mat[{1, t, on_ix}] = 1 + end + end + local fea_txt = net_txt:forward(txt_mat):clone() + -- prepare keypoints + local fea_loc_inp = torch.zeros(opt.batchSize, opt.num_elt, 3) + for n = 1,#data.keypoints do + local id = data.keypoints[n].part_id + local x = data.keypoints[n].x / 256.0 + local y = data.keypoints[n].y / 256.0 + fea_loc_inp[{1,id,1}] = x + fea_loc_inp[{1,id,2}] = y + fea_loc_inp[{1,id,3}] = 1.0 + end + fea_loc = net_kp:forward{noise, fea_txt, fea_loc_inp}:clone() + + local data_loc = torch.zeros(opt.batchSize, opt.num_elt, + opt.keypoint_dim, opt.keypoint_dim) + for b = 1,opt.batchSize do + for s = 1,opt.num_elt do + local point = fea_loc[{b,s,{}}] + if point[3] > 0.5 then + local x = math.min(opt.keypoint_dim, + math.max(1,torch.round(point[1] * opt.keypoint_dim))) + local y = math.min(opt.keypoint_dim, + math.max(1,torch.round(point[2] * opt.keypoint_dim))) + data_loc[{b,s,y,x}] = 1 + end + end + end + local images = net_gen:forward({ { noise, fea_txt }, data_loc }):clone() + images:add(1):mul(0.5) + local img = images:select(1,1) + + local locs_tmp = fea_loc:clone() + locs_tmp:narrow(3,1,2):mul(128) + + if showkps==1 then + print(showkps) + print('drawing keypoints...') + img = util.draw_keypoints(img, locs_tmp[1], 0.03) + end + + print(desc) + + local tmp_fname = '/tmp/tmp_bbox.jpeg' + image.save(tmp_fname, img) + local f = assert(io.open(tmp_fname, "rb")) + local img_binary = f:read("*all") + local img_b64 = 'data:image/jpeg;base64,' .. mime.b64(img_binary) + return img_b64,'image/jpeg' + end + +hello:dispatch_get(hello.index,'/','/index') +hello:dispatch_post(hello.request, '/request') +hello:dispatch_static '/resources/images/.+' +hello:dispatch_static '/resources/css/.+' +hello:dispatch_static '/resources/javascript/.+' + +hello:run(...) diff --git a/demo/orbiter/.DS_Store b/demo/orbiter/.DS_Store new file mode 100644 index 0000000..5008ddf Binary files /dev/null and b/demo/orbiter/.DS_Store differ diff --git a/demo/orbiter/bridge.lua b/demo/orbiter/bridge.lua new file mode 100644 index 0000000..84efc72 --- /dev/null +++ b/demo/orbiter/bridge.lua @@ -0,0 +1,38 @@ +-- Orbiter, a personal web application framework +-- orbiter.orbit acts as a bridge for registering static dispatches +-- that works with both Orbiter and Orbit + +local _M = {} + +local app + +function _M.new(app_) + app = app_ +end + +function _M.dispatch_static(...) + -- remember to strip off the starting @ + local path = debug.getinfo(2, "S").source:sub(2):gsub('\\','/') + if path:find '/' then + path = path:gsub('/[%w_]+%.lua$','') + else -- invoked just as script name + path = '.' + end + if orbit then + local function static_handler(web) + local fpath = path..web.path_info + return app:serve_static(web,fpath) + end + app:dispatch_get(static_handler,...) + return app + else + local obj = require 'orbiter'. new() + obj.root = path + obj:dispatch_static(...) + return obj + end +end + +return _M + + diff --git a/demo/orbiter/controls/calendar.lua b/demo/orbiter/controls/calendar.lua new file mode 100644 index 0000000..c5861ce --- /dev/null +++ b/demo/orbiter/controls/calendar.lua @@ -0,0 +1,41 @@ + +-- http://www.softcomplex.com/products/tigra_calendar/ + +local html = require 'orbiter.html' + +-- if extensions use the bridge dispatch_static, then Orbit applications can +-- use this as well! +local bridge = require 'orbiter.bridge' +bridge.dispatch_static('/resources/javascript/calendar.+', +'/resources/css/calendar.+', + '/resources/images/calendar.+') + +local _M = {} +_M.mode = 'us' + +html.set_defaults { + scripts = '/resources/javascript/calendar.js', + styles = '/resources/css/calendar.css' +} + +function _M.set_mode(mode) + _M.mode = mode +end + +function _M.calendar(form,control,mode) + return html.script ( ([[ + new tcal ({ + formname: '%s', + controlname: '%s', + mode: '%s' + }); + ]]):format(form,control,mode) ) +end + +local input = html.tags 'input' + +function _M.date(form,control) + return input{type='text',name=control},_M.calendar(form,control,_M.mode) +end + +return _M diff --git a/demo/orbiter/controls/dropdown.lua b/demo/orbiter/controls/dropdown.lua new file mode 100644 index 0000000..b62c0f6 --- /dev/null +++ b/demo/orbiter/controls/dropdown.lua @@ -0,0 +1,140 @@ +-- A simple drop-down menu +-- http://javascript-array.com/scripts/simple_drop_down_menu/ + +local html=require 'orbiter.html' +local _M = {} + +html.set_defaults { + inline_style = [[ + +#sddm +{ margin: 0; + padding: 0; + z-index: 30 +} + +#sddm li +{ margin: 0; + padding: 0; + list-style: none; + float: left; + font: bold 11px arial +} + +#sddm li a +{ display: block; + margin: 0 1px 0 0; + padding: 4px 10px; + width: 60px; + background: #5970B2; + color: #FFF; + text-align: center; + text-decoration: none +} + +#sddm li a:hover +{ background: #49A3FF} + +#sddm div +{ position: absolute; + visibility: hidden; + margin: 0; + padding: 0; + background: #EAEBD8; + border: 1px solid #5970B2 +} + + #sddm div a + { position: relative; + display: block; + margin: 0; + padding: 5px 10px; + width: auto; + white-space: nowrap; + text-align: left; + text-decoration: none; + background: #EAEBD8; + color: #2875DE; + font: 11px arial + } + + #sddm div a:hover + { background: #49A3FF; + color: #FFF + } + +]], + inline_script = [[ + + + ]], +} +local a,div = html.tags 'a,div' + +local function item(label,idx,items) + local id = "m"..idx + local link = a { href='#',onmouseover="mopen('"..id.."')",onmouseout="mclosetime()", label} + local idiv = div {id = id, onmouseover="mcancelclosetime()" ,onmouseout="mclosetime()"} + local j = 1 + for i = 1,#items,2 do + idiv[j] = html.link(items[i+1],items[i]) + j = j + 1 + end + return { link, idiv } +end + +function _M.menu(items) + local ls = {} + local j = 1 + for i = 1,#items,2 do + ls[j] = item(items[i],j,items[i+1]) + j = j + 1 + end + ls.id = 'sddm' + return {html.list(ls),div {style='clear:both',''}} +end + +return _M -- orbiter.controls.dropdown diff --git a/demo/orbiter/controls/flot.lua b/demo/orbiter/controls/flot.lua new file mode 100644 index 0000000..4506f53 --- /dev/null +++ b/demo/orbiter/controls/flot.lua @@ -0,0 +1,170 @@ + +-- http://www.flotcharts.org + +local html = require 'orbiter.html' +local jq = require 'orbiter.libs.jquery' + +require 'orbiter.bridge'.dispatch_static('/resources/javascript/jquery.+') + +local flot = {} + +html.set_defaults { + scripts = '/resources/javascript/jquery.flot.min.js', +} + +local interactive + +local function set_interactive () + if not interactive then + html.set_defaults { + scripts = '/resources/javascript/jquery.flot.navigate.min.js', + } + interactive = true + end +end + +local function interleave (xv,yv) + local res = {} + for i = 1,#xv do + res[i] = {xv[i],yv[i]} + end + return res +end + +function flot.range (x1,x2,incr) + local res, i = {}, 1 + for x = x1,x2,incr do + res[i] = x + i = i + 1 + end + return res +end + +local concat,append = table.concat,table.insert +local as_js + +flot.null = setmetatable({},{ + __tostring = function(self) return "null" end +}) + +-- you can of course use any available Lua JSON library here - this is good +-- enough for our purposes. +function as_js (t) + local mt = getmetatable(t) + if type(t) ~= 'table' or (mt and mt.__tostring) then + return type(t) == 'string' and '"'..t..'"' or tostring(t) + elseif #t > 0 then -- it's an array! + local res = {} + for i = 1,#t do + res[i] = as_js(t[i]) + end + return '['..concat(res,',')..']' + else + local res = {} + for k,v in pairs(t) do + append(res,k..':'..as_js(v)) + end + return '{'..concat(res,',')..'}' + end +end + +local kount = 0 +local div = html.tags 'div' + +local script = [[ +var plotvar_%s +function plot_%s (data) { + plotvar_%s = $.plot($("#%s"),data,%s); +} +$(function () { + plot_%s (%s); +}); +]] + +function flot.Plot (opts) + local plot = {} + kount = kount + 1 + plot.idx = "flotdiv"..kount + opts = opts or {} + plot.width = opts.width or 600 + plot.height = opts.height or 400 + plot.xvalues = opts.xvalues + opts.width = nil -- no harm, but they're not valid options. + opts.height = nil + opts.xvalues = nil + + -- navigation plugin + if opts.interactive ~= nil then + opts.zoom = {interactive=opts.interactive} + opts.pan = {interactive=opts.interactive} + opts.interactive = nil + end + if opts.zoom or opts.pan then + set_interactive () + end + + local dataset = {} + + function plot:show () + local id, data, options = self.idx, as_js(dataset), as_js(opts) + --local code = render_script(self.idx,as_js(dataset),as_js(opts)) + return div { + div {id=self.idx, style=('width:%spx;height:%spx'):format(self.width,self.height),''}, + html.script(script:format(id,id,id,id,options,id,data)) + } + end + + function plot:update () + return ('plot_%s(%s);'):format(self.idx, as_js(dataset)) + end + + function plot:clear () + dataset = {} + end + + local Series = {} + Series.__index = Series + + function Series:update(data) + if data.x then + data = interleave(data.x,data.y) + elseif plot.xvalues and type(data[1]) ~= 'table' then + data = interleave(plot.xvalues,data) + end + self.data = data + end + + local function new_series (label,data,kind) + local series = setmetatable(kind or { lines = { show = true }},Series) + series.label = label + if data then + series:update(data) + end + return series + end + + function plot:add_series(label,data,kind) + local series = new_series(label,data,kind) + append(dataset,series) + return series + end + + local function plotmethod (name) + plot[name] = function(self) + return 'plotvar_'..self.idx..'.'..name..'()' + end + end + + if interactive then + plotmethod 'zoomOut' + plotmethod 'zoom' + plotmethod 'pan' + end + + + return plot +end + + +return flot + diff --git a/demo/orbiter/controls/modal.lua b/demo/orbiter/controls/modal.lua new file mode 100644 index 0000000..1008940 --- /dev/null +++ b/demo/orbiter/controls/modal.lua @@ -0,0 +1,58 @@ +local jq = require 'orbiter.libs.jquery' +local html = require 'orbiter.html' +local form = require 'orbiter.form' + +local _M = {} + +html.set_defaults { + inline_style = [[ +#modalbox { + position: absolute; + left: 200px; + top: 200px; + background-color: #EEEEFF; + border: 2px solid #000099; +} +#modaltitle { + background-color: #000099; + color: #EEEEFF; +} +#buttonrow { + width: 100%; + background-color: #EEEEFF; +} +]]; + + inline_script = [[ +function jq_close_modal() { + $('#modalbox').remove() +} +]]; +} + +local div,button = html.tags 'div,button' + +local function _show_modal(f,web) + f:prepare(web) + -- we embed the form in a modal box + return jq 'body' : append ( + div { id='modalbox'; + div { id='modaltitle', "Modal Dialog"}, + f:show(); + html.table {id = 'buttonrow'; { + button{"OK",onclick=("jq_submit_form('%s'); jq_close_modal();"):format(f.id)}, + button{"Cancel",onclick="jq_close_modal();"}, + }} + }) +end + +function _M.new (spec) + spec.buttons = {} + local f = form.new(spec) + f.show_modal = _show_modal + return f +end + + + +return _M diff --git a/demo/orbiter/controls/resources/css/calendar.css b/demo/orbiter/controls/resources/css/calendar.css new file mode 100644 index 0000000..a3ddcae --- /dev/null +++ b/demo/orbiter/controls/resources/css/calendar.css @@ -0,0 +1,95 @@ +/* calendar icon */ +img.tcalIcon { + cursor: pointer; + margin-left: 1px; + vertical-align: middle; +} +/* calendar container element */ +div#tcal { + position: absolute; + visibility: hidden; + z-index: 100; + width: 158px; + padding: 2px 0 0 0; +} +/* all tables in calendar */ +div#tcal table { + width: 100%; + border: 1px solid silver; + border-collapse: collapse; + background-color: white; +} +/* navigation table */ +div#tcal table.ctrl { + border-bottom: 0; +} +/* navigation buttons */ +div#tcal table.ctrl td { + width: 15px; + height: 20px; +} +/* month year header */ +div#tcal table.ctrl th { + background-color: white; + color: black; + border: 0; +} +/* week days header */ +div#tcal th { + border: 1px solid silver; + border-collapse: collapse; + text-align: center; + padding: 3px 0; + font-family: tahoma, verdana, arial; + font-size: 10px; + background-color: gray; + color: white; +} +/* date cells */ +div#tcal td { + border: 0; + border-collapse: collapse; + text-align: center; + padding: 2px 0; + font-family: tahoma, verdana, arial; + font-size: 11px; + width: 22px; + cursor: pointer; +} +/* date highlight + in case of conflicting settings order here determines the priority from least to most important */ +div#tcal td.othermonth { + color: silver; +} +div#tcal td.weekend { + background-color: #ACD6F5; +} +div#tcal td.today { + border: 1px solid red; +} +div#tcal td.selected { + background-color: #FFB3BE; +} +/* iframe element used to suppress windowed controls in IE5/6 */ +iframe#tcalIF { + position: absolute; + visibility: hidden; + z-index: 98; + border: 0; +} +/* transparent shadow */ +div#tcalShade { + position: absolute; + visibility: hidden; + z-index: 99; +} +div#tcalShade table { + border: 0; + border-collapse: collapse; + width: 100%; +} +div#tcalShade table td { + border: 0; + border-collapse: collapse; + padding: 0; +} diff --git a/demo/orbiter/controls/resources/images/calendar/cal.gif b/demo/orbiter/controls/resources/images/calendar/cal.gif new file mode 100644 index 0000000..8526cf5 Binary files /dev/null and b/demo/orbiter/controls/resources/images/calendar/cal.gif differ diff --git a/demo/orbiter/controls/resources/images/calendar/next_mon.gif b/demo/orbiter/controls/resources/images/calendar/next_mon.gif new file mode 100644 index 0000000..14c622f Binary files /dev/null and b/demo/orbiter/controls/resources/images/calendar/next_mon.gif differ diff --git a/demo/orbiter/controls/resources/images/calendar/next_year.gif b/demo/orbiter/controls/resources/images/calendar/next_year.gif new file mode 100644 index 0000000..b66f288 Binary files /dev/null and b/demo/orbiter/controls/resources/images/calendar/next_year.gif differ diff --git a/demo/orbiter/controls/resources/images/calendar/no_cal.gif b/demo/orbiter/controls/resources/images/calendar/no_cal.gif new file mode 100644 index 0000000..adc58e2 Binary files /dev/null and b/demo/orbiter/controls/resources/images/calendar/no_cal.gif differ diff --git a/demo/orbiter/controls/resources/images/calendar/pixel.gif b/demo/orbiter/controls/resources/images/calendar/pixel.gif new file mode 100644 index 0000000..46a2cf0 Binary files /dev/null and b/demo/orbiter/controls/resources/images/calendar/pixel.gif differ diff --git a/demo/orbiter/controls/resources/images/calendar/prev_mon.gif b/demo/orbiter/controls/resources/images/calendar/prev_mon.gif new file mode 100644 index 0000000..12ce7ff Binary files /dev/null and b/demo/orbiter/controls/resources/images/calendar/prev_mon.gif differ diff --git a/demo/orbiter/controls/resources/images/calendar/prev_year.gif b/demo/orbiter/controls/resources/images/calendar/prev_year.gif new file mode 100644 index 0000000..c726b0e Binary files /dev/null and b/demo/orbiter/controls/resources/images/calendar/prev_year.gif differ diff --git a/demo/orbiter/controls/resources/images/calendar/shade_bl.png b/demo/orbiter/controls/resources/images/calendar/shade_bl.png new file mode 100644 index 0000000..29bd554 Binary files /dev/null and b/demo/orbiter/controls/resources/images/calendar/shade_bl.png differ diff --git a/demo/orbiter/controls/resources/images/calendar/shade_bm.png b/demo/orbiter/controls/resources/images/calendar/shade_bm.png new file mode 100644 index 0000000..5c4e0af Binary files /dev/null and b/demo/orbiter/controls/resources/images/calendar/shade_bm.png differ diff --git a/demo/orbiter/controls/resources/images/calendar/shade_br.png b/demo/orbiter/controls/resources/images/calendar/shade_br.png new file mode 100644 index 0000000..ce8a2fa Binary files /dev/null and b/demo/orbiter/controls/resources/images/calendar/shade_br.png differ diff --git a/demo/orbiter/controls/resources/images/calendar/shade_mr.png b/demo/orbiter/controls/resources/images/calendar/shade_mr.png new file mode 100644 index 0000000..4594bc4 Binary files /dev/null and b/demo/orbiter/controls/resources/images/calendar/shade_mr.png differ diff --git a/demo/orbiter/controls/resources/images/calendar/shade_tr.png b/demo/orbiter/controls/resources/images/calendar/shade_tr.png new file mode 100644 index 0000000..2e598c9 Binary files /dev/null and b/demo/orbiter/controls/resources/images/calendar/shade_tr.png differ diff --git a/demo/orbiter/controls/resources/javascript/calendar.js b/demo/orbiter/controls/resources/javascript/calendar.js new file mode 100644 index 0000000..6575f2f --- /dev/null +++ b/demo/orbiter/controls/resources/javascript/calendar.js @@ -0,0 +1,357 @@ +// Tigra Calendar v4.0.3 (01/12/2009) American (mm/dd/yyyy) +// http://www.softcomplex.com/products/tigra_calendar/ +// Public Domain Software... You're welcome. +// Multi-domain version: + +// default settins +var A_TCALDEF = { + 'months' : ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'], + 'weekdays' : ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'], + 'yearscroll': true, // show year scroller + 'weekstart': 0, // first day of week: 0-Su or 1-Mo + 'centyear' : 70, // 2 digit years less than 'centyear' are in 20xx, othewise in 19xx. + 'imgpath' : '/resources/images/calendar/' // directory with calendar images +} +// date parsing function +function f_tcalParseDate (s_date) { + + var re_date, format,i_day = 0,i_month = 1; + var mode = this.a_cfg.mode; + if (mode == "us") { + re_date = /^\s*(\d{1,2})\/(\d{1,2})\/(\d{2,4})\s*$/; + format = "mm/dd/yyyy."; + i_day = 1; i_month = 0; + } else if (mode == "eu") { + re_date = /^\s*(\d{1,2})\-(\d{1,2})\-(\d{2,4})\s*$/; + format = "dd-mm-yyyy."; + } else { + re_date = /^\s*(\d{2,4})\-(\d{1,2})\-(\d{1,2})\s*$/; + format = "yyyy-mm-dd."; + } + if (!re_date.exec(s_date)) + return alert ("Invalid date: '" + s_date + "'.\nAccepted format is " + format) + var res = [Number(RegExp.$1),Number(RegExp.$2),Number(RegExp.$3)]; + var n_day = res[i_day],n_month = res[i_month],n_year = res[2]; + + if (n_year < 100) + n_year += (n_year < this.a_tpl.centyear ? 2000 : 1900); + if (n_month < 1 || n_month > 12) + return alert ("Invalid month value: '" + n_month + "'.\nAllowed range is 01-12."); + var d_numdays = new Date(n_year, n_month, 0); + if (n_day > d_numdays.getDate()) + return alert("Invalid day of month value: '" + n_day + "'.\nAllowed range for selected month is 01 - " + d_numdays.getDate() + "."); + + return new Date (n_year, n_month - 1, n_day); +} +// date generating function +function f_tcalGenerDate (d_date) { + var month = (d_date.getMonth() < 9 ? '0' : '') + (d_date.getMonth() + 1); + var day = (d_date.getDate() < 10 ? '0' : '') + d_date.getDate(); + var year = d_date.getFullYear(); + var res,mode = this.a_cfg.mode; + if (mode == "us") + res = month + "/" + day + "/" + year; + else if (mode == "eu") + res = day + "-" + month + "-" + year; + else + res = year + "-" + month + "-" + year; + return res; +} + +// implementation +function tcal (a_cfg, a_tpl) { + + // apply default template if not specified + if (!a_tpl) + a_tpl = A_TCALDEF; + + if (a_cfg.mode == "eu") + a_tpl.weekstart = 1; + + + // register in global collections + if (!window.A_TCALS) + window.A_TCALS = []; + if (!window.A_TCALSIDX) + window.A_TCALSIDX = []; + + this.s_id = a_cfg.id ? a_cfg.id : A_TCALS.length; + window.A_TCALS[this.s_id] = this; + window.A_TCALSIDX[window.A_TCALSIDX.length] = this; + + // assign methods + this.f_show = f_tcalShow; + this.f_hide = f_tcalHide; + this.f_toggle = f_tcalToggle; + this.f_update = f_tcalUpdate; + this.f_relDate = f_tcalRelDate; + this.f_parseDate = f_tcalParseDate; + this.f_generDate = f_tcalGenerDate; + + // create calendar icon + this.s_iconId = 'tcalico_' + this.s_id; + this.e_icon = f_getElement(this.s_iconId); + if (!this.e_icon) { + document.write('Open Calendar'); + this.e_icon = f_getElement(this.s_iconId); + } + // save received parameters + this.a_cfg = a_cfg; + this.a_tpl = a_tpl; +} + +function f_tcalShow (d_date) { + + // find input field + if (!this.a_cfg.controlname) + throw("TC: control name is not specified"); + if (this.a_cfg.formname) { + var e_form = document.forms[this.a_cfg.formname]; + if (!e_form) + throw("TC: form '" + this.a_cfg.formname + "' can not be found"); + this.e_input = e_form.elements[this.a_cfg.controlname]; + } + else + this.e_input = f_getElement(this.a_cfg.controlname); + + if (!this.e_input || !this.e_input.tagName || this.e_input.tagName != 'INPUT') + throw("TC: element '" + this.a_cfg.controlname + "' does not exist in " + + (this.a_cfg.formname ? "form '" + this.a_cfg.controlname + "'" : 'this document')); + + // dynamically create HTML elements if needed + this.e_div = f_getElement('tcal'); + if (!this.e_div) { + this.e_div = document.createElement("DIV"); + this.e_div.id = 'tcal'; + document.body.appendChild(this.e_div); + } + this.e_shade = f_getElement('tcalShade'); + if (!this.e_shade) { + this.e_shade = document.createElement("DIV"); + this.e_shade.id = 'tcalShade'; + document.body.appendChild(this.e_shade); + } + this.e_iframe = f_getElement('tcalIF') + if (b_ieFix && !this.e_iframe) { + this.e_iframe = document.createElement("IFRAME"); + this.e_iframe.style.filter = 'alpha(opacity=0)'; + this.e_iframe.id = 'tcalIF'; + this.e_iframe.src = this.a_tpl.imgpath + 'pixel.gif'; + document.body.appendChild(this.e_iframe); + } + + // hide all calendars + f_tcalHideAll(); + + // generate HTML and show calendar + this.e_icon = f_getElement(this.s_iconId); + if (!this.f_update()) + return; + + this.e_div.style.visibility = 'visible'; + this.e_shade.style.visibility = 'visible'; + if (this.e_iframe) + this.e_iframe.style.visibility = 'visible'; + + // change icon and status + this.e_icon.src = this.a_tpl.imgpath + 'no_cal.gif'; + this.e_icon.title = 'Close Calendar'; + this.b_visible = true; +} + +function f_tcalHide (n_date) { + if (n_date) + this.e_input.value = this.f_generDate(new Date(n_date)); + + // no action if not visible + if (!this.b_visible) + return; + + // hide elements + if (this.e_iframe) + this.e_iframe.style.visibility = 'hidden'; + if (this.e_shade) + this.e_shade.style.visibility = 'hidden'; + this.e_div.style.visibility = 'hidden'; + + // change icon and status + this.e_icon = f_getElement(this.s_iconId); + this.e_icon.src = this.a_tpl.imgpath + 'cal.gif'; + this.e_icon.title = 'Open Calendar'; + this.b_visible = false; +} + +function f_tcalToggle () { + return this.b_visible ? this.f_hide() : this.f_show(); +} + +function f_tcalUpdate (d_date) { + + var d_today = this.a_cfg.today ? this.f_parseDate(this.a_cfg.today) : f_tcalResetTime(new Date()); + var d_selected = this.e_input.value == '' + ? (this.a_cfg.selected ? this.f_parseDate(this.a_cfg.selected) : d_today) + : this.f_parseDate(this.e_input.value); + + // figure out date to display + if (!d_date) + // selected by default + d_date = d_selected; + else if (typeof(d_date) == 'number') + // get from number + d_date = f_tcalResetTime(new Date(d_date)); + else if (typeof(d_date) == 'string') + // parse from string + this.f_parseDate(d_date); + + if (!d_date) return false; + + // first date to display + var d_firstday = new Date(d_date); + d_firstday.setDate(1); + d_firstday.setDate(1 - (7 + d_firstday.getDay() - this.a_tpl.weekstart) % 7); + + var a_class, s_html = '' + + (this.a_tpl.yearscroll ? '' : '') + + '' + + (this.a_tpl.yearscroll ? '' : '') + + '
' + + this.a_tpl.months[d_date.getMonth()] + ' ' + d_date.getFullYear() + + '
'; + + // print weekdays titles + for (var i = 0; i < 7; i++) + s_html += ''; + s_html += '' ; + + // print calendar table + var n_date, n_month, d_current = new Date(d_firstday); + while (d_current.getMonth() == d_date.getMonth() || + d_current.getMonth() == d_firstday.getMonth()) { + + // print row heder + s_html +=''; + for (var n_wday = 0; n_wday < 7; n_wday++) { + + a_class = []; + n_date = d_current.getDate(); + n_month = d_current.getMonth(); + + // other month + if (d_current.getMonth() != d_date.getMonth()) + a_class[a_class.length] = 'othermonth'; + // weekend + if (d_current.getDay() == 0 || d_current.getDay() == 6) + a_class[a_class.length] = 'weekend'; + // today + if (d_current.valueOf() == d_today.valueOf()) + a_class[a_class.length] = 'today'; + // selected + if (d_current.valueOf() == d_selected.valueOf()) + a_class[a_class.length] = 'selected'; + + s_html += '' + + d_current.setDate(++n_date); + while (d_current.getDate() != n_date && d_current.getMonth() == n_month) { + d_current.setHours(d_current.getHours + 1); + d_current = f_tcalResetTime(d_current); + } + } + // print row footer + s_html +=''; + } + s_html +='
' + this.a_tpl.weekdays[(this.a_tpl.weekstart + i) % 7] + '
' : '>') + n_date + '
'; + + // update HTML, positions and sizes + this.e_div.innerHTML = s_html; + + var n_width = this.e_div.offsetWidth; + var n_height = this.e_div.offsetHeight; + var n_top = f_getPosition (this.e_icon, 'Top') + this.e_icon.offsetHeight; + var n_left = f_getPosition (this.e_icon, 'Left') - n_width + this.e_icon.offsetWidth; + if (n_left < 0) n_left = 0; + + this.e_div.style.left = n_left + 'px'; + this.e_div.style.top = n_top + 'px'; + + this.e_shade.style.width = (n_width + 8) + 'px'; + this.e_shade.style.left = (n_left - 1) + 'px'; + this.e_shade.style.top = (n_top - 1) + 'px'; + this.e_shade.innerHTML = b_ieFix + ? '
' + : '
'; + + if (this.e_iframe) { + this.e_iframe.style.left = n_left + 'px'; + this.e_iframe.style.top = n_top + 'px'; + this.e_iframe.style.width = (n_width + 6) + 'px'; + this.e_iframe.style.height = (n_height + 6) +'px'; + } + return true; +} + +function f_getPosition (e_elemRef, s_coord) { + var n_pos = 0, n_offset, + e_elem = e_elemRef; + + while (e_elem) { + n_offset = e_elem["offset" + s_coord]; + n_pos += n_offset; + e_elem = e_elem.offsetParent; + } + // margin correction in some browsers + if (b_ieMac) + n_pos += parseInt(document.body[s_coord.toLowerCase() + 'Margin']); + else if (b_safari) + n_pos -= n_offset; + + e_elem = e_elemRef; + while (e_elem != document.body) { + n_offset = e_elem["scroll" + s_coord]; + if (n_offset && e_elem.style.overflow == 'scroll') + n_pos -= n_offset; + e_elem = e_elem.parentNode; + } + return n_pos; +} + +function f_tcalRelDate (d_date, d_diff, s_units) { + var s_units = (s_units == 'y' ? 'FullYear' : 'Month'); + var d_result = new Date(d_date); + d_result['set' + s_units](d_date['get' + s_units]() + d_diff); + if (d_result.getDate() != d_date.getDate()) + d_result.setDate(0); + return ' onclick="A_TCALS[\'' + this.s_id + '\'].f_update(' + d_result.valueOf() + ')"'; +} + +function f_tcalHideAll () { + for (var i = 0; i < window.A_TCALSIDX.length; i++) + window.A_TCALSIDX[i].f_hide(); +} + +function f_tcalResetTime (d_date) { + d_date.setHours(0); + d_date.setMinutes(0); + d_date.setSeconds(0); + d_date.setMilliseconds(0); + return d_date; +} + +f_getElement = document.all ? + function (s_id) { return document.all[s_id] } : + function (s_id) { return document.getElementById(s_id) }; + +if (document.addEventListener) + window.addEventListener('scroll', f_tcalHideAll, false); +if (window.attachEvent) + window.attachEvent('onscroll', f_tcalHideAll); + +// global variables +var s_userAgent = navigator.userAgent.toLowerCase(), + re_webkit = /WebKit\/(\d+)/i; +var b_mac = s_userAgent.indexOf('mac') != -1, + b_ie5 = s_userAgent.indexOf('msie 5') != -1, + b_ie6 = s_userAgent.indexOf('msie 6') != -1 && s_userAgent.indexOf('opera') == -1; +var b_ieFix = b_ie5 || b_ie6, + b_ieMac = b_mac && b_ie5, + b_safari = b_mac && re_webkit.exec(s_userAgent) && Number(RegExp.$1) < 500; diff --git a/demo/orbiter/controls/resources/javascript/calendar_eu.js b/demo/orbiter/controls/resources/javascript/calendar_eu.js new file mode 100644 index 0000000..6260ed7 --- /dev/null +++ b/demo/orbiter/controls/resources/javascript/calendar_eu.js @@ -0,0 +1,335 @@ +// Tigra Calendar v4.0.2 (12-01-2009) European (dd-mm-yyyy) +// http://www.softcomplex.com/products/tigra_calendar/ +// Public Domain Software... You're welcome. + +// default settins +var A_TCALDEF = { + 'months' : ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'], + 'weekdays' : ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'], + 'yearscroll': true, // show year scroller + 'weekstart': 1, // first day of week: 0-Su or 1-Mo + 'centyear' : 70, // 2 digit years less than 'centyear' are in 20xx, othewise in 19xx. + 'imgpath' : '/resources/images/calendar/' // directory with calendar images +} +// date parsing function +function f_tcalParseDate (s_date) { + + var re_date = /^\s*(\d{1,2})\-(\d{1,2})\-(\d{2,4})\s*$/; + if (!re_date.exec(s_date)) + return alert ("Invalid date: '" + s_date + "'.\nAccepted format is dd-mm-yyyy.") + var n_day = Number(RegExp.$1), + n_month = Number(RegExp.$2), + n_year = Number(RegExp.$3); + + if (n_year < 100) + n_year += (n_year < this.a_tpl.centyear ? 2000 : 1900); + if (n_month < 1 || n_month > 12) + return alert ("Invalid month value: '" + n_month + "'.\nAllowed range is 01-12."); + var d_numdays = new Date(n_year, n_month, 0); + if (n_day > d_numdays.getDate()) + return alert("Invalid day of month value: '" + n_day + "'.\nAllowed range for selected month is 01 - " + d_numdays.getDate() + "."); + + return new Date (n_year, n_month - 1, n_day); +} +// date generating function +function f_tcalGenerDate (d_date) { + return ( + (d_date.getDate() < 10 ? '0' : '') + d_date.getDate() + "-" + + (d_date.getMonth() < 9 ? '0' : '') + (d_date.getMonth() + 1) + "-" + + d_date.getFullYear() + ); +} + +// implementation +function tcal (a_cfg, a_tpl) { + + // apply default template if not specified + if (!a_tpl) + a_tpl = A_TCALDEF; + + // register in global collections + if (!window.A_TCALS) + window.A_TCALS = []; + if (!window.A_TCALSIDX) + window.A_TCALSIDX = []; + + this.s_id = a_cfg.id ? a_cfg.id : A_TCALS.length; + window.A_TCALS[this.s_id] = this; + window.A_TCALSIDX[window.A_TCALSIDX.length] = this; + + // assign methods + this.f_show = f_tcalShow; + this.f_hide = f_tcalHide; + this.f_toggle = f_tcalToggle; + this.f_update = f_tcalUpdate; + this.f_relDate = f_tcalRelDate; + this.f_parseDate = f_tcalParseDate; + this.f_generDate = f_tcalGenerDate; + + // create calendar icon + this.s_iconId = 'tcalico_' + this.s_id; + this.e_icon = f_getElement(this.s_iconId); + if (!this.e_icon) { + document.write('Open Calendar'); + this.e_icon = f_getElement(this.s_iconId); + } + // save received parameters + this.a_cfg = a_cfg; + this.a_tpl = a_tpl; +} + +function f_tcalShow (d_date) { + + // find input field + if (!this.a_cfg.controlname) + throw("TC: control name is not specified"); + if (this.a_cfg.formname) { + var e_form = document.forms[this.a_cfg.formname]; + if (!e_form) + throw("TC: form '" + this.a_cfg.formname + "' can not be found"); + this.e_input = e_form.elements[this.a_cfg.controlname]; + } + else + this.e_input = f_getElement(this.a_cfg.controlname); + + if (!this.e_input || !this.e_input.tagName || this.e_input.tagName != 'INPUT') + throw("TC: element '" + this.a_cfg.controlname + "' does not exist in " + + (this.a_cfg.formname ? "form '" + this.a_cfg.controlname + "'" : 'this document')); + + // dynamically create HTML elements if needed + this.e_div = f_getElement('tcal'); + if (!this.e_div) { + this.e_div = document.createElement("DIV"); + this.e_div.id = 'tcal'; + document.body.appendChild(this.e_div); + } + this.e_shade = f_getElement('tcalShade'); + if (!this.e_shade) { + this.e_shade = document.createElement("DIV"); + this.e_shade.id = 'tcalShade'; + document.body.appendChild(this.e_shade); + } + this.e_iframe = f_getElement('tcalIF') + if (b_ieFix && !this.e_iframe) { + this.e_iframe = document.createElement("IFRAME"); + this.e_iframe.style.filter = 'alpha(opacity=0)'; + this.e_iframe.id = 'tcalIF'; + this.e_iframe.src = this.a_tpl.imgpath + 'pixel.gif'; + document.body.appendChild(this.e_iframe); + } + + // hide all calendars + f_tcalHideAll(); + + // generate HTML and show calendar + this.e_icon = f_getElement(this.s_iconId); + if (!this.f_update()) + return; + + this.e_div.style.visibility = 'visible'; + this.e_shade.style.visibility = 'visible'; + if (this.e_iframe) + this.e_iframe.style.visibility = 'visible'; + + // change icon and status + this.e_icon.src = this.a_tpl.imgpath + 'no_cal.gif'; + this.e_icon.title = 'Close Calendar'; + this.b_visible = true; +} + +function f_tcalHide (n_date) { + if (n_date) + this.e_input.value = this.f_generDate(new Date(n_date)); + + // no action if not visible + if (!this.b_visible) + return; + + // hide elements + if (this.e_iframe) + this.e_iframe.style.visibility = 'hidden'; + if (this.e_shade) + this.e_shade.style.visibility = 'hidden'; + this.e_div.style.visibility = 'hidden'; + + // change icon and status + this.e_icon = f_getElement(this.s_iconId); + this.e_icon.src = this.a_tpl.imgpath + 'cal.gif'; + this.e_icon.title = 'Open Calendar'; + this.b_visible = false; +} + +function f_tcalToggle () { + return this.b_visible ? this.f_hide() : this.f_show(); +} + +function f_tcalUpdate (d_date) { + + var d_today = this.a_cfg.today ? this.f_parseDate(this.a_cfg.today) : f_tcalResetTime(new Date()); + var d_selected = this.e_input.value == '' + ? (this.a_cfg.selected ? this.f_parseDate(this.a_cfg.selected) : d_today) + : this.f_parseDate(this.e_input.value); + + // figure out date to display + if (!d_date) + // selected by default + d_date = d_selected; + else if (typeof(d_date) == 'number') + // get from number + d_date = f_tcalResetTime(new Date(d_date)); + else if (typeof(d_date) == 'string') + // parse from string + this.f_parseDate(d_date); + + if (!d_date) return false; + + // first date to display + var d_firstday = new Date(d_date); + d_firstday.setDate(1); + d_firstday.setDate(1 - (7 + d_firstday.getDay() - this.a_tpl.weekstart) % 7); + + var a_class, s_html = '' + + (this.a_tpl.yearscroll ? '' : '') + + '' + + (this.a_tpl.yearscroll ? '' : '') + + '
' + + this.a_tpl.months[d_date.getMonth()] + ' ' + d_date.getFullYear() + + '
'; + + // print weekdays titles + for (var i = 0; i < 7; i++) + s_html += ''; + s_html += '' ; + + // print calendar table + var n_date, n_month, d_current = new Date(d_firstday); + while (d_current.getMonth() == d_date.getMonth() || + d_current.getMonth() == d_firstday.getMonth()) { + + // print row heder + s_html +=''; + for (var n_wday = 0; n_wday < 7; n_wday++) { + + a_class = []; + n_date = d_current.getDate(); + n_month = d_current.getMonth(); + + // other month + if (d_current.getMonth() != d_date.getMonth()) + a_class[a_class.length] = 'othermonth'; + // weekend + if (d_current.getDay() == 0 || d_current.getDay() == 6) + a_class[a_class.length] = 'weekend'; + // today + if (d_current.valueOf() == d_today.valueOf()) + a_class[a_class.length] = 'today'; + // selected + if (d_current.valueOf() == d_selected.valueOf()) + a_class[a_class.length] = 'selected'; + + s_html += '' + + d_current.setDate(++n_date); + while (d_current.getDate() != n_date && d_current.getMonth() == n_month) { + d_current.setHours(d_current.getHours + 1); + d_current = f_tcalResetTime(d_current); + } + } + // print row footer + s_html +=''; + } + s_html +='
' + this.a_tpl.weekdays[(this.a_tpl.weekstart + i) % 7] + '
' : '>') + n_date + '
'; + + // update HTML, positions and sizes + this.e_div.innerHTML = s_html; + + var n_width = this.e_div.offsetWidth; + var n_height = this.e_div.offsetHeight; + var n_top = f_getPosition (this.e_icon, 'Top') + this.e_icon.offsetHeight; + var n_left = f_getPosition (this.e_icon, 'Left') - n_width + this.e_icon.offsetWidth; + if (n_left < 0) n_left = 0; + + this.e_div.style.left = n_left + 'px'; + this.e_div.style.top = n_top + 'px'; + + this.e_shade.style.width = (n_width + 8) + 'px'; + this.e_shade.style.left = (n_left - 1) + 'px'; + this.e_shade.style.top = (n_top - 1) + 'px'; + this.e_shade.innerHTML = b_ieFix + ? '
' + : '
'; + + if (this.e_iframe) { + this.e_iframe.style.left = n_left + 'px'; + this.e_iframe.style.top = n_top + 'px'; + this.e_iframe.style.width = (n_width + 6) + 'px'; + this.e_iframe.style.height = (n_height + 6) +'px'; + } + return true; +} + +function f_getPosition (e_elemRef, s_coord) { + var n_pos = 0, n_offset, + e_elem = e_elemRef; + + while (e_elem) { + n_offset = e_elem["offset" + s_coord]; + n_pos += n_offset; + e_elem = e_elem.offsetParent; + } + // margin correction in some browsers + if (b_ieMac) + n_pos += parseInt(document.body[s_coord.toLowerCase() + 'Margin']); + else if (b_safari) + n_pos -= n_offset; + + e_elem = e_elemRef; + while (e_elem != document.body) { + n_offset = e_elem["scroll" + s_coord]; + if (n_offset && e_elem.style.overflow == 'scroll') + n_pos -= n_offset; + e_elem = e_elem.parentNode; + } + return n_pos; +} + +function f_tcalRelDate (d_date, d_diff, s_units) { + var s_units = (s_units == 'y' ? 'FullYear' : 'Month'); + var d_result = new Date(d_date); + d_result['set' + s_units](d_date['get' + s_units]() + d_diff); + if (d_result.getDate() != d_date.getDate()) + d_result.setDate(0); + return ' onclick="A_TCALS[\'' + this.s_id + '\'].f_update(' + d_result.valueOf() + ')"'; +} + +function f_tcalHideAll () { + for (var i = 0; i < window.A_TCALSIDX.length; i++) + window.A_TCALSIDX[i].f_hide(); +} + +function f_tcalResetTime (d_date) { + d_date.setHours(0); + d_date.setMinutes(0); + d_date.setSeconds(0); + d_date.setMilliseconds(0); + return d_date; +} + +f_getElement = document.all ? + function (s_id) { return document.all[s_id] } : + function (s_id) { return document.getElementById(s_id) }; + +if (document.addEventListener) + window.addEventListener('scroll', f_tcalHideAll, false); +if (window.attachEvent) + window.attachEvent('onscroll', f_tcalHideAll); + +// global variables +var s_userAgent = navigator.userAgent.toLowerCase(), + re_webkit = /WebKit\/(\d+)/i; +var b_mac = s_userAgent.indexOf('mac') != -1, + b_ie5 = s_userAgent.indexOf('msie 5') != -1, + b_ie6 = s_userAgent.indexOf('msie 6') != -1 && s_userAgent.indexOf('opera') == -1; +var b_ieFix = b_ie5 || b_ie6, + b_ieMac = b_mac && b_ie5, + b_safari = b_mac && re_webkit.exec(s_userAgent) && Number(RegExp.$1) < 500; diff --git a/demo/orbiter/controls/resources/javascript/jquery.flot.min.js b/demo/orbiter/controls/resources/javascript/jquery.flot.min.js new file mode 100644 index 0000000..4467fc5 --- /dev/null +++ b/demo/orbiter/controls/resources/javascript/jquery.flot.min.js @@ -0,0 +1,6 @@ +/* Javascript plotting library for jQuery, v. 0.7. + * + * Released under the MIT license by IOLA, December 2007. + * + */ +(function(b){b.color={};b.color.make=function(d,e,g,f){var c={};c.r=d||0;c.g=e||0;c.b=g||0;c.a=f!=null?f:1;c.add=function(h,j){for(var k=0;k=1){return"rgb("+[c.r,c.g,c.b].join(",")+")"}else{return"rgba("+[c.r,c.g,c.b,c.a].join(",")+")"}};c.normalize=function(){function h(k,j,l){return jl?l:j)}c.r=h(0,parseInt(c.r),255);c.g=h(0,parseInt(c.g),255);c.b=h(0,parseInt(c.b),255);c.a=h(0,c.a,1);return c};c.clone=function(){return b.color.make(c.r,c.b,c.g,c.a)};return c.normalize()};b.color.extract=function(d,e){var c;do{c=d.css(e).toLowerCase();if(c!=""&&c!="transparent"){break}d=d.parent()}while(!b.nodeName(d.get(0),"body"));if(c=="rgba(0, 0, 0, 0)"){c="transparent"}return b.color.parse(c)};b.color.parse=function(c){var d,f=b.color.make;if(d=/rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(c)){return f(parseInt(d[1],10),parseInt(d[2],10),parseInt(d[3],10))}if(d=/rgba\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]+(?:\.[0-9]+)?)\s*\)/.exec(c)){return f(parseInt(d[1],10),parseInt(d[2],10),parseInt(d[3],10),parseFloat(d[4]))}if(d=/rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(c)){return f(parseFloat(d[1])*2.55,parseFloat(d[2])*2.55,parseFloat(d[3])*2.55)}if(d=/rgba\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\s*\)/.exec(c)){return f(parseFloat(d[1])*2.55,parseFloat(d[2])*2.55,parseFloat(d[3])*2.55,parseFloat(d[4]))}if(d=/#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(c)){return f(parseInt(d[1],16),parseInt(d[2],16),parseInt(d[3],16))}if(d=/#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(c)){return f(parseInt(d[1]+d[1],16),parseInt(d[2]+d[2],16),parseInt(d[3]+d[3],16))}var e=b.trim(c).toLowerCase();if(e=="transparent"){return f(255,255,255,0)}else{d=a[e]||[0,0,0];return f(d[0],d[1],d[2])}};var a={aqua:[0,255,255],azure:[240,255,255],beige:[245,245,220],black:[0,0,0],blue:[0,0,255],brown:[165,42,42],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgrey:[169,169,169],darkgreen:[0,100,0],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkviolet:[148,0,211],fuchsia:[255,0,255],gold:[255,215,0],green:[0,128,0],indigo:[75,0,130],khaki:[240,230,140],lightblue:[173,216,230],lightcyan:[224,255,255],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightyellow:[255,255,224],lime:[0,255,0],magenta:[255,0,255],maroon:[128,0,0],navy:[0,0,128],olive:[128,128,0],orange:[255,165,0],pink:[255,192,203],purple:[128,0,128],violet:[128,0,128],red:[255,0,0],silver:[192,192,192],white:[255,255,255],yellow:[255,255,0]}})(jQuery);(function(c){function b(av,ai,J,af){var Q=[],O={colors:["#edc240","#afd8f8","#cb4b4b","#4da74d","#9440ed"],legend:{show:true,noColumns:1,labelFormatter:null,labelBoxBorderColor:"#ccc",container:null,position:"ne",margin:5,backgroundColor:null,backgroundOpacity:0.85},xaxis:{show:null,position:"bottom",mode:null,color:null,tickColor:null,transform:null,inverseTransform:null,min:null,max:null,autoscaleMargin:null,ticks:null,tickFormatter:null,labelWidth:null,labelHeight:null,reserveSpace:null,tickLength:null,alignTicksWithAxis:null,tickDecimals:null,tickSize:null,minTickSize:null,monthNames:null,timeformat:null,twelveHourClock:false},yaxis:{autoscaleMargin:0.02,position:"left"},xaxes:[],yaxes:[],series:{points:{show:false,radius:3,lineWidth:2,fill:true,fillColor:"#ffffff",symbol:"circle"},lines:{lineWidth:2,fill:false,fillColor:null,steps:false},bars:{show:false,lineWidth:2,barWidth:1,fill:true,fillColor:null,align:"left",horizontal:false},shadowSize:3},grid:{show:true,aboveData:false,color:"#545454",backgroundColor:null,borderColor:null,tickColor:null,labelMargin:5,axisMargin:8,borderWidth:2,minBorderMargin:null,markings:null,markingsColor:"#f4f4f4",markingsLineWidth:2,clickable:false,hoverable:false,autoHighlight:true,mouseActiveRadius:10},hooks:{}},az=null,ad=null,y=null,H=null,A=null,p=[],aw=[],q={left:0,right:0,top:0,bottom:0},G=0,I=0,h=0,w=0,ak={processOptions:[],processRawData:[],processDatapoints:[],drawSeries:[],draw:[],bindEvents:[],drawOverlay:[],shutdown:[]},aq=this;aq.setData=aj;aq.setupGrid=t;aq.draw=W;aq.getPlaceholder=function(){return av};aq.getCanvas=function(){return az};aq.getPlotOffset=function(){return q};aq.width=function(){return h};aq.height=function(){return w};aq.offset=function(){var aB=y.offset();aB.left+=q.left;aB.top+=q.top;return aB};aq.getData=function(){return Q};aq.getAxes=function(){var aC={},aB;c.each(p.concat(aw),function(aD,aE){if(aE){aC[aE.direction+(aE.n!=1?aE.n:"")+"axis"]=aE}});return aC};aq.getXAxes=function(){return p};aq.getYAxes=function(){return aw};aq.c2p=C;aq.p2c=ar;aq.getOptions=function(){return O};aq.highlight=x;aq.unhighlight=T;aq.triggerRedrawOverlay=f;aq.pointOffset=function(aB){return{left:parseInt(p[aA(aB,"x")-1].p2c(+aB.x)+q.left),top:parseInt(aw[aA(aB,"y")-1].p2c(+aB.y)+q.top)}};aq.shutdown=ag;aq.resize=function(){B();g(az);g(ad)};aq.hooks=ak;F(aq);Z(J);X();aj(ai);t();W();ah();function an(aD,aB){aB=[aq].concat(aB);for(var aC=0;aC=O.colors.length){aG=0;++aF}}var aH=0,aN;for(aG=0;aGa3.datamax&&a1!=aB){a3.datamax=a1}}c.each(m(),function(a1,a2){a2.datamin=aO;a2.datamax=aI;a2.used=false});for(aU=0;aU0&&aT[aR-aP]!=null&&aT[aR-aP]!=aT[aR]&&aT[aR-aP+1]!=aT[aR+1]){for(aN=0;aNaM){aM=a0}}if(aX.y){if(a0aV){aV=a0}}}}if(aJ.bars.show){var aY=aJ.bars.align=="left"?0:-aJ.bars.barWidth/2;if(aJ.bars.horizontal){aQ+=aY;aV+=aY+aJ.bars.barWidth}else{aK+=aY;aM+=aY+aJ.bars.barWidth}}aF(aJ.xaxis,aK,aM);aF(aJ.yaxis,aQ,aV)}c.each(m(),function(a1,a2){if(a2.datamin==aO){a2.datamin=null}if(a2.datamax==aI){a2.datamax=null}})}function j(aB,aC){var aD=document.createElement("canvas");aD.className=aC;aD.width=G;aD.height=I;if(!aB){c(aD).css({position:"absolute",left:0,top:0})}c(aD).appendTo(av);if(!aD.getContext){aD=window.G_vmlCanvasManager.initElement(aD)}aD.getContext("2d").save();return aD}function B(){G=av.width();I=av.height();if(G<=0||I<=0){throw"Invalid dimensions for plot, width = "+G+", height = "+I}}function g(aC){if(aC.width!=G){aC.width=G}if(aC.height!=I){aC.height=I}var aB=aC.getContext("2d");aB.restore();aB.save()}function X(){var aC,aB=av.children("canvas.base"),aD=av.children("canvas.overlay");if(aB.length==0||aD==0){av.html("");av.css({padding:0});if(av.css("position")=="static"){av.css("position","relative")}B();az=j(true,"base");ad=j(false,"overlay");aC=false}else{az=aB.get(0);ad=aD.get(0);aC=true}H=az.getContext("2d");A=ad.getContext("2d");y=c([ad,az]);if(aC){av.data("plot").shutdown();aq.resize();A.clearRect(0,0,G,I);y.unbind();av.children().not([az,ad]).remove()}av.data("plot",aq)}function ah(){if(O.grid.hoverable){y.mousemove(aa);y.mouseleave(l)}if(O.grid.clickable){y.click(R)}an(ak.bindEvents,[y])}function ag(){if(M){clearTimeout(M)}y.unbind("mousemove",aa);y.unbind("mouseleave",l);y.unbind("click",R);an(ak.shutdown,[y])}function r(aG){function aC(aH){return aH}var aF,aB,aD=aG.options.transform||aC,aE=aG.options.inverseTransform;if(aG.direction=="x"){aF=aG.scale=h/Math.abs(aD(aG.max)-aD(aG.min));aB=Math.min(aD(aG.max),aD(aG.min))}else{aF=aG.scale=w/Math.abs(aD(aG.max)-aD(aG.min));aF=-aF;aB=Math.max(aD(aG.max),aD(aG.min))}if(aD==aC){aG.p2c=function(aH){return(aH-aB)*aF}}else{aG.p2c=function(aH){return(aD(aH)-aB)*aF}}if(!aE){aG.c2p=function(aH){return aB+aH/aF}}else{aG.c2p=function(aH){return aE(aB+aH/aF)}}}function L(aD){var aB=aD.options,aF,aJ=aD.ticks||[],aI=[],aE,aK=aB.labelWidth,aG=aB.labelHeight,aC;function aH(aM,aL){return c('
'+aM.join("")+"
").appendTo(av)}if(aD.direction=="x"){if(aK==null){aK=Math.floor(G/(aJ.length>0?aJ.length:1))}if(aG==null){aI=[];for(aF=0;aF'+aE+"")}}if(aI.length>0){aI.push('
');aC=aH(aI,"width:10000px;");aG=aC.height();aC.remove()}}}else{if(aK==null||aG==null){for(aF=0;aF'+aE+"")}}if(aI.length>0){aC=aH(aI,"");if(aK==null){aK=aC.children().width()}if(aG==null){aG=aC.find("div.tickLabel").height()}aC.remove()}}}if(aK==null){aK=0}if(aG==null){aG=0}aD.labelWidth=aK;aD.labelHeight=aG}function au(aD){var aC=aD.labelWidth,aL=aD.labelHeight,aH=aD.options.position,aF=aD.options.tickLength,aG=O.grid.axisMargin,aJ=O.grid.labelMargin,aK=aD.direction=="x"?p:aw,aE;var aB=c.grep(aK,function(aN){return aN&&aN.options.position==aH&&aN.reserveSpace});if(c.inArray(aD,aB)==aB.length-1){aG=0}if(aF==null){aF="full"}var aI=c.grep(aK,function(aN){return aN&&aN.reserveSpace});var aM=c.inArray(aD,aI)==0;if(!aM&&aF=="full"){aF=5}if(!isNaN(+aF)){aJ+=+aF}if(aD.direction=="x"){aL+=aJ;if(aH=="bottom"){q.bottom+=aL+aG;aD.box={top:I-q.bottom,height:aL}}else{aD.box={top:q.top+aG,height:aL};q.top+=aL+aG}}else{aC+=aJ;if(aH=="left"){aD.box={left:q.left+aG,width:aC};q.left+=aC+aG}else{q.right+=aC+aG;aD.box={left:G-q.right,width:aC}}}aD.position=aH;aD.tickLength=aF;aD.box.padding=aJ;aD.innermost=aM}function U(aB){if(aB.direction=="x"){aB.box.left=q.left;aB.box.width=h}else{aB.box.top=q.top;aB.box.height=w}}function t(){var aC,aE=m();c.each(aE,function(aF,aG){aG.show=aG.options.show;if(aG.show==null){aG.show=aG.used}aG.reserveSpace=aG.show||aG.options.reserveSpace;n(aG)});allocatedAxes=c.grep(aE,function(aF){return aF.reserveSpace});q.left=q.right=q.top=q.bottom=0;if(O.grid.show){c.each(allocatedAxes,function(aF,aG){S(aG);P(aG);ap(aG,aG.ticks);L(aG)});for(aC=allocatedAxes.length-1;aC>=0;--aC){au(allocatedAxes[aC])}var aD=O.grid.minBorderMargin;if(aD==null){aD=0;for(aC=0;aC=0){aD=0}}if(aF.max==null){aB+=aH*aG;if(aB>0&&aE.datamax!=null&&aE.datamax<=0){aB=0}}}}aE.min=aD;aE.max=aB}function S(aG){var aM=aG.options;var aH;if(typeof aM.ticks=="number"&&aM.ticks>0){aH=aM.ticks}else{aH=0.3*Math.sqrt(aG.direction=="x"?G:I)}var aT=(aG.max-aG.min)/aH,aO,aB,aN,aR,aS,aQ,aI;if(aM.mode=="time"){var aJ={second:1000,minute:60*1000,hour:60*60*1000,day:24*60*60*1000,month:30*24*60*60*1000,year:365.2425*24*60*60*1000};var aK=[[1,"second"],[2,"second"],[5,"second"],[10,"second"],[30,"second"],[1,"minute"],[2,"minute"],[5,"minute"],[10,"minute"],[30,"minute"],[1,"hour"],[2,"hour"],[4,"hour"],[8,"hour"],[12,"hour"],[1,"day"],[2,"day"],[3,"day"],[0.25,"month"],[0.5,"month"],[1,"month"],[2,"month"],[3,"month"],[6,"month"],[1,"year"]];var aC=0;if(aM.minTickSize!=null){if(typeof aM.tickSize=="number"){aC=aM.tickSize}else{aC=aM.minTickSize[0]*aJ[aM.minTickSize[1]]}}for(var aS=0;aS=aC){break}}aO=aK[aS][0];aN=aK[aS][1];if(aN=="year"){aQ=Math.pow(10,Math.floor(Math.log(aT/aJ.year)/Math.LN10));aI=(aT/aJ.year)/aQ;if(aI<1.5){aO=1}else{if(aI<3){aO=2}else{if(aI<7.5){aO=5}else{aO=10}}}aO*=aQ}aG.tickSize=aM.tickSize||[aO,aN];aB=function(aX){var a2=[],a0=aX.tickSize[0],a3=aX.tickSize[1],a1=new Date(aX.min);var aW=a0*aJ[a3];if(a3=="second"){a1.setUTCSeconds(a(a1.getUTCSeconds(),a0))}if(a3=="minute"){a1.setUTCMinutes(a(a1.getUTCMinutes(),a0))}if(a3=="hour"){a1.setUTCHours(a(a1.getUTCHours(),a0))}if(a3=="month"){a1.setUTCMonth(a(a1.getUTCMonth(),a0))}if(a3=="year"){a1.setUTCFullYear(a(a1.getUTCFullYear(),a0))}a1.setUTCMilliseconds(0);if(aW>=aJ.minute){a1.setUTCSeconds(0)}if(aW>=aJ.hour){a1.setUTCMinutes(0)}if(aW>=aJ.day){a1.setUTCHours(0)}if(aW>=aJ.day*4){a1.setUTCDate(1)}if(aW>=aJ.year){a1.setUTCMonth(0)}var a5=0,a4=Number.NaN,aY;do{aY=a4;a4=a1.getTime();a2.push(a4);if(a3=="month"){if(a0<1){a1.setUTCDate(1);var aV=a1.getTime();a1.setUTCMonth(a1.getUTCMonth()+1);var aZ=a1.getTime();a1.setTime(a4+a5*aJ.hour+(aZ-aV)*a0);a5=a1.getUTCHours();a1.setUTCHours(0)}else{a1.setUTCMonth(a1.getUTCMonth()+a0)}}else{if(a3=="year"){a1.setUTCFullYear(a1.getUTCFullYear()+a0)}else{a1.setTime(a4+aW)}}}while(a4aU){aP=aU}aQ=Math.pow(10,-aP);aI=aT/aQ;if(aI<1.5){aO=1}else{if(aI<3){aO=2;if(aI>2.25&&(aU==null||aP+1<=aU)){aO=2.5;++aP}}else{if(aI<7.5){aO=5}else{aO=10}}}aO*=aQ;if(aM.minTickSize!=null&&aO0){if(aM.min==null){aG.min=Math.min(aG.min,aL[0])}if(aM.max==null&&aL.length>1){aG.max=Math.max(aG.max,aL[aL.length-1])}}aB=function(aX){var aY=[],aV,aW;for(aW=0;aW1&&/\..*0$/.test((aD[1]-aD[0]).toFixed(aE)))){aG.tickDecimals=aE}}}}aG.tickGenerator=aB;if(c.isFunction(aM.tickFormatter)){aG.tickFormatter=function(aV,aW){return""+aM.tickFormatter(aV,aW)}}else{aG.tickFormatter=aR}}function P(aF){var aH=aF.options.ticks,aG=[];if(aH==null||(typeof aH=="number"&&aH>0)){aG=aF.tickGenerator(aF)}else{if(aH){if(c.isFunction(aH)){aG=aH({min:aF.min,max:aF.max})}else{aG=aH}}}var aE,aB;aF.ticks=[];for(aE=0;aE1){aC=aD[1]}}else{aB=+aD}if(aC==null){aC=aF.tickFormatter(aB,aF)}if(!isNaN(aB)){aF.ticks.push({v:aB,label:aC})}}}function ap(aB,aC){if(aB.options.autoscaleMargin&&aC.length>0){if(aB.options.min==null){aB.min=Math.min(aB.min,aC[0].v)}if(aB.options.max==null&&aC.length>1){aB.max=Math.max(aB.max,aC[aC.length-1].v)}}}function W(){H.clearRect(0,0,G,I);var aC=O.grid;if(aC.show&&aC.backgroundColor){N()}if(aC.show&&!aC.aboveData){ac()}for(var aB=0;aBaG){var aC=aH;aH=aG;aG=aC}return{from:aH,to:aG,axis:aE}}function N(){H.save();H.translate(q.left,q.top);H.fillStyle=am(O.grid.backgroundColor,w,0,"rgba(255, 255, 255, 0)");H.fillRect(0,0,h,w);H.restore()}function ac(){var aF;H.save();H.translate(q.left,q.top);var aH=O.grid.markings;if(aH){if(c.isFunction(aH)){var aK=aq.getAxes();aK.xmin=aK.xaxis.min;aK.xmax=aK.xaxis.max;aK.ymin=aK.yaxis.min;aK.ymax=aK.yaxis.max;aH=aH(aK)}for(aF=0;aFaC.axis.max||aI.toaI.axis.max){continue}aC.from=Math.max(aC.from,aC.axis.min);aC.to=Math.min(aC.to,aC.axis.max);aI.from=Math.max(aI.from,aI.axis.min);aI.to=Math.min(aI.to,aI.axis.max);if(aC.from==aC.to&&aI.from==aI.to){continue}aC.from=aC.axis.p2c(aC.from);aC.to=aC.axis.p2c(aC.to);aI.from=aI.axis.p2c(aI.from);aI.to=aI.axis.p2c(aI.to);if(aC.from==aC.to||aI.from==aI.to){H.beginPath();H.strokeStyle=aD.color||O.grid.markingsColor;H.lineWidth=aD.lineWidth||O.grid.markingsLineWidth;H.moveTo(aC.from,aI.from);H.lineTo(aC.to,aI.to);H.stroke()}else{H.fillStyle=aD.color||O.grid.markingsColor;H.fillRect(aC.from,aI.to,aC.to-aC.from,aI.from-aI.to)}}}var aK=m(),aM=O.grid.borderWidth;for(var aE=0;aEaB.max||(aQ=="full"&&aM>0&&(aO==aB.min||aO==aB.max))){continue}if(aB.direction=="x"){aN=aB.p2c(aO);aJ=aQ=="full"?-w:aQ;if(aB.position=="top"){aJ=-aJ}}else{aL=aB.p2c(aO);aP=aQ=="full"?-h:aQ;if(aB.position=="left"){aP=-aP}}if(H.lineWidth==1){if(aB.direction=="x"){aN=Math.floor(aN)+0.5}else{aL=Math.floor(aL)+0.5}}H.moveTo(aN,aL);H.lineTo(aN+aP,aL+aJ)}H.stroke()}if(aM){H.lineWidth=aM;H.strokeStyle=O.grid.borderColor;H.strokeRect(-aM/2,-aM/2,h+aM,w+aM)}H.restore()}function k(){av.find(".tickLabels").remove();var aG=['
'];var aJ=m();for(var aD=0;aD');for(var aE=0;aEaC.max){continue}var aK={},aI;if(aC.direction=="x"){aI="center";aK.left=Math.round(q.left+aC.p2c(aH.v)-aC.labelWidth/2);if(aC.position=="bottom"){aK.top=aF.top+aF.padding}else{aK.bottom=I-(aF.top+aF.height-aF.padding)}}else{aK.top=Math.round(q.top+aC.p2c(aH.v)-aC.labelHeight/2);if(aC.position=="left"){aK.right=G-(aF.left+aF.width-aF.padding);aI="right"}else{aK.left=aF.left+aF.padding;aI="left"}}aK.width=aC.labelWidth;var aB=["position:absolute","text-align:"+aI];for(var aL in aK){aB.push(aL+":"+aK[aL]+"px")}aG.push('
'+aH.label+"
")}aG.push("
")}aG.push("");av.append(aG.join(""))}function d(aB){if(aB.lines.show){at(aB)}if(aB.bars.show){e(aB)}if(aB.points.show){ao(aB)}}function at(aE){function aD(aP,aQ,aI,aU,aT){var aV=aP.points,aJ=aP.pointsize,aN=null,aM=null;H.beginPath();for(var aO=aJ;aO=aR&&aS>aT.max){if(aR>aT.max){continue}aL=(aT.max-aS)/(aR-aS)*(aK-aL)+aL;aS=aT.max}else{if(aR>=aS&&aR>aT.max){if(aS>aT.max){continue}aK=(aT.max-aS)/(aR-aS)*(aK-aL)+aL;aR=aT.max}}if(aL<=aK&&aL=aK&&aL>aU.max){if(aK>aU.max){continue}aS=(aU.max-aL)/(aK-aL)*(aR-aS)+aS;aL=aU.max}else{if(aK>=aL&&aK>aU.max){if(aL>aU.max){continue}aR=(aU.max-aL)/(aK-aL)*(aR-aS)+aS;aK=aU.max}}if(aL!=aN||aS!=aM){H.moveTo(aU.p2c(aL)+aQ,aT.p2c(aS)+aI)}aN=aK;aM=aR;H.lineTo(aU.p2c(aK)+aQ,aT.p2c(aR)+aI)}H.stroke()}function aF(aI,aQ,aP){var aW=aI.points,aV=aI.pointsize,aN=Math.min(Math.max(0,aP.min),aP.max),aX=0,aU,aT=false,aM=1,aL=0,aR=0;while(true){if(aV>0&&aX>aW.length+aV){break}aX+=aV;var aZ=aW[aX-aV],aK=aW[aX-aV+aM],aY=aW[aX],aJ=aW[aX+aM];if(aT){if(aV>0&&aZ!=null&&aY==null){aR=aX;aV=-aV;aM=2;continue}if(aV<0&&aX==aL+aV){H.fill();aT=false;aV=-aV;aM=1;aX=aL=aR+aV;continue}}if(aZ==null||aY==null){continue}if(aZ<=aY&&aZ=aY&&aZ>aQ.max){if(aY>aQ.max){continue}aK=(aQ.max-aZ)/(aY-aZ)*(aJ-aK)+aK;aZ=aQ.max}else{if(aY>=aZ&&aY>aQ.max){if(aZ>aQ.max){continue}aJ=(aQ.max-aZ)/(aY-aZ)*(aJ-aK)+aK;aY=aQ.max}}if(!aT){H.beginPath();H.moveTo(aQ.p2c(aZ),aP.p2c(aN));aT=true}if(aK>=aP.max&&aJ>=aP.max){H.lineTo(aQ.p2c(aZ),aP.p2c(aP.max));H.lineTo(aQ.p2c(aY),aP.p2c(aP.max));continue}else{if(aK<=aP.min&&aJ<=aP.min){H.lineTo(aQ.p2c(aZ),aP.p2c(aP.min));H.lineTo(aQ.p2c(aY),aP.p2c(aP.min));continue}}var aO=aZ,aS=aY;if(aK<=aJ&&aK=aP.min){aZ=(aP.min-aK)/(aJ-aK)*(aY-aZ)+aZ;aK=aP.min}else{if(aJ<=aK&&aJ=aP.min){aY=(aP.min-aK)/(aJ-aK)*(aY-aZ)+aZ;aJ=aP.min}}if(aK>=aJ&&aK>aP.max&&aJ<=aP.max){aZ=(aP.max-aK)/(aJ-aK)*(aY-aZ)+aZ;aK=aP.max}else{if(aJ>=aK&&aJ>aP.max&&aK<=aP.max){aY=(aP.max-aK)/(aJ-aK)*(aY-aZ)+aZ;aJ=aP.max}}if(aZ!=aO){H.lineTo(aQ.p2c(aO),aP.p2c(aK))}H.lineTo(aQ.p2c(aZ),aP.p2c(aK));H.lineTo(aQ.p2c(aY),aP.p2c(aJ));if(aY!=aS){H.lineTo(aQ.p2c(aY),aP.p2c(aJ));H.lineTo(aQ.p2c(aS),aP.p2c(aJ))}}}H.save();H.translate(q.left,q.top);H.lineJoin="round";var aG=aE.lines.lineWidth,aB=aE.shadowSize;if(aG>0&&aB>0){H.lineWidth=aB;H.strokeStyle="rgba(0,0,0,0.1)";var aH=Math.PI/18;aD(aE.datapoints,Math.sin(aH)*(aG/2+aB/2),Math.cos(aH)*(aG/2+aB/2),aE.xaxis,aE.yaxis);H.lineWidth=aB/2;aD(aE.datapoints,Math.sin(aH)*(aG/2+aB/4),Math.cos(aH)*(aG/2+aB/4),aE.xaxis,aE.yaxis)}H.lineWidth=aG;H.strokeStyle=aE.color;var aC=ae(aE.lines,aE.color,0,w);if(aC){H.fillStyle=aC;aF(aE.datapoints,aE.xaxis,aE.yaxis)}if(aG>0){aD(aE.datapoints,0,0,aE.xaxis,aE.yaxis)}H.restore()}function ao(aE){function aH(aN,aM,aU,aK,aS,aT,aQ,aJ){var aR=aN.points,aI=aN.pointsize;for(var aL=0;aLaT.max||aOaQ.max){continue}H.beginPath();aP=aT.p2c(aP);aO=aQ.p2c(aO)+aK;if(aJ=="circle"){H.arc(aP,aO,aM,0,aS?Math.PI:Math.PI*2,false)}else{aJ(H,aP,aO,aM,aS)}H.closePath();if(aU){H.fillStyle=aU;H.fill()}H.stroke()}}H.save();H.translate(q.left,q.top);var aG=aE.points.lineWidth,aC=aE.shadowSize,aB=aE.points.radius,aF=aE.points.symbol;if(aG>0&&aC>0){var aD=aC/2;H.lineWidth=aD;H.strokeStyle="rgba(0,0,0,0.1)";aH(aE.datapoints,aB,null,aD+aD/2,true,aE.xaxis,aE.yaxis,aF);H.strokeStyle="rgba(0,0,0,0.2)";aH(aE.datapoints,aB,null,aD/2,true,aE.xaxis,aE.yaxis,aF)}H.lineWidth=aG;H.strokeStyle=aE.color;aH(aE.datapoints,aB,ae(aE.points,aE.color),0,false,aE.xaxis,aE.yaxis,aF);H.restore()}function E(aN,aM,aV,aI,aQ,aF,aD,aL,aK,aU,aR,aC){var aE,aT,aJ,aP,aG,aB,aO,aH,aS;if(aR){aH=aB=aO=true;aG=false;aE=aV;aT=aN;aP=aM+aI;aJ=aM+aQ;if(aTaL.max||aPaK.max){return}if(aEaL.max){aT=aL.max;aB=false}if(aJaK.max){aP=aK.max;aO=false}aE=aL.p2c(aE);aJ=aK.p2c(aJ);aT=aL.p2c(aT);aP=aK.p2c(aP);if(aD){aU.beginPath();aU.moveTo(aE,aJ);aU.lineTo(aE,aP);aU.lineTo(aT,aP);aU.lineTo(aT,aJ);aU.fillStyle=aD(aJ,aP);aU.fill()}if(aC>0&&(aG||aB||aO||aH)){aU.beginPath();aU.moveTo(aE,aJ+aF);if(aG){aU.lineTo(aE,aP+aF)}else{aU.moveTo(aE,aP+aF)}if(aO){aU.lineTo(aT,aP+aF)}else{aU.moveTo(aT,aP+aF)}if(aB){aU.lineTo(aT,aJ+aF)}else{aU.moveTo(aT,aJ+aF)}if(aH){aU.lineTo(aE,aJ+aF)}else{aU.moveTo(aE,aJ+aF)}aU.stroke()}}function e(aD){function aC(aJ,aI,aL,aG,aK,aN,aM){var aO=aJ.points,aF=aJ.pointsize;for(var aH=0;aH")}aH.push("");aF=true}if(aN){aJ=aN(aJ,aM)}aH.push('
'+aJ+"")}if(aF){aH.push("")}if(aH.length==0){return}var aL=''+aH.join("")+"
";if(O.legend.container!=null){c(O.legend.container).html(aL)}else{var aI="",aC=O.legend.position,aD=O.legend.margin;if(aD[0]==null){aD=[aD,aD]}if(aC.charAt(0)=="n"){aI+="top:"+(aD[1]+q.top)+"px;"}else{if(aC.charAt(0)=="s"){aI+="bottom:"+(aD[1]+q.bottom)+"px;"}}if(aC.charAt(1)=="e"){aI+="right:"+(aD[0]+q.right)+"px;"}else{if(aC.charAt(1)=="w"){aI+="left:"+(aD[0]+q.left)+"px;"}}var aK=c('
'+aL.replace('style="','style="position:absolute;'+aI+";")+"
").appendTo(av);if(O.legend.backgroundOpacity!=0){var aG=O.legend.backgroundColor;if(aG==null){aG=O.grid.backgroundColor;if(aG&&typeof aG=="string"){aG=c.color.parse(aG)}else{aG=c.color.extract(aK,"background-color")}aG.a=1;aG=aG.toString()}var aB=aK.children();c('
').prependTo(aK).css("opacity",O.legend.backgroundOpacity)}}}var ab=[],M=null;function K(aI,aG,aD){var aO=O.grid.mouseActiveRadius,a0=aO*aO+1,aY=null,aR=false,aW,aU;for(aW=Q.length-1;aW>=0;--aW){if(!aD(Q[aW])){continue}var aP=Q[aW],aH=aP.xaxis,aF=aP.yaxis,aV=aP.datapoints.points,aT=aP.datapoints.pointsize,aQ=aH.c2p(aI),aN=aF.c2p(aG),aC=aO/aH.scale,aB=aO/aF.scale;if(aH.options.inverseTransform){aC=Number.MAX_VALUE}if(aF.options.inverseTransform){aB=Number.MAX_VALUE}if(aP.lines.show||aP.points.show){for(aU=0;aUaC||aK-aQ<-aC||aJ-aN>aB||aJ-aN<-aB){continue}var aM=Math.abs(aH.p2c(aK)-aI),aL=Math.abs(aF.p2c(aJ)-aG),aS=aM*aM+aL*aL;if(aS=Math.min(aZ,aK)&&aN>=aJ+aE&&aN<=aJ+aX):(aQ>=aK+aE&&aQ<=aK+aX&&aN>=Math.min(aZ,aJ)&&aN<=Math.max(aZ,aJ))){aY=[aW,aU/aT]}}}}if(aY){aW=aY[0];aU=aY[1];aT=Q[aW].datapoints.pointsize;return{datapoint:Q[aW].datapoints.points.slice(aU*aT,(aU+1)*aT),dataIndex:aU,series:Q[aW],seriesIndex:aW}}return null}function aa(aB){if(O.grid.hoverable){u("plothover",aB,function(aC){return aC.hoverable!=false})}}function l(aB){if(O.grid.hoverable){u("plothover",aB,function(aC){return false})}}function R(aB){u("plotclick",aB,function(aC){return aC.clickable!=false})}function u(aC,aB,aD){var aE=y.offset(),aH=aB.pageX-aE.left-q.left,aF=aB.pageY-aE.top-q.top,aJ=C({left:aH,top:aF});aJ.pageX=aB.pageX;aJ.pageY=aB.pageY;var aK=K(aH,aF,aD);if(aK){aK.pageX=parseInt(aK.series.xaxis.p2c(aK.datapoint[0])+aE.left+q.left);aK.pageY=parseInt(aK.series.yaxis.p2c(aK.datapoint[1])+aE.top+q.top)}if(O.grid.autoHighlight){for(var aG=0;aGaH.max||aIaG.max){return}var aF=aE.points.radius+aE.points.lineWidth/2;A.lineWidth=aF;A.strokeStyle=c.color.parse(aE.color).scale("a",0.5).toString();var aB=1.5*aF,aC=aH.p2c(aC),aI=aG.p2c(aI);A.beginPath();if(aE.points.symbol=="circle"){A.arc(aC,aI,aB,0,2*Math.PI,false)}else{aE.points.symbol(A,aC,aI,aB,false)}A.closePath();A.stroke()}function v(aE,aB){A.lineWidth=aE.bars.lineWidth;A.strokeStyle=c.color.parse(aE.color).scale("a",0.5).toString();var aD=c.color.parse(aE.color).scale("a",0.5).toString();var aC=aE.bars.align=="left"?0:-aE.bars.barWidth/2;E(aB[0],aB[1],aB[2]||0,aC,aC+aE.bars.barWidth,0,function(){return aD},aE.xaxis,aE.yaxis,A,aE.bars.horizontal,aE.bars.lineWidth)}function am(aJ,aB,aH,aC){if(typeof aJ=="string"){return aJ}else{var aI=H.createLinearGradient(0,aH,0,aB);for(var aE=0,aD=aJ.colors.length;aE12){n=n-12}else{if(n==0){n=12}}}for(var g=0;g0&&j.which!=m.which)||i(j.target).is(m.not)){return}}switch(j.type){case"mousedown":i.extend(m,i(k).offset(),{elem:k,target:j.target,pageX:j.pageX,pageY:j.pageY});d.add(document,"mousemove mouseup",f,m);g(k,false);h.dragging=null;return false;case !h.dragging&&"mousemove":if(e(j.pageX-m.pageX)+e(j.pageY-m.pageY)w){var A=B;B=w;w=A}var y=w-B;if(E&&((E[0]!=null&&yE[1]))){return}D.min=B;D.max=w});o.setupGrid();o.draw();if(!q.preventEvent){o.getPlaceholder().trigger("plotzoom",[o])}};o.pan=function(p){var q={x:+p.left,y:+p.top};if(isNaN(q.x)){q.x=0}if(isNaN(q.y)){q.y=0}b.each(o.getAxes(),function(s,u){var v=u.options,t,r,w=q[u.direction];t=u.c2p(u.p2c(u.min)+w),r=u.c2p(u.p2c(u.max)+w);var x=v.panRange;if(x===false){return}if(x){if(x[0]!=null&&x[0]>t){w=x[0]-t;t+=w;r+=w}if(x[1]!=null&&x[1]= i1 then + s = s_sub(s,i2+1) + end + local i1,i2 = s_find(s,chrs..'*$') + if i2 >= i1 then + s = s_sub(s,1,i1-1) + end + + return s +end + +--- split a string into a list of strings separated by a delimiter. +local function split(s,re) + local res = {} + re = '[^'..re..']+' + for k in s:gmatch(re) do t_insert(res, strip(k)) end + return res +end + +local function export(name,mod) + local rawget,rawset = _G.rawget,_G.rawset + if not rawget(_G,'__PRIVATE_REQUIRE') then + local path = split(name,'%.') + local T = _G + for i = 1,#path-1 do + local p = rawget(T,path[i]) + if not p then + p = {} + rawset(T,path[i],p) + end + T = p + end + rawset(T,path[#path],mod) + end + return mod +end + +--module (...) +local _M = {} +local Doc = { __type = "doc" }; +Doc.__index = Doc; + +--- create a new document node. +-- @param tag the tag name +-- @param attr optional attributes (table of name-value pairs) +function _M.new(tag, attr, no_last_add) + local last_add = not no_last_add and {} or nil + local doc = { tag = tag, attr = attr or {}, last_add = last_add}; + return setmetatable(doc, Doc); +end + +--- parse an XML document. By default, this uses lxp.lom.parse, but +-- falls back to basic_parse, or if use_basic is true +-- @param text_or_file file or string representation +-- @param is_file whether text_or_file is a file name or not +-- @param use_basic do a basic parse +-- @return a parsed LOM document with the document metatatables set +-- @return nil, error the error can either be a file error or a parse error +function _M.parse(text_or_file, is_file, use_basic) + local parser,status,lom + if use_basic then parser = _M.basic_parse + else + status,lom = pcall(require,'lxp.lom') + if not status then parser = _M.basic_parse else parser = lom.parse end + end + if is_file then + local f,err = io.open(text_or_file) + if not f then return nil,err end + text_or_file = f:read '*a' + f:close() + end + local doc,err = parser(text_or_file) + if not doc then return nil,err end + if lom then + _M.walk(doc,false,function(_,d) + setmetatable(d,Doc) + end) + end + return doc +end + +---- convenient function to add a document node, This updates the last inserted position. +-- @param tag a tag name +-- @param attrs optional set of attributes (name-string pairs) +function Doc:addtag(tag, attrs) + local s = _M.new(tag, attrs); + (self.last_add[#self.last_add] or self):add_direct_child(s); + t_insert(self.last_add, s); + return self; +end + +--- convenient function to add a text node. This updates the last inserted position. +-- @param text a string +function Doc:text(text) + (self.last_add[#self.last_add] or self):add_direct_child(text); + return self; +end + +---- go up one level in a document +function Doc:up() + t_remove(self.last_add); + return self; +end + +function Doc:reset() + local last_add = self.last_add; + for i = 1,#last_add do + last_add[i] = nil; + end + return self; +end + +--- append a child to a document directly. +-- @param child a child node (either text or a document) +function Doc:add_direct_child(child) + t_insert(self, child); +end + +--- append a child to a document at the last element added. +-- @param child a child node (either text or a document) +function Doc:add_child(child) + (self.last_add[#self.last_add] or self):add_direct_child(child); + return self; +end + +--accessing attributes: useful not to have to expose implementation (attr) +--but also can allow attr to be nil in any future optimizations + +--- set attributes of a document node. +-- @param t a table containing attribute/value pairs +function Doc:set_attribs (t) + for k,v in pairs(t) do + self.attr[k] = v + end +end + +--- set a single attribute of a document node. +-- @param a attribute +-- @param v its value +function Doc:set_attrib(a,v) + self.attr[a] = v +end + +--- access the attributes of a document node. +function Doc:get_attribs() + return self.attr +end + + +--- function to create an element with a given tag name and a set of children. +-- @param tag a tag name +-- @param items either text or a table where the hash part is the attributes and the list part is the children. +function _M.elem(tag,items) + local s = _M.new(tag,nil,true) + local append = t_insert + if type(items) == 'string' then items = {items} end + if _M.is_tag(items) then + t_insert(s,items) + elseif type(items) == 'table' then + for k,v in pairs(items) do + if type(k) == 'string' then + s.attr[k] = v + append(s.attr,k) + elseif type(v) == 'table' and not _M.is_tag(v) then + for i,vv in ipairs(v) do + append(s,vv) + end + else + append(s,v) + end + end + end + return s +end + +--- given a list of names, return a number of element constructors. +-- @param list a list of names, or a comma-separated string. +-- @usage local parent,children = doc.tags 'parent,children'
+-- doc = parent {child 'one', child 'two'} +function _M.tags(list,f) + local ctors = {} + if type(list) == 'string' then list = split(list,',') end + for _,tag in ipairs(list) do + local ctor = function(items) return _M.elem(tag,items) end + if f then ctor = f(ctor) end + t_insert(ctors,ctor) + end + return unpack(ctors) +end + +local templ_cache = {} + +local function is_data(data) + return #data == 0 or type(data[1]) ~= 'table' +end + +local function prepare_data(data) + -- a hack for ensuring that $1 maps to first element of data, etc. + -- Either this or could change the gsub call just below. + for i,v in ipairs(data) do + data[tostring(i)] = v + end +end + +--- create a substituted copy of a document, +-- @param templ may be a document or a string representation which will be parsed and cached +-- @param data a table of name-value pairs or a list of such tables +-- @return an XML document +function Doc.subst(templ, data) + if type(data) ~= 'table' or not next(data) then return nil, "data must be a non-empty table" end + if is_data(data) then + prepare_data(data) + end + if type(templ) == 'string' then + if templ_cache[templ] then + templ = templ_cache[templ] + else + local str,err = templ + templ,err = _M.parse(str) + if not templ then return nil,err end + templ_cache[str] = templ + end + end + local function _subst(item) + return _M.clone(templ,function(s) + return s:gsub('%$(%w+)',item) + end) + end + if is_data(data) then return _subst(data) end + local list = {} + for _,item in ipairs(data) do + prepare_data(item) + t_insert(list,_subst(item)) + end + if data.tag then + list = _M.elem(data.tag,list) + end + return list +end + + +--- get the first child with a given tag name. +-- @param tag the tag name +function Doc:child_with_name(tag) + for _, child in ipairs(self) do + if child.tag == tag then return child; end + end +end + +local _children_with_name +function _children_with_name(self,tag,list,recurse) + for _, child in ipairs(self) do if type(child) == 'table' then + if child.tag == tag then t_insert(list,child) end + if recurse then _children_with_name(child,tag,list,recurse) end + end end +end + +--- get all elements in a document that have a given tag. +-- @param tag a tag name +-- @param dont_recurse optionally only return the immediate children with this tag name +-- @return a list of elements +function Doc:get_elements_with_name(tag,dont_recurse) + local res = {} + _children_with_name(self,tag,res,not dont_recurse) + return res +end + +-- iterate over all children of a document node, including text nodes. +function Doc:children() + local i = 0; + return function (a) + i = i + 1 + return a[i]; + end, self, i; +end + +-- return the first child element of a node, if it exists. +function Doc:first_childtag() + if #self == 0 then return end + for _,t in ipairs(self) do + if type(t) == 'table' then return t end + end +end + +function Doc:matching_tags(tag, xmlns) + xmlns = xmlns or self.attr.xmlns; + local tags = self; + local start_i, max_i = 1, #tags; + return function () + for i=start_i,max_i do + local v = tags[i]; + if (not tag or v.tag == tag) + and (not xmlns or xmlns == v.attr.xmlns) then + start_i = i+1; + return v; + end + end + end, tags; +end + +--- iterate over all child elements of a document node. +function Doc:childtags() + local i = 0; + return function (a) + local v + repeat + i = i + 1 + v = self[i] + if v and type(v) == 'table' then return v; end + until not v + end, self[1], i; +end + +--- visit child element of a node and call a function, possibility modifying the document. +-- @param callback a function passed the node (text or element). If it returns nil, that node will be removed. +-- If it returns a value, that will replace the current node. +function Doc:maptags(callback) + local is_tag = _M.is_tag + local i = 1; + while i <= #self do + if is_tag(self[i]) then + local ret = callback(self[i]); + if ret == nil then + t_remove(self, i); + else + self[i] = ret; + i = i + 1; + end + end + end + return self; +end + +local xml_escape +do + local function tostring_q(str) -- for semi-paranoid checking + local tt = type(str) + if tt ~= 'string' then + str = tostring(str) + if tt ~= 'number' then + print('**warning**',tt,'is not a string',str) + end + end + return str + end + local escape_table = { ["'"] = "'", ["\""] = """, ["<"] = "<", [">"] = ">", ["&"] = "&" }; + function xml_escape(str) return (s_gsub(tostring_q(str), "['&<>\"]", escape_table)); end + _M.xml_escape = xml_escape; +end + +-- pretty printing +-- if indent, then put each new tag on its own line +-- if attr_indent, put each new attribute on its own line +local function _dostring(t, buf, self, xml_escape, parentns, idn, indent, attr_indent) + local nsid = 0; + local tag = t.tag + local lf,alf = ""," " + if indent then lf = '\n'..idn end + if attr_indent then alf = '\n'..idn..attr_indent end + t_insert(buf, lf.."<"..tag); + for k, v in pairs(t.attr) do + if type(k) ~= 'number' then -- LOM attr table has list-like part + if s_find(k, "\1", 1, true) then + local ns, attrk = s_match(k, "^([^\1]*)\1?(.*)$"); + nsid = nsid + 1; + t_insert(buf, " xmlns:ns"..nsid.."='"..xml_escape(ns).."' ".."ns"..nsid..":"..attrk.."='"..xml_escape(v).."'"); + elseif not(k == "xmlns" and v == parentns) then + t_insert(buf, alf..k.."='"..xml_escape(v).."'"); + end + end + end + local len,has_children = #t; + if len == 0 then + local out = "/>" + if attr_indent then out = '\n'..idn..out end + t_insert(buf, out); + else + t_insert(buf, ">"); + for n=1,len do + local child = t[n]; + if child.tag then + self(child, buf, self, xml_escape, t.attr.xmlns,idn and idn..indent, indent, attr_indent ); + has_children = true + elseif type(child) == 'string' then -- text element + if not child:find '^\001' then + child = xml_escape(child) + else + child = child:sub(2) + end + t_insert(buf, child); + end + end + t_insert(buf, (has_children and lf or '')..""); + end +end + +---- pretty-print an XML document +--- @param idn an initial indent (indents are all strings) +--- @param indent an indent for each level +--- @param attr_indent if given, indent each attribute pair and put on a separate line +--- @return a string representation +function _M.tostring(t,idn,indent, attr_indent) + local buf = {}; + _dostring(t, buf, _dostring, xml_escape, nil,idn,indent, attr_indent); + return t_concat(buf); +end + +Doc.__tostring = function(d) + return _M.tostring(d,'',' ') +end + +--- get the full text value of an element +function Doc:get_text() + local res = {} + for i,el in ipairs(self) do + if type(el) == 'string' then t_insert(res,el) end + end + return t_concat(res); +end + +--- make a copy of a document +-- @param doc the original document +-- @param strsubst an optional function for handling string copying which could do substitution, etc. +function _M.clone(doc, strsubst) + local lookup_table = {}; + local function _copy(object) + if type(object) ~= "table" then + if strsubst and type(object) == 'string' then return strsubst(object) + else return object; + end + elseif lookup_table[object] then + return lookup_table[object]; + end + local new_table = {}; + lookup_table[object] = new_table; + for index, value in pairs(object) do + new_table[_copy(index)] = _copy(value); -- is cloning keys much use, hm? + end + return setmetatable(new_table, getmetatable(object)); + end + + return _copy(doc) +end + +--- compare two documents. +-- @param t1 any value +-- @param t2 any value +function _M.compare(t1,t2) + local ty1 = type(t1) + local ty2 = type(t2) + if ty1 ~= ty2 then return false, 'type mismatch' end + if ty1 == 'string' then + return t1 == t2 and true or 'text '..t1..' ~= text '..t2 + end + if ty1 ~= 'table' or ty2 ~= 'table' then return false, 'not a document' end + if t1.tag ~= t2.tag then return false, 'tag '..t1.tag..' ~= tag '..t2.tag end + if #t1 ~= #t2 then return false, 'size '..#t1..' ~= size '..#t2..' for tag '..t1.tag end + -- compare attributes + for k,v in pairs(t1.attr) do + if t2.attr[k] ~= v then return false, 'mismatch attrib' end + end + for k,v in pairs(t2.attr) do + if t1.attr[k] ~= v then return false, 'mismatch attrib' end + end + -- compare children + for i = 1,#t1 do + local yes,err = _M.compare(t1[i],t2[i]) + if not yes then return err end + end + return true +end + +--- is this value a document element? +-- @param d any value +function _M.is_tag(d) + return type(d) == 'table' and type(d.tag) == 'string' +end + +--- call the desired function recursively over the document. +-- @param depth_first visit child notes first, then the current node +-- @param operation a function which will receive the current tag name and current node. +function _M.walk (doc, depth_first, operation) + if not depth_first then operation(doc.tag,doc) end + for _,d in ipairs(doc) do + if _M.is_tag(d) then + _M.walk(d,depth_first,operation) + end + end + if depth_first then operation(doc.tag,doc) end +end + +local escapes = { quot = "\"", apos = "'", lt = "<", gt = ">", amp = "&" } +local function unescape(str) return (str:gsub( "&(%a+);", escapes)); end + +local function parseargs(s) + local arg = {} + s:gsub("([%w:]+)%s*=%s*([\"'])(.-)%2", function (w, _, a) + arg[w] = unescape(a) + end) + return arg +end + +--- Parse a simple XML document using a pure Lua parser based on Robero Ierusalimschy's original version. +-- @param s the XML document to be parsed. +-- @param all_text if true, preserves all whitespace. Otherwise only text containing non-whitespace is included. +function _M.basic_parse(s,all_text) + local t_insert,t_remove = table.insert,table.remove + local s_find,s_sub = string.find,string.sub + local stack = {} + local top = {} + t_insert(stack, top) + local ni,c,label,xarg, empty + local i, j = 1, 1 + -- we're not interested in + local _,istart = s_find(s,'^%s*<%?[^%?]+%?>%s*') + if istart then i = istart+1 end + while true do + ni,j,c,label,xarg, empty = s_find(s, "<(%/?)([%w:%-_]+)(.-)(%/?)>", i) + if not ni then break end + local text = s_sub(s, i, ni-1) + if all_text or not s_find(text, "^%s*$") then + t_insert(top, unescape(text)) + end + if empty == "/" then -- empty element tag + t_insert(top, setmetatable({tag=label, attr=parseargs(xarg), empty=1},Doc)) + elseif c == "" then -- start tag + top = setmetatable({tag=label, attr=parseargs(xarg)},Doc) + t_insert(stack, top) -- new level + else -- end tag + local toclose = t_remove(stack) -- remove top + top = stack[#stack] + if #stack < 1 then + error("nothing to close with "..label) + end + if toclose.tag ~= label then + error("trying to close "..toclose.tag.." with "..label) + end + t_insert(top, toclose) + end + i = j+1 + end + local text = s_sub(s, i) + if all_text or not s_find(text, "^%s*$") then + t_insert(stack[#stack], unescape(text)) + end + if #stack > 1 then + error("unclosed "..stack[#stack].tag) + end + local res = stack[1] + return type(res[1])=='string' and res[2] or res[1] +end + +local function empty(attr) + return not attr or not next(attr) +end + +local function is_text(s) return type(s) == 'string' end +local function is_element(d) return type(d) == 'table' and d.tag ~= nil end + +-- returns the key,value pair from a table if it has exactly one entry +local function has_one_element(t) + local key,value = next(t) + if next(t,key) ~= nil then return false end + return key,value +end + +local function tostringn(d) + return tostring(d):sub(1,60) +end + +local function append_capture(res,tbl) + if not empty(tbl) then -- no point in capturing empty tables... + local key + if tbl._ then -- if $_ was set then it is meant as the top-level key for the captured table + key = tbl._ + tbl._ = nil + if empty(tbl) then return end + end + -- a table with only one pair {[0]=value} shall be reduced to that value + local numkey,val = has_one_element(tbl) + if numkey == 0 then tbl = val end + if key then + res[key] = tbl + else -- otherwise, we append the captured table + t_insert(res,tbl) + end + end +end + +local function capture_attrib(res,pat,value) + pat = pat:sub(2) + if pat:find '^%d+$' then -- $1 etc means use this as an array location + pat = tonumber(pat) + end + res[pat] = value + return true +end + +local match +function match(d,pat,res,keep_going) + local ret = true + if d == nil then return false end + -- attribute string matching is straight equality, except if the pattern is a $ capture, + -- which always succeeds. + if type(d) == 'string' then + if type(pat) ~= 'string' then return false end + if pat:find '^%$' then + return capture_attrib(res,pat,d) + else + return d == pat + end + else + -- this is an element node. For a match to succeed, the attributes must + -- match as well. + if d.tag == pat.tag then + if not empty(pat.attr) then + if empty(d.attr) then ret = false + else + for prop,pval in pairs(pat.attr) do + local dval = d.attr[prop] + if not match(dval,pval,res) then ret = false; break end + end + end + end + -- the pattern may have child nodes. We match partially, so that {P1,P2} shall match {X,P1,X,X,P2,..} + if ret and #pat > 0 then + local i,j = 1,1 + local function next_elem() + j = j + 1 -- next child element of data + if is_text(d[j]) then j = j + 1 end + return j <= #d + end + repeat + local p = pat[i] + -- repeated {{<...>}} patterns shall match one or more elements + -- so e.g. {P+} will match {X,X,P,P,X,P,X,X,X} + if is_element(p) and p.repeated then + local found + repeat + local tbl = {} + ret = match(d[j],p,tbl,false) + if ret then + found = false --true + append_capture(res,tbl) + end + until not next_elem() or (found and not ret) + i = i + 1 + else + ret = match(d[j],p,res,false) + if ret then i = i + 1 end + end + until not next_elem() or i > #pat -- run out of elements or patterns to match + -- if every element in our pattern matched ok, then it's been a successful match + if i > #pat then return true end + end + if ret then return true end + else + ret = false + end + -- keep going anyway - look at the children! + if keep_going then + for child in d:childtags() do + ret = match(child,pat,res,keep_going) + if ret then break end + end + end + end + return ret +end + +function Doc:match(pat) + if is_text(pat) then + pat = _M.parse(pat,false,true) + end + _M.walk(pat,false,function(_,d) + if is_text(d[1]) and is_element(d[2]) and is_text(d[3]) and + d[1]:find '%s*{{' and d[3]:find '}}%s*' then + t_remove(d,1) + t_remove(d,2) + d[1].repeated = true + end + end) + + local res = {} + local ret = match(self,pat,res,true) + return res,ret +end + +return export(...,_M) diff --git a/demo/orbiter/fake.lua b/demo/orbiter/fake.lua new file mode 100644 index 0000000..96ec3d8 --- /dev/null +++ b/demo/orbiter/fake.lua @@ -0,0 +1,34 @@ +-- orbiter.fake +-- optional testing functionality - this returns a fake server constructor, +-- which just pumps our request into the loop, receives the output, and closes. +-- currently just does GET requests and is hard-wired to write to stdout. +-- The reader is invited to contemplate the difficulties of doing this in Java or C++. + +local function fake_new (out,lines) + local client = {} + function client:receive() + return table.remove(lines,1) + end + function client:send (stuff) + out:write(stuff) + return true + end + function client:settimeout () + end + function client:close () + out:write '\n' + os.exit() + end + return client +end + +return function(url,port) + local server = {} + function server:accept() + return fake_new (io.stdout, { + "GET "..url.." HTTP/1.1\r\n", + "\r\n" + }) + end + return server +end diff --git a/demo/orbiter/form.lua b/demo/orbiter/form.lua new file mode 100644 index 0000000..fa478bf --- /dev/null +++ b/demo/orbiter/form.lua @@ -0,0 +1,290 @@ +-- Orbiter, a personal web application framework +local orbiter = require 'orbiter' +local html = require 'orbiter.html' +local util = require 'orbiter.util' + +local form = {} + +local button_name = '-button' + +html.set_defaults { + inline_style = [[ + form.orbiter fieldset { border: solid 1px #777; } + form.orbiter table { border: solid 1px #000; } + form.orbiter table td { padding: 6px; vertical-align:top; text-align: left } + form.orbiter ul { list-style-type: none; padding: 0; margin: 0} + form.orbiter ul li { padding-top: 6px; padding-bottom: 6px; } +]] +} + +-- constraints + +function form.range(x1,x2) + return function(x) + if x < x1 or x > x2 then return false,'must be between %f and %f' % {x1,x2} + else return x end + end +end + +function form.match(pat,err) + return function(s) + if not s:find(pat) then return false,err else return s end + end +end + +form.non_blank = form.match('%S', 'may not be blank') + +function form.irange(n1,n2) + return function(x) + if x < n1 or x > n2 then return false,'must be between %d and %d' % {n1,n2} + elseif math.floor(x) ~= x then return false,'must be an integer' + else return x + end + end +end + +local converters = { + number = { + tostring = tostring, + parse = function(s) + local res = tonumber(s) + if not res then return false,'not a number' + else return res + end + end + }, + boolean = { + tostring = tostring, + parse = function(s) return s=='true' and true or false end + }, + string = { + tostring = tostring, + parse = tostring, + } +} + +local select_,option_,form_,label_,textarea_,fieldset_,legend_ = html.tags 'select,option,form,label,textarea,fieldset,legend' +local p = html.tags 'p' + +local function value_set(c,v) c:set_attrib('value',v) end +local function value_get(c) return c:get_attrib('value') end +local function child1_set(c,v) c[1] = v end +local function child1_get(c) return c[1] end + + +local function input(type,name,value,size) + local ctrl = html.elem('input',{ + type=type,name=name,value=value,size=tostring(size) + }) + ctrl.set = value_set + ctrl.get = value_get + return ctrl +end + +local Constraint = util.class()() + +form.textarea = util.class(Constraint) { + init = function(self,args) + self.rows = args.rows + self.cols = args.cols + end; + converter = converters.string, + control = function(self,name,value) + local ctrl = textarea_{name=name, + rows=tostring(self.rows),cols=tostring(self.cols); + value} + ctrl.set = child1_set + ctrl.get = child1_get + return ctrl + end, + __tostring = function(self) return 'text area' end +} + +local function text(name,value,size) + return input('text',name,value,size) +end + +local function checkbox(name,value,size) + return input('checkbox',name,value) +end + +local function listbox(name,value,list,size,multiple) + local ctrl = select_ {name=name, + size = (size and tostring(size) or nil), + multiple = (multiple and 'multiple' or nil) + } + for i,v in ipairs(list) do + ctrl[i] = option_{value=v,selected = (v==value and 'selected' or nil),v} + end + ctrl.set = value_set + ctrl.get = value_get + return ctrl +end + +local function generate_control(obj,var,constraint) + local value = obj[var] + local vtype = type(value) + local cntrl + local converter = converters.string + --print(var,constraint,value,vtype) + if util.class_of(constraint,Constraint) then + --print('value',value) + cntrl = constraint:control(var,value) + converter = constraint.converter + constraint = constraint.constraint + else + if vtype == 'number' then + converter = converters.number + cntrl = text(var,converter.tostring(value),'8') + elseif vtype == 'boolean' then + converter = converters.boolean + cntrl = checkbox(var,converter.tostring(value)) + elseif vtype == 'string' then + local size + if type(constraint) == 'number' then + size = constraint + constraint = nil + end + if util.is_plain(constraint) then + local data = constraint + if not util.is_list(data) then + data = constraint.data + end + if util.is_list(data) then + cntrl = listbox(var,value,data,constraint.size,constraint.multiple) + constraint = nil + end + else + cntrl = text(var,value,size) + end + end + end + return cntrl,converter,constraint +end + +function form.new (t) + local f = { spec_of = {}, spec_table = t } + f.validate = form.validate + f.show = form.show + f.prepare = form.prepare + f.create = form.create + return f +end + +local append = table.insert +local K = 1 + +function form.create (self,web) + local spec = self.spec_table + spec.action = spec.action or web.path_info + if not spec.name then -- forms must have unique ids + spec.name = 'form'..K + K = K + 1 + end + local obj = spec.obj + self.obj = obj + local res = {} + for i = 1,#spec,3 do + -- each row has these three values + local label,var,constraint = spec[i],spec[i+1],spec[i+2] + local id = var -- might be better to autogenerate to ensure uniqueness? + local cntrl,converter,constraint = generate_control(obj,var,constraint) + cntrl:set_attrib('id',id) + label = label_{['for']=id,title=label,label} + local spec = {label=label,cntrl=cntrl,converter=converter,constraint=constraint} + append(res,spec) + self.spec_of[var] = spec + end + self.spec_list = res + local contents + local ftype = spec.type or 'cols' + if ftype == 'cols' or ftype == 'rows' then -- wrap up as a table + local tbl = {} + for i,item in ipairs(res) do + tbl[i] = {item.label,item.cntrl} + end + if ftype == 'rows' then tbl = util.transpose(tbl) end + contents = html.table{ data = tbl } + elseif spec.type == 'list' or spec.type == 'line' then + local items = {} + for i,item in ipairs(res) do + append(items,item.label) + append(items,item.cntrl) + end + if spec.type == 'list' then + contents = html.list { data = items } + else + contents = p(items) + end + end + if spec.title then + contents = fieldset_{legend_(spec.title),contents} + end + self.id = spec.name + local action, obj = spec.action, self.obj + if obj.dispatch_post and type(action) == 'function' then + local callback = action + action = orbiter.prepend_root('/form/'..self.id) + obj:dispatch_post(function(app,web) + self:prepare(web) + return callback(app,web,self) + end,action) + end + self.body = form_{ + name = spec.name; id = self.id; action = action, class = 'orbiter'; + method = spec.method or 'post'; + contents, + } + spec.buttons = spec.buttons or {'submit'} + for _,b in ipairs(spec.buttons) do + append(self.body,input('submit',button_name,b)) + end + return self.body +end + +function form.prepare(self,web) + if web.method == 'get' then + self:create(web) + return true + else -- must be 'post' + local ok,resp = self:validate(web.input) + return not ok + end +end + +function form.show(self) + return self.body +end + +function form.validate (self,values) + local ok = true + local res = {} + self.button = values[button_name] + for var,value in pairs(values) do + local spec = self.spec_of[var] + if spec then + spec.cntrl:set(value) + local val,err = spec.converter.parse(value) + if val and spec.constraint then + val,err = spec.constraint(val) + end + if err then + ok = false + spec.cntrl:set_attribs { + style='background:pink', + title = err + } + else + res[var] = val + end + end + end + if not ok then + return false + else -- only do this if everything is fine! + util.update(self.obj,res) + return true + end +end + +return form diff --git a/demo/orbiter/html.lua b/demo/orbiter/html.lua new file mode 100644 index 0000000..c90345f --- /dev/null +++ b/demo/orbiter/html.lua @@ -0,0 +1,357 @@ +-- Orbiter, a personal web application framework +-- HTML generation using luaexpat LOM format; +-- this provides some higher-level functions for generating HTML lists +-- and tables. + +local _M = {} -- our module +local orbiter = require 'orbiter' +local doc = require 'orbiter.doc' +local text = require 'orbiter.text' +local util = require 'orbiter.util' +local append = table.insert +local is_table,imap,concat_list,reshape2D = util.is_table,util.imap,util.concat_list,util.reshape2D +local compose = util.compose + +_M.is_doc = doc.is_tag +_M.is_elem = doc.is_tag +_M.elem = doc.elem + +function _M.tostring(d) + return doc.tostring(d,'',' ') +end + +_M.raw_tostring = doc.tostring +_M.escape = doc.xml_escape + +function _M.literal(s) + return '\001'..s +end + +function _M.script(s) + return _M.elem("script",{type="text/javascript",_M.literal(s)}) +end + +function _M.register(obj) + obj.content_filter = _M.content_filter +end + +-- convenience function for Orbit programs to register themselves with the bridge-- +function _M.new(obj) + if orbit then + local bridge = require 'orbiter.bridge' + bridge.new(obj) + end +end + +local defaults = {} + +local default_types = { + favicon = {tag='link',rtype='shortcut icon',source='href'}, + styles = {tag='link',rtype='text/css',source='href'}, + scripts = {tag='script',rtype='text/javascript',source='src'}, + inline_style = {tag='style',rtype='text/css'}, + inline_script = {tag='script',rtype='text/javascript'}, +} +local default_types_order = {'favicon','scripts','styles','inline_style','inline_script'} + +function _M.reset_defaults () + defaults = {} +end + +function _M.set_defaults(t) + for k,v in pairs(t) do + local ftype = default_types[k] + if not ftype then error("unknown default field "..k,2) end + defaults[k] = concat_list(defaults[k],v) + end +end + +-- scripts and CSS usually by reference, can be directly embedded +-- within the document +local function fill_head(head,t) + for _,field in ipairs(default_types_order) do + local ftype = default_types[field] + local tag,rtype,source = ftype.tag,ftype.rtype,ftype.source + local items = concat_list(defaults[field],t[field]) + if #items ~= 0 then + for _,item in ipairs(items) do + local hi = {type=rtype} + if tag == 'link' then + if not rtype:find '/' then -- it's not a MIME type + hi.rel = rtype + else + hi.rel = 'stylesheet' + end + end + if source then + hi[source] = orbiter.prepend_root(item) + item = '' + end + hi[1] = _M.literal(item) + append(head,doc.elem(tag,hi)) + end + end + end +end + + +function _M.document(t) + local head = doc.elem('head',doc.elem('title',t.title or 'Orbiter')) + t.favicon = t.favicon or '/resources/favicon.ico' + fill_head(head,t) + if t.refresh then + append(head,doc.elem('meta',{['http-equiv']='refresh',content=t.refresh})) + end + local data = t.body or t + local xmlns + if t.xml then xmlns = "http://www.w3.org/1999/xhtml" end + + local body = util.copy_list(data) + return doc.elem('html',{xmlns=xmlns,head,doc.elem('body',body)}) +end + +function _M.as_text(t) + return _M.tostring(_M.document(t)) +end + +--- the module is directly callable. +-- and is short for @{document}. +-- @usage html { title = 'hello'; .... } +-- @function html +setmetatable(_M,{ + __call = function(o,t) + return _M.document(t) + end +}) + +-- the handlers can now return LOM, tell Orbiter about this... +-- Will adjust MIME type for XHTML +function _M.content_filter(self,content,mime) + if _M.is_doc(content) then + if content.attr.xmlns and not mime then + mime = "application/xhtml+xml" + end + return _M.tostring(content), mime + end + return content,mime +end + +function _M.specialize (fun,defaults) + return function(tbl) + tbl = util.copy(util.force(tbl)) + util.update(tbl,defaults) + local k = util.index_of(tbl,1) + if k then + tbl[k] = tbl[1] + tbl[1] = nil + end + return fun(tbl) + end +end + +local render_function + +function _M.compose (f1,f2) + return compose(render_function(f1),render_function(f2)) +end + +-- concatenating two functions will compose them... +function _M.enable_concatenation_is_composition() + debug.setmetatable(print,{ + __concat = _M.compose; + __index = { + specialize = _M.specialize + } + }) +end + +local dtags = doc.tags + +local TMT = { + __call = function(self,...) return self.tag(...) end; + __index = function(self,name) + local res = _M.specialize(self.tag,{class=name}) + self[name] = res + return res + end; +} + +local function _tag_object(tag) + return setmetatable({tag=tag},TMT) +end + +local function _tags (list) + if is_table(list) and is_table(list[1]) then + local res = {} + for i,item in ipairs(list) do res[i] = item[1] end + res = {dtags(res)} + for i,ctor in ipairs(res) do + local defs = util.copy_map(list[i]) + res[i] = _M.specialize(ctor,defs) + end + return unpack(res) + else + return dtags(list,_tag_object) + end +end + +_M.tags = setmetatable({},{ + __call = function(t,...) return _tags(...) end, + __index = function(t,tag) + local val = _tags(tag) + rawset(t,tag,val) + return val + end +}) + +local a,img = doc.tags 'a,img' + +function _M.link(addr,text) + local id,class,style,title,alt,onclick = nil + if is_table(addr) then addr,text,id,class,style,title,alt,onclick = addr[1],addr[2],addr.id,addr.class,addr.style,addr.title,addr.alt,addr.onclick end + if not text then text = addr end + addr = orbiter.prepend_root(addr) + return a{id=id,href=addr,class=class,style=style,title=title,alt=alt,onclick=onclick,text} +end + +function _M.image(src) + return img{src=orbiter.prepend_root(src)} +end + +function _M.format(patt) + local format = text.formatx + return function(val) + return format(patt,unpack(val)) + end +end + +function render_function(f) + if type(f) == 'string' then + return _M.format(f) + else + return f + end +end + +local function item_op(fun,t) + if t.render then + fun = compose(fun,render_function(t.render)) + t.render = nil + end + return fun +end + +local function copy_common(src,dest) +--~ dest.id = src.id +--~ dest.style = src.style +--~ dest.class = src.class + for k,v in pairs(src) do + if type(k) == 'string' then + dest[k] = v + end + end +end + +local function table_arg(t) + assert(is_table(t)) + local data = t + if t.data then + data = t.data + t.data = nil + end + if t.map then + data = t.map(data) + t.map = nil + end + return data +end + +local ul,ol,li = doc.tags 'ul,ol,li' + +--- Generate an HTML list. +-- either t or t.data must be a single-dimensional array. t.start and t.finish +-- can provide a range over elements to be used. If t.map exists, it's assumed +-- to be a function that processes the array. Optionally, t.render will convert +-- values into strings; may be a function or a +-- The list will be unordered by default, set t.type to 'ordered' or '#' +function _M.list(t) + local data = table_arg(t) + local ctor = (t.type=='ordered' or t.type=='#') and ol or ul + local each = item_op(li,t) + local res = imap(each,data,t.start,t.finish) + t.type = nil + t.start = nil + t.finish = nil + copy_common(t,res) + return ctor(res) +end + +local function set_table_style(res,data,styles) + local function set_style(row,col,style) + local attr = {} + -- important: is this an inline CSS style, or a class name? + if style:find ':' then attr.style = style else attr.class = style end + res[row][col].attr = attr + end + local alias = {} + if styles.alias then + alias = styles.alias + styles.alias = nil + end + for style,where in pairs(styles) do + local svalue = alias[style] or style + local row,col = where.row,where.col + if row and col then + set_style(row,col,svalue) + elseif row then + for col = 1,#data[1] do set_style(row,col,svalue) end + elseif col then + for row = 1,#data do set_style(row,col,svalue) end + end + end +end + +local _table,tr,td,th = doc.tags 'table,tr,td,th' + +--- Generate an HTML table. +-- Data is either t itself or t.data if it exists, and must be a 2D array, +-- unless if t.cols is specified, where the 1D array will be reshaped as a 2D array. +-- If t.headers is an array of names, then the table will have a header. +-- You can specify a range of indices to use in the data using t.start and t.finish +-- (this is useful if using t.data) +function _M.table(t) + local data = table_arg(t) + if t.cols then + data = reshape2D(data,t.cols) + t.cols = nil + end + local each = item_op(td,t) + local function row_op(row) + return tr (imap(each,row)) + end + local res = imap(row_op,data,t.start,t.finish) + t.start = nil + t.finish = nil + if t.headers then + local hdrs = tr (imap(th,t.headers)) + table.insert(res,1,hdrs) + t.headers = nil + end + --res.border = t.border --?? + copy_common(t,res) + res.width = t.width + local res = _table(res) + if t.styles then set_table_style(res,data,t.styles) end + return res +end + +--- this converts a map-like table into a list of {key,value} pairs. +function _M.map2list(t) + local res = {} + for k,v in pairs(t) do + append(res,{k,v}) + end + return res +end + +return _M -- orbiter.html ! diff --git a/demo/orbiter/init.lua b/demo/orbiter/init.lua new file mode 100644 index 0000000..1a8f1de --- /dev/null +++ b/demo/orbiter/init.lua @@ -0,0 +1,802 @@ +--- Orbiter, a compact personal web application framework. +-- Very much inspired by Orbit, with a little webserver borrowed from Webrocks + +local socket = require 'socket.core' + +local _M = {} --- our module +local DIRSEP = package.config:sub(1,1) +local Windows = DIRSEP == '\\' +local t_remove, t_insert, append = table.remove, table.insert, table.insert +local tracing, browser +local help_text = [[ + **** Orbiter v0.3 **** +--addr=IP address (default localhost) +--port=HTTP port (default 8080) +--trace print out some useful verbosity +--test=pattern print out what will be sent to the user agent +--no_headers when using --test, don't print out HTTP headers +--launch open the browser; may point to a particular browser, otherwise system. +]] + +local function quit(msg) + io.stderr:write(msg,'\n') + os.exit(1) +end + +-- sort out Lua 5.2 compatibility in a brutal way.. +if not unpack then + rawset(_G,'unpack',rawget(table,'unpack')) +end + +local trace + +--- Extract flags from an arguments list. +-- (grabbed from luarocks.util) +-- Given string arguments, extract flag arguments into a flags set. +-- For example, given "foo", "--tux=beep", "--bla", "bar", "--baz", +-- it would return the following: +-- {["bla"] = true, ["tux"] = "beep", ["baz"] = true}, "foo", "bar". +function _M.parse_flags(...) + local args = {...} + local flags = {} + for i = #args, 1, -1 do + local flag = args[i]:match("^%-%-(.*)") + if flag then + local var,val = flag:match("([a-z_%-]*)=(.*)") + if val then + flags[var] = val + else + flags[flag] = true + end + t_remove(args, i) + end + end + return flags, unpack(args) +end + +local function readfile (f) + local f,err = io.open(f, 'rb') + if not f then return nil,err end + local s = f:read '*a' + f:close() + return s +end + +local MT = {} +MT.__index = MT + +-- this is the object used by Orbiter itself to provide one basic piece of furniture, +-- the favicon. +local self + +function _M.new(...) + local extensions = {...} + local obj = extensions[1] + -- if passed a table which doesn't have register, then assume we're being called + -- from module() + -- use the module as the object, and manually add our methods to it. + if obj and type(obj) ~= 'string' and not obj.register then + local m = extensions[1] + for k,v in pairs(MT) do m[k] = v end + table.remove(extensions,1) + else + obj = setmetatable({},MT) + end + if not self then + self = true -- hack to prevent endless recursion + self = _M.new() + self:dispatch_static '/resources/favicon%.ico' + end + -- remember to strip off the starting @ + local path = debug.getinfo(2, "S").source:sub(2):gsub('\\','/') + if path:find '/' then + path = path:gsub('/[%w_]+%.lua$','') + else -- invoked just as script name + path = '.' + end + obj.root = path + obj.resources = obj.root..'/resources' + if #extensions > 0 then + for _,e in ipairs(extensions) do + if type(e) == 'string' then + local stat,ext = pcall(require,'orbiter.'..e) + if not stat then quit("cannot load extension: "..e) end + e = ext + end + e.register(obj) + end + end + return obj +end + + + +---- launch the browser ---- + +local browsers = { + "x-www-browser","gnome-open","xdg-open" +} + +local function shell(cmd) + local f = io.popen 'uname -s' + local line = f:read() + f:close() + return line +end + +local function uname() + return shell 'uname s' +end + +local function which(prog) + return shell ('which %s 2> /dev/null' % prog) +end + +local function launch_browser (url,browser) + if browser == true then + browser = nil -- autodetect! + end + if Windows then + os.execute('rundll32 url.dll,FileProtocolHandler '..url) + return + end + if not browser then + local line = uname() + if line == 'Darwin' then + browser = 'open' + else + for _,p in ipairs(browsers) do + if which(p) then browser = p; break end + end + end + end + os.execute(browser..' '..url..'&') +end + +----- Root namespace support --------- + +local function starts_with (path,prefix) + local i1,i2 = path:find(prefix,1,true) -- plain match + return i1 ~= nil and i1 == 1 and i2 == #prefix +end + +function _M.set_root (path) + _M.ROOT = '/'..path + _M.SUBSTITUTIONS = {ROOT=_M.ROOT} +end + +setmetatable(_M,{ + __call = function(self,path) + _M.set_root(path) + return _M + end +}) + +function _M.prepend_root (path) + if _M.ROOT and not (path=='#' or path:match '^http[s]://' or starts_with(path,_M.ROOT)) then + path = _M.ROOT..path + end + return path +end + +-- used to get actual path for static file lookup +function _M.strip_root (file) + if _M.ROOT then + if file == _M.ROOT then + file = '/' + else + local k + file,k = file:gsub(_M.ROOT,'',1) + if k == 0 then error("request was NOT namespaced! "..file) end + end + end + return file +end + +-- hack to let /root as well as /root/ be recognized +local function check_root (file) + if _M.ROOT and file == _M.ROOT then + file = file .. '/' + end + return file +end + +----- URL pattern dispatch -------------- + +local dispatch_set_handler + +local function static_handler(obj,web) + local content,mime = obj:read_content(web.path_info) + if not content then + return '404 Not Found',false + else + return content,mime,{ + ["Cache-Control"] = "max-age=86400" + } + end +end + +function MT:dispatch_get(callback,...) + dispatch_set_handler('GET',self,callback,...) +end + +function MT:dispatch_post(callback,...) + dispatch_set_handler('POST',self,callback,...) +end + +function MT:dispatch_any(callback,...) + dispatch_set_handler('*',self,callback,...) +end + +function MT:dispatch_static(...) + dispatch_set_handler('GET',self,static_handler,...) +end + +local patterns = {} + +function dispatch_set_handler(method,obj,callback,...) + local pats = {...} + if #pats == 1 then + local pat = pats[1] + assert(type(pat) == 'string') + pat = _M.prepend_root(pat) + if tracing then print('pattern '..pat) end + pat = '^'..pat..'$' + local pat_rec = {pat=pat,callback=callback,self=obj,method=method} + -- objects can override existing patterns, so we look for this pattern + -- and replace the handler, if the method is the same + local idx + for i,p in ipairs(patterns) do + if p.pat == pat and p.method == method then idx = i; break end + end + if idx then + patterns[idx] = pat_rec + else + append(patterns,pat_rec) + end + else + for _,pat in ipairs (pats) do + dispatch_set_handler(method,obj,callback,pat) + end + end +end + +-- The idea here is that if multiple patterns match an url, +-- then pick the longest such pattern. +-- Very general patterns (like /(.-)(/.*)) can be long, but very general. +-- So we use the length after stripping out any magic characters. +-- returns the callback, the pattern captures, and the object (if any) +local function match_patterns(method,request,obj) + local max_pat, max_i = 0 + local max_captures + request = check_root(request) + for i = 1,#patterns do + local tpat = patterns[i] + if (tpat.method == '*' or tpat.method == method) and (obj==nil or tpat.self==obj) then + local pat = tpat.pat + if tracing == 'all' then print('trying',pat,request) end + local captures = {request:match(pat)} + local pat_size = #(pat:gsub('[%(%)%.%+%-%*]','')) + if #captures > 0 and pat_size > max_pat then + max_i = i + max_pat = pat_size + max_captures = captures + if tracing then trace('matching '..pat..' '..pat_size) end + end + end + end + if max_captures then + return patterns[max_i].callback,max_captures,patterns[max_i].self + end +end + +local request_filters = {} + +local function process_request_filters(web,file) + for _,f in ipairs(request_filters) do + local newp,obj = f(web,file) + if newp then return newp,obj end + end + return file +end + +function _M.add_request_filter(f) + append(request_filters,f) +end + +function _M.remove_request_filter(f) + local idx + for i, ff in ipairs(request_filters) do + if ff == f then idx = i; break end + end + if idx then table.remove(request_filters,idx) end +end + +function _M.get_pattern_table() + return patterns +end + + +--------------- HTTP Server -------------------- +---- A little web server, based on code by Samuel Saint-Pettersen ---- +-- headers and error handling much improved by Ignacio + +local mime_types = { + other = 'text/plain', + ez = "application/andrew-inset", + atom = "application/atom+xml", + hqx = "application/mac-binhex40", + cpt = "application/mac-compactpro", + mathml = "application/mathml+xml", + doc = "application/msword", + bin = "application/octet-stream", + dms = "application/octet-stream", + lha = "application/octet-stream", + lzh = "application/octet-stream", + exe = "application/octet-stream", + class = "application/octet-stream", + so = "application/octet-stream", + dll = "application/octet-stream", + dmg = "application/octet-stream", + oda = "application/oda", + ogg = "application/ogg", + pdf = "application/pdf", + ai = "application/postscript", + eps = "application/postscript", + ps = "application/postscript", + rdf = "application/rdf+xml", + smi = "application/smil", + smil = "application/smil", + gram = "application/srgs", + grxml = "application/srgs+xml", + mif = "application/vnd.mif", + xul = "application/vnd.mozilla.xul+xml", + xls = "application/vnd.ms-excel", + ppt = "application/vnd.ms-powerpoint", + rm = "application/vnd.rn-realmedia", + wbxml = "application/vnd.wap.wbxml", + wmlc = "application/vnd.wap.wmlc", + wmlsc = "application/vnd.wap.wmlscriptc", + vxml = "application/voicexml+xml", + bcpio = "application/x-bcpio", + vcd = "application/x-cdlink", + pgn = "application/x-chess-pgn", + cpio = "application/x-cpio", + csh = "application/x-csh", + dcr = "application/x-director", + dir = "application/x-director", + dxr = "application/x-director", + dvi = "application/x-dvi", + spl = "application/x-futuresplash", + gtar = "application/x-gtar", + hdf = "application/x-hdf", + xhtml = "application/xhtml+xml", + xht = "application/xhtml+xml", + js = "application/x-javascript", + skp = "application/x-koan", + skd = "application/x-koan", + skt = "application/x-koan", + skm = "application/x-koan", + latex = "application/x-latex", + xml = "application/xml", + xsl = "application/xml", + dtd = "application/xml-dtd", + nc = "application/x-netcdf", + cdf = "application/x-netcdf", + sh = "application/x-sh", + shar = "application/x-shar", + swf = "application/x-shockwave-flash", + xslt = "application/xslt+xml", + sit = "application/x-stuffit", + sv4cpio = "application/x-sv4cpio", + sv4crc = "application/x-sv4crc", + tar = "application/x-tar", + tcl = "application/x-tcl", + tex = "application/x-tex", + texinfo = "application/x-texinfo", + texi = "application/x-texinfo", + t = "application/x-troff", + tr = "application/x-troff", + roff = "application/x-troff", + man = "application/x-troff-man", + me = "application/x-troff-me", + ms = "application/x-troff-ms", + ustar = "application/x-ustar", + src = "application/x-wais-source", + zip = "application/zip", + au = "audio/basic", + snd = "audio/basic", + mid = "audio/midi", + midi = "audio/midi", + kar = "audio/midi", + mpga = "audio/mpeg", + mp2 = "audio/mpeg", + mp3 = "audio/mpeg", + aif = "audio/x-aiff", + aiff = "audio/x-aiff", + aifc = "audio/x-aiff", + m3u = "audio/x-mpegurl", + ram = "audio/x-pn-realaudio", + ra = "audio/x-pn-realaudio", + wav = "audio/x-wav", + pdb = "chemical/x-pdb", + xyz = "chemical/x-xyz", + bmp = "image/bmp", + cgm = "image/cgm", + gif = "image/gif", + ief = "image/ief", + jpeg = "image/jpeg", + jpg = "image/jpeg", + jpe = "image/jpeg", + png = "image/png", + svg = "image/svg+xml", + svgz = "image/svg+xml", + tiff = "image/tiff", + tif = "image/tiff", + djvu = "image/vnd.djvu", + djv = "image/vnd.djvu", + wbmp = "image/vnd.wap.wbmp", + ras = "image/x-cmu-raster", + ico = "image/x-icon", + pnm = "image/x-portable-anymap", + pbm = "image/x-portable-bitmap", + pgm = "image/x-portable-graymap", + ppm = "image/x-portable-pixmap", + rgb = "image/x-rgb", + xbm = "image/x-xbitmap", + xpm = "image/x-xpixmap", + xwd = "image/x-xwindowdump", + igs = "model/iges", + iges = "model/iges", + msh = "model/mesh", + mesh = "model/mesh", + silo = "model/mesh", + wrl = "model/vrml", + vrml = "model/vrml", + ics = "text/calendar", + ifb = "text/calendar", + css = "text/css", + html = "text/html", + htm = "text/html", + asc = "text/plain", + txt = "text/plain", + rtx = "text/richtext", + rtf = "text/rtf", + sgml = "text/sgml", + sgm = "text/sgml", + tsv = "text/tab-separated-values", + wml = "text/vnd.wap.wml", + wmls = "text/vnd.wap.wmlscript", + etx = "text/x-setext", + mpeg = "video/mpeg", + mpg = "video/mpeg", + mpe = "video/mpeg", + qt = "video/quicktime", + mov = "video/quicktime", + mxu = "video/vnd.mpegurl", + avi = "video/x-msvideo", + movie = "video/x-sgi-movie", + ice = "x-conference/x-cooltalk", + rss = "application/rss+xml", + atom = "application/atom+xml" +} + +local function url_decode(url) + url = url:gsub('%+',' ') + url = url:gsub('%%(%x%x)',function(c) + c = tonumber(c,16) + return string.char(c) -- ('%s'):format(? + end) + return url +end + +local function url_encode(str) + if not str then return nil end + str = string.gsub (str, "\n", "\r\n") + str = string.gsub (str, "([^%w ])", + function (c) return string.format ("%%%02X", string.byte(c)) end) + str = string.gsub (str, " ", "+") + return str +end + +local function url_split(vars) + local res = {} + for pair in vars:gmatch('[^&]+') do + local k,v = pair:match('([^=]+)=(.*)') + v = url_decode(v) + if res[k] then -- multiple values for this name + if type(res[k]) == 'string' then res[k] = {res[k]} end + append(res[k],v) + else + res[k] = v + end + end + return res +end + +local function send_error(client, code, message) + local header = "HTTP/1.1 " .. code .. "\r\nContent-Type:text/html\r\n" + local msg = ( + [[ + +%s + +

%s

+

%s

+
+Orbiter Web Server v1.0 +]]):format(code, code, message or code) + header = header .. "Content-Length:" .. #msg .. "\r\n\r\n" + client:send(header) + client:send(msg) +end + +local function send_headers (client, code, type, length, sheaders) + local extra = '' + if sheaders then + local res, append = {}, table.insert + for head, value in pairs(sheaders) do + append(res,head..": "..value..'\r\n') + end + extra = table.concat(res) + end + client:send( ("HTTP/1.1 %s\r\n%sContent-Type: %s\r\nContent-Length: %d\r\nConnection: close\r\n\r\n"):format(code, extra, type, length) ) +end + +-- process headers from a connection (borrowed from socket.http) +-- note that the variables have '-' replaced as '_' to make them WSAPI compatible +-- (e.g. HTTP_CONTENT_LENGTH) +local function receiveheaders(sock) + local line, name, value, err + local headers = {} + -- get first line + line, err = sock:receive() + if err then return nil, err end + -- headers go until a blank line is found + while line ~= "" do + -- get field-name and value + name, value = line:match "^(.-):%s*(.*)" + if not (name and value) then return nil, "malformed reponse headers" end + name = 'HTTP_'..name:upper():gsub('%-','_') + -- get next line (value might be folded) + line, err = sock:receive() + if err then return nil, err end + -- unfold any folded values + while line:find("^%s") do + value = value .. line + line = sock:receive() + if err then return nil, err end + end + -- save pair in table + if headers[name] then headers[name] = headers[name] .. ", " .. value + else headers[name] = value end + end + return headers +end + +function MT:get_path_to(file) + return self.root .. file +end + +function MT:read_content(file) + file = _M.strip_root(file) + if file == '/' then file = '/index.html' end + local extension = file:match('%.(%a+)$') or 'other' + local path = self:get_path_to(file) + local content = readfile (path) + if content then + if tracing then trace('returning '..path) end + local mime = mime_types[extension] or 'text/plain' + return content,mime + else + print('error: unable to find '..path) + return false + end +end + +function MT:dispatch(web,path) + local action,captures,obj = match_patterns('GET',path) --?? + if not action or obj ~= self then return nil end + return action(obj,web,unpack(captures)) +end + +local running,last_obj + +function _M.get_last_object() + return last_obj +end + +function trace(stuff) + io.stderr:write(stuff,'\n') +end + +local num_retries = 100 + +-- this is based on socket.bind from LuaSocket. +-- However, we _do_ want to know if the port is already in use, +-- because we want to try again with a higher port number. +local function socket_bind(host,port,backlog) + local sock, err, res + for i = 1,num_retries do + sock, err = socket.tcp() + if not sock then return nil, err end + sock:setoption("reuseaddr", true) + res, err = sock:bind(host, port) + if not res then + if err == 'address already in use' then + port = port + 1 + else + return nil,err + end + else + break + end + end + res, err = sock:listen(backlog) + if not res then return nil, err end + return sock,port +end + +----- Web class ----- +local Web = +{ + vars = {}, + input = {}, + headers = {}, + status = "200 OK", + method = "", + path_info = "" +} + +function Web:redirect(url) + self.status = "302 Found" + self.headers["Location"] = _M.prepend_root(url) + return "redirect" +end + +function Web:link(url, params) + local link = {} + -- url encode parameters + for k, v in pairs(params or {}) do + link[#link + 1] = k .. "=" .. url_encode(v) + end + local qs = table.concat(link, "&") + if qs and qs ~= "" then + return _M.prepend_root(url) .. "?" .. qs + else + return _M.prepend_root(url) + end +end + +function Web:new(o) + o = o or {} -- create object if user does not provide one + setmetatable(o, self) + self.__index = self + return o +end + +function MT:run(...) + local args,flags + flags,args = _M.parse_flags(...) + local addr = flags['addr'] or 'localhost' + local port = flags['port'] or '8080' + + local fake = flags['test'] + local testing = flags['no_headers'] and fake + last_obj = self + + if running then return + else running = true + end + + tracing = flags['trace'] + _M.tracing = tracing + + if flags['help'] then + print(help_text) + os.exit() + end + + if fake then + addr = fake==true and '/' or fake + end + + if self.env then + for k,v in pairs(self) do + if type(v) == 'function' then + setfenv(v,self.env) + end + end + end + + -- create TCP socket on addr:port: allow for a debug hook + local server_ctor = fake and require 'orbiter.fake' or socket_bind + local server, port = assert(server_ctor(addr, tonumber(port))) + if not fake then + local URL = 'http://'..addr..':'..port + print ("Orbiter serving on "..URL) + if flags['launch'] then + launch_browser(URL,flags['launch']) + end + end + -- loop while waiting for a user agent request + while 1 do + -- wait for a connection, set timeout and receive request from user agent + local client = server:accept() + client:settimeout(60) + local request, err = client:receive() + if not err then + local content,file,action,captures,obj,web,vars,headers,err,sheaders,url + if tracing then trace('request: '..request) end + local method = request:match '^([A-Z]+)' + if not fake then + headers,err = receiveheaders(client) + end + if not err then + if headers then + headers.HTTP_REMOTE = client:getpeername() + end + if method == 'POST' then + local size = tonumber(headers.HTTP_CONTENT_LENGTH) + vars = client:receive(size) + if tracing then trace('post: '..vars) end + end + -- resolve requested file from user agent request + file = request:match('(/%S*)') + if method == 'GET' then + url,vars = file:match('([^%?]+)%?(.+)') + if url then file = url end + end + vars = vars and url_split(vars) or {} + -- setup the web object + web = Web:new{ vars = headers, input = vars, method = method:lower(), path_info = file } + web[method=='GET' and 'GET' or 'POST'] = vars + + file, obj = process_request_filters(web,file) + action, captures, obj = match_patterns(method, file, obj) + if action then + -- @doc handlers may specify the MIME type of what they + -- return, if they choose; default is HTML. + local status, content, mime = pcall(action, obj, web, unpack(captures)) + + if status then + if not content and method ~= 'POST' then + status = false + content = '404 Request Failed' + elseif mime == false then + status = false + end + else + print('exception: '..tostring(content)) + end + if content then -- can naturally be nil for POST requests! + if status then + -- @doc if the app or extension object defines a content_filter method, + -- it will receive the content and mime type, and is expected to + -- return the same. + if self.content_filter then + content, mime = self:content_filter(content, mime) + end + if not testing then + send_headers(client, web.status, mime or 'text/html', #content, web.headers) + end + client:send(content) + else + send_error(client, content) + end + end + else -- unmatched pattern!! + send_error (client,'404 Not Found') + end + else + print ('header parsing failed:',err) + end + else + print ('client receive failed',err) + end + -- done with client, close request + client:close() + end +end + +return _M -- orbiter! diff --git a/demo/orbiter/libs/jquery.lua b/demo/orbiter/libs/jquery.lua new file mode 100644 index 0000000..7cacbe5 --- /dev/null +++ b/demo/orbiter/libs/jquery.lua @@ -0,0 +1,265 @@ +local orbiter = require 'orbiter' +local html = require 'orbiter.html' +local text = require 'orbiter.text' +local bridge = require 'orbiter.bridge' +local _M = {} + +local jquery_js = '/resources/jquery-1.8.3.min.js' + +local app = bridge.dispatch_static(text.lua_escape(jquery_js)) + +local ajax_request = '/jq/request' + +html.set_defaults { + scripts = jquery_js, + inline_script = ([[ + function jq_call_server(id,klass,tid) { + $.get("%s",{id: id, group_id: tid, klass: klass }); + } + function jq_file_click(klass,id,tid,event) { + var href = $('#'+id).attr('title'); + if (href == "") { + href = $('#'+id+' span').attr('title'); + } + if (href != "" && href != undefined) { + window.location = href; + } else { // otherwise, it's for the server to handle + jq_call_server(id,klass,tid) + } + event.stopImmediatePropagation(); + return false; + } + function jq_set_click(select,container_id) { + $(select).click(function(event) { + var klass = $(this).attr('class') + return jq_file_click(klass,this.id,container_id,event); + }) + } + function jq_submit_form(id) { + var form = $("form#"+id); + $.post(form.attr("action"), form.serialize()); + } +]]):format(orbiter.prepend_root(ajax_request)), +} + +---- some useful functions ---- + +-- minimal escaping for JS strings +function _M.escape(s) + return tostring(s):gsub("'","\\'"):gsub("\n","\\n") +end + +function _M.eval (s) + return s, "text/javascript" +end + +function _M.alert(s) + return _M.eval('alert("'.._M.escape(s)..'");') +end + +local lua_data_map = {} +local lua_data_index = 1 + +function _M.data_to_id(data) + local ret = ('D%x'):format(lua_data_index) + lua_data_index = lua_data_index + 1 + lua_data_map[ret] = data + return ret +end +local data_to_id = _M.data_to_id + +local function call_if(fun,arg,id) + if fun then + local resp,mtype = fun(arg,id) + mtype = mtype or 'text/javascript' + return tostring(resp),mtype + else + return '' + end +end + +function _M.call_handler(idata,tdata,id,name) + return call_if(idata[name] or tdata[name],idata,id) +end + +-- callback magic: if an item is clicked, then the JS function jq_file_click +-- will make an async request which is handled here. +-- An application may add to this functionality.... +-- (By default, callbacks are assumed to return JavaScript; set another mime type +-- explicitly if this is inappropriate.) +function app:jq_request(web) + local vars = web.input + if orbiter.tracing then print('request wuz ',vars.id, vars.group_id,vars.klass) end + local klass = vars.klass or 'nada' + local idata = lua_data_map[vars.id] or 'nada' + local tdata = lua_data_map[vars.group_id] or 'nada' + if idata == 'nada' and tdata == 'nada' then + print('received nada',vars.klass,vars.id,vars.group_id) + return '' + end + local resp,mtype + if tdata.click_handler then + local resp,mtype = tdata.click_handler(klass,idata,tdata,vars.id) + if resp then return resp,mtype end + end + return _M.call_handler(idata,tdata,vars.id,'click') +end + +app:dispatch_get(app.jq_request,ajax_request) + +function _M.set_data(id,data) + local this = { data = data } + lua_data_map[id] = this + return this +end + +function _M.set_handler (name, id, obj) + if obj[name] then + lua_data_map[id][name] = obj[name] + obj[name] = nil + end +end + +local button_ = html.tags 'button' + +local function as_callback (callback) + if type(callback) == 'table' then + local id = callback.id + callback = function() + return 'jq_submit_form("'..id..'");' + end + end + return callback +end + +function _M.button(label,callback) + return { + button_{class='click-button', + id = data_to_id {click = as_callback(callback)}, + label}, + html.script('jq_set_click("button.click-button","buttons")') + } +end + +function _M.link(label,callback) + return { + span{class='click-link', + id = data_to_id { click = callback }, + label}, + html.script('jq_set_click("span.click-link","buttons")') + } +end + +function _M.reload() + return "window.location.href=window.location.href" +end + +local JMT = {} + +local function has_meta(t,name) + local mt = getmetatable(t) + if not mt then return false + else + return mt[name] ~= nil + end +end + +local js_tostring + +function js_tostring(args) + local concat = table.concat + for i,a in ipairs(args) do + local ta = type(a) + if html.is_doc(a) then + -- don't want pretty-printing here! + a = html.raw_tostring(a) + ta = 'string' + end + if ta == 'table' and not has_meta(a,'__tostring') then + if #a > 0 then -- list-like + return '['..js_tostring(a)..']' + else -- map-like + local vv = {} + for k,v in pairs(a) do + vv[#vv+1] = k..' : '..js_tostring {v} + end + a = '{'..concat(vv,',')..'}' + end + elseif ta == 'string' then + a = '"'.._M.escape(a)..'"' + else + a = tostring(a) + end + args[i] = a + end + return concat(args,',') +end + +function _M.tostring(t) + return js_tostring{t} +end + +local function jqw(code) + return setmetatable({js = code},JMT) +end + +-- this module is callable, e.g. jq("#iden") and creates a jQuery selector +-- expression +setmetatable(_M,{ + __call = function(tbl,selector) + return jqw ('$("'..selector..'")' ) + end +}) + +function JMT.__tostring(self) + return self.js +end + +function JMT.__index(self,method) + if method == '_' then method = ';' + elseif method == '_end' then method = 'end' + end + return jqw(self.js..'.'..method) +end + +function JMT.__call(obj,self,...) + local args = {...} -- assume no nils + return jqw(obj.js..'('..js_tostring(args,',')..')') +end + +function _M.timeout(ms,callback) + local id = data_to_id { click = as_callback(callback) } + return ([[ + setTimeout("jq_call_server('%s',null,null)", %d) + ]]):format(id,ms) +end + +function _M.timeout_script (ms,callback) + return html.script(_M.timeout(ms,callback)) +end + +function _M.use_timer() + html.set_defaults { + inline_script = [[ + var jq_timer_data = [null,null]; + function jq_timer() { + if (jq_timer_data[0] != null) { + jq_call_server(jq_timer_data[0],null,null); + setTimeout("jq_timer()", jq_timer_data[1]); + } + } + ]] + } +end + +function _M.timer(ms,callback) + local id = data_to_id { click = as_callback(callback) } + return ('jq_timer_data = ["%s",%d];setTimeout("jq_timer()", %d)'):format(id,ms,ms) +end + +function _M.cancel_timer() + return 'jq_timer_data[0] = null' +end + + +return _M diff --git a/demo/orbiter/libs/resources/jquery-1.8.3.min.js b/demo/orbiter/libs/resources/jquery-1.8.3.min.js new file mode 100644 index 0000000..3883779 --- /dev/null +++ b/demo/orbiter/libs/resources/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/demo/orbiter/tags.lua b/demo/orbiter/tags.lua new file mode 100644 index 0000000..e598fe4 --- /dev/null +++ b/demo/orbiter/tags.lua @@ -0,0 +1,156 @@ +---- +-- @module tags +local html = require 'orbiter.html' + +local _M = {} + +local html5_tags = { + a = true, + abbr = true, + address = true, + area = true, + article = true, + aside = true, + audio = true, + b = true, + base = true, + bdi = true, + bdo = true, + blockquote = true, + body = true, + br = true, + button = true, + canvas = true, + caption = true, + cite = true, + code = true, + col = true, + colgroup = true, + command = true, + data = true, + datagrid = true, + datalist = true, + dd = true, + del = true, + details = true, + dfn = true, + div = true, + dl = true, + dt = true, + em = true, + embed = true, + eventsource = true, + fieldset = true, + figcaption = true, + figure = true, + footer = true, + form = true, + h1 = true, + h2 = true, + h3 = true, + h4 = true, + h5 = true, + h6 = true, + head = true, + header = true, + hgroup = true, + hr = true, + html = true, + i = true, + iframe = true, + img = true, + input = true, + ins = true, + kbd = true, + keygen = true, + label = true, + legend = true, + li = true, + link = true, + mark = true, + map = true, + menu = true, + meta = true, + meter = true, + nav = true, + noscript = true, + object = true, + ol = true, + optgroup = true, + option = true, + output = true, + p = true, + param = true, + pre = true, + progress = true, + q = true, + ruby = true, + rp = true, + rt = true, + s = true, + samp = true, + script = true, + section = true, + select = true, + small = true, + source = true, + span = true, + strong = true, + style = true, + sub = true, + summary = true, + details = true, + sup = true, + table = true, + tbody = true, + td = true, + textarea = true, + tfoot = true, + th = true, + thead = true, + time = true, + title = true, + tr = true, + track = true, + u = true, + ul = true, + var = true, + video = true, + wbr = true, +} + +local tag,rawget = html.tags,rawget +local env,_G = {html=html},_G + +_M.env = { + __index = function(t,name) + local g = rawget(_G,name) -- in case of strict mode! + if g then return g end + -- see if it's an HTML tag! + name = name:lower() + if html5_tags[name] then + env[name] = tag(name) + else + error("unknown HTML tag "..name,2) + end + return rawget(env,name) + end +} + +setmetatable(env,_M.env) + +function _M.use () + setfenv(2,env) +end + +function _M.set (funs) + for _,f in ipairs(funs) do + setfenv(f,env) + end +end + +function _M.register (obj) + obj.env = env +end + +return _M diff --git a/demo/orbiter/template.lua b/demo/orbiter/template.lua new file mode 100644 index 0000000..15bc9b2 --- /dev/null +++ b/demo/orbiter/template.lua @@ -0,0 +1,108 @@ +-- Orbiter, a personal web application framework +-- Lua template preprocessor +-- Originally by Ricki Lake. +-- + +local append,format = table.insert,string.format + +local parse1,parse2 = "()","(%b())()" +local parse_dollar + +local load = load + +if _VERSION:match '5%.1$' then -- Lua 5.1 compatibility + function load(str,name,mode,env) + local chunk,err = loadstring(str,name) + if chunk then setfenv(chunk,env) end + return chunk,err + end +end + +local function parseDollarParen(pieces, chunk, s, e) + local s = 1 + for term, executed, e in chunk:gmatch (parse_dollar) do + append(pieces, + format("%q..(%s or '')..",chunk:sub(s, term - 1), executed)) + s = e + end + append(pieces, format("%q", chunk:sub(s))) +end +------------------------------------------------------------------------------- +local function parseHashLines(chunk) + local find = string.find + local pieces, s, args = find(chunk,"^\n*#ARGS%s*(%b())[ \t]*\n") + if not args or find(args, "^%(%s*%)$") then + pieces, s = {"return function(_put) ", n = 1}, s or 1 + else + pieces = {"return function(_put, ", args:sub(2), n = 2} + end + while true do + local ss, e, lua = find (chunk,"^#+([^\n]*\n?)", s) + if not e then + ss, e, lua = find(chunk,"\n#+([^\n]*\n?)", s) + append(pieces, "_put(") + parseDollarParen(pieces, chunk:sub(s, ss)) + append(pieces, ")") + if not e then break end + end + append(pieces, lua) + s = e + 1 + end + append(pieces, " end") + return table.concat(pieces) +end + +local template = {} + +function template.substitute(str,env) + env = env or {} + if env.__parent then + setmetatable(env,{__index = env.__parent}) + end + local out,res = {} + parse_dollar = parse1..(env.__dollar or '$')..parse2 + local code = parseHashLines(str) + local fn,err = load(code,'TMP','t',env) + if not fn then return nil,err end + res,fn = pcall(fn) + if not res then return nil,err end + res,err = pcall(fn,function(s) + out[#out+1] = s + end) + if not res then return nil,err end + return table.concat(out) +end + +local cache = {} + +function template.page(file,env) + local app = env.app + if app then file = app.resources..'/'..file end + local do_cache = env.cache + do_cache = do_cache==nil and true + env.app = nil + env.cache = nil + local tmpl + if do_cache then tmpl = cache[file] end + if not tmpl then + local f,err = io.open(file) + if not f then return nil, err end + tmpl = f:read '*a' + f:close() + end + if do_cache then cache[file] = tmpl end + return template.substitute(tmpl,env) +end + +function template.templater (default_env) + return function(file,env) + for k,v in pairs(default_env) do env[k] = v end + return template.page(file,env) + end +end + +return template + + + + diff --git a/demo/orbiter/text.lua b/demo/orbiter/text.lua new file mode 100644 index 0000000..7e3d8b3 --- /dev/null +++ b/demo/orbiter/text.lua @@ -0,0 +1,76 @@ +-- Orbiter, a personal web application framework +-- Yet another little template expansion function, but dead simple (promise!). +-- Also supports Python-like string formatting by overloading % operator. +-- (see http://lua-users.org/wiki/StringInterpolation +local _M = {} + +function _M.lua_escape(s) + return (s:gsub('[%-%.%+%[%]%(%)%$%^%%%?%*]','%%%1')) +end + +local function basic_subst(s,t) + return (s:gsub('%$([%w_]+)',t)) +end + +local format = string.format + +--- version of `string.format` where '%s' uses `tostring` +function _M.formatx (fmt,...) + local args = {...} + local i = 1 + for p in fmt:gmatch('%%.') do + if p == '%s' and type(args[i]) ~= 'string' then + args[i] = tostring(args[i]) + end + i = i + 1 + end + return format(fmt,unpack(args)) +end + +--- Python-like string formatting with % operator. +-- Note this goes further than the original, and will allow these cases: +-- 1. a single value +-- 2. a list of values +-- 3. a map of var=value pairs +-- 4. a function, as in gsub +-- For the second two cases, it uses $-variable substituion. +function _M.enable_python_formatting() + local formatx = _M.formatx + getmetatable("").__mod = function(a, b) + if b == nil then + return a + elseif type(b) == "table" and getmetatable(b) == nil then + if #b == 0 then -- assume a map-like table + return basic_subst(a,b) + else + return formatx(a,unpack(b)) + end + elseif type(b) == 'function' then + return basic_subst(a,b) + else + return formatx(a,b) + end + end +end + +--- really basic templates; +-- (Templates are callable so subst is unnecessary) +-- +-- t = text.Template 'hello $world' +-- print(t:subst {world = 'dolly'}). +function _M.Template(str) + local tpl = {s=str} + function tpl:subst(t) + return basic_subst(str,t) + end + setmetatable(tpl,{ + __call = function(obj,t) + return obj:subst(t) + end + }) + return tpl +end + +_M.subst = basic_subst + +return _M -- orbiter.text diff --git a/demo/orbiter/util.lua b/demo/orbiter/util.lua new file mode 100644 index 0000000..45970ac --- /dev/null +++ b/demo/orbiter/util.lua @@ -0,0 +1,175 @@ +-- Orbiter, a personal web application framework +-- various general facilities like extra table operations and a simple +-- class-based OOP scheme. + +local append = table.insert +local _M = {} + +--- extended type of a value. If the value is a table and it has a metatable, +-- then that metatable is the type. +function _M.type_of(val) + local tv = type(val) + if (tv == 'table' or tv=='userdata') and getmetatable(val) then + return getmetatable(val) + else + return tv + end +end + +local function is_table (t) + return type(t) == 'table' +end +_M.is_table = is_table + +local Class = {} + +function _M.class(base) + local mt = {} + base = base or Class + _M.update(mt,base) + mt._base = base + mt.__index = mt + setmetatable(mt,{ + __call = function (cmt,...) -- Type(args) is the constructor + local obj = {} + setmetatable(obj,mt) + if obj.init then obj:init(...) end + return obj + end + }) + return function(body) + if body then _M.update(mt,body) end + return mt + end +end + +--- is val an instance of the class type type?. +-- @param val any value +-- @param type a class type (metatable) +function _M.class_of(val,tp) + local mt = _M.type_of(val) + if is_table(mt) then + while mt do + if mt == tp then return true end + mt = mt._base + end + end + return false +end + +function _M.is_plain(t) + return is_table(t) and getmetatable(t) == nil +end + +function _M.is_list(t) + return _M.is_plain(t) and #t > 0 +end + +function _M.copy(t) + local res = {} + for k,v in pairs(t) do res[k] = v end + return res +end + +function _M.copy_list(t) + local res = {} + for k,v in ipairs(t) do res[k] = v end + return res +end + +function _M.update(t1,t2) + for k,v in pairs(t2) do t1[k] = v end + return t1 +end + +function _M.force(t) + if not is_table(t) then return {t} + else return t + end +end + +function _M.copy_map(t) + local res = {} + local sz = #t + for k,v in pairs(t) do + if type(k)~='number' or k <= 0 or k > sz then + res[k] = v + end + end + return res +end + +function _M.index_of(t,val) + for k,v in pairs(t) do + if v == val then return k end + end +end + +function _M.imap(fun,t,i1,i2) + local res = {} + i2 = i2 or #t + i1 = i1 or 1 + local j = 1 + for i = i1,i2 do + res[j] = fun (t[i]) + j = j + 1 + end + return res +end + +function _M.compose (f1,f2) + return function(...) + return f1(f2(...)) + end +end + +function _M.concat_list(l1,l2) + l1,l2 = _M.force(l1), _M.force(l2) + local res = {unpack(l1)} + for _,v in ipairs(l2) do + append(res,v) + end + return res +end + +function _M.reshape2D(t,ncols) + local res = {} + local row = {} + for i = 1,#t do + append(row,t[i]) + if i % ncols == 0 then + append(res,row) + row = {} + end + end + return res +end + +function _M.dimensions(t) + if not is_table(t) or #t == 0 then + return nil + end + local n = #t + local m = is_table(#t) and #t[1] or nil + return n,m +end + +function _M.flatten(t) + local n,m = _M.dimensions(t) + assert(m ~= nil,"must be a 2D array") + local res = {} + local k = 1 + for i = 1,n do for j = 1,m do + res[k] = t[i][j] + k = k + 1 + end end + return res +end + +function _M.transpose(t) + local nrows,ncols = _M.dimensions(t) + local arr = _M.flatten(t) + return _M.reshape2D(arr,nrows) +end + +return _M diff --git a/demo/resources/css/dialog-polyfill.css b/demo/resources/css/dialog-polyfill.css new file mode 100644 index 0000000..af6f00a --- /dev/null +++ b/demo/resources/css/dialog-polyfill.css @@ -0,0 +1,40 @@ +dialog { + position: absolute; + left: 0; right: 0; + width: -moz-fit-content; + width: -webkit-fit-content; + width: fit-content; + height: -moz-fit-content; + height: -webkit-fit-content; + height: fit-content; + margin: auto; + border: none; + padding: 1em; + background: white; + color: black; + display: none; +} + +dialog[open] { + display: block; +} + +dialog + .backdrop { + position: fixed; + top: 0; right: 0; bottom: 0; left: 0; + background: rgba(0,0,0,0.1); +} + +/* for small devices, modal dialogs go full-screen */ +@media screen and (max-width: 540px) { + dialog[_polyfill_modal] { /* TODO: implement */ + top: 0; + width: auto; + margin: 1em; + } +} + +._dialog_overlay { + position: fixed; + top: 0; right: 0; bottom: 0; left: 0; +} \ No newline at end of file diff --git a/demo/resources/css/images/ajax-loader.gif b/demo/resources/css/images/ajax-loader.gif new file mode 100644 index 0000000..bc54585 Binary files /dev/null and b/demo/resources/css/images/ajax-loader.gif differ diff --git a/demo/resources/css/images/file.gif b/demo/resources/css/images/file.gif new file mode 100644 index 0000000..7e62167 Binary files /dev/null and b/demo/resources/css/images/file.gif differ diff --git a/demo/resources/css/images/folder-closed.gif b/demo/resources/css/images/folder-closed.gif new file mode 100644 index 0000000..5411078 Binary files /dev/null and b/demo/resources/css/images/folder-closed.gif differ diff --git a/demo/resources/css/images/folder.gif b/demo/resources/css/images/folder.gif new file mode 100644 index 0000000..2b31631 Binary files /dev/null and b/demo/resources/css/images/folder.gif differ diff --git a/demo/resources/css/images/treeview-black-line.gif b/demo/resources/css/images/treeview-black-line.gif new file mode 100644 index 0000000..e549687 Binary files /dev/null and b/demo/resources/css/images/treeview-black-line.gif differ diff --git a/demo/resources/css/images/treeview-black.gif b/demo/resources/css/images/treeview-black.gif new file mode 100644 index 0000000..d549b9f Binary files /dev/null and b/demo/resources/css/images/treeview-black.gif differ diff --git a/demo/resources/css/images/treeview-default-line.gif b/demo/resources/css/images/treeview-default-line.gif new file mode 100644 index 0000000..37114d3 Binary files /dev/null and b/demo/resources/css/images/treeview-default-line.gif differ diff --git a/demo/resources/css/images/treeview-default.gif b/demo/resources/css/images/treeview-default.gif new file mode 100644 index 0000000..a12ac52 Binary files /dev/null and b/demo/resources/css/images/treeview-default.gif differ diff --git a/demo/resources/css/images/treeview-famfamfam.gif b/demo/resources/css/images/treeview-famfamfam.gif new file mode 100644 index 0000000..0cb178e Binary files /dev/null and b/demo/resources/css/images/treeview-famfamfam.gif differ diff --git a/demo/resources/css/images/treeview-gray-line.gif b/demo/resources/css/images/treeview-gray-line.gif new file mode 100644 index 0000000..3760044 Binary files /dev/null and b/demo/resources/css/images/treeview-gray-line.gif differ diff --git a/demo/resources/css/images/treeview-gray.gif b/demo/resources/css/images/treeview-gray.gif new file mode 100644 index 0000000..cfb8a2f Binary files /dev/null and b/demo/resources/css/images/treeview-gray.gif differ diff --git a/demo/resources/css/images/treeview-red-line.gif b/demo/resources/css/images/treeview-red-line.gif new file mode 100644 index 0000000..df9e749 Binary files /dev/null and b/demo/resources/css/images/treeview-red-line.gif differ diff --git a/demo/resources/css/images/treeview-red.gif b/demo/resources/css/images/treeview-red.gif new file mode 100644 index 0000000..3bbb3a1 Binary files /dev/null and b/demo/resources/css/images/treeview-red.gif differ diff --git a/demo/resources/css/jquery.treeview.css b/demo/resources/css/jquery.treeview.css new file mode 100644 index 0000000..8927a99 --- /dev/null +++ b/demo/resources/css/jquery.treeview.css @@ -0,0 +1,74 @@ +.treeview, .treeview ul { + padding: 0; + margin: 0; + list-style: none; +} + +.treeview ul { + background-color: white; + margin-top: 4px; +} + +.treeview .hitarea { + background: url(images/treeview-default.gif) -64px -25px no-repeat; + height: 16px; + width: 16px; + margin-left: -16px; + float: left; + cursor: pointer; +} +/* fix for IE6 */ +* html .hitarea { + display: inline; + float:none; +} + +.treeview li { + margin: 0; + padding: 3px 0pt 3px 16px; +} + +.treeview a.selected { + background-color: #eee; +} + +#treecontrol { margin: 1em 0; display: none; } + +.treeview .hover { color: red; cursor: pointer; } + +.treeview li { background: url(images/treeview-default-line.gif) 0 0 no-repeat; } +.treeview li.collapsable, .treeview li.expandable { background-position: 0 -176px; } + +.treeview .expandable-hitarea { background-position: -80px -3px; } + +.treeview li.last { background-position: 0 -1766px } +.treeview li.lastCollapsable, .treeview li.lastExpandable { background-image: url(images/treeview-default.gif); } +.treeview li.lastCollapsable { background-position: 0 -111px } +.treeview li.lastExpandable { background-position: -32px -67px } + +.treeview div.lastCollapsable-hitarea, .treeview div.lastExpandable-hitarea { background-position: 0; } + +.treeview-red li { background-image: url(images/treeview-red-line.gif); } +.treeview-red .hitarea, .treeview-red li.lastCollapsable, .treeview-red li.lastExpandable { background-image: url(images/treeview-red.gif); } + +.treeview-black li { background-image: url(images/treeview-black-line.gif); } +.treeview-black .hitarea, .treeview-black li.lastCollapsable, .treeview-black li.lastExpandable { background-image: url(images/treeview-black.gif); } + +.treeview-gray li { background-image: url(images/treeview-gray-line.gif); } +.treeview-gray .hitarea, .treeview-gray li.lastCollapsable, .treeview-gray li.lastExpandable { background-image: url(images/treeview-gray.gif); } + +.treeview-famfamfam li { background-image: url(images/treeview-famfamfam-line.gif); } +.treeview-famfamfam .hitarea, .treeview-famfamfam li.lastCollapsable, .treeview-famfamfam li.lastExpandable { background-image: url(images/treeview-famfamfam.gif); } + +.treeview .placeholder { + background: url(images/ajax-loader.gif) 0 0 no-repeat; + height: 16px; + width: 16px; + display: block; +} + +.filetree li { padding: 3px 0 2px 16px; } +.filetree span.folder, .filetree span.file { padding: 1px 0 1px 16px; display: block; } +.filetree span.folder { background: url(images/folder.gif) 0 0 no-repeat; } +.filetree li.expandable span.folder { background: url(images/folder-closed.gif) 0 0 no-repeat; } +.filetree span.file { background: url(images/file.gif) 0 0 no-repeat; } diff --git a/demo/resources/css/style.css b/demo/resources/css/style.css new file mode 100644 index 0000000..c9dd63e --- /dev/null +++ b/demo/resources/css/style.css @@ -0,0 +1,53 @@ +body { + text-align: center; +} + +button.mdl-button { + margin: 30px; +} + +td { + display: table-cell; + vertical-align: middle; + text-align: left; +} + +#placeholder { + opacity: 1.0; + width:256px; + height:256px; + text-align:left; +} + +#obj_img { + text-align:left; + padding:0px; + margin:0px; + width: 256px; + height: 256px; +} +//#placeholder { + //opacity: 0.5; + //position:absolute; +// opacity: 1.0; +// padding-left:0px; +// margin-left:0px; +// left: 0px; +// top: 0px; +// width:256px; +// height:256px; +//} + +#draw_box_canvas { + position:absolute; + margin:0px; + padding:0px; + top: 0px; + left: 0px; + width: 256px; + height: 256px; +} + +.mdl-layout__header { + min-height: 30px; +} diff --git a/demo/resources/css/style_kp.css b/demo/resources/css/style_kp.css new file mode 100644 index 0000000..ee1c011 --- /dev/null +++ b/demo/resources/css/style_kp.css @@ -0,0 +1,53 @@ +body { + text-align: center; +} + +button.mdl-button { + margin: 30px; +} + +td { + display: table-cell; + vertical-align: middle; + text-align: center; +} + +.placeholder { + opacity: 0.80; +} + +.canvas_container { + position: relative; + text-align: left; +} + +.canvas_class { + position:absolute; + top: 0px; + left: 0px; + width: 256px; + height: 256px; +} + +#contextMenu{ + height: 0px; + width: 0px; + border:1px solid green; + background:white; + list-style:none; + padding:3px; + visibility: hidden; +} + +.mdl-layout__header { + min-height: 30px; +} + +.demo-list-control { + width: 300px; +} + +.demo-list-radio { + display: inline; +} + diff --git a/demo/resources/css/style_kp_sam.css b/demo/resources/css/style_kp_sam.css new file mode 100644 index 0000000..e7f6155 --- /dev/null +++ b/demo/resources/css/style_kp_sam.css @@ -0,0 +1,56 @@ +body { + text-align: center; +} + +button.mdl-button { + margin: 30px; +} + +td { + display: table-cell; + vertical-align: middle; + text-align: center; +} + +.placeholder { + opacity: 1.0; +} + +.canvas_container { + position: relative; + text-align: left; +} +.pp_canvas { + background-color: rgba(0,255,255,0.5); +} + +.canvas_class { + position:absolute; + top: 0px; + left: 0px; + height: 512px; + width: 768px; +} + +#contextMenu{ + height: 0px; + width: 0px; + border:1px solid green; + background:white; + list-style:none; + padding:3px; + visibility: hidden; +} + +.mdl-layout__header { + min-height: 30px; +} + +.demo-list-control { + width: 300px; +} + +.demo-list-radio { + display: inline; +} + diff --git a/demo/resources/css/style_kp_sam.css~ b/demo/resources/css/style_kp_sam.css~ new file mode 100644 index 0000000..e7f6155 --- /dev/null +++ b/demo/resources/css/style_kp_sam.css~ @@ -0,0 +1,56 @@ +body { + text-align: center; +} + +button.mdl-button { + margin: 30px; +} + +td { + display: table-cell; + vertical-align: middle; + text-align: center; +} + +.placeholder { + opacity: 1.0; +} + +.canvas_container { + position: relative; + text-align: left; +} +.pp_canvas { + background-color: rgba(0,255,255,0.5); +} + +.canvas_class { + position:absolute; + top: 0px; + left: 0px; + height: 512px; + width: 768px; +} + +#contextMenu{ + height: 0px; + width: 0px; + border:1px solid green; + background:white; + list-style:none; + padding:3px; + visibility: hidden; +} + +.mdl-layout__header { + min-height: 30px; +} + +.demo-list-control { + width: 300px; +} + +.demo-list-radio { + display: inline; +} + diff --git a/demo/resources/css/style_santosh.css b/demo/resources/css/style_santosh.css new file mode 100644 index 0000000..809204d --- /dev/null +++ b/demo/resources/css/style_santosh.css @@ -0,0 +1,52 @@ +body { + text-align: center; +} + +button.mdl-button { + margin: 30px; +} + +td { + display: table-cell; + vertical-align: middle; + text-align: center; +} + +.placeholder { + opacity: 0.5; +} + +.canvas_container { + position: relative; +} + +.canvas_class { + position:absolute; + top: 0px; + left: 0px; + width: 500px; + height: 500px; +} + +#contextMenu{ + height: 0px; + width: 0px; + border:1px solid green; + background:white; + list-style:none; + padding:3px; + visibility: hidden; +} + +.mdl-layout__header { + min-height: 30px; +} + +.demo-list-control { + width: 300px; +} + +.demo-list-radio { + display: inline; +} + diff --git a/demo/resources/images/clear.gif b/demo/resources/images/clear.gif new file mode 100644 index 0000000..f55d454 Binary files /dev/null and b/demo/resources/images/clear.gif differ diff --git a/demo/resources/images/logo.gif b/demo/resources/images/logo.gif new file mode 100644 index 0000000..2f5e4ac Binary files /dev/null and b/demo/resources/images/logo.gif differ diff --git a/demo/resources/images/placeholder.jpg b/demo/resources/images/placeholder.jpg new file mode 100644 index 0000000..a1a354e Binary files /dev/null and b/demo/resources/images/placeholder.jpg differ diff --git a/demo/resources/images/result.jpg b/demo/resources/images/result.jpg new file mode 100644 index 0000000..e60b062 Binary files /dev/null and b/demo/resources/images/result.jpg differ diff --git a/demo/resources/javascript/.generate_kp_sam.js.swp b/demo/resources/javascript/.generate_kp_sam.js.swp new file mode 100644 index 0000000..0f3c27f Binary files /dev/null and b/demo/resources/javascript/.generate_kp_sam.js.swp differ diff --git a/demo/resources/javascript/Disk.js~ b/demo/resources/javascript/Disk.js~ new file mode 100644 index 0000000..c68930f --- /dev/null +++ b/demo/resources/javascript/Disk.js~ @@ -0,0 +1,37 @@ +function SimpleDiskParticle(posX, posY, text, id) { + this.id = id + this.x = posX; + this.y = posY; + this.radius = 15; + this.text = text; + this.bigcolor = 'rgba(255,0,0,0.8)'; + this.smallcolor = 'rgba(255,255,255,0.5)'; + this.textcolor = 'rgba(0,0,0,1)'; +} + +/*Checks whether given point lies inside disk.*/ +SimpleDiskParticle.prototype.hitTest = function(hitX,hitY) { + var dx = this.x - hitX; + var dy = this.y - hitY; + return(dx*dx + dy*dy < this.radius*this.radius); +} + +/*Draws disk.*/ +function draw_disk(y, x, r, color, context) { + context.fillStyle = color; + context.beginPath(); + context.arc(x, y, r, 0, 2*Math.PI, false); + context.closePath(); + context.fill(); +} +/*Draws labeled concentric disks.*/ +SimpleDiskParticle.prototype.drawToContext = function(theContext) { + draw_disk(this.y, this.x, this.radius*1.0, this.bigcolor, theContext); + draw_disk(this.y, this.x, this.radius*0.5, this.smallcolor, theContext); + + theContext.textAlign='center'; + theContext.textBaseline='middle'; + theContext.font = '700 11px Georgia'; + theContext.fillStyle = this.textcolor; + theContext.fillText(this.text, this.x, this.y); +} diff --git a/demo/resources/javascript/DragDisk.js b/demo/resources/javascript/DragDisk.js new file mode 100644 index 0000000..46102ae --- /dev/null +++ b/demo/resources/javascript/DragDisk.js @@ -0,0 +1,38 @@ +function DragDisk(posX, posY, text, id) { + this.id = id + this.x = posX; + this.y = posY; + this.radius = 15; + this.text = text; + this.bigcolor = 'rgba(255,0,0,0.8)'; + this.smallcolor = 'rgba(255,255,255,0.5)'; + this.textcolor = 'rgba(0,0,0,1)'; +} + +/*Checks whether given point lies inside disk.*/ +DragDisk.prototype.hitTest = function(hitX,hitY) { + var dx = this.x - hitX; + var dy = this.y - hitY; + return(dx*dx + dy*dy < this.radius*this.radius); +} + +/*Draws disk.*/ +function draw_disk(y, x, r, color, context) { + context.fillStyle = color; + context.beginPath(); + context.arc(x, y, r, 0, 2*Math.PI, false); + context.closePath(); + context.fill(); +} +/*Draws labeled concentric disks.*/ +DragDisk.prototype.drawToContext = function(theContext) { + /*window.alert("!" + this.y + '!' + this.x);*/ + draw_disk(this.y, this.x, this.radius*1.0, this.bigcolor, theContext); + draw_disk(this.y, this.x, this.radius*0.5, this.smallcolor, theContext); + + theContext.textAlign='center'; + theContext.textBaseline='middle'; + theContext.font = '700 11px Georgia'; + theContext.fillStyle = this.textcolor; + theContext.fillText(this.text, this.x, this.y); +} diff --git a/demo/resources/javascript/DragDisk.js~ b/demo/resources/javascript/DragDisk.js~ new file mode 100644 index 0000000..0e52638 --- /dev/null +++ b/demo/resources/javascript/DragDisk.js~ @@ -0,0 +1,38 @@ +function DragDisk(posX, posY, text, id) { + this.id = id + this.x = posX; + this.y = posY; + this.radius = 15; + this.text = text; + this.bigcolor = 'rgba(255,0,0,0.8)'; + this.smallcolor = 'rgba(255,255,255,0.5)'; + this.textcolor = 'rgba(0,0,0,1)'; +} + +/*Checks whether given point lies inside disk.*/ +DragDisk.prototype.hitTest = function(hitX,hitY) { + var dx = this.x - hitX; + var dy = this.y - hitY; + return(dx*dx + dy*dy < this.radius*this.radius); +} + +/*Draws disk.*/ +function draw_disk(y, x, r, color, context) { + context.fillStyle = color; + context.beginPath(); + context.arc(x, y, r, 0, 2*Math.PI, false); + context.closePath(); + context.fill(); +} +/*Draws labeled concentric disks.*/ +DragDisk.prototype.drawToContext = function(theContext) { +window.alert("!" + this.y + '!' + this.x); + draw_disk(this.y, this.x, this.radius*1.0, this.bigcolor, theContext); + draw_disk(this.y, this.x, this.radius*0.5, this.smallcolor, theContext); + + theContext.textAlign='center'; + theContext.textBaseline='middle'; + theContext.font = '700 11px Georgia'; + theContext.fillStyle = this.textcolor; + theContext.fillText(this.text, this.x, this.y); +} diff --git a/demo/resources/javascript/dialog-polyfill.js b/demo/resources/javascript/dialog-polyfill.js new file mode 100644 index 0000000..e00130e --- /dev/null +++ b/demo/resources/javascript/dialog-polyfill.js @@ -0,0 +1,526 @@ +(function() { + + var supportCustomEvent = window.CustomEvent; + if (!supportCustomEvent || typeof supportCustomEvent == 'object') { + supportCustomEvent = function CustomEvent(event, x) { + x = x || {}; + var ev = document.createEvent('CustomEvent'); + ev.initCustomEvent(event, !!x.bubbles, !!x.cancelable, x.detail || null); + return ev; + }; + supportCustomEvent.prototype = window.Event.prototype; + } + + /** + * Finds the nearest from the passed element. + * + * @param {Element} el to search from + * @return {HTMLDialogElement} dialog found + */ + function findNearestDialog(el) { + while (el) { + if (el.nodeName.toUpperCase() == 'DIALOG') { + return /** @type {HTMLDialogElement} */ (el); + } + el = el.parentElement; + } + return null; + } + + /** + * Blur the specified element, as long as it's not the HTML body element. + * This works around an IE9/10 bug - blurring the body causes Windows to + * blur the whole application. + * + * @param {Element} el to blur + */ + function safeBlur(el) { + if (el && el.blur && el != document.body) { + el.blur(); + } + } + + /** + * @param {!NodeList} nodeList to search + * @param {Node} node to find + * @return {boolean} whether node is inside nodeList + */ + function inNodeList(nodeList, node) { + for (var i = 0; i < nodeList.length; ++i) { + if (nodeList[i] == node) { + return true; + } + } + return false; + } + + /** + * @param {!HTMLDialogElement} dialog to upgrade + * @constructor + */ + function dialogPolyfillInfo(dialog) { + this.dialog_ = dialog; + this.replacedStyleTop_ = false; + this.openAsModal_ = false; + + // Set a11y role. Browsers that support dialog implicitly know this already. + if (!dialog.hasAttribute('role')) { + dialog.setAttribute('role', 'dialog'); + } + + dialog.show = this.show.bind(this); + dialog.showModal = this.showModal.bind(this); + dialog.close = this.close.bind(this); + + if (!('returnValue' in dialog)) { + dialog.returnValue = ''; + } + + this.maybeHideModal = this.maybeHideModal.bind(this); + if ('MutationObserver' in window) { + // IE11+, most other browsers. + var mo = new MutationObserver(this.maybeHideModal); + mo.observe(dialog, { attributes: true, attributeFilter: ['open'] }); + } else { + dialog.addEventListener('DOMAttrModified', this.maybeHideModal); + } + // Note that the DOM is observed inside DialogManager while any dialog + // is being displayed as a modal, to catch modal removal from the DOM. + + Object.defineProperty(dialog, 'open', { + set: this.setOpen.bind(this), + get: dialog.hasAttribute.bind(dialog, 'open') + }); + + this.backdrop_ = document.createElement('div'); + this.backdrop_.className = 'backdrop'; + this.backdropClick_ = this.backdropClick_.bind(this); + } + + dialogPolyfillInfo.prototype = { + + get dialog() { + return this.dialog_; + }, + + /** + * Maybe remove this dialog from the modal top layer. This is called when + * a modal dialog may no longer be tenable, e.g., when the dialog is no + * longer open or is no longer part of the DOM. + */ + maybeHideModal: function() { + if (!this.openAsModal_) { return; } + if (this.dialog_.hasAttribute('open') && + document.body.contains(this.dialog_)) { return; } + + this.openAsModal_ = false; + this.dialog_.style.zIndex = ''; + + // This won't match the native exactly because if the user set + // top on a centered polyfill dialog, that top gets thrown away when the + // dialog is closed. Not sure it's possible to polyfill this perfectly. + if (this.replacedStyleTop_) { + this.dialog_.style.top = ''; + this.replacedStyleTop_ = false; + } + + // Optimistically clear the modal part of this . + this.backdrop_.removeEventListener('click', this.backdropClick_); + if (this.backdrop_.parentElement) { + this.backdrop_.parentElement.removeChild(this.backdrop_); + } + dialogPolyfill.dm.removeDialog(this); + }, + + /** + * @param {boolean} value whether to open or close this dialog + */ + setOpen: function(value) { + if (value) { + this.dialog_.hasAttribute('open') || this.dialog_.setAttribute('open', ''); + } else { + this.dialog_.removeAttribute('open'); + this.maybeHideModal(); // nb. redundant with MutationObserver + } + }, + + /** + * Handles clicks on the fake .backdrop element, redirecting them as if + * they were on the dialog itself. + * + * @param {!Event} e to redirect + */ + backdropClick_: function(e) { + var redirectedEvent = document.createEvent('MouseEvents'); + redirectedEvent.initMouseEvent(e.type, e.bubbles, e.cancelable, window, + e.detail, e.screenX, e.screenY, e.clientX, e.clientY, e.ctrlKey, + e.altKey, e.shiftKey, e.metaKey, e.button, e.relatedTarget); + this.dialog_.dispatchEvent(redirectedEvent); + e.stopPropagation(); + }, + + /** + * Focuses on the first focusable element within the dialog. This will always blur the current + * focus, even if nothing within the dialog is found. + */ + focus_: function() { + // Find element with `autofocus` attribute, or fall back to the first form/tabindex control. + var target = this.dialog_.querySelector('[autofocus]:not([disabled])'); + if (!target) { + // Note that this is 'any focusable area'. This list is probably not exhaustive, but the + // alternative involves stepping through and trying to focus everything. + var opts = ['button', 'input', 'keygen', 'select', 'textarea']; + var query = opts.map(function(el) { + return el + ':not([disabled])'; + }); + // TODO(samthor): tabindex values that are not numeric are not focusable. + query.push('[tabindex]:not([disabled]):not([tabindex=""])'); // tabindex != "", not disabled + target = this.dialog_.querySelector(query.join(', ')); + } + safeBlur(document.activeElement); + target && target.focus(); + }, + + /** + * Sets the zIndex for the backdrop and dialog. + * + * @param {number} backdropZ + * @param {number} dialogZ + */ + updateZIndex: function(backdropZ, dialogZ) { + this.backdrop_.style.zIndex = backdropZ; + this.dialog_.style.zIndex = dialogZ; + }, + + /** + * Shows the dialog. If the dialog is already open, this does nothing. + */ + show: function() { + if (!this.dialog_.open) { + this.setOpen(true); + this.focus_(); + } + }, + + /** + * Show this dialog modally. + */ + showModal: function() { + if (this.dialog_.hasAttribute('open')) { + throw new Error('Failed to execute \'showModal\' on dialog: The element is already open, and therefore cannot be opened modally.'); + } + if (!document.body.contains(this.dialog_)) { + throw new Error('Failed to execute \'showModal\' on dialog: The element is not in a Document.'); + } + if (!dialogPolyfill.dm.pushDialog(this)) { + throw new Error('Failed to execute \'showModal\' on dialog: There are too many open modal dialogs.'); + } + this.show(); + this.openAsModal_ = true; + + // Optionally center vertically, relative to the current viewport. + if (dialogPolyfill.needsCentering(this.dialog_)) { + dialogPolyfill.reposition(this.dialog_); + this.replacedStyleTop_ = true; + } else { + this.replacedStyleTop_ = false; + } + + // Insert backdrop. + this.backdrop_.addEventListener('click', this.backdropClick_); + this.dialog_.parentNode.insertBefore(this.backdrop_, + this.dialog_.nextSibling); + }, + + /** + * Closes this HTMLDialogElement. This is optional vs clearing the open + * attribute, however this fires a 'close' event. + * + * @param {string=} opt_returnValue to use as the returnValue + */ + close: function(opt_returnValue) { + if (!this.dialog_.hasAttribute('open')) { + throw new Error('Failed to execute \'close\' on dialog: The element does not have an \'open\' attribute, and therefore cannot be closed.'); + } + this.setOpen(false); + + // Leave returnValue untouched in case it was set directly on the element + if (opt_returnValue !== undefined) { + this.dialog_.returnValue = opt_returnValue; + } + + // Triggering "close" event for any attached listeners on the . + var closeEvent = new supportCustomEvent('close', { + bubbles: false, + cancelable: false + }); + this.dialog_.dispatchEvent(closeEvent); + } + + }; + + var dialogPolyfill = {}; + + dialogPolyfill.reposition = function(element) { + var scrollTop = document.body.scrollTop || document.documentElement.scrollTop; + var topValue = scrollTop + (window.innerHeight - element.offsetHeight) / 2; + element.style.top = Math.max(scrollTop, topValue) + 'px'; + }; + + dialogPolyfill.isInlinePositionSetByStylesheet = function(element) { + for (var i = 0; i < document.styleSheets.length; ++i) { + var styleSheet = document.styleSheets[i]; + var cssRules = null; + // Some browsers throw on cssRules. + try { + cssRules = styleSheet.cssRules; + } catch (e) {} + if (!cssRules) + continue; + for (var j = 0; j < cssRules.length; ++j) { + var rule = cssRules[j]; + var selectedNodes = null; + // Ignore errors on invalid selector texts. + try { + selectedNodes = document.querySelectorAll(rule.selectorText); + } catch(e) {} + if (!selectedNodes || !inNodeList(selectedNodes, element)) + continue; + var cssTop = rule.style.getPropertyValue('top'); + var cssBottom = rule.style.getPropertyValue('bottom'); + if ((cssTop && cssTop != 'auto') || (cssBottom && cssBottom != 'auto')) + return true; + } + } + return false; + }; + + dialogPolyfill.needsCentering = function(dialog) { + var computedStyle = window.getComputedStyle(dialog); + if (computedStyle.position != 'absolute') { + return false; + } + + // We must determine whether the top/bottom specified value is non-auto. In + // WebKit/Blink, checking computedStyle.top == 'auto' is sufficient, but + // Firefox returns the used value. So we do this crazy thing instead: check + // the inline style and then go through CSS rules. + if ((dialog.style.top != 'auto' && dialog.style.top != '') || + (dialog.style.bottom != 'auto' && dialog.style.bottom != '')) + return false; + return !dialogPolyfill.isInlinePositionSetByStylesheet(dialog); + }; + + /** + * @param {!Element} element to force upgrade + */ + dialogPolyfill.forceRegisterDialog = function(element) { + if (element.showModal) { + console.warn('This browser already supports , the polyfill ' + + 'may not work correctly', element); + } + if (element.nodeName.toUpperCase() != 'DIALOG') { + throw new Error('Failed to register dialog: The element is not a dialog.'); + } + new dialogPolyfillInfo(/** @type {!HTMLDialogElement} */ (element)); + }; + + /** + * @param {!Element} element to upgrade + */ + dialogPolyfill.registerDialog = function(element) { + if (element.showModal) { + console.warn('Can\'t upgrade : already supported', element); + } else { + dialogPolyfill.forceRegisterDialog(element); + } + }; + + /** + * @constructor + */ + dialogPolyfill.DialogManager = function() { + /** @type {!Array} */ + this.pendingDialogStack = []; + + // The overlay is used to simulate how a modal dialog blocks the document. + // The blocking dialog is positioned on top of the overlay, and the rest of + // the dialogs on the pending dialog stack are positioned below it. In the + // actual implementation, the modal dialog stacking is controlled by the + // top layer, where z-index has no effect. + this.overlay = document.createElement('div'); + this.overlay.className = '_dialog_overlay'; + this.overlay.addEventListener('click', function(e) { + e.stopPropagation(); + }); + + this.handleKey_ = this.handleKey_.bind(this); + this.handleFocus_ = this.handleFocus_.bind(this); + this.handleRemove_ = this.handleRemove_.bind(this); + + this.zIndexLow_ = 100000; + this.zIndexHigh_ = 100000 + 150; + }; + + /** + * @return {Element} the top HTML dialog element, if any + */ + dialogPolyfill.DialogManager.prototype.topDialogElement = function() { + if (this.pendingDialogStack.length) { + var t = this.pendingDialogStack[this.pendingDialogStack.length - 1]; + return t.dialog; + } + return null; + }; + + /** + * Called on the first modal dialog being shown. Adds the overlay and related + * handlers. + */ + dialogPolyfill.DialogManager.prototype.blockDocument = function() { + document.body.appendChild(this.overlay); + document.body.addEventListener('focus', this.handleFocus_, true); + document.addEventListener('keydown', this.handleKey_); + document.addEventListener('DOMNodeRemoved', this.handleRemove_); + }; + + /** + * Called on the first modal dialog being removed, i.e., when no more modal + * dialogs are visible. + */ + dialogPolyfill.DialogManager.prototype.unblockDocument = function() { + document.body.removeChild(this.overlay); + document.body.removeEventListener('focus', this.handleFocus_, true); + document.removeEventListener('keydown', this.handleKey_); + document.removeEventListener('DOMNodeRemoved', this.handleRemove_); + }; + + dialogPolyfill.DialogManager.prototype.updateStacking = function() { + var zIndex = this.zIndexLow_; + + for (var i = 0; i < this.pendingDialogStack.length; i++) { + if (i == this.pendingDialogStack.length - 1) { + this.overlay.style.zIndex = zIndex++; + } + this.pendingDialogStack[i].updateZIndex(zIndex++, zIndex++); + } + }; + + dialogPolyfill.DialogManager.prototype.handleFocus_ = function(event) { + var candidate = findNearestDialog(/** @type {Element} */ (event.target)); + if (candidate != this.topDialogElement()) { + event.preventDefault(); + event.stopPropagation(); + safeBlur(/** @type {Element} */ (event.target)); + // TODO: Focus on the browser chrome (aka document) or the dialog itself + // depending on the tab direction. + return false; + } + }; + + dialogPolyfill.DialogManager.prototype.handleKey_ = function(event) { + if (event.keyCode == 27) { + event.preventDefault(); + event.stopPropagation(); + var cancelEvent = new supportCustomEvent('cancel', { + bubbles: false, + cancelable: true + }); + var dialog = this.topDialogElement(); + if (dialog.dispatchEvent(cancelEvent)) { + dialog.close(); + } + } + }; + + dialogPolyfill.DialogManager.prototype.handleRemove_ = function(event) { + if (event.target.nodeName.toUpperCase() != 'DIALOG') { return; } + + var dialog = /** @type {HTMLDialogElement} */ (event.target); + if (!dialog.open) { return; } + + // Find a dialogPolyfillInfo which matches the removed . + this.pendingDialogStack.some(function(dpi) { + if (dpi.dialog == dialog) { + // This call will clear the dialogPolyfillInfo on this DialogManager + // as a side effect. + dpi.maybeHideModal(); + return true; + } + }); + }; + + /** + * @param {!dialogPolyfillInfo} dpi + * @return {boolean} whether the dialog was allowed + */ + dialogPolyfill.DialogManager.prototype.pushDialog = function(dpi) { + var allowed = (this.zIndexHigh_ - this.zIndexLow_) / 2 - 1; + if (this.pendingDialogStack.length >= allowed) { + return false; + } + this.pendingDialogStack.push(dpi); + if (this.pendingDialogStack.length == 1) { + this.blockDocument(); + } + this.updateStacking(); + return true; + }; + + /** + * @param {dialogPolyfillInfo} dpi + */ + dialogPolyfill.DialogManager.prototype.removeDialog = function(dpi) { + var index = this.pendingDialogStack.indexOf(dpi); + if (index == -1) { return; } + + this.pendingDialogStack.splice(index, 1); + this.updateStacking(); + if (this.pendingDialogStack.length == 0) { + this.unblockDocument(); + } + }; + + dialogPolyfill.dm = new dialogPolyfill.DialogManager(); + + /** + * Global form 'dialog' method handler. Closes a dialog correctly on submit + * and possibly sets its return value. + */ + document.addEventListener('submit', function(ev) { + var target = ev.target; + if (!target || !target.hasAttribute('method')) { return; } + if (target.getAttribute('method').toLowerCase() != 'dialog') { return; } + ev.preventDefault(); + + var dialog = findNearestDialog(/** @type {Element} */ (ev.target)); + if (!dialog) { return; } + + // FIXME: The original event doesn't contain the element used to submit the + // form (if any). Look in some possible places. + var returnValue; + var cands = [document.activeElement, ev.explicitOriginalTarget]; + var els = ['BUTTON', 'INPUT']; + cands.some(function(cand) { + if (cand && cand.form == ev.target && els.indexOf(cand.nodeName.toUpperCase()) != -1) { + returnValue = cand.value; + return true; + } + }); + dialog.close(returnValue); + }, true); + + dialogPolyfill['forceRegisterDialog'] = dialogPolyfill.forceRegisterDialog; + dialogPolyfill['registerDialog'] = dialogPolyfill.registerDialog; + + if (typeof define === 'function' && 'amd' in define) { + // AMD support + define(function() { return dialogPolyfill; }); + } else if (typeof module === 'object' && typeof module['exports'] === 'object') { + // CommonJS support + module['exports'] = dialogPolyfill; + } else { + // all others + window['dialogPolyfill'] = dialogPolyfill; + } +})(); \ No newline at end of file diff --git a/demo/resources/javascript/generate.js b/demo/resources/javascript/generate.js new file mode 100644 index 0000000..dc81070 --- /dev/null +++ b/demo/resources/javascript/generate.js @@ -0,0 +1,128 @@ +$(document).ready(function() { + + var canvas, context, startX, endX, startY, endY; + var mouseIsDown = 0; + + function init() { + canvas = document.getElementById("draw_box_canvas"); + context = canvas.getContext("2d"); + + canvas.addEventListener("mousedown", mouseDown, false); + canvas.addEventListener("mousemove", mouseXY, false); + canvas.addEventListener("mouseup", mouseUp, false); + } + + function mouseUp(eve) { + if (mouseIsDown !== 0) { + mouseIsDown = 0; + + // keep it on canvas + context.beginPath(); + context.fillStyle = "rgb(255, 255, 255, 0.5)"; + context.fillRect(startX, startY, Math.abs(startX - endX), Math.abs(startY - endY)); + + // create an object out of init + var elt = document.createElement('div'); + elt.style.top = startY + 'px'; + elt.style.left = startX + 'px'; + elt.style.width = Math.abs(startX - endX) + 'px'; + elt.style.height = Math.abs(startY - endY) + 'px'; + canvas.removeChild(canvas.childNodes[0]); // remove if we want more than one bounding Box + + canvas.appendChild(elt); // put bounding box into DOM + + canvas.style.cursor = "default"; // reset cursor + + var pos = getMousePos(canvas, eve); + endX = pos.x; + endY = pos.y; + drawSquare(); //update on mouse-up + + } + } + + function mouseDown(eve) { + mouseIsDown = 1; + canvas.style.cursor = "crosshair"; + var pos = getMousePos(canvas, eve); + startX = endX = pos.x; + startY = endY = pos.y; + drawSquare(); //update + } + + function mouseXY(eve) { + + if (mouseIsDown !== 0) { + var pos = getMousePos(canvas, eve); + endX = pos.x; + endY = pos.y; + + drawSquare(); + } + } + + function drawSquare() { + // creating a square + var w = endX - startX; + var h = endY - startY; + var offsetX = (w < 0) ? w : 0; + var offsetY = (h < 0) ? h : 0; + var width = Math.abs(w); + var height = Math.abs(h); + + context.clearRect(0, 0, canvas.width, canvas.height); + + context.beginPath(); + context.fillRect(startX + offsetX, startY + offsetY, width, height); + context.fillStyle = 'rgba(255, 0, 0, 0.5)'; + context.fill(); + context.lineWidth = 5; + context.strokeStyle = 'black'; + context.stroke(); + + } + + function getMousePos(canvas, evt) { + var rect = canvas.getBoundingClientRect(); + return { + x: evt.clientX - rect.left, + y: evt.clientY - rect.top + }; + } + init(); + + // document.getElementById("generate_btn").addEventListener("click", function() { + // document.getElementById('obj_img').innerHTML = ""; + // }); + + $('#generate_btn').click(function () { + + var description = $('#description').val(); + + var obj = { + x: startX, + y: startY, + width: Math.abs(endX - startX), + height: Math.abs(endY - startY), + description: description + } + $.ajax({ + data: obj, + url: 'request', + type: "GET", + success: function (msg) { + console.log(msg) + //img = new Image() + //img.src = msg + //context.drawImage(img, 0, 0, 500, 500) + context.clearRect(0, 0, canvas.width, canvas.height); + $('#placeholder').attr('src', msg) + //$('#placeholder2').attr('src', msg) + }, + error: function (msg) { ret = 'Epic fail!'; }, + async: false, + timeout: 10000, + }); + + }); +}); diff --git a/demo/resources/javascript/generate_kp.js b/demo/resources/javascript/generate_kp.js new file mode 100644 index 0000000..145c4ec --- /dev/null +++ b/demo/resources/javascript/generate_kp.js @@ -0,0 +1,388 @@ +function initArray(length, value) { + var arr = []; + for (var i = 0; i < length; i++) { + arr.push(value); + } + return arr; +} + +function get_part_name(part_id) { + switch (parseInt(part_id) - 1) { + case 0: + return "Back"; + break; + case 1: + return "Beak"; + break; + case 2: + return "Belly"; + break; + case 3: + return "Breast"; + break; + case 4: + return "Crown"; + break; + case 5: + return "Forehead"; + break; + case 6: + return "Left Eye"; + break; + case 7: + return "Left Leg"; + break; + case 8: + return "Left Wing"; + break; + case 9: + return "Nape"; + break; + case 10: + return "Right Eye"; + break; + case 11: + return "Right Leg"; + break; + case 12: + return "Right Wing"; + break; + case 13: + return "Tail"; + break; + case 14: + return "Throat"; + break; + } +} + +$(document).ready(function() { + + var mode = 'pp'; // default to bounding box + var canvas, context, startX, endX, startY, endY; + var mouseIsDown = 0; + var option_selected = null; + + var checklist = initArray(15, false); + + canvas = document.getElementById("pp_canvas"); + context = canvas.getContext("2d"); + var cw = canvas.width; + var ch = canvas.height; + + canvas.addEventListener("mousedown", mouseDown_pp, false); + canvas.addEventListener("mousemove", mouseXY_pp, false); + canvas.addEventListener("mouseup", mouseUp_pp, false); + + function findSelection(field) { + var test = document.getElementsByName(field); + var sizes = test.length; + console.log(sizes); + for (var i=0; i < sizes; i++) { + if (test[i].checked==true) { + // alert(test[i].value + ' you got a value'); + return test[i].value; + } + } + } + + function submitForm(field_name) { + + var opt_select = findSelection(field_name); + return opt_select; + } + + + // Ajax requests + function get_bb_prediction() { + + var description = $('#description').val(); + + var obj = { + x: startX, + y: startY, + width: Math.abs(endX - startX), + height: Math.abs(endY - startY), + description: description + }; + + $.ajax({ + data: obj, + url: 'request', + type: "GET", + success: function (msg) { + console.log(msg) + //img = new Image() + //img.src = msg + //context.drawImage(img, 0, 0, 500, 500) + context.clearRect(0, 0, canvas.width, canvas.height); + $('.placeholder').attr('src', msg) + //$('#placeholder2').attr('src', msg) + }, + error: function (msg) { ret = 'Epic fail!'; }, + async: false, + timeout: 10000, + }); + } + + function get_pp_prediction() { + + var description = $('#pp_description').val(); + var keypoints = []; + var canvas_obj = $("#pp_canvas"); + var num_canvas_objs = canvas_obj.children.length; + for (var i = 0; i < num_canvas_objs; i++) { + + var current_child = canvas_obj.children()[i]; + + if (current_child == null) { + continue; + } + + var x = current_child.x; + var y = current_child.y; + var part_id = current_child.part; + var keypoint_obj = { + x: x, + y: y, + part_id: part_id, + }; + + keypoints.push(keypoint_obj); + console.log(keypoints); + } + + var obj = { + description: description, + keypoints: keypoints + }; + + $.ajax({ + data: { "data" : JSON.stringify(obj) }, + url: 'request', + type: "POST", + success: function (msg) { + console.log(msg) + //img = new Image() + //img.src = msg + //context.drawImage(img, 0, 0, canvas.width, canvas.height); + // context.clearRect(0, 0, canvas.width, canvas.height); + $('.placeholder').attr('src', msg) + //$('#placeholder2').attr('src', msg) + }, + error: function (msg) { ret = 'Epic fail!'; }, + async: true, + contentType: "application/json", + timeout: 10000, + }); + + // document.getElementById('pp_description').value=''; + //checklist = initArray(15, false); + } + + // canvas functions + + function mouseUp(eve) { + if (mouseIsDown !== 0) { + mouseIsDown = 0; + + // keep it on canvas + context.beginPath(); + context.fillStyle = "rgb(255, 255, 255, 0.5)"; + context.fillRect(startX, startY, Math.abs(startX - endX), Math.abs(startY - endY)); + + // create an object out of init + var elt = document.createElement('div'); + elt.style.top = startY + 'px'; + elt.style.left = startX + 'px'; + elt.style.width = Math.abs(startX - endX) + 'px'; + elt.style.height = Math.abs(startY - endY) + 'px'; + canvas.removeChild(canvas.childNodes[0]); // remove if we want more than one bounding Box + + canvas.appendChild(elt); // put bounding box into DOM + + canvas.style.cursor = "default"; // reset cursor + + var pos = getMousePos(canvas, eve); + endX = pos.x; + endY = pos.y; + drawSquare(); //update on mouse-up + + } + } + + function mouseDown(eve) { + mouseIsDown = 1; + canvas.style.cursor = "crosshair"; + var pos = getMousePos(canvas, eve); + startX = endX = pos.x; + startY = endY = pos.y; + drawSquare(); //update + } + + function mouseXY(eve) { + + if (mouseIsDown !== 0) { + var pos = getMousePos(canvas, eve); + endX = pos.x; + endY = pos.y; + + drawSquare(); + } + } + + function drawSquare() { + // creating a square + var w = endX - startX; + var h = endY - startY; + var offsetX = (w < 0) ? w : 0; + var offsetY = (h < 0) ? h : 0; + var width = Math.abs(w); + var height = Math.abs(h); + + context.clearRect(0, 0, canvas.width, canvas.height); + + context.beginPath(); + context.fillRect(startX + offsetX, startY + offsetY, width, height); + context.fillStyle = 'rgba(255, 0, 0, 0.5)'; + context.fill(); + context.lineWidth = 5; + context.strokeStyle = 'black'; + context.stroke(); + } + + function drawKeyPoint() { + + var dialog = document.querySelector('dialog'); + dialogPolyfill.registerDialog(dialog); + // Now dialog acts like a native . + dialog.showModal(); + + // assumes a default value is chosen + $(".agree").click(function () { + + var part_selected = submitForm("part_select"); + + // verify part has not been selected before + if (checklist[parseInt(part_selected) - 1] == true) { + return; + } + else { + checklist[parseInt(part_selected) - 1] = true; + } + + // draw keypoint + context.beginPath(); + context.fillRect(startX, startY, 10, 10); + context.fillStyle = 'rgba(0, 0, 0, 1)'; + context.font = '15px Georgia'; + context.fillText(get_part_name(part_selected), startX, startY); + context.fill(); + context.lineWidth = 5; + context.strokeStyle = 'red'; + context.stroke(); + + // create an object out of init + var elt = document.createElement('div'); + elt.style.top = startY + 'px'; + elt.style.left = startX + 'px'; + + elt.x = startX; + elt.y = startY; + elt.part = part_selected; + console.log("element part: " + elt.part); + canvas.appendChild(elt); // put bounding box into DOM + dialog.close(); + + return; + }); + + $(".close").click(function () { + dialog.close(); + return null; + }); + } + + + function handle_keypoints() { + var keypoint_args = drawKeyPoint(); + canvas.style.cursor = "default"; // reset cursor + } + + function getMousePos(canvas, evt) { + var rect = canvas.getBoundingClientRect(); + return { + x: evt.clientX - rect.left, + y: evt.clientY - rect.top + }; + } + + // Pick part helpers + function mouseDown_pp(eve) { + mouseIsDown = 1; + canvas.style.cursor = "crosshair"; + var pos = getMousePos(canvas, eve); + startX = endX = pos.x; + startY = endY = pos.y; + context.beginPath(); + context.fillRect(startX, startY, 1, 1); + context.fillStyle = 'rgba(255, 0, 0, 0.5)'; + context.fill(); + context.lineWidth = 5; + context.strokeStyle = 'red'; + context.stroke(); + + // handle_keypoints(); + } + + + function mouseUp_pp(eve) { + if (mouseIsDown !== 0) { + mouseIsDown = 0; + handle_keypoints(); + } + } + + function mouseXY_pp(eve) { + + if (mouseIsDown !== 0) { + var pos = getMousePos(canvas, eve); + endX = pos.x; + endY = pos.y; + // handle_keypoints(); + // var keyPoint_args = drawKeyPoint(); + } + } + + + // Event listeners + + $('#generate_btn').click(function () { + get_bb_prediction(); + }); + + $('#pp_generate_btn').click(function () { + get_pp_prediction(); + }); + + // When enter is pressed, execute prediction + document.getElementById("pp_description").addEventListener("keydown", function(e) { + if (!e) { var e = window.event; } + + // Enter is pressed + if (e.keyCode == 13) { + e.preventDefault(); // sometimes useful + get_pp_prediction(); + } + }, false); + + $("#pp_clear_btn").click(function () { + var canvas = document.getElementById("pp_canvas"); + var context = canvas.getContext("2d"); + context.clearRect(0, 0, canvas.width, canvas.height); + checklist = initArray(15, false); + var canvas = $("#pp_canvas"); + canvas.empty(); + document.getElementById('pp_description').value=''; + }); +}); diff --git a/demo/resources/javascript/generate_kp.js~ b/demo/resources/javascript/generate_kp.js~ new file mode 100644 index 0000000..145c4ec --- /dev/null +++ b/demo/resources/javascript/generate_kp.js~ @@ -0,0 +1,388 @@ +function initArray(length, value) { + var arr = []; + for (var i = 0; i < length; i++) { + arr.push(value); + } + return arr; +} + +function get_part_name(part_id) { + switch (parseInt(part_id) - 1) { + case 0: + return "Back"; + break; + case 1: + return "Beak"; + break; + case 2: + return "Belly"; + break; + case 3: + return "Breast"; + break; + case 4: + return "Crown"; + break; + case 5: + return "Forehead"; + break; + case 6: + return "Left Eye"; + break; + case 7: + return "Left Leg"; + break; + case 8: + return "Left Wing"; + break; + case 9: + return "Nape"; + break; + case 10: + return "Right Eye"; + break; + case 11: + return "Right Leg"; + break; + case 12: + return "Right Wing"; + break; + case 13: + return "Tail"; + break; + case 14: + return "Throat"; + break; + } +} + +$(document).ready(function() { + + var mode = 'pp'; // default to bounding box + var canvas, context, startX, endX, startY, endY; + var mouseIsDown = 0; + var option_selected = null; + + var checklist = initArray(15, false); + + canvas = document.getElementById("pp_canvas"); + context = canvas.getContext("2d"); + var cw = canvas.width; + var ch = canvas.height; + + canvas.addEventListener("mousedown", mouseDown_pp, false); + canvas.addEventListener("mousemove", mouseXY_pp, false); + canvas.addEventListener("mouseup", mouseUp_pp, false); + + function findSelection(field) { + var test = document.getElementsByName(field); + var sizes = test.length; + console.log(sizes); + for (var i=0; i < sizes; i++) { + if (test[i].checked==true) { + // alert(test[i].value + ' you got a value'); + return test[i].value; + } + } + } + + function submitForm(field_name) { + + var opt_select = findSelection(field_name); + return opt_select; + } + + + // Ajax requests + function get_bb_prediction() { + + var description = $('#description').val(); + + var obj = { + x: startX, + y: startY, + width: Math.abs(endX - startX), + height: Math.abs(endY - startY), + description: description + }; + + $.ajax({ + data: obj, + url: 'request', + type: "GET", + success: function (msg) { + console.log(msg) + //img = new Image() + //img.src = msg + //context.drawImage(img, 0, 0, 500, 500) + context.clearRect(0, 0, canvas.width, canvas.height); + $('.placeholder').attr('src', msg) + //$('#placeholder2').attr('src', msg) + }, + error: function (msg) { ret = 'Epic fail!'; }, + async: false, + timeout: 10000, + }); + } + + function get_pp_prediction() { + + var description = $('#pp_description').val(); + var keypoints = []; + var canvas_obj = $("#pp_canvas"); + var num_canvas_objs = canvas_obj.children.length; + for (var i = 0; i < num_canvas_objs; i++) { + + var current_child = canvas_obj.children()[i]; + + if (current_child == null) { + continue; + } + + var x = current_child.x; + var y = current_child.y; + var part_id = current_child.part; + var keypoint_obj = { + x: x, + y: y, + part_id: part_id, + }; + + keypoints.push(keypoint_obj); + console.log(keypoints); + } + + var obj = { + description: description, + keypoints: keypoints + }; + + $.ajax({ + data: { "data" : JSON.stringify(obj) }, + url: 'request', + type: "POST", + success: function (msg) { + console.log(msg) + //img = new Image() + //img.src = msg + //context.drawImage(img, 0, 0, canvas.width, canvas.height); + // context.clearRect(0, 0, canvas.width, canvas.height); + $('.placeholder').attr('src', msg) + //$('#placeholder2').attr('src', msg) + }, + error: function (msg) { ret = 'Epic fail!'; }, + async: true, + contentType: "application/json", + timeout: 10000, + }); + + // document.getElementById('pp_description').value=''; + //checklist = initArray(15, false); + } + + // canvas functions + + function mouseUp(eve) { + if (mouseIsDown !== 0) { + mouseIsDown = 0; + + // keep it on canvas + context.beginPath(); + context.fillStyle = "rgb(255, 255, 255, 0.5)"; + context.fillRect(startX, startY, Math.abs(startX - endX), Math.abs(startY - endY)); + + // create an object out of init + var elt = document.createElement('div'); + elt.style.top = startY + 'px'; + elt.style.left = startX + 'px'; + elt.style.width = Math.abs(startX - endX) + 'px'; + elt.style.height = Math.abs(startY - endY) + 'px'; + canvas.removeChild(canvas.childNodes[0]); // remove if we want more than one bounding Box + + canvas.appendChild(elt); // put bounding box into DOM + + canvas.style.cursor = "default"; // reset cursor + + var pos = getMousePos(canvas, eve); + endX = pos.x; + endY = pos.y; + drawSquare(); //update on mouse-up + + } + } + + function mouseDown(eve) { + mouseIsDown = 1; + canvas.style.cursor = "crosshair"; + var pos = getMousePos(canvas, eve); + startX = endX = pos.x; + startY = endY = pos.y; + drawSquare(); //update + } + + function mouseXY(eve) { + + if (mouseIsDown !== 0) { + var pos = getMousePos(canvas, eve); + endX = pos.x; + endY = pos.y; + + drawSquare(); + } + } + + function drawSquare() { + // creating a square + var w = endX - startX; + var h = endY - startY; + var offsetX = (w < 0) ? w : 0; + var offsetY = (h < 0) ? h : 0; + var width = Math.abs(w); + var height = Math.abs(h); + + context.clearRect(0, 0, canvas.width, canvas.height); + + context.beginPath(); + context.fillRect(startX + offsetX, startY + offsetY, width, height); + context.fillStyle = 'rgba(255, 0, 0, 0.5)'; + context.fill(); + context.lineWidth = 5; + context.strokeStyle = 'black'; + context.stroke(); + } + + function drawKeyPoint() { + + var dialog = document.querySelector('dialog'); + dialogPolyfill.registerDialog(dialog); + // Now dialog acts like a native . + dialog.showModal(); + + // assumes a default value is chosen + $(".agree").click(function () { + + var part_selected = submitForm("part_select"); + + // verify part has not been selected before + if (checklist[parseInt(part_selected) - 1] == true) { + return; + } + else { + checklist[parseInt(part_selected) - 1] = true; + } + + // draw keypoint + context.beginPath(); + context.fillRect(startX, startY, 10, 10); + context.fillStyle = 'rgba(0, 0, 0, 1)'; + context.font = '15px Georgia'; + context.fillText(get_part_name(part_selected), startX, startY); + context.fill(); + context.lineWidth = 5; + context.strokeStyle = 'red'; + context.stroke(); + + // create an object out of init + var elt = document.createElement('div'); + elt.style.top = startY + 'px'; + elt.style.left = startX + 'px'; + + elt.x = startX; + elt.y = startY; + elt.part = part_selected; + console.log("element part: " + elt.part); + canvas.appendChild(elt); // put bounding box into DOM + dialog.close(); + + return; + }); + + $(".close").click(function () { + dialog.close(); + return null; + }); + } + + + function handle_keypoints() { + var keypoint_args = drawKeyPoint(); + canvas.style.cursor = "default"; // reset cursor + } + + function getMousePos(canvas, evt) { + var rect = canvas.getBoundingClientRect(); + return { + x: evt.clientX - rect.left, + y: evt.clientY - rect.top + }; + } + + // Pick part helpers + function mouseDown_pp(eve) { + mouseIsDown = 1; + canvas.style.cursor = "crosshair"; + var pos = getMousePos(canvas, eve); + startX = endX = pos.x; + startY = endY = pos.y; + context.beginPath(); + context.fillRect(startX, startY, 1, 1); + context.fillStyle = 'rgba(255, 0, 0, 0.5)'; + context.fill(); + context.lineWidth = 5; + context.strokeStyle = 'red'; + context.stroke(); + + // handle_keypoints(); + } + + + function mouseUp_pp(eve) { + if (mouseIsDown !== 0) { + mouseIsDown = 0; + handle_keypoints(); + } + } + + function mouseXY_pp(eve) { + + if (mouseIsDown !== 0) { + var pos = getMousePos(canvas, eve); + endX = pos.x; + endY = pos.y; + // handle_keypoints(); + // var keyPoint_args = drawKeyPoint(); + } + } + + + // Event listeners + + $('#generate_btn').click(function () { + get_bb_prediction(); + }); + + $('#pp_generate_btn').click(function () { + get_pp_prediction(); + }); + + // When enter is pressed, execute prediction + document.getElementById("pp_description").addEventListener("keydown", function(e) { + if (!e) { var e = window.event; } + + // Enter is pressed + if (e.keyCode == 13) { + e.preventDefault(); // sometimes useful + get_pp_prediction(); + } + }, false); + + $("#pp_clear_btn").click(function () { + var canvas = document.getElementById("pp_canvas"); + var context = canvas.getContext("2d"); + context.clearRect(0, 0, canvas.width, canvas.height); + checklist = initArray(15, false); + var canvas = $("#pp_canvas"); + canvas.empty(); + document.getElementById('pp_description').value=''; + }); +}); diff --git a/demo/resources/javascript/generate_kp_sam.js b/demo/resources/javascript/generate_kp_sam.js new file mode 100644 index 0000000..6d7e1e0 --- /dev/null +++ b/demo/resources/javascript/generate_kp_sam.js @@ -0,0 +1,248 @@ +$(document).ready(function() { + var mode = 'pp'; // default to bounding box + var canvas, context, startX, endX, startY, endY; + var mouseIsDown = 0; + var option_selected = null; + + canvas = document.getElementById("pp_canvas"); + context = canvas.getContext("2d"); + + /*Canvas variables:*/ + var num_kps = 15; + var pointnames = 'BACK,BEAK,BELY,BRST,CRWN,FRHD,LEYE,LLEG,LWNG,NAPE,REYE,RLEG,RWING,TAIL,THRT'.split(','); + var kp_coors; + var dragIndex; + var dragging; + var mouseX; + var mouseY; + var timer; + var targetX; + var targetY; + + // Ajax requests + function get_bb_prediction() { + var description = $('#description').val(); + var showkps = $('#showkps').val(); + var obj = { + x: startX, + y: startY, + width: Math.abs(endX - startX), + height: Math.abs(endY - startY), + description: description, + showkps: showkps + }; + + $.ajax({ + data: obj, + url: 'request', + type: "GET", + success: function (msg) { + console.log(msg) + context.clearRect(0, 0, canvas.width, canvas.height); + $('.placeholder').attr('src', msg) + }, + error: function (msg) { ret = 'Epic fail!'; }, + async: false, + timeout: 10000, + }); + } + + function get_pp_prediction() { + var description = $('#pp_description').val(); + var showkps = $('#pp_showkps').is(":checked") ? 1 : 0; + // window.alert("!" + showkps); + var keypoints = []; + + for (var i = 0; i < num_kps; i++) { + var current_child = kp_coors[i]; + + if(current_child.x > 256*2) { continue; } + + var x = current_child.x; + var y = current_child.y; + var part_id = current_child.id; + var keypoint_obj = { + x: x/2, + y: y/2, + part_id: (''+(part_id+1)), + }; + + keypoints.push(keypoint_obj); + console.log(keypoints); + } + + var obj = { + description: description, + keypoints: keypoints, + showkps: showkps + }; + + $.ajax({ + data: { "data" : JSON.stringify(obj) }, + url: 'request', + type: "POST", + success: function (msg) { + console.log(msg) + $('.placeholder').attr('src', msg) + }, + error: function (msg) { ret = 'Epic fail!'; }, + async: true, + contentType: "application/json", + timeout: 10000, + }); + } + + // Event listeners + $('#generate_btn').click(function () { + get_bb_prediction(); + }); + $('#pp_generate_btn').click(function () { + get_pp_prediction(); + }); + + // When enter is pressed, execute prediction + document.getElementById("pp_description").addEventListener("keydown", function(e) { + if (!e) { var e = window.event; } + // Enter is pressed + if (e.keyCode == 13) { + e.preventDefault(); // sometimes useful + get_pp_prediction(); + } + }, false); + + $("#pp_clear_btn").click(function () { + init(); + document.getElementById('pp_description').value=''; + }); + + + /******************* + * Canvas methods: + *******************/ + init(); + + + function top_shape() { + return kp_coors[num_kps-1]; + } + + function init() { + kp_coors = []; + makekp_coors(); + drawScreen(); + canvas.addEventListener("mousedown", mouseDownListener, false); + } + + function preferred_position(id) { + var xinit = (256+32)*2; + var yinit = 32*2; + var rows = 13; var vspace = 28*2; + var cols = 2; var hspace = 72*2; + return {x:xinit + (id%cols)*hspace, + y:yinit + (((id-id%cols)/cols)%rows)*vspace}; + } + function makekp_coors() { + var i; + for(i=0; i!=num_kps; i++) { + var xy = preferred_position(i); + var tempShape = new DragDisk(xy.x, xy.y, pointnames[i], i); + kp_coors.push(tempShape); + } + } + + function mouseDownListener(evt) { + var i; + + //getting mouse position correctly + var bRect = canvas.getBoundingClientRect(); + mouseX = (evt.clientX - bRect.left)*(canvas.width/bRect.width); + mouseY = (evt.clientY - bRect.top)*(canvas.height/bRect.height); + + for (i=0; i!=num_kps; i++) { + if (kp_coors[i].hitTest(mouseX, mouseY)) { + dragging = true; + //the following variable will be reset if this loop repeats with another successful hit: + dragIndex = i; + } + } + + if (dragging) { + window.addEventListener("mousemove", mouseMoveListener, false); + + //place currently dragged shape on top + kp_coors.push(kp_coors.splice(dragIndex,1)[0]); + + //The "target" position is where the object should be + targetX = kp_coors[num_kps-1].x; + targetY = kp_coors[num_kps-1].y; + + //start timer + timer = setInterval(onTimerTick, 1000/30); + } + canvas.removeEventListener("mousedown", mouseDownListener, false); + window.addEventListener("mouseup", mouseUpListener, false); + + //prevent mouse-down from affecting main browser window: + if(evt.preventDefault) { evt.preventDefault(); } + return false; + } + + function onTimerTick() { + //because of reordering, the dragging shape is the last one in the array. + kp_coors[num_kps-1].x = targetX; + kp_coors[num_kps-1].y = targetY; + + //stop the timer when the target position is reached (close enough) + if(!dragging) { + kp_coors[num_kps-1].x = targetX; + kp_coors[num_kps-1].y = targetY; + //stop timer: + clearInterval(timer); + } + drawScreen(); + } + + function mouseUpListener(evt) { + if(kp_coors[num_kps-1].x > 256*2) { + var xy = preferred_position(kp_coors[num_kps-1].id); + kp_coors[num_kps-1].y = targetY = xy.y; + kp_coors[num_kps-1].x = targetX = xy.x; + drawScreen(); + } + + canvas.addEventListener("mousedown", mouseDownListener, false); + window.removeEventListener("mouseup", mouseUpListener, false); + if (dragging) { + dragging = false; + window.removeEventListener("mousemove", mouseMoveListener, false); + } + } + + function ensure_bounds(minn,maxx, val) { + if(valmaxx) {return maxx;} + return val; + } + function mouseMoveListener(evt) { + //getting mouse position correctly + var bRect = canvas.getBoundingClientRect(); + mouseY = (evt.clientY - bRect.top)*(canvas.height/bRect.height); + mouseX = (evt.clientX - bRect.left)*(canvas.width/bRect.width); + + //ensure target point within bounds of canvas + targetY = ensure_bounds(0, canvas.height, mouseY); + targetX = ensure_bounds(0, canvas.width, mouseX); + } + + function drawkp_coors() { + context.clearRect(0, 0, canvas.width, canvas.height); + var i; + for (i=0; i!=num_kps; i++) { + kp_coors[i].drawToContext(context); + } + } + + function drawScreen() { + drawkp_coors(); + } +}); diff --git a/demo/resources/javascript/generate_kp_sam.js~ b/demo/resources/javascript/generate_kp_sam.js~ new file mode 100644 index 0000000..9c786e7 --- /dev/null +++ b/demo/resources/javascript/generate_kp_sam.js~ @@ -0,0 +1,243 @@ +$(document).ready(function() { + var mode = 'pp'; // default to bounding box + var canvas, context, startX, endX, startY, endY; + var mouseIsDown = 0; + var option_selected = null; + + canvas = document.getElementById("pp_canvas"); + context = canvas.getContext("2d"); + + /*Canvas variables:*/ + var num_kps = 15; + var pointnames = 'BACK,BEAK,BELY,BRST,CRWN,FRHD,LEYE,LLEG,LWNG,NAPE,REYE,RLEG,RWING,TAIL,THRT'.split(','); + var kp_coors; + var dragIndex; + var dragging; + var mouseX; + var mouseY; + var timer; + var targetX; + var targetY; + + // Ajax requests + function get_bb_prediction() { + var description = $('#description').val(); + var obj = { + x: startX, + y: startY, + width: Math.abs(endX - startX), + height: Math.abs(endY - startY), + description: description + }; + + $.ajax({ + data: obj, + url: 'request', + type: "GET", + success: function (msg) { + console.log(msg) + context.clearRect(0, 0, canvas.width, canvas.height); + $('.placeholder').attr('src', msg) + }, + error: function (msg) { ret = 'Epic fail!'; }, + async: false, + timeout: 10000, + }); + } + + function get_pp_prediction() { + var description = $('#pp_description').val(); + var keypoints = []; + + for (var i = 0; i < num_kps; i++) { + var current_child = kp_coors[i]; + + if(current_child.x > 256*2) { continue; } + + var x = current_child.x; + var y = current_child.y; + var part_id = current_child.id; + var keypoint_obj = { + x: x, + y: y, + part_id: (''+(part_id+1)), + }; + + keypoints.push(keypoint_obj); + console.log(keypoints); + } + + var obj = { + description: description, + keypoints: keypoints + }; + + $.ajax({ + data: { "data" : JSON.stringify(obj) }, + url: 'request', + type: "POST", + success: function (msg) { + console.log(msg) + $('.placeholder').attr('src', msg) + }, + error: function (msg) { ret = 'Epic fail!'; }, + async: true, + contentType: "application/json", + timeout: 10000, + }); + } + + // Event listeners + $('#generate_btn').click(function () { + get_bb_prediction(); + }); + $('#pp_generate_btn').click(function () { + get_pp_prediction(); + }); + + // When enter is pressed, execute prediction + document.getElementById("pp_description").addEventListener("keydown", function(e) { + if (!e) { var e = window.event; } + // Enter is pressed + if (e.keyCode == 13) { + e.preventDefault(); // sometimes useful + get_pp_prediction(); + } + }, false); + + $("#pp_clear_btn").click(function () { + init(); + document.getElementById('pp_description').value=''; + }); + + + /******************* + * Canvas methods: + *******************/ + init(); + + + function top_shape() { + return kp_coors[num_kps-1]; + } + + function init() { + kp_coors = []; + makekp_coors(); + drawScreen(); + canvas.addEventListener("mousedown", mouseDownListener, false); + } + + function preferred_position(id) { + var xinit = (256+32)*2; + var yinit = 32*2; + var rows = 13; var vspace = 28*2; + var cols = 2; var hspace = 72*2; + return {x:xinit + (id%cols)*hspace, + y:yinit + (((id-id%cols)/cols)%rows)*vspace}; + } + function makekp_coors() { + var i; + for(i=0; i!=num_kps; i++) { + var xy = preferred_position(i); + var tempShape = new DragDisk(xy.x, xy.y, pointnames[i], i); + kp_coors.push(tempShape); + } + } + + function mouseDownListener(evt) { + var i; + + //getting mouse position correctly + var bRect = canvas.getBoundingClientRect(); + mouseX = (evt.clientX - bRect.left)*(canvas.width/bRect.width); + mouseY = (evt.clientY - bRect.top)*(canvas.height/bRect.height); + + for (i=0; i!=num_kps; i++) { + if (kp_coors[i].hitTest(mouseX, mouseY)) { + dragging = true; + //the following variable will be reset if this loop repeats with another successful hit: + dragIndex = i; + } + } + + if (dragging) { + window.addEventListener("mousemove", mouseMoveListener, false); + + //place currently dragged shape on top + kp_coors.push(kp_coors.splice(dragIndex,1)[0]); + + //The "target" position is where the object should be + targetX = kp_coors[num_kps-1].x; + targetY = kp_coors[num_kps-1].y; + + //start timer + timer = setInterval(onTimerTick, 1000/30); + } + canvas.removeEventListener("mousedown", mouseDownListener, false); + window.addEventListener("mouseup", mouseUpListener, false); + + //prevent mouse-down from affecting main browser window: + if(evt.preventDefault) { evt.preventDefault(); } + return false; + } + + function onTimerTick() { + //because of reordering, the dragging shape is the last one in the array. + kp_coors[num_kps-1].x = targetX; + kp_coors[num_kps-1].y = targetY; + + //stop the timer when the target position is reached (close enough) + if(!dragging) { + kp_coors[num_kps-1].x = targetX; + kp_coors[num_kps-1].y = targetY; + //stop timer: + clearInterval(timer); + } + drawScreen(); + } + + function mouseUpListener(evt) { + if(kp_coors[num_kps-1].x > 256*2) { + var xy = preferred_position(kp_coors[num_kps-1].id); + kp_coors[num_kps-1].y = targetY = xy.y; + kp_coors[num_kps-1].x = targetX = xy.x; + drawScreen(); + } + + canvas.addEventListener("mousedown", mouseDownListener, false); + window.removeEventListener("mouseup", mouseUpListener, false); + if (dragging) { + dragging = false; + window.removeEventListener("mousemove", mouseMoveListener, false); + } + } + + function ensure_bounds(minn,maxx, val) { + if(valmaxx) {return maxx;} + return val; + } + function mouseMoveListener(evt) { + //getting mouse position correctly + var bRect = canvas.getBoundingClientRect(); + mouseY = (evt.clientY - bRect.top)*(canvas.height/bRect.height); + mouseX = (evt.clientX - bRect.left)*(canvas.width/bRect.width); + + //ensure target point within bounds of canvas + targetY = ensure_bounds(0, canvas.height, mouseY); + targetX = ensure_bounds(0, canvas.width, mouseX); + } + + function drawkp_coors() { + context.clearRect(0, 0, canvas.width, canvas.height); + var i; + for (i=0; i!=num_kps; i++) { + kp_coors[i].drawToContext(context); + } + } + + function drawScreen() { + drawkp_coors(); + } +}); diff --git a/demo/resources/javascript/generate_kp_sam_drag.js b/demo/resources/javascript/generate_kp_sam_drag.js new file mode 100644 index 0000000..648faf5 --- /dev/null +++ b/demo/resources/javascript/generate_kp_sam_drag.js @@ -0,0 +1,247 @@ +$(document).ready(function() { + var mode = 'pp'; // default to bounding box + var canvas, context, startX, endX, startY, endY; + var mouseIsDown = 0; + var option_selected = null; + + canvas = document.getElementById("pp_canvas"); + context = canvas.getContext("2d"); + + /*Canvas variables:*/ + var num_kps = 15; + var pointnames = 'BACK,BEAK,BELY,BRST,CRWN,FRHD,LEYE,LLEG,LWNG,NAPE,REYE,RLEG,RWING,TAIL,THRT'.split(','); + var kp_coors; + var dragIndex; + var dragging; + var mouseX; + var mouseY; + var timer; + var targetX; + var targetY; + + // Ajax requests + function get_bb_prediction() { + var description = $('#description').val(); + var obj = { + x: startX, + y: startY, + width: Math.abs(endX - startX), + height: Math.abs(endY - startY), + description: description + }; + + $.ajax({ + data: obj, + url: 'request', + type: "GET", + success: function (msg) { + console.log(msg) + context.clearRect(0, 0, canvas.width, canvas.height); + $('.placeholder').attr('src', msg) + }, + error: function (msg) { ret = 'Epic fail!'; }, + async: false, + timeout: 10000, + }); + } + + function get_pp_prediction() { + var description = $('#pp_description').val(); + var keypoints = []; + + for (var i = 0; i < num_kps; i++) { + var current_child = kp_coors[i]; + + if(current_child.x > 256*2) { continue; } + + var x = current_child.x; + var y = current_child.y; + var part_id = current_child.id; + var keypoint_obj = { + x: x, + y: y, + part_id: part_id, + }; + + keypoints.push(keypoint_obj); + console.log(keypoints); + } + + var obj = { + description: description, + keypoints: keypoints + }; + + $.ajax({ + data: { "data" : JSON.stringify(obj) }, + url: 'request', + type: "POST", + success: function (msg) { + console.log(msg) + $('.placeholder').attr('src', msg) + }, + error: function (msg) { ret = 'Epic fail!'; }, + async: true, + contentType: "application/json", + timeout: 10000, + }); + } + + // Event listeners + $('#generate_btn').click(function () { + get_bb_prediction(); + }); + $('#pp_generate_btn').click(function () { + get_pp_prediction(); + }); + + // When enter is pressed, execute prediction + document.getElementById("pp_description").addEventListener("keydown", function(e) { + if (!e) { var e = window.event; } + // Enter is pressed + if (e.keyCode == 13) { + e.preventDefault(); // sometimes useful + get_pp_prediction(); + } + }, false); + + $("#pp_clear_btn").click(function () { + var canvas = document.getElementById("pp_canvas"); + var context = canvas.getContext("2d"); + context.clearRect(0, 0, canvas.width, canvas.height); + var canvas = $("#pp_canvas"); + canvas.empty(); + document.getElementById('pp_description').value=''; + }); + + + /******************* + * Canvas methods: + *******************/ + init(); + + + function top_shape() { + return kp_coors[num_kps-1]; + } + + function init() { + kp_coors = []; + makekp_coors(); + drawScreen(); + canvas.addEventListener("mousedown", mouseDownListener, false); + } + + function preferred_position(id) { + var xinit = (256+32)*2; + var yinit = 32*2; + var rows = 13; var vspace = 28*2; + var cols = 2; var hspace = 72*2; + return {x:xinit + (id%cols)*hspace, + y:yinit + (((id-id%cols)/cols)%rows)*vspace}; + } + function makekp_coors() { + var i; + for(i=0; i!=num_kps; i++) { + var xy = preferred_position(i); + var tempShape = new DragDisk(xy.x, xy.y, pointnames[i], i); + kp_coors.push(tempShape); + } + } + + function mouseDownListener(evt) { + var i; + + //getting mouse position correctly + var bRect = canvas.getBoundingClientRect(); + mouseX = (evt.clientX - bRect.left)*(canvas.width/bRect.width); + mouseY = (evt.clientY - bRect.top)*(canvas.height/bRect.height); + + for (i=0; i!=num_kps; i++) { + if (kp_coors[i].hitTest(mouseX, mouseY)) { + dragging = true; + //the following variable will be reset if this loop repeats with another successful hit: + dragIndex = i; + } + } + + if (dragging) { + window.addEventListener("mousemove", mouseMoveListener, false); + + //place currently dragged shape on top + kp_coors.push(kp_coors.splice(dragIndex,1)[0]); + + //The "target" position is where the object should be + targetX = kp_coors[num_kps-1].x; + targetY = kp_coors[num_kps-1].y; + + //start timer + timer = setInterval(onTimerTick, 1000/30); + } + canvas.removeEventListener("mousedown", mouseDownListener, false); + window.addEventListener("mouseup", mouseUpListener, false); + + //prevent mouse-down from affecting main browser window: + if(evt.preventDefault) { evt.preventDefault(); } + return false; + } + + function onTimerTick() { + //because of reordering, the dragging shape is the last one in the array. + kp_coors[num_kps-1].x = targetX; + kp_coors[num_kps-1].y = targetY; + + //stop the timer when the target position is reached (close enough) + if(!dragging) { + kp_coors[num_kps-1].x = targetX; + kp_coors[num_kps-1].y = targetY; + //stop timer: + clearInterval(timer); + } + drawScreen(); + } + + function mouseUpListener(evt) { + if(kp_coors[num_kps-1].x > 256*2) { + var xy = preferred_position(kp_coors[num_kps-1].id); + kp_coors[num_kps-1].y = targetY = xy.y; + kp_coors[num_kps-1].x = targetX = xy.x; + drawScreen(); + } + + canvas.addEventListener("mousedown", mouseDownListener, false); + window.removeEventListener("mouseup", mouseUpListener, false); + if (dragging) { + dragging = false; + window.removeEventListener("mousemove", mouseMoveListener, false); + } + } + + function ensure_bounds(minn,maxx, val) { + if(valmaxx) {return maxx;} + return val; + } + function mouseMoveListener(evt) { + //getting mouse position correctly + var bRect = canvas.getBoundingClientRect(); + mouseY = (evt.clientY - bRect.top)*(canvas.height/bRect.height); + mouseX = (evt.clientX - bRect.left)*(canvas.width/bRect.width); + + //ensure target point within bounds of canvas + targetY = ensure_bounds(0, canvas.height, mouseY); + targetX = ensure_bounds(0, canvas.width, mouseX); + } + + function drawkp_coors() { + context.clearRect(0, 0, canvas.width, canvas.height); + var i; + for (i=0; i!=num_kps; i++) { + kp_coors[i].drawToContext(context); + } + } + + function drawScreen() { + drawkp_coors(); + } +}); diff --git a/demo/resources/javascript/jquery.console.js b/demo/resources/javascript/jquery.console.js new file mode 100644 index 0000000..ce439a6 --- /dev/null +++ b/demo/resources/javascript/jquery.console.js @@ -0,0 +1,624 @@ +// JQuery Console 1.0 +// Sun Feb 21 20:28:47 GMT 2010 +// +// Copyright 2010 Chris Done, Simon David Pratt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// +// 1. Redistributions of source code must retain the above +// copyright notice, this list of conditions and the following +// disclaimer. +// +// 2. Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following +// disclaimer in the documentation and/or other materials +// provided with the distribution. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +// COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN +// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. + +// TESTED ON +// Internet Explorer 6 +// Opera 10.01 +// Chromium 4.0.237.0 (Ubuntu build 31094) +// Firefox 3.5.8, 3.6.2 (Mac) +// Safari 4.0.5 (6531.22.7) (Mac) +// Google Chrome 5.0.375.55 (Mac) + +(function($){ + $.fn.console = function(config){ + //////////////////////////////////////////////////////////////////////// + // Constants + // Some are enums, data types, others just for optimisation + var keyCodes = { + // left + 37: moveBackward, + // right + 39: moveForward, + // up + 38: previousHistory, + // down + 40: nextHistory, + // backspace + 8: backDelete, + // delete + 46: forwardDelete, + // end + 35: moveToEnd, + // start + 36: moveToStart, + // return + 13: commandTrigger, + // tab + 18: doNothing + }; + var ctrlCodes = { + // C-a + 65: moveToStart, + // C-e + 69: moveToEnd, + // C-d + 68: forwardDelete, + // C-n + 78: nextHistory, + // C-p + 80: previousHistory, + // C-b + 66: moveBackward, + // C-f + 70: moveForward, + // C-k + 75: deleteUntilEnd + }; + var altCodes = { + // M-f + 70: moveToNextWord, + // M-b + 66: moveToPreviousWord, + // M-d + 68: deleteNextWord + }; + var cursor = ' '; + // Opera only works with this character, not or ­, + // but IE6 displays this character, which is bad, so just use + // it on Opera. + var wbr = $.browser.opera? '​' : ''; + + //////////////////////////////////////////////////////////////////////// + // Globals + var container = $(this); + var inner = $('
'); + var typer = $(''); + // Prompt + var promptBox; + var prompt; + var promptLabel = config && config.promptLabel? config.promptLabel : "> "; + var continuedPromptLabel = config && config.continuedPromptLabel? + config.continuedPromptLabel : "> "; + var column = 0; + var promptText = ''; + var restoreText = ''; + var continuedText = ''; + // Prompt history stack + var history = []; + var ringn = 0; + // For reasons unknown to The Sword of Michael himself, Opera + // triggers and sends a key character when you hit various + // keys like PgUp, End, etc. So there is no way of knowing + // when a user has typed '#' or End. My solution is in the + // typer.keydown and typer.keypress functions; I use the + // variable below to ignore the keypress event if the keydown + // event succeeds. + var cancelKeyPress = 0; + // When this value is false, the prompt will not respond to input + var acceptInput = true; + // When this value is true, the command has been canceled + var cancelCommand = false; + + // External exports object + var extern = {}; + + //////////////////////////////////////////////////////////////////////// + // Main entry point + (function(){ + container.append(inner); + inner.append(typer); + typer.css({position:'absolute',top:0,left:'-9999px'}); + if (config.welcomeMessage) + message(config.welcomeMessage,'jquery-console-welcome'); + newPromptBox(); + if (config.autofocus) { + inner.addClass('jquery-console-focus'); + typer.focus(); + setTimeout(function(){ + inner.addClass('jquery-console-focus'); + typer.focus(); + },100); + } + extern.inner = inner; + extern.typer = typer; + extern.scrollToBottom = scrollToBottom; + })(); + + //////////////////////////////////////////////////////////////////////// + // Reset terminal + extern.reset = function(){ + var welcome = (typeof config.welcomeMessage != 'undefined'); + inner.parent().fadeOut(function(){ + inner.find('div').each(function(){ + if (!welcome) { + $(this).remove(); + } else { + welcome = false; + } + }); + newPromptBox(); + inner.parent().fadeIn(function(){ + inner.addClass('jquery-console-focus'); + typer.focus(); + }); + }); + }; + + //////////////////////////////////////////////////////////////////////// + // Reset terminal + extern.notice = function(msg,style){ + var n = $('
').append($('
').text(msg)) + .css({visibility:'hidden'}); + container.append(n); + var focused = true; + if (style=='fadeout') + setTimeout(function(){ + n.fadeOut(function(){ + n.remove(); + }); + },4000); + else if (style=='prompt') { + var a = $('
'); + n.append(a); + focused = false; + a.click(function(){ n.fadeOut(function(){ n.remove();inner.css({opacity:1}) }); }); + } + var h = n.height(); + n.css({height:'0px',visibility:'visible'}) + .animate({height:h+'px'},function(){ + if (!focused) inner.css({opacity:0.5}); + }); + n.css('cursor','default'); + return n; + }; + + //////////////////////////////////////////////////////////////////////// + // Make a new prompt box + function newPromptBox() { + column = 0; + promptText = ''; + ringn = 0; // Reset the position of the history ring + enableInput(); + promptBox = $('
'); + var label = $(''); + var labelText = extern.continuedPrompt? continuedPromptLabel : promptLabel; + promptBox.append(label.text(labelText).show()); + label.html(label.html().replace(' ',' ')); + prompt = $(''); + promptBox.append(prompt); + inner.append(promptBox); + updatePromptDisplay(); + }; + + //////////////////////////////////////////////////////////////////////// + // Handle setting focus + container.click(function(){ + inner.addClass('jquery-console-focus'); + inner.removeClass('jquery-console-nofocus'); + typer.focus(); + scrollToBottom(); + return false; + }); + + //////////////////////////////////////////////////////////////////////// + // Handle losing focus + typer.blur(function(){ + inner.removeClass('jquery-console-focus'); + inner.addClass('jquery-console-nofocus'); + }); + + //////////////////////////////////////////////////////////////////////// + // Handle key hit before translation + // For picking up control characters like up/left/down/right + + typer.keydown(function(e){ + cancelKeyPress = 0; + var keyCode = e.keyCode; + // C-c: cancel the execution + if(e.ctrlKey && keyCode == 67) { + cancelKeyPress = keyCode; + cancelExecution(); + return false; + } + if (acceptInput) { + if (keyCode in keyCodes) { + cancelKeyPress = keyCode; + (keyCodes[keyCode])(); + return false; + } else if (e.ctrlKey && keyCode in ctrlCodes) { + cancelKeyPress = keyCode; + (ctrlCodes[keyCode])(); + return false; + } else if (e.altKey && keyCode in altCodes) { + cancelKeyPress = keyCode; + (altCodes[keyCode])(); + return false; + } + } + }); + + //////////////////////////////////////////////////////////////////////// + // Handle key press + typer.keypress(function(e){ + var keyCode = e.keyCode || e.which; + if (isIgnorableKey(e)) { + return false; + } + if (acceptInput && cancelKeyPress != keyCode && keyCode >= 32){ + if (cancelKeyPress) return false; + if (typeof config.charInsertTrigger == 'undefined' || + (typeof config.charInsertTrigger == 'function' && + config.charInsertTrigger(keyCode,promptText))) + typer.consoleInsert(keyCode); + } + if ($.browser.webkit) return false; + }); + + function isIgnorableKey(e) { + // for now just filter alt+tab that we receive on some platforms when + // user switches windows (goes away from the browser) + return ((e.keyCode == keyCodes.tab || e.keyCode == 192) && e.altKey); + }; + + //////////////////////////////////////////////////////////////////////// + // Rotate through the command history + function rotateHistory(n){ + if (history.length == 0) return; + ringn += n; + if (ringn < 0) ringn = history.length; + else if (ringn > history.length) ringn = 0; + var prevText = promptText; + if (ringn == 0) { + promptText = restoreText; + } else { + promptText = history[ringn - 1]; + } + if (config.historyPreserveColumn) { + if (promptText.length < column + 1) { + column = promptText.length; + } else if (column == 0) { + column = promptText.length; + } + } else { + column = promptText.length; + } + updatePromptDisplay(); + }; + + function previousHistory() { + rotateHistory(-1); + }; + + function nextHistory() { + rotateHistory(1); + }; + + // Add something to the history ring + function addToHistory(line){ + history.push(line); + restoreText = ''; + }; + + // Delete the character at the current position + function deleteCharAtPos(){ + if (column < promptText.length){ + promptText = + promptText.substring(0,column) + + promptText.substring(column+1); + restoreText = promptText; + return true; + } else return false; + }; + + function backDelete() { + if (moveColumn(-1)){ + deleteCharAtPos(); + updatePromptDisplay(); + } + }; + + function forwardDelete() { + if (deleteCharAtPos()) + updatePromptDisplay(); + }; + + function deleteUntilEnd() { + while(deleteCharAtPos()) { + updatePromptDisplay(); + } + }; + + function deleteNextWord() { + // A word is defined within this context as a series of alphanumeric + // characters. + // Delete up to the next alphanumeric character + while(column < promptText.length && + !isCharAlphanumeric(promptText[column])) { + deleteCharAtPos(); + updatePromptDisplay(); + } + // Then, delete until the next non-alphanumeric character + while(column < promptText.length && + isCharAlphanumeric(promptText[column])) { + deleteCharAtPos(); + updatePromptDisplay(); + } + }; + + //////////////////////////////////////////////////////////////////////// + // Validate command and trigger it if valid, or show a validation error + function commandTrigger() { + var line = promptText; + if (typeof config.commandValidate == 'function') { + var ret = config.commandValidate(line); + if (ret == true || ret == false) { + if (ret) { + handleCommand(); + } + } else { + commandResult(ret,"jquery-console-message-error"); + } + } else { + handleCommand(); + } + }; + + // Scroll to the bottom of the view + function scrollToBottom() { + inner.attr({ scrollTop: inner.attr("scrollHeight") });; + }; + + function cancelExecution() { + if(typeof config.cancelHandle == 'function') { + config.cancelHandle(); + } + } + + //////////////////////////////////////////////////////////////////////// + // Handle a command + function handleCommand() { + if (typeof config.commandHandle == 'function') { + disableInput(); + addToHistory(promptText); + var text = promptText; + if (extern.continuedPrompt) { + if (continuedText) + continuedText += '\n' + promptText; + else continuedText = promptText; + } else continuedText = undefined; + if (continuedText) text = continuedText; + var ret = config.commandHandle(text,function(msgs){ + commandResult(msgs); + }); + if (extern.continuedPrompt && !continuedText) + continuedText = promptText; + if (typeof ret == 'boolean') { + if (ret) { + // Command succeeded without a result. + commandResult(); + } else { + commandResult('Command failed.', + "jquery-console-message-error"); + } + } else if (typeof ret == "string") { + commandResult(ret,"jquery-console-message-success"); + } else if (typeof ret == 'object' && ret.length) { + commandResult(ret); + } else if (extern.continuedPrompt) { + commandResult(); + } + } + }; + + //////////////////////////////////////////////////////////////////////// + // Disable input + function disableInput() { + acceptInput = false; + }; + + // Enable input + function enableInput() { + acceptInput = true; + } + + //////////////////////////////////////////////////////////////////////// + // Reset the prompt in invalid command + function commandResult(msg,className) { + column = -1; + updatePromptDisplay(); + if (typeof msg == 'string') { + message(msg,className); + } else { + for (var x in msg) { + var ret = msg[x]; + message(ret.msg,ret.className); + } + } + newPromptBox(); + }; + + //////////////////////////////////////////////////////////////////////// + // Display a message + function message(msg,className) { + var mesg = $('
'); + if (className) mesg.addClass(className); + mesg.filledText(msg).hide(); + inner.append(mesg); + mesg.show(); + }; + + //////////////////////////////////////////////////////////////////////// + // Handle normal character insertion + typer.consoleInsert = function(keyCode){ + // TODO: remove redundant indirection + var char = String.fromCharCode(keyCode); + var before = promptText.substring(0,column); + var after = promptText.substring(column); + promptText = before + char + after; + moveColumn(1); + restoreText = promptText; + updatePromptDisplay(); + }; + + //////////////////////////////////////////////////////////////////////// + // Move to another column relative to this one + // Negative means go back, positive means go forward. + function moveColumn(n){ + if (column + n >= 0 && column + n <= promptText.length){ + column += n; + return true; + } else return false; + }; + + function moveForward() { + if(moveColumn(1)) { + updatePromptDisplay(); + return true; + } + return false; + }; + + function moveBackward() { + if(moveColumn(-1)) { + updatePromptDisplay(); + return true; + } + return false; + }; + + function moveToStart() { + if (moveColumn(-column)) + updatePromptDisplay(); + }; + + function moveToEnd() { + if (moveColumn(promptText.length-column)) + updatePromptDisplay(); + }; + + function moveToNextWord() { + while(column < promptText.length && + !isCharAlphanumeric(promptText[column]) && + moveForward()) { + } + while(column < promptText.length && + isCharAlphanumeric(promptText[column]) && + moveForward()) { + } + }; + + function moveToPreviousWord() { + // Move backward until we find the first alphanumeric + while(column -1 >= 0 && + !isCharAlphanumeric(promptText[column-1]) && + moveBackward()) { + } + // Move until we find the first non-alphanumeric + while(column -1 >= 0 && + isCharAlphanumeric(promptText[column-1]) && + moveBackward()) { + } + }; + + function isCharAlphanumeric(charToTest) { + if(typeof charToTest == 'string') { + var code = charToTest.charCodeAt(); + return (code >= 'A'.charCodeAt() && code <= 'Z'.charCodeAt()) || + (code >= 'a'.charCodeAt() && code <= 'z'.charCodeAt()) || + (code >= '0'.charCodeAt() && code <= '9'.charCodeAt()); + } + return false; + }; + + function doNothing() {}; + + extern.promptText = function(text){ + if (text) { + promptText = text; + column = promptText.length; + updatePromptDisplay(); + } + return promptText; + }; + + //////////////////////////////////////////////////////////////////////// + // Update the prompt display + function updatePromptDisplay(){ + var line = promptText; + var html = ''; + if (column > 0 && line == ''){ + // When we have an empty line just display a cursor. + html = cursor; + } else if (column == promptText.length){ + // We're at the end of the line, so we need to display + // the text *and* cursor. + html = htmlEncode(line) + cursor; + } else { + // Grab the current character, if there is one, and + // make it the current cursor. + var before = line.substring(0, column); + var current = line.substring(column,column+1); + if (current){ + current = + '' + + htmlEncode(current) + + ''; + } + var after = line.substring(column+1); + html = htmlEncode(before) + current + htmlEncode(after); + } + prompt.html(html); + scrollToBottom(); + }; + + // Simple HTML encoding + // Simply replace '<', '>' and '&' + // TODO: Use jQuery's .html() trick, or grab a proper, fast + // HTML encoder. + function htmlEncode(text){ + return ( + text.replace(/&/g,'&') + .replace(/&]{10})/g,'$1­' + wbr) + ); + }; + + return extern; + }; + // Simple utility for printing messages + $.fn.filledText = function(txt){ + $(this).text(txt); + $(this).html($(this).html().replace(/\n/g,'
')); + return this; + }; +})(jQuery); diff --git a/demo/resources/javascript/jquery.tools.min.js b/demo/resources/javascript/jquery.tools.min.js new file mode 100644 index 0000000..8672732 --- /dev/null +++ b/demo/resources/javascript/jquery.tools.min.js @@ -0,0 +1,53 @@ +/* + * jQuery Tools 1.2.5 - The missing UI library for the Web + * + * [tabs, tabs.slideshow, tooltip, tooltip.slide, tooltip.dynamic, scrollable, scrollable.autoscroll, scrollable.navigator, overlay, overlay.apple] + * + * NO COPYRIGHTS OR LICENSES. DO WHAT YOU LIKE. + * + * http://flowplayer.org/tools/ + * + * File generated: Tue Nov 30 12:18:48 GMT 2010 + */ +(function(c){function p(d,b,a){var e=this,l=d.add(this),h=d.find(a.tabs),i=b.jquery?b:d.children(b),j;h.length||(h=d.children());i.length||(i=d.parent().find(b));i.length||(i=c(b));c.extend(this,{click:function(f,g){var k=h.eq(f);if(typeof f=="string"&&f.replace("#","")){k=h.filter("[href*="+f.replace("#","")+"]");f=Math.max(h.index(k),0)}if(a.rotate){var n=h.length-1;if(f<0)return e.click(n,g);if(f>n)return e.click(0,g)}if(!k.length){if(j>=0)return e;f=a.initialIndex;k=h.eq(f)}if(f===j)return e; +g=g||c.Event();g.type="onBeforeClick";l.trigger(g,[f]);if(!g.isDefaultPrevented()){o[a.effect].call(e,f,function(){g.type="onClick";l.trigger(g,[f])});j=f;h.removeClass(a.current);k.addClass(a.current);return e}},getConf:function(){return a},getTabs:function(){return h},getPanes:function(){return i},getCurrentPane:function(){return i.eq(j)},getCurrentTab:function(){return h.eq(j)},getIndex:function(){return j},next:function(){return e.click(j+1)},prev:function(){return e.click(j-1)},destroy:function(){h.unbind(a.event).removeClass(a.current); +i.find("a[href^=#]").unbind("click.T");return e}});c.each("onBeforeClick,onClick".split(","),function(f,g){c.isFunction(a[g])&&c(e).bind(g,a[g]);e[g]=function(k){k&&c(e).bind(g,k);return e}});if(a.history&&c.fn.history){c.tools.history.init(h);a.event="history"}h.each(function(f){c(this).bind(a.event,function(g){e.click(f,g);return g.preventDefault()})});i.find("a[href^=#]").bind("click.T",function(f){e.click(c(this).attr("href"),f)});if(location.hash&&a.tabs=="a"&&d.find("[href="+location.hash+"]").length)e.click(location.hash); +else if(a.initialIndex===0||a.initialIndex>0)e.click(a.initialIndex)}c.tools=c.tools||{version:"1.2.5"};c.tools.tabs={conf:{tabs:"a",current:"current",onBeforeClick:null,onClick:null,effect:"default",initialIndex:0,event:"click",rotate:false,history:false},addEffect:function(d,b){o[d]=b}};var o={"default":function(d,b){this.getPanes().hide().eq(d).show();b.call()},fade:function(d,b){var a=this.getConf(),e=a.fadeOutSpeed,l=this.getPanes();e?l.fadeOut(e):l.hide();l.eq(d).fadeIn(a.fadeInSpeed,b)},slide:function(d, +b){this.getPanes().slideUp(200);this.getPanes().eq(d).slideDown(400,b)},ajax:function(d,b){this.getPanes().eq(0).load(this.getTabs().eq(d).attr("href"),b)}},m;c.tools.tabs.addEffect("horizontal",function(d,b){m||(m=this.getPanes().eq(0).width());this.getCurrentPane().animate({width:0},function(){c(this).hide()});this.getPanes().eq(d).animate({width:m},function(){c(this).show();b.call()})});c.fn.tabs=function(d,b){var a=this.data("tabs");if(a){a.destroy();this.removeData("tabs")}if(c.isFunction(b))b= +{onBeforeClick:b};b=c.extend({},c.tools.tabs.conf,b);this.each(function(){a=new p(c(this),d,b);c(this).data("tabs",a)});return b.api?a:this}})(jQuery); +(function(c){function p(g,a){function m(f){var e=c(f);return e.length<2?e:g.parent().find(f)}var b=this,i=g.add(this),d=g.data("tabs"),h,j=true,n=m(a.next).click(function(){d.next()}),k=m(a.prev).click(function(){d.prev()});c.extend(b,{getTabs:function(){return d},getConf:function(){return a},play:function(){if(h)return b;var f=c.Event("onBeforePlay");i.trigger(f);if(f.isDefaultPrevented())return b;h=setInterval(d.next,a.interval);j=false;i.trigger("onPlay");return b},pause:function(){if(!h)return b; +var f=c.Event("onBeforePause");i.trigger(f);if(f.isDefaultPrevented())return b;h=clearInterval(h);i.trigger("onPause");return b},stop:function(){b.pause();j=true}});c.each("onBeforePlay,onPlay,onBeforePause,onPause".split(","),function(f,e){c.isFunction(a[e])&&c(b).bind(e,a[e]);b[e]=function(q){return c(b).bind(e,q)}});a.autopause&&d.getTabs().add(n).add(k).add(d.getPanes()).hover(b.pause,function(){j||b.play()});a.autoplay&&b.play();a.clickable&&d.getPanes().click(function(){d.next()});if(!d.getConf().rotate){var l= +a.disabledClass;d.getIndex()||k.addClass(l);d.onBeforeClick(function(f,e){k.toggleClass(l,!e);n.toggleClass(l,e==d.getTabs().length-1)})}}var o;o=c.tools.tabs.slideshow={conf:{next:".forward",prev:".backward",disabledClass:"disabled",autoplay:false,autopause:true,interval:3E3,clickable:true,api:false}};c.fn.slideshow=function(g){var a=this.data("slideshow");if(a)return a;g=c.extend({},o.conf,g);this.each(function(){a=new p(c(this),g);c(this).data("slideshow",a)});return g.api?a:this}})(jQuery); +(function(f){function p(a,b,c){var h=c.relative?a.position().top:a.offset().top,d=c.relative?a.position().left:a.offset().left,i=c.position[0];h-=b.outerHeight()-c.offset[0];d+=a.outerWidth()+c.offset[1];if(/iPad/i.test(navigator.userAgent))h-=f(window).scrollTop();var j=b.outerHeight()+a.outerHeight();if(i=="center")h+=j/2;if(i=="bottom")h+=j;i=c.position[1];a=b.outerWidth()+a.outerWidth();if(i=="center")d-=a/2;if(i=="left")d-=a;return{top:h,left:d}}function u(a,b){var c=this,h=a.add(c),d,i=0,j= +0,m=a.attr("title"),q=a.attr("data-tooltip"),r=o[b.effect],l,s=a.is(":input"),v=s&&a.is(":checkbox, :radio, select, :button, :submit"),t=a.attr("type"),k=b.events[t]||b.events[s?v?"widget":"input":"def"];if(!r)throw'Nonexistent effect "'+b.effect+'"';k=k.split(/,\s*/);if(k.length!=2)throw"Tooltip: bad events configuration for "+t;a.bind(k[0],function(e){clearTimeout(i);if(b.predelay)j=setTimeout(function(){c.show(e)},b.predelay);else c.show(e)}).bind(k[1],function(e){clearTimeout(j);if(b.delay)i= +setTimeout(function(){c.hide(e)},b.delay);else c.hide(e)});if(m&&b.cancelDefault){a.removeAttr("title");a.data("title",m)}f.extend(c,{show:function(e){if(!d){if(q)d=f(q);else if(b.tip)d=f(b.tip).eq(0);else if(m)d=f(b.layout).addClass(b.tipClass).appendTo(document.body).hide().append(m);else{d=a.next();d.length||(d=a.parent().next())}if(!d.length)throw"Cannot find tooltip for "+a;}if(c.isShown())return c;d.stop(true,true);var g=p(a,d,b);b.tip&&d.html(a.data("title"));e=e||f.Event();e.type="onBeforeShow"; +h.trigger(e,[g]);if(e.isDefaultPrevented())return c;g=p(a,d,b);d.css({position:"absolute",top:g.top,left:g.left});l=true;r[0].call(c,function(){e.type="onShow";l="full";h.trigger(e)});g=b.events.tooltip.split(/,\s*/);if(!d.data("__set")){d.bind(g[0],function(){clearTimeout(i);clearTimeout(j)});g[1]&&!a.is("input:not(:checkbox, :radio), textarea")&&d.bind(g[1],function(n){n.relatedTarget!=a[0]&&a.trigger(k[1].split(" ")[0])});d.data("__set",true)}return c},hide:function(e){if(!d||!c.isShown())return c; +e=e||f.Event();e.type="onBeforeHide";h.trigger(e);if(!e.isDefaultPrevented()){l=false;o[b.effect][1].call(c,function(){e.type="onHide";h.trigger(e)});return c}},isShown:function(e){return e?l=="full":l},getConf:function(){return b},getTip:function(){return d},getTrigger:function(){return a}});f.each("onHide,onBeforeShow,onShow,onBeforeHide".split(","),function(e,g){f.isFunction(b[g])&&f(c).bind(g,b[g]);c[g]=function(n){n&&f(c).bind(g,n);return c}})}f.tools=f.tools||{version:"1.2.5"};f.tools.tooltip= +{conf:{effect:"toggle",fadeOutSpeed:"fast",predelay:0,delay:30,opacity:1,tip:0,position:["top","center"],offset:[0,0],relative:false,cancelDefault:true,events:{def:"mouseenter,mouseleave",input:"focus,blur",widget:"focus mouseenter,blur mouseleave",tooltip:"mouseenter,mouseleave"},layout:"
",tipClass:"tooltip"},addEffect:function(a,b,c){o[a]=[b,c]}};var o={toggle:[function(a){var b=this.getConf(),c=this.getTip();b=b.opacity;b<1&&c.css({opacity:b});c.show();a.call()},function(a){this.getTip().hide(); +a.call()}],fade:[function(a){var b=this.getConf();this.getTip().fadeTo(b.fadeInSpeed,b.opacity,a)},function(a){this.getTip().fadeOut(this.getConf().fadeOutSpeed,a)}]};f.fn.tooltip=function(a){var b=this.data("tooltip");if(b)return b;a=f.extend(true,{},f.tools.tooltip.conf,a);if(typeof a.position=="string")a.position=a.position.split(/,?\s/);this.each(function(){b=new u(f(this),a);f(this).data("tooltip",b)});return a.api?b:this}})(jQuery); +(function(d){var i=d.tools.tooltip;d.extend(i.conf,{direction:"up",bounce:false,slideOffset:10,slideInSpeed:200,slideOutSpeed:200,slideFade:!d.browser.msie});var e={up:["-","top"],down:["+","top"],left:["-","left"],right:["+","left"]};i.addEffect("slide",function(g){var a=this.getConf(),f=this.getTip(),b=a.slideFade?{opacity:a.opacity}:{},c=e[a.direction]||e.up;b[c[1]]=c[0]+"="+a.slideOffset;a.slideFade&&f.css({opacity:0});f.show().animate(b,a.slideInSpeed,g)},function(g){var a=this.getConf(),f=a.slideOffset, +b=a.slideFade?{opacity:0}:{},c=e[a.direction]||e.up,h=""+c[0];if(a.bounce)h=h=="+"?"-":"+";b[c[1]]=h+"="+f;this.getTip().animate(b,a.slideOutSpeed,function(){d(this).hide();g.call()})})})(jQuery); +(function(g){function j(a){var c=g(window),d=c.width()+c.scrollLeft(),h=c.height()+c.scrollTop();return[a.offset().top<=c.scrollTop(),d<=a.offset().left+a.width(),h<=a.offset().top+a.height(),c.scrollLeft()>=a.offset().left]}function k(a){for(var c=a.length;c--;)if(a[c])return false;return true}var i=g.tools.tooltip;i.dynamic={conf:{classNames:"top right bottom left"}};g.fn.dynamic=function(a){if(typeof a=="number")a={speed:a};a=g.extend({},i.dynamic.conf,a);var c=a.classNames.split(/\s/),d;this.each(function(){var h= +g(this).tooltip().onBeforeShow(function(e,f){e=this.getTip();var b=this.getConf();d||(d=[b.position[0],b.position[1],b.offset[0],b.offset[1],g.extend({},b)]);g.extend(b,d[4]);b.position=[d[0],d[1]];b.offset=[d[2],d[3]];e.css({visibility:"hidden",position:"absolute",top:f.top,left:f.left}).show();f=j(e);if(!k(f)){if(f[2]){g.extend(b,a.top);b.position[0]="top";e.addClass(c[0])}if(f[3]){g.extend(b,a.right);b.position[1]="right";e.addClass(c[1])}if(f[0]){g.extend(b,a.bottom);b.position[0]="bottom";e.addClass(c[2])}if(f[1]){g.extend(b, +a.left);b.position[1]="left";e.addClass(c[3])}if(f[0]||f[2])b.offset[0]*=-1;if(f[1]||f[3])b.offset[1]*=-1}e.css({visibility:"visible"}).hide()});h.onBeforeShow(function(){var e=this.getConf();this.getTip();setTimeout(function(){e.position=[d[0],d[1]];e.offset=[d[2],d[3]]},0)});h.onHide(function(){var e=this.getTip();e.removeClass(a.classNames)});ret=h});return a.api?ret:this}})(jQuery); +(function(e){function p(f,c){var b=e(c);return b.length<2?b:f.parent().find(c)}function u(f,c){var b=this,n=f.add(b),g=f.children(),l=0,j=c.vertical;k||(k=b);if(g.length>1)g=e(c.items,f);e.extend(b,{getConf:function(){return c},getIndex:function(){return l},getSize:function(){return b.getItems().size()},getNaviButtons:function(){return o.add(q)},getRoot:function(){return f},getItemWrap:function(){return g},getItems:function(){return g.children(c.item).not("."+c.clonedClass)},move:function(a,d){return b.seekTo(l+ +a,d)},next:function(a){return b.move(1,a)},prev:function(a){return b.move(-1,a)},begin:function(a){return b.seekTo(0,a)},end:function(a){return b.seekTo(b.getSize()-1,a)},focus:function(){return k=b},addItem:function(a){a=e(a);if(c.circular){g.children("."+c.clonedClass+":last").before(a);g.children("."+c.clonedClass+":first").replaceWith(a.clone().addClass(c.clonedClass))}else g.append(a);n.trigger("onAddItem",[a]);return b},seekTo:function(a,d,h){a.jquery||(a*=1);if(c.circular&&a===0&&l==-1&&d!== +0)return b;if(!c.circular&&a<0||a>b.getSize()||a<-1)return b;var i=a;if(a.jquery)a=b.getItems().index(a);else i=b.getItems().eq(a);var r=e.Event("onBeforeSeek");if(!h){n.trigger(r,[a,d]);if(r.isDefaultPrevented()||!i.length)return b}i=j?{top:-i.position().top}:{left:-i.position().left};l=a;k=b;if(d===undefined)d=c.speed;g.animate(i,d,c.easing,h||function(){n.trigger("onSeek",[a])});return b}});e.each(["onBeforeSeek","onSeek","onAddItem"],function(a,d){e.isFunction(c[d])&&e(b).bind(d,c[d]);b[d]=function(h){h&& +e(b).bind(d,h);return b}});if(c.circular){var s=b.getItems().slice(-1).clone().prependTo(g),t=b.getItems().eq(1).clone().appendTo(g);s.add(t).addClass(c.clonedClass);b.onBeforeSeek(function(a,d,h){if(!a.isDefaultPrevented())if(d==-1){b.seekTo(s,h,function(){b.end(0)});return a.preventDefault()}else d==b.getSize()&&b.seekTo(t,h,function(){b.begin(0)})});b.seekTo(0,0,function(){})}var o=p(f,c.prev).click(function(){b.prev()}),q=p(f,c.next).click(function(){b.next()});if(!c.circular&&b.getSize()>1){b.onBeforeSeek(function(a, +d){setTimeout(function(){if(!a.isDefaultPrevented()){o.toggleClass(c.disabledClass,d<=0);q.toggleClass(c.disabledClass,d>=b.getSize()-1)}},1)});c.initialIndex||o.addClass(c.disabledClass)}c.mousewheel&&e.fn.mousewheel&&f.mousewheel(function(a,d){if(c.mousewheel){b.move(d<0?1:-1,c.wheelSpeed||50);return false}});if(c.touch){var m={};g[0].ontouchstart=function(a){a=a.touches[0];m.x=a.clientX;m.y=a.clientY};g[0].ontouchmove=function(a){if(a.touches.length==1&&!g.is(":animated")){var d=a.touches[0],h= +m.x-d.clientX;d=m.y-d.clientY;b[j&&d>0||!j&&h>0?"next":"prev"]();a.preventDefault()}}}c.keyboard&&e(document).bind("keydown.scrollable",function(a){if(!(!c.keyboard||a.altKey||a.ctrlKey||e(a.target).is(":input")))if(!(c.keyboard!="static"&&k!=b)){var d=a.keyCode;if(j&&(d==38||d==40)){b.move(d==38?-1:1);return a.preventDefault()}if(!j&&(d==37||d==39)){b.move(d==37?-1:1);return a.preventDefault()}}});c.initialIndex&&b.seekTo(c.initialIndex,0,function(){})}e.tools=e.tools||{version:"1.2.5"};e.tools.scrollable= +{conf:{activeClass:"active",circular:false,clonedClass:"cloned",disabledClass:"disabled",easing:"swing",initialIndex:0,item:null,items:".items",keyboard:true,mousewheel:false,next:".next",prev:".prev",speed:400,vertical:false,touch:true,wheelSpeed:0}};var k;e.fn.scrollable=function(f){var c=this.data("scrollable");if(c)return c;f=e.extend({},e.tools.scrollable.conf,f);this.each(function(){c=new u(e(this),f);e(this).data("scrollable",c)});return f.api?c:this}})(jQuery); +(function(b){var f=b.tools.scrollable;f.autoscroll={conf:{autoplay:true,interval:3E3,autopause:true}};b.fn.autoscroll=function(c){if(typeof c=="number")c={interval:c};var d=b.extend({},f.autoscroll.conf,c),g;this.each(function(){var a=b(this).data("scrollable");if(a)g=a;var e,h=true;a.play=function(){if(!e){h=false;e=setInterval(function(){a.next()},d.interval)}};a.pause=function(){e=clearInterval(e)};a.stop=function(){a.pause();h=true};d.autopause&&a.getRoot().add(a.getNaviButtons()).hover(a.pause, +a.play);d.autoplay&&a.play()});return d.api?g:this}})(jQuery); +(function(d){function p(b,g){var h=d(g);return h.length<2?h:b.parent().find(g)}var m=d.tools.scrollable;m.navigator={conf:{navi:".navi",naviItem:null,activeClass:"active",indexed:false,idPrefix:null,history:false}};d.fn.navigator=function(b){if(typeof b=="string")b={navi:b};b=d.extend({},m.navigator.conf,b);var g;this.each(function(){function h(a,c,i){e.seekTo(c);if(j){if(location.hash)location.hash=a.attr("href").replace("#","")}else return i.preventDefault()}function f(){return k.find(b.naviItem|| +"> *")}function n(a){var c=d("<"+(b.naviItem||"a")+"/>").click(function(i){h(d(this),a,i)}).attr("href","#"+a);a===0&&c.addClass(l);b.indexed&&c.text(a+1);b.idPrefix&&c.attr("id",b.idPrefix+a);return c.appendTo(k)}function o(a,c){a=f().eq(c.replace("#",""));a.length||(a=f().filter("[href="+c+"]"));a.click()}var e=d(this).data("scrollable"),k=b.navi.jquery?b.navi:p(e.getRoot(),b.navi),q=e.getNaviButtons(),l=b.activeClass,j=b.history&&d.fn.history;if(e)g=e;e.getNaviButtons=function(){return q.add(k)}; +f().length?f().each(function(a){d(this).click(function(c){h(d(this),a,c)})}):d.each(e.getItems(),function(a){n(a)});e.onBeforeSeek(function(a,c){setTimeout(function(){if(!a.isDefaultPrevented()){var i=f().eq(c);!a.isDefaultPrevented()&&i.length&&f().removeClass(l).eq(c).addClass(l)}},1)});e.onAddItem(function(a,c){c=n(e.getItems().index(c));j&&c.history(o)});j&&f().history(o)});return b.api?g:this}})(jQuery); +(function(a){function t(d,b){var c=this,j=d.add(c),o=a(window),k,f,m,g=a.tools.expose&&(b.mask||b.expose),n=Math.random().toString().slice(10);if(g){if(typeof g=="string")g={color:g};g.closeOnClick=g.closeOnEsc=false}var p=b.target||d.attr("rel");f=p?a(p):d;if(!f.length)throw"Could not find Overlay: "+p;d&&d.index(f)==-1&&d.click(function(e){c.load(e);return e.preventDefault()});a.extend(c,{load:function(e){if(c.isOpened())return c;var h=q[b.effect];if(!h)throw'Overlay: cannot find effect : "'+b.effect+ +'"';b.oneInstance&&a.each(s,function(){this.close(e)});e=e||a.Event();e.type="onBeforeLoad";j.trigger(e);if(e.isDefaultPrevented())return c;m=true;g&&a(f).expose(g);var i=b.top,r=b.left,u=f.outerWidth({margin:true}),v=f.outerHeight({margin:true});if(typeof i=="string")i=i=="center"?Math.max((o.height()-v)/2,0):parseInt(i,10)/100*o.height();if(r=="center")r=Math.max((o.width()-u)/2,0);h[0].call(c,{top:i,left:r},function(){if(m){e.type="onLoad";j.trigger(e)}});g&&b.closeOnClick&&a.mask.getMask().one("click", +c.close);b.closeOnClick&&a(document).bind("click."+n,function(l){a(l.target).parents(f).length||c.close(l)});b.closeOnEsc&&a(document).bind("keydown."+n,function(l){l.keyCode==27&&c.close(l)});return c},close:function(e){if(!c.isOpened())return c;e=e||a.Event();e.type="onBeforeClose";j.trigger(e);if(!e.isDefaultPrevented()){m=false;q[b.effect][1].call(c,function(){e.type="onClose";j.trigger(e)});a(document).unbind("click."+n).unbind("keydown."+n);g&&a.mask.close();return c}},getOverlay:function(){return f}, +getTrigger:function(){return d},getClosers:function(){return k},isOpened:function(){return m},getConf:function(){return b}});a.each("onBeforeLoad,onStart,onLoad,onBeforeClose,onClose".split(","),function(e,h){a.isFunction(b[h])&&a(c).bind(h,b[h]);c[h]=function(i){i&&a(c).bind(h,i);return c}});k=f.find(b.close||".close");if(!k.length&&!b.close){k=a('');f.prepend(k)}k.click(function(e){c.close(e)});b.load&&c.load()}a.tools=a.tools||{version:"1.2.5"};a.tools.overlay={addEffect:function(d, +b,c){q[d]=[b,c]},conf:{close:null,closeOnClick:true,closeOnEsc:true,closeSpeed:"fast",effect:"default",fixed:!a.browser.msie||a.browser.version>6,left:"center",load:false,mask:null,oneInstance:true,speed:"normal",target:null,top:"10%"}};var s=[],q={};a.tools.overlay.addEffect("default",function(d,b){var c=this.getConf(),j=a(window);if(!c.fixed){d.top+=j.scrollTop();d.left+=j.scrollLeft()}d.position=c.fixed?"fixed":"absolute";this.getOverlay().css(d).fadeIn(c.speed,b)},function(d){this.getOverlay().fadeOut(this.getConf().closeSpeed, +d)});a.fn.overlay=function(d){var b=this.data("overlay");if(b)return b;if(a.isFunction(d))d={onBeforeLoad:d};d=a.extend(true,{},a.tools.overlay.conf,d);this.each(function(){b=new t(a(this),d);s.push(b);a(this).data("overlay",b)});return d.api?b:this}})(jQuery); +(function(h){function k(d){var e=d.offset();return{top:e.top+d.height()/2,left:e.left+d.width()/2}}var l=h.tools.overlay,f=h(window);h.extend(l.conf,{start:{top:null,left:null},fadeInSpeed:"fast",zIndex:9999});function o(d,e){var a=this.getOverlay(),c=this.getConf(),g=this.getTrigger(),p=this,m=a.outerWidth({margin:true}),b=a.data("img"),n=c.fixed?"fixed":"absolute";if(!b){b=a.css("backgroundImage");if(!b)throw"background-image CSS property not set for overlay";b=b.slice(b.indexOf("(")+1,b.indexOf(")")).replace(/\"/g, +"");a.css("backgroundImage","none");b=h('');b.css({border:0,display:"none"}).width(m);h("body").append(b);a.data("img",b)}var i=c.start.top||Math.round(f.height()/2),j=c.start.left||Math.round(f.width()/2);if(g){g=k(g);i=g.top;j=g.left}if(c.fixed){i-=f.scrollTop();j-=f.scrollLeft()}else{d.top+=f.scrollTop();d.left+=f.scrollLeft()}b.css({position:"absolute",top:i,left:j,width:0,zIndex:c.zIndex}).show();d.position=n;a.css(d);b.animate({top:a.css("top"),left:a.css("left"),width:m}, +c.speed,function(){a.css("zIndex",c.zIndex+1).fadeIn(c.fadeInSpeed,function(){p.isOpened()&&!h(this).index(a)?e.call():a.hide()})}).css("position",n)}function q(d){var e=this.getOverlay().hide(),a=this.getConf(),c=this.getTrigger();e=e.data("img");var g={top:a.start.top,left:a.start.left,width:0};c&&h.extend(g,k(c));a.fixed&&e.css({position:"absolute"}).animate({top:"+="+f.scrollTop(),left:"+="+f.scrollLeft()},0);e.animate(g,a.closeSpeed,d)}l.addEffect("apple",o,q)})(jQuery); diff --git a/demo/resources/javascript/jquery.treeview.js b/demo/resources/javascript/jquery.treeview.js new file mode 100644 index 0000000..588ab6e --- /dev/null +++ b/demo/resources/javascript/jquery.treeview.js @@ -0,0 +1,245 @@ +/* + * Treeview pre-1.4.1 - jQuery plugin to hide and show branches of a tree + * + * http://bassistance.de/jquery-plugins/jquery-plugin-treeview/ + * http://docs.jquery.com/Plugins/Treeview + * + * Copyright (c) 2007 Jörn Zaefferer + * + * Dual licensed under the MIT and GPL licenses: + * http://www.opensource.org/licenses/mit-license.php + * http://www.gnu.org/licenses/gpl.html + * + * Revision: $Id: jquery.treeview.js 5759 2008-07-01 07:50:28Z joern.zaefferer $ + * + */ + +;(function($) { + + $.extend($.fn, { + swapClass: function(c1, c2) { + var c1Elements = this.filter('.' + c1); + this.filter('.' + c2).removeClass(c2).addClass(c1); + c1Elements.removeClass(c1).addClass(c2); + return this; + }, + replaceClass: function(c1, c2) { + return this.filter('.' + c1).removeClass(c1).addClass(c2).end(); + }, + hoverClass: function(className) { + className = className || "hover"; + return this.hover(function() { + $(this).addClass(className); + }, function() { + $(this).removeClass(className); + }); + }, + heightToggle: function(animated, callback) { + animated ? + this.animate({ height: "toggle" }, animated, callback) : + this.each(function(){ + jQuery(this)[ jQuery(this).is(":hidden") ? "show" : "hide" ](); + if(callback) + callback.apply(this, arguments); + }); + }, + heightHide: function(animated, callback) { + if (animated) { + this.animate({ height: "hide" }, animated, callback); + } else { + this.hide(); + if (callback) + this.each(callback); + } + }, + prepareBranches: function(settings) { + if (!settings.prerendered) { + // mark last tree items + this.filter(":last-child:not(ul)").addClass(CLASSES.last); + // collapse whole tree, or only those marked as closed, anyway except those marked as open + this.filter((settings.collapsed ? "" : "." + CLASSES.closed) + ":not(." + CLASSES.open + ")").find(">ul").hide(); + } + // return all items with sublists + return this.filter(":has(>ul)"); + }, + applyClasses: function(settings, toggler) { + this.filter(":has(>ul):not(:has(>a))").find(">span").unbind("click.treeview").bind("click.treeview", function(event) { + // don't handle click events on children, eg. checkboxes + if ( this == event.target ) + toggler.apply($(this).next()); + }).add( $("a", this) ).hoverClass(); + + if (!settings.prerendered) { + // handle closed ones first + this.filter(":has(>ul:hidden)") + .addClass(CLASSES.expandable) + .replaceClass(CLASSES.last, CLASSES.lastExpandable); + + // handle open ones + this.not(":has(>ul:hidden)") + .addClass(CLASSES.collapsable) + .replaceClass(CLASSES.last, CLASSES.lastCollapsable); + + // create hitarea if not present + var hitarea = this.find("div." + CLASSES.hitarea); + if (!hitarea.length) + hitarea = this.prepend("
").find("div." + CLASSES.hitarea); + hitarea.removeClass().addClass(CLASSES.hitarea).each(function() { + var classes = ""; + $.each($(this).parent().attr("class").split(" "), function() { + classes += this + "-hitarea "; + }); + $(this).addClass( classes ); + }) + } + + // apply event to hitarea + this.find("div." + CLASSES.hitarea).click( toggler ); + }, + treeview: function(settings) { + + settings = $.extend({ + cookieId: "treeview" + }, settings); + + if ( settings.toggle ) { + var callback = settings.toggle; + settings.toggle = function() { + return callback.apply($(this).parent()[0], arguments); + }; + } + + // factory for treecontroller + function treeController(tree, control) { + // factory for click handlers + function handler(filter) { + return function() { + // reuse toggle event handler, applying the elements to toggle + // start searching for all hitareas + toggler.apply( $("div." + CLASSES.hitarea, tree).filter(function() { + // for plain toggle, no filter is provided, otherwise we need to check the parent element + return filter ? $(this).parent("." + filter).length : true; + }) ); + return false; + }; + } + // click on first element to collapse tree + $("a:eq(0)", control).click( handler(CLASSES.collapsable) ); + // click on second to expand tree + $("a:eq(1)", control).click( handler(CLASSES.expandable) ); + // click on third to toggle tree + $("a:eq(2)", control).click( handler() ); + } + + // handle toggle event + function toggler() { + $(this) + .parent() + // swap classes for hitarea + .find(">.hitarea") + .swapClass( CLASSES.collapsableHitarea, CLASSES.expandableHitarea ) + .swapClass( CLASSES.lastCollapsableHitarea, CLASSES.lastExpandableHitarea ) + .end() + // swap classes for parent li + .swapClass( CLASSES.collapsable, CLASSES.expandable ) + .swapClass( CLASSES.lastCollapsable, CLASSES.lastExpandable ) + // find child lists + .find( ">ul" ) + // toggle them + .heightToggle( settings.animated, settings.toggle ); + if ( settings.unique ) { + $(this).parent() + .siblings() + // swap classes for hitarea + .find(">.hitarea") + .replaceClass( CLASSES.collapsableHitarea, CLASSES.expandableHitarea ) + .replaceClass( CLASSES.lastCollapsableHitarea, CLASSES.lastExpandableHitarea ) + .end() + .replaceClass( CLASSES.collapsable, CLASSES.expandable ) + .replaceClass( CLASSES.lastCollapsable, CLASSES.lastExpandable ) + .find( ">ul" ) + .heightHide( settings.animated, settings.toggle ); + } + } + this.data("toggler", toggler); + + function serialize() { + function binary(arg) { + return arg ? 1 : 0; + } + var data = []; + branches.each(function(i, e) { + data[i] = $(e).is(":has(>ul:visible)") ? 1 : 0; + }); + $.cookie(settings.cookieId, data.join(""), settings.cookieOptions ); + } + + function deserialize() { + var stored = $.cookie(settings.cookieId); + if ( stored ) { + var data = stored.split(""); + branches.each(function(i, e) { + $(e).find(">ul")[ parseInt(data[i]) ? "show" : "hide" ](); + }); + } + } + + // add treeview class to activate styles + this.addClass("treeview"); + + // prepare branches and find all tree items with child lists + var branches = this.find("li").prepareBranches(settings); + + switch(settings.persist) { + case "cookie": + var toggleCallback = settings.toggle; + settings.toggle = function() { + serialize(); + if (toggleCallback) { + toggleCallback.apply(this, arguments); + } + }; + deserialize(); + break; + case "location": + var current = this.find("a").filter(function() { return this.href.toLowerCase() == location.href.toLowerCase(); }); + if ( current.length ) { + current.addClass("selected").parents("ul, li").add( current.next() ).show(); + } + break; + } + + branches.applyClasses(settings, toggler); + + // if control option is set, create the treecontroller and show it + if ( settings.control ) { + treeController(this, settings.control); + $(settings.control).show(); + } + + return this; + } + }); + + // classes used by the plugin + // need to be styled via external stylesheet, see first example + $.treeview = {}; + var CLASSES = ($.treeview.classes = { + open: "open", + closed: "closed", + expandable: "expandable", + expandableHitarea: "expandable-hitarea", + lastExpandableHitarea: "lastExpandable-hitarea", + collapsable: "collapsable", + collapsableHitarea: "collapsable-hitarea", + lastCollapsableHitarea: "lastCollapsable-hitarea", + lastCollapsable: "lastCollapsable", + lastExpandable: "lastExpandable", + last: "last", + hitarea: "hitarea" + }); + + // provide backwards compability + $.fn.Treeview = $.fn.treeview; + +})(jQuery); \ No newline at end of file diff --git a/demo/resources/javascript/send_params.js b/demo/resources/javascript/send_params.js new file mode 100644 index 0000000..d6cfdd2 --- /dev/null +++ b/demo/resources/javascript/send_params.js @@ -0,0 +1,12 @@ +$('#generate_btn').click(function () { + var obj = { + x: 0, + y: 0, + width: 0, + height: 0 + } + + $.get({ + + }) +}) \ No newline at end of file diff --git a/demo/resources/notes b/demo/resources/notes new file mode 100644 index 0000000..0dcee54 --- /dev/null +++ b/demo/resources/notes @@ -0,0 +1 @@ +hey, we should include a link to that xkcd about birds / machine learning haha diff --git a/demo/resources/template.ltp b/demo/resources/template.ltp new file mode 100644 index 0000000..6781572 --- /dev/null +++ b/demo/resources/template.ltp @@ -0,0 +1,10 @@ + + +

Hello, Template!

+
    +# for _,s in ipairs(data) do +
  • @(s)
  • +# end +
+ +