code
stringlengths 501
5.19M
| package
stringlengths 2
81
| path
stringlengths 9
304
| filename
stringlengths 4
145
|
---|---|---|---|
# Zetattel
An SDK to help send messages through the zettatel API
# Usage
## Quick sms
to use this package, you can either git clone or install using pip:
```
pip install zettatel==0.1.3.1
```
This will install all the required packages. Next we need to initialize the packacge as shown below:
```
from zettatel.message import Client
message = Client(
"username",
"password",
"senderId"
)
```
To send a quick message use the following sample:
```
message.send_quick_SMS('254712345678', "this is test from python package")
```
To send a scheduled quick sms :
```
message.send_quick_smartlink_sms(
'254712345678', "this is test from python package",scheduleTime = '2023-09-16 13:24')
```
## Group SMS
1. To send message to a group:
```
message.send_group_sms("group name","message")
```
2. To send a scheduled group sms
```
message.send_group_scheduled_sms("group name","message","scheduledTime eg 2023-09-16 13:24")
```
## Delivery Status
1. Get delivery status by transaction ID:
```
message.delivery_status_by_transactionid("transactionid: int")
```
2. Get message delivery report of a particular day:
```
message.delivery_status_by_day("date")
```
3. Get overal delivery report summary:
```
message.delivery_status_by_summary()
```
## Sender ID
to get your sender Id use :
```
res = message.get_senderID()
print(res.text)
```
## Groups
1. To create a group:
```
message.create_group("groupname")
```
2. To get all the groups:
```
message.get_groups()
```
3. To update a group:
```
message.update_group("newgroupname","groupid")
```
## Contacts
This are teh contacts that will be available in the specified groups.
1. To create conntacts:
```
message.create_contact("contact name","mobile number","group id")
```
2. To update contact:
```
message.update_contact("contact name","mobile number","group id")
```
3. To get all the contacts in a group:
```
message.get_contact("group name")
```
| zettatel | /zettatel-0.1.3.1.tar.gz/zettatel-0.1.3.1/README.md | README.md |
// Coverage.py HTML report browser code.
/*jslint browser: true, sloppy: true, vars: true, plusplus: true, maxerr: 50, indent: 4 */
/*global coverage: true, document, window, $ */
coverage = {};
// General helpers
function debounce(callback, wait) {
let timeoutId = null;
return function(...args) {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => {
callback.apply(this, args);
}, wait);
};
};
function checkVisible(element) {
const rect = element.getBoundingClientRect();
const viewBottom = Math.max(document.documentElement.clientHeight, window.innerHeight);
const viewTop = 30;
return !(rect.bottom < viewTop || rect.top >= viewBottom);
}
function on_click(sel, fn) {
const elt = document.querySelector(sel);
if (elt) {
elt.addEventListener("click", fn);
}
}
// Helpers for table sorting
function getCellValue(row, column = 0) {
const cell = row.cells[column]
if (cell.childElementCount == 1) {
const child = cell.firstElementChild
if (child instanceof HTMLTimeElement && child.dateTime) {
return child.dateTime
} else if (child instanceof HTMLDataElement && child.value) {
return child.value
}
}
return cell.innerText || cell.textContent;
}
function rowComparator(rowA, rowB, column = 0) {
let valueA = getCellValue(rowA, column);
let valueB = getCellValue(rowB, column);
if (!isNaN(valueA) && !isNaN(valueB)) {
return valueA - valueB
}
return valueA.localeCompare(valueB, undefined, {numeric: true});
}
function sortColumn(th) {
// Get the current sorting direction of the selected header,
// clear state on other headers and then set the new sorting direction
const currentSortOrder = th.getAttribute("aria-sort");
[...th.parentElement.cells].forEach(header => header.setAttribute("aria-sort", "none"));
if (currentSortOrder === "none") {
th.setAttribute("aria-sort", th.dataset.defaultSortOrder || "ascending");
} else {
th.setAttribute("aria-sort", currentSortOrder === "ascending" ? "descending" : "ascending");
}
const column = [...th.parentElement.cells].indexOf(th)
// Sort all rows and afterwards append them in order to move them in the DOM
Array.from(th.closest("table").querySelectorAll("tbody tr"))
.sort((rowA, rowB) => rowComparator(rowA, rowB, column) * (th.getAttribute("aria-sort") === "ascending" ? 1 : -1))
.forEach(tr => tr.parentElement.appendChild(tr) );
}
// Find all the elements with data-shortcut attribute, and use them to assign a shortcut key.
coverage.assign_shortkeys = function () {
document.querySelectorAll("[data-shortcut]").forEach(element => {
document.addEventListener("keypress", event => {
if (event.target.tagName.toLowerCase() === "input") {
return; // ignore keypress from search filter
}
if (event.key === element.dataset.shortcut) {
element.click();
}
});
});
};
// Create the events for the filter box.
coverage.wire_up_filter = function () {
// Cache elements.
const table = document.querySelector("table.index");
const table_body_rows = table.querySelectorAll("tbody tr");
const no_rows = document.getElementById("no_rows");
// Observe filter keyevents.
document.getElementById("filter").addEventListener("input", debounce(event => {
// Keep running total of each metric, first index contains number of shown rows
const totals = new Array(table.rows[0].cells.length).fill(0);
// Accumulate the percentage as fraction
totals[totals.length - 1] = { "numer": 0, "denom": 0 };
// Hide / show elements.
table_body_rows.forEach(row => {
if (!row.cells[0].textContent.includes(event.target.value)) {
// hide
row.classList.add("hidden");
return;
}
// show
row.classList.remove("hidden");
totals[0]++;
for (let column = 1; column < totals.length; column++) {
// Accumulate dynamic totals
cell = row.cells[column]
if (column === totals.length - 1) {
// Last column contains percentage
const [numer, denom] = cell.dataset.ratio.split(" ");
totals[column]["numer"] += parseInt(numer, 10);
totals[column]["denom"] += parseInt(denom, 10);
} else {
totals[column] += parseInt(cell.textContent, 10);
}
}
});
// Show placeholder if no rows will be displayed.
if (!totals[0]) {
// Show placeholder, hide table.
no_rows.style.display = "block";
table.style.display = "none";
return;
}
// Hide placeholder, show table.
no_rows.style.display = null;
table.style.display = null;
const footer = table.tFoot.rows[0];
// Calculate new dynamic sum values based on visible rows.
for (let column = 1; column < totals.length; column++) {
// Get footer cell element.
const cell = footer.cells[column];
// Set value into dynamic footer cell element.
if (column === totals.length - 1) {
// Percentage column uses the numerator and denominator,
// and adapts to the number of decimal places.
const match = /\.([0-9]+)/.exec(cell.textContent);
const places = match ? match[1].length : 0;
const { numer, denom } = totals[column];
cell.dataset.ratio = `${numer} ${denom}`;
// Check denom to prevent NaN if filtered files contain no statements
cell.textContent = denom
? `${(numer * 100 / denom).toFixed(places)}%`
: `${(100).toFixed(places)}%`;
} else {
cell.textContent = totals[column];
}
}
}));
// Trigger change event on setup, to force filter on page refresh
// (filter value may still be present).
document.getElementById("filter").dispatchEvent(new Event("input"));
};
coverage.INDEX_SORT_STORAGE = "COVERAGE_INDEX_SORT_2";
// Loaded on index.html
coverage.index_ready = function () {
coverage.assign_shortkeys();
coverage.wire_up_filter();
document.querySelectorAll("[data-sortable] th[aria-sort]").forEach(
th => th.addEventListener("click", e => sortColumn(e.target))
);
// Look for a localStorage item containing previous sort settings:
const stored_list = localStorage.getItem(coverage.INDEX_SORT_STORAGE);
if (stored_list) {
const {column, direction} = JSON.parse(stored_list);
const th = document.querySelector("[data-sortable]").tHead.rows[0].cells[column];
th.setAttribute("aria-sort", direction === "ascending" ? "descending" : "ascending");
th.click()
}
// Watch for page unload events so we can save the final sort settings:
window.addEventListener("unload", function () {
const th = document.querySelector('[data-sortable] th[aria-sort="ascending"], [data-sortable] [aria-sort="descending"]');
if (!th) {
return;
}
localStorage.setItem(coverage.INDEX_SORT_STORAGE, JSON.stringify({
column: [...th.parentElement.cells].indexOf(th),
direction: th.getAttribute("aria-sort"),
}));
});
on_click(".button_prev_file", coverage.to_prev_file);
on_click(".button_next_file", coverage.to_next_file);
on_click(".button_show_hide_help", coverage.show_hide_help);
};
// -- pyfile stuff --
coverage.LINE_FILTERS_STORAGE = "COVERAGE_LINE_FILTERS";
coverage.pyfile_ready = function () {
// If we're directed to a particular line number, highlight the line.
var frag = location.hash;
if (frag.length > 2 && frag[1] === 't') {
document.querySelector(frag).closest(".n").classList.add("highlight");
coverage.set_sel(parseInt(frag.substr(2), 10));
} else {
coverage.set_sel(0);
}
on_click(".button_toggle_run", coverage.toggle_lines);
on_click(".button_toggle_mis", coverage.toggle_lines);
on_click(".button_toggle_exc", coverage.toggle_lines);
on_click(".button_toggle_par", coverage.toggle_lines);
on_click(".button_next_chunk", coverage.to_next_chunk_nicely);
on_click(".button_prev_chunk", coverage.to_prev_chunk_nicely);
on_click(".button_top_of_page", coverage.to_top);
on_click(".button_first_chunk", coverage.to_first_chunk);
on_click(".button_prev_file", coverage.to_prev_file);
on_click(".button_next_file", coverage.to_next_file);
on_click(".button_to_index", coverage.to_index);
on_click(".button_show_hide_help", coverage.show_hide_help);
coverage.filters = undefined;
try {
coverage.filters = localStorage.getItem(coverage.LINE_FILTERS_STORAGE);
} catch(err) {}
if (coverage.filters) {
coverage.filters = JSON.parse(coverage.filters);
}
else {
coverage.filters = {run: false, exc: true, mis: true, par: true};
}
for (cls in coverage.filters) {
coverage.set_line_visibilty(cls, coverage.filters[cls]);
}
coverage.assign_shortkeys();
coverage.init_scroll_markers();
coverage.wire_up_sticky_header();
// Rebuild scroll markers when the window height changes.
window.addEventListener("resize", coverage.build_scroll_markers);
};
coverage.toggle_lines = function (event) {
const btn = event.target.closest("button");
const category = btn.value
const show = !btn.classList.contains("show_" + category);
coverage.set_line_visibilty(category, show);
coverage.build_scroll_markers();
coverage.filters[category] = show;
try {
localStorage.setItem(coverage.LINE_FILTERS_STORAGE, JSON.stringify(coverage.filters));
} catch(err) {}
};
coverage.set_line_visibilty = function (category, should_show) {
const cls = "show_" + category;
const btn = document.querySelector(".button_toggle_" + category);
if (btn) {
if (should_show) {
document.querySelectorAll("#source ." + category).forEach(e => e.classList.add(cls));
btn.classList.add(cls);
}
else {
document.querySelectorAll("#source ." + category).forEach(e => e.classList.remove(cls));
btn.classList.remove(cls);
}
}
};
// Return the nth line div.
coverage.line_elt = function (n) {
return document.getElementById("t" + n)?.closest("p");
};
// Set the selection. b and e are line numbers.
coverage.set_sel = function (b, e) {
// The first line selected.
coverage.sel_begin = b;
// The next line not selected.
coverage.sel_end = (e === undefined) ? b+1 : e;
};
coverage.to_top = function () {
coverage.set_sel(0, 1);
coverage.scroll_window(0);
};
coverage.to_first_chunk = function () {
coverage.set_sel(0, 1);
coverage.to_next_chunk();
};
coverage.to_prev_file = function () {
window.location = document.getElementById("prevFileLink").href;
}
coverage.to_next_file = function () {
window.location = document.getElementById("nextFileLink").href;
}
coverage.to_index = function () {
location.href = document.getElementById("indexLink").href;
}
coverage.show_hide_help = function () {
const helpCheck = document.getElementById("help_panel_state")
helpCheck.checked = !helpCheck.checked;
}
// Return a string indicating what kind of chunk this line belongs to,
// or null if not a chunk.
coverage.chunk_indicator = function (line_elt) {
const classes = line_elt?.className;
if (!classes) {
return null;
}
const match = classes.match(/\bshow_\w+\b/);
if (!match) {
return null;
}
return match[0];
};
coverage.to_next_chunk = function () {
const c = coverage;
// Find the start of the next colored chunk.
var probe = c.sel_end;
var chunk_indicator, probe_line;
while (true) {
probe_line = c.line_elt(probe);
if (!probe_line) {
return;
}
chunk_indicator = c.chunk_indicator(probe_line);
if (chunk_indicator) {
break;
}
probe++;
}
// There's a next chunk, `probe` points to it.
var begin = probe;
// Find the end of this chunk.
var next_indicator = chunk_indicator;
while (next_indicator === chunk_indicator) {
probe++;
probe_line = c.line_elt(probe);
next_indicator = c.chunk_indicator(probe_line);
}
c.set_sel(begin, probe);
c.show_selection();
};
coverage.to_prev_chunk = function () {
const c = coverage;
// Find the end of the prev colored chunk.
var probe = c.sel_begin-1;
var probe_line = c.line_elt(probe);
if (!probe_line) {
return;
}
var chunk_indicator = c.chunk_indicator(probe_line);
while (probe > 1 && !chunk_indicator) {
probe--;
probe_line = c.line_elt(probe);
if (!probe_line) {
return;
}
chunk_indicator = c.chunk_indicator(probe_line);
}
// There's a prev chunk, `probe` points to its last line.
var end = probe+1;
// Find the beginning of this chunk.
var prev_indicator = chunk_indicator;
while (prev_indicator === chunk_indicator) {
probe--;
if (probe <= 0) {
return;
}
probe_line = c.line_elt(probe);
prev_indicator = c.chunk_indicator(probe_line);
}
c.set_sel(probe+1, end);
c.show_selection();
};
// Returns 0, 1, or 2: how many of the two ends of the selection are on
// the screen right now?
coverage.selection_ends_on_screen = function () {
if (coverage.sel_begin === 0) {
return 0;
}
const begin = coverage.line_elt(coverage.sel_begin);
const end = coverage.line_elt(coverage.sel_end-1);
return (
(checkVisible(begin) ? 1 : 0)
+ (checkVisible(end) ? 1 : 0)
);
};
coverage.to_next_chunk_nicely = function () {
if (coverage.selection_ends_on_screen() === 0) {
// The selection is entirely off the screen:
// Set the top line on the screen as selection.
// This will select the top-left of the viewport
// As this is most likely the span with the line number we take the parent
const line = document.elementFromPoint(0, 0).parentElement;
if (line.parentElement !== document.getElementById("source")) {
// The element is not a source line but the header or similar
coverage.select_line_or_chunk(1);
} else {
// We extract the line number from the id
coverage.select_line_or_chunk(parseInt(line.id.substring(1), 10));
}
}
coverage.to_next_chunk();
};
coverage.to_prev_chunk_nicely = function () {
if (coverage.selection_ends_on_screen() === 0) {
// The selection is entirely off the screen:
// Set the lowest line on the screen as selection.
// This will select the bottom-left of the viewport
// As this is most likely the span with the line number we take the parent
const line = document.elementFromPoint(document.documentElement.clientHeight-1, 0).parentElement;
if (line.parentElement !== document.getElementById("source")) {
// The element is not a source line but the header or similar
coverage.select_line_or_chunk(coverage.lines_len);
} else {
// We extract the line number from the id
coverage.select_line_or_chunk(parseInt(line.id.substring(1), 10));
}
}
coverage.to_prev_chunk();
};
// Select line number lineno, or if it is in a colored chunk, select the
// entire chunk
coverage.select_line_or_chunk = function (lineno) {
var c = coverage;
var probe_line = c.line_elt(lineno);
if (!probe_line) {
return;
}
var the_indicator = c.chunk_indicator(probe_line);
if (the_indicator) {
// The line is in a highlighted chunk.
// Search backward for the first line.
var probe = lineno;
var indicator = the_indicator;
while (probe > 0 && indicator === the_indicator) {
probe--;
probe_line = c.line_elt(probe);
if (!probe_line) {
break;
}
indicator = c.chunk_indicator(probe_line);
}
var begin = probe + 1;
// Search forward for the last line.
probe = lineno;
indicator = the_indicator;
while (indicator === the_indicator) {
probe++;
probe_line = c.line_elt(probe);
indicator = c.chunk_indicator(probe_line);
}
coverage.set_sel(begin, probe);
}
else {
coverage.set_sel(lineno);
}
};
coverage.show_selection = function () {
// Highlight the lines in the chunk
document.querySelectorAll("#source .highlight").forEach(e => e.classList.remove("highlight"));
for (let probe = coverage.sel_begin; probe < coverage.sel_end; probe++) {
coverage.line_elt(probe).querySelector(".n").classList.add("highlight");
}
coverage.scroll_to_selection();
};
coverage.scroll_to_selection = function () {
// Scroll the page if the chunk isn't fully visible.
if (coverage.selection_ends_on_screen() < 2) {
const element = coverage.line_elt(coverage.sel_begin);
coverage.scroll_window(element.offsetTop - 60);
}
};
coverage.scroll_window = function (to_pos) {
window.scroll({top: to_pos, behavior: "smooth"});
};
coverage.init_scroll_markers = function () {
// Init some variables
coverage.lines_len = document.querySelectorAll('#source > p').length;
// Build html
coverage.build_scroll_markers();
};
coverage.build_scroll_markers = function () {
const temp_scroll_marker = document.getElementById('scroll_marker')
if (temp_scroll_marker) temp_scroll_marker.remove();
// Don't build markers if the window has no scroll bar.
if (document.body.scrollHeight <= window.innerHeight) {
return;
}
const marker_scale = window.innerHeight / document.body.scrollHeight;
const line_height = Math.min(Math.max(3, window.innerHeight / coverage.lines_len), 10);
let previous_line = -99, last_mark, last_top;
const scroll_marker = document.createElement("div");
scroll_marker.id = "scroll_marker";
document.getElementById('source').querySelectorAll(
'p.show_run, p.show_mis, p.show_exc, p.show_exc, p.show_par'
).forEach(element => {
const line_top = Math.floor(element.offsetTop * marker_scale);
const line_number = parseInt(element.querySelector(".n a").id.substr(1));
if (line_number === previous_line + 1) {
// If this solid missed block just make previous mark higher.
last_mark.style.height = `${line_top + line_height - last_top}px`;
} else {
// Add colored line in scroll_marker block.
last_mark = document.createElement("div");
last_mark.id = `m${line_number}`;
last_mark.classList.add("marker");
last_mark.style.height = `${line_height}px`;
last_mark.style.top = `${line_top}px`;
scroll_marker.append(last_mark);
last_top = line_top;
}
previous_line = line_number;
});
// Append last to prevent layout calculation
document.body.append(scroll_marker);
};
coverage.wire_up_sticky_header = function () {
const header = document.querySelector('header');
const header_bottom = (
header.querySelector('.content h2').getBoundingClientRect().top -
header.getBoundingClientRect().top
);
function updateHeader() {
if (window.scrollY > header_bottom) {
header.classList.add('sticky');
} else {
header.classList.remove('sticky');
}
}
window.addEventListener('scroll', updateHeader);
updateHeader();
};
document.addEventListener("DOMContentLoaded", () => {
if (document.body.classList.contains("indexfile")) {
coverage.index_ready();
} else {
coverage.pyfile_ready();
}
}); | zettel | /zettel-0.0.0.post9000.tar.gz/zettel-0.0.0.post9000/htmlcov/coverage_html.js | coverage_html.js |
<img src="https://nextcloud.priteshtupe.com/s/DT2KJDTgTmQy5Rc/preview" alt="Zettel Merken Image">
<hr />
<p align="center"><strong>Supercharge your learning by combining two of the most revolutionary ideas in knowledge enhancement!</strong></p>
<hr />
<p align="center">
<img alt="GitHub tag (latest SemVer)" src="https://img.shields.io/github/v/tag/empat94/zettel-merken">
<a href="https://github.com/EMPAT94/zettel-merken/blob/main/LICENSE"><img alt="GitHub license" src="https://img.shields.io/github/license/EMPAT94/zettel-merken"></a>
<a href="https://github.com/EMPAT94/zettel-merken/issues"><img alt="GitHub issues" src="https://img.shields.io/github/issues/EMPAT94/zettel-merken"></a>
<img alt="GitHub last commit" src="https://img.shields.io/github/last-commit/empat94/zettel-merken">
<br /> <br />
# Introduction
Zettel stands for "note" and Merken stands for "remember" in German. A literal translation would imply "Remember your notes", but that is an overly simplistic definition of what the title stands for.
To be precise, Zettel Merken is a fusion of two impactful ideas in the field of knowledge management and learning enhancement: "Zettelkasten" and "Spaced Repetition".
## What is Zettelkasten?
The [Wikipedia article](https://en.wikipedia.org/wiki/Zettelkasten) defines zettelkasten as "The zettelkasten is a system of note-taking and personal knowledge management used in research and study".
<br />
<div align="center">
<a title="David B. Clear, CC BY-SA 4.0 <https://creativecommons.org/licenses/by-sa/4.0>, via Wikimedia Commons" href="https://commons.wikimedia.org/wiki/File:Zettelkasten_paper_schematic.png"><img width="512" alt="Zettelkasten paper schematic" src="https://upload.wikimedia.org/wikipedia/commons/thumb/1/1a/Zettelkasten_paper_schematic.png/512px-Zettelkasten_paper_schematic.png"></a>
</div>
<br />
[zettelkasten.de](https://zettelkasten.de/introduction/) is a wonderful little site that is all about, well, zettelkasten. Do read the [introduction](https://zettelkasten.de/introduction/). To pick an excerpt from there:
> A Zettelkasten is a personal tool for thinking and writing. [...] The difference to other systems is that you create a web of thoughts instead of notes of arbitrary size and form, and emphasize connection, not a collection.
If I had to explain the concept to someone in a hurry, I'd say: Zettelkasten = Mind Map + Flash Cards
Of course, it is _not_ entirely either, so I would recommend following the links above for a more detailed understanding.
### How I use Zettelkasten
I take notes for _everything_! From doing research for my web novels to learning new languages, from my transaction history to ongoing projects, suffice to say I have a _lot_ of notes. However, I have come to realize that not all my notes are highly connected. Rather, a collection of notes is usually extremely cohesive with one another but largely decoupled from the rest. So I follow a sort-of watered-down system like so:
0. One single folder called "notes"
1. An index (No direct notes made here, only links), usually named "index.md".
2. A "hub" for each topic. Imagine a hub as a collection (like a notebook or a drawer). One hub usually points to one large topic.
3. A "zettel" for each atomic piece of info. All zettels for a topic are linked into the hub and are stored in a folder usually named after the same.
That's it! To expand on the above, here is a sample of my current notes directory:
```sh
~/Notes
├── index.md
├── books-and-articles.md
├── books-and-articles
│ ├── atomic-habits.md
│ └── ledger-accounting.md
├── code-notes.md
├── code-notes
│ ├── python.md
│ └── vim.md
├── learning-french.md
├── learning-french
│ ├── basics-1.1.md
│ ├── basics-1.2.md
│ └── basics-1.3.md
├── transactions.md
└── transactions
├── 01-2022.md
└── 02-2022.md
```
As you can see above, I have hubs after each topic: zettel-merken, books-and-articles, learning-french, etc. Each hub has a file.md and folder with the same name. I take all my notes in neovim in markdown format No special plugins, just a couple of functions and mapping. See wiki.
Thus, my `index.md` will look like:
```markdown
# INDEX
- [Learning French](./learning-french.md)
```
and my `learning-french.md`:
```markdown
# Learning French
- [Basics 1.1](./learning-french/basics-1.1.md)
- [Basics 1.2](./learning-french/basics-1.2.md)
- [Basics 1.3](./learning-french/basics-1.3.md)
```
Concerning zettels, I try to have them in an easily digestible format. Each zettels has a microscopic focus on the information it is trying to convey. That is - all the content inside a zettel must directly relate to a single matter or flow in one direction. The size of the file is irrelevant, although I try to keep it short and simple.
For example, `basics-1.1` might look like:
```markdown
# Basic 1.1
## Level 0
- un = a (sounds: un)
- et = and (sounds: ae)
- un chat = a cat (sounds: un shaa)
- un homme = a man (sounds: un oum)
- un garcon = a boy (sounds: un gars-on)
- un chat et un homme = A cat and a man
```
Also, I _try_ to avoid more than one layer of nesting below the "notes" folder but in some cases, it is inevitable. However, there should never be a need to go beyond two layers.
After following the above system consistently for a few months, you'll have a decent-sized collection of notes all linked together in a proper structure. That being said, simply "collecting" notes is never going to help you learn in the long term. That is where the Spaced Repetition comes in!
## What is Spaced Repetition?
Excerpt from [Wikipedia article](https://en.wikipedia.org/wiki/Spaced_repetition):
> The basis for spaced repetition research was laid by Hermann Ebbinghaus, who suggested that information loss over time follows a forgetting curve, but that forgetting could be reset with repetition based on active recall.
<br />
<div align="center">
<a title="The original uploader was Icez at English Wikipedia., Public domain, via Wikimedia Commons" href="https://commons.wikimedia.org/wiki/File:ForgettingCurve.svg"><img style="background-color:white" width="256" alt="ForgettingCurve" src="https://upload.wikimedia.org/wikipedia/commons/thumb/4/4e/ForgettingCurve.svg/256px-ForgettingCurve.svg.png"></a>
</div>
<br />
Excerpt from [e-student.org](https://e-student.org/spaced-repetition/):
> Spaced repetition is a memory technique that involves reviewing and recalling information at optimal spacing intervals until the information is learned at a sufficient level.
It is quite difficult to manually track hundreds of notes and review a set everyday. You'd have to keep logs of when each topic was visited, how many repetitions were completed, when the next review will be and so on. Quite cumbersome!
That is were Zettel Merken comes into play. Not only does this program keep track of your every note and its schedule, it also automatically emails notes that are due for review for the day! How awesome is that? It is quite easy to use too!
## Setup
**_NOTE: Code was written in and tested on Manjaro Linux (kernel 5.18) with Python 3.10 (compatible with 3.9)_**
1. Install
```shell
python -m pip install zettelmerken
```
2. Configure
```shell
python -m zettelmerken --config
```
Create a `config.json` in either `~/.config/zettel_merken/` or `~/zettel_merken`, and open in default editor.
3. Initialize
```shell
python -m zettelmerken --init
```
Create systemd units to exectute zettelmerken on a daily basis.
- Help
```shell
python -m zettelmerken --help
```
## TODOs
### v0.2
- [ ] Add slack webhook alternative to email
- [ ] Add a wiki
### v0.3
- [ ] MacOS Support
## Maybes
- [ ] config.toml instead of config.json?
- [ ] Windows Support?
- [ ] Per-note schedule?
- [ ] Docker Image?
| zettelmerken | /zettelmerken-0.1.4.tar.gz/zettelmerken-0.1.4/README.md | README.md |
# Zettels
Zettels is a command line tool implementing Niklas Luhmann's system of a
"Zettelkasten".
# Anouncement: Reimplementation
This implementation of Zettels is no longer actively developed. Instead, I
chose to reimplement Zettels from scratch in Rust.
While doing so, I added a lot of features and separated the command line
interface from the backend, which is now a library called `libzettels`,
sporting an API that can be used to easily build other user interfaces.
# Check the reimplementation out:
## 1. Zettels - Command line tool
- [Repo](https://gitlab.com/sthesing/zettels)
- [crates.io](https://crates.io/crates/zettels)
## 2. Libzettels - Backend
- [Repo](https://gitlab.com/sthesing/libzettels)
- [crates.io](https://crates.io/crates/libzettels)
# Where is the old README?
- [OLD-README.md](OLD-README.md)
| zettels | /zettels-0.7.0-py3-none-any.whl/zettels-0.7.0.dist-info/DESCRIPTION.rst | DESCRIPTION.rst |
# zettlekasten
Software that try to implement a simple zettlekasten coded in Python.
## Kesako?!
> The Zettelkasten principles
>
> A Zettelkasten is a phenomenal tool for storing and organizing your
> knowledge, extending your> memory, generating new connections
> between ideas, and increasing your writing output. However, to make
> the most of a Zettelkasten, you should follow some key principles.
>
> 1. The principle of atomicity: The term was coined by Christian
> Tietze. It means that each note should contain one idea and one
> idea only. This makes it possible to link ideas with a lase
> focus.
>
> 2. The principle of autonomy: Each note should be autonomous,
> meaning it should be self-contained and comprehensible on its
> own. This allows notes to be moved, processed, separated, and
> concatenated independently of its neighbors. It also ensures that
> notes remain useful even if the original source of information
> disappears.
>
> 3. Always link your notes: Whenever you add a note, make sure to
> link it to already existing notes. Avoid notes that are
> disconnected from other notes. As Luhmann himself put it, “each
> note is just an element that derives its quality from the network
> of links in the system. A note that is not connected to the
> network will be lost, will be forgotten by the Zettelkasten”
> (original in German).
>
> 4. Explain why you’re linking notes: Whenever you are connecting two
> notes by a link, make sure to briefly explain why you are linking
> them. Otherwise, years down the road when you revisit your notes,
> you may have no idea why you connected them.
>
> 5. Use your own words: Don’t copy and paste. If you come across an
> interesting idea and want to add it to your Zettelkasten, you
> must express that idea with your own words, in a way that you’ll
> be sure to understand years later. Don’t turn your Zettelkasten
> into a dump of copy-and-pasted information.
>
> 6. Keep references: Always add references to your notes so that you
> know where you got an idea from. This prevents plagiarism and
> makes it easy for you to revisit the original source later on.
>
> 7. Add your own thoughts to the Zettelkasten: If you have thoughts
> of your own, add them to the Zettelkasten as notes while keeping
> in mind the principle of atomicity, autonomy, and the need for
> linking.
>
> 8. Don’t worry about structure: Don’t worry about putting notes in
> neat folders or into unique preconceived categories. As Schmidt
> put it, in a Zettelkasten “there are no privileged positions” and
> “there is no top and no bottom.” The organization develops
> organically.
>
> 9. Add connection notes: As you begin to see connections among
> seemingly random notes, create connection notes, that is,
> specific notes whose purpose is to link together other notes and
> explain their relationship.
>
> 10. Add outline notes: As ideas begin to coalesce into themes,
> create outline notes. An outline note is a note that simply
> contains a sequence of links to other notes, putting those other
> notes into a particular order to create a story, narrative, or
> argument.
>
> 11. Never delete: Don’t delete old notes. Instead, link to new notes
> that explain what’s wrong with the old ones. In that way, your
> Zettelkasten will reflect how your thinking has evolved over
> time, which will prevent hindsight bias. Moreover, if you don’t
> delete, you might revisit old ideas that may turn out to be
> correct after all.
>
> 12. Add notes without fear: You can never have too much information
> in your Zettelkasten. At worst, you’ll add notes that won’t be
> of immediate use. But adding more notes will never break your
> Zettelkasten or interfere with its proper operation. Remember,
> Luhmann had 90,000 notes in his Zettelkasten!
>
> https://writingcooperative.com/zettelkasten-how-one-german-scholar-was-so-freakishly-productive-997e4e0ca125
| zettlekasten | /zettlekasten-0.0.2.tar.gz/zettlekasten-0.0.2/README.md | README.md |
Introduction
============
zettwerk.clickmap integrates a clickmap/heatmap tool into Plone. These tools are for visualisation of user clicks on the page. So you can see, what part of the pages might be more interesting for your visitors, and which are not. Some good known tracking tools are offering the same, but this one adds no external url, cause it handles all to collect and show the clicks.
You can selective enable or disalbe the content type objects which gets logged and view the results in an overlay image.
Things to know
==============
The concept works best, if the page uses a fixed width layout. But it also tries to work with variable width layouts. To handle this, you must setup the tool to a given "reference" width, where all clicks gets transformed to. Use the plone control panel to do so, and read the given comments.
It is also important to know, that the control panel gui gives you a list of all available objects, which you can choose the ones, you want to log. But this also means, that on big sites, the generation of the list might took a while. I am looking for an alternate widget to select the pages.
The storage of the clicks is handle by a BTree data structure. This might be ok for small to mid-sized pages, but there es no experiance with heavy load pages.
And the last side note: clicks of users with edit permissions of an object will never be logged, cause the inline edit gui won't suite to the generated output image/map.
Plone compatibility
===================
The actual work is only tested in Plone 4. There is also a Plone 3 version tagged in the svn which should work, but it is not tested with the latest versions. It also contains jquery-ui javascript resources, which are now removed in trunk (and so for Plone 4). (Anyone knows a lightwight drag'n'drop lib for jquery?)
Installation
============
Add zettwerk.clickmap to your buildout eggs. After running buildout and starting the instance, you can install Zettwerk Clickmap via portal_quickinstaller to your plone instance. Switch to the control panel and use the configlet to adapt the settings.
| zettwerk.clickmap | /zettwerk.clickmap-1.0.zip/zettwerk.clickmap-1.0/README.txt | README.txt |
from Products.CMFCore.utils import UniqueObject
from OFS.SimpleItem import SimpleItem
from Products.CMFCore.utils import getToolByName, _checkPermission
from Products.CMFCore.permissions import ModifyPortalContent
from zope.interface import implements
from Products.statusmessages.interfaces import IStatusMessage
from zettwerk.clickmap import clickmapMessageFactory as _
from zettwerk.clickmap.interfaces import IClickmap
from BTrees.IOBTree import IOBTree
from BTrees.OOBTree import OOBTree
from BTrees.IIBTree import IIBTree
from time import time
import drawer
from DateTime import DateTime
class ClickmapTool(UniqueObject, SimpleItem):
""" Tool that handles logging and viewing of clikcs """
implements(IClickmap)
id = 'portal_clickmap'
## internal attributes
logger = None
enabled = False
pages = [] ## the list of uids, which gets logged
output_width = 1024
output_height = 768
right_align_threshold = 0
def isThisPageDoLogging(self, uid, context):
"""
return True or False, to control the js functionality
edit users always gets False, cause the layout differs heavily from the
normal views.
"""
if _checkPermission(ModifyPortalContent, context):
return False
if uid in self.pages and self.enabled:
return True
return False
def getControlPanel(self):
""" some html for the overlay control in the output of the image. """
(yesterday, now) = self._getDefaultTimespan()
default_start = yesterday.strftime('%Y/%m/%d %H:%M')
default_end = now.strftime('%Y/%m/%d %H:%M')
returner = []
returner.append(u'<form id="clickmap_output_controller_form" style="float: left;">')
returner.append(u'<h5>%s</h5>' %(_(u"Clickmap output controller")))
returner.append(u'<input type="text" name="start" value="%s"> %s <br />' %(default_start, _(u"Start time")))
returner.append(u'<input type="text" name="end" value="%s"> %s <br />' %(default_end, _(u"End time")))
returner.append(u'<input type="submit" name="refresh" value="%s">' %(_(u"Refresh")))
returner.append(u'</form>')
returner.append(u'<br style="clear: both;" />')
return '\n'.join(returner)
def _getDefaultTimespan(self):
""" return the inital timestop for the output controller: 1 day """
now = DateTime()
yesterday = now - 1
return (yesterday, now)
def drawImage(self, uid, start=None, end=None):
""" read the requested data and generate the output image """
if not start or not end:
start, end = self._getDefaultTimespan()
else:
try:
start = DateTime(start)
end = DateTime(end)
except:
start, end = self._getDefaultTimespan()
## transform the DateTime objects to integer seconds
start = int(start)
end = int(end)
coords = self._getCoordsByUid(uid,
start=start,
end=end)
imagepath = drawer.do(self.output_width,
self.output_height,
coords)
r = self.REQUEST.RESPONSE
r.setHeader('content-type', 'image/png')
i = open(imagepath, 'rb')
b = i.read()
i.close()
r.write(b)
def _getCoordsByUid(self, uid, start, end):
""" """
uid_log = self.logger.get(uid)
if uid_log is not None:
return self._transformLogToCoordsToDraw(uid_log, start, end)
return [] ## fallback
def _transformLogToCoordsToDraw(self, log_data, start, end):
""" """
result = {}
for timestamp, coord in log_data.items(start,
end):
x, y = coord[0], coord[1]
key = (x, y)
value = result.get(key, 1)
result[key] = value + 1
return ((item[0], item[1], value) for item, value in result.items())
def initLogger(self, force=False):
"""
a wrapper for _initLogger, which checks some conditions.
@param force: boolean, to force reset the logger
@returns: redirects to the controlpanel form
"""
if self.logger is not None and force:
self.logger = None
if self.logger is None:
self._initLogger()
message = _(u"Clickmap logger initialized.")
IStatusMessage(self.REQUEST).addStatusMessage(message, type='info')
self.REQUEST.RESPONSE.redirect('%s/@@clickmap-controlpanel' \
%(getToolByName(self, 'portal_url')()))
return
return str(doInit)
def _initLogger(self):
""" reset the logger attribute """
self.logger = OOBTree()
def _get_uid_log(self, uid):
"""
return the IOBTree that holds the data of the given uid. If there is no
one for the requested uid, create it.
"""
if self.logger is None:
self._initLogger()
uid_log = self.logger.get(uid)
if uid_log is None:
uid_log = IOBTree()
self.logger[uid] = uid_log
return uid_log
def _remove_uid_from_log(self, uid):
"""
remove a logged page from the logger
"""
if self.logger.get(uid) is not None:
del self.logger[uid]
def _store_request(self, uid, log_data):
"""
store the request.
@param uid: the uid of the object to log
@param log_data: the IIBTree object to store
"""
uid_log = self._get_uid_log(uid)
uid_log[int(time())] = log_data
def clicker(self, uid, x, y, w):
"""
the parameters are stored transformed to the reference layout
"""
if w > self.output_width:
return "" ## sorry, we dont support this...
if x > self.right_align_threshold:
x += (self.output_width - w)
log_data = IIBTree([(0, x),
(1, y)])
self._store_request(uid,
log_data)
return "ok"
def debug_info(self):
"""
transform the logged data to readable data for debugging...
"""
result = {}
for uid, log in self.logger.items():
log_data = []
for timestamp, data in log.items():
log_data.append("%s: x -> %s | y -> %s" %(timestamp, data[0], data[1]))
result[uid] = log_data
import pprint
pprint.pprint(result)
return "see console output...." | zettwerk.clickmap | /zettwerk.clickmap-1.0.zip/zettwerk.clickmap-1.0/zettwerk/clickmap/ClickmapTool.py | ClickmapTool.py |
from zope.formlib import form
from plone.fieldsets.fieldsets import FormFieldsets
from zope.component import adapts
from zope.interface import implements
from Products.CMFDefault.formlib.schema import ProxyFieldProperty
from Products.CMFDefault.formlib.schema import SchemaAdapterBase
from Products.CMFPlone.interfaces import IPloneSiteRoot
from Products.CMFCore.utils import getToolByName
from Products.CMFPlone.utils import safe_unicode
from plone.app.controlpanel.form import ControlPanelForm
from zope.app.form.browser import MultiSelectWidget
from zope.app.form.browser import DisplayWidget
from zettwerk.clickmap import clickmapMessageFactory as _
from zettwerk.clickmap.interfaces import IClickmap, IClickmapSettings, IClickmapOutput
class ClickmapControlPanelAdapter(SchemaAdapterBase):
adapts(IPloneSiteRoot)
implements(IClickmap)
def __init__(self, context):
super(ClickmapControlPanelAdapter, self).__init__(context)
self.portal = context
clickmap_tool = getToolByName(self.portal, 'portal_clickmap')
self.context = clickmap_tool
output = ProxyFieldProperty(IClickmap['output'])
setup = ProxyFieldProperty(IClickmap['setup'])
reset = ProxyFieldProperty(IClickmap['reset'])
enabled = ProxyFieldProperty(IClickmap['enabled'])
pages = ProxyFieldProperty(IClickmap['pages'])
output_width = ProxyFieldProperty(IClickmap['output_width'])
right_align_threshold = ProxyFieldProperty(IClickmap['right_align_threshold'])
output_height = ProxyFieldProperty(IClickmap['output_height'])
def get_output_data(self):
""" read the log data from the tool and prepare for output """
logger = self.context.logger
if logger is None:
return []
uids = logger.keys()
catalog = getToolByName(self.portal, 'portal_catalog')
returner = []
for uid in uids:
uid_log = logger.get(uid)
brains = catalog(UID=uid)
## check for old log data
if not brains:
self.context._remove_uid_from_log(uid)
continue
brain = brains[0] ## uid is unique
returner.append({
'url': brain.getURL(),
'title': brain['Title'],
'clicks': len(uid_log)
})
return returner
class ListPagesMultiSelectWidget(MultiSelectWidget):
def __init__(self, field, request):
super(ListPagesMultiSelectWidget, self).__init__(
field, field.value_type.vocabulary, request
)
class JSSetupWidget(DisplayWidget):
""" integrate some js functionality, to setup the clickmap settings """
def __call__(self):
setup_description = u"""This tries to check, if your layout uses a variable or a fixed width.
Using a variable width, the current display witdh will be used as
reference. Then you should also check the right-align threshold."""
return u'<a href="javascript:clickmapSetup()">%s</a><br />' \
u'<div class="formHelp">%s</div>' %(_(u"Click here for automatical setup"),
_(setup_description))
class ResetWidget(DisplayWidget):
""" a link to call the reset routine of the tool """
def __call__(self):
return '<a href="javascript:confirmClickmapReset()">Click here</a> if you want to reset your already logged clicks.'
class OutputWidget(DisplayWidget):
""" list the logged pages as links to view the clickmap output """
def __call__(self):
adapter = self.context.context
returner = []
returner.append(u'<div class="formHelp">%s</div>' %(_("This list containes all available log data.")))
returner.append(u'<ul>')
for page in adapter.get_output_data():
returner.append(safe_unicode('<li><strong>%(title)s</strong>: view <a target="_blank" href="%(url)s?show_clickmap_output=true">authenticated</a> or view <a target="_blank" href="%(url)s/clickmap_anonym_view">anonymous</a> (Clicks: %(clicks)s)' %(page)))
returner.append(u'</ul>')
return u'\n'.join(returner)
settings = FormFieldsets(IClickmapSettings)
settings.id = 'settings'
settings.label = _(u'Settings')
output = FormFieldsets(IClickmapOutput)
output.id = 'output'
output.label = _(u'Output')
class ClickmapControlPanel(ControlPanelForm):
form_fields = FormFieldsets(settings, output)
form_fields['pages'].custom_widget = ListPagesMultiSelectWidget
form_fields['setup'].custom_widget = JSSetupWidget
form_fields['setup'].for_display = True
form_fields['reset'].custom_widget = ResetWidget
form_fields['reset'].for_display = True
form_fields['output'].custom_widget = OutputWidget
form_fields['output'].for_display = True
label = _(u"Zettwerk Clickmap")
description = _(u'Important: by changing the width, height or threshold settings, already logged clicks might be not suitable any more. You should then reset the log.') | zettwerk.clickmap | /zettwerk.clickmap-1.0.zip/zettwerk.clickmap-1.0/zettwerk/clickmap/browser/clickmap.py | clickmap.py |
(function(jq) {
jq.fn.saveClicks = function() {
$(this).bind('mousedown.clickmap', function(evt) {
var data = collectClickerData(evt);
jq.post(clickmap_tool_url+'/clicker', {
'x:int': data['x'],
'y:int': data['y'],
'w:int': data['w'],
'uid': clickmap_uid
});
});
};
jq.fn.stopSaveClicks = function() {
$(this).unbind('mousedown.clickmap');
};
})(jQuery);
function collectClickerData(evt) {
/*
collect the values, needed for the clicker call.
x: is the x position of the click relative from #visual-portal-wrapper
y: is the y position of the click relative from #visual-portal-wrapper
w: is the witdh (inclusive paddings and borders) from #visual-portal-wrapper
*/
var visual_reference = getVisualReference();
return {'x': parseInt(evt.pageX - visual_reference.offset()['left']),
'y': parseInt(evt.pageY - visual_reference.offset()['top']),
'w': visual_reference.outerWidth()};
}
function getVisualReference() {
/* all used coordinates are relative to a reference. */
return $('#visual-portal-wrapper');
}
function showClickmapOutput() {
var visual_reference = getVisualReference();
visual_reference.width(clickmap_output_width); // make the coords suitable
var src = clickmap_tool_url+'/drawImage';
src += '?uid='+clickmap_uid;
var pos = visual_reference.offset();
var styles = 'z-index: 100; left: '+pos['left']+'px; top: '+pos['top']+'px;';
styles += 'position: absolute; background-color: silver; display: none; border: 1px solid red';
var output_image_tag = '<img src="'+src+'" width="'+visual_reference.outerWidth()+'" />';
var controller_styles = 'z-index: 101; left: 300px; top: 0px; width: 300px; height=100px; padding: 3px; ';
controller_styles += 'position: absolute; background-color: silver; border: 1px solid orange';
var output_controller = '<div style="'+controller_styles+'" id="clickmap_output_controller"></div>';
visual_reference.append('<div style="'+styles+'" id="clickmap_output">'+output_image_tag+output_controller+'</div>');
$('#clickmap_output').fadeTo('slow',
0.0,
function() { $(this).show(); }
);
$('#clickmap_output').fadeTo('slow', 0.63);
$('#clickmap_output_controller').load(clickmap_tool_url+'/getControlPanel', {}, enableControlPanelForm);
}
function enableControlPanelForm() {
$('#clickmap_output_controller_form input[name=refresh]').click(function() {
var start = $('#clickmap_output_controller_form input[name=start]').val();
var end = $('#clickmap_output_controller_form input[name=end]').val();
if (start && end) {
var new_src = clickmap_tool_url+'/drawImage?uid='+clickmap_uid+'&start='+start+'&end='+end;
$('#clickmap_output').fadeTo('fast', 0.0);
$('#clickmap_output img').attr('src', new_src);
$('#clickmap_output').fadeTo('slow', 0.63);
} else {
alert ("Please enter some date");
}
return false;
});
}
function clickmapSetup() {
/*
we resize the windows viewport to check if the visual reference resizes also.
If so, then the page has a variable width and the right_align_threshold must be set.
Otherwise, the page uses a fixed width and the threshold must not be set.
*/
var current_window_width = window.outerWidth;
var visual_reference = getVisualReference();
var current_visual_reference_width = visual_reference.outerWidth();
window.resizeTo(current_visual_reference_width + 10,
window.outerHeight);
var is_constant_layout = current_visual_reference_width == visual_reference.outerWidth();
window.resizeTo(current_window_width,
window.outerHeight);
$('#form\\.output_width').val(visual_reference.outerWidth());
$('#form\\.output_height').val(window.outerHeight);
if (is_constant_layout) {
$('#form\\.right_align_threshold').val(0);
} else {
$('#form\\.right_align_threshold').val(Math.round(visual_reference.outerWidth() / 3 * 2));
}
}
function confirmClickmapReset() {
if (window.confirm('Are you sure?')) {
document.location.href = clickmap_tool_url+'/initLogger?force:bool=True';
}
}
$(document.body).ready(function() {
if (clickmap_uid != '') {
if (show_clickmap_output) {
showClickmapOutput();
}
else
if (clickmap_do)
$('#visual-portal-wrapper').saveClicks();
}
}); | zettwerk.clickmap | /zettwerk.clickmap-1.0.zip/zettwerk.clickmap-1.0/zettwerk/clickmap/browser/javascripts/clickmap.js | clickmap.js |
Introduction
============
zettwerk.fullcalendar integrates the jQuery FullCalendar into Plone 4.
Also check out zettwerk.ui for on-the-fly theming of the calendar and you plone site.
Use-Cases
=========
Basically this addon gives you a new view for Topics (and Folders) to display all event-like contenttypes with the jQuery Fullcalendar. Results from the Topic criteria which are not event-like CT´s will be ignored.
If you have developed you own event type it will be displayed as long as it implements the right interface or is based on ATEvent.
An Event will be 'all-day' if the starttime hour and minutes were left empty when the event was created.
All displayed events link to the corresponding object.
Time-Format
===========
Beginning with version 0.2.1 zettwerk.fullcalendar uses Plone site's preferred time format. It defaults to display a.m./p.m. which might not be so common in european contries. To change it, switch to the ZMI and click the portal_properties object. Then look for the site_properties and open it. Change the field 'localTimeOnlyFormat' to something more common like %H:%M.
Installation
============
Add zettwerk.fullcalendar to your buildout eggs. After running buildout and starting the instance, you can install Zettwerk Fullcalendar via portal_quickinstaller to your plone instance. zettwerk.fullcalendar requires Plone 4.
Usage
=====
Add a Topic anywhere on your site and set the criterias to your needs. All event-like results can now be displayed with the jQuery Fullcalendar by selecting the Calendar view in the Topic´s display menu. For Folders, just do the same: select the Calendar view and you are done. All event-like content objects will be shown.
Note
====
zettwerk.fullcalendar is out of the box ready to use zettwerk.ui to apply jquery.ui's css to the calendar view. There is only one problem with the ordering of the registered css in plone's portal_css (registry): if you installed zettwerk.ui after zettwerk.fullcalendar make sure to move the resource with id "++resource++jquery.fullcalendar/fullcalendar.css" to the bottom of all registered css files. You can do this by switching to the ZMI of you plone instance - click portal_css - search the id given above und use the arrows to move it down. At the end click "save".
| zettwerk.fullcalendar | /zettwerk.fullcalendar-0.3.1.zip/zettwerk.fullcalendar-0.3.1/README.txt | README.txt |
Introduction
============
This is a full-blown functional test. The emphasis here is on testing what
the user may input and see, and the system is largely tested as a black box.
We use PloneTestCase to set up this test as well, so we have a full Plone site
to play with. We *can* inspect the state of the portal, e.g. using
self.portal and self.folder, but it is often frowned upon since you are not
treating the system as a black box. Also, if you, for example, log in or set
roles using calls like self.setRoles(), these are not reflected in the test
browser, which runs as a separate session.
Being a doctest, we can tell a story here.
First, we must perform some setup. We use the testbrowser that is shipped
with Five, as this provides proper Zope 2 integration. Most of the
documentation, though, is in the underlying zope.testbrower package.
>>> from Products.Five.testbrowser import Browser
>>> browser = Browser()
>>> portal_url = self.portal.absolute_url()
The following is useful when writing and debugging testbrowser tests. It lets
us see all error messages in the error_log.
>>> self.portal.error_log._ignored_exceptions = ()
With that in place, we can go to the portal front page and log in. We will
do this using the default user from PloneTestCase:
>>> from Products.PloneTestCase.setup import portal_owner, default_password
>>> browser.open(portal_url)
We have the login portlet, so let's use that.
>>> browser.getControl(name='__ac_name').value = portal_owner
>>> browser.getControl(name='__ac_password').value = default_password
>>> browser.getControl(name='submit').click()
Here, we set the value of the fields on the login form and then simulate a
submit click.
We then test that we are still on the portal front page:
>>> browser.url == portal_url
True
And we ensure that we get the friendly logged-in message:
>>> "You are now logged in" in browser.contents
True
-*- extra stuff goes here -*-
| zettwerk.fullcalendar | /zettwerk.fullcalendar-0.3.1.zip/zettwerk.fullcalendar-0.3.1/zettwerk/fullcalendar/README.txt | README.txt |
from zope.i18nmessageid import MessageFactory
from zettwerk.fullcalendar import config
from Products.Archetypes import atapi
from Products.CMFCore import utils
# Define a message factory for when this product is internationalised.
# This will be imported with the special name "_" in most modules. Strings
# like _(u"message") will then be extracted by i18n tools for translation.
fullcalendarMessageFactory = MessageFactory('zettwerk.fullcalendar')
from AccessControl import allow_module
allow_module('zettwerk.fullcalendar.browser.calendarview')
def initialize(context):
"""Initializer called when used as a Zope 2 product.
This is referenced from configure.zcml. Regstrations as a "Zope 2 product"
is necessary for GenericSetup profiles to work, for example.
Here, we call the Archetypes machinery to register our content types
with Zope and the CMF.
"""
# Retrieve the content types that have been registered with Archetypes
# This happens when the content type is imported and the registerType()
# call in the content type's module is invoked. Actually, this happens
# during ZCML processing, but we do it here again to be explicit. Of
# course, even if we import the module several times, it is only run
# once.
content_types, constructors, ftis = atapi.process_types(
atapi.listTypes(config.PROJECTNAME),
config.PROJECTNAME)
# Now initialize all these content types. The initialization process takes
# care of registering low-level Zope 2 factories, including the relevant
# add-permission. These are listed in config.py. We use different
# permissions for each content type to allow maximum flexibility of who
# can add which content types, where. The roles are set up in rolemap.xml
# in the GenericSetup profile.
for atype, constructor in zip(content_types, constructors):
utils.ContentInit('%s: %s' % (config.PROJECTNAME, atype.portal_type),
content_types=(atype, ),
permission=config.ADD_PERMISSIONS[atype.portal_type],
extra_constructors=(constructor,),
).initialize(context) | zettwerk.fullcalendar | /zettwerk.fullcalendar-0.3.1.zip/zettwerk.fullcalendar-0.3.1/zettwerk/fullcalendar/__init__.py | __init__.py |
from zope.interface import implements, Interface
from zope.i18n import translate
from Products.Five import BrowserView
from Products.CMFCore.utils import getToolByName
from simplejson.encoder import JSONEncoder
from zettwerk.fullcalendar import fullcalendarMessageFactory as _
class ICalendarView(Interface):
"""
calendar view interface
"""
def getDefaultOptions():
""" build fullcalendar options dict var defaultCalendarOptions = {} """
def _encodeJSON(data):
""" encodes given data in json """
def _localizedWeekdays():
""" returns localized weekdays """
def _localizedWeekdaysShort():
""" returns localized weekdays short"""
def _localizedMonthNames():
""" returns localized month names """
def _localizedMonthNamesShort():
""" returns localized month names short"""
def _localizedNames():
""" return localized strings """
class CalendarView(BrowserView):
"""
calendar browser view that shows the calendar
"""
implements(ICalendarView)
def __init__(self, context, request):
self.context = context
self.request = request
self.preview = ''
@property
def portal_translation(self):
return getToolByName(self.context, 'translation_service')
@property
def site_properties(self):
return getToolByName(self.context, 'portal_properties').site_properties
@property
def portal(self):
return getToolByName(self.context, 'portal_url').getPortalObject()
def _localizedWeekdays(self):
""" returns localized weekdays """
ret = []
trans = self.portal_translation.translate
for i in range(7):
ret.append(trans(self.portal_translation.day_msgid(i),
domain='plonelocales',
context=self.context.REQUEST))
return ret
def _localizedWeekdaysShort(self):
""" returns localized weekdays short"""
ret = []
trans = self.portal_translation.translate
for i in range(7):
ret.append(trans(self.portal_translation.day_msgid(i, 's'),
domain='plonelocales',
context=self.context.REQUEST))
return ret
def _localizedMonthNames(self):
""" returns localized month names """
ret = []
trans = self.portal_translation.translate
for i in range(1, 13):
ret.append(trans(self.portal_translation.month_msgid(i),
domain='plonelocales',
context=self.context.REQUEST))
return ret
def _localizedMonthNamesShort(self):
""" returns localized month names short"""
ret = []
trans = self.portal_translation.translate
for i in range(1, 13):
ret.append(trans(self.portal_translation.month_msgid(i, 'a'),
domain='plonelocales',
context=self.context.REQUEST))
return ret
def _localizedNames(self):
""" return localized strings """
return {'localizedAllDay': translate(_(u'All day'),
context=self.request),
'localizedToday': translate(_(u'Today'),
context=self.request),
'localizedDay': translate(_(u'Day'),
context=self.request),
'localizedWeek': translate(_(u'Week'),
context=self.request),
'localizedMonth': translate(_(u'Month'),
context=self.request),
}
def _encodeJSON(self, data):
""" takes whats given and jsonfies it """
return JSONEncoder().encode(data)
def getDefaultOptions(self):
""" build fullcalendar options dict var defaultCalendarOptions = {} """
namesDict = self._localizedNames()
uiEnabled = False
try:
getToolByName(self.context, 'portal_ui_tool')
uiEnabled = True
except AttributeError:
pass
# Get the localTimeOnlyFormat from the Plone site properties,
# but default to 24h time if not found
# Then, convert it to the format that fullcalendar is expecting
# This strikes me as being hacky, but seems to work well.
try:
localTimeOnlyFormat = self.site_properties.localTimeOnlyFormat
except AttributeError:
localTimeOnlyFormat = "%H:%M"
fullCalendarTimeOnlyFormat = localTimeOnlyFormat.replace('%H', 'H') \
.replace('%M', 'mm') \
.replace('%I', 'h') \
.replace('%p', "t.'m'.") \
.replace('%S', 'ss')
defaultCalendarOptions = {
'preview': self.preview, # this is not a fullcalendar option!
'theme': uiEnabled,
'header': {'left': 'prev,next,today',
'center': 'title',
'right': 'month,agendaWeek,agendaDay'
},
'events': self.context.absolute_url() + '/events_view',
'allDayText': namesDict['localizedAllDay'],
'monthNames': self._localizedMonthNames(),
'monthNamesShort': self._localizedMonthNamesShort(),
'dayNames': self._localizedWeekdays(),
'dayNamesShort': self._localizedWeekdaysShort(),
'titleFormat': {'month': 'MMMM yyyy',
'week': "d.[ MMMM][ yyyy]{ - d. MMMM yyyy}",
'day': 'dddd, d. MMMM yyyy',
},
'columnFormat': {'month': 'dddd',
'week': 'dddd',
'day': ''
},
'axisFormat': fullCalendarTimeOnlyFormat,
'timeFormat':
{'': fullCalendarTimeOnlyFormat,
'agenda': '%s{ - %s}' % (fullCalendarTimeOnlyFormat,
fullCalendarTimeOnlyFormat)},
'firstDay': 1,
'buttonText': {'prev': ' ◄ ',
'next': ' ► ',
'prevYear': ' << ',
'nextYear': ' >> ',
'today': namesDict['localizedToday'],
'month': namesDict['localizedMonth'],
'week': namesDict['localizedWeek'],
'day': namesDict['localizedDay']
},
}
return self._encodeJSON(defaultCalendarOptions) | zettwerk.fullcalendar | /zettwerk.fullcalendar-0.3.1.zip/zettwerk.fullcalendar-0.3.1/zettwerk/fullcalendar/browser/calendarview.py | calendarview.py |
from zope.interface import implements, Interface
from Products.Five import BrowserView
from Products.CMFCore.utils import getToolByName
from DateTime import DateTime
from Products.CMFPlone.utils import normalizeString
from Products.ATContentTypes.interface.interfaces import ICalendarSupport
from Products.ATContentTypes.interface.topic import IATTopic
from Products.ATContentTypes.interface.folder import IATFolder
from simplejson.encoder import JSONEncoder
class IEventsView(Interface):
""" get events view interface """
def getEvents(start=None, end=None):
""" returns all object implementing ICalendarSupport and matching the
criterias """
def getJSONEvents(start=None, end=None):
""" returns all object implementing ICalendarSupport and matching the
criterias jsonfied """
def _encodeJSON(data):
""" encodes given data in json """
def _buildDict(brain):
""" builds a dict from a given brain """
class EventsView(BrowserView):
""" This view is used to collected the events, shown in the calendar. """
implements(IEventsView)
def __init__(self, context, request):
self.context = context
self.request = request
def __call__(self, *args, **kw):
start = self.request.get('start', None)
end = self.request.get('end', None)
return self.getJSONEvents(start, end)
@property
def portal_catalog(self):
return getToolByName(self.context, 'portal_catalog')
def getJSONEvents(self, start=None, end=None):
""" returns all object implementing ICalendarSupport and matching
the criterias """
return self._encodeJSON(self.getEvents(start, end))
def _encodeJSON(self, data):
""" takes whats given and jsonfies it """
return JSONEncoder().encode(data)
def getEvents(self, start=None, end=None):
""" searches the catalog for event like objects in the given
time frame """
query_func = self.portal_catalog.searchResults
if IATFolder.providedBy(self.context):
query_func = self.context.getFolderContents
elif IATTopic.providedBy(self.context) \
and self.context.buildQuery() is not None:
query_func = self.context.queryCatalog
query = {'object_provides': ICalendarSupport.__identifier__}
if start:
query['start'] = {'query': DateTime(int(start)), 'range': 'min'}
if end:
query['end'] = {'query': DateTime(int(end)), 'range': 'max'}
brains = query_func(query)
jret = []
for brain in brains:
jdict = self._buildDict(brain)
jret.append(jdict)
return jret
def _buildDict(self, brain=None):
""" builds a dict from the given brain, suitable for the fullcalendar
javascript """
jdict = {}
if brain:
allDay = False
if brain.start == brain.end:
allDay = True
jdict = {'title': brain.Title,
'start': brain.start.ISO(),
'end': brain.end.ISO(),
'allDay': allDay,
'url': brain.getURL(),
'className': ' '.join(['Subject_'+normalizeString(s) \
for s in brain.Subject])
}
return jdict | zettwerk.fullcalendar | /zettwerk.fullcalendar-0.3.1.zip/zettwerk.fullcalendar-0.3.1/zettwerk/fullcalendar/browser/eventsview.py | eventsview.py |
(function(t,e){function n(e){t.extend(!0,Ce,e)}function r(n,r,c){function u(t){ae?p()&&(S(),M(t)):f()}function f(){oe=r.theme?"ui":"fc",n.addClass("fc"),r.isRTL?n.addClass("fc-rtl"):n.addClass("fc-ltr"),r.theme&&n.addClass("ui-widget"),ae=t("<div class='fc-content' style='position:relative'/>").prependTo(n),ne=new a(ee,r),re=ne.render(),re&&n.prepend(re),y(r.defaultView),r.handleWindowResize&&t(window).resize(x),m()||v()}function v(){setTimeout(function(){!ie.start&&m()&&C()},0)}function h(){ie&&(te("viewDestroy",ie,ie,ie.element),ie.triggerEventDestroy()),t(window).unbind("resize",x),ne.destroy(),ae.remove(),n.removeClass("fc fc-rtl ui-widget")}function p(){return n.is(":visible")}function m(){return t("body").is(":visible")}function y(t){ie&&t==ie.name||D(t)}function D(e){he++,ie&&(te("viewDestroy",ie,ie,ie.element),Y(),ie.triggerEventDestroy(),G(),ie.element.remove(),ne.deactivateButton(ie.name)),ne.activateButton(e),ie=new Se[e](t("<div class='fc-view fc-view-"+e+"' style='position:relative'/>").appendTo(ae),ee),C(),$(),he--}function C(t){(!ie.start||t||ie.start>ge||ge>=ie.end)&&p()&&M(t)}function M(t){he++,ie.start&&(te("viewDestroy",ie,ie,ie.element),Y(),N()),G(),ie.render(ge,t||0),T(),$(),(ie.afterRender||A)(),_(),P(),te("viewRender",ie,ie,ie.element),ie.trigger("viewDisplay",de),he--,z()}function E(){p()&&(Y(),N(),S(),T(),F())}function S(){le=r.contentHeight?r.contentHeight:r.height?r.height-(re?re.height():0)-R(ae):Math.round(ae.width()/Math.max(r.aspectRatio,.5))}function T(){le===e&&S(),he++,ie.setHeight(le),ie.setWidth(ae.width()),he--,se=n.outerWidth()}function x(){if(!he)if(ie.start){var t=++ve;setTimeout(function(){t==ve&&!he&&p()&&se!=(se=n.outerWidth())&&(he++,E(),ie.trigger("windowResize",de),he--)},200)}else v()}function k(){N(),W()}function H(t){N(),F(t)}function F(t){p()&&(ie.setEventData(pe),ie.renderEvents(pe,t),ie.trigger("eventAfterAllRender"))}function N(){ie.triggerEventDestroy(),ie.clearEvents(),ie.clearEventData()}function z(){!r.lazyFetching||ue(ie.visStart,ie.visEnd)?W():F()}function W(){fe(ie.visStart,ie.visEnd)}function O(t){pe=t,F()}function L(t){H(t)}function _(){ne.updateTitle(ie.title)}function P(){var t=new Date;t>=ie.start&&ie.end>t?ne.disableButton("today"):ne.enableButton("today")}function q(t,n,r){ie.select(t,n,r===e?!0:r)}function Y(){ie&&ie.unselect()}function B(){C(-1)}function j(){C(1)}function I(){i(ge,-1),C()}function X(){i(ge,1),C()}function J(){ge=new Date,C()}function V(t,e,n){t instanceof Date?ge=d(t):g(ge,t,e,n),C()}function U(t,n,r){t!==e&&i(ge,t),n!==e&&s(ge,n),r!==e&&l(ge,r),C()}function Z(){return d(ge)}function G(){ae.css({width:"100%",height:ae.height(),overflow:"hidden"})}function $(){ae.css({width:"",height:"",overflow:""})}function Q(){return ie}function K(t,n){return n===e?r[t]:(("height"==t||"contentHeight"==t||"aspectRatio"==t)&&(r[t]=n,E()),e)}function te(t,n){return r[t]?r[t].apply(n||de,Array.prototype.slice.call(arguments,2)):e}var ee=this;ee.options=r,ee.render=u,ee.destroy=h,ee.refetchEvents=k,ee.reportEvents=O,ee.reportEventChange=L,ee.rerenderEvents=H,ee.changeView=y,ee.select=q,ee.unselect=Y,ee.prev=B,ee.next=j,ee.prevYear=I,ee.nextYear=X,ee.today=J,ee.gotoDate=V,ee.incrementDate=U,ee.formatDate=function(t,e){return w(t,e,r)},ee.formatDates=function(t,e,n){return b(t,e,n,r)},ee.getDate=Z,ee.getView=Q,ee.option=K,ee.trigger=te,o.call(ee,r,c);var ne,re,ae,oe,ie,se,le,ce,ue=ee.isFetchNeeded,fe=ee.fetchEvents,de=n[0],ve=0,he=0,ge=new Date,pe=[];g(ge,r.year,r.month,r.date),r.droppable&&t(document).bind("dragstart",function(e,n){var a=e.target,o=t(a);if(!o.parents(".fc").length){var i=r.dropAccept;(t.isFunction(i)?i.call(a,o):o.is(i))&&(ce=a,ie.dragStart(ce,e,n))}}).bind("dragstop",function(t,e){ce&&(ie.dragStop(ce,t,e),ce=null)})}function a(n,r){function a(){v=r.theme?"ui":"fc";var n=r.header;return n?h=t("<table class='fc-header' style='width:100%'/>").append(t("<tr/>").append(i("left")).append(i("center")).append(i("right"))):e}function o(){h.remove()}function i(e){var a=t("<td class='fc-header-"+e+"'/>"),o=r.header[e];return o&&t.each(o.split(" "),function(e){e>0&&a.append("<span class='fc-header-space'/>");var o;t.each(this.split(","),function(e,i){if("title"==i)a.append("<span class='fc-header-title'><h2> </h2></span>"),o&&o.addClass(v+"-corner-right"),o=null;else{var s;if(n[i]?s=n[i]:Se[i]&&(s=function(){u.removeClass(v+"-state-hover"),n.changeView(i)}),s){var l=r.theme?P(r.buttonIcons,i):null,c=P(r.buttonText,i),u=t("<span class='fc-button fc-button-"+i+" "+v+"-state-default'>"+(l?"<span class='fc-icon-wrap'><span class='ui-icon ui-icon-"+l+"'/>"+"</span>":c)+"</span>").click(function(){u.hasClass(v+"-state-disabled")||s()}).mousedown(function(){u.not("."+v+"-state-active").not("."+v+"-state-disabled").addClass(v+"-state-down")}).mouseup(function(){u.removeClass(v+"-state-down")}).hover(function(){u.not("."+v+"-state-active").not("."+v+"-state-disabled").addClass(v+"-state-hover")},function(){u.removeClass(v+"-state-hover").removeClass(v+"-state-down")}).appendTo(a);Y(u),o||u.addClass(v+"-corner-left"),o=u}}}),o&&o.addClass(v+"-corner-right")}),a}function s(t){h.find("h2").html(t)}function l(t){h.find("span.fc-button-"+t).addClass(v+"-state-active")}function c(t){h.find("span.fc-button-"+t).removeClass(v+"-state-active")}function u(t){h.find("span.fc-button-"+t).addClass(v+"-state-disabled")}function f(t){h.find("span.fc-button-"+t).removeClass(v+"-state-disabled")}var d=this;d.render=a,d.destroy=o,d.updateTitle=s,d.activateButton=l,d.deactivateButton=c,d.disableButton=u,d.enableButton=f;var v,h=t([])}function o(n,r){function a(t,e){return!E||E>t||e>S}function o(t,e){E=t,S=e,W=[];var n=++R,r=F.length;N=r;for(var a=0;r>a;a++)i(F[a],n)}function i(e,r){s(e,function(a){if(r==R){if(a){n.eventDataTransform&&(a=t.map(a,n.eventDataTransform)),e.eventDataTransform&&(a=t.map(a,e.eventDataTransform));for(var o=0;a.length>o;o++)a[o].source=e,w(a[o]);W=W.concat(a)}N--,N||k(W)}})}function s(r,a){var o,i,l=Ee.sourceFetchers;for(o=0;l.length>o;o++){if(i=l[o](r,E,S,a),i===!0)return;if("object"==typeof i)return s(i,a),e}var c=r.events;if(c)t.isFunction(c)?(m(),c(d(E),d(S),function(t){a(t),y()})):t.isArray(c)?a(c):a();else{var u=r.url;if(u){var f,v=r.success,h=r.error,g=r.complete;f=t.isFunction(r.data)?r.data():r.data;var p=t.extend({},f||{}),w=X(r.startParam,n.startParam),b=X(r.endParam,n.endParam);w&&(p[w]=Math.round(+E/1e3)),b&&(p[b]=Math.round(+S/1e3)),m(),t.ajax(t.extend({},Te,r,{data:p,success:function(e){e=e||[];var n=I(v,this,arguments);t.isArray(n)&&(e=n),a(e)},error:function(){I(h,this,arguments),a()},complete:function(){I(g,this,arguments),y()}}))}else a()}}function l(t){t=c(t),t&&(N++,i(t,R))}function c(n){return t.isFunction(n)||t.isArray(n)?n={events:n}:"string"==typeof n&&(n={url:n}),"object"==typeof n?(b(n),F.push(n),n):e}function u(e){F=t.grep(F,function(t){return!D(t,e)}),W=t.grep(W,function(t){return!D(t.source,e)}),k(W)}function f(t){var e,n,r=W.length,a=x().defaultEventEnd,o=t.start-t._start,i=t.end?t.end-(t._end||a(t)):0;for(e=0;r>e;e++)n=W[e],n._id==t._id&&n!=t&&(n.start=new Date(+n.start+o),n.end=t.end?n.end?new Date(+n.end+i):new Date(+a(n)+i):null,n.title=t.title,n.url=t.url,n.allDay=t.allDay,n.className=t.className,n.editable=t.editable,n.color=t.color,n.backgroundColor=t.backgroundColor,n.borderColor=t.borderColor,n.textColor=t.textColor,w(n));w(t),k(W)}function v(t,e){w(t),t.source||(e&&(H.events.push(t),t.source=H),W.push(t)),k(W)}function h(e){if(e){if(!t.isFunction(e)){var n=e+"";e=function(t){return t._id==n}}W=t.grep(W,e,!0);for(var r=0;F.length>r;r++)t.isArray(F[r].events)&&(F[r].events=t.grep(F[r].events,e,!0))}else{W=[];for(var r=0;F.length>r;r++)t.isArray(F[r].events)&&(F[r].events=[])}k(W)}function g(e){return t.isFunction(e)?t.grep(W,e):e?(e+="",t.grep(W,function(t){return t._id==e})):W}function m(){z++||T("loading",null,!0,x())}function y(){--z||T("loading",null,!1,x())}function w(t){var r=t.source||{},a=X(r.ignoreTimezone,n.ignoreTimezone);t._id=t._id||(t.id===e?"_fc"+xe++:t.id+""),t.date&&(t.start||(t.start=t.date),delete t.date),t._start=d(t.start=p(t.start,a)),t.end=p(t.end,a),t.end&&t.end<=t.start&&(t.end=null),t._end=t.end?d(t.end):null,t.allDay===e&&(t.allDay=X(r.allDayDefault,n.allDayDefault)),t.className?"string"==typeof t.className&&(t.className=t.className.split(/\s+/)):t.className=[]}function b(t){t.className?"string"==typeof t.className&&(t.className=t.className.split(/\s+/)):t.className=[];for(var e=Ee.sourceNormalizers,n=0;e.length>n;n++)e[n](t)}function D(t,e){return t&&e&&C(t)==C(e)}function C(t){return("object"==typeof t?t.events||t.url:"")||t}var M=this;M.isFetchNeeded=a,M.fetchEvents=o,M.addEventSource=l,M.removeEventSource=u,M.updateEvent=f,M.renderEvent=v,M.removeEvents=h,M.clientEvents=g,M.normalizeEvent=w;for(var E,S,T=M.trigger,x=M.getView,k=M.reportEvents,H={events:[]},F=[H],R=0,N=0,z=0,W=[],A=0;r.length>A;A++)c(r[A])}function i(t,e,n){return t.setFullYear(t.getFullYear()+e),n||f(t),t}function s(t,e,n){if(+t){var r=t.getMonth()+e,a=d(t);for(a.setDate(1),a.setMonth(r),t.setMonth(r),n||f(t);t.getMonth()!=a.getMonth();)t.setDate(t.getDate()+(a>t?1:-1))}return t}function l(t,e,n){if(+t){var r=t.getDate()+e,a=d(t);a.setHours(9),a.setDate(r),t.setDate(r),n||f(t),c(t,a)}return t}function c(t,e){if(+t)for(;t.getDate()!=e.getDate();)t.setTime(+t+(e>t?1:-1)*Fe)}function u(t,e){return t.setMinutes(t.getMinutes()+e),t}function f(t){return t.setHours(0),t.setMinutes(0),t.setSeconds(0),t.setMilliseconds(0),t}function d(t,e){return e?f(new Date(+t)):new Date(+t)}function v(){var t,e=0;do t=new Date(1970,e++,1);while(t.getHours());return t}function h(t,e){return Math.round((d(t,!0)-d(e,!0))/He)}function g(t,n,r,a){n!==e&&n!=t.getFullYear()&&(t.setDate(1),t.setMonth(0),t.setFullYear(n)),r!==e&&r!=t.getMonth()&&(t.setDate(1),t.setMonth(r)),a!==e&&t.setDate(a)}function p(t,n){return"object"==typeof t?t:"number"==typeof t?new Date(1e3*t):"string"==typeof t?t.match(/^\d+(\.\d+)?$/)?new Date(1e3*parseFloat(t)):(n===e&&(n=!0),m(t,n)||(t?new Date(t):null)):null}function m(t,e){var n=t.match(/^([0-9]{4})(-([0-9]{2})(-([0-9]{2})([T ]([0-9]{2}):([0-9]{2})(:([0-9]{2})(\.([0-9]+))?)?(Z|(([-+])([0-9]{2})(:?([0-9]{2}))?))?)?)?)?$/);if(!n)return null;var r=new Date(n[1],0,1);if(e||!n[13]){var a=new Date(n[1],0,1,9,0);n[3]&&(r.setMonth(n[3]-1),a.setMonth(n[3]-1)),n[5]&&(r.setDate(n[5]),a.setDate(n[5])),c(r,a),n[7]&&r.setHours(n[7]),n[8]&&r.setMinutes(n[8]),n[10]&&r.setSeconds(n[10]),n[12]&&r.setMilliseconds(1e3*Number("0."+n[12])),c(r,a)}else if(r.setUTCFullYear(n[1],n[3]?n[3]-1:0,n[5]||1),r.setUTCHours(n[7]||0,n[8]||0,n[10]||0,n[12]?1e3*Number("0."+n[12]):0),n[14]){var o=60*Number(n[16])+(n[18]?Number(n[18]):0);o*="-"==n[15]?1:-1,r=new Date(+r+1e3*60*o)}return r}function y(t){if("number"==typeof t)return 60*t;if("object"==typeof t)return 60*t.getHours()+t.getMinutes();var e=t.match(/(\d+)(?::(\d+))?\s*(\w+)?/);if(e){var n=parseInt(e[1],10);return e[3]&&(n%=12,"p"==e[3].toLowerCase().charAt(0)&&(n+=12)),60*n+(e[2]?parseInt(e[2],10):0)}}function w(t,e,n){return b(t,null,e,n)}function b(t,e,n,r){r=r||Ce;var a,o,i,s,l=t,c=e,u=n.length,f="";for(a=0;u>a;a++)if(o=n.charAt(a),"'"==o){for(i=a+1;u>i;i++)if("'"==n.charAt(i)){l&&(f+=i==a+1?"'":n.substring(a+1,i),a=i);break}}else if("("==o){for(i=a+1;u>i;i++)if(")"==n.charAt(i)){var d=w(l,n.substring(a+1,i),r);parseInt(d.replace(/\D/,""),10)&&(f+=d),a=i;break}}else if("["==o){for(i=a+1;u>i;i++)if("]"==n.charAt(i)){var v=n.substring(a+1,i),d=w(l,v,r);d!=w(c,v,r)&&(f+=d),a=i;break}}else if("{"==o)l=e,c=t;else if("}"==o)l=t,c=e;else{for(i=u;i>a;i--)if(s=Ne[n.substring(a,i)]){l&&(f+=s(l,r)),a=i-1;break}i==a&&l&&(f+=o)}return f}function D(t){var e,n=new Date(t.getTime());return n.setDate(n.getDate()+4-(n.getDay()||7)),e=n.getTime(),n.setMonth(0),n.setDate(1),Math.floor(Math.round((e-n)/864e5)/7)+1}function C(t){return t.end?M(t.end,t.allDay):l(d(t.start),1)}function M(t,e){return t=d(t),e||t.getHours()||t.getMinutes()?l(t,1):f(t)}function E(n,r,a){n.unbind("mouseover").mouseover(function(n){for(var o,i,s,l=n.target;l!=this;)o=l,l=l.parentNode;(i=o._fci)!==e&&(o._fci=e,s=r[i],a(s.event,s.element,s),t(n.target).trigger(n)),n.stopPropagation()})}function S(e,n,r){for(var a,o=0;e.length>o;o++)a=t(e[o]),a.width(Math.max(0,n-x(a,r)))}function T(e,n,r){for(var a,o=0;e.length>o;o++)a=t(e[o]),a.height(Math.max(0,n-R(a,r)))}function x(t,e){return k(t)+F(t)+(e?H(t):0)}function k(e){return(parseFloat(t.css(e[0],"paddingLeft",!0))||0)+(parseFloat(t.css(e[0],"paddingRight",!0))||0)}function H(e){return(parseFloat(t.css(e[0],"marginLeft",!0))||0)+(parseFloat(t.css(e[0],"marginRight",!0))||0)}function F(e){return(parseFloat(t.css(e[0],"borderLeftWidth",!0))||0)+(parseFloat(t.css(e[0],"borderRightWidth",!0))||0)}function R(t,e){return N(t)+W(t)+(e?z(t):0)}function N(e){return(parseFloat(t.css(e[0],"paddingTop",!0))||0)+(parseFloat(t.css(e[0],"paddingBottom",!0))||0)}function z(e){return(parseFloat(t.css(e[0],"marginTop",!0))||0)+(parseFloat(t.css(e[0],"marginBottom",!0))||0)}function W(e){return(parseFloat(t.css(e[0],"borderTopWidth",!0))||0)+(parseFloat(t.css(e[0],"borderBottomWidth",!0))||0)}function A(){}function O(t,e){return t-e}function L(t){return Math.max.apply(Math,t)}function _(t){return(10>t?"0":"")+t}function P(t,n){if(t[n]!==e)return t[n];for(var r,a=n.split(/(?=[A-Z])/),o=a.length-1;o>=0;o--)if(r=t[a[o].toLowerCase()],r!==e)return r;return t[""]}function q(t){return t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/'/g,"'").replace(/"/g,""").replace(/\n/g,"<br />")}function Y(t){t.attr("unselectable","on").css("MozUserSelect","none").bind("selectstart.ui",function(){return!1})}function B(t){t.children().removeClass("fc-first fc-last").filter(":first-child").addClass("fc-first").end().filter(":last-child").addClass("fc-last")}function j(t,e){var n=t.source||{},r=t.color,a=n.color,o=e("eventColor"),i=t.backgroundColor||r||n.backgroundColor||a||e("eventBackgroundColor")||o,s=t.borderColor||r||n.borderColor||a||e("eventBorderColor")||o,l=t.textColor||n.textColor||e("eventTextColor"),c=[];return i&&c.push("background-color:"+i),s&&c.push("border-color:"+s),l&&c.push("color:"+l),c.join(";")}function I(e,n,r){if(t.isFunction(e)&&(e=[e]),e){var a,o;for(a=0;e.length>a;a++)o=e[a].apply(n,r)||o;return o}}function X(){for(var t=0;arguments.length>t;t++)if(arguments[t]!==e)return arguments[t]}function J(t,e){function n(t,e){e&&(s(t,e),t.setDate(1));var n=a("firstDay"),f=d(t,!0);f.setDate(1);var v=s(d(f),1),g=d(f);l(g,-((g.getDay()-n+7)%7)),i(g);var p=d(v);l(p,(7-p.getDay()+n)%7),i(p,-1,!0);var m=c(),y=Math.round(h(p,g)/7);"fixed"==a("weekMode")&&(l(p,7*(6-y)),y=6),r.title=u(f,a("titleFormat")),r.start=f,r.end=v,r.visStart=g,r.visEnd=p,o(y,m,!0)}var r=this;r.render=n,Z.call(r,t,e,"month");var a=r.opt,o=r.renderBasic,i=r.skipHiddenDays,c=r.getCellsPerWeek,u=e.formatDate}function V(t,e){function n(t,e){e&&l(t,7*e);var n=l(d(t),-((t.getDay()-a("firstDay")+7)%7)),u=l(d(n),7),f=d(n);i(f);var v=d(u);i(v,-1,!0);var h=s();r.start=n,r.end=u,r.visStart=f,r.visEnd=v,r.title=c(f,l(d(v),-1),a("titleFormat")),o(1,h,!1)}var r=this;r.render=n,Z.call(r,t,e,"basicWeek");var a=r.opt,o=r.renderBasic,i=r.skipHiddenDays,s=r.getCellsPerWeek,c=e.formatDates}function U(t,e){function n(t,e){e&&l(t,e),i(t,0>e?-1:1);var n=d(t,!0),c=l(d(n),1);r.title=s(t,a("titleFormat")),r.start=r.visStart=n,r.end=r.visEnd=c,o(1,1,!1)}var r=this;r.render=n,Z.call(r,t,e,"basicDay");var a=r.opt,o=r.renderBasic,i=r.skipHiddenDays,s=e.formatDate}function Z(e,n,r){function a(t,e,n){ee=t,ne=e,re=n,o(),j||i(),s()}function o(){le=he("theme")?"ui":"fc",ce=he("columnFormat"),ue=he("weekNumbers"),de=he("weekNumberTitle"),ve="iso"!=he("weekNumberCalculation")?"w":"W"}function i(){Z=t("<div class='fc-event-container' style='position:absolute;z-index:8;top:0;left:0'/>").appendTo(e)}function s(){var n=c();L&&L.remove(),L=t(n).appendTo(e),_=L.find("thead"),P=_.find(".fc-day-header"),j=L.find("tbody"),I=j.find("tr"),X=j.find(".fc-day"),J=I.find("td:first-child"),V=I.eq(0).find(".fc-day > div"),U=I.eq(0).find(".fc-day-content > div"),B(_.add(_.find("tr"))),B(I),I.eq(0).addClass("fc-first"),I.filter(":last").addClass("fc-last"),X.each(function(e,n){var r=Ee(Math.floor(e/ne),e%ne);ge("dayRender",O,r,t(n))}),y(X)}function c(){var t="<table class='fc-border-separate' style='width:100%' cellspacing='0'>"+u()+v()+"</table>";return t}function u(){var t,e,n=le+"-widget-header",r="";for(r+="<thead><tr>",ue&&(r+="<th class='fc-week-number "+n+"'>"+q(de)+"</th>"),t=0;ne>t;t++)e=Ee(0,t),r+="<th class='fc-day-header fc-"+ke[e.getDay()]+" "+n+"'>"+q(xe(e,ce))+"</th>";return r+="</tr></thead>"}function v(){var t,e,n,r=le+"-widget-content",a="";for(a+="<tbody>",t=0;ee>t;t++){for(a+="<tr class='fc-week'>",ue&&(n=Ee(t,0),a+="<td class='fc-week-number "+r+"'>"+"<div>"+q(xe(n,ve))+"</div>"+"</td>"),e=0;ne>e;e++)n=Ee(t,e),a+=h(n);a+="</tr>"}return a+="</tbody>"}function h(t){var e=le+"-widget-content",n=O.start.getMonth(),r=f(new Date),a="",o=["fc-day","fc-"+ke[t.getDay()],e];return t.getMonth()!=n&&o.push("fc-other-month"),+t==+r?o.push("fc-today",le+"-state-highlight"):r>t?o.push("fc-past"):o.push("fc-future"),a+="<td class='"+o.join(" ")+"'"+" data-date='"+xe(t,"yyyy-MM-dd")+"'"+">"+"<div>",re&&(a+="<div class='fc-day-number'>"+t.getDate()+"</div>"),a+="<div class='fc-day-content'><div style='position:relative'> </div></div></div></td>"}function g(e){Q=e;var n,r,a,o=Q-_.height();"variable"==he("weekMode")?n=r=Math.floor(o/(1==ee?2:6)):(n=Math.floor(o/ee),r=o-n*(ee-1)),J.each(function(e,o){ee>e&&(a=t(o),a.find("> div").css("min-height",(e==ee-1?r:n)-R(a)))})}function p(t){$=t,ie.clear(),se.clear(),te=0,ue&&(te=_.find("th.fc-week-number").outerWidth()),K=Math.floor(($-te)/ne),S(P.slice(0,-1),K)}function y(t){t.click(w).mousedown(Me)}function w(e){if(!he("selectable")){var n=m(t(this).data("date"));ge("dayClick",this,n,!0,e)}}function b(t,e,n){n&&ae.build();for(var r=Te(t,e),a=0;r.length>a;a++){var o=r[a];y(D(o.row,o.leftCol,o.row,o.rightCol))}}function D(t,n,r,a){var o=ae.rect(t,n,r,a,e);return be(o,e)}function C(t){return d(t)}function M(t,e){b(t,l(d(e),1),!0)}function E(){Ce()}function T(t,e,n){var r=Se(t),a=X[r.row*ne+r.col];ge("dayClick",a,t,e,n)}function x(t,e){oe.start(function(t){Ce(),t&&D(t.row,t.col,t.row,t.col)},e)}function k(t,e,n){var r=oe.stop();if(Ce(),r){var a=Ee(r);ge("drop",t,a,!0,e,n)}}function H(t){return d(t.start)}function F(t){return ie.left(t)}function N(t){return ie.right(t)}function z(t){return se.left(t)}function W(t){return se.right(t)}function A(t){return I.eq(t)}var O=this;O.renderBasic=a,O.setHeight=g,O.setWidth=p,O.renderDayOverlay=b,O.defaultSelectionEnd=C,O.renderSelection=M,O.clearSelection=E,O.reportDayClick=T,O.dragStart=x,O.dragStop=k,O.defaultEventEnd=H,O.getHoverListener=function(){return oe},O.colLeft=F,O.colRight=N,O.colContentLeft=z,O.colContentRight=W,O.getIsCellAllDay=function(){return!0},O.allDayRow=A,O.getRowCnt=function(){return ee},O.getColCnt=function(){return ne},O.getColWidth=function(){return K},O.getDaySegmentContainer=function(){return Z},fe.call(O,e,n,r),me.call(O),pe.call(O),G.call(O);var L,_,P,j,I,X,J,V,U,Z,$,Q,K,te,ee,ne,re,ae,oe,ie,se,le,ce,ue,de,ve,he=O.opt,ge=O.trigger,be=O.renderOverlay,Ce=O.clearOverlays,Me=O.daySelectionMousedown,Ee=O.cellToDate,Se=O.dateToCell,Te=O.rangeToSegments,xe=n.formatDate;Y(e.addClass("fc-grid")),ae=new ye(function(e,n){var r,a,o;P.each(function(e,i){r=t(i),a=r.offset().left,e&&(o[1]=a),o=[a],n[e]=o}),o[1]=a+r.outerWidth(),I.each(function(n,i){ee>n&&(r=t(i),a=r.offset().top,n&&(o[1]=a),o=[a],e[n]=o)}),o[1]=a+r.outerHeight()}),oe=new we(ae),ie=new De(function(t){return V.eq(t)}),se=new De(function(t){return U.eq(t)})}function G(){function t(t,e){n.renderDayEvents(t,e)}function e(){n.getDaySegmentContainer().empty()}var n=this;n.renderEvents=t,n.clearEvents=e,de.call(n)}function $(t,e){function n(t,e){e&&l(t,7*e);var n=l(d(t),-((t.getDay()-a("firstDay")+7)%7)),u=l(d(n),7),f=d(n);i(f);var v=d(u);i(v,-1,!0);var h=s();r.title=c(f,l(d(v),-1),a("titleFormat")),r.start=n,r.end=u,r.visStart=f,r.visEnd=v,o(h)}var r=this;r.render=n,K.call(r,t,e,"agendaWeek");var a=r.opt,o=r.renderAgenda,i=r.skipHiddenDays,s=r.getCellsPerWeek,c=e.formatDates}function Q(t,e){function n(t,e){e&&l(t,e),i(t,0>e?-1:1);var n=d(t,!0),c=l(d(n),1);r.title=s(t,a("titleFormat")),r.start=r.visStart=n,r.end=r.visEnd=c,o(1)}var r=this;r.render=n,K.call(r,t,e,"agendaDay");var a=r.opt,o=r.renderAgenda,i=r.skipHiddenDays,s=e.formatDate}function K(n,r,a){function o(t){We=t,i(),K?c():s()}function i(){qe=Ue("theme")?"ui":"fc",Ye=Ue("isRTL"),Be=y(Ue("minTime")),je=y(Ue("maxTime")),Ie=Ue("columnFormat"),Xe=Ue("weekNumbers"),Je=Ue("weekNumberTitle"),Ve="iso"!=Ue("weekNumberCalculation")?"w":"W",Re=Ue("snapMinutes")||Ue("slotMinutes")}function s(){var e,r,a,o,i,s=qe+"-widget-header",l=qe+"-widget-content",f=0==Ue("slotMinutes")%15;for(c(),ce=t("<div style='position:absolute;z-index:2;left:0;width:100%'/>").appendTo(n),Ue("allDaySlot")?(ue=t("<div class='fc-event-container' style='position:absolute;z-index:8;top:0;left:0'/>").appendTo(ce),e="<table style='width:100%' class='fc-agenda-allday' cellspacing='0'><tr><th class='"+s+" fc-agenda-axis'>"+Ue("allDayText")+"</th>"+"<td>"+"<div class='fc-day-content'><div style='position:relative'/></div>"+"</td>"+"<th class='"+s+" fc-agenda-gutter'> </th>"+"</tr>"+"</table>",de=t(e).appendTo(ce),ve=de.find("tr"),C(ve.find("td")),ce.append("<div class='fc-agenda-divider "+s+"'>"+"<div class='fc-agenda-divider-inner'/>"+"</div>")):ue=t([]),he=t("<div style='position:absolute;width:100%;overflow-x:hidden;overflow-y:auto'/>").appendTo(ce),ge=t("<div style='position:relative;width:100%;overflow:hidden'/>").appendTo(he),be=t("<div class='fc-event-container' style='position:absolute;z-index:8;top:0;left:0'/>").appendTo(ge),e="<table class='fc-agenda-slots' style='width:100%' cellspacing='0'><tbody>",r=v(),o=u(d(r),je),u(r,Be),Ae=0,a=0;o>r;a++)i=r.getMinutes(),e+="<tr class='fc-slot"+a+" "+(i?"fc-minor":"")+"'>"+"<th class='fc-agenda-axis "+s+"'>"+(f&&i?" ":on(r,Ue("axisFormat")))+"</th>"+"<td class='"+l+"'>"+"<div style='position:relative'> </div>"+"</td>"+"</tr>",u(r,Ue("slotMinutes")),Ae++;e+="</tbody></table>",Ce=t(e).appendTo(ge),M(Ce.find("td"))}function c(){var e=h();K&&K.remove(),K=t(e).appendTo(n),ee=K.find("thead"),ne=ee.find("th").slice(1,-1),re=K.find("tbody"),ae=re.find("td").slice(0,-1),oe=ae.find("> div"),ie=ae.find(".fc-day-content > div"),se=ae.eq(0),le=oe.eq(0),B(ee.add(ee.find("tr"))),B(re.add(re.find("tr")))}function h(){var t="<table style='width:100%' class='fc-agenda-days fc-border-separate' cellspacing='0'>"+g()+p()+"</table>";return t}function g(){var t,e,n,r=qe+"-widget-header",a="";for(a+="<thead><tr>",Xe?(t=nn(0,0),e=on(t,Ve),Ye?e+=Je:e=Je+e,a+="<th class='fc-agenda-axis fc-week-number "+r+"'>"+q(e)+"</th>"):a+="<th class='fc-agenda-axis "+r+"'> </th>",n=0;We>n;n++)t=nn(0,n),a+="<th class='fc-"+ke[t.getDay()]+" fc-col"+n+" "+r+"'>"+q(on(t,Ie))+"</th>";return a+="<th class='fc-agenda-gutter "+r+"'> </th>"+"</tr>"+"</thead>"}function p(){var t,e,n,r,a,o=qe+"-widget-header",i=qe+"-widget-content",s=f(new Date),l="";for(l+="<tbody><tr><th class='fc-agenda-axis "+o+"'> </th>",n="",e=0;We>e;e++)t=nn(0,e),a=["fc-col"+e,"fc-"+ke[t.getDay()],i],+t==+s?a.push(qe+"-state-highlight","fc-today"):s>t?a.push("fc-past"):a.push("fc-future"),r="<td class='"+a.join(" ")+"'>"+"<div>"+"<div class='fc-day-content'>"+"<div style='position:relative'> </div>"+"</div>"+"</div>"+"</td>",n+=r;return l+=n,l+="<td class='fc-agenda-gutter "+i+"'> </td>"+"</tr>"+"</tbody>"}function m(t){t===e&&(t=Se),Se=t,sn={};var n=re.position().top,r=he.position().top,a=Math.min(t-n,Ce.height()+r+1);le.height(a-R(se)),ce.css("top",n),he.height(a-r-1),Fe=Ce.find("tr:first").height()+1,Ne=Ue("slotMinutes")/Re,ze=Fe/Ne}function w(e){Ee=e,_e.clear(),Pe.clear();var n=ee.find("th:first");de&&(n=n.add(de.find("th:first"))),n=n.add(Ce.find("th:first")),Te=0,S(n.width("").each(function(e,n){Te=Math.max(Te,t(n).outerWidth())}),Te);var r=K.find(".fc-agenda-gutter");de&&(r=r.add(de.find("th.fc-agenda-gutter")));var a=he[0].clientWidth;He=he.width()-a,He?(S(r,He),r.show().prev().removeClass("fc-last")):r.hide().prev().addClass("fc-last"),xe=Math.floor((a-Te)/We),S(ne.slice(0,-1),xe)}function b(){function t(){he.scrollTop(r)}var e=v(),n=d(e);n.setHours(Ue("firstHour"));var r=_(e,n)+1;t(),setTimeout(t,0)}function D(){b()}function C(t){t.click(E).mousedown(tn)}function M(t){t.click(E).mousedown(U)}function E(t){if(!Ue("selectable")){var e=Math.min(We-1,Math.floor((t.pageX-K.offset().left-Te)/xe)),n=nn(0,e),r=this.parentNode.className.match(/fc-slot(\d+)/);if(r){var a=parseInt(r[1])*Ue("slotMinutes"),o=Math.floor(a/60);n.setHours(o),n.setMinutes(a%60+Be),Ze("dayClick",ae[e],n,!1,t)}else Ze("dayClick",ae[e],n,!0,t)}}function x(t,e,n){n&&Oe.build();for(var r=an(t,e),a=0;r.length>a;a++){var o=r[a];C(k(o.row,o.leftCol,o.row,o.rightCol))}}function k(t,e,n,r){var a=Oe.rect(t,e,n,r,ce);return Ge(a,ce)}function H(t,e){for(var n=0;We>n;n++){var r=nn(0,n),a=l(d(r),1),o=new Date(Math.max(r,t)),i=new Date(Math.min(a,e));if(i>o){var s=Oe.rect(0,n,0,n,ge),c=_(r,o),u=_(r,i);s.top=c,s.height=u-c,M(Ge(s,ge))}}}function F(t){return _e.left(t)}function N(t){return Pe.left(t)}function z(t){return _e.right(t)}function W(t){return Pe.right(t)}function A(t){return Ue("allDaySlot")&&!t.row}function L(t){var e=nn(0,t.col),n=t.row;return Ue("allDaySlot")&&n--,n>=0&&u(e,Be+n*Re),e}function _(t,n){if(t=d(t,!0),u(d(t),Be)>n)return 0;if(n>=u(d(t),je))return Ce.height();var r=Ue("slotMinutes"),a=60*n.getHours()+n.getMinutes()-Be,o=Math.floor(a/r),i=sn[o];return i===e&&(i=sn[o]=Ce.find("tr").eq(o).find("td div")[0].offsetTop),Math.max(0,Math.round(i-1+Fe*(a%r/r)))}function P(){return ve}function j(t){var e=d(t.start);return t.allDay?e:u(e,Ue("defaultEventMinutes"))}function I(t,e){return e?d(t):u(d(t),Ue("slotMinutes"))}function X(t,e,n){n?Ue("allDaySlot")&&x(t,l(d(e),1),!0):J(t,e)}function J(e,n){var r=Ue("selectHelper");if(Oe.build(),r){var a=rn(e).col;if(a>=0&&We>a){var o=Oe.rect(0,a,0,a,ge),i=_(e,e),s=_(e,n);if(s>i){if(o.top=i,o.height=s-i,o.left+=2,o.width-=5,t.isFunction(r)){var l=r(e,n);l&&(o.position="absolute",Me=t(l).css(o).appendTo(ge))}else o.isStart=!0,o.isEnd=!0,Me=t(en({title:"",start:e,end:n,className:["fc-select-helper"],editable:!1},o)),Me.css("opacity",Ue("dragOpacity"));Me&&(M(Me),ge.append(Me),S(Me,o.width,!0),T(Me,o.height,!0))}}}else H(e,n)}function V(){$e(),Me&&(Me.remove(),Me=null)}function U(e){if(1==e.which&&Ue("selectable")){Ke(e);var n;Le.start(function(t,e){if(V(),t&&t.col==e.col&&!A(t)){var r=L(e),a=L(t);n=[r,u(d(r),Re),a,u(d(a),Re)].sort(O),J(n[0],n[3])}else n=null},e),t(document).one("mouseup",function(t){Le.stop(),n&&(+n[0]==+n[1]&&Z(n[0],!1,t),Qe(n[0],n[3],!1,t))})}}function Z(t,e,n){Ze("dayClick",ae[rn(t).col],t,e,n)}function G(t,e){Le.start(function(t){if($e(),t)if(A(t))k(t.row,t.col,t.row,t.col);else{var e=L(t),n=u(d(e),Ue("defaultEventMinutes"));H(e,n)}},e)}function $(t,e,n){var r=Le.stop();$e(),r&&Ze("drop",t,L(r),A(r),e,n)}var Q=this;Q.renderAgenda=o,Q.setWidth=w,Q.setHeight=m,Q.afterRender=D,Q.defaultEventEnd=j,Q.timePosition=_,Q.getIsCellAllDay=A,Q.allDayRow=P,Q.getCoordinateGrid=function(){return Oe},Q.getHoverListener=function(){return Le},Q.colLeft=F,Q.colRight=z,Q.colContentLeft=N,Q.colContentRight=W,Q.getDaySegmentContainer=function(){return ue},Q.getSlotSegmentContainer=function(){return be},Q.getMinMinute=function(){return Be},Q.getMaxMinute=function(){return je},Q.getSlotContainer=function(){return ge},Q.getRowCnt=function(){return 1},Q.getColCnt=function(){return We},Q.getColWidth=function(){return xe},Q.getSnapHeight=function(){return ze},Q.getSnapMinutes=function(){return Re},Q.defaultSelectionEnd=I,Q.renderDayOverlay=x,Q.renderSelection=X,Q.clearSelection=V,Q.reportDayClick=Z,Q.dragStart=G,Q.dragStop=$,fe.call(Q,n,r,a),me.call(Q),pe.call(Q),te.call(Q);var K,ee,ne,re,ae,oe,ie,se,le,ce,ue,de,ve,he,ge,be,Ce,Me,Ee,Se,Te,xe,He,Fe,Re,Ne,ze,We,Ae,Oe,Le,_e,Pe,qe,Ye,Be,je,Ie,Xe,Je,Ve,Ue=Q.opt,Ze=Q.trigger,Ge=Q.renderOverlay,$e=Q.clearOverlays,Qe=Q.reportSelection,Ke=Q.unselect,tn=Q.daySelectionMousedown,en=Q.slotSegHtml,nn=Q.cellToDate,rn=Q.dateToCell,an=Q.rangeToSegments,on=r.formatDate,sn={};Y(n.addClass("fc-agenda")),Oe=new ye(function(e,n){function r(t){return Math.max(l,Math.min(c,t))}var a,o,i;ne.each(function(e,r){a=t(r),o=a.offset().left,e&&(i[1]=o),i=[o],n[e]=i}),i[1]=o+a.outerWidth(),Ue("allDaySlot")&&(a=ve,o=a.offset().top,e[0]=[o,o+a.outerHeight()]);for(var s=ge.offset().top,l=he.offset().top,c=l+he.outerHeight(),u=0;Ae*Ne>u;u++)e.push([r(s+ze*u),r(s+ze*(u+1))])}),Le=new we(Oe),_e=new De(function(t){return oe.eq(t)}),Pe=new De(function(t){return ie.eq(t)})}function te(){function n(t,e){var n,r=t.length,o=[],i=[];for(n=0;r>n;n++)t[n].allDay?o.push(t[n]):i.push(t[n]);y("allDaySlot")&&(te(o,e),k()),s(a(i),e)}function r(){H().empty(),F().empty()}function a(e){var n,r,a,s,l,c=Y(),f=W(),v=z(),h=t.map(e,i),g=[];for(r=0;c>r;r++)for(n=P(0,r),u(n,f),l=o(e,h,n,u(d(n),v-f)),l=ee(l),a=0;l.length>a;a++)s=l[a],s.col=r,g.push(s);return g}function o(t,e,n,r){var a,o,i,s,l,c,u,f,v=[],h=t.length;for(a=0;h>a;a++)o=t[a],i=o.start,s=e[a],s>n&&r>i&&(n>i?(l=d(n),u=!1):(l=i,u=!0),s>r?(c=d(r),f=!1):(c=s,f=!0),v.push({event:o,start:l,end:c,isStart:u,isEnd:f}));return v.sort(ue)}function i(t){return t.end?d(t.end):u(d(t.start),y("defaultEventMinutes"))}function s(n,r){var a,o,i,s,l,u,d,v,h,g,p,m,b,D,C,M,S=n.length,T="",k=F(),H=y("isRTL");for(a=0;S>a;a++)o=n[a],i=o.event,s=A(o.start,o.start),l=A(o.start,o.end),u=L(o.col),d=_(o.col),v=d-u,d-=.025*v,v=d-u,h=v*(o.forwardCoord-o.backwardCoord),y("slotEventOverlap")&&(h=Math.max(2*(h-10),h)),H?(p=d-o.backwardCoord*v,g=p-h):(g=u+o.backwardCoord*v,p=g+h),g=Math.max(g,u),p=Math.min(p,d),h=p-g,o.top=s,o.left=g,o.outerWidth=h,o.outerHeight=l-s,T+=c(i,o);for(k[0].innerHTML=T,m=k.children(),a=0;S>a;a++)o=n[a],i=o.event,b=t(m[a]),D=w("eventRender",i,i,b),D===!1?b.remove():(D&&D!==!0&&(b.remove(),b=t(D).css({position:"absolute",top:o.top,left:o.left}).appendTo(k)),o.element=b,i._id===r?f(i,b,o):b[0]._fci=a,V(i,b));for(E(k,n,f),a=0;S>a;a++)o=n[a],(b=o.element)&&(o.vsides=R(b,!0),o.hsides=x(b,!0),C=b.find(".fc-event-title"),C.length&&(o.contentTop=C[0].offsetTop));for(a=0;S>a;a++)o=n[a],(b=o.element)&&(b[0].style.width=Math.max(0,o.outerWidth-o.hsides)+"px",M=Math.max(0,o.outerHeight-o.vsides),b[0].style.height=M+"px",i=o.event,o.contentTop!==e&&10>M-o.contentTop&&(b.find("div.fc-event-time").text(re(i.start,y("timeFormat"))+" - "+i.title),b.find("div.fc-event-title").remove()),w("eventAfterRender",i,i,b))}function c(t,e){var n="<",r=t.url,a=j(t,y),o=["fc-event","fc-event-vert"];return b(t)&&o.push("fc-event-draggable"),e.isStart&&o.push("fc-event-start"),e.isEnd&&o.push("fc-event-end"),o=o.concat(t.className),t.source&&(o=o.concat(t.source.className||[])),n+=r?"a href='"+q(t.url)+"'":"div",n+=" class='"+o.join(" ")+"'"+" style="+"'"+"position:absolute;"+"top:"+e.top+"px;"+"left:"+e.left+"px;"+a+"'"+">"+"<div class='fc-event-inner'>"+"<div class='fc-event-time'>"+q(ae(t.start,t.end,y("timeFormat")))+"</div>"+"<div class='fc-event-title'>"+q(t.title||"")+"</div>"+"</div>"+"<div class='fc-event-bg'></div>",e.isEnd&&D(t)&&(n+="<div class='ui-resizable-handle ui-resizable-s'>=</div>"),n+="</"+(r?"a":"div")+">"}function f(t,e,n){var r=e.find("div.fc-event-time");b(t)&&g(t,e,r),n.isEnd&&D(t)&&p(t,e,r),S(t,e)}function v(t,e,n){function r(){c||(e.width(a).height("").draggable("option","grid",null),c=!0)}var a,o,i,s=n.isStart,c=!0,u=N(),f=B(),v=I(),g=X(),p=W();e.draggable({opacity:y("dragOpacity","month"),revertDuration:y("dragRevertDuration"),start:function(n,p){w("eventDragStart",e,t,n,p),Z(t,e),a=e.width(),u.start(function(n,a){if(K(),n){o=!1;var u=P(0,a.col),p=P(0,n.col);i=h(p,u),n.row?s?c&&(e.width(f-10),T(e,v*Math.round((t.end?(t.end-t.start)/Re:y("defaultEventMinutes"))/g)),e.draggable("option","grid",[f,1]),c=!1):o=!0:(Q(l(d(t.start),i),l(C(t),i)),r()),o=o||c&&!i
}else r(),o=!0;e.draggable("option","revert",o)},n,"drag")},stop:function(n,a){if(u.stop(),K(),w("eventDragStop",e,t,n,a),o)r(),e.css("filter",""),U(t,e);else{var s=0;c||(s=Math.round((e.offset().top-J().offset().top)/v)*g+p-(60*t.start.getHours()+t.start.getMinutes())),G(this,t,i,s,c,n,a)}}})}function g(t,e,n){function r(){K(),s&&(f?(n.hide(),e.draggable("option","grid",null),Q(l(d(t.start),b),l(C(t),b))):(a(D),n.css("display",""),e.draggable("option","grid",[T,x])))}function a(e){var r,a=u(d(t.start),e);t.end&&(r=u(d(t.end),e)),n.text(ae(a,r,y("timeFormat")))}var o,i,s,c,f,v,g,p,b,D,M,E=m.getCoordinateGrid(),S=Y(),T=B(),x=I(),k=X();e.draggable({scroll:!1,grid:[T,x],axis:1==S?"y":!1,opacity:y("dragOpacity"),revertDuration:y("dragRevertDuration"),start:function(n,r){w("eventDragStart",e,t,n,r),Z(t,e),E.build(),o=e.position(),i=E.cell(n.pageX,n.pageY),s=c=!0,f=v=O(i),g=p=0,b=0,D=M=0},drag:function(t,n){var a=E.cell(t.pageX,t.pageY);if(s=!!a){if(f=O(a),g=Math.round((n.position.left-o.left)/T),g!=p){var l=P(0,i.col),u=i.col+g;u=Math.max(0,u),u=Math.min(S-1,u);var d=P(0,u);b=h(d,l)}f||(D=Math.round((n.position.top-o.top)/x)*k)}(s!=c||f!=v||g!=p||D!=M)&&(r(),c=s,v=f,p=g,M=D),e.draggable("option","revert",!s)},stop:function(n,a){K(),w("eventDragStop",e,t,n,a),s&&(f||b||D)?G(this,t,b,f?0:D,f,n,a):(s=!0,f=!1,g=0,b=0,D=0,r(),e.css("filter",""),e.css(o),U(t,e))}})}function p(t,e,n){var r,a,o=I(),i=X();e.resizable({handles:{s:".ui-resizable-handle"},grid:o,start:function(n,o){r=a=0,Z(t,e),w("eventResizeStart",this,t,n,o)},resize:function(s,l){r=Math.round((Math.max(o,e.height())-l.originalSize.height)/o),r!=a&&(n.text(ae(t.start,r||t.end?u(M(t),i*r):null,y("timeFormat"))),a=r)},stop:function(n,a){w("eventResizeStop",this,t,n,a),r?$(this,t,0,i*r,n,a):U(t,e)}})}var m=this;m.renderEvents=n,m.clearEvents=r,m.slotSegHtml=c,de.call(m);var y=m.opt,w=m.trigger,b=m.isEventDraggable,D=m.isEventResizable,M=m.eventEnd,S=m.eventElementHandlers,k=m.setHeight,H=m.getDaySegmentContainer,F=m.getSlotSegmentContainer,N=m.getHoverListener,z=m.getMaxMinute,W=m.getMinMinute,A=m.timePosition,O=m.getIsCellAllDay,L=m.colContentLeft,_=m.colContentRight,P=m.cellToDate,Y=m.getColCnt,B=m.getColWidth,I=m.getSnapHeight,X=m.getSnapMinutes,J=m.getSlotContainer,V=m.reportEventElement,U=m.showEvents,Z=m.hideEvents,G=m.eventDrop,$=m.eventResize,Q=m.renderDayOverlay,K=m.clearOverlays,te=m.renderDayEvents,ne=m.calendar,re=ne.formatDate,ae=ne.formatDates;m.draggableDayEvent=v}function ee(t){var e,n=ne(t),r=n[0];if(re(n),r){for(e=0;r.length>e;e++)ae(r[e]);for(e=0;r.length>e;e++)oe(r[e],0,0)}return ie(n)}function ne(t){var e,n,r,a=[];for(e=0;t.length>e;e++){for(n=t[e],r=0;a.length>r&&se(n,a[r]).length;r++);(a[r]||(a[r]=[])).push(n)}return a}function re(t){var e,n,r,a,o;for(e=0;t.length>e;e++)for(n=t[e],r=0;n.length>r;r++)for(a=n[r],a.forwardSegs=[],o=e+1;t.length>o;o++)se(a,t[o],a.forwardSegs)}function ae(t){var n,r,a=t.forwardSegs,o=0;if(t.forwardPressure===e){for(n=0;a.length>n;n++)r=a[n],ae(r),o=Math.max(o,1+r.forwardPressure);t.forwardPressure=o}}function oe(t,n,r){var a,o=t.forwardSegs;if(t.forwardCoord===e)for(o.length?(o.sort(ce),oe(o[0],n+1,r),t.forwardCoord=o[0].backwardCoord):t.forwardCoord=1,t.backwardCoord=t.forwardCoord-(t.forwardCoord-r)/(n+1),a=0;o.length>a;a++)oe(o[a],0,t.forwardCoord)}function ie(t){var e,n,r,a=[];for(e=0;t.length>e;e++)for(n=t[e],r=0;n.length>r;r++)a.push(n[r]);return a}function se(t,e,n){n=n||[];for(var r=0;e.length>r;r++)le(t,e[r])&&n.push(e[r]);return n}function le(t,e){return t.end>e.start&&t.start<e.end}function ce(t,e){return e.forwardPressure-t.forwardPressure||(t.backwardCoord||0)-(e.backwardCoord||0)||ue(t,e)}function ue(t,e){return t.start-e.start||e.end-e.start-(t.end-t.start)||(t.event.title||"").localeCompare(e.event.title)}function fe(n,r,a){function o(e,n){var r=V[e];return t.isPlainObject(r)?P(r,n||a):r}function i(t,e){return r.trigger.apply(r,[t,e||_].concat(Array.prototype.slice.call(arguments,2),[_]))}function s(t){var e=t.source||{};return X(t.startEditable,e.startEditable,o("eventStartEditable"),t.editable,e.editable,o("editable"))&&!o("disableDragging")}function c(t){var e=t.source||{};return X(t.durationEditable,e.durationEditable,o("eventDurationEditable"),t.editable,e.editable,o("editable"))&&!o("disableResizing")}function f(t){j={};var e,n,r=t.length;for(e=0;r>e;e++)n=t[e],j[n._id]?j[n._id].push(n):j[n._id]=[n]}function v(){j={},I={},J=[]}function g(t){return t.end?d(t.end):q(t)}function p(t,e){J.push({event:t,element:e}),I[t._id]?I[t._id].push(e):I[t._id]=[e]}function m(){t.each(J,function(t,e){_.trigger("eventDestroy",e.event,e.event,e.element)})}function y(t,n){n.click(function(r){return n.hasClass("ui-draggable-dragging")||n.hasClass("ui-resizable-resizing")?e:i("eventClick",this,t,r)}).hover(function(e){i("eventMouseover",this,t,e)},function(e){i("eventMouseout",this,t,e)})}function w(t,e){D(t,e,"show")}function b(t,e){D(t,e,"hide")}function D(t,e,n){var r,a=I[t._id],o=a.length;for(r=0;o>r;r++)e&&a[r][0]==e[0]||a[r][n]()}function C(t,e,n,r,a,o,s){var l=e.allDay,c=e._id;E(j[c],n,r,a),i("eventDrop",t,e,n,r,a,function(){E(j[c],-n,-r,l),B(c)},o,s),B(c)}function M(t,e,n,r,a,o){var s=e._id;S(j[s],n,r),i("eventResize",t,e,n,r,function(){S(j[s],-n,-r),B(s)},a,o),B(s)}function E(t,n,r,a){r=r||0;for(var o,i=t.length,s=0;i>s;s++)o=t[s],a!==e&&(o.allDay=a),u(l(o.start,n,!0),r),o.end&&(o.end=u(l(o.end,n,!0),r)),Y(o,V)}function S(t,e,n){n=n||0;for(var r,a=t.length,o=0;a>o;o++)r=t[o],r.end=u(l(g(r),e,!0),n),Y(r,V)}function T(t){return"object"==typeof t&&(t=t.getDay()),G[t]}function x(){return U}function k(t,e,n){for(e=e||1;G[(t.getDay()+(n?e:0)+7)%7];)l(t,e)}function H(){var t=F.apply(null,arguments),e=R(t),n=N(e);return n}function F(t,e){var n=_.getColCnt(),r=K?-1:1,a=K?n-1:0;"object"==typeof t&&(e=t.col,t=t.row);var o=t*n+(e*r+a);return o}function R(t){var e=_.visStart.getDay();return t+=$[e],7*Math.floor(t/U)+Q[(t%U+U)%U]-e}function N(t){var e=d(_.visStart);return l(e,t),e}function z(t){var e=W(t),n=A(e),r=O(n);return r}function W(t){return h(t,_.visStart)}function A(t){var e=_.visStart.getDay();return t+=e,Math.floor(t/7)*U+$[(t%7+7)%7]-$[e]}function O(t){var e=_.getColCnt(),n=K?-1:1,r=K?e-1:0,a=Math.floor(t/e),o=(t%e+e)%e*n+r;return{row:a,col:o}}function L(t,e){for(var n=_.getRowCnt(),r=_.getColCnt(),a=[],o=W(t),i=W(e),s=A(o),l=A(i)-1,c=0;n>c;c++){var u=c*r,f=u+r-1,d=Math.max(s,u),v=Math.min(l,f);if(v>=d){var h=O(d),g=O(v),p=[h.col,g.col].sort(),m=R(d)==o,y=R(v)+1==i;a.push({row:c,leftCol:p[0],rightCol:p[1],isStart:m,isEnd:y})}}return a}var _=this;_.element=n,_.calendar=r,_.name=a,_.opt=o,_.trigger=i,_.isEventDraggable=s,_.isEventResizable=c,_.setEventData=f,_.clearEventData=v,_.eventEnd=g,_.reportEventElement=p,_.triggerEventDestroy=m,_.eventElementHandlers=y,_.showEvents=w,_.hideEvents=b,_.eventDrop=C,_.eventResize=M;var q=_.defaultEventEnd,Y=r.normalizeEvent,B=r.reportEventChange,j={},I={},J=[],V=r.options;_.isHiddenDay=T,_.skipHiddenDays=k,_.getCellsPerWeek=x,_.dateToCell=z,_.dateToDayOffset=W,_.dayOffsetToCellOffset=A,_.cellOffsetToCell=O,_.cellToDate=H,_.cellToCellOffset=F,_.cellOffsetToDayOffset=R,_.dayOffsetToDate=N,_.rangeToSegments=L;var U,Z=o("hiddenDays")||[],G=[],$=[],Q=[],K=o("isRTL");(function(){o("weekends")===!1&&Z.push(0,6);for(var e=0,n=0;7>e;e++)$[e]=n,G[e]=-1!=t.inArray(e,Z),G[e]||(Q[n]=e,n++);if(U=n,!U)throw"invalid hiddenDays"})()}function de(){function e(t,e){var n=r(t,!1,!0);he(n,function(t,e){N(t.event,e)}),w(n,e),he(n,function(t,e){k("eventAfterRender",t.event,t.event,e)})}function n(t,e,n){var a=r([t],!0,!1),o=[];return he(a,function(t,r){t.row===e&&r.css("top",n),o.push(r[0])}),o}function r(e,n,r){var o,l,c=Z(),d=n?t("<div/>"):c,v=a(e);return i(v),o=s(v),d[0].innerHTML=o,l=d.children(),n&&c.append(l),u(v,l),he(v,function(t,e){t.hsides=x(e,!0)}),he(v,function(t,e){e.width(Math.max(0,t.outerWidth-t.hsides))}),he(v,function(t,e){t.outerHeight=e.outerHeight(!0)}),f(v,r),v}function a(t){for(var e=[],n=0;t.length>n;n++){var r=o(t[n]);e.push.apply(e,r)}return e}function o(t){for(var e=t.start,n=C(t),r=ee(e,n),a=0;r.length>a;a++)r[a].event=t;return r}function i(t){for(var e=T("isRTL"),n=0;t.length>n;n++){var r=t[n],a=(e?r.isEnd:r.isStart)?V:X,o=(e?r.isStart:r.isEnd)?U:J,i=a(r.leftCol),s=o(r.rightCol);r.left=i,r.outerWidth=s-i}}function s(t){for(var e="",n=0;t.length>n;n++)e+=c(t[n]);return e}function c(t){var e="",n=T("isRTL"),r=t.event,a=r.url,o=["fc-event","fc-event-hori"];H(r)&&o.push("fc-event-draggable"),t.isStart&&o.push("fc-event-start"),t.isEnd&&o.push("fc-event-end"),o=o.concat(r.className),r.source&&(o=o.concat(r.source.className||[]));var i=j(r,T);return e+=a?"<a href='"+q(a)+"'":"<div",e+=" class='"+o.join(" ")+"'"+" style="+"'"+"position:absolute;"+"left:"+t.left+"px;"+i+"'"+">"+"<div class='fc-event-inner'>",!r.allDay&&t.isStart&&(e+="<span class='fc-event-time'>"+q(G(r.start,r.end,T("timeFormat")))+"</span>"),e+="<span class='fc-event-title'>"+q(r.title||"")+"</span>"+"</div>",t.isEnd&&F(r)&&(e+="<div class='ui-resizable-handle ui-resizable-"+(n?"w":"e")+"'>"+" "+"</div>"),e+="</"+(a?"a":"div")+">"}function u(e,n){for(var r=0;e.length>r;r++){var a=e[r],o=a.event,i=n.eq(r),s=k("eventRender",o,o,i);s===!1?i.remove():(s&&s!==!0&&(s=t(s).css({position:"absolute",left:a.left}),i.replaceWith(s),i=s),a.element=i)}}function f(t,e){var n=v(t),r=y(),a=[];if(e)for(var o=0;r.length>o;o++)r[o].height(n[o]);for(var o=0;r.length>o;o++)a.push(r[o].position().top);he(t,function(t,e){e.css("top",a[t.row]+t.top)})}function v(t){for(var e=P(),n=B(),r=[],a=g(t),o=0;e>o;o++){for(var i=a[o],s=[],l=0;n>l;l++)s.push(0);for(var c=0;i.length>c;c++){var u=i[c];u.top=L(s.slice(u.leftCol,u.rightCol+1));for(var l=u.leftCol;u.rightCol>=l;l++)s[l]=u.top+u.outerHeight}r.push(L(s))}return r}function g(t){var e,n,r,a=P(),o=[];for(e=0;t.length>e;e++)n=t[e],r=n.row,n.element&&(o[r]?o[r].push(n):o[r]=[n]);for(r=0;a>r;r++)o[r]=p(o[r]||[]);return o}function p(t){for(var e=[],n=m(t),r=0;n.length>r;r++)e.push.apply(e,n[r]);return e}function m(t){t.sort(ge);for(var e=[],n=0;t.length>n;n++){for(var r=t[n],a=0;e.length>a&&ve(r,e[a]);a++);e[a]?e[a].push(r):e[a]=[r]}return e}function y(){var t,e=P(),n=[];for(t=0;e>t;t++)n[t]=I(t).find("div.fc-day-content > div");return n}function w(t,e){var n=Z();he(t,function(t,n,r){var a=t.event;a._id===e?b(a,n,t):n[0]._fci=r}),E(n,t,b)}function b(t,e,n){H(t)&&S.draggableDayEvent(t,e,n),n.isEnd&&F(t)&&S.resizableDayEvent(t,e,n),z(t,e)}function D(t,e){var n,r=te();e.draggable({delay:50,opacity:T("dragOpacity"),revertDuration:T("dragRevertDuration"),start:function(a,o){k("eventDragStart",e,t,a,o),A(t,e),r.start(function(r,a,o,i){if(e.draggable("option","revert",!r||!o&&!i),Q(),r){var s=ne(a),c=ne(r);n=h(c,s),$(l(d(t.start),n),l(C(t),n))}else n=0},a,"drag")},stop:function(a,o){r.stop(),Q(),k("eventDragStop",e,t,a,o),n?O(this,t,n,0,t.allDay,a,o):(e.css("filter",""),W(t,e))}})}function M(e,r,a){var o=T("isRTL"),i=o?"w":"e",s=r.find(".ui-resizable-"+i),c=!1;Y(r),r.mousedown(function(t){t.preventDefault()}).click(function(t){c&&(t.preventDefault(),t.stopImmediatePropagation())}),s.mousedown(function(o){function s(n){k("eventResizeStop",this,e,n),t("body").css("cursor",""),u.stop(),Q(),f&&_(this,e,f,0,n),setTimeout(function(){c=!1},0)}if(1==o.which){c=!0;var u=te();P(),B();var f,d,v=r.css("top"),h=t.extend({},e),g=ie(oe(e.start));K(),t("body").css("cursor",i+"-resize").one("mouseup",s),k("eventResizeStart",this,e,o),u.start(function(r,o){if(r){var s=re(o),c=re(r);if(c=Math.max(c,g),f=ae(c)-ae(s)){h.end=l(R(e),f,!0);var u=d;d=n(h,a.row,v),d=t(d),d.find("*").css("cursor",i+"-resize"),u&&u.remove(),A(e)}else d&&(W(e),d.remove(),d=null);Q(),$(e.start,l(C(e),f))}},o)}})}var S=this;S.renderDayEvents=e,S.draggableDayEvent=D,S.resizableDayEvent=M;var T=S.opt,k=S.trigger,H=S.isEventDraggable,F=S.isEventResizable,R=S.eventEnd,N=S.reportEventElement,z=S.eventElementHandlers,W=S.showEvents,A=S.hideEvents,O=S.eventDrop,_=S.eventResize,P=S.getRowCnt,B=S.getColCnt;S.getColWidth;var I=S.allDayRow,X=S.colLeft,J=S.colRight,V=S.colContentLeft,U=S.colContentRight;S.dateToCell;var Z=S.getDaySegmentContainer,G=S.calendar.formatDates,$=S.renderDayOverlay,Q=S.clearOverlays,K=S.clearSelection,te=S.getHoverListener,ee=S.rangeToSegments,ne=S.cellToDate,re=S.cellToCellOffset,ae=S.cellOffsetToDayOffset,oe=S.dateToDayOffset,ie=S.dayOffsetToCellOffset}function ve(t,e){for(var n=0;e.length>n;n++){var r=e[n];if(r.leftCol<=t.rightCol&&r.rightCol>=t.leftCol)return!0}return!1}function he(t,e){for(var n=0;t.length>n;n++){var r=t[n],a=r.element;a&&e(r,a,n)}}function ge(t,e){return e.rightCol-e.leftCol-(t.rightCol-t.leftCol)||e.event.allDay-t.event.allDay||t.event.start-e.event.start||(t.event.title||"").localeCompare(e.event.title)}function pe(){function e(t,e,a){n(),e||(e=l(t,a)),c(t,e,a),r(t,e,a)}function n(t){f&&(f=!1,u(),s("unselect",null,t))}function r(t,e,n,r){f=!0,s("select",null,t,e,n,r)}function a(e){var a=o.cellToDate,s=o.getIsCellAllDay,l=o.getHoverListener(),f=o.reportDayClick;if(1==e.which&&i("selectable")){n(e);var d;l.start(function(t,e){u(),t&&s(t)?(d=[a(e),a(t)].sort(O),c(d[0],d[1],!0)):d=null},e),t(document).one("mouseup",function(t){l.stop(),d&&(+d[0]==+d[1]&&f(d[0],!0,t),r(d[0],d[1],!0,t))})}}var o=this;o.select=e,o.unselect=n,o.reportSelection=r,o.daySelectionMousedown=a;var i=o.opt,s=o.trigger,l=o.defaultSelectionEnd,c=o.renderSelection,u=o.clearSelection,f=!1;i("selectable")&&i("unselectAuto")&&t(document).mousedown(function(e){var r=i("unselectCancel");r&&t(e.target).parents(r).length||n(e)})}function me(){function e(e,n){var r=o.shift();return r||(r=t("<div class='fc-cell-overlay' style='position:absolute;z-index:3'/>")),r[0].parentNode!=n[0]&&r.appendTo(n),a.push(r.css(e).show()),r}function n(){for(var t;t=a.shift();)o.push(t.hide().unbind())}var r=this;r.renderOverlay=e,r.clearOverlays=n;var a=[],o=[]}function ye(t){var e,n,r=this;r.build=function(){e=[],n=[],t(e,n)},r.cell=function(t,r){var a,o=e.length,i=n.length,s=-1,l=-1;for(a=0;o>a;a++)if(r>=e[a][0]&&e[a][1]>r){s=a;break}for(a=0;i>a;a++)if(t>=n[a][0]&&n[a][1]>t){l=a;break}return s>=0&&l>=0?{row:s,col:l}:null},r.rect=function(t,r,a,o,i){var s=i.offset();return{top:e[t][0]-s.top,left:n[r][0]-s.left,width:n[o][1]-n[r][0],height:e[a][1]-e[t][0]}}}function we(e){function n(t){be(t);var n=e.cell(t.pageX,t.pageY);(!n!=!i||n&&(n.row!=i.row||n.col!=i.col))&&(n?(o||(o=n),a(n,o,n.row-o.row,n.col-o.col)):a(n,o),i=n)}var r,a,o,i,s=this;s.start=function(s,l,c){a=s,o=i=null,e.build(),n(l),r=c||"mousemove",t(document).bind(r,n)},s.stop=function(){return t(document).unbind(r,n),i}}function be(t){t.pageX===e&&(t.pageX=t.originalEvent.pageX,t.pageY=t.originalEvent.pageY)}function De(t){function n(e){return a[e]=a[e]||t(e)}var r=this,a={},o={},i={};r.left=function(t){return o[t]=o[t]===e?n(t).position().left:o[t]},r.right=function(t){return i[t]=i[t]===e?r.left(t)+n(t).width():i[t]},r.clear=function(){a={},o={},i={}}}var Ce={defaultView:"month",aspectRatio:1.35,header:{left:"title",center:"",right:"today prev,next"},weekends:!0,weekNumbers:!1,weekNumberCalculation:"iso",weekNumberTitle:"W",allDayDefault:!0,ignoreTimezone:!0,lazyFetching:!0,startParam:"start",endParam:"end",titleFormat:{month:"MMMM yyyy",week:"MMM d[ yyyy]{ '—'[ MMM] d yyyy}",day:"dddd, MMM d, yyyy"},columnFormat:{month:"ddd",week:"ddd M/d",day:"dddd M/d"},timeFormat:{"":"h(:mm)t"},isRTL:!1,firstDay:0,monthNames:["January","February","March","April","May","June","July","August","September","October","November","December"],monthNamesShort:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],dayNames:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],dayNamesShort:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],buttonText:{prev:"<span class='fc-text-arrow'>‹</span>",next:"<span class='fc-text-arrow'>›</span>",prevYear:"<span class='fc-text-arrow'>«</span>",nextYear:"<span class='fc-text-arrow'>»</span>",today:"today",month:"month",week:"week",day:"day"},theme:!1,buttonIcons:{prev:"circle-triangle-w",next:"circle-triangle-e"},unselectAuto:!0,dropAccept:"*",handleWindowResize:!0},Me={header:{left:"next,prev today",center:"",right:"title"},buttonText:{prev:"<span class='fc-text-arrow'>›</span>",next:"<span class='fc-text-arrow'>‹</span>",prevYear:"<span class='fc-text-arrow'>»</span>",nextYear:"<span class='fc-text-arrow'>«</span>"},buttonIcons:{prev:"circle-triangle-e",next:"circle-triangle-w"}},Ee=t.fullCalendar={version:"1.6.4"},Se=Ee.views={};t.fn.fullCalendar=function(n){if("string"==typeof n){var a,o=Array.prototype.slice.call(arguments,1);return this.each(function(){var r=t.data(this,"fullCalendar");if(r&&t.isFunction(r[n])){var i=r[n].apply(r,o);a===e&&(a=i),"destroy"==n&&t.removeData(this,"fullCalendar")}}),a!==e?a:this}n=n||{};var i=n.eventSources||[];return delete n.eventSources,n.events&&(i.push(n.events),delete n.events),n=t.extend(!0,{},Ce,n.isRTL||n.isRTL===e&&Ce.isRTL?Me:{},n),this.each(function(e,a){var o=t(a),s=new r(o,n,i);o.data("fullCalendar",s),s.render()}),this},Ee.sourceNormalizers=[],Ee.sourceFetchers=[];var Te={dataType:"json",cache:!1},xe=1;Ee.addDays=l,Ee.cloneDate=d,Ee.parseDate=p,Ee.parseISO8601=m,Ee.parseTime=y,Ee.formatDate=w,Ee.formatDates=b;var ke=["sun","mon","tue","wed","thu","fri","sat"],He=864e5,Fe=36e5,Re=6e4,Ne={s:function(t){return t.getSeconds()},ss:function(t){return _(t.getSeconds())},m:function(t){return t.getMinutes()},mm:function(t){return _(t.getMinutes())},h:function(t){return t.getHours()%12||12},hh:function(t){return _(t.getHours()%12||12)},H:function(t){return t.getHours()},HH:function(t){return _(t.getHours())},d:function(t){return t.getDate()},dd:function(t){return _(t.getDate())},ddd:function(t,e){return e.dayNamesShort[t.getDay()]},dddd:function(t,e){return e.dayNames[t.getDay()]},M:function(t){return t.getMonth()+1},MM:function(t){return _(t.getMonth()+1)},MMM:function(t,e){return e.monthNamesShort[t.getMonth()]},MMMM:function(t,e){return e.monthNames[t.getMonth()]},yy:function(t){return(t.getFullYear()+"").substring(2)},yyyy:function(t){return t.getFullYear()},t:function(t){return 12>t.getHours()?"a":"p"},tt:function(t){return 12>t.getHours()?"am":"pm"},T:function(t){return 12>t.getHours()?"A":"P"},TT:function(t){return 12>t.getHours()?"AM":"PM"},u:function(t){return w(t,"yyyy-MM-dd'T'HH:mm:ss'Z'")},S:function(t){var e=t.getDate();return e>10&&20>e?"th":["st","nd","rd"][e%10-1]||"th"},w:function(t,e){return e.weekNumberCalculation(t)},W:function(t){return D(t)}};Ee.dateFormatters=Ne,Ee.applyAll=I,Se.month=J,Se.basicWeek=V,Se.basicDay=U,n({weekMode:"fixed"}),Se.agendaWeek=$,Se.agendaDay=Q,n({allDaySlot:!0,allDayText:"all-day",firstHour:6,slotMinutes:30,defaultEventMinutes:120,axisFormat:"h(:mm)tt",timeFormat:{agenda:"h:mm{ - h:mm}"},dragOpacity:{agenda:.5},minTime:0,maxTime:24,slotEventOverlap:!0})})(jQuery); | zettwerk.fullcalendar | /zettwerk.fullcalendar-0.3.1.zip/zettwerk.fullcalendar-0.3.1/zettwerk/fullcalendar/browser/fullcalendar/fullcalendar.min.js | fullcalendar.min.js |
* Use fullcalendar.css for basic styling.
* For event drag & drop, requires jQuery UI draggable.
* For event resizing, requires jQuery UI resizable.
*/
(function($, undefined) {
;;
var defaults = {
// display
defaultView: 'month',
aspectRatio: 1.35,
header: {
left: 'title',
center: '',
right: 'today prev,next'
},
weekends: true,
weekNumbers: false,
weekNumberCalculation: 'iso',
weekNumberTitle: 'W',
// editing
//editable: false,
//disableDragging: false,
//disableResizing: false,
allDayDefault: true,
ignoreTimezone: true,
// event ajax
lazyFetching: true,
startParam: 'start',
endParam: 'end',
// time formats
titleFormat: {
month: 'MMMM yyyy',
week: "MMM d[ yyyy]{ '—'[ MMM] d yyyy}",
day: 'dddd, MMM d, yyyy'
},
columnFormat: {
month: 'ddd',
week: 'ddd M/d',
day: 'dddd M/d'
},
timeFormat: { // for event elements
'': 'h(:mm)t' // default
},
// locale
isRTL: false,
firstDay: 0,
monthNames: ['January','February','March','April','May','June','July','August','September','October','November','December'],
monthNamesShort: ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'],
dayNames: ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'],
dayNamesShort: ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'],
buttonText: {
prev: "<span class='fc-text-arrow'>‹</span>",
next: "<span class='fc-text-arrow'>›</span>",
prevYear: "<span class='fc-text-arrow'>«</span>",
nextYear: "<span class='fc-text-arrow'>»</span>",
today: 'today',
month: 'month',
week: 'week',
day: 'day'
},
// jquery-ui theming
theme: false,
buttonIcons: {
prev: 'circle-triangle-w',
next: 'circle-triangle-e'
},
//selectable: false,
unselectAuto: true,
dropAccept: '*',
handleWindowResize: true
};
// right-to-left defaults
var rtlDefaults = {
header: {
left: 'next,prev today',
center: '',
right: 'title'
},
buttonText: {
prev: "<span class='fc-text-arrow'>›</span>",
next: "<span class='fc-text-arrow'>‹</span>",
prevYear: "<span class='fc-text-arrow'>»</span>",
nextYear: "<span class='fc-text-arrow'>«</span>"
},
buttonIcons: {
prev: 'circle-triangle-e',
next: 'circle-triangle-w'
}
};
;;
var fc = $.fullCalendar = { version: "1.6.4" };
var fcViews = fc.views = {};
$.fn.fullCalendar = function(options) {
// method calling
if (typeof options == 'string') {
var args = Array.prototype.slice.call(arguments, 1);
var res;
this.each(function() {
var calendar = $.data(this, 'fullCalendar');
if (calendar && $.isFunction(calendar[options])) {
var r = calendar[options].apply(calendar, args);
if (res === undefined) {
res = r;
}
if (options == 'destroy') {
$.removeData(this, 'fullCalendar');
}
}
});
if (res !== undefined) {
return res;
}
return this;
}
options = options || {};
// would like to have this logic in EventManager, but needs to happen before options are recursively extended
var eventSources = options.eventSources || [];
delete options.eventSources;
if (options.events) {
eventSources.push(options.events);
delete options.events;
}
options = $.extend(true, {},
defaults,
(options.isRTL || options.isRTL===undefined && defaults.isRTL) ? rtlDefaults : {},
options
);
this.each(function(i, _element) {
var element = $(_element);
var calendar = new Calendar(element, options, eventSources);
element.data('fullCalendar', calendar); // TODO: look into memory leak implications
calendar.render();
});
return this;
};
// function for adding/overriding defaults
function setDefaults(d) {
$.extend(true, defaults, d);
}
;;
function Calendar(element, options, eventSources) {
var t = this;
// exports
t.options = options;
t.render = render;
t.destroy = destroy;
t.refetchEvents = refetchEvents;
t.reportEvents = reportEvents;
t.reportEventChange = reportEventChange;
t.rerenderEvents = rerenderEvents;
t.changeView = changeView;
t.select = select;
t.unselect = unselect;
t.prev = prev;
t.next = next;
t.prevYear = prevYear;
t.nextYear = nextYear;
t.today = today;
t.gotoDate = gotoDate;
t.incrementDate = incrementDate;
t.formatDate = function(format, date) { return formatDate(format, date, options) };
t.formatDates = function(format, date1, date2) { return formatDates(format, date1, date2, options) };
t.getDate = getDate;
t.getView = getView;
t.option = option;
t.trigger = trigger;
// imports
EventManager.call(t, options, eventSources);
var isFetchNeeded = t.isFetchNeeded;
var fetchEvents = t.fetchEvents;
// locals
var _element = element[0];
var header;
var headerElement;
var content;
var tm; // for making theme classes
var currentView;
var elementOuterWidth;
var suggestedViewHeight;
var resizeUID = 0;
var ignoreWindowResize = 0;
var date = new Date();
var events = [];
var _dragElement;
/* Main Rendering
-----------------------------------------------------------------------------*/
setYMD(date, options.year, options.month, options.date);
function render(inc) {
if (!content) {
initialRender();
}
else if (elementVisible()) {
// mainly for the public API
calcSize();
_renderView(inc);
}
}
function initialRender() {
tm = options.theme ? 'ui' : 'fc';
element.addClass('fc');
if (options.isRTL) {
element.addClass('fc-rtl');
}
else {
element.addClass('fc-ltr');
}
if (options.theme) {
element.addClass('ui-widget');
}
content = $("<div class='fc-content' style='position:relative'/>")
.prependTo(element);
header = new Header(t, options);
headerElement = header.render();
if (headerElement) {
element.prepend(headerElement);
}
changeView(options.defaultView);
if (options.handleWindowResize) {
$(window).resize(windowResize);
}
// needed for IE in a 0x0 iframe, b/c when it is resized, never triggers a windowResize
if (!bodyVisible()) {
lateRender();
}
}
// called when we know the calendar couldn't be rendered when it was initialized,
// but we think it's ready now
function lateRender() {
setTimeout(function() { // IE7 needs this so dimensions are calculated correctly
if (!currentView.start && bodyVisible()) { // !currentView.start makes sure this never happens more than once
renderView();
}
},0);
}
function destroy() {
if (currentView) {
trigger('viewDestroy', currentView, currentView, currentView.element);
currentView.triggerEventDestroy();
}
$(window).unbind('resize', windowResize);
header.destroy();
content.remove();
element.removeClass('fc fc-rtl ui-widget');
}
function elementVisible() {
return element.is(':visible');
}
function bodyVisible() {
return $('body').is(':visible');
}
/* View Rendering
-----------------------------------------------------------------------------*/
function changeView(newViewName) {
if (!currentView || newViewName != currentView.name) {
_changeView(newViewName);
}
}
function _changeView(newViewName) {
ignoreWindowResize++;
if (currentView) {
trigger('viewDestroy', currentView, currentView, currentView.element);
unselect();
currentView.triggerEventDestroy(); // trigger 'eventDestroy' for each event
freezeContentHeight();
currentView.element.remove();
header.deactivateButton(currentView.name);
}
header.activateButton(newViewName);
currentView = new fcViews[newViewName](
$("<div class='fc-view fc-view-" + newViewName + "' style='position:relative'/>")
.appendTo(content),
t // the calendar object
);
renderView();
unfreezeContentHeight();
ignoreWindowResize--;
}
function renderView(inc) {
if (
!currentView.start || // never rendered before
inc || date < currentView.start || date >= currentView.end // or new date range
) {
if (elementVisible()) {
_renderView(inc);
}
}
}
function _renderView(inc) { // assumes elementVisible
ignoreWindowResize++;
if (currentView.start) { // already been rendered?
trigger('viewDestroy', currentView, currentView, currentView.element);
unselect();
clearEvents();
}
freezeContentHeight();
currentView.render(date, inc || 0); // the view's render method ONLY renders the skeleton, nothing else
setSize();
unfreezeContentHeight();
(currentView.afterRender || noop)();
updateTitle();
updateTodayButton();
trigger('viewRender', currentView, currentView, currentView.element);
currentView.trigger('viewDisplay', _element); // deprecated
ignoreWindowResize--;
getAndRenderEvents();
}
/* Resizing
-----------------------------------------------------------------------------*/
function updateSize() {
if (elementVisible()) {
unselect();
clearEvents();
calcSize();
setSize();
renderEvents();
}
}
function calcSize() { // assumes elementVisible
if (options.contentHeight) {
suggestedViewHeight = options.contentHeight;
}
else if (options.height) {
suggestedViewHeight = options.height - (headerElement ? headerElement.height() : 0) - vsides(content);
}
else {
suggestedViewHeight = Math.round(content.width() / Math.max(options.aspectRatio, .5));
}
}
function setSize() { // assumes elementVisible
if (suggestedViewHeight === undefined) {
calcSize(); // for first time
// NOTE: we don't want to recalculate on every renderView because
// it could result in oscillating heights due to scrollbars.
}
ignoreWindowResize++;
currentView.setHeight(suggestedViewHeight);
currentView.setWidth(content.width());
ignoreWindowResize--;
elementOuterWidth = element.outerWidth();
}
function windowResize() {
if (!ignoreWindowResize) {
if (currentView.start) { // view has already been rendered
var uid = ++resizeUID;
setTimeout(function() { // add a delay
if (uid == resizeUID && !ignoreWindowResize && elementVisible()) {
if (elementOuterWidth != (elementOuterWidth = element.outerWidth())) {
ignoreWindowResize++; // in case the windowResize callback changes the height
updateSize();
currentView.trigger('windowResize', _element);
ignoreWindowResize--;
}
}
}, 200);
}else{
// calendar must have been initialized in a 0x0 iframe that has just been resized
lateRender();
}
}
}
/* Event Fetching/Rendering
-----------------------------------------------------------------------------*/
// TODO: going forward, most of this stuff should be directly handled by the view
function refetchEvents() { // can be called as an API method
clearEvents();
fetchAndRenderEvents();
}
function rerenderEvents(modifiedEventID) { // can be called as an API method
clearEvents();
renderEvents(modifiedEventID);
}
function renderEvents(modifiedEventID) { // TODO: remove modifiedEventID hack
if (elementVisible()) {
currentView.setEventData(events); // for View.js, TODO: unify with renderEvents
currentView.renderEvents(events, modifiedEventID); // actually render the DOM elements
currentView.trigger('eventAfterAllRender');
}
}
function clearEvents() {
currentView.triggerEventDestroy(); // trigger 'eventDestroy' for each event
currentView.clearEvents(); // actually remove the DOM elements
currentView.clearEventData(); // for View.js, TODO: unify with clearEvents
}
function getAndRenderEvents() {
if (!options.lazyFetching || isFetchNeeded(currentView.visStart, currentView.visEnd)) {
fetchAndRenderEvents();
}
else {
renderEvents();
}
}
function fetchAndRenderEvents() {
fetchEvents(currentView.visStart, currentView.visEnd);
// ... will call reportEvents
// ... which will call renderEvents
}
// called when event data arrives
function reportEvents(_events) {
events = _events;
renderEvents();
}
// called when a single event's data has been changed
function reportEventChange(eventID) {
rerenderEvents(eventID);
}
/* Header Updating
-----------------------------------------------------------------------------*/
function updateTitle() {
header.updateTitle(currentView.title);
}
function updateTodayButton() {
var today = new Date();
if (today >= currentView.start && today < currentView.end) {
header.disableButton('today');
}
else {
header.enableButton('today');
}
}
/* Selection
-----------------------------------------------------------------------------*/
function select(start, end, allDay) {
currentView.select(start, end, allDay===undefined ? true : allDay);
}
function unselect() { // safe to be called before renderView
if (currentView) {
currentView.unselect();
}
}
/* Date
-----------------------------------------------------------------------------*/
function prev() {
renderView(-1);
}
function next() {
renderView(1);
}
function prevYear() {
addYears(date, -1);
renderView();
}
function nextYear() {
addYears(date, 1);
renderView();
}
function today() {
date = new Date();
renderView();
}
function gotoDate(year, month, dateOfMonth) {
if (year instanceof Date) {
date = cloneDate(year); // provided 1 argument, a Date
}else{
setYMD(date, year, month, dateOfMonth);
}
renderView();
}
function incrementDate(years, months, days) {
if (years !== undefined) {
addYears(date, years);
}
if (months !== undefined) {
addMonths(date, months);
}
if (days !== undefined) {
addDays(date, days);
}
renderView();
}
function getDate() {
return cloneDate(date);
}
/* Height "Freezing"
-----------------------------------------------------------------------------*/
function freezeContentHeight() {
content.css({
width: '100%',
height: content.height(),
overflow: 'hidden'
});
}
function unfreezeContentHeight() {
content.css({
width: '',
height: '',
overflow: ''
});
}
/* Misc
-----------------------------------------------------------------------------*/
function getView() {
return currentView;
}
function option(name, value) {
if (value === undefined) {
return options[name];
}
if (name == 'height' || name == 'contentHeight' || name == 'aspectRatio') {
options[name] = value;
updateSize();
}
}
function trigger(name, thisObj) {
if (options[name]) {
return options[name].apply(
thisObj || _element,
Array.prototype.slice.call(arguments, 2)
);
}
}
/* External Dragging
------------------------------------------------------------------------*/
if (options.droppable) {
$(document)
.bind('dragstart', function(ev, ui) {
var _e = ev.target;
var e = $(_e);
if (!e.parents('.fc').length) { // not already inside a calendar
var accept = options.dropAccept;
if ($.isFunction(accept) ? accept.call(_e, e) : e.is(accept)) {
_dragElement = _e;
currentView.dragStart(_dragElement, ev, ui);
}
}
})
.bind('dragstop', function(ev, ui) {
if (_dragElement) {
currentView.dragStop(_dragElement, ev, ui);
_dragElement = null;
}
});
}
}
;;
function Header(calendar, options) {
var t = this;
// exports
t.render = render;
t.destroy = destroy;
t.updateTitle = updateTitle;
t.activateButton = activateButton;
t.deactivateButton = deactivateButton;
t.disableButton = disableButton;
t.enableButton = enableButton;
// locals
var element = $([]);
var tm;
function render() {
tm = options.theme ? 'ui' : 'fc';
var sections = options.header;
if (sections) {
element = $("<table class='fc-header' style='width:100%'/>")
.append(
$("<tr/>")
.append(renderSection('left'))
.append(renderSection('center'))
.append(renderSection('right'))
);
return element;
}
}
function destroy() {
element.remove();
}
function renderSection(position) {
var e = $("<td class='fc-header-" + position + "'/>");
var buttonStr = options.header[position];
if (buttonStr) {
$.each(buttonStr.split(' '), function(i) {
if (i > 0) {
e.append("<span class='fc-header-space'/>");
}
var prevButton;
$.each(this.split(','), function(j, buttonName) {
if (buttonName == 'title') {
e.append("<span class='fc-header-title'><h2> </h2></span>");
if (prevButton) {
prevButton.addClass(tm + '-corner-right');
}
prevButton = null;
}else{
var buttonClick;
if (calendar[buttonName]) {
buttonClick = calendar[buttonName]; // calendar method
}
else if (fcViews[buttonName]) {
buttonClick = function() {
button.removeClass(tm + '-state-hover'); // forget why
calendar.changeView(buttonName);
};
}
if (buttonClick) {
var icon = options.theme ? smartProperty(options.buttonIcons, buttonName) : null; // why are we using smartProperty here?
var text = smartProperty(options.buttonText, buttonName); // why are we using smartProperty here?
var button = $(
"<span class='fc-button fc-button-" + buttonName + " " + tm + "-state-default'>" +
(icon ?
"<span class='fc-icon-wrap'>" +
"<span class='ui-icon ui-icon-" + icon + "'/>" +
"</span>" :
text
) +
"</span>"
)
.click(function() {
if (!button.hasClass(tm + '-state-disabled')) {
buttonClick();
}
})
.mousedown(function() {
button
.not('.' + tm + '-state-active')
.not('.' + tm + '-state-disabled')
.addClass(tm + '-state-down');
})
.mouseup(function() {
button.removeClass(tm + '-state-down');
})
.hover(
function() {
button
.not('.' + tm + '-state-active')
.not('.' + tm + '-state-disabled')
.addClass(tm + '-state-hover');
},
function() {
button
.removeClass(tm + '-state-hover')
.removeClass(tm + '-state-down');
}
)
.appendTo(e);
disableTextSelection(button);
if (!prevButton) {
button.addClass(tm + '-corner-left');
}
prevButton = button;
}
}
});
if (prevButton) {
prevButton.addClass(tm + '-corner-right');
}
});
}
return e;
}
function updateTitle(html) {
element.find('h2')
.html(html);
}
function activateButton(buttonName) {
element.find('span.fc-button-' + buttonName)
.addClass(tm + '-state-active');
}
function deactivateButton(buttonName) {
element.find('span.fc-button-' + buttonName)
.removeClass(tm + '-state-active');
}
function disableButton(buttonName) {
element.find('span.fc-button-' + buttonName)
.addClass(tm + '-state-disabled');
}
function enableButton(buttonName) {
element.find('span.fc-button-' + buttonName)
.removeClass(tm + '-state-disabled');
}
}
;;
fc.sourceNormalizers = [];
fc.sourceFetchers = [];
var ajaxDefaults = {
dataType: 'json',
cache: false
};
var eventGUID = 1;
function EventManager(options, _sources) {
var t = this;
// exports
t.isFetchNeeded = isFetchNeeded;
t.fetchEvents = fetchEvents;
t.addEventSource = addEventSource;
t.removeEventSource = removeEventSource;
t.updateEvent = updateEvent;
t.renderEvent = renderEvent;
t.removeEvents = removeEvents;
t.clientEvents = clientEvents;
t.normalizeEvent = normalizeEvent;
// imports
var trigger = t.trigger;
var getView = t.getView;
var reportEvents = t.reportEvents;
// locals
var stickySource = { events: [] };
var sources = [ stickySource ];
var rangeStart, rangeEnd;
var currentFetchID = 0;
var pendingSourceCnt = 0;
var loadingLevel = 0;
var cache = [];
for (var i=0; i<_sources.length; i++) {
_addEventSource(_sources[i]);
}
/* Fetching
-----------------------------------------------------------------------------*/
function isFetchNeeded(start, end) {
return !rangeStart || start < rangeStart || end > rangeEnd;
}
function fetchEvents(start, end) {
rangeStart = start;
rangeEnd = end;
cache = [];
var fetchID = ++currentFetchID;
var len = sources.length;
pendingSourceCnt = len;
for (var i=0; i<len; i++) {
fetchEventSource(sources[i], fetchID);
}
}
function fetchEventSource(source, fetchID) {
_fetchEventSource(source, function(events) {
if (fetchID == currentFetchID) {
if (events) {
if (options.eventDataTransform) {
events = $.map(events, options.eventDataTransform);
}
if (source.eventDataTransform) {
events = $.map(events, source.eventDataTransform);
}
// TODO: this technique is not ideal for static array event sources.
// For arrays, we'll want to process all events right in the beginning, then never again.
for (var i=0; i<events.length; i++) {
events[i].source = source;
normalizeEvent(events[i]);
}
cache = cache.concat(events);
}
pendingSourceCnt--;
if (!pendingSourceCnt) {
reportEvents(cache);
}
}
});
}
function _fetchEventSource(source, callback) {
var i;
var fetchers = fc.sourceFetchers;
var res;
for (i=0; i<fetchers.length; i++) {
res = fetchers[i](source, rangeStart, rangeEnd, callback);
if (res === true) {
// the fetcher is in charge. made its own async request
return;
}
else if (typeof res == 'object') {
// the fetcher returned a new source. process it
_fetchEventSource(res, callback);
return;
}
}
var events = source.events;
if (events) {
if ($.isFunction(events)) {
pushLoading();
events(cloneDate(rangeStart), cloneDate(rangeEnd), function(events) {
callback(events);
popLoading();
});
}
else if ($.isArray(events)) {
callback(events);
}
else {
callback();
}
}else{
var url = source.url;
if (url) {
var success = source.success;
var error = source.error;
var complete = source.complete;
// retrieve any outbound GET/POST $.ajax data from the options
var customData;
if ($.isFunction(source.data)) {
// supplied as a function that returns a key/value object
customData = source.data();
}
else {
// supplied as a straight key/value object
customData = source.data;
}
// use a copy of the custom data so we can modify the parameters
// and not affect the passed-in object.
var data = $.extend({}, customData || {});
var startParam = firstDefined(source.startParam, options.startParam);
var endParam = firstDefined(source.endParam, options.endParam);
if (startParam) {
data[startParam] = Math.round(+rangeStart / 1000);
}
if (endParam) {
data[endParam] = Math.round(+rangeEnd / 1000);
}
pushLoading();
$.ajax($.extend({}, ajaxDefaults, source, {
data: data,
success: function(events) {
events = events || [];
var res = applyAll(success, this, arguments);
if ($.isArray(res)) {
events = res;
}
callback(events);
},
error: function() {
applyAll(error, this, arguments);
callback();
},
complete: function() {
applyAll(complete, this, arguments);
popLoading();
}
}));
}else{
callback();
}
}
}
/* Sources
-----------------------------------------------------------------------------*/
function addEventSource(source) {
source = _addEventSource(source);
if (source) {
pendingSourceCnt++;
fetchEventSource(source, currentFetchID); // will eventually call reportEvents
}
}
function _addEventSource(source) {
if ($.isFunction(source) || $.isArray(source)) {
source = { events: source };
}
else if (typeof source == 'string') {
source = { url: source };
}
if (typeof source == 'object') {
normalizeSource(source);
sources.push(source);
return source;
}
}
function removeEventSource(source) {
sources = $.grep(sources, function(src) {
return !isSourcesEqual(src, source);
});
// remove all client events from that source
cache = $.grep(cache, function(e) {
return !isSourcesEqual(e.source, source);
});
reportEvents(cache);
}
/* Manipulation
-----------------------------------------------------------------------------*/
function updateEvent(event) { // update an existing event
var i, len = cache.length, e,
defaultEventEnd = getView().defaultEventEnd, // getView???
startDelta = event.start - event._start,
endDelta = event.end ?
(event.end - (event._end || defaultEventEnd(event))) // event._end would be null if event.end
: 0; // was null and event was just resized
for (i=0; i<len; i++) {
e = cache[i];
if (e._id == event._id && e != event) {
e.start = new Date(+e.start + startDelta);
if (event.end) {
if (e.end) {
e.end = new Date(+e.end + endDelta);
}else{
e.end = new Date(+defaultEventEnd(e) + endDelta);
}
}else{
e.end = null;
}
e.title = event.title;
e.url = event.url;
e.allDay = event.allDay;
e.className = event.className;
e.editable = event.editable;
e.color = event.color;
e.backgroundColor = event.backgroundColor;
e.borderColor = event.borderColor;
e.textColor = event.textColor;
normalizeEvent(e);
}
}
normalizeEvent(event);
reportEvents(cache);
}
function renderEvent(event, stick) {
normalizeEvent(event);
if (!event.source) {
if (stick) {
stickySource.events.push(event);
event.source = stickySource;
}
cache.push(event);
}
reportEvents(cache);
}
function removeEvents(filter) {
if (!filter) { // remove all
cache = [];
// clear all array sources
for (var i=0; i<sources.length; i++) {
if ($.isArray(sources[i].events)) {
sources[i].events = [];
}
}
}else{
if (!$.isFunction(filter)) { // an event ID
var id = filter + '';
filter = function(e) {
return e._id == id;
};
}
cache = $.grep(cache, filter, true);
// remove events from array sources
for (var i=0; i<sources.length; i++) {
if ($.isArray(sources[i].events)) {
sources[i].events = $.grep(sources[i].events, filter, true);
}
}
}
reportEvents(cache);
}
function clientEvents(filter) {
if ($.isFunction(filter)) {
return $.grep(cache, filter);
}
else if (filter) { // an event ID
filter += '';
return $.grep(cache, function(e) {
return e._id == filter;
});
}
return cache; // else, return all
}
/* Loading State
-----------------------------------------------------------------------------*/
function pushLoading() {
if (!loadingLevel++) {
trigger('loading', null, true, getView());
}
}
function popLoading() {
if (!--loadingLevel) {
trigger('loading', null, false, getView());
}
}
/* Event Normalization
-----------------------------------------------------------------------------*/
function normalizeEvent(event) {
var source = event.source || {};
var ignoreTimezone = firstDefined(source.ignoreTimezone, options.ignoreTimezone);
event._id = event._id || (event.id === undefined ? '_fc' + eventGUID++ : event.id + '');
if (event.date) {
if (!event.start) {
event.start = event.date;
}
delete event.date;
}
event._start = cloneDate(event.start = parseDate(event.start, ignoreTimezone));
event.end = parseDate(event.end, ignoreTimezone);
if (event.end && event.end <= event.start) {
event.end = null;
}
event._end = event.end ? cloneDate(event.end) : null;
if (event.allDay === undefined) {
event.allDay = firstDefined(source.allDayDefault, options.allDayDefault);
}
if (event.className) {
if (typeof event.className == 'string') {
event.className = event.className.split(/\s+/);
}
}else{
event.className = [];
}
// TODO: if there is no start date, return false to indicate an invalid event
}
/* Utils
------------------------------------------------------------------------------*/
function normalizeSource(source) {
if (source.className) {
// TODO: repeat code, same code for event classNames
if (typeof source.className == 'string') {
source.className = source.className.split(/\s+/);
}
}else{
source.className = [];
}
var normalizers = fc.sourceNormalizers;
for (var i=0; i<normalizers.length; i++) {
normalizers[i](source);
}
}
function isSourcesEqual(source1, source2) {
return source1 && source2 && getSourcePrimitive(source1) == getSourcePrimitive(source2);
}
function getSourcePrimitive(source) {
return ((typeof source == 'object') ? (source.events || source.url) : '') || source;
}
}
;;
fc.addDays = addDays;
fc.cloneDate = cloneDate;
fc.parseDate = parseDate;
fc.parseISO8601 = parseISO8601;
fc.parseTime = parseTime;
fc.formatDate = formatDate;
fc.formatDates = formatDates;
/* Date Math
-----------------------------------------------------------------------------*/
var dayIDs = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'],
DAY_MS = 86400000,
HOUR_MS = 3600000,
MINUTE_MS = 60000;
function addYears(d, n, keepTime) {
d.setFullYear(d.getFullYear() + n);
if (!keepTime) {
clearTime(d);
}
return d;
}
function addMonths(d, n, keepTime) { // prevents day overflow/underflow
if (+d) { // prevent infinite looping on invalid dates
var m = d.getMonth() + n,
check = cloneDate(d);
check.setDate(1);
check.setMonth(m);
d.setMonth(m);
if (!keepTime) {
clearTime(d);
}
while (d.getMonth() != check.getMonth()) {
d.setDate(d.getDate() + (d < check ? 1 : -1));
}
}
return d;
}
function addDays(d, n, keepTime) { // deals with daylight savings
if (+d) {
var dd = d.getDate() + n,
check = cloneDate(d);
check.setHours(9); // set to middle of day
check.setDate(dd);
d.setDate(dd);
if (!keepTime) {
clearTime(d);
}
fixDate(d, check);
}
return d;
}
function fixDate(d, check) { // force d to be on check's YMD, for daylight savings purposes
if (+d) { // prevent infinite looping on invalid dates
while (d.getDate() != check.getDate()) {
d.setTime(+d + (d < check ? 1 : -1) * HOUR_MS);
}
}
}
function addMinutes(d, n) {
d.setMinutes(d.getMinutes() + n);
return d;
}
function clearTime(d) {
d.setHours(0);
d.setMinutes(0);
d.setSeconds(0);
d.setMilliseconds(0);
return d;
}
function cloneDate(d, dontKeepTime) {
if (dontKeepTime) {
return clearTime(new Date(+d));
}
return new Date(+d);
}
function zeroDate() { // returns a Date with time 00:00:00 and dateOfMonth=1
var i=0, d;
do {
d = new Date(1970, i++, 1);
} while (d.getHours()); // != 0
return d;
}
function dayDiff(d1, d2) { // d1 - d2
return Math.round((cloneDate(d1, true) - cloneDate(d2, true)) / DAY_MS);
}
function setYMD(date, y, m, d) {
if (y !== undefined && y != date.getFullYear()) {
date.setDate(1);
date.setMonth(0);
date.setFullYear(y);
}
if (m !== undefined && m != date.getMonth()) {
date.setDate(1);
date.setMonth(m);
}
if (d !== undefined) {
date.setDate(d);
}
}
/* Date Parsing
-----------------------------------------------------------------------------*/
function parseDate(s, ignoreTimezone) { // ignoreTimezone defaults to true
if (typeof s == 'object') { // already a Date object
return s;
}
if (typeof s == 'number') { // a UNIX timestamp
return new Date(s * 1000);
}
if (typeof s == 'string') {
if (s.match(/^\d+(\.\d+)?$/)) { // a UNIX timestamp
return new Date(parseFloat(s) * 1000);
}
if (ignoreTimezone === undefined) {
ignoreTimezone = true;
}
return parseISO8601(s, ignoreTimezone) || (s ? new Date(s) : null);
}
// TODO: never return invalid dates (like from new Date(<string>)), return null instead
return null;
}
function parseISO8601(s, ignoreTimezone) { // ignoreTimezone defaults to false
// derived from http://delete.me.uk/2005/03/iso8601.html
// TODO: for a know glitch/feature, read tests/issue_206_parseDate_dst.html
var m = s.match(/^([0-9]{4})(-([0-9]{2})(-([0-9]{2})([T ]([0-9]{2}):([0-9]{2})(:([0-9]{2})(\.([0-9]+))?)?(Z|(([-+])([0-9]{2})(:?([0-9]{2}))?))?)?)?)?$/);
if (!m) {
return null;
}
var date = new Date(m[1], 0, 1);
if (ignoreTimezone || !m[13]) {
var check = new Date(m[1], 0, 1, 9, 0);
if (m[3]) {
date.setMonth(m[3] - 1);
check.setMonth(m[3] - 1);
}
if (m[5]) {
date.setDate(m[5]);
check.setDate(m[5]);
}
fixDate(date, check);
if (m[7]) {
date.setHours(m[7]);
}
if (m[8]) {
date.setMinutes(m[8]);
}
if (m[10]) {
date.setSeconds(m[10]);
}
if (m[12]) {
date.setMilliseconds(Number("0." + m[12]) * 1000);
}
fixDate(date, check);
}else{
date.setUTCFullYear(
m[1],
m[3] ? m[3] - 1 : 0,
m[5] || 1
);
date.setUTCHours(
m[7] || 0,
m[8] || 0,
m[10] || 0,
m[12] ? Number("0." + m[12]) * 1000 : 0
);
if (m[14]) {
var offset = Number(m[16]) * 60 + (m[18] ? Number(m[18]) : 0);
offset *= m[15] == '-' ? 1 : -1;
date = new Date(+date + (offset * 60 * 1000));
}
}
return date;
}
function parseTime(s) { // returns minutes since start of day
if (typeof s == 'number') { // an hour
return s * 60;
}
if (typeof s == 'object') { // a Date object
return s.getHours() * 60 + s.getMinutes();
}
var m = s.match(/(\d+)(?::(\d+))?\s*(\w+)?/);
if (m) {
var h = parseInt(m[1], 10);
if (m[3]) {
h %= 12;
if (m[3].toLowerCase().charAt(0) == 'p') {
h += 12;
}
}
return h * 60 + (m[2] ? parseInt(m[2], 10) : 0);
}
}
/* Date Formatting
-----------------------------------------------------------------------------*/
// TODO: use same function formatDate(date, [date2], format, [options])
function formatDate(date, format, options) {
return formatDates(date, null, format, options);
}
function formatDates(date1, date2, format, options) {
options = options || defaults;
var date = date1,
otherDate = date2,
i, len = format.length, c,
i2, formatter,
res = '';
for (i=0; i<len; i++) {
c = format.charAt(i);
if (c == "'") {
for (i2=i+1; i2<len; i2++) {
if (format.charAt(i2) == "'") {
if (date) {
if (i2 == i+1) {
res += "'";
}else{
res += format.substring(i+1, i2);
}
i = i2;
}
break;
}
}
}
else if (c == '(') {
for (i2=i+1; i2<len; i2++) {
if (format.charAt(i2) == ')') {
var subres = formatDate(date, format.substring(i+1, i2), options);
if (parseInt(subres.replace(/\D/, ''), 10)) {
res += subres;
}
i = i2;
break;
}
}
}
else if (c == '[') {
for (i2=i+1; i2<len; i2++) {
if (format.charAt(i2) == ']') {
var subformat = format.substring(i+1, i2);
var subres = formatDate(date, subformat, options);
if (subres != formatDate(otherDate, subformat, options)) {
res += subres;
}
i = i2;
break;
}
}
}
else if (c == '{') {
date = date2;
otherDate = date1;
}
else if (c == '}') {
date = date1;
otherDate = date2;
}
else {
for (i2=len; i2>i; i2--) {
if (formatter = dateFormatters[format.substring(i, i2)]) {
if (date) {
res += formatter(date, options);
}
i = i2 - 1;
break;
}
}
if (i2 == i) {
if (date) {
res += c;
}
}
}
}
return res;
};
var dateFormatters = {
s : function(d) { return d.getSeconds() },
ss : function(d) { return zeroPad(d.getSeconds()) },
m : function(d) { return d.getMinutes() },
mm : function(d) { return zeroPad(d.getMinutes()) },
h : function(d) { return d.getHours() % 12 || 12 },
hh : function(d) { return zeroPad(d.getHours() % 12 || 12) },
H : function(d) { return d.getHours() },
HH : function(d) { return zeroPad(d.getHours()) },
d : function(d) { return d.getDate() },
dd : function(d) { return zeroPad(d.getDate()) },
ddd : function(d,o) { return o.dayNamesShort[d.getDay()] },
dddd: function(d,o) { return o.dayNames[d.getDay()] },
M : function(d) { return d.getMonth() + 1 },
MM : function(d) { return zeroPad(d.getMonth() + 1) },
MMM : function(d,o) { return o.monthNamesShort[d.getMonth()] },
MMMM: function(d,o) { return o.monthNames[d.getMonth()] },
yy : function(d) { return (d.getFullYear()+'').substring(2) },
yyyy: function(d) { return d.getFullYear() },
t : function(d) { return d.getHours() < 12 ? 'a' : 'p' },
tt : function(d) { return d.getHours() < 12 ? 'am' : 'pm' },
T : function(d) { return d.getHours() < 12 ? 'A' : 'P' },
TT : function(d) { return d.getHours() < 12 ? 'AM' : 'PM' },
u : function(d) { return formatDate(d, "yyyy-MM-dd'T'HH:mm:ss'Z'") },
S : function(d) {
var date = d.getDate();
if (date > 10 && date < 20) {
return 'th';
}
return ['st', 'nd', 'rd'][date%10-1] || 'th';
},
w : function(d, o) { // local
return o.weekNumberCalculation(d);
},
W : function(d) { // ISO
return iso8601Week(d);
}
};
fc.dateFormatters = dateFormatters;
/* thanks jQuery UI (https://github.com/jquery/jquery-ui/blob/master/ui/jquery.ui.datepicker.js)
*
* Set as calculateWeek to determine the week of the year based on the ISO 8601 definition.
* `date` - the date to get the week for
* `number` - the number of the week within the year that contains this date
*/
function iso8601Week(date) {
var time;
var checkDate = new Date(date.getTime());
// Find Thursday of this week starting on Monday
checkDate.setDate(checkDate.getDate() + 4 - (checkDate.getDay() || 7));
time = checkDate.getTime();
checkDate.setMonth(0); // Compare with Jan 1
checkDate.setDate(1);
return Math.floor(Math.round((time - checkDate) / 86400000) / 7) + 1;
}
;;
fc.applyAll = applyAll;
/* Event Date Math
-----------------------------------------------------------------------------*/
function exclEndDay(event) {
if (event.end) {
return _exclEndDay(event.end, event.allDay);
}else{
return addDays(cloneDate(event.start), 1);
}
}
function _exclEndDay(end, allDay) {
end = cloneDate(end);
return allDay || end.getHours() || end.getMinutes() ? addDays(end, 1) : clearTime(end);
// why don't we check for seconds/ms too?
}
/* Event Element Binding
-----------------------------------------------------------------------------*/
function lazySegBind(container, segs, bindHandlers) {
container.unbind('mouseover').mouseover(function(ev) {
var parent=ev.target, e,
i, seg;
while (parent != this) {
e = parent;
parent = parent.parentNode;
}
if ((i = e._fci) !== undefined) {
e._fci = undefined;
seg = segs[i];
bindHandlers(seg.event, seg.element, seg);
$(ev.target).trigger(ev);
}
ev.stopPropagation();
});
}
/* Element Dimensions
-----------------------------------------------------------------------------*/
function setOuterWidth(element, width, includeMargins) {
for (var i=0, e; i<element.length; i++) {
e = $(element[i]);
e.width(Math.max(0, width - hsides(e, includeMargins)));
}
}
function setOuterHeight(element, height, includeMargins) {
for (var i=0, e; i<element.length; i++) {
e = $(element[i]);
e.height(Math.max(0, height - vsides(e, includeMargins)));
}
}
function hsides(element, includeMargins) {
return hpadding(element) + hborders(element) + (includeMargins ? hmargins(element) : 0);
}
function hpadding(element) {
return (parseFloat($.css(element[0], 'paddingLeft', true)) || 0) +
(parseFloat($.css(element[0], 'paddingRight', true)) || 0);
}
function hmargins(element) {
return (parseFloat($.css(element[0], 'marginLeft', true)) || 0) +
(parseFloat($.css(element[0], 'marginRight', true)) || 0);
}
function hborders(element) {
return (parseFloat($.css(element[0], 'borderLeftWidth', true)) || 0) +
(parseFloat($.css(element[0], 'borderRightWidth', true)) || 0);
}
function vsides(element, includeMargins) {
return vpadding(element) + vborders(element) + (includeMargins ? vmargins(element) : 0);
}
function vpadding(element) {
return (parseFloat($.css(element[0], 'paddingTop', true)) || 0) +
(parseFloat($.css(element[0], 'paddingBottom', true)) || 0);
}
function vmargins(element) {
return (parseFloat($.css(element[0], 'marginTop', true)) || 0) +
(parseFloat($.css(element[0], 'marginBottom', true)) || 0);
}
function vborders(element) {
return (parseFloat($.css(element[0], 'borderTopWidth', true)) || 0) +
(parseFloat($.css(element[0], 'borderBottomWidth', true)) || 0);
}
/* Misc Utils
-----------------------------------------------------------------------------*/
//TODO: arraySlice
//TODO: isFunction, grep ?
function noop() { }
function dateCompare(a, b) {
return a - b;
}
function arrayMax(a) {
return Math.max.apply(Math, a);
}
function zeroPad(n) {
return (n < 10 ? '0' : '') + n;
}
function smartProperty(obj, name) { // get a camel-cased/namespaced property of an object
if (obj[name] !== undefined) {
return obj[name];
}
var parts = name.split(/(?=[A-Z])/),
i=parts.length-1, res;
for (; i>=0; i--) {
res = obj[parts[i].toLowerCase()];
if (res !== undefined) {
return res;
}
}
return obj[''];
}
function htmlEscape(s) {
return s.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/'/g, ''')
.replace(/"/g, '"')
.replace(/\n/g, '<br />');
}
function disableTextSelection(element) {
element
.attr('unselectable', 'on')
.css('MozUserSelect', 'none')
.bind('selectstart.ui', function() { return false; });
}
/*
function enableTextSelection(element) {
element
.attr('unselectable', 'off')
.css('MozUserSelect', '')
.unbind('selectstart.ui');
}
*/
function markFirstLast(e) {
e.children()
.removeClass('fc-first fc-last')
.filter(':first-child')
.addClass('fc-first')
.end()
.filter(':last-child')
.addClass('fc-last');
}
function setDayID(cell, date) {
cell.each(function(i, _cell) {
_cell.className = _cell.className.replace(/^fc-\w*/, 'fc-' + dayIDs[date.getDay()]);
// TODO: make a way that doesn't rely on order of classes
});
}
function getSkinCss(event, opt) {
var source = event.source || {};
var eventColor = event.color;
var sourceColor = source.color;
var optionColor = opt('eventColor');
var backgroundColor =
event.backgroundColor ||
eventColor ||
source.backgroundColor ||
sourceColor ||
opt('eventBackgroundColor') ||
optionColor;
var borderColor =
event.borderColor ||
eventColor ||
source.borderColor ||
sourceColor ||
opt('eventBorderColor') ||
optionColor;
var textColor =
event.textColor ||
source.textColor ||
opt('eventTextColor');
var statements = [];
if (backgroundColor) {
statements.push('background-color:' + backgroundColor);
}
if (borderColor) {
statements.push('border-color:' + borderColor);
}
if (textColor) {
statements.push('color:' + textColor);
}
return statements.join(';');
}
function applyAll(functions, thisObj, args) {
if ($.isFunction(functions)) {
functions = [ functions ];
}
if (functions) {
var i;
var ret;
for (i=0; i<functions.length; i++) {
ret = functions[i].apply(thisObj, args) || ret;
}
return ret;
}
}
function firstDefined() {
for (var i=0; i<arguments.length; i++) {
if (arguments[i] !== undefined) {
return arguments[i];
}
}
}
;;
fcViews.month = MonthView;
function MonthView(element, calendar) {
var t = this;
// exports
t.render = render;
// imports
BasicView.call(t, element, calendar, 'month');
var opt = t.opt;
var renderBasic = t.renderBasic;
var skipHiddenDays = t.skipHiddenDays;
var getCellsPerWeek = t.getCellsPerWeek;
var formatDate = calendar.formatDate;
function render(date, delta) {
if (delta) {
addMonths(date, delta);
date.setDate(1);
}
var firstDay = opt('firstDay');
var start = cloneDate(date, true);
start.setDate(1);
var end = addMonths(cloneDate(start), 1);
var visStart = cloneDate(start);
addDays(visStart, -((visStart.getDay() - firstDay + 7) % 7));
skipHiddenDays(visStart);
var visEnd = cloneDate(end);
addDays(visEnd, (7 - visEnd.getDay() + firstDay) % 7);
skipHiddenDays(visEnd, -1, true);
var colCnt = getCellsPerWeek();
var rowCnt = Math.round(dayDiff(visEnd, visStart) / 7); // should be no need for Math.round
if (opt('weekMode') == 'fixed') {
addDays(visEnd, (6 - rowCnt) * 7); // add weeks to make up for it
rowCnt = 6;
}
t.title = formatDate(start, opt('titleFormat'));
t.start = start;
t.end = end;
t.visStart = visStart;
t.visEnd = visEnd;
renderBasic(rowCnt, colCnt, true);
}
}
;;
fcViews.basicWeek = BasicWeekView;
function BasicWeekView(element, calendar) {
var t = this;
// exports
t.render = render;
// imports
BasicView.call(t, element, calendar, 'basicWeek');
var opt = t.opt;
var renderBasic = t.renderBasic;
var skipHiddenDays = t.skipHiddenDays;
var getCellsPerWeek = t.getCellsPerWeek;
var formatDates = calendar.formatDates;
function render(date, delta) {
if (delta) {
addDays(date, delta * 7);
}
var start = addDays(cloneDate(date), -((date.getDay() - opt('firstDay') + 7) % 7));
var end = addDays(cloneDate(start), 7);
var visStart = cloneDate(start);
skipHiddenDays(visStart);
var visEnd = cloneDate(end);
skipHiddenDays(visEnd, -1, true);
var colCnt = getCellsPerWeek();
t.start = start;
t.end = end;
t.visStart = visStart;
t.visEnd = visEnd;
t.title = formatDates(
visStart,
addDays(cloneDate(visEnd), -1),
opt('titleFormat')
);
renderBasic(1, colCnt, false);
}
}
;;
fcViews.basicDay = BasicDayView;
function BasicDayView(element, calendar) {
var t = this;
// exports
t.render = render;
// imports
BasicView.call(t, element, calendar, 'basicDay');
var opt = t.opt;
var renderBasic = t.renderBasic;
var skipHiddenDays = t.skipHiddenDays;
var formatDate = calendar.formatDate;
function render(date, delta) {
if (delta) {
addDays(date, delta);
}
skipHiddenDays(date, delta < 0 ? -1 : 1);
var start = cloneDate(date, true);
var end = addDays(cloneDate(start), 1);
t.title = formatDate(date, opt('titleFormat'));
t.start = t.visStart = start;
t.end = t.visEnd = end;
renderBasic(1, 1, false);
}
}
;;
setDefaults({
weekMode: 'fixed'
});
function BasicView(element, calendar, viewName) {
var t = this;
// exports
t.renderBasic = renderBasic;
t.setHeight = setHeight;
t.setWidth = setWidth;
t.renderDayOverlay = renderDayOverlay;
t.defaultSelectionEnd = defaultSelectionEnd;
t.renderSelection = renderSelection;
t.clearSelection = clearSelection;
t.reportDayClick = reportDayClick; // for selection (kinda hacky)
t.dragStart = dragStart;
t.dragStop = dragStop;
t.defaultEventEnd = defaultEventEnd;
t.getHoverListener = function() { return hoverListener };
t.colLeft = colLeft;
t.colRight = colRight;
t.colContentLeft = colContentLeft;
t.colContentRight = colContentRight;
t.getIsCellAllDay = function() { return true };
t.allDayRow = allDayRow;
t.getRowCnt = function() { return rowCnt };
t.getColCnt = function() { return colCnt };
t.getColWidth = function() { return colWidth };
t.getDaySegmentContainer = function() { return daySegmentContainer };
// imports
View.call(t, element, calendar, viewName);
OverlayManager.call(t);
SelectionManager.call(t);
BasicEventRenderer.call(t);
var opt = t.opt;
var trigger = t.trigger;
var renderOverlay = t.renderOverlay;
var clearOverlays = t.clearOverlays;
var daySelectionMousedown = t.daySelectionMousedown;
var cellToDate = t.cellToDate;
var dateToCell = t.dateToCell;
var rangeToSegments = t.rangeToSegments;
var formatDate = calendar.formatDate;
// locals
var table;
var head;
var headCells;
var body;
var bodyRows;
var bodyCells;
var bodyFirstCells;
var firstRowCellInners;
var firstRowCellContentInners;
var daySegmentContainer;
var viewWidth;
var viewHeight;
var colWidth;
var weekNumberWidth;
var rowCnt, colCnt;
var showNumbers;
var coordinateGrid;
var hoverListener;
var colPositions;
var colContentPositions;
var tm;
var colFormat;
var showWeekNumbers;
var weekNumberTitle;
var weekNumberFormat;
/* Rendering
------------------------------------------------------------*/
disableTextSelection(element.addClass('fc-grid'));
function renderBasic(_rowCnt, _colCnt, _showNumbers) {
rowCnt = _rowCnt;
colCnt = _colCnt;
showNumbers = _showNumbers;
updateOptions();
if (!body) {
buildEventContainer();
}
buildTable();
}
function updateOptions() {
tm = opt('theme') ? 'ui' : 'fc';
colFormat = opt('columnFormat');
// week # options. (TODO: bad, logic also in other views)
showWeekNumbers = opt('weekNumbers');
weekNumberTitle = opt('weekNumberTitle');
if (opt('weekNumberCalculation') != 'iso') {
weekNumberFormat = "w";
}
else {
weekNumberFormat = "W";
}
}
function buildEventContainer() {
daySegmentContainer =
$("<div class='fc-event-container' style='position:absolute;z-index:8;top:0;left:0'/>")
.appendTo(element);
}
function buildTable() {
var html = buildTableHTML();
if (table) {
table.remove();
}
table = $(html).appendTo(element);
head = table.find('thead');
headCells = head.find('.fc-day-header');
body = table.find('tbody');
bodyRows = body.find('tr');
bodyCells = body.find('.fc-day');
bodyFirstCells = bodyRows.find('td:first-child');
firstRowCellInners = bodyRows.eq(0).find('.fc-day > div');
firstRowCellContentInners = bodyRows.eq(0).find('.fc-day-content > div');
markFirstLast(head.add(head.find('tr'))); // marks first+last tr/th's
markFirstLast(bodyRows); // marks first+last td's
bodyRows.eq(0).addClass('fc-first');
bodyRows.filter(':last').addClass('fc-last');
bodyCells.each(function(i, _cell) {
var date = cellToDate(
Math.floor(i / colCnt),
i % colCnt
);
trigger('dayRender', t, date, $(_cell));
});
dayBind(bodyCells);
}
/* HTML Building
-----------------------------------------------------------*/
function buildTableHTML() {
var html =
"<table class='fc-border-separate' style='width:100%' cellspacing='0'>" +
buildHeadHTML() +
buildBodyHTML() +
"</table>";
return html;
}
function buildHeadHTML() {
var headerClass = tm + "-widget-header";
var html = '';
var col;
var date;
html += "<thead><tr>";
if (showWeekNumbers) {
html +=
"<th class='fc-week-number " + headerClass + "'>" +
htmlEscape(weekNumberTitle) +
"</th>";
}
for (col=0; col<colCnt; col++) {
date = cellToDate(0, col);
html +=
"<th class='fc-day-header fc-" + dayIDs[date.getDay()] + " " + headerClass + "'>" +
htmlEscape(formatDate(date, colFormat)) +
"</th>";
}
html += "</tr></thead>";
return html;
}
function buildBodyHTML() {
var contentClass = tm + "-widget-content";
var html = '';
var row;
var col;
var date;
html += "<tbody>";
for (row=0; row<rowCnt; row++) {
html += "<tr class='fc-week'>";
if (showWeekNumbers) {
date = cellToDate(row, 0);
html +=
"<td class='fc-week-number " + contentClass + "'>" +
"<div>" +
htmlEscape(formatDate(date, weekNumberFormat)) +
"</div>" +
"</td>";
}
for (col=0; col<colCnt; col++) {
date = cellToDate(row, col);
html += buildCellHTML(date);
}
html += "</tr>";
}
html += "</tbody>";
return html;
}
function buildCellHTML(date) {
var contentClass = tm + "-widget-content";
var month = t.start.getMonth();
var today = clearTime(new Date());
var html = '';
var classNames = [
'fc-day',
'fc-' + dayIDs[date.getDay()],
contentClass
];
if (date.getMonth() != month) {
classNames.push('fc-other-month');
}
if (+date == +today) {
classNames.push(
'fc-today',
tm + '-state-highlight'
);
}
else if (date < today) {
classNames.push('fc-past');
}
else {
classNames.push('fc-future');
}
html +=
"<td" +
" class='" + classNames.join(' ') + "'" +
" data-date='" + formatDate(date, 'yyyy-MM-dd') + "'" +
">" +
"<div>";
if (showNumbers) {
html += "<div class='fc-day-number'>" + date.getDate() + "</div>";
}
html +=
"<div class='fc-day-content'>" +
"<div style='position:relative'> </div>" +
"</div>" +
"</div>" +
"</td>";
return html;
}
/* Dimensions
-----------------------------------------------------------*/
function setHeight(height) {
viewHeight = height;
var bodyHeight = viewHeight - head.height();
var rowHeight;
var rowHeightLast;
var cell;
if (opt('weekMode') == 'variable') {
rowHeight = rowHeightLast = Math.floor(bodyHeight / (rowCnt==1 ? 2 : 6));
}else{
rowHeight = Math.floor(bodyHeight / rowCnt);
rowHeightLast = bodyHeight - rowHeight * (rowCnt-1);
}
bodyFirstCells.each(function(i, _cell) {
if (i < rowCnt) {
cell = $(_cell);
cell.find('> div').css(
'min-height',
(i==rowCnt-1 ? rowHeightLast : rowHeight) - vsides(cell)
);
}
});
}
function setWidth(width) {
viewWidth = width;
colPositions.clear();
colContentPositions.clear();
weekNumberWidth = 0;
if (showWeekNumbers) {
weekNumberWidth = head.find('th.fc-week-number').outerWidth();
}
colWidth = Math.floor((viewWidth - weekNumberWidth) / colCnt);
setOuterWidth(headCells.slice(0, -1), colWidth);
}
/* Day clicking and binding
-----------------------------------------------------------*/
function dayBind(days) {
days.click(dayClick)
.mousedown(daySelectionMousedown);
}
function dayClick(ev) {
if (!opt('selectable')) { // if selectable, SelectionManager will worry about dayClick
var date = parseISO8601($(this).data('date'));
trigger('dayClick', this, date, true, ev);
}
}
/* Semi-transparent Overlay Helpers
------------------------------------------------------*/
// TODO: should be consolidated with AgendaView's methods
function renderDayOverlay(overlayStart, overlayEnd, refreshCoordinateGrid) { // overlayEnd is exclusive
if (refreshCoordinateGrid) {
coordinateGrid.build();
}
var segments = rangeToSegments(overlayStart, overlayEnd);
for (var i=0; i<segments.length; i++) {
var segment = segments[i];
dayBind(
renderCellOverlay(
segment.row,
segment.leftCol,
segment.row,
segment.rightCol
)
);
}
}
function renderCellOverlay(row0, col0, row1, col1) { // row1,col1 is inclusive
var rect = coordinateGrid.rect(row0, col0, row1, col1, element);
return renderOverlay(rect, element);
}
/* Selection
-----------------------------------------------------------------------*/
function defaultSelectionEnd(startDate, allDay) {
return cloneDate(startDate);
}
function renderSelection(startDate, endDate, allDay) {
renderDayOverlay(startDate, addDays(cloneDate(endDate), 1), true); // rebuild every time???
}
function clearSelection() {
clearOverlays();
}
function reportDayClick(date, allDay, ev) {
var cell = dateToCell(date);
var _element = bodyCells[cell.row*colCnt + cell.col];
trigger('dayClick', _element, date, allDay, ev);
}
/* External Dragging
-----------------------------------------------------------------------*/
function dragStart(_dragElement, ev, ui) {
hoverListener.start(function(cell) {
clearOverlays();
if (cell) {
renderCellOverlay(cell.row, cell.col, cell.row, cell.col);
}
}, ev);
}
function dragStop(_dragElement, ev, ui) {
var cell = hoverListener.stop();
clearOverlays();
if (cell) {
var d = cellToDate(cell);
trigger('drop', _dragElement, d, true, ev, ui);
}
}
/* Utilities
--------------------------------------------------------*/
function defaultEventEnd(event) {
return cloneDate(event.start);
}
coordinateGrid = new CoordinateGrid(function(rows, cols) {
var e, n, p;
headCells.each(function(i, _e) {
e = $(_e);
n = e.offset().left;
if (i) {
p[1] = n;
}
p = [n];
cols[i] = p;
});
p[1] = n + e.outerWidth();
bodyRows.each(function(i, _e) {
if (i < rowCnt) {
e = $(_e);
n = e.offset().top;
if (i) {
p[1] = n;
}
p = [n];
rows[i] = p;
}
});
p[1] = n + e.outerHeight();
});
hoverListener = new HoverListener(coordinateGrid);
colPositions = new HorizontalPositionCache(function(col) {
return firstRowCellInners.eq(col);
});
colContentPositions = new HorizontalPositionCache(function(col) {
return firstRowCellContentInners.eq(col);
});
function colLeft(col) {
return colPositions.left(col);
}
function colRight(col) {
return colPositions.right(col);
}
function colContentLeft(col) {
return colContentPositions.left(col);
}
function colContentRight(col) {
return colContentPositions.right(col);
}
function allDayRow(i) {
return bodyRows.eq(i);
}
}
;;
function BasicEventRenderer() {
var t = this;
// exports
t.renderEvents = renderEvents;
t.clearEvents = clearEvents;
// imports
DayEventRenderer.call(t);
function renderEvents(events, modifiedEventId) {
t.renderDayEvents(events, modifiedEventId);
}
function clearEvents() {
t.getDaySegmentContainer().empty();
}
// TODO: have this class (and AgendaEventRenderer) be responsible for creating the event container div
}
;;
fcViews.agendaWeek = AgendaWeekView;
function AgendaWeekView(element, calendar) {
var t = this;
// exports
t.render = render;
// imports
AgendaView.call(t, element, calendar, 'agendaWeek');
var opt = t.opt;
var renderAgenda = t.renderAgenda;
var skipHiddenDays = t.skipHiddenDays;
var getCellsPerWeek = t.getCellsPerWeek;
var formatDates = calendar.formatDates;
function render(date, delta) {
if (delta) {
addDays(date, delta * 7);
}
var start = addDays(cloneDate(date), -((date.getDay() - opt('firstDay') + 7) % 7));
var end = addDays(cloneDate(start), 7);
var visStart = cloneDate(start);
skipHiddenDays(visStart);
var visEnd = cloneDate(end);
skipHiddenDays(visEnd, -1, true);
var colCnt = getCellsPerWeek();
t.title = formatDates(
visStart,
addDays(cloneDate(visEnd), -1),
opt('titleFormat')
);
t.start = start;
t.end = end;
t.visStart = visStart;
t.visEnd = visEnd;
renderAgenda(colCnt);
}
}
;;
fcViews.agendaDay = AgendaDayView;
function AgendaDayView(element, calendar) {
var t = this;
// exports
t.render = render;
// imports
AgendaView.call(t, element, calendar, 'agendaDay');
var opt = t.opt;
var renderAgenda = t.renderAgenda;
var skipHiddenDays = t.skipHiddenDays;
var formatDate = calendar.formatDate;
function render(date, delta) {
if (delta) {
addDays(date, delta);
}
skipHiddenDays(date, delta < 0 ? -1 : 1);
var start = cloneDate(date, true);
var end = addDays(cloneDate(start), 1);
t.title = formatDate(date, opt('titleFormat'));
t.start = t.visStart = start;
t.end = t.visEnd = end;
renderAgenda(1);
}
}
;;
setDefaults({
allDaySlot: true,
allDayText: 'all-day',
firstHour: 6,
slotMinutes: 30,
defaultEventMinutes: 120,
axisFormat: 'h(:mm)tt',
timeFormat: {
agenda: 'h:mm{ - h:mm}'
},
dragOpacity: {
agenda: .5
},
minTime: 0,
maxTime: 24,
slotEventOverlap: true
});
// TODO: make it work in quirks mode (event corners, all-day height)
// TODO: test liquid width, especially in IE6
function AgendaView(element, calendar, viewName) {
var t = this;
// exports
t.renderAgenda = renderAgenda;
t.setWidth = setWidth;
t.setHeight = setHeight;
t.afterRender = afterRender;
t.defaultEventEnd = defaultEventEnd;
t.timePosition = timePosition;
t.getIsCellAllDay = getIsCellAllDay;
t.allDayRow = getAllDayRow;
t.getCoordinateGrid = function() { return coordinateGrid }; // specifically for AgendaEventRenderer
t.getHoverListener = function() { return hoverListener };
t.colLeft = colLeft;
t.colRight = colRight;
t.colContentLeft = colContentLeft;
t.colContentRight = colContentRight;
t.getDaySegmentContainer = function() { return daySegmentContainer };
t.getSlotSegmentContainer = function() { return slotSegmentContainer };
t.getMinMinute = function() { return minMinute };
t.getMaxMinute = function() { return maxMinute };
t.getSlotContainer = function() { return slotContainer };
t.getRowCnt = function() { return 1 };
t.getColCnt = function() { return colCnt };
t.getColWidth = function() { return colWidth };
t.getSnapHeight = function() { return snapHeight };
t.getSnapMinutes = function() { return snapMinutes };
t.defaultSelectionEnd = defaultSelectionEnd;
t.renderDayOverlay = renderDayOverlay;
t.renderSelection = renderSelection;
t.clearSelection = clearSelection;
t.reportDayClick = reportDayClick; // selection mousedown hack
t.dragStart = dragStart;
t.dragStop = dragStop;
// imports
View.call(t, element, calendar, viewName);
OverlayManager.call(t);
SelectionManager.call(t);
AgendaEventRenderer.call(t);
var opt = t.opt;
var trigger = t.trigger;
var renderOverlay = t.renderOverlay;
var clearOverlays = t.clearOverlays;
var reportSelection = t.reportSelection;
var unselect = t.unselect;
var daySelectionMousedown = t.daySelectionMousedown;
var slotSegHtml = t.slotSegHtml;
var cellToDate = t.cellToDate;
var dateToCell = t.dateToCell;
var rangeToSegments = t.rangeToSegments;
var formatDate = calendar.formatDate;
// locals
var dayTable;
var dayHead;
var dayHeadCells;
var dayBody;
var dayBodyCells;
var dayBodyCellInners;
var dayBodyCellContentInners;
var dayBodyFirstCell;
var dayBodyFirstCellStretcher;
var slotLayer;
var daySegmentContainer;
var allDayTable;
var allDayRow;
var slotScroller;
var slotContainer;
var slotSegmentContainer;
var slotTable;
var selectionHelper;
var viewWidth;
var viewHeight;
var axisWidth;
var colWidth;
var gutterWidth;
var slotHeight; // TODO: what if slotHeight changes? (see issue 650)
var snapMinutes;
var snapRatio; // ratio of number of "selection" slots to normal slots. (ex: 1, 2, 4)
var snapHeight; // holds the pixel hight of a "selection" slot
var colCnt;
var slotCnt;
var coordinateGrid;
var hoverListener;
var colPositions;
var colContentPositions;
var slotTopCache = {};
var tm;
var rtl;
var minMinute, maxMinute;
var colFormat;
var showWeekNumbers;
var weekNumberTitle;
var weekNumberFormat;
/* Rendering
-----------------------------------------------------------------------------*/
disableTextSelection(element.addClass('fc-agenda'));
function renderAgenda(c) {
colCnt = c;
updateOptions();
if (!dayTable) { // first time rendering?
buildSkeleton(); // builds day table, slot area, events containers
}
else {
buildDayTable(); // rebuilds day table
}
}
function updateOptions() {
tm = opt('theme') ? 'ui' : 'fc';
rtl = opt('isRTL')
minMinute = parseTime(opt('minTime'));
maxMinute = parseTime(opt('maxTime'));
colFormat = opt('columnFormat');
// week # options. (TODO: bad, logic also in other views)
showWeekNumbers = opt('weekNumbers');
weekNumberTitle = opt('weekNumberTitle');
if (opt('weekNumberCalculation') != 'iso') {
weekNumberFormat = "w";
}
else {
weekNumberFormat = "W";
}
snapMinutes = opt('snapMinutes') || opt('slotMinutes');
}
/* Build DOM
-----------------------------------------------------------------------*/
function buildSkeleton() {
var headerClass = tm + "-widget-header";
var contentClass = tm + "-widget-content";
var s;
var d;
var i;
var maxd;
var minutes;
var slotNormal = opt('slotMinutes') % 15 == 0;
buildDayTable();
slotLayer =
$("<div style='position:absolute;z-index:2;left:0;width:100%'/>")
.appendTo(element);
if (opt('allDaySlot')) {
daySegmentContainer =
$("<div class='fc-event-container' style='position:absolute;z-index:8;top:0;left:0'/>")
.appendTo(slotLayer);
s =
"<table style='width:100%' class='fc-agenda-allday' cellspacing='0'>" +
"<tr>" +
"<th class='" + headerClass + " fc-agenda-axis'>" + opt('allDayText') + "</th>" +
"<td>" +
"<div class='fc-day-content'><div style='position:relative'/></div>" +
"</td>" +
"<th class='" + headerClass + " fc-agenda-gutter'> </th>" +
"</tr>" +
"</table>";
allDayTable = $(s).appendTo(slotLayer);
allDayRow = allDayTable.find('tr');
dayBind(allDayRow.find('td'));
slotLayer.append(
"<div class='fc-agenda-divider " + headerClass + "'>" +
"<div class='fc-agenda-divider-inner'/>" +
"</div>"
);
}else{
daySegmentContainer = $([]); // in jQuery 1.4, we can just do $()
}
slotScroller =
$("<div style='position:absolute;width:100%;overflow-x:hidden;overflow-y:auto'/>")
.appendTo(slotLayer);
slotContainer =
$("<div style='position:relative;width:100%;overflow:hidden'/>")
.appendTo(slotScroller);
slotSegmentContainer =
$("<div class='fc-event-container' style='position:absolute;z-index:8;top:0;left:0'/>")
.appendTo(slotContainer);
s =
"<table class='fc-agenda-slots' style='width:100%' cellspacing='0'>" +
"<tbody>";
d = zeroDate();
maxd = addMinutes(cloneDate(d), maxMinute);
addMinutes(d, minMinute);
slotCnt = 0;
for (i=0; d < maxd; i++) {
minutes = d.getMinutes();
s +=
"<tr class='fc-slot" + i + ' ' + (!minutes ? '' : 'fc-minor') + "'>" +
"<th class='fc-agenda-axis " + headerClass + "'>" +
((!slotNormal || !minutes) ? formatDate(d, opt('axisFormat')) : ' ') +
"</th>" +
"<td class='" + contentClass + "'>" +
"<div style='position:relative'> </div>" +
"</td>" +
"</tr>";
addMinutes(d, opt('slotMinutes'));
slotCnt++;
}
s +=
"</tbody>" +
"</table>";
slotTable = $(s).appendTo(slotContainer);
slotBind(slotTable.find('td'));
}
/* Build Day Table
-----------------------------------------------------------------------*/
function buildDayTable() {
var html = buildDayTableHTML();
if (dayTable) {
dayTable.remove();
}
dayTable = $(html).appendTo(element);
dayHead = dayTable.find('thead');
dayHeadCells = dayHead.find('th').slice(1, -1); // exclude gutter
dayBody = dayTable.find('tbody');
dayBodyCells = dayBody.find('td').slice(0, -1); // exclude gutter
dayBodyCellInners = dayBodyCells.find('> div');
dayBodyCellContentInners = dayBodyCells.find('.fc-day-content > div');
dayBodyFirstCell = dayBodyCells.eq(0);
dayBodyFirstCellStretcher = dayBodyCellInners.eq(0);
markFirstLast(dayHead.add(dayHead.find('tr')));
markFirstLast(dayBody.add(dayBody.find('tr')));
// TODO: now that we rebuild the cells every time, we should call dayRender
}
function buildDayTableHTML() {
var html =
"<table style='width:100%' class='fc-agenda-days fc-border-separate' cellspacing='0'>" +
buildDayTableHeadHTML() +
buildDayTableBodyHTML() +
"</table>";
return html;
}
function buildDayTableHeadHTML() {
var headerClass = tm + "-widget-header";
var date;
var html = '';
var weekText;
var col;
html +=
"<thead>" +
"<tr>";
if (showWeekNumbers) {
date = cellToDate(0, 0);
weekText = formatDate(date, weekNumberFormat);
if (rtl) {
weekText += weekNumberTitle;
}
else {
weekText = weekNumberTitle + weekText;
}
html +=
"<th class='fc-agenda-axis fc-week-number " + headerClass + "'>" +
htmlEscape(weekText) +
"</th>";
}
else {
html += "<th class='fc-agenda-axis " + headerClass + "'> </th>";
}
for (col=0; col<colCnt; col++) {
date = cellToDate(0, col);
html +=
"<th class='fc-" + dayIDs[date.getDay()] + " fc-col" + col + ' ' + headerClass + "'>" +
htmlEscape(formatDate(date, colFormat)) +
"</th>";
}
html +=
"<th class='fc-agenda-gutter " + headerClass + "'> </th>" +
"</tr>" +
"</thead>";
return html;
}
function buildDayTableBodyHTML() {
var headerClass = tm + "-widget-header"; // TODO: make these when updateOptions() called
var contentClass = tm + "-widget-content";
var date;
var today = clearTime(new Date());
var col;
var cellsHTML;
var cellHTML;
var classNames;
var html = '';
html +=
"<tbody>" +
"<tr>" +
"<th class='fc-agenda-axis " + headerClass + "'> </th>";
cellsHTML = '';
for (col=0; col<colCnt; col++) {
date = cellToDate(0, col);
classNames = [
'fc-col' + col,
'fc-' + dayIDs[date.getDay()],
contentClass
];
if (+date == +today) {
classNames.push(
tm + '-state-highlight',
'fc-today'
);
}
else if (date < today) {
classNames.push('fc-past');
}
else {
classNames.push('fc-future');
}
cellHTML =
"<td class='" + classNames.join(' ') + "'>" +
"<div>" +
"<div class='fc-day-content'>" +
"<div style='position:relative'> </div>" +
"</div>" +
"</div>" +
"</td>";
cellsHTML += cellHTML;
}
html += cellsHTML;
html +=
"<td class='fc-agenda-gutter " + contentClass + "'> </td>" +
"</tr>" +
"</tbody>";
return html;
}
// TODO: data-date on the cells
/* Dimensions
-----------------------------------------------------------------------*/
function setHeight(height) {
if (height === undefined) {
height = viewHeight;
}
viewHeight = height;
slotTopCache = {};
var headHeight = dayBody.position().top;
var allDayHeight = slotScroller.position().top; // including divider
var bodyHeight = Math.min( // total body height, including borders
height - headHeight, // when scrollbars
slotTable.height() + allDayHeight + 1 // when no scrollbars. +1 for bottom border
);
dayBodyFirstCellStretcher
.height(bodyHeight - vsides(dayBodyFirstCell));
slotLayer.css('top', headHeight);
slotScroller.height(bodyHeight - allDayHeight - 1);
// the stylesheet guarantees that the first row has no border.
// this allows .height() to work well cross-browser.
slotHeight = slotTable.find('tr:first').height() + 1; // +1 for bottom border
snapRatio = opt('slotMinutes') / snapMinutes;
snapHeight = slotHeight / snapRatio;
}
function setWidth(width) {
viewWidth = width;
colPositions.clear();
colContentPositions.clear();
var axisFirstCells = dayHead.find('th:first');
if (allDayTable) {
axisFirstCells = axisFirstCells.add(allDayTable.find('th:first'));
}
axisFirstCells = axisFirstCells.add(slotTable.find('th:first'));
axisWidth = 0;
setOuterWidth(
axisFirstCells
.width('')
.each(function(i, _cell) {
axisWidth = Math.max(axisWidth, $(_cell).outerWidth());
}),
axisWidth
);
var gutterCells = dayTable.find('.fc-agenda-gutter');
if (allDayTable) {
gutterCells = gutterCells.add(allDayTable.find('th.fc-agenda-gutter'));
}
var slotTableWidth = slotScroller[0].clientWidth; // needs to be done after axisWidth (for IE7)
gutterWidth = slotScroller.width() - slotTableWidth;
if (gutterWidth) {
setOuterWidth(gutterCells, gutterWidth);
gutterCells
.show()
.prev()
.removeClass('fc-last');
}else{
gutterCells
.hide()
.prev()
.addClass('fc-last');
}
colWidth = Math.floor((slotTableWidth - axisWidth) / colCnt);
setOuterWidth(dayHeadCells.slice(0, -1), colWidth);
}
/* Scrolling
-----------------------------------------------------------------------*/
function resetScroll() {
var d0 = zeroDate();
var scrollDate = cloneDate(d0);
scrollDate.setHours(opt('firstHour'));
var top = timePosition(d0, scrollDate) + 1; // +1 for the border
function scroll() {
slotScroller.scrollTop(top);
}
scroll();
setTimeout(scroll, 0); // overrides any previous scroll state made by the browser
}
function afterRender() { // after the view has been freshly rendered and sized
resetScroll();
}
/* Slot/Day clicking and binding
-----------------------------------------------------------------------*/
function dayBind(cells) {
cells.click(slotClick)
.mousedown(daySelectionMousedown);
}
function slotBind(cells) {
cells.click(slotClick)
.mousedown(slotSelectionMousedown);
}
function slotClick(ev) {
if (!opt('selectable')) { // if selectable, SelectionManager will worry about dayClick
var col = Math.min(colCnt-1, Math.floor((ev.pageX - dayTable.offset().left - axisWidth) / colWidth));
var date = cellToDate(0, col);
var rowMatch = this.parentNode.className.match(/fc-slot(\d+)/); // TODO: maybe use data
if (rowMatch) {
var mins = parseInt(rowMatch[1]) * opt('slotMinutes');
var hours = Math.floor(mins/60);
date.setHours(hours);
date.setMinutes(mins%60 + minMinute);
trigger('dayClick', dayBodyCells[col], date, false, ev);
}else{
trigger('dayClick', dayBodyCells[col], date, true, ev);
}
}
}
/* Semi-transparent Overlay Helpers
-----------------------------------------------------*/
// TODO: should be consolidated with BasicView's methods
function renderDayOverlay(overlayStart, overlayEnd, refreshCoordinateGrid) { // overlayEnd is exclusive
if (refreshCoordinateGrid) {
coordinateGrid.build();
}
var segments = rangeToSegments(overlayStart, overlayEnd);
for (var i=0; i<segments.length; i++) {
var segment = segments[i];
dayBind(
renderCellOverlay(
segment.row,
segment.leftCol,
segment.row,
segment.rightCol
)
);
}
}
function renderCellOverlay(row0, col0, row1, col1) { // only for all-day?
var rect = coordinateGrid.rect(row0, col0, row1, col1, slotLayer);
return renderOverlay(rect, slotLayer);
}
function renderSlotOverlay(overlayStart, overlayEnd) {
for (var i=0; i<colCnt; i++) {
var dayStart = cellToDate(0, i);
var dayEnd = addDays(cloneDate(dayStart), 1);
var stretchStart = new Date(Math.max(dayStart, overlayStart));
var stretchEnd = new Date(Math.min(dayEnd, overlayEnd));
if (stretchStart < stretchEnd) {
var rect = coordinateGrid.rect(0, i, 0, i, slotContainer); // only use it for horizontal coords
var top = timePosition(dayStart, stretchStart);
var bottom = timePosition(dayStart, stretchEnd);
rect.top = top;
rect.height = bottom - top;
slotBind(
renderOverlay(rect, slotContainer)
);
}
}
}
/* Coordinate Utilities
-----------------------------------------------------------------------------*/
coordinateGrid = new CoordinateGrid(function(rows, cols) {
var e, n, p;
dayHeadCells.each(function(i, _e) {
e = $(_e);
n = e.offset().left;
if (i) {
p[1] = n;
}
p = [n];
cols[i] = p;
});
p[1] = n + e.outerWidth();
if (opt('allDaySlot')) {
e = allDayRow;
n = e.offset().top;
rows[0] = [n, n+e.outerHeight()];
}
var slotTableTop = slotContainer.offset().top;
var slotScrollerTop = slotScroller.offset().top;
var slotScrollerBottom = slotScrollerTop + slotScroller.outerHeight();
function constrain(n) {
return Math.max(slotScrollerTop, Math.min(slotScrollerBottom, n));
}
for (var i=0; i<slotCnt*snapRatio; i++) { // adapt slot count to increased/decreased selection slot count
rows.push([
constrain(slotTableTop + snapHeight*i),
constrain(slotTableTop + snapHeight*(i+1))
]);
}
});
hoverListener = new HoverListener(coordinateGrid);
colPositions = new HorizontalPositionCache(function(col) {
return dayBodyCellInners.eq(col);
});
colContentPositions = new HorizontalPositionCache(function(col) {
return dayBodyCellContentInners.eq(col);
});
function colLeft(col) {
return colPositions.left(col);
}
function colContentLeft(col) {
return colContentPositions.left(col);
}
function colRight(col) {
return colPositions.right(col);
}
function colContentRight(col) {
return colContentPositions.right(col);
}
function getIsCellAllDay(cell) {
return opt('allDaySlot') && !cell.row;
}
function realCellToDate(cell) { // ugh "real" ... but blame it on our abuse of the "cell" system
var d = cellToDate(0, cell.col);
var slotIndex = cell.row;
if (opt('allDaySlot')) {
slotIndex--;
}
if (slotIndex >= 0) {
addMinutes(d, minMinute + slotIndex * snapMinutes);
}
return d;
}
// get the Y coordinate of the given time on the given day (both Date objects)
function timePosition(day, time) { // both date objects. day holds 00:00 of current day
day = cloneDate(day, true);
if (time < addMinutes(cloneDate(day), minMinute)) {
return 0;
}
if (time >= addMinutes(cloneDate(day), maxMinute)) {
return slotTable.height();
}
var slotMinutes = opt('slotMinutes'),
minutes = time.getHours()*60 + time.getMinutes() - minMinute,
slotI = Math.floor(minutes / slotMinutes),
slotTop = slotTopCache[slotI];
if (slotTop === undefined) {
slotTop = slotTopCache[slotI] =
slotTable.find('tr').eq(slotI).find('td div')[0].offsetTop;
// .eq() is faster than ":eq()" selector
// [0].offsetTop is faster than .position().top (do we really need this optimization?)
// a better optimization would be to cache all these divs
}
return Math.max(0, Math.round(
slotTop - 1 + slotHeight * ((minutes % slotMinutes) / slotMinutes)
));
}
function getAllDayRow(index) {
return allDayRow;
}
function defaultEventEnd(event) {
var start = cloneDate(event.start);
if (event.allDay) {
return start;
}
return addMinutes(start, opt('defaultEventMinutes'));
}
/* Selection
---------------------------------------------------------------------------------*/
function defaultSelectionEnd(startDate, allDay) {
if (allDay) {
return cloneDate(startDate);
}
return addMinutes(cloneDate(startDate), opt('slotMinutes'));
}
function renderSelection(startDate, endDate, allDay) { // only for all-day
if (allDay) {
if (opt('allDaySlot')) {
renderDayOverlay(startDate, addDays(cloneDate(endDate), 1), true);
}
}else{
renderSlotSelection(startDate, endDate);
}
}
function renderSlotSelection(startDate, endDate) {
var helperOption = opt('selectHelper');
coordinateGrid.build();
if (helperOption) {
var col = dateToCell(startDate).col;
if (col >= 0 && col < colCnt) { // only works when times are on same day
var rect = coordinateGrid.rect(0, col, 0, col, slotContainer); // only for horizontal coords
var top = timePosition(startDate, startDate);
var bottom = timePosition(startDate, endDate);
if (bottom > top) { // protect against selections that are entirely before or after visible range
rect.top = top;
rect.height = bottom - top;
rect.left += 2;
rect.width -= 5;
if ($.isFunction(helperOption)) {
var helperRes = helperOption(startDate, endDate);
if (helperRes) {
rect.position = 'absolute';
selectionHelper = $(helperRes)
.css(rect)
.appendTo(slotContainer);
}
}else{
rect.isStart = true; // conside rect a "seg" now
rect.isEnd = true; //
selectionHelper = $(slotSegHtml(
{
title: '',
start: startDate,
end: endDate,
className: ['fc-select-helper'],
editable: false
},
rect
));
selectionHelper.css('opacity', opt('dragOpacity'));
}
if (selectionHelper) {
slotBind(selectionHelper);
slotContainer.append(selectionHelper);
setOuterWidth(selectionHelper, rect.width, true); // needs to be after appended
setOuterHeight(selectionHelper, rect.height, true);
}
}
}
}else{
renderSlotOverlay(startDate, endDate);
}
}
function clearSelection() {
clearOverlays();
if (selectionHelper) {
selectionHelper.remove();
selectionHelper = null;
}
}
function slotSelectionMousedown(ev) {
if (ev.which == 1 && opt('selectable')) { // ev.which==1 means left mouse button
unselect(ev);
var dates;
hoverListener.start(function(cell, origCell) {
clearSelection();
if (cell && cell.col == origCell.col && !getIsCellAllDay(cell)) {
var d1 = realCellToDate(origCell);
var d2 = realCellToDate(cell);
dates = [
d1,
addMinutes(cloneDate(d1), snapMinutes), // calculate minutes depending on selection slot minutes
d2,
addMinutes(cloneDate(d2), snapMinutes)
].sort(dateCompare);
renderSlotSelection(dates[0], dates[3]);
}else{
dates = null;
}
}, ev);
$(document).one('mouseup', function(ev) {
hoverListener.stop();
if (dates) {
if (+dates[0] == +dates[1]) {
reportDayClick(dates[0], false, ev);
}
reportSelection(dates[0], dates[3], false, ev);
}
});
}
}
function reportDayClick(date, allDay, ev) {
trigger('dayClick', dayBodyCells[dateToCell(date).col], date, allDay, ev);
}
/* External Dragging
--------------------------------------------------------------------------------*/
function dragStart(_dragElement, ev, ui) {
hoverListener.start(function(cell) {
clearOverlays();
if (cell) {
if (getIsCellAllDay(cell)) {
renderCellOverlay(cell.row, cell.col, cell.row, cell.col);
}else{
var d1 = realCellToDate(cell);
var d2 = addMinutes(cloneDate(d1), opt('defaultEventMinutes'));
renderSlotOverlay(d1, d2);
}
}
}, ev);
}
function dragStop(_dragElement, ev, ui) {
var cell = hoverListener.stop();
clearOverlays();
if (cell) {
trigger('drop', _dragElement, realCellToDate(cell), getIsCellAllDay(cell), ev, ui);
}
}
}
;;
function AgendaEventRenderer() {
var t = this;
// exports
t.renderEvents = renderEvents;
t.clearEvents = clearEvents;
t.slotSegHtml = slotSegHtml;
// imports
DayEventRenderer.call(t);
var opt = t.opt;
var trigger = t.trigger;
var isEventDraggable = t.isEventDraggable;
var isEventResizable = t.isEventResizable;
var eventEnd = t.eventEnd;
var eventElementHandlers = t.eventElementHandlers;
var setHeight = t.setHeight;
var getDaySegmentContainer = t.getDaySegmentContainer;
var getSlotSegmentContainer = t.getSlotSegmentContainer;
var getHoverListener = t.getHoverListener;
var getMaxMinute = t.getMaxMinute;
var getMinMinute = t.getMinMinute;
var timePosition = t.timePosition;
var getIsCellAllDay = t.getIsCellAllDay;
var colContentLeft = t.colContentLeft;
var colContentRight = t.colContentRight;
var cellToDate = t.cellToDate;
var getColCnt = t.getColCnt;
var getColWidth = t.getColWidth;
var getSnapHeight = t.getSnapHeight;
var getSnapMinutes = t.getSnapMinutes;
var getSlotContainer = t.getSlotContainer;
var reportEventElement = t.reportEventElement;
var showEvents = t.showEvents;
var hideEvents = t.hideEvents;
var eventDrop = t.eventDrop;
var eventResize = t.eventResize;
var renderDayOverlay = t.renderDayOverlay;
var clearOverlays = t.clearOverlays;
var renderDayEvents = t.renderDayEvents;
var calendar = t.calendar;
var formatDate = calendar.formatDate;
var formatDates = calendar.formatDates;
// overrides
t.draggableDayEvent = draggableDayEvent;
/* Rendering
----------------------------------------------------------------------------*/
function renderEvents(events, modifiedEventId) {
var i, len=events.length,
dayEvents=[],
slotEvents=[];
for (i=0; i<len; i++) {
if (events[i].allDay) {
dayEvents.push(events[i]);
}else{
slotEvents.push(events[i]);
}
}
if (opt('allDaySlot')) {
renderDayEvents(dayEvents, modifiedEventId);
setHeight(); // no params means set to viewHeight
}
renderSlotSegs(compileSlotSegs(slotEvents), modifiedEventId);
}
function clearEvents() {
getDaySegmentContainer().empty();
getSlotSegmentContainer().empty();
}
function compileSlotSegs(events) {
var colCnt = getColCnt(),
minMinute = getMinMinute(),
maxMinute = getMaxMinute(),
d,
visEventEnds = $.map(events, slotEventEnd),
i,
j, seg,
colSegs,
segs = [];
for (i=0; i<colCnt; i++) {
d = cellToDate(0, i);
addMinutes(d, minMinute);
colSegs = sliceSegs(
events,
visEventEnds,
d,
addMinutes(cloneDate(d), maxMinute-minMinute)
);
colSegs = placeSlotSegs(colSegs); // returns a new order
for (j=0; j<colSegs.length; j++) {
seg = colSegs[j];
seg.col = i;
segs.push(seg);
}
}
return segs;
}
function sliceSegs(events, visEventEnds, start, end) {
var segs = [],
i, len=events.length, event,
eventStart, eventEnd,
segStart, segEnd,
isStart, isEnd;
for (i=0; i<len; i++) {
event = events[i];
eventStart = event.start;
eventEnd = visEventEnds[i];
if (eventEnd > start && eventStart < end) {
if (eventStart < start) {
segStart = cloneDate(start);
isStart = false;
}else{
segStart = eventStart;
isStart = true;
}
if (eventEnd > end) {
segEnd = cloneDate(end);
isEnd = false;
}else{
segEnd = eventEnd;
isEnd = true;
}
segs.push({
event: event,
start: segStart,
end: segEnd,
isStart: isStart,
isEnd: isEnd
});
}
}
return segs.sort(compareSlotSegs);
}
function slotEventEnd(event) {
if (event.end) {
return cloneDate(event.end);
}else{
return addMinutes(cloneDate(event.start), opt('defaultEventMinutes'));
}
}
// renders events in the 'time slots' at the bottom
// TODO: when we refactor this, when user returns `false` eventRender, don't have empty space
// TODO: refactor will include using pixels to detect collisions instead of dates (handy for seg cmp)
function renderSlotSegs(segs, modifiedEventId) {
var i, segCnt=segs.length, seg,
event,
top,
bottom,
columnLeft,
columnRight,
columnWidth,
width,
left,
right,
html = '',
eventElements,
eventElement,
triggerRes,
titleElement,
height,
slotSegmentContainer = getSlotSegmentContainer(),
isRTL = opt('isRTL');
// calculate position/dimensions, create html
for (i=0; i<segCnt; i++) {
seg = segs[i];
event = seg.event;
top = timePosition(seg.start, seg.start);
bottom = timePosition(seg.start, seg.end);
columnLeft = colContentLeft(seg.col);
columnRight = colContentRight(seg.col);
columnWidth = columnRight - columnLeft;
// shave off space on right near scrollbars (2.5%)
// TODO: move this to CSS somehow
columnRight -= columnWidth * .025;
columnWidth = columnRight - columnLeft;
width = columnWidth * (seg.forwardCoord - seg.backwardCoord);
if (opt('slotEventOverlap')) {
// double the width while making sure resize handle is visible
// (assumed to be 20px wide)
width = Math.max(
(width - (20/2)) * 2,
width // narrow columns will want to make the segment smaller than
// the natural width. don't allow it
);
}
if (isRTL) {
right = columnRight - seg.backwardCoord * columnWidth;
left = right - width;
}
else {
left = columnLeft + seg.backwardCoord * columnWidth;
right = left + width;
}
// make sure horizontal coordinates are in bounds
left = Math.max(left, columnLeft);
right = Math.min(right, columnRight);
width = right - left;
seg.top = top;
seg.left = left;
seg.outerWidth = width;
seg.outerHeight = bottom - top;
html += slotSegHtml(event, seg);
}
slotSegmentContainer[0].innerHTML = html; // faster than html()
eventElements = slotSegmentContainer.children();
// retrieve elements, run through eventRender callback, bind event handlers
for (i=0; i<segCnt; i++) {
seg = segs[i];
event = seg.event;
eventElement = $(eventElements[i]); // faster than eq()
triggerRes = trigger('eventRender', event, event, eventElement);
if (triggerRes === false) {
eventElement.remove();
}else{
if (triggerRes && triggerRes !== true) {
eventElement.remove();
eventElement = $(triggerRes)
.css({
position: 'absolute',
top: seg.top,
left: seg.left
})
.appendTo(slotSegmentContainer);
}
seg.element = eventElement;
if (event._id === modifiedEventId) {
bindSlotSeg(event, eventElement, seg);
}else{
eventElement[0]._fci = i; // for lazySegBind
}
reportEventElement(event, eventElement);
}
}
lazySegBind(slotSegmentContainer, segs, bindSlotSeg);
// record event sides and title positions
for (i=0; i<segCnt; i++) {
seg = segs[i];
if (eventElement = seg.element) {
seg.vsides = vsides(eventElement, true);
seg.hsides = hsides(eventElement, true);
titleElement = eventElement.find('.fc-event-title');
if (titleElement.length) {
seg.contentTop = titleElement[0].offsetTop;
}
}
}
// set all positions/dimensions at once
for (i=0; i<segCnt; i++) {
seg = segs[i];
if (eventElement = seg.element) {
eventElement[0].style.width = Math.max(0, seg.outerWidth - seg.hsides) + 'px';
height = Math.max(0, seg.outerHeight - seg.vsides);
eventElement[0].style.height = height + 'px';
event = seg.event;
if (seg.contentTop !== undefined && height - seg.contentTop < 10) {
// not enough room for title, put it in the time (TODO: maybe make both display:inline instead)
eventElement.find('div.fc-event-time')
.text(formatDate(event.start, opt('timeFormat')) + ' - ' + event.title);
eventElement.find('div.fc-event-title')
.remove();
}
trigger('eventAfterRender', event, event, eventElement);
}
}
}
function slotSegHtml(event, seg) {
var html = "<";
var url = event.url;
var skinCss = getSkinCss(event, opt);
var classes = ['fc-event', 'fc-event-vert'];
if (isEventDraggable(event)) {
classes.push('fc-event-draggable');
}
if (seg.isStart) {
classes.push('fc-event-start');
}
if (seg.isEnd) {
classes.push('fc-event-end');
}
classes = classes.concat(event.className);
if (event.source) {
classes = classes.concat(event.source.className || []);
}
if (url) {
html += "a href='" + htmlEscape(event.url) + "'";
}else{
html += "div";
}
html +=
" class='" + classes.join(' ') + "'" +
" style=" +
"'" +
"position:absolute;" +
"top:" + seg.top + "px;" +
"left:" + seg.left + "px;" +
skinCss +
"'" +
">" +
"<div class='fc-event-inner'>" +
"<div class='fc-event-time'>" +
htmlEscape(formatDates(event.start, event.end, opt('timeFormat'))) +
"</div>" +
"<div class='fc-event-title'>" +
htmlEscape(event.title || '') +
"</div>" +
"</div>" +
"<div class='fc-event-bg'></div>";
if (seg.isEnd && isEventResizable(event)) {
html +=
"<div class='ui-resizable-handle ui-resizable-s'>=</div>";
}
html +=
"</" + (url ? "a" : "div") + ">";
return html;
}
function bindSlotSeg(event, eventElement, seg) {
var timeElement = eventElement.find('div.fc-event-time');
if (isEventDraggable(event)) {
draggableSlotEvent(event, eventElement, timeElement);
}
if (seg.isEnd && isEventResizable(event)) {
resizableSlotEvent(event, eventElement, timeElement);
}
eventElementHandlers(event, eventElement);
}
/* Dragging
-----------------------------------------------------------------------------------*/
// when event starts out FULL-DAY
// overrides DayEventRenderer's version because it needs to account for dragging elements
// to and from the slot area.
function draggableDayEvent(event, eventElement, seg) {
var isStart = seg.isStart;
var origWidth;
var revert;
var allDay = true;
var dayDelta;
var hoverListener = getHoverListener();
var colWidth = getColWidth();
var snapHeight = getSnapHeight();
var snapMinutes = getSnapMinutes();
var minMinute = getMinMinute();
eventElement.draggable({
opacity: opt('dragOpacity', 'month'), // use whatever the month view was using
revertDuration: opt('dragRevertDuration'),
start: function(ev, ui) {
trigger('eventDragStart', eventElement, event, ev, ui);
hideEvents(event, eventElement);
origWidth = eventElement.width();
hoverListener.start(function(cell, origCell) {
clearOverlays();
if (cell) {
revert = false;
var origDate = cellToDate(0, origCell.col);
var date = cellToDate(0, cell.col);
dayDelta = dayDiff(date, origDate);
if (!cell.row) {
// on full-days
renderDayOverlay(
addDays(cloneDate(event.start), dayDelta),
addDays(exclEndDay(event), dayDelta)
);
resetElement();
}else{
// mouse is over bottom slots
if (isStart) {
if (allDay) {
// convert event to temporary slot-event
eventElement.width(colWidth - 10); // don't use entire width
setOuterHeight(
eventElement,
snapHeight * Math.round(
(event.end ? ((event.end - event.start) / MINUTE_MS) : opt('defaultEventMinutes')) /
snapMinutes
)
);
eventElement.draggable('option', 'grid', [colWidth, 1]);
allDay = false;
}
}else{
revert = true;
}
}
revert = revert || (allDay && !dayDelta);
}else{
resetElement();
revert = true;
}
eventElement.draggable('option', 'revert', revert);
}, ev, 'drag');
},
stop: function(ev, ui) {
hoverListener.stop();
clearOverlays();
trigger('eventDragStop', eventElement, event, ev, ui);
if (revert) {
// hasn't moved or is out of bounds (draggable has already reverted)
resetElement();
eventElement.css('filter', ''); // clear IE opacity side-effects
showEvents(event, eventElement);
}else{
// changed!
var minuteDelta = 0;
if (!allDay) {
minuteDelta = Math.round((eventElement.offset().top - getSlotContainer().offset().top) / snapHeight)
* snapMinutes
+ minMinute
- (event.start.getHours() * 60 + event.start.getMinutes());
}
eventDrop(this, event, dayDelta, minuteDelta, allDay, ev, ui);
}
}
});
function resetElement() {
if (!allDay) {
eventElement
.width(origWidth)
.height('')
.draggable('option', 'grid', null);
allDay = true;
}
}
}
// when event starts out IN TIMESLOTS
function draggableSlotEvent(event, eventElement, timeElement) {
var coordinateGrid = t.getCoordinateGrid();
var colCnt = getColCnt();
var colWidth = getColWidth();
var snapHeight = getSnapHeight();
var snapMinutes = getSnapMinutes();
// states
var origPosition; // original position of the element, not the mouse
var origCell;
var isInBounds, prevIsInBounds;
var isAllDay, prevIsAllDay;
var colDelta, prevColDelta;
var dayDelta; // derived from colDelta
var minuteDelta, prevMinuteDelta;
eventElement.draggable({
scroll: false,
grid: [ colWidth, snapHeight ],
axis: colCnt==1 ? 'y' : false,
opacity: opt('dragOpacity'),
revertDuration: opt('dragRevertDuration'),
start: function(ev, ui) {
trigger('eventDragStart', eventElement, event, ev, ui);
hideEvents(event, eventElement);
coordinateGrid.build();
// initialize states
origPosition = eventElement.position();
origCell = coordinateGrid.cell(ev.pageX, ev.pageY);
isInBounds = prevIsInBounds = true;
isAllDay = prevIsAllDay = getIsCellAllDay(origCell);
colDelta = prevColDelta = 0;
dayDelta = 0;
minuteDelta = prevMinuteDelta = 0;
},
drag: function(ev, ui) {
// NOTE: this `cell` value is only useful for determining in-bounds and all-day.
// Bad for anything else due to the discrepancy between the mouse position and the
// element position while snapping. (problem revealed in PR #55)
//
// PS- the problem exists for draggableDayEvent() when dragging an all-day event to a slot event.
// We should overhaul the dragging system and stop relying on jQuery UI.
var cell = coordinateGrid.cell(ev.pageX, ev.pageY);
// update states
isInBounds = !!cell;
if (isInBounds) {
isAllDay = getIsCellAllDay(cell);
// calculate column delta
colDelta = Math.round((ui.position.left - origPosition.left) / colWidth);
if (colDelta != prevColDelta) {
// calculate the day delta based off of the original clicked column and the column delta
var origDate = cellToDate(0, origCell.col);
var col = origCell.col + colDelta;
col = Math.max(0, col);
col = Math.min(colCnt-1, col);
var date = cellToDate(0, col);
dayDelta = dayDiff(date, origDate);
}
// calculate minute delta (only if over slots)
if (!isAllDay) {
minuteDelta = Math.round((ui.position.top - origPosition.top) / snapHeight) * snapMinutes;
}
}
// any state changes?
if (
isInBounds != prevIsInBounds ||
isAllDay != prevIsAllDay ||
colDelta != prevColDelta ||
minuteDelta != prevMinuteDelta
) {
updateUI();
// update previous states for next time
prevIsInBounds = isInBounds;
prevIsAllDay = isAllDay;
prevColDelta = colDelta;
prevMinuteDelta = minuteDelta;
}
// if out-of-bounds, revert when done, and vice versa.
eventElement.draggable('option', 'revert', !isInBounds);
},
stop: function(ev, ui) {
clearOverlays();
trigger('eventDragStop', eventElement, event, ev, ui);
if (isInBounds && (isAllDay || dayDelta || minuteDelta)) { // changed!
eventDrop(this, event, dayDelta, isAllDay ? 0 : minuteDelta, isAllDay, ev, ui);
}
else { // either no change or out-of-bounds (draggable has already reverted)
// reset states for next time, and for updateUI()
isInBounds = true;
isAllDay = false;
colDelta = 0;
dayDelta = 0;
minuteDelta = 0;
updateUI();
eventElement.css('filter', ''); // clear IE opacity side-effects
// sometimes fast drags make event revert to wrong position, so reset.
// also, if we dragged the element out of the area because of snapping,
// but the *mouse* is still in bounds, we need to reset the position.
eventElement.css(origPosition);
showEvents(event, eventElement);
}
}
});
function updateUI() {
clearOverlays();
if (isInBounds) {
if (isAllDay) {
timeElement.hide();
eventElement.draggable('option', 'grid', null); // disable grid snapping
renderDayOverlay(
addDays(cloneDate(event.start), dayDelta),
addDays(exclEndDay(event), dayDelta)
);
}
else {
updateTimeText(minuteDelta);
timeElement.css('display', ''); // show() was causing display=inline
eventElement.draggable('option', 'grid', [colWidth, snapHeight]); // re-enable grid snapping
}
}
}
function updateTimeText(minuteDelta) {
var newStart = addMinutes(cloneDate(event.start), minuteDelta);
var newEnd;
if (event.end) {
newEnd = addMinutes(cloneDate(event.end), minuteDelta);
}
timeElement.text(formatDates(newStart, newEnd, opt('timeFormat')));
}
}
/* Resizing
--------------------------------------------------------------------------------------*/
function resizableSlotEvent(event, eventElement, timeElement) {
var snapDelta, prevSnapDelta;
var snapHeight = getSnapHeight();
var snapMinutes = getSnapMinutes();
eventElement.resizable({
handles: {
s: '.ui-resizable-handle'
},
grid: snapHeight,
start: function(ev, ui) {
snapDelta = prevSnapDelta = 0;
hideEvents(event, eventElement);
trigger('eventResizeStart', this, event, ev, ui);
},
resize: function(ev, ui) {
// don't rely on ui.size.height, doesn't take grid into account
snapDelta = Math.round((Math.max(snapHeight, eventElement.height()) - ui.originalSize.height) / snapHeight);
if (snapDelta != prevSnapDelta) {
timeElement.text(
formatDates(
event.start,
(!snapDelta && !event.end) ? null : // no change, so don't display time range
addMinutes(eventEnd(event), snapMinutes*snapDelta),
opt('timeFormat')
)
);
prevSnapDelta = snapDelta;
}
},
stop: function(ev, ui) {
trigger('eventResizeStop', this, event, ev, ui);
if (snapDelta) {
eventResize(this, event, 0, snapMinutes*snapDelta, ev, ui);
}else{
showEvents(event, eventElement);
// BUG: if event was really short, need to put title back in span
}
}
});
}
}
/* Agenda Event Segment Utilities
-----------------------------------------------------------------------------*/
// Sets the seg.backwardCoord and seg.forwardCoord on each segment and returns a new
// list in the order they should be placed into the DOM (an implicit z-index).
function placeSlotSegs(segs) {
var levels = buildSlotSegLevels(segs);
var level0 = levels[0];
var i;
computeForwardSlotSegs(levels);
if (level0) {
for (i=0; i<level0.length; i++) {
computeSlotSegPressures(level0[i]);
}
for (i=0; i<level0.length; i++) {
computeSlotSegCoords(level0[i], 0, 0);
}
}
return flattenSlotSegLevels(levels);
}
// Builds an array of segments "levels". The first level will be the leftmost tier of segments
// if the calendar is left-to-right, or the rightmost if the calendar is right-to-left.
function buildSlotSegLevels(segs) {
var levels = [];
var i, seg;
var j;
for (i=0; i<segs.length; i++) {
seg = segs[i];
// go through all the levels and stop on the first level where there are no collisions
for (j=0; j<levels.length; j++) {
if (!computeSlotSegCollisions(seg, levels[j]).length) {
break;
}
}
(levels[j] || (levels[j] = [])).push(seg);
}
return levels;
}
// For every segment, figure out the other segments that are in subsequent
// levels that also occupy the same vertical space. Accumulate in seg.forwardSegs
function computeForwardSlotSegs(levels) {
var i, level;
var j, seg;
var k;
for (i=0; i<levels.length; i++) {
level = levels[i];
for (j=0; j<level.length; j++) {
seg = level[j];
seg.forwardSegs = [];
for (k=i+1; k<levels.length; k++) {
computeSlotSegCollisions(seg, levels[k], seg.forwardSegs);
}
}
}
}
// Figure out which path forward (via seg.forwardSegs) results in the longest path until
// the furthest edge is reached. The number of segments in this path will be seg.forwardPressure
function computeSlotSegPressures(seg) {
var forwardSegs = seg.forwardSegs;
var forwardPressure = 0;
var i, forwardSeg;
if (seg.forwardPressure === undefined) { // not already computed
for (i=0; i<forwardSegs.length; i++) {
forwardSeg = forwardSegs[i];
// figure out the child's maximum forward path
computeSlotSegPressures(forwardSeg);
// either use the existing maximum, or use the child's forward pressure
// plus one (for the forwardSeg itself)
forwardPressure = Math.max(
forwardPressure,
1 + forwardSeg.forwardPressure
);
}
seg.forwardPressure = forwardPressure;
}
}
// Calculate seg.forwardCoord and seg.backwardCoord for the segment, where both values range
// from 0 to 1. If the calendar is left-to-right, the seg.backwardCoord maps to "left" and
// seg.forwardCoord maps to "right" (via percentage). Vice-versa if the calendar is right-to-left.
//
// The segment might be part of a "series", which means consecutive segments with the same pressure
// who's width is unknown until an edge has been hit. `seriesBackwardPressure` is the number of
// segments behind this one in the current series, and `seriesBackwardCoord` is the starting
// coordinate of the first segment in the series.
function computeSlotSegCoords(seg, seriesBackwardPressure, seriesBackwardCoord) {
var forwardSegs = seg.forwardSegs;
var i;
if (seg.forwardCoord === undefined) { // not already computed
if (!forwardSegs.length) {
// if there are no forward segments, this segment should butt up against the edge
seg.forwardCoord = 1;
}
else {
// sort highest pressure first
forwardSegs.sort(compareForwardSlotSegs);
// this segment's forwardCoord will be calculated from the backwardCoord of the
// highest-pressure forward segment.
computeSlotSegCoords(forwardSegs[0], seriesBackwardPressure + 1, seriesBackwardCoord);
seg.forwardCoord = forwardSegs[0].backwardCoord;
}
// calculate the backwardCoord from the forwardCoord. consider the series
seg.backwardCoord = seg.forwardCoord -
(seg.forwardCoord - seriesBackwardCoord) / // available width for series
(seriesBackwardPressure + 1); // # of segments in the series
// use this segment's coordinates to computed the coordinates of the less-pressurized
// forward segments
for (i=0; i<forwardSegs.length; i++) {
computeSlotSegCoords(forwardSegs[i], 0, seg.forwardCoord);
}
}
}
// Outputs a flat array of segments, from lowest to highest level
function flattenSlotSegLevels(levels) {
var segs = [];
var i, level;
var j;
for (i=0; i<levels.length; i++) {
level = levels[i];
for (j=0; j<level.length; j++) {
segs.push(level[j]);
}
}
return segs;
}
// Find all the segments in `otherSegs` that vertically collide with `seg`.
// Append into an optionally-supplied `results` array and return.
function computeSlotSegCollisions(seg, otherSegs, results) {
results = results || [];
for (var i=0; i<otherSegs.length; i++) {
if (isSlotSegCollision(seg, otherSegs[i])) {
results.push(otherSegs[i]);
}
}
return results;
}
// Do these segments occupy the same vertical space?
function isSlotSegCollision(seg1, seg2) {
return seg1.end > seg2.start && seg1.start < seg2.end;
}
// A cmp function for determining which forward segment to rely on more when computing coordinates.
function compareForwardSlotSegs(seg1, seg2) {
// put higher-pressure first
return seg2.forwardPressure - seg1.forwardPressure ||
// put segments that are closer to initial edge first (and favor ones with no coords yet)
(seg1.backwardCoord || 0) - (seg2.backwardCoord || 0) ||
// do normal sorting...
compareSlotSegs(seg1, seg2);
}
// A cmp function for determining which segment should be closer to the initial edge
// (the left edge on a left-to-right calendar).
function compareSlotSegs(seg1, seg2) {
return seg1.start - seg2.start || // earlier start time goes first
(seg2.end - seg2.start) - (seg1.end - seg1.start) || // tie? longer-duration goes first
(seg1.event.title || '').localeCompare(seg2.event.title); // tie? alphabetically by title
}
;;
function View(element, calendar, viewName) {
var t = this;
// exports
t.element = element;
t.calendar = calendar;
t.name = viewName;
t.opt = opt;
t.trigger = trigger;
t.isEventDraggable = isEventDraggable;
t.isEventResizable = isEventResizable;
t.setEventData = setEventData;
t.clearEventData = clearEventData;
t.eventEnd = eventEnd;
t.reportEventElement = reportEventElement;
t.triggerEventDestroy = triggerEventDestroy;
t.eventElementHandlers = eventElementHandlers;
t.showEvents = showEvents;
t.hideEvents = hideEvents;
t.eventDrop = eventDrop;
t.eventResize = eventResize;
// t.title
// t.start, t.end
// t.visStart, t.visEnd
// imports
var defaultEventEnd = t.defaultEventEnd;
var normalizeEvent = calendar.normalizeEvent; // in EventManager
var reportEventChange = calendar.reportEventChange;
// locals
var eventsByID = {}; // eventID mapped to array of events (there can be multiple b/c of repeating events)
var eventElementsByID = {}; // eventID mapped to array of jQuery elements
var eventElementCouples = []; // array of objects, { event, element } // TODO: unify with segment system
var options = calendar.options;
function opt(name, viewNameOverride) {
var v = options[name];
if ($.isPlainObject(v)) {
return smartProperty(v, viewNameOverride || viewName);
}
return v;
}
function trigger(name, thisObj) {
return calendar.trigger.apply(
calendar,
[name, thisObj || t].concat(Array.prototype.slice.call(arguments, 2), [t])
);
}
/* Event Editable Boolean Calculations
------------------------------------------------------------------------------*/
function isEventDraggable(event) {
var source = event.source || {};
return firstDefined(
event.startEditable,
source.startEditable,
opt('eventStartEditable'),
event.editable,
source.editable,
opt('editable')
)
&& !opt('disableDragging'); // deprecated
}
function isEventResizable(event) { // but also need to make sure the seg.isEnd == true
var source = event.source || {};
return firstDefined(
event.durationEditable,
source.durationEditable,
opt('eventDurationEditable'),
event.editable,
source.editable,
opt('editable')
)
&& !opt('disableResizing'); // deprecated
}
/* Event Data
------------------------------------------------------------------------------*/
function setEventData(events) { // events are already normalized at this point
eventsByID = {};
var i, len=events.length, event;
for (i=0; i<len; i++) {
event = events[i];
if (eventsByID[event._id]) {
eventsByID[event._id].push(event);
}else{
eventsByID[event._id] = [event];
}
}
}
function clearEventData() {
eventsByID = {};
eventElementsByID = {};
eventElementCouples = [];
}
// returns a Date object for an event's end
function eventEnd(event) {
return event.end ? cloneDate(event.end) : defaultEventEnd(event);
}
/* Event Elements
------------------------------------------------------------------------------*/
// report when view creates an element for an event
function reportEventElement(event, element) {
eventElementCouples.push({ event: event, element: element });
if (eventElementsByID[event._id]) {
eventElementsByID[event._id].push(element);
}else{
eventElementsByID[event._id] = [element];
}
}
function triggerEventDestroy() {
$.each(eventElementCouples, function(i, couple) {
t.trigger('eventDestroy', couple.event, couple.event, couple.element);
});
}
// attaches eventClick, eventMouseover, eventMouseout
function eventElementHandlers(event, eventElement) {
eventElement
.click(function(ev) {
if (!eventElement.hasClass('ui-draggable-dragging') &&
!eventElement.hasClass('ui-resizable-resizing')) {
return trigger('eventClick', this, event, ev);
}
})
.hover(
function(ev) {
trigger('eventMouseover', this, event, ev);
},
function(ev) {
trigger('eventMouseout', this, event, ev);
}
);
// TODO: don't fire eventMouseover/eventMouseout *while* dragging is occuring (on subject element)
// TODO: same for resizing
}
function showEvents(event, exceptElement) {
eachEventElement(event, exceptElement, 'show');
}
function hideEvents(event, exceptElement) {
eachEventElement(event, exceptElement, 'hide');
}
function eachEventElement(event, exceptElement, funcName) {
// NOTE: there may be multiple events per ID (repeating events)
// and multiple segments per event
var elements = eventElementsByID[event._id],
i, len = elements.length;
for (i=0; i<len; i++) {
if (!exceptElement || elements[i][0] != exceptElement[0]) {
elements[i][funcName]();
}
}
}
/* Event Modification Reporting
---------------------------------------------------------------------------------*/
function eventDrop(e, event, dayDelta, minuteDelta, allDay, ev, ui) {
var oldAllDay = event.allDay;
var eventId = event._id;
moveEvents(eventsByID[eventId], dayDelta, minuteDelta, allDay);
trigger(
'eventDrop',
e,
event,
dayDelta,
minuteDelta,
allDay,
function() {
// TODO: investigate cases where this inverse technique might not work
moveEvents(eventsByID[eventId], -dayDelta, -minuteDelta, oldAllDay);
reportEventChange(eventId);
},
ev,
ui
);
reportEventChange(eventId);
}
function eventResize(e, event, dayDelta, minuteDelta, ev, ui) {
var eventId = event._id;
elongateEvents(eventsByID[eventId], dayDelta, minuteDelta);
trigger(
'eventResize',
e,
event,
dayDelta,
minuteDelta,
function() {
// TODO: investigate cases where this inverse technique might not work
elongateEvents(eventsByID[eventId], -dayDelta, -minuteDelta);
reportEventChange(eventId);
},
ev,
ui
);
reportEventChange(eventId);
}
/* Event Modification Math
---------------------------------------------------------------------------------*/
function moveEvents(events, dayDelta, minuteDelta, allDay) {
minuteDelta = minuteDelta || 0;
for (var e, len=events.length, i=0; i<len; i++) {
e = events[i];
if (allDay !== undefined) {
e.allDay = allDay;
}
addMinutes(addDays(e.start, dayDelta, true), minuteDelta);
if (e.end) {
e.end = addMinutes(addDays(e.end, dayDelta, true), minuteDelta);
}
normalizeEvent(e, options);
}
}
function elongateEvents(events, dayDelta, minuteDelta) {
minuteDelta = minuteDelta || 0;
for (var e, len=events.length, i=0; i<len; i++) {
e = events[i];
e.end = addMinutes(addDays(eventEnd(e), dayDelta, true), minuteDelta);
normalizeEvent(e, options);
}
}
// ====================================================================================================
// Utilities for day "cells"
// ====================================================================================================
// The "basic" views are completely made up of day cells.
// The "agenda" views have day cells at the top "all day" slot.
// This was the obvious common place to put these utilities, but they should be abstracted out into
// a more meaningful class (like DayEventRenderer).
// ====================================================================================================
// For determining how a given "cell" translates into a "date":
//
// 1. Convert the "cell" (row and column) into a "cell offset" (the # of the cell, cronologically from the first).
// Keep in mind that column indices are inverted with isRTL. This is taken into account.
//
// 2. Convert the "cell offset" to a "day offset" (the # of days since the first visible day in the view).
//
// 3. Convert the "day offset" into a "date" (a JavaScript Date object).
//
// The reverse transformation happens when transforming a date into a cell.
// exports
t.isHiddenDay = isHiddenDay;
t.skipHiddenDays = skipHiddenDays;
t.getCellsPerWeek = getCellsPerWeek;
t.dateToCell = dateToCell;
t.dateToDayOffset = dateToDayOffset;
t.dayOffsetToCellOffset = dayOffsetToCellOffset;
t.cellOffsetToCell = cellOffsetToCell;
t.cellToDate = cellToDate;
t.cellToCellOffset = cellToCellOffset;
t.cellOffsetToDayOffset = cellOffsetToDayOffset;
t.dayOffsetToDate = dayOffsetToDate;
t.rangeToSegments = rangeToSegments;
// internals
var hiddenDays = opt('hiddenDays') || []; // array of day-of-week indices that are hidden
var isHiddenDayHash = []; // is the day-of-week hidden? (hash with day-of-week-index -> bool)
var cellsPerWeek;
var dayToCellMap = []; // hash from dayIndex -> cellIndex, for one week
var cellToDayMap = []; // hash from cellIndex -> dayIndex, for one week
var isRTL = opt('isRTL');
// initialize important internal variables
(function() {
if (opt('weekends') === false) {
hiddenDays.push(0, 6); // 0=sunday, 6=saturday
}
// Loop through a hypothetical week and determine which
// days-of-week are hidden. Record in both hashes (one is the reverse of the other).
for (var dayIndex=0, cellIndex=0; dayIndex<7; dayIndex++) {
dayToCellMap[dayIndex] = cellIndex;
isHiddenDayHash[dayIndex] = $.inArray(dayIndex, hiddenDays) != -1;
if (!isHiddenDayHash[dayIndex]) {
cellToDayMap[cellIndex] = dayIndex;
cellIndex++;
}
}
cellsPerWeek = cellIndex;
if (!cellsPerWeek) {
throw 'invalid hiddenDays'; // all days were hidden? bad.
}
})();
// Is the current day hidden?
// `day` is a day-of-week index (0-6), or a Date object
function isHiddenDay(day) {
if (typeof day == 'object') {
day = day.getDay();
}
return isHiddenDayHash[day];
}
function getCellsPerWeek() {
return cellsPerWeek;
}
// Keep incrementing the current day until it is no longer a hidden day.
// If the initial value of `date` is not a hidden day, don't do anything.
// Pass `isExclusive` as `true` if you are dealing with an end date.
// `inc` defaults to `1` (increment one day forward each time)
function skipHiddenDays(date, inc, isExclusive) {
inc = inc || 1;
while (
isHiddenDayHash[ ( date.getDay() + (isExclusive ? inc : 0) + 7 ) % 7 ]
) {
addDays(date, inc);
}
}
//
// TRANSFORMATIONS: cell -> cell offset -> day offset -> date
//
// cell -> date (combines all transformations)
// Possible arguments:
// - row, col
// - { row:#, col: # }
function cellToDate() {
var cellOffset = cellToCellOffset.apply(null, arguments);
var dayOffset = cellOffsetToDayOffset(cellOffset);
var date = dayOffsetToDate(dayOffset);
return date;
}
// cell -> cell offset
// Possible arguments:
// - row, col
// - { row:#, col:# }
function cellToCellOffset(row, col) {
var colCnt = t.getColCnt();
// rtl variables. wish we could pre-populate these. but where?
var dis = isRTL ? -1 : 1;
var dit = isRTL ? colCnt - 1 : 0;
if (typeof row == 'object') {
col = row.col;
row = row.row;
}
var cellOffset = row * colCnt + (col * dis + dit); // column, adjusted for RTL (dis & dit)
return cellOffset;
}
// cell offset -> day offset
function cellOffsetToDayOffset(cellOffset) {
var day0 = t.visStart.getDay(); // first date's day of week
cellOffset += dayToCellMap[day0]; // normlize cellOffset to beginning-of-week
return Math.floor(cellOffset / cellsPerWeek) * 7 // # of days from full weeks
+ cellToDayMap[ // # of days from partial last week
(cellOffset % cellsPerWeek + cellsPerWeek) % cellsPerWeek // crazy math to handle negative cellOffsets
]
- day0; // adjustment for beginning-of-week normalization
}
// day offset -> date (JavaScript Date object)
function dayOffsetToDate(dayOffset) {
var date = cloneDate(t.visStart);
addDays(date, dayOffset);
return date;
}
//
// TRANSFORMATIONS: date -> day offset -> cell offset -> cell
//
// date -> cell (combines all transformations)
function dateToCell(date) {
var dayOffset = dateToDayOffset(date);
var cellOffset = dayOffsetToCellOffset(dayOffset);
var cell = cellOffsetToCell(cellOffset);
return cell;
}
// date -> day offset
function dateToDayOffset(date) {
return dayDiff(date, t.visStart);
}
// day offset -> cell offset
function dayOffsetToCellOffset(dayOffset) {
var day0 = t.visStart.getDay(); // first date's day of week
dayOffset += day0; // normalize dayOffset to beginning-of-week
return Math.floor(dayOffset / 7) * cellsPerWeek // # of cells from full weeks
+ dayToCellMap[ // # of cells from partial last week
(dayOffset % 7 + 7) % 7 // crazy math to handle negative dayOffsets
]
- dayToCellMap[day0]; // adjustment for beginning-of-week normalization
}
// cell offset -> cell (object with row & col keys)
function cellOffsetToCell(cellOffset) {
var colCnt = t.getColCnt();
// rtl variables. wish we could pre-populate these. but where?
var dis = isRTL ? -1 : 1;
var dit = isRTL ? colCnt - 1 : 0;
var row = Math.floor(cellOffset / colCnt);
var col = ((cellOffset % colCnt + colCnt) % colCnt) * dis + dit; // column, adjusted for RTL (dis & dit)
return {
row: row,
col: col
};
}
//
// Converts a date range into an array of segment objects.
// "Segments" are horizontal stretches of time, sliced up by row.
// A segment object has the following properties:
// - row
// - cols
// - isStart
// - isEnd
//
function rangeToSegments(startDate, endDate) {
var rowCnt = t.getRowCnt();
var colCnt = t.getColCnt();
var segments = []; // array of segments to return
// day offset for given date range
var rangeDayOffsetStart = dateToDayOffset(startDate);
var rangeDayOffsetEnd = dateToDayOffset(endDate); // exclusive
// first and last cell offset for the given date range
// "last" implies inclusivity
var rangeCellOffsetFirst = dayOffsetToCellOffset(rangeDayOffsetStart);
var rangeCellOffsetLast = dayOffsetToCellOffset(rangeDayOffsetEnd) - 1;
// loop through all the rows in the view
for (var row=0; row<rowCnt; row++) {
// first and last cell offset for the row
var rowCellOffsetFirst = row * colCnt;
var rowCellOffsetLast = rowCellOffsetFirst + colCnt - 1;
// get the segment's cell offsets by constraining the range's cell offsets to the bounds of the row
var segmentCellOffsetFirst = Math.max(rangeCellOffsetFirst, rowCellOffsetFirst);
var segmentCellOffsetLast = Math.min(rangeCellOffsetLast, rowCellOffsetLast);
// make sure segment's offsets are valid and in view
if (segmentCellOffsetFirst <= segmentCellOffsetLast) {
// translate to cells
var segmentCellFirst = cellOffsetToCell(segmentCellOffsetFirst);
var segmentCellLast = cellOffsetToCell(segmentCellOffsetLast);
// view might be RTL, so order by leftmost column
var cols = [ segmentCellFirst.col, segmentCellLast.col ].sort();
// Determine if segment's first/last cell is the beginning/end of the date range.
// We need to compare "day offset" because "cell offsets" are often ambiguous and
// can translate to multiple days, and an edge case reveals itself when we the
// range's first cell is hidden (we don't want isStart to be true).
var isStart = cellOffsetToDayOffset(segmentCellOffsetFirst) == rangeDayOffsetStart;
var isEnd = cellOffsetToDayOffset(segmentCellOffsetLast) + 1 == rangeDayOffsetEnd; // +1 for comparing exclusively
segments.push({
row: row,
leftCol: cols[0],
rightCol: cols[1],
isStart: isStart,
isEnd: isEnd
});
}
}
return segments;
}
}
;;
function DayEventRenderer() {
var t = this;
// exports
t.renderDayEvents = renderDayEvents;
t.draggableDayEvent = draggableDayEvent; // made public so that subclasses can override
t.resizableDayEvent = resizableDayEvent; // "
// imports
var opt = t.opt;
var trigger = t.trigger;
var isEventDraggable = t.isEventDraggable;
var isEventResizable = t.isEventResizable;
var eventEnd = t.eventEnd;
var reportEventElement = t.reportEventElement;
var eventElementHandlers = t.eventElementHandlers;
var showEvents = t.showEvents;
var hideEvents = t.hideEvents;
var eventDrop = t.eventDrop;
var eventResize = t.eventResize;
var getRowCnt = t.getRowCnt;
var getColCnt = t.getColCnt;
var getColWidth = t.getColWidth;
var allDayRow = t.allDayRow; // TODO: rename
var colLeft = t.colLeft;
var colRight = t.colRight;
var colContentLeft = t.colContentLeft;
var colContentRight = t.colContentRight;
var dateToCell = t.dateToCell;
var getDaySegmentContainer = t.getDaySegmentContainer;
var formatDates = t.calendar.formatDates;
var renderDayOverlay = t.renderDayOverlay;
var clearOverlays = t.clearOverlays;
var clearSelection = t.clearSelection;
var getHoverListener = t.getHoverListener;
var rangeToSegments = t.rangeToSegments;
var cellToDate = t.cellToDate;
var cellToCellOffset = t.cellToCellOffset;
var cellOffsetToDayOffset = t.cellOffsetToDayOffset;
var dateToDayOffset = t.dateToDayOffset;
var dayOffsetToCellOffset = t.dayOffsetToCellOffset;
// Render `events` onto the calendar, attach mouse event handlers, and call the `eventAfterRender` callback for each.
// Mouse event will be lazily applied, except if the event has an ID of `modifiedEventId`.
// Can only be called when the event container is empty (because it wipes out all innerHTML).
function renderDayEvents(events, modifiedEventId) {
// do the actual rendering. Receive the intermediate "segment" data structures.
var segments = _renderDayEvents(
events,
false, // don't append event elements
true // set the heights of the rows
);
// report the elements to the View, for general drag/resize utilities
segmentElementEach(segments, function(segment, element) {
reportEventElement(segment.event, element);
});
// attach mouse handlers
attachHandlers(segments, modifiedEventId);
// call `eventAfterRender` callback for each event
segmentElementEach(segments, function(segment, element) {
trigger('eventAfterRender', segment.event, segment.event, element);
});
}
// Render an event on the calendar, but don't report them anywhere, and don't attach mouse handlers.
// Append this event element to the event container, which might already be populated with events.
// If an event's segment will have row equal to `adjustRow`, then explicitly set its top coordinate to `adjustTop`.
// This hack is used to maintain continuity when user is manually resizing an event.
// Returns an array of DOM elements for the event.
function renderTempDayEvent(event, adjustRow, adjustTop) {
// actually render the event. `true` for appending element to container.
// Recieve the intermediate "segment" data structures.
var segments = _renderDayEvents(
[ event ],
true, // append event elements
false // don't set the heights of the rows
);
var elements = [];
// Adjust certain elements' top coordinates
segmentElementEach(segments, function(segment, element) {
if (segment.row === adjustRow) {
element.css('top', adjustTop);
}
elements.push(element[0]); // accumulate DOM nodes
});
return elements;
}
// Render events onto the calendar. Only responsible for the VISUAL aspect.
// Not responsible for attaching handlers or calling callbacks.
// Set `doAppend` to `true` for rendering elements without clearing the existing container.
// Set `doRowHeights` to allow setting the height of each row, to compensate for vertical event overflow.
function _renderDayEvents(events, doAppend, doRowHeights) {
// where the DOM nodes will eventually end up
var finalContainer = getDaySegmentContainer();
// the container where the initial HTML will be rendered.
// If `doAppend`==true, uses a temporary container.
var renderContainer = doAppend ? $("<div/>") : finalContainer;
var segments = buildSegments(events);
var html;
var elements;
// calculate the desired `left` and `width` properties on each segment object
calculateHorizontals(segments);
// build the HTML string. relies on `left` property
html = buildHTML(segments);
// render the HTML. innerHTML is considerably faster than jQuery's .html()
renderContainer[0].innerHTML = html;
// retrieve the individual elements
elements = renderContainer.children();
// if we were appending, and thus using a temporary container,
// re-attach elements to the real container.
if (doAppend) {
finalContainer.append(elements);
}
// assigns each element to `segment.event`, after filtering them through user callbacks
resolveElements(segments, elements);
// Calculate the left and right padding+margin for each element.
// We need this for setting each element's desired outer width, because of the W3C box model.
// It's important we do this in a separate pass from acually setting the width on the DOM elements
// because alternating reading/writing dimensions causes reflow for every iteration.
segmentElementEach(segments, function(segment, element) {
segment.hsides = hsides(element, true); // include margins = `true`
});
// Set the width of each element
segmentElementEach(segments, function(segment, element) {
element.width(
Math.max(0, segment.outerWidth - segment.hsides)
);
});
// Grab each element's outerHeight (setVerticals uses this).
// To get an accurate reading, it's important to have each element's width explicitly set already.
segmentElementEach(segments, function(segment, element) {
segment.outerHeight = element.outerHeight(true); // include margins = `true`
});
// Set the top coordinate on each element (requires segment.outerHeight)
setVerticals(segments, doRowHeights);
return segments;
}
// Generate an array of "segments" for all events.
function buildSegments(events) {
var segments = [];
for (var i=0; i<events.length; i++) {
var eventSegments = buildSegmentsForEvent(events[i]);
segments.push.apply(segments, eventSegments); // append an array to an array
}
return segments;
}
// Generate an array of segments for a single event.
// A "segment" is the same data structure that View.rangeToSegments produces,
// with the addition of the `event` property being set to reference the original event.
function buildSegmentsForEvent(event) {
var startDate = event.start;
var endDate = exclEndDay(event);
var segments = rangeToSegments(startDate, endDate);
for (var i=0; i<segments.length; i++) {
segments[i].event = event;
}
return segments;
}
// Sets the `left` and `outerWidth` property of each segment.
// These values are the desired dimensions for the eventual DOM elements.
function calculateHorizontals(segments) {
var isRTL = opt('isRTL');
for (var i=0; i<segments.length; i++) {
var segment = segments[i];
// Determine functions used for calulating the elements left/right coordinates,
// depending on whether the view is RTL or not.
// NOTE:
// colLeft/colRight returns the coordinate butting up the edge of the cell.
// colContentLeft/colContentRight is indented a little bit from the edge.
var leftFunc = (isRTL ? segment.isEnd : segment.isStart) ? colContentLeft : colLeft;
var rightFunc = (isRTL ? segment.isStart : segment.isEnd) ? colContentRight : colRight;
var left = leftFunc(segment.leftCol);
var right = rightFunc(segment.rightCol);
segment.left = left;
segment.outerWidth = right - left;
}
}
// Build a concatenated HTML string for an array of segments
function buildHTML(segments) {
var html = '';
for (var i=0; i<segments.length; i++) {
html += buildHTMLForSegment(segments[i]);
}
return html;
}
// Build an HTML string for a single segment.
// Relies on the following properties:
// - `segment.event` (from `buildSegmentsForEvent`)
// - `segment.left` (from `calculateHorizontals`)
function buildHTMLForSegment(segment) {
var html = '';
var isRTL = opt('isRTL');
var event = segment.event;
var url = event.url;
// generate the list of CSS classNames
var classNames = [ 'fc-event', 'fc-event-hori' ];
if (isEventDraggable(event)) {
classNames.push('fc-event-draggable');
}
if (segment.isStart) {
classNames.push('fc-event-start');
}
if (segment.isEnd) {
classNames.push('fc-event-end');
}
// use the event's configured classNames
// guaranteed to be an array via `normalizeEvent`
classNames = classNames.concat(event.className);
if (event.source) {
// use the event's source's classNames, if specified
classNames = classNames.concat(event.source.className || []);
}
// generate a semicolon delimited CSS string for any of the "skin" properties
// of the event object (`backgroundColor`, `borderColor` and such)
var skinCss = getSkinCss(event, opt);
if (url) {
html += "<a href='" + htmlEscape(url) + "'";
}else{
html += "<div";
}
html +=
" class='" + classNames.join(' ') + "'" +
" style=" +
"'" +
"position:absolute;" +
"left:" + segment.left + "px;" +
skinCss +
"'" +
">" +
"<div class='fc-event-inner'>";
if (!event.allDay && segment.isStart) {
html +=
"<span class='fc-event-time'>" +
htmlEscape(
formatDates(event.start, event.end, opt('timeFormat'))
) +
"</span>";
}
html +=
"<span class='fc-event-title'>" +
htmlEscape(event.title || '') +
"</span>" +
"</div>";
if (segment.isEnd && isEventResizable(event)) {
html +=
"<div class='ui-resizable-handle ui-resizable-" + (isRTL ? 'w' : 'e') + "'>" +
" " + // makes hit area a lot better for IE6/7
"</div>";
}
html += "</" + (url ? "a" : "div") + ">";
// TODO:
// When these elements are initially rendered, they will be briefly visibile on the screen,
// even though their widths/heights are not set.
// SOLUTION: initially set them as visibility:hidden ?
return html;
}
// Associate each segment (an object) with an element (a jQuery object),
// by setting each `segment.element`.
// Run each element through the `eventRender` filter, which allows developers to
// modify an existing element, supply a new one, or cancel rendering.
function resolveElements(segments, elements) {
for (var i=0; i<segments.length; i++) {
var segment = segments[i];
var event = segment.event;
var element = elements.eq(i);
// call the trigger with the original element
var triggerRes = trigger('eventRender', event, event, element);
if (triggerRes === false) {
// if `false`, remove the event from the DOM and don't assign it to `segment.event`
element.remove();
}
else {
if (triggerRes && triggerRes !== true) {
// the trigger returned a new element, but not `true` (which means keep the existing element)
// re-assign the important CSS dimension properties that were already assigned in `buildHTMLForSegment`
triggerRes = $(triggerRes)
.css({
position: 'absolute',
left: segment.left
});
element.replaceWith(triggerRes);
element = triggerRes;
}
segment.element = element;
}
}
}
/* Top-coordinate Methods
-------------------------------------------------------------------------------------------------*/
// Sets the "top" CSS property for each element.
// If `doRowHeights` is `true`, also sets each row's first cell to an explicit height,
// so that if elements vertically overflow, the cell expands vertically to compensate.
function setVerticals(segments, doRowHeights) {
var rowContentHeights = calculateVerticals(segments); // also sets segment.top
var rowContentElements = getRowContentElements(); // returns 1 inner div per row
var rowContentTops = [];
// Set each row's height by setting height of first inner div
if (doRowHeights) {
for (var i=0; i<rowContentElements.length; i++) {
rowContentElements[i].height(rowContentHeights[i]);
}
}
// Get each row's top, relative to the views's origin.
// Important to do this after setting each row's height.
for (var i=0; i<rowContentElements.length; i++) {
rowContentTops.push(
rowContentElements[i].position().top
);
}
// Set each segment element's CSS "top" property.
// Each segment object has a "top" property, which is relative to the row's top, but...
segmentElementEach(segments, function(segment, element) {
element.css(
'top',
rowContentTops[segment.row] + segment.top // ...now, relative to views's origin
);
});
}
// Calculate the "top" coordinate for each segment, relative to the "top" of the row.
// Also, return an array that contains the "content" height for each row
// (the height displaced by the vertically stacked events in the row).
// Requires segments to have their `outerHeight` property already set.
function calculateVerticals(segments) {
var rowCnt = getRowCnt();
var colCnt = getColCnt();
var rowContentHeights = []; // content height for each row
var segmentRows = buildSegmentRows(segments); // an array of segment arrays, one for each row
for (var rowI=0; rowI<rowCnt; rowI++) {
var segmentRow = segmentRows[rowI];
// an array of running total heights for each column.
// initialize with all zeros.
var colHeights = [];
for (var colI=0; colI<colCnt; colI++) {
colHeights.push(0);
}
// loop through every segment
for (var segmentI=0; segmentI<segmentRow.length; segmentI++) {
var segment = segmentRow[segmentI];
// find the segment's top coordinate by looking at the max height
// of all the columns the segment will be in.
segment.top = arrayMax(
colHeights.slice(
segment.leftCol,
segment.rightCol + 1 // make exclusive for slice
)
);
// adjust the columns to account for the segment's height
for (var colI=segment.leftCol; colI<=segment.rightCol; colI++) {
colHeights[colI] = segment.top + segment.outerHeight;
}
}
// the tallest column in the row should be the "content height"
rowContentHeights.push(arrayMax(colHeights));
}
return rowContentHeights;
}
// Build an array of segment arrays, each representing the segments that will
// be in a row of the grid, sorted by which event should be closest to the top.
function buildSegmentRows(segments) {
var rowCnt = getRowCnt();
var segmentRows = [];
var segmentI;
var segment;
var rowI;
// group segments by row
for (segmentI=0; segmentI<segments.length; segmentI++) {
segment = segments[segmentI];
rowI = segment.row;
if (segment.element) { // was rendered?
if (segmentRows[rowI]) {
// already other segments. append to array
segmentRows[rowI].push(segment);
}
else {
// first segment in row. create new array
segmentRows[rowI] = [ segment ];
}
}
}
// sort each row
for (rowI=0; rowI<rowCnt; rowI++) {
segmentRows[rowI] = sortSegmentRow(
segmentRows[rowI] || [] // guarantee an array, even if no segments
);
}
return segmentRows;
}
// Sort an array of segments according to which segment should appear closest to the top
function sortSegmentRow(segments) {
var sortedSegments = [];
// build the subrow array
var subrows = buildSegmentSubrows(segments);
// flatten it
for (var i=0; i<subrows.length; i++) {
sortedSegments.push.apply(sortedSegments, subrows[i]); // append an array to an array
}
return sortedSegments;
}
// Take an array of segments, which are all assumed to be in the same row,
// and sort into subrows.
function buildSegmentSubrows(segments) {
// Give preference to elements with certain criteria, so they have
// a chance to be closer to the top.
segments.sort(compareDaySegments);
var subrows = [];
for (var i=0; i<segments.length; i++) {
var segment = segments[i];
// loop through subrows, starting with the topmost, until the segment
// doesn't collide with other segments.
for (var j=0; j<subrows.length; j++) {
if (!isDaySegmentCollision(segment, subrows[j])) {
break;
}
}
// `j` now holds the desired subrow index
if (subrows[j]) {
subrows[j].push(segment);
}
else {
subrows[j] = [ segment ];
}
}
return subrows;
}
// Return an array of jQuery objects for the placeholder content containers of each row.
// The content containers don't actually contain anything, but their dimensions should match
// the events that are overlaid on top.
function getRowContentElements() {
var i;
var rowCnt = getRowCnt();
var rowDivs = [];
for (i=0; i<rowCnt; i++) {
rowDivs[i] = allDayRow(i)
.find('div.fc-day-content > div');
}
return rowDivs;
}
/* Mouse Handlers
---------------------------------------------------------------------------------------------------*/
// TODO: better documentation!
function attachHandlers(segments, modifiedEventId) {
var segmentContainer = getDaySegmentContainer();
segmentElementEach(segments, function(segment, element, i) {
var event = segment.event;
if (event._id === modifiedEventId) {
bindDaySeg(event, element, segment);
}else{
element[0]._fci = i; // for lazySegBind
}
});
lazySegBind(segmentContainer, segments, bindDaySeg);
}
function bindDaySeg(event, eventElement, segment) {
if (isEventDraggable(event)) {
t.draggableDayEvent(event, eventElement, segment); // use `t` so subclasses can override
}
if (
segment.isEnd && // only allow resizing on the final segment for an event
isEventResizable(event)
) {
t.resizableDayEvent(event, eventElement, segment); // use `t` so subclasses can override
}
// attach all other handlers.
// needs to be after, because resizableDayEvent might stopImmediatePropagation on click
eventElementHandlers(event, eventElement);
}
function draggableDayEvent(event, eventElement) {
var hoverListener = getHoverListener();
var dayDelta;
eventElement.draggable({
delay: 50,
opacity: opt('dragOpacity'),
revertDuration: opt('dragRevertDuration'),
start: function(ev, ui) {
trigger('eventDragStart', eventElement, event, ev, ui);
hideEvents(event, eventElement);
hoverListener.start(function(cell, origCell, rowDelta, colDelta) {
eventElement.draggable('option', 'revert', !cell || !rowDelta && !colDelta);
clearOverlays();
if (cell) {
var origDate = cellToDate(origCell);
var date = cellToDate(cell);
dayDelta = dayDiff(date, origDate);
renderDayOverlay(
addDays(cloneDate(event.start), dayDelta),
addDays(exclEndDay(event), dayDelta)
);
}else{
dayDelta = 0;
}
}, ev, 'drag');
},
stop: function(ev, ui) {
hoverListener.stop();
clearOverlays();
trigger('eventDragStop', eventElement, event, ev, ui);
if (dayDelta) {
eventDrop(this, event, dayDelta, 0, event.allDay, ev, ui);
}else{
eventElement.css('filter', ''); // clear IE opacity side-effects
showEvents(event, eventElement);
}
}
});
}
function resizableDayEvent(event, element, segment) {
var isRTL = opt('isRTL');
var direction = isRTL ? 'w' : 'e';
var handle = element.find('.ui-resizable-' + direction); // TODO: stop using this class because we aren't using jqui for this
var isResizing = false;
// TODO: look into using jquery-ui mouse widget for this stuff
disableTextSelection(element); // prevent native <a> selection for IE
element
.mousedown(function(ev) { // prevent native <a> selection for others
ev.preventDefault();
})
.click(function(ev) {
if (isResizing) {
ev.preventDefault(); // prevent link from being visited (only method that worked in IE6)
ev.stopImmediatePropagation(); // prevent fullcalendar eventClick handler from being called
// (eventElementHandlers needs to be bound after resizableDayEvent)
}
});
handle.mousedown(function(ev) {
if (ev.which != 1) {
return; // needs to be left mouse button
}
isResizing = true;
var hoverListener = getHoverListener();
var rowCnt = getRowCnt();
var colCnt = getColCnt();
var elementTop = element.css('top');
var dayDelta;
var helpers;
var eventCopy = $.extend({}, event);
var minCellOffset = dayOffsetToCellOffset( dateToDayOffset(event.start) );
clearSelection();
$('body')
.css('cursor', direction + '-resize')
.one('mouseup', mouseup);
trigger('eventResizeStart', this, event, ev);
hoverListener.start(function(cell, origCell) {
if (cell) {
var origCellOffset = cellToCellOffset(origCell);
var cellOffset = cellToCellOffset(cell);
// don't let resizing move earlier than start date cell
cellOffset = Math.max(cellOffset, minCellOffset);
dayDelta =
cellOffsetToDayOffset(cellOffset) -
cellOffsetToDayOffset(origCellOffset);
if (dayDelta) {
eventCopy.end = addDays(eventEnd(event), dayDelta, true);
var oldHelpers = helpers;
helpers = renderTempDayEvent(eventCopy, segment.row, elementTop);
helpers = $(helpers); // turn array into a jQuery object
helpers.find('*').css('cursor', direction + '-resize');
if (oldHelpers) {
oldHelpers.remove();
}
hideEvents(event);
}
else {
if (helpers) {
showEvents(event);
helpers.remove();
helpers = null;
}
}
clearOverlays();
renderDayOverlay( // coordinate grid already rebuilt with hoverListener.start()
event.start,
addDays( exclEndDay(event), dayDelta )
// TODO: instead of calling renderDayOverlay() with dates,
// call _renderDayOverlay (or whatever) with cell offsets.
);
}
}, ev);
function mouseup(ev) {
trigger('eventResizeStop', this, event, ev);
$('body').css('cursor', '');
hoverListener.stop();
clearOverlays();
if (dayDelta) {
eventResize(this, event, dayDelta, 0, ev);
// event redraw will clear helpers
}
// otherwise, the drag handler already restored the old events
setTimeout(function() { // make this happen after the element's click event
isResizing = false;
},0);
}
});
}
}
/* Generalized Segment Utilities
-------------------------------------------------------------------------------------------------*/
function isDaySegmentCollision(segment, otherSegments) {
for (var i=0; i<otherSegments.length; i++) {
var otherSegment = otherSegments[i];
if (
otherSegment.leftCol <= segment.rightCol &&
otherSegment.rightCol >= segment.leftCol
) {
return true;
}
}
return false;
}
function segmentElementEach(segments, callback) { // TODO: use in AgendaView?
for (var i=0; i<segments.length; i++) {
var segment = segments[i];
var element = segment.element;
if (element) {
callback(segment, element, i);
}
}
}
// A cmp function for determining which segments should appear higher up
function compareDaySegments(a, b) {
return (b.rightCol - b.leftCol) - (a.rightCol - a.leftCol) || // put wider events first
b.event.allDay - a.event.allDay || // if tie, put all-day events first (booleans cast to 0/1)
a.event.start - b.event.start || // if a tie, sort by event start date
(a.event.title || '').localeCompare(b.event.title) // if a tie, sort by event title
}
;;
//BUG: unselect needs to be triggered when events are dragged+dropped
function SelectionManager() {
var t = this;
// exports
t.select = select;
t.unselect = unselect;
t.reportSelection = reportSelection;
t.daySelectionMousedown = daySelectionMousedown;
// imports
var opt = t.opt;
var trigger = t.trigger;
var defaultSelectionEnd = t.defaultSelectionEnd;
var renderSelection = t.renderSelection;
var clearSelection = t.clearSelection;
// locals
var selected = false;
// unselectAuto
if (opt('selectable') && opt('unselectAuto')) {
$(document).mousedown(function(ev) {
var ignore = opt('unselectCancel');
if (ignore) {
if ($(ev.target).parents(ignore).length) { // could be optimized to stop after first match
return;
}
}
unselect(ev);
});
}
function select(startDate, endDate, allDay) {
unselect();
if (!endDate) {
endDate = defaultSelectionEnd(startDate, allDay);
}
renderSelection(startDate, endDate, allDay);
reportSelection(startDate, endDate, allDay);
}
function unselect(ev) {
if (selected) {
selected = false;
clearSelection();
trigger('unselect', null, ev);
}
}
function reportSelection(startDate, endDate, allDay, ev) {
selected = true;
trigger('select', null, startDate, endDate, allDay, ev);
}
function daySelectionMousedown(ev) { // not really a generic manager method, oh well
var cellToDate = t.cellToDate;
var getIsCellAllDay = t.getIsCellAllDay;
var hoverListener = t.getHoverListener();
var reportDayClick = t.reportDayClick; // this is hacky and sort of weird
if (ev.which == 1 && opt('selectable')) { // which==1 means left mouse button
unselect(ev);
var _mousedownElement = this;
var dates;
hoverListener.start(function(cell, origCell) { // TODO: maybe put cellToDate/getIsCellAllDay info in cell
clearSelection();
if (cell && getIsCellAllDay(cell)) {
dates = [ cellToDate(origCell), cellToDate(cell) ].sort(dateCompare);
renderSelection(dates[0], dates[1], true);
}else{
dates = null;
}
}, ev);
$(document).one('mouseup', function(ev) {
hoverListener.stop();
if (dates) {
if (+dates[0] == +dates[1]) {
reportDayClick(dates[0], true, ev);
}
reportSelection(dates[0], dates[1], true, ev);
}
});
}
}
}
;;
function OverlayManager() {
var t = this;
// exports
t.renderOverlay = renderOverlay;
t.clearOverlays = clearOverlays;
// locals
var usedOverlays = [];
var unusedOverlays = [];
function renderOverlay(rect, parent) {
var e = unusedOverlays.shift();
if (!e) {
e = $("<div class='fc-cell-overlay' style='position:absolute;z-index:3'/>");
}
if (e[0].parentNode != parent[0]) {
e.appendTo(parent);
}
usedOverlays.push(e.css(rect).show());
return e;
}
function clearOverlays() {
var e;
while (e = usedOverlays.shift()) {
unusedOverlays.push(e.hide().unbind());
}
}
}
;;
function CoordinateGrid(buildFunc) {
var t = this;
var rows;
var cols;
t.build = function() {
rows = [];
cols = [];
buildFunc(rows, cols);
};
t.cell = function(x, y) {
var rowCnt = rows.length;
var colCnt = cols.length;
var i, r=-1, c=-1;
for (i=0; i<rowCnt; i++) {
if (y >= rows[i][0] && y < rows[i][1]) {
r = i;
break;
}
}
for (i=0; i<colCnt; i++) {
if (x >= cols[i][0] && x < cols[i][1]) {
c = i;
break;
}
}
return (r>=0 && c>=0) ? { row:r, col:c } : null;
};
t.rect = function(row0, col0, row1, col1, originElement) { // row1,col1 is inclusive
var origin = originElement.offset();
return {
top: rows[row0][0] - origin.top,
left: cols[col0][0] - origin.left,
width: cols[col1][1] - cols[col0][0],
height: rows[row1][1] - rows[row0][0]
};
};
}
;;
function HoverListener(coordinateGrid) {
var t = this;
var bindType;
var change;
var firstCell;
var cell;
t.start = function(_change, ev, _bindType) {
change = _change;
firstCell = cell = null;
coordinateGrid.build();
mouse(ev);
bindType = _bindType || 'mousemove';
$(document).bind(bindType, mouse);
};
function mouse(ev) {
_fixUIEvent(ev); // see below
var newCell = coordinateGrid.cell(ev.pageX, ev.pageY);
if (!newCell != !cell || newCell && (newCell.row != cell.row || newCell.col != cell.col)) {
if (newCell) {
if (!firstCell) {
firstCell = newCell;
}
change(newCell, firstCell, newCell.row-firstCell.row, newCell.col-firstCell.col);
}else{
change(newCell, firstCell);
}
cell = newCell;
}
}
t.stop = function() {
$(document).unbind(bindType, mouse);
return cell;
};
}
// this fix was only necessary for jQuery UI 1.8.16 (and jQuery 1.7 or 1.7.1)
// upgrading to jQuery UI 1.8.17 (and using either jQuery 1.7 or 1.7.1) fixed the problem
// but keep this in here for 1.8.16 users
// and maybe remove it down the line
function _fixUIEvent(event) { // for issue 1168
if (event.pageX === undefined) {
event.pageX = event.originalEvent.pageX;
event.pageY = event.originalEvent.pageY;
}
}
;;
function HorizontalPositionCache(getElement) {
var t = this,
elements = {},
lefts = {},
rights = {};
function e(i) {
return elements[i] = elements[i] || getElement(i);
}
t.left = function(i) {
return lefts[i] = lefts[i] === undefined ? e(i).position().left : lefts[i];
};
t.right = function(i) {
return rights[i] = rights[i] === undefined ? t.left(i) + e(i).width() : rights[i];
};
t.clear = function() {
elements = {};
lefts = {};
rights = {};
};
}
;;
})(jQuery); | zettwerk.fullcalendar | /zettwerk.fullcalendar-0.3.1.zip/zettwerk.fullcalendar-0.3.1/zettwerk/fullcalendar/browser/fullcalendar/fullcalendar.js | fullcalendar.js |
(function($) {
var fc = $.fullCalendar;
var formatDate = fc.formatDate;
var parseISO8601 = fc.parseISO8601;
var addDays = fc.addDays;
var applyAll = fc.applyAll;
fc.sourceNormalizers.push(function(sourceOptions) {
if (sourceOptions.dataType == 'gcal' ||
sourceOptions.dataType === undefined &&
(sourceOptions.url || '').match(/^(http|https):\/\/www.google.com\/calendar\/feeds\//)) {
sourceOptions.dataType = 'gcal';
if (sourceOptions.editable === undefined) {
sourceOptions.editable = false;
}
}
});
fc.sourceFetchers.push(function(sourceOptions, start, end) {
if (sourceOptions.dataType == 'gcal') {
return transformOptions(sourceOptions, start, end);
}
});
function transformOptions(sourceOptions, start, end) {
var success = sourceOptions.success;
var data = $.extend({}, sourceOptions.data || {}, {
'start-min': formatDate(start, 'u'),
'start-max': formatDate(end, 'u'),
'singleevents': true,
'max-results': 9999
});
var ctz = sourceOptions.currentTimezone;
if (ctz) {
data.ctz = ctz = ctz.replace(' ', '_');
}
return $.extend({}, sourceOptions, {
url: sourceOptions.url.replace(/\/basic$/, '/full') + '?alt=json-in-script&callback=?',
dataType: 'jsonp',
data: data,
startParam: false,
endParam: false,
success: function(data) {
var events = [];
if (data.feed.entry) {
$.each(data.feed.entry, function(i, entry) {
var startStr = entry['gd$when'][0]['startTime'];
var start = parseISO8601(startStr, true);
var end = parseISO8601(entry['gd$when'][0]['endTime'], true);
var allDay = startStr.indexOf('T') == -1;
var url;
$.each(entry.link, function(i, link) {
if (link.type == 'text/html') {
url = link.href;
if (ctz) {
url += (url.indexOf('?') == -1 ? '?' : '&') + 'ctz=' + ctz;
}
}
});
if (allDay) {
addDays(end, -1); // make inclusive
}
events.push({
id: entry['gCal$uid']['value'],
title: entry['title']['$t'],
url: url,
start: start,
end: end,
allDay: allDay,
location: entry['gd$where'][0]['valueString'],
description: entry['content']['$t']
});
});
}
var args = [events].concat(Array.prototype.slice.call(arguments, 1));
var res = applyAll(success, this, args);
if ($.isArray(res)) {
return res;
}
return events;
}
});
}
// legacy
fc.gcalFeed = function(url, sourceOptions) {
return $.extend({}, sourceOptions, { url: url, dataType: 'gcal' });
};
})(jQuery); | zettwerk.fullcalendar | /zettwerk.fullcalendar-0.3.1.zip/zettwerk.fullcalendar-0.3.1/zettwerk/fullcalendar/browser/fullcalendar/gcal.js | gcal.js |
Introduction
============
The tasks to add translations to a plone product are more or less always the same:
* Creating and registering the locales directory
* Adding languages
* Call i18ndude with rebuild-pot command
* Call i18ndude with sync command
* Run the last two commands in combination with find-untranslated a couple of times
* And maybe directly compile the mo files
zettwerk.i18nduder tries to make this a little bit easer, by wrapping the i18ndude commands and avoid the folder and path handling by calling it directly from your buildout home folder. It makes nothing, that you can't do with i18ndude directly, but in our internal usage, it made working with translations a little bit easier and faster.
To make this work there is only one assumption made, which should be common in a paster created plone product: your translation domain has the same name as your python package.
Installation
============
Put a i18nduder part to your buildout.cfg and define it like this::
[i18nduder]
recipe = zc.recipe.egg
eggs = ${instance:eggs}
zettwerk.i18nduder
It is important to include your instance eggs, cause duder gets the path of the package by importing it. Also note, that zettwerk.i18nduder includes a dependency to i18ndude.
Available commands and usage
============================
The generated script is called duder. To see a list of commands use the --help argument::
> ./bin/duder --help
> Usage: duder command -p package.name or --help for details
>
> Available commands:
> create Create the locales folder and/or add given languages
> update Call rebuild-pot and sync
> mo Call msgfmt to build the mo files
> find Find untranslated strings (domain independent)
>
> Options:
> -h, --help show this help message and exit
> -p PACKAGE, --package=PACKAGE
> Name of the package
> -d DOMAIN, --domain=DOMAIN
> Name of the i18n domain. Only needed if it is different
> from the package name.
> -l LANGUAGES, --languages=LANGUAGES
> List of comma-separated names of language strings.
> Only used for create command. For example: -l en,de
Examples
========
The following commands are used against a newly created, and registered in your buildout archetype product with the package name dummy.example
First, we create the locales folder and add some languages::
> ./bin/duder create -p dummy.example -l en,de
> Created locales folder at: /home/joerg/Instances/Plone4/src/dummy.example/dummy/example/locales
> Don't forget to add this to your configure.zcml:
> <i18n:registerTranslations directory="locales" / >
> - en language added
> - de language added
To add another language just call it again::
> ./bin/duder create -p dummy.example -l nl
> Locales folder already exists at: /home/joerg/Instances/Plone4/src/dummy.example/dummy/example/locales
> - nl language added
After working with dummy.exmaple some translations must be done::
> ./bin/duder update -p dummy.example
> nl/LC_MESSAGES/dummy.example.po: 1 added, 0 removed
> en/LC_MESSAGES/dummy.example.po: 1 added, 0 removed
> de/LC_MESSAGES/dummy.example.po: 1 added, 0 removed
Note, that the pot/po headers are not manipulated with this. This must be done by hand.
Find-untranslated is also available::
> ./bin/duder find -p dummy.example
> wrote output to: /home/joerg/Instances/Plone4/dummy.example-untranslated
And the mo files can be compiled like this::
> ./bin/duder mo -p dummy.example
This calls "msgfmt", so it must be available on your system.
Notes about domains
===================
It is maybe good to now, that i18ndude can't differentiate domains by the MessageFactory. So if you run duder with the domain option will result with the msgids of the given domain (when used explicitly in your template files with i18n:domain) *and* the translations, which are created via the MessageFactory of you default domain.
Feel free to contact us for suggestions and improvments.
| zettwerk.i18nduder | /zettwerk.i18nduder-0.2.1.tar.gz/zettwerk.i18nduder-0.2.1/README.txt | README.txt |
import i18ndude.script
import os.path
import sys
import subprocess
from StringIO import StringIO
def _get_package_path(options, parser):
""" helper method to return the path to the package.
stops if the path not exists. """
package_name = options.package
try:
__import__(package_name)
package_path = sys.modules[package_name].__path__[0]
except:
parser.error('Invalid package name given')
return package_path
def _get_locales_path(options, parser):
""" helper method to return the path to the locales
folder of the package. stops if the package path not
exists. """
package_path = _get_package_path(options, parser)
return os.path.join(package_path,
'locales')
def _get_po_name(options):
if options.domain:
return options.domain
return options.package
def create(options, parser):
locales_path = _get_locales_path(options, parser)
po_name = _get_po_name(options)
if not os.path.exists(locales_path):
os.mkdir(locales_path)
print "Created locales folder at: %s" % (locales_path)
print "Don't forget to add this to your configure.zcml:"
print '<i18n:registerTranslations directory="locales" />'
else:
print "Locales folder already exists at: %s" % (locales_path)
if options.languages:
for lang in options.languages.split(','):
lang = lang.strip()
if lang:
path_parts = [
locales_path,
lang,
'LC_MESSAGES']
for p in range(len(path_parts)):
target_path = os.path.join(*path_parts[:p + 1])
if not os.path.exists(target_path):
os.mkdir(target_path)
path_parts.append('%s.po' % (po_name))
target_path = os.path.join(*path_parts)
if not os.path.exists(target_path):
file(target_path, 'w').close()
print "- language: %s and domain: %s " \
"added" % (lang, po_name)
else:
print "- language: %s and domain: %s already " \
"exists" % (lang, po_name)
else:
print "No languages given - skipping creation"
def update(options, parser):
locales_path = _get_locales_path(options, parser)
po_name = _get_po_name(options)
if not os.path.exists(locales_path):
parser.error('locales directory not found - run create command first')
os.chdir(locales_path)
dude_command = 'rebuild-pot'
dude_opts = ['--pot',
'%s.pot' % (po_name),
'--create',
po_name,
os.path.join('.', '..')]
sys.argv[1:] = [dude_command] + dude_opts
i18ndude.script.main()
dude_command = 'sync'
for lang in os.listdir('.'):
if os.path.isdir(os.path.join('.', lang)) and \
'LC_MESSAGES' in os.listdir(os.path.join('.', lang)):
local_path = os.path.join(lang,
'LC_MESSAGES',
'%s.po' % (po_name))
dude_opts = ['--pot',
'%s.pot' % (po_name),
local_path]
sys.argv[1:] = [dude_command] + dude_opts
i18ndude.script.main()
print "full path: %s\n" % (os.path.join(locales_path,
local_path))
def find(options, parser):
package_name = options.package
package_path = _get_package_path(options, parser)
os.chdir(package_path)
working_dir = os.getcwd()
output_file = os.path.join(
working_dir,
'%s-untranslated' % (package_name)
)
dude_command = 'find-untranslated'
dude_opts = ['.']
sys.argv[1:] = [dude_command] + dude_opts
output = StringIO()
sys.stdout = output
i18ndude.script.main()
sys.stdout = sys.__stdout__
f = file(output_file, 'w')
f.write(output.getvalue())
f.close()
print "wrote output to: %s" % (output_file)
def mo(options, parser):
po_name = _get_po_name(options)
locales_path = _get_locales_path(options, parser)
if not os.path.exists(locales_path):
parser.error('locales directory not found - run create command first')
os.chdir(locales_path)
for lang in os.listdir('.'):
if os.path.isdir(os.path.join('.', lang)) and \
'LC_MESSAGES' in os.listdir(os.path.join('.', lang)):
po_path = os.path.join(lang,
'LC_MESSAGES',
'%s.po' % (po_name))
mo_path = os.path.join(lang,
'LC_MESSAGES',
'%s.mo' % (po_name))
args = ['msgfmt',
po_path,
'-o',
mo_path]
subprocess.call(args)
print "- language: %s and domain: %s - mo created. " % (lang,
po_name) | zettwerk.i18nduder | /zettwerk.i18nduder-0.2.1.tar.gz/zettwerk.i18nduder-0.2.1/zettwerk/i18nduder/commands.py | commands.py |
Introduction
============
Create mail templates in plone.
If you want to send emails out of plone, you need to create a custom template or method. With this extension it is possible to create mail templates and send them without the need of programming. Nevertheless there is an api to send such created templates by code. For choosing the recipients you can filter by users or groups. In addition there are also extensible user filter, queried through the zca.
Installation
============
Add zettwerk.mailtemplates to your buildout eggs::
eggs = ..
zettwerk.mailtemplates
After running buildout and starting the instance, you can install Zettwerk Mailtemplates via portal_quickinstaller to your instance.
Use-Case
========
Go to the plone configuration and click on the Zettwerk Mailtemplates link, listed under the custom extensions. Use plone's add menu to add a template. Enter a title (which results in the mail subject) and a mail body text. Also set the template-id.
Click on "portal_mail_templates" on the breadcrumb. Now you can filter the recipients by username or group selection. Try the simulate button the get a list of the selected recipients. Hit the send button to send the mail(s).
By filtering a group, you can provide an additional filter. These are registered utilities for zettwerk.mailtemplates.interfaces.IMessageTemplateUserFilter - see the configure.zcml and the utility with the name "registration_reminder" for an example. This on returns only users which have never logged in to your plone site.
Recursive Groups
================
By selecting a group only the toplevel group members are used. If the group contains other groups, there members are not used.
Override Plone's default templates
==================================
It is common to customize Plone's default templates for registration and password reset. zettwerk.mailtemplates supports this through the web - no need to add custom template overrides via code. Just add a template with id 'registration' or 'password_reset' and it is used - that's all.
Todos
=====
* Tests and api documentation needed.
| zettwerk.mailtemplates | /zettwerk.mailtemplates-0.2.2.zip/zettwerk.mailtemplates-0.2.2/README.txt | README.txt |
Introduction
============
This is a full-blown functional test. The emphasis here is on testing what
the user may input and see, and the system is largely tested as a black box.
We use PloneTestCase to set up this test as well, so we have a full Plone site
to play with. We *can* inspect the state of the portal, e.g. using
self.portal and self.folder, but it is often frowned upon since you are not
treating the system as a black box. Also, if you, for example, log in or set
roles using calls like self.setRoles(), these are not reflected in the test
browser, which runs as a separate session.
Being a doctest, we can tell a story here.
First, we must perform some setup. We use the testbrowser that is shipped
with Five, as this provides proper Zope 2 integration. Most of the
documentation, though, is in the underlying zope.testbrower package.
>>> from Products.Five.testbrowser import Browser
>>> browser = Browser()
>>> portal_url = self.portal.absolute_url()
The following is useful when writing and debugging testbrowser tests. It lets
us see all error messages in the error_log.
>>> self.portal.error_log._ignored_exceptions = ()
With that in place, we can go to the portal front page and log in. We will
do this using the default user from PloneTestCase:
>>> from Products.PloneTestCase.setup import portal_owner, default_password
Because add-on themes or products may remove or hide the login portlet, this test will use the login form that comes with plone.
>>> browser.open(portal_url + '/login_form')
>>> browser.getControl(name='__ac_name').value = portal_owner
>>> browser.getControl(name='__ac_password').value = default_password
>>> browser.getControl(name='submit').click()
Here, we set the value of the fields on the login form and then simulate a
submit click. We then ensure that we get the friendly logged-in message:
>>> "You are now logged in" in browser.contents
True
Finally, let's return to the front page of our site before continuing
>>> browser.open(portal_url)
-*- extra stuff goes here -*-
The Template content type
===============================
In this section we are tesing the Template content type by performing
basic operations like adding, updadating and deleting Template content
items.
Adding a new Template content item
--------------------------------
We use the 'Add new' menu to add a new content item.
>>> browser.getLink('Add new').click()
Then we select the type of item we want to add. In this case we select
'Template' and click the 'Add' button to get to the add form.
>>> browser.getControl('Template').click()
>>> browser.getControl(name='form.button.Add').click()
>>> 'Template' in browser.contents
True
Now we fill the form and submit it.
>>> browser.getControl(name='title').value = 'Template Sample'
>>> browser.getControl('Save').click()
>>> 'Changes saved' in browser.contents
True
And we are done! We added a new 'Template' content item to the portal.
Updating an existing Template content item
---------------------------------------
Let's click on the 'edit' tab and update the object attribute values.
>>> browser.getLink('Edit').click()
>>> browser.getControl(name='title').value = 'New Template Sample'
>>> browser.getControl('Save').click()
We check that the changes were applied.
>>> 'Changes saved' in browser.contents
True
>>> 'New Template Sample' in browser.contents
True
Removing a/an Template content item
--------------------------------
If we go to the home page, we can see a tab with the 'New Template
Sample' title in the global navigation tabs.
>>> browser.open(portal_url)
>>> 'New Template Sample' in browser.contents
True
Now we are going to delete the 'New Template Sample' object. First we
go to the contents tab and select the 'New Template Sample' for
deletion.
>>> browser.getLink('Contents').click()
>>> browser.getControl('New Template Sample').click()
We click on the 'Delete' button.
>>> browser.getControl('Delete').click()
>>> 'Item(s) deleted' in browser.contents
True
So, if we go back to the home page, there is no longer a 'New Template
Sample' tab.
>>> browser.open(portal_url)
>>> 'New Template Sample' in browser.contents
False
Adding a new Template content item as contributor
------------------------------------------------
Not only site managers are allowed to add Template content items, but
also site contributors.
Let's logout and then login as 'contributor', a portal member that has the
contributor role assigned.
>>> browser.getLink('Log out').click()
>>> browser.open(portal_url + '/login_form')
>>> browser.getControl(name='__ac_name').value = 'contributor'
>>> browser.getControl(name='__ac_password').value = default_password
>>> browser.getControl(name='submit').click()
>>> browser.open(portal_url)
We use the 'Add new' menu to add a new content item.
>>> browser.getLink('Add new').click()
We select 'Template' and click the 'Add' button to get to the add form.
>>> browser.getControl('Template').click()
>>> browser.getControl(name='form.button.Add').click()
>>> 'Template' in browser.contents
True
Now we fill the form and submit it.
>>> browser.getControl(name='title').value = 'Template Sample'
>>> browser.getControl('Save').click()
>>> 'Changes saved' in browser.contents
True
Done! We added a new Template content item logged in as contributor.
Finally, let's login back as manager.
>>> browser.getLink('Log out').click()
>>> browser.open(portal_url + '/login_form')
>>> browser.getControl(name='__ac_name').value = portal_owner
>>> browser.getControl(name='__ac_password').value = default_password
>>> browser.getControl(name='submit').click()
>>> browser.open(portal_url)
The MailTemplateTool content type
===============================
In this section we are tesing the MailTemplateTool content type by performing
basic operations like adding, updadating and deleting MailTemplateTool content
items.
Adding a new MailTemplateTool content item
--------------------------------
We use the 'Add new' menu to add a new content item.
>>> browser.getLink('Add new').click()
Then we select the type of item we want to add. In this case we select
'MailTemplateTool' and click the 'Add' button to get to the add form.
>>> browser.getControl('MailTemplateTool').click()
>>> browser.getControl(name='form.button.Add').click()
>>> 'MailTemplateTool' in browser.contents
True
Now we fill the form and submit it.
>>> browser.getControl(name='title').value = 'MailTemplateTool Sample'
>>> browser.getControl('Save').click()
>>> 'Changes saved' in browser.contents
True
And we are done! We added a new 'MailTemplateTool' content item to the portal.
Updating an existing MailTemplateTool content item
---------------------------------------
Let's click on the 'edit' tab and update the object attribute values.
>>> browser.getLink('Edit').click()
>>> browser.getControl(name='title').value = 'New MailTemplateTool Sample'
>>> browser.getControl('Save').click()
We check that the changes were applied.
>>> 'Changes saved' in browser.contents
True
>>> 'New MailTemplateTool Sample' in browser.contents
True
Removing a/an MailTemplateTool content item
--------------------------------
If we go to the home page, we can see a tab with the 'New MailTemplateTool
Sample' title in the global navigation tabs.
>>> browser.open(portal_url)
>>> 'New MailTemplateTool Sample' in browser.contents
True
Now we are going to delete the 'New MailTemplateTool Sample' object. First we
go to the contents tab and select the 'New MailTemplateTool Sample' for
deletion.
>>> browser.getLink('Contents').click()
>>> browser.getControl('New MailTemplateTool Sample').click()
We click on the 'Delete' button.
>>> browser.getControl('Delete').click()
>>> 'Item(s) deleted' in browser.contents
True
So, if we go back to the home page, there is no longer a 'New MailTemplateTool
Sample' tab.
>>> browser.open(portal_url)
>>> 'New MailTemplateTool Sample' in browser.contents
False
Adding a new MailTemplateTool content item as contributor
------------------------------------------------
Not only site managers are allowed to add MailTemplateTool content items, but
also site contributors.
Let's logout and then login as 'contributor', a portal member that has the
contributor role assigned.
>>> browser.getLink('Log out').click()
>>> browser.open(portal_url + '/login_form')
>>> browser.getControl(name='__ac_name').value = 'contributor'
>>> browser.getControl(name='__ac_password').value = default_password
>>> browser.getControl(name='submit').click()
>>> browser.open(portal_url)
We use the 'Add new' menu to add a new content item.
>>> browser.getLink('Add new').click()
We select 'MailTemplateTool' and click the 'Add' button to get to the add form.
>>> browser.getControl('MailTemplateTool').click()
>>> browser.getControl(name='form.button.Add').click()
>>> 'MailTemplateTool' in browser.contents
True
Now we fill the form and submit it.
>>> browser.getControl(name='title').value = 'MailTemplateTool Sample'
>>> browser.getControl('Save').click()
>>> 'Changes saved' in browser.contents
True
Done! We added a new MailTemplateTool content item logged in as contributor.
Finally, let's login back as manager.
>>> browser.getLink('Log out').click()
>>> browser.open(portal_url + '/login_form')
>>> browser.getControl(name='__ac_name').value = portal_owner
>>> browser.getControl(name='__ac_password').value = default_password
>>> browser.getControl(name='submit').click()
>>> browser.open(portal_url)
| zettwerk.mailtemplates | /zettwerk.mailtemplates-0.2.2.zip/zettwerk.mailtemplates-0.2.2/zettwerk/mailtemplates/README.txt | README.txt |
from zope.component import getUtilitiesFor
from zope.interface import implements, Interface
from Products.Five import BrowserView
from Products.CMFCore.utils import getToolByName
from zettwerk.mailtemplates.interfaces import IMessageTemplateUserFilter
from zettwerk.mailtemplates.interfaces import IMessageTemplateUserObjectFilter
class Imail_template_toolView(Interface):
"""
mail_template_tool view interface
"""
def test():
""" test method"""
class mail_template_toolView(BrowserView):
"""
mail_template_tool browser view
"""
implements(Imail_template_toolView)
def __init__(self, context, request):
self.context = context
self.request = request
@property
def portal_catalog(self):
return getToolByName(self.context, 'portal_catalog')
@property
def portal_groups(self):
return getToolByName(self.context, 'portal_groups')
@property
def templates(self):
templates = self.context.getFolderContents({'portal_type': 'Template'},
full_objects=True)
return sorted(templates, key=lambda template: template.getTemplateId())
def getGroups(self):
groups = []
all_groups = self.portal_groups.listGroups()
for group in all_groups:
if group.getId() == 'AuthenticatedUsers':
continue
title = group.getProperty('title')
if not title:
title = group.getId()
groups.append((group.getId(), title))
return groups
def getExtraFilters(self):
""" look for registered utilities that might be used as extra
filters. """
returner = [{'name': '',
'title': ''}]
checks = getUtilitiesFor(IMessageTemplateUserFilter)
for check in checks:
returner.append({'name': check[0],
'title': check[1].getTitle(self.request)})
return returner
def getExtraObjectFilters(self):
""" look for registered utilities that might be used as extra
object filters. """
returner = []
checks = getUtilitiesFor(IMessageTemplateUserObjectFilter)
for check in checks:
returner.append({'name': check[0],
'title': check[1].getTitle(self.request),
'objects': check[1].objectList()})
return returner | zettwerk.mailtemplates | /zettwerk.mailtemplates-0.2.2.zip/zettwerk.mailtemplates-0.2.2/zettwerk/mailtemplates/browser/mail_template_toolview.py | mail_template_toolview.py |
from zope.interface import implements, Interface
from zope.component import queryUtility
from Acquisition import aq_base
from Products.Five import BrowserView
from Products.CMFCore.utils import getToolByName
from zettwerk.mailtemplates.interfaces import IMessageTemplateUserFilter
from zettwerk.mailtemplates.interfaces import IMessageTemplateUserObjectFilter
class Isend_emailView(Interface):
"""
send_email view interface
"""
class send_emailView(BrowserView):
"""
send_email browser view
"""
implements(Isend_emailView)
def __init__(self, context, request):
self.context = context
self.request = request
@property
def portal_membership(self):
return getToolByName(self.context, 'portal_membership')
@property
def portal_groups(self):
return getToolByName(self.context, 'portal_groups')
def __call__(self):
""" do something """
try:
targets = self._getMemberTargets()
except ValueError as e:
return e.message
portal_templates = getToolByName(self, 'portal_mail_templates')
template_id = self.request.get('template', '')
for member in targets:
username = member.getUserName()
portal_templates.sendTemplate(
template_id, username
)
return "sent %s emails" % (len(targets))
def _getMemberTargets(self):
""" return the target member objects """
targets = self._getUserTarget()
if not targets:
targets = self._getGroupTargets()
extra_filter = self.request.get('extra_filter', '')
if extra_filter:
extra = queryUtility(IMessageTemplateUserFilter,
name=extra_filter)
if not extra:
raise ValueError(
'Invalid extra filter given: %s' % extra
)
targets = extra.filteredMembers(targets)
extra_object_filters = self.request.get('extra_object_filters', {})
for object_filter, path in extra_object_filters.items():
if path:
obj = self.context.restrictedTraverse(path)
obj_filter = queryUtility(IMessageTemplateUserObjectFilter,
name=object_filter)
if not obj_filter:
raise ValueError(
'Invalid extra obj filter ' \
'given: %s' % object_filter
)
targets = obj_filter.filteredMembers(targets, obj)
return targets
def _getUserTarget(self):
targets = []
user_id = self.request.get('user_id', '')
if user_id:
member = self.portal_membership.getMemberById(user_id)
if not member:
raise ValueError('Invalid user_id given: %s' % (user_id))
targets.append(member)
return targets
def _getGroupTargets(self):
targets = []
group_id = self.request.get('group_id', '')
if not group_id:
targets = self.portal_membership.listMembers()
else:
group = self.portal_groups.getGroupById(group_id)
if not group:
raise ValueError('Invalid group_id given: %s' % (group_id))
targets = group.getGroupMembers()
## only use top-level members, no members of recursive groups
return [t for t in targets \
if not (hasattr(aq_base(t), 'isGroup') and \
aq_base(t).isGroup())]
return targets | zettwerk.mailtemplates | /zettwerk.mailtemplates-0.2.2.zip/zettwerk.mailtemplates-0.2.2/zettwerk/mailtemplates/browser/send_emailview.py | send_emailview.py |
from zope.interface import implements
from Products.CMFCore.utils import UniqueObject
from Products.Archetypes import atapi
from Products.ATContentTypes.content import folder
from Products.ATContentTypes.content import schemata
# -*- Message Factory Imported Here -*-
from zettwerk.mailtemplates.interfaces import IMailTemplateTool
from zettwerk.mailtemplates.config import PROJECTNAME
from Products.CMFCore.utils import getToolByName
from email.Utils import parseaddr
from email.Utils import formataddr
MailTemplateToolSchema = folder.ATFolderSchema.copy() + atapi.Schema((
# -*- Your Archetypes field definitions here ... -*-
))
# Set storage on fields copied from ATFolderSchema, making sure
# they work well with the python bridge properties.
MailTemplateToolSchema['title'].storage = atapi.AnnotationStorage()
MailTemplateToolSchema['description'].storage = atapi.AnnotationStorage()
schemata.finalizeATCTSchema(
MailTemplateToolSchema,
folderish=True,
moveDiscussion=False
)
class MailTemplateTool(UniqueObject, folder.ATFolder):
"""Description of the Example Type"""
implements(IMailTemplateTool)
id = 'portal_mail_templates'
meta_type = "MailTemplateTool"
schema = MailTemplateToolSchema
title = atapi.ATFieldProperty('title')
description = atapi.ATFieldProperty('description')
# -*- Your ATSchema to Python Property Bridges Here ... -*-
def isOverwrittenDefaultTemplate(self, default_template_id):
""" if the default template id matches 'registration' or
'password_reset' - check the existance of these templates. """
try:
return self.getTemplate(default_template_id) is not None
except ValueError:
return False
def hasTemplate(self, template_id):
""" helpler method to check the availabililty of a template
by id. """
try:
self.getTemplate(template_id)
return True
except ValueError:
return False
def getTemplate(self, template_id):
""" return a template by template id """
for template in self.values():
if template.getTemplateId() == template_id:
return template
raise ValueError('Invalid template id')
def sendTemplate(self, template_id, member_id):
""" send the chosen template_id to mto from mfrom
fill the placeholder with values relating to member
"""
template = self.getTemplate(template_id)
mtool = getToolByName(self, 'portal_membership')
ptool = getToolByName(self, 'portal_url')
portal = ptool.getPortalObject()
member = mtool.getMemberById(member_id)
#get the recipient data from the member
to_address = member.getProperty('email', '')
if not to_address:
to_address = member.getProperty('private_email', '')
to_name = member.getProperty('fullname', '')
mto = formataddr((to_name, to_address))
if parseaddr(mto)[1] != to_address:
mto = to_address
#use the portal email and admin name as sender info
from_address = portal.getProperty('email_from_address', '')
from_name = portal.getProperty('email_from_name', '')
mail_charset = portal.getProperty('email_charset', 'utf-8')
mfrom = formataddr((from_name, from_address))
if parseaddr(mfrom)[1] != from_address:
mfrom = from_address
if mto:
body = template.getRenderedBody(member)
subject = template.Title()
mh = getToolByName(self, 'MailHost')
mh.send(body,
mto=mto,
mfrom=mfrom,
subject=subject,
charset=mail_charset,
msg_type='text/plain')
atapi.registerType(MailTemplateTool, PROJECTNAME) | zettwerk.mailtemplates | /zettwerk.mailtemplates-0.2.2.zip/zettwerk.mailtemplates-0.2.2/zettwerk/mailtemplates/content/mailtemplatetool.py | mailtemplatetool.py |
from zope.interface import implements
from DateTime import DateTime
from Products.Archetypes import atapi
from Products.ATContentTypes.content import base
from Products.ATContentTypes.content import schemata
# -*- Message Factory Imported Here -*-
from zettwerk.mailtemplates import mailtemplatesMessageFactory as _
from zettwerk.mailtemplates.interfaces import ITemplate
from zettwerk.mailtemplates.config import PROJECTNAME
from Products.CMFCore.utils import getToolByName
TemplateSchema = schemata.ATContentTypeSchema.copy() + atapi.Schema((
# -*- Your Archetypes field definitions here ... -*-
atapi.StringField(
'templateId',
storage=atapi.AnnotationStorage(),
widget=atapi.StringWidget(
label=_(u"Template id"),
description=_(u"a unique id for the template. You can use a " \
" custom one or use one of the defaults: " \
"'registration', 'password_reset'"),
),
required=True,
),
))
# Set storage on fields copied from ATContentTypeSchema, making sure
# they work well with the python bridge properties.
TemplateSchema['title'].storage = atapi.AnnotationStorage()
TemplateSchema['title'].widget.label = 'Subject'
TemplateSchema['title'].widget.description = 'Enter the mail subject'
TemplateSchema['description'].storage = atapi.AnnotationStorage()
TemplateSchema['description'].widget.label = 'Mail body text'
TemplateSchema['description'].widget.description = '''
You can use python string substitution syntax to insert dynamic values.
Supported keywords are: username, fullname, portal_url, portal_name,
password_reset_link, expires_string. Example: "Hello %(fullname)s"
'''
schemata.finalizeATCTSchema(TemplateSchema, moveDiscussion=False)
class Template(base.ATCTContent):
"""Description of the Example Type"""
implements(ITemplate)
meta_type = "Template"
schema = TemplateSchema
title = atapi.ATFieldProperty('title')
description = atapi.ATFieldProperty('description')
# -*- Your ATSchema to Python Property Bridges Here ... -*-
templateId = atapi.ATFieldProperty('templateId')
def getSubject(self):
""" return the title """
return self.Title()
def getBody(self):
""" return the description """
return self.Description()
def getRenderedBody(self, member, preview=False):
""" will fail on invalid substitutions
returns empty strings if the member does not
have the information or is empty
"""
ptool = getToolByName(self, 'portal_url')
rtool = getToolByName(self, 'portal_password_reset')
portal_url = ptool()
portal_name = ptool.getProperty('title', '')
username = member.getId()
fullname = member.getProperty('fullname', '')
data = {'username': username,
'fullname': fullname,
'portal_url': portal_url,
'portal_name': portal_name}
body = self.getBody()
if not preview:
if body.find('%(password_reset_link)s') != -1 or \
body.find('%(expires_string)s') != -1:
## returns a dict with reset data
reset = rtool.requestReset(username)
data.update(
{'password_reset_link':
rtool.pwreset_constructURL(reset['randomstring'])}
)
data.update(
{'expires_string':
self.toLocalizedTime(reset['expires'], long_format=1)}
)
else:
data.update(
{'password_reset_link': data['portal_url']}
)
data.update(
{'expires_string':
self.toLocalizedTime(DateTime(), long_format=1)}
)
return body % data
def getRenderedBodyPreview(self):
""" return the rendered mail text, will not fail on errors,
and decoded for gui """
mtool = getToolByName(self, 'portal_membership')
ptool = getToolByName(self, 'portal_properties')
output_enc = ptool.site_properties.getProperty('default_charset')
try:
body = self.getRenderedBody(mtool.getAuthenticatedMember(),
preview=True)
if output_enc != 'utf-8':
return body.encode(output_enc)
else:
return body
except Exception as reason:
return 'ERROR: %s' % (repr(reason))
atapi.registerType(Template, PROJECTNAME) | zettwerk.mailtemplates | /zettwerk.mailtemplates-0.2.2.zip/zettwerk.mailtemplates-0.2.2/zettwerk/mailtemplates/content/template.py | template.py |
zettwerk.mobile
===============
Apply jquery.mobile based themes to plone.
Usage
=====
Add zettwerk.mobile to your buildout and install it via quickinstaller. It also installs zettwerk.mobiletheming for url based theme switching. Go to the plone control panel to mobile theming and set up a hostname, under which the theme should be applied.
Themes
======
There is support for jquery.mobile based themes. Just open the themeroller and create your theme. Then download and upload it in the zettwerk.mobile Themes Controlpanel.
See it in action: https://www.youtube.com/watch?v=Q2ID86XkiQQ (with phonegap) or here https://www.youtube.com/watch?v=s7n0IMjltzU (with themeroller support)
| zettwerk.mobile | /zettwerk.mobile-0.2.1.zip/zettwerk.mobile-0.2.1/README.txt | README.txt |
import zipfile
import os.path
from zope.publisher.browser import BrowserView
from zope.component import getUtility
from plone.registry.interfaces import IRegistry
from plone.resource.interfaces import IResourceDirectory
from Products.statusmessages.interfaces import IStatusMessage
from zettwerk.mobile import contentMessageFactory as _
RESOURCE_NAME = 'zettwerkmobile'
class ConfiguredTheme(BrowserView):
def __call__(self):
registry = getUtility(IRegistry)
return registry['zettwerk.mobile.interfaces.IThemesSettings' \
'.themename'] or 'default'
class ThemeUploadForm(BrowserView):
def __call__(self):
uploaded_theme_name = self.update_zip()
if uploaded_theme_name:
## set the uploaded as active theme
self._set_active_theme(uploaded_theme_name)
elif self.request.get('active_theme'):
self._set_active_theme(self.request.get('active_theme'))
return self.index()
@property
def active_theme(self):
registry = getUtility(IRegistry)
return registry['zettwerk.mobile.interfaces.IThemesSettings.themename']
@property
def available_themes(self):
persistentDirectory = getUtility(IResourceDirectory, name="persistent")
if RESOURCE_NAME not in persistentDirectory:
return []
return persistentDirectory[RESOURCE_NAME].listDirectory()
def _set_active_theme(self, name):
""" """
if type(name) is str:
name = name.decode('utf-8')
registry = getUtility(IRegistry)
registry['zettwerk.mobile.interfaces.IThemesSettings.themename'] = name
def _get_theme_name_of_zip(self, zip):
""" we are searching a file, ending of .css in the
first themes subfolder """
for filename in zip.namelist():
parts = os.path.split(filename)
if len(parts) == 2 and parts[0] == 'themes':
prefix = parts[1]
splitted = prefix.split('.')
if len(splitted) == 2 and splitted[1] == 'css':
return splitted[0]
def update_zip(self):
zip = self.request.get('zip', '')
if not zip:
return
zip = zipfile.ZipFile(self.request.form.get('zip'))
theme_name = self._get_theme_name_of_zip(zip)
if not theme_name:
IStatusMessage(self.request).add(_(u"Invalid Zipfile"),
type="error")
return
persistentDirectory = getUtility(IResourceDirectory, name="persistent")
if RESOURCE_NAME not in persistentDirectory:
persistentDirectory.makeDirectory(RESOURCE_NAME)
container = persistentDirectory[RESOURCE_NAME]
## force replace when a theme gets updated
if theme_name in container:
del container[theme_name]
container.makeDirectory(theme_name)
target = container[theme_name]
target.importZip(zip)
return theme_name | zettwerk.mobile | /zettwerk.mobile-0.2.1.zip/zettwerk.mobile-0.2.1/zettwerk/mobile/browser/themes.py | themes.py |
!function(a,b,c){"function"==typeof define&&define.amd?define(["jquery"],function(d){return c(d,a,b),d.mobile}):c(a.jQuery,a,b)}(this,document,function(a,b,c){!function(a){a.mobile={}}(a),function(a){a.extend(a.mobile,{version:"1.4.2",subPageUrlKey:"ui-page",hideUrlBar:!0,keepNative:":jqmData(role='none'), :jqmData(role='nojs')",activePageClass:"ui-page-active",activeBtnClass:"ui-btn-active",focusClass:"ui-focus",ajaxEnabled:!0,hashListeningEnabled:!0,linkBindingEnabled:!0,defaultPageTransition:"fade",maxTransitionWidth:!1,minScrollBack:0,defaultDialogTransition:"pop",pageLoadErrorMessage:"Error Loading Page",pageLoadErrorMessageTheme:"a",phonegapNavigationEnabled:!1,autoInitializePage:!0,pushStateEnabled:!0,ignoreContentEnabled:!1,buttonMarkup:{hoverDelay:200},dynamicBaseEnabled:!0,pageContainer:a(),allowCrossDomainPages:!1,dialogHashKey:"&ui-state=dialog"})}(a,this),function(a,b,c){var d={},e=a.find,f=/(?:\{[\s\S]*\}|\[[\s\S]*\])$/,g=/:jqmData\(([^)]*)\)/g;a.extend(a.mobile,{ns:"",getAttribute:function(b,c){var d;b=b.jquery?b[0]:b,b&&b.getAttribute&&(d=b.getAttribute("data-"+a.mobile.ns+c));try{d="true"===d?!0:"false"===d?!1:"null"===d?null:+d+""===d?+d:f.test(d)?JSON.parse(d):d}catch(e){}return d},nsNormalizeDict:d,nsNormalize:function(b){return d[b]||(d[b]=a.camelCase(a.mobile.ns+b))},closestPageData:function(a){return a.closest(":jqmData(role='page'), :jqmData(role='dialog')").data("mobile-page")}}),a.fn.jqmData=function(b,d){var e;return"undefined"!=typeof b&&(b&&(b=a.mobile.nsNormalize(b)),e=arguments.length<2||d===c?this.data(b):this.data(b,d)),e},a.jqmData=function(b,c,d){var e;return"undefined"!=typeof c&&(e=a.data(b,c?a.mobile.nsNormalize(c):c,d)),e},a.fn.jqmRemoveData=function(b){return this.removeData(a.mobile.nsNormalize(b))},a.jqmRemoveData=function(b,c){return a.removeData(b,a.mobile.nsNormalize(c))},a.find=function(b,c,d,f){return b.indexOf(":jqmData")>-1&&(b=b.replace(g,"[data-"+(a.mobile.ns||"")+"$1]")),e.call(this,b,c,d,f)},a.extend(a.find,e)}(a,this),function(a,b){function d(b,c){var d,f,g,h=b.nodeName.toLowerCase();return"area"===h?(d=b.parentNode,f=d.name,b.href&&f&&"map"===d.nodeName.toLowerCase()?(g=a("img[usemap=#"+f+"]")[0],!!g&&e(g)):!1):(/input|select|textarea|button|object/.test(h)?!b.disabled:"a"===h?b.href||c:c)&&e(b)}function e(b){return a.expr.filters.visible(b)&&!a(b).parents().addBack().filter(function(){return"hidden"===a.css(this,"visibility")}).length}var f=0,g=/^ui-id-\d+$/;a.ui=a.ui||{},a.extend(a.ui,{version:"c0ab71056b936627e8a7821f03c044aec6280a40",keyCode:{BACKSPACE:8,COMMA:188,DELETE:46,DOWN:40,END:35,ENTER:13,ESCAPE:27,HOME:36,LEFT:37,PAGE_DOWN:34,PAGE_UP:33,PERIOD:190,RIGHT:39,SPACE:32,TAB:9,UP:38}}),a.fn.extend({focus:function(b){return function(c,d){return"number"==typeof c?this.each(function(){var b=this;setTimeout(function(){a(b).focus(),d&&d.call(b)},c)}):b.apply(this,arguments)}}(a.fn.focus),scrollParent:function(){var b;return b=a.ui.ie&&/(static|relative)/.test(this.css("position"))||/absolute/.test(this.css("position"))?this.parents().filter(function(){return/(relative|absolute|fixed)/.test(a.css(this,"position"))&&/(auto|scroll)/.test(a.css(this,"overflow")+a.css(this,"overflow-y")+a.css(this,"overflow-x"))}).eq(0):this.parents().filter(function(){return/(auto|scroll)/.test(a.css(this,"overflow")+a.css(this,"overflow-y")+a.css(this,"overflow-x"))}).eq(0),/fixed/.test(this.css("position"))||!b.length?a(this[0].ownerDocument||c):b},uniqueId:function(){return this.each(function(){this.id||(this.id="ui-id-"+ ++f)})},removeUniqueId:function(){return this.each(function(){g.test(this.id)&&a(this).removeAttr("id")})}}),a.extend(a.expr[":"],{data:a.expr.createPseudo?a.expr.createPseudo(function(b){return function(c){return!!a.data(c,b)}}):function(b,c,d){return!!a.data(b,d[3])},focusable:function(b){return d(b,!isNaN(a.attr(b,"tabindex")))},tabbable:function(b){var c=a.attr(b,"tabindex"),e=isNaN(c);return(e||c>=0)&&d(b,!e)}}),a("<a>").outerWidth(1).jquery||a.each(["Width","Height"],function(c,d){function e(b,c,d,e){return a.each(f,function(){c-=parseFloat(a.css(b,"padding"+this))||0,d&&(c-=parseFloat(a.css(b,"border"+this+"Width"))||0),e&&(c-=parseFloat(a.css(b,"margin"+this))||0)}),c}var f="Width"===d?["Left","Right"]:["Top","Bottom"],g=d.toLowerCase(),h={innerWidth:a.fn.innerWidth,innerHeight:a.fn.innerHeight,outerWidth:a.fn.outerWidth,outerHeight:a.fn.outerHeight};a.fn["inner"+d]=function(c){return c===b?h["inner"+d].call(this):this.each(function(){a(this).css(g,e(this,c)+"px")})},a.fn["outer"+d]=function(b,c){return"number"!=typeof b?h["outer"+d].call(this,b):this.each(function(){a(this).css(g,e(this,b,!0,c)+"px")})}}),a.fn.addBack||(a.fn.addBack=function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}),a("<a>").data("a-b","a").removeData("a-b").data("a-b")&&(a.fn.removeData=function(b){return function(c){return arguments.length?b.call(this,a.camelCase(c)):b.call(this)}}(a.fn.removeData)),a.ui.ie=!!/msie [\w.]+/.exec(navigator.userAgent.toLowerCase()),a.support.selectstart="onselectstart"in c.createElement("div"),a.fn.extend({disableSelection:function(){return this.bind((a.support.selectstart?"selectstart":"mousedown")+".ui-disableSelection",function(a){a.preventDefault()})},enableSelection:function(){return this.unbind(".ui-disableSelection")},zIndex:function(d){if(d!==b)return this.css("zIndex",d);if(this.length)for(var e,f,g=a(this[0]);g.length&&g[0]!==c;){if(e=g.css("position"),("absolute"===e||"relative"===e||"fixed"===e)&&(f=parseInt(g.css("zIndex"),10),!isNaN(f)&&0!==f))return f;g=g.parent()}return 0}}),a.ui.plugin={add:function(b,c,d){var e,f=a.ui[b].prototype;for(e in d)f.plugins[e]=f.plugins[e]||[],f.plugins[e].push([c,d[e]])},call:function(a,b,c,d){var e,f=a.plugins[b];if(f&&(d||a.element[0].parentNode&&11!==a.element[0].parentNode.nodeType))for(e=0;e<f.length;e++)a.options[f[e][0]]&&f[e][1].apply(a.element,c)}}}(a),function(a,b){var d=function(b,c){var d=b.parent(),e=[],f=d.children(":jqmData(role='header')"),g=b.children(":jqmData(role='header')"),h=d.children(":jqmData(role='footer')"),i=b.children(":jqmData(role='footer')");return 0===g.length&&f.length>0&&(e=e.concat(f.toArray())),0===i.length&&h.length>0&&(e=e.concat(h.toArray())),a.each(e,function(b,d){c-=a(d).outerHeight()}),Math.max(0,c)};a.extend(a.mobile,{window:a(b),document:a(c),keyCode:a.ui.keyCode,behaviors:{},silentScroll:function(c){"number"!==a.type(c)&&(c=a.mobile.defaultHomeScroll),a.event.special.scrollstart.enabled=!1,setTimeout(function(){b.scrollTo(0,c),a.mobile.document.trigger("silentscroll",{x:0,y:c})},20),setTimeout(function(){a.event.special.scrollstart.enabled=!0},150)},getClosestBaseUrl:function(b){var c=a(b).closest(".ui-page").jqmData("url"),d=a.mobile.path.documentBase.hrefNoHash;return a.mobile.dynamicBaseEnabled&&c&&a.mobile.path.isPath(c)||(c=d),a.mobile.path.makeUrlAbsolute(c,d)},removeActiveLinkClass:function(b){!a.mobile.activeClickedLink||a.mobile.activeClickedLink.closest("."+a.mobile.activePageClass).length&&!b||a.mobile.activeClickedLink.removeClass(a.mobile.activeBtnClass),a.mobile.activeClickedLink=null},getInheritedTheme:function(a,b){for(var c,d,e=a[0],f="",g=/ui-(bar|body|overlay)-([a-z])\b/;e&&(c=e.className||"",!(c&&(d=g.exec(c))&&(f=d[2])));)e=e.parentNode;return f||b||"a"},enhanceable:function(a){return this.haveParents(a,"enhance")},hijackable:function(a){return this.haveParents(a,"ajax")},haveParents:function(b,c){if(!a.mobile.ignoreContentEnabled)return b;var d,e,f,g,h,i=b.length,j=a();for(g=0;i>g;g++){for(e=b.eq(g),f=!1,d=b[g];d;){if(h=d.getAttribute?d.getAttribute("data-"+a.mobile.ns+c):"","false"===h){f=!0;break}d=d.parentNode}f||(j=j.add(e))}return j},getScreenHeight:function(){return b.innerHeight||a.mobile.window.height()},resetActivePageHeight:function(b){var c=a("."+a.mobile.activePageClass),e=c.height(),f=c.outerHeight(!0);b=d(c,"number"==typeof b?b:a.mobile.getScreenHeight()),c.css("min-height",b-(f-e))},loading:function(){var b=this.loading._widget||a(a.mobile.loader.prototype.defaultHtml).loader(),c=b.loader.apply(b,arguments);return this.loading._widget=b,c}}),a.addDependents=function(b,c){var d=a(b),e=d.jqmData("dependents")||a();d.jqmData("dependents",a(e).add(c))},a.fn.extend({removeWithDependents:function(){a.removeWithDependents(this)},enhanceWithin:function(){var b,c={},d=a.mobile.page.prototype.keepNativeSelector(),e=this;a.mobile.nojs&&a.mobile.nojs(this),a.mobile.links&&a.mobile.links(this),a.mobile.degradeInputsWithin&&a.mobile.degradeInputsWithin(this),a.fn.buttonMarkup&&this.find(a.fn.buttonMarkup.initSelector).not(d).jqmEnhanceable().buttonMarkup(),a.fn.fieldcontain&&this.find(":jqmData(role='fieldcontain')").not(d).jqmEnhanceable().fieldcontain(),a.each(a.mobile.widgets,function(b,f){if(f.initSelector){var g=a.mobile.enhanceable(e.find(f.initSelector));g.length>0&&(g=g.not(d)),g.length>0&&(c[f.prototype.widgetName]=g)}});for(b in c)c[b][b]();return this},addDependents:function(b){a.addDependents(this,b)},getEncodedText:function(){return a("<a>").text(this.text()).html()},jqmEnhanceable:function(){return a.mobile.enhanceable(this)},jqmHijackable:function(){return a.mobile.hijackable(this)}}),a.removeWithDependents=function(b){var c=a(b);(c.jqmData("dependents")||a()).remove(),c.remove()},a.addDependents=function(b,c){var d=a(b),e=d.jqmData("dependents")||a();d.jqmData("dependents",a(e).add(c))},a.find.matches=function(b,c){return a.find(b,null,null,c)},a.find.matchesSelector=function(b,c){return a.find(c,null,null,[b]).length>0}}(a,this),function(a,b){var c=0,d=Array.prototype.slice,e=a.cleanData;a.cleanData=function(b){for(var c,d=0;null!=(c=b[d]);d++)try{a(c).triggerHandler("remove")}catch(f){}e(b)},a.widget=function(b,c,d){var e,f,g,h,i={},j=b.split(".")[0];return b=b.split(".")[1],e=j+"-"+b,d||(d=c,c=a.Widget),a.expr[":"][e.toLowerCase()]=function(b){return!!a.data(b,e)},a[j]=a[j]||{},f=a[j][b],g=a[j][b]=function(a,b){return this._createWidget?void(arguments.length&&this._createWidget(a,b)):new g(a,b)},a.extend(g,f,{version:d.version,_proto:a.extend({},d),_childConstructors:[]}),h=new c,h.options=a.widget.extend({},h.options),a.each(d,function(b,d){return a.isFunction(d)?void(i[b]=function(){var a=function(){return c.prototype[b].apply(this,arguments)},e=function(a){return c.prototype[b].apply(this,a)};return function(){var b,c=this._super,f=this._superApply;return this._super=a,this._superApply=e,b=d.apply(this,arguments),this._super=c,this._superApply=f,b}}()):void(i[b]=d)}),g.prototype=a.widget.extend(h,{widgetEventPrefix:f?h.widgetEventPrefix||b:b},i,{constructor:g,namespace:j,widgetName:b,widgetFullName:e}),f?(a.each(f._childConstructors,function(b,c){var d=c.prototype;a.widget(d.namespace+"."+d.widgetName,g,c._proto)}),delete f._childConstructors):c._childConstructors.push(g),a.widget.bridge(b,g),g},a.widget.extend=function(c){for(var e,f,g=d.call(arguments,1),h=0,i=g.length;i>h;h++)for(e in g[h])f=g[h][e],g[h].hasOwnProperty(e)&&f!==b&&(c[e]=a.isPlainObject(f)?a.isPlainObject(c[e])?a.widget.extend({},c[e],f):a.widget.extend({},f):f);return c},a.widget.bridge=function(c,e){var f=e.prototype.widgetFullName||c;a.fn[c]=function(g){var h="string"==typeof g,i=d.call(arguments,1),j=this;return g=!h&&i.length?a.widget.extend.apply(null,[g].concat(i)):g,this.each(h?function(){var d,e=a.data(this,f);return"instance"===g?(j=e,!1):e?a.isFunction(e[g])&&"_"!==g.charAt(0)?(d=e[g].apply(e,i),d!==e&&d!==b?(j=d&&d.jquery?j.pushStack(d.get()):d,!1):void 0):a.error("no such method '"+g+"' for "+c+" widget instance"):a.error("cannot call methods on "+c+" prior to initialization; attempted to call method '"+g+"'")}:function(){var b=a.data(this,f);b?b.option(g||{})._init():a.data(this,f,new e(g,this))}),j}},a.Widget=function(){},a.Widget._childConstructors=[],a.Widget.prototype={widgetName:"widget",widgetEventPrefix:"",defaultElement:"<div>",options:{disabled:!1,create:null},_createWidget:function(b,d){d=a(d||this.defaultElement||this)[0],this.element=a(d),this.uuid=c++,this.eventNamespace="."+this.widgetName+this.uuid,this.options=a.widget.extend({},this.options,this._getCreateOptions(),b),this.bindings=a(),this.hoverable=a(),this.focusable=a(),d!==this&&(a.data(d,this.widgetFullName,this),this._on(!0,this.element,{remove:function(a){a.target===d&&this.destroy()}}),this.document=a(d.style?d.ownerDocument:d.document||d),this.window=a(this.document[0].defaultView||this.document[0].parentWindow)),this._create(),this._trigger("create",null,this._getCreateEventData()),this._init()},_getCreateOptions:a.noop,_getCreateEventData:a.noop,_create:a.noop,_init:a.noop,destroy:function(){this._destroy(),this.element.unbind(this.eventNamespace).removeData(this.widgetFullName).removeData(a.camelCase(this.widgetFullName)),this.widget().unbind(this.eventNamespace).removeAttr("aria-disabled").removeClass(this.widgetFullName+"-disabled ui-state-disabled"),this.bindings.unbind(this.eventNamespace),this.hoverable.removeClass("ui-state-hover"),this.focusable.removeClass("ui-state-focus")},_destroy:a.noop,widget:function(){return this.element},option:function(c,d){var e,f,g,h=c;if(0===arguments.length)return a.widget.extend({},this.options);if("string"==typeof c)if(h={},e=c.split("."),c=e.shift(),e.length){for(f=h[c]=a.widget.extend({},this.options[c]),g=0;g<e.length-1;g++)f[e[g]]=f[e[g]]||{},f=f[e[g]];if(c=e.pop(),d===b)return f[c]===b?null:f[c];f[c]=d}else{if(d===b)return this.options[c]===b?null:this.options[c];h[c]=d}return this._setOptions(h),this},_setOptions:function(a){var b;for(b in a)this._setOption(b,a[b]);return this},_setOption:function(a,b){return this.options[a]=b,"disabled"===a&&(this.widget().toggleClass(this.widgetFullName+"-disabled",!!b),this.hoverable.removeClass("ui-state-hover"),this.focusable.removeClass("ui-state-focus")),this},enable:function(){return this._setOptions({disabled:!1})},disable:function(){return this._setOptions({disabled:!0})},_on:function(b,c,d){var e,f=this;"boolean"!=typeof b&&(d=c,c=b,b=!1),d?(c=e=a(c),this.bindings=this.bindings.add(c)):(d=c,c=this.element,e=this.widget()),a.each(d,function(d,g){function h(){return b||f.options.disabled!==!0&&!a(this).hasClass("ui-state-disabled")?("string"==typeof g?f[g]:g).apply(f,arguments):void 0}"string"!=typeof g&&(h.guid=g.guid=g.guid||h.guid||a.guid++);var i=d.match(/^(\w+)\s*(.*)$/),j=i[1]+f.eventNamespace,k=i[2];k?e.delegate(k,j,h):c.bind(j,h)})},_off:function(a,b){b=(b||"").split(" ").join(this.eventNamespace+" ")+this.eventNamespace,a.unbind(b).undelegate(b)},_delay:function(a,b){function c(){return("string"==typeof a?d[a]:a).apply(d,arguments)}var d=this;return setTimeout(c,b||0)},_hoverable:function(b){this.hoverable=this.hoverable.add(b),this._on(b,{mouseenter:function(b){a(b.currentTarget).addClass("ui-state-hover")},mouseleave:function(b){a(b.currentTarget).removeClass("ui-state-hover")}})},_focusable:function(b){this.focusable=this.focusable.add(b),this._on(b,{focusin:function(b){a(b.currentTarget).addClass("ui-state-focus")},focusout:function(b){a(b.currentTarget).removeClass("ui-state-focus")}})},_trigger:function(b,c,d){var e,f,g=this.options[b];if(d=d||{},c=a.Event(c),c.type=(b===this.widgetEventPrefix?b:this.widgetEventPrefix+b).toLowerCase(),c.target=this.element[0],f=c.originalEvent)for(e in f)e in c||(c[e]=f[e]);return this.element.trigger(c,d),!(a.isFunction(g)&&g.apply(this.element[0],[c].concat(d))===!1||c.isDefaultPrevented())}},a.each({show:"fadeIn",hide:"fadeOut"},function(b,c){a.Widget.prototype["_"+b]=function(d,e,f){"string"==typeof e&&(e={effect:e});var g,h=e?e===!0||"number"==typeof e?c:e.effect||c:b;e=e||{},"number"==typeof e&&(e={duration:e}),g=!a.isEmptyObject(e),e.complete=f,e.delay&&d.delay(e.delay),g&&a.effects&&a.effects.effect[h]?d[b](e):h!==b&&d[h]?d[h](e.duration,e.easing,f):d.queue(function(c){a(this)[b](),f&&f.call(d[0]),c()})}})}(a),function(a){var b=/[A-Z]/g,c=function(a){return"-"+a.toLowerCase()};a.extend(a.Widget.prototype,{_getCreateOptions:function(){var d,e,f=this.element[0],g={};if(!a.mobile.getAttribute(f,"defaults"))for(d in this.options)e=a.mobile.getAttribute(f,d.replace(b,c)),null!=e&&(g[d]=e);return g}}),a.mobile.widget=a.Widget}(a),function(a){var b="ui-loader",c=a("html");a.widget("mobile.loader",{options:{theme:"a",textVisible:!1,html:"",text:"loading"},defaultHtml:"<div class='"+b+"'><span class='ui-icon-loading'></span><h1></h1></div>",fakeFixLoader:function(){var b=a("."+a.mobile.activeBtnClass).first();this.element.css({top:a.support.scrollTop&&this.window.scrollTop()+this.window.height()/2||b.length&&b.offset().top||100})},checkLoaderPosition:function(){var b=this.element.offset(),c=this.window.scrollTop(),d=a.mobile.getScreenHeight();(b.top<c||b.top-c>d)&&(this.element.addClass("ui-loader-fakefix"),this.fakeFixLoader(),this.window.unbind("scroll",this.checkLoaderPosition).bind("scroll",a.proxy(this.fakeFixLoader,this)))},resetHtml:function(){this.element.html(a(this.defaultHtml).html())},show:function(d,e,f){var g,h,i;this.resetHtml(),"object"===a.type(d)?(i=a.extend({},this.options,d),d=i.theme):(i=this.options,d=d||i.theme),h=e||(i.text===!1?"":i.text),c.addClass("ui-loading"),g=i.textVisible,this.element.attr("class",b+" ui-corner-all ui-body-"+d+" ui-loader-"+(g||e||d.text?"verbose":"default")+(i.textonly||f?" ui-loader-textonly":"")),i.html?this.element.html(i.html):this.element.find("h1").text(h),this.element.appendTo(a.mobile.pageContainer),this.checkLoaderPosition(),this.window.bind("scroll",a.proxy(this.checkLoaderPosition,this))},hide:function(){c.removeClass("ui-loading"),this.options.text&&this.element.removeClass("ui-loader-fakefix"),a.mobile.window.unbind("scroll",this.fakeFixLoader),a.mobile.window.unbind("scroll",this.checkLoaderPosition)}})}(a,this),function(a,b,d){"$:nomunge";function e(a){return a=a||location.href,"#"+a.replace(/^[^#]*#?(.*)$/,"$1")}var f,g="hashchange",h=c,i=a.event.special,j=h.documentMode,k="on"+g in b&&(j===d||j>7);a.fn[g]=function(a){return a?this.bind(g,a):this.trigger(g)},a.fn[g].delay=50,i[g]=a.extend(i[g],{setup:function(){return k?!1:void a(f.start)},teardown:function(){return k?!1:void a(f.stop)}}),f=function(){function c(){var d=e(),h=n(j);d!==j?(m(j=d,h),a(b).trigger(g)):h!==j&&(location.href=location.href.replace(/#.*/,"")+h),f=setTimeout(c,a.fn[g].delay)}var f,i={},j=e(),l=function(a){return a},m=l,n=l;return i.start=function(){f||c()},i.stop=function(){f&&clearTimeout(f),f=d},b.attachEvent&&!b.addEventListener&&!k&&function(){var b,d;i.start=function(){b||(d=a.fn[g].src,d=d&&d+e(),b=a('<iframe tabindex="-1" title="empty"/>').hide().one("load",function(){d||m(e()),c()}).attr("src",d||"javascript:0").insertAfter("body")[0].contentWindow,h.onpropertychange=function(){try{"title"===event.propertyName&&(b.document.title=h.title)}catch(a){}})},i.stop=l,n=function(){return e(b.location.href)},m=function(c,d){var e=b.document,f=a.fn[g].domain;c!==d&&(e.title=h.title,e.open(),f&&e.write('<script>document.domain="'+f+'"</script>'),e.close(),b.location.hash=c)}}(),i}()}(a,this),function(a){b.matchMedia=b.matchMedia||function(a){var b,c=a.documentElement,d=c.firstElementChild||c.firstChild,e=a.createElement("body"),f=a.createElement("div");return f.id="mq-test-1",f.style.cssText="position:absolute;top:-100em",e.style.background="none",e.appendChild(f),function(a){return f.innerHTML='­<style media="'+a+'"> #mq-test-1 { width: 42px; }</style>',c.insertBefore(e,d),b=42===f.offsetWidth,c.removeChild(e),{matches:b,media:a}}}(c),a.mobile.media=function(a){return b.matchMedia(a).matches}}(a),function(a){var b={touch:"ontouchend"in c};a.mobile.support=a.mobile.support||{},a.extend(a.support,b),a.extend(a.mobile.support,b)}(a),function(a){a.extend(a.support,{orientation:"orientation"in b&&"onorientationchange"in b})}(a),function(a,d){function e(a){var b,c=a.charAt(0).toUpperCase()+a.substr(1),e=(a+" "+o.join(c+" ")+c).split(" ");for(b in e)if(n[e[b]]!==d)return!0}function f(){var c=b,d=!(!c.document.createElementNS||!c.document.createElementNS("http://www.w3.org/2000/svg","svg").createSVGRect||c.opera&&-1===navigator.userAgent.indexOf("Chrome")),e=function(b){b&&d||a("html").addClass("ui-nosvg")},f=new c.Image;f.onerror=function(){e(!1)},f.onload=function(){e(1===f.width&&1===f.height)},f.src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw=="}function g(){var e,f,g,h="transform-3d",i=a.mobile.media("(-"+o.join("-"+h+"),(-")+"-"+h+"),("+h+")");if(i)return!!i;e=c.createElement("div"),f={MozTransform:"-moz-transform",transform:"transform"},m.append(e);for(g in f)e.style[g]!==d&&(e.style[g]="translate3d( 100px, 1px, 1px )",i=b.getComputedStyle(e).getPropertyValue(f[g]));return!!i&&"none"!==i}function h(){var b,c,d=location.protocol+"//"+location.host+location.pathname+"ui-dir/",e=a("head base"),f=null,g="";return e.length?g=e.attr("href"):e=f=a("<base>",{href:d}).appendTo("head"),b=a("<a href='testurl' />").prependTo(m),c=b[0].href,e[0].href=g||location.pathname,f&&f.remove(),0===c.indexOf(d)}function i(){var a,d=c.createElement("x"),e=c.documentElement,f=b.getComputedStyle;return"pointerEvents"in d.style?(d.style.pointerEvents="auto",d.style.pointerEvents="x",e.appendChild(d),a=f&&"auto"===f(d,"").pointerEvents,e.removeChild(d),!!a):!1}function j(){var a=c.createElement("div");return"undefined"!=typeof a.getBoundingClientRect}function k(){var a=b,c=navigator.userAgent,d=navigator.platform,e=c.match(/AppleWebKit\/([0-9]+)/),f=!!e&&e[1],g=c.match(/Fennec\/([0-9]+)/),h=!!g&&g[1],i=c.match(/Opera Mobi\/([0-9]+)/),j=!!i&&i[1];return(d.indexOf("iPhone")>-1||d.indexOf("iPad")>-1||d.indexOf("iPod")>-1)&&f&&534>f||a.operamini&&"[object OperaMini]"==={}.toString.call(a.operamini)||i&&7458>j||c.indexOf("Android")>-1&&f&&533>f||h&&6>h||"palmGetResource"in b&&f&&534>f||c.indexOf("MeeGo")>-1&&c.indexOf("NokiaBrowser/8.5.0")>-1?!1:!0}var l,m=a("<body>").prependTo("html"),n=m[0].style,o=["Webkit","Moz","O"],p="palmGetResource"in b,q=b.operamini&&"[object OperaMini]"==={}.toString.call(b.operamini),r=b.blackberry&&!e("-webkit-transform");a.extend(a.mobile,{browser:{}}),a.mobile.browser.oldIE=function(){var a=3,b=c.createElement("div"),d=b.all||[];do b.innerHTML="<!--[if gt IE "+ ++a+"]><br><![endif]-->";while(d[0]);return a>4?a:!a}(),a.extend(a.support,{pushState:"pushState"in history&&"replaceState"in history&&!(b.navigator.userAgent.indexOf("Firefox")>=0&&b.top!==b)&&-1===b.navigator.userAgent.search(/CriOS/),mediaquery:a.mobile.media("only all"),cssPseudoElement:!!e("content"),touchOverflow:!!e("overflowScrolling"),cssTransform3d:g(),boxShadow:!!e("boxShadow")&&!r,fixedPosition:k(),scrollTop:("pageXOffset"in b||"scrollTop"in c.documentElement||"scrollTop"in m[0])&&!p&&!q,dynamicBaseTag:h(),cssPointerEvents:i(),boundingRect:j(),inlineSVG:f}),m.remove(),l=function(){var a=b.navigator.userAgent;return a.indexOf("Nokia")>-1&&(a.indexOf("Symbian/3")>-1||a.indexOf("Series60/5")>-1)&&a.indexOf("AppleWebKit")>-1&&a.match(/(BrowserNG|NokiaBrowser)\/7\.[0-3]/)}(),a.mobile.gradeA=function(){return(a.support.mediaquery&&a.support.cssPseudoElement||a.mobile.browser.oldIE&&a.mobile.browser.oldIE>=8)&&(a.support.boundingRect||null!==a.fn.jquery.match(/1\.[0-7+]\.[0-9+]?/))},a.mobile.ajaxBlacklist=b.blackberry&&!b.WebKitPoint||q||l,l&&a(function(){a("head link[rel='stylesheet']").attr("rel","alternate stylesheet").attr("rel","stylesheet")}),a.support.boxShadow||a("html").addClass("ui-noboxshadow")}(a),function(a,b){var c,d=a.mobile.window,e=function(){};a.event.special.beforenavigate={setup:function(){d.on("navigate",e)},teardown:function(){d.off("navigate",e)}},a.event.special.navigate=c={bound:!1,pushStateEnabled:!0,originalEventName:b,isPushStateEnabled:function(){return a.support.pushState&&a.mobile.pushStateEnabled===!0&&this.isHashChangeEnabled()},isHashChangeEnabled:function(){return a.mobile.hashListeningEnabled===!0},popstate:function(b){var c=new a.Event("navigate"),e=new a.Event("beforenavigate"),f=b.originalEvent.state||{};e.originalEvent=b,d.trigger(e),e.isDefaultPrevented()||(b.historyState&&a.extend(f,b.historyState),c.originalEvent=b,setTimeout(function(){d.trigger(c,{state:f})},0))},hashchange:function(b){var c=new a.Event("navigate"),e=new a.Event("beforenavigate");e.originalEvent=b,d.trigger(e),e.isDefaultPrevented()||(c.originalEvent=b,d.trigger(c,{state:b.hashchangeState||{}}))},setup:function(){c.bound||(c.bound=!0,c.isPushStateEnabled()?(c.originalEventName="popstate",d.bind("popstate.navigate",c.popstate)):c.isHashChangeEnabled()&&(c.originalEventName="hashchange",d.bind("hashchange.navigate",c.hashchange)))}}}(a),function(a,c){var d,e,f="&ui-state=dialog";a.mobile.path=d={uiStateKey:"&ui-state",urlParseRE:/^\s*(((([^:\/#\?]+:)?(?:(\/\/)((?:(([^:@\/#\?]+)(?:\:([^:@\/#\?]+))?)@)?(([^:\/#\?\]\[]+|\[[^\/\]@#?]+\])(?:\:([0-9]+))?))?)?)?((\/?(?:[^\/\?#]+\/+)*)([^\?#]*)))?(\?[^#]+)?)(#.*)?/,getLocation:function(a){var b=a?this.parseUrl(a):location,c=this.parseUrl(a||location.href).hash;return c="#"===c?"":c,b.protocol+"//"+b.host+b.pathname+b.search+c},getDocumentUrl:function(b){return b?a.extend({},d.documentUrl):d.documentUrl.href},parseLocation:function(){return this.parseUrl(this.getLocation())},parseUrl:function(b){if("object"===a.type(b))return b;var c=d.urlParseRE.exec(b||"")||[];return{href:c[0]||"",hrefNoHash:c[1]||"",hrefNoSearch:c[2]||"",domain:c[3]||"",protocol:c[4]||"",doubleSlash:c[5]||"",authority:c[6]||"",username:c[8]||"",password:c[9]||"",host:c[10]||"",hostname:c[11]||"",port:c[12]||"",pathname:c[13]||"",directory:c[14]||"",filename:c[15]||"",search:c[16]||"",hash:c[17]||""}},makePathAbsolute:function(a,b){var c,d,e,f;if(a&&"/"===a.charAt(0))return a;for(a=a||"",b=b?b.replace(/^\/|(\/[^\/]*|[^\/]+)$/g,""):"",c=b?b.split("/"):[],d=a.split("/"),e=0;e<d.length;e++)switch(f=d[e]){case".":break;case"..":c.length&&c.pop();break;default:c.push(f)}return"/"+c.join("/")},isSameDomain:function(a,b){return d.parseUrl(a).domain===d.parseUrl(b).domain},isRelativeUrl:function(a){return""===d.parseUrl(a).protocol},isAbsoluteUrl:function(a){return""!==d.parseUrl(a).protocol},makeUrlAbsolute:function(a,b){if(!d.isRelativeUrl(a))return a;b===c&&(b=this.documentBase);var e=d.parseUrl(a),f=d.parseUrl(b),g=e.protocol||f.protocol,h=e.protocol?e.doubleSlash:e.doubleSlash||f.doubleSlash,i=e.authority||f.authority,j=""!==e.pathname,k=d.makePathAbsolute(e.pathname||f.filename,f.pathname),l=e.search||!j&&f.search||"",m=e.hash;return g+h+i+k+l+m},addSearchParams:function(b,c){var e=d.parseUrl(b),f="object"==typeof c?a.param(c):c,g=e.search||"?";return e.hrefNoSearch+g+("?"!==g.charAt(g.length-1)?"&":"")+f+(e.hash||"")},convertUrlToDataUrl:function(a){var c=d.parseUrl(a);return d.isEmbeddedPage(c)?c.hash.split(f)[0].replace(/^#/,"").replace(/\?.*$/,""):d.isSameDomain(c,this.documentBase)?c.hrefNoHash.replace(this.documentBase.domain,"").split(f)[0]:b.decodeURIComponent(a)},get:function(a){return a===c&&(a=d.parseLocation().hash),d.stripHash(a).replace(/[^\/]*\.[^\/*]+$/,"")},set:function(a){location.hash=a},isPath:function(a){return/\//.test(a)},clean:function(a){return a.replace(this.documentBase.domain,"")},stripHash:function(a){return a.replace(/^#/,"")},stripQueryParams:function(a){return a.replace(/\?.*$/,"")},cleanHash:function(a){return d.stripHash(a.replace(/\?.*$/,"").replace(f,""))},isHashValid:function(a){return/^#[^#]+$/.test(a)},isExternal:function(a){var b=d.parseUrl(a);return b.protocol&&b.domain!==this.documentUrl.domain?!0:!1},hasProtocol:function(a){return/^(:?\w+:)/.test(a)},isEmbeddedPage:function(a){var b=d.parseUrl(a);return""!==b.protocol?!this.isPath(b.hash)&&b.hash&&(b.hrefNoHash===this.documentUrl.hrefNoHash||this.documentBaseDiffers&&b.hrefNoHash===this.documentBase.hrefNoHash):/^#/.test(b.href)},squash:function(a,b){var c,e,f,g,h=this.isPath(a),i=this.parseUrl(a),j=i.hash,k="";return b=b||(d.isPath(a)?d.getLocation():d.getDocumentUrl()),e=h?d.stripHash(a):a,e=d.isPath(i.hash)?d.stripHash(i.hash):e,g=e.indexOf(this.uiStateKey),g>-1&&(k=e.slice(g),e=e.slice(0,g)),c=d.makeUrlAbsolute(e,b),f=this.parseUrl(c).search,h?((d.isPath(j)||0===j.replace("#","").indexOf(this.uiStateKey))&&(j=""),k&&-1===j.indexOf(this.uiStateKey)&&(j+=k),-1===j.indexOf("#")&&""!==j&&(j="#"+j),c=d.parseUrl(c),c=c.protocol+"//"+c.host+c.pathname+f+j):c+=c.indexOf("#")>-1?k:"#"+k,c},isPreservableHash:function(a){return 0===a.replace("#","").indexOf(this.uiStateKey)},hashToSelector:function(a){var b="#"===a.substring(0,1);return b&&(a=a.substring(1)),(b?"#":"")+a.replace(/([!"#$%&'()*+,./:;<=>?@[\]^`{|}~])/g,"\\$1")},getFilePath:function(b){var c="&"+a.mobile.subPageUrlKey;return b&&b.split(c)[0].split(f)[0]},isFirstPageUrl:function(b){var e=d.parseUrl(d.makeUrlAbsolute(b,this.documentBase)),f=e.hrefNoHash===this.documentUrl.hrefNoHash||this.documentBaseDiffers&&e.hrefNoHash===this.documentBase.hrefNoHash,g=a.mobile.firstPage,h=g&&g[0]?g[0].id:c;return f&&(!e.hash||"#"===e.hash||h&&e.hash.replace(/^#/,"")===h)},isPermittedCrossDomainRequest:function(b,c){return a.mobile.allowCrossDomainPages&&("file:"===b.protocol||"content:"===b.protocol)&&-1!==c.search(/^https?:/)}},d.documentUrl=d.parseLocation(),e=a("head").find("base"),d.documentBase=e.length?d.parseUrl(d.makeUrlAbsolute(e.attr("href"),d.documentUrl.href)):d.documentUrl,d.documentBaseDiffers=d.documentUrl.hrefNoHash!==d.documentBase.hrefNoHash,d.getDocumentBase=function(b){return b?a.extend({},d.documentBase):d.documentBase.href},a.extend(a.mobile,{getDocumentUrl:d.getDocumentUrl,getDocumentBase:d.getDocumentBase})}(a),function(a,b){a.mobile.History=function(a,b){this.stack=a||[],this.activeIndex=b||0},a.extend(a.mobile.History.prototype,{getActive:function(){return this.stack[this.activeIndex]},getLast:function(){return this.stack[this.previousIndex]},getNext:function(){return this.stack[this.activeIndex+1]},getPrev:function(){return this.stack[this.activeIndex-1]},add:function(a,b){b=b||{},this.getNext()&&this.clearForward(),b.hash&&-1===b.hash.indexOf("#")&&(b.hash="#"+b.hash),b.url=a,this.stack.push(b),this.activeIndex=this.stack.length-1},clearForward:function(){this.stack=this.stack.slice(0,this.activeIndex+1)},find:function(a,b,c){b=b||this.stack;var d,e,f,g=b.length;for(e=0;g>e;e++)if(d=b[e],(decodeURIComponent(a)===decodeURIComponent(d.url)||decodeURIComponent(a)===decodeURIComponent(d.hash))&&(f=e,c))return f;return f},closest:function(a){var c,d=this.activeIndex;return c=this.find(a,this.stack.slice(0,d)),c===b&&(c=this.find(a,this.stack.slice(d),!0),c=c===b?c:c+d),c},direct:function(c){var d=this.closest(c.url),e=this.activeIndex;d!==b&&(this.activeIndex=d,this.previousIndex=e),e>d?(c.present||c.back||a.noop)(this.getActive(),"back"):d>e?(c.present||c.forward||a.noop)(this.getActive(),"forward"):d===b&&c.missing&&c.missing(this.getActive())}})}(a),function(a){var d=a.mobile.path,e=location.href;a.mobile.Navigator=function(b){this.history=b,this.ignoreInitialHashChange=!0,a.mobile.window.bind({"popstate.history":a.proxy(this.popstate,this),"hashchange.history":a.proxy(this.hashchange,this)})},a.extend(a.mobile.Navigator.prototype,{squash:function(e,f){var g,h,i=d.isPath(e)?d.stripHash(e):e;return h=d.squash(e),g=a.extend({hash:i,url:h},f),b.history.replaceState(g,g.title||c.title,h),g},hash:function(a,b){var c,e,f,g;return c=d.parseUrl(a),e=d.parseLocation(),e.pathname+e.search===c.pathname+c.search?f=c.hash?c.hash:c.pathname+c.search:d.isPath(a)?(g=d.parseUrl(b),f=g.pathname+g.search+(d.isPreservableHash(g.hash)?g.hash.replace("#",""):"")):f=a,f},go:function(e,f,g){var h,i,j,k,l=a.event.special.navigate.isPushStateEnabled();i=d.squash(e),j=this.hash(e,i),g&&j!==d.stripHash(d.parseLocation().hash)&&(this.preventNextHashChange=g),this.preventHashAssignPopState=!0,b.location.hash=j,this.preventHashAssignPopState=!1,h=a.extend({url:i,hash:j,title:c.title},f),l&&(k=new a.Event("popstate"),k.originalEvent={type:"popstate",state:null},this.squash(e,h),g||(this.ignorePopState=!0,a.mobile.window.trigger(k))),this.history.add(h.url,h)},popstate:function(b){var c,f;
if(a.event.special.navigate.isPushStateEnabled())return this.preventHashAssignPopState?(this.preventHashAssignPopState=!1,void b.stopImmediatePropagation()):this.ignorePopState?void(this.ignorePopState=!1):!b.originalEvent.state&&1===this.history.stack.length&&this.ignoreInitialHashChange&&(this.ignoreInitialHashChange=!1,location.href===e)?void b.preventDefault():(c=d.parseLocation().hash,!b.originalEvent.state&&c?(f=this.squash(c),this.history.add(f.url,f),void(b.historyState=f)):void this.history.direct({url:(b.originalEvent.state||{}).url||c,present:function(c,d){b.historyState=a.extend({},c),b.historyState.direction=d}}))},hashchange:function(b){var e,f;if(a.event.special.navigate.isHashChangeEnabled()&&!a.event.special.navigate.isPushStateEnabled()){if(this.preventNextHashChange)return this.preventNextHashChange=!1,void b.stopImmediatePropagation();e=this.history,f=d.parseLocation().hash,this.history.direct({url:f,present:function(c,d){b.hashchangeState=a.extend({},c),b.hashchangeState.direction=d},missing:function(){e.add(f,{hash:f,title:c.title})}})}}})}(a),function(a){a.mobile.navigate=function(b,c,d){a.mobile.navigate.navigator.go(b,c,d)},a.mobile.navigate.history=new a.mobile.History,a.mobile.navigate.navigator=new a.mobile.Navigator(a.mobile.navigate.history);var b=a.mobile.path.parseLocation();a.mobile.navigate.history.add(b.href,{hash:b.hash})}(a),function(a,b){var d={animation:{},transition:{}},e=c.createElement("a"),f=["","webkit-","moz-","o-"];a.each(["animation","transition"],function(c,g){var h=0===c?g+"-name":g;a.each(f,function(c,f){return e.style[a.camelCase(f+h)]!==b?(d[g].prefix=f,!1):void 0}),d[g].duration=a.camelCase(d[g].prefix+g+"-duration"),d[g].event=a.camelCase(d[g].prefix+g+"-end"),""===d[g].prefix&&(d[g].event=d[g].event.toLowerCase())}),a.support.cssTransitions=d.transition.prefix!==b,a.support.cssAnimations=d.animation.prefix!==b,a(e).remove(),a.fn.animationComplete=function(e,f,g){var h,i,j=this,k=f&&"animation"!==f?"transition":"animation";return a.support.cssTransitions&&"transition"===k||a.support.cssAnimations&&"animation"===k?(g===b&&(a(this).context!==c&&(i=3e3*parseFloat(a(this).css(d[k].duration))),(0===i||i===b||isNaN(i))&&(i=a.fn.animationComplete.defaultDuration)),h=setTimeout(function(){a(j).off(d[k].event),e.apply(j)},i),a(this).one(d[k].event,function(){clearTimeout(h),e.call(this,arguments)})):(setTimeout(a.proxy(e,this),0),a(this))},a.fn.animationComplete.defaultDuration=1e3}(a),function(a,b,c,d){function e(a){for(;a&&"undefined"!=typeof a.originalEvent;)a=a.originalEvent;return a}function f(b,c){var f,g,h,i,j,k,l,m,n,o=b.type;if(b=a.Event(b),b.type=c,f=b.originalEvent,g=a.event.props,o.search(/^(mouse|click)/)>-1&&(g=E),f)for(l=g.length,i;l;)i=g[--l],b[i]=f[i];if(o.search(/mouse(down|up)|click/)>-1&&!b.which&&(b.which=1),-1!==o.search(/^touch/)&&(h=e(f),o=h.touches,j=h.changedTouches,k=o&&o.length?o[0]:j&&j.length?j[0]:d))for(m=0,n=C.length;n>m;m++)i=C[m],b[i]=k[i];return b}function g(b){for(var c,d,e={};b;){c=a.data(b,z);for(d in c)c[d]&&(e[d]=e.hasVirtualBinding=!0);b=b.parentNode}return e}function h(b,c){for(var d;b;){if(d=a.data(b,z),d&&(!c||d[c]))return b;b=b.parentNode}return null}function i(){M=!1}function j(){M=!0}function k(){Q=0,K.length=0,L=!1,j()}function l(){i()}function m(){n(),G=setTimeout(function(){G=0,k()},a.vmouse.resetTimerDuration)}function n(){G&&(clearTimeout(G),G=0)}function o(b,c,d){var e;return(d&&d[b]||!d&&h(c.target,b))&&(e=f(c,b),a(c.target).trigger(e)),e}function p(b){var c,d=a.data(b.target,A);L||Q&&Q===d||(c=o("v"+b.type,b),c&&(c.isDefaultPrevented()&&b.preventDefault(),c.isPropagationStopped()&&b.stopPropagation(),c.isImmediatePropagationStopped()&&b.stopImmediatePropagation()))}function q(b){var c,d,f,h=e(b).touches;h&&1===h.length&&(c=b.target,d=g(c),d.hasVirtualBinding&&(Q=P++,a.data(c,A,Q),n(),l(),J=!1,f=e(b).touches[0],H=f.pageX,I=f.pageY,o("vmouseover",b,d),o("vmousedown",b,d)))}function r(a){M||(J||o("vmousecancel",a,g(a.target)),J=!0,m())}function s(b){if(!M){var c=e(b).touches[0],d=J,f=a.vmouse.moveDistanceThreshold,h=g(b.target);J=J||Math.abs(c.pageX-H)>f||Math.abs(c.pageY-I)>f,J&&!d&&o("vmousecancel",b,h),o("vmousemove",b,h),m()}}function t(a){if(!M){j();var b,c,d=g(a.target);o("vmouseup",a,d),J||(b=o("vclick",a,d),b&&b.isDefaultPrevented()&&(c=e(a).changedTouches[0],K.push({touchID:Q,x:c.clientX,y:c.clientY}),L=!0)),o("vmouseout",a,d),J=!1,m()}}function u(b){var c,d=a.data(b,z);if(d)for(c in d)if(d[c])return!0;return!1}function v(){}function w(b){var c=b.substr(1);return{setup:function(){u(this)||a.data(this,z,{});var d=a.data(this,z);d[b]=!0,F[b]=(F[b]||0)+1,1===F[b]&&O.bind(c,p),a(this).bind(c,v),N&&(F.touchstart=(F.touchstart||0)+1,1===F.touchstart&&O.bind("touchstart",q).bind("touchend",t).bind("touchmove",s).bind("scroll",r))},teardown:function(){--F[b],F[b]||O.unbind(c,p),N&&(--F.touchstart,F.touchstart||O.unbind("touchstart",q).unbind("touchmove",s).unbind("touchend",t).unbind("scroll",r));var d=a(this),e=a.data(this,z);e&&(e[b]=!1),d.unbind(c,v),u(this)||d.removeData(z)}}}var x,y,z="virtualMouseBindings",A="virtualTouchID",B="vmouseover vmousedown vmousemove vmouseup vclick vmouseout vmousecancel".split(" "),C="clientX clientY pageX pageY screenX screenY".split(" "),D=a.event.mouseHooks?a.event.mouseHooks.props:[],E=a.event.props.concat(D),F={},G=0,H=0,I=0,J=!1,K=[],L=!1,M=!1,N="addEventListener"in c,O=a(c),P=1,Q=0;for(a.vmouse={moveDistanceThreshold:10,clickDistanceThreshold:10,resetTimerDuration:1500},y=0;y<B.length;y++)a.event.special[B[y]]=w(B[y]);N&&c.addEventListener("click",function(b){var c,d,e,f,g,h,i=K.length,j=b.target;if(i)for(c=b.clientX,d=b.clientY,x=a.vmouse.clickDistanceThreshold,e=j;e;){for(f=0;i>f;f++)if(g=K[f],h=0,e===j&&Math.abs(g.x-c)<x&&Math.abs(g.y-d)<x||a.data(e,A)===g.touchID)return b.preventDefault(),void b.stopPropagation();e=e.parentNode}},!0)}(a,b,c),function(a,b,d){function e(b,c,e,f){var g=e.type;e.type=c,f?a.event.trigger(e,d,b):a.event.dispatch.call(b,e),e.type=g}var f=a(c),g=a.mobile.support.touch,h="touchmove scroll",i=g?"touchstart":"mousedown",j=g?"touchend":"mouseup",k=g?"touchmove":"mousemove";a.each("touchstart touchmove touchend tap taphold swipe swipeleft swiperight scrollstart scrollstop".split(" "),function(b,c){a.fn[c]=function(a){return a?this.bind(c,a):this.trigger(c)},a.attrFn&&(a.attrFn[c]=!0)}),a.event.special.scrollstart={enabled:!0,setup:function(){function b(a,b){c=b,e(f,c?"scrollstart":"scrollstop",a)}var c,d,f=this,g=a(f);g.bind(h,function(e){a.event.special.scrollstart.enabled&&(c||b(e,!0),clearTimeout(d),d=setTimeout(function(){b(e,!1)},50))})},teardown:function(){a(this).unbind(h)}},a.event.special.tap={tapholdThreshold:750,emitTapOnTaphold:!0,setup:function(){var b=this,c=a(b),d=!1;c.bind("vmousedown",function(g){function h(){clearTimeout(k)}function i(){h(),c.unbind("vclick",j).unbind("vmouseup",h),f.unbind("vmousecancel",i)}function j(a){i(),d||l!==a.target?d&&a.stopPropagation():e(b,"tap",a)}if(d=!1,g.which&&1!==g.which)return!1;var k,l=g.target;c.bind("vmouseup",h).bind("vclick",j),f.bind("vmousecancel",i),k=setTimeout(function(){a.event.special.tap.emitTapOnTaphold||(d=!0),e(b,"taphold",a.Event("taphold",{target:l}))},a.event.special.tap.tapholdThreshold)})},teardown:function(){a(this).unbind("vmousedown").unbind("vclick").unbind("vmouseup"),f.unbind("vmousecancel")}},a.event.special.swipe={scrollSupressionThreshold:30,durationThreshold:1e3,horizontalDistanceThreshold:30,verticalDistanceThreshold:30,getLocation:function(a){var c=b.pageXOffset,d=b.pageYOffset,e=a.clientX,f=a.clientY;return 0===a.pageY&&Math.floor(f)>Math.floor(a.pageY)||0===a.pageX&&Math.floor(e)>Math.floor(a.pageX)?(e-=c,f-=d):(f<a.pageY-d||e<a.pageX-c)&&(e=a.pageX-c,f=a.pageY-d),{x:e,y:f}},start:function(b){var c=b.originalEvent.touches?b.originalEvent.touches[0]:b,d=a.event.special.swipe.getLocation(c);return{time:(new Date).getTime(),coords:[d.x,d.y],origin:a(b.target)}},stop:function(b){var c=b.originalEvent.touches?b.originalEvent.touches[0]:b,d=a.event.special.swipe.getLocation(c);return{time:(new Date).getTime(),coords:[d.x,d.y]}},handleSwipe:function(b,c,d,f){if(c.time-b.time<a.event.special.swipe.durationThreshold&&Math.abs(b.coords[0]-c.coords[0])>a.event.special.swipe.horizontalDistanceThreshold&&Math.abs(b.coords[1]-c.coords[1])<a.event.special.swipe.verticalDistanceThreshold){var g=b.coords[0]>c.coords[0]?"swipeleft":"swiperight";return e(d,"swipe",a.Event("swipe",{target:f,swipestart:b,swipestop:c}),!0),e(d,g,a.Event(g,{target:f,swipestart:b,swipestop:c}),!0),!0}return!1},eventInProgress:!1,setup:function(){var b,c=this,d=a(c),e={};b=a.data(this,"mobile-events"),b||(b={length:0},a.data(this,"mobile-events",b)),b.length++,b.swipe=e,e.start=function(b){if(!a.event.special.swipe.eventInProgress){a.event.special.swipe.eventInProgress=!0;var d,g=a.event.special.swipe.start(b),h=b.target,i=!1;e.move=function(b){g&&(d=a.event.special.swipe.stop(b),i||(i=a.event.special.swipe.handleSwipe(g,d,c,h),i&&(a.event.special.swipe.eventInProgress=!1)),Math.abs(g.coords[0]-d.coords[0])>a.event.special.swipe.scrollSupressionThreshold&&b.preventDefault())},e.stop=function(){i=!0,a.event.special.swipe.eventInProgress=!1,f.off(k,e.move),e.move=null},f.on(k,e.move).one(j,e.stop)}},d.on(i,e.start)},teardown:function(){var b,c;b=a.data(this,"mobile-events"),b&&(c=b.swipe,delete b.swipe,b.length--,0===b.length&&a.removeData(this,"mobile-events")),c&&(c.start&&a(this).off(i,c.start),c.move&&f.off(k,c.move),c.stop&&f.off(j,c.stop))}},a.each({scrollstop:"scrollstart",taphold:"tap",swipeleft:"swipe",swiperight:"swipe"},function(b,c){a.event.special[b]={setup:function(){a(this).bind(c,a.noop)},teardown:function(){a(this).unbind(c)}}})}(a,this),function(a){a.event.special.throttledresize={setup:function(){a(this).bind("resize",f)},teardown:function(){a(this).unbind("resize",f)}};var b,c,d,e=250,f=function(){c=(new Date).getTime(),d=c-g,d>=e?(g=c,a(this).trigger("throttledresize")):(b&&clearTimeout(b),b=setTimeout(f,e-d))},g=0}(a),function(a,b){function d(){var a=e();a!==f&&(f=a,l.trigger(m))}var e,f,g,h,i,j,k,l=a(b),m="orientationchange",n={0:!0,180:!0};a.support.orientation&&(i=b.innerWidth||l.width(),j=b.innerHeight||l.height(),k=50,g=i>j&&i-j>k,h=n[b.orientation],(g&&h||!g&&!h)&&(n={"-90":!0,90:!0})),a.event.special.orientationchange=a.extend({},a.event.special.orientationchange,{setup:function(){return a.support.orientation&&!a.event.special.orientationchange.disabled?!1:(f=e(),void l.bind("throttledresize",d))},teardown:function(){return a.support.orientation&&!a.event.special.orientationchange.disabled?!1:void l.unbind("throttledresize",d)},add:function(a){var b=a.handler;a.handler=function(a){return a.orientation=e(),b.apply(this,arguments)}}}),a.event.special.orientationchange.orientation=e=function(){var d=!0,e=c.documentElement;return d=a.support.orientation?n[b.orientation]:e&&e.clientWidth/e.clientHeight<1.1,d?"portrait":"landscape"},a.fn[m]=function(a){return a?this.bind(m,a):this.trigger(m)},a.attrFn&&(a.attrFn[m]=!0)}(a,this),function(a){var b=a("head").children("base"),c={element:b.length?b:a("<base>",{href:a.mobile.path.documentBase.hrefNoHash}).prependTo(a("head")),linkSelector:"[src], link[href], a[rel='external'], :jqmData(ajax='false'), a[target]",set:function(b){a.mobile.dynamicBaseEnabled&&a.support.dynamicBaseTag&&c.element.attr("href",a.mobile.path.makeUrlAbsolute(b,a.mobile.path.documentBase))},rewrite:function(b,d){var e=a.mobile.path.get(b);d.find(c.linkSelector).each(function(b,c){var d=a(c).is("[href]")?"href":a(c).is("[src]")?"src":"action",f=a(c).attr(d);f=f.replace(location.protocol+"//"+location.host+location.pathname,""),/^(\w+:|#|\/)/.test(f)||a(c).attr(d,e+f)})},reset:function(){c.element.attr("href",a.mobile.path.documentBase.hrefNoSearch)}};a.mobile.base=c}(a),function(a,b){a.mobile.widgets={};var c=a.widget,d=a.mobile.keepNative;a.widget=function(c){return function(){var d=c.apply(this,arguments),e=d.prototype.widgetName;return d.initSelector=d.prototype.initSelector!==b?d.prototype.initSelector:":jqmData(role='"+e+"')",a.mobile.widgets[e]=d,d}}(a.widget),a.extend(a.widget,c),a.mobile.document.on("create",function(b){a(b.target).enhanceWithin()}),a.widget("mobile.page",{options:{theme:"a",domCache:!1,keepNativeDefault:a.mobile.keepNative,contentTheme:null,enhanced:!1},_createWidget:function(){a.Widget.prototype._createWidget.apply(this,arguments),this._trigger("init")},_create:function(){return this._trigger("beforecreate")===!1?!1:(this.options.enhanced||this._enhance(),this._on(this.element,{pagebeforehide:"removeContainerBackground",pagebeforeshow:"_handlePageBeforeShow"}),this.element.enhanceWithin(),void("dialog"===a.mobile.getAttribute(this.element[0],"role")&&a.mobile.dialog&&this.element.dialog()))},_enhance:function(){var c="data-"+a.mobile.ns,d=this;this.options.role&&this.element.attr("data-"+a.mobile.ns+"role",this.options.role),this.element.attr("tabindex","0").addClass("ui-page ui-page-theme-"+this.options.theme),this.element.find("["+c+"role='content']").each(function(){var e=a(this),f=this.getAttribute(c+"theme")||b;d.options.contentTheme=f||d.options.contentTheme||d.options.dialog&&d.options.theme||"dialog"===d.element.jqmData("role")&&d.options.theme,e.addClass("ui-content"),d.options.contentTheme&&e.addClass("ui-body-"+d.options.contentTheme),e.attr("role","main").addClass("ui-content")})},bindRemove:function(b){var c=this.element;!c.data("mobile-page").options.domCache&&c.is(":jqmData(external-page='true')")&&c.bind("pagehide.remove",b||function(b,c){if(!c.samePage){var d=a(this),e=new a.Event("pageremove");d.trigger(e),e.isDefaultPrevented()||d.removeWithDependents()}})},_setOptions:function(c){c.theme!==b&&this.element.removeClass("ui-page-theme-"+this.options.theme).addClass("ui-page-theme-"+c.theme),c.contentTheme!==b&&this.element.find("[data-"+a.mobile.ns+"='content']").removeClass("ui-body-"+this.options.contentTheme).addClass("ui-body-"+c.contentTheme)},_handlePageBeforeShow:function(){this.setContainerBackground()},removeContainerBackground:function(){this.element.closest(":mobile-pagecontainer").pagecontainer({theme:"none"})},setContainerBackground:function(a){this.element.parent().pagecontainer({theme:a||this.options.theme})},keepNativeSelector:function(){var b=this.options,c=a.trim(b.keepNative||""),e=a.trim(a.mobile.keepNative),f=a.trim(b.keepNativeDefault),g=d===e?"":e,h=""===g?f:"";return(c?[c]:[]).concat(g?[g]:[]).concat(h?[h]:[]).join(", ")}})}(a),function(a,d){a.widget("mobile.pagecontainer",{options:{theme:"a"},initSelector:!1,_create:function(){this.setLastScrollEnabled=!0,this._on(this.window,{navigate:"_disableRecordScroll",scrollstop:"_delayedRecordScroll"}),this._on(this.window,{navigate:"_filterNavigateEvents"}),this._on({pagechange:"_afterContentChange"}),this.window.one("navigate",a.proxy(function(){this.setLastScrollEnabled=!0},this))},_setOptions:function(a){a.theme!==d&&"none"!==a.theme?this.element.removeClass("ui-overlay-"+this.options.theme).addClass("ui-overlay-"+a.theme):a.theme!==d&&this.element.removeClass("ui-overlay-"+this.options.theme),this._super(a)},_disableRecordScroll:function(){this.setLastScrollEnabled=!1},_enableRecordScroll:function(){this.setLastScrollEnabled=!0},_afterContentChange:function(){this.setLastScrollEnabled=!0,this._off(this.window,"scrollstop"),this._on(this.window,{scrollstop:"_delayedRecordScroll"})},_recordScroll:function(){if(this.setLastScrollEnabled){var a,b,c,d=this._getActiveHistory();d&&(a=this._getScroll(),b=this._getMinScroll(),c=this._getDefaultScroll(),d.lastScroll=b>a?c:a)}},_delayedRecordScroll:function(){setTimeout(a.proxy(this,"_recordScroll"),100)},_getScroll:function(){return this.window.scrollTop()},_getMinScroll:function(){return a.mobile.minScrollBack},_getDefaultScroll:function(){return a.mobile.defaultHomeScroll},_filterNavigateEvents:function(b,c){var d;b.originalEvent&&b.originalEvent.isDefaultPrevented()||(d=b.originalEvent.type.indexOf("hashchange")>-1?c.state.hash:c.state.url,d||(d=this._getHash()),d&&"#"!==d&&0!==d.indexOf("#"+a.mobile.path.uiStateKey)||(d=location.href),this._handleNavigate(d,c.state))},_getHash:function(){return a.mobile.path.parseLocation().hash},getActivePage:function(){return this.activePage},_getInitialContent:function(){return a.mobile.firstPage},_getHistory:function(){return a.mobile.navigate.history},_getActiveHistory:function(){return a.mobile.navigate.history.getActive()},_getDocumentBase:function(){return a.mobile.path.documentBase},back:function(){this.go(-1)},forward:function(){this.go(1)},go:function(c){if(a.mobile.hashListeningEnabled)b.history.go(c);else{var d=a.mobile.navigate.history.activeIndex,e=d+parseInt(c,10),f=a.mobile.navigate.history.stack[e].url,g=c>=1?"forward":"back";a.mobile.navigate.history.activeIndex=e,a.mobile.navigate.history.previousIndex=d,this.change(f,{direction:g,changeHash:!1,fromHashChange:!0})}},_handleDestination:function(b){var c;return"string"===a.type(b)&&(b=a.mobile.path.stripHash(b)),b&&(c=this._getHistory(),b=a.mobile.path.isPath(b)?b:a.mobile.path.makeUrlAbsolute("#"+b,this._getDocumentBase()),b===a.mobile.path.makeUrlAbsolute("#"+c.initialDst,this._getDocumentBase())&&c.stack.length&&c.stack[0].url!==c.initialDst.replace(a.mobile.dialogHashKey,"")&&(b=this._getInitialContent())),b||this._getInitialContent()},_handleDialog:function(b,c){var d,e,f=this.getActivePage();return f&&!f.hasClass("ui-dialog")?("back"===c.direction?this.back():this.forward(),!1):(d=c.pageUrl,e=this._getActiveHistory(),a.extend(b,{role:e.role,transition:e.transition,reverse:"back"===c.direction}),d)},_handleNavigate:function(b,c){var e=a.mobile.path.stripHash(b),f=this._getHistory(),g=0===f.stack.length?"none":d,h={changeHash:!1,fromHashChange:!0,reverse:"back"===c.direction};a.extend(h,c,{transition:(f.getLast()||{}).transition||g}),f.activeIndex>0&&e.indexOf(a.mobile.dialogHashKey)>-1&&f.initialDst!==e&&(e=this._handleDialog(h,c),e===!1)||this._changeContent(this._handleDestination(e),h)},_changeContent:function(b,c){a.mobile.changePage(b,c)},_getBase:function(){return a.mobile.base},_getNs:function(){return a.mobile.ns},_enhance:function(a,b){return a.page({role:b})},_include:function(a,b){a.appendTo(this.element),this._enhance(a,b.role),a.page("bindRemove")},_find:function(b){var c,d=this._createFileUrl(b),e=this._createDataUrl(b),f=this._getInitialContent();return c=this.element.children("[data-"+this._getNs()+"url='"+e+"']"),0===c.length&&e&&!a.mobile.path.isPath(e)&&(c=this.element.children(a.mobile.path.hashToSelector("#"+e)).attr("data-"+this._getNs()+"url",e).jqmData("url",e)),0===c.length&&a.mobile.path.isFirstPageUrl(d)&&f&&f.parent().length&&(c=a(f)),c},_getLoader:function(){return a.mobile.loading()},_showLoading:function(b,c,d,e){this._loadMsg||(this._loadMsg=setTimeout(a.proxy(function(){this._getLoader().loader("show",c,d,e),this._loadMsg=0},this),b))},_hideLoading:function(){clearTimeout(this._loadMsg),this._loadMsg=0,this._getLoader().loader("hide")},_showError:function(){this._hideLoading(),this._showLoading(0,a.mobile.pageLoadErrorMessageTheme,a.mobile.pageLoadErrorMessage,!0),setTimeout(a.proxy(this,"_hideLoading"),1500)},_parse:function(b,c){var d,e=a("<div></div>");return e.get(0).innerHTML=b,d=e.find(":jqmData(role='page'), :jqmData(role='dialog')").first(),d.length||(d=a("<div data-"+this._getNs()+"role='page'>"+(b.split(/<\/?body[^>]*>/gim)[1]||"")+"</div>")),d.attr("data-"+this._getNs()+"url",a.mobile.path.convertUrlToDataUrl(c)).attr("data-"+this._getNs()+"external-page",!0),d},_setLoadedTitle:function(b,c){var d=c.match(/<title[^>]*>([^<]*)/)&&RegExp.$1;d&&!b.jqmData("title")&&(d=a("<div>"+d+"</div>").text(),b.jqmData("title",d))},_isRewritableBaseTag:function(){return a.mobile.dynamicBaseEnabled&&!a.support.dynamicBaseTag},_createDataUrl:function(b){return a.mobile.path.convertUrlToDataUrl(b)},_createFileUrl:function(b){return a.mobile.path.getFilePath(b)},_triggerWithDeprecated:function(b,c,d){var e=a.Event("page"+b),f=a.Event(this.widgetName+b);return(d||this.element).trigger(e,c),this.element.trigger(f,c),{deprecatedEvent:e,event:f}},_loadSuccess:function(b,c,e,f){var g=this._createFileUrl(b),h=this._createDataUrl(b);return a.proxy(function(i,j,k){var l,m=new RegExp("(<[^>]+\\bdata-"+this._getNs()+"role=[\"']?page[\"']?[^>]*>)"),n=new RegExp("\\bdata-"+this._getNs()+"url=[\"']?([^\"'>]*)[\"']?");m.test(i)&&RegExp.$1&&n.test(RegExp.$1)&&RegExp.$1&&(g=a.mobile.path.getFilePath(a("<div>"+RegExp.$1+"</div>").text())),e.prefetch===d&&this._getBase().set(g),l=this._parse(i,g),this._setLoadedTitle(l,i),c.xhr=k,c.textStatus=j,c.page=l,c.content=l,this._trigger("load",d,c)&&(this._isRewritableBaseTag()&&l&&this._getBase().rewrite(g,l),this._include(l,e),b.indexOf("&"+a.mobile.subPageUrlKey)>-1&&(l=this.element.children("[data-"+this._getNs()+"url='"+h+"']")),e.showLoadMsg&&this._hideLoading(),this.element.trigger("pageload"),f.resolve(b,e,l))},this)},_loadDefaults:{type:"get",data:d,reloadPage:!1,reload:!1,role:d,showLoadMsg:!1,loadMsgDelay:50},load:function(b,c){var e,f,g,h,i=c&&c.deferred||a.Deferred(),j=a.extend({},this._loadDefaults,c),k=null,l=a.mobile.path.makeUrlAbsolute(b,this._findBaseWithDefault());return j.reload=j.reloadPage,j.data&&"get"===j.type&&(l=a.mobile.path.addSearchParams(l,j.data),j.data=d),j.data&&"post"===j.type&&(j.reload=!0),e=this._createFileUrl(l),f=this._createDataUrl(l),k=this._find(l),0===k.length&&a.mobile.path.isEmbeddedPage(e)&&!a.mobile.path.isFirstPageUrl(e)?void i.reject(l,j):(this._getBase().reset(),k.length&&!j.reload?(this._enhance(k,j.role),i.resolve(l,j,k),void(j.prefetch||this._getBase().set(b))):(h={url:b,absUrl:l,dataUrl:f,deferred:i,options:j},g=this._triggerWithDeprecated("beforeload",h),g.deprecatedEvent.isDefaultPrevented()||g.event.isDefaultPrevented()?void 0:(j.showLoadMsg&&this._showLoading(j.loadMsgDelay),j.prefetch===d&&this._getBase().reset(),a.mobile.allowCrossDomainPages||a.mobile.path.isSameDomain(a.mobile.path.documentUrl,l)?void a.ajax({url:e,type:j.type,data:j.data,contentType:j.contentType,dataType:"html",success:this._loadSuccess(l,h,j,i),error:this._loadError(l,h,j,i)}):void i.reject(l,j))))},_loadError:function(b,c,d,e){return a.proxy(function(f,g,h){this._getBase().set(a.mobile.path.get()),c.xhr=f,c.textStatus=g,c.errorThrown=h;var i=this._triggerWithDeprecated("loadfailed",c);i.deprecatedEvent.isDefaultPrevented()||i.event.isDefaultPrevented()||(d.showLoadMsg&&this._showError(),e.reject(b,d))},this)},_getTransitionHandler:function(b){return b=a.mobile._maybeDegradeTransition(b),a.mobile.transitionHandlers[b]||a.mobile.defaultTransitionHandler},_triggerCssTransitionEvents:function(b,c,d){var e=!1;d=d||"",c&&(b[0]===c[0]&&(e=!0),this._triggerWithDeprecated(d+"hide",{nextPage:b,samePage:e},c)),this._triggerWithDeprecated(d+"show",{prevPage:c||a("")},b)},_cssTransition:function(b,c,d){var e,f,g=d.transition,h=d.reverse,i=d.deferred;this._triggerCssTransitionEvents(b,c,"before"),this._hideLoading(),e=this._getTransitionHandler(g),f=new e(g,h,b,c).transition(),f.done(function(){i.resolve.apply(i,arguments)}),f.done(a.proxy(function(){this._triggerCssTransitionEvents(b,c)},this))},_releaseTransitionLock:function(){f=!1,e.length>0&&a.mobile.changePage.apply(null,e.pop())},_removeActiveLinkClass:function(b){a.mobile.removeActiveLinkClass(b)},_loadUrl:function(b,c,d){d.target=b,d.deferred=a.Deferred(),this.load(b,d),d.deferred.done(a.proxy(function(a,b,d){f=!1,b.absUrl=c.absUrl,this.transition(d,c,b)},this)),d.deferred.fail(a.proxy(function(){this._removeActiveLinkClass(!0),this._releaseTransitionLock(),this._triggerWithDeprecated("changefailed",c)},this))},_triggerPageBeforeChange:function(b,c,d){var e=new a.Event("pagebeforechange");return a.extend(c,{toPage:b,options:d}),c.absUrl="string"===a.type(b)?a.mobile.path.makeUrlAbsolute(b,this._findBaseWithDefault()):d.absUrl,this.element.trigger(e,c),e.isDefaultPrevented()?!1:!0},change:function(b,c){if(f)return void e.unshift(arguments);var d=a.extend({},a.mobile.changePage.defaults,c),g={};d.fromPage=d.fromPage||this.activePage,this._triggerPageBeforeChange(b,g,d)&&(b=g.toPage,"string"===a.type(b)?(f=!0,this._loadUrl(b,g,d)):this.transition(b,g,d))},transition:function(b,g,h){var i,j,k,l,m,n,o,p,q,r,s,t,u,v;if(f)return void e.unshift([b,h]);if(this._triggerPageBeforeChange(b,g,h)&&(v=this._triggerWithDeprecated("beforetransition",g),!v.deprecatedEvent.isDefaultPrevented()&&!v.event.isDefaultPrevented())){if(f=!0,b[0]!==a.mobile.firstPage[0]||h.dataUrl||(h.dataUrl=a.mobile.path.documentUrl.hrefNoHash),i=h.fromPage,j=h.dataUrl&&a.mobile.path.convertUrlToDataUrl(h.dataUrl)||b.jqmData("url"),k=j,l=a.mobile.path.getFilePath(j),m=a.mobile.navigate.history.getActive(),n=0===a.mobile.navigate.history.activeIndex,o=0,p=c.title,q=("dialog"===h.role||"dialog"===b.jqmData("role"))&&b.jqmData("dialog")!==!0,i&&i[0]===b[0]&&!h.allowSamePageTransition)return f=!1,this._triggerWithDeprecated("transition",g),this.element.trigger("pagechange",g),void(h.fromHashChange&&a.mobile.navigate.history.direct({url:j}));b.page({role:h.role}),h.fromHashChange&&(o="back"===h.direction?-1:1);try{c.activeElement&&"body"!==c.activeElement.nodeName.toLowerCase()?a(c.activeElement).blur():a("input:focus, textarea:focus, select:focus").blur()}catch(w){}r=!1,q&&m&&(m.url&&m.url.indexOf(a.mobile.dialogHashKey)>-1&&this.activePage&&!this.activePage.hasClass("ui-dialog")&&a.mobile.navigate.history.activeIndex>0&&(h.changeHash=!1,r=!0),j=m.url||"",j+=!r&&j.indexOf("#")>-1?a.mobile.dialogHashKey:"#"+a.mobile.dialogHashKey,0===a.mobile.navigate.history.activeIndex&&j===a.mobile.navigate.history.initialDst&&(j+=a.mobile.dialogHashKey)),s=m?b.jqmData("title")||b.children(":jqmData(role='header')").find(".ui-title").text():p,s&&p===c.title&&(p=s),b.jqmData("title")||b.jqmData("title",p),h.transition=h.transition||(o&&!n?m.transition:d)||(q?a.mobile.defaultDialogTransition:a.mobile.defaultPageTransition),!o&&r&&(a.mobile.navigate.history.getActive().pageUrl=k),j&&!h.fromHashChange&&(!a.mobile.path.isPath(j)&&j.indexOf("#")<0&&(j="#"+j),t={transition:h.transition,title:p,pageUrl:k,role:h.role},h.changeHash!==!1&&a.mobile.hashListeningEnabled?a.mobile.navigate(j,t,!0):b[0]!==a.mobile.firstPage[0]&&a.mobile.navigate.history.add(j,t)),c.title=p,a.mobile.activePage=b,this.activePage=b,h.reverse=h.reverse||0>o,u=a.Deferred(),this._cssTransition(b,i,{transition:h.transition,reverse:h.reverse,deferred:u}),u.done(a.proxy(function(c,d,e,f,i){a.mobile.removeActiveLinkClass(),h.duplicateCachedPage&&h.duplicateCachedPage.remove(),i||a.mobile.focusPage(b),this._releaseTransitionLock(),this.element.trigger("pagechange",g),this._triggerWithDeprecated("transition",g)},this))}},_findBaseWithDefault:function(){var b=this.activePage&&a.mobile.getClosestBaseUrl(this.activePage);return b||a.mobile.path.documentBase.hrefNoHash}}),a.mobile.navreadyDeferred=a.Deferred();var e=[],f=!1}(a),function(a,c){function d(a){for(;a&&("string"!=typeof a.nodeName||"a"!==a.nodeName.toLowerCase());)a=a.parentNode;return a}var e=a.Deferred(),f=a.Deferred(),g=a.mobile.path.documentUrl,h=null;a.mobile.loadPage=function(b,c){var d;return c=c||{},d=c.pageContainer||a.mobile.pageContainer,c.deferred=a.Deferred(),d.pagecontainer("load",b,c),c.deferred.promise()},a.mobile.back=function(){var c=b.navigator;this.phonegapNavigationEnabled&&c&&c.app&&c.app.backHistory?c.app.backHistory():a.mobile.pageContainer.pagecontainer("back")},a.mobile.focusPage=function(a){var b=a.find("[autofocus]"),c=a.find(".ui-title:eq(0)");return b.length?void b.focus():void(c.length?c.focus():a.focus())},a.mobile._maybeDegradeTransition=a.mobile._maybeDegradeTransition||function(a){return a},a.mobile.changePage=function(b,c){a.mobile.pageContainer.pagecontainer("change",b,c)},a.mobile.changePage.defaults={transition:c,reverse:!1,changeHash:!0,fromHashChange:!1,role:c,duplicateCachedPage:c,pageContainer:c,showLoadMsg:!0,dataUrl:c,fromPage:c,allowSamePageTransition:!1},a.mobile._registerInternalEvents=function(){var e=function(b,c){var d,e,f,i,j=!0;return!a.mobile.ajaxEnabled||b.is(":jqmData(ajax='false')")||!b.jqmHijackable().length||b.attr("target")?!1:(d=h&&h.attr("formaction")||b.attr("action"),i=(b.attr("method")||"get").toLowerCase(),d||(d=a.mobile.getClosestBaseUrl(b),"get"===i&&(d=a.mobile.path.parseUrl(d).hrefNoSearch),d===a.mobile.path.documentBase.hrefNoHash&&(d=g.hrefNoSearch)),d=a.mobile.path.makeUrlAbsolute(d,a.mobile.getClosestBaseUrl(b)),a.mobile.path.isExternal(d)&&!a.mobile.path.isPermittedCrossDomainRequest(g,d)?!1:(c||(e=b.serializeArray(),h&&h[0].form===b[0]&&(f=h.attr("name"),f&&(a.each(e,function(a,b){return b.name===f?(f="",!1):void 0}),f&&e.push({name:f,value:h.attr("value")}))),j={url:d,options:{type:i,data:a.param(e),transition:b.jqmData("transition"),reverse:"reverse"===b.jqmData("direction"),reloadPage:!0}}),j))};a.mobile.document.delegate("form","submit",function(b){var c;b.isDefaultPrevented()||(c=e(a(this)),c&&(a.mobile.changePage(c.url,c.options),b.preventDefault()))}),a.mobile.document.bind("vclick",function(b){var c,f,g=b.target,i=!1;if(!(b.which>1)&&a.mobile.linkBindingEnabled){if(h=a(g),a.data(g,"mobile-button")){if(!e(a(g).closest("form"),!0))return;g.parentNode&&(g=g.parentNode)}else{if(g=d(g),!g||"#"===a.mobile.path.parseUrl(g.getAttribute("href")||"#").hash)return;if(!a(g).jqmHijackable().length)return}~g.className.indexOf("ui-link-inherit")?g.parentNode&&(f=a.data(g.parentNode,"buttonElements")):f=a.data(g,"buttonElements"),f?g=f.outer:i=!0,c=a(g),i&&(c=c.closest(".ui-btn")),c.length>0&&!c.hasClass("ui-state-disabled")&&(a.mobile.removeActiveLinkClass(!0),a.mobile.activeClickedLink=c,a.mobile.activeClickedLink.addClass(a.mobile.activeBtnClass))}}),a.mobile.document.bind("click",function(e){if(a.mobile.linkBindingEnabled&&!e.isDefaultPrevented()){var f,h,i,j,k,l,m,n=d(e.target),o=a(n),p=function(){b.setTimeout(function(){a.mobile.removeActiveLinkClass(!0)},200)};if(a.mobile.activeClickedLink&&a.mobile.activeClickedLink[0]===e.target.parentNode&&p(),n&&!(e.which>1)&&o.jqmHijackable().length){if(o.is(":jqmData(rel='back')"))return a.mobile.back(),!1;if(f=a.mobile.getClosestBaseUrl(o),h=a.mobile.path.makeUrlAbsolute(o.attr("href")||"#",f),!a.mobile.ajaxEnabled&&!a.mobile.path.isEmbeddedPage(h))return void p();if(-1!==h.search("#")){if(h=h.replace(/[^#]*#/,""),!h)return void e.preventDefault();h=a.mobile.path.isPath(h)?a.mobile.path.makeUrlAbsolute(h,f):a.mobile.path.makeUrlAbsolute("#"+h,g.hrefNoHash)}if(i=o.is("[rel='external']")||o.is(":jqmData(ajax='false')")||o.is("[target]"),j=i||a.mobile.path.isExternal(h)&&!a.mobile.path.isPermittedCrossDomainRequest(g,h))return void p();k=o.jqmData("transition"),l="reverse"===o.jqmData("direction")||o.jqmData("back"),m=o.attr("data-"+a.mobile.ns+"rel")||c,a.mobile.changePage(h,{transition:k,reverse:l,role:m,link:o}),e.preventDefault()}}}),a.mobile.document.delegate(".ui-page","pageshow.prefetch",function(){var b=[];a(this).find("a:jqmData(prefetch)").each(function(){var c=a(this),d=c.attr("href");d&&-1===a.inArray(d,b)&&(b.push(d),a.mobile.loadPage(d,{role:c.attr("data-"+a.mobile.ns+"rel"),prefetch:!0}))})}),a.mobile.pageContainer.pagecontainer(),a.mobile.document.bind("pageshow",function(){f?f.done(a.mobile.resetActivePageHeight):a.mobile.resetActivePageHeight()}),a.mobile.window.bind("throttledresize",a.mobile.resetActivePageHeight)},a(function(){e.resolve()}),a.mobile.window.load(function(){f.resolve(),f=null}),a.when(e,a.mobile.navreadyDeferred).done(function(){a.mobile._registerInternalEvents()})}(a),function(a,b){a.mobile.Transition=function(){this.init.apply(this,arguments)},a.extend(a.mobile.Transition.prototype,{toPreClass:" ui-page-pre-in",init:function(b,c,d,e){a.extend(this,{name:b,reverse:c,$to:d,$from:e,deferred:new a.Deferred})},cleanFrom:function(){this.$from.removeClass(a.mobile.activePageClass+" out in reverse "+this.name).height("")},beforeDoneIn:function(){},beforeDoneOut:function(){},beforeStartOut:function(){},doneIn:function(){this.beforeDoneIn(),this.$to.removeClass("out in reverse "+this.name).height(""),this.toggleViewportClass(),a.mobile.window.scrollTop()!==this.toScroll&&this.scrollPage(),this.sequential||this.$to.addClass(a.mobile.activePageClass),this.deferred.resolve(this.name,this.reverse,this.$to,this.$from,!0)
},doneOut:function(a,b,c,d){this.beforeDoneOut(),this.startIn(a,b,c,d)},hideIn:function(a){this.$to.css("z-index",-10),a.call(this),this.$to.css("z-index","")},scrollPage:function(){a.event.special.scrollstart.enabled=!1,(a.mobile.hideUrlBar||this.toScroll!==a.mobile.defaultHomeScroll)&&b.scrollTo(0,this.toScroll),setTimeout(function(){a.event.special.scrollstart.enabled=!0},150)},startIn:function(b,c,d,e){this.hideIn(function(){this.$to.addClass(a.mobile.activePageClass+this.toPreClass),e||a.mobile.focusPage(this.$to),this.$to.height(b+this.toScroll),d||this.scrollPage()}),this.$to.removeClass(this.toPreClass).addClass(this.name+" in "+c),d?this.doneIn():this.$to.animationComplete(a.proxy(function(){this.doneIn()},this))},startOut:function(b,c,d){this.beforeStartOut(b,c,d),this.$from.height(b+a.mobile.window.scrollTop()).addClass(this.name+" out"+c)},toggleViewportClass:function(){a.mobile.pageContainer.toggleClass("ui-mobile-viewport-transitioning viewport-"+this.name)},transition:function(){var b,c=this.reverse?" reverse":"",d=a.mobile.getScreenHeight(),e=a.mobile.maxTransitionWidth!==!1&&a.mobile.window.width()>a.mobile.maxTransitionWidth;return this.toScroll=a.mobile.navigate.history.getActive().lastScroll||a.mobile.defaultHomeScroll,b=!a.support.cssTransitions||!a.support.cssAnimations||e||!this.name||"none"===this.name||Math.max(a.mobile.window.scrollTop(),this.toScroll)>a.mobile.getMaxScrollForTransition(),this.toggleViewportClass(),this.$from&&!b?this.startOut(d,c,b):this.doneOut(d,c,b,!0),this.deferred.promise()}})}(a,this),function(a){a.mobile.SerialTransition=function(){this.init.apply(this,arguments)},a.extend(a.mobile.SerialTransition.prototype,a.mobile.Transition.prototype,{sequential:!0,beforeDoneOut:function(){this.$from&&this.cleanFrom()},beforeStartOut:function(b,c,d){this.$from.animationComplete(a.proxy(function(){this.doneOut(b,c,d)},this))}})}(a),function(a){a.mobile.ConcurrentTransition=function(){this.init.apply(this,arguments)},a.extend(a.mobile.ConcurrentTransition.prototype,a.mobile.Transition.prototype,{sequential:!1,beforeDoneIn:function(){this.$from&&this.cleanFrom()},beforeStartOut:function(a,b,c){this.doneOut(a,b,c)}})}(a),function(a){var b=function(){return 3*a.mobile.getScreenHeight()};a.mobile.transitionHandlers={sequential:a.mobile.SerialTransition,simultaneous:a.mobile.ConcurrentTransition},a.mobile.defaultTransitionHandler=a.mobile.transitionHandlers.sequential,a.mobile.transitionFallbacks={},a.mobile._maybeDegradeTransition=function(b){return b&&!a.support.cssTransform3d&&a.mobile.transitionFallbacks[b]&&(b=a.mobile.transitionFallbacks[b]),b},a.mobile.getMaxScrollForTransition=a.mobile.getMaxScrollForTransition||b}(a),function(a){a.mobile.transitionFallbacks.flip="fade"}(a,this),function(a){a.mobile.transitionFallbacks.flow="fade"}(a,this),function(a){a.mobile.transitionFallbacks.pop="fade"}(a,this),function(a){a.mobile.transitionHandlers.slide=a.mobile.transitionHandlers.simultaneous,a.mobile.transitionFallbacks.slide="fade"}(a,this),function(a){a.mobile.transitionFallbacks.slidedown="fade"}(a,this),function(a){a.mobile.transitionFallbacks.slidefade="fade"}(a,this),function(a){a.mobile.transitionFallbacks.slideup="fade"}(a,this),function(a){a.mobile.transitionFallbacks.turn="fade"}(a,this),function(a){a.mobile.degradeInputs={color:!1,date:!1,datetime:!1,"datetime-local":!1,email:!1,month:!1,number:!1,range:"number",search:"text",tel:!1,time:!1,url:!1,week:!1},a.mobile.page.prototype.options.degradeInputs=a.mobile.degradeInputs,a.mobile.degradeInputsWithin=function(b){b=a(b),b.find("input").not(a.mobile.page.prototype.keepNativeSelector()).each(function(){var b,c,d,e,f=a(this),g=this.getAttribute("type"),h=a.mobile.degradeInputs[g]||"text";a.mobile.degradeInputs[g]&&(b=a("<div>").html(f.clone()).html(),c=b.indexOf(" type=")>-1,d=c?/\s+type=["']?\w+['"]?/:/\/?>/,e=' type="'+h+'" data-'+a.mobile.ns+'type="'+g+'"'+(c?"":">"),f.replaceWith(b.replace(d,e)))})}}(a),function(a,b,c){a.widget("mobile.page",a.mobile.page,{options:{closeBtn:"left",closeBtnText:"Close",overlayTheme:"a",corners:!0,dialog:!1},_create:function(){this._super(),this.options.dialog&&(a.extend(this,{_inner:this.element.children(),_headerCloseButton:null}),this.options.enhanced||this._setCloseBtn(this.options.closeBtn))},_enhance:function(){this._super(),this.options.dialog&&this.element.addClass("ui-dialog").wrapInner(a("<div/>",{role:"dialog","class":"ui-dialog-contain ui-overlay-shadow"+(this.options.corners?" ui-corner-all":"")}))},_setOptions:function(b){var d,e,f=this.options;b.corners!==c&&this._inner.toggleClass("ui-corner-all",!!b.corners),b.overlayTheme!==c&&a.mobile.activePage[0]===this.element[0]&&(f.overlayTheme=b.overlayTheme,this._handlePageBeforeShow()),b.closeBtnText!==c&&(d=f.closeBtn,e=b.closeBtnText),b.closeBtn!==c&&(d=b.closeBtn),d&&this._setCloseBtn(d,e),this._super(b)},_handlePageBeforeShow:function(){this.options.overlayTheme&&this.options.dialog?(this.removeContainerBackground(),this.setContainerBackground(this.options.overlayTheme)):this._super()},_setCloseBtn:function(b,c){var d,e=this._headerCloseButton;b="left"===b?"left":"right"===b?"right":"none","none"===b?e&&(e.remove(),e=null):e?(e.removeClass("ui-btn-left ui-btn-right").addClass("ui-btn-"+b),c&&e.text(c)):(d=this._inner.find(":jqmData(role='header')").first(),e=a("<a></a>",{href:"#","class":"ui-btn ui-corner-all ui-icon-delete ui-btn-icon-notext ui-btn-"+b}).attr("data-"+a.mobile.ns+"rel","back").text(c||this.options.closeBtnText||"").prependTo(d)),this._headerCloseButton=e}})}(a,this),function(a,b,c){a.widget("mobile.dialog",{options:{closeBtn:"left",closeBtnText:"Close",overlayTheme:"a",corners:!0},_handlePageBeforeShow:function(){this._isCloseable=!0,this.options.overlayTheme&&this.element.page("removeContainerBackground").page("setContainerBackground",this.options.overlayTheme)},_handlePageBeforeHide:function(){this._isCloseable=!1},_handleVClickSubmit:function(b){var c,d=a(b.target).closest("vclick"===b.type?"a":"form");d.length&&!d.jqmData("transition")&&(c={},c["data-"+a.mobile.ns+"transition"]=(a.mobile.navigate.history.getActive()||{}).transition||a.mobile.defaultDialogTransition,c["data-"+a.mobile.ns+"direction"]="reverse",d.attr(c))},_create:function(){var b=this.element,c=this.options;b.addClass("ui-dialog").wrapInner(a("<div/>",{role:"dialog","class":"ui-dialog-contain ui-overlay-shadow"+(c.corners?" ui-corner-all":"")})),a.extend(this,{_isCloseable:!1,_inner:b.children(),_headerCloseButton:null}),this._on(b,{vclick:"_handleVClickSubmit",submit:"_handleVClickSubmit",pagebeforeshow:"_handlePageBeforeShow",pagebeforehide:"_handlePageBeforeHide"}),this._setCloseBtn(c.closeBtn)},_setOptions:function(b){var d,e,f=this.options;b.corners!==c&&this._inner.toggleClass("ui-corner-all",!!b.corners),b.overlayTheme!==c&&a.mobile.activePage[0]===this.element[0]&&(f.overlayTheme=b.overlayTheme,this._handlePageBeforeShow()),b.closeBtnText!==c&&(d=f.closeBtn,e=b.closeBtnText),b.closeBtn!==c&&(d=b.closeBtn),d&&this._setCloseBtn(d,e),this._super(b)},_setCloseBtn:function(b,c){var d,e=this._headerCloseButton;b="left"===b?"left":"right"===b?"right":"none","none"===b?e&&(e.remove(),e=null):e?(e.removeClass("ui-btn-left ui-btn-right").addClass("ui-btn-"+b),c&&e.text(c)):(d=this._inner.find(":jqmData(role='header')").first(),e=a("<a></a>",{role:"button",href:"#","class":"ui-btn ui-corner-all ui-icon-delete ui-btn-icon-notext ui-btn-"+b}).text(c||this.options.closeBtnText||"").prependTo(d),this._on(e,{click:"close"})),this._headerCloseButton=e},close:function(){var b=a.mobile.navigate.history;this._isCloseable&&(this._isCloseable=!1,a.mobile.hashListeningEnabled&&b.activeIndex>0?a.mobile.back():a.mobile.pageContainer.pagecontainer("back"))}})}(a,this),function(a,b){var c=/([A-Z])/g,d=function(a){return"ui-btn-icon-"+(null===a?"left":a)};a.widget("mobile.collapsible",{options:{enhanced:!1,expandCueText:null,collapseCueText:null,collapsed:!0,heading:"h1,h2,h3,h4,h5,h6,legend",collapsedIcon:null,expandedIcon:null,iconpos:null,theme:null,contentTheme:null,inset:null,corners:null,mini:null},_create:function(){var b=this.element,c={accordion:b.closest(":jqmData(role='collapsible-set'),:jqmData(role='collapsibleset')"+(a.mobile.collapsibleset?", :mobile-collapsibleset":"")).addClass("ui-collapsible-set")};this._ui=c,this._renderedOptions=this._getOptions(this.options),this.options.enhanced?(c.heading=a(".ui-collapsible-heading",this.element[0]),c.content=c.heading.next(),c.anchor=a("a",c.heading[0]).first(),c.status=c.anchor.children(".ui-collapsible-heading-status")):this._enhance(b,c),this._on(c.heading,{tap:function(){c.heading.find("a").first().addClass(a.mobile.activeBtnClass)},click:function(a){this._handleExpandCollapse(!c.heading.hasClass("ui-collapsible-heading-collapsed")),a.preventDefault(),a.stopPropagation()}})},_getOptions:function(b){var d,e=this._ui.accordion,f=this._ui.accordionWidget;b=a.extend({},b),e.length&&!f&&(this._ui.accordionWidget=f=e.data("mobile-collapsibleset"));for(d in b)b[d]=null!=b[d]?b[d]:f?f.options[d]:e.length?a.mobile.getAttribute(e[0],d.replace(c,"-$1").toLowerCase()):null,null==b[d]&&(b[d]=a.mobile.collapsible.defaults[d]);return b},_themeClassFromOption:function(a,b){return b?"none"===b?"":a+b:""},_enhance:function(b,c){var e,f=this._renderedOptions,g=this._themeClassFromOption("ui-body-",f.contentTheme);return b.addClass("ui-collapsible "+(f.inset?"ui-collapsible-inset ":"")+(f.inset&&f.corners?"ui-corner-all ":"")+(g?"ui-collapsible-themed-content ":"")),c.originalHeading=b.children(this.options.heading).first(),c.content=b.wrapInner("<div class='ui-collapsible-content "+g+"'></div>").children(".ui-collapsible-content"),c.heading=c.originalHeading,c.heading.is("legend")&&(c.heading=a("<div role='heading'>"+c.heading.html()+"</div>"),c.placeholder=a("<div><!-- placeholder for legend --></div>").insertBefore(c.originalHeading),c.originalHeading.remove()),e=f.collapsed?f.collapsedIcon?"ui-icon-"+f.collapsedIcon:"":f.expandedIcon?"ui-icon-"+f.expandedIcon:"",c.status=a("<span class='ui-collapsible-heading-status'></span>"),c.anchor=c.heading.detach().addClass("ui-collapsible-heading").append(c.status).wrapInner("<a href='#' class='ui-collapsible-heading-toggle'></a>").find("a").first().addClass("ui-btn "+(e?e+" ":"")+(e?d(f.iconpos)+" ":"")+this._themeClassFromOption("ui-btn-",f.theme)+" "+(f.mini?"ui-mini ":"")),c.heading.insertBefore(c.content),this._handleExpandCollapse(this.options.collapsed),c},refresh:function(){this._applyOptions(this.options),this._renderedOptions=this._getOptions(this.options)},_applyOptions:function(a){var c,e,f,g,h,i=this.element,j=this._renderedOptions,k=this._ui,l=k.anchor,m=k.status,n=this._getOptions(a);a.collapsed!==b&&this._handleExpandCollapse(a.collapsed),c=i.hasClass("ui-collapsible-collapsed"),c?n.expandCueText!==b&&m.text(n.expandCueText):n.collapseCueText!==b&&m.text(n.collapseCueText),h=n.collapsedIcon!==b?n.collapsedIcon!==!1:j.collapsedIcon!==!1,(n.iconpos!==b||n.collapsedIcon!==b||n.expandedIcon!==b)&&(l.removeClass([d(j.iconpos)].concat(j.expandedIcon?["ui-icon-"+j.expandedIcon]:[]).concat(j.collapsedIcon?["ui-icon-"+j.collapsedIcon]:[]).join(" ")),h&&l.addClass([d(n.iconpos!==b?n.iconpos:j.iconpos)].concat(c?["ui-icon-"+(n.collapsedIcon!==b?n.collapsedIcon:j.collapsedIcon)]:["ui-icon-"+(n.expandedIcon!==b?n.expandedIcon:j.expandedIcon)]).join(" "))),n.theme!==b&&(f=this._themeClassFromOption("ui-btn-",j.theme),e=this._themeClassFromOption("ui-btn-",n.theme),l.removeClass(f).addClass(e)),n.contentTheme!==b&&(f=this._themeClassFromOption("ui-body-",j.contentTheme),e=this._themeClassFromOption("ui-body-",n.contentTheme),k.content.removeClass(f).addClass(e)),n.inset!==b&&(i.toggleClass("ui-collapsible-inset",n.inset),g=!(!n.inset||!n.corners&&!j.corners)),n.corners!==b&&(g=!(!n.corners||!n.inset&&!j.inset)),g!==b&&i.toggleClass("ui-corner-all",g),n.mini!==b&&l.toggleClass("ui-mini",n.mini)},_setOptions:function(a){this._applyOptions(a),this._super(a),this._renderedOptions=this._getOptions(this.options)},_handleExpandCollapse:function(b){var c=this._renderedOptions,d=this._ui;d.status.text(b?c.expandCueText:c.collapseCueText),d.heading.toggleClass("ui-collapsible-heading-collapsed",b).find("a").first().toggleClass("ui-icon-"+c.expandedIcon,!b).toggleClass("ui-icon-"+c.collapsedIcon,b||c.expandedIcon===c.collapsedIcon).removeClass(a.mobile.activeBtnClass),this.element.toggleClass("ui-collapsible-collapsed",b),d.content.toggleClass("ui-collapsible-content-collapsed",b).attr("aria-hidden",b).trigger("updatelayout"),this.options.collapsed=b,this._trigger(b?"collapse":"expand")},expand:function(){this._handleExpandCollapse(!1)},collapse:function(){this._handleExpandCollapse(!0)},_destroy:function(){var a=this._ui,b=this.options;b.enhanced||(a.placeholder?(a.originalHeading.insertBefore(a.placeholder),a.placeholder.remove(),a.heading.remove()):(a.status.remove(),a.heading.removeClass("ui-collapsible-heading ui-collapsible-heading-collapsed").children().contents().unwrap()),a.anchor.contents().unwrap(),a.content.contents().unwrap(),this.element.removeClass("ui-collapsible ui-collapsible-collapsed ui-collapsible-themed-content ui-collapsible-inset ui-corner-all"))}}),a.mobile.collapsible.defaults={expandCueText:" click to expand contents",collapseCueText:" click to collapse contents",collapsedIcon:"plus",contentTheme:"inherit",expandedIcon:"minus",iconpos:"left",inset:!0,corners:!0,theme:"inherit",mini:!1}}(a),function(a){a.mobile.behaviors.addFirstLastClasses={_getVisibles:function(a,b){var c;return b?c=a.not(".ui-screen-hidden"):(c=a.filter(":visible"),0===c.length&&(c=a.not(".ui-screen-hidden"))),c},_addFirstLastClasses:function(a,b,c){a.removeClass("ui-first-child ui-last-child"),b.eq(0).addClass("ui-first-child").end().last().addClass("ui-last-child"),c||this.element.trigger("updatelayout")},_removeFirstLastClasses:function(a){a.removeClass("ui-first-child ui-last-child")}}}(a),function(a,b){var c=":mobile-collapsible, "+a.mobile.collapsible.initSelector;a.widget("mobile.collapsibleset",a.extend({initSelector:":jqmData(role='collapsible-set'),:jqmData(role='collapsibleset')",options:a.extend({enhanced:!1},a.mobile.collapsible.defaults),_handleCollapsibleExpand:function(b){var c=a(b.target).closest(".ui-collapsible");c.parent().is(":mobile-collapsibleset, :jqmData(role='collapsible-set')")&&c.siblings(".ui-collapsible:not(.ui-collapsible-collapsed)").collapsible("collapse")},_create:function(){var b=this.element,c=this.options;a.extend(this,{_classes:""}),c.enhanced||(b.addClass("ui-collapsible-set "+this._themeClassFromOption("ui-group-theme-",c.theme)+" "+(c.corners&&c.inset?"ui-corner-all ":"")),this.element.find(a.mobile.collapsible.initSelector).collapsible()),this._on(b,{collapsibleexpand:"_handleCollapsibleExpand"})},_themeClassFromOption:function(a,b){return b?"none"===b?"":a+b:""},_init:function(){this._refresh(!0),this.element.children(c).filter(":jqmData(collapsed='false')").collapsible("expand")},_setOptions:function(a){var c,d,e=this.element,f=this._themeClassFromOption("ui-group-theme-",a.theme);return f&&e.removeClass(this._themeClassFromOption("ui-group-theme-",this.options.theme)).addClass(f),a.inset!==b&&(d=!(!a.inset||!a.corners&&!this.options.corners)),a.corners!==b&&(d=!(!a.corners||!a.inset&&!this.options.inset)),d!==b&&e.toggleClass("ui-corner-all",d),c=this._super(a),this.element.children(":mobile-collapsible").collapsible("refresh"),c},_destroy:function(){var a=this.element;this._removeFirstLastClasses(a.children(c)),a.removeClass("ui-collapsible-set ui-corner-all "+this._themeClassFromOption("ui-group-theme-",this.options.theme)).children(":mobile-collapsible").collapsible("destroy")},_refresh:function(b){var d=this.element.children(c);this.element.find(a.mobile.collapsible.initSelector).not(".ui-collapsible").collapsible(),this._addFirstLastClasses(d,this._getVisibles(d,b),b)},refresh:function(){this._refresh(!1)}},a.mobile.behaviors.addFirstLastClasses))}(a),function(a){a.fn.fieldcontain=function(){return this.addClass("ui-field-contain")}}(a),function(a){a.fn.grid=function(b){return this.each(function(){var c,d,e=a(this),f=a.extend({grid:null},b),g=e.children(),h={solo:1,a:2,b:3,c:4,d:5},i=f.grid;if(!i)if(g.length<=5)for(d in h)h[d]===g.length&&(i=d);else i="a",e.addClass("ui-grid-duo");c=h[i],e.addClass("ui-grid-"+i),g.filter(":nth-child("+c+"n+1)").addClass("ui-block-a"),c>1&&g.filter(":nth-child("+c+"n+2)").addClass("ui-block-b"),c>2&&g.filter(":nth-child("+c+"n+3)").addClass("ui-block-c"),c>3&&g.filter(":nth-child("+c+"n+4)").addClass("ui-block-d"),c>4&&g.filter(":nth-child("+c+"n+5)").addClass("ui-block-e")})}}(a),function(a,b){a.widget("mobile.navbar",{options:{iconpos:"top",grid:null},_create:function(){var d=this.element,e=d.find("a"),f=e.filter(":jqmData(icon)").length?this.options.iconpos:b;d.addClass("ui-navbar").attr("role","navigation").find("ul").jqmEnhanceable().grid({grid:this.options.grid}),e.each(function(){var b=a.mobile.getAttribute(this,"icon"),c=a.mobile.getAttribute(this,"theme"),d="ui-btn";c&&(d+=" ui-btn-"+c),b&&(d+=" ui-icon-"+b+" ui-btn-icon-"+f),a(this).addClass(d)}),d.delegate("a","vclick",function(){var b=a(this);b.hasClass("ui-state-disabled")||b.hasClass("ui-disabled")||b.hasClass(a.mobile.activeBtnClass)||(e.removeClass(a.mobile.activeBtnClass),b.addClass(a.mobile.activeBtnClass),a(c).one("pagehide",function(){b.removeClass(a.mobile.activeBtnClass)}))}),d.closest(".ui-page").bind("pagebeforeshow",function(){e.filter(".ui-state-persist").addClass(a.mobile.activeBtnClass)})}})}(a),function(a){var b=a.mobile.getAttribute;a.widget("mobile.listview",a.extend({options:{theme:null,countTheme:null,dividerTheme:null,icon:"carat-r",splitIcon:"carat-r",splitTheme:null,corners:!0,shadow:!0,inset:!1},_create:function(){var a=this,b="";b+=a.options.inset?" ui-listview-inset":"",a.options.inset&&(b+=a.options.corners?" ui-corner-all":"",b+=a.options.shadow?" ui-shadow":""),a.element.addClass(" ui-listview"+b),a.refresh(!0)},_findFirstElementByTagName:function(a,b,c,d){var e={};for(e[c]=e[d]=!0;a;){if(e[a.nodeName])return a;a=a[b]}return null},_addThumbClasses:function(b){var c,d,e=b.length;for(c=0;e>c;c++)d=a(this._findFirstElementByTagName(b[c].firstChild,"nextSibling","img","IMG")),d.length&&a(this._findFirstElementByTagName(d[0].parentNode,"parentNode","li","LI")).addClass(d.hasClass("ui-li-icon")?"ui-li-has-icon":"ui-li-has-thumb")},_getChildrenByTagName:function(b,c,d){var e=[],f={};for(f[c]=f[d]=!0,b=b.firstChild;b;)f[b.nodeName]&&e.push(b),b=b.nextSibling;return a(e)},_beforeListviewRefresh:a.noop,_afterListviewRefresh:a.noop,refresh:function(c){var d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x=this.options,y=this.element,z=!!a.nodeName(y[0],"ol"),A=y.attr("start"),B={},C=y.find(".ui-li-count"),D=b(y[0],"counttheme")||this.options.countTheme,E=D?"ui-body-"+D:"ui-body-inherit";for(x.theme&&y.addClass("ui-group-theme-"+x.theme),z&&(A||0===A)&&(n=parseInt(A,10)-1,y.css("counter-reset","listnumbering "+n)),this._beforeListviewRefresh(),w=this._getChildrenByTagName(y[0],"li","LI"),e=0,f=w.length;f>e;e++)g=w.eq(e),h="",(c||g[0].className.search(/\bui-li-static\b|\bui-li-divider\b/)<0)&&(l=this._getChildrenByTagName(g[0],"a","A"),m="list-divider"===b(g[0],"role"),p=g.attr("value"),i=b(g[0],"theme"),l.length&&l[0].className.search(/\bui-btn\b/)<0&&!m?(j=b(g[0],"icon"),k=j===!1?!1:j||x.icon,l.removeClass("ui-link"),d="ui-btn",i&&(d+=" ui-btn-"+i),l.length>1?(h="ui-li-has-alt",q=l.last(),r=b(q[0],"theme")||x.splitTheme||b(g[0],"theme",!0),s=r?" ui-btn-"+r:"",t=b(q[0],"icon")||b(g[0],"icon")||x.splitIcon,u="ui-btn ui-btn-icon-notext ui-icon-"+t+s,q.attr("title",a.trim(q.getEncodedText())).addClass(u).empty()):k&&(d+=" ui-btn-icon-right ui-icon-"+k),l.first().addClass(d)):m?(v=b(g[0],"theme")||x.dividerTheme||x.theme,h="ui-li-divider ui-bar-"+(v?v:"inherit"),g.attr("role","heading")):l.length<=0&&(h="ui-li-static ui-body-"+(i?i:"inherit")),z&&p&&(o=parseInt(p,10)-1,g.css("counter-reset","listnumbering "+o))),B[h]||(B[h]=[]),B[h].push(g[0]);for(h in B)a(B[h]).addClass(h);C.each(function(){a(this).closest("li").addClass("ui-li-has-count")}),E&&C.addClass(E),this._addThumbClasses(w),this._addThumbClasses(w.find(".ui-btn")),this._afterListviewRefresh(),this._addFirstLastClasses(w,this._getVisibles(w,c),c)}},a.mobile.behaviors.addFirstLastClasses))}(a),function(a){function b(b){var c=a.trim(b.text())||null;return c?c=c.slice(0,1).toUpperCase():null}a.widget("mobile.listview",a.mobile.listview,{options:{autodividers:!1,autodividersSelector:b},_beforeListviewRefresh:function(){this.options.autodividers&&(this._replaceDividers(),this._superApply(arguments))},_replaceDividers:function(){var b,d,e,f,g,h=null,i=this.element;for(i.children("li:jqmData(role='list-divider')").remove(),d=i.children("li"),b=0;b<d.length;b++)e=d[b],f=this.options.autodividersSelector(a(e)),f&&h!==f&&(g=c.createElement("li"),g.appendChild(c.createTextNode(f)),g.setAttribute("data-"+a.mobile.ns+"role","list-divider"),e.parentNode.insertBefore(g,e)),h=f}})}(a),function(a){var b=/(^|\s)ui-li-divider($|\s)/,c=/(^|\s)ui-screen-hidden($|\s)/;a.widget("mobile.listview",a.mobile.listview,{options:{hideDividers:!1},_afterListviewRefresh:function(){var a,d,e,f=!0;if(this._superApply(arguments),this.options.hideDividers)for(a=this._getChildrenByTagName(this.element[0],"li","LI"),d=a.length-1;d>-1;d--)e=a[d],e.className.match(b)?(f&&(e.className=e.className+" ui-screen-hidden"),f=!0):e.className.match(c)||(f=!1)}})}(a),function(a){a.mobile.nojs=function(b){a(":jqmData(role='nojs')",b).addClass("ui-nojs")}}(a),function(a){a.mobile.behaviors.formReset={_handleFormReset:function(){this._on(this.element.closest("form"),{reset:function(){this._delay("_reset")}})}}}(a),function(a,b){var c=a.mobile.path.hashToSelector;a.widget("mobile.checkboxradio",a.extend({initSelector:"input:not( :jqmData(role='flipswitch' ) )[type='checkbox'],input[type='radio']:not( :jqmData(role='flipswitch' ))",options:{theme:"inherit",mini:!1,wrapperClass:null,enhanced:!1,iconpos:"left"},_create:function(){var b=this.element,d=this.options,e=function(a,b){return a.jqmData(b)||a.closest("form, fieldset").jqmData(b)},f=b.closest("label"),g=f.length?f:b.closest("form, fieldset, :jqmData(role='page'), :jqmData(role='dialog')").find("label").filter("[for='"+c(b[0].id)+"']").first(),h=b[0].type,i="ui-"+h+"-on",j="ui-"+h+"-off";("checkbox"===h||"radio"===h)&&(this.element[0].disabled&&(this.options.disabled=!0),d.iconpos=e(b,"iconpos")||g.attr("data-"+a.mobile.ns+"iconpos")||d.iconpos,d.mini=e(b,"mini")||d.mini,a.extend(this,{input:b,label:g,parentLabel:f,inputtype:h,checkedClass:i,uncheckedClass:j}),this.options.enhanced||this._enhance(),this._on(g,{vmouseover:"_handleLabelVMouseOver",vclick:"_handleLabelVClick"}),this._on(b,{vmousedown:"_cacheVals",vclick:"_handleInputVClick",focus:"_handleInputFocus",blur:"_handleInputBlur"}),this._handleFormReset(),this.refresh())},_enhance:function(){this.label.addClass("ui-btn ui-corner-all"),this.parentLabel.length>0?this.input.add(this.label).wrapAll(this._wrapper()):(this.element.wrap(this._wrapper()),this.element.parent().prepend(this.label)),this._setOptions({theme:this.options.theme,iconpos:this.options.iconpos,mini:this.options.mini})},_wrapper:function(){return a("<div class='"+(this.options.wrapperClass?this.options.wrapperClass:"")+" ui-"+this.inputtype+(this.options.disabled?" ui-state-disabled":"")+"' ></div>")},_handleInputFocus:function(){this.label.addClass(a.mobile.focusClass)},_handleInputBlur:function(){this.label.removeClass(a.mobile.focusClass)},_handleInputVClick:function(){this.element.prop("checked",this.element.is(":checked")),this._getInputSet().not(this.element).prop("checked",!1),this._updateAll()},_handleLabelVMouseOver:function(a){this.label.parent().hasClass("ui-state-disabled")&&a.stopPropagation()},_handleLabelVClick:function(a){var b=this.element;return b.is(":disabled")?void a.preventDefault():(this._cacheVals(),b.prop("checked","radio"===this.inputtype&&!0||!b.prop("checked")),b.triggerHandler("click"),this._getInputSet().not(b).prop("checked",!1),this._updateAll(),!1)},_cacheVals:function(){this._getInputSet().each(function(){a(this).attr("data-"+a.mobile.ns+"cacheVal",this.checked)})},_getInputSet:function(){var b,d,e=this.element[0],f=e.name,g=e.form,h=this.element.parents().last().get(0),i=this.element;return f&&"radio"===this.inputtype&&h&&(b="input[type='radio'][name='"+c(f)+"']",g?(d=g.id,d&&(i=a(b+"[form='"+c(d)+"']",h)),i=a(g).find(b).filter(function(){return this.form===g}).add(i)):i=a(b,h).filter(function(){return!this.form})),i},_updateAll:function(){var b=this;this._getInputSet().each(function(){var c=a(this);(this.checked||"checkbox"===b.inputtype)&&c.trigger("change")}).checkboxradio("refresh")},_reset:function(){this.refresh()},_hasIcon:function(){var b,c,d=a.mobile.controlgroup;return d&&(b=this.element.closest(":mobile-controlgroup,"+d.prototype.initSelector),b.length>0)?(c=a.data(b[0],"mobile-controlgroup"),"horizontal"!==(c?c.options.type:b.attr("data-"+a.mobile.ns+"type"))):!0},refresh:function(){var b=this._hasIcon(),c=this.element[0].checked,d=a.mobile.activeBtnClass,e="ui-btn-icon-"+this.options.iconpos,f=[],g=[];b?(g.push(d),f.push(e)):(g.push(e),(c?f:g).push(d)),c?(f.push(this.checkedClass),g.push(this.uncheckedClass)):(f.push(this.uncheckedClass),g.push(this.checkedClass)),this.label.addClass(f.join(" ")).removeClass(g.join(" "))},widget:function(){return this.label.parent()},_setOptions:function(a){var c=this.label,d=this.options,e=this.widget(),f=this._hasIcon();a.disabled!==b&&(this.input.prop("disabled",!!a.disabled),e.toggleClass("ui-state-disabled",!!a.disabled)),a.mini!==b&&e.toggleClass("ui-mini",!!a.mini),a.theme!==b&&c.removeClass("ui-btn-"+d.theme).addClass("ui-btn-"+a.theme),a.wrapperClass!==b&&e.removeClass(d.wrapperClass).addClass(a.wrapperClass),a.iconpos!==b&&f?c.removeClass("ui-btn-icon-"+d.iconpos).addClass("ui-btn-icon-"+a.iconpos):f||c.removeClass("ui-btn-icon-"+d.iconpos),this._super(a)}},a.mobile.behaviors.formReset))}(a),function(a,b){a.widget("mobile.button",{initSelector:"input[type='button'], input[type='submit'], input[type='reset']",options:{theme:null,icon:null,iconpos:"left",iconshadow:!1,corners:!0,shadow:!0,inline:null,mini:null,wrapperClass:null,enhanced:!1},_create:function(){this.element.is(":disabled")&&(this.options.disabled=!0),this.options.enhanced||this._enhance(),a.extend(this,{wrapper:this.element.parent()}),this._on({focus:function(){this.widget().addClass(a.mobile.focusClass)},blur:function(){this.widget().removeClass(a.mobile.focusClass)}}),this.refresh(!0)},_enhance:function(){this.element.wrap(this._button())},_button:function(){var b=this.options,c=this._getIconClasses(this.options);return a("<div class='ui-btn ui-input-btn"+(b.wrapperClass?" "+b.wrapperClass:"")+(b.theme?" ui-btn-"+b.theme:"")+(b.corners?" ui-corner-all":"")+(b.shadow?" ui-shadow":"")+(b.inline?" ui-btn-inline":"")+(b.mini?" ui-mini":"")+(b.disabled?" ui-state-disabled":"")+(c?" "+c:"")+"' >"+this.element.val()+"</div>")},widget:function(){return this.wrapper},_destroy:function(){this.element.insertBefore(this.button),this.button.remove()},_getIconClasses:function(a){return a.icon?"ui-icon-"+a.icon+(a.iconshadow?" ui-shadow-icon":"")+" ui-btn-icon-"+a.iconpos:""},_setOptions:function(c){var d=this.widget();c.theme!==b&&d.removeClass(this.options.theme).addClass("ui-btn-"+c.theme),c.corners!==b&&d.toggleClass("ui-corner-all",c.corners),c.shadow!==b&&d.toggleClass("ui-shadow",c.shadow),c.inline!==b&&d.toggleClass("ui-btn-inline",c.inline),c.mini!==b&&d.toggleClass("ui-mini",c.mini),c.disabled!==b&&(this.element.prop("disabled",c.disabled),d.toggleClass("ui-state-disabled",c.disabled)),(c.icon!==b||c.iconshadow!==b||c.iconpos!==b)&&d.removeClass(this._getIconClasses(this.options)).addClass(this._getIconClasses(a.extend({},this.options,c))),this._super(c)},refresh:function(b){var c,d=this.element.prop("disabled");this.options.icon&&"notext"===this.options.iconpos&&this.element.attr("title")&&this.element.attr("title",this.element.val()),b||(c=this.element.detach(),a(this.wrapper).text(this.element.val()).append(c)),this.options.disabled!==d&&this._setOptions({disabled:d})}})}(a),function(a){var b=a("meta[name=viewport]"),c=b.attr("content"),d=c+",maximum-scale=1, user-scalable=no",e=c+",maximum-scale=10, user-scalable=yes",f=/(user-scalable[\s]*=[\s]*no)|(maximum-scale[\s]*=[\s]*1)[$,\s]/.test(c);a.mobile.zoom=a.extend({},{enabled:!f,locked:!1,disable:function(c){f||a.mobile.zoom.locked||(b.attr("content",d),a.mobile.zoom.enabled=!1,a.mobile.zoom.locked=c||!1)},enable:function(c){f||a.mobile.zoom.locked&&c!==!0||(b.attr("content",e),a.mobile.zoom.enabled=!0,a.mobile.zoom.locked=!1)},restore:function(){f||(b.attr("content",c),a.mobile.zoom.enabled=!0)}})}(a),function(a,b){a.widget("mobile.textinput",{initSelector:"input[type='text'],input[type='search'],:jqmData(type='search'),input[type='number'],:jqmData(type='number'),input[type='password'],input[type='email'],input[type='url'],input[type='tel'],textarea,input[type='time'],input[type='date'],input[type='month'],input[type='week'],input[type='datetime'],input[type='datetime-local'],input[type='color'],input:not([type]),input[type='file']",options:{theme:null,corners:!0,mini:!1,preventFocusZoom:/iPhone|iPad|iPod/.test(navigator.platform)&&navigator.userAgent.indexOf("AppleWebKit")>-1,wrapperClass:"",enhanced:!1},_create:function(){var b=this.options,c=this.element.is("[type='search'], :jqmData(type='search')"),d="TEXTAREA"===this.element[0].tagName,e=this.element.is("[data-"+(a.mobile.ns||"")+"type='range']"),f=(this.element.is("input")||this.element.is("[data-"+(a.mobile.ns||"")+"type='search']"))&&!e;this.element.prop("disabled")&&(b.disabled=!0),a.extend(this,{classes:this._classesFromOptions(),isSearch:c,isTextarea:d,isRange:e,inputNeedsWrap:f}),this._autoCorrect(),b.enhanced||this._enhance(),this._on({focus:"_handleFocus",blur:"_handleBlur"})},refresh:function(){this.setOptions({disabled:this.element.is(":disabled")})},_enhance:function(){var a=[];this.isTextarea&&a.push("ui-input-text"),(this.isTextarea||this.isRange)&&a.push("ui-shadow-inset"),this.inputNeedsWrap?this.element.wrap(this._wrap()):a=a.concat(this.classes),this.element.addClass(a.join(" "))},widget:function(){return this.inputNeedsWrap?this.element.parent():this.element},_classesFromOptions:function(){var a=this.options,b=[];return b.push("ui-body-"+(null===a.theme?"inherit":a.theme)),a.corners&&b.push("ui-corner-all"),a.mini&&b.push("ui-mini"),a.disabled&&b.push("ui-state-disabled"),a.wrapperClass&&b.push(a.wrapperClass),b},_wrap:function(){return a("<div class='"+(this.isSearch?"ui-input-search ":"ui-input-text ")+this.classes.join(" ")+" ui-shadow-inset'></div>")},_autoCorrect:function(){"undefined"==typeof this.element[0].autocorrect||a.support.touchOverflow||(this.element[0].setAttribute("autocorrect","off"),this.element[0].setAttribute("autocomplete","off"))},_handleBlur:function(){this.widget().removeClass(a.mobile.focusClass),this.options.preventFocusZoom&&a.mobile.zoom.enable(!0)},_handleFocus:function(){this.options.preventFocusZoom&&a.mobile.zoom.disable(!0),this.widget().addClass(a.mobile.focusClass)},_setOptions:function(a){var c=this.widget();this._super(a),(a.disabled!==b||a.mini!==b||a.corners!==b||a.theme!==b||a.wrapperClass!==b)&&(c.removeClass(this.classes.join(" ")),this.classes=this._classesFromOptions(),c.addClass(this.classes.join(" "))),a.disabled!==b&&this.element.prop("disabled",!!a.disabled)},_destroy:function(){this.options.enhanced||(this.inputNeedsWrap&&this.element.unwrap(),this.element.removeClass("ui-input-text "+this.classes.join(" ")))}})}(a),function(a,d){a.widget("mobile.slider",a.extend({initSelector:"input[type='range'], :jqmData(type='range'), :jqmData(role='slider')",widgetEventPrefix:"slide",options:{theme:null,trackTheme:null,corners:!0,mini:!1,highlight:!1},_create:function(){var e,f,g,h,i,j,k,l,m,n,o=this,p=this.element,q=this.options.trackTheme||a.mobile.getAttribute(p[0],"theme"),r=q?" ui-bar-"+q:" ui-bar-inherit",s=this.options.corners||p.jqmData("corners")?" ui-corner-all":"",t=this.options.mini||p.jqmData("mini")?" ui-mini":"",u=p[0].nodeName.toLowerCase(),v="select"===u,w=p.parent().is(":jqmData(role='rangeslider')"),x=v?"ui-slider-switch":"",y=p.attr("id"),z=a("[for='"+y+"']"),A=z.attr("id")||y+"-label",B=v?0:parseFloat(p.attr("min")),C=v?p.find("option").length-1:parseFloat(p.attr("max")),D=b.parseFloat(p.attr("step")||1),E=c.createElement("a"),F=a(E),G=c.createElement("div"),H=a(G),I=this.options.highlight&&!v?function(){var b=c.createElement("div");
return b.className="ui-slider-bg "+a.mobile.activeBtnClass,a(b).prependTo(H)}():!1;if(z.attr("id",A),this.isToggleSwitch=v,E.setAttribute("href","#"),G.setAttribute("role","application"),G.className=[this.isToggleSwitch?"ui-slider ui-slider-track ui-shadow-inset ":"ui-slider-track ui-shadow-inset ",x,r,s,t].join(""),E.className="ui-slider-handle",G.appendChild(E),F.attr({role:"slider","aria-valuemin":B,"aria-valuemax":C,"aria-valuenow":this._value(),"aria-valuetext":this._value(),title:this._value(),"aria-labelledby":A}),a.extend(this,{slider:H,handle:F,control:p,type:u,step:D,max:C,min:B,valuebg:I,isRangeslider:w,dragging:!1,beforeStart:null,userModified:!1,mouseMoved:!1}),v){for(k=p.attr("tabindex"),k&&F.attr("tabindex",k),p.attr("tabindex","-1").focus(function(){a(this).blur(),F.focus()}),f=c.createElement("div"),f.className="ui-slider-inneroffset",g=0,h=G.childNodes.length;h>g;g++)f.appendChild(G.childNodes[g]);for(G.appendChild(f),F.addClass("ui-slider-handle-snapping"),e=p.find("option"),i=0,j=e.length;j>i;i++)l=i?"a":"b",m=i?" "+a.mobile.activeBtnClass:"",n=c.createElement("span"),n.className=["ui-slider-label ui-slider-label-",l,m].join(""),n.setAttribute("role","img"),n.appendChild(c.createTextNode(e[i].innerHTML)),a(n).prependTo(H);o._labels=a(".ui-slider-label",H)}p.addClass(v?"ui-slider-switch":"ui-slider-input"),this._on(p,{change:"_controlChange",keyup:"_controlKeyup",blur:"_controlBlur",vmouseup:"_controlVMouseUp"}),H.bind("vmousedown",a.proxy(this._sliderVMouseDown,this)).bind("vclick",!1),this._on(c,{vmousemove:"_preventDocumentDrag"}),this._on(H.add(c),{vmouseup:"_sliderVMouseUp"}),H.insertAfter(p),v||w||(f=this.options.mini?"<div class='ui-slider ui-mini'>":"<div class='ui-slider'>",p.add(H).wrapAll(f)),this._on(this.handle,{vmousedown:"_handleVMouseDown",keydown:"_handleKeydown",keyup:"_handleKeyup"}),this.handle.bind("vclick",!1),this._handleFormReset(),this.refresh(d,d,!0)},_setOptions:function(a){a.theme!==d&&this._setTheme(a.theme),a.trackTheme!==d&&this._setTrackTheme(a.trackTheme),a.corners!==d&&this._setCorners(a.corners),a.mini!==d&&this._setMini(a.mini),a.highlight!==d&&this._setHighlight(a.highlight),a.disabled!==d&&this._setDisabled(a.disabled),this._super(a)},_controlChange:function(a){return this._trigger("controlchange",a)===!1?!1:void(this.mouseMoved||this.refresh(this._value(),!0))},_controlKeyup:function(){this.refresh(this._value(),!0,!0)},_controlBlur:function(){this.refresh(this._value(),!0)},_controlVMouseUp:function(){this._checkedRefresh()},_handleVMouseDown:function(){this.handle.focus()},_handleKeydown:function(b){var c=this._value();if(!this.options.disabled){switch(b.keyCode){case a.mobile.keyCode.HOME:case a.mobile.keyCode.END:case a.mobile.keyCode.PAGE_UP:case a.mobile.keyCode.PAGE_DOWN:case a.mobile.keyCode.UP:case a.mobile.keyCode.RIGHT:case a.mobile.keyCode.DOWN:case a.mobile.keyCode.LEFT:b.preventDefault(),this._keySliding||(this._keySliding=!0,this.handle.addClass("ui-state-active"))}switch(b.keyCode){case a.mobile.keyCode.HOME:this.refresh(this.min);break;case a.mobile.keyCode.END:this.refresh(this.max);break;case a.mobile.keyCode.PAGE_UP:case a.mobile.keyCode.UP:case a.mobile.keyCode.RIGHT:this.refresh(c+this.step);break;case a.mobile.keyCode.PAGE_DOWN:case a.mobile.keyCode.DOWN:case a.mobile.keyCode.LEFT:this.refresh(c-this.step)}}},_handleKeyup:function(){this._keySliding&&(this._keySliding=!1,this.handle.removeClass("ui-state-active"))},_sliderVMouseDown:function(a){return this.options.disabled||1!==a.which&&0!==a.which&&a.which!==d?!1:this._trigger("beforestart",a)===!1?!1:(this.dragging=!0,this.userModified=!1,this.mouseMoved=!1,this.isToggleSwitch&&(this.beforeStart=this.element[0].selectedIndex),this.refresh(a),this._trigger("start"),!1)},_sliderVMouseUp:function(){return this.dragging?(this.dragging=!1,this.isToggleSwitch&&(this.handle.addClass("ui-slider-handle-snapping"),this.refresh(this.mouseMoved?this.userModified?0===this.beforeStart?1:0:this.beforeStart:0===this.beforeStart?1:0)),this.mouseMoved=!1,this._trigger("stop"),!1):void 0},_preventDocumentDrag:function(a){return this._trigger("drag",a)===!1?!1:this.dragging&&!this.options.disabled?(this.mouseMoved=!0,this.isToggleSwitch&&this.handle.removeClass("ui-slider-handle-snapping"),this.refresh(a),this.userModified=this.beforeStart!==this.element[0].selectedIndex,!1):void 0},_checkedRefresh:function(){this.value!==this._value()&&this.refresh(this._value())},_value:function(){return this.isToggleSwitch?this.element[0].selectedIndex:parseFloat(this.element.val())},_reset:function(){this.refresh(d,!1,!0)},refresh:function(b,d,e){var f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z=this,A=a.mobile.getAttribute(this.element[0],"theme"),B=this.options.theme||A,C=B?" ui-btn-"+B:"",D=this.options.trackTheme||A,E=D?" ui-bar-"+D:" ui-bar-inherit",F=this.options.corners?" ui-corner-all":"",G=this.options.mini?" ui-mini":"";if(z.slider[0].className=[this.isToggleSwitch?"ui-slider ui-slider-switch ui-slider-track ui-shadow-inset":"ui-slider-track ui-shadow-inset",E,F,G].join(""),(this.options.disabled||this.element.prop("disabled"))&&this.disable(),this.value=this._value(),this.options.highlight&&!this.isToggleSwitch&&0===this.slider.find(".ui-slider-bg").length&&(this.valuebg=function(){var b=c.createElement("div");return b.className="ui-slider-bg "+a.mobile.activeBtnClass,a(b).prependTo(z.slider)}()),this.handle.addClass("ui-btn"+C+" ui-shadow"),l=this.element,m=!this.isToggleSwitch,n=m?[]:l.find("option"),o=m?parseFloat(l.attr("min")):0,p=m?parseFloat(l.attr("max")):n.length-1,q=m&&parseFloat(l.attr("step"))>0?parseFloat(l.attr("step")):1,"object"==typeof b){if(h=b,i=8,f=this.slider.offset().left,g=this.slider.width(),j=g/((p-o)/q),!this.dragging||h.pageX<f-i||h.pageX>f+g+i)return;k=j>1?(h.pageX-f)/g*100:Math.round((h.pageX-f)/g*100)}else null==b&&(b=m?parseFloat(l.val()||0):l[0].selectedIndex),k=(parseFloat(b)-o)/(p-o)*100;if(!isNaN(k)&&(r=k/100*(p-o)+o,s=(r-o)%q,t=r-s,2*Math.abs(s)>=q&&(t+=s>0?q:-q),u=100/((p-o)/q),r=parseFloat(t.toFixed(5)),"undefined"==typeof j&&(j=g/((p-o)/q)),j>1&&m&&(k=(r-o)*u*(1/q)),0>k&&(k=0),k>100&&(k=100),o>r&&(r=o),r>p&&(r=p),this.handle.css("left",k+"%"),this.handle[0].setAttribute("aria-valuenow",m?r:n.eq(r).attr("value")),this.handle[0].setAttribute("aria-valuetext",m?r:n.eq(r).getEncodedText()),this.handle[0].setAttribute("title",m?r:n.eq(r).getEncodedText()),this.valuebg&&this.valuebg.css("width",k+"%"),this._labels&&(v=this.handle.width()/this.slider.width()*100,w=k&&v+(100-v)*k/100,x=100===k?0:Math.min(v+100-w,100),this._labels.each(function(){var b=a(this).hasClass("ui-slider-label-a");a(this).width((b?w:x)+"%")})),!e)){if(y=!1,m?(y=l.val()!==r,l.val(r)):(y=l[0].selectedIndex!==r,l[0].selectedIndex=r),this._trigger("beforechange",b)===!1)return!1;!d&&y&&l.trigger("change")}},_setHighlight:function(a){a=!!a,a?(this.options.highlight=!!a,this.refresh()):this.valuebg&&(this.valuebg.remove(),this.valuebg=!1)},_setTheme:function(a){this.handle.removeClass("ui-btn-"+this.options.theme).addClass("ui-btn-"+a);var b=this.options.theme?this.options.theme:"inherit",c=a?a:"inherit";this.control.removeClass("ui-body-"+b).addClass("ui-body-"+c)},_setTrackTheme:function(a){var b=this.options.trackTheme?this.options.trackTheme:"inherit",c=a?a:"inherit";this.slider.removeClass("ui-body-"+b).addClass("ui-body-"+c)},_setMini:function(a){a=!!a,this.isToggleSwitch||this.isRangeslider||(this.slider.parent().toggleClass("ui-mini",a),this.element.toggleClass("ui-mini",a)),this.slider.toggleClass("ui-mini",a)},_setCorners:function(a){this.slider.toggleClass("ui-corner-all",a),this.isToggleSwitch||this.control.toggleClass("ui-corner-all",a)},_setDisabled:function(a){a=!!a,this.element.prop("disabled",a),this.slider.toggleClass("ui-state-disabled",a).attr("aria-disabled",a)}},a.mobile.behaviors.formReset))}(a),function(a){function b(){return c||(c=a("<div></div>",{"class":"ui-slider-popup ui-shadow ui-corner-all"})),c.clone()}var c;a.widget("mobile.slider",a.mobile.slider,{options:{popupEnabled:!1,showValue:!1},_create:function(){this._super(),a.extend(this,{_currentValue:null,_popup:null,_popupVisible:!1}),this._setOption("popupEnabled",this.options.popupEnabled),this._on(this.handle,{vmousedown:"_showPopup"}),this._on(this.slider.add(this.document),{vmouseup:"_hidePopup"}),this._refresh()},_positionPopup:function(){var a=this.handle.offset();this._popup.offset({left:a.left+(this.handle.width()-this._popup.width())/2,top:a.top-this._popup.outerHeight()-5})},_setOption:function(a,c){this._super(a,c),"showValue"===a?this.handle.html(c&&!this.options.mini?this._value():""):"popupEnabled"===a&&c&&!this._popup&&(this._popup=b().addClass("ui-body-"+(this.options.theme||"a")).hide().insertBefore(this.element))},refresh:function(){this._super.apply(this,arguments),this._refresh()},_refresh:function(){var a,b=this.options;b.popupEnabled&&this.handle.removeAttr("title"),a=this._value(),a!==this._currentValue&&(this._currentValue=a,b.popupEnabled&&this._popup?(this._positionPopup(),this._popup.html(a)):b.showValue&&!this.options.mini&&this.handle.html(a))},_showPopup:function(){this.options.popupEnabled&&!this._popupVisible&&(this.handle.html(""),this._popup.show(),this._positionPopup(),this._popupVisible=!0)},_hidePopup:function(){var a=this.options;a.popupEnabled&&this._popupVisible&&(a.showValue&&!a.mini&&this.handle.html(this._value()),this._popup.hide(),this._popupVisible=!1)}})}(a),function(a,b){a.widget("mobile.flipswitch",a.extend({options:{onText:"On",offText:"Off",theme:null,enhanced:!1,wrapperClass:null,corners:!0,mini:!1},_create:function(){this.options.enhanced?a.extend(this,{flipswitch:this.element.parent(),on:this.element.find(".ui-flipswitch-on").eq(0),off:this.element.find(".ui-flipswitch-off").eq(0),type:this.element.get(0).tagName}):this._enhance(),this._handleFormReset(),this._originalTabIndex=this.element.attr("tabindex"),null!=this._originalTabIndex&&this.on.attr("tabindex",this._originalTabIndex),this.element.attr("tabindex","-1"),this._on({focus:"_handleInputFocus"}),this.element.is(":disabled")&&this._setOptions({disabled:!0}),this._on(this.flipswitch,{click:"_toggle",swipeleft:"_left",swiperight:"_right"}),this._on(this.on,{keydown:"_keydown"}),this._on({change:"refresh"})},_handleInputFocus:function(){this.on.focus()},widget:function(){return this.flipswitch},_left:function(){this.flipswitch.removeClass("ui-flipswitch-active"),"SELECT"===this.type?this.element.get(0).selectedIndex=0:this.element.prop("checked",!1),this.element.trigger("change")},_right:function(){this.flipswitch.addClass("ui-flipswitch-active"),"SELECT"===this.type?this.element.get(0).selectedIndex=1:this.element.prop("checked",!0),this.element.trigger("change")},_enhance:function(){var b=a("<div>"),c=this.options,d=this.element,e=c.theme?c.theme:"inherit",f=a("<a></a>",{href:"#"}),g=a("<span></span>"),h=d.get(0).tagName,i="INPUT"===h?c.onText:d.find("option").eq(1).text(),j="INPUT"===h?c.offText:d.find("option").eq(0).text();f.addClass("ui-flipswitch-on ui-btn ui-shadow ui-btn-inherit").text(i),g.addClass("ui-flipswitch-off").text(j),b.addClass("ui-flipswitch ui-shadow-inset ui-bar-"+e+" "+(c.wrapperClass?c.wrapperClass:"")+" "+(d.is(":checked")||d.find("option").eq(1).is(":selected")?"ui-flipswitch-active":"")+(d.is(":disabled")?" ui-state-disabled":"")+(c.corners?" ui-corner-all":"")+(c.mini?" ui-mini":"")).append(f,g),d.addClass("ui-flipswitch-input").after(b).appendTo(b),a.extend(this,{flipswitch:b,on:f,off:g,type:h})},_reset:function(){this.refresh()},refresh:function(){var a,b=this.flipswitch.hasClass("ui-flipswitch-active")?"_right":"_left";a="SELECT"===this.type?this.element.get(0).selectedIndex>0?"_right":"_left":this.element.prop("checked")?"_right":"_left",a!==b&&this[a]()},_toggle:function(){var a=this.flipswitch.hasClass("ui-flipswitch-active")?"_left":"_right";this[a]()},_keydown:function(b){b.which===a.mobile.keyCode.LEFT?this._left():b.which===a.mobile.keyCode.RIGHT?this._right():b.which===a.mobile.keyCode.SPACE&&(this._toggle(),b.preventDefault())},_setOptions:function(a){if(a.theme!==b){var c=a.theme?a.theme:"inherit",d=a.theme?a.theme:"inherit";this.widget().removeClass("ui-bar-"+c).addClass("ui-bar-"+d)}a.onText!==b&&this.on.text(a.onText),a.offText!==b&&this.off.text(a.offText),a.disabled!==b&&this.widget().toggleClass("ui-state-disabled",a.disabled),a.mini!==b&&this.widget().toggleClass("ui-mini",a.mini),a.corners!==b&&this.widget().toggleClass("ui-corner-all",a.corners),this._super(a)},_destroy:function(){this.options.enhanced||(null!=this._originalTabIndex?this.element.attr("tabindex",this._originalTabIndex):this.element.removeAttr("tabindex"),this.on.remove(),this.off.remove(),this.element.unwrap(),this.flipswitch.remove(),this.removeClass("ui-flipswitch-input"))}},a.mobile.behaviors.formReset))}(a),function(a,b){a.widget("mobile.rangeslider",a.extend({options:{theme:null,trackTheme:null,corners:!0,mini:!1,highlight:!0},_create:function(){var b=this.element,c=this.options.mini?"ui-rangeslider ui-mini":"ui-rangeslider",d=b.find("input").first(),e=b.find("input").last(),f=b.find("label").first(),g=a.data(d.get(0),"mobile-slider")||a.data(d.slider().get(0),"mobile-slider"),h=a.data(e.get(0),"mobile-slider")||a.data(e.slider().get(0),"mobile-slider"),i=g.slider,j=h.slider,k=g.handle,l=a("<div class='ui-rangeslider-sliders' />").appendTo(b);d.addClass("ui-rangeslider-first"),e.addClass("ui-rangeslider-last"),b.addClass(c),i.appendTo(l),j.appendTo(l),f.insertBefore(b),k.prependTo(j),a.extend(this,{_inputFirst:d,_inputLast:e,_sliderFirst:i,_sliderLast:j,_label:f,_targetVal:null,_sliderTarget:!1,_sliders:l,_proxy:!1}),this.refresh(),this._on(this.element.find("input.ui-slider-input"),{slidebeforestart:"_slidebeforestart",slidestop:"_slidestop",slidedrag:"_slidedrag",slidebeforechange:"_change",blur:"_change",keyup:"_change"}),this._on({mousedown:"_change"}),this._on(this.element.closest("form"),{reset:"_handleReset"}),this._on(k,{vmousedown:"_dragFirstHandle"})},_handleReset:function(){var a=this;setTimeout(function(){a._updateHighlight()},0)},_dragFirstHandle:function(b){return a.data(this._inputFirst.get(0),"mobile-slider").dragging=!0,a.data(this._inputFirst.get(0),"mobile-slider").refresh(b),!1},_slidedrag:function(b){var c=a(b.target).is(this._inputFirst),d=c?this._inputLast:this._inputFirst;return this._sliderTarget=!1,"first"===this._proxy&&c||"last"===this._proxy&&!c?(a.data(d.get(0),"mobile-slider").dragging=!0,a.data(d.get(0),"mobile-slider").refresh(b),!1):void 0},_slidestop:function(b){var c=a(b.target).is(this._inputFirst);this._proxy=!1,this.element.find("input").trigger("vmouseup"),this._sliderFirst.css("z-index",c?1:"")},_slidebeforestart:function(b){this._sliderTarget=!1,a(b.originalEvent.target).hasClass("ui-slider-track")&&(this._sliderTarget=!0,this._targetVal=a(b.target).val())},_setOptions:function(a){a.theme!==b&&this._setTheme(a.theme),a.trackTheme!==b&&this._setTrackTheme(a.trackTheme),a.mini!==b&&this._setMini(a.mini),a.highlight!==b&&this._setHighlight(a.highlight),this._super(a),this.refresh()},refresh:function(){var a=this.element,b=this.options;(this._inputFirst.is(":disabled")||this._inputLast.is(":disabled"))&&(this.options.disabled=!0),a.find("input").slider({theme:b.theme,trackTheme:b.trackTheme,disabled:b.disabled,corners:b.corners,mini:b.mini,highlight:b.highlight}).slider("refresh"),this._updateHighlight()},_change:function(b){if("keyup"===b.type)return this._updateHighlight(),!1;var c=this,d=parseFloat(this._inputFirst.val(),10),e=parseFloat(this._inputLast.val(),10),f=a(b.target).hasClass("ui-rangeslider-first"),g=f?this._inputFirst:this._inputLast,h=f?this._inputLast:this._inputFirst;if(this._inputFirst.val()>this._inputLast.val()&&"mousedown"===b.type&&!a(b.target).hasClass("ui-slider-handle"))g.blur();else if("mousedown"===b.type)return;return d>e&&!this._sliderTarget?(g.val(f?e:d).slider("refresh"),this._trigger("normalize")):d>e&&(g.val(this._targetVal).slider("refresh"),setTimeout(function(){h.val(f?d:e).slider("refresh"),a.data(h.get(0),"mobile-slider").handle.focus(),c._sliderFirst.css("z-index",f?"":1),c._trigger("normalize")},0),this._proxy=f?"first":"last"),d===e?(a.data(g.get(0),"mobile-slider").handle.css("z-index",1),a.data(h.get(0),"mobile-slider").handle.css("z-index",0)):(a.data(h.get(0),"mobile-slider").handle.css("z-index",""),a.data(g.get(0),"mobile-slider").handle.css("z-index","")),this._updateHighlight(),d>=e?!1:void 0},_updateHighlight:function(){var b=parseInt(a.data(this._inputFirst.get(0),"mobile-slider").handle.get(0).style.left,10),c=parseInt(a.data(this._inputLast.get(0),"mobile-slider").handle.get(0).style.left,10),d=c-b;this.element.find(".ui-slider-bg").css({"margin-left":b+"%",width:d+"%"})},_setTheme:function(a){this._inputFirst.slider("option","theme",a),this._inputLast.slider("option","theme",a)},_setTrackTheme:function(a){this._inputFirst.slider("option","trackTheme",a),this._inputLast.slider("option","trackTheme",a)},_setMini:function(a){this._inputFirst.slider("option","mini",a),this._inputLast.slider("option","mini",a),this.element.toggleClass("ui-mini",!!a)},_setHighlight:function(a){this._inputFirst.slider("option","highlight",a),this._inputLast.slider("option","highlight",a)},_destroy:function(){this._label.prependTo(this.element),this.element.removeClass("ui-rangeslider ui-mini"),this._inputFirst.after(this._sliderFirst),this._inputLast.after(this._sliderLast),this._sliders.remove(),this.element.find("input").removeClass("ui-rangeslider-first ui-rangeslider-last").slider("destroy")}},a.mobile.behaviors.formReset))}(a),function(a,b){a.widget("mobile.textinput",a.mobile.textinput,{options:{clearBtn:!1,clearBtnText:"Clear text"},_create:function(){this._super(),(this.options.clearBtn||this.isSearch)&&this._addClearBtn()},clearButton:function(){return a("<a href='#' class='ui-input-clear ui-btn ui-icon-delete ui-btn-icon-notext ui-corner-all' title='"+this.options.clearBtnText+"'>"+this.options.clearBtnText+"</a>")},_clearBtnClick:function(a){this.element.val("").focus().trigger("change"),this._clearBtn.addClass("ui-input-clear-hidden"),a.preventDefault()},_addClearBtn:function(){this.options.enhanced||this._enhanceClear(),a.extend(this,{_clearBtn:this.widget().find("a.ui-input-clear")}),this._bindClearEvents(),this._toggleClear()},_enhanceClear:function(){this.clearButton().appendTo(this.widget()),this.widget().addClass("ui-input-has-clear")},_bindClearEvents:function(){this._on(this._clearBtn,{click:"_clearBtnClick"}),this._on({keyup:"_toggleClear",change:"_toggleClear",input:"_toggleClear",focus:"_toggleClear",blur:"_toggleClear",cut:"_toggleClear",paste:"_toggleClear"})},_unbindClear:function(){this._off(this._clearBtn,"click"),this._off(this.element,"keyup change input focus blur cut paste")},_setOptions:function(a){this._super(a),a.clearBtn===b||this.element.is("textarea, :jqmData(type='range')")||(a.clearBtn?this._addClearBtn():this._destroyClear()),a.clearBtnText!==b&&this._clearBtn!==b&&this._clearBtn.text(a.clearBtnText).attr("title",a.clearBtnText)},_toggleClear:function(){this._delay("_toggleClearClass",0)},_toggleClearClass:function(){this._clearBtn.toggleClass("ui-input-clear-hidden",!this.element.val())},_destroyClear:function(){this.widget().removeClass("ui-input-has-clear"),this._unbindClear(),this._clearBtn.remove()},_destroy:function(){this._super(),this._destroyClear()}})}(a),function(a,b){a.widget("mobile.textinput",a.mobile.textinput,{options:{autogrow:!0,keyupTimeoutBuffer:100},_create:function(){this._super(),this.options.autogrow&&this.isTextarea&&this._autogrow()},_autogrow:function(){this.element.addClass("ui-textinput-autogrow"),this._on({keyup:"_timeout",change:"_timeout",input:"_timeout",paste:"_timeout"}),this._on(!0,this.document,{pageshow:"_handleShow",popupbeforeposition:"_handleShow",updatelayout:"_handleShow",panelopen:"_handleShow"})},_handleShow:function(b){a.contains(b.target,this.element[0])&&this.element.is(":visible")&&("popupbeforeposition"!==b.type&&this.element.addClass("ui-textinput-autogrow-resize").animationComplete(a.proxy(function(){this.element.removeClass("ui-textinput-autogrow-resize")},this),"transition"),this._timeout())},_unbindAutogrow:function(){this.element.removeClass("ui-textinput-autogrow"),this._off(this.element,"keyup change input paste"),this._off(this.document,"pageshow popupbeforeposition updatelayout panelopen")},keyupTimeout:null,_prepareHeightUpdate:function(a){this.keyupTimeout&&clearTimeout(this.keyupTimeout),a===b?this._updateHeight():this.keyupTimeout=this._delay("_updateHeight",a)},_timeout:function(){this._prepareHeightUpdate(this.options.keyupTimeoutBuffer)},_updateHeight:function(){var a,b,c,d,e,f,g,h,i,j=this.window.scrollTop();this.keyupTimeout=0,"onpage"in this.element[0]||this.element.css({height:0,"min-height":0,"max-height":0}),d=this.element[0].scrollHeight,e=this.element[0].clientHeight,f=parseFloat(this.element.css("border-top-width")),g=parseFloat(this.element.css("border-bottom-width")),h=f+g,i=d+h+15,0===e&&(a=parseFloat(this.element.css("padding-top")),b=parseFloat(this.element.css("padding-bottom")),c=a+b,i+=c),this.element.css({height:i,"min-height":"","max-height":""}),this.window.scrollTop(j)},refresh:function(){this.options.autogrow&&this.isTextarea&&this._updateHeight()},_setOptions:function(a){this._super(a),a.autogrow!==b&&this.isTextarea&&(a.autogrow?this._autogrow():this._unbindAutogrow())}})}(a),function(a){a.widget("mobile.selectmenu",a.extend({initSelector:"select:not( :jqmData(role='slider')):not( :jqmData(role='flipswitch') )",options:{theme:null,icon:"carat-d",iconpos:"right",inline:!1,corners:!0,shadow:!0,iconshadow:!1,overlayTheme:null,dividerTheme:null,hidePlaceholderMenuItems:!0,closeText:"Close",nativeMenu:!0,preventFocusZoom:/iPhone|iPad|iPod/.test(navigator.platform)&&navigator.userAgent.indexOf("AppleWebKit")>-1,mini:!1},_button:function(){return a("<div/>")},_setDisabled:function(a){return this.element.attr("disabled",a),this.button.attr("aria-disabled",a),this._setOption("disabled",a)},_focusButton:function(){var a=this;setTimeout(function(){a.button.focus()},40)},_selectOptions:function(){return this.select.find("option")},_preExtension:function(){var b=this.options.inline||this.element.jqmData("inline"),c=this.options.mini||this.element.jqmData("mini"),d="";~this.element[0].className.indexOf("ui-btn-left")&&(d=" ui-btn-left"),~this.element[0].className.indexOf("ui-btn-right")&&(d=" ui-btn-right"),b&&(d+=" ui-btn-inline"),c&&(d+=" ui-mini"),this.select=this.element.removeClass("ui-btn-left ui-btn-right").wrap("<div class='ui-select"+d+"'>"),this.selectId=this.select.attr("id")||"select-"+this.uuid,this.buttonId=this.selectId+"-button",this.label=a("label[for='"+this.selectId+"']"),this.isMultiple=this.select[0].multiple},_destroy:function(){var a=this.element.parents(".ui-select");a.length>0&&(a.is(".ui-btn-left, .ui-btn-right")&&this.element.addClass(a.hasClass("ui-btn-left")?"ui-btn-left":"ui-btn-right"),this.element.insertAfter(a),a.remove())},_create:function(){this._preExtension(),this.button=this._button();var c=this,d=this.options,e=d.icon?d.iconpos||this.select.jqmData("iconpos"):!1,f=this.button.insertBefore(this.select).attr("id",this.buttonId).addClass("ui-btn"+(d.icon?" ui-icon-"+d.icon+" ui-btn-icon-"+e+(d.iconshadow?" ui-shadow-icon":""):"")+(d.theme?" ui-btn-"+d.theme:"")+(d.corners?" ui-corner-all":"")+(d.shadow?" ui-shadow":""));this.setButtonText(),d.nativeMenu&&b.opera&&b.opera.version&&f.addClass("ui-select-nativeonly"),this.isMultiple&&(this.buttonCount=a("<span>").addClass("ui-li-count ui-body-inherit").hide().appendTo(f.addClass("ui-li-has-count"))),(d.disabled||this.element.attr("disabled"))&&this.disable(),this.select.change(function(){c.refresh(),d.nativeMenu&&this.blur()}),this._handleFormReset(),this._on(this.button,{keydown:"_handleKeydown"}),this.build()},build:function(){var b=this;this.select.appendTo(b.button).bind("vmousedown",function(){b.button.addClass(a.mobile.activeBtnClass)}).bind("focus",function(){b.button.addClass(a.mobile.focusClass)}).bind("blur",function(){b.button.removeClass(a.mobile.focusClass)}).bind("focus vmouseover",function(){b.button.trigger("vmouseover")}).bind("vmousemove",function(){b.button.removeClass(a.mobile.activeBtnClass)}).bind("change blur vmouseout",function(){b.button.trigger("vmouseout").removeClass(a.mobile.activeBtnClass)}),b.button.bind("vmousedown",function(){b.options.preventFocusZoom&&a.mobile.zoom.disable(!0)}),b.label.bind("click focus",function(){b.options.preventFocusZoom&&a.mobile.zoom.disable(!0)}),b.select.bind("focus",function(){b.options.preventFocusZoom&&a.mobile.zoom.disable(!0)}),b.button.bind("mouseup",function(){b.options.preventFocusZoom&&setTimeout(function(){a.mobile.zoom.enable(!0)},0)}),b.select.bind("blur",function(){b.options.preventFocusZoom&&a.mobile.zoom.enable(!0)})},selected:function(){return this._selectOptions().filter(":selected")},selectedIndices:function(){var a=this;return this.selected().map(function(){return a._selectOptions().index(this)}).get()},setButtonText:function(){var b=this,d=this.selected(),e=this.placeholder,f=a(c.createElement("span"));this.button.children("span").not(".ui-li-count").remove().end().end().prepend(function(){return e=d.length?d.map(function(){return a(this).text()}).get().join(", "):b.placeholder,e?f.text(e):f.html(" "),f.addClass(b.select.attr("class")).addClass(d.attr("class")).removeClass("ui-screen-hidden")}())},setButtonCount:function(){var a=this.selected();this.isMultiple&&this.buttonCount[a.length>1?"show":"hide"]().text(a.length)},_handleKeydown:function(){this._delay("_refreshButton")},_reset:function(){this.refresh()},_refreshButton:function(){this.setButtonText(),this.setButtonCount()},refresh:function(){this._refreshButton()},open:a.noop,close:a.noop,disable:function(){this._setDisabled(!0),this.button.addClass("ui-state-disabled")},enable:function(){this._setDisabled(!1),this.button.removeClass("ui-state-disabled")}},a.mobile.behaviors.formReset))}(a),function(a){a.mobile.links=function(b){a(b).find("a").jqmEnhanceable().filter(":jqmData(rel='popup')[href][href!='']").each(function(){var a=this,b=a.getAttribute("href").substring(1);b&&(a.setAttribute("aria-haspopup",!0),a.setAttribute("aria-owns",b),a.setAttribute("aria-expanded",!1))}).end().not(".ui-btn, :jqmData(role='none'), :jqmData(role='nojs')").addClass("ui-link")}}(a),function(a,c){function d(a,b,c,d){var e=d;return e=b>a?c+(a-b)/2:Math.min(Math.max(c,d-b/2),c+a-b)}function e(a){return{x:a.scrollLeft(),y:a.scrollTop(),cx:a[0].innerWidth||a.width(),cy:a[0].innerHeight||a.height()}}a.widget("mobile.popup",{options:{wrapperClass:null,theme:null,overlayTheme:null,shadow:!0,corners:!0,transition:"none",positionTo:"origin",tolerance:null,closeLinkSelector:"a:jqmData(rel='back')",closeLinkEvents:"click.popup",navigateEvents:"navigate.popup",closeEvents:"navigate.popup pagebeforechange.popup",dismissible:!0,enhanced:!1,history:!a.mobile.browser.oldIE},_create:function(){var b=this.element,c=b.attr("id"),d=this.options;d.history=d.history&&a.mobile.ajaxEnabled&&a.mobile.hashListeningEnabled,a.extend(this,{_scrollTop:0,_page:b.closest(".ui-page"),_ui:null,_fallbackTransition:"",_currentTransition:!1,_prerequisites:null,_isOpen:!1,_tolerance:null,_resizeData:null,_ignoreResizeTo:0,_orientationchangeInProgress:!1}),0===this._page.length&&(this._page=a("body")),d.enhanced?this._ui={container:b.parent(),screen:b.parent().prev(),placeholder:a(this.document[0].getElementById(c+"-placeholder"))}:(this._ui=this._enhance(b,c),this._applyTransition(d.transition)),this._setTolerance(d.tolerance)._ui.focusElement=this._ui.container,this._on(this._ui.screen,{vclick:"_eatEventAndClose"}),this._on(this.window,{orientationchange:a.proxy(this,"_handleWindowOrientationchange"),resize:a.proxy(this,"_handleWindowResize"),keyup:a.proxy(this,"_handleWindowKeyUp")}),this._on(this.document,{focusin:"_handleDocumentFocusIn"})},_enhance:function(b,c){var d=this.options,e=d.wrapperClass,f={screen:a("<div class='ui-screen-hidden ui-popup-screen "+this._themeClassFromOption("ui-overlay-",d.overlayTheme)+"'></div>"),placeholder:a("<div style='display: none;'><!-- placeholder --></div>"),container:a("<div class='ui-popup-container ui-popup-hidden ui-popup-truncate"+(e?" "+e:"")+"'></div>")},g=this.document[0].createDocumentFragment();return g.appendChild(f.screen[0]),g.appendChild(f.container[0]),c&&(f.screen.attr("id",c+"-screen"),f.container.attr("id",c+"-popup"),f.placeholder.attr("id",c+"-placeholder").html("<!-- placeholder for "+c+" -->")),this._page[0].appendChild(g),f.placeholder.insertAfter(b),b.detach().addClass("ui-popup "+this._themeClassFromOption("ui-body-",d.theme)+" "+(d.shadow?"ui-overlay-shadow ":"")+(d.corners?"ui-corner-all ":"")).appendTo(f.container),f},_eatEventAndClose:function(a){return a.preventDefault(),a.stopImmediatePropagation(),this.options.dismissible&&this.close(),!1},_resizeScreen:function(){var a=this._ui.screen,b=this._ui.container.outerHeight(!0),c=a.removeAttr("style").height(),d=this.document.height()-1;d>c?a.height(d):b>c&&a.height(b)},_handleWindowKeyUp:function(b){return this._isOpen&&b.keyCode===a.mobile.keyCode.ESCAPE?this._eatEventAndClose(b):void 0},_expectResizeEvent:function(){var a=e(this.window);if(this._resizeData){if(a.x===this._resizeData.windowCoordinates.x&&a.y===this._resizeData.windowCoordinates.y&&a.cx===this._resizeData.windowCoordinates.cx&&a.cy===this._resizeData.windowCoordinates.cy)return!1;clearTimeout(this._resizeData.timeoutId)}return this._resizeData={timeoutId:this._delay("_resizeTimeout",200),windowCoordinates:a},!0},_resizeTimeout:function(){this._isOpen?this._expectResizeEvent()||(this._ui.container.hasClass("ui-popup-hidden")&&(this._ui.container.removeClass("ui-popup-hidden ui-popup-truncate"),this.reposition({positionTo:"window"}),this._ignoreResizeEvents()),this._resizeScreen(),this._resizeData=null,this._orientationchangeInProgress=!1):(this._resizeData=null,this._orientationchangeInProgress=!1)},_stopIgnoringResizeEvents:function(){this._ignoreResizeTo=0},_ignoreResizeEvents:function(){this._ignoreResizeTo&&clearTimeout(this._ignoreResizeTo),this._ignoreResizeTo=this._delay("_stopIgnoringResizeEvents",1e3)},_handleWindowResize:function(){this._isOpen&&0===this._ignoreResizeTo&&(!this._expectResizeEvent()&&!this._orientationchangeInProgress||this._ui.container.hasClass("ui-popup-hidden")||this._ui.container.addClass("ui-popup-hidden ui-popup-truncate").removeAttr("style"))},_handleWindowOrientationchange:function(){!this._orientationchangeInProgress&&this._isOpen&&0===this._ignoreResizeTo&&(this._expectResizeEvent(),this._orientationchangeInProgress=!0)},_handleDocumentFocusIn:function(b){var c,d=b.target,e=this._ui;if(this._isOpen){if(d!==e.container[0]){if(c=a(d),0===c.parents().filter(e.container[0]).length)return a(this.document[0].activeElement).one("focus",function(){c.blur()}),e.focusElement.focus(),b.preventDefault(),b.stopImmediatePropagation(),!1;e.focusElement[0]===e.container[0]&&(e.focusElement=c)}this._ignoreResizeEvents()}},_themeClassFromOption:function(a,b){return b?"none"===b?"":a+b:a+"inherit"},_applyTransition:function(b){return b&&(this._ui.container.removeClass(this._fallbackTransition),"none"!==b&&(this._fallbackTransition=a.mobile._maybeDegradeTransition(b),"none"===this._fallbackTransition&&(this._fallbackTransition=""),this._ui.container.addClass(this._fallbackTransition))),this},_setOptions:function(a){var b=this.options,d=this.element,e=this._ui.screen;return a.wrapperClass!==c&&this._ui.container.removeClass(b.wrapperClass).addClass(a.wrapperClass),a.theme!==c&&d.removeClass(this._themeClassFromOption("ui-body-",b.theme)).addClass(this._themeClassFromOption("ui-body-",a.theme)),a.overlayTheme!==c&&(e.removeClass(this._themeClassFromOption("ui-overlay-",b.overlayTheme)).addClass(this._themeClassFromOption("ui-overlay-",a.overlayTheme)),this._isOpen&&e.addClass("in")),a.shadow!==c&&d.toggleClass("ui-overlay-shadow",a.shadow),a.corners!==c&&d.toggleClass("ui-corner-all",a.corners),a.transition!==c&&(this._currentTransition||this._applyTransition(a.transition)),a.tolerance!==c&&this._setTolerance(a.tolerance),a.disabled!==c&&a.disabled&&this.close(),this._super(a)
},_setTolerance:function(b){var d,e={t:30,r:15,b:30,l:15};if(b!==c)switch(d=String(b).split(","),a.each(d,function(a,b){d[a]=parseInt(b,10)}),d.length){case 1:isNaN(d[0])||(e.t=e.r=e.b=e.l=d[0]);break;case 2:isNaN(d[0])||(e.t=e.b=d[0]),isNaN(d[1])||(e.l=e.r=d[1]);break;case 4:isNaN(d[0])||(e.t=d[0]),isNaN(d[1])||(e.r=d[1]),isNaN(d[2])||(e.b=d[2]),isNaN(d[3])||(e.l=d[3])}return this._tolerance=e,this},_clampPopupWidth:function(a){var b,c=e(this.window),d={x:this._tolerance.l,y:c.y+this._tolerance.t,cx:c.cx-this._tolerance.l-this._tolerance.r,cy:c.cy-this._tolerance.t-this._tolerance.b};return a||this._ui.container.css("max-width",d.cx),b={cx:this._ui.container.outerWidth(!0),cy:this._ui.container.outerHeight(!0)},{rc:d,menuSize:b}},_calculateFinalLocation:function(a,b){var c,e=b.rc,f=b.menuSize;return c={left:d(e.cx,f.cx,e.x,a.x),top:d(e.cy,f.cy,e.y,a.y)},c.top=Math.max(0,c.top),c.top-=Math.min(c.top,Math.max(0,c.top+f.cy-this.document.height())),c},_placementCoords:function(a){return this._calculateFinalLocation(a,this._clampPopupWidth())},_createPrerequisites:function(b,c,d){var e,f=this;e={screen:a.Deferred(),container:a.Deferred()},e.screen.then(function(){e===f._prerequisites&&b()}),e.container.then(function(){e===f._prerequisites&&c()}),a.when(e.screen,e.container).done(function(){e===f._prerequisites&&(f._prerequisites=null,d())}),f._prerequisites=e},_animate:function(b){return this._ui.screen.removeClass(b.classToRemove).addClass(b.screenClassToAdd),b.prerequisites.screen.resolve(),b.transition&&"none"!==b.transition&&(b.applyTransition&&this._applyTransition(b.transition),this._fallbackTransition)?void this._ui.container.addClass(b.containerClassToAdd).removeClass(b.classToRemove).animationComplete(a.proxy(b.prerequisites.container,"resolve")):(this._ui.container.removeClass(b.classToRemove),void b.prerequisites.container.resolve())},_desiredCoords:function(b){var c,d=null,f=e(this.window),g=b.x,h=b.y,i=b.positionTo;if(i&&"origin"!==i)if("window"===i)g=f.cx/2+f.x,h=f.cy/2+f.y;else{try{d=a(i)}catch(j){d=null}d&&(d.filter(":visible"),0===d.length&&(d=null))}return d&&(c=d.offset(),g=c.left+d.outerWidth()/2,h=c.top+d.outerHeight()/2),("number"!==a.type(g)||isNaN(g))&&(g=f.cx/2+f.x),("number"!==a.type(h)||isNaN(h))&&(h=f.cy/2+f.y),{x:g,y:h}},_reposition:function(a){a={x:a.x,y:a.y,positionTo:a.positionTo},this._trigger("beforeposition",c,a),this._ui.container.offset(this._placementCoords(this._desiredCoords(a)))},reposition:function(a){this._isOpen&&this._reposition(a)},_openPrerequisitesComplete:function(){var a=this.element.attr("id");this._ui.container.addClass("ui-popup-active"),this._isOpen=!0,this._resizeScreen(),this._ui.container.attr("tabindex","0").focus(),this._ignoreResizeEvents(),a&&this.document.find("[aria-haspopup='true'][aria-owns='"+a+"']").attr("aria-expanded",!0),this._trigger("afteropen")},_open:function(b){var c=a.extend({},this.options,b),d=function(){var a=navigator.userAgent,b=a.match(/AppleWebKit\/([0-9\.]+)/),c=!!b&&b[1],d=a.match(/Android (\d+(?:\.\d+))/),e=!!d&&d[1],f=a.indexOf("Chrome")>-1;return null!==d&&"4.0"===e&&c&&c>534.13&&!f?!0:!1}();this._createPrerequisites(a.noop,a.noop,a.proxy(this,"_openPrerequisitesComplete")),this._currentTransition=c.transition,this._applyTransition(c.transition),this._ui.screen.removeClass("ui-screen-hidden"),this._ui.container.removeClass("ui-popup-truncate"),this._reposition(c),this._ui.container.removeClass("ui-popup-hidden"),this.options.overlayTheme&&d&&this.element.closest(".ui-page").addClass("ui-popup-open"),this._animate({additionalCondition:!0,transition:c.transition,classToRemove:"",screenClassToAdd:"in",containerClassToAdd:"in",applyTransition:!1,prerequisites:this._prerequisites})},_closePrerequisiteScreen:function(){this._ui.screen.removeClass("out").addClass("ui-screen-hidden")},_closePrerequisiteContainer:function(){this._ui.container.removeClass("reverse out").addClass("ui-popup-hidden ui-popup-truncate").removeAttr("style")},_closePrerequisitesDone:function(){var b=this._ui.container,d=this.element.attr("id");b.removeAttr("tabindex"),a.mobile.popup.active=c,a(":focus",b[0]).add(b[0]).blur(),d&&this.document.find("[aria-haspopup='true'][aria-owns='"+d+"']").attr("aria-expanded",!1),this._trigger("afterclose")},_close:function(b){this._ui.container.removeClass("ui-popup-active"),this._page.removeClass("ui-popup-open"),this._isOpen=!1,this._createPrerequisites(a.proxy(this,"_closePrerequisiteScreen"),a.proxy(this,"_closePrerequisiteContainer"),a.proxy(this,"_closePrerequisitesDone")),this._animate({additionalCondition:this._ui.screen.hasClass("in"),transition:b?"none":this._currentTransition,classToRemove:"in",screenClassToAdd:"out",containerClassToAdd:"reverse out",applyTransition:!0,prerequisites:this._prerequisites})},_unenhance:function(){this.options.enhanced||(this._setOptions({theme:a.mobile.popup.prototype.options.theme}),this.element.detach().insertAfter(this._ui.placeholder).removeClass("ui-popup ui-overlay-shadow ui-corner-all ui-body-inherit"),this._ui.screen.remove(),this._ui.container.remove(),this._ui.placeholder.remove())},_destroy:function(){return a.mobile.popup.active===this?(this.element.one("popupafterclose",a.proxy(this,"_unenhance")),this.close()):this._unenhance(),this},_closePopup:function(c,d){var e,f,g=this.options,h=!1;c&&c.isDefaultPrevented()||a.mobile.popup.active!==this||(b.scrollTo(0,this._scrollTop),c&&"pagebeforechange"===c.type&&d&&(e="string"==typeof d.toPage?d.toPage:d.toPage.jqmData("url"),e=a.mobile.path.parseUrl(e),f=e.pathname+e.search+e.hash,this._myUrl!==a.mobile.path.makeUrlAbsolute(f)?h=!0:c.preventDefault()),this.window.off(g.closeEvents),this.element.undelegate(g.closeLinkSelector,g.closeLinkEvents),this._close(h))},_bindContainerClose:function(){this.window.on(this.options.closeEvents,a.proxy(this,"_closePopup"))},widget:function(){return this._ui.container},open:function(b){var c,d,e,f,g,h,i=this,j=this.options;return a.mobile.popup.active||j.disabled?this:(a.mobile.popup.active=this,this._scrollTop=this.window.scrollTop(),j.history?(h=a.mobile.navigate.history,d=a.mobile.dialogHashKey,e=a.mobile.activePage,f=e?e.hasClass("ui-dialog"):!1,this._myUrl=c=h.getActive().url,(g=c.indexOf(d)>-1&&!f&&h.activeIndex>0)?(i._open(b),i._bindContainerClose(),this):(-1!==c.indexOf(d)||f?c=a.mobile.path.parseLocation().hash+d:c+=c.indexOf("#")>-1?d:"#"+d,0===h.activeIndex&&c===h.initialDst&&(c+=d),this.window.one("beforenavigate",function(a){a.preventDefault(),i._open(b),i._bindContainerClose()}),this.urlAltered=!0,a.mobile.navigate(c,{role:"dialog"}),this)):(i._open(b),i._bindContainerClose(),i.element.delegate(j.closeLinkSelector,j.closeLinkEvents,function(a){i.close(),a.preventDefault()}),this))},close:function(){return a.mobile.popup.active!==this?this:(this._scrollTop=this.window.scrollTop(),this.options.history&&this.urlAltered?(a.mobile.back(),this.urlAltered=!1):this._closePopup(),this)}}),a.mobile.popup.handleLink=function(b){var c,d=a.mobile.path,e=a(d.hashToSelector(d.parseUrl(b.attr("href")).hash)).first();e.length>0&&e.data("mobile-popup")&&(c=b.offset(),e.popup("open",{x:c.left+b.outerWidth()/2,y:c.top+b.outerHeight()/2,transition:b.jqmData("transition"),positionTo:b.jqmData("position-to")})),setTimeout(function(){b.removeClass(a.mobile.activeBtnClass)},300)},a.mobile.document.on("pagebeforechange",function(b,c){"popup"===c.options.role&&(a.mobile.popup.handleLink(c.options.link),b.preventDefault())})}(a),function(a,b){var d=".ui-disabled,.ui-state-disabled,.ui-li-divider,.ui-screen-hidden,:jqmData(role='placeholder')",e=function(a,b,c){var e=a[c+"All"]().not(d).first();e.length&&(b.blur().attr("tabindex","-1"),e.find("a").first().focus())};a.widget("mobile.selectmenu",a.mobile.selectmenu,{_create:function(){var a=this.options;return a.nativeMenu=a.nativeMenu||this.element.parents(":jqmData(role='popup'),:mobile-popup").length>0,this._super()},_handleSelectFocus:function(){this.element.blur(),this.button.focus()},_handleKeydown:function(a){this._super(a),this._handleButtonVclickKeydown(a)},_handleButtonVclickKeydown:function(b){this.options.disabled||this.isOpen||("vclick"===b.type||b.keyCode&&(b.keyCode===a.mobile.keyCode.ENTER||b.keyCode===a.mobile.keyCode.SPACE))&&(this._decideFormat(),"overlay"===this.menuType?this.button.attr("href","#"+this.popupId).attr("data-"+(a.mobile.ns||"")+"rel","popup"):this.button.attr("href","#"+this.dialogId).attr("data-"+(a.mobile.ns||"")+"rel","dialog"),this.isOpen=!0)},_handleListFocus:function(b){var c="focusin"===b.type?{tabindex:"0",event:"vmouseover"}:{tabindex:"-1",event:"vmouseout"};a(b.target).attr("tabindex",c.tabindex).trigger(c.event)},_handleListKeydown:function(b){var c=a(b.target),d=c.closest("li");switch(b.keyCode){case 38:return e(d,c,"prev"),!1;case 40:return e(d,c,"next"),!1;case 13:case 32:return c.trigger("click"),!1}},_handleMenuPageHide:function(){this.thisPage.page("bindRemove")},_handleHeaderCloseClick:function(){return"overlay"===this.menuType?(this.close(),!1):void 0},build:function(){var c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w=this.options;return w.nativeMenu?this._super():(v=this,c=this.selectId,d=c+"-listbox",e=c+"-dialog",f=this.label,g=this.element.closest(".ui-page"),h=this.element[0].multiple,i=c+"-menu",j=w.theme?" data-"+a.mobile.ns+"theme='"+w.theme+"'":"",k=w.overlayTheme||w.theme||null,l=k?" data-"+a.mobile.ns+"overlay-theme='"+k+"'":"",m=w.dividerTheme&&h?" data-"+a.mobile.ns+"divider-theme='"+w.dividerTheme+"'":"",n=a("<div data-"+a.mobile.ns+"role='dialog' class='ui-selectmenu' id='"+e+"'"+j+l+"><div data-"+a.mobile.ns+"role='header'><div class='ui-title'>"+f.getEncodedText()+"</div></div><div data-"+a.mobile.ns+"role='content'></div></div>"),o=a("<div id='"+d+"' class='ui-selectmenu'></div>").insertAfter(this.select).popup({theme:w.overlayTheme}),p=a("<ul class='ui-selectmenu-list' id='"+i+"' role='listbox' aria-labelledby='"+this.buttonId+"'"+j+m+"></ul>").appendTo(o),q=a("<div class='ui-header ui-bar-"+(w.theme?w.theme:"inherit")+"'></div>").prependTo(o),r=a("<h1 class='ui-title'></h1>").appendTo(q),this.isMultiple&&(u=a("<a>",{role:"button",text:w.closeText,href:"#","class":"ui-btn ui-corner-all ui-btn-left ui-btn-icon-notext ui-icon-delete"}).appendTo(q)),a.extend(this,{selectId:c,menuId:i,popupId:d,dialogId:e,thisPage:g,menuPage:n,label:f,isMultiple:h,theme:w.theme,listbox:o,list:p,header:q,headerTitle:r,headerClose:u,menuPageContent:s,menuPageClose:t,placeholder:""}),this.refresh(),this._origTabIndex===b&&(this._origTabIndex=null===this.select[0].getAttribute("tabindex")?!1:this.select.attr("tabindex")),this.select.attr("tabindex","-1"),this._on(this.select,{focus:"_handleSelectFocus"}),this._on(this.button,{vclick:"_handleButtonVclickKeydown"}),this.list.attr("role","listbox"),this._on(this.list,{focusin:"_handleListFocus",focusout:"_handleListFocus",keydown:"_handleListKeydown"}),this.list.delegate("li:not(.ui-disabled,.ui-state-disabled,.ui-li-divider)","click",function(b){var c=v.select[0].selectedIndex,d=a.mobile.getAttribute(this,"option-index"),e=v._selectOptions().eq(d)[0];e.selected=v.isMultiple?!e.selected:!0,v.isMultiple&&a(this).find("a").toggleClass("ui-checkbox-on",e.selected).toggleClass("ui-checkbox-off",!e.selected),(v.isMultiple||c!==d)&&v.select.trigger("change"),v.isMultiple?v.list.find("li:not(.ui-li-divider)").eq(d).find("a").first().focus():v.close(),b.preventDefault()}),this._on(this.menuPage,{pagehide:"_handleMenuPageHide"}),this._on(this.listbox,{popupafterclose:"close"}),this.isMultiple&&this._on(this.headerClose,{click:"_handleHeaderCloseClick"}),this)},_isRebuildRequired:function(){var a=this.list.find("li"),b=this._selectOptions().not(".ui-screen-hidden");return b.text()!==a.text()},selected:function(){return this._selectOptions().filter(":selected:not( :jqmData(placeholder='true') )")},refresh:function(b){var c,d;return this.options.nativeMenu?this._super(b):(c=this,(b||this._isRebuildRequired())&&c._buildList(),d=this.selectedIndices(),c.setButtonText(),c.setButtonCount(),void c.list.find("li:not(.ui-li-divider)").find("a").removeClass(a.mobile.activeBtnClass).end().attr("aria-selected",!1).each(function(b){if(a.inArray(b,d)>-1){var e=a(this);e.attr("aria-selected",!0),c.isMultiple?e.find("a").removeClass("ui-checkbox-off").addClass("ui-checkbox-on"):e.hasClass("ui-screen-hidden")?e.next().find("a").addClass(a.mobile.activeBtnClass):e.find("a").addClass(a.mobile.activeBtnClass)}}))},close:function(){if(!this.options.disabled&&this.isOpen){var a=this;"page"===a.menuType?(a.menuPage.dialog("close"),a.list.appendTo(a.listbox)):a.listbox.popup("close"),a._focusButton(),a.isOpen=!1}},open:function(){this.button.click()},_focusMenuItem:function(){var b=this.list.find("a."+a.mobile.activeBtnClass);0===b.length&&(b=this.list.find("li:not("+d+") a.ui-btn")),b.first().focus()},_decideFormat:function(){var b=this,c=this.window,d=b.list.parent(),e=d.outerHeight(),f=c.scrollTop(),g=b.button.offset().top,h=c.height();e>h-80||!a.support.scrollTop?(b.menuPage.appendTo(a.mobile.pageContainer).page(),b.menuPageContent=b.menuPage.find(".ui-content"),b.menuPageClose=b.menuPage.find(".ui-header a"),b.thisPage.unbind("pagehide.remove"),0===f&&g>h&&b.thisPage.one("pagehide",function(){a(this).jqmData("lastScroll",g)}),b.menuPage.one({pageshow:a.proxy(this,"_focusMenuItem"),pagehide:a.proxy(this,"close")}),b.menuType="page",b.menuPageContent.append(b.list),b.menuPage.find("div .ui-title").text(b.label.text())):(b.menuType="overlay",b.listbox.one({popupafteropen:a.proxy(this,"_focusMenuItem")}))},_buildList:function(){var b,d,e,f,g,h,i,j,k,l,m,n,o,p,q=this,r=this.options,s=this.placeholder,t=!0,u="false",v="data-"+a.mobile.ns,w=v+"option-index",x=v+"icon",y=v+"role",z=v+"placeholder",A=c.createDocumentFragment(),B=!1;for(q.list.empty().filter(".ui-listview").listview("destroy"),b=this._selectOptions(),d=b.length,e=this.select[0],g=0;d>g;g++,B=!1)h=b[g],i=a(h),i.hasClass("ui-screen-hidden")||(j=h.parentNode,k=i.text(),l=c.createElement("a"),m=[],l.setAttribute("href","#"),l.appendChild(c.createTextNode(k)),j!==e&&"optgroup"===j.nodeName.toLowerCase()&&(n=j.getAttribute("label"),n!==f&&(o=c.createElement("li"),o.setAttribute(y,"list-divider"),o.setAttribute("role","option"),o.setAttribute("tabindex","-1"),o.appendChild(c.createTextNode(n)),A.appendChild(o),f=n)),!t||h.getAttribute("value")&&0!==k.length&&!i.jqmData("placeholder")||(t=!1,B=!0,null===h.getAttribute(z)&&(this._removePlaceholderAttr=!0),h.setAttribute(z,!0),r.hidePlaceholderMenuItems&&m.push("ui-screen-hidden"),s!==k&&(s=q.placeholder=k)),p=c.createElement("li"),h.disabled&&(m.push("ui-state-disabled"),p.setAttribute("aria-disabled",!0)),p.setAttribute(w,g),p.setAttribute(x,u),B&&p.setAttribute(z,!0),p.className=m.join(" "),p.setAttribute("role","option"),l.setAttribute("tabindex","-1"),this.isMultiple&&a(l).addClass("ui-btn ui-checkbox-off ui-btn-icon-right"),p.appendChild(l),A.appendChild(p));q.list[0].appendChild(A),this.isMultiple||s.length?this.headerTitle.text(this.placeholder):this.header.addClass("ui-screen-hidden"),q.list.listview()},_button:function(){return this.options.nativeMenu?this._super():a("<a>",{href:"#",role:"button",id:this.buttonId,"aria-haspopup":"true","aria-owns":this.menuId})},_destroy:function(){this.options.nativeMenu||(this.close(),this._origTabIndex!==b&&(this._origTabIndex!==!1?this.select.attr("tabindex",this._origTabIndex):this.select.removeAttr("tabindex")),this._removePlaceholderAttr&&this._selectOptions().removeAttr("data-"+a.mobile.ns+"placeholder"),this.listbox.remove(),this.menuPage.remove()),this._super()}})}(a),function(a,b){function c(a,b){var c=b?b:[];return c.push("ui-btn"),a.theme&&c.push("ui-btn-"+a.theme),a.icon&&(c=c.concat(["ui-icon-"+a.icon,"ui-btn-icon-"+a.iconpos]),a.iconshadow&&c.push("ui-shadow-icon")),a.inline&&c.push("ui-btn-inline"),a.shadow&&c.push("ui-shadow"),a.corners&&c.push("ui-corner-all"),a.mini&&c.push("ui-mini"),c}function d(a){var c,d,e,g=!1,h=!0,i={icon:"",inline:!1,shadow:!1,corners:!1,iconshadow:!1,mini:!1},j=[];for(a=a.split(" "),c=0;c<a.length;c++)e=!0,d=f[a[c]],d!==b?(e=!1,i[d]=!0):0===a[c].indexOf("ui-btn-icon-")?(e=!1,h=!1,i.iconpos=a[c].substring(12)):0===a[c].indexOf("ui-icon-")?(e=!1,i.icon=a[c].substring(8)):0===a[c].indexOf("ui-btn-")&&8===a[c].length?(e=!1,i.theme=a[c].substring(7)):"ui-btn"===a[c]&&(e=!1,g=!0),e&&j.push(a[c]);return h&&(i.icon=""),{options:i,unknownClasses:j,alreadyEnhanced:g}}function e(a){return"-"+a.toLowerCase()}var f={"ui-shadow":"shadow","ui-corner-all":"corners","ui-btn-inline":"inline","ui-shadow-icon":"iconshadow","ui-mini":"mini"},g=function(){var c=a.mobile.getAttribute.apply(this,arguments);return null==c?b:c},h=/[A-Z]/g;a.fn.buttonMarkup=function(f,i){var j,k,l,m,n,o=a.fn.buttonMarkup.defaults;for(j=0;j<this.length;j++){if(l=this[j],k=i?{alreadyEnhanced:!1,unknownClasses:[]}:d(l.className),m=a.extend({},k.alreadyEnhanced?k.options:{},f),!k.alreadyEnhanced)for(n in o)m[n]===b&&(m[n]=g(l,n.replace(h,e)));l.className=c(a.extend({},o,m),k.unknownClasses).join(" "),"button"!==l.tagName.toLowerCase()&&l.setAttribute("role","button")}return this},a.fn.buttonMarkup.defaults={icon:"",iconpos:"left",theme:null,inline:!1,shadow:!0,corners:!0,iconshadow:!1,mini:!1},a.extend(a.fn.buttonMarkup,{initSelector:"a:jqmData(role='button'), .ui-bar > a, .ui-bar > :jqmData(role='controlgroup') > a, button"})}(a),function(a,b){a.widget("mobile.controlgroup",a.extend({options:{enhanced:!1,theme:null,shadow:!1,corners:!0,excludeInvisible:!0,type:"vertical",mini:!1},_create:function(){var b=this.element,c=this.options;a.fn.buttonMarkup&&this.element.find(a.fn.buttonMarkup.initSelector).buttonMarkup(),a.each(this._childWidgets,a.proxy(function(b,c){a.mobile[c]&&this.element.find(a.mobile[c].initSelector).not(a.mobile.page.prototype.keepNativeSelector())[c]()},this)),a.extend(this,{_ui:null,_initialRefresh:!0}),this._ui=c.enhanced?{groupLegend:b.children(".ui-controlgroup-label").children(),childWrapper:b.children(".ui-controlgroup-controls")}:this._enhance()},_childWidgets:["checkboxradio","selectmenu","button"],_themeClassFromOption:function(a){return a?"none"===a?"":"ui-group-theme-"+a:""},_enhance:function(){var b=this.element,c=this.options,d={groupLegend:b.children("legend"),childWrapper:b.addClass("ui-controlgroup ui-controlgroup-"+("horizontal"===c.type?"horizontal":"vertical")+" "+this._themeClassFromOption(c.theme)+" "+(c.corners?"ui-corner-all ":"")+(c.mini?"ui-mini ":"")).wrapInner("<div class='ui-controlgroup-controls "+(c.shadow===!0?"ui-shadow":"")+"'></div>").children()};return d.groupLegend.length>0&&a("<div role='heading' class='ui-controlgroup-label'></div>").append(d.groupLegend).prependTo(b),d},_init:function(){this.refresh()},_setOptions:function(a){var c,d,e=this.element;return a.type!==b&&(e.removeClass("ui-controlgroup-horizontal ui-controlgroup-vertical").addClass("ui-controlgroup-"+("horizontal"===a.type?"horizontal":"vertical")),c=!0),a.theme!==b&&e.removeClass(this._themeClassFromOption(this.options.theme)).addClass(this._themeClassFromOption(a.theme)),a.corners!==b&&e.toggleClass("ui-corner-all",a.corners),a.mini!==b&&e.toggleClass("ui-mini",a.mini),a.shadow!==b&&this._ui.childWrapper.toggleClass("ui-shadow",a.shadow),a.excludeInvisible!==b&&(this.options.excludeInvisible=a.excludeInvisible,c=!0),d=this._super(a),c&&this.refresh(),d},container:function(){return this._ui.childWrapper},refresh:function(){var b=this.container(),c=b.find(".ui-btn").not(".ui-slider-handle"),d=this._initialRefresh;a.mobile.checkboxradio&&b.find(":mobile-checkboxradio").checkboxradio("refresh"),this._addFirstLastClasses(c,this.options.excludeInvisible?this._getVisibles(c,d):c,d),this._initialRefresh=!1},_destroy:function(){var a,b,c=this.options;return c.enhanced?this:(a=this._ui,b=this.element.removeClass("ui-controlgroup ui-controlgroup-horizontal ui-controlgroup-vertical ui-corner-all ui-mini "+this._themeClassFromOption(c.theme)).find(".ui-btn").not(".ui-slider-handle"),this._removeFirstLastClasses(b),a.groupLegend.unwrap(),void a.childWrapper.children().unwrap())}},a.mobile.behaviors.addFirstLastClasses))}(a),function(a,b){a.widget("mobile.toolbar",{initSelector:":jqmData(role='footer'), :jqmData(role='header')",options:{theme:null,addBackBtn:!1,backBtnTheme:null,backBtnText:"Back"},_create:function(){var b,c,d=this.element.is(":jqmData(role='header')")?"header":"footer",e=this.element.closest(".ui-page");0===e.length&&(e=!1,this._on(this.document,{pageshow:"refresh"})),a.extend(this,{role:d,page:e,leftbtn:b,rightbtn:c}),this.element.attr("role","header"===d?"banner":"contentinfo").addClass("ui-"+d),this.refresh(),this._setOptions(this.options)},_setOptions:function(c){if(c.addBackBtn!==b&&(this.options.addBackBtn&&"header"===this.role&&a(".ui-page").length>1&&this.page[0].getAttribute("data-"+a.mobile.ns+"url")!==a.mobile.path.stripHash(location.hash)&&!this.leftbtn?this._addBackButton():this.element.find(".ui-toolbar-back-btn").remove()),null!=c.backBtnTheme&&this.element.find(".ui-toolbar-back-btn").addClass("ui-btn ui-btn-"+c.backBtnTheme),c.backBtnText!==b&&this.element.find(".ui-toolbar-back-btn .ui-btn-text").text(c.backBtnText),c.theme!==b){var d=this.options.theme?this.options.theme:"inherit",e=c.theme?c.theme:"inherit";this.element.removeClass("ui-bar-"+d).addClass("ui-bar-"+e)}this._super(c)},refresh:function(){"header"===this.role&&this._addHeaderButtonClasses(),this.page||(this._setRelative(),"footer"===this.role&&this.element.appendTo("body")),this._addHeadingClasses(),this._btnMarkup()},_setRelative:function(){a("[data-"+a.mobile.ns+"role='page']").css({position:"relative"})},_btnMarkup:function(){this.element.children("a").filter(":not([data-"+a.mobile.ns+"role='none'])").attr("data-"+a.mobile.ns+"role","button"),this.element.trigger("create")},_addHeaderButtonClasses:function(){var a=this.element.children("a, button");this.leftbtn=a.hasClass("ui-btn-left"),this.rightbtn=a.hasClass("ui-btn-right"),this.leftbtn=this.leftbtn||a.eq(0).not(".ui-btn-right").addClass("ui-btn-left").length,this.rightbtn=this.rightbtn||a.eq(1).addClass("ui-btn-right").length},_addBackButton:function(){var b=this.options,c=b.backBtnTheme||b.theme;a("<a role='button' href='javascript:void(0);' class='ui-btn ui-corner-all ui-shadow ui-btn-left "+(c?"ui-btn-"+c+" ":"")+"ui-toolbar-back-btn ui-icon-carat-l ui-btn-icon-left' data-"+a.mobile.ns+"rel='back'>"+b.backBtnText+"</a>").prependTo(this.element)},_addHeadingClasses:function(){this.element.children("h1, h2, h3, h4, h5, h6").addClass("ui-title").attr({role:"heading","aria-level":"1"})}})}(a),function(a,b){a.widget("mobile.toolbar",a.mobile.toolbar,{options:{position:null,visibleOnPageShow:!0,disablePageZoom:!0,transition:"slide",fullscreen:!1,tapToggle:!0,tapToggleBlacklist:"a, button, input, select, textarea, .ui-header-fixed, .ui-footer-fixed, .ui-flipswitch, .ui-popup, .ui-panel, .ui-panel-dismiss-open",hideDuringFocus:"input, textarea, select",updatePagePadding:!0,trackPersistentToolbars:!0,supportBlacklist:function(){return!a.support.fixedPosition}},_create:function(){this._super(),"fixed"!==this.options.position||this.options.supportBlacklist()||this._makeFixed()},_makeFixed:function(){this.element.addClass("ui-"+this.role+"-fixed"),this.updatePagePadding(),this._addTransitionClass(),this._bindPageEvents(),this._bindToggleHandlers()},_setOptions:function(c){if("fixed"===c.position&&"fixed"!==this.options.position&&this._makeFixed(),"fixed"===this.options.position&&!this.options.supportBlacklist()){var d=this.page?this.page:a(".ui-page-active").length>0?a(".ui-page-active"):a(".ui-page").eq(0);c.fullscreen!==b&&(c.fullscreen?(this.element.addClass("ui-"+this.role+"-fullscreen"),d.addClass("ui-page-"+this.role+"-fullscreen")):(this.element.removeClass("ui-"+this.role+"-fullscreen"),d.removeClass("ui-page-"+this.role+"-fullscreen").addClass("ui-page-"+this.role+"-fixed")))}this._super(c)},_addTransitionClass:function(){var a=this.options.transition;a&&"none"!==a&&("slide"===a&&(a=this.element.hasClass("ui-header")?"slidedown":"slideup"),this.element.addClass(a))},_bindPageEvents:function(){var a=this.page?this.element.closest(".ui-page"):this.document;this._on(a,{pagebeforeshow:"_handlePageBeforeShow",webkitAnimationStart:"_handleAnimationStart",animationstart:"_handleAnimationStart",updatelayout:"_handleAnimationStart",pageshow:"_handlePageShow",pagebeforehide:"_handlePageBeforeHide"})},_handlePageBeforeShow:function(){var b=this.options;b.disablePageZoom&&a.mobile.zoom.disable(!0),b.visibleOnPageShow||this.hide(!0)},_handleAnimationStart:function(){this.options.updatePagePadding&&this.updatePagePadding(this.page?this.page:".ui-page-active")},_handlePageShow:function(){this.updatePagePadding(this.page?this.page:".ui-page-active"),this.options.updatePagePadding&&this._on(this.window,{throttledresize:"updatePagePadding"})},_handlePageBeforeHide:function(b,c){var d,e,f,g,h=this.options;h.disablePageZoom&&a.mobile.zoom.enable(!0),h.updatePagePadding&&this._off(this.window,"throttledresize"),h.trackPersistentToolbars&&(d=a(".ui-footer-fixed:jqmData(id)",this.page),e=a(".ui-header-fixed:jqmData(id)",this.page),f=d.length&&c.nextPage&&a(".ui-footer-fixed:jqmData(id='"+d.jqmData("id")+"')",c.nextPage)||a(),g=e.length&&c.nextPage&&a(".ui-header-fixed:jqmData(id='"+e.jqmData("id")+"')",c.nextPage)||a(),(f.length||g.length)&&(f.add(g).appendTo(a.mobile.pageContainer),c.nextPage.one("pageshow",function(){g.prependTo(this),f.appendTo(this)})))},_visible:!0,updatePagePadding:function(c){var d=this.element,e="header"===this.role,f=parseFloat(d.css(e?"top":"bottom"));this.options.fullscreen||(c=c&&c.type===b&&c||this.page||d.closest(".ui-page"),c=this.page?this.page:".ui-page-active",a(c).css("padding-"+(e?"top":"bottom"),d.outerHeight()+f))},_useTransition:function(b){var c=this.window,d=this.element,e=c.scrollTop(),f=d.height(),g=this.page?d.closest(".ui-page").height():a(".ui-page-active").height(),h=a.mobile.getScreenHeight();return!b&&(this.options.transition&&"none"!==this.options.transition&&("header"===this.role&&!this.options.fullscreen&&e>f||"footer"===this.role&&!this.options.fullscreen&&g-f>e+h)||this.options.fullscreen)},show:function(a){var b="ui-fixed-hidden",c=this.element;this._useTransition(a)?c.removeClass("out "+b).addClass("in").animationComplete(function(){c.removeClass("in")}):c.removeClass(b),this._visible=!0},hide:function(a){var b="ui-fixed-hidden",c=this.element,d="out"+("slide"===this.options.transition?" reverse":"");this._useTransition(a)?c.addClass(d).removeClass("in").animationComplete(function(){c.addClass(b).removeClass(d)}):c.addClass(b).removeClass(d),this._visible=!1},toggle:function(){this[this._visible?"hide":"show"]()},_bindToggleHandlers:function(){var b,c,d=this,e=d.options,f=!0,g=this.page?this.page:a(".ui-page");g.bind("vclick",function(b){e.tapToggle&&!a(b.target).closest(e.tapToggleBlacklist).length&&d.toggle()}).bind("focusin focusout",function(g){screen.width<1025&&a(g.target).is(e.hideDuringFocus)&&!a(g.target).closest(".ui-header-fixed, .ui-footer-fixed").length&&("focusout"!==g.type||f?"focusin"===g.type&&f&&(clearTimeout(b),f=!1,c=setTimeout(function(){d.hide()},0)):(f=!0,clearTimeout(c),b=setTimeout(function(){d.show()},0)))})},_setRelative:function(){"fixed"!==this.options.position&&a("[data-"+a.mobile.ns+"role='page']").css({position:"relative"})},_destroy:function(){var a=this.element,b=a.hasClass("ui-header");a.closest(".ui-page").css("padding-"+(b?"top":"bottom"),""),a.removeClass("ui-header-fixed ui-footer-fixed ui-header-fullscreen ui-footer-fullscreen in out fade slidedown slideup ui-fixed-hidden"),a.closest(".ui-page").removeClass("ui-page-header-fixed ui-page-footer-fixed ui-page-header-fullscreen ui-page-footer-fullscreen")}})}(a),function(a){a.widget("mobile.toolbar",a.mobile.toolbar,{_makeFixed:function(){this._super(),this._workarounds()},_workarounds:function(){var a=navigator.userAgent,b=navigator.platform,c=a.match(/AppleWebKit\/([0-9]+)/),d=!!c&&c[1],e=null,f=this;if(b.indexOf("iPhone")>-1||b.indexOf("iPad")>-1||b.indexOf("iPod")>-1)e="ios";else{if(!(a.indexOf("Android")>-1))return;e="android"}if("ios"===e)f._bindScrollWorkaround();else{if(!("android"===e&&d&&534>d))return;f._bindScrollWorkaround(),f._bindListThumbWorkaround()}},_viewportOffset:function(){var a=this.element,b=a.hasClass("ui-header"),c=Math.abs(a.offset().top-this.window.scrollTop());return b||(c=Math.round(c-this.window.height()+a.outerHeight())-60),c},_bindScrollWorkaround:function(){var a=this;this._on(this.window,{scrollstop:function(){var b=a._viewportOffset();b>2&&a._visible&&a._triggerRedraw()}})},_bindListThumbWorkaround:function(){this.element.closest(".ui-page").addClass("ui-android-2x-fixed")},_triggerRedraw:function(){var b=parseFloat(a(".ui-page-active").css("padding-bottom"));a(".ui-page-active").css("padding-bottom",b+1+"px"),setTimeout(function(){a(".ui-page-active").css("padding-bottom",b+"px")},0)},destroy:function(){this._super(),this.element.closest(".ui-page-active").removeClass("ui-android-2x-fix")}})}(a),function(a,b){function c(){var a=e.clone(),b=a.eq(0),c=a.eq(1),d=c.children();return{arEls:c.add(b),gd:b,ct:c,ar:d}}var d=a.mobile.browser.oldIE&&a.mobile.browser.oldIE<=8,e=a("<div class='ui-popup-arrow-guide'></div><div class='ui-popup-arrow-container"+(d?" ie":"")+"'><div class='ui-popup-arrow'></div></div>");a.widget("mobile.popup",a.mobile.popup,{options:{arrow:""},_create:function(){var a,b=this._super();return this.options.arrow&&(this._ui.arrow=a=this._addArrow()),b},_addArrow:function(){var a,b=this.options,d=c();return a=this._themeClassFromOption("ui-body-",b.theme),d.ar.addClass(a+(b.shadow?" ui-overlay-shadow":"")),d.arEls.hide().appendTo(this.element),d},_unenhance:function(){var a=this._ui.arrow;return a&&a.arEls.remove(),this._super()},_tryAnArrow:function(a,b,c,d,e){var f,g,h,i={},j={};return d.arFull[a.dimKey]>d.guideDims[a.dimKey]?e:(i[a.fst]=c[a.fst]+(d.arHalf[a.oDimKey]+d.menuHalf[a.oDimKey])*a.offsetFactor-d.contentBox[a.fst]+(d.clampInfo.menuSize[a.oDimKey]-d.contentBox[a.oDimKey])*a.arrowOffsetFactor,i[a.snd]=c[a.snd],f=d.result||this._calculateFinalLocation(i,d.clampInfo),g={x:f.left,y:f.top},j[a.fst]=g[a.fst]+d.contentBox[a.fst]+a.tipOffset,j[a.snd]=Math.max(f[a.prop]+d.guideOffset[a.prop]+d.arHalf[a.dimKey],Math.min(f[a.prop]+d.guideOffset[a.prop]+d.guideDims[a.dimKey]-d.arHalf[a.dimKey],c[a.snd])),h=Math.abs(c.x-j.x)+Math.abs(c.y-j.y),(!e||h<e.diff)&&(j[a.snd]-=d.arHalf[a.dimKey]+f[a.prop]+d.contentBox[a.snd],e={dir:b,diff:h,result:f,posProp:a.prop,posVal:j[a.snd]}),e)},_getPlacementState:function(a){var b,c,d=this._ui.arrow,e={clampInfo:this._clampPopupWidth(!a),arFull:{cx:d.ct.width(),cy:d.ct.height()},guideDims:{cx:d.gd.width(),cy:d.gd.height()},guideOffset:d.gd.offset()};return b=this.element.offset(),d.gd.css({left:0,top:0,right:0,bottom:0}),c=d.gd.offset(),e.contentBox={x:c.left-b.left,y:c.top-b.top,cx:d.gd.width(),cy:d.gd.height()},d.gd.removeAttr("style"),e.guideOffset={left:e.guideOffset.left-b.left,top:e.guideOffset.top-b.top},e.arHalf={cx:e.arFull.cx/2,cy:e.arFull.cy/2},e.menuHalf={cx:e.clampInfo.menuSize.cx/2,cy:e.clampInfo.menuSize.cy/2},e},_placementCoords:function(b){var c,e,f,g,h,i=this.options.arrow,j=this._ui.arrow;return j?(j.arEls.show(),h={},c=this._getPlacementState(!0),f={l:{fst:"x",snd:"y",prop:"top",dimKey:"cy",oDimKey:"cx",offsetFactor:1,tipOffset:-c.arHalf.cx,arrowOffsetFactor:0},r:{fst:"x",snd:"y",prop:"top",dimKey:"cy",oDimKey:"cx",offsetFactor:-1,tipOffset:c.arHalf.cx+c.contentBox.cx,arrowOffsetFactor:1},b:{fst:"y",snd:"x",prop:"left",dimKey:"cx",oDimKey:"cy",offsetFactor:-1,tipOffset:c.arHalf.cy+c.contentBox.cy,arrowOffsetFactor:1},t:{fst:"y",snd:"x",prop:"left",dimKey:"cx",oDimKey:"cy",offsetFactor:1,tipOffset:-c.arHalf.cy,arrowOffsetFactor:0}},a.each((i===!0?"l,t,r,b":i).split(","),a.proxy(function(a,d){e=this._tryAnArrow(f[d],d,b,c,e)},this)),e?(j.ct.removeClass("ui-popup-arrow-l ui-popup-arrow-t ui-popup-arrow-r ui-popup-arrow-b").addClass("ui-popup-arrow-"+e.dir).removeAttr("style").css(e.posProp,e.posVal).show(),d||(g=this.element.offset(),h[f[e.dir].fst]=j.ct.offset(),h[f[e.dir].snd]={left:g.left+c.contentBox.x,top:g.top+c.contentBox.y}),e.result):(j.arEls.hide(),this._super(b))):this._super(b)
},_setOptions:function(a){var c,d=this.options.theme,e=this._ui.arrow,f=this._super(a);if(a.arrow!==b){if(!e&&a.arrow)return void(this._ui.arrow=this._addArrow());e&&!a.arrow&&(e.arEls.remove(),this._ui.arrow=null)}return e=this._ui.arrow,e&&(a.theme!==b&&(d=this._themeClassFromOption("ui-body-",d),c=this._themeClassFromOption("ui-body-",a.theme),e.ar.removeClass(d).addClass(c)),a.shadow!==b&&e.ar.toggleClass("ui-overlay-shadow",a.shadow)),f},_destroy:function(){var a=this._ui.arrow;return a&&a.arEls.remove(),this._super()}})}(a),function(a,c){a.widget("mobile.panel",{options:{classes:{panel:"ui-panel",panelOpen:"ui-panel-open",panelClosed:"ui-panel-closed",panelFixed:"ui-panel-fixed",panelInner:"ui-panel-inner",modal:"ui-panel-dismiss",modalOpen:"ui-panel-dismiss-open",pageContainer:"ui-panel-page-container",pageWrapper:"ui-panel-wrapper",pageFixedToolbar:"ui-panel-fixed-toolbar",pageContentPrefix:"ui-panel-page-content",animate:"ui-panel-animate"},animate:!0,theme:null,position:"left",dismissible:!0,display:"reveal",swipeClose:!0,positionFixed:!1},_closeLink:null,_parentPage:null,_page:null,_modal:null,_panelInner:null,_wrapper:null,_fixedToolbars:null,_create:function(){var b=this.element,c=b.closest(".ui-page, :jqmData(role='page')");a.extend(this,{_closeLink:b.find(":jqmData(rel='close')"),_parentPage:c.length>0?c:!1,_openedPage:null,_page:this._getPage,_panelInner:this._getPanelInner(),_fixedToolbars:this._getFixedToolbars}),"overlay"!==this.options.display&&this._getWrapper(),this._addPanelClasses(),a.support.cssTransform3d&&this.options.animate&&this.element.addClass(this.options.classes.animate),this._bindUpdateLayout(),this._bindCloseEvents(),this._bindLinkListeners(),this._bindPageEvents(),this.options.dismissible&&this._createModal(),this._bindSwipeEvents()},_getPanelInner:function(){var a=this.element.find("."+this.options.classes.panelInner);return 0===a.length&&(a=this.element.children().wrapAll("<div class='"+this.options.classes.panelInner+"' />").parent()),a},_createModal:function(){var b=this,c=b._parentPage?b._parentPage.parent():b.element.parent();b._modal=a("<div class='"+b.options.classes.modal+"'></div>").on("mousedown",function(){b.close()}).appendTo(c)},_getPage:function(){var b=this._openedPage||this._parentPage||a("."+a.mobile.activePageClass);return b},_getWrapper:function(){var a=this._page().find("."+this.options.classes.pageWrapper);0===a.length&&(a=this._page().children(".ui-header:not(.ui-header-fixed), .ui-content:not(.ui-popup), .ui-footer:not(.ui-footer-fixed)").wrapAll("<div class='"+this.options.classes.pageWrapper+"'></div>").parent()),this._wrapper=a},_getFixedToolbars:function(){var b=a("body").children(".ui-header-fixed, .ui-footer-fixed"),c=this._page().find(".ui-header-fixed, .ui-footer-fixed"),d=b.add(c).addClass(this.options.classes.pageFixedToolbar);return d},_getPosDisplayClasses:function(a){return a+"-position-"+this.options.position+" "+a+"-display-"+this.options.display},_getPanelClasses:function(){var a=this.options.classes.panel+" "+this._getPosDisplayClasses(this.options.classes.panel)+" "+this.options.classes.panelClosed+" ui-body-"+(this.options.theme?this.options.theme:"inherit");return this.options.positionFixed&&(a+=" "+this.options.classes.panelFixed),a},_addPanelClasses:function(){this.element.addClass(this._getPanelClasses())},_handleCloseClickAndEatEvent:function(a){return a.isDefaultPrevented()?void 0:(a.preventDefault(),this.close(),!1)},_handleCloseClick:function(a){a.isDefaultPrevented()||this.close()},_bindCloseEvents:function(){this._on(this._closeLink,{click:"_handleCloseClick"}),this._on({"click a:jqmData(ajax='false')":"_handleCloseClick"})},_positionPanel:function(b){var c=this,d=c._panelInner.outerHeight(),e=d>a.mobile.getScreenHeight();e||!c.options.positionFixed?(e&&(c._unfixPanel(),a.mobile.resetActivePageHeight(d)),b&&this.window[0].scrollTo(0,a.mobile.defaultHomeScroll)):c._fixPanel()},_bindFixListener:function(){this._on(a(b),{throttledresize:"_positionPanel"})},_unbindFixListener:function(){this._off(a(b),"throttledresize")},_unfixPanel:function(){this.options.positionFixed&&a.support.fixedPosition&&this.element.removeClass(this.options.classes.panelFixed)},_fixPanel:function(){this.options.positionFixed&&a.support.fixedPosition&&this.element.addClass(this.options.classes.panelFixed)},_bindUpdateLayout:function(){var a=this;a.element.on("updatelayout",function(){a._open&&a._positionPanel()})},_bindLinkListeners:function(){this._on("body",{"click a":"_handleClick"})},_handleClick:function(b){var d,e=this.element.attr("id");return b.currentTarget.href.split("#")[1]===e&&e!==c?(b.preventDefault(),d=a(b.target),d.hasClass("ui-btn")&&(d.addClass(a.mobile.activeBtnClass),this.element.one("panelopen panelclose",function(){d.removeClass(a.mobile.activeBtnClass)})),this.toggle(),!1):void 0},_bindSwipeEvents:function(){var a=this,b=a._modal?a.element.add(a._modal):a.element;a.options.swipeClose&&("left"===a.options.position?b.on("swipeleft.panel",function(){a.close()}):b.on("swiperight.panel",function(){a.close()}))},_bindPageEvents:function(){var a=this;this.document.on("panelbeforeopen",function(b){a._open&&b.target!==a.element[0]&&a.close()}).on("keyup.panel",function(b){27===b.keyCode&&a._open&&a.close()}),this._parentPage||"overlay"===this.options.display||this._on(this.document,{pageshow:"_getWrapper"}),a._parentPage?this.document.on("pagehide",":jqmData(role='page')",function(){a._open&&a.close(!0)}):this.document.on("pagebeforehide",function(){a._open&&a.close(!0)})},_open:!1,_pageContentOpenClasses:null,_modalOpenClasses:null,open:function(b){if(!this._open){var c=this,d=c.options,e=function(){c.document.off("panelclose"),c._page().jqmData("panel","open"),a.support.cssTransform3d&&d.animate&&"overlay"!==d.display&&(c._wrapper.addClass(d.classes.animate),c._fixedToolbars().addClass(d.classes.animate)),!b&&a.support.cssTransform3d&&d.animate?c.element.animationComplete(f,"transition"):setTimeout(f,0),d.theme&&"overlay"!==d.display&&c._page().parent().addClass(d.classes.pageContainer+"-themed "+d.classes.pageContainer+"-"+d.theme),c.element.removeClass(d.classes.panelClosed).addClass(d.classes.panelOpen),c._positionPanel(!0),c._pageContentOpenClasses=c._getPosDisplayClasses(d.classes.pageContentPrefix),"overlay"!==d.display&&(c._page().parent().addClass(d.classes.pageContainer),c._wrapper.addClass(c._pageContentOpenClasses),c._fixedToolbars().addClass(c._pageContentOpenClasses)),c._modalOpenClasses=c._getPosDisplayClasses(d.classes.modal)+" "+d.classes.modalOpen,c._modal&&c._modal.addClass(c._modalOpenClasses).height(Math.max(c._modal.height(),c.document.height()))},f=function(){"overlay"!==d.display&&(c._wrapper.addClass(d.classes.pageContentPrefix+"-open"),c._fixedToolbars().addClass(d.classes.pageContentPrefix+"-open")),c._bindFixListener(),c._trigger("open"),c._openedPage=c._page()};c._trigger("beforeopen"),"open"===c._page().jqmData("panel")?c.document.on("panelclose",function(){e()}):e(),c._open=!0}},close:function(b){if(this._open){var c=this,d=this.options,e=function(){c.element.removeClass(d.classes.panelOpen),"overlay"!==d.display&&(c._wrapper.removeClass(c._pageContentOpenClasses),c._fixedToolbars().removeClass(c._pageContentOpenClasses)),!b&&a.support.cssTransform3d&&d.animate?c.element.animationComplete(f,"transition"):setTimeout(f,0),c._modal&&c._modal.removeClass(c._modalOpenClasses)},f=function(){d.theme&&"overlay"!==d.display&&c._page().parent().removeClass(d.classes.pageContainer+"-themed "+d.classes.pageContainer+"-"+d.theme),c.element.addClass(d.classes.panelClosed),"overlay"!==d.display&&(c._page().parent().removeClass(d.classes.pageContainer),c._wrapper.removeClass(d.classes.pageContentPrefix+"-open"),c._fixedToolbars().removeClass(d.classes.pageContentPrefix+"-open")),a.support.cssTransform3d&&d.animate&&"overlay"!==d.display&&(c._wrapper.removeClass(d.classes.animate),c._fixedToolbars().removeClass(d.classes.animate)),c._fixPanel(),c._unbindFixListener(),a.mobile.resetActivePageHeight(),c._page().jqmRemoveData("panel"),c._trigger("close"),c._openedPage=null};c._trigger("beforeclose"),e(),c._open=!1}},toggle:function(){this[this._open?"close":"open"]()},_destroy:function(){var b,c=this.options,d=a("body > :mobile-panel").length+a.mobile.activePage.find(":mobile-panel").length>1;"overlay"!==c.display&&(b=a("body > :mobile-panel").add(a.mobile.activePage.find(":mobile-panel")),0===b.not(".ui-panel-display-overlay").not(this.element).length&&this._wrapper.children().unwrap(),this._open&&(this._fixedToolbars().removeClass(c.classes.pageContentPrefix+"-open"),a.support.cssTransform3d&&c.animate&&this._fixedToolbars().removeClass(c.classes.animate),this._page().parent().removeClass(c.classes.pageContainer),c.theme&&this._page().parent().removeClass(c.classes.pageContainer+"-themed "+c.classes.pageContainer+"-"+c.theme))),d||this.document.off("panelopen panelclose"),this._open&&this._page().jqmRemoveData("panel"),this._panelInner.children().unwrap(),this.element.removeClass([this._getPanelClasses(),c.classes.panelOpen,c.classes.animate].join(" ")).off("swipeleft.panel swiperight.panel").off("panelbeforeopen").off("panelhide").off("keyup.panel").off("updatelayout"),this._modal&&this._modal.remove()}})}(a),function(a,b){a.widget("mobile.table",{options:{classes:{table:"ui-table"},enhanced:!1},_create:function(){this.options.enhanced||this.element.addClass(this.options.classes.table),a.extend(this,{headers:b,allHeaders:b}),this._refresh(!0)},_setHeaders:function(){var a=this.element.find("thead tr");this.headers=this.element.find("tr:eq(0)").children(),this.allHeaders=this.headers.add(a.children())},refresh:function(){this._refresh()},rebuild:a.noop,_refresh:function(){var b=this.element,c=b.find("thead tr");this._setHeaders(),c.each(function(){var d=0;a(this).children().each(function(){var e,f=parseInt(this.getAttribute("colspan"),10),g=":nth-child("+(d+1)+")";if(this.setAttribute("data-"+a.mobile.ns+"colstart",d+1),f)for(e=0;f-1>e;e++)d++,g+=", :nth-child("+(d+1)+")";a(this).jqmData("cells",b.find("tr").not(c.eq(0)).not(this).children(g)),d++})})}})}(a),function(a){a.widget("mobile.table",a.mobile.table,{options:{mode:"columntoggle",columnBtnTheme:null,columnPopupTheme:null,columnBtnText:"Columns...",classes:a.extend(a.mobile.table.prototype.options.classes,{popup:"ui-table-columntoggle-popup",columnBtn:"ui-table-columntoggle-btn",priorityPrefix:"ui-table-priority-",columnToggleTable:"ui-table-columntoggle"})},_create:function(){this._super(),"columntoggle"===this.options.mode&&(a.extend(this,{_menu:null}),this.options.enhanced?(this._menu=a(this.document[0].getElementById(this._id()+"-popup")).children().first(),this._addToggles(this._menu,!0)):(this._menu=this._enhanceColToggle(),this.element.addClass(this.options.classes.columnToggleTable)),this._setupEvents(),this._setToggleState())},_id:function(){return this.element.attr("id")||this.widgetName+this.uuid},_setupEvents:function(){this._on(this.window,{throttledresize:"_setToggleState"}),this._on(this._menu,{"change input":"_menuInputChange"})},_addToggles:function(b,c){var d,e=0,f=this.options,g=b.controlgroup("container");c?d=b.find("input"):g.empty(),this.headers.not("td").each(function(){var b=a(this),h=a.mobile.getAttribute(this,"priority"),i=b.add(b.jqmData("cells"));h&&(i.addClass(f.classes.priorityPrefix+h),(c?d.eq(e++):a("<label><input type='checkbox' checked />"+(b.children("abbr").first().attr("title")||b.text())+"</label>").appendTo(g).children(0).checkboxradio({theme:f.columnPopupTheme})).jqmData("cells",i))}),c||b.controlgroup("refresh")},_menuInputChange:function(b){var c=a(b.target),d=c[0].checked;c.jqmData("cells").toggleClass("ui-table-cell-hidden",!d).toggleClass("ui-table-cell-visible",d),c[0].getAttribute("locked")?(c.removeAttr("locked"),this._unlockCells(c.jqmData("cells"))):c.attr("locked",!0)},_unlockCells:function(a){a.removeClass("ui-table-cell-hidden ui-table-cell-visible")},_enhanceColToggle:function(){var b,c,d,e,f=this.element,g=this.options,h=a.mobile.ns,i=this.document[0].createDocumentFragment();return b=this._id()+"-popup",c=a("<a href='#"+b+"' class='"+g.classes.columnBtn+" ui-btn ui-btn-"+(g.columnBtnTheme||"a")+" ui-corner-all ui-shadow ui-mini' data-"+h+"rel='popup'>"+g.columnBtnText+"</a>"),d=a("<div class='"+g.classes.popup+"' id='"+b+"'></div>"),e=a("<fieldset></fieldset>").controlgroup(),this._addToggles(e,!1),e.appendTo(d),i.appendChild(d[0]),i.appendChild(c[0]),f.before(i),d.popup(),e},rebuild:function(){this._super(),"columntoggle"===this.options.mode&&this._refresh(!1)},_refresh:function(a){this._super(a),a||"columntoggle"!==this.options.mode||(this._unlockCells(this.element.find(".ui-table-cell-hidden, .ui-table-cell-visible")),this._addToggles(this._menu,a),this._setToggleState())},_setToggleState:function(){this._menu.find("input").each(function(){var b=a(this);this.checked="table-cell"===b.jqmData("cells").eq(0).css("display"),b.checkboxradio("refresh")})},_destroy:function(){this._super()}})}(a),function(a){a.widget("mobile.table",a.mobile.table,{options:{mode:"reflow",classes:a.extend(a.mobile.table.prototype.options.classes,{reflowTable:"ui-table-reflow",cellLabels:"ui-table-cell-label"})},_create:function(){this._super(),"reflow"===this.options.mode&&(this.options.enhanced||(this.element.addClass(this.options.classes.reflowTable),this._updateReflow()))},rebuild:function(){this._super(),"reflow"===this.options.mode&&this._refresh(!1)},_refresh:function(a){this._super(a),a||"reflow"!==this.options.mode||this._updateReflow()},_updateReflow:function(){var b=this,c=this.options;a(b.allHeaders.get().reverse()).each(function(){var d,e,f=a(this).jqmData("cells"),g=a.mobile.getAttribute(this,"colstart"),h=f.not(this).filter("thead th").length&&" ui-table-cell-label-top",i=a(this).text();""!==i&&(h?(d=parseInt(this.getAttribute("colspan"),10),e="",d&&(e="td:nth-child("+d+"n + "+g+")"),b._addLabels(f.filter(e),c.classes.cellLabels+h,i)):b._addLabels(f,c.classes.cellLabels,i))})},_addLabels:function(a,b,c){a.not(":has(b."+b+")").prepend("<b class='"+b+"'>"+c+"</b>")}})}(a),function(a,c){var d=function(b,c){return-1===(""+(a.mobile.getAttribute(this,"filtertext")||a(this).text())).toLowerCase().indexOf(c)};a.widget("mobile.filterable",{initSelector:":jqmData(filter='true')",options:{filterReveal:!1,filterCallback:d,enhanced:!1,input:null,children:"> li, > option, > optgroup option, > tbody tr, > .ui-controlgroup-controls > .ui-btn, > .ui-controlgroup-controls > .ui-checkbox, > .ui-controlgroup-controls > .ui-radio"},_create:function(){var b=this.options;a.extend(this,{_search:null,_timer:0}),this._setInput(b.input),b.enhanced||this._filterItems((this._search&&this._search.val()||"").toLowerCase())},_onKeyUp:function(){var c,d,e=this._search;if(e){if(c=e.val().toLowerCase(),d=a.mobile.getAttribute(e[0],"lastval")+"",d&&d===c)return;this._timer&&(b.clearTimeout(this._timer),this._timer=0),this._timer=this._delay(function(){this._trigger("beforefilter",null,{input:e}),e[0].setAttribute("data-"+a.mobile.ns+"lastval",c),this._filterItems(c),this._timer=0},250)}},_getFilterableItems:function(){var b=this.element,c=this.options.children,d=c?a.isFunction(c)?c():c.nodeName?a(c):c.jquery?c:this.element.find(c):{length:0};return 0===d.length&&(d=b.children()),d},_filterItems:function(b){var c,e,f,g,h=[],i=[],j=this.options,k=this._getFilterableItems();if(null!=b)for(e=j.filterCallback||d,f=k.length,c=0;f>c;c++)g=e.call(k[c],c,b)?i:h,g.push(k[c]);0===i.length?k[j.filterReveal?"addClass":"removeClass"]("ui-screen-hidden"):(a(i).addClass("ui-screen-hidden"),a(h).removeClass("ui-screen-hidden")),this._refreshChildWidget(),this._trigger("filter",null,{items:k})},_refreshChildWidget:function(){var b,c,d=["collapsibleset","selectmenu","controlgroup","listview"];for(c=d.length-1;c>-1;c--)b=d[c],a.mobile[b]&&(b=this.element.data("mobile-"+b),b&&a.isFunction(b.refresh)&&b.refresh())},_setInput:function(c){var d=this._search;this._timer&&(b.clearTimeout(this._timer),this._timer=0),d&&(this._off(d,"keyup change input"),d=null),c&&(d=c.jquery?c:c.nodeName?a(c):this.document.find(c),this._on(d,{keyup:"_onKeyUp",change:"_onKeyUp",input:"_onKeyUp"})),this._search=d},_setOptions:function(a){var b=!(a.filterReveal===c&&a.filterCallback===c&&a.children===c);this._super(a),a.input!==c&&(this._setInput(a.input),b=!0),b&&this.refresh()},_destroy:function(){var a=this.options,b=this._getFilterableItems();a.enhanced?b.toggleClass("ui-screen-hidden",a.filterReveal):b.removeClass("ui-screen-hidden")},refresh:function(){this._timer&&(b.clearTimeout(this._timer),this._timer=0),this._filterItems((this._search&&this._search.val()||"").toLowerCase())}})}(a),function(a,b){var c=function(a,b){return function(c){b.call(this,c),a._syncTextInputOptions(c)}},d=/(^|\s)ui-li-divider(\s|$)/,e=a.mobile.filterable.prototype.options.filterCallback;a.mobile.filterable.prototype.options.filterCallback=function(a,b){return!this.className.match(d)&&e.call(this,a,b)},a.widget("mobile.filterable",a.mobile.filterable,{options:{filterPlaceholder:"Filter items...",filterTheme:null},_create:function(){var b,c,d=this.element,e=["collapsibleset","selectmenu","controlgroup","listview"],f={};for(this._super(),a.extend(this,{_widget:null}),b=e.length-1;b>-1;b--)if(c=e[b],a.mobile[c]){if(this._setWidget(d.data("mobile-"+c)))break;f[c+"create"]="_handleCreate"}this._widget||this._on(d,f)},_handleCreate:function(a){this._setWidget(this.element.data("mobile-"+a.type.substring(0,a.type.length-6)))},_trigger:function(a,b,c){this._widget&&"mobile-listview"===this._widget.widgetFullName&&"beforefilter"===a&&this._widget._trigger("beforefilter",b,c),this._super(a,b,c)},_setWidget:function(a){return!this._widget&&a&&(this._widget=a,this._widget._setOptions=c(this,this._widget._setOptions)),this._widget&&(this._syncTextInputOptions(this._widget.options),"listview"===this._widget.widgetName&&(this._widget.options.hideDividers=!0,this._widget.element.listview("refresh"))),!!this._widget},_isSearchInternal:function(){return this._search&&this._search.jqmData("ui-filterable-"+this.uuid+"-internal")},_setInput:function(b){var c=this.options,d=!0,e={};if(!b){if(this._isSearchInternal())return;d=!1,b=a("<input data-"+a.mobile.ns+"type='search' placeholder='"+c.filterPlaceholder+"'></input>").jqmData("ui-filterable-"+this.uuid+"-internal",!0),a("<form class='ui-filterable'></form>").append(b).submit(function(a){a.preventDefault(),b.blur()}).insertBefore(this.element),a.mobile.textinput&&(null!=this.options.filterTheme&&(e.theme=c.filterTheme),b.textinput(e))}this._super(b),this._isSearchInternal()&&d&&this._search.attr("placeholder",this.options.filterPlaceholder)},_setOptions:function(c){var d=this._super(c);return c.filterPlaceholder!==b&&this._isSearchInternal()&&this._search.attr("placeholder",c.filterPlaceholder),c.filterTheme!==b&&this._search&&a.mobile.textinput&&this._search.textinput("option","theme",c.filterTheme),d},_destroy:function(){this._isSearchInternal()&&this._search.remove(),this._super()},_syncTextInputOptions:function(c){var d,e={};if(this._isSearchInternal()&&a.mobile.textinput){for(d in a.mobile.textinput.prototype.options)c[d]!==b&&(e[d]="theme"===d&&null!=this.options.filterTheme?this.options.filterTheme:c[d]);this._search.textinput("option",e)}}})}(a),function(a,b){function c(){return++e}function d(a){return a.hash.length>1&&decodeURIComponent(a.href.replace(f,""))===decodeURIComponent(location.href.replace(f,""))}var e=0,f=/#.*$/;a.widget("ui.tabs",{version:"fadf2b312a05040436451c64bbfaf4814bc62c56",delay:300,options:{active:null,collapsible:!1,event:"click",heightStyle:"content",hide:null,show:null,activate:null,beforeActivate:null,beforeLoad:null,load:null},_create:function(){var b=this,c=this.options;this.running=!1,this.element.addClass("ui-tabs ui-widget ui-widget-content ui-corner-all").toggleClass("ui-tabs-collapsible",c.collapsible).delegate(".ui-tabs-nav > li","mousedown"+this.eventNamespace,function(b){a(this).is(".ui-state-disabled")&&b.preventDefault()}).delegate(".ui-tabs-anchor","focus"+this.eventNamespace,function(){a(this).closest("li").is(".ui-state-disabled")&&this.blur()}),this._processTabs(),c.active=this._initialActive(),a.isArray(c.disabled)&&(c.disabled=a.unique(c.disabled.concat(a.map(this.tabs.filter(".ui-state-disabled"),function(a){return b.tabs.index(a)}))).sort()),this.active=this.options.active!==!1&&this.anchors.length?this._findActive(c.active):a(),this._refresh(),this.active.length&&this.load(c.active)},_initialActive:function(){var b=this.options.active,c=this.options.collapsible,d=location.hash.substring(1);return null===b&&(d&&this.tabs.each(function(c,e){return a(e).attr("aria-controls")===d?(b=c,!1):void 0}),null===b&&(b=this.tabs.index(this.tabs.filter(".ui-tabs-active"))),(null===b||-1===b)&&(b=this.tabs.length?0:!1)),b!==!1&&(b=this.tabs.index(this.tabs.eq(b)),-1===b&&(b=c?!1:0)),!c&&b===!1&&this.anchors.length&&(b=0),b},_getCreateEventData:function(){return{tab:this.active,panel:this.active.length?this._getPanelForTab(this.active):a()}},_tabKeydown:function(b){var c=a(this.document[0].activeElement).closest("li"),d=this.tabs.index(c),e=!0;if(!this._handlePageNav(b)){switch(b.keyCode){case a.ui.keyCode.RIGHT:case a.ui.keyCode.DOWN:d++;break;case a.ui.keyCode.UP:case a.ui.keyCode.LEFT:e=!1,d--;break;case a.ui.keyCode.END:d=this.anchors.length-1;break;case a.ui.keyCode.HOME:d=0;break;case a.ui.keyCode.SPACE:return b.preventDefault(),clearTimeout(this.activating),void this._activate(d);case a.ui.keyCode.ENTER:return b.preventDefault(),clearTimeout(this.activating),void this._activate(d===this.options.active?!1:d);default:return}b.preventDefault(),clearTimeout(this.activating),d=this._focusNextTab(d,e),b.ctrlKey||(c.attr("aria-selected","false"),this.tabs.eq(d).attr("aria-selected","true"),this.activating=this._delay(function(){this.option("active",d)},this.delay))}},_panelKeydown:function(b){this._handlePageNav(b)||b.ctrlKey&&b.keyCode===a.ui.keyCode.UP&&(b.preventDefault(),this.active.focus())},_handlePageNav:function(b){return b.altKey&&b.keyCode===a.ui.keyCode.PAGE_UP?(this._activate(this._focusNextTab(this.options.active-1,!1)),!0):b.altKey&&b.keyCode===a.ui.keyCode.PAGE_DOWN?(this._activate(this._focusNextTab(this.options.active+1,!0)),!0):void 0},_findNextTab:function(b,c){function d(){return b>e&&(b=0),0>b&&(b=e),b}for(var e=this.tabs.length-1;-1!==a.inArray(d(),this.options.disabled);)b=c?b+1:b-1;return b},_focusNextTab:function(a,b){return a=this._findNextTab(a,b),this.tabs.eq(a).focus(),a},_setOption:function(a,b){return"active"===a?void this._activate(b):"disabled"===a?void this._setupDisabled(b):(this._super(a,b),"collapsible"===a&&(this.element.toggleClass("ui-tabs-collapsible",b),b||this.options.active!==!1||this._activate(0)),"event"===a&&this._setupEvents(b),void("heightStyle"===a&&this._setupHeightStyle(b)))},_tabId:function(a){return a.attr("aria-controls")||"ui-tabs-"+c()},_sanitizeSelector:function(a){return a?a.replace(/[!"$%&'()*+,.\/:;<=>?@\[\]\^`{|}~]/g,"\\$&"):""},refresh:function(){var b=this.options,c=this.tablist.children(":has(a[href])");b.disabled=a.map(c.filter(".ui-state-disabled"),function(a){return c.index(a)}),this._processTabs(),b.active!==!1&&this.anchors.length?this.active.length&&!a.contains(this.tablist[0],this.active[0])?this.tabs.length===b.disabled.length?(b.active=!1,this.active=a()):this._activate(this._findNextTab(Math.max(0,b.active-1),!1)):b.active=this.tabs.index(this.active):(b.active=!1,this.active=a()),this._refresh()},_refresh:function(){this._setupDisabled(this.options.disabled),this._setupEvents(this.options.event),this._setupHeightStyle(this.options.heightStyle),this.tabs.not(this.active).attr({"aria-selected":"false",tabIndex:-1}),this.panels.not(this._getPanelForTab(this.active)).hide().attr({"aria-expanded":"false","aria-hidden":"true"}),this.active.length?(this.active.addClass("ui-tabs-active ui-state-active").attr({"aria-selected":"true",tabIndex:0}),this._getPanelForTab(this.active).show().attr({"aria-expanded":"true","aria-hidden":"false"})):this.tabs.eq(0).attr("tabIndex",0)},_processTabs:function(){var b=this;this.tablist=this._getList().addClass("ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all").attr("role","tablist"),this.tabs=this.tablist.find("> li:has(a[href])").addClass("ui-state-default ui-corner-top").attr({role:"tab",tabIndex:-1}),this.anchors=this.tabs.map(function(){return a("a",this)[0]}).addClass("ui-tabs-anchor").attr({role:"presentation",tabIndex:-1}),this.panels=a(),this.anchors.each(function(c,e){var f,g,h,i=a(e).uniqueId().attr("id"),j=a(e).closest("li"),k=j.attr("aria-controls");d(e)?(f=e.hash,g=b.element.find(b._sanitizeSelector(f))):(h=b._tabId(j),f="#"+h,g=b.element.find(f),g.length||(g=b._createPanel(h),g.insertAfter(b.panels[c-1]||b.tablist)),g.attr("aria-live","polite")),g.length&&(b.panels=b.panels.add(g)),k&&j.data("ui-tabs-aria-controls",k),j.attr({"aria-controls":f.substring(1),"aria-labelledby":i}),g.attr("aria-labelledby",i)}),this.panels.addClass("ui-tabs-panel ui-widget-content ui-corner-bottom").attr("role","tabpanel")},_getList:function(){return this.element.find("ol,ul").eq(0)},_createPanel:function(b){return a("<div>").attr("id",b).addClass("ui-tabs-panel ui-widget-content ui-corner-bottom").data("ui-tabs-destroy",!0)},_setupDisabled:function(b){a.isArray(b)&&(b.length?b.length===this.anchors.length&&(b=!0):b=!1);for(var c,d=0;c=this.tabs[d];d++)b===!0||-1!==a.inArray(d,b)?a(c).addClass("ui-state-disabled").attr("aria-disabled","true"):a(c).removeClass("ui-state-disabled").removeAttr("aria-disabled");this.options.disabled=b},_setupEvents:function(b){var c={click:function(a){a.preventDefault()}};b&&a.each(b.split(" "),function(a,b){c[b]="_eventHandler"}),this._off(this.anchors.add(this.tabs).add(this.panels)),this._on(this.anchors,c),this._on(this.tabs,{keydown:"_tabKeydown"}),this._on(this.panels,{keydown:"_panelKeydown"}),this._focusable(this.tabs),this._hoverable(this.tabs)},_setupHeightStyle:function(b){var c,d=this.element.parent();"fill"===b?(c=d.height(),c-=this.element.outerHeight()-this.element.height(),this.element.siblings(":visible").each(function(){var b=a(this),d=b.css("position");"absolute"!==d&&"fixed"!==d&&(c-=b.outerHeight(!0))}),this.element.children().not(this.panels).each(function(){c-=a(this).outerHeight(!0)}),this.panels.each(function(){a(this).height(Math.max(0,c-a(this).innerHeight()+a(this).height()))}).css("overflow","auto")):"auto"===b&&(c=0,this.panels.each(function(){c=Math.max(c,a(this).height("").height())}).height(c))},_eventHandler:function(b){var c=this.options,d=this.active,e=a(b.currentTarget),f=e.closest("li"),g=f[0]===d[0],h=g&&c.collapsible,i=h?a():this._getPanelForTab(f),j=d.length?this._getPanelForTab(d):a(),k={oldTab:d,oldPanel:j,newTab:h?a():f,newPanel:i};b.preventDefault(),f.hasClass("ui-state-disabled")||f.hasClass("ui-tabs-loading")||this.running||g&&!c.collapsible||this._trigger("beforeActivate",b,k)===!1||(c.active=h?!1:this.tabs.index(f),this.active=g?a():f,this.xhr&&this.xhr.abort(),j.length||i.length||a.error("jQuery UI Tabs: Mismatching fragment identifier."),i.length&&this.load(this.tabs.index(f),b),this._toggle(b,k))},_toggle:function(b,c){function d(){f.running=!1,f._trigger("activate",b,c)}function e(){c.newTab.closest("li").addClass("ui-tabs-active ui-state-active"),g.length&&f.options.show?f._show(g,f.options.show,d):(g.show(),d())}var f=this,g=c.newPanel,h=c.oldPanel;this.running=!0,h.length&&this.options.hide?this._hide(h,this.options.hide,function(){c.oldTab.closest("li").removeClass("ui-tabs-active ui-state-active"),e()}):(c.oldTab.closest("li").removeClass("ui-tabs-active ui-state-active"),h.hide(),e()),h.attr({"aria-expanded":"false","aria-hidden":"true"}),c.oldTab.attr("aria-selected","false"),g.length&&h.length?c.oldTab.attr("tabIndex",-1):g.length&&this.tabs.filter(function(){return 0===a(this).attr("tabIndex")}).attr("tabIndex",-1),g.attr({"aria-expanded":"true","aria-hidden":"false"}),c.newTab.attr({"aria-selected":"true",tabIndex:0})},_activate:function(b){var c,d=this._findActive(b);d[0]!==this.active[0]&&(d.length||(d=this.active),c=d.find(".ui-tabs-anchor")[0],this._eventHandler({target:c,currentTarget:c,preventDefault:a.noop}))},_findActive:function(b){return b===!1?a():this.tabs.eq(b)},_getIndex:function(a){return"string"==typeof a&&(a=this.anchors.index(this.anchors.filter("[href$='"+a+"']"))),a},_destroy:function(){this.xhr&&this.xhr.abort(),this.element.removeClass("ui-tabs ui-widget ui-widget-content ui-corner-all ui-tabs-collapsible"),this.tablist.removeClass("ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all").removeAttr("role"),this.anchors.removeClass("ui-tabs-anchor").removeAttr("role").removeAttr("tabIndex").removeUniqueId(),this.tabs.add(this.panels).each(function(){a.data(this,"ui-tabs-destroy")?a(this).remove():a(this).removeClass("ui-state-default ui-state-active ui-state-disabled ui-corner-top ui-corner-bottom ui-widget-content ui-tabs-active ui-tabs-panel").removeAttr("tabIndex").removeAttr("aria-live").removeAttr("aria-busy").removeAttr("aria-selected").removeAttr("aria-labelledby").removeAttr("aria-hidden").removeAttr("aria-expanded").removeAttr("role")}),this.tabs.each(function(){var b=a(this),c=b.data("ui-tabs-aria-controls");c?b.attr("aria-controls",c).removeData("ui-tabs-aria-controls"):b.removeAttr("aria-controls")}),this.panels.show(),"content"!==this.options.heightStyle&&this.panels.css("height","")},enable:function(c){var d=this.options.disabled;d!==!1&&(c===b?d=!1:(c=this._getIndex(c),d=a.isArray(d)?a.map(d,function(a){return a!==c?a:null}):a.map(this.tabs,function(a,b){return b!==c?b:null})),this._setupDisabled(d))},disable:function(c){var d=this.options.disabled;if(d!==!0){if(c===b)d=!0;else{if(c=this._getIndex(c),-1!==a.inArray(c,d))return;d=a.isArray(d)?a.merge([c],d).sort():[c]}this._setupDisabled(d)}},load:function(b,c){b=this._getIndex(b);var e=this,f=this.tabs.eq(b),g=f.find(".ui-tabs-anchor"),h=this._getPanelForTab(f),i={tab:f,panel:h};d(g[0])||(this.xhr=a.ajax(this._ajaxSettings(g,c,i)),this.xhr&&"canceled"!==this.xhr.statusText&&(f.addClass("ui-tabs-loading"),h.attr("aria-busy","true"),this.xhr.success(function(a){setTimeout(function(){h.html(a),e._trigger("load",c,i)},1)}).complete(function(a,b){setTimeout(function(){"abort"===b&&e.panels.stop(!1,!0),f.removeClass("ui-tabs-loading"),h.removeAttr("aria-busy"),a===e.xhr&&delete e.xhr},1)})))},_ajaxSettings:function(b,c,d){var e=this;return{url:b.attr("href"),beforeSend:function(b,f){return e._trigger("beforeLoad",c,a.extend({jqXHR:b,ajaxSettings:f},d))}}},_getPanelForTab:function(b){var c=a(b).attr("aria-controls");return this.element.find(this._sanitizeSelector("#"+c))}})}(a),function(){}(a),function(a,b){function c(a){e=a.originalEvent,i=e.accelerationIncludingGravity,f=Math.abs(i.x),g=Math.abs(i.y),h=Math.abs(i.z),!b.orientation&&(f>7||(h>6&&8>g||8>h&&g>6)&&f>5)?d.enabled&&d.disable():d.enabled||d.enable()}a.mobile.iosorientationfixEnabled=!0;var d,e,f,g,h,i,j=navigator.userAgent;return/iPhone|iPad|iPod/.test(navigator.platform)&&/OS [1-5]_[0-9_]* like Mac OS X/i.test(j)&&j.indexOf("AppleWebKit")>-1?(d=a.mobile.zoom,void a.mobile.document.on("mobileinit",function(){a.mobile.iosorientationfixEnabled&&a.mobile.window.bind("orientationchange.iosorientationfix",d.enable).bind("devicemotion.iosorientationfix",c)})):void(a.mobile.iosorientationfixEnabled=!1)}(a,this),function(a,b){function d(){e.removeClass("ui-mobile-rendering")}var e=a("html"),f=a.mobile.window;a(b.document).trigger("mobileinit"),a.mobile.gradeA()&&(a.mobile.ajaxBlacklist&&(a.mobile.ajaxEnabled=!1),e.addClass("ui-mobile ui-mobile-rendering"),setTimeout(d,5e3),a.extend(a.mobile,{initializePage:function(){var b=a.mobile.path,e=a(":jqmData(role='page'), :jqmData(role='dialog')"),g=b.stripHash(b.stripQueryParams(b.parseLocation().hash)),h=c.getElementById(g);
e.length||(e=a("body").wrapInner("<div data-"+a.mobile.ns+"role='page'></div>").children(0)),e.each(function(){var b=a(this);b[0].getAttribute("data-"+a.mobile.ns+"url")||b.attr("data-"+a.mobile.ns+"url",b.attr("id")||location.pathname+location.search)}),a.mobile.firstPage=e.first(),a.mobile.pageContainer=a.mobile.firstPage.parent().addClass("ui-mobile-viewport").pagecontainer(),a.mobile.navreadyDeferred.resolve(),f.trigger("pagecontainercreate"),a.mobile.loading("show"),d(),a.mobile.hashListeningEnabled&&a.mobile.path.isHashValid(location.hash)&&(a(h).is(":jqmData(role='page')")||a.mobile.path.isPath(g)||g===a.mobile.dialogHashKey)?a.event.special.navigate.isPushStateEnabled()?(a.mobile.navigate.history.stack=[],a.mobile.navigate(a.mobile.path.isPath(location.hash)?location.hash:location.href)):f.trigger("hashchange",[!0]):(a.mobile.path.isHashValid(location.hash)&&(a.mobile.navigate.history.initialDst=g.replace("#","")),a.event.special.navigate.isPushStateEnabled()&&a.mobile.navigate.navigator.squash(b.parseLocation().href),a.mobile.changePage(a.mobile.firstPage,{transition:"none",reverse:!0,changeHash:!1,fromHashChange:!0}))}}),a(function(){a.support.inlineSVG(),a.mobile.hideUrlBar&&b.scrollTo(0,1),a.mobile.defaultHomeScroll=a.support.scrollTop&&1!==a.mobile.window.scrollTop()?1:0,a.mobile.autoInitializePage&&a.mobile.initializePage(),a.mobile.hideUrlBar&&f.load(a.mobile.silentScroll),a.support.cssPointerEvents||a.mobile.document.delegate(".ui-state-disabled,.ui-disabled","vclick",function(a){a.preventDefault(),a.stopImmediatePropagation()})}))}(a,this)});
//# sourceMappingURL=jquery.mobile-1.4.2.min.map | zettwerk.mobile | /zettwerk.mobile-0.2.1.zip/zettwerk.mobile-0.2.1/zettwerk/mobile/static/jquery.mobile-1.4.2/jquery.mobile-1.4.2.min.js | jquery.mobile-1.4.2.min.js |
(function($) {
var pluginName = 'gmap';
var DATA_INITIAL_VIEW = "44.80,-93.16,5";
function parseLatLng(string) {
if (!string) string = DATA_INITIAL_VIEW;
var parts = string.split(',');
if (parts.length != 2) throw 'Invalid lat/lng: "'+string+'"';
var lat = parseFloat(parts[0]);
var lng = parseFloat(parts[1]);
if (isNaN(lat) || lat < -90 || lat > 90 || isNaN(lng) || lng < -180 || lng > 180)
throw 'Invalid lat/lng: "'+string+'"';
return new google.maps.LatLng(lat, lng);
}
function parseLatLngZoom(string) {
if (!string) string = DATA_INITIAL_VIEW;
var parts = string.split(',');
if (parts.length != 3) throw 'Invalid lat/lng/zoom: "'+string+'"';
var lat = parseFloat(parts[0]);
var lng = parseFloat(parts[1]);
var zoom = parseInt(parts[2]);
if (isNaN(lat) || lat < -90 || lat > 90 || isNaN(lng) || lng < -180 || lng > 180 || zoom < 3 || zoom > 30)
throw 'Invalid lat/lng/zoom: "'+string+'"';
return { center: new google.maps.LatLng(lat, lng), zoom: zoom };
}
var commands = {
init: function(config) {
if (!('google' in window) || !('maps' in google)) {
throw 'Google maps API did not complete loading';
}
var $this = $(this);
$this.data(pluginName, config);
// Set up UI
$this.addClass('ui-gmap').html('<div class="ui-gmap-canvas"></div>');
// Figure out the initial view and construct the googlemap
var opts = parseLatLngZoom($this.attr('data-initial-view'));
opts.mapTypeId = google.maps.MapTypeId.ROADMAP;
opts.zoomControlOptions = {
position: google.maps.ControlPosition.LEFT_CENTER
};
var $canvas = $this.find('.ui-gmap-canvas');
var map = new google.maps.Map($canvas.get(0), opts);
$this.data(pluginName + '.map', map);
if (config.autoAddMarkers) {
$(this).gmap('addMarkersFromDOM');
}
// propagate resize events
$canvas.resize(function(e) {
google.maps.event.trigger(map, 'resize');
});
// ideally we would like to say: "resize the map if it or any parent goes from hidden->visible"
// but we don't have that event available, so the caller needs to be responsible for now
},
addMarkersFromDOM: function() {
var data = [];
$('[data-marker-info]').each(function() {
try {
var pos = parseLatLng($(this).attr('data-marker-info'));
data.push({ position: pos,
title: $(this).find('.ui-gmap-marker-title').html(),
content: $(this).find('.ui-gmap-marker-info').andSelf().filter('.ui-gmap-marker-info').clone().get(0)
});
}
catch (e) {
console.log(e);
}
});
var config = $(this).data(pluginName);
var map = $(this).data(pluginName + '.map');
var bounds = $(this).gmap('addMarkers', data);
if (!bounds.isEmpty()) {
var span = bounds.toSpan();
if (span.lat() < 0.0001 || span.lng() < 0.0001) {
map.setCenter(bounds.getCenter());
map.setZoom(config.zoomForSingleMarker);
}
else {
map.fitBounds(bounds);
}
}
},
addMarkers: function(data) {
var config = $(this).data(pluginName);
var map = $(this).data(pluginName + '.map');
var bounds = new google.maps.LatLngBounds();
var info = new InfoBox({
boxStyle: {
border: "1px solid black",
background: "white",
width: "220px",
padding: "5px"
}
,closeBoxURL: "http://maps.google.com/mapfiles/close.gif"
});
// Feel free to make lat/lng dynamic
var lat="44.80";
var lon = "-93.16";
if (lat && lon) {
var myLocation = new google.maps.LatLng(lat, lon);
new google.maps.Marker({ map:map, position:myLocation, icon:"http://labs.google.com/ridefinder/images/mm_20_green.png" });
bounds.extend(myLocation);
}
$.each(data, function(i) {
var icon = "http://maps.google.com/mapfiles/marker.png";
var marker = new google.maps.Marker({ map:map, position:this.position, title:this.title, icon:icon });
var content = this.content;
if (content) {
google.maps.event.addListener(marker, 'click', (function(map, marker, content) { return function() {
info.setContent($(content).html());
info.open(map, marker);
};})(map, marker, content));
}
bounds.extend(this.position);
});
return bounds;
}
};
var defaultConfig = {
autoAddMarkers: true,
zoomForSingleMarker: 15,
infoWindowConfig: { maxWidth: 175 }
};
$.fn[pluginName] = function() {
if (arguments.length == 0) {
var config = $.extend({}, defaultConfig);
$(this).each(function() {
commands.init.call(this, config);
});
return this;
}
if (arguments.length == 1 && $.isPlainObject(arguments[0])) {
var config = $.extend({}, defaultConfig, arguments[0]);
$(this).each(function() {
commands.init.call(this, config);
});
return this;
}
var cmd = commands[arguments[0]];
if ($.isFunction(cmd)) {
var args = [];
for (var i = 1; i < arguments.length; i++) args.push(arguments[i]);
return cmd.apply(this, args);
}
else {
alert('Function '+arguments[0]+' is not supported by the '+pluginName+' plugin.');
}
return this;
};
})(jQuery); | zettwerk.mobile | /zettwerk.mobile-0.2.1.zip/zettwerk.mobile-0.2.1/zettwerk/mobile/static/jquery.mobile-1.4.2/demos/map-list-toggle/jquery.gmap.js | jquery.gmap.js |
( function( $, undefined ) {
// Eventually, the real handleLink function should pass the coordinates and
// size of the rectangle representing the origin into popup's "open" method, or
// maybe the origin itself, instead of merely the midpoint of it. Here, the
// origin (link) is saved in lastLink, and appended to the options in the
// overridden version of open. Thankfully, JS is not multithreaded. Hooray!
var lastLink,
origHandleLink = $.mobile.popup.handleLink,
handleLink = function( link ) {
lastLink = link;
return origHandleLink.apply( this, arguments );
};
$.mobile.popup.handleLink = handleLink;
$.widget( "mobile.popup", $.mobile.popup, {
options: {
align: "0.5,0.5"
},
open: function( options ) {
this._ui.link = lastLink;
return this._super( options );
},
_closePrereqsDone: function() {
this._ui.link = null;
this._superApply( arguments );
},
_alignmentToCoeffs: function( alignment ) {
return {
originCoeff:
alignment < 0 ? 0 :
alignment <= 1 ? alignment :
1,
popupCoeff:
alignment < 0 ? alignment :
alignment <= 1 ? -alignment :
alignment - 2
};
},
_getAlignment: function() {
var ar, align;
if ( this.options.align ) {
ar = this.options.align.split( "," );
}
if ( ar && ar.length > 0 ) {
align = {
x: parseFloat( ar[ 0 ] ),
y: ar.length > 1 ? parseFloat( ar[ 1 ] ) : align.x
};
}
if ( align && !( isNaN( align.x ) || isNaN( align.y ) ) ) {
return {
x: this._alignmentToCoeffs( align.x ),
y: this._alignmentToCoeffs( align.y )
};
}
},
_setOptions: function( options ) {
var linkOffset, linkSize;
this._super( options );
if ( this._isOpen &&
options.align !== undefined &&
this._ui.link !== null &&
( this._ui.link.jqmData( "position-to" ) === "origin" ||
this.options.positionTo === "origin" ) ) {
linkOffset = this._ui.link.offset();
linkSize = {
cx: this._ui.link.outerWidth(),
cy: this._ui.link.outerHeight()
};
this._reposition({
x: linkOffset.left + linkSize.cx / 2,
y: linkOffset.top + linkSize.cy / 2,
positionTo: "origin"
});
}
},
_alignedCoord: function( start, coeffs, originSize, popupSize ) {
return (
// Start at the origin
start +
// Apply lignment
coeffs.originCoeff * originSize + coeffs.popupCoeff * popupSize +
// Resulting coordinate needs to be that of the middle of the popup, so
// add half a popup width
popupSize / 2 );
},
_desiredCoords: function( options ) {
var linkBox, offset, clampInfo,
alignment = this._getAlignment();
if ( alignment && options.positionTo === "origin" && this._ui.link ) {
// Grab the size of the popup and the offset and size of the link
clampInfo = this._clampPopupWidth( true );
clampInfo.menuSize.cx = Math.min( clampInfo.menuSize.cx, clampInfo.rc.cx );
offset = this._ui.link.offset();
linkBox = {
x: offset.left,
y: offset.top,
cx: this._ui.link.outerWidth(),
cy: this._ui.link.outerHeight()
};
// Determine the desired coordinates of the middle of the popup
options.x = this._alignedCoord( linkBox.x, alignment.x, linkBox.cx, clampInfo.menuSize.cx );
options.y = this._alignedCoord( linkBox.y, alignment.y, linkBox.cy, clampInfo.menuSize.cy );
}
return this._super( options );
}
});
})( jQuery ); | zettwerk.mobile | /zettwerk.mobile-0.2.1.zip/zettwerk.mobile-0.2.1/zettwerk/mobile/static/jquery.mobile-1.4.2/demos/popup-alignment/popup.alignment.js | popup.alignment.js |
(function( $, undefined ) {
//special click handling to make widget work remove after nav changes in 1.4
var href,
ele = "";
$( document ).on( "click", "a", function( e ) {
href = $( this ).attr( "href" );
var hash = $.mobile.path.parseUrl( href );
if( typeof href !== "undefined" && hash !== "" && href !== href.replace( hash,"" ) && hash.search( "/" ) !== -1 ){
//remove the hash from the link to allow normal loading of the page.
var newHref = href.replace( hash,"" );
$( this ).attr( "href", newHref );
}
ele = $( this );
});
$( document ).on( "pagebeforechange", function( e, f ){
f.originalHref = href;
});
$( document ).on("pagebeforechange", function( e,f ){
var hash = $.mobile.path.parseUrl(f.toPage).hash,
hashEl, hashElInPage;
try {
hashEl = $( hash );
} catch( e ) {
hashEl = $();
}
try {
hashElInPage = $( ".ui-page-active " + hash );
} catch( e ) {
hashElInPage = $();
}
if( typeof hash !== "undefined" &&
hash.search( "/" ) === -1 &&
hash !== "" &&
hashEl.length > 0 &&
!hashEl.hasClass( "ui-page" ) &&
!hashEl.hasClass( "ui-popup" ) &&
hashEl.data('role') !== "page" &&
!hashElInPage.hasClass( "ui-panel" ) &&
!hashElInPage.hasClass( "ui-popup" ) ) {
//scroll to the id
var pos = hashEl.offset().top;
$.mobile.silentScroll( pos );
$.mobile.navigate( hash, '', true );
} else if( typeof f.toPage !== "object" &&
hash !== "" &&
$.mobile.path.parseUrl( href ).hash !== "" &&
!hashEl.hasClass( "ui-page" ) && hashEl.attr('data-role') !== "page" &&
!hashElInPage.hasClass( "ui-panel" ) &&
!hashElInPage.hasClass( "ui-popup" ) ) {
$( ele ).attr( "href", href );
$.mobile.document.one( "pagechange", function() {
if( typeof hash !== "undefined" &&
hash.search( "/" ) === -1 &&
hash !== "" &&
hashEl.length > 0 &&
hashElInPage.length > 0 &&
!hashEl.hasClass( "ui-page" ) &&
hashEl.data('role') !== "page" &&
!hashElInPage.hasClass( "ui-panel" ) &&
!hashElInPage.hasClass( "ui-popup" ) ) {
hash = $.mobile.path.parseUrl( href ).hash;
var pos = hashElInPage.offset().top;
$.mobile.silentScroll( pos );
}
} );
}
});
$( document ).on( "mobileinit", function(){
hash = window.location.hash;
$.mobile.document.one( "pageshow", function(){
var hashEl, hashElInPage;
try {
hashEl = $( hash );
} catch( e ) {
hashEl = $();
}
try {
hashElInPage = $( ".ui-page-active " + hash );
} catch( e ) {
hashElInPage = $();
}
if( hash !== "" &&
hashEl.length > 0 &&
hashElInPage.length > 0 &&
hashEl.attr('data-role') !== "page" &&
!hashEl.hasClass( "ui-page" ) &&
!hashElInPage.hasClass( "ui-panel" ) &&
!hashElInPage.hasClass( "ui-popup" ) &&
!hashEl.is( "body" ) ){
var pos = hashElInPage.offset().top;
setTimeout( function(){
$.mobile.silentScroll( pos );
}, 100 );
}
});
});
//h2 widget
$( document ).on( "mobileinit", function(){
$.widget( "mobile.h2linker", {
options:{
initSelector: ":jqmData(quicklinks='true')"
},
_create:function(){
var self = this,
bodyid = "ui-page-top",
panel = "<div data-role='panel' class='jqm-nav-panel jqm-quicklink-panel' data-position='right' data-display='overlay' data-theme='a'><ul data-role='listview' data-inset='false' data-theme='a' data-divider-theme='a' data-icon='false' class='jqm-list'><li data-role='list-divider'>Quick Links</li></ul></div>",
first = true,
h2dictionary = new Object();
if(typeof $("body").attr("id") === "undefined"){
$("body").attr("id",bodyid);
} else {
bodyid = $("body").attr("id");
}
this.element.find("div.jqm-content>h2").each(function(){
var id, text = $(this).text();
if(typeof $(this).attr("id") === "undefined"){
id = text.replace(/[^\.a-z0-9:_-]+/gi,"");
$(this).attr( "id", id );
} else {
id = $(this).attr("id");
}
h2dictionary[id] = text;
if(!first){
$(this).before( "<a href='#" + bodyid + "' class='jqm-deeplink ui-icon-carat-u ui-alt-icon'>Top</a>");
} else {
$(this).before("<a href='#' data-ajax='false' class='jqm-deeplink jqm-open-quicklink-panel ui-icon-carat-l ui-alt-icon'>Quick Links</a>");
}
first = false;
});
this._on(".jqm-open-quicklink-panel", {
"click": function(){
$(".ui-page-active .jqm-quicklink-panel").panel("open");
return false;
}
});
this._on( document, {
"pagebeforechange": function(){
this.element.find(".jqm-quicklink-panel").panel("close");
this.element.find(".jqm-quicklink-panel .ui-btn-active").removeClass("ui-btn-active");
}
});
if( $(h2dictionary).length > 0 ){
this.element.prepend(panel)
this.element.find(".jqm-quicklink-panel").panel().find("ul").listview();
}
$.each(h2dictionary,function(id,text){
self.element.find(".jqm-quicklink-panel ul").append("<li><a href='#"+id+"'>"+text+"</a></li>");
});
self.element.find(".jqm-quicklink-panel ul").listview("refresh");
}
});
});
$( document ).bind( "pagecreate create", function( e ) {
var initselector = $.mobile.h2linker.prototype.options.initSelector;
if($(e.target).data("quicklinks")){
$(e.target).h2linker();
}
});
})( jQuery ); | zettwerk.mobile | /zettwerk.mobile-0.2.1.zip/zettwerk.mobile-0.2.1/zettwerk/mobile/static/jquery.mobile-1.4.2/demos/_assets/js/h2widget.js | h2widget.js |
if ( location.protocol.substr(0,4) === 'file' ||
location.protocol.substr(0,11) === '*-extension' ||
location.protocol.substr(0,6) === 'widget' ) {
// Start with links with only the trailing slash and that aren't external links
var fixLinks = function() {
$( "a[href$='/'], a[href='.'], a[href='..']" ).not( "[rel='external']" ).each( function() {
if( !$( this ).attr( "href" ).match("http") ){
this.href = $( this ).attr( "href" ).replace( /\/$/, "" ) + "/index.html";
}
});
};
// Fix the links for the initial page
$( fixLinks );
// Fix the links for subsequent ajax page loads
$( document ).on( "pagecreate", fixLinks );
// Check to see if ajax can be used. This does a quick ajax request and blocks the page until its done
$.ajax({
url: '.',
async: false,
isLocal: true
}).error(function() {
// Ajax doesn't work so turn it off
$( document ).on( "mobileinit", function() {
$.mobile.ajaxEnabled = false;
var message = $( '<div>' , {
'class': "jqm-content",
style: "border:none; padding: 10px 15px; overflow: auto;",
'data-ajax-warning': true
});
message
.append( "<h3>Note: Navigation may not work if viewed locally</h3>" )
.append( "<p>The Ajax-based navigation used throughout the jQuery Mobile docs may need to be viewed on a web server to work in certain browsers. If you see an error message when you click a link, please try a different browser.</p>" );
$( document ).on( "pagecreate", function( event ) {
$( event.target ).append( message );
});
});
});
}
$( document ).on( "pagecreate", ".jqm-demos", function( event ) {
var search,
page = $( this ),
that = this,
searchUrl = ( $( this ).hasClass( "jqm-home" ) ) ? "_search/" : "../_search/",
searchContents = $( ".jqm-search ul.jqm-list" ).find( "li:not(.ui-collapsible)" ),
version = $.mobile.version || "dev",
words = version.split( "-" ),
ver = words[0],
str = words[1] || "",
text = ver;
// Insert jqm version in header
if ( str.indexOf( "rc" ) == -1 ) {
str = str.charAt( 0 ).toUpperCase() + str.slice( 1 );
} else {
str = str.toUpperCase().replace( ".", "" );
}
if ( $.mobile.version && str ) {
text += " " + str;
}
$( ".jqm-version" ).html( text );
// Global navmenu panel
$( ".jqm-navmenu-panel ul" ).listview();
$( document ).on( "panelopen", ".jqm-search-panel", function() {
$( this ).find( "input" ).focus();
})
$( ".jqm-navmenu-link" ).on( "click", function() {
page.find( ".jqm-navmenu-panel:not(.jqm-panel-page-nav)" ).panel( "open" );
});
// Turn off autocomplete / correct for demos search
$( this ).find( ".jqm-search input" ).attr( "autocomplete", "off" ).attr( "autocorrect", "off" );
// Global search
$( ".jqm-search-link" ).on( "click", function() {
page.find( ".jqm-search-panel" ).panel( "open" );
});
// Initalize search panel list and filter also remove collapsibles
$( this ).find( ".jqm-search ul.jqm-list" ).html( searchContents ).listview({
inset: false,
theme: null,
dividerTheme: null,
icon: false,
autodividers: true,
autodividersSelector: function ( li ) {
return "";
},
arrowKeyNav: true,
enterToNav: true,
highlight: true,
submitTo: searchUrl
}).filterable();
// Initalize search page list and remove collapsibles
$( this ).find( ".jqm-search-results-wrap ul.jqm-list" ).html( searchContents ).listview({
inset: true,
theme: null,
dividerTheme: null,
icon: false,
arrowKeyNav: true,
enterToNav: true,
highlight: true
}).filterable();
// Fix links on homepage to point to sub directories
if ( $( event.target ).hasClass( "jqm-home") ) {
$( this ).find( "a" ).each( function() {
$( this ).attr( "href", $( this ).attr( "href" ).replace( "../", "" ) );
});
}
// Search results page get search query string and enter it into filter then trigger keyup to filter
if ( $( event.target ).hasClass( "jqm-demos-search-results") ) {
search = $.mobile.path.parseUrl( window.location.href ).search.split( "=" )[ 1 ];
setTimeout(function() {
e = $.Event( "keyup" );
e.which = 65;
$( that ).find( ".jqm-content .jqm-search-results-wrap input" ).val( search ).trigger(e).trigger( "change" );
}, 0 );
}
});
// Append keywords list to each list item
$( document ).one( "pagecreate", ".jqm-demos", function( event ) {
$( this ).find( ".jqm-search-results-list li, .jqm-search li" ).each(function() {
var text = $( this ).attr( "data-filtertext" );
$( this )
.find( "a" )
.append( "<span class='jqm-search-results-keywords ui-li-desc'>" + text + "</span>" );
});
});
// Functions for highlighting text used for keywords highlight in search
jQuery.fn.highlight = function( pat ) {
function innerHighlight( node, pat ) {
var skip = 0;
if ( node.nodeType == 3 ) {
var pos = node.data.toUpperCase().indexOf( pat );
if ( pos >= 0 ) {
var spannode = document.createElement( "span" );
spannode.className = "jqm-search-results-highlight";
var middlebit = node.splitText( pos );
var endbit = middlebit.splitText( pat.length );
var middleclone = middlebit.cloneNode( true );
spannode.appendChild( middleclone );
middlebit.parentNode.replaceChild( spannode, middlebit );
skip = 1;
}
} else if ( node.nodeType == 1 && node.childNodes && !/(script|style)/i.test( node.tagName ) ) {
for ( var i = 0; i < node.childNodes.length; ++i ) {
i += innerHighlight( node.childNodes[i], pat );
}
}
return skip;
}
return this.length && pat && pat.length ? this.each(function() {
innerHighlight( this, pat.toUpperCase() );
}) : this;
};
// Function to remove highlights in text
jQuery.fn.removeHighlight = function() {
return this.find( "span.jqm-search-results-highlight" ).each(function() {
this.parentNode.firstChild.nodeName;
with ( this.parentNode ) {
replaceChild( this.firstChild, this );
normalize();
}
}).end();
};
// Extension to listview to add keyboard navigation
$( document ).on( "mobileinit", function() {
(function( $, undefined ) {
$.widget( "mobile.listview", $.mobile.listview, {
options: {
arrowKeyNav: false,
enterToNav: false,
highlight: false,
submitTo: false
},
_create: function() {
this._super();
if ( this.options.arrowKeyNav ) {
this._on( document, { "pageshow": "arrowKeyNav" });
}
if ( this.options.enterToNav ) {
this._on( document, { "pageshow": "enterToNav" });
}
},
submitTo: function() {
var url,
form = this.element.parent().find( "form" );
form.attr( "method", "get" )
.attr( "action", this.options.submitTo );
url = this.options.submitTo + "?search=" + this.element.parent().find( "input" ).val();
window.location = url;
},
enterToNav: function() {
var form = this.element.parent().find( "form" );
form.append( "<button type='submit' data-icon='carat-r' data-inline='true' class='ui-hidden-accessible' data-iconpos='notext'>Submit</button>" )
.parent()
.trigger( "create" );
this.element.parent().find( "form" ).children( ".ui-btn" ).addClass( "ui-hidden-accessible" );
this._on( form, {
"submit": "submitHandler"
});
},
enhanced: false,
arrowKeyNav: function() {
var input = this.element.prev("form").find( "input" );
if ( !this.enhanced ) {
this._on( input, {
"keyup": "handleKeyUp"
});
this.enhanced = true;
}
},
handleKeyUp: function( e ) {
var search,
input = this.element.prev("form").find( "input" );
if ( e.which === $.ui.keyCode.DOWN ) {
if ( this.element.find( "li.ui-btn-active" ).length === 0 ) {
this.element.find( "li:first" ).toggleClass( "ui-btn-active" ).find("a").toggleClass( "ui-btn-active" );
} else {
this.element.find( "li.ui-btn-active a" ).toggleClass( "ui-btn-active");
this.element.find( "li.ui-btn-active" ).toggleClass( "ui-btn-active" ).next().toggleClass( "ui-btn-active" ).find("a").toggleClass( "ui-btn-active" );
}
this.highlightDown();
} else if ( e.which === $.ui.keyCode.UP ) {
if ( this.element.find( "li.ui-btn-active" ).length !== 0 ) {
this.element.find( "li.ui-btn-active a" ).toggleClass( "ui-btn-active");
this.element.find( "li.ui-btn-active" ).toggleClass( "ui-btn-active" ).prev().toggleClass( "ui-btn-active" ).find("a").toggleClass( "ui-btn-active" );
} else {
this.element.find( "li:last" ).toggleClass( "ui-btn-active" ).find("a").toggleClass( "ui-btn-active" );
}
this.highlightUp();
} else if ( typeof e.which !== "undefined" ) {
this.element.find( "li.ui-btn-active" ).removeClass( "ui-btn-active" );
if ( this.options.highlight ) {
search = input.val();
this.element.find( "li" ).each(function() {
$( this ).removeHighlight();
$( this ).highlight( search );
});
}
}
},
submitHandler: function() {
if ( this.element.find( "li.ui-btn-active" ).length !== 0 ) {
var href = this.element.find( "li.ui-btn-active a" ).attr( "href" );
$( ":mobile-pagecontainer" ).pagecontainer( "change", href );
return false;
}
if ( this.options.submitTo ) {
this.submitTo();
}
},
highlightDown: function() {
if ( this.element.find( "li.ui-btn-active" ).hasClass( "ui-screen-hidden" ) ) {
this.element.find( "li.ui-btn-active" ).find("a").toggleClass( "ui-btn-active" );
this.element.find( "li.ui-btn-active" ).toggleClass( "ui-btn-active" ).next().toggleClass( "ui-btn-active" ).find("a").toggleClass( "ui-btn-active" );
this.highlightDown();
}
return;
},
highlightUp: function() {
if ( this.element.find( "li.ui-btn-active" ).hasClass( "ui-screen-hidden" ) ) {
this.element.find( "li.ui-btn-active" ).find("a").toggleClass( "ui-btn-active" );
this.element.find( "li.ui-btn-active" ).toggleClass( "ui-btn-active" ).prev().toggleClass( "ui-btn-active" ).find("a").toggleClass( "ui-btn-active" );
this.highlightUp();
}
return;
}
});
})( jQuery );
}); | zettwerk.mobile | /zettwerk.mobile-0.2.1.zip/zettwerk.mobile-0.2.1/zettwerk/mobile/static/jquery.mobile-1.4.2/demos/_assets/js/jqm-demos.js | jqm-demos.js |
(function( $, undefined ) {
//special click handling to make widget work remove after nav changes in 1.4
var href,
ele = "";
$( document ).on( "click", "a", function( e ) {
href = $( this ).attr( "href" );
var hash = $.mobile.path.parseUrl( href );
if( typeof href !== "undefined" && hash !== "" && href !== href.replace( hash,"" ) && hash.search( "/" ) !== -1 ){
//remove the hash from the link to allow normal loading of the page.
var newHref = href.replace( hash,"" );
$( this ).attr( "href", newHref );
}
ele = $( this );
});
$( document ).on( "pagebeforechange", function( e, f ){
f.originalHref = href;
});
$( document ).on("pagebeforechange", function( e,f ){
var hash = $.mobile.path.parseUrl(f.toPage).hash,
hashEl, hashElInPage;
try {
hashEl = $( hash );
} catch( e ) {
hashEl = $();
}
try {
hashElInPage = $( ".ui-page-active " + hash );
} catch( e ) {
hashElInPage = $();
}
if( typeof hash !== "undefined" &&
hash.search( "/" ) === -1 &&
hash !== "" &&
hashEl.length > 0 &&
!hashEl.hasClass( "ui-page" ) &&
!hashEl.hasClass( "ui-popup" ) &&
hashEl.data('role') !== "page" &&
!hashElInPage.hasClass( "ui-panel" ) &&
!hashElInPage.hasClass( "ui-popup" ) ) {
//scroll to the id
var pos = hashEl.offset().top;
$.mobile.silentScroll( pos );
$.mobile.navigate( hash, '', true );
} else if( typeof f.toPage !== "object" &&
hash !== "" &&
$.mobile.path.parseUrl( href ).hash !== "" &&
!hashEl.hasClass( "ui-page" ) && hashEl.attr('data-role') !== "page" &&
!hashElInPage.hasClass( "ui-panel" ) &&
!hashElInPage.hasClass( "ui-popup" ) ) {
$( ele ).attr( "href", href );
$.mobile.document.one( "pagechange", function() {
if( typeof hash !== "undefined" &&
hash.search( "/" ) === -1 &&
hash !== "" &&
hashEl.length > 0 &&
hashElInPage.length > 0 &&
!hashEl.hasClass( "ui-page" ) &&
hashEl.data('role') !== "page" &&
!hashElInPage.hasClass( "ui-panel" ) &&
!hashElInPage.hasClass( "ui-popup" ) ) {
hash = $.mobile.path.parseUrl( href ).hash;
var pos = hashElInPage.offset().top;
$.mobile.silentScroll( pos );
}
} );
}
});
$( document ).on( "mobileinit", function(){
hash = window.location.hash;
$.mobile.document.one( "pageshow", function(){
var hashEl, hashElInPage;
try {
hashEl = $( hash );
} catch( e ) {
hashEl = $();
}
try {
hashElInPage = $( ".ui-page-active " + hash );
} catch( e ) {
hashElInPage = $();
}
if( hash !== "" &&
hashEl.length > 0 &&
hashElInPage.length > 0 &&
hashEl.attr('data-role') !== "page" &&
!hashEl.hasClass( "ui-page" ) &&
!hashElInPage.hasClass( "ui-panel" ) &&
!hashElInPage.hasClass( "ui-popup" ) &&
!hashEl.is( "body" ) ){
var pos = hashElInPage.offset().top;
setTimeout( function(){
$.mobile.silentScroll( pos );
}, 100 );
}
});
});
//h2 widget
$( document ).on( "mobileinit", function(){
$.widget( "mobile.h2linker", {
options:{
initSelector: ":jqmData(quicklinks='true')"
},
_create:function(){
var self = this,
bodyid = "ui-page-top",
panel = "<div data-role='panel' class='jqm-nav-panel jqm-quicklink-panel' data-position='right' data-display='overlay' data-theme='a'><ul data-role='listview' data-inset='false' data-theme='a' data-divider-theme='a' data-icon='false' class='jqm-list'><li data-role='list-divider'>Quick Links</li></ul></div>",
first = true,
h2dictionary = new Object();
if(typeof $("body").attr("id") === "undefined"){
$("body").attr("id",bodyid);
} else {
bodyid = $("body").attr("id");
}
this.element.find("div.jqm-content>h2").each(function(){
var id, text = $(this).text();
if(typeof $(this).attr("id") === "undefined"){
id = text.replace(/[^\.a-z0-9:_-]+/gi,"");
$(this).attr( "id", id );
} else {
id = $(this).attr("id");
}
h2dictionary[id] = text;
if(!first){
$(this).before( "<a href='#" + bodyid + "' class='jqm-deeplink ui-icon-carat-u ui-alt-icon'>Top</a>");
} else {
$(this).before("<a href='#' data-ajax='false' class='jqm-deeplink jqm-open-quicklink-panel ui-icon-carat-l ui-alt-icon'>Quick Links</a>");
}
first = false;
});
this._on(".jqm-open-quicklink-panel", {
"click": function(){
$(".ui-page-active .jqm-quicklink-panel").panel("open");
return false;
}
});
this._on( document, {
"pagebeforechange": function(){
this.element.find(".jqm-quicklink-panel").panel("close");
this.element.find(".jqm-quicklink-panel .ui-btn-active").removeClass("ui-btn-active");
}
});
if( $(h2dictionary).length > 0 ){
this.element.prepend(panel)
this.element.find(".jqm-quicklink-panel").panel().find("ul").listview();
}
$.each(h2dictionary,function(id,text){
self.element.find(".jqm-quicklink-panel ul").append("<li><a href='#"+id+"'>"+text+"</a></li>");
});
self.element.find(".jqm-quicklink-panel ul").listview("refresh");
}
});
});
$( document ).bind( "pagecreate create", function( e ) {
var initselector = $.mobile.h2linker.prototype.options.initSelector;
if($(e.target).data("quicklinks")){
$(e.target).h2linker();
}
});
})( jQuery );
// Turn off Ajax for local file browsing
if ( location.protocol.substr(0,4) === 'file' ||
location.protocol.substr(0,11) === '*-extension' ||
location.protocol.substr(0,6) === 'widget' ) {
// Start with links with only the trailing slash and that aren't external links
var fixLinks = function() {
$( "a[href$='/'], a[href='.'], a[href='..']" ).not( "[rel='external']" ).each( function() {
if( !$( this ).attr( "href" ).match("http") ){
this.href = $( this ).attr( "href" ).replace( /\/$/, "" ) + "/index.html";
}
});
};
// Fix the links for the initial page
$( fixLinks );
// Fix the links for subsequent ajax page loads
$( document ).on( "pagecreate", fixLinks );
// Check to see if ajax can be used. This does a quick ajax request and blocks the page until its done
$.ajax({
url: '.',
async: false,
isLocal: true
}).error(function() {
// Ajax doesn't work so turn it off
$( document ).on( "mobileinit", function() {
$.mobile.ajaxEnabled = false;
var message = $( '<div>' , {
'class': "jqm-content",
style: "border:none; padding: 10px 15px; overflow: auto;",
'data-ajax-warning': true
});
message
.append( "<h3>Note: Navigation may not work if viewed locally</h3>" )
.append( "<p>The Ajax-based navigation used throughout the jQuery Mobile docs may need to be viewed on a web server to work in certain browsers. If you see an error message when you click a link, please try a different browser.</p>" );
$( document ).on( "pagecreate", function( event ) {
$( event.target ).append( message );
});
});
});
}
$( document ).on( "pagecreate", ".jqm-demos", function( event ) {
var search,
page = $( this ),
that = this,
searchUrl = ( $( this ).hasClass( "jqm-home" ) ) ? "_search/" : "../_search/",
searchContents = $( ".jqm-search ul.jqm-list" ).find( "li:not(.ui-collapsible)" ),
version = $.mobile.version || "dev",
words = version.split( "-" ),
ver = words[0],
str = words[1] || "",
text = ver;
// Insert jqm version in header
if ( str.indexOf( "rc" ) == -1 ) {
str = str.charAt( 0 ).toUpperCase() + str.slice( 1 );
} else {
str = str.toUpperCase().replace( ".", "" );
}
if ( $.mobile.version && str ) {
text += " " + str;
}
$( ".jqm-version" ).html( text );
// Global navmenu panel
$( ".jqm-navmenu-panel ul" ).listview();
$( document ).on( "panelopen", ".jqm-search-panel", function() {
$( this ).find( "input" ).focus();
})
$( ".jqm-navmenu-link" ).on( "click", function() {
page.find( ".jqm-navmenu-panel:not(.jqm-panel-page-nav)" ).panel( "open" );
});
// Turn off autocomplete / correct for demos search
$( this ).find( ".jqm-search input" ).attr( "autocomplete", "off" ).attr( "autocorrect", "off" );
// Global search
$( ".jqm-search-link" ).on( "click", function() {
page.find( ".jqm-search-panel" ).panel( "open" );
});
// Initalize search panel list and filter also remove collapsibles
$( this ).find( ".jqm-search ul.jqm-list" ).html( searchContents ).listview({
inset: false,
theme: null,
dividerTheme: null,
icon: false,
autodividers: true,
autodividersSelector: function ( li ) {
return "";
},
arrowKeyNav: true,
enterToNav: true,
highlight: true,
submitTo: searchUrl
}).filterable();
// Initalize search page list and remove collapsibles
$( this ).find( ".jqm-search-results-wrap ul.jqm-list" ).html( searchContents ).listview({
inset: true,
theme: null,
dividerTheme: null,
icon: false,
arrowKeyNav: true,
enterToNav: true,
highlight: true
}).filterable();
// Fix links on homepage to point to sub directories
if ( $( event.target ).hasClass( "jqm-home") ) {
$( this ).find( "a" ).each( function() {
$( this ).attr( "href", $( this ).attr( "href" ).replace( "../", "" ) );
});
}
// Search results page get search query string and enter it into filter then trigger keyup to filter
if ( $( event.target ).hasClass( "jqm-demos-search-results") ) {
search = $.mobile.path.parseUrl( window.location.href ).search.split( "=" )[ 1 ];
setTimeout(function() {
e = $.Event( "keyup" );
e.which = 65;
$( that ).find( ".jqm-content .jqm-search-results-wrap input" ).val( search ).trigger(e).trigger( "change" );
}, 0 );
}
});
// Append keywords list to each list item
$( document ).one( "pagecreate", ".jqm-demos", function( event ) {
$( this ).find( ".jqm-search-results-list li, .jqm-search li" ).each(function() {
var text = $( this ).attr( "data-filtertext" );
$( this )
.find( "a" )
.append( "<span class='jqm-search-results-keywords ui-li-desc'>" + text + "</span>" );
});
});
// Functions for highlighting text used for keywords highlight in search
jQuery.fn.highlight = function( pat ) {
function innerHighlight( node, pat ) {
var skip = 0;
if ( node.nodeType == 3 ) {
var pos = node.data.toUpperCase().indexOf( pat );
if ( pos >= 0 ) {
var spannode = document.createElement( "span" );
spannode.className = "jqm-search-results-highlight";
var middlebit = node.splitText( pos );
var endbit = middlebit.splitText( pat.length );
var middleclone = middlebit.cloneNode( true );
spannode.appendChild( middleclone );
middlebit.parentNode.replaceChild( spannode, middlebit );
skip = 1;
}
} else if ( node.nodeType == 1 && node.childNodes && !/(script|style)/i.test( node.tagName ) ) {
for ( var i = 0; i < node.childNodes.length; ++i ) {
i += innerHighlight( node.childNodes[i], pat );
}
}
return skip;
}
return this.length && pat && pat.length ? this.each(function() {
innerHighlight( this, pat.toUpperCase() );
}) : this;
};
// Function to remove highlights in text
jQuery.fn.removeHighlight = function() {
return this.find( "span.jqm-search-results-highlight" ).each(function() {
this.parentNode.firstChild.nodeName;
with ( this.parentNode ) {
replaceChild( this.firstChild, this );
normalize();
}
}).end();
};
// Extension to listview to add keyboard navigation
$( document ).on( "mobileinit", function() {
(function( $, undefined ) {
$.widget( "mobile.listview", $.mobile.listview, {
options: {
arrowKeyNav: false,
enterToNav: false,
highlight: false,
submitTo: false
},
_create: function() {
this._super();
if ( this.options.arrowKeyNav ) {
this._on( document, { "pageshow": "arrowKeyNav" });
}
if ( this.options.enterToNav ) {
this._on( document, { "pageshow": "enterToNav" });
}
},
submitTo: function() {
var url,
form = this.element.parent().find( "form" );
form.attr( "method", "get" )
.attr( "action", this.options.submitTo );
url = this.options.submitTo + "?search=" + this.element.parent().find( "input" ).val();
window.location = url;
},
enterToNav: function() {
var form = this.element.parent().find( "form" );
form.append( "<button type='submit' data-icon='carat-r' data-inline='true' class='ui-hidden-accessible' data-iconpos='notext'>Submit</button>" )
.parent()
.trigger( "create" );
this.element.parent().find( "form" ).children( ".ui-btn" ).addClass( "ui-hidden-accessible" );
this._on( form, {
"submit": "submitHandler"
});
},
enhanced: false,
arrowKeyNav: function() {
var input = this.element.prev("form").find( "input" );
if ( !this.enhanced ) {
this._on( input, {
"keyup": "handleKeyUp"
});
this.enhanced = true;
}
},
handleKeyUp: function( e ) {
var search,
input = this.element.prev("form").find( "input" );
if ( e.which === $.ui.keyCode.DOWN ) {
if ( this.element.find( "li.ui-btn-active" ).length === 0 ) {
this.element.find( "li:first" ).toggleClass( "ui-btn-active" ).find("a").toggleClass( "ui-btn-active" );
} else {
this.element.find( "li.ui-btn-active a" ).toggleClass( "ui-btn-active");
this.element.find( "li.ui-btn-active" ).toggleClass( "ui-btn-active" ).next().toggleClass( "ui-btn-active" ).find("a").toggleClass( "ui-btn-active" );
}
this.highlightDown();
} else if ( e.which === $.ui.keyCode.UP ) {
if ( this.element.find( "li.ui-btn-active" ).length !== 0 ) {
this.element.find( "li.ui-btn-active a" ).toggleClass( "ui-btn-active");
this.element.find( "li.ui-btn-active" ).toggleClass( "ui-btn-active" ).prev().toggleClass( "ui-btn-active" ).find("a").toggleClass( "ui-btn-active" );
} else {
this.element.find( "li:last" ).toggleClass( "ui-btn-active" ).find("a").toggleClass( "ui-btn-active" );
}
this.highlightUp();
} else if ( typeof e.which !== "undefined" ) {
this.element.find( "li.ui-btn-active" ).removeClass( "ui-btn-active" );
if ( this.options.highlight ) {
search = input.val();
this.element.find( "li" ).each(function() {
$( this ).removeHighlight();
$( this ).highlight( search );
});
}
}
},
submitHandler: function() {
if ( this.element.find( "li.ui-btn-active" ).length !== 0 ) {
var href = this.element.find( "li.ui-btn-active a" ).attr( "href" );
$( ":mobile-pagecontainer" ).pagecontainer( "change", href );
return false;
}
if ( this.options.submitTo ) {
this.submitTo();
}
},
highlightDown: function() {
if ( this.element.find( "li.ui-btn-active" ).hasClass( "ui-screen-hidden" ) ) {
this.element.find( "li.ui-btn-active" ).find("a").toggleClass( "ui-btn-active" );
this.element.find( "li.ui-btn-active" ).toggleClass( "ui-btn-active" ).next().toggleClass( "ui-btn-active" ).find("a").toggleClass( "ui-btn-active" );
this.highlightDown();
}
return;
},
highlightUp: function() {
if ( this.element.find( "li.ui-btn-active" ).hasClass( "ui-screen-hidden" ) ) {
this.element.find( "li.ui-btn-active" ).find("a").toggleClass( "ui-btn-active" );
this.element.find( "li.ui-btn-active" ).toggleClass( "ui-btn-active" ).prev().toggleClass( "ui-btn-active" ).find("a").toggleClass( "ui-btn-active" );
this.highlightUp();
}
return;
}
});
})( jQuery );
});
// View demo source code
function attachPopupHandler( popup, sources ) {
popup.one( "popupbeforeposition", function() {
var
collapsibleSet = popup.find( "[data-role='collapsibleset']" ),
collapsible, pre;
$.each( sources, function( idx, options ) {
collapsible = $( "<div data-role='collapsible' data-collapsed='true' data-theme='" + options.theme + "' data-iconpos='right' data-collapsed-icon='carat-l' data-expanded-icon='carat-d' data-content-theme='b'>" +
"<h1>" + options.title + "</h1>" +
"<pre class='brush: " + options.brush + ";'></pre>" +
"</div>" );
pre = collapsible.find( "pre" );
pre.append( options.data.replace( /</gmi, '<' ) );
collapsible
.appendTo( collapsibleSet )
.on( "collapsiblecollapse", function() {
popup.popup( "reposition", { positionTo: "window" } );
})
.on( "collapsibleexpand", function() {
var doReposition = true;
collapsibleSet.find( ":mobile-collapsible" ).not( this ).each( function() {
if ( $( this ).collapsible( "option", "expanded" ) ) {
doReposition = false;
}
});
if ( doReposition ) {
popup.popup( "reposition", { positionTo: "window" } );
}
});
SyntaxHighlighter.highlight( {}, pre[ 0 ] );
});
collapsibleSet.find( "[data-role='collapsible']" ).first().attr( "data-collapsed", "false" );
popup.trigger( "create" );
});
}
function getSnippet( type, selector, source ) {
var text = "", el, absUrl, hash;
if ( selector === "true" ) {
selector = "";
}
// First, try to grab a tag in this document
if ( !$.mobile.path.isPath( selector ) ) {
el = source.find( type + selector );
// If this is not an embedded style, try a stylesheet reference
if ( el.length === 0 && type === "style" ) {
el = source.find( "link[rel='stylesheet']" + selector );
}
text = $( "<div></div>" ).append( el.contents().clone() ).html();
if ( !text ) {
text = "";
selector = el.attr( "href" ) || el.attr( "src" ) || "";
}
}
// If not, try to SJAX in the document referred to by the selector
if ( !text && selector ) {
absUrl = $.mobile.path.makeUrlAbsolute( selector );
hash = $.mobile.path.parseUrl( absUrl ).hash;
// selector is a path to SJAX in
$.ajax( absUrl, { async: false, dataType: "text" } )
.success( function( data, textStatus, jqXHR ) {
text = data;
// If there's a hash we assume this is an HTML document that has a tag
// inside whose ID is the hash
if ( hash ) {
text = $( "<div></div>" ).append( $( data ).find( hash ).contents().clone() ).html();
}
});
}
return text;
}
$( document ).bind( "pagebeforechange", function( e, data ) {
var popup, sources;
if ( data.options && data.options.role === "popup" && data.options.link ) {
sources = data.options.link.jqmData( "sources" );
if ( sources ) {
popup = $( "<div id='jqm-view-source' class='jqm-view-source' data-role='popup' data-theme='none' data-position-to='window'>" +
"<div data-role='collapsibleset' data-inset='true'></div>" +
"</div>" );
attachPopupHandler( popup, sources );
popup
.appendTo( $.mobile.activePage )
.popup()
.bind( "popupafterclose", function() {
popup.remove();
})
.popup( "open" );
e.preventDefault();
}
}
});
function makeButton() {
var d = document.createElement( "div" )
a = document.createElement( "a" ),
txt = document.createTextNode( "View Source" );
a.className = "jqm-view-source-link ui-btn ui-corner-all ui-btn-inline ui-mini";
a.setAttribute( "href", "#popupDemo" );
a.setAttribute( "data-rel", "popup" );
a.appendChild( txt );
d.appendChild( a );
return $( d );
}
$.fn.viewSourceCode = function() {
return $( this ).each( function() {
var button = makeButton(),
self = $( this ),
snippetSource = self.parents( ".ui-page,:jqmData(role='page')" ).add( $( "head" ) ),
fixData = function( data ) {
return data.replace( /\s+$/gm, "" );
},
data,
sources = [];
// Collect source code before it becomes enhanced
if ( self.is( "[data-demo-html]" ) ) {
if ( self.attr( "data-demo-html" ) === "true" ) {
data = self.html();
} else {
data = $( "<div></div>" ).append( $( self.attr( "data-demo-html" ) ).clone() ).html();
}
sources.push( { title: "HTML", theme: "c", brush: "xml", data: fixData( data ) } );
}
if ( self.is( "[data-demo-php]" ) ) {
$.ajax( self.attr( "data-demo-php" ), { async: false } )
.success( function( incoming ) {
data = incoming;
})
.error( function() {
data = "// Failed to retrieve PHP source code";
});
sources.push( { title: "PHP", theme: "d", brush: "php", data: fixData( data ) } );
}
if ( self.is( "[data-demo-js]" ) ) {
data = getSnippet( "script", self.attr( "data-demo-js" ), snippetSource );
sources.push( { title: "JS", theme: "e", brush: "js", data: fixData( data ) } );
}
if ( self.is( "[data-demo-css]" ) ) {
data = getSnippet( "style", self.attr( "data-demo-css" ), snippetSource );
sources.push( { title: "CSS", theme: "f", brush: "css", data: fixData( data ) } );
}
button.insertAfter( this );
button.children().jqmData( "sources", sources );
});
};
$( document ).on( "pagebeforecreate", "[data-role='page']", function() {
$( this ).find( "[data-demo-html], [data-demo-js], [data-demo-css], [data-demo-php]" ).viewSourceCode();
SyntaxHighlighter.defaults['toolbar'] = false;
SyntaxHighlighter.defaults['auto-links'] = false;
});
$( document ).on( "pagecreate", function( e ) {
// prevent page scroll while scrolling source code
$( document ).on( "mousewheel", ".jqm-view-source .ui-collapsible-content", function( event, delta ) {
if ( delta > 0 && $( this ).scrollTop() === 0 ) {
event.preventDefault();
} else if ( delta < 0 && $( this ).scrollTop() === $( this ).get( 0 ).scrollHeight - $( this ).innerHeight() ) {
event.preventDefault();
}
});
// reposition when switching between html / js / css
$( e.target ).delegate( ".jqm-view-source .ui-collapsible", "expand", function() {
$( this ).parents( ":mobile-popup" ).popup( "reposition", { positionTo: "window" } );
});
$( e.target ).delegate( ".jqm-view-source", "popupbeforeposition", function() {
// max height: screen height - tolerance (2*30px) - 42px for each collapsible heading
var x = $( this ).find( ".ui-collapsible" ).length,
maxHeight = $.mobile.getScreenHeight() - 60 - ( x * 42 );
$( this ).find( ".ui-collapsible-content" ).css( "max-height", maxHeight + "px" );
// keep line numbers and code lines in sync
$(".ui-collapsible:not(.ui-collapsible-collapsed) .gutter", this ).find( ".line" ).css( "height", "");
$(".ui-collapsible:not(.ui-collapsible-collapsed) .code", this ).find( ".line" ).each( function() {
if ( $( this ).height() !== 16 ) {
var height = $( this ).height(),
linenumber = ".number" + /number(\w+)/.exec( this.className )[1],
gutter = $( this ).parents( "tr" ).find( "td.gutter" ).first(),
line = $( gutter ).find( linenumber );
$( line ).height( height );
}
});
});
});
/**
* SyntaxHighlighter
* http://alexgorbatchev.com/SyntaxHighlighter
*
* SyntaxHighlighter is donationware. If you are using it, please donate.
* http://alexgorbatchev.com/SyntaxHighlighter/donate.html
*
* @version
* 3.0.83 (July 02 2010)
*
* @copyright
* Copyright (C) 2004-2010 Alex Gorbatchev.
*
* @license
* Dual licensed under the MIT and GPL licenses.
*/
eval(function(p,a,c,k,e,d){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--){d[e(c)]=k[c]||e(c)}k=[function(e){return d[e]}];e=function() {return'\\w+'};c=1};while(c--){if(k[c]){p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c])}}return p}('K M;I(M)1S 2U("2a\'t 4k M 4K 2g 3l 4G 4H");(6(){6 r(f,e){I(!M.1R(f))1S 3m("3s 15 4R");K a=f.1w;f=M(f.1m,t(f)+(e||""));I(a)f.1w={1m:a.1m,19:a.19?a.19.1a(0):N};H f}6 t(f){H(f.1J?"g":"")+(f.4s?"i":"")+(f.4p?"m":"")+(f.4v?"x":"")+(f.3n?"y":"")}6 B(f,e,a,b){K c=u.L,d,h,g;v=R;5K{O(;c--;){g=u[c];I(a&g.3r&&(!g.2p||g.2p.W(b))){g.2q.12=e;I((h=g.2q.X(f))&&h.P===e){d={3k:g.2b.W(b,h,a),1C:h};1N}}}}5v(i){1S i}5q{v=11}H d}6 p(f,e,a){I(3b.Z.1i)H f.1i(e,a);O(a=a||0;a<f.L;a++)I(f[a]===e)H a;H-1}M=6(f,e){K a=[],b=M.1B,c=0,d,h;I(M.1R(f)){I(e!==1d)1S 3m("2a\'t 5r 5I 5F 5B 5C 15 5E 5p");H r(f)}I(v)1S 2U("2a\'t W 3l M 59 5m 5g 5x 5i");e=e||"";O(d={2N:11,19:[],2K:6(g){H e.1i(g)>-1},3d:6(g){e+=g}};c<f.L;)I(h=B(f,c,b,d)){a.U(h.3k);c+=h.1C[0].L||1}Y I(h=n.X.W(z[b],f.1a(c))){a.U(h[0]);c+=h[0].L}Y{h=f.3a(c);I(h==="[")b=M.2I;Y I(h==="]")b=M.1B;a.U(h);c++}a=15(a.1K(""),n.Q.W(e,w,""));a.1w={1m:f,19:d.2N?d.19:N};H a};M.3v="1.5.0";M.2I=1;M.1B=2;K C=/\\$(?:(\\d\\d?|[$&`\'])|{([$\\w]+)})/g,w=/[^5h]+|([\\s\\S])(?=[\\s\\S]*\\1)/g,A=/^(?:[?*+]|{\\d+(?:,\\d*)?})\\??/,v=11,u=[],n={X:15.Z.X,1A:15.Z.1A,1C:1r.Z.1C,Q:1r.Z.Q,1e:1r.Z.1e},x=n.X.W(/()??/,"")[1]===1d,D=6(){K f=/^/g;n.1A.W(f,"");H!f.12}(),y=6(){K f=/x/g;n.Q.W("x",f,"");H!f.12}(),E=15.Z.3n!==1d,z={};z[M.2I]=/^(?:\\\\(?:[0-3][0-7]{0,2}|[4-7][0-7]?|x[\\29-26-f]{2}|u[\\29-26-f]{4}|c[A-3o-z]|[\\s\\S]))/;z[M.1B]=/^(?:\\\\(?:0(?:[0-3][0-7]{0,2}|[4-7][0-7]?)?|[1-9]\\d*|x[\\29-26-f]{2}|u[\\29-26-f]{4}|c[A-3o-z]|[\\s\\S])|\\(\\?[:=!]|[?*+]\\?|{\\d+(?:,\\d*)?}\\??)/;M.1h=6(f,e,a,b){u.U({2q:r(f,"g"+(E?"y":"")),2b:e,3r:a||M.1B,2p:b||N})};M.2n=6(f,e){K a=f+"/"+(e||"");H M.2n[a]||(M.2n[a]=M(f,e))};M.3c=6(f){H r(f,"g")};M.5l=6(f){H f.Q(/[-[\\]{}()*+?.,\\\\^$|#\\s]/g,"\\\\$&")};M.5e=6(f,e,a,b){e=r(e,"g"+(b&&E?"y":""));e.12=a=a||0;f=e.X(f);H b?f&&f.P===a?f:N:f};M.3q=6(){M.1h=6(){1S 2U("2a\'t 55 1h 54 3q")}};M.1R=6(f){H 53.Z.1q.W(f)==="[2m 15]"};M.3p=6(f,e,a,b){O(K c=r(e,"g"),d=-1,h;h=c.X(f);){a.W(b,h,++d,f,c);c.12===h.P&&c.12++}I(e.1J)e.12=0};M.57=6(f,e){H 6 a(b,c){K d=e[c].1I?e[c]:{1I:e[c]},h=r(d.1I,"g"),g=[],i;O(i=0;i<b.L;i++)M.3p(b[i],h,6(k){g.U(d.3j?k[d.3j]||"":k[0])});H c===e.L-1||!g.L?g:a(g,c+1)}([f],0)};15.Z.1p=6(f,e){H J.X(e[0])};15.Z.W=6(f,e){H J.X(e)};15.Z.X=6(f){K e=n.X.1p(J,14),a;I(e){I(!x&&e.L>1&&p(e,"")>-1){a=15(J.1m,n.Q.W(t(J),"g",""));n.Q.W(f.1a(e.P),a,6(){O(K c=1;c<14.L-2;c++)I(14[c]===1d)e[c]=1d})}I(J.1w&&J.1w.19)O(K b=1;b<e.L;b++)I(a=J.1w.19[b-1])e[a]=e[b];!D&&J.1J&&!e[0].L&&J.12>e.P&&J.12--}H e};I(!D)15.Z.1A=6(f){(f=n.X.W(J,f))&&J.1J&&!f[0].L&&J.12>f.P&&J.12--;H!!f};1r.Z.1C=6(f){M.1R(f)||(f=15(f));I(f.1J){K e=n.1C.1p(J,14);f.12=0;H e}H f.X(J)};1r.Z.Q=6(f,e){K a=M.1R(f),b,c;I(a&&1j e.58()==="3f"&&e.1i("${")===-1&&y)H n.Q.1p(J,14);I(a){I(f.1w)b=f.1w.19}Y f+="";I(1j e==="6")c=n.Q.W(J,f,6(){I(b){14[0]=1f 1r(14[0]);O(K d=0;d<b.L;d++)I(b[d])14[0][b[d]]=14[d+1]}I(a&&f.1J)f.12=14[14.L-2]+14[0].L;H e.1p(N,14)});Y{c=J+"";c=n.Q.W(c,f,6(){K d=14;H n.Q.W(e,C,6(h,g,i){I(g)5b(g){24"$":H"$";24"&":H d[0];24"`":H d[d.L-1].1a(0,d[d.L-2]);24"\'":H d[d.L-1].1a(d[d.L-2]+d[0].L);5a:i="";g=+g;I(!g)H h;O(;g>d.L-3;){i=1r.Z.1a.W(g,-1)+i;g=1Q.3i(g/10)}H(g?d[g]||"":"$")+i}Y{g=+i;I(g<=d.L-3)H d[g];g=b?p(b,i):-1;H g>-1?d[g+1]:h}})})}I(a&&f.1J)f.12=0;H c};1r.Z.1e=6(f,e){I(!M.1R(f))H n.1e.1p(J,14);K a=J+"",b=[],c=0,d,h;I(e===1d||+e<0)e=5D;Y{e=1Q.3i(+e);I(!e)H[]}O(f=M.3c(f);d=f.X(a);){I(f.12>c){b.U(a.1a(c,d.P));d.L>1&&d.P<a.L&&3b.Z.U.1p(b,d.1a(1));h=d[0].L;c=f.12;I(b.L>=e)1N}f.12===d.P&&f.12++}I(c===a.L){I(!n.1A.W(f,"")||h)b.U("")}Y b.U(a.1a(c));H b.L>e?b.1a(0,e):b};M.1h(/\\(\\?#[^)]*\\)/,6(f){H n.1A.W(A,f.2S.1a(f.P+f[0].L))?"":"(?:)"});M.1h(/\\((?!\\?)/,6(){J.19.U(N);H"("});M.1h(/\\(\\?<([$\\w]+)>/,6(f){J.19.U(f[1]);J.2N=R;H"("});M.1h(/\\\\k<([\\w$]+)>/,6(f){K e=p(J.19,f[1]);H e>-1?"\\\\"+(e+1)+(3R(f.2S.3a(f.P+f[0].L))?"":"(?:)"):f[0]});M.1h(/\\[\\^?]/,6(f){H f[0]==="[]"?"\\\\b\\\\B":"[\\\\s\\\\S]"});M.1h(/^\\(\\?([5A]+)\\)/,6(f){J.3d(f[1]);H""});M.1h(/(?:\\s+|#.*)+/,6(f){H n.1A.W(A,f.2S.1a(f.P+f[0].L))?"":"(?:)"},M.1B,6(){H J.2K("x")});M.1h(/\\./,6(){H"[\\\\s\\\\S]"},M.1B,6(){H J.2K("s")})})();1j 2e!="1d"&&(2e.M=M);K 1v=6(){6 r(a,b){a.1l.1i(b)!=-1||(a.1l+=" "+b)}6 t(a){H a.1i("3e")==0?a:"3e"+a}6 B(a){H e.1Y.2A[t(a)]}6 p(a,b,c){I(a==N)H N;K d=c!=R?a.3G:[a.2G],h={"#":"1c",".":"1l"}[b.1o(0,1)]||"3h",g,i;g=h!="3h"?b.1o(1):b.5u();I((a[h]||"").1i(g)!=-1)H a;O(a=0;d&&a<d.L&&i==N;a++)i=p(d[a],b,c);H i}6 C(a,b){K c={},d;O(d 2g a)c[d]=a[d];O(d 2g b)c[d]=b[d];H c}6 w(a,b,c,d){6 h(g){g=g||1P.5y;I(!g.1F){g.1F=g.52;g.3N=6(){J.5w=11}}c.W(d||1P,g)}a.3g?a.3g("4U"+b,h):a.4y(b,h,11)}6 A(a,b){K c=e.1Y.2j,d=N;I(c==N){c={};O(K h 2g e.1U){K g=e.1U[h];d=g.4x;I(d!=N){g.1V=h.4w();O(g=0;g<d.L;g++)c[d[g]]=h}}e.1Y.2j=c}d=e.1U[c[a]];d==N&&b!=11&&1P.1X(e.13.1x.1X+(e.13.1x.3E+a));H d}6 v(a,b){O(K c=a.1e("\\n"),d=0;d<c.L;d++)c[d]=b(c[d],d);H c.1K("\\n")}6 u(a,b){I(a==N||a.L==0||a=="\\n")H a;a=a.Q(/</g,"&1y;");a=a.Q(/ {2,}/g,6(c){O(K d="",h=0;h<c.L-1;h++)d+=e.13.1W;H d+" "});I(b!=N)a=v(a,6(c){I(c.L==0)H"";K d="";c=c.Q(/^(&2s;| )+/,6(h){d=h;H""});I(c.L==0)H d;H d+\'<17 1g="\'+b+\'">\'+c+"</17>"});H a}6 n(a,b){a.1e("\\n");O(K c="",d=0;d<50;d++)c+=" ";H a=v(a,6(h){I(h.1i("\\t")==-1)H h;O(K g=0;(g=h.1i("\\t"))!=-1;)h=h.1o(0,g)+c.1o(0,b-g%b)+h.1o(g+1,h.L);H h})}6 x(a){H a.Q(/^\\s+|\\s+$/g,"")}6 D(a,b){I(a.P<b.P)H-1;Y I(a.P>b.P)H 1;Y I(a.L<b.L)H-1;Y I(a.L>b.L)H 1;H 0}6 y(a,b){6 c(k){H k[0]}O(K d=N,h=[],g=b.2D?b.2D:c;(d=b.1I.X(a))!=N;){K i=g(d,b);I(1j i=="3f")i=[1f e.2L(i,d.P,b.23)];h=h.1O(i)}H h}6 E(a){K b=/(.*)((&1G;|&1y;).*)/;H a.Q(e.3A.3M,6(c){K d="",h=N;I(h=b.X(c)){c=h[1];d=h[2]}H\'<a 2h="\'+c+\'">\'+c+"</a>"+d})}6 z(){O(K a=1E.36("1k"),b=[],c=0;c<a.L;c++)a[c].3s=="20"&&b.U(a[c]);H b}6 f(a){a=a.1F;K b=p(a,".20",R);a=p(a,".3O",R);K c=1E.4i("3t");I(!(!a||!b||p(a,"3t"))){B(b.1c);r(b,"1m");O(K d=a.3G,h=[],g=0;g<d.L;g++)h.U(d[g].4z||d[g].4A);h=h.1K("\\r");c.39(1E.4D(h));a.39(c);c.2C();c.4C();w(c,"4u",6(){c.2G.4E(c);b.1l=b.1l.Q("1m","")})}}I(1j 3F!="1d"&&1j M=="1d")M=3F("M").M;K e={2v:{"1g-27":"","2i-1s":1,"2z-1s-2t":11,1M:N,1t:N,"42-45":R,"43-22":4,1u:R,16:R,"3V-17":R,2l:11,"41-40":R,2k:11,"1z-1k":11},13:{1W:"&2s;",2M:R,46:11,44:11,34:"4n",1x:{21:"4o 1m",2P:"?",1X:"1v\\n\\n",3E:"4r\'t 4t 1D O: ",4g:"4m 4B\'t 51 O 1z-1k 4F: ",37:\'<!4T 1z 4S "-//4V//3H 4W 1.0 4Z//4Y" "1Z://2y.3L.3K/4X/3I/3H/3I-4P.4J"><1z 4I="1Z://2y.3L.3K/4L/5L"><3J><4N 1Z-4M="5G-5M" 6K="2O/1z; 6J=6I-8" /><1t>6L 1v</1t></3J><3B 1L="25-6M:6Q,6P,6O,6N-6F;6y-2f:#6x;2f:#6w;25-22:6v;2O-3D:3C;"><T 1L="2O-3D:3C;3w-32:1.6z;"><T 1L="25-22:6A-6E;">1v</T><T 1L="25-22:.6C;3w-6B:6R;"><T>3v 3.0.76 (72 73 3x)</T><T><a 2h="1Z://3u.2w/1v" 1F="38" 1L="2f:#3y">1Z://3u.2w/1v</a></T><T>70 17 6U 71.</T><T>6T 6X-3x 6Y 6D.</T></T><T>6t 61 60 J 1k, 5Z <a 2h="6u://2y.62.2w/63-66/65?64=5X-5W&5P=5O" 1L="2f:#3y">5R</a> 5V <2R/>5U 5T 5S!</T></T></3B></1z>\'}},1Y:{2j:N,2A:{}},1U:{},3A:{6n:/\\/\\*[\\s\\S]*?\\*\\//2c,6m:/\\/\\/.*$/2c,6l:/#.*$/2c,6k:/"([^\\\\"\\n]|\\\\.)*"/g,6o:/\'([^\\\\\'\\n]|\\\\.)*\'/g,6p:1f M(\'"([^\\\\\\\\"]|\\\\\\\\.)*"\',"3z"),6s:1f M("\'([^\\\\\\\\\']|\\\\\\\\.)*\'","3z"),6q:/(&1y;|<)!--[\\s\\S]*?--(&1G;|>)/2c,3M:/\\w+:\\/\\/[\\w-.\\/?%&=:@;]*/g,6a:{18:/(&1y;|<)\\?=?/g,1b:/\\?(&1G;|>)/g},69:{18:/(&1y;|<)%=?/g,1b:/%(&1G;|>)/g},6d:{18:/(&1y;|<)\\s*1k.*?(&1G;|>)/2T,1b:/(&1y;|<)\\/\\s*1k\\s*(&1G;|>)/2T}},16:{1H:6(a){6 b(i,k){H e.16.2o(i,k,e.13.1x[k])}O(K c=\'<T 1g="16">\',d=e.16.2x,h=d.2X,g=0;g<h.L;g++)c+=(d[h[g]].1H||b)(a,h[g]);c+="</T>";H c},2o:6(a,b,c){H\'<2W><a 2h="#" 1g="6e 6h\'+b+" "+b+\'">\'+c+"</a></2W>"},2b:6(a){K b=a.1F,c=b.1l||"";b=B(p(b,".20",R).1c);K d=6(h){H(h=15(h+"6f(\\\\w+)").X(c))?h[1]:N}("6g");b&&d&&e.16.2x[d].2B(b);a.3N()},2x:{2X:["21","2P"],21:{1H:6(a){I(a.V("2l")!=R)H"";K b=a.V("1t");H e.16.2o(a,"21",b?b:e.13.1x.21)},2B:6(a){a=1E.6j(t(a.1c));a.1l=a.1l.Q("47","")}},2P:{2B:6(){K a="68=0";a+=", 18="+(31.30-33)/2+", 32="+(31.2Z-2Y)/2+", 30=33, 2Z=2Y";a=a.Q(/^,/,"");a=1P.6Z("","38",a);a.2C();K b=a.1E;b.6W(e.13.1x.37);b.6V();a.2C()}}}},35:6(a,b){K c;I(b)c=[b];Y{c=1E.36(e.13.34);O(K d=[],h=0;h<c.L;h++)d.U(c[h]);c=d}c=c;d=[];I(e.13.2M)c=c.1O(z());I(c.L===0)H d;O(h=0;h<c.L;h++){O(K g=c[h],i=a,k=c[h].1l,j=3W 0,l={},m=1f M("^\\\\[(?<2V>(.*?))\\\\]$"),s=1f M("(?<27>[\\\\w-]+)\\\\s*:\\\\s*(?<1T>[\\\\w-%#]+|\\\\[.*?\\\\]|\\".*?\\"|\'.*?\')\\\\s*;?","g");(j=s.X(k))!=N;){K o=j.1T.Q(/^[\'"]|[\'"]$/g,"");I(o!=N&&m.1A(o)){o=m.X(o);o=o.2V.L>0?o.2V.1e(/\\s*,\\s*/):[]}l[j.27]=o}g={1F:g,1n:C(i,l)};g.1n.1D!=N&&d.U(g)}H d},1M:6(a,b){K c=J.35(a,b),d=N,h=e.13;I(c.L!==0)O(K g=0;g<c.L;g++){b=c[g];K i=b.1F,k=b.1n,j=k.1D,l;I(j!=N){I(k["1z-1k"]=="R"||e.2v["1z-1k"]==R){d=1f e.4l(j);j="4O"}Y I(d=A(j))d=1f d;Y 6H;l=i.3X;I(h.2M){l=l;K m=x(l),s=11;I(m.1i("<![6G[")==0){m=m.4h(9);s=R}K o=m.L;I(m.1i("]]\\>")==o-3){m=m.4h(0,o-3);s=R}l=s?m:l}I((i.1t||"")!="")k.1t=i.1t;k.1D=j;d.2Q(k);b=d.2F(l);I((i.1c||"")!="")b.1c=i.1c;i.2G.74(b,i)}}},2E:6(a){w(1P,"4k",6(){e.1M(a)})}};e.2E=e.2E;e.1M=e.1M;e.2L=6(a,b,c){J.1T=a;J.P=b;J.L=a.L;J.23=c;J.1V=N};e.2L.Z.1q=6(){H J.1T};e.4l=6(a){6 b(j,l){O(K m=0;m<j.L;m++)j[m].P+=l}K c=A(a),d,h=1f e.1U.5Y,g=J,i="2F 1H 2Q".1e(" ");I(c!=N){d=1f c;O(K k=0;k<i.L;k++)(6(){K j=i[k];g[j]=6(){H h[j].1p(h,14)}})();d.28==N?1P.1X(e.13.1x.1X+(e.13.1x.4g+a)):h.2J.U({1I:d.28.17,2D:6(j){O(K l=j.17,m=[],s=d.2J,o=j.P+j.18.L,F=d.28,q,G=0;G<s.L;G++){q=y(l,s[G]);b(q,o);m=m.1O(q)}I(F.18!=N&&j.18!=N){q=y(j.18,F.18);b(q,j.P);m=m.1O(q)}I(F.1b!=N&&j.1b!=N){q=y(j.1b,F.1b);b(q,j.P+j[0].5Q(j.1b));m=m.1O(q)}O(j=0;j<m.L;j++)m[j].1V=c.1V;H m}})}};e.4j=6(){};e.4j.Z={V:6(a,b){K c=J.1n[a];c=c==N?b:c;K d={"R":R,"11":11}[c];H d==N?c:d},3Y:6(a){H 1E.4i(a)},4c:6(a,b){K c=[];I(a!=N)O(K d=0;d<a.L;d++)I(1j a[d]=="2m")c=c.1O(y(b,a[d]));H J.4e(c.6b(D))},4e:6(a){O(K b=0;b<a.L;b++)I(a[b]!==N)O(K c=a[b],d=c.P+c.L,h=b+1;h<a.L&&a[b]!==N;h++){K g=a[h];I(g!==N)I(g.P>d)1N;Y I(g.P==c.P&&g.L>c.L)a[b]=N;Y I(g.P>=c.P&&g.P<d)a[h]=N}H a},4d:6(a){K b=[],c=2u(J.V("2i-1s"));v(a,6(d,h){b.U(h+c)});H b},3U:6(a){K b=J.V("1M",[]);I(1j b!="2m"&&b.U==N)b=[b];a:{a=a.1q();K c=3W 0;O(c=c=1Q.6c(c||0,0);c<b.L;c++)I(b[c]==a){b=c;1N a}b=-1}H b!=-1},2r:6(a,b,c){a=["1s","6i"+b,"P"+a,"6r"+(b%2==0?1:2).1q()];J.3U(b)&&a.U("67");b==0&&a.U("1N");H\'<T 1g="\'+a.1K(" ")+\'">\'+c+"</T>"},3Q:6(a,b){K c="",d=a.1e("\\n").L,h=2u(J.V("2i-1s")),g=J.V("2z-1s-2t");I(g==R)g=(h+d-1).1q().L;Y I(3R(g)==R)g=0;O(K i=0;i<d;i++){K k=b?b[i]:h+i,j;I(k==0)j=e.13.1W;Y{j=g;O(K l=k.1q();l.L<j;)l="0"+l;j=l}a=j;c+=J.2r(i,k,a)}H c},49:6(a,b){a=x(a);K c=a.1e("\\n");J.V("2z-1s-2t");K d=2u(J.V("2i-1s"));a="";O(K h=J.V("1D"),g=0;g<c.L;g++){K i=c[g],k=/^(&2s;|\\s)+/.X(i),j=N,l=b?b[g]:d+g;I(k!=N){j=k[0].1q();i=i.1o(j.L);j=j.Q(" ",e.13.1W)}i=x(i);I(i.L==0)i=e.13.1W;a+=J.2r(g,l,(j!=N?\'<17 1g="\'+h+\' 5N">\'+j+"</17>":"")+i)}H a},4f:6(a){H a?"<4a>"+a+"</4a>":""},4b:6(a,b){6 c(l){H(l=l?l.1V||g:g)?l+" ":""}O(K d=0,h="",g=J.V("1D",""),i=0;i<b.L;i++){K k=b[i],j;I(!(k===N||k.L===0)){j=c(k);h+=u(a.1o(d,k.P-d),j+"48")+u(k.1T,j+k.23);d=k.P+k.L+(k.75||0)}}h+=u(a.1o(d),c()+"48");H h},1H:6(a){K b="",c=["20"],d;I(J.V("2k")==R)J.1n.16=J.1n.1u=11;1l="20";J.V("2l")==R&&c.U("47");I((1u=J.V("1u"))==11)c.U("6S");c.U(J.V("1g-27"));c.U(J.V("1D"));a=a.Q(/^[ ]*[\\n]+|[\\n]*[ ]*$/g,"").Q(/\\r/g," ");b=J.V("43-22");I(J.V("42-45")==R)a=n(a,b);Y{O(K h="",g=0;g<b;g++)h+=" ";a=a.Q(/\\t/g,h)}a=a;a:{b=a=a;h=/<2R\\s*\\/?>|&1y;2R\\s*\\/?&1G;/2T;I(e.13.46==R)b=b.Q(h,"\\n");I(e.13.44==R)b=b.Q(h,"");b=b.1e("\\n");h=/^\\s*/;g=4Q;O(K i=0;i<b.L&&g>0;i++){K k=b[i];I(x(k).L!=0){k=h.X(k);I(k==N){a=a;1N a}g=1Q.4q(k[0].L,g)}}I(g>0)O(i=0;i<b.L;i++)b[i]=b[i].1o(g);a=b.1K("\\n")}I(1u)d=J.4d(a);b=J.4c(J.2J,a);b=J.4b(a,b);b=J.49(b,d);I(J.V("41-40"))b=E(b);1j 2H!="1d"&&2H.3S&&2H.3S.1C(/5s/)&&c.U("5t");H b=\'<T 1c="\'+t(J.1c)+\'" 1g="\'+c.1K(" ")+\'">\'+(J.V("16")?e.16.1H(J):"")+\'<3Z 5z="0" 5H="0" 5J="0">\'+J.4f(J.V("1t"))+"<3T><3P>"+(1u?\'<2d 1g="1u">\'+J.3Q(a)+"</2d>":"")+\'<2d 1g="17"><T 1g="3O">\'+b+"</T></2d></3P></3T></3Z></T>"},2F:6(a){I(a===N)a="";J.17=a;K b=J.3Y("T");b.3X=J.1H(a);J.V("16")&&w(p(b,".16"),"5c",e.16.2b);J.V("3V-17")&&w(p(b,".17"),"56",f);H b},2Q:6(a){J.1c=""+1Q.5d(1Q.5n()*5k).1q();e.1Y.2A[t(J.1c)]=J;J.1n=C(e.2v,a||{});I(J.V("2k")==R)J.1n.16=J.1n.1u=11},5j:6(a){a=a.Q(/^\\s+|\\s+$/g,"").Q(/\\s+/g,"|");H"\\\\b(?:"+a+")\\\\b"},5f:6(a){J.28={18:{1I:a.18,23:"1k"},1b:{1I:a.1b,23:"1k"},17:1f M("(?<18>"+a.18.1m+")(?<17>.*?)(?<1b>"+a.1b.1m+")","5o")}}};H e}();1j 2e!="1d"&&(2e.1v=1v);',62,441,'||||||function|||||||||||||||||||||||||||||||||||||return|if|this|var|length|XRegExp|null|for|index|replace|true||div|push|getParam|call|exec|else|prototype||false|lastIndex|config|arguments|RegExp|toolbar|code|left|captureNames|slice|right|id|undefined|split|new|class|addToken|indexOf|typeof|script|className|source|params|substr|apply|toString|String|line|title|gutter|SyntaxHighlighter|_xregexp|strings|lt|html|test|OUTSIDE_CLASS|match|brush|document|target|gt|getHtml|regex|global|join|style|highlight|break|concat|window|Math|isRegExp|throw|value|brushes|brushName|space|alert|vars|http|syntaxhighlighter|expandSource|size|css|case|font|Fa|name|htmlScript|dA|can|handler|gm|td|exports|color|in|href|first|discoveredBrushes|light|collapse|object|cache|getButtonHtml|trigger|pattern|getLineHtml|nbsp|numbers|parseInt|defaults|com|items|www|pad|highlighters|execute|focus|func|all|getDiv|parentNode|navigator|INSIDE_CLASS|regexList|hasFlag|Match|useScriptTags|hasNamedCapture|text|help|init|br|input|gi|Error|values|span|list|250|height|width|screen|top|500|tagName|findElements|getElementsByTagName|aboutDialog|_blank|appendChild|charAt|Array|copyAsGlobal|setFlag|highlighter_|string|attachEvent|nodeName|floor|backref|output|the|TypeError|sticky|Za|iterate|freezeTokens|scope|type|textarea|alexgorbatchev|version|margin|2010|005896|gs|regexLib|body|center|align|noBrush|require|childNodes|DTD|xhtml1|head|org|w3|url|preventDefault|container|tr|getLineNumbersHtml|isNaN|userAgent|tbody|isLineHighlighted|quick|void|innerHTML|create|table|links|auto|smart|tab|stripBrs|tabs|bloggerMode|collapsed|plain|getCodeLinesHtml|caption|getMatchesHtml|findMatches|figureOutLineNumbers|removeNestedMatches|getTitleHtml|brushNotHtmlScript|substring|createElement|Highlighter|load|HtmlScript|Brush|pre|expand|multiline|min|Can|ignoreCase|find|blur|extended|toLowerCase|aliases|addEventListener|innerText|textContent|wasn|select|createTextNode|removeChild|option|same|frame|xmlns|dtd|twice|1999|equiv|meta|htmlscript|transitional|1E3|expected|PUBLIC|DOCTYPE|on|W3C|XHTML|TR|EN|Transitional||configured|srcElement|Object|after|run|dblclick|matchChain|valueOf|constructor|default|switch|click|round|execAt|forHtmlScript|token|gimy|functions|getKeywords|1E6|escape|within|random|sgi|another|finally|supply|MSIE|ie|toUpperCase|catch|returnValue|definition|event|border|imsx|constructing|one|Infinity|from|when|Content|cellpadding|flags|cellspacing|try|xhtml|Type|spaces|2930402|hosted_button_id|lastIndexOf|donate|active|development|keep|to|xclick|_s|Xml|please|like|you|paypal|cgi|cmd|webscr|bin|highlighted|scrollbars|aspScriptTags|phpScriptTags|sort|max|scriptScriptTags|toolbar_item|_|command|command_|number|getElementById|doubleQuotedString|singleLinePerlComments|singleLineCComments|multiLineCComments|singleQuotedString|multiLineDoubleQuotedString|xmlComments|alt|multiLineSingleQuotedString|If|https|1em|000|fff|background|5em|xx|bottom|75em|Gorbatchev|large|serif|CDATA|continue|utf|charset|content|About|family|sans|Helvetica|Arial|Geneva|3em|nogutter|Copyright|syntax|close|write|2004|Alex|open|JavaScript|highlighter|July|02|replaceChild|offset|83'.split('|'),0,{}))
;(function()
{
// CommonJS
typeof(require) != 'undefined' ? SyntaxHighlighter = require('shCore').SyntaxHighlighter : null;
function Brush()
{
function process(match, regexInfo)
{
var constructor = SyntaxHighlighter.Match,
code = match[0],
tag = new XRegExp('(<|<)[\\s\\/\\?]*(?<name>[:\\w-\\.]+)', 'xg').exec(code),
result = []
;
if (match.attributes != null)
{
var attributes,
regex = new XRegExp('(?<name> [\\w:\\-\\.]+)' +
'\\s*=\\s*' +
'(?<value> ".*?"|\'.*?\'|\\w+)',
'xg');
while ((attributes = regex.exec(code)) != null)
{
result.push(new constructor(attributes.name, match.index + attributes.index, 'color1'));
result.push(new constructor(attributes.value, match.index + attributes.index + attributes[0].indexOf(attributes.value), 'string'));
}
}
if (tag != null)
result.push(
new constructor(tag.name, match.index + tag[0].indexOf(tag.name), 'keyword')
);
return result;
}
this.regexList = [
{ regex: new XRegExp('(\\<|<)\\!\\[[\\w\\s]*?\\[(.|\\s)*?\\]\\](\\>|>)', 'gm'), css: 'color2' }, // <![ ... [ ... ]]>
{ regex: SyntaxHighlighter.regexLib.xmlComments, css: 'comments' }, // <!-- ... -->
{ regex: new XRegExp('(<|<)[\\s\\/\\?]*(\\w+)(?<attributes>.*?)[\\s\\/\\?]*(>|>)', 'sg'), func: process }
];
};
Brush.prototype = new SyntaxHighlighter.Highlighter();
Brush.aliases = ['xml', 'xhtml', 'xslt', 'html'];
SyntaxHighlighter.brushes.Xml = Brush;
// CommonJS
typeof(exports) != 'undefined' ? exports.Brush = Brush : null;
})();
;(function()
{
// CommonJS
typeof(require) != 'undefined' ? SyntaxHighlighter = require('shCore').SyntaxHighlighter : null;
function Brush()
{
var keywords = 'break case catch continue ' +
'default delete do else false ' +
'for function if in instanceof ' +
'new null return super switch ' +
'this throw true try typeof var while with'
;
var r = SyntaxHighlighter.regexLib;
this.regexList = [
{ regex: r.multiLineDoubleQuotedString, css: 'string' }, // double quoted strings
{ regex: r.multiLineSingleQuotedString, css: 'string' }, // single quoted strings
{ regex: r.singleLineCComments, css: 'comments' }, // one line comments
{ regex: r.multiLineCComments, css: 'comments' }, // multiline comments
{ regex: /\s*#.*/gm, css: 'preprocessor' }, // preprocessor tags like #region and #endregion
{ regex: new RegExp(this.getKeywords(keywords), 'gm'), css: 'keyword' } // keywords
];
this.forHtmlScript(r.scriptScriptTags);
};
Brush.prototype = new SyntaxHighlighter.Highlighter();
Brush.aliases = ['js', 'jscript', 'javascript'];
SyntaxHighlighter.brushes.JScript = Brush;
// CommonJS
typeof(exports) != 'undefined' ? exports.Brush = Brush : null;
})();
;(function()
{
// CommonJS
typeof(require) != 'undefined' ? SyntaxHighlighter = require('shCore').SyntaxHighlighter : null;
function Brush()
{
function getKeywordsCSS(str)
{
return '\\b([a-z_]|)' + str.replace(/ /g, '(?=:)\\b|\\b([a-z_\\*]|\\*|)') + '(?=:)\\b';
};
function getValuesCSS(str)
{
return '\\b' + str.replace(/ /g, '(?!-)(?!:)\\b|\\b()') + '\:\\b';
};
var keywords = 'ascent azimuth background-attachment background-color background-image background-position ' +
'background-repeat background baseline bbox border-collapse border-color border-spacing border-style border-top ' +
'border-right border-bottom border-left border-top-color border-right-color border-bottom-color border-left-color ' +
'border-top-style border-right-style border-bottom-style border-left-style border-top-width border-right-width ' +
'border-bottom-width border-left-width border-width border bottom cap-height caption-side centerline clear clip color ' +
'content counter-increment counter-reset cue-after cue-before cue cursor definition-src descent direction display ' +
'elevation empty-cells float font-size-adjust font-family font-size font-stretch font-style font-variant font-weight font ' +
'height left letter-spacing line-height list-style-image list-style-position list-style-type list-style margin-top ' +
'margin-right margin-bottom margin-left margin marker-offset marks mathline max-height max-width min-height min-width opacity orphans ' +
'outline-color outline-style outline-width outline overflow padding-top padding-right padding-bottom padding-left padding page ' +
'page-break-after page-break-before page-break-inside pause pause-after pause-before pitch pitch-range play-during position ' +
'quotes right richness size slope src speak-header speak-numeral speak-punctuation speak speech-rate stemh stemv stress ' +
'table-layout text-align top text-decoration text-indent text-shadow text-transform unicode-bidi unicode-range units-per-em ' +
'vertical-align visibility voice-family volume white-space widows width widths word-spacing x-height z-index';
var values = 'above absolute all always aqua armenian attr aural auto avoid baseline behind below bidi-override black blink block blue bold bolder '+
'both bottom braille capitalize caption center center-left center-right circle close-quote code collapse compact condensed '+
'continuous counter counters crop cross crosshair cursive dashed decimal decimal-leading-zero default digits disc dotted double '+
'embed embossed e-resize expanded extra-condensed extra-expanded fantasy far-left far-right fast faster fixed format fuchsia '+
'gray green groove handheld hebrew help hidden hide high higher icon inline-table inline inset inside invert italic '+
'justify landscape large larger left-side left leftwards level lighter lime line-through list-item local loud lower-alpha '+
'lowercase lower-greek lower-latin lower-roman lower low ltr marker maroon medium message-box middle mix move narrower '+
'navy ne-resize no-close-quote none no-open-quote no-repeat normal nowrap n-resize nw-resize oblique olive once open-quote outset '+
'outside overline pointer portrait pre print projection purple red relative repeat repeat-x repeat-y rgb ridge right right-side '+
'rightwards rtl run-in screen scroll semi-condensed semi-expanded separate se-resize show silent silver slower slow '+
'small small-caps small-caption smaller soft solid speech spell-out square s-resize static status-bar sub super sw-resize '+
'table-caption table-cell table-column table-column-group table-footer-group table-header-group table-row table-row-group teal '+
'text-bottom text-top thick thin top transparent tty tv ultra-condensed ultra-expanded underline upper-alpha uppercase upper-latin '+
'upper-roman url visible wait white wider w-resize x-fast x-high x-large x-loud x-low x-slow x-small x-soft xx-large xx-small yellow';
var fonts = '[mM]onospace [tT]ahoma [vV]erdana [aA]rial [hH]elvetica [sS]ans-serif [sS]erif [cC]ourier mono sans serif';
this.regexList = [
{ regex: SyntaxHighlighter.regexLib.multiLineCComments, css: 'comments' }, // multiline comments
{ regex: SyntaxHighlighter.regexLib.doubleQuotedString, css: 'string' }, // double quoted strings
{ regex: SyntaxHighlighter.regexLib.singleQuotedString, css: 'string' }, // single quoted strings
{ regex: /\#[a-fA-F0-9]{3,6}/g, css: 'value' }, // html colors
{ regex: /(-?\d+)(\.\d+)?(px|em|pt|\:|\%|)/g, css: 'value' }, // sizes
{ regex: /!important/g, css: 'color3' }, // !important
{ regex: new RegExp(getKeywordsCSS(keywords), 'gm'), css: 'keyword' }, // keywords
{ regex: new RegExp(getValuesCSS(values), 'g'), css: 'value' }, // values
{ regex: new RegExp(this.getKeywords(fonts), 'g'), css: 'color1' } // fonts
];
this.forHtmlScript({
left: /(<|<)\s*style.*?(>|>)/gi,
right: /(<|<)\/\s*style\s*(>|>)/gi
});
};
Brush.prototype = new SyntaxHighlighter.Highlighter();
Brush.aliases = ['css'];
SyntaxHighlighter.brushes.CSS = Brush;
// CommonJS
typeof(exports) != 'undefined' ? exports.Brush = Brush : null;
})();
;(function()
{
// CommonJS
typeof(require) != 'undefined' ? SyntaxHighlighter = require('shCore').SyntaxHighlighter : null;
function Brush()
{
var funcs = 'abs acos acosh addcslashes addslashes ' +
'array_change_key_case array_chunk array_combine array_count_values array_diff '+
'array_diff_assoc array_diff_key array_diff_uassoc array_diff_ukey array_fill '+
'array_filter array_flip array_intersect array_intersect_assoc array_intersect_key '+
'array_intersect_uassoc array_intersect_ukey array_key_exists array_keys array_map '+
'array_merge array_merge_recursive array_multisort array_pad array_pop array_product '+
'array_push array_rand array_reduce array_reverse array_search array_shift '+
'array_slice array_splice array_sum array_udiff array_udiff_assoc '+
'array_udiff_uassoc array_uintersect array_uintersect_assoc '+
'array_uintersect_uassoc array_unique array_unshift array_values array_walk '+
'array_walk_recursive atan atan2 atanh base64_decode base64_encode base_convert '+
'basename bcadd bccomp bcdiv bcmod bcmul bindec bindtextdomain bzclose bzcompress '+
'bzdecompress bzerrno bzerror bzerrstr bzflush bzopen bzread bzwrite ceil chdir '+
'checkdate checkdnsrr chgrp chmod chop chown chr chroot chunk_split class_exists '+
'closedir closelog copy cos cosh count count_chars date decbin dechex decoct '+
'deg2rad delete ebcdic2ascii echo empty end ereg ereg_replace eregi eregi_replace error_log '+
'error_reporting escapeshellarg escapeshellcmd eval exec exit exp explode extension_loaded '+
'feof fflush fgetc fgetcsv fgets fgetss file_exists file_get_contents file_put_contents '+
'fileatime filectime filegroup fileinode filemtime fileowner fileperms filesize filetype '+
'floatval flock floor flush fmod fnmatch fopen fpassthru fprintf fputcsv fputs fread fscanf '+
'fseek fsockopen fstat ftell ftok getallheaders getcwd getdate getenv gethostbyaddr gethostbyname '+
'gethostbynamel getimagesize getlastmod getmxrr getmygid getmyinode getmypid getmyuid getopt '+
'getprotobyname getprotobynumber getrandmax getrusage getservbyname getservbyport gettext '+
'gettimeofday gettype glob gmdate gmmktime ini_alter ini_get ini_get_all ini_restore ini_set '+
'interface_exists intval ip2long is_a is_array is_bool is_callable is_dir is_double '+
'is_executable is_file is_finite is_float is_infinite is_int is_integer is_link is_long '+
'is_nan is_null is_numeric is_object is_readable is_real is_resource is_scalar is_soap_fault '+
'is_string is_subclass_of is_uploaded_file is_writable is_writeable mkdir mktime nl2br '+
'parse_ini_file parse_str parse_url passthru pathinfo print readlink realpath rewind rewinddir rmdir '+
'round str_ireplace str_pad str_repeat str_replace str_rot13 str_shuffle str_split '+
'str_word_count strcasecmp strchr strcmp strcoll strcspn strftime strip_tags stripcslashes '+
'stripos stripslashes stristr strlen strnatcasecmp strnatcmp strncasecmp strncmp strpbrk '+
'strpos strptime strrchr strrev strripos strrpos strspn strstr strtok strtolower strtotime '+
'strtoupper strtr strval substr substr_compare';
var keywords = 'abstract and array as break case catch cfunction class clone const continue declare default die do ' +
'else elseif enddeclare endfor endforeach endif endswitch endwhile extends final for foreach ' +
'function include include_once global goto if implements interface instanceof namespace new ' +
'old_function or private protected public return require require_once static switch ' +
'throw try use var while xor ';
var constants = '__FILE__ __LINE__ __METHOD__ __FUNCTION__ __CLASS__';
this.regexList = [
{ regex: SyntaxHighlighter.regexLib.singleLineCComments, css: 'comments' }, // one line comments
{ regex: SyntaxHighlighter.regexLib.multiLineCComments, css: 'comments' }, // multiline comments
{ regex: SyntaxHighlighter.regexLib.doubleQuotedString, css: 'string' }, // double quoted strings
{ regex: SyntaxHighlighter.regexLib.singleQuotedString, css: 'string' }, // single quoted strings
{ regex: /\$\w+/g, css: 'variable' }, // variables
{ regex: new RegExp(this.getKeywords(funcs), 'gmi'), css: 'functions' }, // common functions
{ regex: new RegExp(this.getKeywords(constants), 'gmi'), css: 'constants' }, // constants
{ regex: new RegExp(this.getKeywords(keywords), 'gm'), css: 'keyword' } // keyword
];
this.forHtmlScript(SyntaxHighlighter.regexLib.phpScriptTags);
};
Brush.prototype = new SyntaxHighlighter.Highlighter();
Brush.aliases = ['php'];
SyntaxHighlighter.brushes.Php = Brush;
// CommonJS
typeof(exports) != 'undefined' ? exports.Brush = Brush : null;
})();
/*! Copyright (c) 2011 Brandon Aaron (http://brandonaaron.net)
* Licensed under the MIT License (LICENSE.txt).
*
* Thanks to: http://adomas.org/javascript-mouse-wheel/ for some pointers.
* Thanks to: Mathias Bank(http://www.mathias-bank.de) for a scope bug fix.
* Thanks to: Seamus Leahy for adding deltaX and deltaY
*
* Version: 3.0.6
*
* Requires: 1.2.2+
*/
(function($) {
var types = ['DOMMouseScroll', 'mousewheel'];
if ($.event.fixHooks) {
for ( var i=types.length; i; ) {
$.event.fixHooks[ types[--i] ] = $.event.mouseHooks;
}
}
$.event.special.mousewheel = {
setup: function() {
if ( this.addEventListener ) {
for ( var i=types.length; i; ) {
this.addEventListener( types[--i], handler, false );
}
} else {
this.onmousewheel = handler;
}
},
teardown: function() {
if ( this.removeEventListener ) {
for ( var i=types.length; i; ) {
this.removeEventListener( types[--i], handler, false );
}
} else {
this.onmousewheel = null;
}
}
};
$.fn.extend({
mousewheel: function(fn) {
return fn ? this.bind("mousewheel", fn) : this.trigger("mousewheel");
},
unmousewheel: function(fn) {
return this.unbind("mousewheel", fn);
}
});
function handler(event) {
var orgEvent = event || window.event, args = [].slice.call( arguments, 1 ), delta = 0, returnValue = true, deltaX = 0, deltaY = 0;
event = $.event.fix(orgEvent);
event.type = "mousewheel";
// Old school scrollwheel delta
if ( orgEvent.wheelDelta ) { delta = orgEvent.wheelDelta/120; }
if ( orgEvent.detail ) { delta = -orgEvent.detail/3; }
// New school multidimensional scroll (touchpads) deltas
deltaY = delta;
// Gecko
if ( orgEvent.axis !== undefined && orgEvent.axis === orgEvent.HORIZONTAL_AXIS ) {
deltaY = 0;
deltaX = -1*delta;
}
// Webkit
if ( orgEvent.wheelDeltaY !== undefined ) { deltaY = orgEvent.wheelDeltaY/120; }
if ( orgEvent.wheelDeltaX !== undefined ) { deltaX = -1*orgEvent.wheelDeltaX/120; }
// Add event and delta to the front of the arguments
args.unshift(event, delta, deltaX, deltaY);
return ($.event.dispatch || $.event.handle).apply(this, args);
}
})(jQuery); | zettwerk.mobile | /zettwerk.mobile-0.2.1.zip/zettwerk.mobile-0.2.1/zettwerk/mobile/static/jquery.mobile-1.4.2/demos/_assets/js/index.js | index.js |
function attachPopupHandler( popup, sources ) {
popup.one( "popupbeforeposition", function() {
var
collapsibleSet = popup.find( "[data-role='collapsibleset']" ),
collapsible, pre;
$.each( sources, function( idx, options ) {
collapsible = $( "<div data-role='collapsible' data-collapsed='true' data-theme='" + options.theme + "' data-iconpos='right' data-collapsed-icon='carat-l' data-expanded-icon='carat-d' data-content-theme='b'>" +
"<h1>" + options.title + "</h1>" +
"<pre class='brush: " + options.brush + ";'></pre>" +
"</div>" );
pre = collapsible.find( "pre" );
pre.append( options.data.replace( /</gmi, '<' ) );
collapsible
.appendTo( collapsibleSet )
.on( "collapsiblecollapse", function() {
popup.popup( "reposition", { positionTo: "window" } );
})
.on( "collapsibleexpand", function() {
var doReposition = true;
collapsibleSet.find( ":mobile-collapsible" ).not( this ).each( function() {
if ( $( this ).collapsible( "option", "expanded" ) ) {
doReposition = false;
}
});
if ( doReposition ) {
popup.popup( "reposition", { positionTo: "window" } );
}
});
SyntaxHighlighter.highlight( {}, pre[ 0 ] );
});
collapsibleSet.find( "[data-role='collapsible']" ).first().attr( "data-collapsed", "false" );
popup.trigger( "create" );
});
}
function getSnippet( type, selector, source ) {
var text = "", el, absUrl, hash;
if ( selector === "true" ) {
selector = "";
}
// First, try to grab a tag in this document
if ( !$.mobile.path.isPath( selector ) ) {
el = source.find( type + selector );
// If this is not an embedded style, try a stylesheet reference
if ( el.length === 0 && type === "style" ) {
el = source.find( "link[rel='stylesheet']" + selector );
}
text = $( "<div></div>" ).append( el.contents().clone() ).html();
if ( !text ) {
text = "";
selector = el.attr( "href" ) || el.attr( "src" ) || "";
}
}
// If not, try to SJAX in the document referred to by the selector
if ( !text && selector ) {
absUrl = $.mobile.path.makeUrlAbsolute( selector );
hash = $.mobile.path.parseUrl( absUrl ).hash;
// selector is a path to SJAX in
$.ajax( absUrl, { async: false, dataType: "text" } )
.success( function( data, textStatus, jqXHR ) {
text = data;
// If there's a hash we assume this is an HTML document that has a tag
// inside whose ID is the hash
if ( hash ) {
text = $( "<div></div>" ).append( $( data ).find( hash ).contents().clone() ).html();
}
});
}
return text;
}
$( document ).bind( "pagebeforechange", function( e, data ) {
var popup, sources;
if ( data.options && data.options.role === "popup" && data.options.link ) {
sources = data.options.link.jqmData( "sources" );
if ( sources ) {
popup = $( "<div id='jqm-view-source' class='jqm-view-source' data-role='popup' data-theme='none' data-position-to='window'>" +
"<div data-role='collapsibleset' data-inset='true'></div>" +
"</div>" );
attachPopupHandler( popup, sources );
popup
.appendTo( $.mobile.activePage )
.popup()
.bind( "popupafterclose", function() {
popup.remove();
})
.popup( "open" );
e.preventDefault();
}
}
});
function makeButton() {
var d = document.createElement( "div" )
a = document.createElement( "a" ),
txt = document.createTextNode( "View Source" );
a.className = "jqm-view-source-link ui-btn ui-corner-all ui-btn-inline ui-mini";
a.setAttribute( "href", "#popupDemo" );
a.setAttribute( "data-rel", "popup" );
a.appendChild( txt );
d.appendChild( a );
return $( d );
}
$.fn.viewSourceCode = function() {
return $( this ).each( function() {
var button = makeButton(),
self = $( this ),
snippetSource = self.parents( ".ui-page,:jqmData(role='page')" ).add( $( "head" ) ),
fixData = function( data ) {
return data.replace( /\s+$/gm, "" );
},
data,
sources = [];
// Collect source code before it becomes enhanced
if ( self.is( "[data-demo-html]" ) ) {
if ( self.attr( "data-demo-html" ) === "true" ) {
data = self.html();
} else {
data = $( "<div></div>" ).append( $( self.attr( "data-demo-html" ) ).clone() ).html();
}
sources.push( { title: "HTML", theme: "c", brush: "xml", data: fixData( data ) } );
}
if ( self.is( "[data-demo-php]" ) ) {
$.ajax( self.attr( "data-demo-php" ), { async: false } )
.success( function( incoming ) {
data = incoming;
})
.error( function() {
data = "// Failed to retrieve PHP source code";
});
sources.push( { title: "PHP", theme: "d", brush: "php", data: fixData( data ) } );
}
if ( self.is( "[data-demo-js]" ) ) {
data = getSnippet( "script", self.attr( "data-demo-js" ), snippetSource );
sources.push( { title: "JS", theme: "e", brush: "js", data: fixData( data ) } );
}
if ( self.is( "[data-demo-css]" ) ) {
data = getSnippet( "style", self.attr( "data-demo-css" ), snippetSource );
sources.push( { title: "CSS", theme: "f", brush: "css", data: fixData( data ) } );
}
button.insertAfter( this );
button.children().jqmData( "sources", sources );
});
};
$( document ).on( "pagebeforecreate", "[data-role='page']", function() {
$( this ).find( "[data-demo-html], [data-demo-js], [data-demo-css], [data-demo-php]" ).viewSourceCode();
SyntaxHighlighter.defaults['toolbar'] = false;
SyntaxHighlighter.defaults['auto-links'] = false;
});
$( document ).on( "pagecreate", function( e ) {
// prevent page scroll while scrolling source code
$( document ).on( "mousewheel", ".jqm-view-source .ui-collapsible-content", function( event, delta ) {
if ( delta > 0 && $( this ).scrollTop() === 0 ) {
event.preventDefault();
} else if ( delta < 0 && $( this ).scrollTop() === $( this ).get( 0 ).scrollHeight - $( this ).innerHeight() ) {
event.preventDefault();
}
});
// reposition when switching between html / js / css
$( e.target ).delegate( ".jqm-view-source .ui-collapsible", "expand", function() {
$( this ).parents( ":mobile-popup" ).popup( "reposition", { positionTo: "window" } );
});
$( e.target ).delegate( ".jqm-view-source", "popupbeforeposition", function() {
// max height: screen height - tolerance (2*30px) - 42px for each collapsible heading
var x = $( this ).find( ".ui-collapsible" ).length,
maxHeight = $.mobile.getScreenHeight() - 60 - ( x * 42 );
$( this ).find( ".ui-collapsible-content" ).css( "max-height", maxHeight + "px" );
// keep line numbers and code lines in sync
$(".ui-collapsible:not(.ui-collapsible-collapsed) .gutter", this ).find( ".line" ).css( "height", "");
$(".ui-collapsible:not(.ui-collapsible-collapsed) .code", this ).find( ".line" ).each( function() {
if ( $( this ).height() !== 16 ) {
var height = $( this ).height(),
linenumber = ".number" + /number(\w+)/.exec( this.className )[1],
gutter = $( this ).parents( "tr" ).find( "td.gutter" ).first(),
line = $( gutter ).find( linenumber );
$( line ).height( height );
}
});
});
});
/**
* SyntaxHighlighter
* http://alexgorbatchev.com/SyntaxHighlighter
*
* SyntaxHighlighter is donationware. If you are using it, please donate.
* http://alexgorbatchev.com/SyntaxHighlighter/donate.html
*
* @version
* 3.0.83 (July 02 2010)
*
* @copyright
* Copyright (C) 2004-2010 Alex Gorbatchev.
*
* @license
* Dual licensed under the MIT and GPL licenses.
*/
eval(function(p,a,c,k,e,d){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--){d[e(c)]=k[c]||e(c)}k=[function(e){return d[e]}];e=function() {return'\\w+'};c=1};while(c--){if(k[c]){p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c])}}return p}('K M;I(M)1S 2U("2a\'t 4k M 4K 2g 3l 4G 4H");(6(){6 r(f,e){I(!M.1R(f))1S 3m("3s 15 4R");K a=f.1w;f=M(f.1m,t(f)+(e||""));I(a)f.1w={1m:a.1m,19:a.19?a.19.1a(0):N};H f}6 t(f){H(f.1J?"g":"")+(f.4s?"i":"")+(f.4p?"m":"")+(f.4v?"x":"")+(f.3n?"y":"")}6 B(f,e,a,b){K c=u.L,d,h,g;v=R;5K{O(;c--;){g=u[c];I(a&g.3r&&(!g.2p||g.2p.W(b))){g.2q.12=e;I((h=g.2q.X(f))&&h.P===e){d={3k:g.2b.W(b,h,a),1C:h};1N}}}}5v(i){1S i}5q{v=11}H d}6 p(f,e,a){I(3b.Z.1i)H f.1i(e,a);O(a=a||0;a<f.L;a++)I(f[a]===e)H a;H-1}M=6(f,e){K a=[],b=M.1B,c=0,d,h;I(M.1R(f)){I(e!==1d)1S 3m("2a\'t 5r 5I 5F 5B 5C 15 5E 5p");H r(f)}I(v)1S 2U("2a\'t W 3l M 59 5m 5g 5x 5i");e=e||"";O(d={2N:11,19:[],2K:6(g){H e.1i(g)>-1},3d:6(g){e+=g}};c<f.L;)I(h=B(f,c,b,d)){a.U(h.3k);c+=h.1C[0].L||1}Y I(h=n.X.W(z[b],f.1a(c))){a.U(h[0]);c+=h[0].L}Y{h=f.3a(c);I(h==="[")b=M.2I;Y I(h==="]")b=M.1B;a.U(h);c++}a=15(a.1K(""),n.Q.W(e,w,""));a.1w={1m:f,19:d.2N?d.19:N};H a};M.3v="1.5.0";M.2I=1;M.1B=2;K C=/\\$(?:(\\d\\d?|[$&`\'])|{([$\\w]+)})/g,w=/[^5h]+|([\\s\\S])(?=[\\s\\S]*\\1)/g,A=/^(?:[?*+]|{\\d+(?:,\\d*)?})\\??/,v=11,u=[],n={X:15.Z.X,1A:15.Z.1A,1C:1r.Z.1C,Q:1r.Z.Q,1e:1r.Z.1e},x=n.X.W(/()??/,"")[1]===1d,D=6(){K f=/^/g;n.1A.W(f,"");H!f.12}(),y=6(){K f=/x/g;n.Q.W("x",f,"");H!f.12}(),E=15.Z.3n!==1d,z={};z[M.2I]=/^(?:\\\\(?:[0-3][0-7]{0,2}|[4-7][0-7]?|x[\\29-26-f]{2}|u[\\29-26-f]{4}|c[A-3o-z]|[\\s\\S]))/;z[M.1B]=/^(?:\\\\(?:0(?:[0-3][0-7]{0,2}|[4-7][0-7]?)?|[1-9]\\d*|x[\\29-26-f]{2}|u[\\29-26-f]{4}|c[A-3o-z]|[\\s\\S])|\\(\\?[:=!]|[?*+]\\?|{\\d+(?:,\\d*)?}\\??)/;M.1h=6(f,e,a,b){u.U({2q:r(f,"g"+(E?"y":"")),2b:e,3r:a||M.1B,2p:b||N})};M.2n=6(f,e){K a=f+"/"+(e||"");H M.2n[a]||(M.2n[a]=M(f,e))};M.3c=6(f){H r(f,"g")};M.5l=6(f){H f.Q(/[-[\\]{}()*+?.,\\\\^$|#\\s]/g,"\\\\$&")};M.5e=6(f,e,a,b){e=r(e,"g"+(b&&E?"y":""));e.12=a=a||0;f=e.X(f);H b?f&&f.P===a?f:N:f};M.3q=6(){M.1h=6(){1S 2U("2a\'t 55 1h 54 3q")}};M.1R=6(f){H 53.Z.1q.W(f)==="[2m 15]"};M.3p=6(f,e,a,b){O(K c=r(e,"g"),d=-1,h;h=c.X(f);){a.W(b,h,++d,f,c);c.12===h.P&&c.12++}I(e.1J)e.12=0};M.57=6(f,e){H 6 a(b,c){K d=e[c].1I?e[c]:{1I:e[c]},h=r(d.1I,"g"),g=[],i;O(i=0;i<b.L;i++)M.3p(b[i],h,6(k){g.U(d.3j?k[d.3j]||"":k[0])});H c===e.L-1||!g.L?g:a(g,c+1)}([f],0)};15.Z.1p=6(f,e){H J.X(e[0])};15.Z.W=6(f,e){H J.X(e)};15.Z.X=6(f){K e=n.X.1p(J,14),a;I(e){I(!x&&e.L>1&&p(e,"")>-1){a=15(J.1m,n.Q.W(t(J),"g",""));n.Q.W(f.1a(e.P),a,6(){O(K c=1;c<14.L-2;c++)I(14[c]===1d)e[c]=1d})}I(J.1w&&J.1w.19)O(K b=1;b<e.L;b++)I(a=J.1w.19[b-1])e[a]=e[b];!D&&J.1J&&!e[0].L&&J.12>e.P&&J.12--}H e};I(!D)15.Z.1A=6(f){(f=n.X.W(J,f))&&J.1J&&!f[0].L&&J.12>f.P&&J.12--;H!!f};1r.Z.1C=6(f){M.1R(f)||(f=15(f));I(f.1J){K e=n.1C.1p(J,14);f.12=0;H e}H f.X(J)};1r.Z.Q=6(f,e){K a=M.1R(f),b,c;I(a&&1j e.58()==="3f"&&e.1i("${")===-1&&y)H n.Q.1p(J,14);I(a){I(f.1w)b=f.1w.19}Y f+="";I(1j e==="6")c=n.Q.W(J,f,6(){I(b){14[0]=1f 1r(14[0]);O(K d=0;d<b.L;d++)I(b[d])14[0][b[d]]=14[d+1]}I(a&&f.1J)f.12=14[14.L-2]+14[0].L;H e.1p(N,14)});Y{c=J+"";c=n.Q.W(c,f,6(){K d=14;H n.Q.W(e,C,6(h,g,i){I(g)5b(g){24"$":H"$";24"&":H d[0];24"`":H d[d.L-1].1a(0,d[d.L-2]);24"\'":H d[d.L-1].1a(d[d.L-2]+d[0].L);5a:i="";g=+g;I(!g)H h;O(;g>d.L-3;){i=1r.Z.1a.W(g,-1)+i;g=1Q.3i(g/10)}H(g?d[g]||"":"$")+i}Y{g=+i;I(g<=d.L-3)H d[g];g=b?p(b,i):-1;H g>-1?d[g+1]:h}})})}I(a&&f.1J)f.12=0;H c};1r.Z.1e=6(f,e){I(!M.1R(f))H n.1e.1p(J,14);K a=J+"",b=[],c=0,d,h;I(e===1d||+e<0)e=5D;Y{e=1Q.3i(+e);I(!e)H[]}O(f=M.3c(f);d=f.X(a);){I(f.12>c){b.U(a.1a(c,d.P));d.L>1&&d.P<a.L&&3b.Z.U.1p(b,d.1a(1));h=d[0].L;c=f.12;I(b.L>=e)1N}f.12===d.P&&f.12++}I(c===a.L){I(!n.1A.W(f,"")||h)b.U("")}Y b.U(a.1a(c));H b.L>e?b.1a(0,e):b};M.1h(/\\(\\?#[^)]*\\)/,6(f){H n.1A.W(A,f.2S.1a(f.P+f[0].L))?"":"(?:)"});M.1h(/\\((?!\\?)/,6(){J.19.U(N);H"("});M.1h(/\\(\\?<([$\\w]+)>/,6(f){J.19.U(f[1]);J.2N=R;H"("});M.1h(/\\\\k<([\\w$]+)>/,6(f){K e=p(J.19,f[1]);H e>-1?"\\\\"+(e+1)+(3R(f.2S.3a(f.P+f[0].L))?"":"(?:)"):f[0]});M.1h(/\\[\\^?]/,6(f){H f[0]==="[]"?"\\\\b\\\\B":"[\\\\s\\\\S]"});M.1h(/^\\(\\?([5A]+)\\)/,6(f){J.3d(f[1]);H""});M.1h(/(?:\\s+|#.*)+/,6(f){H n.1A.W(A,f.2S.1a(f.P+f[0].L))?"":"(?:)"},M.1B,6(){H J.2K("x")});M.1h(/\\./,6(){H"[\\\\s\\\\S]"},M.1B,6(){H J.2K("s")})})();1j 2e!="1d"&&(2e.M=M);K 1v=6(){6 r(a,b){a.1l.1i(b)!=-1||(a.1l+=" "+b)}6 t(a){H a.1i("3e")==0?a:"3e"+a}6 B(a){H e.1Y.2A[t(a)]}6 p(a,b,c){I(a==N)H N;K d=c!=R?a.3G:[a.2G],h={"#":"1c",".":"1l"}[b.1o(0,1)]||"3h",g,i;g=h!="3h"?b.1o(1):b.5u();I((a[h]||"").1i(g)!=-1)H a;O(a=0;d&&a<d.L&&i==N;a++)i=p(d[a],b,c);H i}6 C(a,b){K c={},d;O(d 2g a)c[d]=a[d];O(d 2g b)c[d]=b[d];H c}6 w(a,b,c,d){6 h(g){g=g||1P.5y;I(!g.1F){g.1F=g.52;g.3N=6(){J.5w=11}}c.W(d||1P,g)}a.3g?a.3g("4U"+b,h):a.4y(b,h,11)}6 A(a,b){K c=e.1Y.2j,d=N;I(c==N){c={};O(K h 2g e.1U){K g=e.1U[h];d=g.4x;I(d!=N){g.1V=h.4w();O(g=0;g<d.L;g++)c[d[g]]=h}}e.1Y.2j=c}d=e.1U[c[a]];d==N&&b!=11&&1P.1X(e.13.1x.1X+(e.13.1x.3E+a));H d}6 v(a,b){O(K c=a.1e("\\n"),d=0;d<c.L;d++)c[d]=b(c[d],d);H c.1K("\\n")}6 u(a,b){I(a==N||a.L==0||a=="\\n")H a;a=a.Q(/</g,"&1y;");a=a.Q(/ {2,}/g,6(c){O(K d="",h=0;h<c.L-1;h++)d+=e.13.1W;H d+" "});I(b!=N)a=v(a,6(c){I(c.L==0)H"";K d="";c=c.Q(/^(&2s;| )+/,6(h){d=h;H""});I(c.L==0)H d;H d+\'<17 1g="\'+b+\'">\'+c+"</17>"});H a}6 n(a,b){a.1e("\\n");O(K c="",d=0;d<50;d++)c+=" ";H a=v(a,6(h){I(h.1i("\\t")==-1)H h;O(K g=0;(g=h.1i("\\t"))!=-1;)h=h.1o(0,g)+c.1o(0,b-g%b)+h.1o(g+1,h.L);H h})}6 x(a){H a.Q(/^\\s+|\\s+$/g,"")}6 D(a,b){I(a.P<b.P)H-1;Y I(a.P>b.P)H 1;Y I(a.L<b.L)H-1;Y I(a.L>b.L)H 1;H 0}6 y(a,b){6 c(k){H k[0]}O(K d=N,h=[],g=b.2D?b.2D:c;(d=b.1I.X(a))!=N;){K i=g(d,b);I(1j i=="3f")i=[1f e.2L(i,d.P,b.23)];h=h.1O(i)}H h}6 E(a){K b=/(.*)((&1G;|&1y;).*)/;H a.Q(e.3A.3M,6(c){K d="",h=N;I(h=b.X(c)){c=h[1];d=h[2]}H\'<a 2h="\'+c+\'">\'+c+"</a>"+d})}6 z(){O(K a=1E.36("1k"),b=[],c=0;c<a.L;c++)a[c].3s=="20"&&b.U(a[c]);H b}6 f(a){a=a.1F;K b=p(a,".20",R);a=p(a,".3O",R);K c=1E.4i("3t");I(!(!a||!b||p(a,"3t"))){B(b.1c);r(b,"1m");O(K d=a.3G,h=[],g=0;g<d.L;g++)h.U(d[g].4z||d[g].4A);h=h.1K("\\r");c.39(1E.4D(h));a.39(c);c.2C();c.4C();w(c,"4u",6(){c.2G.4E(c);b.1l=b.1l.Q("1m","")})}}I(1j 3F!="1d"&&1j M=="1d")M=3F("M").M;K e={2v:{"1g-27":"","2i-1s":1,"2z-1s-2t":11,1M:N,1t:N,"42-45":R,"43-22":4,1u:R,16:R,"3V-17":R,2l:11,"41-40":R,2k:11,"1z-1k":11},13:{1W:"&2s;",2M:R,46:11,44:11,34:"4n",1x:{21:"4o 1m",2P:"?",1X:"1v\\n\\n",3E:"4r\'t 4t 1D O: ",4g:"4m 4B\'t 51 O 1z-1k 4F: ",37:\'<!4T 1z 4S "-//4V//3H 4W 1.0 4Z//4Y" "1Z://2y.3L.3K/4X/3I/3H/3I-4P.4J"><1z 4I="1Z://2y.3L.3K/4L/5L"><3J><4N 1Z-4M="5G-5M" 6K="2O/1z; 6J=6I-8" /><1t>6L 1v</1t></3J><3B 1L="25-6M:6Q,6P,6O,6N-6F;6y-2f:#6x;2f:#6w;25-22:6v;2O-3D:3C;"><T 1L="2O-3D:3C;3w-32:1.6z;"><T 1L="25-22:6A-6E;">1v</T><T 1L="25-22:.6C;3w-6B:6R;"><T>3v 3.0.76 (72 73 3x)</T><T><a 2h="1Z://3u.2w/1v" 1F="38" 1L="2f:#3y">1Z://3u.2w/1v</a></T><T>70 17 6U 71.</T><T>6T 6X-3x 6Y 6D.</T></T><T>6t 61 60 J 1k, 5Z <a 2h="6u://2y.62.2w/63-66/65?64=5X-5W&5P=5O" 1L="2f:#3y">5R</a> 5V <2R/>5U 5T 5S!</T></T></3B></1z>\'}},1Y:{2j:N,2A:{}},1U:{},3A:{6n:/\\/\\*[\\s\\S]*?\\*\\//2c,6m:/\\/\\/.*$/2c,6l:/#.*$/2c,6k:/"([^\\\\"\\n]|\\\\.)*"/g,6o:/\'([^\\\\\'\\n]|\\\\.)*\'/g,6p:1f M(\'"([^\\\\\\\\"]|\\\\\\\\.)*"\',"3z"),6s:1f M("\'([^\\\\\\\\\']|\\\\\\\\.)*\'","3z"),6q:/(&1y;|<)!--[\\s\\S]*?--(&1G;|>)/2c,3M:/\\w+:\\/\\/[\\w-.\\/?%&=:@;]*/g,6a:{18:/(&1y;|<)\\?=?/g,1b:/\\?(&1G;|>)/g},69:{18:/(&1y;|<)%=?/g,1b:/%(&1G;|>)/g},6d:{18:/(&1y;|<)\\s*1k.*?(&1G;|>)/2T,1b:/(&1y;|<)\\/\\s*1k\\s*(&1G;|>)/2T}},16:{1H:6(a){6 b(i,k){H e.16.2o(i,k,e.13.1x[k])}O(K c=\'<T 1g="16">\',d=e.16.2x,h=d.2X,g=0;g<h.L;g++)c+=(d[h[g]].1H||b)(a,h[g]);c+="</T>";H c},2o:6(a,b,c){H\'<2W><a 2h="#" 1g="6e 6h\'+b+" "+b+\'">\'+c+"</a></2W>"},2b:6(a){K b=a.1F,c=b.1l||"";b=B(p(b,".20",R).1c);K d=6(h){H(h=15(h+"6f(\\\\w+)").X(c))?h[1]:N}("6g");b&&d&&e.16.2x[d].2B(b);a.3N()},2x:{2X:["21","2P"],21:{1H:6(a){I(a.V("2l")!=R)H"";K b=a.V("1t");H e.16.2o(a,"21",b?b:e.13.1x.21)},2B:6(a){a=1E.6j(t(a.1c));a.1l=a.1l.Q("47","")}},2P:{2B:6(){K a="68=0";a+=", 18="+(31.30-33)/2+", 32="+(31.2Z-2Y)/2+", 30=33, 2Z=2Y";a=a.Q(/^,/,"");a=1P.6Z("","38",a);a.2C();K b=a.1E;b.6W(e.13.1x.37);b.6V();a.2C()}}}},35:6(a,b){K c;I(b)c=[b];Y{c=1E.36(e.13.34);O(K d=[],h=0;h<c.L;h++)d.U(c[h]);c=d}c=c;d=[];I(e.13.2M)c=c.1O(z());I(c.L===0)H d;O(h=0;h<c.L;h++){O(K g=c[h],i=a,k=c[h].1l,j=3W 0,l={},m=1f M("^\\\\[(?<2V>(.*?))\\\\]$"),s=1f M("(?<27>[\\\\w-]+)\\\\s*:\\\\s*(?<1T>[\\\\w-%#]+|\\\\[.*?\\\\]|\\".*?\\"|\'.*?\')\\\\s*;?","g");(j=s.X(k))!=N;){K o=j.1T.Q(/^[\'"]|[\'"]$/g,"");I(o!=N&&m.1A(o)){o=m.X(o);o=o.2V.L>0?o.2V.1e(/\\s*,\\s*/):[]}l[j.27]=o}g={1F:g,1n:C(i,l)};g.1n.1D!=N&&d.U(g)}H d},1M:6(a,b){K c=J.35(a,b),d=N,h=e.13;I(c.L!==0)O(K g=0;g<c.L;g++){b=c[g];K i=b.1F,k=b.1n,j=k.1D,l;I(j!=N){I(k["1z-1k"]=="R"||e.2v["1z-1k"]==R){d=1f e.4l(j);j="4O"}Y I(d=A(j))d=1f d;Y 6H;l=i.3X;I(h.2M){l=l;K m=x(l),s=11;I(m.1i("<![6G[")==0){m=m.4h(9);s=R}K o=m.L;I(m.1i("]]\\>")==o-3){m=m.4h(0,o-3);s=R}l=s?m:l}I((i.1t||"")!="")k.1t=i.1t;k.1D=j;d.2Q(k);b=d.2F(l);I((i.1c||"")!="")b.1c=i.1c;i.2G.74(b,i)}}},2E:6(a){w(1P,"4k",6(){e.1M(a)})}};e.2E=e.2E;e.1M=e.1M;e.2L=6(a,b,c){J.1T=a;J.P=b;J.L=a.L;J.23=c;J.1V=N};e.2L.Z.1q=6(){H J.1T};e.4l=6(a){6 b(j,l){O(K m=0;m<j.L;m++)j[m].P+=l}K c=A(a),d,h=1f e.1U.5Y,g=J,i="2F 1H 2Q".1e(" ");I(c!=N){d=1f c;O(K k=0;k<i.L;k++)(6(){K j=i[k];g[j]=6(){H h[j].1p(h,14)}})();d.28==N?1P.1X(e.13.1x.1X+(e.13.1x.4g+a)):h.2J.U({1I:d.28.17,2D:6(j){O(K l=j.17,m=[],s=d.2J,o=j.P+j.18.L,F=d.28,q,G=0;G<s.L;G++){q=y(l,s[G]);b(q,o);m=m.1O(q)}I(F.18!=N&&j.18!=N){q=y(j.18,F.18);b(q,j.P);m=m.1O(q)}I(F.1b!=N&&j.1b!=N){q=y(j.1b,F.1b);b(q,j.P+j[0].5Q(j.1b));m=m.1O(q)}O(j=0;j<m.L;j++)m[j].1V=c.1V;H m}})}};e.4j=6(){};e.4j.Z={V:6(a,b){K c=J.1n[a];c=c==N?b:c;K d={"R":R,"11":11}[c];H d==N?c:d},3Y:6(a){H 1E.4i(a)},4c:6(a,b){K c=[];I(a!=N)O(K d=0;d<a.L;d++)I(1j a[d]=="2m")c=c.1O(y(b,a[d]));H J.4e(c.6b(D))},4e:6(a){O(K b=0;b<a.L;b++)I(a[b]!==N)O(K c=a[b],d=c.P+c.L,h=b+1;h<a.L&&a[b]!==N;h++){K g=a[h];I(g!==N)I(g.P>d)1N;Y I(g.P==c.P&&g.L>c.L)a[b]=N;Y I(g.P>=c.P&&g.P<d)a[h]=N}H a},4d:6(a){K b=[],c=2u(J.V("2i-1s"));v(a,6(d,h){b.U(h+c)});H b},3U:6(a){K b=J.V("1M",[]);I(1j b!="2m"&&b.U==N)b=[b];a:{a=a.1q();K c=3W 0;O(c=c=1Q.6c(c||0,0);c<b.L;c++)I(b[c]==a){b=c;1N a}b=-1}H b!=-1},2r:6(a,b,c){a=["1s","6i"+b,"P"+a,"6r"+(b%2==0?1:2).1q()];J.3U(b)&&a.U("67");b==0&&a.U("1N");H\'<T 1g="\'+a.1K(" ")+\'">\'+c+"</T>"},3Q:6(a,b){K c="",d=a.1e("\\n").L,h=2u(J.V("2i-1s")),g=J.V("2z-1s-2t");I(g==R)g=(h+d-1).1q().L;Y I(3R(g)==R)g=0;O(K i=0;i<d;i++){K k=b?b[i]:h+i,j;I(k==0)j=e.13.1W;Y{j=g;O(K l=k.1q();l.L<j;)l="0"+l;j=l}a=j;c+=J.2r(i,k,a)}H c},49:6(a,b){a=x(a);K c=a.1e("\\n");J.V("2z-1s-2t");K d=2u(J.V("2i-1s"));a="";O(K h=J.V("1D"),g=0;g<c.L;g++){K i=c[g],k=/^(&2s;|\\s)+/.X(i),j=N,l=b?b[g]:d+g;I(k!=N){j=k[0].1q();i=i.1o(j.L);j=j.Q(" ",e.13.1W)}i=x(i);I(i.L==0)i=e.13.1W;a+=J.2r(g,l,(j!=N?\'<17 1g="\'+h+\' 5N">\'+j+"</17>":"")+i)}H a},4f:6(a){H a?"<4a>"+a+"</4a>":""},4b:6(a,b){6 c(l){H(l=l?l.1V||g:g)?l+" ":""}O(K d=0,h="",g=J.V("1D",""),i=0;i<b.L;i++){K k=b[i],j;I(!(k===N||k.L===0)){j=c(k);h+=u(a.1o(d,k.P-d),j+"48")+u(k.1T,j+k.23);d=k.P+k.L+(k.75||0)}}h+=u(a.1o(d),c()+"48");H h},1H:6(a){K b="",c=["20"],d;I(J.V("2k")==R)J.1n.16=J.1n.1u=11;1l="20";J.V("2l")==R&&c.U("47");I((1u=J.V("1u"))==11)c.U("6S");c.U(J.V("1g-27"));c.U(J.V("1D"));a=a.Q(/^[ ]*[\\n]+|[\\n]*[ ]*$/g,"").Q(/\\r/g," ");b=J.V("43-22");I(J.V("42-45")==R)a=n(a,b);Y{O(K h="",g=0;g<b;g++)h+=" ";a=a.Q(/\\t/g,h)}a=a;a:{b=a=a;h=/<2R\\s*\\/?>|&1y;2R\\s*\\/?&1G;/2T;I(e.13.46==R)b=b.Q(h,"\\n");I(e.13.44==R)b=b.Q(h,"");b=b.1e("\\n");h=/^\\s*/;g=4Q;O(K i=0;i<b.L&&g>0;i++){K k=b[i];I(x(k).L!=0){k=h.X(k);I(k==N){a=a;1N a}g=1Q.4q(k[0].L,g)}}I(g>0)O(i=0;i<b.L;i++)b[i]=b[i].1o(g);a=b.1K("\\n")}I(1u)d=J.4d(a);b=J.4c(J.2J,a);b=J.4b(a,b);b=J.49(b,d);I(J.V("41-40"))b=E(b);1j 2H!="1d"&&2H.3S&&2H.3S.1C(/5s/)&&c.U("5t");H b=\'<T 1c="\'+t(J.1c)+\'" 1g="\'+c.1K(" ")+\'">\'+(J.V("16")?e.16.1H(J):"")+\'<3Z 5z="0" 5H="0" 5J="0">\'+J.4f(J.V("1t"))+"<3T><3P>"+(1u?\'<2d 1g="1u">\'+J.3Q(a)+"</2d>":"")+\'<2d 1g="17"><T 1g="3O">\'+b+"</T></2d></3P></3T></3Z></T>"},2F:6(a){I(a===N)a="";J.17=a;K b=J.3Y("T");b.3X=J.1H(a);J.V("16")&&w(p(b,".16"),"5c",e.16.2b);J.V("3V-17")&&w(p(b,".17"),"56",f);H b},2Q:6(a){J.1c=""+1Q.5d(1Q.5n()*5k).1q();e.1Y.2A[t(J.1c)]=J;J.1n=C(e.2v,a||{});I(J.V("2k")==R)J.1n.16=J.1n.1u=11},5j:6(a){a=a.Q(/^\\s+|\\s+$/g,"").Q(/\\s+/g,"|");H"\\\\b(?:"+a+")\\\\b"},5f:6(a){J.28={18:{1I:a.18,23:"1k"},1b:{1I:a.1b,23:"1k"},17:1f M("(?<18>"+a.18.1m+")(?<17>.*?)(?<1b>"+a.1b.1m+")","5o")}}};H e}();1j 2e!="1d"&&(2e.1v=1v);',62,441,'||||||function|||||||||||||||||||||||||||||||||||||return|if|this|var|length|XRegExp|null|for|index|replace|true||div|push|getParam|call|exec|else|prototype||false|lastIndex|config|arguments|RegExp|toolbar|code|left|captureNames|slice|right|id|undefined|split|new|class|addToken|indexOf|typeof|script|className|source|params|substr|apply|toString|String|line|title|gutter|SyntaxHighlighter|_xregexp|strings|lt|html|test|OUTSIDE_CLASS|match|brush|document|target|gt|getHtml|regex|global|join|style|highlight|break|concat|window|Math|isRegExp|throw|value|brushes|brushName|space|alert|vars|http|syntaxhighlighter|expandSource|size|css|case|font|Fa|name|htmlScript|dA|can|handler|gm|td|exports|color|in|href|first|discoveredBrushes|light|collapse|object|cache|getButtonHtml|trigger|pattern|getLineHtml|nbsp|numbers|parseInt|defaults|com|items|www|pad|highlighters|execute|focus|func|all|getDiv|parentNode|navigator|INSIDE_CLASS|regexList|hasFlag|Match|useScriptTags|hasNamedCapture|text|help|init|br|input|gi|Error|values|span|list|250|height|width|screen|top|500|tagName|findElements|getElementsByTagName|aboutDialog|_blank|appendChild|charAt|Array|copyAsGlobal|setFlag|highlighter_|string|attachEvent|nodeName|floor|backref|output|the|TypeError|sticky|Za|iterate|freezeTokens|scope|type|textarea|alexgorbatchev|version|margin|2010|005896|gs|regexLib|body|center|align|noBrush|require|childNodes|DTD|xhtml1|head|org|w3|url|preventDefault|container|tr|getLineNumbersHtml|isNaN|userAgent|tbody|isLineHighlighted|quick|void|innerHTML|create|table|links|auto|smart|tab|stripBrs|tabs|bloggerMode|collapsed|plain|getCodeLinesHtml|caption|getMatchesHtml|findMatches|figureOutLineNumbers|removeNestedMatches|getTitleHtml|brushNotHtmlScript|substring|createElement|Highlighter|load|HtmlScript|Brush|pre|expand|multiline|min|Can|ignoreCase|find|blur|extended|toLowerCase|aliases|addEventListener|innerText|textContent|wasn|select|createTextNode|removeChild|option|same|frame|xmlns|dtd|twice|1999|equiv|meta|htmlscript|transitional|1E3|expected|PUBLIC|DOCTYPE|on|W3C|XHTML|TR|EN|Transitional||configured|srcElement|Object|after|run|dblclick|matchChain|valueOf|constructor|default|switch|click|round|execAt|forHtmlScript|token|gimy|functions|getKeywords|1E6|escape|within|random|sgi|another|finally|supply|MSIE|ie|toUpperCase|catch|returnValue|definition|event|border|imsx|constructing|one|Infinity|from|when|Content|cellpadding|flags|cellspacing|try|xhtml|Type|spaces|2930402|hosted_button_id|lastIndexOf|donate|active|development|keep|to|xclick|_s|Xml|please|like|you|paypal|cgi|cmd|webscr|bin|highlighted|scrollbars|aspScriptTags|phpScriptTags|sort|max|scriptScriptTags|toolbar_item|_|command|command_|number|getElementById|doubleQuotedString|singleLinePerlComments|singleLineCComments|multiLineCComments|singleQuotedString|multiLineDoubleQuotedString|xmlComments|alt|multiLineSingleQuotedString|If|https|1em|000|fff|background|5em|xx|bottom|75em|Gorbatchev|large|serif|CDATA|continue|utf|charset|content|About|family|sans|Helvetica|Arial|Geneva|3em|nogutter|Copyright|syntax|close|write|2004|Alex|open|JavaScript|highlighter|July|02|replaceChild|offset|83'.split('|'),0,{}))
;(function()
{
// CommonJS
typeof(require) != 'undefined' ? SyntaxHighlighter = require('shCore').SyntaxHighlighter : null;
function Brush()
{
function process(match, regexInfo)
{
var constructor = SyntaxHighlighter.Match,
code = match[0],
tag = new XRegExp('(<|<)[\\s\\/\\?]*(?<name>[:\\w-\\.]+)', 'xg').exec(code),
result = []
;
if (match.attributes != null)
{
var attributes,
regex = new XRegExp('(?<name> [\\w:\\-\\.]+)' +
'\\s*=\\s*' +
'(?<value> ".*?"|\'.*?\'|\\w+)',
'xg');
while ((attributes = regex.exec(code)) != null)
{
result.push(new constructor(attributes.name, match.index + attributes.index, 'color1'));
result.push(new constructor(attributes.value, match.index + attributes.index + attributes[0].indexOf(attributes.value), 'string'));
}
}
if (tag != null)
result.push(
new constructor(tag.name, match.index + tag[0].indexOf(tag.name), 'keyword')
);
return result;
}
this.regexList = [
{ regex: new XRegExp('(\\<|<)\\!\\[[\\w\\s]*?\\[(.|\\s)*?\\]\\](\\>|>)', 'gm'), css: 'color2' }, // <![ ... [ ... ]]>
{ regex: SyntaxHighlighter.regexLib.xmlComments, css: 'comments' }, // <!-- ... -->
{ regex: new XRegExp('(<|<)[\\s\\/\\?]*(\\w+)(?<attributes>.*?)[\\s\\/\\?]*(>|>)', 'sg'), func: process }
];
};
Brush.prototype = new SyntaxHighlighter.Highlighter();
Brush.aliases = ['xml', 'xhtml', 'xslt', 'html'];
SyntaxHighlighter.brushes.Xml = Brush;
// CommonJS
typeof(exports) != 'undefined' ? exports.Brush = Brush : null;
})();
;(function()
{
// CommonJS
typeof(require) != 'undefined' ? SyntaxHighlighter = require('shCore').SyntaxHighlighter : null;
function Brush()
{
var keywords = 'break case catch continue ' +
'default delete do else false ' +
'for function if in instanceof ' +
'new null return super switch ' +
'this throw true try typeof var while with'
;
var r = SyntaxHighlighter.regexLib;
this.regexList = [
{ regex: r.multiLineDoubleQuotedString, css: 'string' }, // double quoted strings
{ regex: r.multiLineSingleQuotedString, css: 'string' }, // single quoted strings
{ regex: r.singleLineCComments, css: 'comments' }, // one line comments
{ regex: r.multiLineCComments, css: 'comments' }, // multiline comments
{ regex: /\s*#.*/gm, css: 'preprocessor' }, // preprocessor tags like #region and #endregion
{ regex: new RegExp(this.getKeywords(keywords), 'gm'), css: 'keyword' } // keywords
];
this.forHtmlScript(r.scriptScriptTags);
};
Brush.prototype = new SyntaxHighlighter.Highlighter();
Brush.aliases = ['js', 'jscript', 'javascript'];
SyntaxHighlighter.brushes.JScript = Brush;
// CommonJS
typeof(exports) != 'undefined' ? exports.Brush = Brush : null;
})();
;(function()
{
// CommonJS
typeof(require) != 'undefined' ? SyntaxHighlighter = require('shCore').SyntaxHighlighter : null;
function Brush()
{
function getKeywordsCSS(str)
{
return '\\b([a-z_]|)' + str.replace(/ /g, '(?=:)\\b|\\b([a-z_\\*]|\\*|)') + '(?=:)\\b';
};
function getValuesCSS(str)
{
return '\\b' + str.replace(/ /g, '(?!-)(?!:)\\b|\\b()') + '\:\\b';
};
var keywords = 'ascent azimuth background-attachment background-color background-image background-position ' +
'background-repeat background baseline bbox border-collapse border-color border-spacing border-style border-top ' +
'border-right border-bottom border-left border-top-color border-right-color border-bottom-color border-left-color ' +
'border-top-style border-right-style border-bottom-style border-left-style border-top-width border-right-width ' +
'border-bottom-width border-left-width border-width border bottom cap-height caption-side centerline clear clip color ' +
'content counter-increment counter-reset cue-after cue-before cue cursor definition-src descent direction display ' +
'elevation empty-cells float font-size-adjust font-family font-size font-stretch font-style font-variant font-weight font ' +
'height left letter-spacing line-height list-style-image list-style-position list-style-type list-style margin-top ' +
'margin-right margin-bottom margin-left margin marker-offset marks mathline max-height max-width min-height min-width opacity orphans ' +
'outline-color outline-style outline-width outline overflow padding-top padding-right padding-bottom padding-left padding page ' +
'page-break-after page-break-before page-break-inside pause pause-after pause-before pitch pitch-range play-during position ' +
'quotes right richness size slope src speak-header speak-numeral speak-punctuation speak speech-rate stemh stemv stress ' +
'table-layout text-align top text-decoration text-indent text-shadow text-transform unicode-bidi unicode-range units-per-em ' +
'vertical-align visibility voice-family volume white-space widows width widths word-spacing x-height z-index';
var values = 'above absolute all always aqua armenian attr aural auto avoid baseline behind below bidi-override black blink block blue bold bolder '+
'both bottom braille capitalize caption center center-left center-right circle close-quote code collapse compact condensed '+
'continuous counter counters crop cross crosshair cursive dashed decimal decimal-leading-zero default digits disc dotted double '+
'embed embossed e-resize expanded extra-condensed extra-expanded fantasy far-left far-right fast faster fixed format fuchsia '+
'gray green groove handheld hebrew help hidden hide high higher icon inline-table inline inset inside invert italic '+
'justify landscape large larger left-side left leftwards level lighter lime line-through list-item local loud lower-alpha '+
'lowercase lower-greek lower-latin lower-roman lower low ltr marker maroon medium message-box middle mix move narrower '+
'navy ne-resize no-close-quote none no-open-quote no-repeat normal nowrap n-resize nw-resize oblique olive once open-quote outset '+
'outside overline pointer portrait pre print projection purple red relative repeat repeat-x repeat-y rgb ridge right right-side '+
'rightwards rtl run-in screen scroll semi-condensed semi-expanded separate se-resize show silent silver slower slow '+
'small small-caps small-caption smaller soft solid speech spell-out square s-resize static status-bar sub super sw-resize '+
'table-caption table-cell table-column table-column-group table-footer-group table-header-group table-row table-row-group teal '+
'text-bottom text-top thick thin top transparent tty tv ultra-condensed ultra-expanded underline upper-alpha uppercase upper-latin '+
'upper-roman url visible wait white wider w-resize x-fast x-high x-large x-loud x-low x-slow x-small x-soft xx-large xx-small yellow';
var fonts = '[mM]onospace [tT]ahoma [vV]erdana [aA]rial [hH]elvetica [sS]ans-serif [sS]erif [cC]ourier mono sans serif';
this.regexList = [
{ regex: SyntaxHighlighter.regexLib.multiLineCComments, css: 'comments' }, // multiline comments
{ regex: SyntaxHighlighter.regexLib.doubleQuotedString, css: 'string' }, // double quoted strings
{ regex: SyntaxHighlighter.regexLib.singleQuotedString, css: 'string' }, // single quoted strings
{ regex: /\#[a-fA-F0-9]{3,6}/g, css: 'value' }, // html colors
{ regex: /(-?\d+)(\.\d+)?(px|em|pt|\:|\%|)/g, css: 'value' }, // sizes
{ regex: /!important/g, css: 'color3' }, // !important
{ regex: new RegExp(getKeywordsCSS(keywords), 'gm'), css: 'keyword' }, // keywords
{ regex: new RegExp(getValuesCSS(values), 'g'), css: 'value' }, // values
{ regex: new RegExp(this.getKeywords(fonts), 'g'), css: 'color1' } // fonts
];
this.forHtmlScript({
left: /(<|<)\s*style.*?(>|>)/gi,
right: /(<|<)\/\s*style\s*(>|>)/gi
});
};
Brush.prototype = new SyntaxHighlighter.Highlighter();
Brush.aliases = ['css'];
SyntaxHighlighter.brushes.CSS = Brush;
// CommonJS
typeof(exports) != 'undefined' ? exports.Brush = Brush : null;
})();
;(function()
{
// CommonJS
typeof(require) != 'undefined' ? SyntaxHighlighter = require('shCore').SyntaxHighlighter : null;
function Brush()
{
var funcs = 'abs acos acosh addcslashes addslashes ' +
'array_change_key_case array_chunk array_combine array_count_values array_diff '+
'array_diff_assoc array_diff_key array_diff_uassoc array_diff_ukey array_fill '+
'array_filter array_flip array_intersect array_intersect_assoc array_intersect_key '+
'array_intersect_uassoc array_intersect_ukey array_key_exists array_keys array_map '+
'array_merge array_merge_recursive array_multisort array_pad array_pop array_product '+
'array_push array_rand array_reduce array_reverse array_search array_shift '+
'array_slice array_splice array_sum array_udiff array_udiff_assoc '+
'array_udiff_uassoc array_uintersect array_uintersect_assoc '+
'array_uintersect_uassoc array_unique array_unshift array_values array_walk '+
'array_walk_recursive atan atan2 atanh base64_decode base64_encode base_convert '+
'basename bcadd bccomp bcdiv bcmod bcmul bindec bindtextdomain bzclose bzcompress '+
'bzdecompress bzerrno bzerror bzerrstr bzflush bzopen bzread bzwrite ceil chdir '+
'checkdate checkdnsrr chgrp chmod chop chown chr chroot chunk_split class_exists '+
'closedir closelog copy cos cosh count count_chars date decbin dechex decoct '+
'deg2rad delete ebcdic2ascii echo empty end ereg ereg_replace eregi eregi_replace error_log '+
'error_reporting escapeshellarg escapeshellcmd eval exec exit exp explode extension_loaded '+
'feof fflush fgetc fgetcsv fgets fgetss file_exists file_get_contents file_put_contents '+
'fileatime filectime filegroup fileinode filemtime fileowner fileperms filesize filetype '+
'floatval flock floor flush fmod fnmatch fopen fpassthru fprintf fputcsv fputs fread fscanf '+
'fseek fsockopen fstat ftell ftok getallheaders getcwd getdate getenv gethostbyaddr gethostbyname '+
'gethostbynamel getimagesize getlastmod getmxrr getmygid getmyinode getmypid getmyuid getopt '+
'getprotobyname getprotobynumber getrandmax getrusage getservbyname getservbyport gettext '+
'gettimeofday gettype glob gmdate gmmktime ini_alter ini_get ini_get_all ini_restore ini_set '+
'interface_exists intval ip2long is_a is_array is_bool is_callable is_dir is_double '+
'is_executable is_file is_finite is_float is_infinite is_int is_integer is_link is_long '+
'is_nan is_null is_numeric is_object is_readable is_real is_resource is_scalar is_soap_fault '+
'is_string is_subclass_of is_uploaded_file is_writable is_writeable mkdir mktime nl2br '+
'parse_ini_file parse_str parse_url passthru pathinfo print readlink realpath rewind rewinddir rmdir '+
'round str_ireplace str_pad str_repeat str_replace str_rot13 str_shuffle str_split '+
'str_word_count strcasecmp strchr strcmp strcoll strcspn strftime strip_tags stripcslashes '+
'stripos stripslashes stristr strlen strnatcasecmp strnatcmp strncasecmp strncmp strpbrk '+
'strpos strptime strrchr strrev strripos strrpos strspn strstr strtok strtolower strtotime '+
'strtoupper strtr strval substr substr_compare';
var keywords = 'abstract and array as break case catch cfunction class clone const continue declare default die do ' +
'else elseif enddeclare endfor endforeach endif endswitch endwhile extends final for foreach ' +
'function include include_once global goto if implements interface instanceof namespace new ' +
'old_function or private protected public return require require_once static switch ' +
'throw try use var while xor ';
var constants = '__FILE__ __LINE__ __METHOD__ __FUNCTION__ __CLASS__';
this.regexList = [
{ regex: SyntaxHighlighter.regexLib.singleLineCComments, css: 'comments' }, // one line comments
{ regex: SyntaxHighlighter.regexLib.multiLineCComments, css: 'comments' }, // multiline comments
{ regex: SyntaxHighlighter.regexLib.doubleQuotedString, css: 'string' }, // double quoted strings
{ regex: SyntaxHighlighter.regexLib.singleQuotedString, css: 'string' }, // single quoted strings
{ regex: /\$\w+/g, css: 'variable' }, // variables
{ regex: new RegExp(this.getKeywords(funcs), 'gmi'), css: 'functions' }, // common functions
{ regex: new RegExp(this.getKeywords(constants), 'gmi'), css: 'constants' }, // constants
{ regex: new RegExp(this.getKeywords(keywords), 'gm'), css: 'keyword' } // keyword
];
this.forHtmlScript(SyntaxHighlighter.regexLib.phpScriptTags);
};
Brush.prototype = new SyntaxHighlighter.Highlighter();
Brush.aliases = ['php'];
SyntaxHighlighter.brushes.Php = Brush;
// CommonJS
typeof(exports) != 'undefined' ? exports.Brush = Brush : null;
})();
/*! Copyright (c) 2011 Brandon Aaron (http://brandonaaron.net)
* Licensed under the MIT License (LICENSE.txt).
*
* Thanks to: http://adomas.org/javascript-mouse-wheel/ for some pointers.
* Thanks to: Mathias Bank(http://www.mathias-bank.de) for a scope bug fix.
* Thanks to: Seamus Leahy for adding deltaX and deltaY
*
* Version: 3.0.6
*
* Requires: 1.2.2+
*/
(function($) {
var types = ['DOMMouseScroll', 'mousewheel'];
if ($.event.fixHooks) {
for ( var i=types.length; i; ) {
$.event.fixHooks[ types[--i] ] = $.event.mouseHooks;
}
}
$.event.special.mousewheel = {
setup: function() {
if ( this.addEventListener ) {
for ( var i=types.length; i; ) {
this.addEventListener( types[--i], handler, false );
}
} else {
this.onmousewheel = handler;
}
},
teardown: function() {
if ( this.removeEventListener ) {
for ( var i=types.length; i; ) {
this.removeEventListener( types[--i], handler, false );
}
} else {
this.onmousewheel = null;
}
}
};
$.fn.extend({
mousewheel: function(fn) {
return fn ? this.bind("mousewheel", fn) : this.trigger("mousewheel");
},
unmousewheel: function(fn) {
return this.unbind("mousewheel", fn);
}
});
function handler(event) {
var orgEvent = event || window.event, args = [].slice.call( arguments, 1 ), delta = 0, returnValue = true, deltaX = 0, deltaY = 0;
event = $.event.fix(orgEvent);
event.type = "mousewheel";
// Old school scrollwheel delta
if ( orgEvent.wheelDelta ) { delta = orgEvent.wheelDelta/120; }
if ( orgEvent.detail ) { delta = -orgEvent.detail/3; }
// New school multidimensional scroll (touchpads) deltas
deltaY = delta;
// Gecko
if ( orgEvent.axis !== undefined && orgEvent.axis === orgEvent.HORIZONTAL_AXIS ) {
deltaY = 0;
deltaX = -1*delta;
}
// Webkit
if ( orgEvent.wheelDeltaY !== undefined ) { deltaY = orgEvent.wheelDeltaY/120; }
if ( orgEvent.wheelDeltaX !== undefined ) { deltaX = -1*orgEvent.wheelDeltaX/120; }
// Add event and delta to the front of the arguments
args.unshift(event, delta, deltaX, deltaY);
return ($.event.dispatch || $.event.handle).apply(this, args);
}
})(jQuery); | zettwerk.mobile | /zettwerk.mobile-0.2.1.zip/zettwerk.mobile-0.2.1/zettwerk/mobile/static/jquery.mobile-1.4.2/demos/_assets/js/view-source.js | view-source.js |
$.mobile.document.on( "pageshow", "#demo-page", function() {
var head = $( ".ui-page-active [data-role='header']" ),
foot = $( ".ui-page-active [data-role='footer']" ),
headerheight = head.outerHeight();
$.mobile.window.on( "throttledresize", function() {
$( "#sorter" ).height( $.mobile.window.height() - headerheight - 20 ).css( "top", headerheight + 18 );
});
$( "#sorter" ).height( $.mobile.window.height() - headerheight - 20 ).css( "top", headerheight + 18 );
$.mobile.window.scroll( function( e ) {
var headTop = $(window).scrollTop();
if( headTop < headerheight && headTop > 0 ) {
$( "#sorter" ).css({
"top": headerheight + 15 - headTop,
"height": $.mobile.window.height() - headerheight - 20
});
} else if ( headTop >= headerheight && headTop > 0 && parseInt( headTop + $.mobile.window.height( )) < parseInt( foot.offset().top ) ) {
$( "#sorter" ).css({
"top": "15px",
"height": $.mobile.window.height()
});
$("#sorter li").height( "3.7%" );
} else if ( parseInt( headTop + $.mobile.window.height() ) >= parseInt( foot.offset().top ) && parseInt( headTop + $.mobile.window.height() ) <= parseInt( foot.offset().top ) + foot.height() ) {
$( "#sorter" ).css({
"top": "15px",
"height": $.mobile.window.height() - ( parseInt( headTop + $.mobile.window.height() ) - parseInt( foot.offset().top ) + 8 )
});
} else if( parseInt( headTop + $.mobile.window.height() ) >= parseInt( foot.offset().top ) ) {
$( "#sorter" ).css({
"top": "15px"
});
} else {
$( "#sorter" ).css( "top", headerheight + 15 );
}
});
$( "#sorter li" ).click( function() {
var top,
letter = $( this ).text(),
divider = $( "#sortedList" ).find( "li.ui-li-divider:contains(" + letter + ")" );
if ( divider.length > 0 ) {
top = divider.offset().top;
$.mobile.silentScroll( top );
} else {
return false;
}
});
$( "#sorter li" ).hover(function() {
$( this ).addClass( "ui-btn-up-b" ).removeClass( "ui-btn-up-c" );
}, function() {
$( this ).removeClass( "ui-btn-up-b" ).addClass( "ui-btn-up-c" );
});
}); | zettwerk.mobile | /zettwerk.mobile-0.2.1.zip/zettwerk.mobile-0.2.1/zettwerk/mobile/static/jquery.mobile-1.4.2/demos/listview-autodividers-linkbar/autodividers-linkbar.js | autodividers-linkbar.js |
// Includes file dependencies
define([
"jquery",
"backbone",
"../models/CategoryModel" ], function( $, Backbone, CategoryModel ) {
// Extends Backbone.Router
var Collection = Backbone.Collection.extend( {
// The Collection constructor
initialize: function( models, options ) {
// Sets the type instance property (ie. animals)
this.type = options.type;
},
// Sets the Collection model property to be a Category Model
model: CategoryModel,
// Sample JSON data that in a real app will most likely come from a REST web service
jsonArray: [
{ "category": "animals", "type": "Pets" },
{ "category": "animals", "type": "Farm Animals" },
{ "category": "animals", "type": "Wild Animals" },
{ "category": "colors", "type": "Blue" },
{ "category": "colors", "type": "Green" },
{ "category": "colors", "type": "Orange" },
{ "category": "colors", "type": "Purple" },
{ "category": "colors", "type": "Red" },
{ "category": "colors", "type": "Yellow" },
{ "category": "colors", "type": "Violet" },
{ "category": "vehicles", "type": "Cars" },
{ "category": "vehicles", "type": "Planes" },
{ "category": "vehicles", "type": "Construction" }
],
// Overriding the Backbone.sync method (the Backbone.fetch method calls the sync method when trying to fetch data)
sync: function( method, model, options ) {
// Local Variables
// ===============
// Instantiates an empty array
var categories = [],
// Stores the this context in the self variable
self = this,
// Creates a jQuery Deferred Object
deferred = $.Deferred();
// Uses a setTimeout to mimic a real world application that retrieves data asynchronously
setTimeout( function() {
// Filters the above sample JSON data to return an array of only the correct category type
categories = _.filter( self.jsonArray, function( row ) {
return row.category === self.type;
} );
// Calls the options.success method and passes an array of objects (Internally saves these objects as models to the current collection)
options.success( categories );
// Triggers the custom `added` method (which the Category View listens for)
self.trigger( "added" );
// Resolves the deferred object (this triggers the changePage method inside of the Category Router)
deferred.resolve();
}, 1000);
// Returns the deferred object
return deferred;
}
} );
// Returns the Model class
return Collection;
} ); | zettwerk.mobile | /zettwerk.mobile-0.2.1.zip/zettwerk.mobile-0.2.1/zettwerk/mobile/static/jquery.mobile-1.4.2/demos/backbone-requirejs/js/collections/CategoriesCollection.js | CategoriesCollection.js |
// Includes file dependencies
define([
"jquery",
"backbone",
"../models/CategoryModel",
"../collections/CategoriesCollection",
"../views/CategoryView"
], function( $, Backbone, CategoryModel, CategoriesCollection, CategoryView ) {
// Extends Backbone.Router
var CategoryRouter = Backbone.Router.extend( {
// The Router constructor
initialize: function() {
// Instantiates a new Animal Category View
this.animalsView = new CategoryView( { el: "#animals", collection: new CategoriesCollection( [] , { type: "animals" } ) } );
// Instantiates a new Colors Category View
this.colorsView = new CategoryView( { el: "#colors", collection: new CategoriesCollection( [] , { type: "colors" } ) } );
// Instantiates a new Vehicles Category View
this.vehiclesView = new CategoryView( { el: "#vehicles", collection: new CategoriesCollection( [] , { type: "vehicles" } ) } );
// Tells Backbone to start watching for hashchange events
Backbone.history.start();
},
// Backbone.js Routes
routes: {
// When there is no hash bang on the url, the home method is called
"": "home",
// When #category? is on the url, the category method is called
"category?:type": "category"
},
// Home method
home: function() {
// Programatically changes to the categories page
$.mobile.changePage( "#categories" , { reverse: false, changeHash: false } );
},
// Category method that passes in the type that is appended to the url hash
category: function(type) {
// Stores the current Category View inside of the currentView variable
var currentView = this[ type + "View" ];
// If there are no collections in the current Category View
if(!currentView.collection.length) {
// Show's the jQuery Mobile loading icon
$.mobile.loading( "show" );
// Fetches the Collection of Category Models for the current Category View
currentView.collection.fetch().done( function() {
// Programatically changes to the current categories page
$.mobile.changePage( "#" + type, { reverse: false, changeHash: false } );
} );
}
// If there already collections in the current Category View
else {
// Programatically changes to the current categories page
$.mobile.changePage( "#" + type, { reverse: false, changeHash: false } );
}
}
} );
// Returns the Router class
return CategoryRouter;
} ); | zettwerk.mobile | /zettwerk.mobile-0.2.1.zip/zettwerk.mobile-0.2.1/zettwerk/mobile/static/jquery.mobile-1.4.2/demos/backbone-requirejs/js/routers/mobileRouter.js | mobileRouter.js |
!function(a,b,c){"function"==typeof define&&define.amd?define(["jquery"],function(d){return c(d,a,b),d.mobile}):c(a.jQuery,a,b)}(this,document,function(a,b,c){!function(a){a.mobile={}}(a),function(a){a.extend(a.mobile,{version:"1.4.2",subPageUrlKey:"ui-page",hideUrlBar:!0,keepNative:":jqmData(role='none'), :jqmData(role='nojs')",activePageClass:"ui-page-active",activeBtnClass:"ui-btn-active",focusClass:"ui-focus",ajaxEnabled:!0,hashListeningEnabled:!0,linkBindingEnabled:!0,defaultPageTransition:"fade",maxTransitionWidth:!1,minScrollBack:0,defaultDialogTransition:"pop",pageLoadErrorMessage:"Error Loading Page",pageLoadErrorMessageTheme:"a",phonegapNavigationEnabled:!1,autoInitializePage:!0,pushStateEnabled:!0,ignoreContentEnabled:!1,buttonMarkup:{hoverDelay:200},dynamicBaseEnabled:!0,pageContainer:a(),allowCrossDomainPages:!1,dialogHashKey:"&ui-state=dialog"})}(a,this),function(a,b,c){var d={},e=a.find,f=/(?:\{[\s\S]*\}|\[[\s\S]*\])$/,g=/:jqmData\(([^)]*)\)/g;a.extend(a.mobile,{ns:"",getAttribute:function(b,c){var d;b=b.jquery?b[0]:b,b&&b.getAttribute&&(d=b.getAttribute("data-"+a.mobile.ns+c));try{d="true"===d?!0:"false"===d?!1:"null"===d?null:+d+""===d?+d:f.test(d)?JSON.parse(d):d}catch(e){}return d},nsNormalizeDict:d,nsNormalize:function(b){return d[b]||(d[b]=a.camelCase(a.mobile.ns+b))},closestPageData:function(a){return a.closest(":jqmData(role='page'), :jqmData(role='dialog')").data("mobile-page")}}),a.fn.jqmData=function(b,d){var e;return"undefined"!=typeof b&&(b&&(b=a.mobile.nsNormalize(b)),e=arguments.length<2||d===c?this.data(b):this.data(b,d)),e},a.jqmData=function(b,c,d){var e;return"undefined"!=typeof c&&(e=a.data(b,c?a.mobile.nsNormalize(c):c,d)),e},a.fn.jqmRemoveData=function(b){return this.removeData(a.mobile.nsNormalize(b))},a.jqmRemoveData=function(b,c){return a.removeData(b,a.mobile.nsNormalize(c))},a.find=function(b,c,d,f){return b.indexOf(":jqmData")>-1&&(b=b.replace(g,"[data-"+(a.mobile.ns||"")+"$1]")),e.call(this,b,c,d,f)},a.extend(a.find,e)}(a,this),function(a,b){function d(b,c){var d,f,g,h=b.nodeName.toLowerCase();return"area"===h?(d=b.parentNode,f=d.name,b.href&&f&&"map"===d.nodeName.toLowerCase()?(g=a("img[usemap=#"+f+"]")[0],!!g&&e(g)):!1):(/input|select|textarea|button|object/.test(h)?!b.disabled:"a"===h?b.href||c:c)&&e(b)}function e(b){return a.expr.filters.visible(b)&&!a(b).parents().addBack().filter(function(){return"hidden"===a.css(this,"visibility")}).length}var f=0,g=/^ui-id-\d+$/;a.ui=a.ui||{},a.extend(a.ui,{version:"c0ab71056b936627e8a7821f03c044aec6280a40",keyCode:{BACKSPACE:8,COMMA:188,DELETE:46,DOWN:40,END:35,ENTER:13,ESCAPE:27,HOME:36,LEFT:37,PAGE_DOWN:34,PAGE_UP:33,PERIOD:190,RIGHT:39,SPACE:32,TAB:9,UP:38}}),a.fn.extend({focus:function(b){return function(c,d){return"number"==typeof c?this.each(function(){var b=this;setTimeout(function(){a(b).focus(),d&&d.call(b)},c)}):b.apply(this,arguments)}}(a.fn.focus),scrollParent:function(){var b;return b=a.ui.ie&&/(static|relative)/.test(this.css("position"))||/absolute/.test(this.css("position"))?this.parents().filter(function(){return/(relative|absolute|fixed)/.test(a.css(this,"position"))&&/(auto|scroll)/.test(a.css(this,"overflow")+a.css(this,"overflow-y")+a.css(this,"overflow-x"))}).eq(0):this.parents().filter(function(){return/(auto|scroll)/.test(a.css(this,"overflow")+a.css(this,"overflow-y")+a.css(this,"overflow-x"))}).eq(0),/fixed/.test(this.css("position"))||!b.length?a(this[0].ownerDocument||c):b},uniqueId:function(){return this.each(function(){this.id||(this.id="ui-id-"+ ++f)})},removeUniqueId:function(){return this.each(function(){g.test(this.id)&&a(this).removeAttr("id")})}}),a.extend(a.expr[":"],{data:a.expr.createPseudo?a.expr.createPseudo(function(b){return function(c){return!!a.data(c,b)}}):function(b,c,d){return!!a.data(b,d[3])},focusable:function(b){return d(b,!isNaN(a.attr(b,"tabindex")))},tabbable:function(b){var c=a.attr(b,"tabindex"),e=isNaN(c);return(e||c>=0)&&d(b,!e)}}),a("<a>").outerWidth(1).jquery||a.each(["Width","Height"],function(c,d){function e(b,c,d,e){return a.each(f,function(){c-=parseFloat(a.css(b,"padding"+this))||0,d&&(c-=parseFloat(a.css(b,"border"+this+"Width"))||0),e&&(c-=parseFloat(a.css(b,"margin"+this))||0)}),c}var f="Width"===d?["Left","Right"]:["Top","Bottom"],g=d.toLowerCase(),h={innerWidth:a.fn.innerWidth,innerHeight:a.fn.innerHeight,outerWidth:a.fn.outerWidth,outerHeight:a.fn.outerHeight};a.fn["inner"+d]=function(c){return c===b?h["inner"+d].call(this):this.each(function(){a(this).css(g,e(this,c)+"px")})},a.fn["outer"+d]=function(b,c){return"number"!=typeof b?h["outer"+d].call(this,b):this.each(function(){a(this).css(g,e(this,b,!0,c)+"px")})}}),a.fn.addBack||(a.fn.addBack=function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}),a("<a>").data("a-b","a").removeData("a-b").data("a-b")&&(a.fn.removeData=function(b){return function(c){return arguments.length?b.call(this,a.camelCase(c)):b.call(this)}}(a.fn.removeData)),a.ui.ie=!!/msie [\w.]+/.exec(navigator.userAgent.toLowerCase()),a.support.selectstart="onselectstart"in c.createElement("div"),a.fn.extend({disableSelection:function(){return this.bind((a.support.selectstart?"selectstart":"mousedown")+".ui-disableSelection",function(a){a.preventDefault()})},enableSelection:function(){return this.unbind(".ui-disableSelection")},zIndex:function(d){if(d!==b)return this.css("zIndex",d);if(this.length)for(var e,f,g=a(this[0]);g.length&&g[0]!==c;){if(e=g.css("position"),("absolute"===e||"relative"===e||"fixed"===e)&&(f=parseInt(g.css("zIndex"),10),!isNaN(f)&&0!==f))return f;g=g.parent()}return 0}}),a.ui.plugin={add:function(b,c,d){var e,f=a.ui[b].prototype;for(e in d)f.plugins[e]=f.plugins[e]||[],f.plugins[e].push([c,d[e]])},call:function(a,b,c,d){var e,f=a.plugins[b];if(f&&(d||a.element[0].parentNode&&11!==a.element[0].parentNode.nodeType))for(e=0;e<f.length;e++)a.options[f[e][0]]&&f[e][1].apply(a.element,c)}}}(a),function(a,b){var d=function(b,c){var d=b.parent(),e=[],f=d.children(":jqmData(role='header')"),g=b.children(":jqmData(role='header')"),h=d.children(":jqmData(role='footer')"),i=b.children(":jqmData(role='footer')");return 0===g.length&&f.length>0&&(e=e.concat(f.toArray())),0===i.length&&h.length>0&&(e=e.concat(h.toArray())),a.each(e,function(b,d){c-=a(d).outerHeight()}),Math.max(0,c)};a.extend(a.mobile,{window:a(b),document:a(c),keyCode:a.ui.keyCode,behaviors:{},silentScroll:function(c){"number"!==a.type(c)&&(c=a.mobile.defaultHomeScroll),a.event.special.scrollstart.enabled=!1,setTimeout(function(){b.scrollTo(0,c),a.mobile.document.trigger("silentscroll",{x:0,y:c})},20),setTimeout(function(){a.event.special.scrollstart.enabled=!0},150)},getClosestBaseUrl:function(b){var c=a(b).closest(".ui-page").jqmData("url"),d=a.mobile.path.documentBase.hrefNoHash;return a.mobile.dynamicBaseEnabled&&c&&a.mobile.path.isPath(c)||(c=d),a.mobile.path.makeUrlAbsolute(c,d)},removeActiveLinkClass:function(b){!a.mobile.activeClickedLink||a.mobile.activeClickedLink.closest("."+a.mobile.activePageClass).length&&!b||a.mobile.activeClickedLink.removeClass(a.mobile.activeBtnClass),a.mobile.activeClickedLink=null},getInheritedTheme:function(a,b){for(var c,d,e=a[0],f="",g=/ui-(bar|body|overlay)-([a-z])\b/;e&&(c=e.className||"",!(c&&(d=g.exec(c))&&(f=d[2])));)e=e.parentNode;return f||b||"a"},enhanceable:function(a){return this.haveParents(a,"enhance")},hijackable:function(a){return this.haveParents(a,"ajax")},haveParents:function(b,c){if(!a.mobile.ignoreContentEnabled)return b;var d,e,f,g,h,i=b.length,j=a();for(g=0;i>g;g++){for(e=b.eq(g),f=!1,d=b[g];d;){if(h=d.getAttribute?d.getAttribute("data-"+a.mobile.ns+c):"","false"===h){f=!0;break}d=d.parentNode}f||(j=j.add(e))}return j},getScreenHeight:function(){return b.innerHeight||a.mobile.window.height()},resetActivePageHeight:function(b){var c=a("."+a.mobile.activePageClass),e=c.height(),f=c.outerHeight(!0);b=d(c,"number"==typeof b?b:a.mobile.getScreenHeight()),c.css("min-height",b-(f-e))},loading:function(){var b=this.loading._widget||a(a.mobile.loader.prototype.defaultHtml).loader(),c=b.loader.apply(b,arguments);return this.loading._widget=b,c}}),a.addDependents=function(b,c){var d=a(b),e=d.jqmData("dependents")||a();d.jqmData("dependents",a(e).add(c))},a.fn.extend({removeWithDependents:function(){a.removeWithDependents(this)},enhanceWithin:function(){var b,c={},d=a.mobile.page.prototype.keepNativeSelector(),e=this;a.mobile.nojs&&a.mobile.nojs(this),a.mobile.links&&a.mobile.links(this),a.mobile.degradeInputsWithin&&a.mobile.degradeInputsWithin(this),a.fn.buttonMarkup&&this.find(a.fn.buttonMarkup.initSelector).not(d).jqmEnhanceable().buttonMarkup(),a.fn.fieldcontain&&this.find(":jqmData(role='fieldcontain')").not(d).jqmEnhanceable().fieldcontain(),a.each(a.mobile.widgets,function(b,f){if(f.initSelector){var g=a.mobile.enhanceable(e.find(f.initSelector));g.length>0&&(g=g.not(d)),g.length>0&&(c[f.prototype.widgetName]=g)}});for(b in c)c[b][b]();return this},addDependents:function(b){a.addDependents(this,b)},getEncodedText:function(){return a("<a>").text(this.text()).html()},jqmEnhanceable:function(){return a.mobile.enhanceable(this)},jqmHijackable:function(){return a.mobile.hijackable(this)}}),a.removeWithDependents=function(b){var c=a(b);(c.jqmData("dependents")||a()).remove(),c.remove()},a.addDependents=function(b,c){var d=a(b),e=d.jqmData("dependents")||a();d.jqmData("dependents",a(e).add(c))},a.find.matches=function(b,c){return a.find(b,null,null,c)},a.find.matchesSelector=function(b,c){return a.find(c,null,null,[b]).length>0}}(a,this),function(a,b){var c=0,d=Array.prototype.slice,e=a.cleanData;a.cleanData=function(b){for(var c,d=0;null!=(c=b[d]);d++)try{a(c).triggerHandler("remove")}catch(f){}e(b)},a.widget=function(b,c,d){var e,f,g,h,i={},j=b.split(".")[0];return b=b.split(".")[1],e=j+"-"+b,d||(d=c,c=a.Widget),a.expr[":"][e.toLowerCase()]=function(b){return!!a.data(b,e)},a[j]=a[j]||{},f=a[j][b],g=a[j][b]=function(a,b){return this._createWidget?void(arguments.length&&this._createWidget(a,b)):new g(a,b)},a.extend(g,f,{version:d.version,_proto:a.extend({},d),_childConstructors:[]}),h=new c,h.options=a.widget.extend({},h.options),a.each(d,function(b,d){return a.isFunction(d)?void(i[b]=function(){var a=function(){return c.prototype[b].apply(this,arguments)},e=function(a){return c.prototype[b].apply(this,a)};return function(){var b,c=this._super,f=this._superApply;return this._super=a,this._superApply=e,b=d.apply(this,arguments),this._super=c,this._superApply=f,b}}()):void(i[b]=d)}),g.prototype=a.widget.extend(h,{widgetEventPrefix:f?h.widgetEventPrefix||b:b},i,{constructor:g,namespace:j,widgetName:b,widgetFullName:e}),f?(a.each(f._childConstructors,function(b,c){var d=c.prototype;a.widget(d.namespace+"."+d.widgetName,g,c._proto)}),delete f._childConstructors):c._childConstructors.push(g),a.widget.bridge(b,g),g},a.widget.extend=function(c){for(var e,f,g=d.call(arguments,1),h=0,i=g.length;i>h;h++)for(e in g[h])f=g[h][e],g[h].hasOwnProperty(e)&&f!==b&&(c[e]=a.isPlainObject(f)?a.isPlainObject(c[e])?a.widget.extend({},c[e],f):a.widget.extend({},f):f);return c},a.widget.bridge=function(c,e){var f=e.prototype.widgetFullName||c;a.fn[c]=function(g){var h="string"==typeof g,i=d.call(arguments,1),j=this;return g=!h&&i.length?a.widget.extend.apply(null,[g].concat(i)):g,this.each(h?function(){var d,e=a.data(this,f);return"instance"===g?(j=e,!1):e?a.isFunction(e[g])&&"_"!==g.charAt(0)?(d=e[g].apply(e,i),d!==e&&d!==b?(j=d&&d.jquery?j.pushStack(d.get()):d,!1):void 0):a.error("no such method '"+g+"' for "+c+" widget instance"):a.error("cannot call methods on "+c+" prior to initialization; attempted to call method '"+g+"'")}:function(){var b=a.data(this,f);b?b.option(g||{})._init():a.data(this,f,new e(g,this))}),j}},a.Widget=function(){},a.Widget._childConstructors=[],a.Widget.prototype={widgetName:"widget",widgetEventPrefix:"",defaultElement:"<div>",options:{disabled:!1,create:null},_createWidget:function(b,d){d=a(d||this.defaultElement||this)[0],this.element=a(d),this.uuid=c++,this.eventNamespace="."+this.widgetName+this.uuid,this.options=a.widget.extend({},this.options,this._getCreateOptions(),b),this.bindings=a(),this.hoverable=a(),this.focusable=a(),d!==this&&(a.data(d,this.widgetFullName,this),this._on(!0,this.element,{remove:function(a){a.target===d&&this.destroy()}}),this.document=a(d.style?d.ownerDocument:d.document||d),this.window=a(this.document[0].defaultView||this.document[0].parentWindow)),this._create(),this._trigger("create",null,this._getCreateEventData()),this._init()},_getCreateOptions:a.noop,_getCreateEventData:a.noop,_create:a.noop,_init:a.noop,destroy:function(){this._destroy(),this.element.unbind(this.eventNamespace).removeData(this.widgetFullName).removeData(a.camelCase(this.widgetFullName)),this.widget().unbind(this.eventNamespace).removeAttr("aria-disabled").removeClass(this.widgetFullName+"-disabled ui-state-disabled"),this.bindings.unbind(this.eventNamespace),this.hoverable.removeClass("ui-state-hover"),this.focusable.removeClass("ui-state-focus")},_destroy:a.noop,widget:function(){return this.element},option:function(c,d){var e,f,g,h=c;if(0===arguments.length)return a.widget.extend({},this.options);if("string"==typeof c)if(h={},e=c.split("."),c=e.shift(),e.length){for(f=h[c]=a.widget.extend({},this.options[c]),g=0;g<e.length-1;g++)f[e[g]]=f[e[g]]||{},f=f[e[g]];if(c=e.pop(),d===b)return f[c]===b?null:f[c];f[c]=d}else{if(d===b)return this.options[c]===b?null:this.options[c];h[c]=d}return this._setOptions(h),this},_setOptions:function(a){var b;for(b in a)this._setOption(b,a[b]);return this},_setOption:function(a,b){return this.options[a]=b,"disabled"===a&&(this.widget().toggleClass(this.widgetFullName+"-disabled",!!b),this.hoverable.removeClass("ui-state-hover"),this.focusable.removeClass("ui-state-focus")),this},enable:function(){return this._setOptions({disabled:!1})},disable:function(){return this._setOptions({disabled:!0})},_on:function(b,c,d){var e,f=this;"boolean"!=typeof b&&(d=c,c=b,b=!1),d?(c=e=a(c),this.bindings=this.bindings.add(c)):(d=c,c=this.element,e=this.widget()),a.each(d,function(d,g){function h(){return b||f.options.disabled!==!0&&!a(this).hasClass("ui-state-disabled")?("string"==typeof g?f[g]:g).apply(f,arguments):void 0}"string"!=typeof g&&(h.guid=g.guid=g.guid||h.guid||a.guid++);var i=d.match(/^(\w+)\s*(.*)$/),j=i[1]+f.eventNamespace,k=i[2];k?e.delegate(k,j,h):c.bind(j,h)})},_off:function(a,b){b=(b||"").split(" ").join(this.eventNamespace+" ")+this.eventNamespace,a.unbind(b).undelegate(b)},_delay:function(a,b){function c(){return("string"==typeof a?d[a]:a).apply(d,arguments)}var d=this;return setTimeout(c,b||0)},_hoverable:function(b){this.hoverable=this.hoverable.add(b),this._on(b,{mouseenter:function(b){a(b.currentTarget).addClass("ui-state-hover")},mouseleave:function(b){a(b.currentTarget).removeClass("ui-state-hover")}})},_focusable:function(b){this.focusable=this.focusable.add(b),this._on(b,{focusin:function(b){a(b.currentTarget).addClass("ui-state-focus")},focusout:function(b){a(b.currentTarget).removeClass("ui-state-focus")}})},_trigger:function(b,c,d){var e,f,g=this.options[b];if(d=d||{},c=a.Event(c),c.type=(b===this.widgetEventPrefix?b:this.widgetEventPrefix+b).toLowerCase(),c.target=this.element[0],f=c.originalEvent)for(e in f)e in c||(c[e]=f[e]);return this.element.trigger(c,d),!(a.isFunction(g)&&g.apply(this.element[0],[c].concat(d))===!1||c.isDefaultPrevented())}},a.each({show:"fadeIn",hide:"fadeOut"},function(b,c){a.Widget.prototype["_"+b]=function(d,e,f){"string"==typeof e&&(e={effect:e});var g,h=e?e===!0||"number"==typeof e?c:e.effect||c:b;e=e||{},"number"==typeof e&&(e={duration:e}),g=!a.isEmptyObject(e),e.complete=f,e.delay&&d.delay(e.delay),g&&a.effects&&a.effects.effect[h]?d[b](e):h!==b&&d[h]?d[h](e.duration,e.easing,f):d.queue(function(c){a(this)[b](),f&&f.call(d[0]),c()})}})}(a),function(a){var b=/[A-Z]/g,c=function(a){return"-"+a.toLowerCase()};a.extend(a.Widget.prototype,{_getCreateOptions:function(){var d,e,f=this.element[0],g={};if(!a.mobile.getAttribute(f,"defaults"))for(d in this.options)e=a.mobile.getAttribute(f,d.replace(b,c)),null!=e&&(g[d]=e);return g}}),a.mobile.widget=a.Widget}(a),function(a){var b="ui-loader",c=a("html");a.widget("mobile.loader",{options:{theme:"a",textVisible:!1,html:"",text:"loading"},defaultHtml:"<div class='"+b+"'><span class='ui-icon-loading'></span><h1></h1></div>",fakeFixLoader:function(){var b=a("."+a.mobile.activeBtnClass).first();this.element.css({top:a.support.scrollTop&&this.window.scrollTop()+this.window.height()/2||b.length&&b.offset().top||100})},checkLoaderPosition:function(){var b=this.element.offset(),c=this.window.scrollTop(),d=a.mobile.getScreenHeight();(b.top<c||b.top-c>d)&&(this.element.addClass("ui-loader-fakefix"),this.fakeFixLoader(),this.window.unbind("scroll",this.checkLoaderPosition).bind("scroll",a.proxy(this.fakeFixLoader,this)))},resetHtml:function(){this.element.html(a(this.defaultHtml).html())},show:function(d,e,f){var g,h,i;this.resetHtml(),"object"===a.type(d)?(i=a.extend({},this.options,d),d=i.theme):(i=this.options,d=d||i.theme),h=e||(i.text===!1?"":i.text),c.addClass("ui-loading"),g=i.textVisible,this.element.attr("class",b+" ui-corner-all ui-body-"+d+" ui-loader-"+(g||e||d.text?"verbose":"default")+(i.textonly||f?" ui-loader-textonly":"")),i.html?this.element.html(i.html):this.element.find("h1").text(h),this.element.appendTo(a.mobile.pageContainer),this.checkLoaderPosition(),this.window.bind("scroll",a.proxy(this.checkLoaderPosition,this))},hide:function(){c.removeClass("ui-loading"),this.options.text&&this.element.removeClass("ui-loader-fakefix"),a.mobile.window.unbind("scroll",this.fakeFixLoader),a.mobile.window.unbind("scroll",this.checkLoaderPosition)}})}(a,this),function(a,b,d){"$:nomunge";function e(a){return a=a||location.href,"#"+a.replace(/^[^#]*#?(.*)$/,"$1")}var f,g="hashchange",h=c,i=a.event.special,j=h.documentMode,k="on"+g in b&&(j===d||j>7);a.fn[g]=function(a){return a?this.bind(g,a):this.trigger(g)},a.fn[g].delay=50,i[g]=a.extend(i[g],{setup:function(){return k?!1:void a(f.start)},teardown:function(){return k?!1:void a(f.stop)}}),f=function(){function c(){var d=e(),h=n(j);d!==j?(m(j=d,h),a(b).trigger(g)):h!==j&&(location.href=location.href.replace(/#.*/,"")+h),f=setTimeout(c,a.fn[g].delay)}var f,i={},j=e(),l=function(a){return a},m=l,n=l;return i.start=function(){f||c()},i.stop=function(){f&&clearTimeout(f),f=d},b.attachEvent&&!b.addEventListener&&!k&&function(){var b,d;i.start=function(){b||(d=a.fn[g].src,d=d&&d+e(),b=a('<iframe tabindex="-1" title="empty"/>').hide().one("load",function(){d||m(e()),c()}).attr("src",d||"javascript:0").insertAfter("body")[0].contentWindow,h.onpropertychange=function(){try{"title"===event.propertyName&&(b.document.title=h.title)}catch(a){}})},i.stop=l,n=function(){return e(b.location.href)},m=function(c,d){var e=b.document,f=a.fn[g].domain;c!==d&&(e.title=h.title,e.open(),f&&e.write('<script>document.domain="'+f+'"</script>'),e.close(),b.location.hash=c)}}(),i}()}(a,this),function(a){b.matchMedia=b.matchMedia||function(a){var b,c=a.documentElement,d=c.firstElementChild||c.firstChild,e=a.createElement("body"),f=a.createElement("div");return f.id="mq-test-1",f.style.cssText="position:absolute;top:-100em",e.style.background="none",e.appendChild(f),function(a){return f.innerHTML='­<style media="'+a+'"> #mq-test-1 { width: 42px; }</style>',c.insertBefore(e,d),b=42===f.offsetWidth,c.removeChild(e),{matches:b,media:a}}}(c),a.mobile.media=function(a){return b.matchMedia(a).matches}}(a),function(a){var b={touch:"ontouchend"in c};a.mobile.support=a.mobile.support||{},a.extend(a.support,b),a.extend(a.mobile.support,b)}(a),function(a){a.extend(a.support,{orientation:"orientation"in b&&"onorientationchange"in b})}(a),function(a,d){function e(a){var b,c=a.charAt(0).toUpperCase()+a.substr(1),e=(a+" "+o.join(c+" ")+c).split(" ");for(b in e)if(n[e[b]]!==d)return!0}function f(){var c=b,d=!(!c.document.createElementNS||!c.document.createElementNS("http://www.w3.org/2000/svg","svg").createSVGRect||c.opera&&-1===navigator.userAgent.indexOf("Chrome")),e=function(b){b&&d||a("html").addClass("ui-nosvg")},f=new c.Image;f.onerror=function(){e(!1)},f.onload=function(){e(1===f.width&&1===f.height)},f.src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw=="}function g(){var e,f,g,h="transform-3d",i=a.mobile.media("(-"+o.join("-"+h+"),(-")+"-"+h+"),("+h+")");if(i)return!!i;e=c.createElement("div"),f={MozTransform:"-moz-transform",transform:"transform"},m.append(e);for(g in f)e.style[g]!==d&&(e.style[g]="translate3d( 100px, 1px, 1px )",i=b.getComputedStyle(e).getPropertyValue(f[g]));return!!i&&"none"!==i}function h(){var b,c,d=location.protocol+"//"+location.host+location.pathname+"ui-dir/",e=a("head base"),f=null,g="";return e.length?g=e.attr("href"):e=f=a("<base>",{href:d}).appendTo("head"),b=a("<a href='testurl' />").prependTo(m),c=b[0].href,e[0].href=g||location.pathname,f&&f.remove(),0===c.indexOf(d)}function i(){var a,d=c.createElement("x"),e=c.documentElement,f=b.getComputedStyle;return"pointerEvents"in d.style?(d.style.pointerEvents="auto",d.style.pointerEvents="x",e.appendChild(d),a=f&&"auto"===f(d,"").pointerEvents,e.removeChild(d),!!a):!1}function j(){var a=c.createElement("div");return"undefined"!=typeof a.getBoundingClientRect}function k(){var a=b,c=navigator.userAgent,d=navigator.platform,e=c.match(/AppleWebKit\/([0-9]+)/),f=!!e&&e[1],g=c.match(/Fennec\/([0-9]+)/),h=!!g&&g[1],i=c.match(/Opera Mobi\/([0-9]+)/),j=!!i&&i[1];return(d.indexOf("iPhone")>-1||d.indexOf("iPad")>-1||d.indexOf("iPod")>-1)&&f&&534>f||a.operamini&&"[object OperaMini]"==={}.toString.call(a.operamini)||i&&7458>j||c.indexOf("Android")>-1&&f&&533>f||h&&6>h||"palmGetResource"in b&&f&&534>f||c.indexOf("MeeGo")>-1&&c.indexOf("NokiaBrowser/8.5.0")>-1?!1:!0}var l,m=a("<body>").prependTo("html"),n=m[0].style,o=["Webkit","Moz","O"],p="palmGetResource"in b,q=b.operamini&&"[object OperaMini]"==={}.toString.call(b.operamini),r=b.blackberry&&!e("-webkit-transform");a.extend(a.mobile,{browser:{}}),a.mobile.browser.oldIE=function(){var a=3,b=c.createElement("div"),d=b.all||[];do b.innerHTML="<!--[if gt IE "+ ++a+"]><br><![endif]-->";while(d[0]);return a>4?a:!a}(),a.extend(a.support,{pushState:"pushState"in history&&"replaceState"in history&&!(b.navigator.userAgent.indexOf("Firefox")>=0&&b.top!==b)&&-1===b.navigator.userAgent.search(/CriOS/),mediaquery:a.mobile.media("only all"),cssPseudoElement:!!e("content"),touchOverflow:!!e("overflowScrolling"),cssTransform3d:g(),boxShadow:!!e("boxShadow")&&!r,fixedPosition:k(),scrollTop:("pageXOffset"in b||"scrollTop"in c.documentElement||"scrollTop"in m[0])&&!p&&!q,dynamicBaseTag:h(),cssPointerEvents:i(),boundingRect:j(),inlineSVG:f}),m.remove(),l=function(){var a=b.navigator.userAgent;return a.indexOf("Nokia")>-1&&(a.indexOf("Symbian/3")>-1||a.indexOf("Series60/5")>-1)&&a.indexOf("AppleWebKit")>-1&&a.match(/(BrowserNG|NokiaBrowser)\/7\.[0-3]/)}(),a.mobile.gradeA=function(){return(a.support.mediaquery&&a.support.cssPseudoElement||a.mobile.browser.oldIE&&a.mobile.browser.oldIE>=8)&&(a.support.boundingRect||null!==a.fn.jquery.match(/1\.[0-7+]\.[0-9+]?/))},a.mobile.ajaxBlacklist=b.blackberry&&!b.WebKitPoint||q||l,l&&a(function(){a("head link[rel='stylesheet']").attr("rel","alternate stylesheet").attr("rel","stylesheet")}),a.support.boxShadow||a("html").addClass("ui-noboxshadow")}(a),function(a,b){var c,d=a.mobile.window,e=function(){};a.event.special.beforenavigate={setup:function(){d.on("navigate",e)},teardown:function(){d.off("navigate",e)}},a.event.special.navigate=c={bound:!1,pushStateEnabled:!0,originalEventName:b,isPushStateEnabled:function(){return a.support.pushState&&a.mobile.pushStateEnabled===!0&&this.isHashChangeEnabled()},isHashChangeEnabled:function(){return a.mobile.hashListeningEnabled===!0},popstate:function(b){var c=new a.Event("navigate"),e=new a.Event("beforenavigate"),f=b.originalEvent.state||{};e.originalEvent=b,d.trigger(e),e.isDefaultPrevented()||(b.historyState&&a.extend(f,b.historyState),c.originalEvent=b,setTimeout(function(){d.trigger(c,{state:f})},0))},hashchange:function(b){var c=new a.Event("navigate"),e=new a.Event("beforenavigate");e.originalEvent=b,d.trigger(e),e.isDefaultPrevented()||(c.originalEvent=b,d.trigger(c,{state:b.hashchangeState||{}}))},setup:function(){c.bound||(c.bound=!0,c.isPushStateEnabled()?(c.originalEventName="popstate",d.bind("popstate.navigate",c.popstate)):c.isHashChangeEnabled()&&(c.originalEventName="hashchange",d.bind("hashchange.navigate",c.hashchange)))}}}(a),function(a,c){var d,e,f="&ui-state=dialog";a.mobile.path=d={uiStateKey:"&ui-state",urlParseRE:/^\s*(((([^:\/#\?]+:)?(?:(\/\/)((?:(([^:@\/#\?]+)(?:\:([^:@\/#\?]+))?)@)?(([^:\/#\?\]\[]+|\[[^\/\]@#?]+\])(?:\:([0-9]+))?))?)?)?((\/?(?:[^\/\?#]+\/+)*)([^\?#]*)))?(\?[^#]+)?)(#.*)?/,getLocation:function(a){var b=a?this.parseUrl(a):location,c=this.parseUrl(a||location.href).hash;return c="#"===c?"":c,b.protocol+"//"+b.host+b.pathname+b.search+c},getDocumentUrl:function(b){return b?a.extend({},d.documentUrl):d.documentUrl.href},parseLocation:function(){return this.parseUrl(this.getLocation())},parseUrl:function(b){if("object"===a.type(b))return b;var c=d.urlParseRE.exec(b||"")||[];return{href:c[0]||"",hrefNoHash:c[1]||"",hrefNoSearch:c[2]||"",domain:c[3]||"",protocol:c[4]||"",doubleSlash:c[5]||"",authority:c[6]||"",username:c[8]||"",password:c[9]||"",host:c[10]||"",hostname:c[11]||"",port:c[12]||"",pathname:c[13]||"",directory:c[14]||"",filename:c[15]||"",search:c[16]||"",hash:c[17]||""}},makePathAbsolute:function(a,b){var c,d,e,f;if(a&&"/"===a.charAt(0))return a;for(a=a||"",b=b?b.replace(/^\/|(\/[^\/]*|[^\/]+)$/g,""):"",c=b?b.split("/"):[],d=a.split("/"),e=0;e<d.length;e++)switch(f=d[e]){case".":break;case"..":c.length&&c.pop();break;default:c.push(f)}return"/"+c.join("/")},isSameDomain:function(a,b){return d.parseUrl(a).domain===d.parseUrl(b).domain},isRelativeUrl:function(a){return""===d.parseUrl(a).protocol},isAbsoluteUrl:function(a){return""!==d.parseUrl(a).protocol},makeUrlAbsolute:function(a,b){if(!d.isRelativeUrl(a))return a;b===c&&(b=this.documentBase);var e=d.parseUrl(a),f=d.parseUrl(b),g=e.protocol||f.protocol,h=e.protocol?e.doubleSlash:e.doubleSlash||f.doubleSlash,i=e.authority||f.authority,j=""!==e.pathname,k=d.makePathAbsolute(e.pathname||f.filename,f.pathname),l=e.search||!j&&f.search||"",m=e.hash;return g+h+i+k+l+m},addSearchParams:function(b,c){var e=d.parseUrl(b),f="object"==typeof c?a.param(c):c,g=e.search||"?";return e.hrefNoSearch+g+("?"!==g.charAt(g.length-1)?"&":"")+f+(e.hash||"")},convertUrlToDataUrl:function(a){var c=d.parseUrl(a);return d.isEmbeddedPage(c)?c.hash.split(f)[0].replace(/^#/,"").replace(/\?.*$/,""):d.isSameDomain(c,this.documentBase)?c.hrefNoHash.replace(this.documentBase.domain,"").split(f)[0]:b.decodeURIComponent(a)},get:function(a){return a===c&&(a=d.parseLocation().hash),d.stripHash(a).replace(/[^\/]*\.[^\/*]+$/,"")},set:function(a){location.hash=a},isPath:function(a){return/\//.test(a)},clean:function(a){return a.replace(this.documentBase.domain,"")},stripHash:function(a){return a.replace(/^#/,"")},stripQueryParams:function(a){return a.replace(/\?.*$/,"")},cleanHash:function(a){return d.stripHash(a.replace(/\?.*$/,"").replace(f,""))},isHashValid:function(a){return/^#[^#]+$/.test(a)},isExternal:function(a){var b=d.parseUrl(a);return b.protocol&&b.domain!==this.documentUrl.domain?!0:!1},hasProtocol:function(a){return/^(:?\w+:)/.test(a)},isEmbeddedPage:function(a){var b=d.parseUrl(a);return""!==b.protocol?!this.isPath(b.hash)&&b.hash&&(b.hrefNoHash===this.documentUrl.hrefNoHash||this.documentBaseDiffers&&b.hrefNoHash===this.documentBase.hrefNoHash):/^#/.test(b.href)},squash:function(a,b){var c,e,f,g,h=this.isPath(a),i=this.parseUrl(a),j=i.hash,k="";return b=b||(d.isPath(a)?d.getLocation():d.getDocumentUrl()),e=h?d.stripHash(a):a,e=d.isPath(i.hash)?d.stripHash(i.hash):e,g=e.indexOf(this.uiStateKey),g>-1&&(k=e.slice(g),e=e.slice(0,g)),c=d.makeUrlAbsolute(e,b),f=this.parseUrl(c).search,h?((d.isPath(j)||0===j.replace("#","").indexOf(this.uiStateKey))&&(j=""),k&&-1===j.indexOf(this.uiStateKey)&&(j+=k),-1===j.indexOf("#")&&""!==j&&(j="#"+j),c=d.parseUrl(c),c=c.protocol+"//"+c.host+c.pathname+f+j):c+=c.indexOf("#")>-1?k:"#"+k,c},isPreservableHash:function(a){return 0===a.replace("#","").indexOf(this.uiStateKey)},hashToSelector:function(a){var b="#"===a.substring(0,1);return b&&(a=a.substring(1)),(b?"#":"")+a.replace(/([!"#$%&'()*+,./:;<=>?@[\]^`{|}~])/g,"\\$1")},getFilePath:function(b){var c="&"+a.mobile.subPageUrlKey;return b&&b.split(c)[0].split(f)[0]},isFirstPageUrl:function(b){var e=d.parseUrl(d.makeUrlAbsolute(b,this.documentBase)),f=e.hrefNoHash===this.documentUrl.hrefNoHash||this.documentBaseDiffers&&e.hrefNoHash===this.documentBase.hrefNoHash,g=a.mobile.firstPage,h=g&&g[0]?g[0].id:c;return f&&(!e.hash||"#"===e.hash||h&&e.hash.replace(/^#/,"")===h)},isPermittedCrossDomainRequest:function(b,c){return a.mobile.allowCrossDomainPages&&("file:"===b.protocol||"content:"===b.protocol)&&-1!==c.search(/^https?:/)}},d.documentUrl=d.parseLocation(),e=a("head").find("base"),d.documentBase=e.length?d.parseUrl(d.makeUrlAbsolute(e.attr("href"),d.documentUrl.href)):d.documentUrl,d.documentBaseDiffers=d.documentUrl.hrefNoHash!==d.documentBase.hrefNoHash,d.getDocumentBase=function(b){return b?a.extend({},d.documentBase):d.documentBase.href},a.extend(a.mobile,{getDocumentUrl:d.getDocumentUrl,getDocumentBase:d.getDocumentBase})}(a),function(a,b){a.mobile.History=function(a,b){this.stack=a||[],this.activeIndex=b||0},a.extend(a.mobile.History.prototype,{getActive:function(){return this.stack[this.activeIndex]},getLast:function(){return this.stack[this.previousIndex]},getNext:function(){return this.stack[this.activeIndex+1]},getPrev:function(){return this.stack[this.activeIndex-1]},add:function(a,b){b=b||{},this.getNext()&&this.clearForward(),b.hash&&-1===b.hash.indexOf("#")&&(b.hash="#"+b.hash),b.url=a,this.stack.push(b),this.activeIndex=this.stack.length-1},clearForward:function(){this.stack=this.stack.slice(0,this.activeIndex+1)},find:function(a,b,c){b=b||this.stack;var d,e,f,g=b.length;for(e=0;g>e;e++)if(d=b[e],(decodeURIComponent(a)===decodeURIComponent(d.url)||decodeURIComponent(a)===decodeURIComponent(d.hash))&&(f=e,c))return f;return f},closest:function(a){var c,d=this.activeIndex;return c=this.find(a,this.stack.slice(0,d)),c===b&&(c=this.find(a,this.stack.slice(d),!0),c=c===b?c:c+d),c},direct:function(c){var d=this.closest(c.url),e=this.activeIndex;d!==b&&(this.activeIndex=d,this.previousIndex=e),e>d?(c.present||c.back||a.noop)(this.getActive(),"back"):d>e?(c.present||c.forward||a.noop)(this.getActive(),"forward"):d===b&&c.missing&&c.missing(this.getActive())}})}(a),function(a){var d=a.mobile.path,e=location.href;a.mobile.Navigator=function(b){this.history=b,this.ignoreInitialHashChange=!0,a.mobile.window.bind({"popstate.history":a.proxy(this.popstate,this),"hashchange.history":a.proxy(this.hashchange,this)})},a.extend(a.mobile.Navigator.prototype,{squash:function(e,f){var g,h,i=d.isPath(e)?d.stripHash(e):e;return h=d.squash(e),g=a.extend({hash:i,url:h},f),b.history.replaceState(g,g.title||c.title,h),g},hash:function(a,b){var c,e,f,g;return c=d.parseUrl(a),e=d.parseLocation(),e.pathname+e.search===c.pathname+c.search?f=c.hash?c.hash:c.pathname+c.search:d.isPath(a)?(g=d.parseUrl(b),f=g.pathname+g.search+(d.isPreservableHash(g.hash)?g.hash.replace("#",""):"")):f=a,f},go:function(e,f,g){var h,i,j,k,l=a.event.special.navigate.isPushStateEnabled();i=d.squash(e),j=this.hash(e,i),g&&j!==d.stripHash(d.parseLocation().hash)&&(this.preventNextHashChange=g),this.preventHashAssignPopState=!0,b.location.hash=j,this.preventHashAssignPopState=!1,h=a.extend({url:i,hash:j,title:c.title},f),l&&(k=new a.Event("popstate"),k.originalEvent={type:"popstate",state:null},this.squash(e,h),g||(this.ignorePopState=!0,a.mobile.window.trigger(k))),this.history.add(h.url,h)},popstate:function(b){var c,f;
if(a.event.special.navigate.isPushStateEnabled())return this.preventHashAssignPopState?(this.preventHashAssignPopState=!1,void b.stopImmediatePropagation()):this.ignorePopState?void(this.ignorePopState=!1):!b.originalEvent.state&&1===this.history.stack.length&&this.ignoreInitialHashChange&&(this.ignoreInitialHashChange=!1,location.href===e)?void b.preventDefault():(c=d.parseLocation().hash,!b.originalEvent.state&&c?(f=this.squash(c),this.history.add(f.url,f),void(b.historyState=f)):void this.history.direct({url:(b.originalEvent.state||{}).url||c,present:function(c,d){b.historyState=a.extend({},c),b.historyState.direction=d}}))},hashchange:function(b){var e,f;if(a.event.special.navigate.isHashChangeEnabled()&&!a.event.special.navigate.isPushStateEnabled()){if(this.preventNextHashChange)return this.preventNextHashChange=!1,void b.stopImmediatePropagation();e=this.history,f=d.parseLocation().hash,this.history.direct({url:f,present:function(c,d){b.hashchangeState=a.extend({},c),b.hashchangeState.direction=d},missing:function(){e.add(f,{hash:f,title:c.title})}})}}})}(a),function(a){a.mobile.navigate=function(b,c,d){a.mobile.navigate.navigator.go(b,c,d)},a.mobile.navigate.history=new a.mobile.History,a.mobile.navigate.navigator=new a.mobile.Navigator(a.mobile.navigate.history);var b=a.mobile.path.parseLocation();a.mobile.navigate.history.add(b.href,{hash:b.hash})}(a),function(a,b){var d={animation:{},transition:{}},e=c.createElement("a"),f=["","webkit-","moz-","o-"];a.each(["animation","transition"],function(c,g){var h=0===c?g+"-name":g;a.each(f,function(c,f){return e.style[a.camelCase(f+h)]!==b?(d[g].prefix=f,!1):void 0}),d[g].duration=a.camelCase(d[g].prefix+g+"-duration"),d[g].event=a.camelCase(d[g].prefix+g+"-end"),""===d[g].prefix&&(d[g].event=d[g].event.toLowerCase())}),a.support.cssTransitions=d.transition.prefix!==b,a.support.cssAnimations=d.animation.prefix!==b,a(e).remove(),a.fn.animationComplete=function(e,f,g){var h,i,j=this,k=f&&"animation"!==f?"transition":"animation";return a.support.cssTransitions&&"transition"===k||a.support.cssAnimations&&"animation"===k?(g===b&&(a(this).context!==c&&(i=3e3*parseFloat(a(this).css(d[k].duration))),(0===i||i===b||isNaN(i))&&(i=a.fn.animationComplete.defaultDuration)),h=setTimeout(function(){a(j).off(d[k].event),e.apply(j)},i),a(this).one(d[k].event,function(){clearTimeout(h),e.call(this,arguments)})):(setTimeout(a.proxy(e,this),0),a(this))},a.fn.animationComplete.defaultDuration=1e3}(a),function(a,b,c,d){function e(a){for(;a&&"undefined"!=typeof a.originalEvent;)a=a.originalEvent;return a}function f(b,c){var f,g,h,i,j,k,l,m,n,o=b.type;if(b=a.Event(b),b.type=c,f=b.originalEvent,g=a.event.props,o.search(/^(mouse|click)/)>-1&&(g=E),f)for(l=g.length,i;l;)i=g[--l],b[i]=f[i];if(o.search(/mouse(down|up)|click/)>-1&&!b.which&&(b.which=1),-1!==o.search(/^touch/)&&(h=e(f),o=h.touches,j=h.changedTouches,k=o&&o.length?o[0]:j&&j.length?j[0]:d))for(m=0,n=C.length;n>m;m++)i=C[m],b[i]=k[i];return b}function g(b){for(var c,d,e={};b;){c=a.data(b,z);for(d in c)c[d]&&(e[d]=e.hasVirtualBinding=!0);b=b.parentNode}return e}function h(b,c){for(var d;b;){if(d=a.data(b,z),d&&(!c||d[c]))return b;b=b.parentNode}return null}function i(){M=!1}function j(){M=!0}function k(){Q=0,K.length=0,L=!1,j()}function l(){i()}function m(){n(),G=setTimeout(function(){G=0,k()},a.vmouse.resetTimerDuration)}function n(){G&&(clearTimeout(G),G=0)}function o(b,c,d){var e;return(d&&d[b]||!d&&h(c.target,b))&&(e=f(c,b),a(c.target).trigger(e)),e}function p(b){var c,d=a.data(b.target,A);L||Q&&Q===d||(c=o("v"+b.type,b),c&&(c.isDefaultPrevented()&&b.preventDefault(),c.isPropagationStopped()&&b.stopPropagation(),c.isImmediatePropagationStopped()&&b.stopImmediatePropagation()))}function q(b){var c,d,f,h=e(b).touches;h&&1===h.length&&(c=b.target,d=g(c),d.hasVirtualBinding&&(Q=P++,a.data(c,A,Q),n(),l(),J=!1,f=e(b).touches[0],H=f.pageX,I=f.pageY,o("vmouseover",b,d),o("vmousedown",b,d)))}function r(a){M||(J||o("vmousecancel",a,g(a.target)),J=!0,m())}function s(b){if(!M){var c=e(b).touches[0],d=J,f=a.vmouse.moveDistanceThreshold,h=g(b.target);J=J||Math.abs(c.pageX-H)>f||Math.abs(c.pageY-I)>f,J&&!d&&o("vmousecancel",b,h),o("vmousemove",b,h),m()}}function t(a){if(!M){j();var b,c,d=g(a.target);o("vmouseup",a,d),J||(b=o("vclick",a,d),b&&b.isDefaultPrevented()&&(c=e(a).changedTouches[0],K.push({touchID:Q,x:c.clientX,y:c.clientY}),L=!0)),o("vmouseout",a,d),J=!1,m()}}function u(b){var c,d=a.data(b,z);if(d)for(c in d)if(d[c])return!0;return!1}function v(){}function w(b){var c=b.substr(1);return{setup:function(){u(this)||a.data(this,z,{});var d=a.data(this,z);d[b]=!0,F[b]=(F[b]||0)+1,1===F[b]&&O.bind(c,p),a(this).bind(c,v),N&&(F.touchstart=(F.touchstart||0)+1,1===F.touchstart&&O.bind("touchstart",q).bind("touchend",t).bind("touchmove",s).bind("scroll",r))},teardown:function(){--F[b],F[b]||O.unbind(c,p),N&&(--F.touchstart,F.touchstart||O.unbind("touchstart",q).unbind("touchmove",s).unbind("touchend",t).unbind("scroll",r));var d=a(this),e=a.data(this,z);e&&(e[b]=!1),d.unbind(c,v),u(this)||d.removeData(z)}}}var x,y,z="virtualMouseBindings",A="virtualTouchID",B="vmouseover vmousedown vmousemove vmouseup vclick vmouseout vmousecancel".split(" "),C="clientX clientY pageX pageY screenX screenY".split(" "),D=a.event.mouseHooks?a.event.mouseHooks.props:[],E=a.event.props.concat(D),F={},G=0,H=0,I=0,J=!1,K=[],L=!1,M=!1,N="addEventListener"in c,O=a(c),P=1,Q=0;for(a.vmouse={moveDistanceThreshold:10,clickDistanceThreshold:10,resetTimerDuration:1500},y=0;y<B.length;y++)a.event.special[B[y]]=w(B[y]);N&&c.addEventListener("click",function(b){var c,d,e,f,g,h,i=K.length,j=b.target;if(i)for(c=b.clientX,d=b.clientY,x=a.vmouse.clickDistanceThreshold,e=j;e;){for(f=0;i>f;f++)if(g=K[f],h=0,e===j&&Math.abs(g.x-c)<x&&Math.abs(g.y-d)<x||a.data(e,A)===g.touchID)return b.preventDefault(),void b.stopPropagation();e=e.parentNode}},!0)}(a,b,c),function(a,b,d){function e(b,c,e,f){var g=e.type;e.type=c,f?a.event.trigger(e,d,b):a.event.dispatch.call(b,e),e.type=g}var f=a(c),g=a.mobile.support.touch,h="touchmove scroll",i=g?"touchstart":"mousedown",j=g?"touchend":"mouseup",k=g?"touchmove":"mousemove";a.each("touchstart touchmove touchend tap taphold swipe swipeleft swiperight scrollstart scrollstop".split(" "),function(b,c){a.fn[c]=function(a){return a?this.bind(c,a):this.trigger(c)},a.attrFn&&(a.attrFn[c]=!0)}),a.event.special.scrollstart={enabled:!0,setup:function(){function b(a,b){c=b,e(f,c?"scrollstart":"scrollstop",a)}var c,d,f=this,g=a(f);g.bind(h,function(e){a.event.special.scrollstart.enabled&&(c||b(e,!0),clearTimeout(d),d=setTimeout(function(){b(e,!1)},50))})},teardown:function(){a(this).unbind(h)}},a.event.special.tap={tapholdThreshold:750,emitTapOnTaphold:!0,setup:function(){var b=this,c=a(b),d=!1;c.bind("vmousedown",function(g){function h(){clearTimeout(k)}function i(){h(),c.unbind("vclick",j).unbind("vmouseup",h),f.unbind("vmousecancel",i)}function j(a){i(),d||l!==a.target?d&&a.stopPropagation():e(b,"tap",a)}if(d=!1,g.which&&1!==g.which)return!1;var k,l=g.target;c.bind("vmouseup",h).bind("vclick",j),f.bind("vmousecancel",i),k=setTimeout(function(){a.event.special.tap.emitTapOnTaphold||(d=!0),e(b,"taphold",a.Event("taphold",{target:l}))},a.event.special.tap.tapholdThreshold)})},teardown:function(){a(this).unbind("vmousedown").unbind("vclick").unbind("vmouseup"),f.unbind("vmousecancel")}},a.event.special.swipe={scrollSupressionThreshold:30,durationThreshold:1e3,horizontalDistanceThreshold:30,verticalDistanceThreshold:30,getLocation:function(a){var c=b.pageXOffset,d=b.pageYOffset,e=a.clientX,f=a.clientY;return 0===a.pageY&&Math.floor(f)>Math.floor(a.pageY)||0===a.pageX&&Math.floor(e)>Math.floor(a.pageX)?(e-=c,f-=d):(f<a.pageY-d||e<a.pageX-c)&&(e=a.pageX-c,f=a.pageY-d),{x:e,y:f}},start:function(b){var c=b.originalEvent.touches?b.originalEvent.touches[0]:b,d=a.event.special.swipe.getLocation(c);return{time:(new Date).getTime(),coords:[d.x,d.y],origin:a(b.target)}},stop:function(b){var c=b.originalEvent.touches?b.originalEvent.touches[0]:b,d=a.event.special.swipe.getLocation(c);return{time:(new Date).getTime(),coords:[d.x,d.y]}},handleSwipe:function(b,c,d,f){if(c.time-b.time<a.event.special.swipe.durationThreshold&&Math.abs(b.coords[0]-c.coords[0])>a.event.special.swipe.horizontalDistanceThreshold&&Math.abs(b.coords[1]-c.coords[1])<a.event.special.swipe.verticalDistanceThreshold){var g=b.coords[0]>c.coords[0]?"swipeleft":"swiperight";return e(d,"swipe",a.Event("swipe",{target:f,swipestart:b,swipestop:c}),!0),e(d,g,a.Event(g,{target:f,swipestart:b,swipestop:c}),!0),!0}return!1},eventInProgress:!1,setup:function(){var b,c=this,d=a(c),e={};b=a.data(this,"mobile-events"),b||(b={length:0},a.data(this,"mobile-events",b)),b.length++,b.swipe=e,e.start=function(b){if(!a.event.special.swipe.eventInProgress){a.event.special.swipe.eventInProgress=!0;var d,g=a.event.special.swipe.start(b),h=b.target,i=!1;e.move=function(b){g&&(d=a.event.special.swipe.stop(b),i||(i=a.event.special.swipe.handleSwipe(g,d,c,h),i&&(a.event.special.swipe.eventInProgress=!1)),Math.abs(g.coords[0]-d.coords[0])>a.event.special.swipe.scrollSupressionThreshold&&b.preventDefault())},e.stop=function(){i=!0,a.event.special.swipe.eventInProgress=!1,f.off(k,e.move),e.move=null},f.on(k,e.move).one(j,e.stop)}},d.on(i,e.start)},teardown:function(){var b,c;b=a.data(this,"mobile-events"),b&&(c=b.swipe,delete b.swipe,b.length--,0===b.length&&a.removeData(this,"mobile-events")),c&&(c.start&&a(this).off(i,c.start),c.move&&f.off(k,c.move),c.stop&&f.off(j,c.stop))}},a.each({scrollstop:"scrollstart",taphold:"tap",swipeleft:"swipe",swiperight:"swipe"},function(b,c){a.event.special[b]={setup:function(){a(this).bind(c,a.noop)},teardown:function(){a(this).unbind(c)}}})}(a,this),function(a){a.event.special.throttledresize={setup:function(){a(this).bind("resize",f)},teardown:function(){a(this).unbind("resize",f)}};var b,c,d,e=250,f=function(){c=(new Date).getTime(),d=c-g,d>=e?(g=c,a(this).trigger("throttledresize")):(b&&clearTimeout(b),b=setTimeout(f,e-d))},g=0}(a),function(a,b){function d(){var a=e();a!==f&&(f=a,l.trigger(m))}var e,f,g,h,i,j,k,l=a(b),m="orientationchange",n={0:!0,180:!0};a.support.orientation&&(i=b.innerWidth||l.width(),j=b.innerHeight||l.height(),k=50,g=i>j&&i-j>k,h=n[b.orientation],(g&&h||!g&&!h)&&(n={"-90":!0,90:!0})),a.event.special.orientationchange=a.extend({},a.event.special.orientationchange,{setup:function(){return a.support.orientation&&!a.event.special.orientationchange.disabled?!1:(f=e(),void l.bind("throttledresize",d))},teardown:function(){return a.support.orientation&&!a.event.special.orientationchange.disabled?!1:void l.unbind("throttledresize",d)},add:function(a){var b=a.handler;a.handler=function(a){return a.orientation=e(),b.apply(this,arguments)}}}),a.event.special.orientationchange.orientation=e=function(){var d=!0,e=c.documentElement;return d=a.support.orientation?n[b.orientation]:e&&e.clientWidth/e.clientHeight<1.1,d?"portrait":"landscape"},a.fn[m]=function(a){return a?this.bind(m,a):this.trigger(m)},a.attrFn&&(a.attrFn[m]=!0)}(a,this),function(a){var b=a("head").children("base"),c={element:b.length?b:a("<base>",{href:a.mobile.path.documentBase.hrefNoHash}).prependTo(a("head")),linkSelector:"[src], link[href], a[rel='external'], :jqmData(ajax='false'), a[target]",set:function(b){a.mobile.dynamicBaseEnabled&&a.support.dynamicBaseTag&&c.element.attr("href",a.mobile.path.makeUrlAbsolute(b,a.mobile.path.documentBase))},rewrite:function(b,d){var e=a.mobile.path.get(b);d.find(c.linkSelector).each(function(b,c){var d=a(c).is("[href]")?"href":a(c).is("[src]")?"src":"action",f=a(c).attr(d);f=f.replace(location.protocol+"//"+location.host+location.pathname,""),/^(\w+:|#|\/)/.test(f)||a(c).attr(d,e+f)})},reset:function(){c.element.attr("href",a.mobile.path.documentBase.hrefNoSearch)}};a.mobile.base=c}(a),function(a,b){a.mobile.widgets={};var c=a.widget,d=a.mobile.keepNative;a.widget=function(c){return function(){var d=c.apply(this,arguments),e=d.prototype.widgetName;return d.initSelector=d.prototype.initSelector!==b?d.prototype.initSelector:":jqmData(role='"+e+"')",a.mobile.widgets[e]=d,d}}(a.widget),a.extend(a.widget,c),a.mobile.document.on("create",function(b){a(b.target).enhanceWithin()}),a.widget("mobile.page",{options:{theme:"a",domCache:!1,keepNativeDefault:a.mobile.keepNative,contentTheme:null,enhanced:!1},_createWidget:function(){a.Widget.prototype._createWidget.apply(this,arguments),this._trigger("init")},_create:function(){return this._trigger("beforecreate")===!1?!1:(this.options.enhanced||this._enhance(),this._on(this.element,{pagebeforehide:"removeContainerBackground",pagebeforeshow:"_handlePageBeforeShow"}),this.element.enhanceWithin(),void("dialog"===a.mobile.getAttribute(this.element[0],"role")&&a.mobile.dialog&&this.element.dialog()))},_enhance:function(){var c="data-"+a.mobile.ns,d=this;this.options.role&&this.element.attr("data-"+a.mobile.ns+"role",this.options.role),this.element.attr("tabindex","0").addClass("ui-page ui-page-theme-"+this.options.theme),this.element.find("["+c+"role='content']").each(function(){var e=a(this),f=this.getAttribute(c+"theme")||b;d.options.contentTheme=f||d.options.contentTheme||d.options.dialog&&d.options.theme||"dialog"===d.element.jqmData("role")&&d.options.theme,e.addClass("ui-content"),d.options.contentTheme&&e.addClass("ui-body-"+d.options.contentTheme),e.attr("role","main").addClass("ui-content")})},bindRemove:function(b){var c=this.element;!c.data("mobile-page").options.domCache&&c.is(":jqmData(external-page='true')")&&c.bind("pagehide.remove",b||function(b,c){if(!c.samePage){var d=a(this),e=new a.Event("pageremove");d.trigger(e),e.isDefaultPrevented()||d.removeWithDependents()}})},_setOptions:function(c){c.theme!==b&&this.element.removeClass("ui-page-theme-"+this.options.theme).addClass("ui-page-theme-"+c.theme),c.contentTheme!==b&&this.element.find("[data-"+a.mobile.ns+"='content']").removeClass("ui-body-"+this.options.contentTheme).addClass("ui-body-"+c.contentTheme)},_handlePageBeforeShow:function(){this.setContainerBackground()},removeContainerBackground:function(){this.element.closest(":mobile-pagecontainer").pagecontainer({theme:"none"})},setContainerBackground:function(a){this.element.parent().pagecontainer({theme:a||this.options.theme})},keepNativeSelector:function(){var b=this.options,c=a.trim(b.keepNative||""),e=a.trim(a.mobile.keepNative),f=a.trim(b.keepNativeDefault),g=d===e?"":e,h=""===g?f:"";return(c?[c]:[]).concat(g?[g]:[]).concat(h?[h]:[]).join(", ")}})}(a),function(a,d){a.widget("mobile.pagecontainer",{options:{theme:"a"},initSelector:!1,_create:function(){this.setLastScrollEnabled=!0,this._on(this.window,{navigate:"_disableRecordScroll",scrollstop:"_delayedRecordScroll"}),this._on(this.window,{navigate:"_filterNavigateEvents"}),this._on({pagechange:"_afterContentChange"}),this.window.one("navigate",a.proxy(function(){this.setLastScrollEnabled=!0},this))},_setOptions:function(a){a.theme!==d&&"none"!==a.theme?this.element.removeClass("ui-overlay-"+this.options.theme).addClass("ui-overlay-"+a.theme):a.theme!==d&&this.element.removeClass("ui-overlay-"+this.options.theme),this._super(a)},_disableRecordScroll:function(){this.setLastScrollEnabled=!1},_enableRecordScroll:function(){this.setLastScrollEnabled=!0},_afterContentChange:function(){this.setLastScrollEnabled=!0,this._off(this.window,"scrollstop"),this._on(this.window,{scrollstop:"_delayedRecordScroll"})},_recordScroll:function(){if(this.setLastScrollEnabled){var a,b,c,d=this._getActiveHistory();d&&(a=this._getScroll(),b=this._getMinScroll(),c=this._getDefaultScroll(),d.lastScroll=b>a?c:a)}},_delayedRecordScroll:function(){setTimeout(a.proxy(this,"_recordScroll"),100)},_getScroll:function(){return this.window.scrollTop()},_getMinScroll:function(){return a.mobile.minScrollBack},_getDefaultScroll:function(){return a.mobile.defaultHomeScroll},_filterNavigateEvents:function(b,c){var d;b.originalEvent&&b.originalEvent.isDefaultPrevented()||(d=b.originalEvent.type.indexOf("hashchange")>-1?c.state.hash:c.state.url,d||(d=this._getHash()),d&&"#"!==d&&0!==d.indexOf("#"+a.mobile.path.uiStateKey)||(d=location.href),this._handleNavigate(d,c.state))},_getHash:function(){return a.mobile.path.parseLocation().hash},getActivePage:function(){return this.activePage},_getInitialContent:function(){return a.mobile.firstPage},_getHistory:function(){return a.mobile.navigate.history},_getActiveHistory:function(){return a.mobile.navigate.history.getActive()},_getDocumentBase:function(){return a.mobile.path.documentBase},back:function(){this.go(-1)},forward:function(){this.go(1)},go:function(c){if(a.mobile.hashListeningEnabled)b.history.go(c);else{var d=a.mobile.navigate.history.activeIndex,e=d+parseInt(c,10),f=a.mobile.navigate.history.stack[e].url,g=c>=1?"forward":"back";a.mobile.navigate.history.activeIndex=e,a.mobile.navigate.history.previousIndex=d,this.change(f,{direction:g,changeHash:!1,fromHashChange:!0})}},_handleDestination:function(b){var c;return"string"===a.type(b)&&(b=a.mobile.path.stripHash(b)),b&&(c=this._getHistory(),b=a.mobile.path.isPath(b)?b:a.mobile.path.makeUrlAbsolute("#"+b,this._getDocumentBase()),b===a.mobile.path.makeUrlAbsolute("#"+c.initialDst,this._getDocumentBase())&&c.stack.length&&c.stack[0].url!==c.initialDst.replace(a.mobile.dialogHashKey,"")&&(b=this._getInitialContent())),b||this._getInitialContent()},_handleDialog:function(b,c){var d,e,f=this.getActivePage();return f&&!f.hasClass("ui-dialog")?("back"===c.direction?this.back():this.forward(),!1):(d=c.pageUrl,e=this._getActiveHistory(),a.extend(b,{role:e.role,transition:e.transition,reverse:"back"===c.direction}),d)},_handleNavigate:function(b,c){var e=a.mobile.path.stripHash(b),f=this._getHistory(),g=0===f.stack.length?"none":d,h={changeHash:!1,fromHashChange:!0,reverse:"back"===c.direction};a.extend(h,c,{transition:(f.getLast()||{}).transition||g}),f.activeIndex>0&&e.indexOf(a.mobile.dialogHashKey)>-1&&f.initialDst!==e&&(e=this._handleDialog(h,c),e===!1)||this._changeContent(this._handleDestination(e),h)},_changeContent:function(b,c){a.mobile.changePage(b,c)},_getBase:function(){return a.mobile.base},_getNs:function(){return a.mobile.ns},_enhance:function(a,b){return a.page({role:b})},_include:function(a,b){a.appendTo(this.element),this._enhance(a,b.role),a.page("bindRemove")},_find:function(b){var c,d=this._createFileUrl(b),e=this._createDataUrl(b),f=this._getInitialContent();return c=this.element.children("[data-"+this._getNs()+"url='"+e+"']"),0===c.length&&e&&!a.mobile.path.isPath(e)&&(c=this.element.children(a.mobile.path.hashToSelector("#"+e)).attr("data-"+this._getNs()+"url",e).jqmData("url",e)),0===c.length&&a.mobile.path.isFirstPageUrl(d)&&f&&f.parent().length&&(c=a(f)),c},_getLoader:function(){return a.mobile.loading()},_showLoading:function(b,c,d,e){this._loadMsg||(this._loadMsg=setTimeout(a.proxy(function(){this._getLoader().loader("show",c,d,e),this._loadMsg=0},this),b))},_hideLoading:function(){clearTimeout(this._loadMsg),this._loadMsg=0,this._getLoader().loader("hide")},_showError:function(){this._hideLoading(),this._showLoading(0,a.mobile.pageLoadErrorMessageTheme,a.mobile.pageLoadErrorMessage,!0),setTimeout(a.proxy(this,"_hideLoading"),1500)},_parse:function(b,c){var d,e=a("<div></div>");return e.get(0).innerHTML=b,d=e.find(":jqmData(role='page'), :jqmData(role='dialog')").first(),d.length||(d=a("<div data-"+this._getNs()+"role='page'>"+(b.split(/<\/?body[^>]*>/gim)[1]||"")+"</div>")),d.attr("data-"+this._getNs()+"url",a.mobile.path.convertUrlToDataUrl(c)).attr("data-"+this._getNs()+"external-page",!0),d},_setLoadedTitle:function(b,c){var d=c.match(/<title[^>]*>([^<]*)/)&&RegExp.$1;d&&!b.jqmData("title")&&(d=a("<div>"+d+"</div>").text(),b.jqmData("title",d))},_isRewritableBaseTag:function(){return a.mobile.dynamicBaseEnabled&&!a.support.dynamicBaseTag},_createDataUrl:function(b){return a.mobile.path.convertUrlToDataUrl(b)},_createFileUrl:function(b){return a.mobile.path.getFilePath(b)},_triggerWithDeprecated:function(b,c,d){var e=a.Event("page"+b),f=a.Event(this.widgetName+b);return(d||this.element).trigger(e,c),this.element.trigger(f,c),{deprecatedEvent:e,event:f}},_loadSuccess:function(b,c,e,f){var g=this._createFileUrl(b),h=this._createDataUrl(b);return a.proxy(function(i,j,k){var l,m=new RegExp("(<[^>]+\\bdata-"+this._getNs()+"role=[\"']?page[\"']?[^>]*>)"),n=new RegExp("\\bdata-"+this._getNs()+"url=[\"']?([^\"'>]*)[\"']?");m.test(i)&&RegExp.$1&&n.test(RegExp.$1)&&RegExp.$1&&(g=a.mobile.path.getFilePath(a("<div>"+RegExp.$1+"</div>").text())),e.prefetch===d&&this._getBase().set(g),l=this._parse(i,g),this._setLoadedTitle(l,i),c.xhr=k,c.textStatus=j,c.page=l,c.content=l,this._trigger("load",d,c)&&(this._isRewritableBaseTag()&&l&&this._getBase().rewrite(g,l),this._include(l,e),b.indexOf("&"+a.mobile.subPageUrlKey)>-1&&(l=this.element.children("[data-"+this._getNs()+"url='"+h+"']")),e.showLoadMsg&&this._hideLoading(),this.element.trigger("pageload"),f.resolve(b,e,l))},this)},_loadDefaults:{type:"get",data:d,reloadPage:!1,reload:!1,role:d,showLoadMsg:!1,loadMsgDelay:50},load:function(b,c){var e,f,g,h,i=c&&c.deferred||a.Deferred(),j=a.extend({},this._loadDefaults,c),k=null,l=a.mobile.path.makeUrlAbsolute(b,this._findBaseWithDefault());return j.reload=j.reloadPage,j.data&&"get"===j.type&&(l=a.mobile.path.addSearchParams(l,j.data),j.data=d),j.data&&"post"===j.type&&(j.reload=!0),e=this._createFileUrl(l),f=this._createDataUrl(l),k=this._find(l),0===k.length&&a.mobile.path.isEmbeddedPage(e)&&!a.mobile.path.isFirstPageUrl(e)?void i.reject(l,j):(this._getBase().reset(),k.length&&!j.reload?(this._enhance(k,j.role),i.resolve(l,j,k),void(j.prefetch||this._getBase().set(b))):(h={url:b,absUrl:l,dataUrl:f,deferred:i,options:j},g=this._triggerWithDeprecated("beforeload",h),g.deprecatedEvent.isDefaultPrevented()||g.event.isDefaultPrevented()?void 0:(j.showLoadMsg&&this._showLoading(j.loadMsgDelay),j.prefetch===d&&this._getBase().reset(),a.mobile.allowCrossDomainPages||a.mobile.path.isSameDomain(a.mobile.path.documentUrl,l)?void a.ajax({url:e,type:j.type,data:j.data,contentType:j.contentType,dataType:"html",success:this._loadSuccess(l,h,j,i),error:this._loadError(l,h,j,i)}):void i.reject(l,j))))},_loadError:function(b,c,d,e){return a.proxy(function(f,g,h){this._getBase().set(a.mobile.path.get()),c.xhr=f,c.textStatus=g,c.errorThrown=h;var i=this._triggerWithDeprecated("loadfailed",c);i.deprecatedEvent.isDefaultPrevented()||i.event.isDefaultPrevented()||(d.showLoadMsg&&this._showError(),e.reject(b,d))},this)},_getTransitionHandler:function(b){return b=a.mobile._maybeDegradeTransition(b),a.mobile.transitionHandlers[b]||a.mobile.defaultTransitionHandler},_triggerCssTransitionEvents:function(b,c,d){var e=!1;d=d||"",c&&(b[0]===c[0]&&(e=!0),this._triggerWithDeprecated(d+"hide",{nextPage:b,samePage:e},c)),this._triggerWithDeprecated(d+"show",{prevPage:c||a("")},b)},_cssTransition:function(b,c,d){var e,f,g=d.transition,h=d.reverse,i=d.deferred;this._triggerCssTransitionEvents(b,c,"before"),this._hideLoading(),e=this._getTransitionHandler(g),f=new e(g,h,b,c).transition(),f.done(function(){i.resolve.apply(i,arguments)}),f.done(a.proxy(function(){this._triggerCssTransitionEvents(b,c)},this))},_releaseTransitionLock:function(){f=!1,e.length>0&&a.mobile.changePage.apply(null,e.pop())},_removeActiveLinkClass:function(b){a.mobile.removeActiveLinkClass(b)},_loadUrl:function(b,c,d){d.target=b,d.deferred=a.Deferred(),this.load(b,d),d.deferred.done(a.proxy(function(a,b,d){f=!1,b.absUrl=c.absUrl,this.transition(d,c,b)},this)),d.deferred.fail(a.proxy(function(){this._removeActiveLinkClass(!0),this._releaseTransitionLock(),this._triggerWithDeprecated("changefailed",c)},this))},_triggerPageBeforeChange:function(b,c,d){var e=new a.Event("pagebeforechange");return a.extend(c,{toPage:b,options:d}),c.absUrl="string"===a.type(b)?a.mobile.path.makeUrlAbsolute(b,this._findBaseWithDefault()):d.absUrl,this.element.trigger(e,c),e.isDefaultPrevented()?!1:!0},change:function(b,c){if(f)return void e.unshift(arguments);var d=a.extend({},a.mobile.changePage.defaults,c),g={};d.fromPage=d.fromPage||this.activePage,this._triggerPageBeforeChange(b,g,d)&&(b=g.toPage,"string"===a.type(b)?(f=!0,this._loadUrl(b,g,d)):this.transition(b,g,d))},transition:function(b,g,h){var i,j,k,l,m,n,o,p,q,r,s,t,u,v;if(f)return void e.unshift([b,h]);if(this._triggerPageBeforeChange(b,g,h)&&(v=this._triggerWithDeprecated("beforetransition",g),!v.deprecatedEvent.isDefaultPrevented()&&!v.event.isDefaultPrevented())){if(f=!0,b[0]!==a.mobile.firstPage[0]||h.dataUrl||(h.dataUrl=a.mobile.path.documentUrl.hrefNoHash),i=h.fromPage,j=h.dataUrl&&a.mobile.path.convertUrlToDataUrl(h.dataUrl)||b.jqmData("url"),k=j,l=a.mobile.path.getFilePath(j),m=a.mobile.navigate.history.getActive(),n=0===a.mobile.navigate.history.activeIndex,o=0,p=c.title,q=("dialog"===h.role||"dialog"===b.jqmData("role"))&&b.jqmData("dialog")!==!0,i&&i[0]===b[0]&&!h.allowSamePageTransition)return f=!1,this._triggerWithDeprecated("transition",g),this.element.trigger("pagechange",g),void(h.fromHashChange&&a.mobile.navigate.history.direct({url:j}));b.page({role:h.role}),h.fromHashChange&&(o="back"===h.direction?-1:1);try{c.activeElement&&"body"!==c.activeElement.nodeName.toLowerCase()?a(c.activeElement).blur():a("input:focus, textarea:focus, select:focus").blur()}catch(w){}r=!1,q&&m&&(m.url&&m.url.indexOf(a.mobile.dialogHashKey)>-1&&this.activePage&&!this.activePage.hasClass("ui-dialog")&&a.mobile.navigate.history.activeIndex>0&&(h.changeHash=!1,r=!0),j=m.url||"",j+=!r&&j.indexOf("#")>-1?a.mobile.dialogHashKey:"#"+a.mobile.dialogHashKey,0===a.mobile.navigate.history.activeIndex&&j===a.mobile.navigate.history.initialDst&&(j+=a.mobile.dialogHashKey)),s=m?b.jqmData("title")||b.children(":jqmData(role='header')").find(".ui-title").text():p,s&&p===c.title&&(p=s),b.jqmData("title")||b.jqmData("title",p),h.transition=h.transition||(o&&!n?m.transition:d)||(q?a.mobile.defaultDialogTransition:a.mobile.defaultPageTransition),!o&&r&&(a.mobile.navigate.history.getActive().pageUrl=k),j&&!h.fromHashChange&&(!a.mobile.path.isPath(j)&&j.indexOf("#")<0&&(j="#"+j),t={transition:h.transition,title:p,pageUrl:k,role:h.role},h.changeHash!==!1&&a.mobile.hashListeningEnabled?a.mobile.navigate(j,t,!0):b[0]!==a.mobile.firstPage[0]&&a.mobile.navigate.history.add(j,t)),c.title=p,a.mobile.activePage=b,this.activePage=b,h.reverse=h.reverse||0>o,u=a.Deferred(),this._cssTransition(b,i,{transition:h.transition,reverse:h.reverse,deferred:u}),u.done(a.proxy(function(c,d,e,f,i){a.mobile.removeActiveLinkClass(),h.duplicateCachedPage&&h.duplicateCachedPage.remove(),i||a.mobile.focusPage(b),this._releaseTransitionLock(),this.element.trigger("pagechange",g),this._triggerWithDeprecated("transition",g)},this))}},_findBaseWithDefault:function(){var b=this.activePage&&a.mobile.getClosestBaseUrl(this.activePage);return b||a.mobile.path.documentBase.hrefNoHash}}),a.mobile.navreadyDeferred=a.Deferred();var e=[],f=!1}(a),function(a,c){function d(a){for(;a&&("string"!=typeof a.nodeName||"a"!==a.nodeName.toLowerCase());)a=a.parentNode;return a}var e=a.Deferred(),f=a.Deferred(),g=a.mobile.path.documentUrl,h=null;a.mobile.loadPage=function(b,c){var d;return c=c||{},d=c.pageContainer||a.mobile.pageContainer,c.deferred=a.Deferred(),d.pagecontainer("load",b,c),c.deferred.promise()},a.mobile.back=function(){var c=b.navigator;this.phonegapNavigationEnabled&&c&&c.app&&c.app.backHistory?c.app.backHistory():a.mobile.pageContainer.pagecontainer("back")},a.mobile.focusPage=function(a){var b=a.find("[autofocus]"),c=a.find(".ui-title:eq(0)");return b.length?void b.focus():void(c.length?c.focus():a.focus())},a.mobile._maybeDegradeTransition=a.mobile._maybeDegradeTransition||function(a){return a},a.mobile.changePage=function(b,c){a.mobile.pageContainer.pagecontainer("change",b,c)},a.mobile.changePage.defaults={transition:c,reverse:!1,changeHash:!0,fromHashChange:!1,role:c,duplicateCachedPage:c,pageContainer:c,showLoadMsg:!0,dataUrl:c,fromPage:c,allowSamePageTransition:!1},a.mobile._registerInternalEvents=function(){var e=function(b,c){var d,e,f,i,j=!0;return!a.mobile.ajaxEnabled||b.is(":jqmData(ajax='false')")||!b.jqmHijackable().length||b.attr("target")?!1:(d=h&&h.attr("formaction")||b.attr("action"),i=(b.attr("method")||"get").toLowerCase(),d||(d=a.mobile.getClosestBaseUrl(b),"get"===i&&(d=a.mobile.path.parseUrl(d).hrefNoSearch),d===a.mobile.path.documentBase.hrefNoHash&&(d=g.hrefNoSearch)),d=a.mobile.path.makeUrlAbsolute(d,a.mobile.getClosestBaseUrl(b)),a.mobile.path.isExternal(d)&&!a.mobile.path.isPermittedCrossDomainRequest(g,d)?!1:(c||(e=b.serializeArray(),h&&h[0].form===b[0]&&(f=h.attr("name"),f&&(a.each(e,function(a,b){return b.name===f?(f="",!1):void 0}),f&&e.push({name:f,value:h.attr("value")}))),j={url:d,options:{type:i,data:a.param(e),transition:b.jqmData("transition"),reverse:"reverse"===b.jqmData("direction"),reloadPage:!0}}),j))};a.mobile.document.delegate("form","submit",function(b){var c;b.isDefaultPrevented()||(c=e(a(this)),c&&(a.mobile.changePage(c.url,c.options),b.preventDefault()))}),a.mobile.document.bind("vclick",function(b){var c,f,g=b.target,i=!1;if(!(b.which>1)&&a.mobile.linkBindingEnabled){if(h=a(g),a.data(g,"mobile-button")){if(!e(a(g).closest("form"),!0))return;g.parentNode&&(g=g.parentNode)}else{if(g=d(g),!g||"#"===a.mobile.path.parseUrl(g.getAttribute("href")||"#").hash)return;if(!a(g).jqmHijackable().length)return}~g.className.indexOf("ui-link-inherit")?g.parentNode&&(f=a.data(g.parentNode,"buttonElements")):f=a.data(g,"buttonElements"),f?g=f.outer:i=!0,c=a(g),i&&(c=c.closest(".ui-btn")),c.length>0&&!c.hasClass("ui-state-disabled")&&(a.mobile.removeActiveLinkClass(!0),a.mobile.activeClickedLink=c,a.mobile.activeClickedLink.addClass(a.mobile.activeBtnClass))}}),a.mobile.document.bind("click",function(e){if(a.mobile.linkBindingEnabled&&!e.isDefaultPrevented()){var f,h,i,j,k,l,m,n=d(e.target),o=a(n),p=function(){b.setTimeout(function(){a.mobile.removeActiveLinkClass(!0)},200)};if(a.mobile.activeClickedLink&&a.mobile.activeClickedLink[0]===e.target.parentNode&&p(),n&&!(e.which>1)&&o.jqmHijackable().length){if(o.is(":jqmData(rel='back')"))return a.mobile.back(),!1;if(f=a.mobile.getClosestBaseUrl(o),h=a.mobile.path.makeUrlAbsolute(o.attr("href")||"#",f),!a.mobile.ajaxEnabled&&!a.mobile.path.isEmbeddedPage(h))return void p();if(-1!==h.search("#")){if(h=h.replace(/[^#]*#/,""),!h)return void e.preventDefault();h=a.mobile.path.isPath(h)?a.mobile.path.makeUrlAbsolute(h,f):a.mobile.path.makeUrlAbsolute("#"+h,g.hrefNoHash)}if(i=o.is("[rel='external']")||o.is(":jqmData(ajax='false')")||o.is("[target]"),j=i||a.mobile.path.isExternal(h)&&!a.mobile.path.isPermittedCrossDomainRequest(g,h))return void p();k=o.jqmData("transition"),l="reverse"===o.jqmData("direction")||o.jqmData("back"),m=o.attr("data-"+a.mobile.ns+"rel")||c,a.mobile.changePage(h,{transition:k,reverse:l,role:m,link:o}),e.preventDefault()}}}),a.mobile.document.delegate(".ui-page","pageshow.prefetch",function(){var b=[];a(this).find("a:jqmData(prefetch)").each(function(){var c=a(this),d=c.attr("href");d&&-1===a.inArray(d,b)&&(b.push(d),a.mobile.loadPage(d,{role:c.attr("data-"+a.mobile.ns+"rel"),prefetch:!0}))})}),a.mobile.pageContainer.pagecontainer(),a.mobile.document.bind("pageshow",function(){f?f.done(a.mobile.resetActivePageHeight):a.mobile.resetActivePageHeight()}),a.mobile.window.bind("throttledresize",a.mobile.resetActivePageHeight)},a(function(){e.resolve()}),a.mobile.window.load(function(){f.resolve(),f=null}),a.when(e,a.mobile.navreadyDeferred).done(function(){a.mobile._registerInternalEvents()})}(a),function(a,b){a.mobile.Transition=function(){this.init.apply(this,arguments)},a.extend(a.mobile.Transition.prototype,{toPreClass:" ui-page-pre-in",init:function(b,c,d,e){a.extend(this,{name:b,reverse:c,$to:d,$from:e,deferred:new a.Deferred})},cleanFrom:function(){this.$from.removeClass(a.mobile.activePageClass+" out in reverse "+this.name).height("")},beforeDoneIn:function(){},beforeDoneOut:function(){},beforeStartOut:function(){},doneIn:function(){this.beforeDoneIn(),this.$to.removeClass("out in reverse "+this.name).height(""),this.toggleViewportClass(),a.mobile.window.scrollTop()!==this.toScroll&&this.scrollPage(),this.sequential||this.$to.addClass(a.mobile.activePageClass),this.deferred.resolve(this.name,this.reverse,this.$to,this.$from,!0)
},doneOut:function(a,b,c,d){this.beforeDoneOut(),this.startIn(a,b,c,d)},hideIn:function(a){this.$to.css("z-index",-10),a.call(this),this.$to.css("z-index","")},scrollPage:function(){a.event.special.scrollstart.enabled=!1,(a.mobile.hideUrlBar||this.toScroll!==a.mobile.defaultHomeScroll)&&b.scrollTo(0,this.toScroll),setTimeout(function(){a.event.special.scrollstart.enabled=!0},150)},startIn:function(b,c,d,e){this.hideIn(function(){this.$to.addClass(a.mobile.activePageClass+this.toPreClass),e||a.mobile.focusPage(this.$to),this.$to.height(b+this.toScroll),d||this.scrollPage()}),this.$to.removeClass(this.toPreClass).addClass(this.name+" in "+c),d?this.doneIn():this.$to.animationComplete(a.proxy(function(){this.doneIn()},this))},startOut:function(b,c,d){this.beforeStartOut(b,c,d),this.$from.height(b+a.mobile.window.scrollTop()).addClass(this.name+" out"+c)},toggleViewportClass:function(){a.mobile.pageContainer.toggleClass("ui-mobile-viewport-transitioning viewport-"+this.name)},transition:function(){var b,c=this.reverse?" reverse":"",d=a.mobile.getScreenHeight(),e=a.mobile.maxTransitionWidth!==!1&&a.mobile.window.width()>a.mobile.maxTransitionWidth;return this.toScroll=a.mobile.navigate.history.getActive().lastScroll||a.mobile.defaultHomeScroll,b=!a.support.cssTransitions||!a.support.cssAnimations||e||!this.name||"none"===this.name||Math.max(a.mobile.window.scrollTop(),this.toScroll)>a.mobile.getMaxScrollForTransition(),this.toggleViewportClass(),this.$from&&!b?this.startOut(d,c,b):this.doneOut(d,c,b,!0),this.deferred.promise()}})}(a,this),function(a){a.mobile.SerialTransition=function(){this.init.apply(this,arguments)},a.extend(a.mobile.SerialTransition.prototype,a.mobile.Transition.prototype,{sequential:!0,beforeDoneOut:function(){this.$from&&this.cleanFrom()},beforeStartOut:function(b,c,d){this.$from.animationComplete(a.proxy(function(){this.doneOut(b,c,d)},this))}})}(a),function(a){a.mobile.ConcurrentTransition=function(){this.init.apply(this,arguments)},a.extend(a.mobile.ConcurrentTransition.prototype,a.mobile.Transition.prototype,{sequential:!1,beforeDoneIn:function(){this.$from&&this.cleanFrom()},beforeStartOut:function(a,b,c){this.doneOut(a,b,c)}})}(a),function(a){var b=function(){return 3*a.mobile.getScreenHeight()};a.mobile.transitionHandlers={sequential:a.mobile.SerialTransition,simultaneous:a.mobile.ConcurrentTransition},a.mobile.defaultTransitionHandler=a.mobile.transitionHandlers.sequential,a.mobile.transitionFallbacks={},a.mobile._maybeDegradeTransition=function(b){return b&&!a.support.cssTransform3d&&a.mobile.transitionFallbacks[b]&&(b=a.mobile.transitionFallbacks[b]),b},a.mobile.getMaxScrollForTransition=a.mobile.getMaxScrollForTransition||b}(a),function(a){a.mobile.transitionFallbacks.flip="fade"}(a,this),function(a){a.mobile.transitionFallbacks.flow="fade"}(a,this),function(a){a.mobile.transitionFallbacks.pop="fade"}(a,this),function(a){a.mobile.transitionHandlers.slide=a.mobile.transitionHandlers.simultaneous,a.mobile.transitionFallbacks.slide="fade"}(a,this),function(a){a.mobile.transitionFallbacks.slidedown="fade"}(a,this),function(a){a.mobile.transitionFallbacks.slidefade="fade"}(a,this),function(a){a.mobile.transitionFallbacks.slideup="fade"}(a,this),function(a){a.mobile.transitionFallbacks.turn="fade"}(a,this),function(a){a.mobile.degradeInputs={color:!1,date:!1,datetime:!1,"datetime-local":!1,email:!1,month:!1,number:!1,range:"number",search:"text",tel:!1,time:!1,url:!1,week:!1},a.mobile.page.prototype.options.degradeInputs=a.mobile.degradeInputs,a.mobile.degradeInputsWithin=function(b){b=a(b),b.find("input").not(a.mobile.page.prototype.keepNativeSelector()).each(function(){var b,c,d,e,f=a(this),g=this.getAttribute("type"),h=a.mobile.degradeInputs[g]||"text";a.mobile.degradeInputs[g]&&(b=a("<div>").html(f.clone()).html(),c=b.indexOf(" type=")>-1,d=c?/\s+type=["']?\w+['"]?/:/\/?>/,e=' type="'+h+'" data-'+a.mobile.ns+'type="'+g+'"'+(c?"":">"),f.replaceWith(b.replace(d,e)))})}}(a),function(a,b,c){a.widget("mobile.page",a.mobile.page,{options:{closeBtn:"left",closeBtnText:"Close",overlayTheme:"a",corners:!0,dialog:!1},_create:function(){this._super(),this.options.dialog&&(a.extend(this,{_inner:this.element.children(),_headerCloseButton:null}),this.options.enhanced||this._setCloseBtn(this.options.closeBtn))},_enhance:function(){this._super(),this.options.dialog&&this.element.addClass("ui-dialog").wrapInner(a("<div/>",{role:"dialog","class":"ui-dialog-contain ui-overlay-shadow"+(this.options.corners?" ui-corner-all":"")}))},_setOptions:function(b){var d,e,f=this.options;b.corners!==c&&this._inner.toggleClass("ui-corner-all",!!b.corners),b.overlayTheme!==c&&a.mobile.activePage[0]===this.element[0]&&(f.overlayTheme=b.overlayTheme,this._handlePageBeforeShow()),b.closeBtnText!==c&&(d=f.closeBtn,e=b.closeBtnText),b.closeBtn!==c&&(d=b.closeBtn),d&&this._setCloseBtn(d,e),this._super(b)},_handlePageBeforeShow:function(){this.options.overlayTheme&&this.options.dialog?(this.removeContainerBackground(),this.setContainerBackground(this.options.overlayTheme)):this._super()},_setCloseBtn:function(b,c){var d,e=this._headerCloseButton;b="left"===b?"left":"right"===b?"right":"none","none"===b?e&&(e.remove(),e=null):e?(e.removeClass("ui-btn-left ui-btn-right").addClass("ui-btn-"+b),c&&e.text(c)):(d=this._inner.find(":jqmData(role='header')").first(),e=a("<a></a>",{href:"#","class":"ui-btn ui-corner-all ui-icon-delete ui-btn-icon-notext ui-btn-"+b}).attr("data-"+a.mobile.ns+"rel","back").text(c||this.options.closeBtnText||"").prependTo(d)),this._headerCloseButton=e}})}(a,this),function(a,b,c){a.widget("mobile.dialog",{options:{closeBtn:"left",closeBtnText:"Close",overlayTheme:"a",corners:!0},_handlePageBeforeShow:function(){this._isCloseable=!0,this.options.overlayTheme&&this.element.page("removeContainerBackground").page("setContainerBackground",this.options.overlayTheme)},_handlePageBeforeHide:function(){this._isCloseable=!1},_handleVClickSubmit:function(b){var c,d=a(b.target).closest("vclick"===b.type?"a":"form");d.length&&!d.jqmData("transition")&&(c={},c["data-"+a.mobile.ns+"transition"]=(a.mobile.navigate.history.getActive()||{}).transition||a.mobile.defaultDialogTransition,c["data-"+a.mobile.ns+"direction"]="reverse",d.attr(c))},_create:function(){var b=this.element,c=this.options;b.addClass("ui-dialog").wrapInner(a("<div/>",{role:"dialog","class":"ui-dialog-contain ui-overlay-shadow"+(c.corners?" ui-corner-all":"")})),a.extend(this,{_isCloseable:!1,_inner:b.children(),_headerCloseButton:null}),this._on(b,{vclick:"_handleVClickSubmit",submit:"_handleVClickSubmit",pagebeforeshow:"_handlePageBeforeShow",pagebeforehide:"_handlePageBeforeHide"}),this._setCloseBtn(c.closeBtn)},_setOptions:function(b){var d,e,f=this.options;b.corners!==c&&this._inner.toggleClass("ui-corner-all",!!b.corners),b.overlayTheme!==c&&a.mobile.activePage[0]===this.element[0]&&(f.overlayTheme=b.overlayTheme,this._handlePageBeforeShow()),b.closeBtnText!==c&&(d=f.closeBtn,e=b.closeBtnText),b.closeBtn!==c&&(d=b.closeBtn),d&&this._setCloseBtn(d,e),this._super(b)},_setCloseBtn:function(b,c){var d,e=this._headerCloseButton;b="left"===b?"left":"right"===b?"right":"none","none"===b?e&&(e.remove(),e=null):e?(e.removeClass("ui-btn-left ui-btn-right").addClass("ui-btn-"+b),c&&e.text(c)):(d=this._inner.find(":jqmData(role='header')").first(),e=a("<a></a>",{role:"button",href:"#","class":"ui-btn ui-corner-all ui-icon-delete ui-btn-icon-notext ui-btn-"+b}).text(c||this.options.closeBtnText||"").prependTo(d),this._on(e,{click:"close"})),this._headerCloseButton=e},close:function(){var b=a.mobile.navigate.history;this._isCloseable&&(this._isCloseable=!1,a.mobile.hashListeningEnabled&&b.activeIndex>0?a.mobile.back():a.mobile.pageContainer.pagecontainer("back"))}})}(a,this),function(a,b){var c=/([A-Z])/g,d=function(a){return"ui-btn-icon-"+(null===a?"left":a)};a.widget("mobile.collapsible",{options:{enhanced:!1,expandCueText:null,collapseCueText:null,collapsed:!0,heading:"h1,h2,h3,h4,h5,h6,legend",collapsedIcon:null,expandedIcon:null,iconpos:null,theme:null,contentTheme:null,inset:null,corners:null,mini:null},_create:function(){var b=this.element,c={accordion:b.closest(":jqmData(role='collapsible-set'),:jqmData(role='collapsibleset')"+(a.mobile.collapsibleset?", :mobile-collapsibleset":"")).addClass("ui-collapsible-set")};this._ui=c,this._renderedOptions=this._getOptions(this.options),this.options.enhanced?(c.heading=a(".ui-collapsible-heading",this.element[0]),c.content=c.heading.next(),c.anchor=a("a",c.heading[0]).first(),c.status=c.anchor.children(".ui-collapsible-heading-status")):this._enhance(b,c),this._on(c.heading,{tap:function(){c.heading.find("a").first().addClass(a.mobile.activeBtnClass)},click:function(a){this._handleExpandCollapse(!c.heading.hasClass("ui-collapsible-heading-collapsed")),a.preventDefault(),a.stopPropagation()}})},_getOptions:function(b){var d,e=this._ui.accordion,f=this._ui.accordionWidget;b=a.extend({},b),e.length&&!f&&(this._ui.accordionWidget=f=e.data("mobile-collapsibleset"));for(d in b)b[d]=null!=b[d]?b[d]:f?f.options[d]:e.length?a.mobile.getAttribute(e[0],d.replace(c,"-$1").toLowerCase()):null,null==b[d]&&(b[d]=a.mobile.collapsible.defaults[d]);return b},_themeClassFromOption:function(a,b){return b?"none"===b?"":a+b:""},_enhance:function(b,c){var e,f=this._renderedOptions,g=this._themeClassFromOption("ui-body-",f.contentTheme);return b.addClass("ui-collapsible "+(f.inset?"ui-collapsible-inset ":"")+(f.inset&&f.corners?"ui-corner-all ":"")+(g?"ui-collapsible-themed-content ":"")),c.originalHeading=b.children(this.options.heading).first(),c.content=b.wrapInner("<div class='ui-collapsible-content "+g+"'></div>").children(".ui-collapsible-content"),c.heading=c.originalHeading,c.heading.is("legend")&&(c.heading=a("<div role='heading'>"+c.heading.html()+"</div>"),c.placeholder=a("<div><!-- placeholder for legend --></div>").insertBefore(c.originalHeading),c.originalHeading.remove()),e=f.collapsed?f.collapsedIcon?"ui-icon-"+f.collapsedIcon:"":f.expandedIcon?"ui-icon-"+f.expandedIcon:"",c.status=a("<span class='ui-collapsible-heading-status'></span>"),c.anchor=c.heading.detach().addClass("ui-collapsible-heading").append(c.status).wrapInner("<a href='#' class='ui-collapsible-heading-toggle'></a>").find("a").first().addClass("ui-btn "+(e?e+" ":"")+(e?d(f.iconpos)+" ":"")+this._themeClassFromOption("ui-btn-",f.theme)+" "+(f.mini?"ui-mini ":"")),c.heading.insertBefore(c.content),this._handleExpandCollapse(this.options.collapsed),c},refresh:function(){this._applyOptions(this.options),this._renderedOptions=this._getOptions(this.options)},_applyOptions:function(a){var c,e,f,g,h,i=this.element,j=this._renderedOptions,k=this._ui,l=k.anchor,m=k.status,n=this._getOptions(a);a.collapsed!==b&&this._handleExpandCollapse(a.collapsed),c=i.hasClass("ui-collapsible-collapsed"),c?n.expandCueText!==b&&m.text(n.expandCueText):n.collapseCueText!==b&&m.text(n.collapseCueText),h=n.collapsedIcon!==b?n.collapsedIcon!==!1:j.collapsedIcon!==!1,(n.iconpos!==b||n.collapsedIcon!==b||n.expandedIcon!==b)&&(l.removeClass([d(j.iconpos)].concat(j.expandedIcon?["ui-icon-"+j.expandedIcon]:[]).concat(j.collapsedIcon?["ui-icon-"+j.collapsedIcon]:[]).join(" ")),h&&l.addClass([d(n.iconpos!==b?n.iconpos:j.iconpos)].concat(c?["ui-icon-"+(n.collapsedIcon!==b?n.collapsedIcon:j.collapsedIcon)]:["ui-icon-"+(n.expandedIcon!==b?n.expandedIcon:j.expandedIcon)]).join(" "))),n.theme!==b&&(f=this._themeClassFromOption("ui-btn-",j.theme),e=this._themeClassFromOption("ui-btn-",n.theme),l.removeClass(f).addClass(e)),n.contentTheme!==b&&(f=this._themeClassFromOption("ui-body-",j.contentTheme),e=this._themeClassFromOption("ui-body-",n.contentTheme),k.content.removeClass(f).addClass(e)),n.inset!==b&&(i.toggleClass("ui-collapsible-inset",n.inset),g=!(!n.inset||!n.corners&&!j.corners)),n.corners!==b&&(g=!(!n.corners||!n.inset&&!j.inset)),g!==b&&i.toggleClass("ui-corner-all",g),n.mini!==b&&l.toggleClass("ui-mini",n.mini)},_setOptions:function(a){this._applyOptions(a),this._super(a),this._renderedOptions=this._getOptions(this.options)},_handleExpandCollapse:function(b){var c=this._renderedOptions,d=this._ui;d.status.text(b?c.expandCueText:c.collapseCueText),d.heading.toggleClass("ui-collapsible-heading-collapsed",b).find("a").first().toggleClass("ui-icon-"+c.expandedIcon,!b).toggleClass("ui-icon-"+c.collapsedIcon,b||c.expandedIcon===c.collapsedIcon).removeClass(a.mobile.activeBtnClass),this.element.toggleClass("ui-collapsible-collapsed",b),d.content.toggleClass("ui-collapsible-content-collapsed",b).attr("aria-hidden",b).trigger("updatelayout"),this.options.collapsed=b,this._trigger(b?"collapse":"expand")},expand:function(){this._handleExpandCollapse(!1)},collapse:function(){this._handleExpandCollapse(!0)},_destroy:function(){var a=this._ui,b=this.options;b.enhanced||(a.placeholder?(a.originalHeading.insertBefore(a.placeholder),a.placeholder.remove(),a.heading.remove()):(a.status.remove(),a.heading.removeClass("ui-collapsible-heading ui-collapsible-heading-collapsed").children().contents().unwrap()),a.anchor.contents().unwrap(),a.content.contents().unwrap(),this.element.removeClass("ui-collapsible ui-collapsible-collapsed ui-collapsible-themed-content ui-collapsible-inset ui-corner-all"))}}),a.mobile.collapsible.defaults={expandCueText:" click to expand contents",collapseCueText:" click to collapse contents",collapsedIcon:"plus",contentTheme:"inherit",expandedIcon:"minus",iconpos:"left",inset:!0,corners:!0,theme:"inherit",mini:!1}}(a),function(a){a.mobile.behaviors.addFirstLastClasses={_getVisibles:function(a,b){var c;return b?c=a.not(".ui-screen-hidden"):(c=a.filter(":visible"),0===c.length&&(c=a.not(".ui-screen-hidden"))),c},_addFirstLastClasses:function(a,b,c){a.removeClass("ui-first-child ui-last-child"),b.eq(0).addClass("ui-first-child").end().last().addClass("ui-last-child"),c||this.element.trigger("updatelayout")},_removeFirstLastClasses:function(a){a.removeClass("ui-first-child ui-last-child")}}}(a),function(a,b){var c=":mobile-collapsible, "+a.mobile.collapsible.initSelector;a.widget("mobile.collapsibleset",a.extend({initSelector:":jqmData(role='collapsible-set'),:jqmData(role='collapsibleset')",options:a.extend({enhanced:!1},a.mobile.collapsible.defaults),_handleCollapsibleExpand:function(b){var c=a(b.target).closest(".ui-collapsible");c.parent().is(":mobile-collapsibleset, :jqmData(role='collapsible-set')")&&c.siblings(".ui-collapsible:not(.ui-collapsible-collapsed)").collapsible("collapse")},_create:function(){var b=this.element,c=this.options;a.extend(this,{_classes:""}),c.enhanced||(b.addClass("ui-collapsible-set "+this._themeClassFromOption("ui-group-theme-",c.theme)+" "+(c.corners&&c.inset?"ui-corner-all ":"")),this.element.find(a.mobile.collapsible.initSelector).collapsible()),this._on(b,{collapsibleexpand:"_handleCollapsibleExpand"})},_themeClassFromOption:function(a,b){return b?"none"===b?"":a+b:""},_init:function(){this._refresh(!0),this.element.children(c).filter(":jqmData(collapsed='false')").collapsible("expand")},_setOptions:function(a){var c,d,e=this.element,f=this._themeClassFromOption("ui-group-theme-",a.theme);return f&&e.removeClass(this._themeClassFromOption("ui-group-theme-",this.options.theme)).addClass(f),a.inset!==b&&(d=!(!a.inset||!a.corners&&!this.options.corners)),a.corners!==b&&(d=!(!a.corners||!a.inset&&!this.options.inset)),d!==b&&e.toggleClass("ui-corner-all",d),c=this._super(a),this.element.children(":mobile-collapsible").collapsible("refresh"),c},_destroy:function(){var a=this.element;this._removeFirstLastClasses(a.children(c)),a.removeClass("ui-collapsible-set ui-corner-all "+this._themeClassFromOption("ui-group-theme-",this.options.theme)).children(":mobile-collapsible").collapsible("destroy")},_refresh:function(b){var d=this.element.children(c);this.element.find(a.mobile.collapsible.initSelector).not(".ui-collapsible").collapsible(),this._addFirstLastClasses(d,this._getVisibles(d,b),b)},refresh:function(){this._refresh(!1)}},a.mobile.behaviors.addFirstLastClasses))}(a),function(a){a.fn.fieldcontain=function(){return this.addClass("ui-field-contain")}}(a),function(a){a.fn.grid=function(b){return this.each(function(){var c,d,e=a(this),f=a.extend({grid:null},b),g=e.children(),h={solo:1,a:2,b:3,c:4,d:5},i=f.grid;if(!i)if(g.length<=5)for(d in h)h[d]===g.length&&(i=d);else i="a",e.addClass("ui-grid-duo");c=h[i],e.addClass("ui-grid-"+i),g.filter(":nth-child("+c+"n+1)").addClass("ui-block-a"),c>1&&g.filter(":nth-child("+c+"n+2)").addClass("ui-block-b"),c>2&&g.filter(":nth-child("+c+"n+3)").addClass("ui-block-c"),c>3&&g.filter(":nth-child("+c+"n+4)").addClass("ui-block-d"),c>4&&g.filter(":nth-child("+c+"n+5)").addClass("ui-block-e")})}}(a),function(a,b){a.widget("mobile.navbar",{options:{iconpos:"top",grid:null},_create:function(){var d=this.element,e=d.find("a"),f=e.filter(":jqmData(icon)").length?this.options.iconpos:b;d.addClass("ui-navbar").attr("role","navigation").find("ul").jqmEnhanceable().grid({grid:this.options.grid}),e.each(function(){var b=a.mobile.getAttribute(this,"icon"),c=a.mobile.getAttribute(this,"theme"),d="ui-btn";c&&(d+=" ui-btn-"+c),b&&(d+=" ui-icon-"+b+" ui-btn-icon-"+f),a(this).addClass(d)}),d.delegate("a","vclick",function(){var b=a(this);b.hasClass("ui-state-disabled")||b.hasClass("ui-disabled")||b.hasClass(a.mobile.activeBtnClass)||(e.removeClass(a.mobile.activeBtnClass),b.addClass(a.mobile.activeBtnClass),a(c).one("pagehide",function(){b.removeClass(a.mobile.activeBtnClass)}))}),d.closest(".ui-page").bind("pagebeforeshow",function(){e.filter(".ui-state-persist").addClass(a.mobile.activeBtnClass)})}})}(a),function(a){var b=a.mobile.getAttribute;a.widget("mobile.listview",a.extend({options:{theme:null,countTheme:null,dividerTheme:null,icon:"carat-r",splitIcon:"carat-r",splitTheme:null,corners:!0,shadow:!0,inset:!1},_create:function(){var a=this,b="";b+=a.options.inset?" ui-listview-inset":"",a.options.inset&&(b+=a.options.corners?" ui-corner-all":"",b+=a.options.shadow?" ui-shadow":""),a.element.addClass(" ui-listview"+b),a.refresh(!0)},_findFirstElementByTagName:function(a,b,c,d){var e={};for(e[c]=e[d]=!0;a;){if(e[a.nodeName])return a;a=a[b]}return null},_addThumbClasses:function(b){var c,d,e=b.length;for(c=0;e>c;c++)d=a(this._findFirstElementByTagName(b[c].firstChild,"nextSibling","img","IMG")),d.length&&a(this._findFirstElementByTagName(d[0].parentNode,"parentNode","li","LI")).addClass(d.hasClass("ui-li-icon")?"ui-li-has-icon":"ui-li-has-thumb")},_getChildrenByTagName:function(b,c,d){var e=[],f={};for(f[c]=f[d]=!0,b=b.firstChild;b;)f[b.nodeName]&&e.push(b),b=b.nextSibling;return a(e)},_beforeListviewRefresh:a.noop,_afterListviewRefresh:a.noop,refresh:function(c){var d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x=this.options,y=this.element,z=!!a.nodeName(y[0],"ol"),A=y.attr("start"),B={},C=y.find(".ui-li-count"),D=b(y[0],"counttheme")||this.options.countTheme,E=D?"ui-body-"+D:"ui-body-inherit";for(x.theme&&y.addClass("ui-group-theme-"+x.theme),z&&(A||0===A)&&(n=parseInt(A,10)-1,y.css("counter-reset","listnumbering "+n)),this._beforeListviewRefresh(),w=this._getChildrenByTagName(y[0],"li","LI"),e=0,f=w.length;f>e;e++)g=w.eq(e),h="",(c||g[0].className.search(/\bui-li-static\b|\bui-li-divider\b/)<0)&&(l=this._getChildrenByTagName(g[0],"a","A"),m="list-divider"===b(g[0],"role"),p=g.attr("value"),i=b(g[0],"theme"),l.length&&l[0].className.search(/\bui-btn\b/)<0&&!m?(j=b(g[0],"icon"),k=j===!1?!1:j||x.icon,l.removeClass("ui-link"),d="ui-btn",i&&(d+=" ui-btn-"+i),l.length>1?(h="ui-li-has-alt",q=l.last(),r=b(q[0],"theme")||x.splitTheme||b(g[0],"theme",!0),s=r?" ui-btn-"+r:"",t=b(q[0],"icon")||b(g[0],"icon")||x.splitIcon,u="ui-btn ui-btn-icon-notext ui-icon-"+t+s,q.attr("title",a.trim(q.getEncodedText())).addClass(u).empty()):k&&(d+=" ui-btn-icon-right ui-icon-"+k),l.first().addClass(d)):m?(v=b(g[0],"theme")||x.dividerTheme||x.theme,h="ui-li-divider ui-bar-"+(v?v:"inherit"),g.attr("role","heading")):l.length<=0&&(h="ui-li-static ui-body-"+(i?i:"inherit")),z&&p&&(o=parseInt(p,10)-1,g.css("counter-reset","listnumbering "+o))),B[h]||(B[h]=[]),B[h].push(g[0]);for(h in B)a(B[h]).addClass(h);C.each(function(){a(this).closest("li").addClass("ui-li-has-count")}),E&&C.addClass(E),this._addThumbClasses(w),this._addThumbClasses(w.find(".ui-btn")),this._afterListviewRefresh(),this._addFirstLastClasses(w,this._getVisibles(w,c),c)}},a.mobile.behaviors.addFirstLastClasses))}(a),function(a){function b(b){var c=a.trim(b.text())||null;return c?c=c.slice(0,1).toUpperCase():null}a.widget("mobile.listview",a.mobile.listview,{options:{autodividers:!1,autodividersSelector:b},_beforeListviewRefresh:function(){this.options.autodividers&&(this._replaceDividers(),this._superApply(arguments))},_replaceDividers:function(){var b,d,e,f,g,h=null,i=this.element;for(i.children("li:jqmData(role='list-divider')").remove(),d=i.children("li"),b=0;b<d.length;b++)e=d[b],f=this.options.autodividersSelector(a(e)),f&&h!==f&&(g=c.createElement("li"),g.appendChild(c.createTextNode(f)),g.setAttribute("data-"+a.mobile.ns+"role","list-divider"),e.parentNode.insertBefore(g,e)),h=f}})}(a),function(a){var b=/(^|\s)ui-li-divider($|\s)/,c=/(^|\s)ui-screen-hidden($|\s)/;a.widget("mobile.listview",a.mobile.listview,{options:{hideDividers:!1},_afterListviewRefresh:function(){var a,d,e,f=!0;if(this._superApply(arguments),this.options.hideDividers)for(a=this._getChildrenByTagName(this.element[0],"li","LI"),d=a.length-1;d>-1;d--)e=a[d],e.className.match(b)?(f&&(e.className=e.className+" ui-screen-hidden"),f=!0):e.className.match(c)||(f=!1)}})}(a),function(a){a.mobile.nojs=function(b){a(":jqmData(role='nojs')",b).addClass("ui-nojs")}}(a),function(a){a.mobile.behaviors.formReset={_handleFormReset:function(){this._on(this.element.closest("form"),{reset:function(){this._delay("_reset")}})}}}(a),function(a,b){var c=a.mobile.path.hashToSelector;a.widget("mobile.checkboxradio",a.extend({initSelector:"input:not( :jqmData(role='flipswitch' ) )[type='checkbox'],input[type='radio']:not( :jqmData(role='flipswitch' ))",options:{theme:"inherit",mini:!1,wrapperClass:null,enhanced:!1,iconpos:"left"},_create:function(){var b=this.element,d=this.options,e=function(a,b){return a.jqmData(b)||a.closest("form, fieldset").jqmData(b)},f=b.closest("label"),g=f.length?f:b.closest("form, fieldset, :jqmData(role='page'), :jqmData(role='dialog')").find("label").filter("[for='"+c(b[0].id)+"']").first(),h=b[0].type,i="ui-"+h+"-on",j="ui-"+h+"-off";("checkbox"===h||"radio"===h)&&(this.element[0].disabled&&(this.options.disabled=!0),d.iconpos=e(b,"iconpos")||g.attr("data-"+a.mobile.ns+"iconpos")||d.iconpos,d.mini=e(b,"mini")||d.mini,a.extend(this,{input:b,label:g,parentLabel:f,inputtype:h,checkedClass:i,uncheckedClass:j}),this.options.enhanced||this._enhance(),this._on(g,{vmouseover:"_handleLabelVMouseOver",vclick:"_handleLabelVClick"}),this._on(b,{vmousedown:"_cacheVals",vclick:"_handleInputVClick",focus:"_handleInputFocus",blur:"_handleInputBlur"}),this._handleFormReset(),this.refresh())},_enhance:function(){this.label.addClass("ui-btn ui-corner-all"),this.parentLabel.length>0?this.input.add(this.label).wrapAll(this._wrapper()):(this.element.wrap(this._wrapper()),this.element.parent().prepend(this.label)),this._setOptions({theme:this.options.theme,iconpos:this.options.iconpos,mini:this.options.mini})},_wrapper:function(){return a("<div class='"+(this.options.wrapperClass?this.options.wrapperClass:"")+" ui-"+this.inputtype+(this.options.disabled?" ui-state-disabled":"")+"' ></div>")},_handleInputFocus:function(){this.label.addClass(a.mobile.focusClass)},_handleInputBlur:function(){this.label.removeClass(a.mobile.focusClass)},_handleInputVClick:function(){this.element.prop("checked",this.element.is(":checked")),this._getInputSet().not(this.element).prop("checked",!1),this._updateAll()},_handleLabelVMouseOver:function(a){this.label.parent().hasClass("ui-state-disabled")&&a.stopPropagation()},_handleLabelVClick:function(a){var b=this.element;return b.is(":disabled")?void a.preventDefault():(this._cacheVals(),b.prop("checked","radio"===this.inputtype&&!0||!b.prop("checked")),b.triggerHandler("click"),this._getInputSet().not(b).prop("checked",!1),this._updateAll(),!1)},_cacheVals:function(){this._getInputSet().each(function(){a(this).attr("data-"+a.mobile.ns+"cacheVal",this.checked)})},_getInputSet:function(){var b,d,e=this.element[0],f=e.name,g=e.form,h=this.element.parents().last().get(0),i=this.element;return f&&"radio"===this.inputtype&&h&&(b="input[type='radio'][name='"+c(f)+"']",g?(d=g.id,d&&(i=a(b+"[form='"+c(d)+"']",h)),i=a(g).find(b).filter(function(){return this.form===g}).add(i)):i=a(b,h).filter(function(){return!this.form})),i},_updateAll:function(){var b=this;this._getInputSet().each(function(){var c=a(this);(this.checked||"checkbox"===b.inputtype)&&c.trigger("change")}).checkboxradio("refresh")},_reset:function(){this.refresh()},_hasIcon:function(){var b,c,d=a.mobile.controlgroup;return d&&(b=this.element.closest(":mobile-controlgroup,"+d.prototype.initSelector),b.length>0)?(c=a.data(b[0],"mobile-controlgroup"),"horizontal"!==(c?c.options.type:b.attr("data-"+a.mobile.ns+"type"))):!0},refresh:function(){var b=this._hasIcon(),c=this.element[0].checked,d=a.mobile.activeBtnClass,e="ui-btn-icon-"+this.options.iconpos,f=[],g=[];b?(g.push(d),f.push(e)):(g.push(e),(c?f:g).push(d)),c?(f.push(this.checkedClass),g.push(this.uncheckedClass)):(f.push(this.uncheckedClass),g.push(this.checkedClass)),this.label.addClass(f.join(" ")).removeClass(g.join(" "))},widget:function(){return this.label.parent()},_setOptions:function(a){var c=this.label,d=this.options,e=this.widget(),f=this._hasIcon();a.disabled!==b&&(this.input.prop("disabled",!!a.disabled),e.toggleClass("ui-state-disabled",!!a.disabled)),a.mini!==b&&e.toggleClass("ui-mini",!!a.mini),a.theme!==b&&c.removeClass("ui-btn-"+d.theme).addClass("ui-btn-"+a.theme),a.wrapperClass!==b&&e.removeClass(d.wrapperClass).addClass(a.wrapperClass),a.iconpos!==b&&f?c.removeClass("ui-btn-icon-"+d.iconpos).addClass("ui-btn-icon-"+a.iconpos):f||c.removeClass("ui-btn-icon-"+d.iconpos),this._super(a)}},a.mobile.behaviors.formReset))}(a),function(a,b){a.widget("mobile.button",{initSelector:"input[type='button'], input[type='submit'], input[type='reset']",options:{theme:null,icon:null,iconpos:"left",iconshadow:!1,corners:!0,shadow:!0,inline:null,mini:null,wrapperClass:null,enhanced:!1},_create:function(){this.element.is(":disabled")&&(this.options.disabled=!0),this.options.enhanced||this._enhance(),a.extend(this,{wrapper:this.element.parent()}),this._on({focus:function(){this.widget().addClass(a.mobile.focusClass)},blur:function(){this.widget().removeClass(a.mobile.focusClass)}}),this.refresh(!0)},_enhance:function(){this.element.wrap(this._button())},_button:function(){var b=this.options,c=this._getIconClasses(this.options);return a("<div class='ui-btn ui-input-btn"+(b.wrapperClass?" "+b.wrapperClass:"")+(b.theme?" ui-btn-"+b.theme:"")+(b.corners?" ui-corner-all":"")+(b.shadow?" ui-shadow":"")+(b.inline?" ui-btn-inline":"")+(b.mini?" ui-mini":"")+(b.disabled?" ui-state-disabled":"")+(c?" "+c:"")+"' >"+this.element.val()+"</div>")},widget:function(){return this.wrapper},_destroy:function(){this.element.insertBefore(this.button),this.button.remove()},_getIconClasses:function(a){return a.icon?"ui-icon-"+a.icon+(a.iconshadow?" ui-shadow-icon":"")+" ui-btn-icon-"+a.iconpos:""},_setOptions:function(c){var d=this.widget();c.theme!==b&&d.removeClass(this.options.theme).addClass("ui-btn-"+c.theme),c.corners!==b&&d.toggleClass("ui-corner-all",c.corners),c.shadow!==b&&d.toggleClass("ui-shadow",c.shadow),c.inline!==b&&d.toggleClass("ui-btn-inline",c.inline),c.mini!==b&&d.toggleClass("ui-mini",c.mini),c.disabled!==b&&(this.element.prop("disabled",c.disabled),d.toggleClass("ui-state-disabled",c.disabled)),(c.icon!==b||c.iconshadow!==b||c.iconpos!==b)&&d.removeClass(this._getIconClasses(this.options)).addClass(this._getIconClasses(a.extend({},this.options,c))),this._super(c)},refresh:function(b){var c,d=this.element.prop("disabled");this.options.icon&&"notext"===this.options.iconpos&&this.element.attr("title")&&this.element.attr("title",this.element.val()),b||(c=this.element.detach(),a(this.wrapper).text(this.element.val()).append(c)),this.options.disabled!==d&&this._setOptions({disabled:d})}})}(a),function(a){var b=a("meta[name=viewport]"),c=b.attr("content"),d=c+",maximum-scale=1, user-scalable=no",e=c+",maximum-scale=10, user-scalable=yes",f=/(user-scalable[\s]*=[\s]*no)|(maximum-scale[\s]*=[\s]*1)[$,\s]/.test(c);a.mobile.zoom=a.extend({},{enabled:!f,locked:!1,disable:function(c){f||a.mobile.zoom.locked||(b.attr("content",d),a.mobile.zoom.enabled=!1,a.mobile.zoom.locked=c||!1)},enable:function(c){f||a.mobile.zoom.locked&&c!==!0||(b.attr("content",e),a.mobile.zoom.enabled=!0,a.mobile.zoom.locked=!1)},restore:function(){f||(b.attr("content",c),a.mobile.zoom.enabled=!0)}})}(a),function(a,b){a.widget("mobile.textinput",{initSelector:"input[type='text'],input[type='search'],:jqmData(type='search'),input[type='number'],:jqmData(type='number'),input[type='password'],input[type='email'],input[type='url'],input[type='tel'],textarea,input[type='time'],input[type='date'],input[type='month'],input[type='week'],input[type='datetime'],input[type='datetime-local'],input[type='color'],input:not([type]),input[type='file']",options:{theme:null,corners:!0,mini:!1,preventFocusZoom:/iPhone|iPad|iPod/.test(navigator.platform)&&navigator.userAgent.indexOf("AppleWebKit")>-1,wrapperClass:"",enhanced:!1},_create:function(){var b=this.options,c=this.element.is("[type='search'], :jqmData(type='search')"),d="TEXTAREA"===this.element[0].tagName,e=this.element.is("[data-"+(a.mobile.ns||"")+"type='range']"),f=(this.element.is("input")||this.element.is("[data-"+(a.mobile.ns||"")+"type='search']"))&&!e;this.element.prop("disabled")&&(b.disabled=!0),a.extend(this,{classes:this._classesFromOptions(),isSearch:c,isTextarea:d,isRange:e,inputNeedsWrap:f}),this._autoCorrect(),b.enhanced||this._enhance(),this._on({focus:"_handleFocus",blur:"_handleBlur"})},refresh:function(){this.setOptions({disabled:this.element.is(":disabled")})},_enhance:function(){var a=[];this.isTextarea&&a.push("ui-input-text"),(this.isTextarea||this.isRange)&&a.push("ui-shadow-inset"),this.inputNeedsWrap?this.element.wrap(this._wrap()):a=a.concat(this.classes),this.element.addClass(a.join(" "))},widget:function(){return this.inputNeedsWrap?this.element.parent():this.element},_classesFromOptions:function(){var a=this.options,b=[];return b.push("ui-body-"+(null===a.theme?"inherit":a.theme)),a.corners&&b.push("ui-corner-all"),a.mini&&b.push("ui-mini"),a.disabled&&b.push("ui-state-disabled"),a.wrapperClass&&b.push(a.wrapperClass),b},_wrap:function(){return a("<div class='"+(this.isSearch?"ui-input-search ":"ui-input-text ")+this.classes.join(" ")+" ui-shadow-inset'></div>")},_autoCorrect:function(){"undefined"==typeof this.element[0].autocorrect||a.support.touchOverflow||(this.element[0].setAttribute("autocorrect","off"),this.element[0].setAttribute("autocomplete","off"))},_handleBlur:function(){this.widget().removeClass(a.mobile.focusClass),this.options.preventFocusZoom&&a.mobile.zoom.enable(!0)},_handleFocus:function(){this.options.preventFocusZoom&&a.mobile.zoom.disable(!0),this.widget().addClass(a.mobile.focusClass)},_setOptions:function(a){var c=this.widget();this._super(a),(a.disabled!==b||a.mini!==b||a.corners!==b||a.theme!==b||a.wrapperClass!==b)&&(c.removeClass(this.classes.join(" ")),this.classes=this._classesFromOptions(),c.addClass(this.classes.join(" "))),a.disabled!==b&&this.element.prop("disabled",!!a.disabled)},_destroy:function(){this.options.enhanced||(this.inputNeedsWrap&&this.element.unwrap(),this.element.removeClass("ui-input-text "+this.classes.join(" ")))}})}(a),function(a,d){a.widget("mobile.slider",a.extend({initSelector:"input[type='range'], :jqmData(type='range'), :jqmData(role='slider')",widgetEventPrefix:"slide",options:{theme:null,trackTheme:null,corners:!0,mini:!1,highlight:!1},_create:function(){var e,f,g,h,i,j,k,l,m,n,o=this,p=this.element,q=this.options.trackTheme||a.mobile.getAttribute(p[0],"theme"),r=q?" ui-bar-"+q:" ui-bar-inherit",s=this.options.corners||p.jqmData("corners")?" ui-corner-all":"",t=this.options.mini||p.jqmData("mini")?" ui-mini":"",u=p[0].nodeName.toLowerCase(),v="select"===u,w=p.parent().is(":jqmData(role='rangeslider')"),x=v?"ui-slider-switch":"",y=p.attr("id"),z=a("[for='"+y+"']"),A=z.attr("id")||y+"-label",B=v?0:parseFloat(p.attr("min")),C=v?p.find("option").length-1:parseFloat(p.attr("max")),D=b.parseFloat(p.attr("step")||1),E=c.createElement("a"),F=a(E),G=c.createElement("div"),H=a(G),I=this.options.highlight&&!v?function(){var b=c.createElement("div");
return b.className="ui-slider-bg "+a.mobile.activeBtnClass,a(b).prependTo(H)}():!1;if(z.attr("id",A),this.isToggleSwitch=v,E.setAttribute("href","#"),G.setAttribute("role","application"),G.className=[this.isToggleSwitch?"ui-slider ui-slider-track ui-shadow-inset ":"ui-slider-track ui-shadow-inset ",x,r,s,t].join(""),E.className="ui-slider-handle",G.appendChild(E),F.attr({role:"slider","aria-valuemin":B,"aria-valuemax":C,"aria-valuenow":this._value(),"aria-valuetext":this._value(),title:this._value(),"aria-labelledby":A}),a.extend(this,{slider:H,handle:F,control:p,type:u,step:D,max:C,min:B,valuebg:I,isRangeslider:w,dragging:!1,beforeStart:null,userModified:!1,mouseMoved:!1}),v){for(k=p.attr("tabindex"),k&&F.attr("tabindex",k),p.attr("tabindex","-1").focus(function(){a(this).blur(),F.focus()}),f=c.createElement("div"),f.className="ui-slider-inneroffset",g=0,h=G.childNodes.length;h>g;g++)f.appendChild(G.childNodes[g]);for(G.appendChild(f),F.addClass("ui-slider-handle-snapping"),e=p.find("option"),i=0,j=e.length;j>i;i++)l=i?"a":"b",m=i?" "+a.mobile.activeBtnClass:"",n=c.createElement("span"),n.className=["ui-slider-label ui-slider-label-",l,m].join(""),n.setAttribute("role","img"),n.appendChild(c.createTextNode(e[i].innerHTML)),a(n).prependTo(H);o._labels=a(".ui-slider-label",H)}p.addClass(v?"ui-slider-switch":"ui-slider-input"),this._on(p,{change:"_controlChange",keyup:"_controlKeyup",blur:"_controlBlur",vmouseup:"_controlVMouseUp"}),H.bind("vmousedown",a.proxy(this._sliderVMouseDown,this)).bind("vclick",!1),this._on(c,{vmousemove:"_preventDocumentDrag"}),this._on(H.add(c),{vmouseup:"_sliderVMouseUp"}),H.insertAfter(p),v||w||(f=this.options.mini?"<div class='ui-slider ui-mini'>":"<div class='ui-slider'>",p.add(H).wrapAll(f)),this._on(this.handle,{vmousedown:"_handleVMouseDown",keydown:"_handleKeydown",keyup:"_handleKeyup"}),this.handle.bind("vclick",!1),this._handleFormReset(),this.refresh(d,d,!0)},_setOptions:function(a){a.theme!==d&&this._setTheme(a.theme),a.trackTheme!==d&&this._setTrackTheme(a.trackTheme),a.corners!==d&&this._setCorners(a.corners),a.mini!==d&&this._setMini(a.mini),a.highlight!==d&&this._setHighlight(a.highlight),a.disabled!==d&&this._setDisabled(a.disabled),this._super(a)},_controlChange:function(a){return this._trigger("controlchange",a)===!1?!1:void(this.mouseMoved||this.refresh(this._value(),!0))},_controlKeyup:function(){this.refresh(this._value(),!0,!0)},_controlBlur:function(){this.refresh(this._value(),!0)},_controlVMouseUp:function(){this._checkedRefresh()},_handleVMouseDown:function(){this.handle.focus()},_handleKeydown:function(b){var c=this._value();if(!this.options.disabled){switch(b.keyCode){case a.mobile.keyCode.HOME:case a.mobile.keyCode.END:case a.mobile.keyCode.PAGE_UP:case a.mobile.keyCode.PAGE_DOWN:case a.mobile.keyCode.UP:case a.mobile.keyCode.RIGHT:case a.mobile.keyCode.DOWN:case a.mobile.keyCode.LEFT:b.preventDefault(),this._keySliding||(this._keySliding=!0,this.handle.addClass("ui-state-active"))}switch(b.keyCode){case a.mobile.keyCode.HOME:this.refresh(this.min);break;case a.mobile.keyCode.END:this.refresh(this.max);break;case a.mobile.keyCode.PAGE_UP:case a.mobile.keyCode.UP:case a.mobile.keyCode.RIGHT:this.refresh(c+this.step);break;case a.mobile.keyCode.PAGE_DOWN:case a.mobile.keyCode.DOWN:case a.mobile.keyCode.LEFT:this.refresh(c-this.step)}}},_handleKeyup:function(){this._keySliding&&(this._keySliding=!1,this.handle.removeClass("ui-state-active"))},_sliderVMouseDown:function(a){return this.options.disabled||1!==a.which&&0!==a.which&&a.which!==d?!1:this._trigger("beforestart",a)===!1?!1:(this.dragging=!0,this.userModified=!1,this.mouseMoved=!1,this.isToggleSwitch&&(this.beforeStart=this.element[0].selectedIndex),this.refresh(a),this._trigger("start"),!1)},_sliderVMouseUp:function(){return this.dragging?(this.dragging=!1,this.isToggleSwitch&&(this.handle.addClass("ui-slider-handle-snapping"),this.refresh(this.mouseMoved?this.userModified?0===this.beforeStart?1:0:this.beforeStart:0===this.beforeStart?1:0)),this.mouseMoved=!1,this._trigger("stop"),!1):void 0},_preventDocumentDrag:function(a){return this._trigger("drag",a)===!1?!1:this.dragging&&!this.options.disabled?(this.mouseMoved=!0,this.isToggleSwitch&&this.handle.removeClass("ui-slider-handle-snapping"),this.refresh(a),this.userModified=this.beforeStart!==this.element[0].selectedIndex,!1):void 0},_checkedRefresh:function(){this.value!==this._value()&&this.refresh(this._value())},_value:function(){return this.isToggleSwitch?this.element[0].selectedIndex:parseFloat(this.element.val())},_reset:function(){this.refresh(d,!1,!0)},refresh:function(b,d,e){var f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z=this,A=a.mobile.getAttribute(this.element[0],"theme"),B=this.options.theme||A,C=B?" ui-btn-"+B:"",D=this.options.trackTheme||A,E=D?" ui-bar-"+D:" ui-bar-inherit",F=this.options.corners?" ui-corner-all":"",G=this.options.mini?" ui-mini":"";if(z.slider[0].className=[this.isToggleSwitch?"ui-slider ui-slider-switch ui-slider-track ui-shadow-inset":"ui-slider-track ui-shadow-inset",E,F,G].join(""),(this.options.disabled||this.element.prop("disabled"))&&this.disable(),this.value=this._value(),this.options.highlight&&!this.isToggleSwitch&&0===this.slider.find(".ui-slider-bg").length&&(this.valuebg=function(){var b=c.createElement("div");return b.className="ui-slider-bg "+a.mobile.activeBtnClass,a(b).prependTo(z.slider)}()),this.handle.addClass("ui-btn"+C+" ui-shadow"),l=this.element,m=!this.isToggleSwitch,n=m?[]:l.find("option"),o=m?parseFloat(l.attr("min")):0,p=m?parseFloat(l.attr("max")):n.length-1,q=m&&parseFloat(l.attr("step"))>0?parseFloat(l.attr("step")):1,"object"==typeof b){if(h=b,i=8,f=this.slider.offset().left,g=this.slider.width(),j=g/((p-o)/q),!this.dragging||h.pageX<f-i||h.pageX>f+g+i)return;k=j>1?(h.pageX-f)/g*100:Math.round((h.pageX-f)/g*100)}else null==b&&(b=m?parseFloat(l.val()||0):l[0].selectedIndex),k=(parseFloat(b)-o)/(p-o)*100;if(!isNaN(k)&&(r=k/100*(p-o)+o,s=(r-o)%q,t=r-s,2*Math.abs(s)>=q&&(t+=s>0?q:-q),u=100/((p-o)/q),r=parseFloat(t.toFixed(5)),"undefined"==typeof j&&(j=g/((p-o)/q)),j>1&&m&&(k=(r-o)*u*(1/q)),0>k&&(k=0),k>100&&(k=100),o>r&&(r=o),r>p&&(r=p),this.handle.css("left",k+"%"),this.handle[0].setAttribute("aria-valuenow",m?r:n.eq(r).attr("value")),this.handle[0].setAttribute("aria-valuetext",m?r:n.eq(r).getEncodedText()),this.handle[0].setAttribute("title",m?r:n.eq(r).getEncodedText()),this.valuebg&&this.valuebg.css("width",k+"%"),this._labels&&(v=this.handle.width()/this.slider.width()*100,w=k&&v+(100-v)*k/100,x=100===k?0:Math.min(v+100-w,100),this._labels.each(function(){var b=a(this).hasClass("ui-slider-label-a");a(this).width((b?w:x)+"%")})),!e)){if(y=!1,m?(y=l.val()!==r,l.val(r)):(y=l[0].selectedIndex!==r,l[0].selectedIndex=r),this._trigger("beforechange",b)===!1)return!1;!d&&y&&l.trigger("change")}},_setHighlight:function(a){a=!!a,a?(this.options.highlight=!!a,this.refresh()):this.valuebg&&(this.valuebg.remove(),this.valuebg=!1)},_setTheme:function(a){this.handle.removeClass("ui-btn-"+this.options.theme).addClass("ui-btn-"+a);var b=this.options.theme?this.options.theme:"inherit",c=a?a:"inherit";this.control.removeClass("ui-body-"+b).addClass("ui-body-"+c)},_setTrackTheme:function(a){var b=this.options.trackTheme?this.options.trackTheme:"inherit",c=a?a:"inherit";this.slider.removeClass("ui-body-"+b).addClass("ui-body-"+c)},_setMini:function(a){a=!!a,this.isToggleSwitch||this.isRangeslider||(this.slider.parent().toggleClass("ui-mini",a),this.element.toggleClass("ui-mini",a)),this.slider.toggleClass("ui-mini",a)},_setCorners:function(a){this.slider.toggleClass("ui-corner-all",a),this.isToggleSwitch||this.control.toggleClass("ui-corner-all",a)},_setDisabled:function(a){a=!!a,this.element.prop("disabled",a),this.slider.toggleClass("ui-state-disabled",a).attr("aria-disabled",a)}},a.mobile.behaviors.formReset))}(a),function(a){function b(){return c||(c=a("<div></div>",{"class":"ui-slider-popup ui-shadow ui-corner-all"})),c.clone()}var c;a.widget("mobile.slider",a.mobile.slider,{options:{popupEnabled:!1,showValue:!1},_create:function(){this._super(),a.extend(this,{_currentValue:null,_popup:null,_popupVisible:!1}),this._setOption("popupEnabled",this.options.popupEnabled),this._on(this.handle,{vmousedown:"_showPopup"}),this._on(this.slider.add(this.document),{vmouseup:"_hidePopup"}),this._refresh()},_positionPopup:function(){var a=this.handle.offset();this._popup.offset({left:a.left+(this.handle.width()-this._popup.width())/2,top:a.top-this._popup.outerHeight()-5})},_setOption:function(a,c){this._super(a,c),"showValue"===a?this.handle.html(c&&!this.options.mini?this._value():""):"popupEnabled"===a&&c&&!this._popup&&(this._popup=b().addClass("ui-body-"+(this.options.theme||"a")).hide().insertBefore(this.element))},refresh:function(){this._super.apply(this,arguments),this._refresh()},_refresh:function(){var a,b=this.options;b.popupEnabled&&this.handle.removeAttr("title"),a=this._value(),a!==this._currentValue&&(this._currentValue=a,b.popupEnabled&&this._popup?(this._positionPopup(),this._popup.html(a)):b.showValue&&!this.options.mini&&this.handle.html(a))},_showPopup:function(){this.options.popupEnabled&&!this._popupVisible&&(this.handle.html(""),this._popup.show(),this._positionPopup(),this._popupVisible=!0)},_hidePopup:function(){var a=this.options;a.popupEnabled&&this._popupVisible&&(a.showValue&&!a.mini&&this.handle.html(this._value()),this._popup.hide(),this._popupVisible=!1)}})}(a),function(a,b){a.widget("mobile.flipswitch",a.extend({options:{onText:"On",offText:"Off",theme:null,enhanced:!1,wrapperClass:null,corners:!0,mini:!1},_create:function(){this.options.enhanced?a.extend(this,{flipswitch:this.element.parent(),on:this.element.find(".ui-flipswitch-on").eq(0),off:this.element.find(".ui-flipswitch-off").eq(0),type:this.element.get(0).tagName}):this._enhance(),this._handleFormReset(),this._originalTabIndex=this.element.attr("tabindex"),null!=this._originalTabIndex&&this.on.attr("tabindex",this._originalTabIndex),this.element.attr("tabindex","-1"),this._on({focus:"_handleInputFocus"}),this.element.is(":disabled")&&this._setOptions({disabled:!0}),this._on(this.flipswitch,{click:"_toggle",swipeleft:"_left",swiperight:"_right"}),this._on(this.on,{keydown:"_keydown"}),this._on({change:"refresh"})},_handleInputFocus:function(){this.on.focus()},widget:function(){return this.flipswitch},_left:function(){this.flipswitch.removeClass("ui-flipswitch-active"),"SELECT"===this.type?this.element.get(0).selectedIndex=0:this.element.prop("checked",!1),this.element.trigger("change")},_right:function(){this.flipswitch.addClass("ui-flipswitch-active"),"SELECT"===this.type?this.element.get(0).selectedIndex=1:this.element.prop("checked",!0),this.element.trigger("change")},_enhance:function(){var b=a("<div>"),c=this.options,d=this.element,e=c.theme?c.theme:"inherit",f=a("<a></a>",{href:"#"}),g=a("<span></span>"),h=d.get(0).tagName,i="INPUT"===h?c.onText:d.find("option").eq(1).text(),j="INPUT"===h?c.offText:d.find("option").eq(0).text();f.addClass("ui-flipswitch-on ui-btn ui-shadow ui-btn-inherit").text(i),g.addClass("ui-flipswitch-off").text(j),b.addClass("ui-flipswitch ui-shadow-inset ui-bar-"+e+" "+(c.wrapperClass?c.wrapperClass:"")+" "+(d.is(":checked")||d.find("option").eq(1).is(":selected")?"ui-flipswitch-active":"")+(d.is(":disabled")?" ui-state-disabled":"")+(c.corners?" ui-corner-all":"")+(c.mini?" ui-mini":"")).append(f,g),d.addClass("ui-flipswitch-input").after(b).appendTo(b),a.extend(this,{flipswitch:b,on:f,off:g,type:h})},_reset:function(){this.refresh()},refresh:function(){var a,b=this.flipswitch.hasClass("ui-flipswitch-active")?"_right":"_left";a="SELECT"===this.type?this.element.get(0).selectedIndex>0?"_right":"_left":this.element.prop("checked")?"_right":"_left",a!==b&&this[a]()},_toggle:function(){var a=this.flipswitch.hasClass("ui-flipswitch-active")?"_left":"_right";this[a]()},_keydown:function(b){b.which===a.mobile.keyCode.LEFT?this._left():b.which===a.mobile.keyCode.RIGHT?this._right():b.which===a.mobile.keyCode.SPACE&&(this._toggle(),b.preventDefault())},_setOptions:function(a){if(a.theme!==b){var c=a.theme?a.theme:"inherit",d=a.theme?a.theme:"inherit";this.widget().removeClass("ui-bar-"+c).addClass("ui-bar-"+d)}a.onText!==b&&this.on.text(a.onText),a.offText!==b&&this.off.text(a.offText),a.disabled!==b&&this.widget().toggleClass("ui-state-disabled",a.disabled),a.mini!==b&&this.widget().toggleClass("ui-mini",a.mini),a.corners!==b&&this.widget().toggleClass("ui-corner-all",a.corners),this._super(a)},_destroy:function(){this.options.enhanced||(null!=this._originalTabIndex?this.element.attr("tabindex",this._originalTabIndex):this.element.removeAttr("tabindex"),this.on.remove(),this.off.remove(),this.element.unwrap(),this.flipswitch.remove(),this.removeClass("ui-flipswitch-input"))}},a.mobile.behaviors.formReset))}(a),function(a,b){a.widget("mobile.rangeslider",a.extend({options:{theme:null,trackTheme:null,corners:!0,mini:!1,highlight:!0},_create:function(){var b=this.element,c=this.options.mini?"ui-rangeslider ui-mini":"ui-rangeslider",d=b.find("input").first(),e=b.find("input").last(),f=b.find("label").first(),g=a.data(d.get(0),"mobile-slider")||a.data(d.slider().get(0),"mobile-slider"),h=a.data(e.get(0),"mobile-slider")||a.data(e.slider().get(0),"mobile-slider"),i=g.slider,j=h.slider,k=g.handle,l=a("<div class='ui-rangeslider-sliders' />").appendTo(b);d.addClass("ui-rangeslider-first"),e.addClass("ui-rangeslider-last"),b.addClass(c),i.appendTo(l),j.appendTo(l),f.insertBefore(b),k.prependTo(j),a.extend(this,{_inputFirst:d,_inputLast:e,_sliderFirst:i,_sliderLast:j,_label:f,_targetVal:null,_sliderTarget:!1,_sliders:l,_proxy:!1}),this.refresh(),this._on(this.element.find("input.ui-slider-input"),{slidebeforestart:"_slidebeforestart",slidestop:"_slidestop",slidedrag:"_slidedrag",slidebeforechange:"_change",blur:"_change",keyup:"_change"}),this._on({mousedown:"_change"}),this._on(this.element.closest("form"),{reset:"_handleReset"}),this._on(k,{vmousedown:"_dragFirstHandle"})},_handleReset:function(){var a=this;setTimeout(function(){a._updateHighlight()},0)},_dragFirstHandle:function(b){return a.data(this._inputFirst.get(0),"mobile-slider").dragging=!0,a.data(this._inputFirst.get(0),"mobile-slider").refresh(b),!1},_slidedrag:function(b){var c=a(b.target).is(this._inputFirst),d=c?this._inputLast:this._inputFirst;return this._sliderTarget=!1,"first"===this._proxy&&c||"last"===this._proxy&&!c?(a.data(d.get(0),"mobile-slider").dragging=!0,a.data(d.get(0),"mobile-slider").refresh(b),!1):void 0},_slidestop:function(b){var c=a(b.target).is(this._inputFirst);this._proxy=!1,this.element.find("input").trigger("vmouseup"),this._sliderFirst.css("z-index",c?1:"")},_slidebeforestart:function(b){this._sliderTarget=!1,a(b.originalEvent.target).hasClass("ui-slider-track")&&(this._sliderTarget=!0,this._targetVal=a(b.target).val())},_setOptions:function(a){a.theme!==b&&this._setTheme(a.theme),a.trackTheme!==b&&this._setTrackTheme(a.trackTheme),a.mini!==b&&this._setMini(a.mini),a.highlight!==b&&this._setHighlight(a.highlight),this._super(a),this.refresh()},refresh:function(){var a=this.element,b=this.options;(this._inputFirst.is(":disabled")||this._inputLast.is(":disabled"))&&(this.options.disabled=!0),a.find("input").slider({theme:b.theme,trackTheme:b.trackTheme,disabled:b.disabled,corners:b.corners,mini:b.mini,highlight:b.highlight}).slider("refresh"),this._updateHighlight()},_change:function(b){if("keyup"===b.type)return this._updateHighlight(),!1;var c=this,d=parseFloat(this._inputFirst.val(),10),e=parseFloat(this._inputLast.val(),10),f=a(b.target).hasClass("ui-rangeslider-first"),g=f?this._inputFirst:this._inputLast,h=f?this._inputLast:this._inputFirst;if(this._inputFirst.val()>this._inputLast.val()&&"mousedown"===b.type&&!a(b.target).hasClass("ui-slider-handle"))g.blur();else if("mousedown"===b.type)return;return d>e&&!this._sliderTarget?(g.val(f?e:d).slider("refresh"),this._trigger("normalize")):d>e&&(g.val(this._targetVal).slider("refresh"),setTimeout(function(){h.val(f?d:e).slider("refresh"),a.data(h.get(0),"mobile-slider").handle.focus(),c._sliderFirst.css("z-index",f?"":1),c._trigger("normalize")},0),this._proxy=f?"first":"last"),d===e?(a.data(g.get(0),"mobile-slider").handle.css("z-index",1),a.data(h.get(0),"mobile-slider").handle.css("z-index",0)):(a.data(h.get(0),"mobile-slider").handle.css("z-index",""),a.data(g.get(0),"mobile-slider").handle.css("z-index","")),this._updateHighlight(),d>=e?!1:void 0},_updateHighlight:function(){var b=parseInt(a.data(this._inputFirst.get(0),"mobile-slider").handle.get(0).style.left,10),c=parseInt(a.data(this._inputLast.get(0),"mobile-slider").handle.get(0).style.left,10),d=c-b;this.element.find(".ui-slider-bg").css({"margin-left":b+"%",width:d+"%"})},_setTheme:function(a){this._inputFirst.slider("option","theme",a),this._inputLast.slider("option","theme",a)},_setTrackTheme:function(a){this._inputFirst.slider("option","trackTheme",a),this._inputLast.slider("option","trackTheme",a)},_setMini:function(a){this._inputFirst.slider("option","mini",a),this._inputLast.slider("option","mini",a),this.element.toggleClass("ui-mini",!!a)},_setHighlight:function(a){this._inputFirst.slider("option","highlight",a),this._inputLast.slider("option","highlight",a)},_destroy:function(){this._label.prependTo(this.element),this.element.removeClass("ui-rangeslider ui-mini"),this._inputFirst.after(this._sliderFirst),this._inputLast.after(this._sliderLast),this._sliders.remove(),this.element.find("input").removeClass("ui-rangeslider-first ui-rangeslider-last").slider("destroy")}},a.mobile.behaviors.formReset))}(a),function(a,b){a.widget("mobile.textinput",a.mobile.textinput,{options:{clearBtn:!1,clearBtnText:"Clear text"},_create:function(){this._super(),(this.options.clearBtn||this.isSearch)&&this._addClearBtn()},clearButton:function(){return a("<a href='#' class='ui-input-clear ui-btn ui-icon-delete ui-btn-icon-notext ui-corner-all' title='"+this.options.clearBtnText+"'>"+this.options.clearBtnText+"</a>")},_clearBtnClick:function(a){this.element.val("").focus().trigger("change"),this._clearBtn.addClass("ui-input-clear-hidden"),a.preventDefault()},_addClearBtn:function(){this.options.enhanced||this._enhanceClear(),a.extend(this,{_clearBtn:this.widget().find("a.ui-input-clear")}),this._bindClearEvents(),this._toggleClear()},_enhanceClear:function(){this.clearButton().appendTo(this.widget()),this.widget().addClass("ui-input-has-clear")},_bindClearEvents:function(){this._on(this._clearBtn,{click:"_clearBtnClick"}),this._on({keyup:"_toggleClear",change:"_toggleClear",input:"_toggleClear",focus:"_toggleClear",blur:"_toggleClear",cut:"_toggleClear",paste:"_toggleClear"})},_unbindClear:function(){this._off(this._clearBtn,"click"),this._off(this.element,"keyup change input focus blur cut paste")},_setOptions:function(a){this._super(a),a.clearBtn===b||this.element.is("textarea, :jqmData(type='range')")||(a.clearBtn?this._addClearBtn():this._destroyClear()),a.clearBtnText!==b&&this._clearBtn!==b&&this._clearBtn.text(a.clearBtnText).attr("title",a.clearBtnText)},_toggleClear:function(){this._delay("_toggleClearClass",0)},_toggleClearClass:function(){this._clearBtn.toggleClass("ui-input-clear-hidden",!this.element.val())},_destroyClear:function(){this.widget().removeClass("ui-input-has-clear"),this._unbindClear(),this._clearBtn.remove()},_destroy:function(){this._super(),this._destroyClear()}})}(a),function(a,b){a.widget("mobile.textinput",a.mobile.textinput,{options:{autogrow:!0,keyupTimeoutBuffer:100},_create:function(){this._super(),this.options.autogrow&&this.isTextarea&&this._autogrow()},_autogrow:function(){this.element.addClass("ui-textinput-autogrow"),this._on({keyup:"_timeout",change:"_timeout",input:"_timeout",paste:"_timeout"}),this._on(!0,this.document,{pageshow:"_handleShow",popupbeforeposition:"_handleShow",updatelayout:"_handleShow",panelopen:"_handleShow"})},_handleShow:function(b){a.contains(b.target,this.element[0])&&this.element.is(":visible")&&("popupbeforeposition"!==b.type&&this.element.addClass("ui-textinput-autogrow-resize").animationComplete(a.proxy(function(){this.element.removeClass("ui-textinput-autogrow-resize")},this),"transition"),this._timeout())},_unbindAutogrow:function(){this.element.removeClass("ui-textinput-autogrow"),this._off(this.element,"keyup change input paste"),this._off(this.document,"pageshow popupbeforeposition updatelayout panelopen")},keyupTimeout:null,_prepareHeightUpdate:function(a){this.keyupTimeout&&clearTimeout(this.keyupTimeout),a===b?this._updateHeight():this.keyupTimeout=this._delay("_updateHeight",a)},_timeout:function(){this._prepareHeightUpdate(this.options.keyupTimeoutBuffer)},_updateHeight:function(){var a,b,c,d,e,f,g,h,i,j=this.window.scrollTop();this.keyupTimeout=0,"onpage"in this.element[0]||this.element.css({height:0,"min-height":0,"max-height":0}),d=this.element[0].scrollHeight,e=this.element[0].clientHeight,f=parseFloat(this.element.css("border-top-width")),g=parseFloat(this.element.css("border-bottom-width")),h=f+g,i=d+h+15,0===e&&(a=parseFloat(this.element.css("padding-top")),b=parseFloat(this.element.css("padding-bottom")),c=a+b,i+=c),this.element.css({height:i,"min-height":"","max-height":""}),this.window.scrollTop(j)},refresh:function(){this.options.autogrow&&this.isTextarea&&this._updateHeight()},_setOptions:function(a){this._super(a),a.autogrow!==b&&this.isTextarea&&(a.autogrow?this._autogrow():this._unbindAutogrow())}})}(a),function(a){a.widget("mobile.selectmenu",a.extend({initSelector:"select:not( :jqmData(role='slider')):not( :jqmData(role='flipswitch') )",options:{theme:null,icon:"carat-d",iconpos:"right",inline:!1,corners:!0,shadow:!0,iconshadow:!1,overlayTheme:null,dividerTheme:null,hidePlaceholderMenuItems:!0,closeText:"Close",nativeMenu:!0,preventFocusZoom:/iPhone|iPad|iPod/.test(navigator.platform)&&navigator.userAgent.indexOf("AppleWebKit")>-1,mini:!1},_button:function(){return a("<div/>")},_setDisabled:function(a){return this.element.attr("disabled",a),this.button.attr("aria-disabled",a),this._setOption("disabled",a)},_focusButton:function(){var a=this;setTimeout(function(){a.button.focus()},40)},_selectOptions:function(){return this.select.find("option")},_preExtension:function(){var b=this.options.inline||this.element.jqmData("inline"),c=this.options.mini||this.element.jqmData("mini"),d="";~this.element[0].className.indexOf("ui-btn-left")&&(d=" ui-btn-left"),~this.element[0].className.indexOf("ui-btn-right")&&(d=" ui-btn-right"),b&&(d+=" ui-btn-inline"),c&&(d+=" ui-mini"),this.select=this.element.removeClass("ui-btn-left ui-btn-right").wrap("<div class='ui-select"+d+"'>"),this.selectId=this.select.attr("id")||"select-"+this.uuid,this.buttonId=this.selectId+"-button",this.label=a("label[for='"+this.selectId+"']"),this.isMultiple=this.select[0].multiple},_destroy:function(){var a=this.element.parents(".ui-select");a.length>0&&(a.is(".ui-btn-left, .ui-btn-right")&&this.element.addClass(a.hasClass("ui-btn-left")?"ui-btn-left":"ui-btn-right"),this.element.insertAfter(a),a.remove())},_create:function(){this._preExtension(),this.button=this._button();var c=this,d=this.options,e=d.icon?d.iconpos||this.select.jqmData("iconpos"):!1,f=this.button.insertBefore(this.select).attr("id",this.buttonId).addClass("ui-btn"+(d.icon?" ui-icon-"+d.icon+" ui-btn-icon-"+e+(d.iconshadow?" ui-shadow-icon":""):"")+(d.theme?" ui-btn-"+d.theme:"")+(d.corners?" ui-corner-all":"")+(d.shadow?" ui-shadow":""));this.setButtonText(),d.nativeMenu&&b.opera&&b.opera.version&&f.addClass("ui-select-nativeonly"),this.isMultiple&&(this.buttonCount=a("<span>").addClass("ui-li-count ui-body-inherit").hide().appendTo(f.addClass("ui-li-has-count"))),(d.disabled||this.element.attr("disabled"))&&this.disable(),this.select.change(function(){c.refresh(),d.nativeMenu&&this.blur()}),this._handleFormReset(),this._on(this.button,{keydown:"_handleKeydown"}),this.build()},build:function(){var b=this;this.select.appendTo(b.button).bind("vmousedown",function(){b.button.addClass(a.mobile.activeBtnClass)}).bind("focus",function(){b.button.addClass(a.mobile.focusClass)}).bind("blur",function(){b.button.removeClass(a.mobile.focusClass)}).bind("focus vmouseover",function(){b.button.trigger("vmouseover")}).bind("vmousemove",function(){b.button.removeClass(a.mobile.activeBtnClass)}).bind("change blur vmouseout",function(){b.button.trigger("vmouseout").removeClass(a.mobile.activeBtnClass)}),b.button.bind("vmousedown",function(){b.options.preventFocusZoom&&a.mobile.zoom.disable(!0)}),b.label.bind("click focus",function(){b.options.preventFocusZoom&&a.mobile.zoom.disable(!0)}),b.select.bind("focus",function(){b.options.preventFocusZoom&&a.mobile.zoom.disable(!0)}),b.button.bind("mouseup",function(){b.options.preventFocusZoom&&setTimeout(function(){a.mobile.zoom.enable(!0)},0)}),b.select.bind("blur",function(){b.options.preventFocusZoom&&a.mobile.zoom.enable(!0)})},selected:function(){return this._selectOptions().filter(":selected")},selectedIndices:function(){var a=this;return this.selected().map(function(){return a._selectOptions().index(this)}).get()},setButtonText:function(){var b=this,d=this.selected(),e=this.placeholder,f=a(c.createElement("span"));this.button.children("span").not(".ui-li-count").remove().end().end().prepend(function(){return e=d.length?d.map(function(){return a(this).text()}).get().join(", "):b.placeholder,e?f.text(e):f.html(" "),f.addClass(b.select.attr("class")).addClass(d.attr("class")).removeClass("ui-screen-hidden")}())},setButtonCount:function(){var a=this.selected();this.isMultiple&&this.buttonCount[a.length>1?"show":"hide"]().text(a.length)},_handleKeydown:function(){this._delay("_refreshButton")},_reset:function(){this.refresh()},_refreshButton:function(){this.setButtonText(),this.setButtonCount()},refresh:function(){this._refreshButton()},open:a.noop,close:a.noop,disable:function(){this._setDisabled(!0),this.button.addClass("ui-state-disabled")},enable:function(){this._setDisabled(!1),this.button.removeClass("ui-state-disabled")}},a.mobile.behaviors.formReset))}(a),function(a){a.mobile.links=function(b){a(b).find("a").jqmEnhanceable().filter(":jqmData(rel='popup')[href][href!='']").each(function(){var a=this,b=a.getAttribute("href").substring(1);b&&(a.setAttribute("aria-haspopup",!0),a.setAttribute("aria-owns",b),a.setAttribute("aria-expanded",!1))}).end().not(".ui-btn, :jqmData(role='none'), :jqmData(role='nojs')").addClass("ui-link")}}(a),function(a,c){function d(a,b,c,d){var e=d;return e=b>a?c+(a-b)/2:Math.min(Math.max(c,d-b/2),c+a-b)}function e(a){return{x:a.scrollLeft(),y:a.scrollTop(),cx:a[0].innerWidth||a.width(),cy:a[0].innerHeight||a.height()}}a.widget("mobile.popup",{options:{wrapperClass:null,theme:null,overlayTheme:null,shadow:!0,corners:!0,transition:"none",positionTo:"origin",tolerance:null,closeLinkSelector:"a:jqmData(rel='back')",closeLinkEvents:"click.popup",navigateEvents:"navigate.popup",closeEvents:"navigate.popup pagebeforechange.popup",dismissible:!0,enhanced:!1,history:!a.mobile.browser.oldIE},_create:function(){var b=this.element,c=b.attr("id"),d=this.options;d.history=d.history&&a.mobile.ajaxEnabled&&a.mobile.hashListeningEnabled,a.extend(this,{_scrollTop:0,_page:b.closest(".ui-page"),_ui:null,_fallbackTransition:"",_currentTransition:!1,_prerequisites:null,_isOpen:!1,_tolerance:null,_resizeData:null,_ignoreResizeTo:0,_orientationchangeInProgress:!1}),0===this._page.length&&(this._page=a("body")),d.enhanced?this._ui={container:b.parent(),screen:b.parent().prev(),placeholder:a(this.document[0].getElementById(c+"-placeholder"))}:(this._ui=this._enhance(b,c),this._applyTransition(d.transition)),this._setTolerance(d.tolerance)._ui.focusElement=this._ui.container,this._on(this._ui.screen,{vclick:"_eatEventAndClose"}),this._on(this.window,{orientationchange:a.proxy(this,"_handleWindowOrientationchange"),resize:a.proxy(this,"_handleWindowResize"),keyup:a.proxy(this,"_handleWindowKeyUp")}),this._on(this.document,{focusin:"_handleDocumentFocusIn"})},_enhance:function(b,c){var d=this.options,e=d.wrapperClass,f={screen:a("<div class='ui-screen-hidden ui-popup-screen "+this._themeClassFromOption("ui-overlay-",d.overlayTheme)+"'></div>"),placeholder:a("<div style='display: none;'><!-- placeholder --></div>"),container:a("<div class='ui-popup-container ui-popup-hidden ui-popup-truncate"+(e?" "+e:"")+"'></div>")},g=this.document[0].createDocumentFragment();return g.appendChild(f.screen[0]),g.appendChild(f.container[0]),c&&(f.screen.attr("id",c+"-screen"),f.container.attr("id",c+"-popup"),f.placeholder.attr("id",c+"-placeholder").html("<!-- placeholder for "+c+" -->")),this._page[0].appendChild(g),f.placeholder.insertAfter(b),b.detach().addClass("ui-popup "+this._themeClassFromOption("ui-body-",d.theme)+" "+(d.shadow?"ui-overlay-shadow ":"")+(d.corners?"ui-corner-all ":"")).appendTo(f.container),f},_eatEventAndClose:function(a){return a.preventDefault(),a.stopImmediatePropagation(),this.options.dismissible&&this.close(),!1},_resizeScreen:function(){var a=this._ui.screen,b=this._ui.container.outerHeight(!0),c=a.removeAttr("style").height(),d=this.document.height()-1;d>c?a.height(d):b>c&&a.height(b)},_handleWindowKeyUp:function(b){return this._isOpen&&b.keyCode===a.mobile.keyCode.ESCAPE?this._eatEventAndClose(b):void 0},_expectResizeEvent:function(){var a=e(this.window);if(this._resizeData){if(a.x===this._resizeData.windowCoordinates.x&&a.y===this._resizeData.windowCoordinates.y&&a.cx===this._resizeData.windowCoordinates.cx&&a.cy===this._resizeData.windowCoordinates.cy)return!1;clearTimeout(this._resizeData.timeoutId)}return this._resizeData={timeoutId:this._delay("_resizeTimeout",200),windowCoordinates:a},!0},_resizeTimeout:function(){this._isOpen?this._expectResizeEvent()||(this._ui.container.hasClass("ui-popup-hidden")&&(this._ui.container.removeClass("ui-popup-hidden ui-popup-truncate"),this.reposition({positionTo:"window"}),this._ignoreResizeEvents()),this._resizeScreen(),this._resizeData=null,this._orientationchangeInProgress=!1):(this._resizeData=null,this._orientationchangeInProgress=!1)},_stopIgnoringResizeEvents:function(){this._ignoreResizeTo=0},_ignoreResizeEvents:function(){this._ignoreResizeTo&&clearTimeout(this._ignoreResizeTo),this._ignoreResizeTo=this._delay("_stopIgnoringResizeEvents",1e3)},_handleWindowResize:function(){this._isOpen&&0===this._ignoreResizeTo&&(!this._expectResizeEvent()&&!this._orientationchangeInProgress||this._ui.container.hasClass("ui-popup-hidden")||this._ui.container.addClass("ui-popup-hidden ui-popup-truncate").removeAttr("style"))},_handleWindowOrientationchange:function(){!this._orientationchangeInProgress&&this._isOpen&&0===this._ignoreResizeTo&&(this._expectResizeEvent(),this._orientationchangeInProgress=!0)},_handleDocumentFocusIn:function(b){var c,d=b.target,e=this._ui;if(this._isOpen){if(d!==e.container[0]){if(c=a(d),0===c.parents().filter(e.container[0]).length)return a(this.document[0].activeElement).one("focus",function(){c.blur()}),e.focusElement.focus(),b.preventDefault(),b.stopImmediatePropagation(),!1;e.focusElement[0]===e.container[0]&&(e.focusElement=c)}this._ignoreResizeEvents()}},_themeClassFromOption:function(a,b){return b?"none"===b?"":a+b:a+"inherit"},_applyTransition:function(b){return b&&(this._ui.container.removeClass(this._fallbackTransition),"none"!==b&&(this._fallbackTransition=a.mobile._maybeDegradeTransition(b),"none"===this._fallbackTransition&&(this._fallbackTransition=""),this._ui.container.addClass(this._fallbackTransition))),this},_setOptions:function(a){var b=this.options,d=this.element,e=this._ui.screen;return a.wrapperClass!==c&&this._ui.container.removeClass(b.wrapperClass).addClass(a.wrapperClass),a.theme!==c&&d.removeClass(this._themeClassFromOption("ui-body-",b.theme)).addClass(this._themeClassFromOption("ui-body-",a.theme)),a.overlayTheme!==c&&(e.removeClass(this._themeClassFromOption("ui-overlay-",b.overlayTheme)).addClass(this._themeClassFromOption("ui-overlay-",a.overlayTheme)),this._isOpen&&e.addClass("in")),a.shadow!==c&&d.toggleClass("ui-overlay-shadow",a.shadow),a.corners!==c&&d.toggleClass("ui-corner-all",a.corners),a.transition!==c&&(this._currentTransition||this._applyTransition(a.transition)),a.tolerance!==c&&this._setTolerance(a.tolerance),a.disabled!==c&&a.disabled&&this.close(),this._super(a)
},_setTolerance:function(b){var d,e={t:30,r:15,b:30,l:15};if(b!==c)switch(d=String(b).split(","),a.each(d,function(a,b){d[a]=parseInt(b,10)}),d.length){case 1:isNaN(d[0])||(e.t=e.r=e.b=e.l=d[0]);break;case 2:isNaN(d[0])||(e.t=e.b=d[0]),isNaN(d[1])||(e.l=e.r=d[1]);break;case 4:isNaN(d[0])||(e.t=d[0]),isNaN(d[1])||(e.r=d[1]),isNaN(d[2])||(e.b=d[2]),isNaN(d[3])||(e.l=d[3])}return this._tolerance=e,this},_clampPopupWidth:function(a){var b,c=e(this.window),d={x:this._tolerance.l,y:c.y+this._tolerance.t,cx:c.cx-this._tolerance.l-this._tolerance.r,cy:c.cy-this._tolerance.t-this._tolerance.b};return a||this._ui.container.css("max-width",d.cx),b={cx:this._ui.container.outerWidth(!0),cy:this._ui.container.outerHeight(!0)},{rc:d,menuSize:b}},_calculateFinalLocation:function(a,b){var c,e=b.rc,f=b.menuSize;return c={left:d(e.cx,f.cx,e.x,a.x),top:d(e.cy,f.cy,e.y,a.y)},c.top=Math.max(0,c.top),c.top-=Math.min(c.top,Math.max(0,c.top+f.cy-this.document.height())),c},_placementCoords:function(a){return this._calculateFinalLocation(a,this._clampPopupWidth())},_createPrerequisites:function(b,c,d){var e,f=this;e={screen:a.Deferred(),container:a.Deferred()},e.screen.then(function(){e===f._prerequisites&&b()}),e.container.then(function(){e===f._prerequisites&&c()}),a.when(e.screen,e.container).done(function(){e===f._prerequisites&&(f._prerequisites=null,d())}),f._prerequisites=e},_animate:function(b){return this._ui.screen.removeClass(b.classToRemove).addClass(b.screenClassToAdd),b.prerequisites.screen.resolve(),b.transition&&"none"!==b.transition&&(b.applyTransition&&this._applyTransition(b.transition),this._fallbackTransition)?void this._ui.container.addClass(b.containerClassToAdd).removeClass(b.classToRemove).animationComplete(a.proxy(b.prerequisites.container,"resolve")):(this._ui.container.removeClass(b.classToRemove),void b.prerequisites.container.resolve())},_desiredCoords:function(b){var c,d=null,f=e(this.window),g=b.x,h=b.y,i=b.positionTo;if(i&&"origin"!==i)if("window"===i)g=f.cx/2+f.x,h=f.cy/2+f.y;else{try{d=a(i)}catch(j){d=null}d&&(d.filter(":visible"),0===d.length&&(d=null))}return d&&(c=d.offset(),g=c.left+d.outerWidth()/2,h=c.top+d.outerHeight()/2),("number"!==a.type(g)||isNaN(g))&&(g=f.cx/2+f.x),("number"!==a.type(h)||isNaN(h))&&(h=f.cy/2+f.y),{x:g,y:h}},_reposition:function(a){a={x:a.x,y:a.y,positionTo:a.positionTo},this._trigger("beforeposition",c,a),this._ui.container.offset(this._placementCoords(this._desiredCoords(a)))},reposition:function(a){this._isOpen&&this._reposition(a)},_openPrerequisitesComplete:function(){var a=this.element.attr("id");this._ui.container.addClass("ui-popup-active"),this._isOpen=!0,this._resizeScreen(),this._ui.container.attr("tabindex","0").focus(),this._ignoreResizeEvents(),a&&this.document.find("[aria-haspopup='true'][aria-owns='"+a+"']").attr("aria-expanded",!0),this._trigger("afteropen")},_open:function(b){var c=a.extend({},this.options,b),d=function(){var a=navigator.userAgent,b=a.match(/AppleWebKit\/([0-9\.]+)/),c=!!b&&b[1],d=a.match(/Android (\d+(?:\.\d+))/),e=!!d&&d[1],f=a.indexOf("Chrome")>-1;return null!==d&&"4.0"===e&&c&&c>534.13&&!f?!0:!1}();this._createPrerequisites(a.noop,a.noop,a.proxy(this,"_openPrerequisitesComplete")),this._currentTransition=c.transition,this._applyTransition(c.transition),this._ui.screen.removeClass("ui-screen-hidden"),this._ui.container.removeClass("ui-popup-truncate"),this._reposition(c),this._ui.container.removeClass("ui-popup-hidden"),this.options.overlayTheme&&d&&this.element.closest(".ui-page").addClass("ui-popup-open"),this._animate({additionalCondition:!0,transition:c.transition,classToRemove:"",screenClassToAdd:"in",containerClassToAdd:"in",applyTransition:!1,prerequisites:this._prerequisites})},_closePrerequisiteScreen:function(){this._ui.screen.removeClass("out").addClass("ui-screen-hidden")},_closePrerequisiteContainer:function(){this._ui.container.removeClass("reverse out").addClass("ui-popup-hidden ui-popup-truncate").removeAttr("style")},_closePrerequisitesDone:function(){var b=this._ui.container,d=this.element.attr("id");b.removeAttr("tabindex"),a.mobile.popup.active=c,a(":focus",b[0]).add(b[0]).blur(),d&&this.document.find("[aria-haspopup='true'][aria-owns='"+d+"']").attr("aria-expanded",!1),this._trigger("afterclose")},_close:function(b){this._ui.container.removeClass("ui-popup-active"),this._page.removeClass("ui-popup-open"),this._isOpen=!1,this._createPrerequisites(a.proxy(this,"_closePrerequisiteScreen"),a.proxy(this,"_closePrerequisiteContainer"),a.proxy(this,"_closePrerequisitesDone")),this._animate({additionalCondition:this._ui.screen.hasClass("in"),transition:b?"none":this._currentTransition,classToRemove:"in",screenClassToAdd:"out",containerClassToAdd:"reverse out",applyTransition:!0,prerequisites:this._prerequisites})},_unenhance:function(){this.options.enhanced||(this._setOptions({theme:a.mobile.popup.prototype.options.theme}),this.element.detach().insertAfter(this._ui.placeholder).removeClass("ui-popup ui-overlay-shadow ui-corner-all ui-body-inherit"),this._ui.screen.remove(),this._ui.container.remove(),this._ui.placeholder.remove())},_destroy:function(){return a.mobile.popup.active===this?(this.element.one("popupafterclose",a.proxy(this,"_unenhance")),this.close()):this._unenhance(),this},_closePopup:function(c,d){var e,f,g=this.options,h=!1;c&&c.isDefaultPrevented()||a.mobile.popup.active!==this||(b.scrollTo(0,this._scrollTop),c&&"pagebeforechange"===c.type&&d&&(e="string"==typeof d.toPage?d.toPage:d.toPage.jqmData("url"),e=a.mobile.path.parseUrl(e),f=e.pathname+e.search+e.hash,this._myUrl!==a.mobile.path.makeUrlAbsolute(f)?h=!0:c.preventDefault()),this.window.off(g.closeEvents),this.element.undelegate(g.closeLinkSelector,g.closeLinkEvents),this._close(h))},_bindContainerClose:function(){this.window.on(this.options.closeEvents,a.proxy(this,"_closePopup"))},widget:function(){return this._ui.container},open:function(b){var c,d,e,f,g,h,i=this,j=this.options;return a.mobile.popup.active||j.disabled?this:(a.mobile.popup.active=this,this._scrollTop=this.window.scrollTop(),j.history?(h=a.mobile.navigate.history,d=a.mobile.dialogHashKey,e=a.mobile.activePage,f=e?e.hasClass("ui-dialog"):!1,this._myUrl=c=h.getActive().url,(g=c.indexOf(d)>-1&&!f&&h.activeIndex>0)?(i._open(b),i._bindContainerClose(),this):(-1!==c.indexOf(d)||f?c=a.mobile.path.parseLocation().hash+d:c+=c.indexOf("#")>-1?d:"#"+d,0===h.activeIndex&&c===h.initialDst&&(c+=d),this.window.one("beforenavigate",function(a){a.preventDefault(),i._open(b),i._bindContainerClose()}),this.urlAltered=!0,a.mobile.navigate(c,{role:"dialog"}),this)):(i._open(b),i._bindContainerClose(),i.element.delegate(j.closeLinkSelector,j.closeLinkEvents,function(a){i.close(),a.preventDefault()}),this))},close:function(){return a.mobile.popup.active!==this?this:(this._scrollTop=this.window.scrollTop(),this.options.history&&this.urlAltered?(a.mobile.back(),this.urlAltered=!1):this._closePopup(),this)}}),a.mobile.popup.handleLink=function(b){var c,d=a.mobile.path,e=a(d.hashToSelector(d.parseUrl(b.attr("href")).hash)).first();e.length>0&&e.data("mobile-popup")&&(c=b.offset(),e.popup("open",{x:c.left+b.outerWidth()/2,y:c.top+b.outerHeight()/2,transition:b.jqmData("transition"),positionTo:b.jqmData("position-to")})),setTimeout(function(){b.removeClass(a.mobile.activeBtnClass)},300)},a.mobile.document.on("pagebeforechange",function(b,c){"popup"===c.options.role&&(a.mobile.popup.handleLink(c.options.link),b.preventDefault())})}(a),function(a,b){var d=".ui-disabled,.ui-state-disabled,.ui-li-divider,.ui-screen-hidden,:jqmData(role='placeholder')",e=function(a,b,c){var e=a[c+"All"]().not(d).first();e.length&&(b.blur().attr("tabindex","-1"),e.find("a").first().focus())};a.widget("mobile.selectmenu",a.mobile.selectmenu,{_create:function(){var a=this.options;return a.nativeMenu=a.nativeMenu||this.element.parents(":jqmData(role='popup'),:mobile-popup").length>0,this._super()},_handleSelectFocus:function(){this.element.blur(),this.button.focus()},_handleKeydown:function(a){this._super(a),this._handleButtonVclickKeydown(a)},_handleButtonVclickKeydown:function(b){this.options.disabled||this.isOpen||("vclick"===b.type||b.keyCode&&(b.keyCode===a.mobile.keyCode.ENTER||b.keyCode===a.mobile.keyCode.SPACE))&&(this._decideFormat(),"overlay"===this.menuType?this.button.attr("href","#"+this.popupId).attr("data-"+(a.mobile.ns||"")+"rel","popup"):this.button.attr("href","#"+this.dialogId).attr("data-"+(a.mobile.ns||"")+"rel","dialog"),this.isOpen=!0)},_handleListFocus:function(b){var c="focusin"===b.type?{tabindex:"0",event:"vmouseover"}:{tabindex:"-1",event:"vmouseout"};a(b.target).attr("tabindex",c.tabindex).trigger(c.event)},_handleListKeydown:function(b){var c=a(b.target),d=c.closest("li");switch(b.keyCode){case 38:return e(d,c,"prev"),!1;case 40:return e(d,c,"next"),!1;case 13:case 32:return c.trigger("click"),!1}},_handleMenuPageHide:function(){this.thisPage.page("bindRemove")},_handleHeaderCloseClick:function(){return"overlay"===this.menuType?(this.close(),!1):void 0},build:function(){var c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w=this.options;return w.nativeMenu?this._super():(v=this,c=this.selectId,d=c+"-listbox",e=c+"-dialog",f=this.label,g=this.element.closest(".ui-page"),h=this.element[0].multiple,i=c+"-menu",j=w.theme?" data-"+a.mobile.ns+"theme='"+w.theme+"'":"",k=w.overlayTheme||w.theme||null,l=k?" data-"+a.mobile.ns+"overlay-theme='"+k+"'":"",m=w.dividerTheme&&h?" data-"+a.mobile.ns+"divider-theme='"+w.dividerTheme+"'":"",n=a("<div data-"+a.mobile.ns+"role='dialog' class='ui-selectmenu' id='"+e+"'"+j+l+"><div data-"+a.mobile.ns+"role='header'><div class='ui-title'>"+f.getEncodedText()+"</div></div><div data-"+a.mobile.ns+"role='content'></div></div>"),o=a("<div id='"+d+"' class='ui-selectmenu'></div>").insertAfter(this.select).popup({theme:w.overlayTheme}),p=a("<ul class='ui-selectmenu-list' id='"+i+"' role='listbox' aria-labelledby='"+this.buttonId+"'"+j+m+"></ul>").appendTo(o),q=a("<div class='ui-header ui-bar-"+(w.theme?w.theme:"inherit")+"'></div>").prependTo(o),r=a("<h1 class='ui-title'></h1>").appendTo(q),this.isMultiple&&(u=a("<a>",{role:"button",text:w.closeText,href:"#","class":"ui-btn ui-corner-all ui-btn-left ui-btn-icon-notext ui-icon-delete"}).appendTo(q)),a.extend(this,{selectId:c,menuId:i,popupId:d,dialogId:e,thisPage:g,menuPage:n,label:f,isMultiple:h,theme:w.theme,listbox:o,list:p,header:q,headerTitle:r,headerClose:u,menuPageContent:s,menuPageClose:t,placeholder:""}),this.refresh(),this._origTabIndex===b&&(this._origTabIndex=null===this.select[0].getAttribute("tabindex")?!1:this.select.attr("tabindex")),this.select.attr("tabindex","-1"),this._on(this.select,{focus:"_handleSelectFocus"}),this._on(this.button,{vclick:"_handleButtonVclickKeydown"}),this.list.attr("role","listbox"),this._on(this.list,{focusin:"_handleListFocus",focusout:"_handleListFocus",keydown:"_handleListKeydown"}),this.list.delegate("li:not(.ui-disabled,.ui-state-disabled,.ui-li-divider)","click",function(b){var c=v.select[0].selectedIndex,d=a.mobile.getAttribute(this,"option-index"),e=v._selectOptions().eq(d)[0];e.selected=v.isMultiple?!e.selected:!0,v.isMultiple&&a(this).find("a").toggleClass("ui-checkbox-on",e.selected).toggleClass("ui-checkbox-off",!e.selected),(v.isMultiple||c!==d)&&v.select.trigger("change"),v.isMultiple?v.list.find("li:not(.ui-li-divider)").eq(d).find("a").first().focus():v.close(),b.preventDefault()}),this._on(this.menuPage,{pagehide:"_handleMenuPageHide"}),this._on(this.listbox,{popupafterclose:"close"}),this.isMultiple&&this._on(this.headerClose,{click:"_handleHeaderCloseClick"}),this)},_isRebuildRequired:function(){var a=this.list.find("li"),b=this._selectOptions().not(".ui-screen-hidden");return b.text()!==a.text()},selected:function(){return this._selectOptions().filter(":selected:not( :jqmData(placeholder='true') )")},refresh:function(b){var c,d;return this.options.nativeMenu?this._super(b):(c=this,(b||this._isRebuildRequired())&&c._buildList(),d=this.selectedIndices(),c.setButtonText(),c.setButtonCount(),void c.list.find("li:not(.ui-li-divider)").find("a").removeClass(a.mobile.activeBtnClass).end().attr("aria-selected",!1).each(function(b){if(a.inArray(b,d)>-1){var e=a(this);e.attr("aria-selected",!0),c.isMultiple?e.find("a").removeClass("ui-checkbox-off").addClass("ui-checkbox-on"):e.hasClass("ui-screen-hidden")?e.next().find("a").addClass(a.mobile.activeBtnClass):e.find("a").addClass(a.mobile.activeBtnClass)}}))},close:function(){if(!this.options.disabled&&this.isOpen){var a=this;"page"===a.menuType?(a.menuPage.dialog("close"),a.list.appendTo(a.listbox)):a.listbox.popup("close"),a._focusButton(),a.isOpen=!1}},open:function(){this.button.click()},_focusMenuItem:function(){var b=this.list.find("a."+a.mobile.activeBtnClass);0===b.length&&(b=this.list.find("li:not("+d+") a.ui-btn")),b.first().focus()},_decideFormat:function(){var b=this,c=this.window,d=b.list.parent(),e=d.outerHeight(),f=c.scrollTop(),g=b.button.offset().top,h=c.height();e>h-80||!a.support.scrollTop?(b.menuPage.appendTo(a.mobile.pageContainer).page(),b.menuPageContent=b.menuPage.find(".ui-content"),b.menuPageClose=b.menuPage.find(".ui-header a"),b.thisPage.unbind("pagehide.remove"),0===f&&g>h&&b.thisPage.one("pagehide",function(){a(this).jqmData("lastScroll",g)}),b.menuPage.one({pageshow:a.proxy(this,"_focusMenuItem"),pagehide:a.proxy(this,"close")}),b.menuType="page",b.menuPageContent.append(b.list),b.menuPage.find("div .ui-title").text(b.label.text())):(b.menuType="overlay",b.listbox.one({popupafteropen:a.proxy(this,"_focusMenuItem")}))},_buildList:function(){var b,d,e,f,g,h,i,j,k,l,m,n,o,p,q=this,r=this.options,s=this.placeholder,t=!0,u="false",v="data-"+a.mobile.ns,w=v+"option-index",x=v+"icon",y=v+"role",z=v+"placeholder",A=c.createDocumentFragment(),B=!1;for(q.list.empty().filter(".ui-listview").listview("destroy"),b=this._selectOptions(),d=b.length,e=this.select[0],g=0;d>g;g++,B=!1)h=b[g],i=a(h),i.hasClass("ui-screen-hidden")||(j=h.parentNode,k=i.text(),l=c.createElement("a"),m=[],l.setAttribute("href","#"),l.appendChild(c.createTextNode(k)),j!==e&&"optgroup"===j.nodeName.toLowerCase()&&(n=j.getAttribute("label"),n!==f&&(o=c.createElement("li"),o.setAttribute(y,"list-divider"),o.setAttribute("role","option"),o.setAttribute("tabindex","-1"),o.appendChild(c.createTextNode(n)),A.appendChild(o),f=n)),!t||h.getAttribute("value")&&0!==k.length&&!i.jqmData("placeholder")||(t=!1,B=!0,null===h.getAttribute(z)&&(this._removePlaceholderAttr=!0),h.setAttribute(z,!0),r.hidePlaceholderMenuItems&&m.push("ui-screen-hidden"),s!==k&&(s=q.placeholder=k)),p=c.createElement("li"),h.disabled&&(m.push("ui-state-disabled"),p.setAttribute("aria-disabled",!0)),p.setAttribute(w,g),p.setAttribute(x,u),B&&p.setAttribute(z,!0),p.className=m.join(" "),p.setAttribute("role","option"),l.setAttribute("tabindex","-1"),this.isMultiple&&a(l).addClass("ui-btn ui-checkbox-off ui-btn-icon-right"),p.appendChild(l),A.appendChild(p));q.list[0].appendChild(A),this.isMultiple||s.length?this.headerTitle.text(this.placeholder):this.header.addClass("ui-screen-hidden"),q.list.listview()},_button:function(){return this.options.nativeMenu?this._super():a("<a>",{href:"#",role:"button",id:this.buttonId,"aria-haspopup":"true","aria-owns":this.menuId})},_destroy:function(){this.options.nativeMenu||(this.close(),this._origTabIndex!==b&&(this._origTabIndex!==!1?this.select.attr("tabindex",this._origTabIndex):this.select.removeAttr("tabindex")),this._removePlaceholderAttr&&this._selectOptions().removeAttr("data-"+a.mobile.ns+"placeholder"),this.listbox.remove(),this.menuPage.remove()),this._super()}})}(a),function(a,b){function c(a,b){var c=b?b:[];return c.push("ui-btn"),a.theme&&c.push("ui-btn-"+a.theme),a.icon&&(c=c.concat(["ui-icon-"+a.icon,"ui-btn-icon-"+a.iconpos]),a.iconshadow&&c.push("ui-shadow-icon")),a.inline&&c.push("ui-btn-inline"),a.shadow&&c.push("ui-shadow"),a.corners&&c.push("ui-corner-all"),a.mini&&c.push("ui-mini"),c}function d(a){var c,d,e,g=!1,h=!0,i={icon:"",inline:!1,shadow:!1,corners:!1,iconshadow:!1,mini:!1},j=[];for(a=a.split(" "),c=0;c<a.length;c++)e=!0,d=f[a[c]],d!==b?(e=!1,i[d]=!0):0===a[c].indexOf("ui-btn-icon-")?(e=!1,h=!1,i.iconpos=a[c].substring(12)):0===a[c].indexOf("ui-icon-")?(e=!1,i.icon=a[c].substring(8)):0===a[c].indexOf("ui-btn-")&&8===a[c].length?(e=!1,i.theme=a[c].substring(7)):"ui-btn"===a[c]&&(e=!1,g=!0),e&&j.push(a[c]);return h&&(i.icon=""),{options:i,unknownClasses:j,alreadyEnhanced:g}}function e(a){return"-"+a.toLowerCase()}var f={"ui-shadow":"shadow","ui-corner-all":"corners","ui-btn-inline":"inline","ui-shadow-icon":"iconshadow","ui-mini":"mini"},g=function(){var c=a.mobile.getAttribute.apply(this,arguments);return null==c?b:c},h=/[A-Z]/g;a.fn.buttonMarkup=function(f,i){var j,k,l,m,n,o=a.fn.buttonMarkup.defaults;for(j=0;j<this.length;j++){if(l=this[j],k=i?{alreadyEnhanced:!1,unknownClasses:[]}:d(l.className),m=a.extend({},k.alreadyEnhanced?k.options:{},f),!k.alreadyEnhanced)for(n in o)m[n]===b&&(m[n]=g(l,n.replace(h,e)));l.className=c(a.extend({},o,m),k.unknownClasses).join(" "),"button"!==l.tagName.toLowerCase()&&l.setAttribute("role","button")}return this},a.fn.buttonMarkup.defaults={icon:"",iconpos:"left",theme:null,inline:!1,shadow:!0,corners:!0,iconshadow:!1,mini:!1},a.extend(a.fn.buttonMarkup,{initSelector:"a:jqmData(role='button'), .ui-bar > a, .ui-bar > :jqmData(role='controlgroup') > a, button"})}(a),function(a,b){a.widget("mobile.controlgroup",a.extend({options:{enhanced:!1,theme:null,shadow:!1,corners:!0,excludeInvisible:!0,type:"vertical",mini:!1},_create:function(){var b=this.element,c=this.options;a.fn.buttonMarkup&&this.element.find(a.fn.buttonMarkup.initSelector).buttonMarkup(),a.each(this._childWidgets,a.proxy(function(b,c){a.mobile[c]&&this.element.find(a.mobile[c].initSelector).not(a.mobile.page.prototype.keepNativeSelector())[c]()},this)),a.extend(this,{_ui:null,_initialRefresh:!0}),this._ui=c.enhanced?{groupLegend:b.children(".ui-controlgroup-label").children(),childWrapper:b.children(".ui-controlgroup-controls")}:this._enhance()},_childWidgets:["checkboxradio","selectmenu","button"],_themeClassFromOption:function(a){return a?"none"===a?"":"ui-group-theme-"+a:""},_enhance:function(){var b=this.element,c=this.options,d={groupLegend:b.children("legend"),childWrapper:b.addClass("ui-controlgroup ui-controlgroup-"+("horizontal"===c.type?"horizontal":"vertical")+" "+this._themeClassFromOption(c.theme)+" "+(c.corners?"ui-corner-all ":"")+(c.mini?"ui-mini ":"")).wrapInner("<div class='ui-controlgroup-controls "+(c.shadow===!0?"ui-shadow":"")+"'></div>").children()};return d.groupLegend.length>0&&a("<div role='heading' class='ui-controlgroup-label'></div>").append(d.groupLegend).prependTo(b),d},_init:function(){this.refresh()},_setOptions:function(a){var c,d,e=this.element;return a.type!==b&&(e.removeClass("ui-controlgroup-horizontal ui-controlgroup-vertical").addClass("ui-controlgroup-"+("horizontal"===a.type?"horizontal":"vertical")),c=!0),a.theme!==b&&e.removeClass(this._themeClassFromOption(this.options.theme)).addClass(this._themeClassFromOption(a.theme)),a.corners!==b&&e.toggleClass("ui-corner-all",a.corners),a.mini!==b&&e.toggleClass("ui-mini",a.mini),a.shadow!==b&&this._ui.childWrapper.toggleClass("ui-shadow",a.shadow),a.excludeInvisible!==b&&(this.options.excludeInvisible=a.excludeInvisible,c=!0),d=this._super(a),c&&this.refresh(),d},container:function(){return this._ui.childWrapper},refresh:function(){var b=this.container(),c=b.find(".ui-btn").not(".ui-slider-handle"),d=this._initialRefresh;a.mobile.checkboxradio&&b.find(":mobile-checkboxradio").checkboxradio("refresh"),this._addFirstLastClasses(c,this.options.excludeInvisible?this._getVisibles(c,d):c,d),this._initialRefresh=!1},_destroy:function(){var a,b,c=this.options;return c.enhanced?this:(a=this._ui,b=this.element.removeClass("ui-controlgroup ui-controlgroup-horizontal ui-controlgroup-vertical ui-corner-all ui-mini "+this._themeClassFromOption(c.theme)).find(".ui-btn").not(".ui-slider-handle"),this._removeFirstLastClasses(b),a.groupLegend.unwrap(),void a.childWrapper.children().unwrap())}},a.mobile.behaviors.addFirstLastClasses))}(a),function(a,b){a.widget("mobile.toolbar",{initSelector:":jqmData(role='footer'), :jqmData(role='header')",options:{theme:null,addBackBtn:!1,backBtnTheme:null,backBtnText:"Back"},_create:function(){var b,c,d=this.element.is(":jqmData(role='header')")?"header":"footer",e=this.element.closest(".ui-page");0===e.length&&(e=!1,this._on(this.document,{pageshow:"refresh"})),a.extend(this,{role:d,page:e,leftbtn:b,rightbtn:c}),this.element.attr("role","header"===d?"banner":"contentinfo").addClass("ui-"+d),this.refresh(),this._setOptions(this.options)},_setOptions:function(c){if(c.addBackBtn!==b&&(this.options.addBackBtn&&"header"===this.role&&a(".ui-page").length>1&&this.page[0].getAttribute("data-"+a.mobile.ns+"url")!==a.mobile.path.stripHash(location.hash)&&!this.leftbtn?this._addBackButton():this.element.find(".ui-toolbar-back-btn").remove()),null!=c.backBtnTheme&&this.element.find(".ui-toolbar-back-btn").addClass("ui-btn ui-btn-"+c.backBtnTheme),c.backBtnText!==b&&this.element.find(".ui-toolbar-back-btn .ui-btn-text").text(c.backBtnText),c.theme!==b){var d=this.options.theme?this.options.theme:"inherit",e=c.theme?c.theme:"inherit";this.element.removeClass("ui-bar-"+d).addClass("ui-bar-"+e)}this._super(c)},refresh:function(){"header"===this.role&&this._addHeaderButtonClasses(),this.page||(this._setRelative(),"footer"===this.role&&this.element.appendTo("body")),this._addHeadingClasses(),this._btnMarkup()},_setRelative:function(){a("[data-"+a.mobile.ns+"role='page']").css({position:"relative"})},_btnMarkup:function(){this.element.children("a").filter(":not([data-"+a.mobile.ns+"role='none'])").attr("data-"+a.mobile.ns+"role","button"),this.element.trigger("create")},_addHeaderButtonClasses:function(){var a=this.element.children("a, button");this.leftbtn=a.hasClass("ui-btn-left"),this.rightbtn=a.hasClass("ui-btn-right"),this.leftbtn=this.leftbtn||a.eq(0).not(".ui-btn-right").addClass("ui-btn-left").length,this.rightbtn=this.rightbtn||a.eq(1).addClass("ui-btn-right").length},_addBackButton:function(){var b=this.options,c=b.backBtnTheme||b.theme;a("<a role='button' href='javascript:void(0);' class='ui-btn ui-corner-all ui-shadow ui-btn-left "+(c?"ui-btn-"+c+" ":"")+"ui-toolbar-back-btn ui-icon-carat-l ui-btn-icon-left' data-"+a.mobile.ns+"rel='back'>"+b.backBtnText+"</a>").prependTo(this.element)},_addHeadingClasses:function(){this.element.children("h1, h2, h3, h4, h5, h6").addClass("ui-title").attr({role:"heading","aria-level":"1"})}})}(a),function(a,b){a.widget("mobile.toolbar",a.mobile.toolbar,{options:{position:null,visibleOnPageShow:!0,disablePageZoom:!0,transition:"slide",fullscreen:!1,tapToggle:!0,tapToggleBlacklist:"a, button, input, select, textarea, .ui-header-fixed, .ui-footer-fixed, .ui-flipswitch, .ui-popup, .ui-panel, .ui-panel-dismiss-open",hideDuringFocus:"input, textarea, select",updatePagePadding:!0,trackPersistentToolbars:!0,supportBlacklist:function(){return!a.support.fixedPosition}},_create:function(){this._super(),"fixed"!==this.options.position||this.options.supportBlacklist()||this._makeFixed()},_makeFixed:function(){this.element.addClass("ui-"+this.role+"-fixed"),this.updatePagePadding(),this._addTransitionClass(),this._bindPageEvents(),this._bindToggleHandlers()},_setOptions:function(c){if("fixed"===c.position&&"fixed"!==this.options.position&&this._makeFixed(),"fixed"===this.options.position&&!this.options.supportBlacklist()){var d=this.page?this.page:a(".ui-page-active").length>0?a(".ui-page-active"):a(".ui-page").eq(0);c.fullscreen!==b&&(c.fullscreen?(this.element.addClass("ui-"+this.role+"-fullscreen"),d.addClass("ui-page-"+this.role+"-fullscreen")):(this.element.removeClass("ui-"+this.role+"-fullscreen"),d.removeClass("ui-page-"+this.role+"-fullscreen").addClass("ui-page-"+this.role+"-fixed")))}this._super(c)},_addTransitionClass:function(){var a=this.options.transition;a&&"none"!==a&&("slide"===a&&(a=this.element.hasClass("ui-header")?"slidedown":"slideup"),this.element.addClass(a))},_bindPageEvents:function(){var a=this.page?this.element.closest(".ui-page"):this.document;this._on(a,{pagebeforeshow:"_handlePageBeforeShow",webkitAnimationStart:"_handleAnimationStart",animationstart:"_handleAnimationStart",updatelayout:"_handleAnimationStart",pageshow:"_handlePageShow",pagebeforehide:"_handlePageBeforeHide"})},_handlePageBeforeShow:function(){var b=this.options;b.disablePageZoom&&a.mobile.zoom.disable(!0),b.visibleOnPageShow||this.hide(!0)},_handleAnimationStart:function(){this.options.updatePagePadding&&this.updatePagePadding(this.page?this.page:".ui-page-active")},_handlePageShow:function(){this.updatePagePadding(this.page?this.page:".ui-page-active"),this.options.updatePagePadding&&this._on(this.window,{throttledresize:"updatePagePadding"})},_handlePageBeforeHide:function(b,c){var d,e,f,g,h=this.options;h.disablePageZoom&&a.mobile.zoom.enable(!0),h.updatePagePadding&&this._off(this.window,"throttledresize"),h.trackPersistentToolbars&&(d=a(".ui-footer-fixed:jqmData(id)",this.page),e=a(".ui-header-fixed:jqmData(id)",this.page),f=d.length&&c.nextPage&&a(".ui-footer-fixed:jqmData(id='"+d.jqmData("id")+"')",c.nextPage)||a(),g=e.length&&c.nextPage&&a(".ui-header-fixed:jqmData(id='"+e.jqmData("id")+"')",c.nextPage)||a(),(f.length||g.length)&&(f.add(g).appendTo(a.mobile.pageContainer),c.nextPage.one("pageshow",function(){g.prependTo(this),f.appendTo(this)})))},_visible:!0,updatePagePadding:function(c){var d=this.element,e="header"===this.role,f=parseFloat(d.css(e?"top":"bottom"));this.options.fullscreen||(c=c&&c.type===b&&c||this.page||d.closest(".ui-page"),c=this.page?this.page:".ui-page-active",a(c).css("padding-"+(e?"top":"bottom"),d.outerHeight()+f))},_useTransition:function(b){var c=this.window,d=this.element,e=c.scrollTop(),f=d.height(),g=this.page?d.closest(".ui-page").height():a(".ui-page-active").height(),h=a.mobile.getScreenHeight();return!b&&(this.options.transition&&"none"!==this.options.transition&&("header"===this.role&&!this.options.fullscreen&&e>f||"footer"===this.role&&!this.options.fullscreen&&g-f>e+h)||this.options.fullscreen)},show:function(a){var b="ui-fixed-hidden",c=this.element;this._useTransition(a)?c.removeClass("out "+b).addClass("in").animationComplete(function(){c.removeClass("in")}):c.removeClass(b),this._visible=!0},hide:function(a){var b="ui-fixed-hidden",c=this.element,d="out"+("slide"===this.options.transition?" reverse":"");this._useTransition(a)?c.addClass(d).removeClass("in").animationComplete(function(){c.addClass(b).removeClass(d)}):c.addClass(b).removeClass(d),this._visible=!1},toggle:function(){this[this._visible?"hide":"show"]()},_bindToggleHandlers:function(){var b,c,d=this,e=d.options,f=!0,g=this.page?this.page:a(".ui-page");g.bind("vclick",function(b){e.tapToggle&&!a(b.target).closest(e.tapToggleBlacklist).length&&d.toggle()}).bind("focusin focusout",function(g){screen.width<1025&&a(g.target).is(e.hideDuringFocus)&&!a(g.target).closest(".ui-header-fixed, .ui-footer-fixed").length&&("focusout"!==g.type||f?"focusin"===g.type&&f&&(clearTimeout(b),f=!1,c=setTimeout(function(){d.hide()},0)):(f=!0,clearTimeout(c),b=setTimeout(function(){d.show()},0)))})},_setRelative:function(){"fixed"!==this.options.position&&a("[data-"+a.mobile.ns+"role='page']").css({position:"relative"})},_destroy:function(){var a=this.element,b=a.hasClass("ui-header");a.closest(".ui-page").css("padding-"+(b?"top":"bottom"),""),a.removeClass("ui-header-fixed ui-footer-fixed ui-header-fullscreen ui-footer-fullscreen in out fade slidedown slideup ui-fixed-hidden"),a.closest(".ui-page").removeClass("ui-page-header-fixed ui-page-footer-fixed ui-page-header-fullscreen ui-page-footer-fullscreen")}})}(a),function(a){a.widget("mobile.toolbar",a.mobile.toolbar,{_makeFixed:function(){this._super(),this._workarounds()},_workarounds:function(){var a=navigator.userAgent,b=navigator.platform,c=a.match(/AppleWebKit\/([0-9]+)/),d=!!c&&c[1],e=null,f=this;if(b.indexOf("iPhone")>-1||b.indexOf("iPad")>-1||b.indexOf("iPod")>-1)e="ios";else{if(!(a.indexOf("Android")>-1))return;e="android"}if("ios"===e)f._bindScrollWorkaround();else{if(!("android"===e&&d&&534>d))return;f._bindScrollWorkaround(),f._bindListThumbWorkaround()}},_viewportOffset:function(){var a=this.element,b=a.hasClass("ui-header"),c=Math.abs(a.offset().top-this.window.scrollTop());return b||(c=Math.round(c-this.window.height()+a.outerHeight())-60),c},_bindScrollWorkaround:function(){var a=this;this._on(this.window,{scrollstop:function(){var b=a._viewportOffset();b>2&&a._visible&&a._triggerRedraw()}})},_bindListThumbWorkaround:function(){this.element.closest(".ui-page").addClass("ui-android-2x-fixed")},_triggerRedraw:function(){var b=parseFloat(a(".ui-page-active").css("padding-bottom"));a(".ui-page-active").css("padding-bottom",b+1+"px"),setTimeout(function(){a(".ui-page-active").css("padding-bottom",b+"px")},0)},destroy:function(){this._super(),this.element.closest(".ui-page-active").removeClass("ui-android-2x-fix")}})}(a),function(a,b){function c(){var a=e.clone(),b=a.eq(0),c=a.eq(1),d=c.children();return{arEls:c.add(b),gd:b,ct:c,ar:d}}var d=a.mobile.browser.oldIE&&a.mobile.browser.oldIE<=8,e=a("<div class='ui-popup-arrow-guide'></div><div class='ui-popup-arrow-container"+(d?" ie":"")+"'><div class='ui-popup-arrow'></div></div>");a.widget("mobile.popup",a.mobile.popup,{options:{arrow:""},_create:function(){var a,b=this._super();return this.options.arrow&&(this._ui.arrow=a=this._addArrow()),b},_addArrow:function(){var a,b=this.options,d=c();return a=this._themeClassFromOption("ui-body-",b.theme),d.ar.addClass(a+(b.shadow?" ui-overlay-shadow":"")),d.arEls.hide().appendTo(this.element),d},_unenhance:function(){var a=this._ui.arrow;return a&&a.arEls.remove(),this._super()},_tryAnArrow:function(a,b,c,d,e){var f,g,h,i={},j={};return d.arFull[a.dimKey]>d.guideDims[a.dimKey]?e:(i[a.fst]=c[a.fst]+(d.arHalf[a.oDimKey]+d.menuHalf[a.oDimKey])*a.offsetFactor-d.contentBox[a.fst]+(d.clampInfo.menuSize[a.oDimKey]-d.contentBox[a.oDimKey])*a.arrowOffsetFactor,i[a.snd]=c[a.snd],f=d.result||this._calculateFinalLocation(i,d.clampInfo),g={x:f.left,y:f.top},j[a.fst]=g[a.fst]+d.contentBox[a.fst]+a.tipOffset,j[a.snd]=Math.max(f[a.prop]+d.guideOffset[a.prop]+d.arHalf[a.dimKey],Math.min(f[a.prop]+d.guideOffset[a.prop]+d.guideDims[a.dimKey]-d.arHalf[a.dimKey],c[a.snd])),h=Math.abs(c.x-j.x)+Math.abs(c.y-j.y),(!e||h<e.diff)&&(j[a.snd]-=d.arHalf[a.dimKey]+f[a.prop]+d.contentBox[a.snd],e={dir:b,diff:h,result:f,posProp:a.prop,posVal:j[a.snd]}),e)},_getPlacementState:function(a){var b,c,d=this._ui.arrow,e={clampInfo:this._clampPopupWidth(!a),arFull:{cx:d.ct.width(),cy:d.ct.height()},guideDims:{cx:d.gd.width(),cy:d.gd.height()},guideOffset:d.gd.offset()};return b=this.element.offset(),d.gd.css({left:0,top:0,right:0,bottom:0}),c=d.gd.offset(),e.contentBox={x:c.left-b.left,y:c.top-b.top,cx:d.gd.width(),cy:d.gd.height()},d.gd.removeAttr("style"),e.guideOffset={left:e.guideOffset.left-b.left,top:e.guideOffset.top-b.top},e.arHalf={cx:e.arFull.cx/2,cy:e.arFull.cy/2},e.menuHalf={cx:e.clampInfo.menuSize.cx/2,cy:e.clampInfo.menuSize.cy/2},e},_placementCoords:function(b){var c,e,f,g,h,i=this.options.arrow,j=this._ui.arrow;return j?(j.arEls.show(),h={},c=this._getPlacementState(!0),f={l:{fst:"x",snd:"y",prop:"top",dimKey:"cy",oDimKey:"cx",offsetFactor:1,tipOffset:-c.arHalf.cx,arrowOffsetFactor:0},r:{fst:"x",snd:"y",prop:"top",dimKey:"cy",oDimKey:"cx",offsetFactor:-1,tipOffset:c.arHalf.cx+c.contentBox.cx,arrowOffsetFactor:1},b:{fst:"y",snd:"x",prop:"left",dimKey:"cx",oDimKey:"cy",offsetFactor:-1,tipOffset:c.arHalf.cy+c.contentBox.cy,arrowOffsetFactor:1},t:{fst:"y",snd:"x",prop:"left",dimKey:"cx",oDimKey:"cy",offsetFactor:1,tipOffset:-c.arHalf.cy,arrowOffsetFactor:0}},a.each((i===!0?"l,t,r,b":i).split(","),a.proxy(function(a,d){e=this._tryAnArrow(f[d],d,b,c,e)},this)),e?(j.ct.removeClass("ui-popup-arrow-l ui-popup-arrow-t ui-popup-arrow-r ui-popup-arrow-b").addClass("ui-popup-arrow-"+e.dir).removeAttr("style").css(e.posProp,e.posVal).show(),d||(g=this.element.offset(),h[f[e.dir].fst]=j.ct.offset(),h[f[e.dir].snd]={left:g.left+c.contentBox.x,top:g.top+c.contentBox.y}),e.result):(j.arEls.hide(),this._super(b))):this._super(b)
},_setOptions:function(a){var c,d=this.options.theme,e=this._ui.arrow,f=this._super(a);if(a.arrow!==b){if(!e&&a.arrow)return void(this._ui.arrow=this._addArrow());e&&!a.arrow&&(e.arEls.remove(),this._ui.arrow=null)}return e=this._ui.arrow,e&&(a.theme!==b&&(d=this._themeClassFromOption("ui-body-",d),c=this._themeClassFromOption("ui-body-",a.theme),e.ar.removeClass(d).addClass(c)),a.shadow!==b&&e.ar.toggleClass("ui-overlay-shadow",a.shadow)),f},_destroy:function(){var a=this._ui.arrow;return a&&a.arEls.remove(),this._super()}})}(a),function(a,c){a.widget("mobile.panel",{options:{classes:{panel:"ui-panel",panelOpen:"ui-panel-open",panelClosed:"ui-panel-closed",panelFixed:"ui-panel-fixed",panelInner:"ui-panel-inner",modal:"ui-panel-dismiss",modalOpen:"ui-panel-dismiss-open",pageContainer:"ui-panel-page-container",pageWrapper:"ui-panel-wrapper",pageFixedToolbar:"ui-panel-fixed-toolbar",pageContentPrefix:"ui-panel-page-content",animate:"ui-panel-animate"},animate:!0,theme:null,position:"left",dismissible:!0,display:"reveal",swipeClose:!0,positionFixed:!1},_closeLink:null,_parentPage:null,_page:null,_modal:null,_panelInner:null,_wrapper:null,_fixedToolbars:null,_create:function(){var b=this.element,c=b.closest(".ui-page, :jqmData(role='page')");a.extend(this,{_closeLink:b.find(":jqmData(rel='close')"),_parentPage:c.length>0?c:!1,_openedPage:null,_page:this._getPage,_panelInner:this._getPanelInner(),_fixedToolbars:this._getFixedToolbars}),"overlay"!==this.options.display&&this._getWrapper(),this._addPanelClasses(),a.support.cssTransform3d&&this.options.animate&&this.element.addClass(this.options.classes.animate),this._bindUpdateLayout(),this._bindCloseEvents(),this._bindLinkListeners(),this._bindPageEvents(),this.options.dismissible&&this._createModal(),this._bindSwipeEvents()},_getPanelInner:function(){var a=this.element.find("."+this.options.classes.panelInner);return 0===a.length&&(a=this.element.children().wrapAll("<div class='"+this.options.classes.panelInner+"' />").parent()),a},_createModal:function(){var b=this,c=b._parentPage?b._parentPage.parent():b.element.parent();b._modal=a("<div class='"+b.options.classes.modal+"'></div>").on("mousedown",function(){b.close()}).appendTo(c)},_getPage:function(){var b=this._openedPage||this._parentPage||a("."+a.mobile.activePageClass);return b},_getWrapper:function(){var a=this._page().find("."+this.options.classes.pageWrapper);0===a.length&&(a=this._page().children(".ui-header:not(.ui-header-fixed), .ui-content:not(.ui-popup), .ui-footer:not(.ui-footer-fixed)").wrapAll("<div class='"+this.options.classes.pageWrapper+"'></div>").parent()),this._wrapper=a},_getFixedToolbars:function(){var b=a("body").children(".ui-header-fixed, .ui-footer-fixed"),c=this._page().find(".ui-header-fixed, .ui-footer-fixed"),d=b.add(c).addClass(this.options.classes.pageFixedToolbar);return d},_getPosDisplayClasses:function(a){return a+"-position-"+this.options.position+" "+a+"-display-"+this.options.display},_getPanelClasses:function(){var a=this.options.classes.panel+" "+this._getPosDisplayClasses(this.options.classes.panel)+" "+this.options.classes.panelClosed+" ui-body-"+(this.options.theme?this.options.theme:"inherit");return this.options.positionFixed&&(a+=" "+this.options.classes.panelFixed),a},_addPanelClasses:function(){this.element.addClass(this._getPanelClasses())},_handleCloseClickAndEatEvent:function(a){return a.isDefaultPrevented()?void 0:(a.preventDefault(),this.close(),!1)},_handleCloseClick:function(a){a.isDefaultPrevented()||this.close()},_bindCloseEvents:function(){this._on(this._closeLink,{click:"_handleCloseClick"}),this._on({"click a:jqmData(ajax='false')":"_handleCloseClick"})},_positionPanel:function(b){var c=this,d=c._panelInner.outerHeight(),e=d>a.mobile.getScreenHeight();e||!c.options.positionFixed?(e&&(c._unfixPanel(),a.mobile.resetActivePageHeight(d)),b&&this.window[0].scrollTo(0,a.mobile.defaultHomeScroll)):c._fixPanel()},_bindFixListener:function(){this._on(a(b),{throttledresize:"_positionPanel"})},_unbindFixListener:function(){this._off(a(b),"throttledresize")},_unfixPanel:function(){this.options.positionFixed&&a.support.fixedPosition&&this.element.removeClass(this.options.classes.panelFixed)},_fixPanel:function(){this.options.positionFixed&&a.support.fixedPosition&&this.element.addClass(this.options.classes.panelFixed)},_bindUpdateLayout:function(){var a=this;a.element.on("updatelayout",function(){a._open&&a._positionPanel()})},_bindLinkListeners:function(){this._on("body",{"click a":"_handleClick"})},_handleClick:function(b){var d,e=this.element.attr("id");return b.currentTarget.href.split("#")[1]===e&&e!==c?(b.preventDefault(),d=a(b.target),d.hasClass("ui-btn")&&(d.addClass(a.mobile.activeBtnClass),this.element.one("panelopen panelclose",function(){d.removeClass(a.mobile.activeBtnClass)})),this.toggle(),!1):void 0},_bindSwipeEvents:function(){var a=this,b=a._modal?a.element.add(a._modal):a.element;a.options.swipeClose&&("left"===a.options.position?b.on("swipeleft.panel",function(){a.close()}):b.on("swiperight.panel",function(){a.close()}))},_bindPageEvents:function(){var a=this;this.document.on("panelbeforeopen",function(b){a._open&&b.target!==a.element[0]&&a.close()}).on("keyup.panel",function(b){27===b.keyCode&&a._open&&a.close()}),this._parentPage||"overlay"===this.options.display||this._on(this.document,{pageshow:"_getWrapper"}),a._parentPage?this.document.on("pagehide",":jqmData(role='page')",function(){a._open&&a.close(!0)}):this.document.on("pagebeforehide",function(){a._open&&a.close(!0)})},_open:!1,_pageContentOpenClasses:null,_modalOpenClasses:null,open:function(b){if(!this._open){var c=this,d=c.options,e=function(){c.document.off("panelclose"),c._page().jqmData("panel","open"),a.support.cssTransform3d&&d.animate&&"overlay"!==d.display&&(c._wrapper.addClass(d.classes.animate),c._fixedToolbars().addClass(d.classes.animate)),!b&&a.support.cssTransform3d&&d.animate?c.element.animationComplete(f,"transition"):setTimeout(f,0),d.theme&&"overlay"!==d.display&&c._page().parent().addClass(d.classes.pageContainer+"-themed "+d.classes.pageContainer+"-"+d.theme),c.element.removeClass(d.classes.panelClosed).addClass(d.classes.panelOpen),c._positionPanel(!0),c._pageContentOpenClasses=c._getPosDisplayClasses(d.classes.pageContentPrefix),"overlay"!==d.display&&(c._page().parent().addClass(d.classes.pageContainer),c._wrapper.addClass(c._pageContentOpenClasses),c._fixedToolbars().addClass(c._pageContentOpenClasses)),c._modalOpenClasses=c._getPosDisplayClasses(d.classes.modal)+" "+d.classes.modalOpen,c._modal&&c._modal.addClass(c._modalOpenClasses).height(Math.max(c._modal.height(),c.document.height()))},f=function(){"overlay"!==d.display&&(c._wrapper.addClass(d.classes.pageContentPrefix+"-open"),c._fixedToolbars().addClass(d.classes.pageContentPrefix+"-open")),c._bindFixListener(),c._trigger("open"),c._openedPage=c._page()};c._trigger("beforeopen"),"open"===c._page().jqmData("panel")?c.document.on("panelclose",function(){e()}):e(),c._open=!0}},close:function(b){if(this._open){var c=this,d=this.options,e=function(){c.element.removeClass(d.classes.panelOpen),"overlay"!==d.display&&(c._wrapper.removeClass(c._pageContentOpenClasses),c._fixedToolbars().removeClass(c._pageContentOpenClasses)),!b&&a.support.cssTransform3d&&d.animate?c.element.animationComplete(f,"transition"):setTimeout(f,0),c._modal&&c._modal.removeClass(c._modalOpenClasses)},f=function(){d.theme&&"overlay"!==d.display&&c._page().parent().removeClass(d.classes.pageContainer+"-themed "+d.classes.pageContainer+"-"+d.theme),c.element.addClass(d.classes.panelClosed),"overlay"!==d.display&&(c._page().parent().removeClass(d.classes.pageContainer),c._wrapper.removeClass(d.classes.pageContentPrefix+"-open"),c._fixedToolbars().removeClass(d.classes.pageContentPrefix+"-open")),a.support.cssTransform3d&&d.animate&&"overlay"!==d.display&&(c._wrapper.removeClass(d.classes.animate),c._fixedToolbars().removeClass(d.classes.animate)),c._fixPanel(),c._unbindFixListener(),a.mobile.resetActivePageHeight(),c._page().jqmRemoveData("panel"),c._trigger("close"),c._openedPage=null};c._trigger("beforeclose"),e(),c._open=!1}},toggle:function(){this[this._open?"close":"open"]()},_destroy:function(){var b,c=this.options,d=a("body > :mobile-panel").length+a.mobile.activePage.find(":mobile-panel").length>1;"overlay"!==c.display&&(b=a("body > :mobile-panel").add(a.mobile.activePage.find(":mobile-panel")),0===b.not(".ui-panel-display-overlay").not(this.element).length&&this._wrapper.children().unwrap(),this._open&&(this._fixedToolbars().removeClass(c.classes.pageContentPrefix+"-open"),a.support.cssTransform3d&&c.animate&&this._fixedToolbars().removeClass(c.classes.animate),this._page().parent().removeClass(c.classes.pageContainer),c.theme&&this._page().parent().removeClass(c.classes.pageContainer+"-themed "+c.classes.pageContainer+"-"+c.theme))),d||this.document.off("panelopen panelclose"),this._open&&this._page().jqmRemoveData("panel"),this._panelInner.children().unwrap(),this.element.removeClass([this._getPanelClasses(),c.classes.panelOpen,c.classes.animate].join(" ")).off("swipeleft.panel swiperight.panel").off("panelbeforeopen").off("panelhide").off("keyup.panel").off("updatelayout"),this._modal&&this._modal.remove()}})}(a),function(a,b){a.widget("mobile.table",{options:{classes:{table:"ui-table"},enhanced:!1},_create:function(){this.options.enhanced||this.element.addClass(this.options.classes.table),a.extend(this,{headers:b,allHeaders:b}),this._refresh(!0)},_setHeaders:function(){var a=this.element.find("thead tr");this.headers=this.element.find("tr:eq(0)").children(),this.allHeaders=this.headers.add(a.children())},refresh:function(){this._refresh()},rebuild:a.noop,_refresh:function(){var b=this.element,c=b.find("thead tr");this._setHeaders(),c.each(function(){var d=0;a(this).children().each(function(){var e,f=parseInt(this.getAttribute("colspan"),10),g=":nth-child("+(d+1)+")";if(this.setAttribute("data-"+a.mobile.ns+"colstart",d+1),f)for(e=0;f-1>e;e++)d++,g+=", :nth-child("+(d+1)+")";a(this).jqmData("cells",b.find("tr").not(c.eq(0)).not(this).children(g)),d++})})}})}(a),function(a){a.widget("mobile.table",a.mobile.table,{options:{mode:"columntoggle",columnBtnTheme:null,columnPopupTheme:null,columnBtnText:"Columns...",classes:a.extend(a.mobile.table.prototype.options.classes,{popup:"ui-table-columntoggle-popup",columnBtn:"ui-table-columntoggle-btn",priorityPrefix:"ui-table-priority-",columnToggleTable:"ui-table-columntoggle"})},_create:function(){this._super(),"columntoggle"===this.options.mode&&(a.extend(this,{_menu:null}),this.options.enhanced?(this._menu=a(this.document[0].getElementById(this._id()+"-popup")).children().first(),this._addToggles(this._menu,!0)):(this._menu=this._enhanceColToggle(),this.element.addClass(this.options.classes.columnToggleTable)),this._setupEvents(),this._setToggleState())},_id:function(){return this.element.attr("id")||this.widgetName+this.uuid},_setupEvents:function(){this._on(this.window,{throttledresize:"_setToggleState"}),this._on(this._menu,{"change input":"_menuInputChange"})},_addToggles:function(b,c){var d,e=0,f=this.options,g=b.controlgroup("container");c?d=b.find("input"):g.empty(),this.headers.not("td").each(function(){var b=a(this),h=a.mobile.getAttribute(this,"priority"),i=b.add(b.jqmData("cells"));h&&(i.addClass(f.classes.priorityPrefix+h),(c?d.eq(e++):a("<label><input type='checkbox' checked />"+(b.children("abbr").first().attr("title")||b.text())+"</label>").appendTo(g).children(0).checkboxradio({theme:f.columnPopupTheme})).jqmData("cells",i))}),c||b.controlgroup("refresh")},_menuInputChange:function(b){var c=a(b.target),d=c[0].checked;c.jqmData("cells").toggleClass("ui-table-cell-hidden",!d).toggleClass("ui-table-cell-visible",d),c[0].getAttribute("locked")?(c.removeAttr("locked"),this._unlockCells(c.jqmData("cells"))):c.attr("locked",!0)},_unlockCells:function(a){a.removeClass("ui-table-cell-hidden ui-table-cell-visible")},_enhanceColToggle:function(){var b,c,d,e,f=this.element,g=this.options,h=a.mobile.ns,i=this.document[0].createDocumentFragment();return b=this._id()+"-popup",c=a("<a href='#"+b+"' class='"+g.classes.columnBtn+" ui-btn ui-btn-"+(g.columnBtnTheme||"a")+" ui-corner-all ui-shadow ui-mini' data-"+h+"rel='popup'>"+g.columnBtnText+"</a>"),d=a("<div class='"+g.classes.popup+"' id='"+b+"'></div>"),e=a("<fieldset></fieldset>").controlgroup(),this._addToggles(e,!1),e.appendTo(d),i.appendChild(d[0]),i.appendChild(c[0]),f.before(i),d.popup(),e},rebuild:function(){this._super(),"columntoggle"===this.options.mode&&this._refresh(!1)},_refresh:function(a){this._super(a),a||"columntoggle"!==this.options.mode||(this._unlockCells(this.element.find(".ui-table-cell-hidden, .ui-table-cell-visible")),this._addToggles(this._menu,a),this._setToggleState())},_setToggleState:function(){this._menu.find("input").each(function(){var b=a(this);this.checked="table-cell"===b.jqmData("cells").eq(0).css("display"),b.checkboxradio("refresh")})},_destroy:function(){this._super()}})}(a),function(a){a.widget("mobile.table",a.mobile.table,{options:{mode:"reflow",classes:a.extend(a.mobile.table.prototype.options.classes,{reflowTable:"ui-table-reflow",cellLabels:"ui-table-cell-label"})},_create:function(){this._super(),"reflow"===this.options.mode&&(this.options.enhanced||(this.element.addClass(this.options.classes.reflowTable),this._updateReflow()))},rebuild:function(){this._super(),"reflow"===this.options.mode&&this._refresh(!1)},_refresh:function(a){this._super(a),a||"reflow"!==this.options.mode||this._updateReflow()},_updateReflow:function(){var b=this,c=this.options;a(b.allHeaders.get().reverse()).each(function(){var d,e,f=a(this).jqmData("cells"),g=a.mobile.getAttribute(this,"colstart"),h=f.not(this).filter("thead th").length&&" ui-table-cell-label-top",i=a(this).text();""!==i&&(h?(d=parseInt(this.getAttribute("colspan"),10),e="",d&&(e="td:nth-child("+d+"n + "+g+")"),b._addLabels(f.filter(e),c.classes.cellLabels+h,i)):b._addLabels(f,c.classes.cellLabels,i))})},_addLabels:function(a,b,c){a.not(":has(b."+b+")").prepend("<b class='"+b+"'>"+c+"</b>")}})}(a),function(a,c){var d=function(b,c){return-1===(""+(a.mobile.getAttribute(this,"filtertext")||a(this).text())).toLowerCase().indexOf(c)};a.widget("mobile.filterable",{initSelector:":jqmData(filter='true')",options:{filterReveal:!1,filterCallback:d,enhanced:!1,input:null,children:"> li, > option, > optgroup option, > tbody tr, > .ui-controlgroup-controls > .ui-btn, > .ui-controlgroup-controls > .ui-checkbox, > .ui-controlgroup-controls > .ui-radio"},_create:function(){var b=this.options;a.extend(this,{_search:null,_timer:0}),this._setInput(b.input),b.enhanced||this._filterItems((this._search&&this._search.val()||"").toLowerCase())},_onKeyUp:function(){var c,d,e=this._search;if(e){if(c=e.val().toLowerCase(),d=a.mobile.getAttribute(e[0],"lastval")+"",d&&d===c)return;this._timer&&(b.clearTimeout(this._timer),this._timer=0),this._timer=this._delay(function(){this._trigger("beforefilter",null,{input:e}),e[0].setAttribute("data-"+a.mobile.ns+"lastval",c),this._filterItems(c),this._timer=0},250)}},_getFilterableItems:function(){var b=this.element,c=this.options.children,d=c?a.isFunction(c)?c():c.nodeName?a(c):c.jquery?c:this.element.find(c):{length:0};return 0===d.length&&(d=b.children()),d},_filterItems:function(b){var c,e,f,g,h=[],i=[],j=this.options,k=this._getFilterableItems();if(null!=b)for(e=j.filterCallback||d,f=k.length,c=0;f>c;c++)g=e.call(k[c],c,b)?i:h,g.push(k[c]);0===i.length?k[j.filterReveal?"addClass":"removeClass"]("ui-screen-hidden"):(a(i).addClass("ui-screen-hidden"),a(h).removeClass("ui-screen-hidden")),this._refreshChildWidget(),this._trigger("filter",null,{items:k})},_refreshChildWidget:function(){var b,c,d=["collapsibleset","selectmenu","controlgroup","listview"];for(c=d.length-1;c>-1;c--)b=d[c],a.mobile[b]&&(b=this.element.data("mobile-"+b),b&&a.isFunction(b.refresh)&&b.refresh())},_setInput:function(c){var d=this._search;this._timer&&(b.clearTimeout(this._timer),this._timer=0),d&&(this._off(d,"keyup change input"),d=null),c&&(d=c.jquery?c:c.nodeName?a(c):this.document.find(c),this._on(d,{keyup:"_onKeyUp",change:"_onKeyUp",input:"_onKeyUp"})),this._search=d},_setOptions:function(a){var b=!(a.filterReveal===c&&a.filterCallback===c&&a.children===c);this._super(a),a.input!==c&&(this._setInput(a.input),b=!0),b&&this.refresh()},_destroy:function(){var a=this.options,b=this._getFilterableItems();a.enhanced?b.toggleClass("ui-screen-hidden",a.filterReveal):b.removeClass("ui-screen-hidden")},refresh:function(){this._timer&&(b.clearTimeout(this._timer),this._timer=0),this._filterItems((this._search&&this._search.val()||"").toLowerCase())}})}(a),function(a,b){var c=function(a,b){return function(c){b.call(this,c),a._syncTextInputOptions(c)}},d=/(^|\s)ui-li-divider(\s|$)/,e=a.mobile.filterable.prototype.options.filterCallback;a.mobile.filterable.prototype.options.filterCallback=function(a,b){return!this.className.match(d)&&e.call(this,a,b)},a.widget("mobile.filterable",a.mobile.filterable,{options:{filterPlaceholder:"Filter items...",filterTheme:null},_create:function(){var b,c,d=this.element,e=["collapsibleset","selectmenu","controlgroup","listview"],f={};for(this._super(),a.extend(this,{_widget:null}),b=e.length-1;b>-1;b--)if(c=e[b],a.mobile[c]){if(this._setWidget(d.data("mobile-"+c)))break;f[c+"create"]="_handleCreate"}this._widget||this._on(d,f)},_handleCreate:function(a){this._setWidget(this.element.data("mobile-"+a.type.substring(0,a.type.length-6)))},_trigger:function(a,b,c){this._widget&&"mobile-listview"===this._widget.widgetFullName&&"beforefilter"===a&&this._widget._trigger("beforefilter",b,c),this._super(a,b,c)},_setWidget:function(a){return!this._widget&&a&&(this._widget=a,this._widget._setOptions=c(this,this._widget._setOptions)),this._widget&&(this._syncTextInputOptions(this._widget.options),"listview"===this._widget.widgetName&&(this._widget.options.hideDividers=!0,this._widget.element.listview("refresh"))),!!this._widget},_isSearchInternal:function(){return this._search&&this._search.jqmData("ui-filterable-"+this.uuid+"-internal")},_setInput:function(b){var c=this.options,d=!0,e={};if(!b){if(this._isSearchInternal())return;d=!1,b=a("<input data-"+a.mobile.ns+"type='search' placeholder='"+c.filterPlaceholder+"'></input>").jqmData("ui-filterable-"+this.uuid+"-internal",!0),a("<form class='ui-filterable'></form>").append(b).submit(function(a){a.preventDefault(),b.blur()}).insertBefore(this.element),a.mobile.textinput&&(null!=this.options.filterTheme&&(e.theme=c.filterTheme),b.textinput(e))}this._super(b),this._isSearchInternal()&&d&&this._search.attr("placeholder",this.options.filterPlaceholder)},_setOptions:function(c){var d=this._super(c);return c.filterPlaceholder!==b&&this._isSearchInternal()&&this._search.attr("placeholder",c.filterPlaceholder),c.filterTheme!==b&&this._search&&a.mobile.textinput&&this._search.textinput("option","theme",c.filterTheme),d},_destroy:function(){this._isSearchInternal()&&this._search.remove(),this._super()},_syncTextInputOptions:function(c){var d,e={};if(this._isSearchInternal()&&a.mobile.textinput){for(d in a.mobile.textinput.prototype.options)c[d]!==b&&(e[d]="theme"===d&&null!=this.options.filterTheme?this.options.filterTheme:c[d]);this._search.textinput("option",e)}}})}(a),function(a,b){function c(){return++e}function d(a){return a.hash.length>1&&decodeURIComponent(a.href.replace(f,""))===decodeURIComponent(location.href.replace(f,""))}var e=0,f=/#.*$/;a.widget("ui.tabs",{version:"fadf2b312a05040436451c64bbfaf4814bc62c56",delay:300,options:{active:null,collapsible:!1,event:"click",heightStyle:"content",hide:null,show:null,activate:null,beforeActivate:null,beforeLoad:null,load:null},_create:function(){var b=this,c=this.options;this.running=!1,this.element.addClass("ui-tabs ui-widget ui-widget-content ui-corner-all").toggleClass("ui-tabs-collapsible",c.collapsible).delegate(".ui-tabs-nav > li","mousedown"+this.eventNamespace,function(b){a(this).is(".ui-state-disabled")&&b.preventDefault()}).delegate(".ui-tabs-anchor","focus"+this.eventNamespace,function(){a(this).closest("li").is(".ui-state-disabled")&&this.blur()}),this._processTabs(),c.active=this._initialActive(),a.isArray(c.disabled)&&(c.disabled=a.unique(c.disabled.concat(a.map(this.tabs.filter(".ui-state-disabled"),function(a){return b.tabs.index(a)}))).sort()),this.active=this.options.active!==!1&&this.anchors.length?this._findActive(c.active):a(),this._refresh(),this.active.length&&this.load(c.active)},_initialActive:function(){var b=this.options.active,c=this.options.collapsible,d=location.hash.substring(1);return null===b&&(d&&this.tabs.each(function(c,e){return a(e).attr("aria-controls")===d?(b=c,!1):void 0}),null===b&&(b=this.tabs.index(this.tabs.filter(".ui-tabs-active"))),(null===b||-1===b)&&(b=this.tabs.length?0:!1)),b!==!1&&(b=this.tabs.index(this.tabs.eq(b)),-1===b&&(b=c?!1:0)),!c&&b===!1&&this.anchors.length&&(b=0),b},_getCreateEventData:function(){return{tab:this.active,panel:this.active.length?this._getPanelForTab(this.active):a()}},_tabKeydown:function(b){var c=a(this.document[0].activeElement).closest("li"),d=this.tabs.index(c),e=!0;if(!this._handlePageNav(b)){switch(b.keyCode){case a.ui.keyCode.RIGHT:case a.ui.keyCode.DOWN:d++;break;case a.ui.keyCode.UP:case a.ui.keyCode.LEFT:e=!1,d--;break;case a.ui.keyCode.END:d=this.anchors.length-1;break;case a.ui.keyCode.HOME:d=0;break;case a.ui.keyCode.SPACE:return b.preventDefault(),clearTimeout(this.activating),void this._activate(d);case a.ui.keyCode.ENTER:return b.preventDefault(),clearTimeout(this.activating),void this._activate(d===this.options.active?!1:d);default:return}b.preventDefault(),clearTimeout(this.activating),d=this._focusNextTab(d,e),b.ctrlKey||(c.attr("aria-selected","false"),this.tabs.eq(d).attr("aria-selected","true"),this.activating=this._delay(function(){this.option("active",d)},this.delay))}},_panelKeydown:function(b){this._handlePageNav(b)||b.ctrlKey&&b.keyCode===a.ui.keyCode.UP&&(b.preventDefault(),this.active.focus())},_handlePageNav:function(b){return b.altKey&&b.keyCode===a.ui.keyCode.PAGE_UP?(this._activate(this._focusNextTab(this.options.active-1,!1)),!0):b.altKey&&b.keyCode===a.ui.keyCode.PAGE_DOWN?(this._activate(this._focusNextTab(this.options.active+1,!0)),!0):void 0},_findNextTab:function(b,c){function d(){return b>e&&(b=0),0>b&&(b=e),b}for(var e=this.tabs.length-1;-1!==a.inArray(d(),this.options.disabled);)b=c?b+1:b-1;return b},_focusNextTab:function(a,b){return a=this._findNextTab(a,b),this.tabs.eq(a).focus(),a},_setOption:function(a,b){return"active"===a?void this._activate(b):"disabled"===a?void this._setupDisabled(b):(this._super(a,b),"collapsible"===a&&(this.element.toggleClass("ui-tabs-collapsible",b),b||this.options.active!==!1||this._activate(0)),"event"===a&&this._setupEvents(b),void("heightStyle"===a&&this._setupHeightStyle(b)))},_tabId:function(a){return a.attr("aria-controls")||"ui-tabs-"+c()},_sanitizeSelector:function(a){return a?a.replace(/[!"$%&'()*+,.\/:;<=>?@\[\]\^`{|}~]/g,"\\$&"):""},refresh:function(){var b=this.options,c=this.tablist.children(":has(a[href])");b.disabled=a.map(c.filter(".ui-state-disabled"),function(a){return c.index(a)}),this._processTabs(),b.active!==!1&&this.anchors.length?this.active.length&&!a.contains(this.tablist[0],this.active[0])?this.tabs.length===b.disabled.length?(b.active=!1,this.active=a()):this._activate(this._findNextTab(Math.max(0,b.active-1),!1)):b.active=this.tabs.index(this.active):(b.active=!1,this.active=a()),this._refresh()},_refresh:function(){this._setupDisabled(this.options.disabled),this._setupEvents(this.options.event),this._setupHeightStyle(this.options.heightStyle),this.tabs.not(this.active).attr({"aria-selected":"false",tabIndex:-1}),this.panels.not(this._getPanelForTab(this.active)).hide().attr({"aria-expanded":"false","aria-hidden":"true"}),this.active.length?(this.active.addClass("ui-tabs-active ui-state-active").attr({"aria-selected":"true",tabIndex:0}),this._getPanelForTab(this.active).show().attr({"aria-expanded":"true","aria-hidden":"false"})):this.tabs.eq(0).attr("tabIndex",0)},_processTabs:function(){var b=this;this.tablist=this._getList().addClass("ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all").attr("role","tablist"),this.tabs=this.tablist.find("> li:has(a[href])").addClass("ui-state-default ui-corner-top").attr({role:"tab",tabIndex:-1}),this.anchors=this.tabs.map(function(){return a("a",this)[0]}).addClass("ui-tabs-anchor").attr({role:"presentation",tabIndex:-1}),this.panels=a(),this.anchors.each(function(c,e){var f,g,h,i=a(e).uniqueId().attr("id"),j=a(e).closest("li"),k=j.attr("aria-controls");d(e)?(f=e.hash,g=b.element.find(b._sanitizeSelector(f))):(h=b._tabId(j),f="#"+h,g=b.element.find(f),g.length||(g=b._createPanel(h),g.insertAfter(b.panels[c-1]||b.tablist)),g.attr("aria-live","polite")),g.length&&(b.panels=b.panels.add(g)),k&&j.data("ui-tabs-aria-controls",k),j.attr({"aria-controls":f.substring(1),"aria-labelledby":i}),g.attr("aria-labelledby",i)}),this.panels.addClass("ui-tabs-panel ui-widget-content ui-corner-bottom").attr("role","tabpanel")},_getList:function(){return this.element.find("ol,ul").eq(0)},_createPanel:function(b){return a("<div>").attr("id",b).addClass("ui-tabs-panel ui-widget-content ui-corner-bottom").data("ui-tabs-destroy",!0)},_setupDisabled:function(b){a.isArray(b)&&(b.length?b.length===this.anchors.length&&(b=!0):b=!1);for(var c,d=0;c=this.tabs[d];d++)b===!0||-1!==a.inArray(d,b)?a(c).addClass("ui-state-disabled").attr("aria-disabled","true"):a(c).removeClass("ui-state-disabled").removeAttr("aria-disabled");this.options.disabled=b},_setupEvents:function(b){var c={click:function(a){a.preventDefault()}};b&&a.each(b.split(" "),function(a,b){c[b]="_eventHandler"}),this._off(this.anchors.add(this.tabs).add(this.panels)),this._on(this.anchors,c),this._on(this.tabs,{keydown:"_tabKeydown"}),this._on(this.panels,{keydown:"_panelKeydown"}),this._focusable(this.tabs),this._hoverable(this.tabs)},_setupHeightStyle:function(b){var c,d=this.element.parent();"fill"===b?(c=d.height(),c-=this.element.outerHeight()-this.element.height(),this.element.siblings(":visible").each(function(){var b=a(this),d=b.css("position");"absolute"!==d&&"fixed"!==d&&(c-=b.outerHeight(!0))}),this.element.children().not(this.panels).each(function(){c-=a(this).outerHeight(!0)}),this.panels.each(function(){a(this).height(Math.max(0,c-a(this).innerHeight()+a(this).height()))}).css("overflow","auto")):"auto"===b&&(c=0,this.panels.each(function(){c=Math.max(c,a(this).height("").height())}).height(c))},_eventHandler:function(b){var c=this.options,d=this.active,e=a(b.currentTarget),f=e.closest("li"),g=f[0]===d[0],h=g&&c.collapsible,i=h?a():this._getPanelForTab(f),j=d.length?this._getPanelForTab(d):a(),k={oldTab:d,oldPanel:j,newTab:h?a():f,newPanel:i};b.preventDefault(),f.hasClass("ui-state-disabled")||f.hasClass("ui-tabs-loading")||this.running||g&&!c.collapsible||this._trigger("beforeActivate",b,k)===!1||(c.active=h?!1:this.tabs.index(f),this.active=g?a():f,this.xhr&&this.xhr.abort(),j.length||i.length||a.error("jQuery UI Tabs: Mismatching fragment identifier."),i.length&&this.load(this.tabs.index(f),b),this._toggle(b,k))},_toggle:function(b,c){function d(){f.running=!1,f._trigger("activate",b,c)}function e(){c.newTab.closest("li").addClass("ui-tabs-active ui-state-active"),g.length&&f.options.show?f._show(g,f.options.show,d):(g.show(),d())}var f=this,g=c.newPanel,h=c.oldPanel;this.running=!0,h.length&&this.options.hide?this._hide(h,this.options.hide,function(){c.oldTab.closest("li").removeClass("ui-tabs-active ui-state-active"),e()}):(c.oldTab.closest("li").removeClass("ui-tabs-active ui-state-active"),h.hide(),e()),h.attr({"aria-expanded":"false","aria-hidden":"true"}),c.oldTab.attr("aria-selected","false"),g.length&&h.length?c.oldTab.attr("tabIndex",-1):g.length&&this.tabs.filter(function(){return 0===a(this).attr("tabIndex")}).attr("tabIndex",-1),g.attr({"aria-expanded":"true","aria-hidden":"false"}),c.newTab.attr({"aria-selected":"true",tabIndex:0})},_activate:function(b){var c,d=this._findActive(b);d[0]!==this.active[0]&&(d.length||(d=this.active),c=d.find(".ui-tabs-anchor")[0],this._eventHandler({target:c,currentTarget:c,preventDefault:a.noop}))},_findActive:function(b){return b===!1?a():this.tabs.eq(b)},_getIndex:function(a){return"string"==typeof a&&(a=this.anchors.index(this.anchors.filter("[href$='"+a+"']"))),a},_destroy:function(){this.xhr&&this.xhr.abort(),this.element.removeClass("ui-tabs ui-widget ui-widget-content ui-corner-all ui-tabs-collapsible"),this.tablist.removeClass("ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all").removeAttr("role"),this.anchors.removeClass("ui-tabs-anchor").removeAttr("role").removeAttr("tabIndex").removeUniqueId(),this.tabs.add(this.panels).each(function(){a.data(this,"ui-tabs-destroy")?a(this).remove():a(this).removeClass("ui-state-default ui-state-active ui-state-disabled ui-corner-top ui-corner-bottom ui-widget-content ui-tabs-active ui-tabs-panel").removeAttr("tabIndex").removeAttr("aria-live").removeAttr("aria-busy").removeAttr("aria-selected").removeAttr("aria-labelledby").removeAttr("aria-hidden").removeAttr("aria-expanded").removeAttr("role")}),this.tabs.each(function(){var b=a(this),c=b.data("ui-tabs-aria-controls");c?b.attr("aria-controls",c).removeData("ui-tabs-aria-controls"):b.removeAttr("aria-controls")}),this.panels.show(),"content"!==this.options.heightStyle&&this.panels.css("height","")},enable:function(c){var d=this.options.disabled;d!==!1&&(c===b?d=!1:(c=this._getIndex(c),d=a.isArray(d)?a.map(d,function(a){return a!==c?a:null}):a.map(this.tabs,function(a,b){return b!==c?b:null})),this._setupDisabled(d))},disable:function(c){var d=this.options.disabled;if(d!==!0){if(c===b)d=!0;else{if(c=this._getIndex(c),-1!==a.inArray(c,d))return;d=a.isArray(d)?a.merge([c],d).sort():[c]}this._setupDisabled(d)}},load:function(b,c){b=this._getIndex(b);var e=this,f=this.tabs.eq(b),g=f.find(".ui-tabs-anchor"),h=this._getPanelForTab(f),i={tab:f,panel:h};d(g[0])||(this.xhr=a.ajax(this._ajaxSettings(g,c,i)),this.xhr&&"canceled"!==this.xhr.statusText&&(f.addClass("ui-tabs-loading"),h.attr("aria-busy","true"),this.xhr.success(function(a){setTimeout(function(){h.html(a),e._trigger("load",c,i)},1)}).complete(function(a,b){setTimeout(function(){"abort"===b&&e.panels.stop(!1,!0),f.removeClass("ui-tabs-loading"),h.removeAttr("aria-busy"),a===e.xhr&&delete e.xhr},1)})))},_ajaxSettings:function(b,c,d){var e=this;return{url:b.attr("href"),beforeSend:function(b,f){return e._trigger("beforeLoad",c,a.extend({jqXHR:b,ajaxSettings:f},d))}}},_getPanelForTab:function(b){var c=a(b).attr("aria-controls");return this.element.find(this._sanitizeSelector("#"+c))}})}(a),function(){}(a),function(a,b){function c(a){e=a.originalEvent,i=e.accelerationIncludingGravity,f=Math.abs(i.x),g=Math.abs(i.y),h=Math.abs(i.z),!b.orientation&&(f>7||(h>6&&8>g||8>h&&g>6)&&f>5)?d.enabled&&d.disable():d.enabled||d.enable()}a.mobile.iosorientationfixEnabled=!0;var d,e,f,g,h,i,j=navigator.userAgent;return/iPhone|iPad|iPod/.test(navigator.platform)&&/OS [1-5]_[0-9_]* like Mac OS X/i.test(j)&&j.indexOf("AppleWebKit")>-1?(d=a.mobile.zoom,void a.mobile.document.on("mobileinit",function(){a.mobile.iosorientationfixEnabled&&a.mobile.window.bind("orientationchange.iosorientationfix",d.enable).bind("devicemotion.iosorientationfix",c)})):void(a.mobile.iosorientationfixEnabled=!1)}(a,this),function(a,b){function d(){e.removeClass("ui-mobile-rendering")}var e=a("html"),f=a.mobile.window;a(b.document).trigger("mobileinit"),a.mobile.gradeA()&&(a.mobile.ajaxBlacklist&&(a.mobile.ajaxEnabled=!1),e.addClass("ui-mobile ui-mobile-rendering"),setTimeout(d,5e3),a.extend(a.mobile,{initializePage:function(){var b=a.mobile.path,e=a(":jqmData(role='page'), :jqmData(role='dialog')"),g=b.stripHash(b.stripQueryParams(b.parseLocation().hash)),h=c.getElementById(g);
e.length||(e=a("body").wrapInner("<div data-"+a.mobile.ns+"role='page'></div>").children(0)),e.each(function(){var b=a(this);b[0].getAttribute("data-"+a.mobile.ns+"url")||b.attr("data-"+a.mobile.ns+"url",b.attr("id")||location.pathname+location.search)}),a.mobile.firstPage=e.first(),a.mobile.pageContainer=a.mobile.firstPage.parent().addClass("ui-mobile-viewport").pagecontainer(),a.mobile.navreadyDeferred.resolve(),f.trigger("pagecontainercreate"),a.mobile.loading("show"),d(),a.mobile.hashListeningEnabled&&a.mobile.path.isHashValid(location.hash)&&(a(h).is(":jqmData(role='page')")||a.mobile.path.isPath(g)||g===a.mobile.dialogHashKey)?a.event.special.navigate.isPushStateEnabled()?(a.mobile.navigate.history.stack=[],a.mobile.navigate(a.mobile.path.isPath(location.hash)?location.hash:location.href)):f.trigger("hashchange",[!0]):(a.mobile.path.isHashValid(location.hash)&&(a.mobile.navigate.history.initialDst=g.replace("#","")),a.event.special.navigate.isPushStateEnabled()&&a.mobile.navigate.navigator.squash(b.parseLocation().href),a.mobile.changePage(a.mobile.firstPage,{transition:"none",reverse:!0,changeHash:!1,fromHashChange:!0}))}}),a(function(){a.support.inlineSVG(),a.mobile.hideUrlBar&&b.scrollTo(0,1),a.mobile.defaultHomeScroll=a.support.scrollTop&&1!==a.mobile.window.scrollTop()?1:0,a.mobile.autoInitializePage&&a.mobile.initializePage(),a.mobile.hideUrlBar&&f.load(a.mobile.silentScroll),a.support.cssPointerEvents||a.mobile.document.delegate(".ui-state-disabled,.ui-disabled","vclick",function(a){a.preventDefault(),a.stopImmediatePropagation()})}))}(a,this)});
//# sourceMappingURL=jquery.mobile-1.4.2.min.map | zettwerk.mobile | /zettwerk.mobile-0.2.1.zip/zettwerk.mobile-0.2.1/zettwerk/mobile/static/jquery.mobile-1.4.2/demos/js/jquery.mobile-1.4.2.min.js | jquery.mobile-1.4.2.min.js |
$( document ).one( "pagecreate", ".demo-page", function() {
// Initialize the external persistent header and footer
$( "#header" ).toolbar({ theme: "b" });
$( "#footer" ).toolbar({ theme: "b" });
// Handler for navigating to the next page
function navnext( next ) {
$( ":mobile-pagecontainer" ).pagecontainer( "change", next + ".html", {
transition: "slide"
});
}
// Handler for navigating to the previous page
function navprev( prev ) {
$( ":mobile-pagecontainer" ).pagecontainer( "change", prev + ".html", {
transition: "slide",
reverse: true
});
}
// Navigate to the next page on swipeleft
$( document ).on( "swipeleft", ".ui-page", function( event ) {
// Get the filename of the next page. We stored that in the data-next
// attribute in the original markup.
var next = $( this ).jqmData( "next" );
// Check if there is a next page and
// swipes may also happen when the user highlights text, so ignore those.
// We're only interested in swipes on the page.
if ( next && ( event.target === $( this )[ 0 ] ) ) {
navnext( next );
}
});
// Navigate to the next page when the "next" button in the footer is clicked
$( document ).on( "click", ".next", function() {
var next = $( ".ui-page-active" ).jqmData( "next" );
// Check if there is a next page
if ( next ) {
navnext( next );
}
});
// The same for the navigating to the previous page
$( document ).on( "swiperight", ".ui-page", function( event ) {
var prev = $( this ).jqmData( "prev" );
if ( prev && ( event.target === $( this )[ 0 ] ) ) {
navprev( prev );
}
});
$( document ).on( "click", ".prev", function() {
var prev = $( ".ui-page-active" ).jqmData( "prev" );
if ( prev ) {
navprev( prev );
}
});
});
$( document ).on( "pageshow", ".demo-page", function() {
var thePage = $( this ),
title = thePage.jqmData( "title" ),
next = thePage.jqmData( "next" ),
prev = thePage.jqmData( "prev" );
// Point the "Trivia" button to the popup for the current page.
$( "#trivia-button" ).attr( "href", "#" + thePage.find( ".trivia" ).attr( "id" ) );
// We use the same header on each page
// so we have to update the title
$( "#header h1" ).text( title );
// Prefetch the next page
// We added data-dom-cache="true" to the page so it won't be deleted
// so there is no need to prefetch it
if ( next ) {
$( ":mobile-pagecontainer" ).pagecontainer( "load", next + ".html" );
}
// We disable the next or previous buttons in the footer
// if there is no next or previous page
// We use the same footer on each page
// so first we remove the disabled class if it is there
$( ".next.ui-state-disabled, .prev.ui-state-disabled" ).removeClass( "ui-state-disabled" );
if ( ! next ) {
$( ".next" ).addClass( "ui-state-disabled" );
}
if ( ! prev ) {
$( ".prev" ).addClass( "ui-state-disabled" );
}
}); | zettwerk.mobile | /zettwerk.mobile-0.2.1.zip/zettwerk.mobile-0.2.1/zettwerk/mobile/static/jquery.mobile-1.4.2/demos/swipe-page/swipe-page.js | swipe-page.js |
zettwerk.mobiletheming
======================
Switching mobile themes based on urls
Usage
=====
Install zettwerk.mobiletheming via quickinstaller.
A new control panel entry makes it possible to change settings.
Enter the hostnames on which the mobile theme should be applied.
Choose the diazo theme to use for selected URL.
There is also some settings for "redirecting urls", it works like this:
1) A javascript is installed in portal_javascript
2) This javascript redirects urls to the url set in the control panel.
3) Redirects works for mobile devices.
4) You can choose if you want to redirect iPads and tablets, too.
5) There is a setting
See this example with the zettwerk.mobile theme: https://www.youtube.com/watch?v=Q2ID86XkiQQ
Generic Setup
=============
This product also provides a GenericSetup extension for integrators to set these settings via a xml profile file. Place the file "mobiletheming.xml" in your (default) generic setup profile and change it as you need. You can also export your current settings via portal_setup -> Export. The export step is called "Mobiletheming Settings".
Example content, taken from `zettwerk.mobile <https://github.com/collective/zettwerk.mobile/tree/master/zettwerk/mobile/profiles/default/mobiletheming.xml>`_::
<?xml version="1.0"?>
<settings>
<themename>zettwerk.mobile</themename>
<hostnames>
<element>http://localhost:8080</element>
</hostnames>
<ipad>False</ipad>
<tablets>False</tablets>
</settings>
| zettwerk.mobiletheming | /zettwerk.mobiletheming-0.2.1.zip/zettwerk.mobiletheming-0.2.1/README.txt | README.txt |
from plone.app.theming.transform import ThemeTransform
from zope.component import queryUtility
from zope.component import getUtility
from plone.app.theming.interfaces import IThemeSettings
from plone.app.theming.utils import getAvailableThemes
from plone.app.theming.utils import compileThemeTransform
from plone.app.theming.utils import prepareThemeParameters
from plone.app.theming.utils import findContext
from plone.app.theming.transform import _Cache
from plone.registry.interfaces import IRegistry
class MobileThemeTransform(ThemeTransform):
order = 8850
def _getActive(self):
""" check if the mobile theming for this url is active """
active = False
registry = getUtility(IRegistry)
base1 = self.request.get('BASE1')
_xx_, base1 = base1.split('://', 1)
host = base1.lower()
hostnames = registry[
'zettwerk.mobiletheming.interfaces.IMobileThemingSettings' \
'.hostnames'
]
if hostnames:
for hostname in hostnames or ():
if host == hostname or \
hostname == "http://%s" % (host):
active = True
return active
def transformIterable(self, result, encoding):
"""Apply the transform if required
"""
active = self._getActive()
registry = getUtility(IRegistry)
themename = registry[
'zettwerk.mobiletheming.interfaces.IMobileThemingSettings' \
'.themename'
]
availableThemes = getAvailableThemes()
mobile = None
for item in availableThemes:
if item.__name__ == themename:
mobile = item
active = active and True
if not active or mobile is None:
## return the default theme
result = super(MobileThemeTransform, self) \
.transformIterable(result, encoding)
return result
registry = queryUtility(IRegistry)
settings = registry.forInterface(IThemeSettings, False)
class S(object):
rules = mobile.rules
doctype = settings.doctype
absolutePrefix = settings.absolutePrefix
readNetwork = settings.readNetwork
parameterExpressions = settings.parameterExpressions
fake_settings = S()
return self.transformIterableWithSettings(result, encoding,
fake_settings)
def transformIterableWithSettings(self, result, encoding, settings):
""" """
result = self.parseTree(result)
if result is None:
return None
if settings.doctype:
result.doctype = settings.doctype
if not result.doctype.endswith('\n'):
result.doctype += '\n'
transform = compileThemeTransform(settings.rules,
settings.absolutePrefix,
settings.readNetwork,
settings.parameterExpressions)
if transform is None:
return None
cache = _Cache()
parameterExpressions = settings.parameterExpressions or {}
params = prepareThemeParameters(findContext(self.request),
self.request,
parameterExpressions,
cache)
transformed = transform(result.tree, **params)
if transformed is not None:
# Transformed worked, swap content with result
result.tree = transformed
return result | zettwerk.mobiletheming | /zettwerk.mobiletheming-0.2.1.zip/zettwerk.mobiletheming-0.2.1/src/zettwerk/mobiletheming/transform.py | transform.py |
from lxml import etree
from zope.component import getUtility
from plone.registry.interfaces import IRegistry
from zettwerk.mobiletheming.interfaces import IMobileThemingSettings
def importSettings(context):
""" import the settings """
data = context.readDataFile('mobiletheming.xml')
if not data:
return
settings = getUtility(IRegistry) \
.forInterface(IMobileThemingSettings, False)
tree = etree.fromstring(data)
themename = tree.find('themename')
if themename is not None:
value = themename.text.strip()
## todo: skip unavailable themes
settings.themename = value
hostnames = tree.find('hostnames')
if hostnames is not None:
values = []
for element in hostnames.findall('element'):
values.append(element.text.strip())
settings.hostnames = tuple(values)
ipad = tree.find('ipad')
if ipad is not None:
value = ipad.text.strip()
if value.lower() in ("y", "yes", "true", "t", "1", "on",):
settings.ipad = True
elif value.lower() in ("n", "no", "false", "f", "0", "off",):
settings.ipad = False
else:
raise ValueError("%s is not a valid value for <ipad />" % value)
tablets = tree.find('tablets')
if tablets is not None:
value = tablets.text.strip()
if value.lower() in ("y", "yes", "true", "t", "1", "on",):
settings.tablets = True
elif value.lower() in ("n", "no", "false", "f", "0", "off",):
settings.tablets = False
else:
raise ValueError("%s is not a valid value for <tablets />" % value)
def exportSettings(context):
""" export the settings """
settings = getUtility(IRegistry) \
.forInterface(IMobileThemingSettings, False)
filename = 'mobiletheming.xml'
root = etree.Element('settings')
themename = etree.SubElement(root, 'themename')
themename.text = settings.themename
hostnames = etree.SubElement(root, 'hostnames')
for hostname in settings.hostnames:
entry = etree.SubElement(hostnames, 'element')
entry.text = hostname
ipad = etree.SubElement(root, 'ipad')
ipad.text = unicode(settings.ipad)
tablets = etree.SubElement(root, 'tablets')
tablets.text = unicode(settings.tablets)
body = '<?xml version="1.0"?>\n' + etree.tostring(root, pretty_print=True)
context.writeDataFile(filename, body, 'text/xml') | zettwerk.mobiletheming | /zettwerk.mobiletheming-0.2.1.zip/zettwerk.mobiletheming-0.2.1/src/zettwerk/mobiletheming/genericsetup.py | genericsetup.py |
from Products.Five.browser import BrowserView
from zope.component import getUtility
from zope.component import getMultiAdapter
from plone.registry.interfaces import IRegistry
from urlparse import urlparse
class MobRedirected(BrowserView):
def __call__(self, request=None, ref='', url=''):
""" Sends the user to the same page they were at before going to mobile
site."""
refpage = urlparse(url)
redirect_to = refpage.path
if refpage.query:
redirect_to += ('?' + refpage.query)
return self.context.REQUEST.RESPONSE.redirect(redirect_to)
class JavaScript(BrowserView):
def __call__(self, request=None, response=None):
"""Returns configurations."""
self.registry = getUtility(IRegistry)
self.request.response.setHeader("Content-type", "text/javascript")
## only return the redirect stuff, if the mobile theming
## is _not_ active for this url
active = getMultiAdapter((request.get('PUBLISHED', None), request),
name='zettwerk_mobiletheming_transform') \
._getActive()
hostname = self.hostname
force_path_and_query = ''
if self.fullurl and not active:
force_path_and_query += '/@@mobredirected/?url='
ref = urlparse(self.request.get_header("referer"))
force_path_and_query += ref.path
if ref.query:
force_path_and_query += '?'
force_path_and_query += ref.query
if not active and hostname:
script_url = '/++resource++zettwerk.mobiletheming.scripts' \
'/me.redirect.min.js'
return """\
var mobile_domain = "%(hostname)s";
var ipad = "%(ipad)s";
var other_tablets = "%(tablets)s";
var force_path_and_query = "%(force_path_and_query)s";
document.write(unescape("%%3Cscript """ \
""" src='%(script_url)s' """ \
""" type='text/javascript'%%3E%""" \
"""%3C/script%%3E"));""" % {
'hostname': hostname,
'ipad': self.ipad,
'tablets': self.tablets,
'force_path_and_query': force_path_and_query,
'script_url': script_url,
}
return ''
@property
def hostname(self):
registry = getUtility(IRegistry)
hostnames = registry[
'zettwerk.mobiletheming.interfaces.IMobileThemingSettings' \
'.hostnames'
]
if not hostnames:
return ''
first = hostnames[0]
parts = urlparse(first)
## two cases:
## 1. no rewritten url with port and plone instance
## 2. rewritten url without plone instance
## for both cases, no protocol (http/s) is needed
if parts.port:
## there is a port, so append the portal id
return '%s:%s/%s' % (
parts.hostname,
parts.port,
self.context.portal_url.getPortalObject().getId()
)
else:
return parts.hostname
@property
def tablets(self):
return self.registry[
'zettwerk.mobiletheming.interfaces.IMobileThemingSettings' \
'.tablets']
@property
def ipad(self):
return self.registry[
'zettwerk.mobiletheming.interfaces.IMobileThemingSettings' \
'.ipad']
@property
def fullurl(self):
return self.registry[
'zettwerk.mobiletheming.interfaces.IMobileThemingSettings' \
'.fullurl'] | zettwerk.mobiletheming | /zettwerk.mobiletheming-0.2.1.zip/zettwerk.mobiletheming-0.2.1/src/zettwerk/mobiletheming/browser/view.py | view.py |
var MobileEsp={initCompleted:false,isWebkit:false,isMobilePhone:false,isIphone:false,isAndroid:false,isAndroidPhone:false,isTierTablet:false,isTierIphone:false,isTierRichCss:false,isTierGenericMobile:false,engineWebKit:"webkit",deviceIphone:"iphone",deviceIpod:"ipod",deviceIpad:"ipad",deviceMacPpc:"macintosh",deviceAndroid:"android",deviceGoogleTV:"googletv",deviceHtcFlyer:"htc_flyer",deviceWinPhone7:"windows phone os 7",deviceWinPhone8:"windows phone 8",deviceWinMob:"windows ce",deviceWindows:"windows",deviceIeMob:"iemobile",devicePpc:"ppc",enginePie:"wm5 pie",deviceBB:"blackberry",deviceBB10:"bb10",vndRIM:"vnd.rim",deviceBBStorm:"blackberry95",deviceBBBold:"blackberry97",deviceBBBoldTouch:"blackberry 99",deviceBBTour:"blackberry96",deviceBBCurve:"blackberry89",deviceBBCurveTouch:"blackberry 938",deviceBBTorch:"blackberry 98",deviceBBPlaybook:"playbook",deviceSymbian:"symbian",deviceSymbos:"symbos",deviceS60:"series60",deviceS70:"series70",deviceS80:"series80",deviceS90:"series90",devicePalm:"palm",deviceWebOS:"webos",deviceWebOShp:"hpwos",engineBlazer:"blazer",engineXiino:"xiino",deviceNuvifone:"nuvifone",deviceBada:"bada",deviceTizen:"tizen",deviceMeego:"meego",deviceKindle:"kindle",engineSilk:"silk-accelerated",vndwap:"vnd.wap",wml:"wml",deviceTablet:"tablet",deviceBrew:"brew",deviceDanger:"danger",deviceHiptop:"hiptop",devicePlaystation:"playstation",devicePlaystationVita:"vita",deviceNintendoDs:"nitro",deviceNintendo:"nintendo",deviceWii:"wii",deviceXbox:"xbox",deviceArchos:"archos",engineOpera:"opera",engineNetfront:"netfront",engineUpBrowser:"up.browser",engineOpenWeb:"openweb",deviceMidp:"midp",uplink:"up.link",engineTelecaQ:"teleca q",engineObigo:"obigo",devicePda:"pda",mini:"mini",mobile:"mobile",mobi:"mobi",maemo:"maemo",linux:"linux",mylocom2:"sony/com",manuSonyEricsson:"sonyericsson",manuericsson:"ericsson",manuSamsung1:"sec-sgh",manuSony:"sony",manuHtc:"htc",svcDocomo:"docomo",svcKddi:"kddi",svcVodafone:"vodafone",disUpdate:"update",uagent:"",InitDeviceScan:function(){this.initCompleted=false;if(navigator&&navigator.userAgent){this.uagent=navigator.userAgent.toLowerCase()}this.isWebkit=this.DetectWebkit();this.isIphone=this.DetectIphone();this.isAndroid=this.DetectAndroid();this.isAndroidPhone=this.DetectAndroidPhone();this.isTierIphone=this.DetectTierIphone();this.isTierTablet=this.DetectTierTablet();this.isMobilePhone=this.DetectMobileQuick();this.isTierRichCss=this.DetectTierRichCss();this.isTierGenericMobile=this.DetectTierOtherPhones();this.initCompleted=true},DetectIphone:function(){if(this.initCompleted||this.isIphone){return this.isIphone}if(this.uagent.search(this.deviceIphone)>-1){if(this.DetectIpad()||this.DetectIpod()){return false}else{return true}}else{return false}},DetectIpod:function(){if(this.uagent.search(this.deviceIpod)>-1){return true}else{return false}},DetectIphoneOrIpod:function(){if(this.DetectIphone()||this.DetectIpod()){return true}else{return false}},DetectIpad:function(){if(this.uagent.search(this.deviceIpad)>-1&&this.DetectWebkit()){return true}else{return false}},DetectIos:function(){if(this.DetectIphoneOrIpod()||this.DetectIpad()){return true}else{return false}},DetectAndroid:function(){if(this.initCompleted||this.isAndroid){return this.isAndroid}if((this.uagent.search(this.deviceAndroid)>-1)||this.DetectGoogleTV()){return true}if(this.uagent.search(this.deviceHtcFlyer)>-1){return true}else{return false}},DetectAndroidPhone:function(){if(this.initCompleted||this.isAndroidPhone){return this.isAndroidPhone}if(this.DetectAndroid()&&(this.uagent.search(this.mobile)>-1)){return true}if(this.DetectOperaAndroidPhone()){return true}if(this.uagent.search(this.deviceHtcFlyer)>-1){return true}else{return false}},DetectAndroidTablet:function(){if(!this.DetectAndroid()){return false}if(this.DetectOperaMobile()){return false}if(this.uagent.search(this.deviceHtcFlyer)>-1){return false}if(this.uagent.search(this.mobile)>-1){return false}else{return true}},DetectAndroidWebKit:function(){if(this.DetectAndroid()&&this.DetectWebkit()){return true}else{return false}},DetectGoogleTV:function(){if(this.uagent.search(this.deviceGoogleTV)>-1){return true}else{return false}},DetectWebkit:function(){if(this.initCompleted||this.isWebkit){return this.isWebkit}if(this.uagent.search(this.engineWebKit)>-1){return true}else{return false}},DetectWindowsPhone:function(){if(this.DetectWindowsPhone7()||this.DetectWindowsPhone8()){return true}else{return false}},DetectWindowsPhone7:function(){if(this.uagent.search(this.deviceWinPhone7)>-1){return true}else{return false}},DetectWindowsPhone8:function(){if(this.uagent.search(this.deviceWinPhone8)>-1){return true}else{return false}},DetectWindowsMobile:function(){if(this.DetectWindowsPhone()){return false}if(this.uagent.search(this.deviceWinMob)>-1||this.uagent.search(this.deviceIeMob)>-1||this.uagent.search(this.enginePie)>-1){return true}if((this.uagent.search(this.devicePpc)>-1)&&!(this.uagent.search(this.deviceMacPpc)>-1)){return true}if(this.uagent.search(this.manuHtc)>-1&&this.uagent.search(this.deviceWindows)>-1){return true}else{return false}},DetectBlackBerry:function(){if((this.uagent.search(this.deviceBB)>-1)||(this.uagent.search(this.vndRIM)>-1)){return true}if(this.DetectBlackBerry10Phone()){return true}else{return false}},DetectBlackBerry10Phone:function(){if((this.uagent.search(this.deviceBB10)>-1)&&(this.uagent.search(this.mobile)>-1)){return true}else{return false}},DetectBlackBerryTablet:function(){if(this.uagent.search(this.deviceBBPlaybook)>-1){return true}else{return false}},DetectBlackBerryWebKit:function(){if(this.DetectBlackBerry()&&this.uagent.search(this.engineWebKit)>-1){return true}else{return false}},DetectBlackBerryTouch:function(){if(this.DetectBlackBerry()&&((this.uagent.search(this.deviceBBStorm)>-1)||(this.uagent.search(this.deviceBBTorch)>-1)||(this.uagent.search(this.deviceBBBoldTouch)>-1)||(this.uagent.search(this.deviceBBCurveTouch)>-1))){return true}else{return false}},DetectBlackBerryHigh:function(){if(this.DetectBlackBerryWebKit()){return false}if((this.DetectBlackBerry())&&(this.DetectBlackBerryTouch()||this.uagent.search(this.deviceBBBold)>-1||this.uagent.search(this.deviceBBTour)>-1||this.uagent.search(this.deviceBBCurve)>-1)){return true}else{return false}},DetectBlackBerryLow:function(){if(this.DetectBlackBerry()){if(this.DetectBlackBerryHigh()||this.DetectBlackBerryWebKit()){return false}else{return true}}else{return false}},DetectS60OssBrowser:function(){if(this.DetectWebkit()){if((this.uagent.search(this.deviceS60)>-1||this.uagent.search(this.deviceSymbian)>-1)){return true}else{return false}}else{return false}},DetectSymbianOS:function(){if(this.uagent.search(this.deviceSymbian)>-1||this.uagent.search(this.deviceS60)>-1||((this.uagent.search(this.deviceSymbos)>-1)&&(this.DetectOperaMobile))||this.uagent.search(this.deviceS70)>-1||this.uagent.search(this.deviceS80)>-1||this.uagent.search(this.deviceS90)>-1){return true}else{return false}},DetectPalmOS:function(){if(this.DetectPalmWebOS()){return false}if(this.uagent.search(this.devicePalm)>-1||this.uagent.search(this.engineBlazer)>-1||this.uagent.search(this.engineXiino)>-1){return true}else{return false}},DetectPalmWebOS:function(){if(this.uagent.search(this.deviceWebOS)>-1){return true}else{return false}},DetectWebOSTablet:function(){if(this.uagent.search(this.deviceWebOShp)>-1&&this.uagent.search(this.deviceTablet)>-1){return true}else{return false}},DetectOperaMobile:function(){if((this.uagent.search(this.engineOpera)>-1)&&((this.uagent.search(this.mini)>-1||this.uagent.search(this.mobi)>-1))){return true}else{return false}},DetectOperaAndroidPhone:function(){if((this.uagent.search(this.engineOpera)>-1)&&(this.uagent.search(this.deviceAndroid)>-1)&&(this.uagent.search(this.mobi)>-1)){return true}else{return false}},DetectOperaAndroidTablet:function(){if((this.uagent.search(this.engineOpera)>-1)&&(this.uagent.search(this.deviceAndroid)>-1)&&(this.uagent.search(this.deviceTablet)>-1)){return true}else{return false}},DetectKindle:function(){if(this.uagent.search(this.deviceKindle)>-1&&!this.DetectAndroid()){return true}else{return false}},DetectAmazonSilk:function(){if(this.uagent.search(this.engineSilk)>-1){return true}else{return false}},DetectGarminNuvifone:function(){if(this.uagent.search(this.deviceNuvifone)>-1){return true}else{return false}},DetectBada:function(){if(this.uagent.search(this.deviceBada)>-1){return true}else{return false}},DetectTizen:function(){if(this.uagent.search(this.deviceTizen)>-1){return true}else{return false}},DetectMeego:function(){if(this.uagent.search(this.deviceMeego)>-1){return true}else{return false}},DetectDangerHiptop:function(){if(this.uagent.search(this.deviceDanger)>-1||this.uagent.search(this.deviceHiptop)>-1){return true}else{return false}},DetectSonyMylo:function(){if((this.uagent.search(this.manuSony)>-1)&&((this.uagent.search(this.qtembedded)>-1)||(this.uagent.search(this.mylocom2)>-1))){return true}else{return false}},DetectMaemoTablet:function(){if(this.uagent.search(this.maemo)>-1){return true}if((this.uagent.search(this.linux)>-1)&&(this.uagent.search(this.deviceTablet)>-1)&&!this.DetectWebOSTablet()&&!this.DetectAndroid()){return true}else{return false}},DetectArchos:function(){if(this.uagent.search(this.deviceArchos)>-1){return true}else{return false}},DetectGameConsole:function(){if(this.DetectSonyPlaystation()||this.DetectNintendo()||this.DetectXbox()){return true}else{return false}},DetectSonyPlaystation:function(){if(this.uagent.search(this.devicePlaystation)>-1){return true}else{return false}},DetectGamingHandheld:function(){if((this.uagent.search(this.devicePlaystation)>-1)&&(this.uagent.search(this.devicePlaystationVita)>-1)){return true}else{return false}},DetectNintendo:function(){if(this.uagent.search(this.deviceNintendo)>-1||this.uagent.search(this.deviceWii)>-1||this.uagent.search(this.deviceNintendoDs)>-1){return true}else{return false}},DetectXbox:function(){if(this.uagent.search(this.deviceXbox)>-1){return true}else{return false}},DetectBrewDevice:function(){if(this.uagent.search(this.deviceBrew)>-1){return true}else{return false}},DetectSmartphone:function(){if(this.DetectTierIphone()||this.DetectS60OssBrowser()||this.DetectSymbianOS()||this.DetectWindowsMobile()||this.DetectBlackBerry()||this.DetectPalmOS()){return true}return false},DetectMobileQuick:function(){if(this.DetectTierTablet()){return false}if(this.initCompleted||this.isMobilePhone){return this.isMobilePhone}if(this.DetectSmartphone()){return true}if(this.uagent.search(this.mobile)>-1){return true}if(this.DetectKindle()||this.DetectAmazonSilk()){return true}if(this.uagent.search(this.deviceMidp)>-1||this.DetectBrewDevice()){return true}if(this.DetectOperaMobile()||this.DetectArchos()){return true}if((this.uagent.search(this.engineObigo)>-1)||(this.uagent.search(this.engineNetfront)>-1)||(this.uagent.search(this.engineUpBrowser)>-1)||(this.uagent.search(this.engineOpenWeb)>-1)){return true}return false},DetectMobileLong:function(){if(this.DetectMobileQuick()){return true}if(this.DetectGameConsole()){return true}if(this.DetectDangerHiptop()||this.DetectMaemoTablet()||this.DetectSonyMylo()||this.DetectGarminNuvifone()){return true}if((this.uagent.search(this.devicePda)>-1)&&!(this.uagent.search(this.disUpdate)>-1)){return true}if(this.uagent.search(this.manuSamsung1)>-1||this.uagent.search(this.manuSonyEricsson)>-1||this.uagent.search(this.manuericsson)>-1){return true}if((this.uagent.search(this.svcDocomo)>-1)||(this.uagent.search(this.svcKddi)>-1)||(this.uagent.search(this.svcVodafone)>-1)){return true}return false},DetectTierTablet:function(){if(this.initCompleted||this.isTierTablet){return this.isTierTablet}if(this.DetectIpad()||this.DetectAndroidTablet()||this.DetectBlackBerryTablet()||this.DetectWebOSTablet()){return true}else{return false}},DetectTierIphone:function(){if(this.initCompleted||this.isTierIphone){return this.isTierIphone}if(this.DetectIphoneOrIpod()||this.DetectAndroidPhone()||this.DetectWindowsPhone()||this.DetectBlackBerry10Phone()||this.DetectPalmWebOS()||this.DetectBada()||this.DetectTizen()||this.DetectGamingHandheld()){return true}if(this.DetectBlackBerryWebKit()&&this.DetectBlackBerryTouch()){return true}else{return false}},DetectTierRichCss:function(){if(this.initCompleted||this.isTierRichCss){return this.isTierRichCss}if(this.DetectTierIphone()||this.DetectKindle()||this.DetectTierTablet()){return false}if(!this.DetectMobileQuick()){return false}if(this.DetectWebkit()){return true}if(this.DetectS60OssBrowser()||this.DetectBlackBerryHigh()||this.DetectWindowsMobile()||(this.uagent.search(this.engineTelecaQ)>-1)){return true}else{return false}},DetectTierOtherPhones:function(){if(this.initCompleted||this.isTierGenericMobile){return this.isTierGenericMobile}if(this.DetectTierIphone()||this.DetectTierRichCss()||this.DetectTierTablet()){return false}if(this.DetectMobileLong()){return true}else{return false}}};MobileEsp.InitDeviceScan();
/* *******************************************
// Copyright 2010-2013, bMobilized Inc.
// *******************************************
*/
function log2console(a){if(window.console&&console.log){console.log(a)}}var fullweb=location.href.indexOf("fullweb=1")>0||document.cookie.indexOf("fullweb=1")>-1;if(fullweb){var d=new Date();var __cookie_duration=(typeof cookie_duration=="undefined")?1440:cookie_duration;d.setTime(d.getTime()+(__cookie_duration*60*1000));document.cookie="fullweb=1; expires="+d.toGMTString()+"; path=/"}log2console("UA = "+MobileEsp.uagent);var isadbot=(MobileEsp.uagent.search("adsbot")>-1);if(!fullweb&&!isadbot){var __ipad=(typeof ipad=="undefined")?true:ipad;log2console("__ipad = "+__ipad);var __other_tablets=(typeof other_tablets=="undefined")?true:other_tablets;log2console("__other_tablets = "+__other_tablets);if(MobileEsp.DetectMobileLong()||(__ipad&&MobileEsp.DetectIpad())||(__other_tablets&&(MobileEsp.DetectAndroidTablet()||MobileEsp.DetectBlackBerryTablet()||MobileEsp.DetectWebOSTablet()))){var __force_http=(typeof force_http=="undefined")?false:force_http;log2console("__force_http = "+__force_http);var __protocol=__force_http?"http:":location.protocol;log2console("__protocol = "+__protocol);var __force_path_and_query=(typeof force_path_and_query=="undefined")?"":force_path_and_query;log2console("__force_path_and_query = "+__force_path_and_query);var __referrer=(typeof document.referrer=="undefined")?"":document.referrer;log2console("__referrer = "+__referrer);var __force_url=(typeof force_url=="undefined")?location.href:force_url;log2console("__force_url = "+__force_url);var __r=__protocol+"//"+mobile_domain;if(__force_path_and_query==""){if(__referrer!=""){__r+="/?ref="+encodeURIComponent(__referrer)}if(__force_url!=""){__r+=((__referrer=="")?"/?url=":"&url=")+encodeURIComponent(__force_url)}}else{__r+=__force_path_and_query}log2console("__r = "+__r);window.top.location=__r}}; | zettwerk.mobiletheming | /zettwerk.mobiletheming-0.2.1.zip/zettwerk.mobiletheming-0.2.1/src/zettwerk/mobiletheming/browser/scripts/me.redirect.min.js | me.redirect.min.js |
Introduction
============
zettwerk.ui integrates jquery.ui's themeroller based themes into Plone 4.x. Themeroller is a tool to dynamically customize the jquery.ui css classes. For details about jquery.ui theming and themeroller see http://jqueryui.com/themeroller/.
See it in action: https://www.youtube.com/watch?v=izgJ9GOSuNw
Note: with version 2.0 the dynamic integration of the themeroller widget stops working. But you can include manually downloaded themes. Follow the instructions on the "add theme" page linked on the Zettwerk UI Themer conrol panel. For future versions, it is planned to add a custom widget with live preview again. To see how it worked with versions below 2.0 see http://www.youtube.com/watch?v=p4_jU-5HUYA
Usage
=====
With this add-on it is very easy to adapt the look and color scheme of your plone site. After installation, there is a new extension product listed in the plone controlpanel which is called "Zettwerk UI Themer". See the instructions given on that page to choose and add themes.
Feel free to contact us for feedback.
Technical background and pre 1.0 versions
=========================================
For versions below 1.0 zettwerk.ui made heavy use of javascript to manipulate the dom and css of the generated output page. This was ok for prototyping but probably not for production. Especially slower browsers shows some kind of flickering, till all manipulations were applied. With version 1.0, the complete concept to do most of the manipulation changed to xsl-transforms, applied via diazo / plone.app.theming. This results in a much better user experience. On the other hand, zettwerk.ui acts now as a skin (while the former one was none).
Installation
============
Add zettwerk.ui to your buildout eggs::
eggs = ..
zettwerk.ui
After running buildout and starting the instance, you can install Zettwerk UI Themer via portal_quickinstaller to your plone instance. zettwerk.ui requires Plone 4.1 cause it depends on `plone.app.theming <http://pypi.python.org/pypi/plone.app.theming>`_. If you want to use zettwerk.ui in Plone 4.0 you can also use `version 0.40 <http://pypi.python.org/pypi/zettwerk.ui/0.40>`_, which is the last one, (officially) supporting Plone 4.0.x.
Filesystem dependency
=====================
Created themes are downloaded to the servers filesystem. So a directory is needed, to store these files. At the moment, this is located always relative from your INSTANCE_HOME: ../../zettwerk.ui.downloads. In a common buildout environment, that is directly inside your buildout folder.
Deployment and reuse of themes
==============================
You can easily move the dowloaded themes from the download folder from one buildout instance to another. So to deploy a theme just copy the folder with the name of your theme from your develop server to your live server. It should be immediatelly available (without restart) - but only if the download folder was already created.
| zettwerk.ui | /zettwerk.ui-2.0.zip/zettwerk.ui-2.0/README.txt | README.txt |
import os
import re
import zipfile
import fileinput
from stat import S_ISDIR, ST_MODE
import Globals
CSS_FILENAME = 'jquery-ui-.custom.css'
INSTANCE_HOME = getattr(Globals, 'INSTANCE_HOME', None)
if INSTANCE_HOME is not None:
BUILDOUT_HOME = os.path.join(INSTANCE_HOME, '..', '..')
DOWNLOAD_HOME = os.path.join(BUILDOUT_HOME, 'zettwerk.ui.downloads')
else:
## fail-safe when used without zope
BUILDOUT_HOME = '.'
DOWNLOAD_HOME = os.path.join(BUILDOUT_HOME, 'zettwerk.ui.downloads')
def isAvailable():
""" """
return os.path.exists(DOWNLOAD_HOME)
def createDownloadFolder():
""" Create the download directory. """
if not isAvailable():
os.mkdir(DOWNLOAD_HOME)
def storeBinaryFile(name, content):
""" """
filepath = os.path.join(DOWNLOAD_HOME, '%s.zip' % (name))
f = open(filepath, 'wb')
f.write(content)
f.close()
def extractZipFile(name):
""" """
if not os.path.exists(os.path.join(DOWNLOAD_HOME, name)):
os.mkdir(os.path.join(DOWNLOAD_HOME, name))
if not os.path.exists(os.path.join(DOWNLOAD_HOME, name, 'images')):
os.mkdir(os.path.join(DOWNLOAD_HOME, name, 'images'))
filename = '%s.zip' % (name)
f = os.path.join(DOWNLOAD_HOME, filename)
z = zipfile.ZipFile(f, 'r')
for content in z.namelist():
if content.find('css/custom-theme/') == 0:
part = content.replace('css/custom-theme/', '')
output = os.path.join(DOWNLOAD_HOME, name, part)
getter = z.read(content)
setter = file(output, 'wb')
setter.write(getter)
setter.close()
z.close()
def isCustomTheme(name):
""" check if this is a custom file or a default theme """
return os.path.exists(
os.path.join(DOWNLOAD_HOME,
name,
'jquery-ui-1.9.2.custom.css')
)
def getDirectoriesOfDownloadHome():
""" return all directories of the download
home folder. """
dirs = []
if isAvailable():
for name in os.listdir(DOWNLOAD_HOME):
if S_ISDIR(os.stat(os.path.join(DOWNLOAD_HOME, name))[ST_MODE]):
dirs.append(name)
return dirs
def getThemeHashOfCustomCSS(theme_dir):
filepath = os.path.join(DOWNLOAD_HOME,
theme_dir,
CSS_FILENAME)
reg = re.compile('visit http://jqueryui.com/themeroller/\?(.+)', re.S)
if os.path.exists(filepath):
for line in fileinput.input(filepath):
match = reg.search(line)
if match:
fileinput.close()
return match.group(1) | zettwerk.ui | /zettwerk.ui-2.0.zip/zettwerk.ui-2.0/zettwerk/ui/filesystem.py | filesystem.py |
from Products.statusmessages.interfaces import IStatusMessage
from Products.CMFCore.utils import UniqueObject, getToolByName
from OFS.SimpleItem import SimpleItem
from persistent.mapping import PersistentMapping
from zope.interface import Interface
from zope.interface import implements
from zope import schema
from zope.i18n import translate
from zettwerk.ui import messageFactory as _
import urllib2
from urllib import urlencode
import zipfile
from ..filesystem import extractZipFile, storeBinaryFile, \
createDownloadFolder, getDirectoriesOfDownloadHome, \
getThemeHashOfCustomCSS, isCustomTheme
from ..resources import registerResourceDirectory
from ..filesystem import DOWNLOAD_HOME
UI_DOWNLOAD_URL = 'http://jqueryui.com/download'
## a list of jquery.ui elements, needed for the url to download a new theme.
UI = """ui.core.js
ui.widget.js
ui.mouse.js
ui.position.js
ui.draggable.js
ui.droppable.js
ui.resizable.js
ui.selectable.js
ui.sortable.js
ui.accordion.js
ui.autocomplete.js
ui.button.js
ui.dialog.js
ui.slider.js
ui.tabs.js
ui.datepicker.js
ui.progressbar.js
effects.core.js
effects.blind.js
effects.bounce.js
effects.clip.js
effects.drop.js
effects.explode.js
effects.fold.js
effects.highlight.js
effects.pulsate.js
effects.scale.js
effects.shake.js
effects.slide.js
effects.transfer.js"""
class IUIToolTheme(Interface):
""" UITool interface defining needed schema fields. """
theme = schema.Choice(title=_(u"Theme"),
required=False,
vocabulary="zettwerk.ui.ListThemesVocabulary")
class IUIToolThemeroller(Interface):
""" UITool interface for themeroller fields """
themeroller = schema.TextLine(
title=_("Themeroller")
)
class IUITool(IUIToolTheme, IUIToolThemeroller):
""" Mixin Interface """
pass
class UITool(UniqueObject, SimpleItem):
""" The UITool handles creation and loading of ui themes. """
implements(IUITool)
id = 'portal_ui_tool'
## implement the fields, given through the interfaces
theme = ''
download = ''
themeroller = ''
themeHashes = None
def cp_js_translations(self):
""" return some translated js strings """
return u'var sorry_only_firefox = "%s";\n' \
u'var nothing_themed = "%s";\n' \
u'var name_missing = "%s";\n' \
u'var no_sunburst_name = "%s";\n' \
u'var no_special_chars = "%s";\n\n' % (
translate(_(u"Sorry, due to security restrictions, this tool " \
u"only works in Firefox"),
domain='zettwerk.ui',
context=self.REQUEST),
translate(_(u"Download name given but nothing themed - please " \
"use themeroller"),
domain='zettwerk.ui',
context=self.REQUEST),
translate(_(u"You opened themeroller, but no download name is " \
u"given. Click ok to continue and ignore your " \
u"changes or click cancel to enter a name."),
domain='zettwerk.ui',
context=self.REQUEST),
translate(_(u"Sorry, sunburst is an invalid name"),
domain='zettwerk.ui',
context=self.REQUEST),
translate(_(u"Please use no special characters."),
domain='zettwerk.ui',
context=self.REQUEST),
)
def css(self, *args):
""" Generate the css rules, suitable for the given settings. """
content_type_header = 'text/css;charset=UTF-8'
self.REQUEST.RESPONSE.setHeader('content-type',
content_type_header)
result = ""
if self.theme:
## the sunburst resource in portal_css is disabled
## cause enable/disabling resources in service mode
## seems not to work as i expect
if self.theme == u'sunburst':
result += '@import "++resource++jquery-ui-themes/' \
'sunburst/jqueryui.css";'
else:
resource_base = '++resource++zettwerk.ui.themes'
css_filename = 'jquery.ui.theme.css';
if isCustomTheme(self.theme):
css_filename = 'jquery-ui-1.9.2.custom.css'
result += '@import "%s/%s/%s";' % (
resource_base,
self.theme,
css_filename
)
return result
def _redirectToCPView(self, msg=None):
""" Just a redirect. """
if msg is not None:
utils = getToolByName(self, 'plone_utils')
utils.addPortalMessage(msg)
portal_url = getToolByName(self, 'portal_url')
url = '%s/%s/@@ui-controlpanel' % (portal_url(),
self.getId())
return self.REQUEST.RESPONSE.redirect(url)
def _rebuildThemeHashes(self):
""" For edit existing themes, the hash is needed. They are stored
in self.themeHashes. The problem with this: by quick-reinstalling
zettwerk.ui this attribute get None. Also, if new themes were
copied 'by hand' (as described in the README for deploying) the
themeHashes doesn't know the copied theme's hash. This method
reads all available themes and the theme-custom.css file to rebuild
the themeHashes attribute. Its called every time the control panel
view is called. """
if self.themeHashes is None:
self.themeHashes = PersistentMapping()
theme_dirs = getDirectoriesOfDownloadHome()
for theme_dir in theme_dirs:
theme_hash = getThemeHashOfCustomCSS(theme_dir)
if theme_hash:
self.themeHashes.update({theme_dir: theme_hash})
self._handleSunburst()
def _handleSunburst(self):
"""" since we support collective.js.jqueryui, it would make
sense to add the provided sunburst theme as a theme, too. """
## no, i don't want to pep8-ify this string
self.themeHashes.update(
{'sunburst': '?ffDefault=%20Arial,FreeSans,sans-serif&fwDefault=normal&fsDefault=0.9em&cornerRadius=5px&bgColorHeader=dddddd&bgTextureHeader=01_flat.png&bgImgOpacityHeader=75&borderColorHeader=cccccc&fcHeader=444444&iconColorHeader=205c90&bgColorContent=ffffff&bgTextureContent=01_flat.png&bgImgOpacityContent=100&borderColorContent=cccccc&fcContent=444444&iconColorContent=205c90&bgColorDefault=205c90&bgTextureDefault=01_flat.png&bgImgOpacityDefault=45&borderColorDefault=cccccc&fcDefault=ffffff&iconColorDefault=ffffff&bgColorHover=dddddd&bgTextureHover=01_flat.png&bgImgOpacityHover=75&borderColorHover=448dae&fcHover=444444&iconColorHover=444444&bgColorActive=75ad0a&bgTextureActive=01_flat.png&bgImgOpacityActive=50&borderColorActive=cccccc&fcActive=ffffff&iconColorActive=ffffff&bgColorHighlight=ffdd77&bgTextureHighlight=01_flat.png&bgImgOpacityHighlight=55&borderColorHighlight=dd8800&fcHighlight=000000&iconColorHighlight=dd8800&bgColorError=ffddcc&bgTextureError=01_flat.png&bgImgOpacityError=45&borderColorError=dd0000&fcError=000000&iconColorError=dd0000&bgColorOverlay=aaaaaa&bgTextureOverlay=01_flat.png&bgImgOpacityOverlay=75&opacityOverlay=30&bgColorShadow=999999&bgTextureShadow=01_flat.png&bgImgOpacityShadow=55&opacityShadow=45&thicknessShadow=0px&offsetTopShadow=5px&offsetLeftShadow=5px&cornerRadiusShadow=5px'}
)
def createDLDirectory(self):
""" Create the storage and register the resource"""
createDownloadFolder()
registerResourceDirectory(name='zettwerk.ui.themes',
directory=DOWNLOAD_HOME)
self._redirectToCPView(_(u"Directory created"))
def handleDownload(self, name, hash):
""" Download a new theme, created by themeroller.
@param name: string with the name of the new theme.
@param hash: themeroller hash, with theme settings.
"""
url = self._prepareUIDownloadUrl(hash)
handler = urllib2.urlopen(url)
content = handler.read()
storeBinaryFile(name, content)
self._enableNewTheme(name, hash)
def _enableNewTheme(self, name, hash):
""" Extract the downloaded theme and set it as current theme. """
try:
extractZipFile(name)
except zipfile.BadZipfile:
## This might fail as mentioned by Jensens
## mostly caused by the themeroller webservice
IStatusMessage(self.REQUEST) \
.addStatusMessage(
_(u'The downloaded zipfile is corrupt. This could mean ' \
u'that the themeroller webservice has problems. The ' \
u'common fix for this is, to wait a day or two and ' \
'try it again.'),
"error")
return
if self.themeHashes is None:
self.themeHashes = PersistentMapping()
self.themeHashes.update({name: hash})
self.theme = name
def _prepareUIDownloadUrl(self, hash):
""" Built the download url. """
data = []
data.append(('download', 'true'))
for part in UI.split('\n'):
part = part.strip()
if part:
data.append(('files[]', part))
data.append(('theme', '?' + hash))
data.append(('scope', ''))
data.append(('t-name', 'custom-theme'))
data.append(('ui-version', '1.8'))
data = urlencode(data)
return "%s?%s" % (UI_DOWNLOAD_URL, data) | zettwerk.ui | /zettwerk.ui-2.0.zip/zettwerk.ui-2.0/zettwerk/ui/tool/tool.py | tool.py |
from Products.CMFDefault.formlib.schema import SchemaAdapterBase
from plone.app.controlpanel.form import ControlPanelForm
from plone.fieldsets.fieldsets import FormFieldsets
from zope.app.form.browser import DisplayWidget
from zope.i18n import translate
from zope.component import adapts
from zope.interface import implements
from Products.CMFPlone.interfaces import IPloneSiteRoot
from Products.CMFCore.utils import getToolByName
from ..tool.tool import IUITool, IUIToolTheme, \
IUIToolThemeroller
from zettwerk.ui import messageFactory as _
from ..filesystem import isAvailable, DOWNLOAD_HOME
class UIControlPanelAdapter(SchemaAdapterBase):
""" Adapter for the interface schema fields """
adapts(IPloneSiteRoot)
implements(IUITool)
def __init__(self, context):
super(UIControlPanelAdapter, self).__init__(context)
self.portal = context
ui_tool = getToolByName(self.portal, 'portal_ui_tool')
self.context = ui_tool
theme = FormFieldsets(IUIToolTheme)
theme.id = 'theme'
theme.label = _(u"Existing themes")
theme.description = _(u'Please select a theme from the existing ones.')
themeroller = FormFieldsets(IUIToolThemeroller)
themeroller.id = 'themeroller'
themeroller.label = _('Add theme')
class ThemeDisplayWidget(DisplayWidget):
""" Display the create directory link """
def __call__(self):
tool = self.context.context
tool._rebuildThemeHashes()
create_help = translate(_(u"Create download directory at: "),
domain="zettwerk.ui",
context=self.request)
create_text = "%s <br />%s" % (create_help, DOWNLOAD_HOME)
create_dl = u'<a class="createDLD" ' \
u'href="javascript:createDLDirectory()">%s</a>' % (create_text)
if isAvailable():
return _(u"add_theme_description_text", """<p>Sadly,
the on the fly themeroller integration does not work anymore. But
it is possible, to download and add new themes by hand. There are
two kind of themes: Jquery UI Default themes and custom ones.</p>
<p>To include all the default themes follow these steps:
<ol>
<li>Download the zip file from <a href="http://jqueryui.com/resources/download/jquery-ui-themes-1.9.2.zip">http://jqueryui.com/resources/download/jquery-ui-themes-1.9.2.zip</a></li>
<li>Extract the contents/subfolders of the themes folder to your zettwerk.ui download directory.</li>
<li>Reload this page and choose a theme.</li>
</ol>
</p>
<p style="margin-top: 2em">To include a custom theme follow these steps:
<ol>
<li>Go to the themeroller page at <a target="_blank" href="http://jqueryui.com/themeroller/">http://jqueryui.com/themeroller/</a> and create your theme with the themeroller tool.</li>
<li>Click Download theme (in the themeroller widget)</li>
<li>On the next page, choose the legacy Version (1.9.2 at the moment)</li>
<li>Scroll to the bottom of the page set a folder name which gets the theme name.</li>
<li>Click download</li>
<li>Extract the folder css/$your_theme_name to your zettwerk.ui download directory.</li>
<li>Reload this page and choose a theme.</li>
</ol>
</p>
""")
else:
return create_dl
class UIControlPanel(ControlPanelForm):
""" Build the ControlPanel form. """
form_fields = FormFieldsets(theme, themeroller)
form_fields['themeroller'].custom_widget = ThemeDisplayWidget
form_fields['themeroller'].for_display = True
label = _(u"Zettwerk UI Themer")
description = ''
# def __call__(self):
# | zettwerk.ui | /zettwerk.ui-2.0.zip/zettwerk.ui-2.0/zettwerk/ui/browser/cp_view.py | cp_view.py |
$(document).ready(function() {
enablePersonalTool();
enableForms();
enableDialogs();
enableTabs();
enableGlobalTabs();
enableEditBar();
});
var enablePersonalTool = function() {
// enable overlay, cause the id is changed
// taken from Products.CMFPlone.skins.plone_ecmascript/popupforms.js
$('#portal-personaltools-ui a[href$="/login"], #portal-personaltools-ui a[href$="/login_form"]').prepOverlay(
{
subtype: 'ajax',
filter: common_content_filter,
formselector: 'form#login_form',
noform: function () {
if (location.href.search(/pwreset_finish$/) >= 0) {
return 'redirect';
} else {
return 'reload';
}
},
redirect: function () {
var href = location.href;
if (href.search(/pwreset_finish$/) >= 0) {
return href.slice(0, href.length-14) + 'logged_in';
} else {
return href;
}
}
}
);
// custom stuff
$('#portal-personaltools-ui').hover(function() {
$(this).addClass('ui-state-hover');
}, function() {
$(this).removeClass('ui-state-hover');
});
$('#portal-personaltools-ui dd a').hover(function() {
$(this).addClass('ui-state-hover');
}, function() {
$(this).removeClass('ui-state-hover');
});
};
var enableForms = function($content) {
if (!$content) {
var $content = $('body');
}
$content.find('.optionsToggle').removeClass('optionsToggle');
$content.find('select, textarea, input:text, input:password').bind({
focusin: function() {
$(this).addClass('ui-state-focus');
},
focusout: function() {
$(this).removeClass('ui-state-focus');
}
});
$content.find(".hover").hover(function(){
$(this).addClass("ui-state-hover");
},function(){
$(this).removeClass("ui-state-hover");
});
}
var enableDialogs = function() {
$("a.link-overlay").unbind('click').click(function() {
// remove old dialogs
$('#dialogContainer').remove();
// use the links content as default title of the dialog
var title = $(this).html();
$.get($(this).attr('href'),
{},
function(data) {
showDialogContent(data,title)
}
);
return false; // avoid the execution of the regular link
});
$("form.link-overlay input[type='submit']").unbind('click').click(function() {
// remove old dialogs
$('#dialogContainer').remove();
// use the links content as default title of the dialog
var title = '';
$.get($(this).parents('form').attr('action'),
{},
function(data) {
showDialogContent(data,title)
}
);
return false; // avoid the execution of the regular link
});
};
var showDialogContent = function(data, title) {
var $content = $(data).find('#content');
// take the first heading as dialog title, if available
$content.find('h1.documentFirstHeading').each(function() {
title = $(this).html();
$(this).hide();
});
$('<div id="dialogContainer" title="'+title+'"></div>').appendTo('body');
// search for submit buttons and use them as dialog buttons
var buttons = {};
$content.find('input[type=submit]').each(function() {
var buttonValue = $(this).val();
buttons[buttonValue] = function() {
$('input[type=submit][value='+buttonValue+']').click();
};
$(this).hide();
});
// bring up the dialog
$content.appendTo('#dialogContainer');
enableForms($content);
var $dialog = $('#dialogContainer').dialog({width: '60%', buttons: buttons});
console.log($dialog);
$dialog.parent().css('z-index', '1000000');
};
var enableTabs = function() {
$('div.ui-tabs > ul > li').hover(function() {
$(this).addClass('ui-state-hover');
$(this).find('span').addClass('ui-state-hover');
}, function() {
$(this).removeClass('ui-state-hover');
$(this).find('span').removeClass('ui-state-hover');
});
$('div.ui-tabs > ul > li a').click(function() {
// handle the tabs
$(this).parent().parent().find('.ui-state-active').removeClass('ui-state-active');
$(this).parent().addClass('ui-state-active');
$(this).find('span').addClass('ui-state-active');
// hide all fieldsets
$('div.ui-tabs>fieldset,div.ui-tabs>dd').hide();
var active_id = $(this).attr('href'); // thats the hidden legend in the fieldset
var $active = $(active_id);
if ($active[0].tagName.toLowerCase() == 'dd') {
$active.show();
} else {
$active.parent().show();
}
return false;
});
$('ul.ui-tabs-nav').find('.selected').parent().addClass('ui-state-active');
};
var enableGlobalTabs = function() {
$('#portal-globalnav-ui > li').hover(function() {
$(this).addClass('ui-state-hover');
}, function() {
$(this).removeClass('ui-state-hover');
});
};
var edit_bar_interval = null;
var enableEditBar = function() {
edit_bar_interval = window.setInterval('enableEditBar2()', 100);
}
var enableEditBar2 = function() {
if ($('#edit-bar-ui').length) {
window.clearInterval(edit_bar_interval);
$('#content-views-ui li a').hover(function() {
$(this).addClass('ui-state-hover');
}, function() {
$(this).removeClass('ui-state-hover');
});
$('#content-views-ui li a').css('border', '0').css('line-height', '2em');
$('#contentActionMenus-ui dl.actionMenu').hover(function() {
$(this).addClass('ui-state-hover ui-corner-bottom').css('border', '0px');
}, function() {
$(this).removeClass('ui-state-hover ui-corner-bttom');
});
$('#contentActionMenus-ui a.actionMenuSelected').addClass('ui-state-default ui-corner-all');
$('#contentActionMenus-ui a').addClass('ui-corner-all');
$('#contentActionMenus-ui a').hover(function() {
$(this).addClass('ui-state-hover');
}, function() {
$(this).removeClass('ui-state-hover');
});
$('dd.actionMenuContent').addClass('ui-state-active');
}
} | zettwerk.ui | /zettwerk.ui-2.0.zip/zettwerk.ui-2.0/zettwerk/ui/static/gui.js | gui.js |
Introduction
============
At the point of writing, zettwerk.users provides an additional view /@@userlist_view. This view can be found via the plone controlpanel "Zettwerk Users".
It lists the users, available in your plone instance, and shows your wether the user already logged in or not. You can select all users that did not log in yet and reset their passwords. However, it is also possible to select single users by hand.
You can filter the users by groups. By default, all users are shown.
Installation
============
Just put zettwerk.users into your buildout.cfg
[instance]
...
eggs += zettwerk.users
zcml += zettwerk.users
...
Use the portal_quickinstaller to register the "Zettwerk Users" to the controlpanel.
| zettwerk.users | /zettwerk.users-0.1.tar.gz/zettwerk.users-0.1/README.txt | README.txt |
from Acquisition import aq_inner
from zope.interface import implements, Interface
from Products.Five import BrowserView
from Products.CMFCore.utils import getToolByName
from Products.statusmessages.interfaces import IStatusMessage
from Products.CMFPlone.PloneBatch import Batch
from zettwerk.users import usersMessageFactory as _
class IUserListView(Interface):
"""
UserList view interface
"""
class UserListView(BrowserView):
"""
UserList browser view
"""
implements(IUserListView)
def __init__(self, context, request):
self.context = context
self.request = request
self.pagesize = 20
self.selectcurrentbatch = False
self.selectedusers = []
self.selectorphan = False
@property
def portal_catalog(self):
return getToolByName(self.context, 'portal_catalog')
@property
def portal(self):
return getToolByName(self.context, 'portal_url').getPortalObject()
@property
def portal_membership(self):
return getToolByName(self.context, 'portal_membership')
@property
def portal_groups(self):
return getToolByName(self.context, 'portal_groups')
@property
def plone_url(self):
return self.portal.absolute_url()
@property
def show_select_all_items(self):
return not self.request.get('select', '').lower() in ('all',
'batch')
@property
def show_select_orphan_items(self):
return not self.request.get('select', '').lower() in ('orphan',)
def _getMembers(self):
""" Returns a list of members """
return self.portal_membership.listMembers()
def _getMembersByGroup(self, group_id):
""" Returns a list of members of a group """
group = self.portal_groups.getGroupById(group_id)
if group:
return group.getGroupMembers()
return []
def _getMemberInfo(self, member):
""" Returns necessary infos of member """
login_time = member.getProperty('login_time')
initial_login = str(login_time) != '2000/01/01'
return {'fullname': member.getProperty('fullname'),
'username': member.getId(),
'email': member.getProperty('email'),
'url': self.plone_url + '/author/' + member.getId(),
'last_login_time': member.getProperty('last_login_time'),
'initial_login': initial_login,
'checked': False}
def _setChecked(self, member_info, checked=[]):
""" Updates member_info, sets 'checked': True or False """
member_info['checked'] = self.selectcurrentbatch\
or member_info['username'] in self.selectedusers
if self.selectorphan and not member_info.get('initial_login', True):
member_info['checked'] = True
return member_info
def _getContents(self, group_id):
""" returns a list of contents """
if group_id:
contents = self._getMembersByGroup(group_id)
else:
contents = self._getMembers()
return contents
def _resetPasswords(self):
""" Reset password of requested users.
Returns number of reset password requests """
selected_all = not self.show_select_all_items
selected_orphan = not self.show_select_orphan_items
ptool = getToolByName(self.context, 'portal_registration')
group_id = self.request.get('group_id', None)
if selected_all:
members = [m.getId() for m in self._getContents(group_id)]
elif selected_orphan:
contents = map(self._getMemberInfo, self._getContents(group_id))
members = [m['username'] for m in contents
if not m.get('initial_login', False)]
else:
members = self.request.get('users')
if not isinstance(members, (list, tuple)):
raise(TypeError('members must be list or tuple'))
ret = 0
for member in members:
try:
ptool.mailPassword(member, self.request)
ret += 1
except ValueError:
# XXX: Logging? but should not happen in reality?
pass
return ret
def _countOrphan(self, members):
""" Return number of orphan members """
return sum([int(not m.get('initial_login', False)) for m in members])
def getUsers(self):
""" Returns list of users """
b_start = self.request.get('b_start', 0)
show_all = self.request.get('show_all', '').lower() == 'true'
group_id = self.request.get('group_id', None)
checked = self.request.get('users', [])
self.selectcurrentbatch = not self.show_select_all_items
self.selectorphan = not self.show_select_orphan_items
if isinstance(checked, basestring):
checked = [checked]
if not isinstance(checked, (list, tuple)):
raise(TypeError('checked must be list or tuple'))
self.selectedusers = checked
contents = map(self._getMemberInfo, self._getContents(group_id))
if show_all:
pagesize = len(contents)
else:
pagesize = self.pagesize
batch = Batch(contents, pagesize, b_start, orphan=1)
map(self._setChecked, batch)
batch.orphans = self._countOrphan(contents)
return batch
def __call__(self):
""" Reset passwords if necessary. Call supers __call__ """
reset_passwords = self.request.form.get('reset_passwords', None)
if reset_passwords:
ret = self._resetPasswords()
msgid = _(u"userlist_reset_passwords",
default=u"Passwords of ${count} users resetted",
mapping={u"count": ret})
# Use inherited translate() function to get the final text string
translated = self.context.translate(msgid)
# Show the final result count to the user as a status message
messages = IStatusMessage(self.request)
messages.addStatusMessage(translated, type="info")
# Redirect to this view, but forget selected items and so on...
self.request.RESPONSE.redirect(
self.context.absolute_url() + '/@@userlist_view')
return None
return super(UserListView, self).__call__() | zettwerk.users | /zettwerk.users-0.1.tar.gz/zettwerk.users-0.1/zettwerk/users/browser/userlistview.py | userlistview.py |
Zetup
=====
|image0| |image1|
.. |image0| image:: http://www.gnu.org/graphics/lgplv3-88x31.png
:target: https://gnu.org/licenses/lgpl.html
.. |image1| image:: https://img.shields.io/pypi/pyversions/zetup.svg
:target: https://python.org
|image0| |image1|
.. |image0| image:: https://img.shields.io/pypi/v/zetup.svg
:target: https://pypi.python.org/pypi/zetup
.. |image1| image:: https://img.shields.io/pypi/dd/zetup.svg
:target: https://pypi.python.org/pypi/zetup
|image0| |Build status|
.. |image0| image:: https://travis-ci.org/userzimmermann/zetup.py.svg?branch=master
:target: https://travis-ci.org/userzimmermann/zetup.py
.. |Build status| image:: https://ci.appveyor.com/api/projects/status/3wm8jnisoft5x7qr?svg=true
:target: https://ci.appveyor.com/project/userzimmermann/zetup-py
Zimmermann's Python Package Setup
---------------------------------
- https://bitbucket.org/userzimmermann/zetup.py
- https://github.com/userzimmermann/zetup.py
- https://www.openhub.net/p/python-zetup
| zetup | /zetup-0.2.64.tar.gz/zetup-0.2.64/README.rst | README.rst |
# ZETUP | Zimmermann's Extensible Tools for Unified Projects
[](
https://gnu.org/licenses/lgpl.html)
[](
https://python.org)
[](
https://pypi.python.org/pypi/zetup)
[](
https://pypi.python.org/pypi/zetup)
[](
https://travis-ci.org/zimmermanncode/zetup)
[](
https://ci.appveyor.com/project/zimmermanncode/zetup)
[](
https://www.openhub.net/p/python-zetup)
**Hg** repository: https://bitbucket.org/zimmermanncode/zetup
**Git** mirror repositories:
* https://github.com/zimmermanncode/zetup
* https://gitlab.com/zimmermanncode/zetup
| zetup | /zetup-0.2.64.tar.gz/zetup-0.2.64/README.md | README.md |
# ZETUP
[](
https://gnu.org/licenses/lgpl.html)
[](
https://python.org)
[](
https://pypi.python.org/pypi/zetup)
[](
https://pypi.python.org/pypi/zetup)
[](
https://travis-ci.org/userzimmermann/zetup.py)
[](
https://ci.appveyor.com/project/userzimmermann/zetup-py)
## Zimmermann's Extensible Tools for Unified Project setups
* https://bitbucket.org/zimmermanncode/zetup
* https://github.com/zimmermanncode/zetup
* https://gitlab.com/zimmermanncode/zetup
* https://www.openhub.net/p/python-zetup
| zetup | /zetup-0.2.64.tar.gz/zetup-0.2.64/README.ipynb | README.ipynb |
# `zetuptools`
`zetuptools` contains a command line tool, `install-directives`, used to aid in post-install and post-uninstall steps for packages installed with `pip`.
It originally had some other functions I considered useful in a `setup.py` file, but these have been scrapped as of version 3.0 as they cause too many dependecy confusions.
## Usage
The idea is to write a custom class that extends `InstallDirective`, overriding its `_install` and `_uninstall` functions. This should be placed in a Python package called `install_directives`.
These overridden functions will be automatically called upon running the command line tool as such.
```text
usage: install-directives [-h] [--log_level {CRITICAL,ERROR,WARNING,INFO,DEBUG}] package {install,uninstall}
positional arguments:
package
{install,uninstall}
optional arguments:
-h, --help show this help message and exit
--log_level {CRITICAL,ERROR,WARNING,INFO,DEBUG}
how verbose
```
See [`apt-repo`](https://github.com/zmarffy/apt-repo) for a real-world example of this. Note the placement of `install_directives` as well as the fact that the README mentions that you should run `install-directives apt-repo install` after the `pip` package is installed.
Note that this is extremely helpful for building Docker images related to the project. There is a function called `build_docker_images` that will do just that. Check out its docstring.
`install-directives [package_name] uninstall` should be run *before* the uninstallation of the `pip` package. Similarly, a `remove_docker_images` function exists.
| zetuptools | /zetuptools-3.0.0.tar.gz/zetuptools-3.0.0/README.md | README.md |
.. -*- mode: rst -*-
|TravisBuild| |Colab| |PythonVersions| |Coveralls| |ReadTheDocs| |LGTM| |Black|
.. |TravisBuild| image:: https://travis-ci.org/nkthiebaut/zeugma.svg?branch=master&service=github
:target: https://travis-ci.org/nkthiebaut/zeugma
.. |Colab| image:: https://colab.research.google.com/assets/colab-badge.svg
:target: https://colab.research.google.com/github/nkthiebaut/zeugma/
.. |PythonVersions| image:: https://img.shields.io/pypi/pyversions/zeugma.svg
:target: https://github.com/nkthiebaut/zeugma
.. |Coveralls| image:: https://img.shields.io/coveralls/github/nkthiebaut/zeugma.svg
:target: https://coveralls.io/github/nkthiebaut/zeugma?branch=master
.. |ReadTheDocs| image:: https://readthedocs.org/projects/zeugma/badge/
:target: https://zeugma.readthedocs.io/en/latest/
.. |LGTM| image:: https://img.shields.io/lgtm/grade/python/g/nkthiebaut/zeugma.svg?logo=lgtm
:target: https://lgtm.com/projects/g/nkthiebaut/zeugma/context:python
.. |Black| image:: https://img.shields.io/badge/code%20style-black-000000.svg
:target: https://github.com/ambv/black
======
Zeugma
======
.. inclusion-marker-do-not-remove
📝 Natural language processing (NLP) utils: word embeddings (Word2Vec, GloVe, FastText, ...) and preprocessing transformers, compatible with `scikit-learn Pipelines <http://scikit-learn.org/stable/modules/generated/sklearn.pipeline.Pipeline.html>`_. 🛠 Check the `documentation <https://zeugma.readthedocs.io/en/latest/>`_ for more information.
Installation
------------
Install package with ``pip install zeugma``.
Examples
--------
Embedding transformers can be either be used with downloaded embeddings (they
all come with a default embedding URL) or trained.
Pretrained embeddings
*********************
As an illustrative example the cosine similarity of the sentences *what is zeugma* and *a figure of speech* is computed using the `GloVe <https://nlp.stanford.edu/projects/glove/>`_ pretrained embeddings.::
>>> from zeugma.embeddings import EmbeddingTransformer
>>> glove = EmbeddingTransformer('glove')
>>> embeddings = glove.transform(['what is zeugma', 'a figure of speech'])
>>> from sklearn.metrics.pairwise import cosine_similarity
>>> cosine_similarity(embeddings)[0, 1]
0.8721696
Training embeddings
*******************
To train your own Word2Vec embeddings use the `Gensim sklearn API <https://radimrehurek.com/gensim/sklearn_api/w2vmodel.html>`_.
Fine-tuning embeddings
**********************
Embeddings fine tuning (training embeddings with preloaded values) will be implemented in the future.
Other examples
**************
Usage examples are present in the ``examples`` folder.
Additional examples using Zeugma can be found `in some posts of my blog <https://data4thought.com>`_.
Contribute
----------
Feel free to fork this repo and submit a Pull Request.
Development
***********
The development workflow for this repo is the following:
1. create a virtual environment: ``python -m venv venv && source venv/bin/activate``
2. install required packages: ``pip install -r requirements.txt``
3. install the pre-commit hooks: ``pre-commit install``
4. install the package itself in editable mode: ``pip install -e .``
5. run the test suite with: ``pytest`` from the root folder
Distribution via PyPI
*********************
To upload a new version to PyPI, simply:
1. tag your new version on git: ``git tag -a x.x -m "my tag message"``
2. update the download_url field in the ``setup.py`` file
3. commit, push the code and the tag (``git push origin x.x``), and make a PR
4. Make sure you have a ``.pypirc`` file structured like `this <https://docs.python.org/3.3/distutils/packageindex.html#the-pypirc-file>`_ in your home folder (you can use ``https://upload.pypi.org/legacy/`` for the URL field)
5. once the updated code is present in master run ``python setup.py sdist && twine upload dist/*`` from the root of the package to distribute it.
Building documentation
**********************
To build the documentation locally simply run ``make html`` from the ``docs`` folder.
Bonus: what's a zeugma?
-----------------------
It's a figure of speech: "The act of using a word, particularly an adjective or verb, to apply to more than one noun when its sense is appropriate to only one." (from `Wiktionary <https://en.wiktionary.org/wiki/zeugma>`_).
For example, "He lost his wallet and his mind." is a zeugma.
| zeugma | /zeugma-0.49.tar.gz/zeugma-0.49/README.rst | README.rst |
Zeus client
===========
Zeus client is a command line tool to facilitate execution of advanced zeus_
election administrative operations such as cryptographical mix and partial
decryption of submitted ballots.
.. _zeus: https://zeus.grnet.gr/
Install
-------
.. hint::
Python 2.7 along with the pip packaging tool is required to be installed_
Installing `zeus-client` tool should be as simple as ::
$ pip install zeus-client
$ zeus-client --help
.. _installed: https://www.python.org/downloads/
Remote mix
----------
The `mix` command can be used for elections with `remote mixing` enabled during
initial election parametrization. Once election voting closes and zeus
completes the first mix of encrypted ballots, Zeus produces the election remote
mix URL to the election administrator. The URL can be shared across the
preferred set of participants as required by the election process. Each
participant takes part to the election mix as follows::
- Download previously set of mixed ciphers
- Generate a new mix
- Upload the new ballot mix (will be used as input for the next mix)
`zeus-client` automatically takes care of all of the above steps::
$ zeus-client mix <election-mix-url> <mix-id> <rounds> <parallel>
# e.g.
$ zeus-client mix https://zeus-testing.grnet.gr/zeus/elections/election-uuid/mix/unique-id my-election 128 4
- **election-mix-url** the election mix URL as provided by the election
administrator.
- **mix-id** is an election identification string used as a prefix
for the generated filenames.
- **rounds** is an integer related to mixnet security
parameters. Using a low number produces fast results but could diminish mix
security. It is advised to use an integer equal or greater than `128`.
- **parallel** should be set to the number of CPU cores of your system.
Decryption
----------
1. Download election ciphertexts::
$ zeus-client download ciphers "<trustee-login-url>" ballots-encrypted
2. Compute partial decryptions
$ zeus-client decrypt ballots-encrypted ballots-partially-decrypted "<path-to-trustee-secret-key>"
3. Submit partial decryptions
$ zeus-client upload factors ballots-partially-decrypted "<trustee-login-url>"
| zeus-client | /zeus-client-0.1.7.tar.gz/zeus-client-0.1.7/README.client.rst | README.client.rst |
The Zeus election server
========================
LICENCE: This code is released under the GPL v3 or later
This is a fork of Ben Adida's Helios server. The differences from Helios are as follows:
* Whereas Helios produces election results, Zeus produces a tally of the ballots cast.
* This allows Zeus to be used in voting systems other than approval voting (which is supported
by Helios), since the vote tally can be fed to any other system that actually produces the
election results.
* In terms of overall architecture and implementation it is closer to the [original Helios
implementation](http://static.usenix.org/events/sec08/tech/full_papers/adida/adida.pdf) than Helios v. 3.
| zeus-client | /zeus-client-0.1.7.tar.gz/zeus-client-0.1.7/README.md | README.md |
import os
import sys
PYTHON_MAJOR = sys.version_info[0]
from datetime import datetime
from random import randint, choice as rand_choice
from collections import deque
from hashlib import sha256, sha1
from itertools import izip, izip_longest, cycle, chain, repeat
from math import log
from bisect import bisect_right
import Crypto.Util.number as number
inverse = number.inverse
from Crypto import Random
from os import (fork, kill, getpid, waitpid, ftruncate, lseek, fstat,
read, write, unlink, open as os_open, close,
O_CREAT, O_RDWR, O_APPEND, SEEK_CUR, SEEK_SET)
from fcntl import flock, LOCK_EX, LOCK_UN
from multiprocessing import Semaphore, Queue as mpQueue
from Queue import Empty, Full
from select import select
from signal import SIGKILL
from errno import ESRCH
from cStringIO import StringIO
from marshal import loads as marshal_loads, dumps as marshal_dumps
from json import load as json_load
import inspect
import importlib
from time import time, sleep
try:
from gmpy import mpz
_pow = pow
def pow(b, e, m):
return int(_pow(mpz(b), e, m))
except ImportError:
print "Warning: Could not import gmpy. Falling back to SLOW crypto."
bit_length = lambda num: num.bit_length()
if sys.version_info < (2, 7):
def bit_length(num):
s = bin(num)
s = s.lstrip('-0b')
return len(s)
class ZeusError(Exception):
pass
ALPHA = 0
BETA = 1
PROOF = 2
VOTER_KEY_CEIL = 2**256
VOTER_SLOT_CEIL = 2**48
MIN_MIX_ROUNDS = 3
V_CAST_VOTE = 'CAST VOTE'
V_PUBLIC_AUDIT = 'PUBLIC AUDIT'
V_PUBLIC_AUDIT_FAILED = 'PUBLIC AUDIT FAILED'
V_AUDIT_REQUEST = 'AUDIT REQUEST'
V_FINGERPRINT = 'FINGERPRINT: '
V_INDEX = 'INDEX: '
V_PREVIOUS = 'PREVIOUS VOTE: '
V_VOTER = 'VOTER: '
V_ELECTION = 'ELECTION PUBLIC: '
V_ZEUS_PUBLIC = 'ZEUS PUBLIC: '
V_TRUSTEES = 'TRUSTEE PUBLICS: '
V_CANDIDATES = 'CANDIDATES: '
V_MODULUS = 'MODULUS: '
V_GENERATOR = 'GENERATOR: '
V_ORDER = 'ORDER: '
V_ALPHA = 'ALPHA: '
V_BETA = 'BETA: '
V_COMMITMENT = 'COMMITMENT: '
V_CHALLENGE = 'CHALLENGE: '
V_RESPONSE = 'RESPONSE: '
V_COMMENTS = 'COMMENTS: '
_random_generator_file = Random.new()
def c2048():
p = 19936216778566278769000253703181821530777724513886984297472278095277636456087690955868900309738872419217596317525891498128424073395840060513894962337598264322558055230566786268714502738012916669517912719860309819086261817093999047426105645828097562635912023767088410684153615689914052935698627462693772783508681806906452733153116119222181911280990397752728529137894709311659730447623090500459340155653968608895572426146788021409657502780399150625362771073012861137005134355305397837208305921803153308069591184864176876279550962831273252563865904505239163777934648725590326075580394712644972925907314817076990800469107L
q = (p - 1) / 2
g0 = 9413060360466448686039353223715000895476653994878292629580005715413149309413036670654764332965742884842644976907757623558004566639402772235441684360505344528020498265000752015019397070007216279360736764344882321624397028370364113905272387950790871846302871493514381824738727519597460997038917208851728646071589006043553117796202327835258471557309074326286364547643265711871602511049432774864712871101230345650552324151494772279651818096255453921354231946373043379760842748887723994561573824188324702878924365252191380946510359485948529040410642676919518011031107993744638249385966735471272747905107277767654692463409L
g = pow(g0, 2, p)
x = 1469094658184849175779600697490107440856998313689389490776822841770551060089241836869172678278809937016665355003873748036083276189561224629758766413235740137792419398556764972234641620802215276336480535455350626659186073159498839187349683464453803368381196713476682865017622180273953889824537824501190403304240471132731832092945870620932265054884989114885295452717633367777747206369772317509159592997530169042333075097870804756411795033721522447406584029422454978336174636570508703615698164528722276189939139007204305798392366034278815933412668128491320768153146364358419045059174243838675639479996053159200364750820L
y = pow(g, x, p)
return p, q, g, x, y
def c4096():
p = 989739086584899206262870941495275160824429055560857686533827330176266094758539805894052465425543742758378056898916975688830042897464663659316565658681455337631927169716594388227886841821639348093631558865282436882702647379556880510663048896169189712894445414625772725732980365633359489925655152255197807877415565545449245335018149917344244391646710898790373814092708148348289809496148127266128833710713633812316745730790666494269135285419129739194203790948402949190257625314846368819402852639076747258804218169971481348145318863502143264235860548952952629360195804480954275950242210138303839522271423213661499105830190864499755639732898861749724262040063985288535046880936634385786991760416836059387492478292392296693123148006004504907256931727674349140604415435481566616601234362361163612719971993921275099527816595952109693903651179235539510208063074745067478443861419069632592470768800311029260991453478110191856848938562584343057011570850668669874203441257913658507505815731791465642613383737548884273783647521116197224510681540408057273432623662515464447911234487758557242493633676467408119838655147603852339915225523319492414694881196888820764825261617098818167419935357949154327914941970389468946121733826997098869038220817867L
q = (p - 1) / 2
g0 = 905379109279378054831667933021934383049203365537289539394872239929964585601843446288620085443488215849235670964548330175314482714496692320746423694498241639600420478719942396782710397961384242806030551242192462751290192948710587865133212966245479354320246142602442604733345159076201107781809110926242797620743135121644363670775798795477440466184912353407400277976761890802684500243308628180860899087380817190547647023064960578905266420963880594962888959726707822636419644103299943828117478223829675719242465626206333420547052590211049681468686068299735376912002300947541151842072332585948807353379717577259205480481848616672575793598861753734098315126325768793219682113886710293716896643847366229743727909553144369466788439959883261553813689358512428875932488880462227384092880763795982392286068303024867839002503956419627171380097115921561294617590444883631704182199378743252195067113032765888842970561649353739790451845746283977126938388768194155261756458620157130236063008120298689861009201257816492322336749660466823368953374665392072697027974796990473518319104748485861774121624711704031122201281866933558898944724654566536575747335471017845835905901881155585701928903481835039679354164368715779020008195518681150433222291955165L
g = pow(g0, 2, p)
x = 647933544049795511827798129172072110981142881302659046504851880714758189954678388061140591638507897688860150172786162388977702691017897290499481587217235024527398988456841084908316048392761588172586494519258100136278585068551347732010458598151493508354286285844575102407190886593809138094472405420010538813082865337021620149988134381297015579494516853390895025461601426731339937104058096140467926750506030942064743367210283897615531268109510758446261715511997406060121720139820616153611665890031155426795567735688778815148659805920368916905139235816256626015209460683662523842754345740675086282580899535810538696220285715754930732549385883748798637705838427072703804103334932744710977146180956976178075890301249522417212403111332457542823335873806433530059450282385350277072533852089242268226463602337771206993440307129522655918026737300583697821541073342234103193338354556016483037272142964453985093357683693494958668743388232300130381063922852993385893280464288436851062428165061787405879100666008436508712657212533042512552400211216182296391299371649632892185300062585730422510058896752881990053421349276475246102235172848735409746894932366562445227945573810219957699804623611666670328066491935505098459909869015330820515152531557L
y = pow(g, x, p)
return p, q, g, x, y
p, q, g, x, y = c2048()
_default_crypto = {}
_default_crypto['modulus'] = p
_default_crypto['order'] = q
_default_crypto['generator'] = g
_default_public_key = {}
_default_public_key.update(_default_crypto)
_default_public_key['public'] = y
_default_secret_key = {}
_default_secret_key.update(_default_crypto)
_default_secret_key['secret'] = x
def crypto_args(cryptosys):
return [cryptosys['modulus'], cryptosys['generator'], cryptosys['order']]
def crypto_from_args(p, g, q):
return {'modulus': p, 'generator': g, 'order': q}
def key_proof(k):
return [k['commitment'], k['challenge'], k['response']]
def key_public(pk):
return pk['public']
def key_secret(sk):
return sk['secret']
def pk_args(pk):
return [pk['modulus'], pk['generator'], pk['order'], pk['public']]
def pk_all_args(pk):
return [pk['modulus'], pk['generator'], pk['order'], pk['public'],
['commitment'], pk['challenge'], pk['response']]
def pk_noproof_from_args(p, g, q, y):
return {'modulus': p, 'generator': g, 'order': q, 'public': y}
def pk_from_args(p, g, q, y, t, c, f):
return {'modulus': p, 'generator': g, 'order': q, 'public': y,
'commitment': t, 'challenge': c, 'response': f}
def sk_args(pk):
return [pk['modulus'], pk['generator'], pk['order'], pk['secret']]
def sk_all_args(sk):
return [sk['modulus'], sk['generator'], sk['order'],
sk['secret'], sk['public'],
['commitment'], sk['challenge'], sk['response']]
def sk_from_args(p, g, q, x, y, t, c, f):
return {'modulus': p, 'generator': g, 'order': q,
'secret': x, 'public': y,
'commitment': t, 'challenge': c, 'response': f}
def get_timestamp():
return datetime.strftime(datetime.utcnow(), "%Y-%m-%dT%H:%M:%S.%fZ")
def to_canonical(obj, out=None):
toplevel = 0
if out is None:
toplevel = 1
out = StringIO()
if isinstance(obj, basestring):
if isinstance(obj, unicode):
obj = obj.encode('utf-8')
z = len(obj)
x = "%x" % z
w = ("%02x" % len(x))[:2]
out.write("%s%s_" % (w, x))
out.write(obj)
elif isinstance(obj, int) or isinstance(obj, long):
s = "%x" % obj
z = len(s)
x = "%x" % z
w = ("%02x" % len(x))[:2]
out.write("%s%s0%s" % (w, x, s))
elif isinstance(obj, dict):
out.write('{\x0a')
cobj = {}
for k, v in obj.iteritems():
if not isinstance(k, str):
if isinstance(k, unicode):
k = k.encode('utf-8')
elif isinstance(k, int) or isinstance(k, long):
k = str(k)
else:
m = "Unsupported dict key type '%s'" % (type(k),)
cobj[k] = v
del obj
keys = cobj.keys()
keys.sort()
prev = None
for k in keys:
if prev is not None:
out.write(',\x0a')
if k == prev:
tail = '...' if len(k) > 64 else ''
m = "duplicate key '%s' in dict" % (k[:64] + tail,)
raise AssertionError(m)
to_canonical(k, out=out)
out.write(': ')
to_canonical(cobj[k], out=out)
prev = k
out.write('}\x0a')
elif isinstance(obj, list) or isinstance(obj, tuple):
out.write('[\x0a')
iterobj = iter(obj)
for o in iterobj:
to_canonical(o, out=out)
break
for o in iterobj:
out.write(',\x0a')
to_canonical(o, out=out)
out.write(']\x0a')
elif obj is None:
out.write('null')
else:
m = "to_canonical: invalid object type '%s'" % (type(obj),)
raise AssertionError(m)
if toplevel:
out.seek(0)
return out.read()
def from_canonical(inp, unicode_strings=0, s=''):
if isinstance(inp, str):
inp = StringIO(inp)
read = inp.read
if not s:
s = read(2)
if s == 'nu':
s += read(2)
if s == 'null':
return None
else:
m = ("byte %d: invalid token '%s' instead of 'null'"
% (inp.tell(), s))
raise ValueError(m)
if s == '[\x0a':
obj = []
append = obj.append
while 1:
s = read(2)
if not s:
m = "byte %d: eof within a list" % inp.tell()
raise ValueError(m)
if s == ']\x0a':
return obj
item = from_canonical(inp, unicode_strings=unicode_strings, s=s)
append(item)
s = read(2)
if s == ']\x0a':
return obj
if s != ',\x0a':
m = ("byte %d: in list: illegal token '%s' instead of ',\\n'"
% (inp.tell(), s))
raise ValueError(m)
if s == '{\x0a':
obj = {}
while 1:
s = read(2)
if not s:
m = "byte %d: eof within dict" % inp.tell()
raise ValueError(m)
if s == '}\x0a':
return obj
key = from_canonical(inp, unicode_strings=unicode_strings, s=s)
s = read(2)
if s != ': ':
m = ("byte %d: invalid token '%s' instead of ': '"
% (inp.tell(), s))
raise ValueError(m)
value = from_canonical(inp, unicode_strings=unicode_strings)
obj[key] = value # allow key TypeError rise through
s = read(2)
if not s:
m = "byte %d: eof inside dict" % inp.tell()
raise ValueError(m)
if s == '}\x0a':
return obj
if s != ',\x0a':
m = ("byte %d: illegal token '%s' in dict instead of ',\\n'"
% (inp.tell(), s))
raise ValueError(m)
w = int(s, 16)
s = read(w)
if len(s) != w:
m = "byte %d: eof while reading header size %d" % (inp.tell(), w)
raise ValueError(m)
z = int(s, 16)
c = read(1)
if not c:
m = "byte %d: eof while reading object tag" % inp.tell()
raise ValueError(m)
s = read(z)
if len(s) != z:
m = "byte %d: eof while reading object size %d" % (inp.tell(), z)
raise ValueError(m)
if c == '_':
if unicode_strings:
try:
s = s.decode('utf-8')
except UnicodeDecodeError:
pass
return s
elif c == '0':
num = int(s, 16)
return num
else:
m = "byte %d: invalid object tag '%d'" % (inp.tell()-z, c)
raise ValueError(m)
#class Empty(Exception):
# pass
#class Full(Exception):
# pass
class EOF(Exception):
pass
MV_ASYNCARGS = '=ASYNCARGS='
MV_EXCEPTION = '=EXCEPTION='
def wait_read(fd, block=True, timeout=0):
if block:
timeout = None
while 1:
r, w, x = select([fd], [], [], timeout)
if not r:
if not block:
raise Empty()
else:
raise EOF("Select Error")
if block:
st = fstat(fd)
if not st.st_size:
sleep(0.01)
continue
def read_all(fd, size):
got = 0
s = ''
while got < size:
r = read(fd, size-got)
if not r:
break
got += len(r)
s += r
return s
def wait_write(fd, block=True, timeout=0):
if block:
timeout = None
r, w, x = select([], [fd], [], timeout)
if not w:
if not block:
raise Full()
else:
raise EOF("Write Error")
def write_all(fd, data):
size = len(data)
written = 0
while written < size:
w = write(fd, buffer(data, written, size-written))
if not w:
m = "Write EOF"
raise EOF(m)
written += w
return written
class CheapQueue(object):
_initpid = None
_pid = _initpid
_serial = 0
@classmethod
def atfork(cls):
cls._pid = getpid()
def __init__(self):
pid = getpid()
self._initpid = pid
self._pid = None
serial = CheapQueue._serial + 1
CheapQueue._serial = serial
self.serial = serial
self.frontfile = '/dev/shm/cheapQ.%s.%s.front' % (pid, serial)
self.backfile = '/dev/shm/cheapQ.%s.%s.back' % (pid, serial)
self.front_fd = None
self.back_fd = None
self.front_sem = Semaphore(0)
self.back_sem = Semaphore(0)
self.getcount = 0
self.putcount = 0
self.get_input = self.init_input
self.get_output = self.init_output
def init(self):
frontfile = self.frontfile
self.front_fd = os_open(frontfile, O_RDWR|O_CREAT|O_APPEND, 0600)
backfile = self.backfile
self.back_fd = os_open(backfile, O_RDWR|O_CREAT|O_APPEND, 0600)
self._pid = getpid()
del self.get_output
del self.get_input
def __del__(self):
try:
close(self.front_fd)
close(self.back_fd)
unlink(self.frontfile)
unlink(self.backfile)
except:
pass
def init_input(self):
self.init()
return self.get_input()
def init_output(self):
self.init()
return self.get_output()
def get_input(self):
if self._pid == self._initpid:
return self.front_sem, self.front_fd
else:
return self.back_sem, self.back_fd
def get_output(self):
if self._pid == self._initpid:
return self.back_sem, self.back_fd
else:
return self.front_sem, self.front_fd
def down(self, sema, timeout=None):
#if timeout is None:
# print ("REQ DOWN %d %d %d [%d %d]"
# % (self.serial, getpid(), sema._semlock.handle,
# self.front_sem._semlock.handle,
# self.back_sem._semlock.handle))
ret = sema.acquire(True, timeout=timeout)
#if ret:
# print "DOWN %d %d" % (self.serial, getpid())
return ret
def up(self, sema, timeout=None):
sema.release()
#print ("UP %d %d %d [%d %d]"
# % (self.serial, getpid(), sema._semlock.handle,
# self.front_sem._semlock.handle,
# self.back_sem._semlock.handle))
def put(self, obj, block=True, timeout=0):
data = marshal_dumps(obj)
sema, fd = self.get_output()
#if self._pid == self._initpid:
# print "> PUT ", getpid(), self.serial, self.putcount, '-'
#else:
# print " PUT <", getpid(), self.serial, self.putcount, '-'
chk = sha256(data).digest()
flock(fd, LOCK_EX)
try:
write_all(fd, "%016x%s" % (len(data), chk))
write_all(fd, data)
finally:
flock(fd, LOCK_UN)
self.up(sema)
self.putcount += 1
def get(self, block=True, timeout=0):
if block:
timeout=None
sema, fd = self.get_input()
#if self._pid == self._initpid:
# print "< GET ", getpid(), self.serial, self.getcount, '-'
#else:
# print " GET >", getpid(), self.serial, self.getcount, '-'
if not self.down(sema, timeout=timeout):
raise Empty()
flock(fd, LOCK_EX)
try:
header = read_all(fd, 48)
chk = header[16:]
header = header[:16]
size = int(header, 16)
data = read_all(fd, size)
pos = lseek(fd, 0, SEEK_CUR)
if pos > 1048576:
st = fstat(fd)
if pos >= st.st_size:
ftruncate(fd, 0)
lseek(fd, 0, SEEK_SET)
finally:
flock(fd, LOCK_UN)
_chk = sha256(data).digest()
if chk != _chk:
raise AssertionError("Corrupt Data!")
obj = marshal_loads(data)
self.getcount += 1
return obj
Queue = mpQueue
if os.path.exists("/dev/shm"):
Queue = CheapQueue
def async_call(func, args, kw, channel):
argspec = inspect.getargspec(func)
if argspec.keywords or 'async_channel' in argspec.args:
kw['async_channel'] = channel
return func(*args, **kw)
def async_worker(link):
while 1:
inp = link.receive()
if inp is None:
break
try:
if not isinstance(inp, tuple) and inp and inp[0] != MV_ASYNCARGS:
m = "%x: first input not in MV_ASYNCARGS format: '%s'" % (inp,)
raise ValueError(m)
mv, mod, func, args, kw = inp
mod = importlib.import_module(mod)
func = getattr(mod, func)
ret = async_call(func, args, kw, link)
link.send(ret)
except Exception, e:
import traceback
e = (MV_EXCEPTION, traceback.format_exc())
link.send_shared(e)
raise
finally:
link.disconnect()
class AsyncWorkerLink(object):
def __init__(self, pool, index):
self.pool = pool
self.index = index
def send(self, data, wait=1):
self.pool.master_queue.put((self.index, data), block=wait)
def receive(self, wait=1):
ret = self.pool.worker_queues[self.index].get(block=wait)
if isinstance(ret, tuple) and ret and ret[0] == MV_EXCEPTION:
raise Exception(ret[1])
return ret
def send_shared(self, data, wait=1):
self.pool.master_queue.put((0, data), block=wait)
def disconnect(self, wait=1):
self.pool.master_queue.put((self.index, None), block=wait)
class AsyncWorkerPool(object):
def __init__(self, nr_parallel, worker_func):
master_queue = Queue()
self.master_queue = master_queue
self.worker_queues = [master_queue] + [
Queue() for _ in xrange(nr_parallel)]
worker_pids = []
self.worker_pids = worker_pids
append = worker_pids.append
for i in xrange(nr_parallel):
pid = fork()
Random.atfork()
CheapQueue.atfork()
if not pid:
try:
worker_link = AsyncWorkerLink(self, i+1)
worker_func(worker_link)
finally:
try:
kill(getpid(), SIGKILL)
except:
pass
while 1:
print "PLEASE KILL ME"
sleep(1)
append(pid)
def kill(self):
for pid in self.worker_pids:
try:
kill(pid, SIGKILL)
waitpid(pid, 0)
except OSError, e:
if e.errno != ESRCH:
raise
def send(self, worker, data):
if not worker:
m = "Controller attempt to write to master link"
raise AssertionError(m)
self.worker_queues[worker].put(data)
def receive(self, wait=1):
try:
val = self.master_queue.get(block=wait)
except Empty:
val = None
return val
class AsyncChannel(object):
def __init__(self, controller):
self.controller = controller
self.channel_no = controller.get_channel()
def send(self, data):
return self.controller.send(self.channel_no, data)
def receive(self, wait=1):
data = self.controller.receive(self.channel_no, wait=wait)
if isinstance(data, tuple) and data and data[0] == MV_EXCEPTION:
raise Exception(data[1])
return data
class AsyncFunc(object):
def __init__(self, controller, func, args, kw):
self.controller = controller
self.func = func
self.args = args
self.kw = kw
def __call__(self, *args, **kw):
call_kw = dict(self.kw)
call_kw.update(kw)
call_args = self.args + args
call_func = self.func
controller = self.controller
async_args = (MV_ASYNCARGS,
call_func.__module__, call_func.__name__,
call_args, call_kw)
channel = AsyncChannel(controller)
controller.submit(channel.channel_no, async_args)
return channel
class AsyncController(object):
serial = 0
parallel = 0
channel_queue = None
shared_queue = None
def __new__(cls, *args, **kw):
parallel = int(kw.get('parallel', 2))
self = object.__new__(cls)
master_link = AsyncWorkerPool(parallel, async_worker)
self.master_link = master_link
self.idle_workers = set(xrange(1, parallel + 1))
self.worker_to_channel = [0] + [None] * (parallel)
self.channel_to_worker = {0: 0}
self.pending = deque()
self.channels = {0: deque()}
self.parallel = parallel
return self
def __del__(self):
self.shutdown()
def shutdown(self):
master_link = self.master_link
for i in xrange(1, self.parallel + 1):
master_link.send(i, None)
sleep(0.3)
self.master_link.kill()
def get_channel(self):
channel = self.serial + 1
self.serial = channel
return channel
def process(self, wait=0):
master_link = self.master_link
idle_workers = self.idle_workers
pending = self.pending
channel_to_worker = self.channel_to_worker
worker_to_channel = self.worker_to_channel
channels = self.channels
_wait = wait
while 1:
blocked = []
while pending:
channel, data = pending.pop()
if channel in channel_to_worker:
worker = channel_to_worker[channel]
master_link.send(worker, data)
elif not idle_workers:
blocked.append((channel, data))
else:
worker = idle_workers.pop()
channel_to_worker[channel] = worker
worker_to_channel[worker] = channel
master_link.send(worker, data)
for b in blocked:
pending.appendleft(b)
data = master_link.receive(wait=_wait)
if data is None:
break
_wait = 0
worker, data = data
channel = worker_to_channel[worker]
if channel is None:
continue
if data is None:
if worker > 0:
worker_to_channel[worker] = None
else:
m = "Attempt to disconnect master link"
raise AssertionError(m)
if channel > 0:
del channel_to_worker[channel]
else:
m = "Attempt to close master channel"
raise AssertionError(m)
idle_workers.add(worker)
else:
channels[channel].appendleft(data)
def send(self, channel_no, data):
channel_to_worker = self.channel_to_worker
if channel_no not in channel_to_worker:
return
worker = channel_to_worker[channel_no]
self.master_link.send(worker, data)
def receive(self, channel_no, wait=1):
channels = self.channels
if channel_no not in channels:
return None
self.process(wait=0)
while 1:
if not channels[channel_no]:
if (channel_no is not None and
channel_no not in self.channel_to_worker):
del channels[channel_no]
return None
if not wait:
return None
self.process(wait=1)
else:
val = channels[channel_no].pop()
return val
def receive_shared(self, wait=1):
val = self.receive(0, wait=wait)
if isinstance(val, tuple) and val and val[0] == MV_EXCEPTION:
raise Exception(val[1])
return val
def submit(self, channel_no, async_args):
channels = self.channels
if channel_no in channels:
m = "Channel already in use"
raise ValueError(m)
channels[channel_no] = deque()
self.pending.appendleft((channel_no, async_args))
if self.parallel <= 0:
async_worker
self.process(wait=0)
def make_async(self, func, *args, **kw):
return AsyncFunc(self, func, args, kw)
class TellerStream(object):
def __init__(self, outstream=None, output_interval_ms=2000,
buffering=1, buffer_feeds=0):
self.oms = output_interval_ms
self.outstream = outstream
self.last_output = 0
self.last_eject = 0
self.buffer_feeds = buffer_feeds
self.buffering = buffering
self.buffered_lines = []
def write(self, data):
buffer_feeds = self.buffer_feeds
eject = not buffer_feeds and (1 if '\n' in data else 0)
if not self.buffering:
self.buffered_lines = []
self.buffered_lines.append(data)
t = time()
tdiff = (t - self.last_output) * 1000.0
if eject or self.last_eject or tdiff > self.oms:
self.last_output = t
self.flush()
self.last_eject = eject
def flush(self):
outstream = self.outstream
if outstream:
outstream.write(''.join(self.buffered_lines))
self.buffered_lines = []
class Teller(object):
name = None
total = None
current = None
finished = None
status_fmt = None
status_args = None
start_time = None
disabled = False
children = None
parent = None
resuming = None
outstream = None
last_active = None
last_teller = [None]
last_ejected = [None]
last_line = ['']
redirect = True
fail_parent = True
raise_errors = True
default_tell = True
suppress_exceptions = False
default_status_fmt = '%d/%d'
eol = '\r'
feed = '\n'
prefix_filler = '| '
status_sep = ' ... '
start_mark = '-- '
pending_mark = '| '
notice_mark = '| :: '
fail_mark = '!! '
finish_mark = '++ '
start_status = ' '
pending_status = ' '
fail_status = '*FAIL*'
finish_status = ' -OK- '
def __init__(self, name='', total=1, current=0, depth=0,
parent=None, resume=False, subtask=False,
outstream=sys.stderr, **kw):
if subtask and parent:
name = str(parent) + '/' + name
self.feed = ''
self.name = name
self.depth = depth
self.total = total
self.current = current
self.clear_size = 0
self.parent = parent
self.children = {}
self.set_format()
self.resuming = resume
self.outstream = outstream
self.start_time = time()
for k, v in kw.iteritems():
a = getattr(self, k, None)
if (a is None and not (isinstance(a, basestring)
or isinstance(a, bool))):
continue
setattr(self, k, v)
def set_format(self):
current = self.current
total = self.total
if total == 1:
self.status_fmt = ''
self.status_args = ()
return
self.status_fmt = self.default_status_fmt
self.status_args = (current, total)
def kill_child(self, child_id):
children = self.children
if child_id in children:
del children[child_id]
def __str__(self):
total = self.total
current = self.current
status_fmt = self.status_fmt
if status_fmt is None:
self.set_format()
status_fmt = self.status_fmt
start_time = self.start_time
running_time = time() - start_time
finished = self.finished
if finished is None:
mark = self.start_mark
status = self.start_status
elif finished > 0:
mark = self.finish_mark
status = self.finish_status
elif finished < 0:
mark = self.fail_mark
status = self.fail_status
elif finished == 0:
mark = self.pending_mark
status = self.pending_status
else:
m = "Finished not None or int: %r" % (finished,)
raise ValueError(m)
line = (self.prefix_filler * (self.depth - 1)) + mark
line += self.name + self.status_sep
line += self.status_fmt % self.status_args
line += status
if running_time > 2 and current > 0 and current < total:
ss = running_time * (total - current) / current
mm = ss / 60
ss = ss % 60
hh = mm / 60
mm = mm % 60
line += 'approx. %02d:%02d:%02d left' % (hh, mm, ss)
return line
def disable(self):
self.disabled = True
for child in self.children.values():
child.disable()
def tell(self, feed=False, eject=False):
if self.disabled:
return
line = self.__str__()
self.output(line, feed=feed, eject=eject)
def output(self, text, feed=False, eject=0):
outstream = self.outstream
if outstream is None or self.disabled:
return
feeder = self.feed
eol = self.eol
text += eol
last_line = self.last_line
if eol.endswith('\r'):
clear_line = ' ' * len(last_line[0]) + '\r'
else:
clear_line = ''
text = clear_line + text
last_teller = self.last_teller
teller = last_teller[0]
last_ejected = self.last_ejected
ejected = last_ejected[0]
if not ejected and (feed or teller != self):
text = feeder + text
if eject:
text += feeder * eject
outstream.write(text)
last_teller[0] = self
last_ejected[0] = eject
junk, sep, last = text.rpartition('\n')
last_line[0] = last[len(clear_line):]
def check_tell(self, tell, feed=False, eject=False):
if tell or (tell is None and self.default_tell):
self.tell(feed=feed, eject=eject)
def active(self):
if not self.redirect:
return self
last_active = self.last_active
if (last_active is not None
and last_active == self.last_teller[0]
and not last_active.disabled):
return last_active
while 1:
children = self.children
if not children:
return self
if len(children) != 1:
m = ("Cannot redirect: more than one children are active! "
"Either start one children at a time, "
"or set redirect=False")
raise ValueError(m)
self, = children.values()
return self
def task(self, name='', total=1, current=0,
resume=False, subtask=False, **kw):
self = self.active()
children = self.children
kw['parent'] = self
kw['depth'] = self.depth + 1
kw['outstream'] = self.outstream
kw['fail_parent'] = self.fail_parent
kw['active'] = self.active
task = self.__class__(name=name, total=total, current=current,
resume=resume, subtask=subtask, **kw)
children[id(task)] = task
task.check_tell(None)
return task
def notice(self, fmt, *args):
self = self.active()
text = fmt % args
lines = []
append = lines.append
for text_line in text.split('\n'):
line = self.prefix_filler * (self.depth-1) + self.notice_mark
line += text_line
append(line)
final_text = '\n'.join(lines)
self.output(final_text, feed=1, eject=1)
def __enter__(self):
if self.disabled:
m = "Task '%s' has been disabled" % (self.name,)
raise ValueError(m)
return self
def __exit__(self, exc_type, exc_val, exc_tb):
if exc_type is None:
if not self.resuming:
self.end(1)
self.resuming = 0
return None
self.end(-1)
if self.raise_errors:
return None
if not self.suppress_exceptions:
import traceback
traceback.print_exc()
return True
def end(self, finished, name='', tell=None):
if self.disabled:
return
self.finished = finished
eject = 2
parent = self.parent
if parent and parent.parent:
eject = 1
self.check_tell(tell, eject=eject)
task = self
while 1:
if task is None or task.name.startswith(name):
break
task = task.parent
if task is not None:
parent = task.parent
if parent is not None:
parent.kill_child(id(task))
if finished < 0 and task.fail_parent:
parent.fail(tell=tell)
task.disable()
def resume(self):
self = self.active()
self.resuming = 1
return self
def status(self, status_fmt, *status_args, **kw):
self = self.active()
tell = kw.get('tell', None)
self.status_fmt = status_fmt
self.status_args = status_args
self.check_tell(tell)
def progress(self, current, tell=None):
self = self.active()
self.current = current
total = self.total
self.status_fmt = self.default_status_fmt
self.status_args = (current, total)
if total and current >= total:
self.finished = 1
self.check_tell(tell)
def advance(self, delta_current=1, tell=None):
self = self.active()
current = self.current + delta_current
self.current = current
total = self.total
self.status_fmt = self.default_status_fmt
self.status_args = (current, total)
if total and current >= total:
self.finished = 1
self.check_tell(tell)
def get_current(self):
self = self.active()
return self.current
def get_total(self):
self = self.active()
return self.total
def get_finished(self):
self = self.active()
return self.finished
def finish(self, name='', tell=None):
self = self.active()
return self.end(1, name=name, tell=tell)
def fail(self, name='', tell=None):
self = self.active()
return self.end(-1, name=name, tell=tell)
_teller = Teller()
def validate_cryptosystem(modulus, generator, order, teller=_teller):
m = None
p = modulus
g = generator
q = order
with teller.task("Validating Cryptosystem", resume=1):
teller.notice("modulus : %s...", ("%x" % p)[:32])
teller.notice("generator : %s...", ("%x" % g)[:32])
teller.notice("group order : %s...", ("%x" % q)[:32])
task = teller.task
with task("is the modulus size >= 2048 bits?"):
if log(p, 2) <= 2047:
m = "MODULUS BIT SIZE < 2048"
raise AssertionError(m)
with task("is the modulus 3mod4?"):
if p % 4 != 3:
m = "MODULUS NOT 3(MOD 4)"
raise AssertionError(m)
with task("is the modulus prime?"):
if not number.isPrime(p):
m = "MODULUS NOT PRIME"
raise AssertionError(m)
with task("is the ElGamal group order prime?"):
if not number.isPrime(q):
m = "ELGAMAL GROUP ORDER NOT PRIME"
raise AssertionError(m)
with task("is the ElGamal group, the modulus quadratic residues?"):
if 2*q + 1 != p:
m = "ELGAMAL GROUP IS NOT THE MODULUS' QUADRATIC RESIDUES"
raise AssertionError(m)
with task("is the generator size >= 2000 bits?"):
if log(g, 2) <= 2000:
m = "GENERATOR SMALLER THAN 2000 BITS"
raise AssertionError(m)
with task("is the generator valid?"):
if g >= p and pow(g, q, p) != 1:
m = "INVALID ELGAMAL GROUP GENERATOR"
raise AssertionError(m)
if m is not None:
teller.fail()
else:
teller.finish()
return not m
def get_choice_params(nr_choices, nr_candidates=None, max_choices=None):
if nr_candidates is None:
nr_candidates = nr_choices
if max_choices is None:
max_choices = nr_candidates
if nr_choices < 0 or nr_candidates <= 0 or max_choices <= 0:
m = ("invalid parameters not (%d < 0 or %d <= 0 or %d <= 0)"
% (nr_choices, nr_candidates, max_choices))
raise ZeusError(m)
if nr_choices > max_choices:
m = ("Invalid number of choices (%d expected up to %d)" %
(nr_choices, max_choices))
raise AssertionError(m)
return [nr_candidates, max_choices]
def validate_choices(choices, nr_candidates=None, max_choices=None):
nr_candidates, max_choices = \
get_choice_params(len(choices), nr_candidates, max_choices)
choice_iter = iter(enumerate(choices))
for i, choice in choice_iter:
m = nr_candidates - i
if choice < 0 or choice >= m:
m = "Choice #%d: %d not in range [%d, %d]" % (i, choice, 0, m)
raise AssertionError(m)
m -= 1
return 1
def permutation_to_selection(permutation):
nr_elements = len(permutation)
lefts = list([None]) * nr_elements
rights = list([None]) * nr_elements
offsets = list([None]) * nr_elements
shifts = list([0]) * nr_elements
maxdepth = 0
iter_permutation = iter(permutation)
for offset in iter_permutation:
offsets[0] = offset
break
pop = 1
selection = [offset]
output = selection.append
for offset in iter_permutation:
node = 0
shift = 0
depth = 0
while 1:
node_offset = offsets[node]
if offset < node_offset:
shifts[node] += 1
left = lefts[node]
if left is None:
left = pop
pop += 1
offsets[left] = offset
lefts[node] = left
break
node = left
elif offset > node_offset:
right = rights[node]
shift += shifts[node] + 1
if right is None:
right = pop
pop += 1
offsets[right] = offset
rights[node] = right
break
node = right
else:
m = "Duplicate offset insert: %d!" % offset
raise ValueError(m)
depth += 1
output(offset - shift)
if depth > maxdepth:
maxdepth = depth
return selection
def get_random_selection(nr_elements, full=1):
selection = []
variable = not bool(full)
append = selection.append
for m in xrange(nr_elements, 1, -1):
r = get_random_int(0, m+variable)
if r == m:
break
append(r)
else:
append(0)
return selection
def get_random_party_selection(nr_elements, nr_parties=2):
party = get_random_int(0, nr_parties)
per_party = nr_elements // nr_parties
low = party * per_party
high = (party + 1) * per_party
if nr_elements - high < per_party:
high = nr_elements
choices = []
append = choices.append
r = get_random_int(0, 2**(high - low))
for i in xrange(low, high):
skip = r & 1
r >>= 1
if skip:
continue
append(i)
return to_relative_answers(choices, nr_elements)
def selection_to_permutation(selection):
nr_elements = len(selection)
lefts = list([None]) * nr_elements
rights = list([None]) * nr_elements
leftpops = list([0]) * nr_elements
pop = 1
iter_selection = iter(reversed(selection))
for pos in iter_selection:
break
for pos in iter_selection:
node = 0
cur = 0
depth = 0
while 1:
leftpop = leftpops[node]
newcur = cur + leftpop + 1
if pos >= newcur:
right = rights[node]
if right is None:
rights[node] = pop
pop += 1
break
node = right
cur = newcur
else:
leftpops[node] += 1
left = lefts[node]
if left is None:
lefts[node] = pop
pop += 1
break
node = left
maxdepth = 0
depth = 0
stack = [0]
append = stack.append
pop = stack.pop
permutation = list([None]) * nr_elements
offset = 0
while stack:
node = pop()
if node < 0:
permutation[nr_elements + node] = offset
offset += 1
continue
depth += 1
if depth > maxdepth:
maxdepth = depth
right = rights[node]
if right is not None:
append(right)
append(-node-1)
left = lefts[node]
if left is not None:
append(left)
return permutation
def get_random_permutation(nr_elements):
return selection_to_permutation(get_random_selection(nr_elements, full=1))
_terms = {}
def get_term(n, k):
if k >= n:
return 1
if n in _terms:
t = _terms[n]
if k in t:
return t[k]
else:
t = {n: 1}
_terms[n] = t
m = k
while 1:
m += 1
if m in t:
break
term = t[m]
while 1:
term *= m
m -= 1
t[m] = term
if m <= k:
break
return term
_offsets = {}
def get_offsets(n):
if n in _offsets:
return _offsets[n]
offsets = []
append = offsets.append
sumus = 0
i = 0
while 1:
sumus += get_term(n, n-i)
append(sumus)
if i == n:
break
i += 1
_offsets[n] = offsets
return offsets
_factors = {}
def get_factor(b, n):
if n <= 1:
return 1
if b in _factors:
t = _factors[b]
if n in t:
return t[n]
else:
t = {1: 1}
_factors[b] = t
i = n
while 1:
i -= 1
if i in t:
break
f = t[i]
while 1:
f *= b + i
i += 1
t[i] = f
if i >= n:
break
return f
def gamma_encode(choices, nr_candidates=None, max_choices=None):
nr_choices = len(choices)
nr_candidates, max_choices = \
get_choice_params(nr_choices, nr_candidates, max_choices)
if not nr_choices:
return 0
offsets = get_offsets(nr_candidates)
sumus = offsets[nr_choices - 1]
b = nr_candidates - nr_choices
i = 1
while 1:
sumus += choices[-i] * get_factor(b, i)
if i >= nr_choices:
break
i += 1
return sumus
def gamma_encoding_max(nr_candidates, max_choices=None):
if max_choices is None:
max_choices = nr_candidates
if nr_candidates <= 0:
return 0
choices = range(nr_candidates - 1, nr_candidates - max_choices -1, -1)
return gamma_encode(choices, nr_candidates, max_choices)
def gamma_decode(sumus, nr_candidates=None, max_choices=None):
nr_candidates, max_choices = \
get_choice_params(nr_candidates, nr_candidates, max_choices)
if sumus <= 0:
return []
offsets = get_offsets(nr_candidates)
nr_choices = bisect_right(offsets, sumus)
sumus -= offsets[nr_choices - 1]
choices = []
append = choices.append
b = nr_candidates - nr_choices
i = nr_choices
while 1:
choice, sumus = divmod(sumus, get_factor(b, i))
append(choice)
if i <= 1:
break
i -= 1
return choices
def verify_gamma_encoding(n, completeness=1):
choice_sets = {}
encode_limit = get_offsets(n)[-1]
encoded_limit = gamma_encode(range(n-1, -1, -1), n) + 1
if encode_limit != encoded_limit:
m = "Incorrect encode limit %d vs %d!" % (encode_limit, encoded_limit)
raise AssertionError(m)
for encoded in xrange(encode_limit):
choices = tuple(gamma_decode(encoded, n))
new_encoded = gamma_encode(choices, n)
if new_encoded != encoded:
m = ("Incorrect encoding %s to %d instead of %d"
% (choices, new_encoded, encoded))
raise AssertionError(m)
if not completeness:
continue
nr_choices = len(choices)
if nr_choices not in choice_sets:
choice_sets[nr_choices] = set()
choice_set = choice_sets[nr_choices]
if choices in choice_set:
m = ("Duplicate decoding for %d: %s!" % (encoded, choices))
choice_set.add(choices)
if not completeness:
return
for i in xrange(n + 1):
if i not in choice_sets:
m = "Encoding is not bijective! missing choice set %d" % (i,)
AssertionError(m)
c = len(choice_sets[i])
t = get_term(n, n-i)
if c != t:
m = ("Encoding is not bijective! "
"length-%d choices are %d instead of %d"
% (i, c, t))
raise AssertionError(m)
print "%d length-%d choices OK" % (c, i)
def factorial_encode(choices, nr_candidates=None, max_choices=None):
nr_choices = len(choices)
nr_candidates, max_choices = \
get_choice_params(nr_choices, nr_candidates, max_choices)
sumus = 0
base = nr_candidates + 1
factor = 1
for choice in choices:
choice += 1
if choice >= base:
m = ("Cannot vote for %dth candidate when there are only %d remaining"
% (choice, base - 1))
raise ZeusError(m)
sumus += choice * factor
factor *= base
base -= 1
return sumus
def factorial_decode(encoded, nr_candidates=None, max_choices=None):
nr_candidates, max_choices = \
get_choice_params(nr_candidates, nr_candidates, max_choices)
if encoded <= 0:
return []
sumus = encoded
factors = []
append = factors.append
base = nr_candidates + 1
factor = 1
while factor <= sumus:
append(factor)
factor *= base
base -= 1
factors.reverse()
choices = []
append = choices.append
for factor in factors:
choice, sumus = divmod(sumus, factor)
if choice == 0:
break
append(choice - 1)
if sumus != 0:
m = ("Invalid encoding %d" % (encoded,))
raise AssertionError(m)
nr_choices = len(choices)
if nr_choices > max_choices:
m = ("Decoding came up with more choices than allowed: %d > %d"
% (nr_choices, max_choices))
raise AssertionError(m)
choices.reverse()
return choices
def maxbase_encode(choices, nr_candidates=None, max_choices=None):
nr_candidates, max_choices = \
get_choice_params(len(choices), nr_candidates, max_choices)
base = nr_candidates + 2
sumus = 0
e = 1
for i, choice in enumerate(choices):
sumus += (choice + 1) * e
e *= base
return sumus
def maxbase_decode(sumus, nr_candidates, max_choices=None):
nr_candidates, max_choices = \
get_choice_params(nr_candidates, nr_candidates, max_choices)
choices = []
append = choices.append
base = nr_candidates + 2
while sumus > 0:
sumus, choice = divmod(sumus, base)
append(choice - 1)
return choices
def cross_check_encodings(n):
# verify_gamma_encoding(n)
encode_limit = gamma_encode(range(n-1, -1, -1), n) + 1
for e in xrange(encode_limit):
choices = gamma_decode(e, n)
maxbase_encoded = maxbase_encode(choices, n)
maxbase_choices = maxbase_decode(maxbase_encoded, n)
factorial_encoded = factorial_encode(choices, n)
factorial_choices = factorial_decode(factorial_encoded, n)
if (factorial_choices != maxbase_choices
or factorial_choices != choices
or maxbase_choices != choices):
m = ("gamma_encoded: %d, choices mismatch: "
"gamma %s, maxbase %s, factorial %s"
% (e, choices, maxbase_choices, factorial_choices))
raise AssertionError(m)
def gamma_decode_to_candidates(encoded, candidates):
nr_candidates = len(candidates)
selection = gamma_decode(encoded, nr_candidates)
choices = to_absolute_answers(selection, nr_candidates)
return [candidates[i] for i in choices]
def gamma_count_candidates(encoded_list, candidates):
encoded_list = sorted(encoded_list)
iter_encoded_list = iter(encoded_list)
lastone = None
counts = []
append = counts.append
for lastone in iter_encoded_list:
count = 1
break
for encoded in chain(iter_encoded_list, [None]):
if encoded == lastone:
count += 1
else:
append([count] + gamma_decode_to_candidates(lastone, candidates))
count = 1
lastone = encoded
return counts
def range_split_candidates(candidates_and_points):
candidates = []
pointlist = []
iterator = iter(candidates_and_points)
old_nr_points = None
expecting_candidate = True
candidates_over = False
points_over = False
for entry in iterator:
if not entry:
m = "Invalid candidate entry {entry!r}"
m = m.format(entry=entry)
raise FormatError(m)
while True:
if points_over or expecting_candidate:
assert not candidates_over
if entry[0].isdigit():
if points_over:
m = "Invalid candidate {entry!r}"
m = m.format(entry=entry)
raise FormatError(m)
else:
candidates_over = True
expecting_candidate = False
continue
candidates.append(entry)
if not points_over:
expecting_candidate = False
break
if candidates_over or not expecting_candidate:
assert not points_over
if not entry.isdigit():
if candidates_over:
m = "Invalid points form {entry!r}"
m = m.format(entry=entry)
raise FormatError(m)
else:
points_over = True
continue
nr_points = int(entry)
if nr_points <= 0:
m = "Invalid points value {nr}"
m = m.format(nr=nr_points)
raise FormatError(m)
if old_nr_points is not None and nr_points >= old_nr_points:
m = "Invalid points <{nr_points}> not in descending order!"
m = m.format(nr_points=nr_points)
raise FormatError(m)
old_nr_points = nr_points
pointlist.append(nr_points)
if not candidates_over:
expecting_candidate = True
break
raise AssertionError()
if not candidates or not pointlist:
m = ("Neither candidates ({candidates}) "
"nor point list ({pointlist}) can be empty")
m = m.format(candidates=candidates, pointlist=pointlist)
raise FormatError(m)
return candidates, pointlist
def gamma_decode_to_range_ballot(encoded, candidates_and_points):
nr_candidates = len(candidates_and_points)
selection = gamma_decode(encoded, nr_candidates=nr_candidates,
max_choices=nr_candidates)
permutation = to_absolute_answers(selection, nr_candidates)
ballot = {}
counts = {}
valid = False
candidate = None
old_nr_points = None
for i, index in enumerate(permutation):
choice = candidates_and_points[index]
if i & 1:
if not choice or not choice.isdigit():
valid = False
break
nr_points = int(choice)
if old_nr_points is not None and nr_points >= old_nr_points:
valid = False
break
old_nr_points = nr_points
assert candidate is not None
assert candidate not in counts
counts[candidate] = nr_points
candidate = None
else:
assert candidate is None
if not choice or choice[0].isdigit():
valid = False
break
candidate = choice
else:
# no break or exception
if candidate is None:
ballot['candidates'] = counts
valid = True
else:
valid = False
ballot['valid'] = valid
return ballot
def combine_candidates_and_points(candidates, points):
candidates_and_points = []
append = candidates_and_points.append
for c, p in izip_longest(candidates, points):
if c is not None:
append(c)
if p is not None:
append(str(p))
return candidates_and_points
def range_params_from_candidates(candidates):
params = candidates[-1]
try:
params = map(int, params.split('-'))
candidates = candidates[:-1]
except ValueError:
params = [0, len(candidates)]
return candidates, '-'.join(map(str, params))
def gamma_count_range(encoded_list, candidates_and_points, params=None):
if params is None:
candidates_and_points, params = \
range_params_from_candidates(candidates_and_points)
candidates, pointlist = range_split_candidates(candidates_and_points)
detailed = {}
totals = {}
ballots = []
min_choices, max_choices = map(int, params.strip().split("-"))
max_encoded = gamma_encoding_max(len(candidates_and_points))
for c in candidates:
candidate_stats = {}
for points in pointlist:
candidate_stats[points] = 0
detailed[c] = candidate_stats
totals[c] = 0
for e in encoded_list:
assert isinstance(e, (int, long))
if e > max_encoded:
ballot = {'valid': False}
else:
ballot = gamma_decode_to_range_ballot(e, candidates_and_points)
ballots.append(ballot)
if not ballot['valid']:
continue
# validate min/max choices
if ballot['valid']:
nr_choices = len(ballot['candidates'].keys())
if nr_choices != 0 and (nr_choices > max_choices or \
nr_choices < min_choices):
ballot['valid'] = False
ballot_scores = ballot['candidates']
for candidate, points in ballot_scores.iteritems():
assert candidate in candidates
totals[candidate] += points
detailed[candidate][points] += 1
results = {}
results['candidates'] = candidates
results['points'] = pointlist
totals = [(v, k) for k, v in totals.iteritems()]
totals.sort()
totals.reverse()
results['totals'] = totals
results['detailed'] = detailed
results['ballots'] = ballots
return results
PARTY_SEPARATOR = ': '
PARTY_OPTION_SEPARATOR = ', '
def strforce(thing, encoding='utf8'):
if isinstance(thing, unicode):
return thing.encode(encoding)
return str(thing)
class FormatError(ValueError):
pass
def parse_party_options(optstring):
substrings = optstring.split(PARTY_OPTION_SEPARATOR, 1)
range_str = substrings[0]
r = range_str.split('-')
if len(r) != 2:
m = ("Malformed min-max choices option '%s'"
% (range_str,))
raise FormatError(m)
min_choices, max_choices = r
try:
min_choices = int(min_choices)
max_choices = int(max_choices)
except ValueError:
m = ("Malformed numbers in "
"min-max choices option in '%s'" % (optstring,))
raise FormatError(m)
group = None
if len(substrings) == 2:
group_str = substrings[1]
try:
group = int(group_str)
except ValueError:
m = "Malformed decimal group number in option '%s'" % (group_str,)
raise FormatError(m)
options = {'opt_min_choices': min_choices,
'opt_max_choices': max_choices,
'group': group}
return options
def parties_from_candidates(candidates, separator=PARTY_SEPARATOR):
parties = {}
theparty = None
group_no = 0
nr_groups = 1
for i, candidate in enumerate(candidates):
candidate = strforce(candidate)
party, sep, name = candidate.partition(separator)
if party and not name:
name = party
party = ''
if theparty is None or party != theparty:
if party not in parties:
opts = parse_party_options(name)
group = opts['group']
if group is None:
group = group_no
opts['group'] = group
if group not in (group_no, nr_groups):
m = ("Party group numbers must begin at zero and "
"increase monotonically. Expected %d but got %d") % (
group_no, opts['group'])
raise FormatError(m)
group_no = group
nr_groups = group + 1
opts['choice_index'] = i
parties[party] = opts
theparty = party
continue
parties[theparty][i] = name
return parties, nr_groups
def gamma_decode_to_party_ballot(encoded, candidates, parties, nr_groups,
separator=PARTY_SEPARATOR):
nr_candidates = len(candidates)
selection = gamma_decode(encoded, nr_candidates)
choices = to_absolute_answers(selection, nr_candidates)
voted_candidates = []
voted_parties = []
voted_parties_counts = {}
last_index = -1
thegroup = None
party_list = None
valid = True
invalid_reason = None
no_candidates_flag = 0
for i in choices:
if i <= last_index or no_candidates_flag:
valid = False
invalid_reason = ("invalid index: %d <= %d -- choices: %s"
% (i, last_index, choices))
voted_candidates = None
thegroup = None
break
last_index = i
candidate = candidates[i]
candidate = strforce(candidate)
party, sep, name = candidate.partition(separator)
if party and not name:
name = party
party = ''
if party not in parties:
m = "Voted party list not found"
raise AssertionError(m)
party_list = parties[party]
group = party_list['group']
if group >= nr_groups:
m = "Group number out of limits! (%d > %d)" % (group, nr_groups)
raise AssertionError(m)
if thegroup is None:
thegroup = group
if i == party_list['choice_index']:
no_candidates_flag = 1
#continue
if thegroup != group:
valid = False
invalid_reason = ('Choices from different groups '
'(%d, %d)') % (thegroup, group)
voted_candidates = None
thegroup = None
break
if not no_candidates_flag:
if i not in party_list:
m = "Candidate not found in party list"
raise AssertionError(m)
list_name = party_list[i]
if name != list_name:
m = "Candidate name mismatch (%s vs %s)" % (name, list_name)
raise AssertionError(m)
# name = party_list[i]
if not voted_parties or voted_parties[-1] != party:
voted_parties.append(party)
if party not in voted_parties_counts:
voted_parties_counts[party] = 0
voted_parties_counts[party] += 1
if not no_candidates_flag:
voted_candidates.append((party, name))
if choices and valid:
# validate number of choices for each party separately
for party, nr_choices in voted_parties_counts.iteritems():
party_list = parties[party]
max_choices = party_list['opt_max_choices']
min_choices = party_list['opt_min_choices']
if (nr_choices < min_choices or
nr_choices > max_choices):
valid = False
invalid_reason = ("Invalid min/max choices "
"(min: %d, max: %d, 'choices: %d") % (
min_choices, max_choices, nr_choices)
break
if not valid:
voted_candidates = None
thegroup = None
ballot = {'parties': voted_parties,
'group': thegroup,
'candidates': voted_candidates,
'invalid_reason': invalid_reason,
'valid': valid}
return ballot
def gamma_count_parties(encoded_list, candidates, separator=PARTY_SEPARATOR):
invalid_count = 0
blank_count = 0
candidate_counters = {}
party_counters = {}
ballots = []
invalid_ballots = []
invalid_append = invalid_ballots.append
append = ballots.append
parties, nr_groups = parties_from_candidates(candidates,
separator=separator)
for party, party_candidates in parties.iteritems():
party_counters[party] = 0
for index, candidate in party_candidates.iteritems():
if not isinstance(index, (int, long)):
continue
candidate_counters[(party, candidate)] = 0
for encoded in encoded_list:
ballot = gamma_decode_to_party_ballot(encoded, candidates, parties,
nr_groups, separator=separator)
if not ballot['valid']:
invalid_count += 1
invalid_append(ballot)
continue
append(ballot)
ballot_parties = ballot['parties']
for party in ballot_parties:
if party not in party_counters:
m = "Cannot find initialized counter at '%s'!" % (party)
raise AssertionError(m)
party_counters[party] += 1
ballot_candidates = ballot['candidates']
filtered_candidates = []
filtered_append = filtered_candidates.append
for party, candidate in ballot_candidates:
key = (party, candidate)
if key not in candidate_counters:
if len(ballot_candidates) != 1:
m = "Cannot find initialized counter at %s!" % (key,)
raise FormatError()
opts = parse_party_options(candidate)
filtered_append((party, ''))
continue
else:
filtered_append((party, candidate))
candidate_counters[key] += 1
ballot['candidates'] = filtered_candidates
if not ballot_parties and not ballot_candidates:
blank_count += 1
party_counts = [(-v, k) for k, v in party_counters.iteritems()]
party_counts.sort()
fmt = "%s" + separator + "%s"
party_counts = [(-v, k) for v, k in party_counts]
candidate_counts = [(-v, fmt % k)
for k, v in candidate_counters.iteritems()]
candidate_counts.sort()
candidate_counts = [(-v, k) for v, k in candidate_counts]
results = {'ballots': ballots,
'parties': parties,
'party_counts': party_counts,
'candidate_counts': candidate_counts,
'ballot_count': len(ballots) + invalid_count,
'blank_count': blank_count,
'invalid_ballots': invalid_ballots,
'invalid_count': invalid_count}
return results
def chooser(answers, candidates):
candidates = list(candidates)
nr_candidates = len(candidates)
validate_choices(answers, nr_candidates, nr_candidates)
rank = []
append = rank.append
for answer in answers:
append(candidates.pop(answer))
return [rank, candidates]
def strbin_to_int_mul(string):
# lsb
s = 0
base = 1
for c in string:
s += ord(c) * base
base *= 256
return s
def strbin_to_int_native(string):
return int.from_bytes(string)
if PYTHON_MAJOR == 3:
strbin_to_int = strbin_to_int_native
else:
strbin_to_int = strbin_to_int_mul
def bit_iterator(nr, infinite=True):
while nr:
yield nr & 1
nr >>= 1
if not infinite:
return
while 1:
yield 0
def get_random_int(minimum, ceiling):
top = ceiling - minimum
nr_bits = bit_length(top)
nr_bytes = (nr_bits - 1) / 8 + 1
strbin = _random_generator_file.read(nr_bytes)
num = strbin_to_int(strbin)
shift = bit_length(num) - nr_bits
if shift > 0:
num >>= shift
if num >= top:
num -= top
return num + minimum
def get_random_element(modulus, generator, order):
exponent = get_random_int(2, order)
element = pow(generator, exponent, modulus)
return element
def validate_element(modulus, generator, order, element):
legendre = pow(element, order, modulus)
return legendre == 1
def encrypt(message, modulus, generator, order, public, randomness=None):
if randomness is None:
randomness = get_random_int(1, order)
message = message + 1
if message >= order:
m = "message is too large"
raise ValueError(m)
legendre = pow(message, order, modulus)
if legendre != 1:
message = -message % modulus
alpha = pow(generator, randomness, modulus)
beta = (message * pow(public, randomness, modulus)) % modulus
return [alpha, beta, randomness]
def decrypt_with_randomness(modulus, generator, order, public,
beta, secret):
encoded = pow(public, secret, modulus)
encoded = inverse(encoded, modulus)
encoded = (encoded * beta) % modulus
if encoded >= order:
encoded = -encoded % modulus
return encoded - 1
def decrypt_with_decryptor(modulus, generator, order, beta, decryptor):
decryptor = inverse(decryptor, modulus)
message = (decryptor * beta) % modulus
legendre = pow(message, order, modulus)
if legendre not in (0, 1, -1 % modulus):
m = "This should be impossible. Invalid encryption."
raise AssertionError(m)
if message >= order:
message = -message % modulus
return message - 1
def decrypt(modulus, generator, order, secret, alpha, beta):
decryptor = pow(alpha, secret, modulus)
return decrypt_with_decryptor(modulus, generator, order, beta, decryptor)
def numbers_hash(numbers):
h = sha256()
update = h.update
for num in numbers:
update("%x:" % num)
return h.hexdigest()
def texts_hash(texts):
h = sha256()
texts_gen = ((t.encode('utf8') if not isinstance(t, str) else t)
for t in texts)
h.update('\x00'.join(texts_gen))
return h.digest()
def number_from_texts_hash(modulus, *texts):
digest = texts_hash(texts)
number = strbin_to_int(digest) % modulus
return number
def number_from_numbers_hash(modulus, *numbers):
digest = numbers_hash(numbers)
number = strbin_to_int(digest) % modulus
return number
def element_from_texts_hash(modulus, generator, order, *texts):
num_hash = numbers_hash((modulus, generator, order))
digest = texts_hash((num_hash,) + texts)
number = strbin_to_int(digest) % order
element = pow(generator, number, modulus)
return element
def element_from_elements_hash(modulus, generator, order, *elements):
digest = numbers_hash((modulus, generator, order) + elements)
number = strbin_to_int(digest) % order
element = pow(generator, number, modulus)
return element
def prove_dlog_zeus(modulus, generator, order, power, dlog,
*extra_challenge_input):
randomness = get_random_int(2, order)
commitment = pow(generator, randomness, modulus)
challenge = element_from_elements_hash(modulus, generator, order,
power, commitment,
*extra_challenge_input)
response = (randomness + challenge * dlog) % order
return [commitment, challenge, response]
def verify_dlog_power_zeus(modulus, generator, order, power,
commitment, challenge, response,
*extra_challenge_input):
_challenge = element_from_elements_hash(modulus, generator, order,
power, commitment,
*extra_challenge_input)
if _challenge != challenge:
return 0
return (pow(generator, response, modulus)
== ((commitment * pow(power, challenge, modulus)) % modulus))
prove_dlog = prove_dlog_zeus
verify_dlog_power = verify_dlog_power_zeus
def generate_keypair(modulus, generator, order, secret_key=None):
if secret_key is None:
secret_key = get_random_element(modulus, generator, order)
elif not validate_element(modulus, generator, order, secret_key):
m = "Invalid secret key is not a quadratic residue"
raise AssertionError(m)
public = pow(generator, secret_key, modulus)
commitment, challenge, response = \
prove_dlog(modulus, generator, order, public, secret_key)
return [secret_key, public, commitment, challenge, response]
def validate_public_key(modulus, generator, order, public_key,
commitment, challenge, response):
if not validate_element(modulus, generator, order, public_key):
return 0
return verify_dlog_power(modulus, generator, order, public_key,
commitment, challenge, response)
def prove_ddh_tuple_zeus(modulus, generator, order,
message, base_power, message_power, exponent):
randomness = get_random_int(2, order)
base_commitment = pow(generator, randomness, modulus)
message_commitment = pow(message, randomness, modulus)
args = (modulus, generator, order, base_power, base_commitment,
message, message_power, message_commitment)
challenge = element_from_elements_hash(*args)
response = (randomness + challenge * exponent) % order
return [base_commitment, message_commitment, challenge, response]
def verify_ddh_tuple_zeus(modulus, generator, order,
message, base_power, message_power,
base_commitment, message_commitment,
challenge, response):
args = (modulus, generator, order, base_power, base_commitment,
message, message_power, message_commitment)
_challenge = element_from_elements_hash(*args)
if _challenge != challenge:
return 0
b = (base_commitment * pow(base_power, challenge, modulus)) % modulus
if b != pow(generator, response, modulus):
return 0
m = (message_commitment * pow(message_power, challenge, modulus)) % modulus
if m != pow(message, response, modulus):
return 0
return 1
prove_ddh_tuple = prove_ddh_tuple_zeus
verify_ddh_tuple = verify_ddh_tuple_zeus
def prove_encryption(modulus, generator, order, alpha, beta, secret):
"""Prove ElGamal encryption"""
ret = prove_dlog(modulus, generator, order, alpha, secret, beta)
commitment, challenge, response = ret
return [commitment, challenge, response]
def verify_encryption(modulus, generator, order, alpha, beta,
commitment, challenge, response):
"""Verify ElGamal encryption"""
ret = verify_dlog_power(modulus, generator, order, alpha,
commitment, challenge, response, beta)
return ret
def sign_element(element, modulus, generator, order, key):
"""Compute ElGamal signature"""
while 1:
w = 2 * get_random_int(3, order) - 1
r = pow(generator, w, modulus)
modulus1 = modulus - 1
w = inverse(w, modulus1)
s = (w * ((element - (r*key) % modulus1))) % modulus1
if s != 0:
break
return {'r': r, 's': s, 'e': element,
'crypto': {'modulus': modulus,
'generator': generator,
'order': order}}
def verify_element_signature(signature, modulus, generator, order, public):
"""Verify ElGamal signature"""
r = signature['r']
s = signature['s']
e = signature['e']
if 'crypto' in signature:
crypto = signature['crypto']
if (crypto['modulus'] != modulus or
crypto['generator'] != generator or
crypto['order'] != order):
return 0
if r <= 0 or r >= modulus:
return 0
x0 = (pow(public, r, modulus) * pow(r, s, modulus)) % modulus
x1 = pow(generator, e, modulus)
if x0 != x1:
return 0
return 1
def sign_text_message(text_message, modulus, generator, order, key):
element = element_from_texts_hash(modulus, generator, order, text_message)
signature = sign_element(element, modulus, generator, order, key)
signature['m'] = text_message
return signature
def verify_text_signature(signature, modulus, generator, order, public):
text_message = signature['m']
element = element_from_texts_hash(modulus, generator, order, text_message)
if element != signature['e']:
return 0
return verify_element_signature(signature,
modulus, generator, order, public)
def encode_selection(selection, nr_candidates=None):
if nr_candidates is None:
nr_candidates = len(selection)
return gamma_encode(selection, nr_candidates, nr_candidates)
def vote_from_encoded(modulus, generator, order, public,
voter, encoded, nr_candidates,
audit_code=None, publish=None):
alpha, beta, rnd = encrypt(encoded, modulus, generator, order, public)
proof = prove_encryption(modulus, generator, order, alpha, beta, rnd)
commitment, challenge, response = proof
eb = {'modulus': modulus,
'generator': generator,
'order': order,
'public': public,
'alpha': alpha,
'beta': beta,
'commitment': commitment,
'challenge': challenge,
'response': response}
fingerprint = numbers_hash((modulus, generator, alpha, beta,
commitment, challenge, response))
vote = {'voter': voter,
'fingerprint': fingerprint,
'encrypted_ballot': eb}
if audit_code:
vote['audit_code'] = audit_code
if publish:
vote['voter_secret'] = rnd
return vote
def sign_vote(vote, trustees, candidates, comments,
modulus, generator, order, public, secret):
eb = vote['encrypted_ballot']
election = eb['public']
fingerprint = vote['fingerprint']
previous_vote = vote['previous']
index = vote['index']
status = vote['status']
m00 = status
m01 = (V_FINGERPRINT + "%s") % fingerprint
m02 = (V_INDEX + "%s") % (("%d" % index) if index is not None else 'NONE')
m03 = (V_PREVIOUS + "%s") % (previous_vote,)
m04 = (V_ELECTION + "%x") % election
m05 = (V_ZEUS_PUBLIC + "%x") % public
m06 = (V_TRUSTEES + "%s") % (' '.join(("%x" % t) for t in trustees),)
m07 = (V_CANDIDATES + "%s") % (' % '.join(("%s" % c) for c in candidates),)
m08 = (V_MODULUS + "%x") % modulus
m09 = (V_GENERATOR + "%x") % generator
m10 = (V_ORDER + "%x") % order
m11 = (V_ALPHA + "%x") % eb['alpha']
m12 = (V_BETA + "%x") % eb['beta']
m13 = (V_COMMITMENT + "%x") % eb['commitment']
m14 = (V_CHALLENGE + "%x") % eb['challenge']
m15 = (V_RESPONSE + "%x") % eb['response']
m16 = (V_COMMENTS + "%s") % (comments,)
message = '\n'.join((m00, m01, m02, m03, m04, m05, m06, m07,
m08, m09, m10, m11, m12, m13, m14, m15, m16))
signature = sign_text_message(message, modulus, generator, order, secret)
text = signature['m']
text += '\n-----------------\n'
text += '%x\n%x\n%x\n' % (signature['e'], signature['r'], signature['s'])
return text
def verify_vote_signature(vote_signature):
message, sep, e, r, s, null = vote_signature.rsplit('\n', 5)
e = int(e, 16)
r = int(r, 16)
s = int(s, 16)
(m00, m01, m02, m03, m04, m05, m06, m07,
m08, m09, m10, m11, m12, m13, m14, m15, m16) = message.split('\n', 16)
if (not (m00.startswith(V_CAST_VOTE)
or m00.startswith(V_AUDIT_REQUEST)
or m00.startswith(V_PUBLIC_AUDIT)
or m00.startswith(V_PUBLIC_AUDIT_FAILED))
or not m01.startswith(V_FINGERPRINT)
or not m02.startswith(V_INDEX)
or not m03.startswith(V_PREVIOUS)
or not m04.startswith(V_ELECTION)
or not m05.startswith(V_ZEUS_PUBLIC)
or not m06.startswith(V_TRUSTEES)
or not m07.startswith(V_CANDIDATES)
or not m08.startswith(V_MODULUS)
or not m09.startswith(V_GENERATOR)
or not m10.startswith(V_ORDER)
or not m11.startswith(V_ALPHA)
or not m12.startswith(V_BETA)
or not m13.startswith(V_COMMITMENT)
or not m14.startswith(V_CHALLENGE)
or not m15.startswith(V_RESPONSE)
or not m16.startswith(V_COMMENTS)):
m = "Invalid vote signature structure!"
raise ZeusError(m)
status = m00
fingerprint = m01[len(V_FINGERPRINT):]
index_str = m02[len(V_INDEX):]
if index_str == 'NONE':
index = None
elif index_str.isdigit():
index = int(index_str)
else:
m = "Invalid vote index '%s'" % (index_str,)
raise ZeusError(m)
previous = m03[len(V_PREVIOUS):]
public = int(m04[len(V_ELECTION):], 16)
zeus_public = int(m05[len(V_ZEUS_PUBLIC):], 16)
_m06 = m06[len(V_TRUSTEES):]
trustees = [int(x, 16) for x in _m06.split(' ')] if _m06 else []
_m07 = m07[len(V_CANDIDATES):]
candidates = _m07.split(' % ')
modulus = int(m08[len(V_MODULUS):], 16)
generator = int(m09[len(V_GENERATOR):], 16)
order = int(m10[len(V_ORDER):], 16)
alpha = int(m11[len(V_ALPHA):], 16)
beta = int(m12[len(V_BETA):], 16)
commitment = int(m13[len(V_COMMITMENT):], 16)
challenge = int(m14[len(V_CHALLENGE):], 16)
response = int(m15[len(V_RESPONSE):], 16)
comments = m16[len(V_COMMENTS):]
signature = {'m': message, 'r': r, 's': s, 'e': e}
if not verify_text_signature(signature, modulus, generator, order,
zeus_public):
m = "Invalid vote signature!"
raise ZeusError(m)
if (index is not None and
not verify_encryption(modulus, generator, order, alpha, beta,
commitment, challenge, response)):
m = "Invalid vote encryption proof in valid signature!"
raise AssertionError(m)
crypto = [modulus, generator, order]
eb = {'alpha': alpha, 'beta': beta,
'public': public,
'commitment': commitment,
'challenge': challenge,
'response': response}
vote = {'status': status,
'fingerprint': fingerprint,
'previous': previous,
'index': index,
'public': public,
'encrypted_ballot': eb}
return vote, crypto, trustees, candidates, comments
def to_relative_answers(choices, nr_candidates):
"""
Answer choices helper, convert absolute indexed answers to relative.
e.g. for candidates [A, B, C] absolute choices [1, 2, 0] will be converted
to [1, 1, 0].
"""
relative = []
candidates = list(range(nr_candidates))
choices = [candidates.index(c) for c in choices]
for choice in choices:
index = candidates.index(choice)
relative.append(index)
candidates.remove(choice)
return relative
def to_absolute_answers(choices, nr_candidates):
"""
Inverts `to_relative_answers` result.
"""
absolute_choices = []
candidates = list(range(nr_candidates))
tmp_cands = candidates[:]
for choice in choices:
choice = tmp_cands[choice]
absolute_choices.append(candidates.index(choice))
tmp_cands.remove(choice)
return absolute_choices
def get_random_permutation_gamma(nr_elements):
if nr_elements <= 0:
return []
low = list([0]) * nr_elements
high = range(nr_elements - 1, -1, -1)
max_low = gamma_encode(low, nr_elements)
max_high = gamma_encode(high, nr_elements)
rand = get_random_int(max_low, max_high + 1)
selection = gamma_decode(rand, nr_elements)
return selection
def compute_decryption_factors1(modulus, generator, order, secret, ciphers,
teller=_teller):
factors = []
public = pow(generator, secret, modulus)
append = factors.append
nr_ciphers = len(ciphers)
with teller.task("Computing decryption factors", total=nr_ciphers):
for alpha, beta in ciphers:
factor = pow(alpha, secret, modulus)
proof = prove_ddh_tuple(modulus, generator, order,
alpha, public, factor, secret)
append([factor, proof])
teller.advance()
return factors
def compute_some_decryption_factors(modulus, generator, order,
secret, public, ciphers,
teller=None, async_channel=None,
report_thresh=16):
count = 0
factors = []
append = factors.append
for alpha, beta in ciphers:
factor = pow(alpha, secret, modulus)
proof = prove_ddh_tuple(modulus, generator, order,
alpha, public, factor, secret)
append([factor, proof])
count += 1
if count >= report_thresh:
if teller is not None:
teller.advance(count)
if async_channel is not None:
async_channel.send_shared(count)
count = 0
if count:
if teller is not None:
teller.advance(count)
if async_channel is not None:
async_channel.send_shared(count)
return factors
def compute_decryption_factors(modulus, generator, order, secret, ciphers,
teller=_teller, nr_parallel=1):
if nr_parallel <= 0:
return compute_decryption_factors1(modulus, generator, order,
secret, ciphers, teller=teller)
public = pow(generator, secret, modulus)
nr_ciphers = len(ciphers)
async = AsyncController(parallel=nr_parallel)
compute_some = async.make_async(compute_some_decryption_factors)
d, q = divmod(nr_ciphers, nr_parallel)
if not d:
d = nr_ciphers
index = range(0, nr_ciphers, d)
with teller.task("Computing decryption factors", total=nr_ciphers):
channels = [compute_some(modulus, generator, order,
secret, public, ciphers[i:i+d])
for i in index]
count = 0
while count < nr_ciphers:
nr = async.receive_shared(wait=1)
teller.advance(nr)
count += nr
factors = []
for c in channels:
r = c.receive(wait=1)
factors.extend(r)
async.shutdown()
return factors
def verify_decryption_factors1(modulus, generator, order, public,
ciphers, factors, teller=_teller):
nr_ciphers = len(ciphers)
if nr_ciphers != len(factors):
return 0
with teller.task("Verifying decryption factors", total=nr_ciphers):
for cipher, factor in izip(ciphers, factors):
alpha, beta = cipher
factor, proof = factor
if not verify_ddh_tuple(modulus, generator, order, alpha, public,
factor, *proof):
teller.fail()
return 0
teller.advance()
return 1
def verify_some_decryption_factors(modulus, generator, order,
public, ciphers, factors,
teller=None, async_channel=None,
report_thresh=16):
count = 0
for cipher, factor in izip(ciphers, factors):
alpha, beta = cipher
factor, proof = factor
if not verify_ddh_tuple(modulus, generator, order, alpha, public,
factor, *proof):
if async_channel is not None:
async_channel.send_shared(-1)
if teller is not None:
teller.fail()
return 0
count += 1
if count >= report_thresh:
if teller is not None:
teller.advance(count)
if async_channel is not None:
async_channel.send_shared(count)
count = 0
if count:
if teller is not None:
teller.advance(count)
if async_channel is not None:
async_channel.send_shared(count)
return 1
def verify_decryption_factors(modulus, generator, order, public,
ciphers, factors, teller=_teller,
nr_parallel=1):
if nr_parallel <= 0:
return verify_decryption_factors1(modulus, generator, order, public,
ciphers, factors, teller=teller)
nr_ciphers = len(ciphers)
if nr_ciphers != len(factors):
return 0
async = AsyncController(parallel=nr_parallel)
verify_some = async.make_async(verify_some_decryption_factors)
d, q = divmod(nr_ciphers, nr_parallel)
if not d:
d = nr_ciphers
index = range(0, nr_ciphers, d)
with teller.task("Verifying decryption factors", total=nr_ciphers):
channels = [verify_some(modulus, generator, order,
public, ciphers[i:i+d], factors[i:i+d])
for i in index]
count = 0
while count < nr_ciphers:
nr = async.receive_shared(wait=1)
if nr < 0:
async.shutdown()
teller.fail()
return 0
teller.advance(nr)
count += nr
async.shutdown()
return 1
def combine_decryption_factors(modulus, factor_collection):
if not factor_collection:
return
master_factors = []
append = master_factors.append
for decryption_factors in izip(*factor_collection):
master_factor = 1
for factor, proof in decryption_factors:
master_factor = (master_factor * factor) % modulus
append(master_factor)
return master_factors
class ZeusCoreElection(object):
stage = 'UNINITIALIZED'
def __init__(self, cryptosystem=crypto_args(_default_crypto),
teller=_teller, shuffle_module=None,
**kw):
self.teller = teller
if shuffle_module is None:
import zeus_sk as shuffle_module
self.shuffle_module = shuffle_module
self.do_init_creating()
self.do_init_voting()
self.do_init_mixing()
self.do_init_decrypting()
self.do_init_finished()
self.init_creating(cryptosystem)
if 'nr_parallel' not in kw:
kw['nr_parallel'] = 0
self.set_option(**kw)
def do_set_stage(self, stage):
self.stage = stage
def do_get_stage(self):
return self.stage
def do_assert_stage(self, stage):
if self.stage != stage:
m = "Election must be in stage '%s' not '%s'" % (stage, self.stage)
raise ZeusError(m)
### CREATING BACKEND API ###
def do_init_creating(self):
self.cryptosys = None
self.candidates = []
self.voters = {}
self.audit_codes = {}
self.options = {}
self.zeus_secret = None
self.zeus_public = None
self.zeus_key_proof = None
self.trustees = {}
self.election_public = None
def do_store_cryptosystem(self, modulus, generator, order):
self.cryptosys = [modulus, generator, order]
def do_get_cryptosystem(self):
return self.cryptosys
def do_store_zeus_key(self, secret, public,
commitment, challenge, response):
self.zeus_secret = secret
self.zeus_public = public
self.zeus_key_proof = [commitment, challenge, response]
def do_get_zeus_secret(self):
return self.zeus_secret
def do_get_zeus_public(self):
return self.zeus_public
def do_get_zeus_key_proof(self):
return self.zeus_key_proof
def do_store_election_public(self, public):
self.election_public = public
def do_get_election_public(self):
return self.election_public
def do_get_public_election_key(self):
args = self.cryptosys + [self.election_public]
return pk_from_args(*args)
def do_get_zeus_key(self):
args = self.cryptosys
args += [self.zeus_secret, self.zeus_public]
args += self.zeus_key_proof
return sk_from_args(*args)
def do_set_option(self, kw):
self.options.update(kw)
def do_get_option(self, name):
options = self.options
return options[name] if name in options else None
def do_get_options(self):
return dict(self.options)
def do_store_trustee(self, public, commitment, challenge, response):
trustees = self.trustees
trustees[public] = [commitment, challenge, response]
def do_get_trustee(self, public):
trustees = self.trustees
if public not in trustees:
return None
return trustees[public]
def do_get_trustees(self):
return self.trustees
def do_store_candidates(self, names):
self.candidates += names
def do_get_candidates(self):
return self.candidates
def do_store_voters(self, voters):
self.voters.update(voters)
def do_get_voter(self, voter_key):
voters = self.voters
if voter_key not in voters:
return None
return voters[voter_key]
def do_get_voters(self):
return dict(self.voters)
def do_store_voter_audit_codes(self, audit_codes):
self.audit_codes.update(audit_codes)
def do_get_voter_audit_codes(self, voter_key):
audit_codes = self.audit_codes
if voter_key not in audit_codes:
return None
return audit_codes[voter_key]
def do_get_all_voter_audit_codes(self):
return dict(self.audit_codes)
### VOTING BACKEND API ###
def do_init_voting(self):
self.cast_vote_index = []
self.votes = {}
self.cast_votes = {}
self.audit_requests = {}
self.audit_publications = []
self.excluded_voters = {}
def do_store_audit_publication(self, fingerprint):
self.audit_publications.append(fingerprint)
def do_get_audit_publications(self):
return list(self.audit_publications)
def do_store_audit_request(self, fingerprint, voter_key):
audit_requests = self.audit_requests
audit_requests[fingerprint] = voter_key
def do_get_audit_request(self, fingerprint):
audit_requests = self.audit_requests
if fingerprint not in audit_requests:
return None
return audit_requests[fingerprint]
def do_get_audit_requests(self):
return dict(self.audit_requests)
def do_store_votes(self, votes):
for vote in votes:
fingerprint = vote['fingerprint']
self.votes[fingerprint] = vote
def do_get_vote(self, fingerprint):
return self.votes.get(fingerprint, None)
def do_get_votes(self):
return dict(self.votes)
def do_index_vote(self, fingerprint):
cast_vote_index = self.cast_vote_index
index = len(cast_vote_index)
cast_vote_index.append(fingerprint)
return index
def do_get_index_vote(self, index):
cast_vote_index = self.cast_vote_index
if index >= len(cast_vote_index):
return None
return cast_vote_index[index]
def do_get_vote_index(self):
return list(self.cast_vote_index)
def do_append_vote(self, voter_key, fingerprint):
cast_votes = self.cast_votes
if voter_key not in cast_votes:
cast_votes[voter_key] = []
cast_votes[voter_key].append(fingerprint)
def do_get_cast_votes(self, voter_key):
cast_votes = self.cast_votes
if voter_key not in cast_votes:
return None
return cast_votes[voter_key]
def do_get_all_cast_votes(self):
return dict(self.cast_votes)
def do_store_excluded_voter(self, voter_key, reason):
self.excluded_voters[voter_key] = reason
def do_get_excluded_voters(self):
return dict(self.excluded_voters)
def custom_audit_publication_message(self, vote):
return ''
def custom_audit_request_message(self, vote):
return ''
def custom_cast_vote_message(self, vote):
return ''
### MIXING BACKEND API ###
def do_init_mixing(self):
self.mixes = []
def do_store_mix(self, mix):
self.mixes.append(mix)
def do_get_last_mix(self):
mixes = self.mixes
if not mixes:
return None
return mixes[-1]
def do_get_all_mixes(self):
return list(self.mixes)
### DECRYPTING BACKEND API ###
def do_init_decrypting(self):
self.trustee_factors = {}
self.zeus_decryption_factors = []
def do_store_trustee_factors(self, trustee_factors):
trustee_public = trustee_factors['trustee_public']
factors = trustee_factors['decryption_factors']
self.trustee_factors[trustee_public] = factors
def do_get_all_trustee_factors(self):
return dict(self.trustee_factors)
def do_store_zeus_factors(self, zeus_decryption_factors):
self.zeus_decryption_factors = zeus_decryption_factors
def do_get_zeus_factors(self):
return self.zeus_decryption_factors
### FINISHED BACKEND API ###
def do_init_finished(self):
self.results = None
def do_store_results(self, plaintexts):
self.results = list(plaintexts)
def do_get_results(self):
return self.results
### GENERIC IMPLEMENTATION ###
def set_option(self, **kw):
#self.do_assert_stage('CREATING')
return self.do_set_option(kw)
def get_option(self, name):
return self.do_get_option(name)
def init_creating(self, cryptosystem):
modulus, generator, order = cryptosystem
self.do_store_cryptosystem(modulus, generator, order)
self.do_set_stage('CREATING')
@classmethod
def new_at_creating(cls, cryptosystem=_default_crypto,
teller=_teller, **kw):
self = cls(cryptosystem, teller=teller, **kw)
return self
def create_zeus_key(self, secret_key=None):
# No need to assert creating, all other stages must have a key
if self.do_get_zeus_secret() is not None:
m = "Zeus key already initialized"
raise ZeusError(m)
modulus, generator, order = self.do_get_cryptosystem()
key_info = generate_keypair(modulus, generator, order,
secret_key=secret_key)
secret, public, commitment, challenge, response = key_info
self.do_store_zeus_key(secret, public, commitment, challenge, response)
return key_info
def invalidate_election_public(self):
self.do_store_election_public(None)
def compute_election_public(self):
trustees = self.do_get_trustees()
public = self.do_get_zeus_public()
modulus, generator, order = self.do_get_cryptosystem()
for trustee in trustees:
public = (public * trustee) % modulus
self.do_store_election_public(public)
def add_trustee(self, trustee_public_key, trustee_key_proof):
self.do_assert_stage('CREATING')
p, g, q = self.do_get_cryptosystem()
args = [p, g, q, trustee_public_key] + trustee_key_proof
if not validate_public_key(*args):
m = "Cannot validate key"
raise ZeusError(m)
election_public = self.do_get_election_public()
if election_public is None:
election_public = 1
modulus, generator, order = self.do_get_cryptosystem()
self.invalidate_election_public()
self.do_store_trustee(trustee_public_key, *trustee_key_proof)
self.compute_election_public()
def reprove_trustee(self, trustee_public_key, trustee_key_proof):
self.do_assert_stage('CREATING')
if not self.do_get_trustee(trustee_public_key):
m = "Trustee does not exist!"
raise ZeusError(m)
return self.add_trustee(trustee_public_key, trustee_key_proof)
def add_candidates(self, *names):
candidates = set(self.do_get_candidates())
for name in names:
if name in candidates:
m = "Candidate '%s' already exists!"
raise ZeusError(m)
if '%' in name:
m = "Candidate name cannot contain character '%%'"
raise ZeusError(m)
if '\n' in name:
m = "Candidate name cannot contain character '\\n'"
raise ZeusError(m)
self.do_store_candidates(names)
def add_voters(self, *voters):
name_set = set(v[0] for v in self.do_get_voters().itervalues())
intersection = name_set.intersection(v[0] for v in voters)
if intersection:
m = "Voter '%s' already exists!" % (intersection.pop(),)
raise ZeusError(m)
new_voters = {}
voter_audit_codes = {}
for name, weight in voters:
voter_key = "%x" % get_random_int(2, VOTER_KEY_CEIL)
new_voters[voter_key] = (name, weight)
audit_codes = list(get_random_int(2, VOTER_SLOT_CEIL)
for _ in xrange(3))
voter_audit_codes[voter_key] = audit_codes
self.do_store_voters(new_voters)
self.do_store_voter_audit_codes(voter_audit_codes)
def validate_creating(self):
teller = self.teller
teller.task("Validating stage: 'CREATING'")
with teller.task("Validating Candidates"):
candidates = self.do_get_candidates()
nr_candidates = len(candidates)
if nr_candidates <= 1:
m = "Not enough candidates for election!"
raise ZeusError(m)
if len(set(candidates)) != nr_candidates:
m = "Duplicate candidates!"
raise ZeusError(m)
teller.notice("%d candidates" % nr_candidates)
with teller.task("Validating Voters"):
voters = self.do_get_voters()
if not voters:
m = "No voters for election!"
raise ZeusError(m)
with teller.task("Validating Voter Names"):
names = [v[0] for v in voters.itervalues()]
nr_names = len(names)
if len(set(names)) != nr_names:
m = "Duplicate voter names!"
raise ZeusError(m)
del names
with teller.task("Validating Voter Keys"):
keys = voters.keys()
nr_keys = len(keys)
if len(set(keys)) != nr_keys:
m = "Duplicate voter keys!"
raise ZeusError(m)
with teller.task("Validating voter audit_codes"):
audit_codes = self.do_get_all_voter_audit_codes()
if audit_codes.keys() != keys:
m = "Slots do not correspond to voters!"
raise ZeusError(m)
audit_code_set = set(tuple(v) for v in audit_codes.values())
if len(audit_code_set) < nr_keys / 2:
m = "Slots don't have enough variation!"
raise ZeusError(m)
teller.notice("%d voters" % nr_keys)
modulus, generator, order = self.do_get_cryptosystem()
if not validate_cryptosystem(modulus, generator, order, teller=teller):
m = "Invalid Cryptosystem!"
raise AssertionError(m)
with teller.task("Validating Zeus Election Key"):
secret = self.do_get_zeus_secret()
public = self.do_get_zeus_public()
key_proof = self.do_get_zeus_key_proof()
if secret is not None:
if not validate_element(modulus, generator, order, secret):
m = "Invalid Secret Key"
raise AssertionError(m)
_public = pow(generator, secret, modulus)
if _public != public:
m = "Invalid Public Key"
raise AssertionError(m)
if not validate_public_key(modulus, generator, order,
public, *key_proof):
m = "Invalid Key Proof"
raise AssertionError(m)
trustees = self.do_get_trustees()
nr_trustees = len(trustees)
with teller.task("Validating Trustees", total=nr_trustees):
for public, proof in trustees.iteritems():
commitment, challenge, response = proof
if not validate_public_key(modulus, generator, order, public,
commitment, challenge, response):
m = "Invalid Trustee: %x" % public
raise AssertionError(m)
teller.advance()
election_public = self.do_get_election_public()
with teller.task("Validating Election Public Key"):
_election_public = self.do_get_zeus_public()
for public in trustees:
_election_public = (_election_public * public) % modulus
if _election_public != election_public:
m = "Invalid Election Public Key!"
raise AssertionError(m)
teller.finish('Validating stage')
def export_creating(self):
stage = self.do_get_stage()
if stage in ('UNINITIALIZED', 'CREATING'):
m = "Stage 'CREATING' must have passed before it can be exported"
raise ZeusError(m)
creating = {}
creating['candidates'] = self.do_get_candidates()
creating['voters'] = self.do_get_voters()
creating['cryptosystem'] = self.do_get_cryptosystem()
creating['zeus_public'] = self.do_get_zeus_public()
creating['zeus_key_proof'] = self.do_get_zeus_key_proof()
creating['election_public'] = self.do_get_election_public()
creating['trustees'] = self.do_get_trustees()
creating['voters'] = self.do_get_voters()
creating['voter_audit_codes'] = self.do_get_all_voter_audit_codes()
return creating
def set_voting(self):
stage = self.do_get_stage()
if stage == 'VOTING':
m = "Already in stage 'VOTING'"
raise ZeusError(m)
if stage != 'CREATING':
m = "Cannot transition from stage '%s' to 'VOTING'" % (stage,)
raise ZeusError(m)
if not self.get_option('no_verify'):
self.validate_creating()
self.do_set_stage('VOTING')
@classmethod
def new_at_voting(cls, voting, teller=_teller, **kw):
self = cls.new_at_creating(teller=teller, **kw)
#self.do_set_option(voting.get('options', {}))
self.do_store_candidates(voting['candidates'])
self.do_store_cryptosystem(*voting['cryptosystem'])
self.do_store_zeus_key(None,
voting['zeus_public'],
*voting['zeus_key_proof'])
self.do_store_election_public(voting['election_public'])
for t in voting['trustees'].iteritems():
trustee_public_key, trustee_key_proof = t
trustee_public_key = int(trustee_public_key)
self.do_store_trustee(trustee_public_key, *trustee_key_proof)
for voter_key, reason in voting['excluded_voters'].iteritems():
self.do_store_excluded_voter(voter_key, reason)
self.do_store_voters(voting['voters'])
self.do_store_voter_audit_codes(voting['voter_audit_codes'])
self.do_set_stage('VOTING')
return self
def validate_submitted_vote(self, vote):
keys = set(('voter', 'encrypted_ballot', 'fingerprint',
'audit_code', 'voter_secret'))
nr_keys = len(keys)
vote_keys = vote.keys()
if len(vote_keys) > len(keys):
m = "Extra vote contents"
raise ZeusError(m)
if len(set(keys).union(vote_keys)) != nr_keys:
m = "Invalid Vote: Extra vote contents"
raise ZeusError(m)
if 'voter' not in vote:
m = "'voter' field missing from vote"
raise ZeusError(m)
if 'encrypted_ballot' not in vote:
m = "'encrypted_ballot' field missing from vote"
raise ZeusError(m)
if 'fingerprint' not in vote:
m = "'fingerprint' field missing from vote"
raise ZeusError(m)
eb = vote['encrypted_ballot']
keys = set(('modulus', 'generator', 'order', 'public',
'alpha', 'beta',
'commitment', 'challenge', 'response'))
if set(eb.keys()) != keys:
m = "Invalid encrypted ballot format!"
raise ZeusError(m)
eb = dict(eb)
vote = dict(vote)
vote['encrypted_ballot'] = eb
crypto = self.do_get_cryptosystem()
eb_crypto = [eb.pop('modulus'), eb.pop('generator'), eb.pop('order')]
if crypto != eb_crypto:
m = "Invalid encrypted ballot cryptosystem"
raise ZeusError(m)
alpha = eb['alpha']
beta = eb['beta']
commitment = eb['commitment']
challenge = eb['challenge']
response = eb['response']
modulus, generator, order = crypto
if not verify_encryption(modulus, generator, order, alpha, beta,
commitment, challenge, response):
m = "Invalid vote encryption proof!"
raise ZeusError(m)
fingerprint = numbers_hash((modulus, generator, alpha, beta,
commitment, challenge, response))
if fingerprint != vote['fingerprint']:
m = "Invalid vote fingerprint!"
raise ZeusError(m)
stored = self.do_get_vote(fingerprint)
if stored is not None:
m = "Vote has already been cast!"
raise ZeusError(m)
return vote
def sign_vote(self, vote, comments):
modulus, generator, order = self.do_get_cryptosystem()
candidates = self.do_get_candidates()
public = self.do_get_zeus_public()
secret = self.do_get_zeus_secret()
trustees = list(self.do_get_trustees())
trustees.sort()
signature = sign_vote(vote, trustees, candidates, comments,
modulus, generator, order, public, secret)
self.verify_vote_signature(signature)
return signature
def verify_vote_signature(self, vote_signature):
vote_info = verify_vote_signature(vote_signature)
vote, vote_crypto, vote_trustees, vote_candidates, comments = vote_info
trustees = list(self.do_get_trustees())
trustees.sort()
crypto = self.do_get_cryptosystem()
public = self.do_get_election_public()
eb = vote['encrypted_ballot']
if crypto != vote_crypto:
m = "Cannot verify vote signature: Cryptosystem mismatch!"
raise ZeusError(m)
if public != eb['public']:
m = "Cannot verify vote signature: Election public mismatch!"
raise ZeusError(m)
if set(trustees) != set(vote_trustees):
m = "Vote signature: trustees mismatch!"
raise AssertionError(m)
candidates = self.do_get_candidates()
if candidates != vote_candidates:
m = "Vote signature: candidates mismatch!"
raise AssertionError(m)
return vote
def validate_vote(self, signed_vote):
election = signed_vote['encrypted_ballot']['public']
fingerprint = signed_vote['fingerprint']
index = signed_vote['index']
previous = signed_vote['previous']
if election != self.do_get_election_public():
m = "Election mismatch in vote!"
raise ZeusError(m)
stored = self.do_get_vote(fingerprint)
if not stored:
m = "Cannot find verified vote [%s] in store!" % (fingerprint,)
raise AssertionError(m)
if index:
indexed_fingerprint = self.do_get_index_vote(index)
if indexed_fingerprint != fingerprint:
m = ("Corrupt vote index: "
"signed vote [%s] with index %d not found: "
"index %d holds vote [%s]"
% (fingerprint, index, index, indexed_fingerprint))
raise AssertionError(m)
if previous and self.do_get_vote(previous) is None:
m = "Cannot find valid previous vote [%s] in store!" % (previous,)
raise AssertionError(m)
def verify_vote(self, vote):
if 'signature' not in vote:
m = "No signature found in vote!"
raise ZeusError(m)
signature = vote['signature']
signed_vote = self.verify_vote_signature(signature)
return self.validate_vote(signed_vote)
def cast_vote(self, vote):
self.do_assert_stage('VOTING')
fingerprint = vote['fingerprint']
voter_key = vote['voter']
voter = self.do_get_voter(voter_key)
audit_codes = self.do_get_voter_audit_codes(voter_key)
if not voter and not audit_codes:
m = "Invalid voter key!"
raise ZeusError(m)
if not voter or not audit_codes:
m = "Voter audit_code inconsistency! Invalid Election."
raise AssertionError(m)
audit_request = self.do_get_audit_request(fingerprint)
voter_secret = vote['voter_secret'] if 'voter_secret' in vote else None
voter_audit_code = vote['audit_code'] if 'audit_code' in vote else None
if voter_secret:
# This is an audit publication
if not voter_audit_code:
m = "Invalid audit vote publication! No audit_code given."
raise ZeusError(m)
if voter_audit_code in audit_codes:
m = "Invalid audit vote publication! Invalid audit_code given."
raise ZeusError(m)
if voter_key != audit_request:
m = "Cannot find prior audit request for publish request!"
raise ZeusError(m)
vote['previous'] = ''
vote['index'] = None
vote['status'] = V_PUBLIC_AUDIT
missing, failed = self.verify_audit_votes(votes=[vote])
if missing:
m = "This should have been impossible"
raise AssertionError(m)
if failed:
vote['status'] = V_PUBLIC_AUDIT_FAILED
comments = self.custom_audit_publication_message(vote)
signature = self.sign_vote(vote, comments)
vote['signature'] = signature
self.do_store_audit_publication(fingerprint)
self.do_store_votes((vote,))
return signature
if not voter_audit_code:
skip_audit = self.do_get_option('skip_audit')
if skip_audit or skip_audit is None:
# skip auditing for submission simplicity
voter_audit_code = audit_codes[0]
else:
m = ("Invalid vote submission! "
"No audit_code given but skip_audit is disabled")
raise ZeusError(m)
if voter_audit_code not in audit_codes:
# This is an audit request submission
if audit_request:
m = ("Audit request for vote [%s] already exists!"
% (fingerprint,))
raise ZeusError(m)
vote['previous'] = ''
vote['index'] = None
vote['status'] = V_AUDIT_REQUEST
comments = self.custom_audit_request_message(vote)
signature = self.sign_vote(vote, comments)
vote['signature'] = signature
self.do_store_audit_request(fingerprint, voter_key)
self.do_store_votes((vote,))
return signature
# This is a genuine vote submission
if self.do_get_vote(fingerprint):
m = "Vote [%s] already cast!" % (fingerprint,)
raise ZeusError(m)
cast_votes = self.do_get_cast_votes(voter_key)
vote_limit = self.get_option('vote_limit')
if vote_limit and len(cast_votes) >= vote_limit:
m = "Maximum allowed number of votes reached: %d" % vote_limit
raise ZeusError(m)
if not cast_votes:
previous_fingerprint = ''
else:
previous_fingerprint = cast_votes[-1]
vote = self.validate_submitted_vote(vote)
vote['previous'] = previous_fingerprint
vote['status'] = V_CAST_VOTE
index = self.do_index_vote(fingerprint)
vote['index'] = index
comments = self.custom_cast_vote_message(vote)
signature = self.sign_vote(vote, comments)
vote['signature'] = signature
self.do_append_vote(voter_key, fingerprint)
self.do_store_votes((vote,))
# DANGER: commit all data to disk before giving a signature out!
return signature
def verify_audit_votes(self, votes=None):
teller = self.teller
if not votes:
audit_reqs = self.do_get_audit_requests()
get_vote = self.do_get_vote
votes = [dict(get_vote(f)) for f in audit_reqs]
add_plaintext = 0
else:
add_plaintext = 1
failed = []
missing = []
modulus, generator, order = self.do_get_cryptosystem()
public = self.do_get_election_public()
nr_candidates = len(self.do_get_candidates())
max_encoded = gamma_encoding_max(nr_candidates)
with teller.task("Verifying audit votes", total=len(votes)):
for vote in votes:
if not 'voter_secret' in vote:
missing.append(vote)
m = "[%s] public audit secret not found"
teller.notice(m, vote['fingerprint'])
teller.advance()
continue
voter_secret = vote['voter_secret']
eb = vote['encrypted_ballot']
if not verify_encryption(modulus, generator, order,
eb['alpha'], eb['beta'],
eb['commitment'],
eb['challenge'],
eb['response']):
failed.append(vote)
m = "failed audit [%s]"
teller.notice(m, vote['fingerprint'])
teller.advance()
continue
alpha = pow(generator, voter_secret, modulus)
if alpha != eb['alpha']:
failed.append(vote)
m = "[%s] ciphertext mismatch: wrong key"
teller.notice(m, vote['fingerprint'])
teller.advance()
continue
beta = eb['beta']
encoded = decrypt_with_randomness(modulus, generator, order,
public, beta, voter_secret)
if encoded > max_encoded:
m = "[%s] invalid plaintext!"
teller.notice(m, vote['fingerprint'])
failed.append(vote)
if add_plaintext:
vote['plaintext'] = encoded
teller.advance()
return missing, failed
def exclude_voter(self, voter_key, reason=''):
stage = self.do_get_stage()
if stage in ('FINISHED', 'DECRYPTING', 'MIXING'):
m = "Cannot exclude voter in stage '%s'!" % (stage,)
raise ZeusError(m)
self.do_store_excluded_voter(voter_key, reason)
def validate_voting(self):
teller = self.teller
teller.task("Validating state: 'VOTING'")
all_cast_votes = self.do_get_all_cast_votes()
all_votes = self.do_get_votes()
nr_votes = len(all_votes)
with teller.task("Validating cast votes", total=nr_votes):
for voter_key, cast_votes in all_cast_votes.iteritems():
previous = ''
for cast_vote in cast_votes:
if cast_vote not in all_votes:
m = ("Vote %s/[%s] not found in vote archive!"
% (voter_key, cast_vote))
raise AssertionError(m)
vote = all_votes[cast_vote]
vote_previous = vote['previous']
if vote_previous != previous:
m = ("Vote %s/[%s] previous '%s' != '%s'"
% (voter_key, cast_vote, vote_previous, previous))
raise AssertionError(m)
self.verify_vote(vote)
del all_votes[cast_vote]
teller.advance()
previous = cast_vote
audit_pubs = self.do_get_audit_publications()
nr_audit_pubs = len(audit_pubs)
with teller.task("Validating audit publications", total=nr_audit_pubs):
all_audit_requests = self.do_get_audit_requests()
for audit_vote in audit_pubs:
if audit_vote not in all_votes:
m = "Audit vote [%s] not found in vote archive!" % (audit_vote,)
raise AssertionError(m)
vote = all_votes[audit_vote]
self.verify_vote(vote)
msg = vote['signature']
if msg.startswith(V_PUBLIC_AUDIT):
if vote['fingerprint'] not in all_audit_requests:
m = "Public audit vote not found in requests!"
raise AssertionError(m)
else:
m = "Invalid audit vote!"
raise AssertionError(m)
teller.advance()
all_audit_requests = self.do_get_audit_requests()
nr_all_audit_requests = len(all_audit_requests)
with teller.task("Validating audit requests",
total=nr_all_audit_requests):
for audit_request, voter_key in all_audit_requests.iteritems():
if audit_request not in all_votes:
m = ("Audit request %s/[%s] not found in vote archive!"
% (voter_key, audit_request))
raise AssertionError(m)
vote = all_votes[audit_request]
self.verify_vote(vote)
del all_votes[audit_request]
teller.advance()
if all_votes:
m = "%d unaccounted votes in archive!" % len(all_votes)
raise AssertionError(m)
excluded = self.do_get_excluded_voters()
nr_excluded = len(excluded)
with teller.task("Validating excluded voters", total=nr_excluded):
for voter_key, reason in excluded.iteritems():
voter = self.do_get_voter(voter_key)
if voter is None:
m = "Nonexistent excluded voter '%s'!" % voter_key
raise AssertionError(m)
teller.advance()
teller.finish('Validating state')
def export_voting(self):
stage = self.do_get_stage()
if stage in ('UNINITIALIZED', 'CREATING'):
m = ("Stage 'VOTING' must have been reached "
"before it can be exported")
raise ZeusError(m)
voting = self.export_creating()
voting['votes'] = self.do_get_votes().values()
voting['cast_vote_index'] = self.do_get_vote_index()
voting['cast_votes'] = self.do_get_all_cast_votes()
voting['audit_requests'] = self.do_get_audit_requests()
voting['audit_publications'] = self.do_get_audit_publications()
voting['excluded_voters'] = self.do_get_excluded_voters()
return voting
def extract_votes_for_mixing(self):
vote_index = self.do_get_vote_index()
nr_votes = len(vote_index)
scratch = list([None]) * nr_votes
counted = list([None]) * nr_votes
do_get_vote = self.do_get_vote
vote_count = 0
excluded_voters = self.do_get_excluded_voters()
excluded_votes = set()
update = excluded_votes.update
for voter_key, reason in excluded_voters.iteritems():
update(self.do_get_cast_votes(voter_key))
for i, fingerprint in enumerate(vote_index):
vote = dict(do_get_vote(fingerprint))
index = vote['index']
if i != index:
m = "Index mismatch %d != %d. Corrupt index!" % (i, index)
raise AssertionError(m)
if fingerprint in excluded_votes:
continue
voter_key = vote['voter']
voter_name, voter_weight = self.do_get_voter(voter_key)
eb = vote['encrypted_ballot']
_vote = [eb['alpha'], eb['beta'], voter_weight]
scratch[i] = _vote
counted[i] = fingerprint
previous = vote['previous']
if not previous:
vote_count += 1
continue
previous_vote = dict(do_get_vote(previous))
previous_index = previous_vote['index']
if previous_index >= index or scratch[previous_index] is None:
m = "Inconsistent index!"
raise AssertionError(m)
if previous_vote['voter'] != vote['voter']:
m = ("Voter mismatch '%s' vs '%s'!"
% (previous_vote['voter'], vote['voter']))
raise AssertionError(m)
scratch[previous_index] = None
counted[previous_index] = None
votes_for_mixing = []
counted_list = []
counted_votes = 0
for c, v in izip(counted, scratch):
if (c, v) == (None, None):
continue
elif None in (c, v):
raise AssertionError()
counted_votes += 1
alpha, beta, weight = v
vote = [alpha, beta]
votes_for_mixing.extend(repeat(vote, weight))
counted_list.extend(repeat(c, weight))
if counted_votes != vote_count:
m = ("Vote count mismatch %d != %d. Corrupt index!"
% (counted_votes, vote_count))
raise AssertionError(m)
crypto = self.do_get_cryptosystem()
modulus, generator, order = crypto
public = self.do_get_election_public()
mix = {'modulus': modulus,
'generator': generator,
'order': order,
'public': public,
'original_ciphers': votes_for_mixing,
'mixed_ciphers': votes_for_mixing}
return mix, counted_list
def set_mixing(self):
stage = self.do_get_stage()
if stage == 'MIXING':
m = "Already in stage 'MIXING'"
raise ZeusError(m)
if stage != 'VOTING':
m = "Cannot transition from stage '%s' to 'MIXING'" % (stage,)
raise ZeusError(m)
if not self.get_option('no_verify'):
self.validate_voting()
votes_for_mixing, counted_list = self.extract_votes_for_mixing()
self.do_store_mix(votes_for_mixing)
self.do_set_stage('MIXING')
@classmethod
def new_at_mixing(cls, mixing, teller=_teller, **kw):
self = cls.new_at_voting(mixing, teller=teller, **kw)
self.do_store_votes(mixing['votes'])
for fingerprint in mixing['cast_vote_index']:
self.do_index_vote(fingerprint)
for voter_key, fingerprints in mixing['cast_votes'].iteritems():
for fingerprint in fingerprints:
self.do_append_vote(voter_key, fingerprint)
for fingerprint, voter_key in mixing['audit_requests'].iteritems():
self.do_store_audit_request(fingerprint, voter_key)
for fingerprint in mixing['audit_publications']:
self.do_store_audit_publication(fingerprint)
votes_for_mixing, counted_list = self.extract_votes_for_mixing()
self.do_store_mix(votes_for_mixing)
self.do_set_stage('MIXING')
return self
def get_last_mix(self):
self.do_assert_stage('MIXING')
last_mix = dict(self.do_get_last_mix())
last_mix.pop('offset_collections', None)
last_mix.pop('random_collections', None)
last_mix.pop('cipher_collections', None)
return last_mix
def validate_mix(self, mix):
teller = self.teller
nr_parallel = self.get_option('nr_parallel')
if nr_parallel is None:
nr_parallel = 2
modulus = mix['modulus']
generator = mix['generator']
order = mix['order']
if 'cipher_collections' not in mix:
m = "Invalid mix: no proof!"
raise ZeusError(m)
min_rounds = self.get_option('min_mix_rounds') or MIN_MIX_ROUNDS
nr_rounds = len(mix['cipher_collections'])
if nr_rounds < min_rounds:
m = ("Invalid mix: fewer than required mix rounds: %d < %d"
% (nr_rounds, min_rounds))
raise ZeusError(m)
crypto = self.do_get_cryptosystem()
if [modulus, generator, order] != crypto:
m = "Invalid mix: cryptosystem mismatch!"
raise ZeusError(m)
original_ciphers = mix['original_ciphers']
last_mix = self.do_get_last_mix()
if original_ciphers != last_mix['mixed_ciphers']:
m = "Invalid mix: not a mix of latest ciphers!"
raise ZeusError(m)
if not self.shuffle_module.verify_cipher_mix(
mix, teller=teller, nr_parallel=nr_parallel):
m = "Invalid mix: proof verification failed!"
raise ZeusError(m)
def add_mix(self, mix):
self.do_assert_stage('MIXING')
self.validate_mix(mix)
self.do_store_mix(mix)
def validate_mixing(self):
teller = self.teller
nr_parallel = self.get_option('nr_parallel')
if nr_parallel is None:
nr_parallel = 2
teller.task("Validating state: 'MIXING'")
crypto = self.do_get_cryptosystem()
previous = None
mixes = self.do_get_all_mixes()
min_mixes = self.get_option('min_mixes') or 1
nr_mixes = len(mixes) - 1
if nr_mixes < min_mixes:
m = "Not enough mixes: %d. Minimum %d." % (nr_mixes, min_mixes)
raise AssertionError(m)
with teller.task("Validate mixes", total=nr_mixes):
for i, mix in enumerate(mixes):
if [mix['modulus'], mix['generator'], mix['order']] != crypto:
m = "Mix data corruption: Cryptosystem mismatch!"
raise AssertionError(m)
if previous:
previous_mixed = previous['mixed_ciphers']
original_ciphers = mix['original_ciphers']
if original_ciphers != previous_mixed:
m = ("Invalid mix %d/%d: Does not mix previous one"
% (i+1, nr_mixes))
raise AssertionError(m)
if not self.shuffle_module.verify_cipher_mix(
mix, teller=teller, nr_parallel=nr_parallel):
m = "Invalid mix proof"
raise AssertionError(m)
teller.advance()
else:
t = self.extract_votes_for_mixing()
votes_for_mixing, counted_list = t
original_ciphers = mix['original_ciphers']
if len(original_ciphers) != len(counted_list):
m = "Invalid extraction for mixing!"
raise AssertionError(m)
if original_ciphers != votes_for_mixing['original_ciphers']:
m = "Invalid first mix: Does not mix votes in archive!"
raise AssertionError(m)
counted_set = set(counted_list)
del counted_list
excluded = self.do_get_excluded_voters()
for voter_key, reason in excluded.iteritems():
cast_votes = self.do_get_cast_votes(voter_key)
for fingerprint in cast_votes:
if fingerprint in counted_set:
m = ("Invalid extraction for mixing: "
"vote [%s] from voter '%s' not excluded!"
% (fingerprint, voter_key))
raise AssertionError(m)
del votes_for_mixing
del excluded
previous = mix
teller.finish('Validating state')
def export_mixing(self):
stage = self.do_get_stage()
if stage in ('UNINITIALIZED', 'CREATING', 'VOTING', 'MIXING'):
m = "Stage 'MIXING' must have passed before it can be exported"
raise ZeusError(m)
mixing = self.export_voting()
mixes = self.do_get_all_mixes()[1:]
mixing['mixes'] = mixes
return mixing
def set_decrypting(self):
stage = self.do_get_stage()
if stage == 'DECRYPTING':
m = "Already in stage 'DECRYPTING'"
raise ZeusError(m)
if stage != 'MIXING':
m = "Cannot transition from stage '%s' to 'DECRYPTING'" % (stage,)
raise ZeusError(m)
if not self.get_option('no_verify'):
self.validate_mixing()
self.compute_zeus_factors()
self.do_set_stage('DECRYPTING')
def export_decrypting(self):
stage = self.do_get_stage()
if stage not in ('FINISHED'):
m = "Stage 'DECRYPTING' must have passed before it can be exported"
raise ZeusError(m)
decrypting = self.export_mixing()
all_factors = self.do_get_all_trustee_factors()
trustee_factors = [{'trustee_public': k, 'decryption_factors': v}
for k, v in all_factors.iteritems()]
decrypting['trustee_factors'] = trustee_factors
zeus_factors = self.do_get_zeus_factors()
decrypting['zeus_decryption_factors'] = zeus_factors
return decrypting
@classmethod
def new_at_decrypting(cls, decrypting, teller=_teller, **kw):
self = cls.new_at_mixing(decrypting, teller=teller, **kw)
for mix in decrypting['mixes']:
self.do_store_mix(mix)
if 'trustee_factors' in decrypting:
all_trustee_factors = decrypting['trustee_factors']
for trustee_factors in all_trustee_factors:
self.do_store_trustee_factors(trustee_factors)
if 'zeus_decryption_factors' in decrypting:
self.do_store_zeus_factors(decrypting['zeus_decryption_factors'])
self.do_set_stage('DECRYPTING')
return self
def get_mixed_ballots(self):
#self.do_assert_stage('DECRYPTING')
last_mix = self.do_get_last_mix()
if last_mix is None:
return []
return list(last_mix['mixed_ciphers'])
def validate_trustee_factors(self, trustee_factors):
teller = self.teller
if ('trustee_public' not in trustee_factors or
'decryption_factors' not in trustee_factors):
m = "Invalid trustee factors format"
raise ZeusError(m)
trustee_public = trustee_factors['trustee_public']
trustees = self.do_get_trustees()
if trustee_public not in trustees:
m = "Invalid trustee factors: No such trustee!"
raise ZeusError(m)
crypto = self.do_get_cryptosystem()
modulus = trustee_factors['modulus']
generator = trustee_factors['generator']
order = trustee_factors['order']
if [modulus, generator, order] != crypto:
m = "Invalid trustee factors: Cryptosystem mismatch"
raise ZeusError(m)
factors = trustee_factors['decryption_factors']
ciphers = self.get_mixed_ballots()
nr_parallel = self.get_option('nr_parallel')
if not verify_decryption_factors(modulus, generator, order,
trustee_public,
ciphers, factors,
teller=teller,
nr_parallel=nr_parallel):
print "MODULUS", modulus
print "GENERATOR", generator
print "ORDER", order
#print "CIPHERS", ciphers
print "FACTORS", factors
print "PK", trustee_public
factors = repr(factors)[:40]
m = "Invalid trustee factor proof ({})!".format(factors)
raise ZeusError(m)
return 1
def add_trustee_factors(self, trustee_factors):
self.do_assert_stage('DECRYPTING')
if not self.validate_trustee_factors(trustee_factors):
m = "Invalid trustee factors"
raise ZeusError(m)
self.do_store_trustee_factors(trustee_factors)
def validate_decrypting(self):
teller = self.teller
teller.task("Validating stage: 'DECRYPTING'")
crypto = self.do_get_cryptosystem()
modulus, generator, order = crypto
trustees = self.do_get_trustees()
all_factors = self.do_get_all_trustee_factors()
nr_trustees = len(trustees)
nr_factors = len(all_factors)
if nr_trustees != nr_factors:
m = ("There are %d trustees, but only %d factors!"
% (nr_trustees, nr_factors))
raise ZeusError(m)
mixed_ballots = self.get_mixed_ballots()
for trustee in trustees:
if trustee not in all_factors:
m = "Invalid decryption factors: trustee mismatch!"
raise AssertionError(m)
nr_parallel = self.get_option('nr_parallel')
factors = all_factors[trustee]
if not verify_decryption_factors(modulus, generator, order,
trustee, mixed_ballots, factors,
teller=teller,
nr_parallel=nr_parallel):
m = "Invalid trustee factors proof!"
raise ZeusError(m)
zeus_factors = self.do_get_zeus_factors()
zeus_public = self.do_get_zeus_public()
if not verify_decryption_factors(modulus, generator, order,
zeus_public, mixed_ballots,
zeus_factors, teller=teller):
m = "Invalid zeus factors proof!"
raise ZeusError(m)
teller.finish()
def compute_zeus_factors(self):
Random.atfork()
teller = self.teller
mixed_ballots = self.get_mixed_ballots()
modulus, generator, order = self.do_get_cryptosystem()
secret = self.do_get_zeus_secret()
nr_parallel = self.get_option('nr_parallel')
with teller.task("Computing Zeus factors"):
zeus_factors = compute_decryption_factors(modulus, generator,
order,
secret, mixed_ballots,
teller=teller,
nr_parallel=nr_parallel)
self.do_store_zeus_factors(zeus_factors)
def decrypt_ballots(self):
teller = self.teller
mixed_ballots = self.get_mixed_ballots()
modulus, generator, order = self.do_get_cryptosystem()
zeus_factors = self.do_get_zeus_factors()
all_factors = self.do_get_all_trustee_factors().values()
all_factors.append(zeus_factors)
decryption_factors = combine_decryption_factors(modulus, all_factors)
plaintexts = []
append = plaintexts.append
with teller.task("Decrypting ballots", total=len(mixed_ballots)):
for ballot, factor in izip(mixed_ballots, decryption_factors):
plaintext = decrypt_with_decryptor(modulus, generator, order,
ballot[BETA], factor)
append(plaintext)
teller.advance()
self.do_store_results(plaintexts)
return plaintexts
def validate_finished(self):
teller = self.teller
with teller.task("Validating STAGE: 'FINISHED'"):
old_results = self.do_get_results()
results = self.decrypt_ballots()
if old_results and old_results != results:
m = "Old results did not match new results!"
raise AssertionError(m)
def set_finished(self):
stage = self.do_get_stage()
if stage == 'FINISHED':
m = "Already in stage 'FINISHED'"
raise ZeusError(m)
if stage != 'DECRYPTING':
m = "Cannot transition from stage '%s' to 'FINISHED'" % (stage,)
raise ZeusError(m)
if not self.get_option('no_verify'):
self.validate_decrypting()
self.decrypt_ballots()
self.do_set_stage('FINISHED')
def export_finished(self):
stage = self.do_get_stage()
if stage != 'FINISHED':
m = ("Stage 'FINISHED' must have been reached "
"before it can be exported")
raise ZeusError(m)
finished = self.export_decrypting()
finished['results'] = self.do_get_results()
fingerprint = sha256(to_canonical(finished)).hexdigest()
finished['election_fingerprint'] = fingerprint
report = ''
trustees = list(self.do_get_trustees())
trustees.sort()
for i, trustee in enumerate(trustees):
report += 'TRUSTEE %d: %x\n' % (i, trustee)
candidates = self.do_get_candidates()
report += '\n'
for i, candidate in enumerate(candidates):
report += 'CANDIDATE %d: %s\n' % (i, candidate)
report += '\n'
excluded = self.do_get_excluded_voters()
if excluded:
for i, (voter, reason) in enumerate(excluded.iteritems()):
report += 'EXCLUDED VOTER %d: %s (%s)\n' % (i, voter, reason)
report += '\n'
report += 'ZEUS ELECTION FINGERPRINT: %s\n' % (fingerprint,)
finished['election_report'] = report
return finished
@classmethod
def new_at_finished(cls, finished, teller=_teller, **kw):
self = cls.new_at_decrypting(finished, teller=teller, **kw)
self.do_store_results(finished['results'])
finished.pop('election_report', None)
fingerprint = finished.pop('election_fingerprint', None)
_fingerprint = sha256(to_canonical(finished)).hexdigest()
if fingerprint is not None:
if fingerprint != _fingerprint:
m = "Election fingerprint mismatch!"
#print "WARNING: " + m
raise AssertionError(m)
fingerprint = _fingerprint
self.election_fingerprint = fingerprint
self.do_set_stage('FINISHED')
return self
def get_results(self):
self.do_assert_stage('FINISHED')
results = self.do_get_results()
return results
_export_methods = {
'CREATING': None,
'VOTING': 'export_creating',
'MIXING': 'export_voting',
'DECRYPTING': 'export_mixing',
'FINISHED': 'export_finished',
}
def export(self):
stage = self.do_get_stage()
method_name = self._export_methods[stage]
if method_name is None:
m = "Cannot export stage '%s'" % (stage,)
raise ValueError(m)
return getattr(self, method_name)(), stage
def validate(self):
self.validate_creating()
self.validate_voting()
self.validate_mixing()
self.validate_decrypting()
self.validate_finished()
return 1
### CLIENT REFERENCE ###
def mk_random_trustee(self):
crypto = self.do_get_cryptosystem()
modulus, generator, order = crypto
secret = get_random_int(3, order)
public = pow(generator, secret, modulus)
proof = prove_dlog(modulus, generator, order, public, secret)
return sk_from_args(modulus, generator, order, secret, public, *proof)
def mk_reprove_trustee(self, public, secret):
modulus, generator, order = self.do_get_cryptosystem()
proof = prove_dlog(modulus, generator, order, public, secret)
return sk_from_args(modulus, generator, order, secret, public, *proof)
def mk_psudorandom_selection(self):
selections = []
append = selections.append
nr_candidates = len(self.do_get_candidates())
if not nr_candidates:
m = "No candidates!"
raise ValueError(m)
z = 0
for m in xrange(nr_candidates-1, -1, -1):
r = randint(0, m)
if r == 0:
z = 1
if z:
append(0)
else:
append(r)
return selections
def mk_random_vote(self, selection=None, voter=None,
audit_code=None, publish=None):
modulus, generator, order = self.do_get_cryptosystem()
public = self.do_get_election_public()
candidates = self.do_get_candidates()
nr_candidates = len(candidates)
if selection is None:
r = get_random_int(0, 4)
if r & 1:
selection = get_random_selection(nr_candidates, full=0)
else:
selection = get_random_party_selection(nr_candidates, 2)
voters = None
if voter is None:
voters = self.do_get_voters()
voter = rand_choice(voters.keys())
encoded = encode_selection(selection, nr_candidates)
valid = True
if audit_code:
if voters is None:
voters = self.do_get_voters()
voter_audit_codes = self.do_get_voter_audit_codes(voter)
if audit_code < 0:
if voter not in voters:
m = ("Valid audit_code requested but voter not found!")
raise ValueError(m)
audit_code = voter_audit_codes[0]
elif voter not in voters:
valid = False
elif audit_code not in voter_audit_codes:
valid = False
vote = vote_from_encoded(modulus, generator, order, public,
voter, encoded, nr_candidates,
audit_code=audit_code, publish=1)
rnd = vote['voter_secret']
if not publish:
del vote['voter_secret']
return vote, selection, encoded if valid else None, rnd
def mk_stage_creating(self, teller=_teller):
nr_candidates = self._nr_candidates
candidates = []
append = candidates.append
mid = nr_candidates // 2
first = 1
for i in xrange(0, mid):
if first:
append("Party-A" + PARTY_SEPARATOR + "0-2, 0")
first = 0
append("Party-A" + PARTY_SEPARATOR + "Candidate-%04d" % i)
first = 1
for i in xrange(mid, nr_candidates):
if first:
append("Party-B" + PARTY_SEPARATOR + "0-2, 1")
first = 0
append("Party-B" + PARTY_SEPARATOR + "Candidate-%04d" % i)
voter_range = xrange(self._nr_voters)
voters = [(("Voter-%08d" % x), 1) for x in voter_range]
self.create_zeus_key()
self.add_candidates(*candidates)
self.add_voters(*voters)
trustees = [self.mk_random_trustee()
for _ in xrange(self._nr_trustees)]
for trustee in trustees:
self.add_trustee(key_public(trustee), key_proof(trustee))
trustees = [self.mk_reprove_trustee(key_public(t), key_secret(t))
for t in trustees]
for trustee in trustees:
self.reprove_trustee(key_public(trustee), key_proof(trustee))
self._trustees = trustees
def mk_stage_voting(self, teller=_teller):
selections = []
plaintexts = {}
votes = []
voters = list(self.do_get_voters())
for i, voter in zip(xrange(self._nr_votes), cycle(voters)):
kw = {'audit_code': -1} if (i & 1) else {}
kw['voter'] = voter
vote, selection, encoded, rnd = self.mk_random_vote(**kw)
if vote['voter'] != voter:
m = "Vote has wrong voter!"
raise AssertionError(m)
selections.append(selection)
if encoded is not None:
plaintexts[voter] = encoded
votes.append(vote)
signature = self.cast_vote(vote)
if not signature.startswith(V_CAST_VOTE):
m = "Invalid cast vote signature!"
raise AssertionError(m)
teller.advance()
with teller.task("Excluding last voter"):
cast_votes = self.do_get_cast_votes(voter)
if not cast_votes:
m = "Voter has no votes!"
raise AssertionError(m)
self.exclude_voter(voter)
del selections[-1]
del plaintexts[voter]
self._selections = selections
self._plaintexts = plaintexts
self._votes = votes
with teller.task("Casting a valid audit vote"):
vote, selection, encoded, rnd = self.mk_random_vote(audit_code=1)
signature = self.cast_vote(vote)
if not signature.startswith(V_AUDIT_REQUEST):
m = "Invalid audit request reply!"
raise AssertionError(m)
vote['voter_secret'] = rnd
self.cast_vote(vote)
self.verify_audit_votes()
with teller.task("Casting an invalid audit vote"):
vote, selection, encoded, rnd = self.mk_random_vote(audit_code=1)
signature = self.cast_vote(vote)
if not signature.startswith(V_AUDIT_REQUEST):
m = "Invalid audit request reply!"
raise AssertionError(m)
vote['voter_secret'] = rnd
eb = vote['encrypted_ballot']
phony = eb['alpha'] + 1
eb['alpha'] = phony
self._phony = phony
modulus, generator, order = self.do_get_cryptosystem()
alpha = eb['alpha']
beta = eb['beta']
commitment = eb['commitment']
challenge = eb['challenge']
response = eb['response']
if verify_encryption(modulus, generator, order, alpha, beta,
commitment, challenge, response):
m = "This should have failed"
raise AssertionError(m)
signature = self.cast_vote(vote)
if not signature.startswith(V_PUBLIC_AUDIT):
m = "Invalid public audit reply!"
raise AssertionError(m)
def mk_stage_mixing(self, teller=_teller):
for _ in xrange(self._nr_mixes):
cipher_collection = self.get_last_mix()
nr_parallel = self.get_option('nr_parallel')
mixed_collection = self.shuffle_module.mix_ciphers(
cipher_collection,
nr_rounds=self._nr_rounds,
teller=teller,
nr_parallel=nr_parallel)
self.add_mix(mixed_collection)
teller.advance()
def mk_stage_decrypting(self, teller=_teller):
modulus, generator, order = self.do_get_cryptosystem()
nr_parallel = self.get_option('nr_parallel')
ciphers = self.get_mixed_ballots()
with teller.task("Calculating and adding decryption factors",
total=self._nr_trustees):
for trustee in self._trustees:
factors = compute_decryption_factors(
modulus, generator, order,
key_secret(trustee), ciphers,
teller=teller, nr_parallel=nr_parallel)
trustee_factors = {'trustee_public': key_public(trustee),
'decryption_factors': factors,
'modulus': modulus,
'generator': generator,
'order': order}
self.add_trustee_factors(trustee_factors)
teller.advance()
def mk_stage_finished(self, teller=_teller):
with teller.task("Validating results"):
results = self.get_results()
nr_voters = len(self.do_get_voters())
if len(results) != min(self._nr_votes, nr_voters) - 1:
m = "Vote exclusion was not performed! results: %d vs %d"
m = m % (len(results), self._nr_votes - 1)
raise AssertionError(m)
if sorted(results) != sorted(self._plaintexts.values()):
m = ("Invalid Election! "
"Casted plaintexts do not match plaintext results!")
raise AssertionError(m)
missing, failed = self.verify_audit_votes()
if (missing or not failed or
not failed[0]['encrypted_ballot']['alpha'] == self._phony):
m = "Invalid audit request not detected!"
raise AssertionError(m)
@classmethod
def mk_random(cls, nr_candidates = 3,
nr_trustees = 2,
nr_voters = 10,
nr_votes = 10,
nr_mixes = 2,
nr_rounds = 8,
stage = 'FINISHED',
teller=_teller, **kw):
self = cls(teller=teller, **kw)
self._nr_candidates = nr_candidates
self._nr_trustees = nr_trustees
self._nr_voters = nr_voters
self._nr_votes = nr_votes
self._nr_mixes = nr_mixes
self._nr_rounds = nr_rounds
stage = stage.upper()
with teller.task("Creating election"):
self.mk_stage_creating(teller=teller)
if stage == 'CREATING':
return self
self.set_voting()
with teller.task("Voting", total=nr_votes):
self.mk_stage_voting(teller=teller)
if stage == 'VOTING':
return self
self.set_mixing()
with teller.task("Mixing", total=nr_mixes):
self.mk_stage_mixing(teller=teller)
if stage == 'MIXING':
return self
self.set_decrypting()
with teller.task("Decrypting"):
self.mk_stage_decrypting(teller=teller)
if stage == 'DECRYPTING':
return self
self.set_finished()
self.mk_stage_finished(teller=teller)
return self
def main():
import argparse
description='Zeus Election Reference Implementation and Verifier.'
epilog="Try 'zeus --generate'"
parser = argparse.ArgumentParser(description=description, epilog=epilog)
parser.add_argument('--election', metavar='infile',
help="Read a FINISHED election from a proofs file and verify it")
parser.add_argument('--verify-signatures', nargs='*',
metavar=('election_file', 'signature_file'),
help="Read an election and a signature from a JSON file "
"and verify the signature")
parser.add_argument('--parallel', dest='nr_procs', default=2,
help="Use multiple processes for parallel mixing")
parser.add_argument('--no-verify', action='store_true', default=False,
help="Do not verify elections")
parser.add_argument('--report', action='store_true', default=False,
help="Display election report")
parser.add_argument('--counted', action='store_true', default=False,
help="Display election counted votes fingerprints")
parser.add_argument('--results', action='store_true', default=False,
help="Display election plaintext results")
parser.add_argument('--count-parties', action='store_true', default=False,
help="Count results based on candidate parties")
parser.add_argument('--count-range', action='store_true', default=False,
help="Count results based on range choices")
parser.add_argument('--count-candidates', action='store_true', default=False,
help="Count results based on candidates choices")
parser.add_argument('--extract-signatures', metavar='prefix',
help="Write election signatures for counted votes to files")
parser.add_argument('--extract-audits', metavar='prefix',
help="Write election public audits to files")
parser.add_argument('--extract-mixed', metavar='prefix',
help="Write election public audits to files")
parser.add_argument('--generate', nargs='*', metavar='outfile',
help="Generate a random election and write it out in JSON")
parser.add_argument('--stage', type=str, default='FINISHED',
help="Generate: Stop when this stage is complete")
parser.add_argument('--candidates', type=int, default=3,
dest='nr_candidates',
help="Generate: Number of candidates")
parser.add_argument('--trustees', type=int, default=2,
dest='nr_trustees',
help="Generate: Number of trustees")
parser.add_argument('--voters', type=int, default=10,
dest='nr_voters',
help="Generate: Number of voters")
parser.add_argument('--votes', type=int, default=10,
dest='nr_votes',
help="Generate: Number of valid votes to cast")
parser.add_argument('--mixes', type=int, default=2,
dest='nr_mixes',
help="Generate: Number of times to mix")
parser.add_argument('--rounds', type=int, default=MIN_MIX_ROUNDS,
dest='nr_rounds',
help="Generate or Mix: Number of mix rounds")
parser.add_argument('--verbose', action='store_true', default=True,
help=("Write validation, verification, and notice messages "
"to standard error"))
parser.add_argument('--quiet', action='store_false', dest='verbose',
help=("Be quiet. Cancel --verbose"))
parser.add_argument('--oms', '--output-interval-ms', type=int,
metavar='millisec', default=200, dest='oms',
help=("Set the output update interval"))
parser.add_argument('--no-buffer', action='store_true', default=False,
help=("Do not keep output in buffer. "
"Keep only the last one to display as per --oms."))
parser.add_argument('--buffer-feeds', action='store_true', default=False,
help=("Buffer output newlines according to --oms "
"instead of sending them out immediately"))
args = parser.parse_args()
def do_extract_signatures(election, prefix='counted', teller=_teller):
vfm, counted_list = election.extract_votes_for_mixing()
count = 0
total = len(counted_list)
with teller.task("Extracting signatures"):
for fingerprint in counted_list:
vote = election.do_get_vote(fingerprint)
signature = vote['signature']
filename = prefix + fingerprint
with open(filename, "w") as f:
f.write(strforce(signature))
count += 1
teller.status("%d/%d '%s'", count, total, filename, tell=1)
return vfm, counted_list
def do_extract_audits(election, prefix='audit', teller=_teller):
audits = election.do_get_audit_publications()
count = 0
total = len(audits)
with teller.task("Extracting audit publications"):
for fingerprint in audits:
vote = election.do_get_vote(fingerprint)
signature = vote['signature']
filename = prefix + '_' + fingerprint
with open(filename, "w") as f:
f.write(strforce(signature))
count += 1
teller.status("%d/%d '%s'", count, total, filename, tell=1)
def do_counted_votes(election):
vfm, counted_list = election.extract_votes_for_mixing()
for i, fingerprint in enumerate(counted_list):
print 'COUNTED VOTE %d: %s' % (i, fingerprint)
print ""
return vfm, counted_list
def do_report(election):
exported, stage = election.export()
if 'election_report' in exported:
print exported['election_report']
return exported, stage
def do_results(election):
results = election.do_get_results()
print 'RESULTS: %s\n' % (' '.join(str(n) for n in results),)
def do_count_parties(election):
results = election.do_get_results()
candidates = election.do_get_candidates()
results = gamma_count_parties(results, candidates)
import json
print json.dumps(results, ensure_ascii=False, indent=2)
def do_count_range(election):
results = election.do_get_results()
candidates = election.do_get_candidates()
results = gamma_count_range(results, candidates)
import json
print json.dumps(results, ensure_ascii=False, indent=2)
def do_count_candidates(election):
results = election.do_get_results()
candidates = election.do_get_candidates()
results = gamma_count_candidates(results, candidates)
import json
print json.dumps(results, ensure_ascii=False, indent=2)
def main_generate(args, teller=_teller, nr_parallel=0):
filename = args.generate
filename = filename[0] if filename else None
no_verify = args.no_verify
election = ZeusCoreElection.mk_random(
nr_candidates = args.nr_candidates,
nr_trustees = args.nr_trustees,
nr_voters = args.nr_voters,
nr_votes = args.nr_votes,
nr_rounds = args.nr_rounds,
stage = args.stage,
teller=teller, nr_parallel=nr_parallel,
no_verify=no_verify)
exported, stage = election.export()
if not filename:
name = ("%x" % election.do_get_election_public())[:16]
filename = 'election-%s-%s.zeus' % (name, stage)
sys.stderr.write("writing out to '%s'\n\n" % (filename,))
with open(filename, "w") as f:
f.write(to_canonical(exported))
report = exported.get('election_report', '')
del exported
if args.extract_signatures:
do_extract_signatures(election, args.extract_signatures,
teller=teller)
if args.extract_audits:
do_extract_audits(election, args, args.extract_audits,
teller=teller)
if args.counted:
do_counted_votes(election)
if args.results:
do_results(election)
if args.count_parties:
do_count_parties(election)
if args.count_range:
do_count_range(election)
if args.count_candidates:
do_count_candidates(election)
if args.report:
print report
def main_verify_election(args, teller=_teller, nr_parallel=0):
no_verify = args.no_verify
filename = args.election
sys.stderr.write("loading election from '%s'\n" % (filename,))
with open(filename, "r") as f:
try:
finished = from_canonical(f, unicode_strings=0)
except ValueError:
finished = json_load(f)
election = ZeusCoreElection.new_at_finished(finished, teller=teller,
nr_parallel=nr_parallel)
if not no_verify:
election.validate()
if args.extract_signatures:
do_extract_signatures(election, args.extract_signatures,
teller=teller)
if args.extract_audits:
do_extract_audits(election, args.extract_audits,
teller=teller)
if args.counted:
do_counted_votes(election)
if args.results:
do_results(election)
if args.count_parties:
do_count_parties(election)
if args.count_range:
do_count_range(election)
if args.count_candidates:
do_count_candidates(election)
if args.report:
do_report(election)
return election
def main_verify_signature(args, teller=_teller, nr_parallel=0):
no_verify = args.no_verify
report = args.report
sigfiles = args.verify_signatures
if len(sigfiles) < 1:
m = "No signature files given!"
raise ValueError(m)
if not args.election:
m = ("cannot verify signature without an election file "
"and at least one signature file")
raise ValueError(m)
election_file = args.election
sys.stderr.write("loading election from '%s'\n" % (election_file,))
with open(election_file, "r") as f:
try:
finished = from_canonical(f, unicode_strings=0)
except ValueError:
finished = json_load(f)
election = ZeusCoreElection.new_at_finished(finished, teller=teller,
nr_parallel=nr_parallel,
no_verify=no_verify)
if report:
do_report()
with teller.task("Verifying signatures", total=len(sigfiles)):
for sigfile in sigfiles:
with open(sigfile, "r") as f:
signature = f.read()
signed_vote = election.verify_vote_signature(signature)
election.validate_vote(signed_vote)
teller.advance()
class Nullstream(object):
def write(*args):
return
def flush(*args):
return
outstream = sys.stderr if args.verbose else Nullstream()
teller_stream = TellerStream(outstream=outstream,
output_interval_ms=args.oms,
buffering=not args.no_buffer,
buffer_feeds=args.buffer_feeds)
teller = Teller(outstream=teller_stream)
if args.no_buffer:
Teller.eol = '\n'
Teller.feed = '\n'
nr_parallel = 0
if args.nr_procs > 0:
nr_parallel = int(args.nr_procs)
if args.generate is not None:
return main_generate(args, teller=teller, nr_parallel=nr_parallel)
elif args.verify_signatures:
return main_verify_signature(args, teller=teller,
nr_parallel=nr_parallel)
elif args.election:
return main_verify_election(args, teller=teller,
nr_parallel=nr_parallel)
else:
parser.print_help()
teller_stream.flush()
def test_decryption():
from zeus_sk import mix_ciphers
g = _default_crypto['generator']
p = _default_crypto['modulus']
q = _default_crypto['order']
texts = [0, 1, 2, 3, 4]
keys = [13, 14, 15, 16]
publics = [pow(g, x, p) for x in keys]
pk = 1
for y in publics:
pk = (pk * y) % p
cts = []
rands = []
for t in texts:
ct = encrypt(t, p, g, q, pk)
cts.append((ct[0], ct[1]))
rands.append(ct[2])
all_factors = []
for x in keys:
factors = compute_decryption_factors(p, g, q, x, cts)
all_factors.append(factors)
master_factors = combine_decryption_factors(p, all_factors)
pts = []
for (alpha, beta), factor in izip(cts, master_factors):
pts.append(decrypt_with_decryptor(p, g, q, beta, factor))
if pts != texts:
raise AssertionError("Z")
cfm = {'modulus': p,
'generator': g,
'order': q,
'public': pk,
'original_ciphers': cts,
'mixed_ciphers': cts}
mix1 = mix_ciphers(cfm)
mix = mix_ciphers(mix1)
cts = mix['mixed_ciphers']
all_factors = []
for x in keys:
factors = compute_decryption_factors(p, g, q, x, cts)
all_factors.append(factors)
master_factors = combine_decryption_factors(p, all_factors)
pts = []
for (alpha, beta), factor in izip(cts, master_factors):
pts.append(decrypt_with_decryptor(p, g, q, beta, factor))
if sorted(pts) != sorted(texts):
raise AssertionError("ZZ")
retval = []
if __name__ == '__main__':
#verify_gamma_encoding(7)
#cross_check_encodings(7)
#test_decryption()
retval.append(main()) | zeus-client | /zeus-client-0.1.7.tar.gz/zeus-client-0.1.7/zeus/core.py | core.py |
import re
import sys
import os
import time
import ssl
import copy
from zeus.core import (c2048, get_random_selection,
gamma_encode, gamma_decode, gamma_encoding_max,
to_relative_answers, to_absolute_answers,
to_canonical, from_canonical,
encrypt, prove_encryption,
decrypt_with_randomness,
compute_decryption_factors,
verify_vote_signature,
parties_from_candidates,
gamma_decode_to_party_ballot,
FormatError)
from httplib import HTTPConnection, HTTPSConnection
from urlparse import urlparse, parse_qsl
from urllib import urlencode, unquote
from os.path import exists
from sys import argv, stderr
from json import loads, dumps, load, dump
from Queue import Queue, Empty
from threading import Thread
from random import choice, shuffle, randint
from base64 import b64encode
p, g, q, x, y = c2048()
def get_http_connection(url):
parsed = urlparse(url)
kwargs = {}
if parsed.scheme == 'https':
default_port = '443'
Conn = HTTPSConnection
kwargs['context'] = ssl._create_unverified_context()
else:
default_port = '80'
Conn = HTTPConnection
host, sep, port = parsed.netloc.partition(':')
if not port:
port = default_port
netloc = host + ':' + port
conn = Conn(netloc, **kwargs)
conn.path = parsed.path
return conn
def generate_voter_file(nr, domain='zeus.minedu.gov.gr'):
return '\n'.join((u'%d, voter-%d@%s, Ψηφοφόρος, %d' % (i, i, domain, i))
for i in xrange(nr))
def generate_vote(p, g, q, y, choices, nr_candidates=None):
if isinstance(choices, int):
nr_candidates = choices
selection = get_random_selection(nr_candidates, full=0)
else:
nr_candidates = nr_candidates or (max(choices) if choices else 0) + 1
selection = to_relative_answers(choices, nr_candidates)
encoded = gamma_encode(selection, nr_candidates)
ct = encrypt(encoded, p, g, q, y)
alpha, beta, rand = ct
proof = prove_encryption(p, g, q, alpha, beta, rand)
commitment, challenge, response = proof
answer = {}
answer['encryption_proof'] = (commitment, challenge, response)
answer['choices'] = [{'alpha': alpha, 'beta': beta}]
encrypted_vote = {}
encrypted_vote['answers'] = [answer]
encrypted_vote['election_uuid'] = ''
encrypted_vote['election_hash'] = ''
return encrypted_vote, encoded, rand
def main_verify(sigfile, randomness=None, plaintext=None):
with open(sigfile) as f:
signature = f.read()
vote_info = verify_vote_signature(signature)
signed_vote, crypto, trustees, candidates, comments = vote_info
eb = signed_vote['encrypted_ballot']
public = eb['public']
modulus, generator, order = crypto
beta = eb['beta']
print 'VERIFIED: Authentic Signature'
if randomness is None:
return
nr_candidates = len(candidates)
encoded = decrypt_with_randomness(modulus, generator, order,
public, beta, randomness)
if plaintext is not None:
if plaintext != encoded:
print 'FAILED: Plaintext Mismatch'
ct = encrypt(plaintext, modulus, generator, order, randomness)
_alpha, _beta, _randomness = ct
alpha = eb['alpha']
if (alpha, beta) != (_alpha, _beta):
print 'FAILED: Invalid Encryption'
max_encoded = gamma_encoding_max(nr_candidates) + 1
print "plaintext: %d" % encoded
print "max plaintext: %d" % max_encoded
if encoded > max_encoded:
print "FAILED: Invalid Vote. Cannot decode."
return
selection = gamma_decode(encoded, nr_candidates)
choices = to_absolute_answers(selection, nr_candidates)
print ""
for i, o in enumerate(choices):
print "%d: [%d] %s" % (i, o, candidates[o])
print ""
def get_poll_info(url):
conn = get_http_connection(url)
path = conn.path
conn.request('GET', path)
response = conn.getresponse()
response.read()
cookie = response.getheader('Set-Cookie')
if not cookie:
raise RuntimeError("Cannot get cookie")
cookie = cookie.split(';')[0]
headers = {'Cookie': cookie}
poll_intro = response.getheader('location')
poll_intro = '/' + poll_intro.split("/", 3)[3]
conn.request('GET', poll_intro, headers=headers)
response = conn.getresponse()
html = response.read()
links_re = re.compile("href=\"(.*polls/.*/l/.*)\"")
try:
links = links_re.findall(html)
poll_id = path.split("/")[-2]
poll_url = filter(lambda x: poll_id in x, links)[0]
except Exception, e:
import pdb; pdb.set_trace()
print html
raise
if 'link-to' in poll_url:
conn.request('GET', poll_url, headers=headers)
response = conn.getresponse()
_headers = response.getheaders()
body = response.read()
poll_url = dict(_headers).get('location')
parsed = urlparse(poll_url)
booth_path = parsed.path
poll_info = dict(parse_qsl(parsed.query))
poll_json_path = urlparse(poll_info['poll_json_url']).path
conn.request('GET', poll_json_path, headers=headers)
response = conn.getresponse()
poll_info['poll_data'] = loads(response.read())
return conn, headers, poll_info
def extract_poll_info(poll_info):
csrf_token = poll_info['token']
voter_path = conn.path
poll_data = poll_info['poll_data']
pk = poll_data['public_key']
p = int(pk['p'])
g = int(pk['g'])
q = int(pk['q'])
y = int(pk['y'])
answers = poll_data['questions'][0]['answers']
cast_path = poll_data['cast_url']
return cast_path, csrf_token, answers, p, g, q, y
def do_cast_vote(conn, cast_path, token, headers, vote):
body = urlencode({'encrypted_vote': dumps(vote), 'csrfmiddlewaretoken': token})
conn.request('POST', cast_path, headers=headers, body=body)
response = conn.getresponse()
body = response.read()
if response.status != 200:
print response.status
conn.close()
def _make_vote(poll_data, choices=None):
pk = poll_data['public_key']
p = int(pk['p'])
g = int(pk['g'])
q = int(pk['q'])
y = int(pk['y'])
candidates = poll_data['questions'][0]['answers']
parties = None
try:
parties, nr_groups = parties_from_candidates(candidates)
except FormatError as e:
pass
if parties:
if randint(0,19) == 0:
choices = []
else:
party_choice = choice(parties.keys())
party = parties[party_choice]
party_candidates = [k for k in party.keys() if isinstance(k, int)]
min_choices = party['opt_min_choices']
max_choices = party['opt_max_choices']
shuffle(party_candidates)
nr_choices = randint(min_choices, max_choices)
choices = party_candidates[:nr_choices]
choices.sort()
vote, encoded, rand = generate_vote(p, g, q, y, choices, len(candidates))
for c in choices:
print "Voting for", c, party[c]
ballot = gamma_decode_to_party_ballot(encoded, candidates,
parties, nr_groups)
if not ballot['valid']:
print "valid", ballot['valid'], ballot['invalid_reason']
else:
choices = choices if choices is not None else len(candidates)
vote, encoded, rand = generate_vote(p, g, q, y, choices)
return vote, encoded, rand
def cast_vote(voter_url, choices=None):
conn, headers, poll_info = get_poll_info(voter_url)
csrf_token = poll_info['token']
headers['Cookie'] += "; csrftoken=%s" % csrf_token
headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8'
headers['Referer'] = voter_url
voter_path = conn.path
vote, encoded, rand = _make_vote(poll_info['poll_data'], choices)
cast_path = poll_info['poll_data']['cast_url']
do_cast_vote(conn, cast_path, csrf_token, headers, vote)
return encoded, rand
def main_generate(nr, domain, voters_file):
if exists(voters_file):
m = "%s: file exists, will not overwrite" % (voters_file,)
raise ValueError(m)
with open(voters_file, "w") as f:
f.write(generate_voter_file(nr, domain=domain).encode('utf-8'))
def main_random_cast_thread(inqueue, outqueue):
while 1:
try:
o = inqueue.get_nowait()
if not o:
break
except Empty, e:
break
i, total, voter_url = o
print "%d/%d" % (i+1, total)
encoded, rand = cast_vote(voter_url)
outqueue.put(encoded)
def main_random_cast(voter_url_file, plaintexts_file, nr_threads=2):
if exists(plaintexts_file):
m = "%s: file exists, will not overwrite" % (plaintexts_file,)
raise ValueError(m)
f = open(plaintexts_file, "w")
voter_urls = open(voter_url_file).read().splitlines()
total = len(voter_urls)
inqueue = Queue(maxsize=total)
outqueue = Queue(maxsize=total)
for i, voter_url in enumerate(voter_urls):
inqueue.put((i, total, voter_url))
#main_random_cast_thread(queue)
threads = [Thread(target=main_random_cast_thread, args=(inqueue, outqueue))
for _ in xrange(nr_threads)]
for t in threads:
t.daemon = True
t.start()
plaintexts = [outqueue.get() for _ in xrange(total)]
f.write(repr(plaintexts))
f.close()
for t in threads:
t.join()
def main_show(url):
conn, cast_path, token, headers, answers, p, g, q, y = get_election(url)
for i, c in enumerate(answers):
if isinstance(c, unicode):
c = c.encode('utf-8')
print "%d: %s" % (i, c)
def main_vote(url, choice_str):
choices = [int(x) for x in choice_str.split(',')]
encoded, rand = cast_vote(url, choices)
print "encoded selection:", encoded
print "encryption randomness:", rand
def do_download_mix(url, savefile):
if exists(savefile):
m = "file '%s' already exists, will not overwrite" % (savefile,)
raise ValueError(m)
conn = get_http_connection(url)
conn.request('GET', conn.path)
response = conn.getresponse()
save_data = response.read()
if "polls" not in url:
polls = loads(save_data)
for i, url in enumerate(polls):
do_download_mix(url, "{}.{}".format(savefile, i))
return
with open(savefile, "w") as f:
f.write(save_data)
return save_data
def get_login(url):
url = unquote(url)
conn = get_http_connection(url)
parsed = urlparse(url)
path_parts = parsed.path.split("/")
_, _, election, _, _, trustee, password = path_parts[-7:]
prefix = "/".join(path_parts[:-6])
auth = b64encode("%s:%s:%s" % (election, trustee, password))
headers = {
'Authorization': 'Basic %s' % auth
}
base_url = "%s/elections/%s/trustee" % (prefix, election)
return conn, headers, base_url
def get_election_info(url):
conn, headers, url = get_login(url)
conn.request('GET', url + '/json', headers=headers)
resp = loads(conn.getresponse().read())
return resp
def do_download_ciphers(url, savefile):
save_data = None
info = get_election_info(url)
for i, poll in enumerate(info['election']['polls']):
curr_file = savefile + ".%d" % i
if exists(curr_file):
m = "file '%s' already exists, will not overwrite" % (curr_file,)
sys.stdout.write(m + "\n")
continue
conn, headers, base = get_login(url)
download_url = urlparse(poll['ciphers_url']).path
conn.request('GET', download_url, headers=headers)
response = conn.getresponse()
save_data = response.read()
with open(curr_file, "w") as f:
f.write(save_data)
return save_data
def do_upload_mix(outfile, url):
if "polls" not in url:
conn = get_http_connection(url)
conn.request('GET', conn.path)
response = conn.getresponse()
polls = loads(response.read())
for i, poll in enumerate(polls):
do_upload_mix("{}.{}".format(outfile, i), poll)
return
with open(outfile) as f:
out_data = f.read()
conn = get_http_connection(url)
conn.request('POST', conn.path, body=out_data)
response = conn.getresponse()
print response.status, response.read()
def do_upload_factors(outfile, url):
poll_index = 0
curr_file = outfile + ".%d" % poll_index
while(exists(curr_file)):
with open(curr_file) as f:
out_data = f.read()
info = get_election_info(url)
path = info['election']['polls'][poll_index]['post_decryption_url']
path = urlparse(path).path
conn, headers, redirect = get_login(url)
body = urlencode({'factors_and_proofs': out_data})
headers = copy.copy(headers)
headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8'
conn.request('POST', path, body=body, headers=headers)
response = conn.getresponse().read()
print response
poll_index += 1
curr_file = outfile + ".%d" % poll_index
def do_mix(mixfile, newfile, nr_rounds, nr_parallel, module):
if exists(newfile):
m = "file '%s' already exists, will not overwrite" % (newfile,)
raise ValueError(m)
if os.path.exists("{}.0".format(mixfile)):
i = 0
while os.path.exists("{}.{}".format(mixfile, i)):
do_mix("{}.{}".format(mixfile, i), "{}.{}".format(newfile, i),
nr_rounds, nr_parallel, module)
i = i + 1
return
with open(mixfile) as f:
mix = from_canonical(f)
new_mix = module.mix_ciphers(mix, nr_rounds=nr_rounds,
nr_parallel=nr_parallel)
with open(newfile, "w") as f:
to_canonical(new_mix, out=f)
return new_mix
def do_automix(url, prefix, nr_rounds, nr_parallel, module):
do_download_mix(url, "{}-votes".format(prefix))
do_mix("{}-votes".format(prefix), "{}-mix".format(prefix), nr_rounds,
nr_parallel, module)
do_upload_mix("{}-mix".format(prefix), url)
def do_decrypt(savefile, outfile, keyfile, nr_parallel):
poll_index = 0
curr_file = savefile + ".0"
with open(keyfile) as f:
key = load(f)
secret = int(key['x'])
pk = key['public_key']
modulus = int(pk['p'])
generator = int(pk['g'])
order = int(pk['q'])
public = int(pk['y'])
del key
while(os.path.isfile(curr_file)):
curr_outfile = outfile + ".%d" % poll_index
if exists(curr_outfile):
m = "file '%s' already exists, will not overwrite" % (curr_outfile,)
sys.stderr.write(m + "\n")
poll_index += 1
curr_file = savefile + ".%d" % poll_index
continue
with open(curr_file) as f:
tally = load(f)['tally']
ciphers = [(int(ct['alpha']), int(ct['beta']))
for ct in tally['tally'][0]]
factors = compute_decryption_factors(modulus, generator, order,
secret, ciphers,
nr_parallel=nr_parallel)
decryption_factors = []
factor_append = decryption_factors.append
decryption_proofs = []
proof_append = decryption_proofs.append
for factor, proof in factors:
factor_append(factor)
f = {}
f['commitment'] = {'A': proof[0], 'B': proof[1]}
f['challenge'] = proof[2]
f['response'] = proof[3]
proof_append(f)
factors_and_proofs = {
'decryption_factors': [decryption_factors],
'decryption_proofs': [decryption_proofs]
}
with open(curr_outfile, "w") as f:
dump(factors_and_proofs, f)
poll_index += 1
curr_file = savefile + ".%d" % poll_index
return factors
def main_help():
usage = ("Usage: {0} generate <nr> <domain> <voters.csv>\n"
" {0} masscast <voter_url_file> <plaintexts_file> [nr_threads]\n"
" {0} show <voter_url>\n"
" {0} castvote <voter_url> <1st>,<2nd>,... (e.g.)\n"
" {0} verify <vote_signature_file> [randomness [plaintext]]\n"
"\n"
" {0} download mix <url> <input.mix>\n"
" {0} mix [<url> <mix-name>|<input.mix> <output.mix>] <nr_rounds> <nr_parallel>\n"
" {0} upload mix <output.mix> <url>\n"
"\n"
" {0} download ciphers <url> <ballots_savefile>\n"
" {0} decrypt <ballots_savefile> <factors_outfile> <key_file> <nr_parallel>\n"
" {0} upload factors <factors_outfile> <url>\n".format(sys.argv[0]))
sys.stderr.write(usage)
raise SystemExit
def main(argv=None):
argv = argv or sys.argv
argc = len(argv)
if argc < 2:
main_help()
cmd = argv[1]
if cmd == 'download':
if argc < 5:
main_help()
if argv[2] == 'mix':
do_download_mix(argv[3], argv[4])
elif argv[2] == 'ciphers':
do_download_ciphers(argv[3], argv[4])
else:
main_help()
elif cmd == 'upload':
if argc < 5:
main_help()
if argv[2] == 'mix':
do_upload_mix(argv[3], argv[4])
elif argv[2] == 'factors':
do_upload_factors(argv[3], argv[4])
else:
main_help()
elif cmd == 'mix':
if argc < 6:
main_help()
import zeus_sk as shuffle_module
if argv[2].startswith("http"):
do_automix(argv[2], argv[3], int(argv[4]), int(argv[5]),
shuffle_module)
else:
do_mix(argv[2], argv[3], int(argv[4]), int(argv[5]),
shuffle_module)
elif cmd == 'decrypt':
if argc < 6:
main_help()
do_decrypt(argv[2], argv[3], argv[4], int(argv[5]))
elif cmd == 'generate':
if argc < 5:
main_help()
main_generate(int(argv[2]), argv[3], argv[4])
elif cmd == 'masscast':
if argc < 4:
main_help()
nr_threads=int(argv[4]) if argc > 4 else 2
main_random_cast(argv[2], argv[3], nr_threads=nr_threads)
elif cmd == 'show':
if argc < 3:
main_help()
main_show(argv[2])
elif cmd == 'castvote':
if argc < 3:
main_help()
if argc == 3:
main_show(argv[2])
else:
main_vote(argv[2], ''.join(argv[3:]))
elif cmd == 'verify':
if argc < 3:
main_help()
randomness = None if argc < 4 else int(argv[3])
plaintext = None if argc < 5 else int(argv[4])
main_verify(argv[2], randomness, plaintext)
else:
main_help()
if __name__ == '__main__':
main(sys.argv) | zeus-client | /zeus-client-0.1.7.tar.gz/zeus-client-0.1.7/zeus/client.py | client.py |
from zeus.core import (
ZeusError, pow, sha256, ALPHA, BETA,
get_random_int, bit_iterator, get_random_permutation,
Random, AsyncController, MIN_MIX_ROUNDS, _teller)
def reencrypt(modulus, generator, order, public, alpha, beta, secret=None):
key = get_random_int(3, order) if secret is None else secret
alpha = (alpha * pow(generator, key, modulus)) % modulus
beta = (beta * pow(public, key, modulus)) % modulus
if secret is None:
return [alpha, beta, key]
return [alpha, beta]
def compute_mix_challenge(cipher_mix):
hasher = sha256()
update = hasher.update
update("%x" % cipher_mix['modulus'])
update("%x" % cipher_mix['generator'])
update("%x" % cipher_mix['order'])
update("%x" % cipher_mix['public'])
original_ciphers = cipher_mix['original_ciphers']
for cipher in original_ciphers:
update("%x" % cipher[ALPHA])
update("%x" % cipher[BETA])
mixed_ciphers = cipher_mix['mixed_ciphers']
for cipher in mixed_ciphers:
update("%x" % cipher[ALPHA])
update("%x" % cipher[BETA])
for ciphers in cipher_mix['cipher_collections']:
for cipher in ciphers:
update("%x" % cipher[ALPHA])
update("%x" % cipher[BETA])
challenge = hasher.hexdigest()
return challenge
def shuffle_ciphers(modulus, generator, order, public, ciphers,
teller=None, report_thresh=128, async_channel=None):
nr_ciphers = len(ciphers)
mixed_offsets = get_random_permutation(nr_ciphers)
mixed_ciphers = list([None]) * nr_ciphers
mixed_randoms = list([None]) * nr_ciphers
count = 0
for i in xrange(nr_ciphers):
alpha, beta = ciphers[i]
alpha, beta, secret = reencrypt(modulus, generator, order, public,
alpha, beta)
mixed_randoms[i] = secret
o = mixed_offsets[i]
mixed_ciphers[o] = [alpha, beta]
count += 1
if count >= report_thresh:
if teller:
teller.advance(count)
if async_channel:
async_channel.send_shared(count, wait=1)
count = 0
if count:
if teller:
teller.advance(count)
if async_channel:
async_channel.send_shared(count, wait=1)
return [mixed_ciphers, mixed_offsets, mixed_randoms]
def mix_ciphers(ciphers_for_mixing, nr_rounds=MIN_MIX_ROUNDS,
teller=_teller, nr_parallel=0):
p = ciphers_for_mixing['modulus']
g = ciphers_for_mixing['generator']
q = ciphers_for_mixing['order']
y = ciphers_for_mixing['public']
original_ciphers = ciphers_for_mixing['mixed_ciphers']
nr_ciphers = len(original_ciphers)
if nr_parallel > 0:
Random.atfork()
async = AsyncController(parallel=nr_parallel)
async_shuffle_ciphers = async.make_async(shuffle_ciphers)
teller.task('Mixing %d ciphers for %d rounds' % (nr_ciphers, nr_rounds))
cipher_mix = {'modulus': p, 'generator': g, 'order': q, 'public': y}
cipher_mix['original_ciphers'] = original_ciphers
with teller.task('Producing final mixed ciphers', total=nr_ciphers):
shuffled = shuffle_ciphers(p, g, q, y, original_ciphers, teller=teller)
mixed_ciphers, mixed_offsets, mixed_randoms = shuffled
cipher_mix['mixed_ciphers'] = mixed_ciphers
total = nr_ciphers * nr_rounds
with teller.task('Producing ciphers for proof', total=total):
if nr_parallel > 0:
channels = [async_shuffle_ciphers(p, g, q, y, original_ciphers,
teller=None)
for _ in xrange(nr_rounds)]
count = 0
while count < total:
nr = async.receive_shared()
teller.advance(nr)
count += nr
collections = [channel.receive(wait=1) for channel in channels]
async.shutdown()
else:
collections = [shuffle_ciphers(p, g, q, y,
original_ciphers, teller=teller)
for _ in xrange(nr_rounds)]
unzipped = [list(x) for x in zip(*collections)]
cipher_collections, offset_collections, random_collections = unzipped
cipher_mix['cipher_collections'] = cipher_collections
cipher_mix['random_collections'] = random_collections
cipher_mix['offset_collections'] = offset_collections
with teller.task('Producing cryptographic hash challenge'):
challenge = compute_mix_challenge(cipher_mix)
cipher_mix['challenge'] = challenge
bits = bit_iterator(int(challenge, 16))
with teller.task('Answering according to challenge', total=nr_rounds):
for i, bit in zip(xrange(nr_rounds), bits):
ciphers = cipher_collections[i]
offsets = offset_collections[i]
randoms = random_collections[i]
if bit == 0:
# Nothing to do, we just publish our offsets and randoms
pass
elif bit == 1:
# The image is given. We now have to prove we know
# both this image's and mixed_ciphers' offsets/randoms
# by providing new offsets/randoms so one can reencode
# this image to end up with mixed_ciphers.
# original_ciphers -> image
# original_ciphers -> mixed_ciphers
# Provide image -> mixed_ciphers
new_offsets = list([None]) * nr_ciphers
new_randoms = list([None]) * nr_ciphers
for j in xrange(nr_ciphers):
cipher_random = randoms[j]
cipher_offset = offsets[j]
mixed_random = mixed_randoms[j]
mixed_offset = mixed_offsets[j]
new_offsets[cipher_offset] = mixed_offset
new_random = (mixed_random - cipher_random) % q
new_randoms[cipher_offset] = new_random
offset_collections[i] = new_offsets
random_collections[i] = new_randoms
del ciphers, offsets, randoms
else:
m = "This should be impossible. Something is broken."
raise AssertionError(m)
teller.advance()
teller.finish('Mixing')
return cipher_mix
def verify_mix_round(p, g, q, y, i, bit, original_ciphers, mixed_ciphers,
ciphers, randoms, offsets,
teller=None, report_thresh=128, async_channel=None):
nr_ciphers = len(original_ciphers)
count = 0
if bit == 0:
for j in xrange(nr_ciphers):
original_cipher = original_ciphers[j]
a = original_cipher[ALPHA]
b = original_cipher[BETA]
r = randoms[j]
new_a, new_b = reencrypt(p, g, q, y, a, b, r)
o = offsets[j]
cipher = ciphers[o]
if new_a != cipher[ALPHA] or new_b != cipher[BETA]:
m = ('MIXING VERIFICATION FAILED AT '
'ROUND %d CIPHER %d bit 0' % (i, j))
raise AssertionError(m)
count += 1
if count >= report_thresh:
if async_channel:
async_channel.send_shared(count)
if teller:
teller.advance(count)
count = 0
elif bit == 1:
for j in xrange(nr_ciphers):
cipher = ciphers[j]
a = cipher[ALPHA]
b = cipher[BETA]
r = randoms[j]
new_a, new_b = reencrypt(p, g, q, y, a, b, r)
o = offsets[j]
mixed_cipher = mixed_ciphers[o]
if new_a != mixed_cipher[ALPHA] or new_b != mixed_cipher[BETA]:
m = ('MIXING VERIFICATION FAILED AT '
'ROUND %d CIPHER %d bit 1' % (i, j))
raise AssertionError(m)
count += 1
if count >= report_thresh:
if async_channel:
async_channel.send_shared(count)
if teller:
teller.advance(count)
count = 0
else:
m = "This should be impossible. Something is broken."
raise AssertionError(m)
if count:
if async_channel:
async_channel.send_shared(count)
if teller:
teller.advance(count)
def verify_cipher_mix(cipher_mix, teller=_teller, nr_parallel=0):
try:
p = cipher_mix['modulus']
g = cipher_mix['generator']
q = cipher_mix['order']
y = cipher_mix['public']
original_ciphers = cipher_mix['original_ciphers']
mixed_ciphers = cipher_mix['mixed_ciphers']
challenge = cipher_mix['challenge']
cipher_collections = cipher_mix['cipher_collections']
offset_collections = cipher_mix['offset_collections']
random_collections = cipher_mix['random_collections']
except KeyError, e:
m = "Invalid cipher mix format"
raise ZeusError(m, e)
if compute_mix_challenge(cipher_mix) != challenge:
m = "Invalid challenge"
raise ZeusError(m)
nr_ciphers = len(original_ciphers)
nr_rounds = len(cipher_collections)
teller.task('Verifying mixing of %d ciphers for %d rounds'
% (nr_ciphers, nr_rounds))
if (len(offset_collections) != nr_rounds or
len(random_collections) != nr_rounds):
m = "Invalid cipher mix format: collections not of the same size!"
raise ZeusError(m)
#if not validate_cryptosystem(p, g, q, teller):
# m = "Invalid cryptosystem"
# raise AssertionError(m)
if nr_parallel > 0:
async = AsyncController(parallel=nr_parallel)
async_verify_mix_round = async.make_async(verify_mix_round)
total = nr_rounds * nr_ciphers
with teller.task('Verifying ciphers', total=total):
channels = []
append = channels.append
for i, bit in zip(xrange(nr_rounds), bit_iterator(int(challenge, 16))):
ciphers = cipher_collections[i]
randoms = random_collections[i]
offsets = offset_collections[i]
if nr_parallel <= 0:
verify_mix_round(p, g, q, y,
i, bit, original_ciphers,
mixed_ciphers, ciphers,
randoms, offsets,
teller=teller)
else:
append(async_verify_mix_round(p, g, q, y, i, bit,
original_ciphers,
mixed_ciphers,
ciphers, randoms, offsets,
teller=None))
if nr_parallel > 0:
count = 0
while count < total:
nr = async.receive_shared(wait=1)
teller.advance(nr)
count += nr
for channel in channels:
channel.receive(wait=1)
async.shutdown()
teller.finish('Verifying mixing')
return 1 | zeus-client | /zeus-client-0.1.7.tar.gz/zeus-client-0.1.7/zeus/zeus_sk.py | zeus_sk.py |
.. image:: https://zeus.lab804.com.br/img/logo_zeus.svg
:alt: Zeus logo
:width: 300
:height: 150
:align: center
:Info: Scaffold flask.
:Repository: https://github.com/murilobsd/zeus
:Author: Murilo Ijanc (http://github.com/murilobsd)
:Site: `https://zeus.lab804.com.br <https://zeus.lab804.com.br>`_
.. image:: https://badge.fury.io/py/zeus-lab804.svg
:target: https://badge.fury.io/py/zeus-lab804
:alt: Pypi Package
.. image:: https://landscape.io/github/murilobsd/zeus/master/landscape.png
:target: https://landscape.io/github/murilobsd/zeus/master
:alt: Code Health
Sobre
=====
Zeus facilita a criação de projetos para `Flask` além de implementar outras
bibliotecas como `flask-cache <https://github.com/thadeusb/flask-cache>`_,
`flask-script <https://github.com/smurfix/flask-script>`_,
`flask-mongonegine <https://github.com/MongoEngine/flask-mongoengine>`_... possui
funcionalidades para criação de módulos e templates.
Instalação
==========
Nós recomendamos o uso do `virtualenv <https://virtualenv.pypa.io/>`_ e do
`pip <https://pip.pypa.io/>`_. Você pode instalar ``pip install -U zeus-lab804``.
é necessário ter `setuptools <http://peak.telecommunity.com/DevCenter/setuptools>`_
uma alternativa ``easy_install -U zeus-lab804``. Por fim, você pode realizar o
download do código em `GitHub <http://github.com/murilobsd/zeus>`_ e rodar ``python
setup.py install``.
Dependências
============
- mongo
- colorama==0.3.7
- colorlog==2.7.0
- Jinja2==2.8
- MarkupSafe==0.23
- pyfiglet==0.7.5
- termcolor==1.1.0
Exemplos
========
Alguns exemplos:
.. code-block:: shell
# Criando Projeto
$ zeus --project meuprojeto
$ cd meuprojeto/
$ pip install -r requirements-dev.txt
$ python manage.py runserver
# Abra seu navegador http://127.0.0.1:5000/
.. code-block:: shell
# Gerando Modulo
$ zeus --module pagamento meuprojeto # Caminho do meuprojeto
# Gerando Template para Modulo
$ zeus --template pagamento meuprojeto # Caminho do meuprojeto
Opções
======
Outras argumentos que podem ser utilizado na **criação do projeto**.
.. code-block:: shell
$ zeus --help
________ _______ __ __ _______. __
| / | ____|| | | | / || |
`---/ / | |__ | | | | | (----`| |
/ / | __| | | | | \ \ | |
/ /----.| |____ | `--' | .----) | |__|
/________||_______| \______/ |_______/ (__)
usage: zeus [-h] [--project PROJECT] [--module MODULE MODULE]
[--template TEMPLATE TEMPLATE] [--author AUTHOR] [--domain DOMAIN]
[--debug DEBUG] [--version]
optional arguments:
-h, --help show this help message and exit
--project PROJECT, -p PROJECT
Creating project.
--module MODULE MODULE, -m MODULE MODULE
Creating module.
--template TEMPLATE TEMPLATE, -t TEMPLATE TEMPLATE
Creating template.
--author AUTHOR, -a AUTHOR
Author of project (default: Lab804).
--domain DOMAIN, -do DOMAIN
Domain, (default: lab804.com.br)
--debug DEBUG, -d DEBUG
Debug mode.
--version, -v show program's version number and exit
Tests
=====
Preciso ter vergonha na cara é gerar testes.
Contribuir
============
Contribua de qualquer forma, veja se sua sugestão já não foi respondida nas
`issues <https://github.com/murilobsd/zeus/issues>`_, crie um logo para o
projeto, de sugestões para exemplos, crie templates, ajude criar a wiki...
| zeus-lab804 | /zeus-lab804-0.1.2.tar.gz/zeus-lab804-0.1.2/README.rst | README.rst |
"""Zeus ...."""
import os
import re
import sys
import uuid
import time
import jinja2
import codecs
import shutil
import logging
import colorlog
import argparse
from colorama import init
from termcolor import cprint
from datetime import datetime
from pyfiglet import figlet_format
init(autoreset=True, strip=not sys.stdout.isatty())
# logging
handler = colorlog.StreamHandler()
handler.setFormatter(colorlog.ColoredFormatter(
'%(log_color)s[%(name)s] \u2192 %(message)s',
datefmt="%d/%m/%Y"))
logger = colorlog.getLogger("ZEUS")
logger.addHandler(handler)
logger.setLevel(logging.INFO)
class CreateFolderException(Exception):
"""Create Folder Module."""
pass
class DuplicateModuleException(Exception):
"""Duplicate Module Name."""
pass
class DuplicateException(Exception):
"""Duplicate Project Name."""
pass
class RenameFolder(Exception):
"""Exception Rename Folder."""
pass
class StructProject:
"""Resposible to struct project.
:class:`commands.StructProject` See :ref:`projects` for more information.
"""
_templatesfld = "templates" # Template folder.
_appfld = "app" # Template app folder
cwd = os.getcwd()
# Where i who?
scriptdir = os.path.dirname(os.path.realpath(__file__))
def __init__(self, name_project, author, domain):
"""Init function."""
self.name = name_project
self.name_project = self._clean_name(name_project)
self.author = author
self.domain = self._adjust_domain(domain)
# path of project
self.projectfolder = os.path.join(self.cwd, self.name_project)
def _clean_name(self, name):
"""Clean name of project."""
logger.debug("Clean name of project.")
return re.sub(r"[\s\.]", "", name.lower())
def _adjust_domain(self, domain):
"""Adjust domain."""
logger.debug("Adjusting domain.")
# TODO: Checking if domain is correctly.
return domain.lower()
def copy_struct(self):
"""Copy folders to project folder path."""
logger.debug("Copy struct of folders with new project.")
try:
shutil.copytree(os.path.join(self.scriptdir, self._templatesfld),
self.projectfolder)
self.rename_folder(os.path.join(self.projectfolder,
self._appfld),
os.path.join(self.projectfolder,
self.name_project))
logger.info("[ \u2714 ] Completed copy data to project folder.")
except Exception as e:
logger.error("[ \u2717 ] " + e)
def random(self, size=32):
"""random values."""
return codecs.encode(os.urandom(size), "hex").decode("utf-8")
def rename_folder(self, src, dst):
"""Rename folder."""
try:
os.rename(src, dst)
return True
except:
raise RenameFolder("Error rename folder: %s" % src)
def write(self, dst, templatef, context, templatefld=None):
"""write contents."""
if templatefld is None:
templatefld = self._templatesfld
# jinja env
template_loader = jinja2.FileSystemLoader(
searchpath=os.path.join(self.scriptdir, templatefld))
template_env = jinja2.Environment(loader=template_loader)
template = template_env.get_template(templatef)
content = template.render(context)
with open(dst, 'w+') as destiny:
destiny.write(content)
return True
class Module(StructProject):
"""Module."""
_modulefld = "_module" # Folder template module.
std_modules = {
"users": ["__init__.py", "controllers.py", "models.py", "forms.py"],
"admin": ["__init__.py", "controllers.py", "models.py", "forms.py"],
"public": ["__init__.py", "controllers.py", "models.py", "forms.py"]
}
def __init__(self, name_project, author, domain):
"""Init function."""
StructProject.__init__(self, name_project, author, domain)
# path of project
self.projectfolder = os.path.join(self.cwd, self.name_project)
# Project exist.
if not os.path.exists(self.projectfolder):
logger.error("[ \u2717 ] Not exist name of project.")
raise Exception("Not exist name of project.")
self.modulesfolder = os.path.join(
self.projectfolder, self.name_project)
def ger_std_modules(self):
"""Generating default modules."""
context = {
"NAMEPROJECT": self.name_project,
"YEAR": datetime.now().year,
"AUTHOR": self.author,
"NAME": self.name,
"MODNAME": None
}
for m_folder in self.std_modules.keys():
files = self.std_modules[m_folder]
for f in files:
templatefile = os.path.join(self.modulesfolder, m_folder,
f)
template = os.path.join(self._appfld, m_folder, f)
# update context key modname
context.update({"MODNAME": m_folder})
self.write(templatefile, template, context)
logger.info("[ \u2714 ] Creating Default Modules.")
def _get_modules(self):
"""return modules folder."""
modules_folder = [folder for folder in
os.listdir(self.modulesfolder)
if os.path.isdir(os.path.join(self.modulesfolder,
folder))]
return modules_folder
def ger_custom(self, name):
"""Generating custom modules."""
custom_name = self._clean_name(name)
mod_path = os.path.join(self.modulesfolder, name)
if os.path.exists(mod_path):
logger.error("[ \u2717 ] Exists same name of module.")
raise DuplicateModuleException("Duplicated module name.")
try:
os.makedirs(mod_path)
except:
logger.error("[ \u2717 ] Error creating module folder.")
raise CreateFolderException("Error creating module folder.")
context = {
"NAMEPROJECT": self.name_project,
"YEAR": datetime.now().year,
"AUTHOR": self.author,
"NAME": self.name,
"MODNAME": custom_name
}
files = ["__init__.py", "controllers.py", "models.py", "forms.py"]
for f in files:
templatefile = os.path.join(mod_path, f)
self.write(templatefile, f, context, templatefld=self._modulefld)
# update __init__.py
self.update_app(custom_name)
logger.info("[ \u2714 ] Completed created module.")
def update_app(self, custom_name):
"""Update for put blueprints and modules in __init__.py."""
template = None
limit = 0
with open(os.path.join(self.modulesfolder, "__init__.py")) as destiny:
template = destiny.readlines()
if not template:
raise Exception("Not exist file __int__.py file")
for num, line in enumerate(template):
str_find = ("from "
+ self.name_project + " import users, admin, public")
if line.startswith(str_find):
list_line = line.split(",")
list_line[-1] = list_line[-1].replace("\n", "")
list_line.append(" " + custom_name + "\n")
line = ",".join(list_line)
template[num] = line
elif line.startswith(" app.register_blueprint("):
limit = num
else:
pass
if limit != 0:
# Template blueprint
tpl_bp = " app.register_blueprint({}.controllers.blueprint)\n"
template.insert(limit + 1, tpl_bp.format(custom_name))
# save update datas
filename = os.path.join(self.modulesfolder, "__init__.py")
with open(filename, "w") as destiny:
destiny.write("".join(template))
class Template(StructProject):
"""Represents Template. Template is an object that create templates modules.
:class:`commands.Template` See :ref:`templates` for more information.
"""
_modulefld = "_template" # Folder template module.
_files = ["create.jinja", "edit.jinja", "get.jinja", "list.jinja"]
def __init__(self, name_project, author, domain):
"""Init function."""
StructProject.__init__(self, name_project, author, domain)
# path of project
self.projectfolder = os.path.join(self.cwd, self.name_project)
# Project exist.
if not os.path.exists(self.projectfolder):
logger.error("[ \u2717 ] Not exist name of project.")
raise Exception("Not exist name of project.")
self.templatesfolder = os.path.join(
self.projectfolder, "templates")
def ger_custom(self, name):
"""Generating custom template."""
custom_name = self._clean_name(name)
tpl_path = os.path.join(self.templatesfolder, name)
if os.path.exists(tpl_path):
logger.error("[ \u2717 ] Exists same name of template.")
raise DuplicateModuleException("Duplicated template name.")
try:
os.makedirs(tpl_path)
except:
logger.error("[ \u2717 ] Error creating template folder.")
raise CreateFolderException("Error creating template folder.")
context = {
"TITLE": name.capitalize(),
"MODNAME": custom_name
}
# TODO: CHANGE THIS PLEASE
for fname in self._files:
templatefile = os.path.join(tpl_path, fname)
# read
filename = os.path.join(self.scriptdir, self._modulefld, fname)
with open(filename) as destiny:
content = destiny.read()
content = content.replace("{{ TITLE }}", context["TITLE"])
content = content.replace("{{MODNAME}}", context["MODNAME"])
# write
with open(templatefile, "w") as destiny:
destiny.write(content)
logger.info("[ \u2714 ] Completed created template.")
class Project(StructProject):
"""Represents Project. Project is an object that create a struct.
:class:`commands.Project` See :ref:`projects` for more information.
"""
def __init__(self, name_project, author, domain):
"""Init function."""
StructProject.__init__(self, name_project, author, domain)
# path of project
self.projectfolder = os.path.join(self.cwd, self.name_project)
# Project exist.
if os.path.exists(self.projectfolder):
logger.error("[ \u2717 ] Exists same name of project.")
raise DuplicateException("Duplicated project name.")
# Copy all data
self.copy_struct()
self.module = Module(self.name_project, self.author, self.domain)
self.context = {
"SECRETKEY": self.random(),
"NAME": self.name,
"DOMAIN": self.domain,
"SALT": uuid.uuid4().hex,
"NAMEPROJECT": self.name_project,
"AUTHOR": self.author,
"YEAR": datetime.now().year,
"MODULES": ["users", "admin", "public"]
}
def _extensions(self):
"""Plugin flask."""
templatefile = os.path.join(self.projectfolder, self.name_project,
"extensions.py")
self.write(templatefile, os.path.join(self._appfld, "extensions.py"),
self.context)
logger.info("[ \u2714 ] Creating Extensions file.")
return True
def _config(self):
"""Config files."""
templatefile = os.path.join(self.projectfolder, self.name_project,
"config.py")
self.write(templatefile, os.path.join(self._appfld, "config.py"),
self.context)
logger.info("[ \u2714 ] Creating config file.")
return True
def _app(self):
"""Generate App file."""
dst = os.path.join(self.projectfolder, self.name_project,
"__init__.py")
self.write(dst, os.path.join(self._appfld, "__init__.py"),
self.context)
logger.info("[ \u2714 ] Creating app file.")
def _manage(self):
"""Generate manage file."""
templatefile = os.path.join(self.projectfolder, "manage.py")
self.write(templatefile, "manage.py", self.context)
logger.info("[ \u2714 ] Creating manage file.")
def _license(self):
"""Generate License."""
templatefile = os.path.join(self.projectfolder, "LICENSE")
self.write(templatefile, "LICENSE", self.context)
logger.info("[ \u2714 ] Creating LICENSE BSD ;-)")
def _readme(self):
"""Generate Readme."""
templatefile = os.path.join(self.projectfolder, "README.rst")
self.write(templatefile, "README.rst", self.context)
logger.info("[ \u2714 ] Creating README.")
def _fabfile(self):
"""Generate Fabfile."""
templatefile = os.path.join(self.projectfolder, "fabfile.py")
self.write(templatefile, "fabfile.py", self.context)
def _uwsgi(self):
"""Generate Uwsgi."""
templatefile = os.path.join(self.projectfolder, "uwsgi.ini")
self.write(templatefile, "uwsgi.ini", self.context)
def _config_files(self):
"""Nginx Supervisor conf files."""
files = ["project_nginx.conf", "project_supervisor.conf"]
folder = os.path.join(self.projectfolder, "config")
for conffile in files:
templatefile = os.path.join(folder, conffile)
self.write(templatefile, os.path.join("config", conffile),
self.context)
def generate(self):
"""Generate Project."""
logger.debug("Starting generating project...")
start = time.time()
# Config
self._config()
# Extensions
self._extensions()
# App
self._app()
# Manage
self._manage()
# License
self._license()
# Readme
self._readme()
# Fabfile
self._fabfile()
# Uwsgi
self._uwsgi()
# Conf files Nginx Supervidor
self._config_files()
# Std. Modules
self.module.ger_std_modules()
end = time.time() - start
cprint("=" * 55, "green", attrs=["bold"])
logger.info("[ \u0231 ] Finishing: %f sec." % end)
def get_arguments():
"""Get Arguments command line."""
parser = argparse.ArgumentParser(
description=cprint(figlet_format("ZeUs!", font="starwars"),
"green", attrs=["bold"]),
prog="zeus")
parser.add_argument("--project", "-p", help="Creating project.",
type=str, default="")
parser.add_argument("--module", "-m", help="Creating module.",
nargs=2)
parser.add_argument("--template", "-t", help="Creating template.",
nargs=2)
parser.add_argument("--author", "-a",
help="Author of project (default: %(default)s).",
type=str, default="Lab804")
parser.add_argument("--domain", "-do",
help="Domain, (default: %(default)s)",
type=str, default="lab804.com.br")
parser.add_argument("--debug", "-d", help="Debug mode.",
type=bool, default=False),
parser.add_argument("--version", "-v", action="version",
version="%(prog)s 0.1.1")
args = parser.parse_args()
return args | zeus-lab804 | /zeus-lab804-0.1.2.tar.gz/zeus-lab804-0.1.2/zeusproject/commands.py | commands.py |
from flask import current_app, render_template, Blueprint, redirect, \
url_for, flash, current_app, request
from flask.ext.security import login_required
{# Get Model #}
from {{NAMEPROJECT}}.{{MODNAME}}.models import {{MODNAME | capitalize}}
{# Get Form #}
from {{NAMEPROJECT}}.{{MODNAME}}.forms import {{MODNAME}}Form
blueprint = Blueprint('{{MODNAME}}', __name__, url_prefix='/{{MODNAME}}')
@login_required
@blueprint.route('/')
def get_all(page=1):
"""Return all {{MODNAME}}.
:param int page: Number of pagination.
"""
_all = {{MODNAME | capitalize}}.objects.all()
current_app.logger.debug(u'Get all {{MODNAME}}.')
return render_template('{{MODNAME}}/list.jinja', _all=_all)
@login_required
@blueprint.route('/create', methods=["GET", "POST"])
def create():
"""Create instance of {{MODNAME}}."""
form = {{MODNAME}}Form(request.form)
if request.method == 'POST' and form.validate():
instance = {{MODNAME | capitalize}}()
form.populate_obj(instance)
instance.save()
flash("Criado com sucesso.", "success")
current_app.logger.debug(u"Create {{MODNAME}}.")
return redirect(url_for("{{MODNAME}}.get_all"))
return render_template('{{MODNAME}}/create.jinja', form=form)
@login_required
@blueprint.route('/<pk>')
def get(pk):
"""Get {{MODNAME}}.
:param ObjectID pk: pk is ObjectID of instance.
"""
current_app.logger.debug(u'Get {{MODNAME}} - %s' % str(pk))
instance = {{MODNAME | capitalize}}.objects.get_or_404(_id=pk)
return render_template('{{MODNAME}}/get.jinja', instance=instance)
@login_required
@blueprint.route('/<pk>/edit', methods=["GET", "POST"])
def edit(pk):
"""Edit {{MODNAME}}.
:param ObjectID pk: pk is objectid of instance.
"""
current_app.logger.debug(u'Edit {{MODNAME}} - %s' % str(pk))
instance = {{MODNAME | capitalize}}.objects.get_or_404(_id=pk)
form = {{MODNAME}}Form(request.form, obj=instance)
if request.method == 'POST' and form.validate():
form.populate_obj(instance)
instance.save()
flash("Alteração salva.", "info")
return redirect(url_for("{{MODNAME}}.get_all"))
return render_template('{{MODNAME}}/edit.jinja', form=form)
@login_required
@blueprint.route('/<pk>/remove')
def remove(pk):
"""Remove instance of {{MODNAME}}.
:param ObjectID pk: pk is objectid of instance.
"""
instance = {{MODNAME | capitalize}}.objects.get_or_404(_id=pk)
instance.remove()
current_app.logger.debug(u'Removed {{MODNAME}} - %s' % str(pk))
flash("Removido com sucesso.", "danger")
return redirect(url_for("{{MODNAME}}.get_all")) | zeus-lab804 | /zeus-lab804-0.1.2.tar.gz/zeus-lab804-0.1.2/zeusproject/_module/controllers.py | controllers.py |
"""Fabric."""
from getpass import getpass
from fabric.api import cd, env, lcd, put, prompt, local, sudo, task, prefix
from fabric.colors import green, red
from fabric.contrib.files import exists, append
local_app_dir = "./"
local_config_dir = "./config"
remote_app_dir = "/home/www"
remote_flask_dir = remote_app_dir + "/{{NAMEPROJECT}}"
remote_nginx_dir = "/etc/nginx/sites-enabled"
remote_supervisor_dir = "/etc/supervisor/conf.d"
remote_systemd_dir = "/etc/systemd/system/"
env.hosts = ["add_ip_or_domain"]
env.user = "root"
DB_APT = "http://repo.mongodb.org/apt/ubuntu trusty/mongodb-org/3.2 multiverse"
PACKAGES = [
"python3",
"python3-pip",
"python3-virtualenv",
"virtualenv",
"nginx",
"git",
"supervisor"
]
def install_dep():
"""Install dependencies."""
sudo("apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv EA312927")
sudo("echo 'deb " + DB_APT + "' > /etc/apt/sources.list.d/mongodb-org-3.2.list")
sudo("apt-get update")
sudo("apt-get install -y " + " ".join(PACKAGES))
def install_db():
"""Install DB."""
sudo("apt-get install -y --allow-unauthenticated mongodb-org")
with lcd(local_config_dir):
with cd(remote_systemd_dir):
put("./mongodb.service", "./", use_sudo=True)
sudo("systemctl enable mongodb")
sudo("systemctl start mongodb")
print(green("Starting MongoDB."))
def install_requirements():
"""Install requirements."""
if exists(remote_app_dir) is False:
sudo("mkdir " + remote_app_dir)
if exists(remote_flask_dir) is False:
sudo("mkdir " + remote_flask_dir)
with lcd(local_app_dir):
with cd(remote_app_dir):
with cd(remote_flask_dir):
put("*", "./", use_sudo=True)
if exists(remote_app_dir + "/env-{{NAMEPROJECT}}") is False:
sudo("virtualenv env-{{NAMEPROJECT}} -p python3")
sudo(
"source env-{{NAMEPROJECT}}/bin/activate && pip install -r {{NAMEPROJECT}}/requirements.txt")
def create_role():
"""Create Remote Role."""
name_role = prompt("Unique name? ")
with cd(remote_app_dir):
sudo(
"source env-{{NAMEPROJECT}}/bin/activate && python {{NAMEPROJECT}}/manage.py create_role -n {}".format(name_role))
def create_user():
"""Create Remote User."""
email = prompt("Email ")
passw = getpass("Password: ")
active = prompt("Activate (y/n): ")
if len(passw) < 6:
print(red("Password length greather than 6 catacters."))
return
if active != "y" or active != "n":
active = "y"
with cd(remote_app_dir):
sudo("source env-{{NAMEPROJECT}}/bin/activate && python {{NAMEPROJECT}}/manage.py create_user -n {} -p {} -a {}".format(email,
passw,
active
))
print(green("Creted User."))
def configure_nginx():
"""Configure Nginx."""
sudo("systemctl start nginx")
if exists("/etc/nginx/sites-enabled/default"):
sudo("rm /etc/nginx/sites-enabled/default")
if exists("/etc/nginx/sites-enabled/{{NAMEPROJECT}}") is False:
sudo("touch /etc/nginx/sites-available/{{NAMEPROJECT}}")
sudo("ln -s /etc/nginx/sites-available/{{NAMEPROJECT}}" +
" /etc/nginx/sites-enabled/{{NAMEPROJECT}}")
with lcd(local_config_dir):
with cd(remote_nginx_dir):
put("./project_nginx.conf", "./{{NAMEPROJECT}}", use_sudo=True)
sudo("systemctl restart nginx")
def configure_supervisor():
"""Configure Supervisor."""
sudo("systemctl enable supervisor")
sudo("systemctl start supervisor")
if exists("/etc/supervisor/conf.d/{{NAMEPROJECT}}.conf") is False:
with lcd(local_config_dir):
with cd(remote_supervisor_dir):
put("./project_supervisor.conf", "./{{NAMEPROJECT}}.conf",
use_sudo=True)
sudo("supervisorctl reread")
sudo("supervisorctl update")
def run_app():
"""Run the app."""
with cd(remote_flask_dir):
sudo("supervisorctl start {{NAMEPROJECT}}")
def deploy():
"""Deploy."""
with lcd(local_app_dir):
with cd(remote_app_dir):
with cd(remote_flask_dir):
put("*", "./", use_sudo=True)
if exists(remote_app_dir + "/env-{{NAMEPROJECT}}") is False:
sudo("virtualenv env-{{NAMEPROJECT}} -p python3")
sudo(
"source env-{{NAMEPROJECT}}/bin/activate && pip install -r {{NAMEPROJECT}}/requirements.txt")
sudo("supervisorctl restart {{NAMEPROJECT}}")
def status():
"""Statu app."""
sudo("supervisorctl status {{NAMEPROJECT}}")
def create():
"""Create app."""
install_dep()
install_db()
install_requirements()
configure_nginx()
configure_supervisor() | zeus-lab804 | /zeus-lab804-0.1.2.tar.gz/zeus-lab804-0.1.2/zeusproject/templates/fabfile.py | fabfile.py |
import os
import logging
from pymongo.uri_parser import parse_uri
class Config:
"""Config."""
def __init__(self):
"""Init."""
self.DEBUG = False
self.TESTING = False
self.PRODUCTION = False
self.SITE_NAME = "{{NAME}}"
self.SITE_LOGO = "/static/img/logo_zeus.svg"
self.SECRET_KEY = '{{SECRETKEY}}'
self.LOG_LEVEL = logging.DEBUG
self.WTF_CSRF_ENABLED = True
# Mongodb support
self.MONGODB_SETTINGS = self.mongo_from_uri(
'mongodb://localhost:27017/{{NAMEPROJECT}}'
)
self.SYS_ADMINS = ['errors@{{DOMAIN}}'] # E-mails to send errors
self.BOOTSTRAP_SERVE_LOCAL = True
self.GOOGLE_ANALYTICS_ID = None # Analytics U-XXXX-YY
self.CACHE_TYPE = "simple"
self.PER_PAGE = 10 # Pagination per page
# Configured Email
self.DEFAULT_MAIL_SENDER = '{{NAME}} < no-reply@{{DOMAIN}} >'
self.MAIL_SERVER = 'mail.{{DOMAIN}}'
self.MAIL_PORT = 587
self.MAIL_USE_SSL = False
self.MAIL_USE_TLS = True
self.MAIL_USERNAME = 'no-reply@{{DOMAIN}}'
self.MAIL_PASSWORD = ''
# Flask-Security setup
self.SECURITY_EMAIL_SENDER = '{{NAME}} < no-reply@{{DOMAIN}} >'
self.SECURITY_PASSWORD_HASH = 'pbkdf2_sha512'
self.SECURITY_PASSWORD_SALT = '{{SALT}}'
self.SECURITY_LOGIN_WITHOUT_CONFIRMATION = True
self.SECURITY_CONFIRMABLE = False
self.SECURITY_REGISTERABLE = True
self.SECURITY_RECOVERABLE = True
self.SECURITY_TRACKABLE = True
self.SECURITY_CHANGEABLE = True
self.SECURITY_SEND_REGISTER_EMAIL = False
# flask security routes
self.SECURITY_URL_PREFIX = '/auth'
self.SECURITY_POST_LOGIN_VIEW = '/'
self.SECURITY_POST_LOGOUT_VIEW = '/auth/login'
self.SECURITY_POST_REGISTER_VIEW = '/'
self.SECURITY_POST_CONFIRM_VIEW = '/auth/login'
# Security Email Subjects
self.SECURITY_EMAIL_SUBJECT_REGISTER = '{{NAME}} - Bem Vindo'
self.SECURITY_EMAIL_SUBJECT_CONFIRM = '{{NAME}} - Por favor confirme seu email'
self.SECURITY_EMAIL_SUBJECT_PASSWORDLESS = u'{{NAME}} - Instruções para acesso'
self.SECURITY_EMAIL_SUBJECT_PASSWORD_NOTICE = '{{NAME}} - Sua senha foi redefinida'
self.SECURITY_EMAIL_SUBJECT_PASSWORD_CHANGE_NOTICE = '{{NAME}} - Sua senha foi alterada'
self.SECURITY_EMAIL_SUBJECT_PASSWORD_RESET = u'{{NAME}} - Instruções de redefinição de senha'
# Security Mensagens
self.SECURITY_MSG_INVALID_PASSWORD = (u'Senha inválida.', 'error')
self.SECURITY_MSG_UNAUTHORIZED = (
u'Você não tem permissão para acessar esta área.', 'error')
self.SECURITY_MSG_CONFIRM_REGISTRATION = (
u'Obrigado. Instruções de confirmação foram enviado para %(email)s.',
'success')
self.SECURITY_MSG_EMAIL_CONFIRMED = (
u'Obrigado. Seu email foi confirmado.', 'success')
self.SECURITY_MSG_ALREADY_CONFIRMED = (
u'Seu email já foi confirmado.', 'info')
self.SECURITY_MSG_INVALID_CONFIRMATION_TOKEN = (
u'Token de confirmação inválido.', 'error')
self.SECURITY_MSG_EMAIL_ALREADY_ASSOCIATED = (
u'%(email)s já está associado a uma conta.', 'error')
self.SECURITY_MSG_PASSWORD_MISMATCH = (
u'Senha não corresponde.', 'error')
self.SECURITY_MSG_RETYPE_PASSWORD_MISMATCH = (
u'Senha não corresponde.', 'error')
self.SECURITY_MSG_INVALID_REDIRECT = (
u'Redirecionamento Redirections outside the domain are forbidden',
'error')
self.SECURITY_MSG_PASSWORD_RESET_REQUEST = (
u'Instruções para resetar sua senha foram enviadas para %(email)s.',
'info')
self.SECURITY_MSG_PASSWORD_RESET_EXPIRED = (
u'Você não resetou sua senha dentro %(within)s. Novas instuções foram enviadas para %(email)s.',
'error')
self.SECURITY_MSG_INVALID_RESET_PASSWORD_TOKEN = (
u'Token inválido para resetar a senha.', 'error')
self.SECURITY_MSG_CONFIRMATION_REQUIRED = (
u'Email requer confirmação.', 'error')
self.SECURITY_MSG_CONFIRMATION_REQUEST = (
u'Confirmation instructions have been sent to %(email)s.', 'info')
self.SECURITY_MSG_CONFIRMATION_EXPIRED = (
u'Você não confirmou o e-mail dentro %(within)s. Novas instuções foram enviadas para %(email)s.',
'error')
self.SECURITY_MSG_LOGIN_EXPIRED = (
u'Você não pode acessar %(within)s. Novas instruções foram enviadas para %(email)s.',
'error')
self.SECURITY_MSG_LOGIN_EMAIL_SENT = (
u'Instruções para efetuar o login foram enviadas para %(email)s.',
'success')
self.SECURITY_MSG_INVALID_LOGIN_TOKEN = (
u'Token de login inválido.', 'error')
self.SECURITY_MSG_DISABLED_ACCOUNT = (u'Conta desabilitada.', 'error')
self.SECURITY_MSG_EMAIL_NOT_PROVIDED = (u'Email não fornecido', 'error')
self.SECURITY_MSG_INVALID_EMAIL_ADDRESS = (
u'Endereço de email inválido.', 'error')
self.SECURITY_MSG_PASSWORD_NOT_PROVIDED = (
u'Senha não fornecida.', 'error')
self.SECURITY_MSG_PASSWORD_NOT_SET = (
u'Nenhuma senha fornecida para esse usuário.', 'error')
self.SECURITY_MSG_PASSWORD_INVALID_LENGTH = (
u'A senha deve possuir no minímo 6 caracteres.', 'error')
self.SECURITY_MSG_USER_DOES_NOT_EXIST = (
u'Email especificado não existe.', 'error')
self.SECURITY_MSG_INVALID_PASSWORD = (u'Senha inválida.', 'error')
self.SECURITY_MSG_PASSWORDLESS_LOGIN_SUCCESSFUL = (
u'Você logou com sucesso.', 'success')
self.SECURITY_MSG_PASSWORD_RESET = (
u'Você resetou sua senha com sucesso e já logou automaticamente.',
'success')
self.SECURITY_MSG_PASSWORD_IS_THE_SAME = (
u'Sua senha deve ser diferente da senha antiga.', 'error')
self.SECURITY_MSG_PASSWORD_CHANGE = (
u'Você alterou a senha com sucesso.', 'success')
self.SECURITY_MSG_LOGIN = (
u'Por favor logue-se para ter acesso a essa página.', 'info')
self.SECURITY_MSG_REFRESH = (
u'Por favor reautentique para acessar essa página.', 'info')
@staticmethod
def mongo_from_uri(uri):
config = parse_uri(uri)
conn_settings = {
'db': config['database'],
'username': config['username'],
'password': config['password'],
'host': config['nodelist'][0][0],
'port': config['nodelist'][0][1]
}
return conn_settings
class Dev(Config):
"""Development Config."""
def __init__(self):
super(Dev, self).__init__()
self.DEBUG = True
self.TESTING = False
self.ENVIROMENT = "Development"
class Prod(Config):
"""Production Config."""
def __init__(self):
super(Prod, self).__init__()
self.DEBUG = False
self.TESTING = False
self.ENVIROMENT = "Production"
self.SECURITY_LOGIN_WITHOUT_CONFIRMATION = False
self.SECURITY_CONFIRMABLE = True
self.LOG_LEVEL = logging.INFO
self.CACHE_TYPE = "simple" # MEMCACHE
self.BOOTSTRAP_SERVE_LOCAL = False
enviroment = os.getenv('ENVIROMENT', 'DEV').lower()
if enviroment == 'prod':
app_config = Prod()
else:
app_config = Dev() | zeus-lab804 | /zeus-lab804-0.1.2.tar.gz/zeus-lab804-0.1.2/zeusproject/templates/app/config.py | config.py |
import os
import sys
import logging
from flask import Flask
from flask_security import Security, MongoEngineUserDatastore
from {{NAMEPROJECT}} import extensions
from {{NAMEPROJECT}}.users.models import User, Role
from {{NAMEPROJECT}}.users.forms import CustomLoginForm, ExtendedRegisterForm
from {{NAMEPROJECT}} import {% if MODULES -%} {% for module in MODULES -%}{% if loop.last -%}{{module}}{%else-%}{{module}}, {%endif-%} {% endfor %}{% endif %}
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
APP_DIR = os.path.dirname(os.path.abspath(__file__))
def create_app():
"""Flask app factory."""
app = Flask(__name__,
template_folder=os.path.join(APP_DIR, "..", 'templates'),
static_folder=os.path.join(APP_DIR, "..", 'static'))
# Config App
app.config.from_object("{{NAMEPROJECT}}.config.app_config")
app.logger.info("Config enviroment: %s" % app.config["ENVIROMENT"])
# Format logging
logging.basicConfig(
level=app.config['LOG_LEVEL'],
format='%(asctime)s %(levelname)s: %(message)s '
'[in %(pathname)s:%(lineno)d]',
datefmt='%d%m%Y-%H:%M%p',
)
email_errors(app)
register_extensions(app)
register_blueprints(app)
return app
def email_errors(app):
""" Sendo erros of email."""
if not app.debug and not app.testing:
import logging.handlers
mail_handler = logging.handlers.SMTPHandler(
'localhost',
os.getenv('USER'),
app.config['SYS_ADMINS'],
'{0} error'.format(app.config['SITE_NAME']),
)
mail_handler.setFormatter(logging.Formatter('''
Message type: %(levelname)s
Location: %(pathname)s:%(lineno)d
Module: %(module)s
Function: %(funcName)s
Time: %(asctime)s
Message:
%(message)s
'''.strip()))
mail_handler.setLevel(logging.ERROR)
app.logger.addHandler(mail_handler)
app.logger.info("Emailing on error is ENABLED")
else:
app.logger.info("Emailing on error is DISABLED")
def register_extensions(app):
"""Call the method 'init_app' to register the extensions in the flask.Flask
object passed as parameter.
:app: flask.Flask object
:returns: None
"""
# DB
app.db = extensions.db
app.db.init_app(app)
# Email
extensions.mail.init_app(app)
# Securirty
app.user_datastore = MongoEngineUserDatastore(app.db, User, Role)
app.security = Security(app, app.user_datastore,
register_form=ExtendedRegisterForm,
login_form=CustomLoginForm)
# Assets
extensions.assets.init_app(app)
assets_out = os.path.join(APP_DIR, "..", "static", "gen")
if not os.path.exists(assets_out):
app.logger.info("Create static folder of minify files.")
os.mkdir(assets_out)
# Fist time, create basic roles.
if Role.objects.count() == 0:
Role.objects.create(name="admin", description="admin roles")
Role.objects.create(name="user", description="user roles")
# Cache
extensions.cache.init_app(app)
# BootStrap
extensions.bootstrap.init_app(app)
def register_blueprints(app):
"""Register all blueprints.
:app: flask.Flask object
:returns: None
"""
{% if MODULES -%}
{% for module in MODULES -%}
app.register_blueprint({{module}}.controllers.blueprint)
{% endfor -%}
{% endif -%} | zeus-lab804 | /zeus-lab804-0.1.2.tar.gz/zeus-lab804-0.1.2/zeusproject/templates/app/__init__.py | __init__.py |
from flask import current_app
from flask_security import UserMixin, RoleMixin
from mongoengine import *
from mongoengine import signals
from mongoengine import fields
from {{NAMEPROJECT}}.extensions import db
class Role(db.Document, RoleMixin):
"""Roles."""
name = db.StringField(max_length=80, unique=True)
description = db.StringField(max_length=255)
class Address(db.EmbeddedDocument):
""" endereco usuario """
tipo = db.StringField()
endereco = db.StringField()
cidade = db.StringField()
estado = db.StringField()
bairro = db.StringField()
complemento = db.StringField()
cep = db.StringField()
numero = db.StringField()
class User(db.Document, UserMixin):
"""User."""
email = db.StringField(max_length=255)
fullname = db.StringField()
username = db.StringField(max_length=255)
password = db.StringField(max_length=255)
active = db.BooleanField(default=False)
confirmed_at = db.DateTimeField()
roles = db.ListField(db.ReferenceField(Role), default=[])
current_login_at = db.DateTimeField()
current_login_ip = db.StringField()
last_login_at = db.DateTimeField()
last_login_ip = db.StringField()
login_count = db.IntField()
avatar = db.StringField()
endereco = db.EmbeddedDocumentField(Address)
@property
def id(self):
"""Return id."""
return self.pk
@classmethod
def by_email(cls, email):
"""Find user by email."""
return cls.objects(email=email).first()
@property
def gravatar(self):
"""Get gravatar."""
email = self.email.strip()
if isinstance(email, unicode):
email = email.encode("utf-8")
import hashlib
encoded = hashlib.md5(email).hexdigest()
return "https://secure.gravatar.com/avatar/%s.png" % encoded
@classmethod
def pre_save(cls, sender, document, **kwargs):
"""Save user and put role user."""
if len(document.roles) == 0:
role = Role.objects.get(name='user')
document.roles = [role]
def __unicode__(self):
"""return object with email."""
return "{}".format(self.email)
signals.pre_save.connect(User.pre_save, sender=User) | zeus-lab804 | /zeus-lab804-0.1.2.tar.gz/zeus-lab804-0.1.2/zeusproject/templates/app/users/models.py | models.py |
if (typeof jQuery === 'undefined') {
throw new Error('Bootstrap\'s JavaScript requires jQuery')
}
+function ($) {
'use strict';
var version = $.fn.jquery.split(' ')[0].split('.')
if ((version[0] < 2 && version[1] < 9) || (version[0] == 1 && version[1] == 9 && version[2] < 1) || (version[0] > 2)) {
throw new Error('Bootstrap\'s JavaScript requires jQuery version 1.9.1 or higher, but lower than version 3')
}
}(jQuery);
/* ========================================================================
* Bootstrap: transition.js v3.3.6
* http://getbootstrap.com/javascript/#transitions
* ========================================================================
* Copyright 2011-2015 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// CSS TRANSITION SUPPORT (Shoutout: http://www.modernizr.com/)
// ============================================================
function transitionEnd() {
var el = document.createElement('bootstrap')
var transEndEventNames = {
WebkitTransition : 'webkitTransitionEnd',
MozTransition : 'transitionend',
OTransition : 'oTransitionEnd otransitionend',
transition : 'transitionend'
}
for (var name in transEndEventNames) {
if (el.style[name] !== undefined) {
return { end: transEndEventNames[name] }
}
}
return false // explicit for ie8 ( ._.)
}
// http://blog.alexmaccaw.com/css-transitions
$.fn.emulateTransitionEnd = function (duration) {
var called = false
var $el = this
$(this).one('bsTransitionEnd', function () { called = true })
var callback = function () { if (!called) $($el).trigger($.support.transition.end) }
setTimeout(callback, duration)
return this
}
$(function () {
$.support.transition = transitionEnd()
if (!$.support.transition) return
$.event.special.bsTransitionEnd = {
bindType: $.support.transition.end,
delegateType: $.support.transition.end,
handle: function (e) {
if ($(e.target).is(this)) return e.handleObj.handler.apply(this, arguments)
}
}
})
}(jQuery);
/* ========================================================================
* Bootstrap: alert.js v3.3.6
* http://getbootstrap.com/javascript/#alerts
* ========================================================================
* Copyright 2011-2015 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// ALERT CLASS DEFINITION
// ======================
var dismiss = '[data-dismiss="alert"]'
var Alert = function (el) {
$(el).on('click', dismiss, this.close)
}
Alert.VERSION = '3.3.6'
Alert.TRANSITION_DURATION = 150
Alert.prototype.close = function (e) {
var $this = $(this)
var selector = $this.attr('data-target')
if (!selector) {
selector = $this.attr('href')
selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7
}
var $parent = $(selector)
if (e) e.preventDefault()
if (!$parent.length) {
$parent = $this.closest('.alert')
}
$parent.trigger(e = $.Event('close.bs.alert'))
if (e.isDefaultPrevented()) return
$parent.removeClass('in')
function removeElement() {
// detach from parent, fire event then clean up data
$parent.detach().trigger('closed.bs.alert').remove()
}
$.support.transition && $parent.hasClass('fade') ?
$parent
.one('bsTransitionEnd', removeElement)
.emulateTransitionEnd(Alert.TRANSITION_DURATION) :
removeElement()
}
// ALERT PLUGIN DEFINITION
// =======================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.alert')
if (!data) $this.data('bs.alert', (data = new Alert(this)))
if (typeof option == 'string') data[option].call($this)
})
}
var old = $.fn.alert
$.fn.alert = Plugin
$.fn.alert.Constructor = Alert
// ALERT NO CONFLICT
// =================
$.fn.alert.noConflict = function () {
$.fn.alert = old
return this
}
// ALERT DATA-API
// ==============
$(document).on('click.bs.alert.data-api', dismiss, Alert.prototype.close)
}(jQuery);
/* ========================================================================
* Bootstrap: button.js v3.3.6
* http://getbootstrap.com/javascript/#buttons
* ========================================================================
* Copyright 2011-2015 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// BUTTON PUBLIC CLASS DEFINITION
// ==============================
var Button = function (element, options) {
this.$element = $(element)
this.options = $.extend({}, Button.DEFAULTS, options)
this.isLoading = false
}
Button.VERSION = '3.3.6'
Button.DEFAULTS = {
loadingText: 'loading...'
}
Button.prototype.setState = function (state) {
var d = 'disabled'
var $el = this.$element
var val = $el.is('input') ? 'val' : 'html'
var data = $el.data()
state += 'Text'
if (data.resetText == null) $el.data('resetText', $el[val]())
// push to event loop to allow forms to submit
setTimeout($.proxy(function () {
$el[val](data[state] == null ? this.options[state] : data[state])
if (state == 'loadingText') {
this.isLoading = true
$el.addClass(d).attr(d, d)
} else if (this.isLoading) {
this.isLoading = false
$el.removeClass(d).removeAttr(d)
}
}, this), 0)
}
Button.prototype.toggle = function () {
var changed = true
var $parent = this.$element.closest('[data-toggle="buttons"]')
if ($parent.length) {
var $input = this.$element.find('input')
if ($input.prop('type') == 'radio') {
if ($input.prop('checked')) changed = false
$parent.find('.active').removeClass('active')
this.$element.addClass('active')
} else if ($input.prop('type') == 'checkbox') {
if (($input.prop('checked')) !== this.$element.hasClass('active')) changed = false
this.$element.toggleClass('active')
}
$input.prop('checked', this.$element.hasClass('active'))
if (changed) $input.trigger('change')
} else {
this.$element.attr('aria-pressed', !this.$element.hasClass('active'))
this.$element.toggleClass('active')
}
}
// BUTTON PLUGIN DEFINITION
// ========================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.button')
var options = typeof option == 'object' && option
if (!data) $this.data('bs.button', (data = new Button(this, options)))
if (option == 'toggle') data.toggle()
else if (option) data.setState(option)
})
}
var old = $.fn.button
$.fn.button = Plugin
$.fn.button.Constructor = Button
// BUTTON NO CONFLICT
// ==================
$.fn.button.noConflict = function () {
$.fn.button = old
return this
}
// BUTTON DATA-API
// ===============
$(document)
.on('click.bs.button.data-api', '[data-toggle^="button"]', function (e) {
var $btn = $(e.target)
if (!$btn.hasClass('btn')) $btn = $btn.closest('.btn')
Plugin.call($btn, 'toggle')
if (!($(e.target).is('input[type="radio"]') || $(e.target).is('input[type="checkbox"]'))) e.preventDefault()
})
.on('focus.bs.button.data-api blur.bs.button.data-api', '[data-toggle^="button"]', function (e) {
$(e.target).closest('.btn').toggleClass('focus', /^focus(in)?$/.test(e.type))
})
}(jQuery);
/* ========================================================================
* Bootstrap: carousel.js v3.3.6
* http://getbootstrap.com/javascript/#carousel
* ========================================================================
* Copyright 2011-2015 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// CAROUSEL CLASS DEFINITION
// =========================
var Carousel = function (element, options) {
this.$element = $(element)
this.$indicators = this.$element.find('.carousel-indicators')
this.options = options
this.paused = null
this.sliding = null
this.interval = null
this.$active = null
this.$items = null
this.options.keyboard && this.$element.on('keydown.bs.carousel', $.proxy(this.keydown, this))
this.options.pause == 'hover' && !('ontouchstart' in document.documentElement) && this.$element
.on('mouseenter.bs.carousel', $.proxy(this.pause, this))
.on('mouseleave.bs.carousel', $.proxy(this.cycle, this))
}
Carousel.VERSION = '3.3.6'
Carousel.TRANSITION_DURATION = 600
Carousel.DEFAULTS = {
interval: 5000,
pause: 'hover',
wrap: true,
keyboard: true
}
Carousel.prototype.keydown = function (e) {
if (/input|textarea/i.test(e.target.tagName)) return
switch (e.which) {
case 37: this.prev(); break
case 39: this.next(); break
default: return
}
e.preventDefault()
}
Carousel.prototype.cycle = function (e) {
e || (this.paused = false)
this.interval && clearInterval(this.interval)
this.options.interval
&& !this.paused
&& (this.interval = setInterval($.proxy(this.next, this), this.options.interval))
return this
}
Carousel.prototype.getItemIndex = function (item) {
this.$items = item.parent().children('.item')
return this.$items.index(item || this.$active)
}
Carousel.prototype.getItemForDirection = function (direction, active) {
var activeIndex = this.getItemIndex(active)
var willWrap = (direction == 'prev' && activeIndex === 0)
|| (direction == 'next' && activeIndex == (this.$items.length - 1))
if (willWrap && !this.options.wrap) return active
var delta = direction == 'prev' ? -1 : 1
var itemIndex = (activeIndex + delta) % this.$items.length
return this.$items.eq(itemIndex)
}
Carousel.prototype.to = function (pos) {
var that = this
var activeIndex = this.getItemIndex(this.$active = this.$element.find('.item.active'))
if (pos > (this.$items.length - 1) || pos < 0) return
if (this.sliding) return this.$element.one('slid.bs.carousel', function () { that.to(pos) }) // yes, "slid"
if (activeIndex == pos) return this.pause().cycle()
return this.slide(pos > activeIndex ? 'next' : 'prev', this.$items.eq(pos))
}
Carousel.prototype.pause = function (e) {
e || (this.paused = true)
if (this.$element.find('.next, .prev').length && $.support.transition) {
this.$element.trigger($.support.transition.end)
this.cycle(true)
}
this.interval = clearInterval(this.interval)
return this
}
Carousel.prototype.next = function () {
if (this.sliding) return
return this.slide('next')
}
Carousel.prototype.prev = function () {
if (this.sliding) return
return this.slide('prev')
}
Carousel.prototype.slide = function (type, next) {
var $active = this.$element.find('.item.active')
var $next = next || this.getItemForDirection(type, $active)
var isCycling = this.interval
var direction = type == 'next' ? 'left' : 'right'
var that = this
if ($next.hasClass('active')) return (this.sliding = false)
var relatedTarget = $next[0]
var slideEvent = $.Event('slide.bs.carousel', {
relatedTarget: relatedTarget,
direction: direction
})
this.$element.trigger(slideEvent)
if (slideEvent.isDefaultPrevented()) return
this.sliding = true
isCycling && this.pause()
if (this.$indicators.length) {
this.$indicators.find('.active').removeClass('active')
var $nextIndicator = $(this.$indicators.children()[this.getItemIndex($next)])
$nextIndicator && $nextIndicator.addClass('active')
}
var slidEvent = $.Event('slid.bs.carousel', { relatedTarget: relatedTarget, direction: direction }) // yes, "slid"
if ($.support.transition && this.$element.hasClass('slide')) {
$next.addClass(type)
$next[0].offsetWidth // force reflow
$active.addClass(direction)
$next.addClass(direction)
$active
.one('bsTransitionEnd', function () {
$next.removeClass([type, direction].join(' ')).addClass('active')
$active.removeClass(['active', direction].join(' '))
that.sliding = false
setTimeout(function () {
that.$element.trigger(slidEvent)
}, 0)
})
.emulateTransitionEnd(Carousel.TRANSITION_DURATION)
} else {
$active.removeClass('active')
$next.addClass('active')
this.sliding = false
this.$element.trigger(slidEvent)
}
isCycling && this.cycle()
return this
}
// CAROUSEL PLUGIN DEFINITION
// ==========================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.carousel')
var options = $.extend({}, Carousel.DEFAULTS, $this.data(), typeof option == 'object' && option)
var action = typeof option == 'string' ? option : options.slide
if (!data) $this.data('bs.carousel', (data = new Carousel(this, options)))
if (typeof option == 'number') data.to(option)
else if (action) data[action]()
else if (options.interval) data.pause().cycle()
})
}
var old = $.fn.carousel
$.fn.carousel = Plugin
$.fn.carousel.Constructor = Carousel
// CAROUSEL NO CONFLICT
// ====================
$.fn.carousel.noConflict = function () {
$.fn.carousel = old
return this
}
// CAROUSEL DATA-API
// =================
var clickHandler = function (e) {
var href
var $this = $(this)
var $target = $($this.attr('data-target') || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')) // strip for ie7
if (!$target.hasClass('carousel')) return
var options = $.extend({}, $target.data(), $this.data())
var slideIndex = $this.attr('data-slide-to')
if (slideIndex) options.interval = false
Plugin.call($target, options)
if (slideIndex) {
$target.data('bs.carousel').to(slideIndex)
}
e.preventDefault()
}
$(document)
.on('click.bs.carousel.data-api', '[data-slide]', clickHandler)
.on('click.bs.carousel.data-api', '[data-slide-to]', clickHandler)
$(window).on('load', function () {
$('[data-ride="carousel"]').each(function () {
var $carousel = $(this)
Plugin.call($carousel, $carousel.data())
})
})
}(jQuery);
/* ========================================================================
* Bootstrap: collapse.js v3.3.6
* http://getbootstrap.com/javascript/#collapse
* ========================================================================
* Copyright 2011-2015 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// COLLAPSE PUBLIC CLASS DEFINITION
// ================================
var Collapse = function (element, options) {
this.$element = $(element)
this.options = $.extend({}, Collapse.DEFAULTS, options)
this.$trigger = $('[data-toggle="collapse"][href="#' + element.id + '"],' +
'[data-toggle="collapse"][data-target="#' + element.id + '"]')
this.transitioning = null
if (this.options.parent) {
this.$parent = this.getParent()
} else {
this.addAriaAndCollapsedClass(this.$element, this.$trigger)
}
if (this.options.toggle) this.toggle()
}
Collapse.VERSION = '3.3.6'
Collapse.TRANSITION_DURATION = 350
Collapse.DEFAULTS = {
toggle: true
}
Collapse.prototype.dimension = function () {
var hasWidth = this.$element.hasClass('width')
return hasWidth ? 'width' : 'height'
}
Collapse.prototype.show = function () {
if (this.transitioning || this.$element.hasClass('in')) return
var activesData
var actives = this.$parent && this.$parent.children('.panel').children('.in, .collapsing')
if (actives && actives.length) {
activesData = actives.data('bs.collapse')
if (activesData && activesData.transitioning) return
}
var startEvent = $.Event('show.bs.collapse')
this.$element.trigger(startEvent)
if (startEvent.isDefaultPrevented()) return
if (actives && actives.length) {
Plugin.call(actives, 'hide')
activesData || actives.data('bs.collapse', null)
}
var dimension = this.dimension()
this.$element
.removeClass('collapse')
.addClass('collapsing')[dimension](0)
.attr('aria-expanded', true)
this.$trigger
.removeClass('collapsed')
.attr('aria-expanded', true)
this.transitioning = 1
var complete = function () {
this.$element
.removeClass('collapsing')
.addClass('collapse in')[dimension]('')
this.transitioning = 0
this.$element
.trigger('shown.bs.collapse')
}
if (!$.support.transition) return complete.call(this)
var scrollSize = $.camelCase(['scroll', dimension].join('-'))
this.$element
.one('bsTransitionEnd', $.proxy(complete, this))
.emulateTransitionEnd(Collapse.TRANSITION_DURATION)[dimension](this.$element[0][scrollSize])
}
Collapse.prototype.hide = function () {
if (this.transitioning || !this.$element.hasClass('in')) return
var startEvent = $.Event('hide.bs.collapse')
this.$element.trigger(startEvent)
if (startEvent.isDefaultPrevented()) return
var dimension = this.dimension()
this.$element[dimension](this.$element[dimension]())[0].offsetHeight
this.$element
.addClass('collapsing')
.removeClass('collapse in')
.attr('aria-expanded', false)
this.$trigger
.addClass('collapsed')
.attr('aria-expanded', false)
this.transitioning = 1
var complete = function () {
this.transitioning = 0
this.$element
.removeClass('collapsing')
.addClass('collapse')
.trigger('hidden.bs.collapse')
}
if (!$.support.transition) return complete.call(this)
this.$element
[dimension](0)
.one('bsTransitionEnd', $.proxy(complete, this))
.emulateTransitionEnd(Collapse.TRANSITION_DURATION)
}
Collapse.prototype.toggle = function () {
this[this.$element.hasClass('in') ? 'hide' : 'show']()
}
Collapse.prototype.getParent = function () {
return $(this.options.parent)
.find('[data-toggle="collapse"][data-parent="' + this.options.parent + '"]')
.each($.proxy(function (i, element) {
var $element = $(element)
this.addAriaAndCollapsedClass(getTargetFromTrigger($element), $element)
}, this))
.end()
}
Collapse.prototype.addAriaAndCollapsedClass = function ($element, $trigger) {
var isOpen = $element.hasClass('in')
$element.attr('aria-expanded', isOpen)
$trigger
.toggleClass('collapsed', !isOpen)
.attr('aria-expanded', isOpen)
}
function getTargetFromTrigger($trigger) {
var href
var target = $trigger.attr('data-target')
|| (href = $trigger.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '') // strip for ie7
return $(target)
}
// COLLAPSE PLUGIN DEFINITION
// ==========================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.collapse')
var options = $.extend({}, Collapse.DEFAULTS, $this.data(), typeof option == 'object' && option)
if (!data && options.toggle && /show|hide/.test(option)) options.toggle = false
if (!data) $this.data('bs.collapse', (data = new Collapse(this, options)))
if (typeof option == 'string') data[option]()
})
}
var old = $.fn.collapse
$.fn.collapse = Plugin
$.fn.collapse.Constructor = Collapse
// COLLAPSE NO CONFLICT
// ====================
$.fn.collapse.noConflict = function () {
$.fn.collapse = old
return this
}
// COLLAPSE DATA-API
// =================
$(document).on('click.bs.collapse.data-api', '[data-toggle="collapse"]', function (e) {
var $this = $(this)
if (!$this.attr('data-target')) e.preventDefault()
var $target = getTargetFromTrigger($this)
var data = $target.data('bs.collapse')
var option = data ? 'toggle' : $this.data()
Plugin.call($target, option)
})
}(jQuery);
/* ========================================================================
* Bootstrap: dropdown.js v3.3.6
* http://getbootstrap.com/javascript/#dropdowns
* ========================================================================
* Copyright 2011-2015 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// DROPDOWN CLASS DEFINITION
// =========================
var backdrop = '.dropdown-backdrop'
var toggle = '[data-toggle="dropdown"]'
var Dropdown = function (element) {
$(element).on('click.bs.dropdown', this.toggle)
}
Dropdown.VERSION = '3.3.6'
function getParent($this) {
var selector = $this.attr('data-target')
if (!selector) {
selector = $this.attr('href')
selector = selector && /#[A-Za-z]/.test(selector) && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7
}
var $parent = selector && $(selector)
return $parent && $parent.length ? $parent : $this.parent()
}
function clearMenus(e) {
if (e && e.which === 3) return
$(backdrop).remove()
$(toggle).each(function () {
var $this = $(this)
var $parent = getParent($this)
var relatedTarget = { relatedTarget: this }
if (!$parent.hasClass('open')) return
if (e && e.type == 'click' && /input|textarea/i.test(e.target.tagName) && $.contains($parent[0], e.target)) return
$parent.trigger(e = $.Event('hide.bs.dropdown', relatedTarget))
if (e.isDefaultPrevented()) return
$this.attr('aria-expanded', 'false')
$parent.removeClass('open').trigger($.Event('hidden.bs.dropdown', relatedTarget))
})
}
Dropdown.prototype.toggle = function (e) {
var $this = $(this)
if ($this.is('.disabled, :disabled')) return
var $parent = getParent($this)
var isActive = $parent.hasClass('open')
clearMenus()
if (!isActive) {
if ('ontouchstart' in document.documentElement && !$parent.closest('.navbar-nav').length) {
// if mobile we use a backdrop because click events don't delegate
$(document.createElement('div'))
.addClass('dropdown-backdrop')
.insertAfter($(this))
.on('click', clearMenus)
}
var relatedTarget = { relatedTarget: this }
$parent.trigger(e = $.Event('show.bs.dropdown', relatedTarget))
if (e.isDefaultPrevented()) return
$this
.trigger('focus')
.attr('aria-expanded', 'true')
$parent
.toggleClass('open')
.trigger($.Event('shown.bs.dropdown', relatedTarget))
}
return false
}
Dropdown.prototype.keydown = function (e) {
if (!/(38|40|27|32)/.test(e.which) || /input|textarea/i.test(e.target.tagName)) return
var $this = $(this)
e.preventDefault()
e.stopPropagation()
if ($this.is('.disabled, :disabled')) return
var $parent = getParent($this)
var isActive = $parent.hasClass('open')
if (!isActive && e.which != 27 || isActive && e.which == 27) {
if (e.which == 27) $parent.find(toggle).trigger('focus')
return $this.trigger('click')
}
var desc = ' li:not(.disabled):visible a'
var $items = $parent.find('.dropdown-menu' + desc)
if (!$items.length) return
var index = $items.index(e.target)
if (e.which == 38 && index > 0) index-- // up
if (e.which == 40 && index < $items.length - 1) index++ // down
if (!~index) index = 0
$items.eq(index).trigger('focus')
}
// DROPDOWN PLUGIN DEFINITION
// ==========================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.dropdown')
if (!data) $this.data('bs.dropdown', (data = new Dropdown(this)))
if (typeof option == 'string') data[option].call($this)
})
}
var old = $.fn.dropdown
$.fn.dropdown = Plugin
$.fn.dropdown.Constructor = Dropdown
// DROPDOWN NO CONFLICT
// ====================
$.fn.dropdown.noConflict = function () {
$.fn.dropdown = old
return this
}
// APPLY TO STANDARD DROPDOWN ELEMENTS
// ===================================
$(document)
.on('click.bs.dropdown.data-api', clearMenus)
.on('click.bs.dropdown.data-api', '.dropdown form', function (e) { e.stopPropagation() })
.on('click.bs.dropdown.data-api', toggle, Dropdown.prototype.toggle)
.on('keydown.bs.dropdown.data-api', toggle, Dropdown.prototype.keydown)
.on('keydown.bs.dropdown.data-api', '.dropdown-menu', Dropdown.prototype.keydown)
}(jQuery);
/* ========================================================================
* Bootstrap: modal.js v3.3.6
* http://getbootstrap.com/javascript/#modals
* ========================================================================
* Copyright 2011-2015 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// MODAL CLASS DEFINITION
// ======================
var Modal = function (element, options) {
this.options = options
this.$body = $(document.body)
this.$element = $(element)
this.$dialog = this.$element.find('.modal-dialog')
this.$backdrop = null
this.isShown = null
this.originalBodyPad = null
this.scrollbarWidth = 0
this.ignoreBackdropClick = false
if (this.options.remote) {
this.$element
.find('.modal-content')
.load(this.options.remote, $.proxy(function () {
this.$element.trigger('loaded.bs.modal')
}, this))
}
}
Modal.VERSION = '3.3.6'
Modal.TRANSITION_DURATION = 300
Modal.BACKDROP_TRANSITION_DURATION = 150
Modal.DEFAULTS = {
backdrop: true,
keyboard: true,
show: true
}
Modal.prototype.toggle = function (_relatedTarget) {
return this.isShown ? this.hide() : this.show(_relatedTarget)
}
Modal.prototype.show = function (_relatedTarget) {
var that = this
var e = $.Event('show.bs.modal', { relatedTarget: _relatedTarget })
this.$element.trigger(e)
if (this.isShown || e.isDefaultPrevented()) return
this.isShown = true
this.checkScrollbar()
this.setScrollbar()
this.$body.addClass('modal-open')
this.escape()
this.resize()
this.$element.on('click.dismiss.bs.modal', '[data-dismiss="modal"]', $.proxy(this.hide, this))
this.$dialog.on('mousedown.dismiss.bs.modal', function () {
that.$element.one('mouseup.dismiss.bs.modal', function (e) {
if ($(e.target).is(that.$element)) that.ignoreBackdropClick = true
})
})
this.backdrop(function () {
var transition = $.support.transition && that.$element.hasClass('fade')
if (!that.$element.parent().length) {
that.$element.appendTo(that.$body) // don't move modals dom position
}
that.$element
.show()
.scrollTop(0)
that.adjustDialog()
if (transition) {
that.$element[0].offsetWidth // force reflow
}
that.$element.addClass('in')
that.enforceFocus()
var e = $.Event('shown.bs.modal', { relatedTarget: _relatedTarget })
transition ?
that.$dialog // wait for modal to slide in
.one('bsTransitionEnd', function () {
that.$element.trigger('focus').trigger(e)
})
.emulateTransitionEnd(Modal.TRANSITION_DURATION) :
that.$element.trigger('focus').trigger(e)
})
}
Modal.prototype.hide = function (e) {
if (e) e.preventDefault()
e = $.Event('hide.bs.modal')
this.$element.trigger(e)
if (!this.isShown || e.isDefaultPrevented()) return
this.isShown = false
this.escape()
this.resize()
$(document).off('focusin.bs.modal')
this.$element
.removeClass('in')
.off('click.dismiss.bs.modal')
.off('mouseup.dismiss.bs.modal')
this.$dialog.off('mousedown.dismiss.bs.modal')
$.support.transition && this.$element.hasClass('fade') ?
this.$element
.one('bsTransitionEnd', $.proxy(this.hideModal, this))
.emulateTransitionEnd(Modal.TRANSITION_DURATION) :
this.hideModal()
}
Modal.prototype.enforceFocus = function () {
$(document)
.off('focusin.bs.modal') // guard against infinite focus loop
.on('focusin.bs.modal', $.proxy(function (e) {
if (this.$element[0] !== e.target && !this.$element.has(e.target).length) {
this.$element.trigger('focus')
}
}, this))
}
Modal.prototype.escape = function () {
if (this.isShown && this.options.keyboard) {
this.$element.on('keydown.dismiss.bs.modal', $.proxy(function (e) {
e.which == 27 && this.hide()
}, this))
} else if (!this.isShown) {
this.$element.off('keydown.dismiss.bs.modal')
}
}
Modal.prototype.resize = function () {
if (this.isShown) {
$(window).on('resize.bs.modal', $.proxy(this.handleUpdate, this))
} else {
$(window).off('resize.bs.modal')
}
}
Modal.prototype.hideModal = function () {
var that = this
this.$element.hide()
this.backdrop(function () {
that.$body.removeClass('modal-open')
that.resetAdjustments()
that.resetScrollbar()
that.$element.trigger('hidden.bs.modal')
})
}
Modal.prototype.removeBackdrop = function () {
this.$backdrop && this.$backdrop.remove()
this.$backdrop = null
}
Modal.prototype.backdrop = function (callback) {
var that = this
var animate = this.$element.hasClass('fade') ? 'fade' : ''
if (this.isShown && this.options.backdrop) {
var doAnimate = $.support.transition && animate
this.$backdrop = $(document.createElement('div'))
.addClass('modal-backdrop ' + animate)
.appendTo(this.$body)
this.$element.on('click.dismiss.bs.modal', $.proxy(function (e) {
if (this.ignoreBackdropClick) {
this.ignoreBackdropClick = false
return
}
if (e.target !== e.currentTarget) return
this.options.backdrop == 'static'
? this.$element[0].focus()
: this.hide()
}, this))
if (doAnimate) this.$backdrop[0].offsetWidth // force reflow
this.$backdrop.addClass('in')
if (!callback) return
doAnimate ?
this.$backdrop
.one('bsTransitionEnd', callback)
.emulateTransitionEnd(Modal.BACKDROP_TRANSITION_DURATION) :
callback()
} else if (!this.isShown && this.$backdrop) {
this.$backdrop.removeClass('in')
var callbackRemove = function () {
that.removeBackdrop()
callback && callback()
}
$.support.transition && this.$element.hasClass('fade') ?
this.$backdrop
.one('bsTransitionEnd', callbackRemove)
.emulateTransitionEnd(Modal.BACKDROP_TRANSITION_DURATION) :
callbackRemove()
} else if (callback) {
callback()
}
}
// these following methods are used to handle overflowing modals
Modal.prototype.handleUpdate = function () {
this.adjustDialog()
}
Modal.prototype.adjustDialog = function () {
var modalIsOverflowing = this.$element[0].scrollHeight > document.documentElement.clientHeight
this.$element.css({
paddingLeft: !this.bodyIsOverflowing && modalIsOverflowing ? this.scrollbarWidth : '',
paddingRight: this.bodyIsOverflowing && !modalIsOverflowing ? this.scrollbarWidth : ''
})
}
Modal.prototype.resetAdjustments = function () {
this.$element.css({
paddingLeft: '',
paddingRight: ''
})
}
Modal.prototype.checkScrollbar = function () {
var fullWindowWidth = window.innerWidth
if (!fullWindowWidth) { // workaround for missing window.innerWidth in IE8
var documentElementRect = document.documentElement.getBoundingClientRect()
fullWindowWidth = documentElementRect.right - Math.abs(documentElementRect.left)
}
this.bodyIsOverflowing = document.body.clientWidth < fullWindowWidth
this.scrollbarWidth = this.measureScrollbar()
}
Modal.prototype.setScrollbar = function () {
var bodyPad = parseInt((this.$body.css('padding-right') || 0), 10)
this.originalBodyPad = document.body.style.paddingRight || ''
if (this.bodyIsOverflowing) this.$body.css('padding-right', bodyPad + this.scrollbarWidth)
}
Modal.prototype.resetScrollbar = function () {
this.$body.css('padding-right', this.originalBodyPad)
}
Modal.prototype.measureScrollbar = function () { // thx walsh
var scrollDiv = document.createElement('div')
scrollDiv.className = 'modal-scrollbar-measure'
this.$body.append(scrollDiv)
var scrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth
this.$body[0].removeChild(scrollDiv)
return scrollbarWidth
}
// MODAL PLUGIN DEFINITION
// =======================
function Plugin(option, _relatedTarget) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.modal')
var options = $.extend({}, Modal.DEFAULTS, $this.data(), typeof option == 'object' && option)
if (!data) $this.data('bs.modal', (data = new Modal(this, options)))
if (typeof option == 'string') data[option](_relatedTarget)
else if (options.show) data.show(_relatedTarget)
})
}
var old = $.fn.modal
$.fn.modal = Plugin
$.fn.modal.Constructor = Modal
// MODAL NO CONFLICT
// =================
$.fn.modal.noConflict = function () {
$.fn.modal = old
return this
}
// MODAL DATA-API
// ==============
$(document).on('click.bs.modal.data-api', '[data-toggle="modal"]', function (e) {
var $this = $(this)
var href = $this.attr('href')
var $target = $($this.attr('data-target') || (href && href.replace(/.*(?=#[^\s]+$)/, ''))) // strip for ie7
var option = $target.data('bs.modal') ? 'toggle' : $.extend({ remote: !/#/.test(href) && href }, $target.data(), $this.data())
if ($this.is('a')) e.preventDefault()
$target.one('show.bs.modal', function (showEvent) {
if (showEvent.isDefaultPrevented()) return // only register focus restorer if modal will actually get shown
$target.one('hidden.bs.modal', function () {
$this.is(':visible') && $this.trigger('focus')
})
})
Plugin.call($target, option, this)
})
}(jQuery);
/* ========================================================================
* Bootstrap: tooltip.js v3.3.6
* http://getbootstrap.com/javascript/#tooltip
* Inspired by the original jQuery.tipsy by Jason Frame
* ========================================================================
* Copyright 2011-2015 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// TOOLTIP PUBLIC CLASS DEFINITION
// ===============================
var Tooltip = function (element, options) {
this.type = null
this.options = null
this.enabled = null
this.timeout = null
this.hoverState = null
this.$element = null
this.inState = null
this.init('tooltip', element, options)
}
Tooltip.VERSION = '3.3.6'
Tooltip.TRANSITION_DURATION = 150
Tooltip.DEFAULTS = {
animation: true,
placement: 'top',
selector: false,
template: '<div class="tooltip" role="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>',
trigger: 'hover focus',
title: '',
delay: 0,
html: false,
container: false,
viewport: {
selector: 'body',
padding: 0
}
}
Tooltip.prototype.init = function (type, element, options) {
this.enabled = true
this.type = type
this.$element = $(element)
this.options = this.getOptions(options)
this.$viewport = this.options.viewport && $($.isFunction(this.options.viewport) ? this.options.viewport.call(this, this.$element) : (this.options.viewport.selector || this.options.viewport))
this.inState = { click: false, hover: false, focus: false }
if (this.$element[0] instanceof document.constructor && !this.options.selector) {
throw new Error('`selector` option must be specified when initializing ' + this.type + ' on the window.document object!')
}
var triggers = this.options.trigger.split(' ')
for (var i = triggers.length; i--;) {
var trigger = triggers[i]
if (trigger == 'click') {
this.$element.on('click.' + this.type, this.options.selector, $.proxy(this.toggle, this))
} else if (trigger != 'manual') {
var eventIn = trigger == 'hover' ? 'mouseenter' : 'focusin'
var eventOut = trigger == 'hover' ? 'mouseleave' : 'focusout'
this.$element.on(eventIn + '.' + this.type, this.options.selector, $.proxy(this.enter, this))
this.$element.on(eventOut + '.' + this.type, this.options.selector, $.proxy(this.leave, this))
}
}
this.options.selector ?
(this._options = $.extend({}, this.options, { trigger: 'manual', selector: '' })) :
this.fixTitle()
}
Tooltip.prototype.getDefaults = function () {
return Tooltip.DEFAULTS
}
Tooltip.prototype.getOptions = function (options) {
options = $.extend({}, this.getDefaults(), this.$element.data(), options)
if (options.delay && typeof options.delay == 'number') {
options.delay = {
show: options.delay,
hide: options.delay
}
}
return options
}
Tooltip.prototype.getDelegateOptions = function () {
var options = {}
var defaults = this.getDefaults()
this._options && $.each(this._options, function (key, value) {
if (defaults[key] != value) options[key] = value
})
return options
}
Tooltip.prototype.enter = function (obj) {
var self = obj instanceof this.constructor ?
obj : $(obj.currentTarget).data('bs.' + this.type)
if (!self) {
self = new this.constructor(obj.currentTarget, this.getDelegateOptions())
$(obj.currentTarget).data('bs.' + this.type, self)
}
if (obj instanceof $.Event) {
self.inState[obj.type == 'focusin' ? 'focus' : 'hover'] = true
}
if (self.tip().hasClass('in') || self.hoverState == 'in') {
self.hoverState = 'in'
return
}
clearTimeout(self.timeout)
self.hoverState = 'in'
if (!self.options.delay || !self.options.delay.show) return self.show()
self.timeout = setTimeout(function () {
if (self.hoverState == 'in') self.show()
}, self.options.delay.show)
}
Tooltip.prototype.isInStateTrue = function () {
for (var key in this.inState) {
if (this.inState[key]) return true
}
return false
}
Tooltip.prototype.leave = function (obj) {
var self = obj instanceof this.constructor ?
obj : $(obj.currentTarget).data('bs.' + this.type)
if (!self) {
self = new this.constructor(obj.currentTarget, this.getDelegateOptions())
$(obj.currentTarget).data('bs.' + this.type, self)
}
if (obj instanceof $.Event) {
self.inState[obj.type == 'focusout' ? 'focus' : 'hover'] = false
}
if (self.isInStateTrue()) return
clearTimeout(self.timeout)
self.hoverState = 'out'
if (!self.options.delay || !self.options.delay.hide) return self.hide()
self.timeout = setTimeout(function () {
if (self.hoverState == 'out') self.hide()
}, self.options.delay.hide)
}
Tooltip.prototype.show = function () {
var e = $.Event('show.bs.' + this.type)
if (this.hasContent() && this.enabled) {
this.$element.trigger(e)
var inDom = $.contains(this.$element[0].ownerDocument.documentElement, this.$element[0])
if (e.isDefaultPrevented() || !inDom) return
var that = this
var $tip = this.tip()
var tipId = this.getUID(this.type)
this.setContent()
$tip.attr('id', tipId)
this.$element.attr('aria-describedby', tipId)
if (this.options.animation) $tip.addClass('fade')
var placement = typeof this.options.placement == 'function' ?
this.options.placement.call(this, $tip[0], this.$element[0]) :
this.options.placement
var autoToken = /\s?auto?\s?/i
var autoPlace = autoToken.test(placement)
if (autoPlace) placement = placement.replace(autoToken, '') || 'top'
$tip
.detach()
.css({ top: 0, left: 0, display: 'block' })
.addClass(placement)
.data('bs.' + this.type, this)
this.options.container ? $tip.appendTo(this.options.container) : $tip.insertAfter(this.$element)
this.$element.trigger('inserted.bs.' + this.type)
var pos = this.getPosition()
var actualWidth = $tip[0].offsetWidth
var actualHeight = $tip[0].offsetHeight
if (autoPlace) {
var orgPlacement = placement
var viewportDim = this.getPosition(this.$viewport)
placement = placement == 'bottom' && pos.bottom + actualHeight > viewportDim.bottom ? 'top' :
placement == 'top' && pos.top - actualHeight < viewportDim.top ? 'bottom' :
placement == 'right' && pos.right + actualWidth > viewportDim.width ? 'left' :
placement == 'left' && pos.left - actualWidth < viewportDim.left ? 'right' :
placement
$tip
.removeClass(orgPlacement)
.addClass(placement)
}
var calculatedOffset = this.getCalculatedOffset(placement, pos, actualWidth, actualHeight)
this.applyPlacement(calculatedOffset, placement)
var complete = function () {
var prevHoverState = that.hoverState
that.$element.trigger('shown.bs.' + that.type)
that.hoverState = null
if (prevHoverState == 'out') that.leave(that)
}
$.support.transition && this.$tip.hasClass('fade') ?
$tip
.one('bsTransitionEnd', complete)
.emulateTransitionEnd(Tooltip.TRANSITION_DURATION) :
complete()
}
}
Tooltip.prototype.applyPlacement = function (offset, placement) {
var $tip = this.tip()
var width = $tip[0].offsetWidth
var height = $tip[0].offsetHeight
// manually read margins because getBoundingClientRect includes difference
var marginTop = parseInt($tip.css('margin-top'), 10)
var marginLeft = parseInt($tip.css('margin-left'), 10)
// we must check for NaN for ie 8/9
if (isNaN(marginTop)) marginTop = 0
if (isNaN(marginLeft)) marginLeft = 0
offset.top += marginTop
offset.left += marginLeft
// $.fn.offset doesn't round pixel values
// so we use setOffset directly with our own function B-0
$.offset.setOffset($tip[0], $.extend({
using: function (props) {
$tip.css({
top: Math.round(props.top),
left: Math.round(props.left)
})
}
}, offset), 0)
$tip.addClass('in')
// check to see if placing tip in new offset caused the tip to resize itself
var actualWidth = $tip[0].offsetWidth
var actualHeight = $tip[0].offsetHeight
if (placement == 'top' && actualHeight != height) {
offset.top = offset.top + height - actualHeight
}
var delta = this.getViewportAdjustedDelta(placement, offset, actualWidth, actualHeight)
if (delta.left) offset.left += delta.left
else offset.top += delta.top
var isVertical = /top|bottom/.test(placement)
var arrowDelta = isVertical ? delta.left * 2 - width + actualWidth : delta.top * 2 - height + actualHeight
var arrowOffsetPosition = isVertical ? 'offsetWidth' : 'offsetHeight'
$tip.offset(offset)
this.replaceArrow(arrowDelta, $tip[0][arrowOffsetPosition], isVertical)
}
Tooltip.prototype.replaceArrow = function (delta, dimension, isVertical) {
this.arrow()
.css(isVertical ? 'left' : 'top', 50 * (1 - delta / dimension) + '%')
.css(isVertical ? 'top' : 'left', '')
}
Tooltip.prototype.setContent = function () {
var $tip = this.tip()
var title = this.getTitle()
$tip.find('.tooltip-inner')[this.options.html ? 'html' : 'text'](title)
$tip.removeClass('fade in top bottom left right')
}
Tooltip.prototype.hide = function (callback) {
var that = this
var $tip = $(this.$tip)
var e = $.Event('hide.bs.' + this.type)
function complete() {
if (that.hoverState != 'in') $tip.detach()
that.$element
.removeAttr('aria-describedby')
.trigger('hidden.bs.' + that.type)
callback && callback()
}
this.$element.trigger(e)
if (e.isDefaultPrevented()) return
$tip.removeClass('in')
$.support.transition && $tip.hasClass('fade') ?
$tip
.one('bsTransitionEnd', complete)
.emulateTransitionEnd(Tooltip.TRANSITION_DURATION) :
complete()
this.hoverState = null
return this
}
Tooltip.prototype.fixTitle = function () {
var $e = this.$element
if ($e.attr('title') || typeof $e.attr('data-original-title') != 'string') {
$e.attr('data-original-title', $e.attr('title') || '').attr('title', '')
}
}
Tooltip.prototype.hasContent = function () {
return this.getTitle()
}
Tooltip.prototype.getPosition = function ($element) {
$element = $element || this.$element
var el = $element[0]
var isBody = el.tagName == 'BODY'
var elRect = el.getBoundingClientRect()
if (elRect.width == null) {
// width and height are missing in IE8, so compute them manually; see https://github.com/twbs/bootstrap/issues/14093
elRect = $.extend({}, elRect, { width: elRect.right - elRect.left, height: elRect.bottom - elRect.top })
}
var elOffset = isBody ? { top: 0, left: 0 } : $element.offset()
var scroll = { scroll: isBody ? document.documentElement.scrollTop || document.body.scrollTop : $element.scrollTop() }
var outerDims = isBody ? { width: $(window).width(), height: $(window).height() } : null
return $.extend({}, elRect, scroll, outerDims, elOffset)
}
Tooltip.prototype.getCalculatedOffset = function (placement, pos, actualWidth, actualHeight) {
return placement == 'bottom' ? { top: pos.top + pos.height, left: pos.left + pos.width / 2 - actualWidth / 2 } :
placement == 'top' ? { top: pos.top - actualHeight, left: pos.left + pos.width / 2 - actualWidth / 2 } :
placement == 'left' ? { top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth } :
/* placement == 'right' */ { top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width }
}
Tooltip.prototype.getViewportAdjustedDelta = function (placement, pos, actualWidth, actualHeight) {
var delta = { top: 0, left: 0 }
if (!this.$viewport) return delta
var viewportPadding = this.options.viewport && this.options.viewport.padding || 0
var viewportDimensions = this.getPosition(this.$viewport)
if (/right|left/.test(placement)) {
var topEdgeOffset = pos.top - viewportPadding - viewportDimensions.scroll
var bottomEdgeOffset = pos.top + viewportPadding - viewportDimensions.scroll + actualHeight
if (topEdgeOffset < viewportDimensions.top) { // top overflow
delta.top = viewportDimensions.top - topEdgeOffset
} else if (bottomEdgeOffset > viewportDimensions.top + viewportDimensions.height) { // bottom overflow
delta.top = viewportDimensions.top + viewportDimensions.height - bottomEdgeOffset
}
} else {
var leftEdgeOffset = pos.left - viewportPadding
var rightEdgeOffset = pos.left + viewportPadding + actualWidth
if (leftEdgeOffset < viewportDimensions.left) { // left overflow
delta.left = viewportDimensions.left - leftEdgeOffset
} else if (rightEdgeOffset > viewportDimensions.right) { // right overflow
delta.left = viewportDimensions.left + viewportDimensions.width - rightEdgeOffset
}
}
return delta
}
Tooltip.prototype.getTitle = function () {
var title
var $e = this.$element
var o = this.options
title = $e.attr('data-original-title')
|| (typeof o.title == 'function' ? o.title.call($e[0]) : o.title)
return title
}
Tooltip.prototype.getUID = function (prefix) {
do prefix += ~~(Math.random() * 1000000)
while (document.getElementById(prefix))
return prefix
}
Tooltip.prototype.tip = function () {
if (!this.$tip) {
this.$tip = $(this.options.template)
if (this.$tip.length != 1) {
throw new Error(this.type + ' `template` option must consist of exactly 1 top-level element!')
}
}
return this.$tip
}
Tooltip.prototype.arrow = function () {
return (this.$arrow = this.$arrow || this.tip().find('.tooltip-arrow'))
}
Tooltip.prototype.enable = function () {
this.enabled = true
}
Tooltip.prototype.disable = function () {
this.enabled = false
}
Tooltip.prototype.toggleEnabled = function () {
this.enabled = !this.enabled
}
Tooltip.prototype.toggle = function (e) {
var self = this
if (e) {
self = $(e.currentTarget).data('bs.' + this.type)
if (!self) {
self = new this.constructor(e.currentTarget, this.getDelegateOptions())
$(e.currentTarget).data('bs.' + this.type, self)
}
}
if (e) {
self.inState.click = !self.inState.click
if (self.isInStateTrue()) self.enter(self)
else self.leave(self)
} else {
self.tip().hasClass('in') ? self.leave(self) : self.enter(self)
}
}
Tooltip.prototype.destroy = function () {
var that = this
clearTimeout(this.timeout)
this.hide(function () {
that.$element.off('.' + that.type).removeData('bs.' + that.type)
if (that.$tip) {
that.$tip.detach()
}
that.$tip = null
that.$arrow = null
that.$viewport = null
})
}
// TOOLTIP PLUGIN DEFINITION
// =========================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.tooltip')
var options = typeof option == 'object' && option
if (!data && /destroy|hide/.test(option)) return
if (!data) $this.data('bs.tooltip', (data = new Tooltip(this, options)))
if (typeof option == 'string') data[option]()
})
}
var old = $.fn.tooltip
$.fn.tooltip = Plugin
$.fn.tooltip.Constructor = Tooltip
// TOOLTIP NO CONFLICT
// ===================
$.fn.tooltip.noConflict = function () {
$.fn.tooltip = old
return this
}
}(jQuery);
/* ========================================================================
* Bootstrap: popover.js v3.3.6
* http://getbootstrap.com/javascript/#popovers
* ========================================================================
* Copyright 2011-2015 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// POPOVER PUBLIC CLASS DEFINITION
// ===============================
var Popover = function (element, options) {
this.init('popover', element, options)
}
if (!$.fn.tooltip) throw new Error('Popover requires tooltip.js')
Popover.VERSION = '3.3.6'
Popover.DEFAULTS = $.extend({}, $.fn.tooltip.Constructor.DEFAULTS, {
placement: 'right',
trigger: 'click',
content: '',
template: '<div class="popover" role="tooltip"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div></div>'
})
// NOTE: POPOVER EXTENDS tooltip.js
// ================================
Popover.prototype = $.extend({}, $.fn.tooltip.Constructor.prototype)
Popover.prototype.constructor = Popover
Popover.prototype.getDefaults = function () {
return Popover.DEFAULTS
}
Popover.prototype.setContent = function () {
var $tip = this.tip()
var title = this.getTitle()
var content = this.getContent()
$tip.find('.popover-title')[this.options.html ? 'html' : 'text'](title)
$tip.find('.popover-content').children().detach().end()[ // we use append for html objects to maintain js events
this.options.html ? (typeof content == 'string' ? 'html' : 'append') : 'text'
](content)
$tip.removeClass('fade top bottom left right in')
// IE8 doesn't accept hiding via the `:empty` pseudo selector, we have to do
// this manually by checking the contents.
if (!$tip.find('.popover-title').html()) $tip.find('.popover-title').hide()
}
Popover.prototype.hasContent = function () {
return this.getTitle() || this.getContent()
}
Popover.prototype.getContent = function () {
var $e = this.$element
var o = this.options
return $e.attr('data-content')
|| (typeof o.content == 'function' ?
o.content.call($e[0]) :
o.content)
}
Popover.prototype.arrow = function () {
return (this.$arrow = this.$arrow || this.tip().find('.arrow'))
}
// POPOVER PLUGIN DEFINITION
// =========================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.popover')
var options = typeof option == 'object' && option
if (!data && /destroy|hide/.test(option)) return
if (!data) $this.data('bs.popover', (data = new Popover(this, options)))
if (typeof option == 'string') data[option]()
})
}
var old = $.fn.popover
$.fn.popover = Plugin
$.fn.popover.Constructor = Popover
// POPOVER NO CONFLICT
// ===================
$.fn.popover.noConflict = function () {
$.fn.popover = old
return this
}
}(jQuery);
/* ========================================================================
* Bootstrap: scrollspy.js v3.3.6
* http://getbootstrap.com/javascript/#scrollspy
* ========================================================================
* Copyright 2011-2015 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// SCROLLSPY CLASS DEFINITION
// ==========================
function ScrollSpy(element, options) {
this.$body = $(document.body)
this.$scrollElement = $(element).is(document.body) ? $(window) : $(element)
this.options = $.extend({}, ScrollSpy.DEFAULTS, options)
this.selector = (this.options.target || '') + ' .nav li > a'
this.offsets = []
this.targets = []
this.activeTarget = null
this.scrollHeight = 0
this.$scrollElement.on('scroll.bs.scrollspy', $.proxy(this.process, this))
this.refresh()
this.process()
}
ScrollSpy.VERSION = '3.3.6'
ScrollSpy.DEFAULTS = {
offset: 10
}
ScrollSpy.prototype.getScrollHeight = function () {
return this.$scrollElement[0].scrollHeight || Math.max(this.$body[0].scrollHeight, document.documentElement.scrollHeight)
}
ScrollSpy.prototype.refresh = function () {
var that = this
var offsetMethod = 'offset'
var offsetBase = 0
this.offsets = []
this.targets = []
this.scrollHeight = this.getScrollHeight()
if (!$.isWindow(this.$scrollElement[0])) {
offsetMethod = 'position'
offsetBase = this.$scrollElement.scrollTop()
}
this.$body
.find(this.selector)
.map(function () {
var $el = $(this)
var href = $el.data('target') || $el.attr('href')
var $href = /^#./.test(href) && $(href)
return ($href
&& $href.length
&& $href.is(':visible')
&& [[$href[offsetMethod]().top + offsetBase, href]]) || null
})
.sort(function (a, b) { return a[0] - b[0] })
.each(function () {
that.offsets.push(this[0])
that.targets.push(this[1])
})
}
ScrollSpy.prototype.process = function () {
var scrollTop = this.$scrollElement.scrollTop() + this.options.offset
var scrollHeight = this.getScrollHeight()
var maxScroll = this.options.offset + scrollHeight - this.$scrollElement.height()
var offsets = this.offsets
var targets = this.targets
var activeTarget = this.activeTarget
var i
if (this.scrollHeight != scrollHeight) {
this.refresh()
}
if (scrollTop >= maxScroll) {
return activeTarget != (i = targets[targets.length - 1]) && this.activate(i)
}
if (activeTarget && scrollTop < offsets[0]) {
this.activeTarget = null
return this.clear()
}
for (i = offsets.length; i--;) {
activeTarget != targets[i]
&& scrollTop >= offsets[i]
&& (offsets[i + 1] === undefined || scrollTop < offsets[i + 1])
&& this.activate(targets[i])
}
}
ScrollSpy.prototype.activate = function (target) {
this.activeTarget = target
this.clear()
var selector = this.selector +
'[data-target="' + target + '"],' +
this.selector + '[href="' + target + '"]'
var active = $(selector)
.parents('li')
.addClass('active')
if (active.parent('.dropdown-menu').length) {
active = active
.closest('li.dropdown')
.addClass('active')
}
active.trigger('activate.bs.scrollspy')
}
ScrollSpy.prototype.clear = function () {
$(this.selector)
.parentsUntil(this.options.target, '.active')
.removeClass('active')
}
// SCROLLSPY PLUGIN DEFINITION
// ===========================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.scrollspy')
var options = typeof option == 'object' && option
if (!data) $this.data('bs.scrollspy', (data = new ScrollSpy(this, options)))
if (typeof option == 'string') data[option]()
})
}
var old = $.fn.scrollspy
$.fn.scrollspy = Plugin
$.fn.scrollspy.Constructor = ScrollSpy
// SCROLLSPY NO CONFLICT
// =====================
$.fn.scrollspy.noConflict = function () {
$.fn.scrollspy = old
return this
}
// SCROLLSPY DATA-API
// ==================
$(window).on('load.bs.scrollspy.data-api', function () {
$('[data-spy="scroll"]').each(function () {
var $spy = $(this)
Plugin.call($spy, $spy.data())
})
})
}(jQuery);
/* ========================================================================
* Bootstrap: tab.js v3.3.6
* http://getbootstrap.com/javascript/#tabs
* ========================================================================
* Copyright 2011-2015 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// TAB CLASS DEFINITION
// ====================
var Tab = function (element) {
// jscs:disable requireDollarBeforejQueryAssignment
this.element = $(element)
// jscs:enable requireDollarBeforejQueryAssignment
}
Tab.VERSION = '3.3.6'
Tab.TRANSITION_DURATION = 150
Tab.prototype.show = function () {
var $this = this.element
var $ul = $this.closest('ul:not(.dropdown-menu)')
var selector = $this.data('target')
if (!selector) {
selector = $this.attr('href')
selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7
}
if ($this.parent('li').hasClass('active')) return
var $previous = $ul.find('.active:last a')
var hideEvent = $.Event('hide.bs.tab', {
relatedTarget: $this[0]
})
var showEvent = $.Event('show.bs.tab', {
relatedTarget: $previous[0]
})
$previous.trigger(hideEvent)
$this.trigger(showEvent)
if (showEvent.isDefaultPrevented() || hideEvent.isDefaultPrevented()) return
var $target = $(selector)
this.activate($this.closest('li'), $ul)
this.activate($target, $target.parent(), function () {
$previous.trigger({
type: 'hidden.bs.tab',
relatedTarget: $this[0]
})
$this.trigger({
type: 'shown.bs.tab',
relatedTarget: $previous[0]
})
})
}
Tab.prototype.activate = function (element, container, callback) {
var $active = container.find('> .active')
var transition = callback
&& $.support.transition
&& ($active.length && $active.hasClass('fade') || !!container.find('> .fade').length)
function next() {
$active
.removeClass('active')
.find('> .dropdown-menu > .active')
.removeClass('active')
.end()
.find('[data-toggle="tab"]')
.attr('aria-expanded', false)
element
.addClass('active')
.find('[data-toggle="tab"]')
.attr('aria-expanded', true)
if (transition) {
element[0].offsetWidth // reflow for transition
element.addClass('in')
} else {
element.removeClass('fade')
}
if (element.parent('.dropdown-menu').length) {
element
.closest('li.dropdown')
.addClass('active')
.end()
.find('[data-toggle="tab"]')
.attr('aria-expanded', true)
}
callback && callback()
}
$active.length && transition ?
$active
.one('bsTransitionEnd', next)
.emulateTransitionEnd(Tab.TRANSITION_DURATION) :
next()
$active.removeClass('in')
}
// TAB PLUGIN DEFINITION
// =====================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.tab')
if (!data) $this.data('bs.tab', (data = new Tab(this)))
if (typeof option == 'string') data[option]()
})
}
var old = $.fn.tab
$.fn.tab = Plugin
$.fn.tab.Constructor = Tab
// TAB NO CONFLICT
// ===============
$.fn.tab.noConflict = function () {
$.fn.tab = old
return this
}
// TAB DATA-API
// ============
var clickHandler = function (e) {
e.preventDefault()
Plugin.call($(this), 'show')
}
$(document)
.on('click.bs.tab.data-api', '[data-toggle="tab"]', clickHandler)
.on('click.bs.tab.data-api', '[data-toggle="pill"]', clickHandler)
}(jQuery);
/* ========================================================================
* Bootstrap: affix.js v3.3.6
* http://getbootstrap.com/javascript/#affix
* ========================================================================
* Copyright 2011-2015 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// AFFIX CLASS DEFINITION
// ======================
var Affix = function (element, options) {
this.options = $.extend({}, Affix.DEFAULTS, options)
this.$target = $(this.options.target)
.on('scroll.bs.affix.data-api', $.proxy(this.checkPosition, this))
.on('click.bs.affix.data-api', $.proxy(this.checkPositionWithEventLoop, this))
this.$element = $(element)
this.affixed = null
this.unpin = null
this.pinnedOffset = null
this.checkPosition()
}
Affix.VERSION = '3.3.6'
Affix.RESET = 'affix affix-top affix-bottom'
Affix.DEFAULTS = {
offset: 0,
target: window
}
Affix.prototype.getState = function (scrollHeight, height, offsetTop, offsetBottom) {
var scrollTop = this.$target.scrollTop()
var position = this.$element.offset()
var targetHeight = this.$target.height()
if (offsetTop != null && this.affixed == 'top') return scrollTop < offsetTop ? 'top' : false
if (this.affixed == 'bottom') {
if (offsetTop != null) return (scrollTop + this.unpin <= position.top) ? false : 'bottom'
return (scrollTop + targetHeight <= scrollHeight - offsetBottom) ? false : 'bottom'
}
var initializing = this.affixed == null
var colliderTop = initializing ? scrollTop : position.top
var colliderHeight = initializing ? targetHeight : height
if (offsetTop != null && scrollTop <= offsetTop) return 'top'
if (offsetBottom != null && (colliderTop + colliderHeight >= scrollHeight - offsetBottom)) return 'bottom'
return false
}
Affix.prototype.getPinnedOffset = function () {
if (this.pinnedOffset) return this.pinnedOffset
this.$element.removeClass(Affix.RESET).addClass('affix')
var scrollTop = this.$target.scrollTop()
var position = this.$element.offset()
return (this.pinnedOffset = position.top - scrollTop)
}
Affix.prototype.checkPositionWithEventLoop = function () {
setTimeout($.proxy(this.checkPosition, this), 1)
}
Affix.prototype.checkPosition = function () {
if (!this.$element.is(':visible')) return
var height = this.$element.height()
var offset = this.options.offset
var offsetTop = offset.top
var offsetBottom = offset.bottom
var scrollHeight = Math.max($(document).height(), $(document.body).height())
if (typeof offset != 'object') offsetBottom = offsetTop = offset
if (typeof offsetTop == 'function') offsetTop = offset.top(this.$element)
if (typeof offsetBottom == 'function') offsetBottom = offset.bottom(this.$element)
var affix = this.getState(scrollHeight, height, offsetTop, offsetBottom)
if (this.affixed != affix) {
if (this.unpin != null) this.$element.css('top', '')
var affixType = 'affix' + (affix ? '-' + affix : '')
var e = $.Event(affixType + '.bs.affix')
this.$element.trigger(e)
if (e.isDefaultPrevented()) return
this.affixed = affix
this.unpin = affix == 'bottom' ? this.getPinnedOffset() : null
this.$element
.removeClass(Affix.RESET)
.addClass(affixType)
.trigger(affixType.replace('affix', 'affixed') + '.bs.affix')
}
if (affix == 'bottom') {
this.$element.offset({
top: scrollHeight - height - offsetBottom
})
}
}
// AFFIX PLUGIN DEFINITION
// =======================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.affix')
var options = typeof option == 'object' && option
if (!data) $this.data('bs.affix', (data = new Affix(this, options)))
if (typeof option == 'string') data[option]()
})
}
var old = $.fn.affix
$.fn.affix = Plugin
$.fn.affix.Constructor = Affix
// AFFIX NO CONFLICT
// =================
$.fn.affix.noConflict = function () {
$.fn.affix = old
return this
}
// AFFIX DATA-API
// ==============
$(window).on('load', function () {
$('[data-spy="affix"]').each(function () {
var $spy = $(this)
var data = $spy.data()
data.offset = data.offset || {}
if (data.offsetBottom != null) data.offset.bottom = data.offsetBottom
if (data.offsetTop != null) data.offset.top = data.offsetTop
Plugin.call($spy, data)
})
})
}(jQuery); | zeus-lab804 | /zeus-lab804-0.1.2.tar.gz/zeus-lab804-0.1.2/zeusproject/templates/static/js/bootstrap.js | bootstrap.js |
import numpy as np
from scipy.fft import fft, ifft
def _autocorr_func_1d(x, norm=True):
"""
Autocorrelation Function of 1-dimensional chain.
Args:
x (array) : 1-dimensional chain.
norm (bool) : By default norm=True and the autocorrelation function will be normalized.
Returns:
The (normalised if norm=True) autocorrelation function of the chain x.
"""
x = np.atleast_1d(x)
if len(x.shape) != 1:
raise ValueError("invalid dimensions for 1D autocorrelation function")
# Next largest power of 2
n = 1
while n < len(x):
n = n << 1
# Compute the auto-correlation function using FFT
#f = np.fft.fft(x - np.mean(x), n=2 * n)
#acf = np.fft.ifft(f * np.conjugate(f))[: len(x)].real
f = fft(x - np.mean(x), n=2 * n)
acf = ifft(f * np.conjugate(f))[: len(x)].real
acf /= 4 * n
# Normalize
if norm:
acf /= acf[0]
return acf
def _autocorr_time_1d(y, c=5.0, method='mk'):
"""
Integrated Autocorrelation Time (IAT) for 1-dimensional chain.
Args:
y (array) : (nsteps, nwalkers) array for one parameter.
c (float) : Truncation parameter of automated windowing procedure of Sokal (1989), default is 5.0.
method (str) : Method to use to compute the IAT. Available options are ``mk`` (Default), ``dfm``, and ``gw``.
Returns:
The IAT of the chain y.
"""
if method not in ['mk', 'dfm', 'gw']:
raise ValueError('Please select one of the supported methods i.e. mk (Recommended), dfm, gw.')
if method == 'mk':
# Minas Karamanis method
f = _autocorr_func_1d(y.reshape((-1), order='C'))
elif method == 'dfm':
# Daniel Forman-Mackey method
f = np.zeros(y.shape[1])
for yy in y:
f += _autocorr_func_1d(yy)
f /= len(y)
else:
# Goodman-Weary method
f = _autocorr_func_1d(np.mean(y, axis=0))
taus = 2.0 * np.cumsum(f) - 1.0
# Automated windowing procedure following Sokal (1989)
def auto_window(taus, c):
m = np.arange(len(taus)) < c * taus
if np.any(m):
return np.argmin(m)
return len(taus) - 1
window = auto_window(taus, c)
return taus[window]
def AutoCorrTime(samples, c=5.0, method='mk'):
"""
Integrated Autocorrelation Time (IAT) for all the chains.
Parameters
----------
samples : array
3-dimensional array of shape (nsteps, nwalkers, ndim)
c : float
Truncation parameter of automated windowing procedure of Sokal (1989), default is 5.0
method : str
Method to use to compute the IAT. Available options are ``mk`` (Default), ``dfm``, and ``gw``.
Returns
-------
taus : array
Array with the IAT of all the chains.
"""
if method not in ['mk', 'dfm', 'gw']:
raise ValueError('Please select one of the supported methods i.e. mk (Recommended), dfm, gw.')
_, _, ndim = np.shape(samples)
taus = np.empty(ndim)
for i in range(ndim):
taus[i] = _autocorr_time_1d(samples[:,:,i].T, c, method)
return taus | zeus-mcmc | /zeus_mcmc-2.5.4-py3-none-any.whl/zeus/autocorr.py | autocorr.py |
import numpy as np
class samples:
'''
Creates object that stores the samples.
Args:
ndim (int): Number of dimensions/parameters
nwalkers (int): Number of walkers.
'''
def __init__(self, ndim, nwalkers):
self.initialised = False
self.index = 0
self.ndim = ndim
self.nwalkers = nwalkers
def extend(self, n, blobs):
"""
Method to extend saving space.
Args:
n (int) : Extend space by n slots.
"""
if self.initialised:
ext = np.empty((n,self.nwalkers,self.ndim))
self.samples = np.concatenate((self.samples,ext),axis=0)
ext = np.empty((n,self.nwalkers))
self.logp = np.concatenate((self.logp,ext),axis=0)
if blobs is not None:
dt = np.dtype((blobs[0].dtype, blobs[0].shape))
ext = np.empty((n,self.nwalkers), dtype=dt)
self.blobs = np.concatenate((self.blobs, ext),axis=0)
else:
self.samples = np.empty((n,self.nwalkers,self.ndim))
self.logp = np.empty((n,self.nwalkers))
if blobs is not None:
dt = np.dtype((blobs[0].dtype, blobs[0].shape))
self.blobs = np.empty((n,self.nwalkers), dtype=dt)
self.initialised = True
def save(self, x, logp, blobs):
"""
Save sample into the storage.
Args:
x (ndarray): Samples to be appended into the storage.
logp (ndarray): Logprob values to be appended into the storage.
"""
self.samples[self.index] = x
self.logp[self.index] = logp
if blobs is not None:
self.blobs[self.index] = blobs
self.index += 1
@property
def chain(self):
"""
Chain property.
Returns:
3D array of shape (nsteps,nwalkers,ndim) containing the samples.
"""
return self.samples[:self.index]
@property
def length(self):
"""
Number of samples per walker.
Returns:
The total number of samples per walker.
"""
return self.index
def flatten(self, discard=0, thin=1):
"""
Flatten samples by thinning them, removing the burn in phase, and combining all the walkers.
Args:
discard (int): Number of burn-in steps to be removed from each walker (default is 0).
thin (int): Thinning parameter (the default value is 1).
Returns:
2D object containing the ndim flattened chains.
"""
return self.chain[discard:self.index:thin,:,:].reshape((-1,self.ndim), order='F')
@property
def logprob(self):
"""
Chain property.
Returns:
2D array of shape (nwalkers,nsteps) containing the log-probabilities.
"""
return self.logp[:self.index]
def flatten_logprob(self, discard=0, thin=1):
"""
Flatten log probability by thinning the chain, removing the burn in phase, and combining all the walkers.
Args:
discard (int): Number of burn-in steps to be removed from each walker (default is 0).
thin (int): Thinning parameter (the default value is 1).
Returns:
1D object containing the logprob of the flattened chains.
"""
return self.logprob[discard:self.index:thin,:].reshape((-1,), order='F')
def flatten_blobs(self, discard=0, thin=1):
"""
Flatten blobs by thinning the chain, removing the burn in phase, and combining all the walkers.
Args:
discard (int): Number of burn-in steps to be removed from each walker (default is 0).
thin (int): Thinning parameter (the default value is 1).
Returns:
(structured) NumPy array containing the blobs metadata.
"""
return self.blobs[discard:self.index:thin,:].reshape((-1,), order='F') | zeus-mcmc | /zeus_mcmc-2.5.4-py3-none-any.whl/zeus/samples.py | samples.py |
import sys
import atexit
MPI = None
def _import_mpi(use_dill=False):
global MPI
try:
from mpi4py import MPI as _MPI
if use_dill:
import dill
_MPI.pickle.__init__(dill.dumps, dill.loads, dill.HIGHEST_PROTOCOL)
MPI = _MPI
except:
raise ImportError("Please install mpi4py")
return MPI
class MPIPool:
"""A processing pool that distributes tasks using MPI.
With this pool class, the master process distributes tasks to worker
processes using an MPI communicator.
This implementation is inspired by @juliohm in `this module
<https://github.com/juliohm/HUM/blob/master/pyhum/utils.py#L24>`_
and was adapted from schwimmbad.
Parameters
----------
comm : :class:`mpi4py.MPI.Comm`, optional
An MPI communicator to distribute tasks with. If ``None``, this uses
``MPI.COMM_WORLD`` by default.
"""
def __init__(self, comm=None):
self.comm = MPI.COMM_WORLD if comm is None else comm
self.master = 0
self.rank = self.comm.Get_rank()
atexit.register(lambda: MPIPool.close(self))
if not self.is_master():
# workers branch here and wait for work
self.wait()
sys.exit(0)
self.workers = set(range(self.comm.size))
self.workers.discard(self.master)
self.size = self.comm.Get_size() - 1
if self.size == 0:
raise ValueError("Tried to create an MPI pool, but there "
"was only one MPI process available. "
"Need at least two.")
def wait(self):
"""Tell the workers to wait and listen for the master process. This is
called automatically when using :meth:`MPIPool.map` and doesn't need to
be called by the user.
"""
if self.is_master():
return
status = MPI.Status()
while True:
task = self.comm.recv(source=self.master, tag=MPI.ANY_TAG, status=status)
if task is None:
# Worker told to quit work
break
func, arg = task
result = func(arg)
# Worker is sending answer with tag
self.comm.ssend(result, self.master, status.tag)
def map(self, worker, tasks):
"""Evaluate a function or callable on each task in parallel using MPI.
The callable, ``worker``, is called on each element of the ``tasks``
iterable. The results are returned in the expected order.
Parameters
----------
worker : callable
A function or callable object that is executed on each element of
the specified ``tasks`` iterable. This object must be picklable
(i.e. it can't be a function scoped within a function or a
``lambda`` function). This should accept a single positional
argument and return a single object.
tasks : iterable
A list or iterable of tasks. Each task can be itself an iterable
(e.g., tuple) of values or data to pass in to the worker function.
Returns
-------
results : list
A list of results from the output of each ``worker()`` call.
"""
# If not the master just wait for instructions.
if not self.is_master():
self.wait()
return
workerset = self.workers.copy()
tasklist = [(tid, (worker, arg)) for tid, arg in enumerate(tasks)]
resultlist = [None] * len(tasklist)
pending = len(tasklist)
while pending:
if workerset and tasklist:
worker = workerset.pop()
taskid, task = tasklist.pop()
# "Sent task %s to worker %s with tag %s"
self.comm.send(task, dest=worker, tag=taskid)
if tasklist:
flag = self.comm.Iprobe(source=MPI.ANY_SOURCE, tag=MPI.ANY_TAG)
if not flag:
continue
else:
self.comm.Probe(source=MPI.ANY_SOURCE, tag=MPI.ANY_TAG)
status = MPI.Status()
result = self.comm.recv(source=MPI.ANY_SOURCE, tag=MPI.ANY_TAG,
status=status)
worker = status.source
taskid = status.tag
# "Master received from worker %s with tag %s"
workerset.add(worker)
resultlist[taskid] = result
pending -= 1
return resultlist
def close(self):
""" Tell all the workers to quit."""
if self.is_worker():
return
for worker in self.workers:
self.comm.send(None, worker, 0)
def is_master(self):
return self.rank == 0
def is_worker(self):
return self.rank != 0
def __enter__(self):
return self
def __exit__(self, *args):
self.close()
def split_ranks(N_ranks, N_chunks):
"""
Divide the ranks into N chunks
"""
seq = range(N_ranks)
avg = int(N_ranks // N_chunks)
remainder = N_ranks % N_chunks
start = 0
end = avg
for i in range(N_chunks):
if remainder:
end += 1
remainder -= 1
yield i, seq[start:end]
start = end
end += avg
class ChainManager:
"""
Class to serve as context manager to handle to MPI-related issues,
specifically, the managing of ``MPIPool`` and splitting of communicators.
This class can be used to run ``nchains`` in parallel with each chain
having its own ``MPIPool`` of parallel walkers.
Parameters
----------
nchains : int
the number of independent chains to run concurrently
comm : MPI.Communicator
the global communicator to split
"""
def __init__(self, nchains=1, comm=None):
global MPI
MPI = _import_mpi(use_dill=False)
self.comm = MPI.COMM_WORLD if comm is None else comm
self.nchains = nchains
# initialize comm for parallel chains
self.chains_group = None
self.chains_comm = None
# intiialize comm for pool of workers for each parallel chain
self.pool_comm = None
self.pool = None
def __enter__(self):
"""
Setup the MPIPool, such that only the ``pool`` master returns,
while the other processes wait for tasks
"""
# split ranks if we need to
if self.comm.size > 1:
ranges = []
for i, ranks in split_ranks(self.comm.size, self.nchains):
ranges.append(ranks[0])
if self.comm.rank in ranks:
color = i
# split the global comm into pools of workers
self.pool_comm = self.comm.Split(color, 0)
# make the comm to communicate b/w parallel runs
if self.nchains >= 1:
self.chains_group = self.comm.group.Incl(ranges)
self.chains_comm = self.comm.Create(self.chains_group)
# initialize the MPI pool, if the comm has more than 1 process
if self.pool_comm is not None and self.pool_comm.size > 1:
self.pool = MPIPool(comm=self.pool_comm)
# explicitly force non-master ranks in pool to wait
if self.pool is not None and not self.pool.is_master():
self.pool.wait()
sys.exit(0)
self.rank = 0
if self.chains_comm is not None:
self.rank = self.chains_comm.rank
return self
def __exit__(self, exc_type, exc_value, exc_traceback):
"""
Exit gracefully by closing and freeing the MPI-related variables
"""
# wait for all the processes, if we more than one
if self.chains_comm is not None and self.chains_comm.size > 1:
self.chains_comm.Barrier()
# close and free the MPI stuff
if self.chains_group is not None:
self.chains_group.Free()
if self.chains_comm is not None:
self.chains_comm.Free()
if self.pool is not None:
self.pool.close()
@property
def get_rank(self):
'''
Get ``rank`` of current ``chain``. The minimum ``rank`` is ``0`` and the maximum is ``nchains-1``.
'''
return self.rank
@property
def get_pool(self):
'''
Get parallel ``pool`` of workers that correspond to a specific chain. This should be used to
parallelize the walkers of each ``chain`` (not the chains themselves). This includes the ``map``
method that ``zeus`` requires.
'''
return self.pool
def gather(self, x, root):
'''
Gather method to gather ``x`` in ``rank = root`` chain.
Parameters
----------
x : Python object
The python object to be gathered.
root : int
The rank of the chain that x is gathered.
Returns
-------
x : Python object
The input object x gathered in ``rank = root``.
'''
return self.chains_comm.gather(x, root=root)
def scatter(self, x, root):
'''
Scatter method to scatter ``x`` from ``rank = root`` chain to the rest.
Parameters
----------
x : Python object
The python object to be scattered.
root : int
The rank of the origin chain from which the x is scattered.
Returns
-------
x : Pythonn object
Part of the input object x that was scattered along the ranks.
'''
return self.chains_comm.scatter(x, root=root)
def allgather(self, x):
'''
Allgather method to gather ``x`` in all chains. This is equivalent to first ``scatter`` and then ``bcast``.
Parameters
----------
x : Python object
The python object to be gathered.
Returns
-------
x : Python object
The python object, gathered in all ranks.
'''
return self.chains_comm.allgather(x)
def bcast(self, x, root):
'''
Broadcast method to send ``x`` from ``rank = root`` to all chains.
Parameters
----------
x : Python object
The python object to be send.
root : int
The rank of the origin chain from which the object x is sent.
Returns
-------
x : Python object
The input object x in all ranks.
'''
return self.chains_comm.bcast(x, root=root) | zeus-mcmc | /zeus_mcmc-2.5.4-py3-none-any.whl/zeus/parallel.py | parallel.py |
import numpy as np
from itertools import permutations
import random
try:
from scipy.stats import gaussian_kde
except ImportError:
gaussian_kde = None
try:
from sklearn.mixture import BayesianGaussianMixture
except ImportError:
BayesianGaussianMixture = None
class DifferentialMove:
r"""
The `Karamanis & Beutler (2020) <https://arxiv.org/abs/2002.06212>`_ "Differential Move" with parallelization.
When this Move is used the walkers move along directions defined by random pairs of walkers sampled (with no
replacement) from the complementary ensemble. This is the default choice and performs well along a wide range
of target distributions.
Parameters
----------
tune : bool
If True then tune this move. Default is True.
mu0 : float
Default value of ``mu`` if ``tune=False``.
"""
def __init__(self, tune=True, mu0=1.0):
self.tune = tune
self.mu0 = mu0
def get_direction(self, X, mu):
r"""
Generate direction vectors.
Parameters
----------
X : array
Array of shape ``(nwalkers//2, ndim)`` with the walker positions of the complementary ensemble.
mu : float
The value of the scale factor ``mu``.
Returns
-------
directions : array
Array of direction vectors of shape ``(nwalkers//2, ndim)``.
"""
nsamples = X.shape[0]
perms = list(permutations(np.arange(nsamples), 2))
pairs = np.asarray(random.sample(perms,nsamples)).T
if not self.tune:
mu = self.mu0
return 2.0 * mu * (X[pairs[0]]-X[pairs[1]]), self.tune
class GaussianMove:
r"""
The `Karamanis & Beutler (2020) <https://arxiv.org/abs/2002.06212>`_ "Gaussian Move" with parallelization.
When this Move is used the walkers move along directions defined by random vectors sampled from the Gaussian
approximation of the walkers of the complementary ensemble.
Parameters
----------
tune : bool
If True then tune this move. Default is True.
mu0 : float
Default value of ``mu`` if ``tune=False``.
"""
def __init__(self, tune=False, mu0=1.0, cov=None):
self.tune = tune
self.mu0 = mu0
self.cov = cov
def get_direction(self, X, mu):
r"""
Generate direction vectors.
Parameters
----------
X : array
Array of shape ``(nwalkers//2, ndim)`` with the walker positions of the complementary ensemble.
mu : float
The value of the scale factor ``mu``.
Returns
-------
directions : array
Array of direction vectors of shape ``(nwalkers//2, ndim)``.
"""
nsamples = X.shape[0]
mean = np.mean(X, axis=0)
if self.cov is None:
cov = np.cov(X, rowvar=False)
else:
cov = self.cov
if not self.tune:
mu = self.mu0
return 2.0 * mu * np.random.multivariate_normal(np.zeros_like(mean),cov,size=nsamples), self.tune
class GlobalMove:
r"""
The `Karamanis & Beutler (2020) <https://arxiv.org/abs/2002.06212>`_ "Global Move" with parallelization.
When this Move is used a Bayesian Gaussian Mixture (BGM) is fitted to the walkers of complementary ensemble.
The walkers move along random directions which connect different components of the BGM in an attempt to
facilitate mode jumping. This Move should be used when the target distribution is multimodal. This move should
be used after any burnin period.
Parameters
----------
tune : bool
If True then tune this move. Default is True.
mu0 : float
Default value of ``mu`` if ``tune=False``.
rescale_cov : float
Rescale the covariance matrices of the BGM components by this factor. This promotes mode jumping.
Default value is 0.001.
n_components : int
The number of mixture components. Depending on the distribution of the walkers the model can
decide not to use all of them.
"""
def __init__(self, tune=True, mu0=1.0, rescale_cov=0.001, n_components=5):
if BayesianGaussianMixture is None:
raise ImportError("you need sklearn.mixture.BayesianGaussianMixture to use the GlobalMove")
self.tune = tune
self.mu0 = mu0
self.rescale_cov = rescale_cov
self.n_components = n_components
def get_direction(self, X, mu):
r"""
Generate direction vectors.
Parameters
----------
X : array
Array of shape ``(nwalkers//2, ndim)`` with the walker positions of the complementary ensemble.
mu : float
The value of the scale factor ``mu``.
Returns
-------
directions : array
Array of direction vectors of shape ``(nwalkers//2, ndim)``.
"""
if not self.tune:
mu = self.mu0
n = X.shape[0]
mixture = BayesianGaussianMixture(n_components=self.n_components)
labels = mixture.fit_predict(X)
means = mixture.means_
covariances = mixture.covariances_
i, j = np.random.choice(labels, 2, replace=False)
if i != j:
directions = np.random.multivariate_normal(means[i], covariances[i]*self.rescale_cov, size=n) - np.random.multivariate_normal(means[j], covariances[j]*self.rescale_cov, size=n)
tune_once = False
else:
directions = mu * np.random.multivariate_normal(np.zeros_like(means[i]), covariances[i], size=n)
if self.tune:
tune_once = True
else:
tune_once = False
return 2.0*directions, tune_once
class KDEMove:
r"""
The `Karamanis & Beutler (2020) <https://arxiv.org/abs/2002.06212>`_ "KDE Move" with parallelization.
When this Move is used the distribution of the walkers of the complementary ensemble is traced using
a Gaussian Kernel Density Estimation methods. The walkers then move along random direction vectos
sampled from this distribution.
Parameters
----------
tune : bool
If True then tune this move. Default is True.
mu0 : float
Default value of ``mu`` if ``tune=False``.
bw_method :
The bandwidth estimation method. See the scipy docs for allowed values.
"""
def __init__(self, tune=False, mu0=1.0, bw_method=None):
if gaussian_kde is None:
raise ImportError("you need scipy.stats.gaussian_kde to use the KDEMove")
self.tune = tune
self.mu0 = mu0
self.bw_method = bw_method
def get_direction(self, X, mu):
r"""
Generate direction vectors.
Parameters
----------
X : array
Array of shape ``(nwalkers//2, ndim)`` with the walker positions of the complementary ensemble.
mu : float
The value of the scale factor ``mu``.
Returns
-------
directions : array
Array of direction vectors of shape ``(nwalkers//2, ndim)``.
"""
n = X.shape[0]
kde = gaussian_kde(X.T, bw_method=self.bw_method)
vectors = kde.resample(2*n).T
directions = vectors[:n] - vectors[n:]
if not self.tune:
mu = self.mu0
return 2.0 * mu * directions, self.tune
class RandomMove:
r"""
The `Karamanis & Beutler (2020) <https://arxiv.org/abs/2002.06212>`_ "Random Move" with parallelization.
When this move is used the walkers move along random directions. There is no communication between the
walkers and this Move corresponds to the vanilla Slice Sampling method. This Move should be used for
debugging purposes only.
Parameters
----------
tune : bool
If True then tune this move. Default is True.
mu0 : float
Default value of ``mu`` if ``tune=False``.
"""
def __init__(self, tune=True, mu0=1.0):
self.tune = tune
self.mu0 = mu0
def get_direction(self, X, mu):
r"""
Generate direction vectors.
Parameters
----------
X : array
Array of shape ``(nwalkers//2, ndim)`` with the walker positions of the complementary ensemble.
mu : float
The value of the scale factor ``mu``.
Returns
-------
directions : array
Array of direction vectors of shape ``(nwalkers//2, ndim)``.
"""
directions = np.random.normal(0.0, 1.0, size=X.shape)
directions /= np.linalg.norm(directions, axis=0)
if not self.tune:
mu = self.mu0
return 2.0 * mu * directions, self.tune | zeus-mcmc | /zeus_mcmc-2.5.4-py3-none-any.whl/zeus/moves.py | moves.py |
import numpy as np
from tqdm import tqdm
import logging
try:
from collections.abc import Iterable
except ImportError:
# for py2.7, will be an Exception in 3.8
from collections import Iterable
from .samples import samples
from .fwrapper import _FunctionWrapper
from .autocorr import AutoCorrTime
from .moves import DifferentialMove
class EnsembleSampler:
"""
An Ensemble Slice Sampler.
Args:
nwalkers (int): The number of walkers in the ensemble.
ndim (int): The number of dimensions/parameters.
logprob_fn (callable): A python function that takes a vector in the
parameter space as input and returns the natural logarithm of the
unnormalised posterior probability at that position.
args (list): Extra arguments to be passed into the logp.
kwargs (list): Extra arguments to be passed into the logp.
moves (list): This can be a single move object, a list of moves, or a “weighted” list of the form ``[(zeus.moves.DifferentialMove(), 0.1), ...]``.
When running, the sampler will randomly select a move from this list (optionally with weights) for each proposal. (default: DifferentialMove)
tune (bool): Tune the scale factor to optimize performance (Default is True.)
tolerance (float): Tuning optimization tolerance (Default is 0.05).
patience (int): Number of tuning steps to wait to make sure that tuning is done (Default is 5).
maxsteps (int): Number of maximum stepping-out steps (Default is 10^4).
mu (float): Scale factor (Default value is 1.0), this will be tuned if tune=True.
maxiter (int): Number of maximum Expansions/Contractions (Default is 10^4).
pool (bool): External pool of workers to distribute workload to multiple CPUs (default is None).
vectorize (bool): If true (default is False), logprob_fn receives not just one point but an array of points, and returns an array of log-probabilities.
blobs_dtype (list): List containing names and dtypes of blobs metadata e.g. ``[("log_prior", float), ("mean", float)]``. It's useful when you want to save multiple species of metadata. Default is None.
verbose (bool): If True (default) print log statements.
check_walkers (bool): If True (default) then check that ``nwalkers >= 2*ndim`` and even.
shuffle_ensemble (bool): If True (default) then shuffle the ensemble of walkers in every iteration before splitting it.
light_mode (bool): If True (default is False) then no expansions are performed after the tuning phase. This can significantly reduce the number of log likelihood evaluations but works best in target distributions that are apprroximately Gaussian.
"""
def __init__(self,
nwalkers,
ndim,
logprob_fn,
args=None,
kwargs=None,
moves=None,
tune=True,
tolerance=0.05,
patience=5,
maxsteps=10000,
mu=1.0,
maxiter=10000,
pool=None,
vectorize=False,
blobs_dtype=None,
verbose=True,
check_walkers=True,
shuffle_ensemble=True,
light_mode=False,
):
# Set up logger
self.logger = logging.getLogger()
for handler in self.logger.handlers[:]:
self.logger.removeHandler(handler)
handler = logging.StreamHandler()
self.logger.addHandler(handler)
if verbose:
self.logger.setLevel(logging.INFO)
else:
self.logger.setLevel(logging.WARNING)
# Parse the move schedule
if moves is None:
self._moves = [DifferentialMove()]
self._weights = [1.0]
elif isinstance(moves, Iterable):
try:
self._moves, self._weights = zip(*moves)
except TypeError:
self._moves = moves
self._weights = np.ones(len(moves))
else:
self._moves = [moves]
self._weights = [1.0]
self._weights = np.atleast_1d(self._weights).astype(float)
self._weights /= np.sum(self._weights)
# Set up Log Probability
self.logprob_fn = _FunctionWrapper(logprob_fn, args, kwargs)
# Set up walkers
self.nwalkers = int(nwalkers)
self.ndim = int(ndim)
self.check_walkers = check_walkers
if self.check_walkers:
if self.nwalkers < 2 * self.ndim:
raise ValueError("Please provide at least (2 * ndim) walkers.")
elif self.nwalkers % 2 == 1:
raise ValueError("Please provide an even number of walkers.")
self.shuffle_ensemble = shuffle_ensemble
# Set up Slice parameters
self.mu = mu
self.mus = []
self.mus.append(self.mu)
self.tune = tune
self.maxsteps = maxsteps
self.patience = patience
self.tolerance = tolerance
self.nexps = []
self.ncons = []
# Set up maximum number of Expansions/Contractions
self.maxiter = maxiter
# Set up pool of workers
self.pool = pool
self.vectorize = vectorize
# Set up blobs dtype
self.blobs_dtype = blobs_dtype
# Initialise Saving space for samples
self.samples = samples(self.ndim, self.nwalkers)
# Initialise iteration counter and state
self.iteration = 0
self.state_X = None
self.state_Z = None
self.state_blobs = None
# Light mode
self.light_mode = light_mode
def run(self, *args, **kwargs):
logging.warning('The run method has been deprecated and it will be removed. Please use the new run_mcmc method.')
return self.run_mcmc(*args, **kwargs)
def reset(self):
"""
Reset the state of the sampler. Delete any samples stored in memory.
"""
self.samples = samples(self.ndim, self.nwalkers)
def get_chain(self, flat=False, thin=1, discard=0):
"""
Get the Markov chain containing the samples.
Args:
flat (bool) : If True then flatten the chain into a 2D array by combining all walkers (default is False).
thin (int) : Thinning parameter (the default value is 1).
discard (int) : Number of burn-in steps to be removed from each walker (default is 0). A float number between
0.0 and 1.0 can be used to indicate what percentage of the chain to be discarded as burnin.
Returns:
Array object containg the Markov chain samples (2D if flat=True, 3D if flat=False).
"""
if discard < 1.0:
discard = int(discard * np.shape(self.chain)[0])
if flat:
return self.samples.flatten(discard=discard, thin=thin)
else:
return self.chain[discard::thin,:,:]
def get_log_prob(self, flat=False, thin=1, discard=0):
"""
Get the value of the log probability function evalutated at the samples of the Markov chain.
Args:
flat (bool) : If True then flatten the chain into a 1D array by combining all walkers (default is False).
thin (int) : Thinning parameter (the default value is 1).
discard (int) : Number of burn-in steps to be removed from each walker (default is 0). A float number between
0.0 and 1.0 can be used to indicate what percentage of the chain to be discarded as burnin.
Returns:
Array containing the value of the log probability at the samples of the Markov chain (1D if flat=True, 2D otherwise).
"""
if discard < 1.0:
discard = int(discard * np.shape(self.chain)[0])
if flat:
return self.samples.flatten_logprob(discard=discard, thin=thin)
else:
return self.samples.logprob[discard::thin,:]
def get_blobs(self, flat=False, thin=1, discard=0):
"""
Get the values of the blobs at each step of the chain.
Args:
flat (bool) : If True then flatten the chain into a 1D array by combining all walkers (default is False).
thin (int) : Thinning parameter (the default value is 1).
discard (int) : Number of burn-in steps to be removed from each walker (default is 0). A float number between 0.0 and 1.0 can be used to indicate what percentage of the chain to be discarded as burnin.
Returns:
(structured) numpy array containing the values of the blobs at each step of the chain.
"""
if discard < 1.0:
discard = int(discard * np.shape(self.chain)[0])
if flat:
return self.samples.flatten_blobs(discard=discard, thin=thin)
else:
return self.samples.blobs[discard::thin,:]
@property
def chain(self):
"""
Returns the chains.
Returns:
Returns the chains of shape (nsteps, nwalkers, ndim).
"""
return self.samples.chain
@property
def act(self):
"""
Integrated Autocorrelation Time (IAT) of the Markov Chain.
Returns:
Array with the IAT of each parameter.
"""
return AutoCorrTime(self.chain[int(self.nsteps/(self.thin*2.0)):,:,:])
@property
def ess(self):
"""
Effective Sampling Size (ESS) of the Markov Chain.
Returns:
ESS
"""
return self.nwalkers * self.samples.length / np.mean(self.act)
@property
def ncall(self):
"""
Number of Log Prob calls.
Returns:
ncall
"""
return np.sum(self.neval)
@property
def efficiency(self):
"""
Effective Samples per Log Probability Evaluation.
Returns:
efficiency
"""
return self.ess / self.ncall
@property
def scale_factor(self):
"""
Scale factor values during tuning.
Returns:
scale factor mu
"""
return np.asarray(self.mus)
@property
def get_last_sample(self):
logging.warning('The ``get_last_sample`` property is deprecated and it will be removed in a future release.\n' + 'Please use the method ``get_last_sample()`` instead.')
return self.chain[-1]
def get_last_sample(self):
"""
Return the last position of the walkers.
"""
return self.chain[-1]
def get_last_log_prob(self):
"""
Return the log probability values for the last position of the walkers.
"""
return self.samples.logprob[-1]
def get_last_blobs(self):
"""
Return the blobs for the last position of the walkers.
"""
return self.samples.blobs[-1]
@property
def summary(self):
"""
Summary of the MCMC run.
"""
logging.info('Summary')
logging.info('-------')
logging.info('Number of Generations: ' + str(self.samples.length))
logging.info('Number of Parameters: ' + str(self.ndim))
logging.info('Number of Walkers: ' + str(self.nwalkers))
logging.info('Number of Tuning Generations: ' + str(len(self.mus)))
logging.info('Scale Factor: ' + str(round(self.mu,6)))
logging.info('Mean Integrated Autocorrelation Time: ' + str(round(np.mean(self.act),2)))
logging.info('Effective Sample Size: ' + str(round(self.ess,2)))
logging.info('Number of Log Probability Evaluations: ' + str(self.ncall))
logging.info('Effective Samples per Log Probability Evaluation: ' + str(round(self.efficiency,6)))
if self.thin > 1:
logging.info('Thinning rate: ' + str(self.thin))
def compute_log_prob(self, coords):
"""
Calculate the vector of log-probability for the walkers
Args:
coords: (ndarray[..., ndim]) The position vector in parameter space where the probability should be calculated.
Returns:
log_prob: A vector of log-probabilities with one entry for each walker in this sub-ensemble.
blob: The list of meta data returned by the ``log_post_fn`` at this position or ``None`` if nothing was returned.
"""
p = coords
# Check that the parameters are in physical ranges.
if np.any(np.isinf(p)):
raise ValueError("At least one parameter value was infinite")
if np.any(np.isnan(p)):
raise ValueError("At least one parameter value was NaN")
# Run the log-probability calculations (optionally in parallel).
if self.vectorize:
results = self.logprob_fn(p)
else:
results = list(self.distribute(self.logprob_fn, (p[i] for i in range(len(p)))))
try:
log_prob = np.array([float(l[0]) for l in results])
blob = [l[1:] for l in results]
except (IndexError, TypeError):
log_prob = np.array([float(l) for l in results])
blob = None
else:
# Get the blobs dtype
if self.blobs_dtype is not None:
dt = self.blobs_dtype
else:
try:
dt = np.atleast_1d(blob[0]).dtype
except ValueError:
dt = np.dtype("object")
blob = np.array(blob, dtype=dt)
# Deal with single blobs properly
shape = blob.shape[1:]
if len(shape):
axes = np.arange(len(shape))[np.array(shape) == 1] + 1
if len(axes):
blob = np.squeeze(blob, tuple(axes))
# Check for log_prob returning NaN.
if np.any(np.isnan(log_prob)):
raise ValueError("Probability function returned NaN")
return log_prob, blob
def run_mcmc(self,
start,
nsteps=1000,
thin=1,
progress=True,
log_prob0=None,
blobs0=None,
thin_by=1,
callbacks=None):
'''
Run MCMC.
Args:
start (float) : Starting point for the walkers. If ``None`` then the sampler proceeds
from the last known position of the walkers.
nsteps (int): Number of steps/generations (default is 1000).
thin (float): Thin the chain by this number (default is 1, no thinning).
progress (bool): If True (default), show progress bar.
log_prob0 (float) : Log probability values of the walkers. Default is ``None``.
blobs0 (float) : Blob value of the walkers. Default is ``None``.
thin_by (float): If you only want to store and yield every
``thin_by`` samples in the chain, set ``thin_by`` to an
integer greater than 1. When this is set, ``iterations *
thin_by`` proposals will be made.
callbacks (function): Callback function or list with multiple callback actions
(e.g. ``[callback_0, callback_1, ...]``) to be evaluated during the run.
Sampling terminates when all of the callback functions return ``True``.
This option is useful in cases in which sampling needs to terminate once
convergence is reached. Examples of callback functions can be found in the API docs.
'''
for _ in self.sample(start,
log_prob0=log_prob0,
blobs0=blobs0,
iterations=nsteps,
thin=thin,
thin_by=thin_by,
progress=progress):
if callbacks is None:
pass
else:
if isinstance(callbacks, list):
# Compute all callbacks
cb_values = [cb(self.iteration, self.get_chain(), self.get_log_prob()) for cb in callbacks]
# Keep only the non-None callbacks
cb_notnan_values = [cb for cb in cb_values if cb != None]
# Check them
if len(cb_notnan_values) < 1:
pass
elif np.all(cb_notnan_values):
break
else:
if callbacks(self.iteration, self.get_chain(), self.get_log_prob()):
break
def sample(self,
start,
log_prob0=None,
blobs0=None,
iterations=1,
thin=1,
thin_by=1,
progress=True):
'''
Advance the chain as a generator. The current iteration index of the generator is given by the ``sampler.iteration`` property.
Args:
start (float) : Starting point for the walkers.
log_prob0 (float) : Log probability values of the walkers. Default is ``None``.
blobs0 (float) : Blob value of the walkers. Default is ``None``.
iterations (int): Number of steps to generate (default is 1).
thin (float): Thin the chain by this number (default is 1, no thinning).
thin_by (float): If you only want to store and yield every
``thin_by`` samples in the chain, set ``thin_by`` to an
integer greater than 1. When this is set, ``iterations *
thin_by`` proposals will be made.
progress (bool): If True (default), show progress bar.
'''
# Define task distributer
if self.pool is None:
self.distribute = map
else:
self.distribute = self.pool.map
# Initialise ensemble of walkers
logging.info('Initialising ensemble of %d walkers...', self.nwalkers)
if start is not None:
if np.shape(start) != (self.nwalkers, self.ndim):
raise ValueError('Incompatible input dimensions! \n' +
'Please provide array of shape (nwalkers, ndim) as the starting position.')
X = np.copy(start)
if log_prob0 is None:
Z, blobs = self.compute_log_prob(X)
else:
Z = np.copy(log_prob0)
blobs = blobs0
elif (self.state_X is not None) and (self.state_Z is not None):
X = np.copy(self.state_X)
Z = np.copy(self.state_Z)
blobs = self.state_blobs
else:
raise ValueError("Cannot have `start=None` if run_mcmc has never been called before.")
if not np.all(np.isfinite(Z)):
raise ValueError('Invalid walker initial positions! \n' +
'Initialise walkers from positions of finite log probability.')
batch = list(np.arange(self.nwalkers))
# Extend saving space
self.thin = int(thin)
self.thin_by = int(thin_by)
if self.thin_by < 0:
raise ValueError('Invalid `thin_by` argument.')
elif self.thin < 0:
raise ValueError('Invalid `thin` argument.')
elif self.thin > 1 and self.thin_by == 1:
self.nsteps = int(iterations)
self.samples.extend(self.nsteps//self.thin, blobs)
self.ncheckpoint = self.thin
elif self.thin_by > 1 and self.thin == 1:
self.nsteps = int(iterations*self.thin_by)
self.samples.extend(self.nsteps//self.thin_by, blobs)
self.ncheckpoint = self.thin_by
elif self.thin == 1 and self.thin_by == 1:
self.nsteps = int(iterations)
self.samples.extend(self.nsteps, blobs)
self.ncheckpoint = 1
else:
raise ValueError('Only one of `thin` and `thin_by` arguments can be used.')
# Define Number of Log Prob Evaluations vector
self.neval = np.zeros(self.nsteps, dtype=int)
# Define tuning count
ncount = 0
# Initialise progress bar
if progress:
t = tqdm(total=self.nsteps, desc='Sampling progress : ')
# Main Loop
for i in range(self.nsteps):
# Initialise number of expansions & contractions
nexp = 0
ncon = 0
move = np.random.choice(self._moves, p=self._weights)
# Shuffle and split ensemble
if self.shuffle_ensemble:
np.random.shuffle(batch)
batch0 = batch[:int(self.nwalkers/2)]
batch1 = batch[int(self.nwalkers/2):]
sets = [[batch0,batch1],[batch1,batch0]]
# Loop over two sets
for ensembles in sets:
indeces = np.arange(int(self.nwalkers/2))
# Define active-inactive ensembles
active, inactive = ensembles
# Compute directions
directions, tune_once = move.get_direction(X[inactive], self.mu)
# Get Z0 = LogP(x0)
Z0 = Z[active] - np.random.exponential(size=int(self.nwalkers/2))
# Set Initial Interval Boundaries
L = - np.random.uniform(0.0,1.0,size=int(self.nwalkers/2))
R = L + 1.0
# Parallel stepping-out
J = np.floor(self.maxsteps * np.random.uniform(0.0,1.0,size=int(self.nwalkers/2)))
K = (self.maxsteps - 1) - J
# Initialise number of Log prob calls
ncall = 0
# Left stepping-out initialisation
mask_J = np.full(int(self.nwalkers/2),True)
Z_L = np.empty(int(self.nwalkers/2))
X_L = np.empty((int(self.nwalkers/2),self.ndim))
# Right stepping-out initialisation
mask_K = np.full(int(self.nwalkers/2),True)
Z_R = np.empty(int(self.nwalkers/2))
X_R = np.empty((int(self.nwalkers/2),self.ndim))
cnt = 0
# Stepping-Out procedure
while len(mask_J[mask_J])>0 or len(mask_K[mask_K])>0:
if len(mask_J[mask_J])>0:
cnt += 1
if len(mask_K[mask_K])>0:
cnt += 1
if cnt > self.maxiter:
raise RuntimeError('Number of expansions exceeded maximum limit! \n' +
'Make sure that the pdf is well-defined. \n' +
'Otherwise increase the maximum limit (maxiter=10^4 by default).')
for j in indeces[mask_J]:
if J[j] < 1:
mask_J[j] = False
for j in indeces[mask_K]:
if K[j] < 1:
mask_K[j] = False
X_L[mask_J] = directions[mask_J] * L[mask_J][:,np.newaxis] + X[active][mask_J]
X_R[mask_K] = directions[mask_K] * R[mask_K][:,np.newaxis] + X[active][mask_K]
if len(X_L[mask_J]) + len(X_R[mask_K]) < 1:
Z_L[mask_J] = np.array([])
Z_R[mask_K] = np.array([])
cnt -= 1
else:
Z_LR_masked, _ = self.compute_log_prob(np.concatenate([X_L[mask_J],X_R[mask_K]]))
#Z_LR_masked = np.array(list(self.distribute(self.logprob_fn, np.concatenate([X_L[mask_J],X_R[mask_K]]))))
Z_L[mask_J] = Z_LR_masked[:X_L[mask_J].shape[0]]
Z_R[mask_K] = Z_LR_masked[X_L[mask_J].shape[0]:]
for j in indeces[mask_J]:
ncall += 1
if Z0[j] < Z_L[j]:
L[j] = L[j] - 1.0
J[j] = J[j] - 1
nexp += 1
else:
mask_J[j] = False
for j in indeces[mask_K]:
ncall += 1
if Z0[j] < Z_R[j]:
R[j] = R[j] + 1.0
K[j] = K[j] - 1
nexp += 1
else:
mask_K[j] = False
# Shrinking procedure
Widths = np.empty(int(self.nwalkers/2))
Z_prime = np.empty(int(self.nwalkers/2))
X_prime = np.empty((int(self.nwalkers/2),self.ndim))
if blobs is not None:
blobs_prime = np.empty(int(self.nwalkers/2), dtype=np.dtype((blobs[0].dtype, blobs[0].shape)))
mask = np.full(int(self.nwalkers/2),True)
cnt = 0
while len(mask[mask])>0:
# Update Widths of intervals
Widths[mask] = L[mask] + np.random.uniform(0.0,1.0,size=len(mask[mask])) * (R[mask] - L[mask])
# Compute New Positions
X_prime[mask] = directions[mask] * Widths[mask][:,np.newaxis] + X[active][mask]
# Calculate LogP of New Positions
if blobs is None:
Z_prime[mask], _ = self.compute_log_prob(X_prime[mask])
#Z_prime[mask] = np.array(list(self.distribute(self.logprob_fn, X_prime[mask])))
else:
Z_prime[mask], blobs_prime[mask] = self.compute_log_prob(X_prime[mask])
# Count LogProb calls
ncall += len(mask[mask])
# Shrink slices
for j in indeces[mask]:
if Z0[j] < Z_prime[j]:
mask[j] = False
else:
if Widths[j] < 0.0:
L[j] = Widths[j]
ncon += 1
elif Widths[j] > 0.0:
R[j] = Widths[j]
ncon += 1
cnt += 1
if cnt > self.maxiter:
raise RuntimeError('Number of contractions exceeded maximum limit! \n' +
'Make sure that the pdf is well-defined. \n' +
'Otherwise increase the maximum limit (maxiter=10^4 by default).')
# Update Positions
X[active] = X_prime
Z[active] = Z_prime
if blobs is not None:
blobs[active] = blobs_prime
self.neval[i] += ncall
# Tune scale factor using Robbins-Monro optimization
if self.tune and tune_once:
self.nexps.append(nexp)
self.ncons.append(ncon)
nexp = max(1, nexp) # This is to prevent the optimizer from getting stuck
self.mu *= 2.0 * nexp / (nexp + ncon)
self.mus.append(self.mu)
if np.abs(nexp / (nexp + ncon) - 0.5) < self.tolerance:
ncount += 1
if ncount > self.patience:
self.tune = False
if self.light_mode:
self.mu *= (1.0 + nexp/self.nwalkers)
self.maxsteps = 1
# Save samples
if (i+1) % self.ncheckpoint == 0:
self.samples.save(X, Z, blobs)
# Update progress bar
if progress:
t.update()
# Update iteration counter and state variables
self.iteration = i + 1
self.state_X = np.copy(X)
self.state_Z = np.copy(Z)
self.state_blobs = blobs
# Yield current state
if (i+1) % self.ncheckpoint == 0:
yield (X, Z, blobs)
# Close progress bar
if progress:
t.close()
class sampler(EnsembleSampler):
def __init__(self, *args, **kwargs):
logging.warning('The sampler class has been deprecated. Please use the new EnsembleSampler class.')
super().__init__(*args, **kwargs) | zeus-mcmc | /zeus_mcmc-2.5.4-py3-none-any.whl/zeus/ensemble.py | ensemble.py |
import numpy as np
def cornerplot(samples,
labels=None,
weights=None,
levels=None,
span=None,
quantiles=[0.025, 0.5, 0.975],
truth=None,
color=None,
alpha=0.5,
linewidth=1.5,
fill=True,
fontsize=10,
show_titles=True,
title_fmt='.2f',
title_fontsize=12,
cut=3,
fig=None,
size=(10,10)):
r"""
Plot corner-plot of samples.
Parameters
----------
samples : array
Array of shape (nsamples, ndim) containing the samples.
labels : list
List of names of for the parameters.
weights : array
Array with weights (useful if different samples have different weights e.g. as in Nested Sampling).
levels : list
The quantiles used for plotting the smoothed 2-D distributions. If not provided, these default to 0.5, 1, 1.5, and 2-sigma contours.
quantiles : list
A list of fractional quantiles to overplot on the 1-D marginalized posteriors as titles. Default is ``[0.025, 0.5, 0.975]`` (spanning the 95%/2-sigma credible interval).
truth : array
Array specifying a point to be highlighted in the plot. It can be the true values of the parameters, the mean, median etc. By default this is None.
color : str
Matplotlib color to be used in the plot.
alpha : float
Transparency value of figure (Default is 0.5).
linewidth : float
Linewidth of plot (Default is 1.5).
fill : bool
If True (Default) the fill the 1D and 2D contours with color.
fontsize : float
Fontsize of axes labels. Default is 10.
show_titles : bool
Whether to display a title above each 1-D marginalized posterior showing the quantiles. Default is True.
title_fmt : str
Format of the titles. Default is ``.2f``.
title_fontsize : float
Fontsize of titles. Default is 12.
cut : float
Factor, multiplied by the smoothing bandwidth, that determines how far the evaluation grid extends past the extreme datapoints.
When set to 0, truncate the curve at the data limits. Default is ``cut=3``.
fig : (figure, axes)
Pre-existing Figure and Axes for the plot. Otherwise create new internally. Default is None.
size : (int, int)
Size of the plot. Default is (10, 10).
Returns
-------
Figure, Axes
The matplotlib figure and axes.
"""
import matplotlib.pyplot as plt
import seaborn as sns
ndim = samples.shape[1]
if labels is None:
labels = [r"$x_{"+str(i+1)+"}$" for i in range(ndim)]
if levels is None:
levels = list(1.0 - np.exp(-0.5 * np.arange(0.5, 2.1, 0.5) ** 2))
levels.append(1.0)
if color is None:
color = "tab:blue"
# Determine plotting bounds.
if span is None:
span = [0.999999426697 for i in range(ndim)]
span = list(span)
if len(span) != ndim:
raise ValueError("Dimension mismatch between samples and span.")
for i, _ in enumerate(span):
try:
xmin, xmax = span[i]
except:
q = [0.5 - 0.5 * span[i], 0.5 + 0.5 * span[i]]
span[i] = _quantile(samples[:,i], q, weights=weights)
idxs = np.arange(ndim**2).reshape(ndim, ndim)
tril = np.tril_indices(ndim)
triu = np.triu_indices(ndim)
lower = list(set(idxs[tril])-set(idxs[triu]))
upper = list(set(idxs[triu])-set(idxs[tril]))
if fig is None:
figure, axes = plt.subplots(ndim, ndim, figsize=size, sharex=False)
else:
figure = fig[0]
axes = fig[1]
for idx, ax in enumerate(axes.flat):
i = idx // ndim
j = idx % ndim
if idx in lower:
ax.set_ylim(span[i])
ax.yaxis.set_major_locator(plt.MaxNLocator(5))
if fill:
ax = sns.kdeplot(x=samples[:,j], y=samples[:,i], weights=weights,
fill=True, color=color,
clip=None, cut=cut,
thresh=levels[0], levels=levels,
ax=ax, alpha=alpha, linewidth=0.0,
)
ax = sns.kdeplot(x=samples[:,j], y=samples[:,i], weights=weights,
fill=False, color=color,
clip=None, cut=cut,
thresh=levels[0], levels=levels,
ax=ax, alpha=alpha, linewidth=linewidth,
)
if truth is not None:
ax.axvline(truth[j], color='k', lw=1.0)
ax.axhline(truth[i], color='k', lw=1.0)
if j == 0:
ax.set_ylabel(labels[i], fontsize=fontsize)
[l.set_rotation(45) for l in ax.get_yticklabels()]
else:
ax.yaxis.set_ticklabels([])
if i == ndim - 1:
ax.xaxis.set_major_locator(plt.MaxNLocator(5))
ax.set_xlabel(labels[j], fontsize=fontsize)
[l.set_rotation(45) for l in ax.get_xticklabels()]
else:
ax.set_xticklabels([])
elif idx in upper:
ax.set_axis_off()
else:
ax.yaxis.set_major_locator(plt.NullLocator())
if fill:
ax = sns.kdeplot(x=samples[:,j],
fill=True, color=color, weights=weights,
clip=None, cut=cut,
ax=ax, linewidth=0.0, alpha=alpha,
)
ax = sns.kdeplot(x=samples[:,j],
fill=None, color=color, weights=weights,
clip=None, cut=cut,
ax=ax, linewidth=linewidth, alpha=alpha,
)
if truth is not None:
ax.axvline(truth[j], color='k', lw=1.0)
if i == ndim - 1:
ax.set_xlabel(labels[j], fontsize=fontsize)
[l.set_rotation(45) for l in ax.get_xticklabels()]
else:
ax.set_xticklabels([])
if show_titles:
ql, qm, qh = _quantile(samples[:,i], quantiles, weights=weights)
q_minus, q_plus = qm - ql, qh - qm
fmt = "{{0:{0}}}".format(title_fmt).format
title = r"${{{0}}}_{{-{1}}}^{{+{2}}}$"
title = title.format(fmt(qm), fmt(q_minus), fmt(q_plus))
title = "{0} = {1}".format(labels[i], title)
ax.set_title(title, fontsize=title_fontsize)
ax.set_xlim(span[j])
ax.xaxis.set_major_locator(plt.MaxNLocator(5))
figure.subplots_adjust(top=0.95, right=0.95, wspace=.05, hspace=.05)
return figure, axes
def _quantile(x, q, weights=None):
"""
Compute (weighted) quantiles from an input set of samples.
Parameters
----------
x : `~numpy.ndarray` with shape (nsamps,)
Input samples.
q : `~numpy.ndarray` with shape (nquantiles,)
The list of quantiles to compute from `[0., 1.]`.
weights : `~numpy.ndarray` with shape (nsamps,), optional
The associated weight from each sample.
Returns
-------
quantiles : `~numpy.ndarray` with shape (nquantiles,)
The weighted sample quantiles computed at `q`.
"""
# Initial check.
x = np.atleast_1d(x)
q = np.atleast_1d(q)
# Quantile check.
if np.any(q < 0.0) or np.any(q > 1.0):
raise ValueError("Quantiles must be between 0. and 1.")
if weights is None:
# If no weights provided, this simply calls `np.percentile`.
return np.percentile(x, list(100.0 * q))
else:
# If weights are provided, compute the weighted quantiles.
weights = np.atleast_1d(weights)
if len(x) != len(weights):
raise ValueError("Dimension mismatch: len(weights) != len(x).")
idx = np.argsort(x) # sort samples
sw = weights[idx] # sort weights
cdf = np.cumsum(sw)[:-1] # compute CDF
cdf /= cdf[-1] # normalize CDF
cdf = np.append(0, cdf) # ensure proper span
quantiles = np.interp(q, cdf, x[idx]).tolist()
return quantiles | zeus-mcmc | /zeus_mcmc-2.5.4-py3-none-any.whl/zeus/plotting.py | plotting.py |
import numpy as np
from .autocorr import AutoCorrTime
try:
import h5py
except ImportError:
h5py = None
class AutocorrelationCallback:
"""
The Autocorrelation Time Callback class checks the integrated autocorrelation time (IAT)
of the chain during the run and terminates sampling if the rate of change of IAT is below
some threshold and the length of the chain is greater than some multiple of the IAT estimate.
Args:
ncheck (int): The number of steps after which the IAT is estimated and the tests are performed.
Default is ``ncheck=100``.
dact (float): Threshold of the rate of change of IAT. Sampling terminates once this threshold is
reached along with the other criteria. Default is ``dact=0.01``.
nact (float): Minimum lenght of the chain as a mutiple of the IAT. Sampling terminates once this threshold is
reached along with the other criteria. Default is ``nact=10``.
discard (float): Percentage of chain to discard prior to estimating the IAT. Default is ``discard=0.5``.
trigger (bool): If ``True`` (default) then terminatate sampling once converged, else just monitor statistics.
method (str): Method to use for the estimation of the IAT. Available options are ``mk`` (Default), ``dfm``, and ``gw``.
"""
def __init__(self, ncheck=100, dact=0.01, nact=10, discard=0.5, trigger=True, method='mk'):
self.ncheck = ncheck
self.dact = dact
self.nact = nact
self.discard = discard
self.trigger = trigger
self.method = method
self.estimates = []
self.old_tau = np.inf
def __call__(self, i, x, y):
"""
Method that calls the callback function.
Args:
i (int): Current iteration of the run.
x (array): Numpy array containing the chain elements up to iteration i for every walker.
y (array): Numpy array containing the log-probability values of all chain elements up to
iteration i for every walker.
Returns:
True if the criteria are satisfied and sampling terminates or False if the criteria are
not satisfied and sampling continues.
"""
converged = False
if i % self.ncheck == 0:
tau = np.mean(AutoCorrTime(x[int(i * self.discard):], method=self.method))
self.estimates.append(tau)
# Check convergence
converged = tau * self.nact < i
converged &= np.abs(self.old_tau - tau) / tau < self.dact
self.old_tau = tau
if self.trigger:
return converged
else:
return None
class SplitRCallback:
"""
The Split-R Callback class checks the Gelman-Rubin criterion during the run by splitting the chain
into multiple parts and terminates sampling if the Split-R coefficient is close to unity.
Args:
ncheck (int): The number of steps after which the Gelman-Rubin statistics is estimated and the tests are performed.
Default is ``ncheck=100``.
epsilon (float): Threshold of the Split-R value. Sampling terminates when ``|R-1|<epsilon``. Default is ``0.05``
nsplits (int): Split each chain into this many pieces. Default is ``2``.
discard (float): Percentage of chain to discard prior to estimating the IAT. Default is ``discard=0.5``.
trigger (bool): If ``True`` (default) then terminatate sampling once converged, else just monitor statistics.
"""
def __init__(self, ncheck=100, epsilon=0.05, nsplits=2, discard=0.5, trigger=True):
self.ncheck = ncheck
self.epsilon = epsilon
self.nsplits = nsplits
self.trigger = trigger
self.discard = discard
self.estimates = []
def __call__(self, i, x, y):
"""
Method that calls the callback function.
Args:
i (int): Current iteration of the run.
x (array): Numpy array containing the chain elements up to iteration i for every walker.
y (array): Numpy array containing the log-probability values of all chain elements up to
iteration i for every walker.
Returns:
True if the criteria are satisfied and sampling terminates or False if the criteria are
not satisfied and sampling continues.
"""
converged = False
if i % self.ncheck == 0:
ndim = x.shape[-1]
samples = np.array_split(x[int(i * self.discard):], self.nsplits)
mean = []
var = []
for sample in samples:
mean.append(np.mean(sample.reshape(-1,ndim),axis=0))
var.append(np.var(sample.reshape(-1,ndim),axis=0))
N = len(sample.reshape(-1,ndim))
Rhat = np.mean(self.estimate_Rhat(mean, var, N))
self.estimates.append(Rhat)
# Check convergence
converged = (Rhat - 1.0) <= self.epsilon
if self.trigger:
return converged
else:
return None
def estimate_Rhat(self, means, vars, N):
_means = [item for sublist in means for item in sublist]
_vars = [item for sublist in vars for item in sublist]
# Between chain variance
B = N * np.var(_means, ddof=1, axis=0)
# Within chain variance
W = np.mean(_vars)
# Weighted variance
Var_hat = (1.0 - 1.0 / N) * W + B / N
# Return R_hat statistic
R_hat = np.sqrt(Var_hat / W)
return R_hat
class MinIterCallback:
"""
The Minimum Iteration Callback class ensure that sampling does not terminate early prior to a
prespecified number of steps.
Args:
nmin (int): The number of minimum steps before other callbacks can terminate the run.
"""
def __init__(self, nmin=1000):
self.nmin = nmin
def __call__(self, i, x, y):
"""
Method that calls the callback function.
Args:
i (int): Current iteration of the run.
x (array): Numpy array containing the chain elements up to iteration i for every walker.
y (array): Numpy array containing the log-probability values of all chain elements up to
iteration i for every walker.
Returns:
True if the criteria are satisfied and sampling terminates or False if the criteria are
not satisfied and sampling continues.
"""
if i >= self.nmin:
return True
else:
return False
class ParallelSplitRCallback:
"""
The Parallel Split-R Callback class extends the functionality of the Split-R Callback to more than one CPUs by
checking the Gelman-Rubin criterion during the run by splitting the chain into multiple parts and combining different
parts from parallel chains and terminates sampling if the Split-R coefficient is close to unity.
Args:
ncheck (int): The number of steps after which the Gelman-Rubin statistics is estimated and the tests are performed.
Default is ``ncheck=100``.
epsilon (float): Threshold of the Split-R value. Sampling terminates when ``|R-1|<epsilon``. Default is ``0.05``
nsplits (int): Split each chain into this many pieces. Default is ``2``.
discard (float): Percentage of chain to discard prior to estimating the IAT. Default is ``discard=0.5``.
trigger (bool): If ``True`` (default) then terminatate sampling once converged, else just monitor statistics.
chainmanager (ChainManager instance): The ``ChainManager`` used to parallelise the sampling process.
"""
def __init__(self, ncheck=100, epsilon=0.01, nsplits=2, discard=0.5, trigger=True, chainmanager=None):
self.ncheck = ncheck
self.epsilon = epsilon
self.nsplits = nsplits
self.trigger = trigger
self.discard = discard
self.estimates = []
if chainmanager is None:
raise ValueError("Please provide a ChainManager instance for this method to work.")
self.cm = chainmanager
def __call__(self, i, x, y):
"""
Method that calls the callback function.
Args:
i (int): Current iteration of the run.
x (array): Numpy array containing the chain elements up to iteration i for every walker.
y (array): Numpy array containing the log-probability values of all chain elements up to
iteration i for every walker.
Returns:
True if the criteria are satisfied and sampling terminates or False if the criteria are
not satisfied and sampling continues.
"""
converged = False
if i % self.ncheck == 0:
ndim = x.shape[-1]
samples = np.array_split(x[int(i * self.discard):], self.nsplits)
mean = []
var = []
for sample in samples:
mean.append(np.mean(sample.reshape(-1,ndim),axis=0))
var.append(np.var(sample.reshape(-1,ndim),axis=0))
N = len(sample.reshape(-1,ndim))
mean_all = self.cm.gather(mean, root=0)
var_all = self.cm.gather(var, root=0)
N_all = np.sum(self.cm.gather(N, root=0))
if self.cm.get_rank == 0:
Rhat = np.mean(self.estimate_Rhat(mean_all, var_all, N_all))
self.estimates.append(Rhat)
# Check convergence
converged = (Rhat - 1.0) <= self.epsilon
converged = self.cm.bcast(converged, root=0)
self.estimates = self.cm.bcast(self.estimates, root=0)
if self.trigger:
return converged
else:
return None
def estimate_Rhat(self, means, vars, N):
_means = [item for sublist in means for item in sublist]
_vars = [item for sublist in vars for item in sublist]
# Between chain variance
B = N * np.var(_means, ddof=1, axis=0)
# Within chain variance
W = np.mean(_vars)
# Weighted variance
Var_hat = (1.0 - 1.0 / N) * W + B / N
# Return R_hat statistic
R_hat = np.sqrt(Var_hat / W)
return R_hat
class SaveProgressCallback:
"""
The Save Progress Callback class iteratively saves the collected samples and log-probability values to a HDF5 file.
Args:
filename (str): Name of the directory and file to save samples. Default is ``./chains.h5``.
ncheck (int): The number of steps after which the samples are saved. Default is ``ncheck=100``.
"""
def __init__(self, filename='./chains.h5', ncheck=100):
if h5py is None:
raise ImportError("You must install 'h5py' to use the SaveProgressCallback")
self.directory = filename
self.initialised = False
self.ncheck = ncheck
def __call__(self, i, x, y):
"""
Method that calls the callback function.
Args:
i (int): Current iteration of the run.
x (array): Numpy array containing the chain elements up to iteration i for every walker.
y (array): Numpy array containing the log-probability values of all chain elements up to
iteration i for every walker.
Returns:
True if the criteria are satisfied and sampling terminates or False if the criteria are
not satisfied and sampling continues.
"""
if i % self.ncheck == 0:
if self.initialised:
self.__save(x[i-self.ncheck:], y[i-self.ncheck:])
else:
self.__initialize_and_save(x[i-self.ncheck:], y[i-self.ncheck:])
return None
def __save(self, x, y):
with h5py.File(self.directory, 'a') as hf:
hf['samples'].resize((hf['samples'].shape[0] + x.shape[0]), axis = 0)
hf['samples'][-x.shape[0]:] = x
hf['logprob'].resize((hf['logprob'].shape[0] + y.shape[0]), axis = 0)
hf['logprob'][-y.shape[0]:] = y
def __initialize_and_save(self, x, y):
with h5py.File(self.directory, 'w') as hf:
hf.create_dataset('samples', data=x, compression="gzip", chunks=True, maxshape=(None,)+x.shape[1:])
hf.create_dataset('logprob', data=y, compression="gzip", chunks=True, maxshape=(None,)+y.shape[1:])
self.initialised = True | zeus-mcmc | /zeus_mcmc-2.5.4-py3-none-any.whl/zeus/callbacks.py | callbacks.py |
<div align="center">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="docs/assets/img/logo_dark.svg">
<source media="(prefers-color-scheme: light)" srcset="docs/assets/img/logo_light.svg">
<img alt="Zeus logo" width="55%" src="docs/assets/img/logo_dark.svg">
</picture>
<h1>Deep Learning Energy Measurement and Optimization</h1>
</div>
[](https://www.usenix.org/conference/nsdi23/presentation/you)
[](https://hub.docker.com/r/symbioticlab/zeus)
[](https://join.slack.com/t/zeus-ml/shared_invite/zt-1najba5mb-WExy7zoNTyaZZfTlUWoLLg)
[](https://github.com/SymbioticLab/Zeus/actions/workflows/deploy_homepage.yaml)
[](/LICENSE)
---
**Project News** ⚡
- \[2023/07\] [`ZeusMonitor`](https://ml.energy/zeus/reference/monitor/#zeus.monitor.ZeusMonitor) was used to profile GPU time and energy consumption for the [ML.ENERGY leaderboard & Colosseum](https://ml.energy/leaderboard).
- \[2023/03\] [Chase](https://symbioticlab.org/publications/files/chase:ccai23/chase-ccai23.pdf), an automatic carbon optimization framework for DNN training, will appear at ICLR'23 workshop.
- \[2022/11\] [Carbon-Aware Zeus](https://taikai.network/gsf/hackathons/carbonhack22/projects/cl95qxjpa70555701uhg96r0ek6/idea) won the **second overall best solution award** at Carbon Hack 22.
---
Zeus is a framework for (1) measuring GPU energy consumption and (2) optimizing energy and time for DNN training.
### Measuring GPU energy
```python
from zeus.monitor import ZeusMonitor
monitor = ZeusMonitor(gpu_indices=[0,1,2,3])
monitor.begin_window("heavy computation")
# Four GPUs consuming energy like crazy!
measurement = monitor.end_window("heavy computation")
print(f"Energy: {measurement.total_energy} J")
print(f"Time : {measurement.time} s")
```
### Finding the optimal GPU power limit
Zeus silently profiles different power limits during training and converges to the optimal one.
```python
from zeus.monitor import ZeusMonitor
from zeus.optimizer import GlobalPowerLimitOptimizer
monitor = ZeusMonitor(gpu_indices=[0,1,2,3])
plo = GlobalPowerLimitOptimizer(monitor)
plo.on_epoch_begin()
for x, y in train_dataloader:
plo.on_step_begin()
# Learn from x and y!
plo.on_step_end()
plo.on_epoch_end()
```
### CLI power and energy monitor
```console
$ python -m zeus.monitor power
[2023-08-22 22:39:59,787] [PowerMonitor](power.py:134) Monitoring power usage of GPUs [0, 1, 2, 3]
2023-08-22 22:40:00.800576
{'GPU0': 66.176, 'GPU1': 68.792, 'GPU2': 66.898, 'GPU3': 67.53}
2023-08-22 22:40:01.842590
{'GPU0': 66.078, 'GPU1': 68.595, 'GPU2': 66.996, 'GPU3': 67.138}
2023-08-22 22:40:02.845734
{'GPU0': 66.078, 'GPU1': 68.693, 'GPU2': 66.898, 'GPU3': 67.236}
2023-08-22 22:40:03.848818
{'GPU0': 66.177, 'GPU1': 68.675, 'GPU2': 67.094, 'GPU3': 66.926}
^C
Total time (s): 4.421529293060303
Total energy (J):
{'GPU0': 198.52566362297537, 'GPU1': 206.22215216255188, 'GPU2': 201.08565518283845, 'GPU3': 201.79834523367884}
```
```console
$ python -m zeus.monitor energy
[2023-08-22 22:44:45,106] [ZeusMonitor](energy.py:157) Monitoring GPU [0, 1, 2, 3].
[2023-08-22 22:44:46,210] [zeus.util.framework](framework.py:38) PyTorch with CUDA support is available.
[2023-08-22 22:44:46,760] [ZeusMonitor](energy.py:329) Measurement window 'zeus.monitor.energy' started.
^C[2023-08-22 22:44:50,205] [ZeusMonitor](energy.py:329) Measurement window 'zeus.monitor.energy' ended.
Total energy (J):
Measurement(time=3.4480526447296143, energy={0: 224.2969999909401, 1: 232.83799999952316, 2: 233.3100000023842, 3: 234.53700000047684})
```
Please refer to our NSDI’23 [paper](https://www.usenix.org/conference/nsdi23/presentation/you) and [slides](https://www.usenix.org/system/files/nsdi23_slides_chung.pdf) for details.
Checkout [Overview](https://ml.energy/zeus/overview/) for a summary.
Zeus is part of [The ML.ENERGY Initiative](https://ml.energy).
## Repository Organization
```
.
├── zeus/ # ⚡ Zeus Python package
│ ├── optimizer/ # - GPU energy and time optimizers
│ ├── run/ # - Tools for running Zeus on real training jobs
│ ├── policy/ # - Optimization policies and extension interfaces
│ ├── util/ # - Utility functions and classes
│ ├── monitor.py # - `ZeusMonitor`: Measure GPU time and energy of any code block
│ ├── controller.py # - Tools for controlling the flow of training
│ ├── callback.py # - Base class for Hugging Face-like training callbacks.
│ ├── simulate.py # - Tools for trace-driven simulation
│ ├── analyze.py # - Analysis functions for power logs
│ └── job.py # - Class for job specification
│
├── zeus_monitor/ # 🔌 GPU power monitor
│ ├── zemo/ # - A header-only library for querying NVML
│ └── main.cpp # - Source code of the power monitor
│
├── examples/ # 🛠️ Examples of integrating Zeus
│
├── capriccio/ # 🌊 A drifting sentiment analysis dataset
│
└── trace/ # 🗃️ Train and power traces for various GPUs and DNNs
```
## Getting Started
Refer to [Getting started](https://ml.energy/zeus/getting_started) for complete instructions on environment setup, installation, and integration.
### Docker image
We provide a Docker image fully equipped with all dependencies and environments.
The only command you need is:
```sh
docker run -it \
--gpus all `# Mount all GPUs` \
--cap-add SYS_ADMIN `# Needed to change the power limit of the GPU` \
--ipc host `# PyTorch DataLoader workers need enough shm` \
symbioticlab/zeus:latest \
bash
```
Refer to [Environment setup](https://ml.energy/zeus/getting_started/environment/) for details.
### Examples
We provide working examples for integrating and running Zeus in the `examples/` directory.
## Extending Zeus
You can easily implement custom policies for batch size and power limit optimization and plug it into Zeus.
Refer to [Extending Zeus](https://ml.energy/zeus/extend/) for details.
## Carbon-Aware Zeus
The use of GPUs for training DNNs results in high carbon emissions and energy consumption. Building on top of Zeus, we introduce *Chase* -- a carbon-aware solution. *Chase* dynamically controls the energy consumption of GPUs; adapts to shifts in carbon intensity during DNN training, reducing carbon footprint with minimal compromises on training performance. To proactively adapt to shifting carbon intensity, a lightweight machine learning algorithm is used to forecast the carbon intensity of the upcoming time frame. For more details on Chase, please refer to our [paper](https://symbioticlab.org/publications/files/chase:ccai23/chase-ccai23.pdf) and the [chase branch](https://github.com/SymbioticLab/Zeus/tree/chase).
## Citation
```bibtex
@inproceedings{zeus-nsdi23,
title = {Zeus: Understanding and Optimizing {GPU} Energy Consumption of {DNN} Training},
author = {Jie You and Jae-Won Chung and Mosharaf Chowdhury},
booktitle = {USENIX NSDI},
year = {2023}
}
```
## Contact
Jae-Won Chung ([email protected])
| zeus-ml | /zeus-ml-0.7.0.tar.gz/zeus-ml-0.7.0/README.md | README.md |
import argparse
import os
import random
import time
from enum import Enum
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.distributed as dist
import torch.optim
from torch.optim.lr_scheduler import StepLR
import torch.utils.data
from torch.utils.data import DataLoader
import torch.utils.data.distributed
import torchvision.transforms as transforms
import torchvision.datasets as datasets
import torchvision.models as models
# ZEUS
from zeus.monitor import ZeusMonitor
from zeus.optimizer import GlobalPowerLimitOptimizer
from zeus.optimizer.power_limit import MaxSlowdownConstraint
from zeus.util.env import get_env
def parse_args() -> argparse.Namespace:
"""Parse command line arguments."""
# List choices of models
model_names = sorted(
name
for name in models.__dict__
if name.islower()
and not name.startswith("__")
and callable(models.__dict__[name])
)
parser = argparse.ArgumentParser(description="PyTorch ImageNet Training")
parser.add_argument("data", metavar="DIR", help="Path to the ImageNet directory")
parser.add_argument(
"-a",
"--arch",
metavar="ARCH",
default="resnet18",
choices=model_names,
help="model architecture: " + " | ".join(model_names) + " (default: resnet18)",
)
parser.add_argument(
"-j",
"--workers",
default=4,
type=int,
metavar="N",
help="number of data loading workers (default: 4)",
)
parser.add_argument(
"--epochs",
default=90,
type=int,
metavar="N",
help="number of total epochs to run",
)
parser.add_argument(
"-b",
"--batch_size",
default=256,
type=int,
metavar="N",
help="mini-batch size (default: 256)",
)
parser.add_argument(
"--lr",
"--learning_rate",
default=0.1,
type=float,
metavar="LR",
help="initial learning rate",
dest="lr",
)
parser.add_argument(
"--momentum", default=0.9, type=float, metavar="M", help="momentum"
)
parser.add_argument(
"--wd",
"--weight_decay",
default=1e-4,
type=float,
metavar="W",
help="weight decay (default: 1e-4)",
dest="weight_decay",
)
parser.add_argument(
"-p",
"--print_freq",
default=10,
type=int,
metavar="N",
help="print frequency (default: 10)",
)
parser.add_argument(
"--seed", default=None, type=int, help="seed for initializing training. "
)
parser.add_argument(
"--gpu", default=0, type=int, metavar="N", help="GPU id to use (default: 0)"
)
return parser.parse_args()
def main():
"""Main function that prepares values and spawns/calls the worker function."""
args = parse_args()
if args.seed is not None:
random.seed(args.seed)
torch.manual_seed(args.seed)
cudnn.deterministic = True
print("=> creating model '{}'".format(args.arch))
model = models.__dict__[args.arch]()
torch.cuda.set_device(args.gpu)
model.cuda(args.gpu)
criterion = nn.CrossEntropyLoss().cuda(args.gpu)
optimizer = torch.optim.SGD(
model.parameters(),
args.lr,
momentum=args.momentum,
weight_decay=args.weight_decay,
)
scheduler = StepLR(optimizer, step_size=30, gamma=0.1)
traindir = os.path.join(args.data, "train")
valdir = os.path.join(args.data, "val")
normalize = transforms.Normalize(
mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]
)
train_dataset = datasets.ImageFolder(
traindir,
transforms.Compose(
[
transforms.RandomResizedCrop(224),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
normalize,
]
),
)
val_dataset = datasets.ImageFolder(
valdir,
transforms.Compose(
[
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
normalize,
]
),
)
train_loader = DataLoader(
train_dataset,
batch_size=args.batch_size,
shuffle=True,
num_workers=args.workers,
pin_memory=True,
)
val_loader = DataLoader(
val_dataset,
batch_size=args.batch_size,
shuffle=False,
num_workers=args.workers,
pin_memory=True,
)
################################## The important part #####################################
# ZeusMonitor is used to profile the time and energy consumption of the GPU.
monitor = ZeusMonitor(gpu_indices=[args.gpu])
# GlobalPowerLimitOptimizer profiles each power limit and selects the best one.
# This is the power limit optimizer that's in the Zeus paper.
plo = GlobalPowerLimitOptimizer(
monitor=monitor,
optimum_selector=MaxSlowdownConstraint(
factor=get_env("ZEUS_MAX_SLOWDOWN", float, 1.1),
),
warmup_steps=10,
profile_steps=40,
pl_step=25,
)
for epoch in range(args.epochs):
plo.on_epoch_begin()
train(train_loader, model, criterion, optimizer, epoch, args, plo)
plo.on_epoch_end()
acc1 = validate(val_loader, model, criterion, args)
print(f"Top-1 accuracy: {acc1}")
scheduler.step()
################################## The important part #####################################
def train(
train_loader, model, criterion, optimizer, epoch, args, power_limit_optimizer
):
batch_time = AverageMeter("Time", ":6.3f")
data_time = AverageMeter("Data", ":6.3f")
losses = AverageMeter("Loss", ":.4e")
top1 = AverageMeter("Acc@1", ":6.2f")
top5 = AverageMeter("Acc@5", ":6.2f")
progress = ProgressMeter(
len(train_loader),
[batch_time, data_time, losses, top1, top5],
prefix="Epoch: [{}]".format(epoch),
)
# switch to train mode
model.train()
end = time.time()
for i, (images, target) in enumerate(train_loader):
power_limit_optimizer.on_step_begin() # Mark the beginning of one training step.
# Load data to GPU
images = images.cuda(args.gpu, non_blocking=True)
target = target.cuda(args.gpu, non_blocking=True)
# measure data loading time
data_time.update(time.time() - end)
# compute output
output = model(images)
loss = criterion(output, target)
# measure accuracy and record loss
acc1, acc5 = accuracy(output, target, topk=(1, 5))
losses.update(loss.item(), images.size(0))
top1.update(acc1[0], images.size(0))
top5.update(acc5[0], images.size(0))
# compute gradient and do SGD step
optimizer.zero_grad()
loss.backward()
optimizer.step()
power_limit_optimizer.on_step_end() # Mark the end of one training step.
# measure elapsed time
batch_time.update(time.time() - end)
end = time.time()
if i % args.print_freq == 0:
progress.display(i + 1)
def validate(val_loader, model, criterion, args):
batch_time = AverageMeter("Time", ":6.3f", Summary.NONE)
losses = AverageMeter("Loss", ":.4e", Summary.NONE)
top1 = AverageMeter("Acc@1", ":6.2f", Summary.AVERAGE)
top5 = AverageMeter("Acc@5", ":6.2f", Summary.AVERAGE)
progress = ProgressMeter(
len(val_loader),
[batch_time, losses, top1, top5],
prefix="Test: ",
)
# switch to evaluate mode
model.eval()
with torch.no_grad():
end = time.time()
for i, (images, target) in enumerate(val_loader):
# Load data to GPU
images = images.cuda(args.gpu, non_blocking=True)
target = target.cuda(args.gpu, non_blocking=True)
# compute output
output = model(images)
loss = criterion(output, target)
# measure accuracy and record loss
acc1, acc5 = accuracy(output, target, topk=(1, 5))
losses.update(loss.item(), images.size(0))
top1.update(acc1[0], images.size(0))
top5.update(acc5[0], images.size(0))
# measure elapsed time
batch_time.update(time.time() - end)
end = time.time()
if i % args.print_freq == 0:
progress.display(i + 1)
progress.display_summary()
return top1.avg
class Summary(Enum):
NONE = 0
AVERAGE = 1
SUM = 2
COUNT = 3
class AverageMeter(object):
"""Computes and stores the average and current value"""
def __init__(self, name, fmt=":f", summary_type=Summary.AVERAGE):
self.name = name
self.fmt = fmt
self.summary_type = summary_type
self.reset()
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def update(self, val, n=1):
self.val = val
self.sum += val * n
self.count += n
self.avg = self.sum / self.count
# DATA PARALLEL
def all_reduce(self):
device = "cuda" if torch.cuda.is_available() else "cpu"
total = torch.tensor([self.sum, self.count], dtype=torch.float32, device=device)
dist.all_reduce(total, dist.ReduceOp.SUM, async_op=False)
self.sum, self.count = total.tolist()
self.avg = self.sum / self.count
def __str__(self):
fmtstr = "{name} {val" + self.fmt + "} ({avg" + self.fmt + "})"
return fmtstr.format(**self.__dict__)
def summary(self):
fmtstr = ""
if self.summary_type is Summary.NONE:
fmtstr = ""
elif self.summary_type is Summary.AVERAGE:
fmtstr = "{name} {avg:.3f}"
elif self.summary_type is Summary.SUM:
fmtstr = "{name} {sum:.3f}"
elif self.summary_type is Summary.COUNT:
fmtstr = "{name} {count:.3f}"
else:
raise ValueError("invalid summary type %r" % self.summary_type)
return fmtstr.format(**self.__dict__)
class ProgressMeter(object):
def __init__(self, num_batches, meters, prefix=""):
self.batch_fmtstr = self._get_batch_fmtstr(num_batches)
self.meters = meters
self.prefix = prefix
def display(self, batch):
entries = [self.prefix + self.batch_fmtstr.format(batch)]
entries += [str(meter) for meter in self.meters]
print("\t".join(entries))
def display_summary(self):
entries = [" *"]
entries += [meter.summary() for meter in self.meters]
print(" ".join(entries))
def _get_batch_fmtstr(self, num_batches):
num_digits = len(str(num_batches // 1))
fmt = "{:" + str(num_digits) + "d}"
return "[" + fmt + "/" + fmt.format(num_batches) + "]"
def accuracy(output, target, topk=(1,)):
"""Computes the accuracy over the k top predictions for the specified values of k"""
with torch.no_grad():
maxk = max(topk)
batch_size = target.size(0)
_, pred = output.topk(maxk, 1, True, True)
pred = pred.t()
correct = pred.eq(target.view(1, -1).expand_as(pred))
res = []
for k in topk:
correct_k = correct[:k].reshape(-1).float().sum(0, keepdim=True)
res.append(correct_k.mul_(100.0 / batch_size))
return res
if __name__ == "__main__":
main() | zeus-ml | /zeus-ml-0.7.0.tar.gz/zeus-ml-0.7.0/examples/imagenet/train_single.py | train_single.py |
import argparse
import os
import random
import time
from enum import Enum
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.distributed as dist
import torch.optim
from torch.optim.lr_scheduler import StepLR
import torch.utils.data
from torch.utils.data import DataLoader
import torch.utils.data.distributed
import torchvision.transforms as transforms
import torchvision.datasets as datasets
import torchvision.models as models
from torch.utils.data import Subset
# ZEUS
from zeus.monitor import ZeusMonitor
from zeus.optimizer import GlobalPowerLimitOptimizer
from zeus.optimizer.power_limit import MaxSlowdownConstraint
from zeus.util.env import get_env
from zeus.callback import Callback, CallbackSet
def parse_args() -> argparse.Namespace:
"""Parse command line arguments."""
# List choices of models
model_names = sorted(
name
for name in models.__dict__
if name.islower()
and not name.startswith("__")
and callable(models.__dict__[name])
)
parser = argparse.ArgumentParser(description="PyTorch ImageNet Training")
parser.add_argument("data", metavar="DIR", help="Path to the ImageNet directory")
parser.add_argument(
"-a",
"--arch",
metavar="ARCH",
default="resnet18",
choices=model_names,
help="model architecture: " + " | ".join(model_names) + " (default: resnet18)",
)
parser.add_argument(
"-j",
"--workers",
default=4,
type=int,
metavar="N",
help="number of data loading workers (default: 4)",
)
parser.add_argument(
"--epochs",
default=90,
type=int,
metavar="N",
help="number of total epochs to run",
)
parser.add_argument(
"-b",
"--batch_size",
default=256,
type=int,
metavar="N",
help="global mini-batch size (default: 256)",
)
parser.add_argument(
"--lr",
"--learning_rate",
default=0.1,
type=float,
metavar="LR",
help="initial learning rate",
dest="lr",
)
parser.add_argument(
"--momentum", default=0.9, type=float, metavar="M", help="momentum"
)
parser.add_argument(
"--wd",
"--weight_decay",
default=1e-4,
type=float,
metavar="W",
help="weight decay (default: 1e-4)",
dest="weight_decay",
)
parser.add_argument(
"-p",
"--print_freq",
default=10,
type=int,
metavar="N",
help="print frequency (default: 10)",
)
parser.add_argument(
"--seed", default=None, type=int, help="seed for initializing training. "
)
return parser.parse_args()
def main():
"""Main function that prepares values and spawns/calls the worker function."""
args = parse_args()
if args.seed is not None:
random.seed(args.seed)
torch.manual_seed(args.seed)
cudnn.deterministic = True
args.gpu = int(os.environ["LOCAL_RANK"])
args.local_world_size = int(os.environ["LOCAL_WORLD_SIZE"])
if args.batch_size % args.local_world_size != 0:
raise ValueError(
"The global batch size should be divisible by the number of GPUs."
)
dist.init_process_group(backend="nccl")
print("=> creating model '{}'".format(args.arch))
model = models.__dict__[args.arch]()
torch.cuda.set_device(args.gpu)
model.cuda(args.gpu)
# When using a single GPU per process and per
# DistributedDataParallel, we need to divide the batch size
# ourselves based on the total number of GPUs of the current node.
args.batch_size = args.batch_size // args.local_world_size
model = torch.nn.parallel.DistributedDataParallel(
model, device_ids=[args.gpu], output_device=args.gpu
)
# define loss function (criterion), optimizer, and learning rate scheduler
criterion = nn.CrossEntropyLoss().cuda(args.gpu)
optimizer = torch.optim.SGD(
model.parameters(),
args.lr,
momentum=args.momentum,
weight_decay=args.weight_decay,
)
scheduler = StepLR(optimizer, step_size=30, gamma=0.1)
traindir = os.path.join(args.data, "train")
valdir = os.path.join(args.data, "val")
normalize = transforms.Normalize(
mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]
)
train_dataset = datasets.ImageFolder(
traindir,
transforms.Compose(
[
transforms.RandomResizedCrop(224),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
normalize,
]
),
)
val_dataset = datasets.ImageFolder(
valdir,
transforms.Compose(
[
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
normalize,
]
),
)
train_sampler = torch.utils.data.distributed.DistributedSampler(train_dataset)
val_sampler = torch.utils.data.distributed.DistributedSampler(
val_dataset, shuffle=False, drop_last=True
)
train_loader = DataLoader(
train_dataset,
batch_size=args.batch_size,
num_workers=args.workers,
pin_memory=True,
sampler=train_sampler,
)
val_loader = DataLoader(
val_dataset,
batch_size=args.batch_size,
num_workers=args.workers,
pin_memory=True,
sampler=val_sampler,
)
# The rank 0 process will monitor and optimize the power limit of all GPUs.
if args.gpu == 0:
callback_set: list[Callback] = [
GlobalPowerLimitOptimizer(
monitor=ZeusMonitor(gpu_indices=None), # All visible GPUs.
optimum_selector=MaxSlowdownConstraint(
factor=get_env("ZEUS_MAX_SLOWDOWN", float, 1.1),
),
warmup_steps=10,
profile_steps=40,
pl_step=25,
)
]
else:
callback_set = []
callbacks = CallbackSet(callback_set)
for epoch in range(args.epochs):
train_sampler.set_epoch(epoch)
callbacks.on_epoch_begin()
train(train_loader, model, criterion, optimizer, epoch, args, callbacks)
callbacks.on_epoch_end()
acc1 = validate(val_loader, model, criterion, args)
print(f"Top-1 accuracy: {acc1}")
scheduler.step()
def train(train_loader, model, criterion, optimizer, epoch, args, callbacks):
batch_time = AverageMeter("Time", ":6.3f")
data_time = AverageMeter("Data", ":6.3f")
losses = AverageMeter("Loss", ":.4e")
top1 = AverageMeter("Acc@1", ":6.2f")
top5 = AverageMeter("Acc@5", ":6.2f")
progress = ProgressMeter(
len(train_loader),
[batch_time, data_time, losses, top1, top5],
prefix="Epoch: [{}]".format(epoch),
)
# switch to train mode
model.train()
end = time.time()
for i, (images, target) in enumerate(train_loader):
callbacks.on_step_begin() # Mark the beginning of the training step.
# Load data to GPU
images = images.cuda(args.gpu)
target = target.cuda(args.gpu)
# measure data loading time
data_time.update(time.time() - end)
# compute output
output = model(images)
loss = criterion(output, target)
# measure accuracy and record loss
acc1, acc5 = accuracy(output, target, topk=(1, 5))
losses.update(loss.item(), images.size(0))
top1.update(acc1[0], images.size(0))
top5.update(acc5[0], images.size(0))
# compute gradient and do SGD step
optimizer.zero_grad()
loss.backward()
optimizer.step()
# measure elapsed time
batch_time.update(time.time() - end)
end = time.time()
callbacks.on_step_end()
if i % args.print_freq == 0:
progress.display(i + 1)
def validate(val_loader, model, criterion, args):
batch_time = AverageMeter("Time", ":6.3f", Summary.NONE)
losses = AverageMeter("Loss", ":.4e", Summary.NONE)
top1 = AverageMeter("Acc@1", ":6.2f", Summary.AVERAGE)
top5 = AverageMeter("Acc@5", ":6.2f", Summary.AVERAGE)
progress = ProgressMeter(
len(val_loader)
+ (len(val_loader.sampler) * args.local_world_size < len(val_loader.dataset)),
[batch_time, losses, top1, top5],
prefix="Test: ",
)
# switch to evaluate mode
model.eval()
with torch.no_grad():
end = time.time()
for i, (images, target) in enumerate(val_loader):
# Load data to GPU
images = images.cuda(args.gpu, non_blocking=True)
target = target.cuda(args.gpu, non_blocking=True)
# compute output
output = model(images)
loss = criterion(output, target)
# measure accuracy and record loss
acc1, acc5 = accuracy(output, target, topk=(1, 5))
losses.update(loss.item(), images.size(0))
top1.update(acc1[0], images.size(0))
top5.update(acc5[0], images.size(0))
# measure elapsed time
batch_time.update(time.time() - end)
end = time.time()
if i % args.print_freq == 0:
progress.display(i + 1)
# aggregate metrics
top1.all_reduce()
top5.all_reduce()
progress.display_summary()
return top1.avg
class Summary(Enum):
NONE = 0
AVERAGE = 1
SUM = 2
COUNT = 3
class AverageMeter(object):
"""Computes and stores the average and current value"""
def __init__(self, name, fmt=":f", summary_type=Summary.AVERAGE):
self.name = name
self.fmt = fmt
self.summary_type = summary_type
self.reset()
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def update(self, val, n=1):
self.val = val
self.sum += val * n
self.count += n
self.avg = self.sum / self.count
# DATA PARALLEL
def all_reduce(self):
device = "cuda" if torch.cuda.is_available() else "cpu"
total = torch.tensor([self.sum, self.count], dtype=torch.float32, device=device)
dist.all_reduce(total, dist.ReduceOp.SUM, async_op=False)
self.sum, self.count = total.tolist()
self.avg = self.sum / self.count
def __str__(self):
fmtstr = "{name} {val" + self.fmt + "} ({avg" + self.fmt + "})"
return fmtstr.format(**self.__dict__)
def summary(self):
fmtstr = ""
if self.summary_type is Summary.NONE:
fmtstr = ""
elif self.summary_type is Summary.AVERAGE:
fmtstr = "{name} {avg:.3f}"
elif self.summary_type is Summary.SUM:
fmtstr = "{name} {sum:.3f}"
elif self.summary_type is Summary.COUNT:
fmtstr = "{name} {count:.3f}"
else:
raise ValueError("invalid summary type %r" % self.summary_type)
return fmtstr.format(**self.__dict__)
class ProgressMeter(object):
def __init__(self, num_batches, meters, prefix=""):
self.batch_fmtstr = self._get_batch_fmtstr(num_batches)
self.meters = meters
self.prefix = prefix
def display(self, batch):
entries = [self.prefix + self.batch_fmtstr.format(batch)]
entries += [str(meter) for meter in self.meters]
print("\t".join(entries))
def display_summary(self):
entries = [" *"]
entries += [meter.summary() for meter in self.meters]
print(" ".join(entries))
def _get_batch_fmtstr(self, num_batches):
num_digits = len(str(num_batches // 1))
fmt = "{:" + str(num_digits) + "d}"
return "[" + fmt + "/" + fmt.format(num_batches) + "]"
def accuracy(output, target, topk=(1,)):
"""Computes the accuracy over the k top predictions for the specified values of k"""
with torch.no_grad():
maxk = max(topk)
batch_size = target.size(0)
_, pred = output.topk(maxk, 1, True, True)
pred = pred.t()
correct = pred.eq(target.view(1, -1).expand_as(pred))
res = []
for k in topk:
correct_k = correct[:k].reshape(-1).float().sum(0, keepdim=True)
res.append(correct_k.mul_(100.0 / batch_size))
return res
if __name__ == "__main__":
main() | zeus-ml | /zeus-ml-0.7.0.tar.gz/zeus-ml-0.7.0/examples/imagenet/train_dp.py | train_dp.py |
from __future__ import annotations
import argparse
from pprint import pprint
from typing import Literal
import pandas as pd
from zeus.job import Job
from zeus.policy.optimizer import JITPowerLimitOptimizer, PruningGTSBatchSizeOptimizer
from zeus.simulate import Simulator
from zeus.analyze import HistoryEntry
def parse_args() -> argparse.Namespace:
"""Parse commandline arguments."""
parser = argparse.ArgumentParser()
parser.add_argument("--dataset", default="librispeech")
parser.add_argument("--model", default="deepspeech2")
parser.add_argument("--optimizer", default="adamw")
parser.add_argument("--target_metric", type=float, default=40.0)
parser.add_argument("--max_epochs", type=int, default=16)
parser.add_argument("--b_0", type=int, default=192)
parser.add_argument(
"--gpu", default="v100", choices=["a40", "v100", "p100", "rtx6000"]
)
parser.add_argument("--eta_knob", type=float, default=0.5)
parser.add_argument("--beta_knob", type=float, default=2.0)
parser.add_argument("--seed", type=int, default=1)
parser.add_argument(
"--num_recurrence",
type=int,
default=None,
help="If None, 2*|B|*|P| will be used as in the paper.",
)
return parser.parse_args()
def read_trace(
gpu: Literal["a40", "v100", "p100", "rtx6000"]
) -> tuple[pd.DataFrame, pd.DataFrame]:
"""Read the train and power trace files as Pandas DataFrames."""
train_df = pd.DataFrame(pd.read_csv("../../trace/summary_train.csv"))
power_df = pd.DataFrame(pd.read_csv(f"../../trace/summary_power_{gpu}.csv"))
return train_df, power_df
def run_simulator(
job: Job,
gpu: Literal["a40", "v100", "p100", "rtx6000"],
eta_knob: float,
beta_knob: float,
num_recurrence: int | None,
seed: int = 1,
) -> list[HistoryEntry]:
"""Run the simulator on the given job."""
# Read in the train and power traces.
train_df, power_df = read_trace(gpu)
# Instantiate optimizers.
plo = JITPowerLimitOptimizer(verbose=True)
bso = PruningGTSBatchSizeOptimizer(seed=seed, verbose=True)
# Instantitate the simulator.
simulator = Simulator(train_df, power_df, bso, plo, seed=seed, verbose=True)
# Use 2 * |B| * |P| is num_recurrence is None.
print(num_recurrence)
if num_recurrence is None:
job_df = job.filter_df(train_df.merge(power_df, how="inner"))
num_recurrence = (
2 * len(job_df.batch_size.unique()) * len(job_df.power_limit.unique())
)
# Run the simulator.
print(num_recurrence)
return simulator.simulate_one_job(job, num_recurrence, beta_knob, eta_knob)
def main(args: argparse.Namespace) -> None:
"""Run the main routine."""
# Instantitate the job specification dataclass.
job = Job(
args.dataset,
args.model,
args.optimizer,
args.target_metric,
args.max_epochs,
args.b_0,
)
# Run the simulator.
history = run_simulator(
job, args.gpu, args.eta_knob, args.beta_knob, args.num_recurrence, args.seed
)
# Print out the list of HistoryEntry's.
pprint(history)
if __name__ == "__main__":
main(parse_args()) | zeus-ml | /zeus-ml-0.7.0.tar.gz/zeus-ml-0.7.0/examples/trace_driven/run_single.py | run_single.py |
from __future__ import annotations
import zlib
import argparse
import multiprocessing as mp
from pprint import pprint
from typing import Literal
from functools import lru_cache
import pandas as pd
from zeus.job import Job
from zeus.simulate import Simulator
from zeus.analyze import HistoryEntry
from zeus.policy import JITPowerLimitOptimizer, PruningGTSBatchSizeOptimizer
def parse_args() -> argparse.Namespace:
"""Parse commandline arguments."""
parser = argparse.ArgumentParser()
parser.add_argument(
"--gpu", default="v100", choices=["a40", "v100", "p100", "rtx6000"]
)
parser.add_argument("--eta_knob", type=float, default=0.5)
parser.add_argument("--beta_knob", type=float, default=2.0)
return parser.parse_args()
def run_simulator(
gpu: Literal["a40", "v100", "p100", "rtx6000"],
eta_knob: float,
beta_knob: float,
) -> list[tuple[str, list[HistoryEntry]]]:
"""Run the simulator on the given job."""
# Read in the Alibaba trace
alibaba_df = pd.DataFrame(pd.read_csv("../../trace/alibaba_groups.csv.xz"))
# Run simulation on all Alibaba recurring job groups.
with mp.Pool(mp.cpu_count()) as p:
alibaba_result = p.starmap(
simulate_group,
(
(group, gpu, eta_knob, beta_knob)
for _, group in alibaba_df.groupby("group")
),
)
return alibaba_result
def simulate_group(
group: pd.DataFrame,
gpu: Literal["a40", "v100", "p100", "rtx6000"],
eta_knob: float,
beta_knob: float,
) -> tuple[str, list[HistoryEntry]]:
"""Perform trace-driven simulation on one Alibaba recurring job group."""
job = get_job_with_defaults(gpu, group.dataset.unique().item())
# Deterministic hashing.
seed = zlib.adler32(group.group.unique().item().encode("utf-8"))
# Instantiate optimizers.
bso = PruningGTSBatchSizeOptimizer(seed=seed, concurrency=True, verbose=False)
plo = JITPowerLimitOptimizer(verbose=False)
# Instantitate the simulator.
simulator = Simulator(
read_train_trace(), read_power_trace(gpu), bso, plo, seed=seed, verbose=False
)
# Run the simulator.
history = simulator.simulate_one_alibaba_group(
job, group, beta_knob=beta_knob, eta_knob=eta_knob
)
return (group.dataset.unique().item(), history)
@lru_cache(maxsize=1)
def read_train_trace() -> pd.DataFrame:
"""Read the train trace file as a Pandas DataFrame."""
return pd.DataFrame(pd.read_csv("../../trace/summary_train.csv"))
@lru_cache(maxsize=1)
def read_power_trace(gpu: Literal["a40", "v100", "p100", "rtx6000"]) -> pd.DataFrame:
"""Read the power trace of the given GPU as a Pandas DataFrame."""
return pd.DataFrame(pd.read_csv(f"../../trace/summary_power_{gpu}.csv"))
def get_job_with_defaults(
gpu: Literal["a40", "v100", "p100", "rtx6000"], dataset: str
) -> Job:
"""Instantiate a Job instance with defaults for the given dataset."""
if dataset not in [
"cifar100",
"imagenet",
"squad",
"librispeech",
"movielens-1m",
"sentiment140",
]:
raise NotImplementedError(f"Unknown dataset {dataset}.")
# Since GPUs have different VRAM capacities, the maximum batch size changes.
power_df = read_power_trace(gpu)
bmax = power_df.loc[power_df.dataset == dataset].batch_size.max().item()
if dataset.lower() == "cifar100":
b0 = min(1024, bmax)
return Job("cifar100", "shufflenetv2", "adadelta", 0.6, 100, b0, 0.1)
elif dataset.lower() == "imagenet":
b0 = min(256, bmax)
return Job("imagenet", "resnet50", "adadelta", 0.65, 100, b0)
elif dataset.lower() == "squad":
b0 = min(32, bmax)
return Job("squad", "bert_base_uncased", "adamw", 84.0, 6, b0)
elif dataset.lower() == "librispeech":
b0 = min(256, bmax)
return Job("librispeech", "deepspeech2", "adamw", 40.0, 16, b0)
elif dataset.lower() == "movielens-1m":
b0 = min(1024, bmax)
return Job("movielens-1m", "ncf", "adam", 0.41, 100, b0)
elif dataset.lower() == "sentiment140":
b0 = min(128, bmax)
return Job("sentiment140", "bert_base_uncased", "adamw", 0.84, 10, b0, 4.00e-7)
else:
raise NotImplementedError(f"Unknown dataset {dataset}.")
if __name__ == "__main__":
# Parse commandline arguments.
args = parse_args()
# Run the simulator.
history = run_simulator(args.gpu, args.eta_knob, args.beta_knob)
# Print out the list of HistoryEntry's.
pprint(history[:20]) | zeus-ml | /zeus-ml-0.7.0.tar.gz/zeus-ml-0.7.0/examples/trace_driven/run_alibaba.py | run_alibaba.py |
import argparse
import os
import random
import time
import warnings
import subprocess
from enum import Enum
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.distributed as dist
import torch.optim
from torch.optim.lr_scheduler import StepLR
import torch.multiprocessing as mp
import torch.utils.data
from torch.utils.data import DataLoader
import torch.utils.data.distributed
import torchvision.transforms as transforms
import torchvision.datasets as datasets
import torchvision.models as models
from torch.utils.data import Subset
# ZEUS
from zeus.run import ZeusDataLoader
def parse_args() -> argparse.Namespace:
"""Parse command line arguments.
Raises:
ValueError: Launching methods arguments are mixed together. Please note that
`--multiprocessing-distributed` is dedicated to using `torch.multiprocessing.launch`
and `--torchrun` is dedicated to using `torchrun`. See more in the script docstring.
"""
# List choices of models
model_names = sorted(
name
for name in models.__dict__
if name.islower()
and not name.startswith("__")
and callable(models.__dict__[name])
)
parser = argparse.ArgumentParser(description="PyTorch ImageNet Training")
parser.add_argument(
"data",
metavar="DIR",
help="Path to the ImageNet directory",
)
parser.add_argument(
"-a",
"--arch",
metavar="ARCH",
default="resnet18",
choices=model_names,
help="model architecture: " + " | ".join(model_names) + " (default: resnet18)",
)
parser.add_argument(
"-j",
"--workers",
default=4,
type=int,
metavar="N",
help="number of data loading workers (default: 4)",
)
parser.add_argument(
"--epochs",
default=90,
type=int,
metavar="N",
help="number of total epochs to run",
)
parser.add_argument(
"--start_epoch",
default=0,
type=int,
metavar="N",
help="manual epoch number (useful on restarts)",
)
parser.add_argument(
"-b",
"--batch_size",
default=256,
type=int,
metavar="N",
help="mini-batch size (default: 256), this is the total "
"batch size of all GPUs on the current node when "
"using Data Parallel or Distributed Data Parallel",
)
parser.add_argument(
"--lr",
"--learning_rate",
default=0.1,
type=float,
metavar="LR",
help="initial learning rate",
dest="lr",
)
parser.add_argument(
"--momentum", default=0.9, type=float, metavar="M", help="momentum"
)
parser.add_argument(
"--wd",
"--weight_decay",
default=1e-4,
type=float,
metavar="W",
help="weight decay (default: 1e-4)",
dest="weight_decay",
)
parser.add_argument(
"-p",
"--print_freq",
default=10,
type=int,
metavar="N",
help="print frequency (default: 10)",
)
parser.add_argument(
"-e",
"--evaluate",
dest="evaluate",
action="store_true",
help="evaluate model on validation set",
)
parser.add_argument(
"--pretrained",
dest="pretrained",
action="store_true",
help="use pre-trained model",
)
parser.add_argument(
"--dist_url",
default="tcp://127.0.0.1:12306",
type=str,
help="url used to set up distributed training",
)
parser.add_argument(
"--dist_backend", default="nccl", type=str, help="distributed backend"
)
parser.add_argument(
"--seed", default=None, type=int, help="seed for initializing training. "
)
parser.add_argument("--gpu", default=None, type=int, help="GPU id to use.")
parser.add_argument(
"--multiprocessing_distributed",
action="store_true",
help="Use `torch.multiprocessing` to launch N processes on this node, "
"which has N GPUs. PLEASE DO NOT use this argument if you are using "
"`torchrun` or ``torch.distributed.launch`.",
)
parser.add_argument(
"--dummy", action="store_true", help="use fake data to benchmark"
)
# ZEUS
parser.add_argument("--zeus", action="store_true", help="Whether to run Zeus.")
parser.add_argument(
"--target_metric",
default=None,
type=float,
help=(
"Stop training when the target metric is reached. This is ignored when running in Zeus mode because"
" ZeusDataLoader will receive the target metric via environment variable and stop training by itself."
),
)
# DATA PARALLEL
parser.add_argument(
"--local_rank",
default=-1,
type=int,
help="Local rank for data parallel training. This is necessary for using the `torch.distributed.launch` utility.",
)
parser.add_argument(
"--local_world_size",
default=-1,
type=int,
help="Local world size for data parallel training.",
)
parser.add_argument(
"--torchrun",
action="store_true",
help="Use torchrun. This means we will read local_rank from environment variable set by `torchrun`.",
)
args = parser.parse_args()
# Sanity check
if args.multiprocessing_distributed and (args.torchrun or args.local_rank >= 0):
raise ValueError(
"Can not set --multiprocessing-distributed when using `torch.distributed.launch` or `torchrun`. "
"Please refer to the docstring for more info about launching methods."
)
return args
def main():
"""Main function that prepares values and spawns/calls the worker function.
Raises:
ValueError: The global batch size passed in by `--batch_size` or `-b`
is not divisible by the number of GPUs.
"""
args = parse_args()
if args.seed is not None:
random.seed(args.seed)
torch.manual_seed(args.seed)
cudnn.deterministic = True
if args.gpu is not None:
warnings.warn(
"You have chosen a specific GPU. This will completely "
"disable data parallelism."
)
# DATA PARALLEL
# Preparation for SLURM
if "SLURM_PROCID" in os.environ:
# Retrieve local_rank.
# We only consider Single GPU for now. So `local_rank == rank`.
args.local_rank = int(os.environ["SLURM_PROCID"])
# Retrieve the node address
node_list = os.environ["SLURM_NODELIST"]
addr = subprocess.getoutput(f"scontrol show hostname {node_list} | head -n1")
# Specify master address and master port
if "MASTER_ADDR" not in os.environ:
os.environ["MASTER_ADDR"] = addr
if "MASTER_PORT" not in os.environ:
os.environ["MASTER_PORT"] = "29500"
# Preparation for torchrun.
# Integrate launching by `torchrun` and `torch.distributed.launch`
# by retrieving local rank from environment variable LOCAL_RANK.
if args.torchrun:
args.local_rank = int(os.environ["LOCAL_RANK"])
args.local_world_size = int(os.environ["LOCAL_WORLD_SIZE"])
args.distributed = args.multiprocessing_distributed or args.local_rank >= 0
ngpus_per_node = torch.cuda.device_count()
# The global batch size passed in by `--batch_size` or `-b` MUST be divisible
# by the number of GPUs available. You can check the number of GPUs available by
# `torch.cuda.device_count()`.
if args.batch_size % ngpus_per_node != 0:
raise ValueError(
"The global batch size passed in by `--batch_size` or `-b` MUST"
" be divisible by the number of GPUs available. Got"
f" global_batch_size={args.batch_size} with {ngpus_per_node} GPUs."
)
if args.multiprocessing_distributed:
# Use `torch.multiprocessing.spawn` to launch distributed processes: the
# main_worker process function.
mp.spawn(main_worker, nprocs=ngpus_per_node, args=(ngpus_per_node, args))
elif args.local_rank >= 0:
# Use `torch.distributed.launch` or `turchrun` or `slurm`.
# Simply call `main_worker` at `local_rank`.
main_worker(args.local_rank, ngpus_per_node, args)
else:
# Use a specific GPU.
# Simply call main_worker function.
main_worker(args.gpu, ngpus_per_node, args)
def main_worker(gpu, ngpus_per_node, args):
"""Worker function that runs on each process."""
args.gpu = gpu
if args.gpu is not None:
print(f"Use GPU {args.gpu} for training")
# DATA PARALLEL
# Step 1: Initialize the default process group.
if args.distributed:
if args.multiprocessing_distributed:
# Use `torch.multiprocessing`
# Spawn N processes, one for each GPU
dist.init_process_group(
backend=args.dist_backend,
init_method=args.dist_url,
world_size=ngpus_per_node,
rank=args.gpu,
)
else:
# Use `torchrun`, `torch.distributed.launch` or SLURM
# `MASTER_ADDR` and `MASTER_PORT` are already set as environment variables,
# so no need to pass to `init_process_group``.
dist.init_process_group(backend=args.dist_backend)
if args.local_world_size < 0:
args.local_world_size = dist.get_world_size()
else:
args.local_world_size = 1
# Step 2: Create a model and wrap it with `DistributedDataParallel`.
if args.pretrained:
print("=> using pre-trained model '{}'".format(args.arch))
model = models.__dict__[args.arch](pretrained=True)
else:
print("=> creating model '{}'".format(args.arch))
model = models.__dict__[args.arch]()
if not torch.cuda.is_available():
print("using CPU, this will be slow")
elif args.distributed:
# DATA PARALLEL
# For multiprocessing distributed, DistributedDataParallel constructor
# should always set the single device scope, otherwise,
# DistributedDataParallel will use all available devices.
if args.gpu is not None:
torch.cuda.set_device(args.gpu)
model.cuda(args.gpu)
# When using a single GPU per process and per
# DistributedDataParallel, we need to divide the batch size
# ourselves based on the total number of GPUs of the current node.
args.batch_size = int(args.batch_size / ngpus_per_node)
args.workers = int((args.workers + ngpus_per_node - 1) / ngpus_per_node)
model = torch.nn.parallel.DistributedDataParallel(
model,
device_ids=[args.gpu],
output_device=args.gpu,
)
else:
model.cuda()
# DistributedDataParallel will divide and allocate batch_size to all
# available GPUs if device_ids are not set
model = torch.nn.parallel.DistributedDataParallel(model)
elif args.gpu is not None:
torch.cuda.set_device(args.gpu)
model = model.cuda(args.gpu)
else:
# DataParallel will divide and allocate batch_size to all available GPUs
if args.arch.startswith("alexnet") or args.arch.startswith("vgg"):
model.features = torch.nn.DataParallel(model.features)
model.cuda()
else:
model = torch.nn.DataParallel(model).cuda()
# define loss function (criterion), optimizer, and learning rate scheduler
criterion = nn.CrossEntropyLoss().cuda(args.gpu)
optimizer = torch.optim.SGD(
model.parameters(),
args.lr,
momentum=args.momentum,
weight_decay=args.weight_decay,
)
"""Sets the learning rate to the initial LR decayed by 10 every 30 epochs"""
scheduler = StepLR(optimizer, step_size=30, gamma=0.1)
# Data loading code
if args.dummy:
print("=> Dummy data is used!")
train_dataset = datasets.FakeData(
1281167, (3, 224, 224), 1000, transforms.ToTensor()
)
val_dataset = datasets.FakeData(
50000, (3, 224, 224), 1000, transforms.ToTensor()
)
else:
traindir = os.path.join(args.data, "train")
valdir = os.path.join(args.data, "val")
normalize = transforms.Normalize(
mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]
)
train_dataset = datasets.ImageFolder(
traindir,
transforms.Compose(
[
transforms.RandomResizedCrop(224),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
normalize,
]
),
)
val_dataset = datasets.ImageFolder(
valdir,
transforms.Compose(
[
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
normalize,
]
),
)
# DATA PARALLEL
# Step 3: Create instances of `DistributedSampler` to restrict data loading
# to a subset of the dataset.
if args.distributed:
train_sampler = torch.utils.data.distributed.DistributedSampler(train_dataset)
val_sampler = torch.utils.data.distributed.DistributedSampler(
val_dataset, shuffle=False, drop_last=True
)
else:
train_sampler = None
val_sampler = None
# ZEUS
# Step 4: Create instances of `ZeusDataLoader`.
if args.zeus:
# ZEUS
# Take either of the launching approaches of the data parallel training on
# single-node multi-GPU will activate the data parallel ("dp") mode in zeus.
# DATA PARALLEL
zeus_distributed = "dp" if args.distributed else None
train_loader = ZeusDataLoader(
train_dataset,
batch_size=args.batch_size,
distributed=zeus_distributed,
max_epochs=args.epochs,
shuffle=(train_sampler is None),
num_workers=args.workers,
pin_memory=True,
sampler=train_sampler,
)
val_loader = ZeusDataLoader(
val_dataset,
batch_size=args.batch_size,
distributed=zeus_distributed,
shuffle=False,
num_workers=args.workers,
pin_memory=True,
sampler=val_sampler,
)
else:
train_loader = DataLoader(
train_dataset,
batch_size=args.batch_size,
shuffle=(train_sampler is None),
num_workers=args.workers,
pin_memory=True,
sampler=train_sampler,
)
val_loader = DataLoader(
val_dataset,
batch_size=args.batch_size,
shuffle=False,
num_workers=args.workers,
pin_memory=True,
sampler=val_sampler,
)
if args.evaluate:
validate(val_loader, model, criterion, args)
return
# ZEUS
if args.zeus:
assert isinstance(train_loader, ZeusDataLoader)
epoch_iter = train_loader.epochs()
else:
epoch_iter = range(args.start_epoch, args.epochs)
for epoch in epoch_iter:
# DATA PARALLEL
if args.distributed:
train_sampler.set_epoch(epoch)
# train for one epoch
train(train_loader, model, criterion, optimizer, epoch, args)
# evaluate on validation set
acc1 = validate(val_loader, model, criterion, args)
scheduler.step()
# ZEUS
if args.zeus:
assert isinstance(train_loader, ZeusDataLoader)
# Scale the accuracy and report to `train_loader`.`
train_loader.report_metric(acc1 / 100, higher_is_better=True)
elif args.target_metric is not None:
if acc1 / 100 >= args.target_metric:
print(
"Reached target metric %s in %s epochs.",
args.target_metric,
epoch + 1,
)
break
def train(train_loader, model, criterion, optimizer, epoch, args):
batch_time = AverageMeter("Time", ":6.3f")
data_time = AverageMeter("Data", ":6.3f")
losses = AverageMeter("Loss", ":.4e")
top1 = AverageMeter("Acc@1", ":6.2f")
top5 = AverageMeter("Acc@5", ":6.2f")
progress = ProgressMeter(
len(train_loader),
[batch_time, data_time, losses, top1, top5],
prefix="Epoch: [{}]".format(epoch),
)
# switch to train mode
model.train()
end = time.time()
for i, (images, target) in enumerate(train_loader):
# measure data loading time
data_time.update(time.time() - end)
# DATA PARALLEL
if args.gpu is not None:
images = images.cuda(args.gpu, non_blocking=True)
if torch.cuda.is_available():
target = target.cuda(args.gpu, non_blocking=True)
# compute output
output = model(images)
loss = criterion(output, target)
# measure accuracy and record loss
acc1, acc5 = accuracy(output, target, topk=(1, 5))
losses.update(loss.item(), images.size(0))
top1.update(acc1[0], images.size(0))
top5.update(acc5[0], images.size(0))
# compute gradient and do SGD step
optimizer.zero_grad()
loss.backward()
optimizer.step()
# measure elapsed time
batch_time.update(time.time() - end)
end = time.time()
if i % args.print_freq == 0:
progress.display(i + 1)
def validate(val_loader, model, criterion, args):
def run_validate(loader, base_progress=0):
with torch.no_grad():
end = time.time()
for i, (images, target) in enumerate(loader):
i = base_progress + i
if args.gpu is not None:
images = images.cuda(args.gpu, non_blocking=True)
if torch.cuda.is_available():
target = target.cuda(args.gpu, non_blocking=True)
# compute output
output = model(images)
loss = criterion(output, target)
# measure accuracy and record loss
acc1, acc5 = accuracy(output, target, topk=(1, 5))
losses.update(loss.item(), images.size(0))
top1.update(acc1[0], images.size(0))
top5.update(acc5[0], images.size(0))
# measure elapsed time
batch_time.update(time.time() - end)
end = time.time()
if i % args.print_freq == 0:
progress.display(i + 1)
batch_time = AverageMeter("Time", ":6.3f", Summary.NONE)
losses = AverageMeter("Loss", ":.4e", Summary.NONE)
top1 = AverageMeter("Acc@1", ":6.2f", Summary.AVERAGE)
top5 = AverageMeter("Acc@5", ":6.2f", Summary.AVERAGE)
progress = ProgressMeter(
len(val_loader)
+ (
args.distributed
and (
len(val_loader.sampler) * args.local_world_size
< len(val_loader.dataset)
)
),
[batch_time, losses, top1, top5],
prefix="Test: ",
)
# switch to evaluate mode
model.eval()
run_validate(val_loader)
# DATA PARALLEL
if args.distributed:
top1.all_reduce()
top5.all_reduce()
if args.distributed and (
len(val_loader.sampler) * args.local_world_size < len(val_loader.dataset)
):
aux_val_dataset = Subset(
val_loader.dataset,
range(
len(val_loader.sampler) * args.local_world_size, len(val_loader.dataset)
),
)
aux_val_loader = torch.utils.data.DataLoader(
aux_val_dataset,
batch_size=args.batch_size,
shuffle=False,
num_workers=args.workers,
pin_memory=True,
)
run_validate(aux_val_loader, len(val_loader))
progress.display_summary()
return top1.avg
class Summary(Enum):
NONE = 0
AVERAGE = 1
SUM = 2
COUNT = 3
class AverageMeter(object):
"""Computes and stores the average and current value"""
def __init__(self, name, fmt=":f", summary_type=Summary.AVERAGE):
self.name = name
self.fmt = fmt
self.summary_type = summary_type
self.reset()
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def update(self, val, n=1):
self.val = val
self.sum += val * n
self.count += n
self.avg = self.sum / self.count
# DATA PARALLEL
def all_reduce(self):
device = "cuda" if torch.cuda.is_available() else "cpu"
total = torch.tensor([self.sum, self.count], dtype=torch.float32, device=device)
dist.all_reduce(total, dist.ReduceOp.SUM, async_op=False)
self.sum, self.count = total.tolist()
self.avg = self.sum / self.count
def __str__(self):
fmtstr = "{name} {val" + self.fmt + "} ({avg" + self.fmt + "})"
return fmtstr.format(**self.__dict__)
def summary(self):
fmtstr = ""
if self.summary_type is Summary.NONE:
fmtstr = ""
elif self.summary_type is Summary.AVERAGE:
fmtstr = "{name} {avg:.3f}"
elif self.summary_type is Summary.SUM:
fmtstr = "{name} {sum:.3f}"
elif self.summary_type is Summary.COUNT:
fmtstr = "{name} {count:.3f}"
else:
raise ValueError("invalid summary type %r" % self.summary_type)
return fmtstr.format(**self.__dict__)
class ProgressMeter(object):
def __init__(self, num_batches, meters, prefix=""):
self.batch_fmtstr = self._get_batch_fmtstr(num_batches)
self.meters = meters
self.prefix = prefix
def display(self, batch):
entries = [self.prefix + self.batch_fmtstr.format(batch)]
entries += [str(meter) for meter in self.meters]
print("\t".join(entries))
def display_summary(self):
entries = [" *"]
entries += [meter.summary() for meter in self.meters]
print(" ".join(entries))
def _get_batch_fmtstr(self, num_batches):
num_digits = len(str(num_batches // 1))
fmt = "{:" + str(num_digits) + "d}"
return "[" + fmt + "/" + fmt.format(num_batches) + "]"
def accuracy(output, target, topk=(1,)):
"""Computes the accuracy over the k top predictions for the specified values of k"""
with torch.no_grad():
maxk = max(topk)
batch_size = target.size(0)
_, pred = output.topk(maxk, 1, True, True)
pred = pred.t()
correct = pred.eq(target.view(1, -1).expand_as(pred))
res = []
for k in topk:
correct_k = correct[:k].reshape(-1).float().sum(0, keepdim=True)
res.append(correct_k.mul_(100.0 / batch_size))
return res
if __name__ == "__main__":
main() | zeus-ml | /zeus-ml-0.7.0.tar.gz/zeus-ml-0.7.0/examples/ZeusDataLoader/imagenet/train.py | train.py |
import argparse
import sys
from pathlib import Path
from zeus.job import Job
from zeus.policy import PruningGTSBatchSizeOptimizer
from zeus.run import ZeusMaster
from zeus.util import FileAndConsole
def parse_args() -> argparse.Namespace:
"""Parse commandline arguments."""
parser = argparse.ArgumentParser()
parser.add_argument(
"data",
metavar="DIR",
help="Path to the ImageNet directory",
)
# This random seed is used for
# 1. Multi-Armed Bandit inside PruningGTSBatchSizeOptimizer, and
# 2. Providing random seeds for training.
# Especially for 2, the random seed given to the nth recurrence job is args.seed + n.
parser.add_argument("--seed", type=int, default=1, help="Random seed")
# Default batch size and learning rate.
# The first recurrence uses these parameters, and it must reach the target metric.
# There is no learning rate because we train the model with Adadelta.
parser.add_argument("--b_0", type=int, default=256, help="Default batch size")
parser.add_argument("--lr_0", type=float, default=0.1, help="Default learning rate")
# The range of batch sizes to consider. The example script generates a list of power-of-two
# batch sizes, but batch sizes need not be power-of-two for Zeus.
parser.add_argument(
"--b_min", type=int, default=8, help="Smallest batch size to consider"
)
parser.add_argument(
"--b_max", type=int, default=1024, help="Largest batch size to consider"
)
# The total number of recurrences.
parser.add_argument(
"--num_recurrence", type=int, default=100, help="Total number of recurrences"
)
# The \\eta knob trades off time and energy consumption. See Equation 2 in the paper.
# The \\beta knob defines the early stopping threshold. See Section 4.4 in the paper.
parser.add_argument(
"--eta_knob", type=float, default=0.5, help="TTA-ETA tradeoff knob"
)
parser.add_argument(
"--beta_knob", type=float, default=2.0, help="Early stopping threshold"
)
# Jobs are terminated when one of the three happens:
# 1. The target validation metric is reached.
# 2. The number of epochs exceeds the maximum number of epochs set.
# 3. The cost of the next epoch is expected to exceed the early stopping threshold.
parser.add_argument(
"--target_metric", type=float, default=0.50, help="Target validation metric"
)
parser.add_argument(
"--max_epochs", type=int, default=100, help="Max number of epochs to train"
)
return parser.parse_args()
def main(args: argparse.Namespace) -> None:
"""Run Zeus on ImageNet."""
# Zeus's batch size optimizer.
# First prunes unpromising batch sizes, and then runs Gaussian Thompson Sampling MAB.
bso = PruningGTSBatchSizeOptimizer(seed=args.seed, verbose=True)
# The top-level class for running Zeus.
# - The batch size optimizer is desinged as a pluggable policy.
# - Paths (log_base and monitor_path) assume our Docker image's directory structure.
master = ZeusMaster(
batch_size_optimizer=bso,
log_base="/workspace/zeus_logs",
seed=args.seed,
monitor_path="/workspace/zeus/zeus_monitor/zeus_monitor",
observer_mode=False,
profile_warmup_iters=20,
profile_measure_iters=80,
)
# Definition of the ImageNet job.
# The `Job` class encloses all information needed to run training. The `command` parameter is
# a command template. Curly-braced parameters are recognized by Zeus and automatically filled.
job = Job(
dataset="imagenet",
network="resnet18",
optimizer="sgd",
target_metric=args.target_metric,
max_epochs=args.max_epochs,
default_bs=args.b_0,
default_lr=args.lr_0,
workdir="/workspace/zeus/examples/imagenet",
# fmt: off
command=[
"torchrun",
"--nnodes", "1",
"--nproc_per_node", "gpu",
"train.py",
args.data,
"--zeus",
"--arch", "resnet18",
"--batch_size", "{batch_size}",
"--learning_rate", "{learning_rate}",
"--epochs", "{epochs}",
"--seed", "{seed}",
"--torchrun",
],
# fmt: on
)
# Generate a list of batch sizes with only power-of-two values.
batch_sizes = [args.b_min]
while (bs := batch_sizes[-1] * 2) <= args.b_max:
batch_sizes.append(bs)
# Create a designated log directory inside `args.log_base` just for this run of Zeus.
# Six types of outputs are generated.
# 1. Power monitor ouptut (`bs{batch_size}+e{epoch_num}+gpu{device_id}.power.log`):
# Raw output of the Zeus power monitor.
# 2. Profiling results (`bs{batch_size}.power.json`):
# Train-time average power consumption and throughput for each power limit,
# the optimal power limit determined from the result of profiling, and
# eval-time average power consumption and throughput for the optimal power limit.
# 3. Training script output (`rec{recurrence_num}+try{trial_num}.train.log`):
# The raw output of the training script. `trial_num` exists because the job
# may be early stopped and re-run with another batch size.
# 4. Training result (`rec{recurrence_num}+try{trial_num}+bs{batch_size}.train.json`):
# The total energy, time, and cost consumed, and the number of epochs trained
# until the job terminated. Also, whether the job reached the target metric at the
# time of termination. Early-stopped jobs will not have reached their target metric.
# 5. ZeusMaster output (`master.log`): Output from ZeusMaster, including MAB outputs.
# 6. Job history (`history.py`):
# A python file holding a list of `HistoryEntry` objects. Intended use is:
# `history = eval(open("history.py").read())` after importing `HistoryEntry`.
master_logdir = master.build_logdir(
job=job,
num_recurrence=args.num_recurrence,
eta_knob=args.eta_knob,
beta_knob=args.beta_knob,
exist_ok=False, # Should err if this directory exists.
)
# Overwrite the stdout file descriptor with an instance of `FileAndConsole`, so that
# all calls to `print` will write to both the console and the master log file.
sys.stdout = FileAndConsole(Path(master_logdir) / "master.log")
# Run Zeus!
master.run(
job=job,
num_recurrence=args.num_recurrence,
batch_sizes=batch_sizes,
beta_knob=args.beta_knob,
eta_knob=args.eta_knob,
)
if __name__ == "__main__":
main(parse_args()) | zeus-ml | /zeus-ml-0.7.0.tar.gz/zeus-ml-0.7.0/examples/ZeusDataLoader/imagenet/run_zeus.py | run_zeus.py |
import random
import argparse
import torch
from torch import nn, optim
from torch.utils.data import DataLoader
from torchvision import datasets, transforms
# ZEUS
from zeus.run import ZeusDataLoader
from models import all_models, get_model
def parse_args() -> argparse.Namespace:
"""Parse command line arguments."""
parser = argparse.ArgumentParser()
parser.add_argument(
"--arch",
metavar="ARCH",
default="shufflenetv2",
choices=all_models,
help="Model architecture: " + " | ".join(all_models),
)
parser.add_argument(
"--epochs", type=int, default=100, help="Maximum number of epochs to train."
)
parser.add_argument("--batch_size", type=int, default=128, help="Batch size.")
parser.add_argument(
"--num_workers", type=int, default=4, help="Number of workers in dataloader."
)
parser.add_argument(
"--seed", type=int, default=None, help="Random seed to use for training."
)
# ZEUS
runtime_mode = parser.add_mutually_exclusive_group()
runtime_mode.add_argument(
"--zeus", action="store_true", help="Whether to run Zeus."
)
return parser.parse_args()
def main(args: argparse.Namespace) -> None:
"""Run the main training routine."""
# Set random seed.
if args.seed is not None:
set_seed(args.seed)
# Prepare model.
# NOTE: Using torchvision.models would be also straightforward. For example:
# model = vars(torchvision.models)[args.arch](num_classes=100)
model = get_model(args.arch)
# Prepare datasets.
train_dataset = datasets.CIFAR100(
root="data",
train=True,
download=True,
transform=transforms.Compose(
[
transforms.RandomCrop(32, padding=4),
transforms.RandomHorizontalFlip(),
transforms.RandomRotation(15),
transforms.ToTensor(),
transforms.Normalize(
mean=(0.5070751592371323, 0.48654887331495095, 0.4409178433670343),
std=(0.2673342858792401, 0.2564384629170883, 0.27615047132568404),
),
]
),
)
val_dataset = datasets.CIFAR100(
root="data",
train=False,
download=True,
transform=transforms.Compose(
[
transforms.ToTensor(),
transforms.Normalize(
mean=(0.5070751592371323, 0.48654887331495095, 0.4409178433670343),
std=(0.2673342858792401, 0.2564384629170883, 0.27615047132568404),
),
]
),
)
# ZEUS
# Prepare dataloaders.
if args.zeus:
# Zeus
train_loader = ZeusDataLoader(
train_dataset,
max_epochs=args.epochs,
batch_size=args.batch_size,
shuffle=True,
num_workers=args.num_workers,
)
val_loader = ZeusDataLoader(
val_dataset,
batch_size=args.batch_size,
shuffle=False,
num_workers=args.num_workers,
)
else:
train_loader = DataLoader(
train_dataset,
batch_size=args.batch_size,
shuffle=True,
num_workers=args.num_workers,
)
val_loader = DataLoader(
val_dataset,
batch_size=args.batch_size,
shuffle=False,
num_workers=args.num_workers,
)
# Send model to CUDA.
model = model.cuda()
# Prepare loss function and optimizer.
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adadelta(model.parameters())
# ZEUS
# ZeusDataLoader may early stop training when the cost is expected
# to exceed the cost upper limit or the target metric was reached.
if args.zeus:
assert isinstance(train_loader, ZeusDataLoader)
epoch_iter = train_loader.epochs()
else:
epoch_iter = range(args.epochs)
# Main training loop.
for epoch in epoch_iter:
train(train_loader, model, criterion, optimizer, epoch, args)
acc = validate(val_loader, model, criterion, epoch, args)
# ZEUS
if args.zeus:
assert isinstance(train_loader, ZeusDataLoader)
train_loader.report_metric(acc, higher_is_better=True)
def train(train_loader, model, criterion, optimizer, epoch, args):
"""Train the model for one epoch."""
model.train()
num_samples = len(train_loader) * args.batch_size
for batch_index, (images, labels) in enumerate(train_loader):
labels = labels.cuda()
images = images.cuda()
optimizer.zero_grad()
outputs = model(images)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
print(
f"Training Epoch: {epoch} [{(batch_index + 1) * args.batch_size}/{num_samples}]"
f"\tLoss: {loss.item():0.4f}"
)
@torch.no_grad()
def validate(val_loader, model, criterion, epoch, args):
"""Evaluate the model on the validation set."""
model.eval()
test_loss = 0.0
correct = 0
num_samples = len(val_loader) * args.batch_size
for images, labels in val_loader:
images = images.cuda()
labels = labels.cuda()
outputs = model(images)
loss = criterion(outputs, labels)
test_loss += loss.item()
_, preds = outputs.max(1)
correct += preds.eq(labels).sum().item()
print(
f"Validation Epoch: {epoch}, Average loss: {test_loss / num_samples:.4f}"
f", Accuracy: {correct / num_samples:.4f}"
)
return correct / num_samples
def set_seed(seed: int) -> None:
"""Set random seed for reproducible results."""
random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
if __name__ == "__main__":
main(parse_args()) | zeus-ml | /zeus-ml-0.7.0.tar.gz/zeus-ml-0.7.0/examples/ZeusDataLoader/cifar100/train.py | train.py |
import argparse
import sys
from pathlib import Path
from zeus.job import Job
from zeus.policy import PruningGTSBatchSizeOptimizer
from zeus.run import ZeusMaster
from zeus.util import FileAndConsole
def parse_args() -> argparse.Namespace:
"""Parse commandline arguments."""
parser = argparse.ArgumentParser()
# This random seed is used for
# 1. Multi-Armed Bandit inside PruningGTSBatchSizeOptimizer, and
# 2. Providing random seeds for training.
# Especially for 2, the random seed given to the nth recurrence job is args.seed + n.
parser.add_argument("--seed", type=int, default=1, help="Random seed")
# Default batch size and learning rate.
# The first recurrence uses these parameters, and it must reach the target metric.
# There is no learning rate because we train the model with Adadelta.
parser.add_argument("--b_0", type=int, default=1024, help="Default batch size")
# The range of batch sizes to consider. The example script generates a list of power-of-two
# batch sizes, but batch sizes need not be power-of-two for Zeus.
parser.add_argument(
"--b_min", type=int, default=8, help="Smallest batch size to consider"
)
parser.add_argument(
"--b_max", type=int, default=4096, help="Largest batch size to consider"
)
# The total number of recurrences.
parser.add_argument(
"--num_recurrence", type=int, default=100, help="Total number of recurrences"
)
# The \\eta knob trades off time and energy consumption. See Equation 2 in the paper.
# The \\beta knob defines the early stopping threshold. See Section 4.4 in the paper.
parser.add_argument(
"--eta_knob", type=float, default=0.5, help="TTA-ETA tradeoff knob"
)
parser.add_argument(
"--beta_knob", type=float, default=2.0, help="Early stopping threshold"
)
# Jobs are terminated when one of the three happens:
# 1. The target validation metric is reached.
# 2. The number of epochs exceeds the maximum number of epochs set.
# 3. The cost of the next epoch is expected to exceed the early stopping threshold.
parser.add_argument(
"--target_metric", type=float, default=0.50, help="Target validation metric"
)
parser.add_argument(
"--max_epochs", type=int, default=100, help="Max number of epochs to train"
)
return parser.parse_args()
def main(args: argparse.Namespace) -> None:
"""Run Zeus on CIFAR100."""
# Zeus's batch size optimizer.
# First prunes unpromising batch sizes, and then runs Gaussian Thompson Sampling MAB.
bso = PruningGTSBatchSizeOptimizer(seed=args.seed, verbose=True)
# The top-level class for running Zeus.
# - The batch size optimizer is desinged as a pluggable policy.
# - Paths (log_base and monitor_path) assume our Docker image's directory structure.
# - For CIFAR100, one epoch of training may not take even ten seconds (especially for
# small models like squeezenet). ZeusDataLoader automatically handles profiling power
# limits over multiple training epochs such that the profiling window of each power
# limit fully fits in one epoch. However, the epoch duration may be so short that
# profiling even one power limit may not fully fit in one epoch. In such cases,
# ZeusDataLoader raises a RuntimeError, and the profiling window should be narrowed
# by giving smaller values to profile_warmup_iters and profile_measure_iters in the
# constructor of ZeusMaster.
master = ZeusMaster(
batch_size_optimizer=bso,
log_base="/workspace/zeus_logs",
seed=args.seed,
monitor_path="/workspace/zeus/zeus_monitor/zeus_monitor",
observer_mode=False,
profile_warmup_iters=10,
profile_measure_iters=40,
)
# Definition of the CIFAR100 job.
# The `Job` class encloses all information needed to run training. The `command` parameter is
# a command template. Curly-braced parameters are recognized by Zeus and automatically filled.
job = Job(
dataset="cifar100",
network="shufflenet",
optimizer="adadelta",
target_metric=args.target_metric,
max_epochs=args.max_epochs,
default_bs=args.b_0,
default_lr=0.1, # Dummy placeholder value.
workdir="/workspace/zeus/examples/cifar100",
# fmt: off
command=[
"python",
"train.py",
"--zeus",
"--arch", "shufflenet",
"--batch_size", "{batch_size}",
"--epochs", "{epochs}",
"--seed", "{seed}",
],
# fmt: on
)
# Generate a list of batch sizes with only power-of-two values.
batch_sizes = [args.b_min]
while (bs := batch_sizes[-1] * 2) <= args.b_max:
batch_sizes.append(bs)
# Create a designated log directory inside `args.log_base` just for this run of Zeus.
# Six types of outputs are generated.
# 1. Power monitor ouptut (`bs{batch_size}+e{epoch_num}+gpu{device_id}.power.log`):
# Raw output of the Zeus power monitor.
# 2. Profiling results (`bs{batch_size}.power.json`):
# Train-time average power consumption and throughput for each power limit,
# the optimal power limit determined from the result of profiling, and
# eval-time average power consumption and throughput for the optimal power limit.
# 3. Training script output (`rec{recurrence_num}+try{trial_num}.train.log`):
# The raw output of the training script. `trial_num` exists because the job
# may be early stopped and re-run with another batch size.
# 4. Training result (`rec{recurrence_num}+try{trial_num}+bs{batch_size}.train.json`):
# The total energy, time, and cost consumed, and the number of epochs trained
# until the job terminated. Also, whether the job reached the target metric at the
# time of termination. Early-stopped jobs will not have reached their target metric.
# 5. ZeusMaster output (`master.log`): Output from ZeusMaster, including MAB outputs.
# 6. Job history (`history.py`):
# A python file holding a list of `HistoryEntry` objects. Intended use is:
# `history = eval(open("history.py").read())` after importing `HistoryEntry`.
master_logdir = master.build_logdir(
job=job,
num_recurrence=args.num_recurrence,
eta_knob=args.eta_knob,
beta_knob=args.beta_knob,
exist_ok=False, # Should err if this directory exists.
)
# Overwrite the stdout file descriptor with an instance of `FileAndConsole`, so that
# all calls to `print` will write to both the console and the master log file.
sys.stdout = FileAndConsole(Path(master_logdir) / "master.log")
# Run Zeus!
master.run(
job=job,
num_recurrence=args.num_recurrence,
batch_sizes=batch_sizes,
beta_knob=args.beta_knob,
eta_knob=args.eta_knob,
)
if __name__ == "__main__":
main(parse_args()) | zeus-ml | /zeus-ml-0.7.0.tar.gz/zeus-ml-0.7.0/examples/ZeusDataLoader/cifar100/run_zeus.py | run_zeus.py |
import torch
import torch.nn as nn
class SeperableConv2d(nn.Module):
#***Figure 4. An “extreme” version of our Inception module,
#with one spatial convolution per output channel of the 1x1
#convolution."""
def __init__(self, input_channels, output_channels, kernel_size, **kwargs):
super().__init__()
self.depthwise = nn.Conv2d(
input_channels,
input_channels,
kernel_size,
groups=input_channels,
bias=False,
**kwargs
)
self.pointwise = nn.Conv2d(input_channels, output_channels, 1, bias=False)
def forward(self, x):
x = self.depthwise(x)
x = self.pointwise(x)
return x
class EntryFlow(nn.Module):
def __init__(self):
super().__init__()
self.conv1 = nn.Sequential(
nn.Conv2d(3, 32, 3, padding=1, bias=False),
nn.BatchNorm2d(32),
nn.ReLU(inplace=True)
)
self.conv2 = nn.Sequential(
nn.Conv2d(32, 64, 3, padding=1, bias=False),
nn.BatchNorm2d(64),
nn.ReLU(inplace=True)
)
self.conv3_residual = nn.Sequential(
SeperableConv2d(64, 128, 3, padding=1),
nn.BatchNorm2d(128),
nn.ReLU(inplace=True),
SeperableConv2d(128, 128, 3, padding=1),
nn.BatchNorm2d(128),
nn.MaxPool2d(3, stride=2, padding=1),
)
self.conv3_shortcut = nn.Sequential(
nn.Conv2d(64, 128, 1, stride=2),
nn.BatchNorm2d(128),
)
self.conv4_residual = nn.Sequential(
nn.ReLU(inplace=True),
SeperableConv2d(128, 256, 3, padding=1),
nn.BatchNorm2d(256),
nn.ReLU(inplace=True),
SeperableConv2d(256, 256, 3, padding=1),
nn.BatchNorm2d(256),
nn.MaxPool2d(3, stride=2, padding=1)
)
self.conv4_shortcut = nn.Sequential(
nn.Conv2d(128, 256, 1, stride=2),
nn.BatchNorm2d(256),
)
#no downsampling
self.conv5_residual = nn.Sequential(
nn.ReLU(inplace=True),
SeperableConv2d(256, 728, 3, padding=1),
nn.BatchNorm2d(728),
nn.ReLU(inplace=True),
SeperableConv2d(728, 728, 3, padding=1),
nn.BatchNorm2d(728),
nn.MaxPool2d(3, 1, padding=1)
)
#no downsampling
self.conv5_shortcut = nn.Sequential(
nn.Conv2d(256, 728, 1),
nn.BatchNorm2d(728)
)
def forward(self, x):
x = self.conv1(x)
x = self.conv2(x)
residual = self.conv3_residual(x)
shortcut = self.conv3_shortcut(x)
x = residual + shortcut
residual = self.conv4_residual(x)
shortcut = self.conv4_shortcut(x)
x = residual + shortcut
residual = self.conv5_residual(x)
shortcut = self.conv5_shortcut(x)
x = residual + shortcut
return x
class MiddleFLowBlock(nn.Module):
def __init__(self):
super().__init__()
self.shortcut = nn.Sequential()
self.conv1 = nn.Sequential(
nn.ReLU(inplace=True),
SeperableConv2d(728, 728, 3, padding=1),
nn.BatchNorm2d(728)
)
self.conv2 = nn.Sequential(
nn.ReLU(inplace=True),
SeperableConv2d(728, 728, 3, padding=1),
nn.BatchNorm2d(728)
)
self.conv3 = nn.Sequential(
nn.ReLU(inplace=True),
SeperableConv2d(728, 728, 3, padding=1),
nn.BatchNorm2d(728)
)
def forward(self, x):
residual = self.conv1(x)
residual = self.conv2(residual)
residual = self.conv3(residual)
shortcut = self.shortcut(x)
return shortcut + residual
class MiddleFlow(nn.Module):
def __init__(self, block):
super().__init__()
#"""then through the middle flow which is repeated eight times"""
self.middel_block = self._make_flow(block, 8)
def forward(self, x):
x = self.middel_block(x)
return x
def _make_flow(self, block, times):
flows = []
for i in range(times):
flows.append(block())
return nn.Sequential(*flows)
class ExitFLow(nn.Module):
def __init__(self):
super().__init__()
self.residual = nn.Sequential(
nn.ReLU(),
SeperableConv2d(728, 728, 3, padding=1),
nn.BatchNorm2d(728),
nn.ReLU(),
SeperableConv2d(728, 1024, 3, padding=1),
nn.BatchNorm2d(1024),
nn.MaxPool2d(3, stride=2, padding=1)
)
self.shortcut = nn.Sequential(
nn.Conv2d(728, 1024, 1, stride=2),
nn.BatchNorm2d(1024)
)
self.conv = nn.Sequential(
SeperableConv2d(1024, 1536, 3, padding=1),
nn.BatchNorm2d(1536),
nn.ReLU(inplace=True),
SeperableConv2d(1536, 2048, 3, padding=1),
nn.BatchNorm2d(2048),
nn.ReLU(inplace=True)
)
self.avgpool = nn.AdaptiveAvgPool2d((1, 1))
def forward(self, x):
shortcut = self.shortcut(x)
residual = self.residual(x)
output = shortcut + residual
output = self.conv(output)
output = self.avgpool(output)
return output
class Xception(nn.Module):
def __init__(self, block, num_class=100):
super().__init__()
self.entry_flow = EntryFlow()
self.middel_flow = MiddleFlow(block)
self.exit_flow = ExitFLow()
self.fc = nn.Linear(2048, num_class)
def forward(self, x):
x = self.entry_flow(x)
x = self.middel_flow(x)
x = self.exit_flow(x)
x = x.view(x.size(0), -1)
x = self.fc(x)
return x
def xception():
return Xception(MiddleFLowBlock) | zeus-ml | /zeus-ml-0.7.0.tar.gz/zeus-ml-0.7.0/examples/ZeusDataLoader/cifar100/models/xception.py | xception.py |
import torch
import torch.nn as nn
import torch.nn.functional as F
class PreActBasic(nn.Module):
expansion = 1
def __init__(self, in_channels, out_channels, stride):
super().__init__()
self.residual = nn.Sequential(
nn.BatchNorm2d(in_channels),
nn.ReLU(inplace=True),
nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=stride, padding=1),
nn.BatchNorm2d(out_channels),
nn.ReLU(inplace=True),
nn.Conv2d(out_channels, out_channels * PreActBasic.expansion, kernel_size=3, padding=1)
)
self.shortcut = nn.Sequential()
if stride != 1 or in_channels != out_channels * PreActBasic.expansion:
self.shortcut = nn.Conv2d(in_channels, out_channels * PreActBasic.expansion, 1, stride=stride)
def forward(self, x):
res = self.residual(x)
shortcut = self.shortcut(x)
return res + shortcut
class PreActBottleNeck(nn.Module):
expansion = 4
def __init__(self, in_channels, out_channels, stride):
super().__init__()
self.residual = nn.Sequential(
nn.BatchNorm2d(in_channels),
nn.ReLU(inplace=True),
nn.Conv2d(in_channels, out_channels, 1, stride=stride),
nn.BatchNorm2d(out_channels),
nn.ReLU(inplace=True),
nn.Conv2d(out_channels, out_channels, 3, padding=1),
nn.BatchNorm2d(out_channels),
nn.ReLU(inplace=True),
nn.Conv2d(out_channels, out_channels * PreActBottleNeck.expansion, 1)
)
self.shortcut = nn.Sequential()
if stride != 1 or in_channels != out_channels * PreActBottleNeck.expansion:
self.shortcut = nn.Conv2d(in_channels, out_channels * PreActBottleNeck.expansion, 1, stride=stride)
def forward(self, x):
res = self.residual(x)
shortcut = self.shortcut(x)
return res + shortcut
class PreActResNet(nn.Module):
def __init__(self, block, num_block, class_num=100):
super().__init__()
self.input_channels = 64
self.pre = nn.Sequential(
nn.Conv2d(3, 64, 3, padding=1),
nn.BatchNorm2d(64),
nn.ReLU(inplace=True)
)
self.stage1 = self._make_layers(block, num_block[0], 64, 1)
self.stage2 = self._make_layers(block, num_block[1], 128, 2)
self.stage3 = self._make_layers(block, num_block[2], 256, 2)
self.stage4 = self._make_layers(block, num_block[3], 512, 2)
self.linear = nn.Linear(self.input_channels, class_num)
def _make_layers(self, block, block_num, out_channels, stride):
layers = []
layers.append(block(self.input_channels, out_channels, stride))
self.input_channels = out_channels * block.expansion
while block_num - 1:
layers.append(block(self.input_channels, out_channels, 1))
self.input_channels = out_channels * block.expansion
block_num -= 1
return nn.Sequential(*layers)
def forward(self, x):
x = self.pre(x)
x = self.stage1(x)
x = self.stage2(x)
x = self.stage3(x)
x = self.stage4(x)
x = F.adaptive_avg_pool2d(x, 1)
x = x.view(x.size(0), -1)
x = self.linear(x)
return x
def preactresnet18():
return PreActResNet(PreActBasic, [2, 2, 2, 2])
def preactresnet34():
return PreActResNet(PreActBasic, [3, 4, 6, 3])
def preactresnet50():
return PreActResNet(PreActBottleNeck, [3, 4, 6, 3])
def preactresnet101():
return PreActResNet(PreActBottleNeck, [3, 4, 23, 3])
def preactresnet152():
return PreActResNet(PreActBottleNeck, [3, 8, 36, 3]) | zeus-ml | /zeus-ml-0.7.0.tar.gz/zeus-ml-0.7.0/examples/ZeusDataLoader/cifar100/models/preactresnet.py | preactresnet.py |
import torch
import torch.nn as nn
class SeperableConv2d(nn.Module):
def __init__(self, input_channels, output_channels, kernel_size, **kwargs):
super().__init__()
self.depthwise = nn.Conv2d(
input_channels,
input_channels,
kernel_size,
groups=input_channels,
**kwargs
)
self.pointwise = nn.Conv2d(
input_channels,
output_channels,
1
)
def forward(self, x):
x = self.depthwise(x)
x = self.pointwise(x)
return x
class SeperableBranch(nn.Module):
def __init__(self, input_channels, output_channels, kernel_size, **kwargs):
"""Adds 2 blocks of [relu-separable conv-batchnorm]."""
super().__init__()
self.block1 = nn.Sequential(
nn.ReLU(),
SeperableConv2d(input_channels, output_channels, kernel_size, **kwargs),
nn.BatchNorm2d(output_channels)
)
self.block2 = nn.Sequential(
nn.ReLU(),
SeperableConv2d(output_channels, output_channels, kernel_size, stride=1, padding=int(kernel_size / 2)),
nn.BatchNorm2d(output_channels)
)
def forward(self, x):
x = self.block1(x)
x = self.block2(x)
return x
class Fit(nn.Module):
"""Make the cell outputs compatible
Args:
prev_filters: filter number of tensor prev, needs to be modified
filters: filter number of normal cell branch output filters
"""
def __init__(self, prev_filters, filters):
super().__init__()
self.relu = nn.ReLU()
self.p1 = nn.Sequential(
nn.AvgPool2d(1, stride=2),
nn.Conv2d(prev_filters, int(filters / 2), 1)
)
#make sure there is no information loss
self.p2 = nn.Sequential(
nn.ConstantPad2d((0, 1, 0, 1), 0),
nn.ConstantPad2d((-1, 0, -1, 0), 0), #cropping
nn.AvgPool2d(1, stride=2),
nn.Conv2d(prev_filters, int(filters / 2), 1)
)
self.bn = nn.BatchNorm2d(filters)
self.dim_reduce = nn.Sequential(
nn.ReLU(),
nn.Conv2d(prev_filters, filters, 1),
nn.BatchNorm2d(filters)
)
self.filters = filters
def forward(self, inputs):
x, prev = inputs
if prev is None:
return x
#image size does not match
elif x.size(2) != prev.size(2):
prev = self.relu(prev)
p1 = self.p1(prev)
p2 = self.p2(prev)
prev = torch.cat([p1, p2], 1)
prev = self.bn(prev)
elif prev.size(1) != self.filters:
prev = self.dim_reduce(prev)
return prev
class NormalCell(nn.Module):
def __init__(self, x_in, prev_in, output_channels):
super().__init__()
self.dem_reduce = nn.Sequential(
nn.ReLU(),
nn.Conv2d(x_in, output_channels, 1, bias=False),
nn.BatchNorm2d(output_channels)
)
self.block1_left = SeperableBranch(
output_channels,
output_channels,
kernel_size=3,
padding=1,
bias=False
)
self.block1_right = nn.Sequential()
self.block2_left = SeperableBranch(
output_channels,
output_channels,
kernel_size=3,
padding=1,
bias=False
)
self.block2_right = SeperableBranch(
output_channels,
output_channels,
kernel_size=5,
padding=2,
bias=False
)
self.block3_left = nn.AvgPool2d(3, stride=1, padding=1)
self.block3_right = nn.Sequential()
self.block4_left = nn.AvgPool2d(3, stride=1, padding=1)
self.block4_right = nn.AvgPool2d(3, stride=1, padding=1)
self.block5_left = SeperableBranch(
output_channels,
output_channels,
kernel_size=5,
padding=2,
bias=False
)
self.block5_right = SeperableBranch(
output_channels,
output_channels,
kernel_size=3,
padding=1,
bias=False
)
self.fit = Fit(prev_in, output_channels)
def forward(self, x):
x, prev = x
#return transformed x as new x, and original x as prev
#only prev tensor needs to be modified
prev = self.fit((x, prev))
h = self.dem_reduce(x)
x1 = self.block1_left(h) + self.block1_right(h)
x2 = self.block2_left(prev) + self.block2_right(h)
x3 = self.block3_left(h) + self.block3_right(h)
x4 = self.block4_left(prev) + self.block4_right(prev)
x5 = self.block5_left(prev) + self.block5_right(prev)
return torch.cat([prev, x1, x2, x3, x4, x5], 1), x
class ReductionCell(nn.Module):
def __init__(self, x_in, prev_in, output_channels):
super().__init__()
self.dim_reduce = nn.Sequential(
nn.ReLU(),
nn.Conv2d(x_in, output_channels, 1),
nn.BatchNorm2d(output_channels)
)
#block1
self.layer1block1_left = SeperableBranch(output_channels, output_channels, 7, stride=2, padding=3)
self.layer1block1_right = SeperableBranch(output_channels, output_channels, 5, stride=2, padding=2)
#block2
self.layer1block2_left = nn.MaxPool2d(3, stride=2, padding=1)
self.layer1block2_right = SeperableBranch(output_channels, output_channels, 7, stride=2, padding=3)
#block3
self.layer1block3_left = nn.AvgPool2d(3, 2, 1)
self.layer1block3_right = SeperableBranch(output_channels, output_channels, 5, stride=2, padding=2)
#block5
self.layer2block1_left = nn.MaxPool2d(3, 2, 1)
self.layer2block1_right = SeperableBranch(output_channels, output_channels, 3, stride=1, padding=1)
#block4
self.layer2block2_left = nn.AvgPool2d(3, 1, 1)
self.layer2block2_right = nn.Sequential()
self.fit = Fit(prev_in, output_channels)
def forward(self, x):
x, prev = x
prev = self.fit((x, prev))
h = self.dim_reduce(x)
layer1block1 = self.layer1block1_left(prev) + self.layer1block1_right(h)
layer1block2 = self.layer1block2_left(h) + self.layer1block2_right(prev)
layer1block3 = self.layer1block3_left(h) + self.layer1block3_right(prev)
layer2block1 = self.layer2block1_left(h) + self.layer2block1_right(layer1block1)
layer2block2 = self.layer2block2_left(layer1block1) + self.layer2block2_right(layer1block2)
return torch.cat([
layer1block2, #https://github.com/keras-team/keras-applications/blob/master/keras_applications/nasnet.py line 739
layer1block3,
layer2block1,
layer2block2
], 1), x
class NasNetA(nn.Module):
def __init__(self, repeat_cell_num, reduction_num, filters, stemfilter, class_num=100):
super().__init__()
self.stem = nn.Sequential(
nn.Conv2d(3, stemfilter, 3, padding=1, bias=False),
nn.BatchNorm2d(stemfilter)
)
self.prev_filters = stemfilter
self.x_filters = stemfilter
self.filters = filters
self.cell_layers = self._make_layers(repeat_cell_num, reduction_num)
self.relu = nn.ReLU()
self.avg = nn.AdaptiveAvgPool2d(1)
self.fc = nn.Linear(self.filters * 6, class_num)
def _make_normal(self, block, repeat, output):
"""make normal cell
Args:
block: cell type
repeat: number of repeated normal cell
output: output filters for each branch in normal cell
Returns:
stacked normal cells
"""
layers = []
for r in range(repeat):
layers.append(block(self.x_filters, self.prev_filters, output))
self.prev_filters = self.x_filters
self.x_filters = output * 6 #concatenate 6 branches
return layers
def _make_reduction(self, block, output):
"""make normal cell
Args:
block: cell type
output: output filters for each branch in reduction cell
Returns:
reduction cell
"""
reduction = block(self.x_filters, self.prev_filters, output)
self.prev_filters = self.x_filters
self.x_filters = output * 4 #stack for 4 branches
return reduction
def _make_layers(self, repeat_cell_num, reduction_num):
layers = []
for i in range(reduction_num):
layers.extend(self._make_normal(NormalCell, repeat_cell_num, self.filters))
self.filters *= 2
layers.append(self._make_reduction(ReductionCell, self.filters))
layers.extend(self._make_normal(NormalCell, repeat_cell_num, self.filters))
return nn.Sequential(*layers)
def forward(self, x):
x = self.stem(x)
prev = None
x, prev = self.cell_layers((x, prev))
x = self.relu(x)
x = self.avg(x)
x = x.view(x.size(0), -1)
x = self.fc(x)
return x
def nasnet():
#stem filters must be 44, it's a pytorch workaround, cant change to other number
return NasNetA(4, 2, 44, 44) | zeus-ml | /zeus-ml-0.7.0.tar.gz/zeus-ml-0.7.0/examples/ZeusDataLoader/cifar100/models/nasnet.py | nasnet.py |
import torch
import torch.nn as nn
class Fire(nn.Module):
def __init__(self, in_channel, out_channel, squzee_channel):
super().__init__()
self.squeeze = nn.Sequential(
nn.Conv2d(in_channel, squzee_channel, 1),
nn.BatchNorm2d(squzee_channel),
nn.ReLU(inplace=True)
)
self.expand_1x1 = nn.Sequential(
nn.Conv2d(squzee_channel, int(out_channel / 2), 1),
nn.BatchNorm2d(int(out_channel / 2)),
nn.ReLU(inplace=True)
)
self.expand_3x3 = nn.Sequential(
nn.Conv2d(squzee_channel, int(out_channel / 2), 3, padding=1),
nn.BatchNorm2d(int(out_channel / 2)),
nn.ReLU(inplace=True)
)
def forward(self, x):
x = self.squeeze(x)
x = torch.cat([
self.expand_1x1(x),
self.expand_3x3(x)
], 1)
return x
class SqueezeNet(nn.Module):
"""mobile net with simple bypass"""
def __init__(self, class_num=100):
super().__init__()
self.stem = nn.Sequential(
nn.Conv2d(3, 96, 3, padding=1),
nn.BatchNorm2d(96),
nn.ReLU(inplace=True),
nn.MaxPool2d(2, 2)
)
self.fire2 = Fire(96, 128, 16)
self.fire3 = Fire(128, 128, 16)
self.fire4 = Fire(128, 256, 32)
self.fire5 = Fire(256, 256, 32)
self.fire6 = Fire(256, 384, 48)
self.fire7 = Fire(384, 384, 48)
self.fire8 = Fire(384, 512, 64)
self.fire9 = Fire(512, 512, 64)
self.conv10 = nn.Conv2d(512, class_num, 1)
self.avg = nn.AdaptiveAvgPool2d(1)
self.maxpool = nn.MaxPool2d(2, 2)
def forward(self, x):
x = self.stem(x)
f2 = self.fire2(x)
f3 = self.fire3(f2) + f2
f4 = self.fire4(f3)
f4 = self.maxpool(f4)
f5 = self.fire5(f4) + f4
f6 = self.fire6(f5)
f7 = self.fire7(f6) + f6
f8 = self.fire8(f7)
f8 = self.maxpool(f8)
f9 = self.fire9(f8)
c10 = self.conv10(f9)
x = self.avg(c10)
x = x.view(x.size(0), -1)
return x
def squeezenet(class_num=100):
return SqueezeNet(class_num=class_num) | zeus-ml | /zeus-ml-0.7.0.tar.gz/zeus-ml-0.7.0/examples/ZeusDataLoader/cifar100/models/squeezenet.py | squeezenet.py |
import torch
import torch.nn as nn
from torch.distributions.bernoulli import Bernoulli
import random
class StochasticDepthBasicBlock(torch.jit.ScriptModule):
expansion=1
def __init__(self, p, in_channels, out_channels, stride=1):
super().__init__()
#self.p = torch.tensor(p).float()
self.p = p
self.residual = nn.Sequential(
nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=stride, padding=1),
nn.BatchNorm2d(out_channels),
nn.ReLU(inplace=True),
nn.Conv2d(out_channels, out_channels * StochasticDepthBasicBlock.expansion, kernel_size=3, padding=1),
nn.BatchNorm2d(out_channels)
)
self.shortcut = nn.Sequential()
if stride != 1 or in_channels != out_channels * StochasticDepthBasicBlock.expansion:
self.shortcut = nn.Sequential(
nn.Conv2d(in_channels, out_channels * StochasticDepthBasicBlock.expansion, kernel_size=1, stride=stride),
nn.BatchNorm2d(out_channels)
)
def survival(self):
var = torch.bernoulli(torch.tensor(self.p).float())
return torch.equal(var, torch.tensor(1).float().to(var.device))
@torch.jit.script_method
def forward(self, x):
if self.training:
if self.survival():
# official torch implementation
# function ResidualDrop:updateOutput(input)
# local skip_forward = self.skip:forward(input)
# self.output:resizeAs(skip_forward):copy(skip_forward)
# if self.train then
# if self.gate then -- only compute convolutional output when gate is open
# self.output:add(self.net:forward(input))
# end
# else
# self.output:add(self.net:forward(input):mul(1-self.deathRate))
# end
# return self.output
# end
# paper:
# Hl = ReLU(bl*fl(Hl−1) + id(Hl−1)).
# paper and their official implementation are different
# paper use relu after output
# official implementation dosen't
#
# other implementions which use relu:
# https://github.com/jiweeo/pytorch-stochastic-depth/blob/a6f95aaffee82d273c1cd73d9ed6ef0718c6683d/models/resnet.py
# https://github.com/dblN/stochastic_depth_keras/blob/master/train.py
# implementations which doesn't use relu:
# https://github.com/transcranial/stochastic-depth/blob/master/stochastic-depth.ipynb
# https://github.com/shamangary/Pytorch-Stochastic-Depth-Resnet/blob/master/TYY_stodepth_lineardecay.py
# I will just stick with the official implementation, I think
# whether add relu after residual won't effect the network
# performance too much
x = self.residual(x) + self.shortcut(x)
else:
# If bl = 0, the ResBlock reduces to the identity function
x = self.shortcut(x)
else:
x = self.residual(x) * self.p + self.shortcut(x)
return x
class StochasticDepthBottleNeck(torch.jit.ScriptModule):
"""Residual block for resnet over 50 layers
"""
expansion = 4
def __init__(self, p, in_channels, out_channels, stride=1):
super().__init__()
self.p = p
self.residual = nn.Sequential(
nn.Conv2d(in_channels, out_channels, kernel_size=1, bias=False),
nn.BatchNorm2d(out_channels),
nn.ReLU(inplace=True),
nn.Conv2d(out_channels, out_channels, stride=stride, kernel_size=3, padding=1, bias=False),
nn.BatchNorm2d(out_channels),
nn.ReLU(inplace=True),
nn.Conv2d(out_channels, out_channels * StochasticDepthBottleNeck.expansion, kernel_size=1, bias=False),
nn.BatchNorm2d(out_channels * StochasticDepthBottleNeck.expansion),
)
self.shortcut = nn.Sequential()
if stride != 1 or in_channels != out_channels * StochasticDepthBottleNeck.expansion:
self.shortcut = nn.Sequential(
nn.Conv2d(in_channels, out_channels * StochasticDepthBottleNeck.expansion, stride=stride, kernel_size=1, bias=False),
nn.BatchNorm2d(out_channels * StochasticDepthBottleNeck.expansion)
)
def survival(self):
var = torch.bernoulli(torch.tensor(self.p).float())
return torch.equal(var, torch.tensor(1).float().to(var.device))
@torch.jit.script_method
def forward(self, x):
if self.training:
if self.survival():
x = self.residual(x) + self.shortcut(x)
else:
x = self.shortcut(x)
else:
x = self.residual(x) * self.p + self.shortcut(x)
return x
class StochasticDepthResNet(nn.Module):
def __init__(self, block, num_block, num_classes=100):
super().__init__()
self.in_channels = 64
self.conv1 = nn.Sequential(
nn.Conv2d(3, 64, kernel_size=3, padding=1),
nn.BatchNorm2d(64),
nn.ReLU(inplace=True)
)
self.step = (1 - 0.5) / (sum(num_block) - 1)
self.pl = 1
self.conv2_x = self._make_layer(block, 64, num_block[0], 1)
self.conv3_x = self._make_layer(block, 128, num_block[1], 2)
self.conv4_x = self._make_layer(block, 256, num_block[2], 2)
self.conv5_x = self._make_layer(block, 512, num_block[3], 2)
self.avg_pool = nn.AdaptiveAvgPool2d((1, 1))
self.fc = nn.Linear(512 * block.expansion, num_classes)
def _make_layer(self, block, out_channels, num_blocks, stride):
strides = [stride] + [1] * (num_blocks - 1)
layers = []
for stride in strides:
layers.append(block(self.pl, self.in_channels, out_channels, stride))
self.in_channels = out_channels * block.expansion
self.pl -= self.step
return nn.Sequential(*layers)
def forward(self, x):
output = self.conv1(x)
output = self.conv2_x(output)
output = self.conv3_x(output)
output = self.conv4_x(output)
output = self.conv5_x(output)
output = self.avg_pool(output)
output = output.view(output.size(0), -1)
output = self.fc(output)
return output
def stochastic_depth_resnet18():
""" return a ResNet 18 object
"""
return StochasticDepthResNet(StochasticDepthBasicBlock, [2, 2, 2, 2])
def stochastic_depth_resnet34():
""" return a ResNet 34 object
"""
return StochasticDepthResNet(StochasticDepthBasicBlock, [3, 4, 6, 3])
def stochastic_depth_resnet50():
""" return a ResNet 50 object
"""
return StochasticDepthResNet(StochasticDepthBottleNeck, [3, 4, 6, 3])
def stochastic_depth_resnet101():
""" return a ResNet 101 object
"""
return StochasticDepthResNet(StochasticDepthBottleNeck, [3, 4, 23, 3])
def stochastic_depth_resnet152():
""" return a ResNet 152 object
"""
return StochasticDepthResNet(StochasticDepthBottleNeck, [3, 8, 36, 3]) | zeus-ml | /zeus-ml-0.7.0.tar.gz/zeus-ml-0.7.0/examples/ZeusDataLoader/cifar100/models/stochasticdepth.py | stochasticdepth.py |
import torch
import torch.nn as nn
#geralized
class ResnetInit(nn.Module):
def __init__(self, in_channel, out_channel, stride):
super().__init__()
#"""The modular unit of the generalized residual network architecture is a
#generalized residual block consisting of parallel states for a residual stream,
#r, which contains identity shortcut connections and is similar to the structure
#of a residual block from the original ResNet with a single convolutional layer
#(parameters W l,r→r )
self.residual_stream_conv = nn.Conv2d(in_channel, out_channel, 3, padding=1, stride=stride)
#"""and a transient stream, t, which is a standard convolutional layer
#(W l,t→t )."""
self.transient_stream_conv = nn.Conv2d(in_channel, out_channel, 3, padding=1, stride=stride)
#"""Two additional sets of convolutional filters in each block (W l,r→t , W l,t→r )
#also transfer information across streams."""
self.residual_stream_conv_across = nn.Conv2d(in_channel, out_channel, 3, padding=1, stride=stride)
#"""We use equal numbers of filters for the residual and transient streams of the
#generalized residual network, but optimizing this hyperparameter could lead to
#further potential improvements."""
self.transient_stream_conv_across = nn.Conv2d(in_channel, out_channel, 3, padding=1, stride=stride)
self.residual_bn_relu = nn.Sequential(
nn.BatchNorm2d(out_channel),
nn.ReLU(inplace=True)
)
self.transient_bn_relu = nn.Sequential(
nn.BatchNorm2d(out_channel),
nn.ReLU(inplace=True)
)
#"""The form of the shortcut connection can be an identity function with
#the appropriate padding or a projection as in He et al. (2015b)."""
self.short_cut = nn.Sequential()
if in_channel != out_channel or stride != 1:
self.short_cut = nn.Sequential(
nn.Conv2d(in_channel, out_channel, kernel_size=1, stride=stride)
)
def forward(self, x):
x_residual, x_transient = x
residual_r_r = self.residual_stream_conv(x_residual)
residual_r_t = self.residual_stream_conv_across(x_residual)
residual_shortcut = self.short_cut(x_residual)
transient_t_t = self.transient_stream_conv(x_transient)
transient_t_r = self.transient_stream_conv_across(x_transient)
#transient_t_t = self.transient_stream_conv(x_residual)
#transient_t_r = self.transient_stream_conv_across(x_residual)
#"""Same-stream and cross-stream activations are summed (along with the
#shortcut connection for the residual stream) before applying batch
#normalization and ReLU nonlinearities (together σ) to get the output
#states of the block (Equation 1) (Ioffe & Szegedy, 2015)."""
x_residual = self.residual_bn_relu(residual_r_r + transient_t_r + residual_shortcut)
x_transient = self.transient_bn_relu(residual_r_t + transient_t_t)
return x_residual, x_transient
class RiRBlock(nn.Module):
def __init__(self, in_channel, out_channel, layer_num, stride, layer=ResnetInit):
super().__init__()
self.resnetinit = self._make_layers(in_channel, out_channel, layer_num, stride)
#self.short_cut = nn.Sequential()
#if stride != 1 or in_channel != out_channel:
# self.short_cut = nn.Conv2d(in_channel, out_channel, kernel_size=1, stride=stride)
def forward(self, x):
x_residual, x_transient = self.resnetinit(x)
#x_residual = x_residual + self.short_cut(x[0])
#x_transient = x_transient + self.short_cut(x[1])
return (x_residual, x_transient)
#"""Replacing each of the convolutional layers within a residual
#block from the original ResNet (Figure 1a) with a generalized residual block
#(Figure 1b) leads us to a new architecture we call ResNet in ResNet (RiR)
#(Figure 1d)."""
def _make_layers(self, in_channel, out_channel, layer_num, stride, layer=ResnetInit):
strides = [stride] + [1] * (layer_num - 1)
layers = nn.Sequential()
for index, s in enumerate(strides):
layers.add_module("generalized layers{}".format(index), layer(in_channel, out_channel, s))
in_channel = out_channel
return layers
class ResnetInResneet(nn.Module):
def __init__(self, num_classes=100):
super().__init__()
base = int(96 / 2)
self.residual_pre_conv = nn.Sequential(
nn.Conv2d(3, base, 3, padding=1),
nn.BatchNorm2d(base),
nn.ReLU(inplace=True)
)
self.transient_pre_conv = nn.Sequential(
nn.Conv2d(3, base, 3, padding=1),
nn.BatchNorm2d(base),
nn.ReLU(inplace=True)
)
self.rir1 = RiRBlock(base, base, 2, 1)
self.rir2 = RiRBlock(base, base, 2, 1)
self.rir3 = RiRBlock(base, base * 2, 2, 2)
self.rir4 = RiRBlock(base * 2, base * 2, 2, 1)
self.rir5 = RiRBlock(base * 2, base * 2, 2, 1)
self.rir6 = RiRBlock(base * 2, base * 4, 2, 2)
self.rir7 = RiRBlock(base * 4, base * 4, 2, 1)
self.rir8 = RiRBlock(base * 4, base * 4, 2, 1)
self.conv1 = nn.Sequential(
nn.Conv2d(384, num_classes, kernel_size=3, stride=2), #without this convolution, loss will soon be nan
nn.BatchNorm2d(num_classes),
nn.ReLU(inplace=True),
)
self.classifier = nn.Sequential(
nn.Linear(900, 450),
nn.ReLU(),
nn.Dropout(),
nn.Linear(450, 100),
)
self._weight_init()
def forward(self, x):
x_residual = self.residual_pre_conv(x)
x_transient = self.transient_pre_conv(x)
x_residual, x_transient = self.rir1((x_residual, x_transient))
x_residual, x_transient = self.rir2((x_residual, x_transient))
x_residual, x_transient = self.rir3((x_residual, x_transient))
x_residual, x_transient = self.rir4((x_residual, x_transient))
x_residual, x_transient = self.rir5((x_residual, x_transient))
x_residual, x_transient = self.rir6((x_residual, x_transient))
x_residual, x_transient = self.rir7((x_residual, x_transient))
x_residual, x_transient = self.rir8((x_residual, x_transient))
h = torch.cat([x_residual, x_transient], 1)
h = self.conv1(h)
h = h.view(h.size()[0], -1)
h = self.classifier(h)
return h
def _weight_init(self):
for m in self.modules():
if isinstance(m, nn.Conv2d):
torch.nn.init.kaiming_normal(m.weight)
m.bias.data.fill_(0.01)
def resnet_in_resnet():
return ResnetInResneet() | zeus-ml | /zeus-ml-0.7.0.tar.gz/zeus-ml-0.7.0/examples/ZeusDataLoader/cifar100/models/rir.py | rir.py |
import torch
import torch.nn as nn
class BasicConv2d(nn.Module):
def __init__(self, input_channels, output_channels, **kwargs):
super().__init__()
self.conv = nn.Conv2d(input_channels, output_channels, bias=False, **kwargs)
self.bn = nn.BatchNorm2d(output_channels)
self.relu = nn.ReLU(inplace=True)
def forward(self, x):
x = self.conv(x)
x = self.bn(x)
x = self.relu(x)
return x
class Inception_Stem(nn.Module):
#"""Figure 3. The schema for stem of the pure Inception-v4 and
#Inception-ResNet-v2 networks. This is the input part of those
#networks."""
def __init__(self, input_channels):
super().__init__()
self.conv1 = nn.Sequential(
BasicConv2d(input_channels, 32, kernel_size=3),
BasicConv2d(32, 32, kernel_size=3, padding=1),
BasicConv2d(32, 64, kernel_size=3, padding=1)
)
self.branch3x3_conv = BasicConv2d(64, 96, kernel_size=3, padding=1)
self.branch3x3_pool = nn.MaxPool2d(3, stride=1, padding=1)
self.branch7x7a = nn.Sequential(
BasicConv2d(160, 64, kernel_size=1),
BasicConv2d(64, 64, kernel_size=(7, 1), padding=(3, 0)),
BasicConv2d(64, 64, kernel_size=(1, 7), padding=(0, 3)),
BasicConv2d(64, 96, kernel_size=3, padding=1)
)
self.branch7x7b = nn.Sequential(
BasicConv2d(160, 64, kernel_size=1),
BasicConv2d(64, 96, kernel_size=3, padding=1)
)
self.branchpoola = nn.MaxPool2d(kernel_size=3, stride=1, padding=1)
self.branchpoolb = BasicConv2d(192, 192, kernel_size=3, stride=1, padding=1)
def forward(self, x):
x = self.conv1(x)
x = [
self.branch3x3_conv(x),
self.branch3x3_pool(x)
]
x = torch.cat(x, 1)
x = [
self.branch7x7a(x),
self.branch7x7b(x)
]
x = torch.cat(x, 1)
x = [
self.branchpoola(x),
self.branchpoolb(x)
]
x = torch.cat(x, 1)
return x
class InceptionA(nn.Module):
#"""Figure 4. The schema for 35 × 35 grid modules of the pure
#Inception-v4 network. This is the Inception-A block of Figure 9."""
def __init__(self, input_channels):
super().__init__()
self.branch3x3stack = nn.Sequential(
BasicConv2d(input_channels, 64, kernel_size=1),
BasicConv2d(64, 96, kernel_size=3, padding=1),
BasicConv2d(96, 96, kernel_size=3, padding=1)
)
self.branch3x3 = nn.Sequential(
BasicConv2d(input_channels, 64, kernel_size=1),
BasicConv2d(64, 96, kernel_size=3, padding=1)
)
self.branch1x1 = BasicConv2d(input_channels, 96, kernel_size=1)
self.branchpool = nn.Sequential(
nn.AvgPool2d(kernel_size=3, stride=1, padding=1),
BasicConv2d(input_channels, 96, kernel_size=1)
)
def forward(self, x):
x = [
self.branch3x3stack(x),
self.branch3x3(x),
self.branch1x1(x),
self.branchpool(x)
]
return torch.cat(x, 1)
class ReductionA(nn.Module):
#"""Figure 7. The schema for 35 × 35 to 17 × 17 reduction module.
#Different variants of this blocks (with various number of filters)
#are used in Figure 9, and 15 in each of the new Inception(-v4, - ResNet-v1,
#-ResNet-v2) variants presented in this paper. The k, l, m, n numbers
#represent filter bank sizes which can be looked up in Table 1.
def __init__(self, input_channels, k, l, m, n):
super().__init__()
self.branch3x3stack = nn.Sequential(
BasicConv2d(input_channels, k, kernel_size=1),
BasicConv2d(k, l, kernel_size=3, padding=1),
BasicConv2d(l, m, kernel_size=3, stride=2)
)
self.branch3x3 = BasicConv2d(input_channels, n, kernel_size=3, stride=2)
self.branchpool = nn.MaxPool2d(kernel_size=3, stride=2)
self.output_channels = input_channels + n + m
def forward(self, x):
x = [
self.branch3x3stack(x),
self.branch3x3(x),
self.branchpool(x)
]
return torch.cat(x, 1)
class InceptionB(nn.Module):
#"""Figure 5. The schema for 17 × 17 grid modules of the pure Inception-v4 network.
#This is the Inception-B block of Figure 9."""
def __init__(self, input_channels):
super().__init__()
self.branch7x7stack = nn.Sequential(
BasicConv2d(input_channels, 192, kernel_size=1),
BasicConv2d(192, 192, kernel_size=(1, 7), padding=(0, 3)),
BasicConv2d(192, 224, kernel_size=(7, 1), padding=(3, 0)),
BasicConv2d(224, 224, kernel_size=(1, 7), padding=(0, 3)),
BasicConv2d(224, 256, kernel_size=(7, 1), padding=(3, 0))
)
self.branch7x7 = nn.Sequential(
BasicConv2d(input_channels, 192, kernel_size=1),
BasicConv2d(192, 224, kernel_size=(1, 7), padding=(0, 3)),
BasicConv2d(224, 256, kernel_size=(7, 1), padding=(3, 0))
)
self.branch1x1 = BasicConv2d(input_channels, 384, kernel_size=1)
self.branchpool = nn.Sequential(
nn.AvgPool2d(3, stride=1, padding=1),
BasicConv2d(input_channels, 128, kernel_size=1)
)
def forward(self, x):
x = [
self.branch1x1(x),
self.branch7x7(x),
self.branch7x7stack(x),
self.branchpool(x)
]
return torch.cat(x, 1)
class ReductionB(nn.Module):
#"""Figure 8. The schema for 17 × 17 to 8 × 8 grid-reduction mod- ule.
#This is the reduction module used by the pure Inception-v4 network in
#Figure 9."""
def __init__(self, input_channels):
super().__init__()
self.branch7x7 = nn.Sequential(
BasicConv2d(input_channels, 256, kernel_size=1),
BasicConv2d(256, 256, kernel_size=(1, 7), padding=(0, 3)),
BasicConv2d(256, 320, kernel_size=(7, 1), padding=(3, 0)),
BasicConv2d(320, 320, kernel_size=3, stride=2, padding=1)
)
self.branch3x3 = nn.Sequential(
BasicConv2d(input_channels, 192, kernel_size=1),
BasicConv2d(192, 192, kernel_size=3, stride=2, padding=1)
)
self.branchpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
def forward(self, x):
x = [
self.branch3x3(x),
self.branch7x7(x),
self.branchpool(x)
]
return torch.cat(x, 1)
class InceptionC(nn.Module):
def __init__(self, input_channels):
#"""Figure 6. The schema for 8×8 grid modules of the pure
#Inceptionv4 network. This is the Inception-C block of Figure 9."""
super().__init__()
self.branch3x3stack = nn.Sequential(
BasicConv2d(input_channels, 384, kernel_size=1),
BasicConv2d(384, 448, kernel_size=(1, 3), padding=(0, 1)),
BasicConv2d(448, 512, kernel_size=(3, 1), padding=(1, 0)),
)
self.branch3x3stacka = BasicConv2d(512, 256, kernel_size=(1, 3), padding=(0, 1))
self.branch3x3stackb = BasicConv2d(512, 256, kernel_size=(3, 1), padding=(1, 0))
self.branch3x3 = BasicConv2d(input_channels, 384, kernel_size=1)
self.branch3x3a = BasicConv2d(384, 256, kernel_size=(3, 1), padding=(1, 0))
self.branch3x3b = BasicConv2d(384, 256, kernel_size=(1, 3), padding=(0, 1))
self.branch1x1 = BasicConv2d(input_channels, 256, kernel_size=1)
self.branchpool = nn.Sequential(
nn.AvgPool2d(kernel_size=3, stride=1, padding=1),
BasicConv2d(input_channels, 256, kernel_size=1)
)
def forward(self, x):
branch3x3stack_output = self.branch3x3stack(x)
branch3x3stack_output = [
self.branch3x3stacka(branch3x3stack_output),
self.branch3x3stackb(branch3x3stack_output)
]
branch3x3stack_output = torch.cat(branch3x3stack_output, 1)
branch3x3_output = self.branch3x3(x)
branch3x3_output = [
self.branch3x3a(branch3x3_output),
self.branch3x3b(branch3x3_output)
]
branch3x3_output = torch.cat(branch3x3_output, 1)
branch1x1_output = self.branch1x1(x)
branchpool = self.branchpool(x)
output = [
branch1x1_output,
branch3x3_output,
branch3x3stack_output,
branchpool
]
return torch.cat(output, 1)
class InceptionV4(nn.Module):
def __init__(self, A, B, C, k=192, l=224, m=256, n=384, class_nums=100):
super().__init__()
self.stem = Inception_Stem(3)
self.inception_a = self._generate_inception_module(384, 384, A, InceptionA)
self.reduction_a = ReductionA(384, k, l, m, n)
output_channels = self.reduction_a.output_channels
self.inception_b = self._generate_inception_module(output_channels, 1024, B, InceptionB)
self.reduction_b = ReductionB(1024)
self.inception_c = self._generate_inception_module(1536, 1536, C, InceptionC)
self.avgpool = nn.AvgPool2d(7)
#"""Dropout (keep 0.8)"""
self.dropout = nn.Dropout2d(1 - 0.8)
self.linear = nn.Linear(1536, class_nums)
def forward(self, x):
x = self.stem(x)
x = self.inception_a(x)
x = self.reduction_a(x)
x = self.inception_b(x)
x = self.reduction_b(x)
x = self.inception_c(x)
x = self.avgpool(x)
x = self.dropout(x)
x = x.view(-1, 1536)
x = self.linear(x)
return x
@staticmethod
def _generate_inception_module(input_channels, output_channels, block_num, block):
layers = nn.Sequential()
for l in range(block_num):
layers.add_module("{}_{}".format(block.__name__, l), block(input_channels))
input_channels = output_channels
return layers
class InceptionResNetA(nn.Module):
#"""Figure 16. The schema for 35 × 35 grid (Inception-ResNet-A)
#module of the Inception-ResNet-v2 network."""
def __init__(self, input_channels):
super().__init__()
self.branch3x3stack = nn.Sequential(
BasicConv2d(input_channels, 32, kernel_size=1),
BasicConv2d(32, 48, kernel_size=3, padding=1),
BasicConv2d(48, 64, kernel_size=3, padding=1)
)
self.branch3x3 = nn.Sequential(
BasicConv2d(input_channels, 32, kernel_size=1),
BasicConv2d(32, 32, kernel_size=3, padding=1)
)
self.branch1x1 = BasicConv2d(input_channels, 32, kernel_size=1)
self.reduction1x1 = nn.Conv2d(128, 384, kernel_size=1)
self.shortcut = nn.Conv2d(input_channels, 384, kernel_size=1)
self.bn = nn.BatchNorm2d(384)
self.relu = nn.ReLU(inplace=True)
def forward(self, x):
residual = [
self.branch1x1(x),
self.branch3x3(x),
self.branch3x3stack(x)
]
residual = torch.cat(residual, 1)
residual = self.reduction1x1(residual)
shortcut = self.shortcut(x)
output = self.bn(shortcut + residual)
output = self.relu(output)
return output
class InceptionResNetB(nn.Module):
#"""Figure 17. The schema for 17 × 17 grid (Inception-ResNet-B) module of
#the Inception-ResNet-v2 network."""
def __init__(self, input_channels):
super().__init__()
self.branch7x7 = nn.Sequential(
BasicConv2d(input_channels, 128, kernel_size=1),
BasicConv2d(128, 160, kernel_size=(1, 7), padding=(0, 3)),
BasicConv2d(160, 192, kernel_size=(7, 1), padding=(3, 0))
)
self.branch1x1 = BasicConv2d(input_channels, 192, kernel_size=1)
self.reduction1x1 = nn.Conv2d(384, 1154, kernel_size=1)
self.shortcut = nn.Conv2d(input_channels, 1154, kernel_size=1)
self.bn = nn.BatchNorm2d(1154)
self.relu = nn.ReLU(inplace=True)
def forward(self, x):
residual = [
self.branch1x1(x),
self.branch7x7(x)
]
residual = torch.cat(residual, 1)
#"""In general we picked some scaling factors between 0.1 and 0.3 to scale the residuals
#before their being added to the accumulated layer activations (cf. Figure 20)."""
residual = self.reduction1x1(residual) * 0.1
shortcut = self.shortcut(x)
output = self.bn(residual + shortcut)
output = self.relu(output)
return output
class InceptionResNetC(nn.Module):
def __init__(self, input_channels):
#Figure 19. The schema for 8×8 grid (Inception-ResNet-C)
#module of the Inception-ResNet-v2 network."""
super().__init__()
self.branch3x3 = nn.Sequential(
BasicConv2d(input_channels, 192, kernel_size=1),
BasicConv2d(192, 224, kernel_size=(1, 3), padding=(0, 1)),
BasicConv2d(224, 256, kernel_size=(3, 1), padding=(1, 0))
)
self.branch1x1 = BasicConv2d(input_channels, 192, kernel_size=1)
self.reduction1x1 = nn.Conv2d(448, 2048, kernel_size=1)
self.shorcut = nn.Conv2d(input_channels, 2048, kernel_size=1)
self.bn = nn.BatchNorm2d(2048)
self.relu = nn.ReLU(inplace=True)
def forward(self, x):
residual = [
self.branch1x1(x),
self.branch3x3(x)
]
residual = torch.cat(residual, 1)
residual = self.reduction1x1(residual) * 0.1
shorcut = self.shorcut(x)
output = self.bn(shorcut + residual)
output = self.relu(output)
return output
class InceptionResNetReductionA(nn.Module):
#"""Figure 7. The schema for 35 × 35 to 17 × 17 reduction module.
#Different variants of this blocks (with various number of filters)
#are used in Figure 9, and 15 in each of the new Inception(-v4, - ResNet-v1,
#-ResNet-v2) variants presented in this paper. The k, l, m, n numbers
#represent filter bank sizes which can be looked up in Table 1.
def __init__(self, input_channels, k, l, m, n):
super().__init__()
self.branch3x3stack = nn.Sequential(
BasicConv2d(input_channels, k, kernel_size=1),
BasicConv2d(k, l, kernel_size=3, padding=1),
BasicConv2d(l, m, kernel_size=3, stride=2)
)
self.branch3x3 = BasicConv2d(input_channels, n, kernel_size=3, stride=2)
self.branchpool = nn.MaxPool2d(kernel_size=3, stride=2)
self.output_channels = input_channels + n + m
def forward(self, x):
x = [
self.branch3x3stack(x),
self.branch3x3(x),
self.branchpool(x)
]
return torch.cat(x, 1)
class InceptionResNetReductionB(nn.Module):
#"""Figure 18. The schema for 17 × 17 to 8 × 8 grid-reduction module.
#Reduction-B module used by the wider Inception-ResNet-v1 network in
#Figure 15."""
#I believe it was a typo(Inception-ResNet-v1 should be Inception-ResNet-v2)
def __init__(self, input_channels):
super().__init__()
self.branchpool = nn.MaxPool2d(3, stride=2)
self.branch3x3a = nn.Sequential(
BasicConv2d(input_channels, 256, kernel_size=1),
BasicConv2d(256, 384, kernel_size=3, stride=2)
)
self.branch3x3b = nn.Sequential(
BasicConv2d(input_channels, 256, kernel_size=1),
BasicConv2d(256, 288, kernel_size=3, stride=2)
)
self.branch3x3stack = nn.Sequential(
BasicConv2d(input_channels, 256, kernel_size=1),
BasicConv2d(256, 288, kernel_size=3, padding=1),
BasicConv2d(288, 320, kernel_size=3, stride=2)
)
def forward(self, x):
x = [
self.branch3x3a(x),
self.branch3x3b(x),
self.branch3x3stack(x),
self.branchpool(x)
]
x = torch.cat(x, 1)
return x
class InceptionResNetV2(nn.Module):
def __init__(self, A, B, C, k=256, l=256, m=384, n=384, class_nums=100):
super().__init__()
self.stem = Inception_Stem(3)
self.inception_resnet_a = self._generate_inception_module(384, 384, A, InceptionResNetA)
self.reduction_a = InceptionResNetReductionA(384, k, l, m, n)
output_channels = self.reduction_a.output_channels
self.inception_resnet_b = self._generate_inception_module(output_channels, 1154, B, InceptionResNetB)
self.reduction_b = InceptionResNetReductionB(1154)
self.inception_resnet_c = self._generate_inception_module(2146, 2048, C, InceptionResNetC)
#6x6 featuresize
self.avgpool = nn.AdaptiveAvgPool2d((1, 1))
#"""Dropout (keep 0.8)"""
self.dropout = nn.Dropout2d(1 - 0.8)
self.linear = nn.Linear(2048, class_nums)
def forward(self, x):
x = self.stem(x)
x = self.inception_resnet_a(x)
x = self.reduction_a(x)
x = self.inception_resnet_b(x)
x = self.reduction_b(x)
x = self.inception_resnet_c(x)
x = self.avgpool(x)
x = self.dropout(x)
x = x.view(-1, 2048)
x = self.linear(x)
return x
@staticmethod
def _generate_inception_module(input_channels, output_channels, block_num, block):
layers = nn.Sequential()
for l in range(block_num):
layers.add_module("{}_{}".format(block.__name__, l), block(input_channels))
input_channels = output_channels
return layers
def inceptionv4():
return InceptionV4(4, 7, 3)
def inception_resnet_v2():
return InceptionResNetV2(5, 10, 5) | zeus-ml | /zeus-ml-0.7.0.tar.gz/zeus-ml-0.7.0/examples/ZeusDataLoader/cifar100/models/inceptionv4.py | inceptionv4.py |
import torch
import torch.nn as nn
import torch.nn.functional as F
class BasicResidualSEBlock(nn.Module):
expansion = 1
def __init__(self, in_channels, out_channels, stride, r=16):
super().__init__()
self.residual = nn.Sequential(
nn.Conv2d(in_channels, out_channels, 3, stride=stride, padding=1),
nn.BatchNorm2d(out_channels),
nn.ReLU(inplace=True),
nn.Conv2d(out_channels, out_channels * self.expansion, 3, padding=1),
nn.BatchNorm2d(out_channels * self.expansion),
nn.ReLU(inplace=True)
)
self.shortcut = nn.Sequential()
if stride != 1 or in_channels != out_channels * self.expansion:
self.shortcut = nn.Sequential(
nn.Conv2d(in_channels, out_channels * self.expansion, 1, stride=stride),
nn.BatchNorm2d(out_channels * self.expansion)
)
self.squeeze = nn.AdaptiveAvgPool2d(1)
self.excitation = nn.Sequential(
nn.Linear(out_channels * self.expansion, out_channels * self.expansion // r),
nn.ReLU(inplace=True),
nn.Linear(out_channels * self.expansion // r, out_channels * self.expansion),
nn.Sigmoid()
)
def forward(self, x):
shortcut = self.shortcut(x)
residual = self.residual(x)
squeeze = self.squeeze(residual)
squeeze = squeeze.view(squeeze.size(0), -1)
excitation = self.excitation(squeeze)
excitation = excitation.view(residual.size(0), residual.size(1), 1, 1)
x = residual * excitation.expand_as(residual) + shortcut
return F.relu(x)
class BottleneckResidualSEBlock(nn.Module):
expansion = 4
def __init__(self, in_channels, out_channels, stride, r=16):
super().__init__()
self.residual = nn.Sequential(
nn.Conv2d(in_channels, out_channels, 1),
nn.BatchNorm2d(out_channels),
nn.ReLU(inplace=True),
nn.Conv2d(out_channels, out_channels, 3, stride=stride, padding=1),
nn.BatchNorm2d(out_channels),
nn.ReLU(inplace=True),
nn.Conv2d(out_channels, out_channels * self.expansion, 1),
nn.BatchNorm2d(out_channels * self.expansion),
nn.ReLU(inplace=True)
)
self.squeeze = nn.AdaptiveAvgPool2d(1)
self.excitation = nn.Sequential(
nn.Linear(out_channels * self.expansion, out_channels * self.expansion // r),
nn.ReLU(inplace=True),
nn.Linear(out_channels * self.expansion // r, out_channels * self.expansion),
nn.Sigmoid()
)
self.shortcut = nn.Sequential()
if stride != 1 or in_channels != out_channels * self.expansion:
self.shortcut = nn.Sequential(
nn.Conv2d(in_channels, out_channels * self.expansion, 1, stride=stride),
nn.BatchNorm2d(out_channels * self.expansion)
)
def forward(self, x):
shortcut = self.shortcut(x)
residual = self.residual(x)
squeeze = self.squeeze(residual)
squeeze = squeeze.view(squeeze.size(0), -1)
excitation = self.excitation(squeeze)
excitation = excitation.view(residual.size(0), residual.size(1), 1, 1)
x = residual * excitation.expand_as(residual) + shortcut
return F.relu(x)
class SEResNet(nn.Module):
def __init__(self, block, block_num, class_num=100):
super().__init__()
self.in_channels = 64
self.pre = nn.Sequential(
nn.Conv2d(3, 64, 3, padding=1),
nn.BatchNorm2d(64),
nn.ReLU(inplace=True)
)
self.stage1 = self._make_stage(block, block_num[0], 64, 1)
self.stage2 = self._make_stage(block, block_num[1], 128, 2)
self.stage3 = self._make_stage(block, block_num[2], 256, 2)
self.stage4 = self._make_stage(block, block_num[3], 512, 2)
self.linear = nn.Linear(self.in_channels, class_num)
def forward(self, x):
x = self.pre(x)
x = self.stage1(x)
x = self.stage2(x)
x = self.stage3(x)
x = self.stage4(x)
x = F.adaptive_avg_pool2d(x, 1)
x = x.view(x.size(0), -1)
x = self.linear(x)
return x
def _make_stage(self, block, num, out_channels, stride):
layers = []
layers.append(block(self.in_channels, out_channels, stride))
self.in_channels = out_channels * block.expansion
while num - 1:
layers.append(block(self.in_channels, out_channels, 1))
num -= 1
return nn.Sequential(*layers)
def seresnet18():
return SEResNet(BasicResidualSEBlock, [2, 2, 2, 2])
def seresnet34():
return SEResNet(BasicResidualSEBlock, [3, 4, 6, 3])
def seresnet50():
return SEResNet(BottleneckResidualSEBlock, [3, 4, 6, 3])
def seresnet101():
return SEResNet(BottleneckResidualSEBlock, [3, 4, 23, 3])
def seresnet152():
return SEResNet(BottleneckResidualSEBlock, [3, 8, 36, 3]) | zeus-ml | /zeus-ml-0.7.0.tar.gz/zeus-ml-0.7.0/examples/ZeusDataLoader/cifar100/models/senet.py | senet.py |
import torch
import torch.nn as nn
#"""Bottleneck layers. Although each layer only produces k
#output feature-maps, it typically has many more inputs. It
#has been noted in [37, 11] that a 1×1 convolution can be in-
#troduced as bottleneck layer before each 3×3 convolution
#to reduce the number of input feature-maps, and thus to
#improve computational efficiency."""
class Bottleneck(nn.Module):
def __init__(self, in_channels, growth_rate):
super().__init__()
#"""In our experiments, we let each 1×1 convolution
#produce 4k feature-maps."""
inner_channel = 4 * growth_rate
#"""We find this design especially effective for DenseNet and
#we refer to our network with such a bottleneck layer, i.e.,
#to the BN-ReLU-Conv(1×1)-BN-ReLU-Conv(3×3) version of H ` ,
#as DenseNet-B."""
self.bottle_neck = nn.Sequential(
nn.BatchNorm2d(in_channels),
nn.ReLU(inplace=True),
nn.Conv2d(in_channels, inner_channel, kernel_size=1, bias=False),
nn.BatchNorm2d(inner_channel),
nn.ReLU(inplace=True),
nn.Conv2d(inner_channel, growth_rate, kernel_size=3, padding=1, bias=False)
)
def forward(self, x):
return torch.cat([x, self.bottle_neck(x)], 1)
#"""We refer to layers between blocks as transition
#layers, which do convolution and pooling."""
class Transition(nn.Module):
def __init__(self, in_channels, out_channels):
super().__init__()
#"""The transition layers used in our experiments
#consist of a batch normalization layer and an 1×1
#convolutional layer followed by a 2×2 average pooling
#layer""".
self.down_sample = nn.Sequential(
nn.BatchNorm2d(in_channels),
nn.Conv2d(in_channels, out_channels, 1, bias=False),
nn.AvgPool2d(2, stride=2)
)
def forward(self, x):
return self.down_sample(x)
#DesneNet-BC
#B stands for bottleneck layer(BN-RELU-CONV(1x1)-BN-RELU-CONV(3x3))
#C stands for compression factor(0<=theta<=1)
class DenseNet(nn.Module):
def __init__(self, block, nblocks, growth_rate=12, reduction=0.5, num_class=100):
super().__init__()
self.growth_rate = growth_rate
#"""Before entering the first dense block, a convolution
#with 16 (or twice the growth rate for DenseNet-BC)
#output channels is performed on the input images."""
inner_channels = 2 * growth_rate
#For convolutional layers with kernel size 3×3, each
#side of the inputs is zero-padded by one pixel to keep
#the feature-map size fixed.
self.conv1 = nn.Conv2d(3, inner_channels, kernel_size=3, padding=1, bias=False)
self.features = nn.Sequential()
for index in range(len(nblocks) - 1):
self.features.add_module("dense_block_layer_{}".format(index), self._make_dense_layers(block, inner_channels, nblocks[index]))
inner_channels += growth_rate * nblocks[index]
#"""If a dense block contains m feature-maps, we let the
#following transition layer generate θm output feature-
#maps, where 0 < θ ≤ 1 is referred to as the compression
#fac-tor.
out_channels = int(reduction * inner_channels) # int() will automatic floor the value
self.features.add_module("transition_layer_{}".format(index), Transition(inner_channels, out_channels))
inner_channels = out_channels
self.features.add_module("dense_block{}".format(len(nblocks) - 1), self._make_dense_layers(block, inner_channels, nblocks[len(nblocks)-1]))
inner_channels += growth_rate * nblocks[len(nblocks) - 1]
self.features.add_module('bn', nn.BatchNorm2d(inner_channels))
self.features.add_module('relu', nn.ReLU(inplace=True))
self.avgpool = nn.AdaptiveAvgPool2d((1, 1))
self.linear = nn.Linear(inner_channels, num_class)
def forward(self, x):
output = self.conv1(x)
output = self.features(output)
output = self.avgpool(output)
output = output.view(output.size()[0], -1)
output = self.linear(output)
return output
def _make_dense_layers(self, block, in_channels, nblocks):
dense_block = nn.Sequential()
for index in range(nblocks):
dense_block.add_module('bottle_neck_layer_{}'.format(index), block(in_channels, self.growth_rate))
in_channels += self.growth_rate
return dense_block
def densenet121():
return DenseNet(Bottleneck, [6,12,24,16], growth_rate=32)
def densenet169():
return DenseNet(Bottleneck, [6,12,32,32], growth_rate=32)
def densenet201():
return DenseNet(Bottleneck, [6,12,48,32], growth_rate=32)
def densenet161():
return DenseNet(Bottleneck, [6,12,36,24], growth_rate=48) | zeus-ml | /zeus-ml-0.7.0.tar.gz/zeus-ml-0.7.0/examples/ZeusDataLoader/cifar100/models/densenet.py | densenet.py |
from functools import partial
import torch
import torch.nn as nn
class BasicConv2d(nn.Module):
def __init__(self, input_channels, output_channels, kernel_size, **kwargs):
super().__init__()
self.conv = nn.Conv2d(input_channels, output_channels, kernel_size, **kwargs)
self.bn = nn.BatchNorm2d(output_channels)
self.relu = nn.ReLU(inplace=True)
def forward(self, x):
x = self.conv(x)
x = self.bn(x)
x = self.relu(x)
return x
class ChannelShuffle(nn.Module):
def __init__(self, groups):
super().__init__()
self.groups = groups
def forward(self, x):
batchsize, channels, height, width = x.data.size()
channels_per_group = int(channels / self.groups)
#"""suppose a convolutional layer with g groups whose output has
#g x n channels; we first reshape the output channel dimension
#into (g, n)"""
x = x.view(batchsize, self.groups, channels_per_group, height, width)
#"""transposing and then flattening it back as the input of next layer."""
x = x.transpose(1, 2).contiguous()
x = x.view(batchsize, -1, height, width)
return x
class DepthwiseConv2d(nn.Module):
def __init__(self, input_channels, output_channels, kernel_size, **kwargs):
super().__init__()
self.depthwise = nn.Sequential(
nn.Conv2d(input_channels, output_channels, kernel_size, **kwargs),
nn.BatchNorm2d(output_channels)
)
def forward(self, x):
return self.depthwise(x)
class PointwiseConv2d(nn.Module):
def __init__(self, input_channels, output_channels, **kwargs):
super().__init__()
self.pointwise = nn.Sequential(
nn.Conv2d(input_channels, output_channels, 1, **kwargs),
nn.BatchNorm2d(output_channels)
)
def forward(self, x):
return self.pointwise(x)
class ShuffleNetUnit(nn.Module):
def __init__(self, input_channels, output_channels, stage, stride, groups):
super().__init__()
#"""Similar to [9], we set the number of bottleneck channels to 1/4
#of the output channels for each ShuffleNet unit."""
self.bottlneck = nn.Sequential(
PointwiseConv2d(
input_channels,
int(output_channels / 4),
groups=groups
),
nn.ReLU(inplace=True)
)
#"""Note that for Stage 2, we do not apply group convolution on the first pointwise
#layer because the number of input channels is relatively small."""
if stage == 2:
self.bottlneck = nn.Sequential(
PointwiseConv2d(
input_channels,
int(output_channels / 4),
groups=groups
),
nn.ReLU(inplace=True)
)
self.channel_shuffle = ChannelShuffle(groups)
self.depthwise = DepthwiseConv2d(
int(output_channels / 4),
int(output_channels / 4),
3,
groups=int(output_channels / 4),
stride=stride,
padding=1
)
self.expand = PointwiseConv2d(
int(output_channels / 4),
output_channels,
groups=groups
)
self.relu = nn.ReLU(inplace=True)
self.fusion = self._add
self.shortcut = nn.Sequential()
#"""As for the case where ShuffleNet is applied with stride,
#we simply make two modifications (see Fig 2 (c)):
#(i) add a 3 × 3 average pooling on the shortcut path;
#(ii) replace the element-wise addition with channel concatenation,
#which makes it easy to enlarge channel dimension with little extra
#computation cost.
if stride != 1 or input_channels != output_channels:
self.shortcut = nn.AvgPool2d(3, stride=2, padding=1)
self.expand = PointwiseConv2d(
int(output_channels / 4),
output_channels - input_channels,
groups=groups
)
self.fusion = self._cat
def _add(self, x, y):
return torch.add(x, y)
def _cat(self, x, y):
return torch.cat([x, y], dim=1)
def forward(self, x):
shortcut = self.shortcut(x)
shuffled = self.bottlneck(x)
shuffled = self.channel_shuffle(shuffled)
shuffled = self.depthwise(shuffled)
shuffled = self.expand(shuffled)
output = self.fusion(shortcut, shuffled)
output = self.relu(output)
return output
class ShuffleNet(nn.Module):
def __init__(self, num_blocks, num_classes=100, groups=3):
super().__init__()
if groups == 1:
out_channels = [24, 144, 288, 567]
elif groups == 2:
out_channels = [24, 200, 400, 800]
elif groups == 3:
out_channels = [24, 240, 480, 960]
elif groups == 4:
out_channels = [24, 272, 544, 1088]
elif groups == 8:
out_channels = [24, 384, 768, 1536]
self.conv1 = BasicConv2d(3, out_channels[0], 3, padding=1, stride=1)
self.input_channels = out_channels[0]
self.stage2 = self._make_stage(
ShuffleNetUnit,
num_blocks[0],
out_channels[1],
stride=2,
stage=2,
groups=groups
)
self.stage3 = self._make_stage(
ShuffleNetUnit,
num_blocks[1],
out_channels[2],
stride=2,
stage=3,
groups=groups
)
self.stage4 = self._make_stage(
ShuffleNetUnit,
num_blocks[2],
out_channels[3],
stride=2,
stage=4,
groups=groups
)
self.avg = nn.AdaptiveAvgPool2d((1, 1))
self.fc = nn.Linear(out_channels[3], num_classes)
def forward(self, x):
x = self.conv1(x)
x = self.stage2(x)
x = self.stage3(x)
x = self.stage4(x)
x = self.avg(x)
x = x.view(x.size(0), -1)
x = self.fc(x)
return x
def _make_stage(self, block, num_blocks, output_channels, stride, stage, groups):
"""make shufflenet stage
Args:
block: block type, shuffle unit
out_channels: output depth channel number of this stage
num_blocks: how many blocks per stage
stride: the stride of the first block of this stage
stage: stage index
groups: group number of group convolution
Return:
return a shuffle net stage
"""
strides = [stride] + [1] * (num_blocks - 1)
stage = []
for stride in strides:
stage.append(
block(
self.input_channels,
output_channels,
stride=stride,
stage=stage,
groups=groups
)
)
self.input_channels = output_channels
return nn.Sequential(*stage)
def shufflenet():
return ShuffleNet([4, 8, 4]) | zeus-ml | /zeus-ml-0.7.0.tar.gz/zeus-ml-0.7.0/examples/ZeusDataLoader/cifar100/models/shufflenet.py | shufflenet.py |
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
#only implements ResNext bottleneck c
#"""This strategy exposes a new dimension, which we call “cardinality”
#(the size of the set of transformations), as an essential factor
#in addition to the dimensions of depth and width."""
CARDINALITY = 32
DEPTH = 4
BASEWIDTH = 64
#"""The grouped convolutional layer in Fig. 3(c) performs 32 groups
#of convolutions whose input and output channels are 4-dimensional.
#The grouped convolutional layer concatenates them as the outputs
#of the layer."""
class ResNextBottleNeckC(nn.Module):
def __init__(self, in_channels, out_channels, stride):
super().__init__()
C = CARDINALITY #How many groups a feature map was splitted into
#"""We note that the input/output width of the template is fixed as
#256-d (Fig. 3), We note that the input/output width of the template
#is fixed as 256-d (Fig. 3), and all widths are dou- bled each time
#when the feature map is subsampled (see Table 1)."""
D = int(DEPTH * out_channels / BASEWIDTH) #number of channels per group
self.split_transforms = nn.Sequential(
nn.Conv2d(in_channels, C * D, kernel_size=1, groups=C, bias=False),
nn.BatchNorm2d(C * D),
nn.ReLU(inplace=True),
nn.Conv2d(C * D, C * D, kernel_size=3, stride=stride, groups=C, padding=1, bias=False),
nn.BatchNorm2d(C * D),
nn.ReLU(inplace=True),
nn.Conv2d(C * D, out_channels * 4, kernel_size=1, bias=False),
nn.BatchNorm2d(out_channels * 4),
)
self.shortcut = nn.Sequential()
if stride != 1 or in_channels != out_channels * 4:
self.shortcut = nn.Sequential(
nn.Conv2d(in_channels, out_channels * 4, stride=stride, kernel_size=1, bias=False),
nn.BatchNorm2d(out_channels * 4)
)
def forward(self, x):
return F.relu(self.split_transforms(x) + self.shortcut(x))
class ResNext(nn.Module):
def __init__(self, block, num_blocks, class_names=100):
super().__init__()
self.in_channels = 64
self.conv1 = nn.Sequential(
nn.Conv2d(3, 64, 3, stride=1, padding=1, bias=False),
nn.BatchNorm2d(64),
nn.ReLU(inplace=True)
)
self.conv2 = self._make_layer(block, num_blocks[0], 64, 1)
self.conv3 = self._make_layer(block, num_blocks[1], 128, 2)
self.conv4 = self._make_layer(block, num_blocks[2], 256, 2)
self.conv5 = self._make_layer(block, num_blocks[3], 512, 2)
self.avg = nn.AdaptiveAvgPool2d((1, 1))
self.fc = nn.Linear(512 * 4, 100)
def forward(self, x):
x = self.conv1(x)
x = self.conv2(x)
x = self.conv3(x)
x = self.conv4(x)
x = self.conv5(x)
x = self.avg(x)
x = x.view(x.size(0), -1)
x = self.fc(x)
return x
def _make_layer(self, block, num_block, out_channels, stride):
"""Building resnext block
Args:
block: block type(default resnext bottleneck c)
num_block: number of blocks per layer
out_channels: output channels per block
stride: block stride
Returns:
a resnext layer
"""
strides = [stride] + [1] * (num_block - 1)
layers = []
for stride in strides:
layers.append(block(self.in_channels, out_channels, stride))
self.in_channels = out_channels * 4
return nn.Sequential(*layers)
def resnext50():
""" return a resnext50(c32x4d) network
"""
return ResNext(ResNextBottleNeckC, [3, 4, 6, 3])
def resnext101():
""" return a resnext101(c32x4d) network
"""
return ResNext(ResNextBottleNeckC, [3, 4, 23, 3])
def resnext152():
""" return a resnext101(c32x4d) network
"""
return ResNext(ResNextBottleNeckC, [3, 4, 36, 3]) | zeus-ml | /zeus-ml-0.7.0.tar.gz/zeus-ml-0.7.0/examples/ZeusDataLoader/cifar100/models/resnext.py | resnext.py |
import torch
import torch.nn as nn
class DepthSeperabelConv2d(nn.Module):
def __init__(self, input_channels, output_channels, kernel_size, **kwargs):
super().__init__()
self.depthwise = nn.Sequential(
nn.Conv2d(
input_channels,
input_channels,
kernel_size,
groups=input_channels,
**kwargs),
nn.BatchNorm2d(input_channels),
nn.ReLU(inplace=True)
)
self.pointwise = nn.Sequential(
nn.Conv2d(input_channels, output_channels, 1),
nn.BatchNorm2d(output_channels),
nn.ReLU(inplace=True)
)
def forward(self, x):
x = self.depthwise(x)
x = self.pointwise(x)
return x
class BasicConv2d(nn.Module):
def __init__(self, input_channels, output_channels, kernel_size, **kwargs):
super().__init__()
self.conv = nn.Conv2d(
input_channels, output_channels, kernel_size, **kwargs)
self.bn = nn.BatchNorm2d(output_channels)
self.relu = nn.ReLU(inplace=True)
def forward(self, x):
x = self.conv(x)
x = self.bn(x)
x = self.relu(x)
return x
class MobileNet(nn.Module):
"""
Args:
width multipler: The role of the width multiplier α is to thin
a network uniformly at each layer. For a given
layer and width multiplier α, the number of
input channels M becomes αM and the number of
output channels N becomes αN.
"""
def __init__(self, width_multiplier=1, class_num=100):
super().__init__()
alpha = width_multiplier
self.stem = nn.Sequential(
BasicConv2d(3, int(32 * alpha), 3, padding=1, bias=False),
DepthSeperabelConv2d(
int(32 * alpha),
int(64 * alpha),
3,
padding=1,
bias=False
)
)
#downsample
self.conv1 = nn.Sequential(
DepthSeperabelConv2d(
int(64 * alpha),
int(128 * alpha),
3,
stride=2,
padding=1,
bias=False
),
DepthSeperabelConv2d(
int(128 * alpha),
int(128 * alpha),
3,
padding=1,
bias=False
)
)
#downsample
self.conv2 = nn.Sequential(
DepthSeperabelConv2d(
int(128 * alpha),
int(256 * alpha),
3,
stride=2,
padding=1,
bias=False
),
DepthSeperabelConv2d(
int(256 * alpha),
int(256 * alpha),
3,
padding=1,
bias=False
)
)
#downsample
self.conv3 = nn.Sequential(
DepthSeperabelConv2d(
int(256 * alpha),
int(512 * alpha),
3,
stride=2,
padding=1,
bias=False
),
DepthSeperabelConv2d(
int(512 * alpha),
int(512 * alpha),
3,
padding=1,
bias=False
),
DepthSeperabelConv2d(
int(512 * alpha),
int(512 * alpha),
3,
padding=1,
bias=False
),
DepthSeperabelConv2d(
int(512 * alpha),
int(512 * alpha),
3,
padding=1,
bias=False
),
DepthSeperabelConv2d(
int(512 * alpha),
int(512 * alpha),
3,
padding=1,
bias=False
),
DepthSeperabelConv2d(
int(512 * alpha),
int(512 * alpha),
3,
padding=1,
bias=False
)
)
#downsample
self.conv4 = nn.Sequential(
DepthSeperabelConv2d(
int(512 * alpha),
int(1024 * alpha),
3,
stride=2,
padding=1,
bias=False
),
DepthSeperabelConv2d(
int(1024 * alpha),
int(1024 * alpha),
3,
padding=1,
bias=False
)
)
self.fc = nn.Linear(int(1024 * alpha), class_num)
self.avg = nn.AdaptiveAvgPool2d(1)
def forward(self, x):
x = self.stem(x)
x = self.conv1(x)
x = self.conv2(x)
x = self.conv3(x)
x = self.conv4(x)
x = self.avg(x)
x = x.view(x.size(0), -1)
x = self.fc(x)
return x
def mobilenet(alpha=1, class_num=100):
return MobileNet(alpha, class_num) | zeus-ml | /zeus-ml-0.7.0.tar.gz/zeus-ml-0.7.0/examples/ZeusDataLoader/cifar100/models/mobilenet.py | mobilenet.py |
import torch
import torch.nn as nn
class BasicBlock(nn.Module):
"""Basic Block for resnet 18 and resnet 34
"""
#BasicBlock and BottleNeck block
#have different output size
#we use class attribute expansion
#to distinct
expansion = 1
def __init__(self, in_channels, out_channels, stride=1):
super().__init__()
#residual function
self.residual_function = nn.Sequential(
nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=stride, padding=1, bias=False),
nn.BatchNorm2d(out_channels),
nn.ReLU(inplace=True),
nn.Conv2d(out_channels, out_channels * BasicBlock.expansion, kernel_size=3, padding=1, bias=False),
nn.BatchNorm2d(out_channels * BasicBlock.expansion)
)
#shortcut
self.shortcut = nn.Sequential()
#the shortcut output dimension is not the same with residual function
#use 1*1 convolution to match the dimension
if stride != 1 or in_channels != BasicBlock.expansion * out_channels:
self.shortcut = nn.Sequential(
nn.Conv2d(in_channels, out_channels * BasicBlock.expansion, kernel_size=1, stride=stride, bias=False),
nn.BatchNorm2d(out_channels * BasicBlock.expansion)
)
def forward(self, x):
return nn.ReLU(inplace=True)(self.residual_function(x) + self.shortcut(x))
class BottleNeck(nn.Module):
"""Residual block for resnet over 50 layers
"""
expansion = 4
def __init__(self, in_channels, out_channels, stride=1):
super().__init__()
self.residual_function = nn.Sequential(
nn.Conv2d(in_channels, out_channels, kernel_size=1, bias=False),
nn.BatchNorm2d(out_channels),
nn.ReLU(inplace=True),
nn.Conv2d(out_channels, out_channels, stride=stride, kernel_size=3, padding=1, bias=False),
nn.BatchNorm2d(out_channels),
nn.ReLU(inplace=True),
nn.Conv2d(out_channels, out_channels * BottleNeck.expansion, kernel_size=1, bias=False),
nn.BatchNorm2d(out_channels * BottleNeck.expansion),
)
self.shortcut = nn.Sequential()
if stride != 1 or in_channels != out_channels * BottleNeck.expansion:
self.shortcut = nn.Sequential(
nn.Conv2d(in_channels, out_channels * BottleNeck.expansion, stride=stride, kernel_size=1, bias=False),
nn.BatchNorm2d(out_channels * BottleNeck.expansion)
)
def forward(self, x):
return nn.ReLU(inplace=True)(self.residual_function(x) + self.shortcut(x))
class ResNet(nn.Module):
def __init__(self, block, num_block, num_classes=100):
super().__init__()
self.in_channels = 64
self.conv1 = nn.Sequential(
nn.Conv2d(3, 64, kernel_size=3, padding=1, bias=False),
nn.BatchNorm2d(64),
nn.ReLU(inplace=True))
#we use a different inputsize than the original paper
#so conv2_x's stride is 1
self.conv2_x = self._make_layer(block, 64, num_block[0], 1)
self.conv3_x = self._make_layer(block, 128, num_block[1], 2)
self.conv4_x = self._make_layer(block, 256, num_block[2], 2)
self.conv5_x = self._make_layer(block, 512, num_block[3], 2)
self.avg_pool = nn.AdaptiveAvgPool2d((1, 1))
self.fc = nn.Linear(512 * block.expansion, num_classes)
def _make_layer(self, block, out_channels, num_blocks, stride):
"""make resnet layers(by layer i didnt mean this 'layer' was the
same as a neuron netowork layer, ex. conv layer), one layer may
contain more than one residual block
Args:
block: block type, basic block or bottle neck block
out_channels: output depth channel number of this layer
num_blocks: how many blocks per layer
stride: the stride of the first block of this layer
Return:
return a resnet layer
"""
# we have num_block blocks per layer, the first block
# could be 1 or 2, other blocks would always be 1
strides = [stride] + [1] * (num_blocks - 1)
layers = []
for stride in strides:
layers.append(block(self.in_channels, out_channels, stride))
self.in_channels = out_channels * block.expansion
return nn.Sequential(*layers)
def forward(self, x):
output = self.conv1(x)
output = self.conv2_x(output)
output = self.conv3_x(output)
output = self.conv4_x(output)
output = self.conv5_x(output)
output = self.avg_pool(output)
output = output.view(output.size(0), -1)
output = self.fc(output)
return output
def resnet18():
""" return a ResNet 18 object
"""
return ResNet(BasicBlock, [2, 2, 2, 2])
def resnet34():
""" return a ResNet 34 object
"""
return ResNet(BasicBlock, [3, 4, 6, 3])
def resnet50():
""" return a ResNet 50 object
"""
return ResNet(BottleNeck, [3, 4, 6, 3])
def resnet101():
""" return a ResNet 101 object
"""
return ResNet(BottleNeck, [3, 4, 23, 3])
def resnet152():
""" return a ResNet 152 object
"""
return ResNet(BottleNeck, [3, 8, 36, 3]) | zeus-ml | /zeus-ml-0.7.0.tar.gz/zeus-ml-0.7.0/examples/ZeusDataLoader/cifar100/models/resnet.py | resnet.py |
import torch
import torch.nn as nn
class Inception(nn.Module):
def __init__(self, input_channels, n1x1, n3x3_reduce, n3x3, n5x5_reduce, n5x5, pool_proj):
super().__init__()
#1x1conv branch
self.b1 = nn.Sequential(
nn.Conv2d(input_channels, n1x1, kernel_size=1),
nn.BatchNorm2d(n1x1),
nn.ReLU(inplace=True)
)
#1x1conv -> 3x3conv branch
self.b2 = nn.Sequential(
nn.Conv2d(input_channels, n3x3_reduce, kernel_size=1),
nn.BatchNorm2d(n3x3_reduce),
nn.ReLU(inplace=True),
nn.Conv2d(n3x3_reduce, n3x3, kernel_size=3, padding=1),
nn.BatchNorm2d(n3x3),
nn.ReLU(inplace=True)
)
#1x1conv -> 5x5conv branch
#we use 2 3x3 conv filters stacked instead
#of 1 5x5 filters to obtain the same receptive
#field with fewer parameters
self.b3 = nn.Sequential(
nn.Conv2d(input_channels, n5x5_reduce, kernel_size=1),
nn.BatchNorm2d(n5x5_reduce),
nn.ReLU(inplace=True),
nn.Conv2d(n5x5_reduce, n5x5, kernel_size=3, padding=1),
nn.BatchNorm2d(n5x5, n5x5),
nn.ReLU(inplace=True),
nn.Conv2d(n5x5, n5x5, kernel_size=3, padding=1),
nn.BatchNorm2d(n5x5),
nn.ReLU(inplace=True)
)
#3x3pooling -> 1x1conv
#same conv
self.b4 = nn.Sequential(
nn.MaxPool2d(3, stride=1, padding=1),
nn.Conv2d(input_channels, pool_proj, kernel_size=1),
nn.BatchNorm2d(pool_proj),
nn.ReLU(inplace=True)
)
def forward(self, x):
return torch.cat([self.b1(x), self.b2(x), self.b3(x), self.b4(x)], dim=1)
class GoogleNet(nn.Module):
def __init__(self, num_class=100):
super().__init__()
self.prelayer = nn.Sequential(
nn.Conv2d(3, 64, kernel_size=3, padding=1, bias=False),
nn.BatchNorm2d(64),
nn.ReLU(inplace=True),
nn.Conv2d(64, 64, kernel_size=3, padding=1, bias=False),
nn.BatchNorm2d(64),
nn.ReLU(inplace=True),
nn.Conv2d(64, 192, kernel_size=3, padding=1, bias=False),
nn.BatchNorm2d(192),
nn.ReLU(inplace=True),
)
#although we only use 1 conv layer as prelayer,
#we still use name a3, b3.......
self.a3 = Inception(192, 64, 96, 128, 16, 32, 32)
self.b3 = Inception(256, 128, 128, 192, 32, 96, 64)
##"""In general, an Inception network is a network consisting of
##modules of the above type stacked upon each other, with occasional
##max-pooling layers with stride 2 to halve the resolution of the
##grid"""
self.maxpool = nn.MaxPool2d(3, stride=2, padding=1)
self.a4 = Inception(480, 192, 96, 208, 16, 48, 64)
self.b4 = Inception(512, 160, 112, 224, 24, 64, 64)
self.c4 = Inception(512, 128, 128, 256, 24, 64, 64)
self.d4 = Inception(512, 112, 144, 288, 32, 64, 64)
self.e4 = Inception(528, 256, 160, 320, 32, 128, 128)
self.a5 = Inception(832, 256, 160, 320, 32, 128, 128)
self.b5 = Inception(832, 384, 192, 384, 48, 128, 128)
#input feature size: 8*8*1024
self.avgpool = nn.AdaptiveAvgPool2d((1, 1))
self.dropout = nn.Dropout2d(p=0.4)
self.linear = nn.Linear(1024, num_class)
def forward(self, x):
x = self.prelayer(x)
x = self.maxpool(x)
x = self.a3(x)
x = self.b3(x)
x = self.maxpool(x)
x = self.a4(x)
x = self.b4(x)
x = self.c4(x)
x = self.d4(x)
x = self.e4(x)
x = self.maxpool(x)
x = self.a5(x)
x = self.b5(x)
#"""It was found that a move from fully connected layers to
#average pooling improved the top-1 accuracy by about 0.6%,
#however the use of dropout remained essential even after
#removing the fully connected layers."""
x = self.avgpool(x)
x = self.dropout(x)
x = x.view(x.size()[0], -1)
x = self.linear(x)
return x
def googlenet():
return GoogleNet() | zeus-ml | /zeus-ml-0.7.0.tar.gz/zeus-ml-0.7.0/examples/ZeusDataLoader/cifar100/models/googlenet.py | googlenet.py |
import torch
import torch.nn as nn
import torch.nn.functional as F
class LinearBottleNeck(nn.Module):
def __init__(self, in_channels, out_channels, stride, t=6, class_num=100):
super().__init__()
self.residual = nn.Sequential(
nn.Conv2d(in_channels, in_channels * t, 1),
nn.BatchNorm2d(in_channels * t),
nn.ReLU6(inplace=True),
nn.Conv2d(in_channels * t, in_channels * t, 3, stride=stride, padding=1, groups=in_channels * t),
nn.BatchNorm2d(in_channels * t),
nn.ReLU6(inplace=True),
nn.Conv2d(in_channels * t, out_channels, 1),
nn.BatchNorm2d(out_channels)
)
self.stride = stride
self.in_channels = in_channels
self.out_channels = out_channels
def forward(self, x):
residual = self.residual(x)
if self.stride == 1 and self.in_channels == self.out_channels:
residual += x
return residual
class MobileNetV2(nn.Module):
def __init__(self, class_num=100):
super().__init__()
self.pre = nn.Sequential(
nn.Conv2d(3, 32, 1, padding=1),
nn.BatchNorm2d(32),
nn.ReLU6(inplace=True)
)
self.stage1 = LinearBottleNeck(32, 16, 1, 1)
self.stage2 = self._make_stage(2, 16, 24, 2, 6)
self.stage3 = self._make_stage(3, 24, 32, 2, 6)
self.stage4 = self._make_stage(4, 32, 64, 2, 6)
self.stage5 = self._make_stage(3, 64, 96, 1, 6)
self.stage6 = self._make_stage(3, 96, 160, 1, 6)
self.stage7 = LinearBottleNeck(160, 320, 1, 6)
self.conv1 = nn.Sequential(
nn.Conv2d(320, 1280, 1),
nn.BatchNorm2d(1280),
nn.ReLU6(inplace=True)
)
self.conv2 = nn.Conv2d(1280, class_num, 1)
def forward(self, x):
x = self.pre(x)
x = self.stage1(x)
x = self.stage2(x)
x = self.stage3(x)
x = self.stage4(x)
x = self.stage5(x)
x = self.stage6(x)
x = self.stage7(x)
x = self.conv1(x)
x = F.adaptive_avg_pool2d(x, 1)
x = self.conv2(x)
x = x.view(x.size(0), -1)
return x
def _make_stage(self, repeat, in_channels, out_channels, stride, t):
layers = []
layers.append(LinearBottleNeck(in_channels, out_channels, stride, t))
while repeat - 1:
layers.append(LinearBottleNeck(out_channels, out_channels, 1, t))
repeat -= 1
return nn.Sequential(*layers)
def mobilenetv2():
return MobileNetV2() | zeus-ml | /zeus-ml-0.7.0.tar.gz/zeus-ml-0.7.0/examples/ZeusDataLoader/cifar100/models/mobilenetv2.py | mobilenetv2.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.