code stringlengths 1 2.08M | language stringclasses 1 value |
|---|---|
/*
* A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined
* in FIPS 180-1
* Version 2.2 Copyright Paul Johnston 2000 - 2009.
* Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
* Distributed under the BSD License
* See http://pajhome.org.uk/crypt/md5 for details.
*/
/*
* Configurable variables. You may need to tweak these to be compatible with
* the server-side, but the defaults work in most cases.
*/
var hexcase = 0; /* hex output format. 0 - lowercase; 1 - uppercase */
var b64pad = "="; /* base-64 pad character. "=" for strict RFC compliance */
/*
* These are the functions you'll usually want to call
* They take string arguments and return either hex or base-64 encoded strings
*/
function hex_sha1(s) { return rstr2hex(rstr_sha1(str2rstr_utf8(s))); }
function b64_sha1(s) { return rstr2b64(rstr_sha1(str2rstr_utf8(s))); }
function any_sha1(s, e) { return rstr2any(rstr_sha1(str2rstr_utf8(s)), e); }
function hex_hmac_sha1(k, d)
{ return rstr2hex(rstr_hmac_sha1(str2rstr_utf8(k), str2rstr_utf8(d))); }
function b64_hmac_sha1(k, d)
{ return rstr2b64(rstr_hmac_sha1(str2rstr_utf8(k), str2rstr_utf8(d))); }
function any_hmac_sha1(k, d, e)
{ return rstr2any(rstr_hmac_sha1(str2rstr_utf8(k), str2rstr_utf8(d)), e); }
/*
* Perform a simple self-test to see if the VM is working
*/
function sha1_vm_test()
{
return hex_sha1("abc").toLowerCase() == "a9993e364706816aba3e25717850c26c9cd0d89d";
}
/*
* Calculate the SHA1 of a raw string
*/
function rstr_sha1(s)
{
return binb2rstr(binb_sha1(rstr2binb(s), s.length * 8));
}
/*
* Calculate the HMAC-SHA1 of a key and some data (raw strings)
*/
function rstr_hmac_sha1(key, data)
{
var bkey = rstr2binb(key);
if(bkey.length > 16) bkey = binb_sha1(bkey, key.length * 8);
var ipad = Array(16), opad = Array(16);
for(var i = 0; i < 16; i++)
{
ipad[i] = bkey[i] ^ 0x36363636;
opad[i] = bkey[i] ^ 0x5C5C5C5C;
}
var hash = binb_sha1(ipad.concat(rstr2binb(data)), 512 + data.length * 8);
return binb2rstr(binb_sha1(opad.concat(hash), 512 + 160));
}
/*
* Convert a raw string to a hex string
*/
function rstr2hex(input)
{
try { hexcase } catch(e) { hexcase=0; }
var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
var output = "";
var x;
for(var i = 0; i < input.length; i++)
{
x = input.charCodeAt(i);
output += hex_tab.charAt((x >>> 4) & 0x0F)
+ hex_tab.charAt( x & 0x0F);
}
return output;
}
/*
* Convert a raw string to a base-64 string
*/
function rstr2b64(input)
{
try { b64pad } catch(e) { b64pad=''; }
var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
var output = "";
var len = input.length;
for(var i = 0; i < len; i += 3)
{
var triplet = (input.charCodeAt(i) << 16)
| (i + 1 < len ? input.charCodeAt(i+1) << 8 : 0)
| (i + 2 < len ? input.charCodeAt(i+2) : 0);
for(var j = 0; j < 4; j++)
{
if(i * 8 + j * 6 > input.length * 8) output += b64pad;
else output += tab.charAt((triplet >>> 6*(3-j)) & 0x3F);
}
}
return output;
}
/*
* Convert a raw string to an arbitrary string encoding
*/
function rstr2any(input, encoding)
{
var divisor = encoding.length;
var remainders = Array();
var i, q, x, quotient;
/* Convert to an array of 16-bit big-endian values, forming the dividend */
var dividend = Array(Math.ceil(input.length / 2));
for(i = 0; i < dividend.length; i++)
{
dividend[i] = (input.charCodeAt(i * 2) << 8) | input.charCodeAt(i * 2 + 1);
}
/*
* Repeatedly perform a long division. The binary array forms the dividend,
* the length of the encoding is the divisor. Once computed, the quotient
* forms the dividend for the next step. We stop when the dividend is zero.
* All remainders are stored for later use.
*/
while(dividend.length > 0)
{
quotient = Array();
x = 0;
for(i = 0; i < dividend.length; i++)
{
x = (x << 16) + dividend[i];
q = Math.floor(x / divisor);
x -= q * divisor;
if(quotient.length > 0 || q > 0)
quotient[quotient.length] = q;
}
remainders[remainders.length] = x;
dividend = quotient;
}
/* Convert the remainders to the output string */
var output = "";
for(i = remainders.length - 1; i >= 0; i--)
output += encoding.charAt(remainders[i]);
/* Append leading zero equivalents */
var full_length = Math.ceil(input.length * 8 /
(Math.log(encoding.length) / Math.log(2)))
for(i = output.length; i < full_length; i++)
output = encoding[0] + output;
return output;
}
/*
* Encode a string as utf-8.
* For efficiency, this assumes the input is valid utf-16.
*/
function str2rstr_utf8(input)
{
var output = "";
var i = -1;
var x, y;
while(++i < input.length)
{
/* Decode utf-16 surrogate pairs */
x = input.charCodeAt(i);
y = i + 1 < input.length ? input.charCodeAt(i + 1) : 0;
if(0xD800 <= x && x <= 0xDBFF && 0xDC00 <= y && y <= 0xDFFF)
{
x = 0x10000 + ((x & 0x03FF) << 10) + (y & 0x03FF);
i++;
}
/* Encode output as utf-8 */
if(x <= 0x7F)
output += String.fromCharCode(x);
else if(x <= 0x7FF)
output += String.fromCharCode(0xC0 | ((x >>> 6 ) & 0x1F),
0x80 | ( x & 0x3F));
else if(x <= 0xFFFF)
output += String.fromCharCode(0xE0 | ((x >>> 12) & 0x0F),
0x80 | ((x >>> 6 ) & 0x3F),
0x80 | ( x & 0x3F));
else if(x <= 0x1FFFFF)
output += String.fromCharCode(0xF0 | ((x >>> 18) & 0x07),
0x80 | ((x >>> 12) & 0x3F),
0x80 | ((x >>> 6 ) & 0x3F),
0x80 | ( x & 0x3F));
}
return output;
}
/*
* Encode a string as utf-16
*/
function str2rstr_utf16le(input)
{
var output = "";
for(var i = 0; i < input.length; i++)
output += String.fromCharCode( input.charCodeAt(i) & 0xFF,
(input.charCodeAt(i) >>> 8) & 0xFF);
return output;
}
function str2rstr_utf16be(input)
{
var output = "";
for(var i = 0; i < input.length; i++)
output += String.fromCharCode((input.charCodeAt(i) >>> 8) & 0xFF,
input.charCodeAt(i) & 0xFF);
return output;
}
/*
* Convert a raw string to an array of big-endian words
* Characters >255 have their high-byte silently ignored.
*/
function rstr2binb(input)
{
var output = Array(input.length >> 2);
for(var i = 0; i < output.length; i++)
output[i] = 0;
for(var i = 0; i < input.length * 8; i += 8)
output[i>>5] |= (input.charCodeAt(i / 8) & 0xFF) << (24 - i % 32);
return output;
}
/*
* Convert an array of big-endian words to a string
*/
function binb2rstr(input)
{
var output = "";
for(var i = 0; i < input.length * 32; i += 8)
output += String.fromCharCode((input[i>>5] >>> (24 - i % 32)) & 0xFF);
return output;
}
/*
* Calculate the SHA-1 of an array of big-endian words, and a bit length
*/
function binb_sha1(x, len)
{
/* append padding */
x[len >> 5] |= 0x80 << (24 - len % 32);
x[((len + 64 >> 9) << 4) + 15] = len;
var w = Array(80);
var a = 1732584193;
var b = -271733879;
var c = -1732584194;
var d = 271733878;
var e = -1009589776;
for(var i = 0; i < x.length; i += 16)
{
var olda = a;
var oldb = b;
var oldc = c;
var oldd = d;
var olde = e;
for(var j = 0; j < 80; j++)
{
if(j < 16) w[j] = x[i + j];
else w[j] = bit_rol(w[j-3] ^ w[j-8] ^ w[j-14] ^ w[j-16], 1);
var t = safe_add(safe_add(bit_rol(a, 5), sha1_ft(j, b, c, d)),
safe_add(safe_add(e, w[j]), sha1_kt(j)));
e = d;
d = c;
c = bit_rol(b, 30);
b = a;
a = t;
}
a = safe_add(a, olda);
b = safe_add(b, oldb);
c = safe_add(c, oldc);
d = safe_add(d, oldd);
e = safe_add(e, olde);
}
return Array(a, b, c, d, e);
}
/*
* Perform the appropriate triplet combination function for the current
* iteration
*/
function sha1_ft(t, b, c, d)
{
if(t < 20) return (b & c) | ((~b) & d);
if(t < 40) return b ^ c ^ d;
if(t < 60) return (b & c) | (b & d) | (c & d);
return b ^ c ^ d;
}
/*
* Determine the appropriate additive constant for the current iteration
*/
function sha1_kt(t)
{
return (t < 20) ? 1518500249 : (t < 40) ? 1859775393 :
(t < 60) ? -1894007588 : -899497514;
}
/*
* Add integers, wrapping at 2^32. This uses 16-bit operations internally
* to work around bugs in some JS interpreters.
*/
function safe_add(x, y)
{
var lsw = (x & 0xFFFF) + (y & 0xFFFF);
var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
return (msw << 16) | (lsw & 0xFFFF);
}
/*
* Bitwise rotate a 32-bit number to the left.
*/
function bit_rol(num, cnt)
{
return (num << cnt) | (num >>> (32 - cnt));
} | JavaScript |
function authentify()
{
var password = document.getElementById("password").value;
password = b64_sha1(password);
document.getElementById("password").value = password;
document.forms[0].submit();
}
function enterKey(e)
{
var key;
if(window.event)
key = window.event.keyCode; //IE
else
key = e.which; //firefox
if(key == 13)
{
authentify();
return true;
}
else
return true;
}
function init()
{
document.getElementById("sendButton").onkeypress = enterKey;
document.getElementById("password").onkeypress = enterKey;
document.getElementById("sendButton").onclick = authentify;
}
window.onload = init; | JavaScript |
function updateList() {
db.transaction(function(tx) {
tx.executeSql("SELECT * FROM RssList", [], readSuccess, errorCB);
}, errorCB);
}
function readSuccess(tx, result) {
var updatenum = 0;
var rowsLen = result.rows.length
$.each(result.rows, function(index) {
var row = result.rows.item(index);
$.getFeed({
url : row['Link'],
dataType : "xml",
success : function(feed) {
updatenum += feed.items.length;
rowsLen-=1;
if (rowsLen==0) {
alert("本次一共更新了"+updatenum+"条新闻");
}
}
});
});
} | JavaScript |
/*
* JQuery URL Parser plugin
* Developed and maintanined by Mark Perkins, mark@allmarkedup.com
* Source repository: https://github.com/allmarkedup/jQuery-URL-Parser
* Licensed under an MIT-style license. See https://github.com/allmarkedup/jQuery-URL-Parser/blob/master/LICENSE for details.
*/
;(function($, undefined) {
var tag2attr = {
a : 'href',
img : 'src',
form : 'action',
base : 'href',
script : 'src',
iframe : 'src',
link : 'href'
},
key = ["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","fragment"], // keys available to query
aliases = { "anchor" : "fragment" }, // aliases for backwards compatability
parser = {
strict : /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/, //less intuitive, more accurate to the specs
loose : /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/ // more intuitive, fails on relative paths and deviates from specs
},
querystring_parser = /(?:^|&|;)([^&=;]*)=?([^&;]*)/g, // supports both ampersand and semicolon-delimted query string key/value pairs
fragment_parser = /(?:^|&|;)([^&=;]*)=?([^&;]*)/g; // supports both ampersand and semicolon-delimted fragment key/value pairs
function parseUri( url, strictMode )
{
var str = decodeURI( url ),
res = parser[ strictMode || false ? "strict" : "loose" ].exec( str ),
uri = { attr : {}, param : {}, seg : {} },
i = 14;
while ( i-- )
{
uri.attr[ key[i] ] = res[i] || "";
}
// build query and fragment parameters
uri.param['query'] = {};
uri.param['fragment'] = {};
uri.attr['query'].replace( querystring_parser, function ( $0, $1, $2 ){
if ($1)
{
uri.param['query'][$1] = $2;
}
});
uri.attr['fragment'].replace( fragment_parser, function ( $0, $1, $2 ){
if ($1)
{
uri.param['fragment'][$1] = $2;
}
});
// split path and fragement into segments
uri.seg['path'] = uri.attr.path.replace(/^\/+|\/+$/g,'').split('/');
uri.seg['fragment'] = uri.attr.fragment.replace(/^\/+|\/+$/g,'').split('/');
// compile a 'base' domain attribute
uri.attr['base'] = uri.attr.host ? uri.attr.protocol+"://"+uri.attr.host + (uri.attr.port ? ":"+uri.attr.port : '') : '';
return uri;
};
function getAttrName( elm )
{
var tn = elm.tagName;
if ( tn !== undefined ) return tag2attr[tn.toLowerCase()];
return tn;
}
$.fn.url = function( strictMode )
{
var url = '';
if ( this.length )
{
url = $(this).attr( getAttrName(this[0]) ) || '';
}
return $.url( url, strictMode );
};
$.url = function( url, strictMode )
{
if ( arguments.length === 1 && url === true )
{
strictMode = true;
url = undefined;
}
strictMode = strictMode || false;
url = url || window.location.toString();
return {
data : parseUri(url, strictMode),
// get various attributes from the URI
attr : function( attr )
{
attr = aliases[attr] || attr;
return attr !== undefined ? this.data.attr[attr] : this.data.attr;
},
// return query string parameters
param : function( param )
{
return param !== undefined ? this.data.param.query[param] : this.data.param.query;
},
// return fragment parameters
fparam : function( param )
{
return param !== undefined ? this.data.param.fragment[param] : this.data.param.fragment;
},
// return path segments
segment : function( seg )
{
if ( seg === undefined )
{
return this.data.seg.path;
}
else
{
seg = seg < 0 ? this.data.seg.path.length + seg : seg - 1; // negative segments count from the end
return this.data.seg.path[seg];
}
},
// return fragment segments
fsegment : function( seg )
{
if ( seg === undefined )
{
return this.data.seg.fragment;
}
else
{
seg = seg < 0 ? this.data.seg.fragment.length + seg : seg - 1; // negative segments count from the end
return this.data.seg.fragment[seg];
}
}
};
};
})(jQuery); | JavaScript |
/**
* Plugin: jquery.zRSSFeed
*
* Version: 1.1.6 (c) Copyright 2010-2012, Zazar Ltd
*
* Description: jQuery plugin for display of RSS feeds via Google Feed API
* (Based on original plugin jGFeed by jQuery HowTo. Filesize function by Cary
* Dunn.)
*
* History: 1.1.6 - Added sort options 1.1.5 - Target option now applies to all
* feed links 1.1.4 - Added option to hide media and now compressed with Google
* Closure 1.1.3 - Check for valid published date 1.1.2 - Added user callback
* function due to issue with ajaxStop after jQuery 1.4.2 1.1.1 - Correction to
* null xml entries and support for media with jQuery < 1.5 1.1.0 - Added
* support for media in enclosure tags 1.0.3 - Added feed link target 1.0.2 -
* Fixed issue with GET parameters (Seb Dangerfield) and SSL option 1.0.1 -
* Corrected issue with multiple instances
*
*/
(function($) {
$.fn.rssfeed = function(url, options, fn) {
// Set pluign defaults
var defaults = {
limit : 20,
header : false,
titletag : 'h4',
date : true,
content : true,
snippet : true,
media : false,
showerror : true,
errormsg : '抱歉,信息加载失败!',
key : null,
ssl : false,
linktarget : '_self',
sort : '',
sortasc : true
};
var options = $.extend(defaults, options);
// Functions
return this.each(function(i, e) {
var $e = $(e);
var s = '';
// Check for valid url
if (url == null)
return false;
// Create Google Feed API address
var api = "http" + s + "://ajax.googleapis.com/ajax/services/feed/load?v=1.0&callback=?&q=" + encodeURIComponent(url);
if (options.limit != null)
api += "&num=" + options.limit;
if (options.key != null)
api += "&key=" + options.key;
api += "&output=json_xml"
// Send request
$.getJSON(api, function(data) {
// Check for error
if (data.responseStatus == 200) {
// Process the feeds
$('#newsListPageContent').show();
$("#errorMsg").hide();
_process(e, data.responseData, options);
// Optional user callback function
if ($.isFunction(fn))
fn.call(this, $e);
} else {
// Handle error if required
$('#newsListPageContent').hide();
$("#errorMsg").show();
if (options.showerror)
if (options.errormsg != '') {
var msg = options.errormsg;
} else {
var msg = data.responseDetails;
}
;
$(e).html('<div class="rssError"><p align="center">' + msg + '</p></div>');
window.plugins.PGLoadingDialog.hide();
}
;
});
});
};
// Function to create HTML result
var _process = function(e, data, options) {
// Get JSON feed data
var feeds = data.feed;
if (!feeds) {
return false;
}
var rowArray = [];
// Add feeds
var list = $('#newsListPageListView');
$('#newsListPageListView').empty();
for ( var i = 0; i < feeds.entries.length; i++) {
rowArray[i] = [];
// Get individual feed
var entry = feeds.entries[i];
var pubDate;
var sort = '';
// Apply sort column
switch (options.sort) {
case 'title':
sort = entry.title;
break;
case 'date':
sort = entry.publishedDate;
break;
}
// Format published date
if (entry.publishedDate) {
var entryDate = new Date(entry.publishedDate);
var pubDate = entryDate.toLocaleDateString() + ' ' + entryDate.toLocaleTimeString();
}
var description=entry.content.replace(/<[^>]+>/g,"");
$('#newsListPageListView').append(
'<li data-icon="false"><a href="javascript:void(0)" my-data="' + entry.title + '#' + entry.link + '#' + entry.publishedDate + '#'
+ description + '">' + entry.title + '</a></li>');
}
list.listview('refresh');
window.plugins.PGLoadingDialog.hide();
};
})(jQuery);
| JavaScript |
var db;
var menuOpen = false;
var menuDiv = "";
var theme;
function onDeviceReady() {
menuDiv = document.querySelector(".menu");
theme = window.localStorage.getItem("theme");
$('.jqm-page').trigger('refresh', theme);
document.addEventListener("menubutton", onMenuKeyDown, false);
try {
var DbName = "RssList_DB";
var version = "1.0";
var displayName = "A RssList Database";
var maxSize = 200000;
db = window.openDatabase(DbName, version, displayName, maxSize);
} catch (e) {
console.log(e);
}
db.transaction(populateDB, errorCB, successCB);
}
// 创建数据表RssList
function populateDB(tx) {
tx.executeSql('CREATE TABLE IF NOT EXISTS RssList (id INTEGER PRIMARY KEY AUTOINCREMENT,Name,Link,Flag)');
}
// 事务执行出错后调用的回调函数
function errorCB(err) {
console.log("Error processing SQL: " + err.code);
}
// 事务执行成功后调用的回调函数 查询数据
function successCB() {
db.transaction(function(tx) {
tx.executeSql("SELECT * FROM RssList", [], querySuccess, errorCB);
}, errorCB);
}
function querySuccess(tx, result) {
if (result.rows.length == 0) {
$("#tipsContent").text("没有订阅RSS新闻").show();
$("#mainContent").hide();
/* $("#RssListView").hide(); */
} else {
$("#tipsContent").hide();
$("#mainContent").show();
/* $("#RssListView").show(); */
var list = $('#RssListView');
$('#RssListView').empty();
$.each(result.rows, function(index) {
var row = result.rows.item(index);
// console.log(row['id']);
$('#RssListView').append(
'<li data-icon="false"><a id="rssNewsA" href="javascript:void(0)" my-data="' + row['Name'] + '#' + row['Link'] + '">'
+ row['Name'] + '</a><span class="ui-li-count">' + row['Flag'] + '</span><a id="deleteRssNews" "my-id=' + row['id']
+ ' data-inline="true" data-rel="dialog" data-transition="slideup"></a></li>');
});
list.listview('refresh');
}
}
// 向数据表中插入订阅的Rss
function insertRss(Rss, cb) {
// alert(" 标题:" + Rss.name + "地址:" + Rss.link + "标签:" + Rss.flag)
// Sometimes you may want to jot down something quickly....
db.transaction(function(tx) {
tx.executeSql("insert into RssList(Name,Link,Flag) values(?,?,?)", [ Rss.name, Rss.link, Rss.flag ]);
}, errorCB, cb);
}
// 删除订阅的RSS
function deleteRss(id, cb) {
// Sometimes you may want to jot down something quickly....
// alert("id=" + id);
db.transaction(function(tx) {
tx.executeSql("DELETE FROM RssList where id=?", [ id ]);
}, errorCB, cb);
}
// 首页面初始化
function init() {
document.addEventListener("deviceready", onDeviceReady, false);
$("#index").live("pageshow", function() {
closeMenu();
successCB();
});
}
function closeMenu() {
$(".menu").attr("style", "display: none;");
menuOpen = false;
}
/* 根据url地址解析RSS内容 */
function parseFeed(url) {
$.getFeed({
url : url,
dataType : "xml",
success : function(feed) {
var list = $('#newsListPageListView');
$('#newsListPageListView').empty();
if (feed.items.length == 0) {
$("#newsListPageContent").html("<p>没有订阅RSS新闻</p>");
$('#newsListPageListView').hide();
} else {
for ( var i = 0; i < feed.items.length; i++) {
var item = feed.items[i];
// console.log(item.updated);
$('#newsListPageListView').append(
'<li data-icon="false" ><a href="javascript:void(0)" my-data="' + item.title + '#' + item.link + '#' + item.updated + '#'
+ item.description + '">' + item.title + '</a></li>');
}
list.listview('refresh');
window.plugins.PGLoadingDialog.hide();
}
}
});
}
/*
* 网络检测函数
*/
function checkConnection() {
var networkState = navigator.network.connection.type;
var states = {};
states[Connection.UNKNOWN] = 'Unknown connection';
states[Connection.ETHERNET] = 'Ethernet connection';
states[Connection.WIFI] = 'WiFi connection';
states[Connection.CELL_2G] = 'Cell 2G connection';
states[Connection.CELL_3G] = 'Cell 3G connection';
states[Connection.CELL_4G] = 'Cell 4G connection';
states[Connection.NONE] = 'No network connection';
//alert("Connection type:" + states[networkState]);
if (states[networkState] == 'No network connection')
return false;
return true;
}
/* 网页跳转函数 */
function MyChangePage(page, args) {
$.mobile.changePage(page, {
transition : "none"
});
$(page).trigger("callback", args);
}
// 点击菜单按钮15:33
function onMenuKeyDown() {
if (menuOpen) {
// console.log("close the menu");
menuDiv.style.display = "none";
menuOpen = false;
} else {
// console.log("open the menu");
menuDiv.style.display = "block";
menuOpen = true;
}
}
// 退出应用程序
function exitApp() {
try {
navigator.notification.confirm('你确定要退出应用程序?', doExit, '信息提示!', '取消,退出');
function doExit(button) {
if (button == 2) {
navigator.app.exitApp();
} else if (button == 1) { // do nothing
menuDiv.style.display = "none";
menuOpen = false;
}
}
} // try end
catch (err) {
alert('ExitApp failed' + err)
} // catch end
}
// 提示信息函数
function showAlert(msg) {
navigator.notification.alert(msg, // 信息
alertDismissed, '信息提示!', // 标题
'关闭');
}
function alertDismissed() {
// do something
}
| JavaScript |
function element_theme_refresh(element, oldTheme, newTheme) {
/* Update the page's new data theme. */
if ($(element).attr('data-theme')) {
$(element).attr('data-theme', newTheme);
}
if ($(element).attr('class')) {
/* Theme classes end in "-[a-z]$", so match that */
var classPattern = new RegExp('-' + oldTheme + '$');
newTheme = '-' + newTheme;
var classes = $(element).attr('class').split(' ');
for ( var key in classes) {
if (classPattern.test(classes[key])) {
classes[key] = classes[key].replace(classPattern, newTheme);
}
}
$(element).attr('class', classes.join(' '));
}
}
$('.jqm-page').bind('refresh', function(e, newTheme) {
/* Default to the "a" theme. */
var oldTheme = $(this).attr('data-theme') || 'a';
newTheme = newTheme || 'a';
$.mobile.page.prototype.options.theme = newTheme;
$.mobile.page.prototype.options.headerTheme = newTheme;
$.mobile.page.prototype.options.contentTheme = newTheme;
$.mobile.page.prototype.options.footerTheme = newTheme;
element_theme_refresh($(this), oldTheme, newTheme);
$(this).find('[data-role="content"]').each(function() {
element_theme_refresh($(this), oldTheme, newTheme);
});
$(this).find('[data-role="header"]').each(function() {
element_theme_refresh($(this), oldTheme, newTheme);
});
});
// $('#first-content a').live('tap', function() {
// $('#forth a').live('tap', function() {
$('#themeList a').live('tap', function() {
var newTheme = $(this).attr('theme');
/* $('#current-theme').text('Current Theme: ' + newTheme);*/
window.localStorage.setItem("theme", newTheme)
$('.jqm-page').trigger('refresh', newTheme);
// $.mobile.changePage("#first");
$.mobile.changePage("index.html", {
transition : "none"
});
});
| JavaScript |
/*
* jQuery Mobile Framework 1.1.0 db342b1f315c282692791aa870455901fdb46a55
* http://jquerymobile.com
*
* Copyright 2011 (c) jQuery Project
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://jquery.org/license
*
*/
(function ( root, doc, factory ) {
if ( typeof define === "function" && define.amd ) {
// AMD. Register as an anonymous module.
define( [ "jquery" ], function ( $ ) {
factory( $, root, doc );
return $.mobile;
});
} else {
// Browser globals
factory( root.jQuery, root, doc );
}
}( this, document, function ( $, window, document, undefined ) {
// This plugin is an experiment for abstracting away the touch and mouse
// events so that developers don't have to worry about which method of input
// the device their document is loaded on supports.
//
// The idea here is to allow the developer to register listeners for the
// basic mouse events, such as mousedown, mousemove, mouseup, and click,
// and the plugin will take care of registering the correct listeners
// behind the scenes to invoke the listener at the fastest possible time
// for that device, while still retaining the order of event firing in
// the traditional mouse environment, should multiple handlers be registered
// on the same element for different events.
//
// The current version exposes the following virtual events to jQuery bind methods:
// "vmouseover vmousedown vmousemove vmouseup vclick vmouseout vmousecancel"
(function( $, window, document, undefined ) {
var dataPropertyName = "virtualMouseBindings",
touchTargetPropertyName = "virtualTouchID",
virtualEventNames = "vmouseover vmousedown vmousemove vmouseup vclick vmouseout vmousecancel".split( " " ),
touchEventProps = "clientX clientY pageX pageY screenX screenY".split( " " ),
mouseHookProps = $.event.mouseHooks ? $.event.mouseHooks.props : [],
mouseEventProps = $.event.props.concat( mouseHookProps ),
activeDocHandlers = {},
resetTimerID = 0,
startX = 0,
startY = 0,
didScroll = false,
clickBlockList = [],
blockMouseTriggers = false,
blockTouchTriggers = false,
eventCaptureSupported = "addEventListener" in document,
$document = $( document ),
nextTouchID = 1,
lastTouchID = 0;
$.vmouse = {
moveDistanceThreshold: 10,
clickDistanceThreshold: 10,
resetTimerDuration: 1500
};
function getNativeEvent( event ) {
while ( event && typeof event.originalEvent !== "undefined" ) {
event = event.originalEvent;
}
return event;
}
function createVirtualEvent( event, eventType ) {
var t = event.type,
oe, props, ne, prop, ct, touch, i, j;
event = $.Event(event);
event.type = eventType;
oe = event.originalEvent;
props = $.event.props;
// addresses separation of $.event.props in to $.event.mouseHook.props and Issue 3280
// https://github.com/jquery/jquery-mobile/issues/3280
if ( t.search( /^(mouse|click)/ ) > -1 ) {
props = mouseEventProps;
}
// copy original event properties over to the new event
// this would happen if we could call $.event.fix instead of $.Event
// but we don't have a way to force an event to be fixed multiple times
if ( oe ) {
for ( i = props.length, prop; i; ) {
prop = props[ --i ];
event[ prop ] = oe[ prop ];
}
}
// make sure that if the mouse and click virtual events are generated
// without a .which one is defined
if ( t.search(/mouse(down|up)|click/) > -1 && !event.which ){
event.which = 1;
}
if ( t.search(/^touch/) !== -1 ) {
ne = getNativeEvent( oe );
t = ne.touches;
ct = ne.changedTouches;
touch = ( t && t.length ) ? t[0] : ( (ct && ct.length) ? ct[ 0 ] : undefined );
if ( touch ) {
for ( j = 0, len = touchEventProps.length; j < len; j++){
prop = touchEventProps[ j ];
event[ prop ] = touch[ prop ];
}
}
}
return event;
}
function getVirtualBindingFlags( element ) {
var flags = {},
b, k;
while ( element ) {
b = $.data( element, dataPropertyName );
for ( k in b ) {
if ( b[ k ] ) {
flags[ k ] = flags.hasVirtualBinding = true;
}
}
element = element.parentNode;
}
return flags;
}
function getClosestElementWithVirtualBinding( element, eventType ) {
var b;
while ( element ) {
b = $.data( element, dataPropertyName );
if ( b && ( !eventType || b[ eventType ] ) ) {
return element;
}
element = element.parentNode;
}
return null;
}
function enableTouchBindings() {
blockTouchTriggers = false;
}
function disableTouchBindings() {
blockTouchTriggers = true;
}
function enableMouseBindings() {
lastTouchID = 0;
clickBlockList.length = 0;
blockMouseTriggers = false;
// When mouse bindings are enabled, our
// touch bindings are disabled.
disableTouchBindings();
}
function disableMouseBindings() {
// When mouse bindings are disabled, our
// touch bindings are enabled.
enableTouchBindings();
}
function startResetTimer() {
clearResetTimer();
resetTimerID = setTimeout(function(){
resetTimerID = 0;
enableMouseBindings();
}, $.vmouse.resetTimerDuration );
}
function clearResetTimer() {
if ( resetTimerID ){
clearTimeout( resetTimerID );
resetTimerID = 0;
}
}
function triggerVirtualEvent( eventType, event, flags ) {
var ve;
if ( ( flags && flags[ eventType ] ) ||
( !flags && getClosestElementWithVirtualBinding( event.target, eventType ) ) ) {
ve = createVirtualEvent( event, eventType );
$( event.target).trigger( ve );
}
return ve;
}
function mouseEventCallback( event ) {
var touchID = $.data(event.target, touchTargetPropertyName);
if ( !blockMouseTriggers && ( !lastTouchID || lastTouchID !== touchID ) ){
var ve = triggerVirtualEvent( "v" + event.type, event );
if ( ve ) {
if ( ve.isDefaultPrevented() ) {
event.preventDefault();
}
if ( ve.isPropagationStopped() ) {
event.stopPropagation();
}
if ( ve.isImmediatePropagationStopped() ) {
event.stopImmediatePropagation();
}
}
}
}
function handleTouchStart( event ) {
var touches = getNativeEvent( event ).touches,
target, flags;
if ( touches && touches.length === 1 ) {
target = event.target;
flags = getVirtualBindingFlags( target );
if ( flags.hasVirtualBinding ) {
lastTouchID = nextTouchID++;
$.data( target, touchTargetPropertyName, lastTouchID );
clearResetTimer();
disableMouseBindings();
didScroll = false;
var t = getNativeEvent( event ).touches[ 0 ];
startX = t.pageX;
startY = t.pageY;
triggerVirtualEvent( "vmouseover", event, flags );
triggerVirtualEvent( "vmousedown", event, flags );
}
}
}
function handleScroll( event ) {
if ( blockTouchTriggers ) {
return;
}
if ( !didScroll ) {
triggerVirtualEvent( "vmousecancel", event, getVirtualBindingFlags( event.target ) );
}
didScroll = true;
startResetTimer();
}
function handleTouchMove( event ) {
if ( blockTouchTriggers ) {
return;
}
var t = getNativeEvent( event ).touches[ 0 ],
didCancel = didScroll,
moveThreshold = $.vmouse.moveDistanceThreshold;
didScroll = didScroll ||
( Math.abs(t.pageX - startX) > moveThreshold ||
Math.abs(t.pageY - startY) > moveThreshold ),
flags = getVirtualBindingFlags( event.target );
if ( didScroll && !didCancel ) {
triggerVirtualEvent( "vmousecancel", event, flags );
}
triggerVirtualEvent( "vmousemove", event, flags );
startResetTimer();
}
function handleTouchEnd( event ) {
if ( blockTouchTriggers ) {
return;
}
disableTouchBindings();
var flags = getVirtualBindingFlags( event.target ),
t;
triggerVirtualEvent( "vmouseup", event, flags );
if ( !didScroll ) {
var ve = triggerVirtualEvent( "vclick", event, flags );
if ( ve && ve.isDefaultPrevented() ) {
// The target of the mouse events that follow the touchend
// event don't necessarily match the target used during the
// touch. This means we need to rely on coordinates for blocking
// any click that is generated.
t = getNativeEvent( event ).changedTouches[ 0 ];
clickBlockList.push({
touchID: lastTouchID,
x: t.clientX,
y: t.clientY
});
// Prevent any mouse events that follow from triggering
// virtual event notifications.
blockMouseTriggers = true;
}
}
triggerVirtualEvent( "vmouseout", event, flags);
didScroll = false;
startResetTimer();
}
function hasVirtualBindings( ele ) {
var bindings = $.data( ele, dataPropertyName ),
k;
if ( bindings ) {
for ( k in bindings ) {
if ( bindings[ k ] ) {
return true;
}
}
}
return false;
}
function dummyMouseHandler(){}
function getSpecialEventObject( eventType ) {
var realType = eventType.substr( 1 );
return {
setup: function( data, namespace ) {
// If this is the first virtual mouse binding for this element,
// add a bindings object to its data.
if ( !hasVirtualBindings( this ) ) {
$.data( this, dataPropertyName, {});
}
// If setup is called, we know it is the first binding for this
// eventType, so initialize the count for the eventType to zero.
var bindings = $.data( this, dataPropertyName );
bindings[ eventType ] = true;
// If this is the first virtual mouse event for this type,
// register a global handler on the document.
activeDocHandlers[ eventType ] = ( activeDocHandlers[ eventType ] || 0 ) + 1;
if ( activeDocHandlers[ eventType ] === 1 ) {
$document.bind( realType, mouseEventCallback );
}
// Some browsers, like Opera Mini, won't dispatch mouse/click events
// for elements unless they actually have handlers registered on them.
// To get around this, we register dummy handlers on the elements.
$( this ).bind( realType, dummyMouseHandler );
// For now, if event capture is not supported, we rely on mouse handlers.
if ( eventCaptureSupported ) {
// If this is the first virtual mouse binding for the document,
// register our touchstart handler on the document.
activeDocHandlers[ "touchstart" ] = ( activeDocHandlers[ "touchstart" ] || 0) + 1;
if (activeDocHandlers[ "touchstart" ] === 1) {
$document.bind( "touchstart", handleTouchStart )
.bind( "touchend", handleTouchEnd )
// On touch platforms, touching the screen and then dragging your finger
// causes the window content to scroll after some distance threshold is
// exceeded. On these platforms, a scroll prevents a click event from being
// dispatched, and on some platforms, even the touchend is suppressed. To
// mimic the suppression of the click event, we need to watch for a scroll
// event. Unfortunately, some platforms like iOS don't dispatch scroll
// events until *AFTER* the user lifts their finger (touchend). This means
// we need to watch both scroll and touchmove events to figure out whether
// or not a scroll happenens before the touchend event is fired.
.bind( "touchmove", handleTouchMove )
.bind( "scroll", handleScroll );
}
}
},
teardown: function( data, namespace ) {
// If this is the last virtual binding for this eventType,
// remove its global handler from the document.
--activeDocHandlers[ eventType ];
if ( !activeDocHandlers[ eventType ] ) {
$document.unbind( realType, mouseEventCallback );
}
if ( eventCaptureSupported ) {
// If this is the last virtual mouse binding in existence,
// remove our document touchstart listener.
--activeDocHandlers[ "touchstart" ];
if ( !activeDocHandlers[ "touchstart" ] ) {
$document.unbind( "touchstart", handleTouchStart )
.unbind( "touchmove", handleTouchMove )
.unbind( "touchend", handleTouchEnd )
.unbind( "scroll", handleScroll );
}
}
var $this = $( this ),
bindings = $.data( this, dataPropertyName );
// teardown may be called when an element was
// removed from the DOM. If this is the case,
// jQuery core may have already stripped the element
// of any data bindings so we need to check it before
// using it.
if ( bindings ) {
bindings[ eventType ] = false;
}
// Unregister the dummy event handler.
$this.unbind( realType, dummyMouseHandler );
// If this is the last virtual mouse binding on the
// element, remove the binding data from the element.
if ( !hasVirtualBindings( this ) ) {
$this.removeData( dataPropertyName );
}
}
};
}
// Expose our custom events to the jQuery bind/unbind mechanism.
for ( var i = 0; i < virtualEventNames.length; i++ ){
$.event.special[ virtualEventNames[ i ] ] = getSpecialEventObject( virtualEventNames[ i ] );
}
// Add a capture click handler to block clicks.
// Note that we require event capture support for this so if the device
// doesn't support it, we punt for now and rely solely on mouse events.
if ( eventCaptureSupported ) {
document.addEventListener( "click", function( e ){
var cnt = clickBlockList.length,
target = e.target,
x, y, ele, i, o, touchID;
if ( cnt ) {
x = e.clientX;
y = e.clientY;
threshold = $.vmouse.clickDistanceThreshold;
// The idea here is to run through the clickBlockList to see if
// the current click event is in the proximity of one of our
// vclick events that had preventDefault() called on it. If we find
// one, then we block the click.
//
// Why do we have to rely on proximity?
//
// Because the target of the touch event that triggered the vclick
// can be different from the target of the click event synthesized
// by the browser. The target of a mouse/click event that is syntehsized
// from a touch event seems to be implementation specific. For example,
// some browsers will fire mouse/click events for a link that is near
// a touch event, even though the target of the touchstart/touchend event
// says the user touched outside the link. Also, it seems that with most
// browsers, the target of the mouse/click event is not calculated until the
// time it is dispatched, so if you replace an element that you touched
// with another element, the target of the mouse/click will be the new
// element underneath that point.
//
// Aside from proximity, we also check to see if the target and any
// of its ancestors were the ones that blocked a click. This is necessary
// because of the strange mouse/click target calculation done in the
// Android 2.1 browser, where if you click on an element, and there is a
// mouse/click handler on one of its ancestors, the target will be the
// innermost child of the touched element, even if that child is no where
// near the point of touch.
ele = target;
while ( ele ) {
for ( i = 0; i < cnt; i++ ) {
o = clickBlockList[ i ];
touchID = 0;
if ( ( ele === target && Math.abs( o.x - x ) < threshold && Math.abs( o.y - y ) < threshold ) ||
$.data( ele, touchTargetPropertyName ) === o.touchID ) {
// XXX: We may want to consider removing matches from the block list
// instead of waiting for the reset timer to fire.
e.preventDefault();
e.stopPropagation();
return;
}
}
ele = ele.parentNode;
}
}
}, true);
}
})( jQuery, window, document );
// Script: jQuery hashchange event
//
// *Version: 1.3, Last updated: 7/21/2010*
//
// Project Home - http://benalman.com/projects/jquery-hashchange-plugin/
// GitHub - http://github.com/cowboy/jquery-hashchange/
// Source - http://github.com/cowboy/jquery-hashchange/raw/master/jquery.ba-hashchange.js
// (Minified) - http://github.com/cowboy/jquery-hashchange/raw/master/jquery.ba-hashchange.min.js (0.8kb gzipped)
//
// About: License
//
// Copyright (c) 2010 "Cowboy" Ben Alman,
// Dual licensed under the MIT and GPL licenses.
// http://benalman.com/about/license/
//
// About: Examples
//
// These working examples, complete with fully commented code, illustrate a few
// ways in which this plugin can be used.
//
// hashchange event - http://benalman.com/code/projects/jquery-hashchange/examples/hashchange/
// document.domain - http://benalman.com/code/projects/jquery-hashchange/examples/document_domain/
//
// About: Support and Testing
//
// Information about what version or versions of jQuery this plugin has been
// tested with, what browsers it has been tested in, and where the unit tests
// reside (so you can test it yourself).
//
// jQuery Versions - 1.2.6, 1.3.2, 1.4.1, 1.4.2
// Browsers Tested - Internet Explorer 6-8, Firefox 2-4, Chrome 5-6, Safari 3.2-5,
// Opera 9.6-10.60, iPhone 3.1, Android 1.6-2.2, BlackBerry 4.6-5.
// Unit Tests - http://benalman.com/code/projects/jquery-hashchange/unit/
//
// About: Known issues
//
// While this jQuery hashchange event implementation is quite stable and
// robust, there are a few unfortunate browser bugs surrounding expected
// hashchange event-based behaviors, independent of any JavaScript
// window.onhashchange abstraction. See the following examples for more
// information:
//
// Chrome: Back Button - http://benalman.com/code/projects/jquery-hashchange/examples/bug-chrome-back-button/
// Firefox: Remote XMLHttpRequest - http://benalman.com/code/projects/jquery-hashchange/examples/bug-firefox-remote-xhr/
// WebKit: Back Button in an Iframe - http://benalman.com/code/projects/jquery-hashchange/examples/bug-webkit-hash-iframe/
// Safari: Back Button from a different domain - http://benalman.com/code/projects/jquery-hashchange/examples/bug-safari-back-from-diff-domain/
//
// Also note that should a browser natively support the window.onhashchange
// event, but not report that it does, the fallback polling loop will be used.
//
// About: Release History
//
// 1.3 - (7/21/2010) Reorganized IE6/7 Iframe code to make it more
// "removable" for mobile-only development. Added IE6/7 document.title
// support. Attempted to make Iframe as hidden as possible by using
// techniques from http://www.paciellogroup.com/blog/?p=604. Added
// support for the "shortcut" format $(window).hashchange( fn ) and
// $(window).hashchange() like jQuery provides for built-in events.
// Renamed jQuery.hashchangeDelay to <jQuery.fn.hashchange.delay> and
// lowered its default value to 50. Added <jQuery.fn.hashchange.domain>
// and <jQuery.fn.hashchange.src> properties plus document-domain.html
// file to address access denied issues when setting document.domain in
// IE6/7.
// 1.2 - (2/11/2010) Fixed a bug where coming back to a page using this plugin
// from a page on another domain would cause an error in Safari 4. Also,
// IE6/7 Iframe is now inserted after the body (this actually works),
// which prevents the page from scrolling when the event is first bound.
// Event can also now be bound before DOM ready, but it won't be usable
// before then in IE6/7.
// 1.1 - (1/21/2010) Incorporated document.documentMode test to fix IE8 bug
// where browser version is incorrectly reported as 8.0, despite
// inclusion of the X-UA-Compatible IE=EmulateIE7 meta tag.
// 1.0 - (1/9/2010) Initial Release. Broke out the jQuery BBQ event.special
// window.onhashchange functionality into a separate plugin for users
// who want just the basic event & back button support, without all the
// extra awesomeness that BBQ provides. This plugin will be included as
// part of jQuery BBQ, but also be available separately.
(function($,window,undefined){
// Reused string.
var str_hashchange = 'hashchange',
// Method / object references.
doc = document,
fake_onhashchange,
special = $.event.special,
// Does the browser support window.onhashchange? Note that IE8 running in
// IE7 compatibility mode reports true for 'onhashchange' in window, even
// though the event isn't supported, so also test document.documentMode.
doc_mode = doc.documentMode,
supports_onhashchange = 'on' + str_hashchange in window && ( doc_mode === undefined || doc_mode > 7 );
// Get location.hash (or what you'd expect location.hash to be) sans any
// leading #. Thanks for making this necessary, Firefox!
function get_fragment( url ) {
url = url || location.href;
return '#' + url.replace( /^[^#]*#?(.*)$/, '$1' );
};
// Method: jQuery.fn.hashchange
//
// Bind a handler to the window.onhashchange event or trigger all bound
// window.onhashchange event handlers. This behavior is consistent with
// jQuery's built-in event handlers.
//
// Usage:
//
// > jQuery(window).hashchange( [ handler ] );
//
// Arguments:
//
// handler - (Function) Optional handler to be bound to the hashchange
// event. This is a "shortcut" for the more verbose form:
// jQuery(window).bind( 'hashchange', handler ). If handler is omitted,
// all bound window.onhashchange event handlers will be triggered. This
// is a shortcut for the more verbose
// jQuery(window).trigger( 'hashchange' ). These forms are described in
// the <hashchange event> section.
//
// Returns:
//
// (jQuery) The initial jQuery collection of elements.
// Allow the "shortcut" format $(elem).hashchange( fn ) for binding and
// $(elem).hashchange() for triggering, like jQuery does for built-in events.
$.fn[ str_hashchange ] = function( fn ) {
return fn ? this.bind( str_hashchange, fn ) : this.trigger( str_hashchange );
};
// Property: jQuery.fn.hashchange.delay
//
// The numeric interval (in milliseconds) at which the <hashchange event>
// polling loop executes. Defaults to 50.
// Property: jQuery.fn.hashchange.domain
//
// If you're setting document.domain in your JavaScript, and you want hash
// history to work in IE6/7, not only must this property be set, but you must
// also set document.domain BEFORE jQuery is loaded into the page. This
// property is only applicable if you are supporting IE6/7 (or IE8 operating
// in "IE7 compatibility" mode).
//
// In addition, the <jQuery.fn.hashchange.src> property must be set to the
// path of the included "document-domain.html" file, which can be renamed or
// modified if necessary (note that the document.domain specified must be the
// same in both your main JavaScript as well as in this file).
//
// Usage:
//
// jQuery.fn.hashchange.domain = document.domain;
// Property: jQuery.fn.hashchange.src
//
// If, for some reason, you need to specify an Iframe src file (for example,
// when setting document.domain as in <jQuery.fn.hashchange.domain>), you can
// do so using this property. Note that when using this property, history
// won't be recorded in IE6/7 until the Iframe src file loads. This property
// is only applicable if you are supporting IE6/7 (or IE8 operating in "IE7
// compatibility" mode).
//
// Usage:
//
// jQuery.fn.hashchange.src = 'path/to/file.html';
$.fn[ str_hashchange ].delay = 50;
/*
$.fn[ str_hashchange ].domain = null;
$.fn[ str_hashchange ].src = null;
*/
// Event: hashchange event
//
// Fired when location.hash changes. In browsers that support it, the native
// HTML5 window.onhashchange event is used, otherwise a polling loop is
// initialized, running every <jQuery.fn.hashchange.delay> milliseconds to
// see if the hash has changed. In IE6/7 (and IE8 operating in "IE7
// compatibility" mode), a hidden Iframe is created to allow the back button
// and hash-based history to work.
//
// Usage as described in <jQuery.fn.hashchange>:
//
// > // Bind an event handler.
// > jQuery(window).hashchange( function(e) {
// > var hash = location.hash;
// > ...
// > });
// >
// > // Manually trigger the event handler.
// > jQuery(window).hashchange();
//
// A more verbose usage that allows for event namespacing:
//
// > // Bind an event handler.
// > jQuery(window).bind( 'hashchange', function(e) {
// > var hash = location.hash;
// > ...
// > });
// >
// > // Manually trigger the event handler.
// > jQuery(window).trigger( 'hashchange' );
//
// Additional Notes:
//
// * The polling loop and Iframe are not created until at least one handler
// is actually bound to the 'hashchange' event.
// * If you need the bound handler(s) to execute immediately, in cases where
// a location.hash exists on page load, via bookmark or page refresh for
// example, use jQuery(window).hashchange() or the more verbose
// jQuery(window).trigger( 'hashchange' ).
// * The event can be bound before DOM ready, but since it won't be usable
// before then in IE6/7 (due to the necessary Iframe), recommended usage is
// to bind it inside a DOM ready handler.
// Override existing $.event.special.hashchange methods (allowing this plugin
// to be defined after jQuery BBQ in BBQ's source code).
special[ str_hashchange ] = $.extend( special[ str_hashchange ], {
// Called only when the first 'hashchange' event is bound to window.
setup: function() {
// If window.onhashchange is supported natively, there's nothing to do..
if ( supports_onhashchange ) { return false; }
// Otherwise, we need to create our own. And we don't want to call this
// until the user binds to the event, just in case they never do, since it
// will create a polling loop and possibly even a hidden Iframe.
$( fake_onhashchange.start );
},
// Called only when the last 'hashchange' event is unbound from window.
teardown: function() {
// If window.onhashchange is supported natively, there's nothing to do..
if ( supports_onhashchange ) { return false; }
// Otherwise, we need to stop ours (if possible).
$( fake_onhashchange.stop );
}
});
// fake_onhashchange does all the work of triggering the window.onhashchange
// event for browsers that don't natively support it, including creating a
// polling loop to watch for hash changes and in IE 6/7 creating a hidden
// Iframe to enable back and forward.
fake_onhashchange = (function(){
var self = {},
timeout_id,
// Remember the initial hash so it doesn't get triggered immediately.
last_hash = get_fragment(),
fn_retval = function(val){ return val; },
history_set = fn_retval,
history_get = fn_retval;
// Start the polling loop.
self.start = function() {
timeout_id || poll();
};
// Stop the polling loop.
self.stop = function() {
timeout_id && clearTimeout( timeout_id );
timeout_id = undefined;
};
// This polling loop checks every $.fn.hashchange.delay milliseconds to see
// if location.hash has changed, and triggers the 'hashchange' event on
// window when necessary.
function poll() {
var hash = get_fragment(),
history_hash = history_get( last_hash );
if ( hash !== last_hash ) {
history_set( last_hash = hash, history_hash );
$(window).trigger( str_hashchange );
} else if ( history_hash !== last_hash ) {
location.href = location.href.replace( /#.*/, '' ) + history_hash;
}
timeout_id = setTimeout( poll, $.fn[ str_hashchange ].delay );
};
// vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
// vvvvvvvvvvvvvvvvvvv REMOVE IF NOT SUPPORTING IE6/7/8 vvvvvvvvvvvvvvvvvvv
// vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
$.browser.msie && !supports_onhashchange && (function(){
// Not only do IE6/7 need the "magical" Iframe treatment, but so does IE8
// when running in "IE7 compatibility" mode.
var iframe,
iframe_src;
// When the event is bound and polling starts in IE 6/7, create a hidden
// Iframe for history handling.
self.start = function(){
if ( !iframe ) {
iframe_src = $.fn[ str_hashchange ].src;
iframe_src = iframe_src && iframe_src + get_fragment();
// Create hidden Iframe. Attempt to make Iframe as hidden as possible
// by using techniques from http://www.paciellogroup.com/blog/?p=604.
iframe = $('<iframe tabindex="-1" title="empty"/>').hide()
// When Iframe has completely loaded, initialize the history and
// start polling.
.one( 'load', function(){
iframe_src || history_set( get_fragment() );
poll();
})
// Load Iframe src if specified, otherwise nothing.
.attr( 'src', iframe_src || 'javascript:0' )
// Append Iframe after the end of the body to prevent unnecessary
// initial page scrolling (yes, this works).
.insertAfter( 'body' )[0].contentWindow;
// Whenever `document.title` changes, update the Iframe's title to
// prettify the back/next history menu entries. Since IE sometimes
// errors with "Unspecified error" the very first time this is set
// (yes, very useful) wrap this with a try/catch block.
doc.onpropertychange = function(){
try {
if ( event.propertyName === 'title' ) {
iframe.document.title = doc.title;
}
} catch(e) {}
};
}
};
// Override the "stop" method since an IE6/7 Iframe was created. Even
// if there are no longer any bound event handlers, the polling loop
// is still necessary for back/next to work at all!
self.stop = fn_retval;
// Get history by looking at the hidden Iframe's location.hash.
history_get = function() {
return get_fragment( iframe.location.href );
};
// Set a new history item by opening and then closing the Iframe
// document, *then* setting its location.hash. If document.domain has
// been set, update that as well.
history_set = function( hash, history_hash ) {
var iframe_doc = iframe.document,
domain = $.fn[ str_hashchange ].domain;
if ( hash !== history_hash ) {
// Update Iframe with any initial `document.title` that might be set.
iframe_doc.title = doc.title;
// Opening the Iframe's document after it has been closed is what
// actually adds a history entry.
iframe_doc.open();
// Set document.domain for the Iframe document as well, if necessary.
domain && iframe_doc.write( '<script>document.domain="' + domain + '"</script>' );
iframe_doc.close();
// Update the Iframe's hash, for great justice.
iframe.location.hash = hash;
}
};
})();
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// ^^^^^^^^^^^^^^^^^^^ REMOVE IF NOT SUPPORTING IE6/7/8 ^^^^^^^^^^^^^^^^^^^
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
return self;
})();
})(jQuery,this);
/*!
* jQuery UI Widget @VERSION
*
* Copyright 2010, AUTHORS.txt (http://jqueryui.com/about)
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://jquery.org/license
*
* http://docs.jquery.com/UI/Widget
*/
(function( $, undefined ) {
// jQuery 1.4+
if ( $.cleanData ) {
var _cleanData = $.cleanData;
$.cleanData = function( elems ) {
for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) {
$( elem ).triggerHandler( "remove" );
}
_cleanData( elems );
};
} else {
var _remove = $.fn.remove;
$.fn.remove = function( selector, keepData ) {
return this.each(function() {
if ( !keepData ) {
if ( !selector || $.filter( selector, [ this ] ).length ) {
$( "*", this ).add( [ this ] ).each(function() {
$( this ).triggerHandler( "remove" );
});
}
}
return _remove.call( $(this), selector, keepData );
});
};
}
$.widget = function( name, base, prototype ) {
var namespace = name.split( "." )[ 0 ],
fullName;
name = name.split( "." )[ 1 ];
fullName = namespace + "-" + name;
if ( !prototype ) {
prototype = base;
base = $.Widget;
}
// create selector for plugin
$.expr[ ":" ][ fullName ] = function( elem ) {
return !!$.data( elem, name );
};
$[ namespace ] = $[ namespace ] || {};
$[ namespace ][ name ] = function( options, element ) {
// allow instantiation without initializing for simple inheritance
if ( arguments.length ) {
this._createWidget( options, element );
}
};
var basePrototype = new base();
// we need to make the options hash a property directly on the new instance
// otherwise we'll modify the options hash on the prototype that we're
// inheriting from
// $.each( basePrototype, function( key, val ) {
// if ( $.isPlainObject(val) ) {
// basePrototype[ key ] = $.extend( {}, val );
// }
// });
basePrototype.options = $.extend( true, {}, basePrototype.options );
$[ namespace ][ name ].prototype = $.extend( true, basePrototype, {
namespace: namespace,
widgetName: name,
widgetEventPrefix: $[ namespace ][ name ].prototype.widgetEventPrefix || name,
widgetBaseClass: fullName
}, prototype );
$.widget.bridge( name, $[ namespace ][ name ] );
};
$.widget.bridge = function( name, object ) {
$.fn[ name ] = function( options ) {
var isMethodCall = typeof options === "string",
args = Array.prototype.slice.call( arguments, 1 ),
returnValue = this;
// allow multiple hashes to be passed on init
options = !isMethodCall && args.length ?
$.extend.apply( null, [ true, options ].concat(args) ) :
options;
// prevent calls to internal methods
if ( isMethodCall && options.charAt( 0 ) === "_" ) {
return returnValue;
}
if ( isMethodCall ) {
this.each(function() {
var instance = $.data( this, name );
if ( !instance ) {
throw "cannot call methods on " + name + " prior to initialization; " +
"attempted to call method '" + options + "'";
}
if ( !$.isFunction( instance[options] ) ) {
throw "no such method '" + options + "' for " + name + " widget instance";
}
var methodValue = instance[ options ].apply( instance, args );
if ( methodValue !== instance && methodValue !== undefined ) {
returnValue = methodValue;
return false;
}
});
} else {
this.each(function() {
var instance = $.data( this, name );
if ( instance ) {
instance.option( options || {} )._init();
} else {
$.data( this, name, new object( options, this ) );
}
});
}
return returnValue;
};
};
$.Widget = function( options, element ) {
// allow instantiation without initializing for simple inheritance
if ( arguments.length ) {
this._createWidget( options, element );
}
};
$.Widget.prototype = {
widgetName: "widget",
widgetEventPrefix: "",
options: {
disabled: false
},
_createWidget: function( options, element ) {
// $.widget.bridge stores the plugin instance, but we do it anyway
// so that it's stored even before the _create function runs
$.data( element, this.widgetName, this );
this.element = $( element );
this.options = $.extend( true, {},
this.options,
this._getCreateOptions(),
options );
var self = this;
this.element.bind( "remove." + this.widgetName, function() {
self.destroy();
});
this._create();
this._trigger( "create" );
this._init();
},
_getCreateOptions: function() {
var options = {};
if ( $.metadata ) {
options = $.metadata.get( element )[ this.widgetName ];
}
return options;
},
_create: function() {},
_init: function() {},
destroy: function() {
this.element
.unbind( "." + this.widgetName )
.removeData( this.widgetName );
this.widget()
.unbind( "." + this.widgetName )
.removeAttr( "aria-disabled" )
.removeClass(
this.widgetBaseClass + "-disabled " +
"ui-state-disabled" );
},
widget: function() {
return this.element;
},
option: function( key, value ) {
var options = key;
if ( arguments.length === 0 ) {
// don't return a reference to the internal hash
return $.extend( {}, this.options );
}
if (typeof key === "string" ) {
if ( value === undefined ) {
return this.options[ key ];
}
options = {};
options[ key ] = value;
}
this._setOptions( options );
return this;
},
_setOptions: function( options ) {
var self = this;
$.each( options, function( key, value ) {
self._setOption( key, value );
});
return this;
},
_setOption: function( key, value ) {
this.options[ key ] = value;
if ( key === "disabled" ) {
this.widget()
[ value ? "addClass" : "removeClass"](
this.widgetBaseClass + "-disabled" + " " +
"ui-state-disabled" )
.attr( "aria-disabled", value );
}
return this;
},
enable: function() {
return this._setOption( "disabled", false );
},
disable: function() {
return this._setOption( "disabled", true );
},
_trigger: function( type, event, data ) {
var callback = this.options[ type ];
event = $.Event( event );
event.type = ( type === this.widgetEventPrefix ?
type :
this.widgetEventPrefix + type ).toLowerCase();
data = data || {};
// copy original event properties over to the new event
// this would happen if we could call $.event.fix instead of $.Event
// but we don't have a way to force an event to be fixed multiple times
if ( event.originalEvent ) {
for ( var i = $.event.props.length, prop; i; ) {
prop = $.event.props[ --i ];
event[ prop ] = event.originalEvent[ prop ];
}
}
this.element.trigger( event, data );
return !( $.isFunction(callback) &&
callback.call( this.element[0], event, data ) === false ||
event.isDefaultPrevented() );
}
};
})( jQuery );
(function( $, undefined ) {
$.widget( "mobile.widget", {
// decorate the parent _createWidget to trigger `widgetinit` for users
// who wish to do post post `widgetcreate` alterations/additions
//
// TODO create a pull request for jquery ui to trigger this event
// in the original _createWidget
_createWidget: function() {
$.Widget.prototype._createWidget.apply( this, arguments );
this._trigger( 'init' );
},
_getCreateOptions: function() {
var elem = this.element,
options = {};
$.each( this.options, function( option ) {
var value = elem.jqmData( option.replace( /[A-Z]/g, function( c ) {
return "-" + c.toLowerCase();
})
);
if ( value !== undefined ) {
options[ option ] = value;
}
});
return options;
},
enhanceWithin: function( target, useKeepNative ) {
this.enhance( $( this.options.initSelector, $( target )), useKeepNative );
},
enhance: function( targets, useKeepNative ) {
var page, keepNative, $widgetElements = $( targets ), self = this;
// if ignoreContentEnabled is set to true the framework should
// only enhance the selected elements when they do NOT have a
// parent with the data-namespace-ignore attribute
$widgetElements = $.mobile.enhanceable( $widgetElements );
if ( useKeepNative && $widgetElements.length ) {
// TODO remove dependency on the page widget for the keepNative.
// Currently the keepNative value is defined on the page prototype so
// the method is as well
page = $.mobile.closestPageData( $widgetElements );
keepNative = (page && page.keepNativeSelector()) || "";
$widgetElements = $widgetElements.not( keepNative );
}
$widgetElements[ this.widgetName ]();
},
raise: function( msg ) {
throw "Widget [" + this.widgetName + "]: " + msg;
}
});
})( jQuery );
(function( $, window, undefined ) {
var nsNormalizeDict = {};
// jQuery.mobile configurable options
$.mobile = $.extend( {}, {
// Version of the jQuery Mobile Framework
version: "1.1.0",
// Namespace used framework-wide for data-attrs. Default is no namespace
ns: "",
// Define the url parameter used for referencing widget-generated sub-pages.
// Translates to to example.html&ui-page=subpageIdentifier
// hash segment before &ui-page= is used to make Ajax request
subPageUrlKey: "ui-page",
// Class assigned to page currently in view, and during transitions
activePageClass: "ui-page-active",
// Class used for "active" button state, from CSS framework
activeBtnClass: "ui-btn-active",
// Class used for "focus" form element state, from CSS framework
focusClass: "ui-focus",
// Automatically handle clicks and form submissions through Ajax, when same-domain
ajaxEnabled: true,
// Automatically load and show pages based on location.hash
hashListeningEnabled: true,
// disable to prevent jquery from bothering with links
linkBindingEnabled: true,
// Set default page transition - 'none' for no transitions
defaultPageTransition: "fade",
// Set maximum window width for transitions to apply - 'false' for no limit
maxTransitionWidth: false,
// Minimum scroll distance that will be remembered when returning to a page
minScrollBack: 250,
// DEPRECATED: the following property is no longer in use, but defined until 2.0 to prevent conflicts
touchOverflowEnabled: false,
// Set default dialog transition - 'none' for no transitions
defaultDialogTransition: "pop",
// Show loading message during Ajax requests
// if false, message will not appear, but loading classes will still be toggled on html el
loadingMessage: "loading",
// Error response message - appears when an Ajax page request fails
pageLoadErrorMessage: "Error Loading Page",
// Should the text be visble in the loading message?
loadingMessageTextVisible: false,
// When the text is visible, what theme does the loading box use?
loadingMessageTheme: "a",
// For error messages, which theme does the box uses?
pageLoadErrorMessageTheme: "e",
//automatically initialize the DOM when it's ready
autoInitializePage: true,
pushStateEnabled: true,
// allows users to opt in to ignoring content by marking a parent element as
// data-ignored
ignoreContentEnabled: false,
// turn of binding to the native orientationchange due to android orientation behavior
orientationChangeEnabled: true,
buttonMarkup: {
hoverDelay: 200
},
// TODO might be useful upstream in jquery itself ?
keyCode: {
ALT: 18,
BACKSPACE: 8,
CAPS_LOCK: 20,
COMMA: 188,
COMMAND: 91,
COMMAND_LEFT: 91, // COMMAND
COMMAND_RIGHT: 93,
CONTROL: 17,
DELETE: 46,
DOWN: 40,
END: 35,
ENTER: 13,
ESCAPE: 27,
HOME: 36,
INSERT: 45,
LEFT: 37,
MENU: 93, // COMMAND_RIGHT
NUMPAD_ADD: 107,
NUMPAD_DECIMAL: 110,
NUMPAD_DIVIDE: 111,
NUMPAD_ENTER: 108,
NUMPAD_MULTIPLY: 106,
NUMPAD_SUBTRACT: 109,
PAGE_DOWN: 34,
PAGE_UP: 33,
PERIOD: 190,
RIGHT: 39,
SHIFT: 16,
SPACE: 32,
TAB: 9,
UP: 38,
WINDOWS: 91 // COMMAND
},
// Scroll page vertically: scroll to 0 to hide iOS address bar, or pass a Y value
silentScroll: function( ypos ) {
if ( $.type( ypos ) !== "number" ) {
ypos = $.mobile.defaultHomeScroll;
}
// prevent scrollstart and scrollstop events
$.event.special.scrollstart.enabled = false;
setTimeout(function() {
window.scrollTo( 0, ypos );
$( document ).trigger( "silentscroll", { x: 0, y: ypos });
}, 20 );
setTimeout(function() {
$.event.special.scrollstart.enabled = true;
}, 150 );
},
// Expose our cache for testing purposes.
nsNormalizeDict: nsNormalizeDict,
// Take a data attribute property, prepend the namespace
// and then camel case the attribute string. Add the result
// to our nsNormalizeDict so we don't have to do this again.
nsNormalize: function( prop ) {
if ( !prop ) {
return;
}
return nsNormalizeDict[ prop ] || ( nsNormalizeDict[ prop ] = $.camelCase( $.mobile.ns + prop ) );
},
getInheritedTheme: function( el, defaultTheme ) {
// Find the closest parent with a theme class on it. Note that
// we are not using $.fn.closest() on purpose here because this
// method gets called quite a bit and we need it to be as fast
// as possible.
var e = el[ 0 ],
ltr = "",
re = /ui-(bar|body|overlay)-([a-z])\b/,
c, m;
while ( e ) {
var c = e.className || "";
if ( ( m = re.exec( c ) ) && ( ltr = m[ 2 ] ) ) {
// We found a parent with a theme class
// on it so bail from this loop.
break;
}
e = e.parentNode;
}
// Return the theme letter we found, if none, return the
// specified default.
return ltr || defaultTheme || "a";
},
// TODO the following $ and $.fn extensions can/probably should be moved into jquery.mobile.core.helpers
//
// Find the closest javascript page element to gather settings data jsperf test
// http://jsperf.com/single-complex-selector-vs-many-complex-selectors/edit
// possibly naive, but it shows that the parsing overhead for *just* the page selector vs
// the page and dialog selector is negligable. This could probably be speed up by
// doing a similar parent node traversal to the one found in the inherited theme code above
closestPageData: function( $target ) {
return $target
.closest(':jqmData(role="page"), :jqmData(role="dialog")')
.data("page");
},
enhanceable: function( $set ) {
return this.haveParents( $set, "enhance" );
},
hijackable: function( $set ) {
return this.haveParents( $set, "ajax" );
},
haveParents: function( $set, attr ) {
if( !$.mobile.ignoreContentEnabled ){
return $set;
}
var count = $set.length,
$newSet = $(),
e, $element, excluded;
for ( var i = 0; i < count; i++ ) {
$element = $set.eq( i );
excluded = false;
e = $set[ i ];
while ( e ) {
var c = e.getAttribute ? e.getAttribute( "data-" + $.mobile.ns + attr ) : "";
if ( c === "false" ) {
excluded = true;
break;
}
e = e.parentNode;
}
if ( !excluded ) {
$newSet = $newSet.add( $element );
}
}
return $newSet;
}
}, $.mobile );
// Mobile version of data and removeData and hasData methods
// ensures all data is set and retrieved using jQuery Mobile's data namespace
$.fn.jqmData = function( prop, value ) {
var result;
if ( typeof prop != "undefined" ) {
if ( prop ) {
prop = $.mobile.nsNormalize( prop );
}
result = this.data.apply( this, arguments.length < 2 ? [ prop ] : [ prop, value ] );
}
return result;
};
$.jqmData = function( elem, prop, value ) {
var result;
if ( typeof prop != "undefined" ) {
result = $.data( elem, prop ? $.mobile.nsNormalize( prop ) : prop, value );
}
return result;
};
$.fn.jqmRemoveData = function( prop ) {
return this.removeData( $.mobile.nsNormalize( prop ) );
};
$.jqmRemoveData = function( elem, prop ) {
return $.removeData( elem, $.mobile.nsNormalize( prop ) );
};
$.fn.removeWithDependents = function() {
$.removeWithDependents( this );
};
$.removeWithDependents = function( elem ) {
var $elem = $( elem );
( $elem.jqmData('dependents') || $() ).remove();
$elem.remove();
};
$.fn.addDependents = function( newDependents ) {
$.addDependents( $(this), newDependents );
};
$.addDependents = function( elem, newDependents ) {
var dependents = $(elem).jqmData( 'dependents' ) || $();
$(elem).jqmData( 'dependents', $.merge(dependents, newDependents) );
};
// note that this helper doesn't attempt to handle the callback
// or setting of an html elements text, its only purpose is
// to return the html encoded version of the text in all cases. (thus the name)
$.fn.getEncodedText = function() {
return $( "<div/>" ).text( $(this).text() ).html();
};
// fluent helper function for the mobile namespaced equivalent
$.fn.jqmEnhanceable = function() {
return $.mobile.enhanceable( this );
};
$.fn.jqmHijackable = function() {
return $.mobile.hijackable( this );
};
// Monkey-patching Sizzle to filter the :jqmData selector
var oldFind = $.find,
jqmDataRE = /:jqmData\(([^)]*)\)/g;
$.find = function( selector, context, ret, extra ) {
selector = selector.replace( jqmDataRE, "[data-" + ( $.mobile.ns || "" ) + "$1]" );
return oldFind.call( this, selector, context, ret, extra );
};
$.extend( $.find, oldFind );
$.find.matches = function( expr, set ) {
return $.find( expr, null, null, set );
};
$.find.matchesSelector = function( node, expr ) {
return $.find( expr, null, null, [ node ] ).length > 0;
};
})( jQuery, this );
(function( $, undefined ) {
var $window = $( window ),
$html = $( "html" );
/* $.mobile.media method: pass a CSS media type or query and get a bool return
note: this feature relies on actual media query support for media queries, though types will work most anywhere
examples:
$.mobile.media('screen') // tests for screen media type
$.mobile.media('screen and (min-width: 480px)') // tests for screen media type with window width > 480px
$.mobile.media('@media screen and (-webkit-min-device-pixel-ratio: 2)') // tests for webkit 2x pixel ratio (iPhone 4)
*/
$.mobile.media = (function() {
// TODO: use window.matchMedia once at least one UA implements it
var cache = {},
testDiv = $( "<div id='jquery-mediatest'>" ),
fakeBody = $( "<body>" ).append( testDiv );
return function( query ) {
if ( !( query in cache ) ) {
var styleBlock = document.createElement( "style" ),
cssrule = "@media " + query + " { #jquery-mediatest { position:absolute; } }";
//must set type for IE!
styleBlock.type = "text/css";
if ( styleBlock.styleSheet ){
styleBlock.styleSheet.cssText = cssrule;
} else {
styleBlock.appendChild( document.createTextNode(cssrule) );
}
$html.prepend( fakeBody ).prepend( styleBlock );
cache[ query ] = testDiv.css( "position" ) === "absolute";
fakeBody.add( styleBlock ).remove();
}
return cache[ query ];
};
})();
})(jQuery);
(function( $, undefined ) {
var fakeBody = $( "<body>" ).prependTo( "html" ),
fbCSS = fakeBody[ 0 ].style,
vendors = [ "Webkit", "Moz", "O" ],
webos = "palmGetResource" in window, //only used to rule out scrollTop
operamini = window.operamini && ({}).toString.call( window.operamini ) === "[object OperaMini]",
bb = window.blackberry; //only used to rule out box shadow, as it's filled opaque on BB
// thx Modernizr
function propExists( prop ) {
var uc_prop = prop.charAt( 0 ).toUpperCase() + prop.substr( 1 ),
props = ( prop + " " + vendors.join( uc_prop + " " ) + uc_prop ).split( " " );
for ( var v in props ){
if ( fbCSS[ props[ v ] ] !== undefined ) {
return true;
}
}
}
function validStyle( prop, value, check_vend ) {
var div = document.createElement('div'),
uc = function( txt ) {
return txt.charAt( 0 ).toUpperCase() + txt.substr( 1 )
},
vend_pref = function( vend ) {
return "-" + vend.charAt( 0 ).toLowerCase() + vend.substr( 1 ) + "-";
},
check_style = function( vend ) {
var vend_prop = vend_pref( vend ) + prop + ": " + value + ";",
uc_vend = uc( vend ),
propStyle = uc_vend + uc( prop );
div.setAttribute( "style", vend_prop );
if( !!div.style[ propStyle ] ) {
ret = true;
}
},
check_vends = check_vend ? [ check_vend ] : vendors,
ret;
for( i = 0; i < check_vends.length; i++ ) {
check_style( check_vends[i] );
}
return !!ret;
}
// Thanks to Modernizr src for this test idea. `perspective` check is limited to Moz to prevent a false positive for 3D transforms on Android.
function transform3dTest() {
var prop = "transform-3d";
return validStyle( 'perspective', '10px', 'moz' ) || $.mobile.media( "(-" + vendors.join( "-" + prop + "),(-" ) + "-" + prop + "),(" + prop + ")" );
}
// Test for dynamic-updating base tag support ( allows us to avoid href,src attr rewriting )
function baseTagTest() {
var fauxBase = location.protocol + "//" + location.host + location.pathname + "ui-dir/",
base = $( "head base" ),
fauxEle = null,
href = "",
link, rebase;
if ( !base.length ) {
base = fauxEle = $( "<base>", { "href": fauxBase }).appendTo( "head" );
} else {
href = base.attr( "href" );
}
link = $( "<a href='testurl' />" ).prependTo( fakeBody );
rebase = link[ 0 ].href;
base[ 0 ].href = href || location.pathname;
if ( fauxEle ) {
fauxEle.remove();
}
return rebase.indexOf( fauxBase ) === 0;
}
// non-UA-based IE version check by James Padolsey, modified by jdalton - from http://gist.github.com/527683
// allows for inclusion of IE 6+, including Windows Mobile 7
$.extend( $.mobile, { browser: {} } );
$.mobile.browser.ie = (function() {
var v = 3,
div = document.createElement( "div" ),
a = div.all || [];
// added {} to silence closure compiler warnings. registering my dislike of all things
// overly clever here for future reference
while ( div.innerHTML = "<!--[if gt IE " + ( ++v ) + "]><br><![endif]-->", a[ 0 ] ){};
return v > 4 ? v : !v;
})();
$.extend( $.support, {
orientation: "orientation" in window && "onorientationchange" in window,
touch: "ontouchend" in document,
cssTransitions: "WebKitTransitionEvent" in window || validStyle( 'transition', 'height 100ms linear' ),
pushState: "pushState" in history && "replaceState" in history,
mediaquery: $.mobile.media( "only all" ),
cssPseudoElement: !!propExists( "content" ),
touchOverflow: !!propExists( "overflowScrolling" ),
cssTransform3d: transform3dTest(),
boxShadow: !!propExists( "boxShadow" ) && !bb,
scrollTop: ( "pageXOffset" in window || "scrollTop" in document.documentElement || "scrollTop" in fakeBody[ 0 ] ) && !webos && !operamini,
dynamicBaseTag: baseTagTest()
});
fakeBody.remove();
// $.mobile.ajaxBlacklist is used to override ajaxEnabled on platforms that have known conflicts with hash history updates (BB5, Symbian)
// or that generally work better browsing in regular http for full page refreshes (Opera Mini)
// Note: This detection below is used as a last resort.
// We recommend only using these detection methods when all other more reliable/forward-looking approaches are not possible
var nokiaLTE7_3 = (function(){
var ua = window.navigator.userAgent;
//The following is an attempt to match Nokia browsers that are running Symbian/s60, with webkit, version 7.3 or older
return ua.indexOf( "Nokia" ) > -1 &&
( ua.indexOf( "Symbian/3" ) > -1 || ua.indexOf( "Series60/5" ) > -1 ) &&
ua.indexOf( "AppleWebKit" ) > -1 &&
ua.match( /(BrowserNG|NokiaBrowser)\/7\.[0-3]/ );
})();
// Support conditions that must be met in order to proceed
// default enhanced qualifications are media query support OR IE 7+
$.mobile.gradeA = function(){
return $.support.mediaquery || $.mobile.browser.ie && $.mobile.browser.ie >= 7;
};
$.mobile.ajaxBlacklist =
// BlackBerry browsers, pre-webkit
window.blackberry && !window.WebKitPoint ||
// Opera Mini
operamini ||
// Symbian webkits pre 7.3
nokiaLTE7_3;
// Lastly, this workaround is the only way we've found so far to get pre 7.3 Symbian webkit devices
// to render the stylesheets when they're referenced before this script, as we'd recommend doing.
// This simply reappends the CSS in place, which for some reason makes it apply
if ( nokiaLTE7_3 ) {
$(function() {
$( "head link[rel='stylesheet']" ).attr( "rel", "alternate stylesheet" ).attr( "rel", "stylesheet" );
});
}
// For ruling out shadows via css
if ( !$.support.boxShadow ) {
$( "html" ).addClass( "ui-mobile-nosupport-boxshadow" );
}
})( jQuery );
(function( $, window, undefined ) {
// add new event shortcuts
$.each( ( "touchstart touchmove touchend orientationchange throttledresize " +
"tap taphold swipe swipeleft swiperight scrollstart scrollstop" ).split( " " ), function( i, name ) {
$.fn[ name ] = function( fn ) {
return fn ? this.bind( name, fn ) : this.trigger( name );
};
$.attrFn[ name ] = true;
});
var supportTouch = $.support.touch,
scrollEvent = "touchmove scroll",
touchStartEvent = supportTouch ? "touchstart" : "mousedown",
touchStopEvent = supportTouch ? "touchend" : "mouseup",
touchMoveEvent = supportTouch ? "touchmove" : "mousemove";
function triggerCustomEvent( obj, eventType, event ) {
var originalType = event.type;
event.type = eventType;
$.event.handle.call( obj, event );
event.type = originalType;
}
// also handles scrollstop
$.event.special.scrollstart = {
enabled: true,
setup: function() {
var thisObject = this,
$this = $( thisObject ),
scrolling,
timer;
function trigger( event, state ) {
scrolling = state;
triggerCustomEvent( thisObject, scrolling ? "scrollstart" : "scrollstop", event );
}
// iPhone triggers scroll after a small delay; use touchmove instead
$this.bind( scrollEvent, function( event ) {
if ( !$.event.special.scrollstart.enabled ) {
return;
}
if ( !scrolling ) {
trigger( event, true );
}
clearTimeout( timer );
timer = setTimeout(function() {
trigger( event, false );
}, 50 );
});
}
};
// also handles taphold
$.event.special.tap = {
setup: function() {
var thisObject = this,
$this = $( thisObject );
$this.bind( "vmousedown", function( event ) {
if ( event.which && event.which !== 1 ) {
return false;
}
var origTarget = event.target,
origEvent = event.originalEvent,
timer;
function clearTapTimer() {
clearTimeout( timer );
}
function clearTapHandlers() {
clearTapTimer();
$this.unbind( "vclick", clickHandler )
.unbind( "vmouseup", clearTapTimer );
$( document ).unbind( "vmousecancel", clearTapHandlers );
}
function clickHandler(event) {
clearTapHandlers();
// ONLY trigger a 'tap' event if the start target is
// the same as the stop target.
if ( origTarget == event.target ) {
triggerCustomEvent( thisObject, "tap", event );
}
}
$this.bind( "vmouseup", clearTapTimer )
.bind( "vclick", clickHandler );
$( document ).bind( "vmousecancel", clearTapHandlers );
timer = setTimeout(function() {
triggerCustomEvent( thisObject, "taphold", $.Event( "taphold", { target: origTarget } ) );
}, 750 );
});
}
};
// also handles swipeleft, swiperight
$.event.special.swipe = {
scrollSupressionThreshold: 10, // More than this horizontal displacement, and we will suppress scrolling.
durationThreshold: 1000, // More time than this, and it isn't a swipe.
horizontalDistanceThreshold: 30, // Swipe horizontal displacement must be more than this.
verticalDistanceThreshold: 75, // Swipe vertical displacement must be less than this.
setup: function() {
var thisObject = this,
$this = $( thisObject );
$this.bind( touchStartEvent, function( event ) {
var data = event.originalEvent.touches ?
event.originalEvent.touches[ 0 ] : event,
start = {
time: ( new Date() ).getTime(),
coords: [ data.pageX, data.pageY ],
origin: $( event.target )
},
stop;
function moveHandler( event ) {
if ( !start ) {
return;
}
var data = event.originalEvent.touches ?
event.originalEvent.touches[ 0 ] : event;
stop = {
time: ( new Date() ).getTime(),
coords: [ data.pageX, data.pageY ]
};
// prevent scrolling
if ( Math.abs( start.coords[ 0 ] - stop.coords[ 0 ] ) > $.event.special.swipe.scrollSupressionThreshold ) {
event.preventDefault();
}
}
$this.bind( touchMoveEvent, moveHandler )
.one( touchStopEvent, function( event ) {
$this.unbind( touchMoveEvent, moveHandler );
if ( start && stop ) {
if ( stop.time - start.time < $.event.special.swipe.durationThreshold &&
Math.abs( start.coords[ 0 ] - stop.coords[ 0 ] ) > $.event.special.swipe.horizontalDistanceThreshold &&
Math.abs( start.coords[ 1 ] - stop.coords[ 1 ] ) < $.event.special.swipe.verticalDistanceThreshold ) {
start.origin.trigger( "swipe" )
.trigger( start.coords[0] > stop.coords[ 0 ] ? "swipeleft" : "swiperight" );
}
}
start = stop = undefined;
});
});
}
};
(function( $, window ) {
// "Cowboy" Ben Alman
var win = $( window ),
special_event,
get_orientation,
last_orientation,
initial_orientation_is_landscape,
initial_orientation_is_default,
portrait_map = { "0": true, "180": true };
// It seems that some device/browser vendors use window.orientation values 0 and 180 to
// denote the "default" orientation. For iOS devices, and most other smart-phones tested,
// the default orientation is always "portrait", but in some Android and RIM based tablets,
// the default orientation is "landscape". The following code attempts to use the window
// dimensions to figure out what the current orientation is, and then makes adjustments
// to the to the portrait_map if necessary, so that we can properly decode the
// window.orientation value whenever get_orientation() is called.
//
// Note that we used to use a media query to figure out what the orientation the browser
// thinks it is in:
//
// initial_orientation_is_landscape = $.mobile.media("all and (orientation: landscape)");
//
// but there was an iPhone/iPod Touch bug beginning with iOS 4.2, up through iOS 5.1,
// where the browser *ALWAYS* applied the landscape media query. This bug does not
// happen on iPad.
if ( $.support.orientation ) {
// Check the window width and height to figure out what the current orientation
// of the device is at this moment. Note that we've initialized the portrait map
// values to 0 and 180, *AND* we purposely check for landscape so that if we guess
// wrong, , we default to the assumption that portrait is the default orientation.
// We use a threshold check below because on some platforms like iOS, the iPhone
// form-factor can report a larger width than height if the user turns on the
// developer console. The actual threshold value is somewhat arbitrary, we just
// need to make sure it is large enough to exclude the developer console case.
var ww = window.innerWidth || $( window ).width(),
wh = window.innerHeight || $( window ).height(),
landscape_threshold = 50;
initial_orientation_is_landscape = ww > wh && ( ww - wh ) > landscape_threshold;
// Now check to see if the current window.orientation is 0 or 180.
initial_orientation_is_default = portrait_map[ window.orientation ];
// If the initial orientation is landscape, but window.orientation reports 0 or 180, *OR*
// if the initial orientation is portrait, but window.orientation reports 90 or -90, we
// need to flip our portrait_map values because landscape is the default orientation for
// this device/browser.
if ( ( initial_orientation_is_landscape && initial_orientation_is_default ) || ( !initial_orientation_is_landscape && !initial_orientation_is_default ) ) {
portrait_map = { "-90": true, "90": true };
}
}
$.event.special.orientationchange = special_event = {
setup: function() {
// If the event is supported natively, return false so that jQuery
// will bind to the event using DOM methods.
if ( $.support.orientation && $.mobile.orientationChangeEnabled ) {
return false;
}
// Get the current orientation to avoid initial double-triggering.
last_orientation = get_orientation();
// Because the orientationchange event doesn't exist, simulate the
// event by testing window dimensions on resize.
win.bind( "throttledresize", handler );
},
teardown: function(){
// If the event is not supported natively, return false so that
// jQuery will unbind the event using DOM methods.
if ( $.support.orientation && $.mobile.orientationChangeEnabled ) {
return false;
}
// Because the orientationchange event doesn't exist, unbind the
// resize event handler.
win.unbind( "throttledresize", handler );
},
add: function( handleObj ) {
// Save a reference to the bound event handler.
var old_handler = handleObj.handler;
handleObj.handler = function( event ) {
// Modify event object, adding the .orientation property.
event.orientation = get_orientation();
// Call the originally-bound event handler and return its result.
return old_handler.apply( this, arguments );
};
}
};
// If the event is not supported natively, this handler will be bound to
// the window resize event to simulate the orientationchange event.
function handler() {
// Get the current orientation.
var orientation = get_orientation();
if ( orientation !== last_orientation ) {
// The orientation has changed, so trigger the orientationchange event.
last_orientation = orientation;
win.trigger( "orientationchange" );
}
}
// Get the current page orientation. This method is exposed publicly, should it
// be needed, as jQuery.event.special.orientationchange.orientation()
$.event.special.orientationchange.orientation = get_orientation = function() {
var isPortrait = true, elem = document.documentElement;
// prefer window orientation to the calculation based on screensize as
// the actual screen resize takes place before or after the orientation change event
// has been fired depending on implementation (eg android 2.3 is before, iphone after).
// More testing is required to determine if a more reliable method of determining the new screensize
// is possible when orientationchange is fired. (eg, use media queries + element + opacity)
if ( $.support.orientation ) {
// if the window orientation registers as 0 or 180 degrees report
// portrait, otherwise landscape
isPortrait = portrait_map[ window.orientation ];
} else {
isPortrait = elem && elem.clientWidth / elem.clientHeight < 1.1;
}
return isPortrait ? "portrait" : "landscape";
};
})( jQuery, window );
// throttled resize event
(function() {
$.event.special.throttledresize = {
setup: function() {
$( this ).bind( "resize", handler );
},
teardown: function(){
$( this ).unbind( "resize", handler );
}
};
var throttle = 250,
handler = function() {
curr = ( new Date() ).getTime();
diff = curr - lastCall;
if ( diff >= throttle ) {
lastCall = curr;
$( this ).trigger( "throttledresize" );
} else {
if ( heldCall ) {
clearTimeout( heldCall );
}
// Promise a held call will still execute
heldCall = setTimeout( handler, throttle - diff );
}
},
lastCall = 0,
heldCall,
curr,
diff;
})();
$.each({
scrollstop: "scrollstart",
taphold: "tap",
swipeleft: "swipe",
swiperight: "swipe"
}, function( event, sourceEvent ) {
$.event.special[ event ] = {
setup: function() {
$( this ).bind( sourceEvent, $.noop );
}
};
});
})( jQuery, this );
(function( $, undefined ) {
$.widget( "mobile.page", $.mobile.widget, {
options: {
theme: "c",
domCache: false,
keepNativeDefault: ":jqmData(role='none'), :jqmData(role='nojs')"
},
_create: function() {
var self = this;
// if false is returned by the callbacks do not create the page
if( self._trigger( "beforecreate" ) === false ){
return false;
}
self.element
.attr( "tabindex", "0" )
.addClass( "ui-page ui-body-" + self.options.theme )
.bind( "pagebeforehide", function(){
self.removeContainerBackground();
} )
.bind( "pagebeforeshow", function(){
self.setContainerBackground();
} );
},
removeContainerBackground: function(){
$.mobile.pageContainer.removeClass( "ui-overlay-" + $.mobile.getInheritedTheme( this.element.parent() ) );
},
// set the page container background to the page theme
setContainerBackground: function( theme ){
if( this.options.theme ){
$.mobile.pageContainer.addClass( "ui-overlay-" + ( theme || this.options.theme ) );
}
},
keepNativeSelector: function() {
var options = this.options,
keepNativeDefined = options.keepNative && $.trim(options.keepNative);
if( keepNativeDefined && options.keepNative !== options.keepNativeDefault ){
return [options.keepNative, options.keepNativeDefault].join(", ");
}
return options.keepNativeDefault;
}
});
})( jQuery );
(function( $, window, undefined ) {
var createHandler = function( sequential ){
// Default to sequential
if( sequential === undefined ){
sequential = true;
}
return function( name, reverse, $to, $from ) {
var deferred = new $.Deferred(),
reverseClass = reverse ? " reverse" : "",
active = $.mobile.urlHistory.getActive(),
toScroll = active.lastScroll || $.mobile.defaultHomeScroll,
screenHeight = $.mobile.getScreenHeight(),
maxTransitionOverride = $.mobile.maxTransitionWidth !== false && $( window ).width() > $.mobile.maxTransitionWidth,
none = !$.support.cssTransitions || maxTransitionOverride || !name || name === "none",
toggleViewportClass = function(){
$.mobile.pageContainer.toggleClass( "ui-mobile-viewport-transitioning viewport-" + name );
},
scrollPage = function(){
// By using scrollTo instead of silentScroll, we can keep things better in order
// Just to be precautios, disable scrollstart listening like silentScroll would
$.event.special.scrollstart.enabled = false;
window.scrollTo( 0, toScroll );
// reenable scrollstart listening like silentScroll would
setTimeout(function() {
$.event.special.scrollstart.enabled = true;
}, 150 );
},
cleanFrom = function(){
$from
.removeClass( $.mobile.activePageClass + " out in reverse " + name )
.height( "" );
},
startOut = function(){
// if it's not sequential, call the doneOut transition to start the TO page animating in simultaneously
if( !sequential ){
doneOut();
}
else {
$from.animationComplete( doneOut );
}
// Set the from page's height and start it transitioning out
// Note: setting an explicit height helps eliminate tiling in the transitions
$from
.height( screenHeight + $(window ).scrollTop() )
.addClass( name + " out" + reverseClass );
},
doneOut = function() {
if ( $from && sequential ) {
cleanFrom();
}
startIn();
},
startIn = function(){
$to.addClass( $.mobile.activePageClass );
// Send focus to page as it is now display: block
$.mobile.focusPage( $to );
// Set to page height
$to.height( screenHeight + toScroll );
scrollPage();
if( !none ){
$to.animationComplete( doneIn );
}
$to.addClass( name + " in" + reverseClass );
if( none ){
doneIn();
}
},
doneIn = function() {
if ( !sequential ) {
if( $from ){
cleanFrom();
}
}
$to
.removeClass( "out in reverse " + name )
.height( "" );
toggleViewportClass();
// In some browsers (iOS5), 3D transitions block the ability to scroll to the desired location during transition
// This ensures we jump to that spot after the fact, if we aren't there already.
if( $( window ).scrollTop() !== toScroll ){
scrollPage();
}
deferred.resolve( name, reverse, $to, $from, true );
};
toggleViewportClass();
if ( $from && !none ) {
startOut();
}
else {
doneOut();
}
return deferred.promise();
};
}
// generate the handlers from the above
var sequentialHandler = createHandler(),
simultaneousHandler = createHandler( false );
// Make our transition handler the public default.
$.mobile.defaultTransitionHandler = sequentialHandler;
//transition handler dictionary for 3rd party transitions
$.mobile.transitionHandlers = {
"default": $.mobile.defaultTransitionHandler,
"sequential": sequentialHandler,
"simultaneous": simultaneousHandler
};
$.mobile.transitionFallbacks = {};
})( jQuery, this );
( function( $, undefined ) {
//define vars for interal use
var $window = $( window ),
$html = $( 'html' ),
$head = $( 'head' ),
//url path helpers for use in relative url management
path = {
// This scary looking regular expression parses an absolute URL or its relative
// variants (protocol, site, document, query, and hash), into the various
// components (protocol, host, path, query, fragment, etc that make up the
// URL as well as some other commonly used sub-parts. When used with RegExp.exec()
// or String.match, it parses the URL into a results array that looks like this:
//
// [0]: http://jblas:password@mycompany.com:8080/mail/inbox?msg=1234&type=unread#msg-content
// [1]: http://jblas:password@mycompany.com:8080/mail/inbox?msg=1234&type=unread
// [2]: http://jblas:password@mycompany.com:8080/mail/inbox
// [3]: http://jblas:password@mycompany.com:8080
// [4]: http:
// [5]: //
// [6]: jblas:password@mycompany.com:8080
// [7]: jblas:password
// [8]: jblas
// [9]: password
// [10]: mycompany.com:8080
// [11]: mycompany.com
// [12]: 8080
// [13]: /mail/inbox
// [14]: /mail/
// [15]: inbox
// [16]: ?msg=1234&type=unread
// [17]: #msg-content
//
urlParseRE: /^(((([^:\/#\?]+:)?(?:(\/\/)((?:(([^:@\/#\?]+)(?:\:([^:@\/#\?]+))?)@)?(([^:\/#\?\]\[]+|\[[^\/\]@#?]+\])(?:\:([0-9]+))?))?)?)?((\/?(?:[^\/\?#]+\/+)*)([^\?#]*)))?(\?[^#]+)?)(#.*)?/,
//Parse a URL into a structure that allows easy access to
//all of the URL components by name.
parseUrl: function( url ) {
// If we're passed an object, we'll assume that it is
// a parsed url object and just return it back to the caller.
if ( $.type( url ) === "object" ) {
return url;
}
var matches = path.urlParseRE.exec( url || "" ) || [];
// Create an object that allows the caller to access the sub-matches
// by name. Note that IE returns an empty string instead of undefined,
// like all other browsers do, so we normalize everything so its consistent
// no matter what browser we're running on.
return {
href: matches[ 0 ] || "",
hrefNoHash: matches[ 1 ] || "",
hrefNoSearch: matches[ 2 ] || "",
domain: matches[ 3 ] || "",
protocol: matches[ 4 ] || "",
doubleSlash: matches[ 5 ] || "",
authority: matches[ 6 ] || "",
username: matches[ 8 ] || "",
password: matches[ 9 ] || "",
host: matches[ 10 ] || "",
hostname: matches[ 11 ] || "",
port: matches[ 12 ] || "",
pathname: matches[ 13 ] || "",
directory: matches[ 14 ] || "",
filename: matches[ 15 ] || "",
search: matches[ 16 ] || "",
hash: matches[ 17 ] || ""
};
},
//Turn relPath into an asbolute path. absPath is
//an optional absolute path which describes what
//relPath is relative to.
makePathAbsolute: function( relPath, absPath ) {
if ( relPath && relPath.charAt( 0 ) === "/" ) {
return relPath;
}
relPath = relPath || "";
absPath = absPath ? absPath.replace( /^\/|(\/[^\/]*|[^\/]+)$/g, "" ) : "";
var absStack = absPath ? absPath.split( "/" ) : [],
relStack = relPath.split( "/" );
for ( var i = 0; i < relStack.length; i++ ) {
var d = relStack[ i ];
switch ( d ) {
case ".":
break;
case "..":
if ( absStack.length ) {
absStack.pop();
}
break;
default:
absStack.push( d );
break;
}
}
return "/" + absStack.join( "/" );
},
//Returns true if both urls have the same domain.
isSameDomain: function( absUrl1, absUrl2 ) {
return path.parseUrl( absUrl1 ).domain === path.parseUrl( absUrl2 ).domain;
},
//Returns true for any relative variant.
isRelativeUrl: function( url ) {
// All relative Url variants have one thing in common, no protocol.
return path.parseUrl( url ).protocol === "";
},
//Returns true for an absolute url.
isAbsoluteUrl: function( url ) {
return path.parseUrl( url ).protocol !== "";
},
//Turn the specified realtive URL into an absolute one. This function
//can handle all relative variants (protocol, site, document, query, fragment).
makeUrlAbsolute: function( relUrl, absUrl ) {
if ( !path.isRelativeUrl( relUrl ) ) {
return relUrl;
}
var relObj = path.parseUrl( relUrl ),
absObj = path.parseUrl( absUrl ),
protocol = relObj.protocol || absObj.protocol,
doubleSlash = relObj.protocol ? relObj.doubleSlash : ( relObj.doubleSlash || absObj.doubleSlash ),
authority = relObj.authority || absObj.authority,
hasPath = relObj.pathname !== "",
pathname = path.makePathAbsolute( relObj.pathname || absObj.filename, absObj.pathname ),
search = relObj.search || ( !hasPath && absObj.search ) || "",
hash = relObj.hash;
return protocol + doubleSlash + authority + pathname + search + hash;
},
//Add search (aka query) params to the specified url.
addSearchParams: function( url, params ) {
var u = path.parseUrl( url ),
p = ( typeof params === "object" ) ? $.param( params ) : params,
s = u.search || "?";
return u.hrefNoSearch + s + ( s.charAt( s.length - 1 ) !== "?" ? "&" : "" ) + p + ( u.hash || "" );
},
convertUrlToDataUrl: function( absUrl ) {
var u = path.parseUrl( absUrl );
if ( path.isEmbeddedPage( u ) ) {
// For embedded pages, remove the dialog hash key as in getFilePath(),
// otherwise the Data Url won't match the id of the embedded Page.
return u.hash.split( dialogHashKey )[0].replace( /^#/, "" );
} else if ( path.isSameDomain( u, documentBase ) ) {
return u.hrefNoHash.replace( documentBase.domain, "" );
}
return absUrl;
},
//get path from current hash, or from a file path
get: function( newPath ) {
if( newPath === undefined ) {
newPath = location.hash;
}
return path.stripHash( newPath ).replace( /[^\/]*\.[^\/*]+$/, '' );
},
//return the substring of a filepath before the sub-page key, for making a server request
getFilePath: function( path ) {
var splitkey = '&' + $.mobile.subPageUrlKey;
return path && path.split( splitkey )[0].split( dialogHashKey )[0];
},
//set location hash to path
set: function( path ) {
location.hash = path;
},
//test if a given url (string) is a path
//NOTE might be exceptionally naive
isPath: function( url ) {
return ( /\// ).test( url );
},
//return a url path with the window's location protocol/hostname/pathname removed
clean: function( url ) {
return url.replace( documentBase.domain, "" );
},
//just return the url without an initial #
stripHash: function( url ) {
return url.replace( /^#/, "" );
},
//remove the preceding hash, any query params, and dialog notations
cleanHash: function( hash ) {
return path.stripHash( hash.replace( /\?.*$/, "" ).replace( dialogHashKey, "" ) );
},
//check whether a url is referencing the same domain, or an external domain or different protocol
//could be mailto, etc
isExternal: function( url ) {
var u = path.parseUrl( url );
return u.protocol && u.domain !== documentUrl.domain ? true : false;
},
hasProtocol: function( url ) {
return ( /^(:?\w+:)/ ).test( url );
},
//check if the specified url refers to the first page in the main application document.
isFirstPageUrl: function( url ) {
// We only deal with absolute paths.
var u = path.parseUrl( path.makeUrlAbsolute( url, documentBase ) ),
// Does the url have the same path as the document?
samePath = u.hrefNoHash === documentUrl.hrefNoHash || ( documentBaseDiffers && u.hrefNoHash === documentBase.hrefNoHash ),
// Get the first page element.
fp = $.mobile.firstPage,
// Get the id of the first page element if it has one.
fpId = fp && fp[0] ? fp[0].id : undefined;
// The url refers to the first page if the path matches the document and
// it either has no hash value, or the hash is exactly equal to the id of the
// first page element.
return samePath && ( !u.hash || u.hash === "#" || ( fpId && u.hash.replace( /^#/, "" ) === fpId ) );
},
isEmbeddedPage: function( url ) {
var u = path.parseUrl( url );
//if the path is absolute, then we need to compare the url against
//both the documentUrl and the documentBase. The main reason for this
//is that links embedded within external documents will refer to the
//application document, whereas links embedded within the application
//document will be resolved against the document base.
if ( u.protocol !== "" ) {
return ( u.hash && ( u.hrefNoHash === documentUrl.hrefNoHash || ( documentBaseDiffers && u.hrefNoHash === documentBase.hrefNoHash ) ) );
}
return (/^#/).test( u.href );
}
},
//will be defined when a link is clicked and given an active class
$activeClickedLink = null,
//urlHistory is purely here to make guesses at whether the back or forward button was clicked
//and provide an appropriate transition
urlHistory = {
// Array of pages that are visited during a single page load.
// Each has a url and optional transition, title, and pageUrl (which represents the file path, in cases where URL is obscured, such as dialogs)
stack: [],
//maintain an index number for the active page in the stack
activeIndex: 0,
//get active
getActive: function() {
return urlHistory.stack[ urlHistory.activeIndex ];
},
getPrev: function() {
return urlHistory.stack[ urlHistory.activeIndex - 1 ];
},
getNext: function() {
return urlHistory.stack[ urlHistory.activeIndex + 1 ];
},
// addNew is used whenever a new page is added
addNew: function( url, transition, title, pageUrl, role ) {
//if there's forward history, wipe it
if( urlHistory.getNext() ) {
urlHistory.clearForward();
}
urlHistory.stack.push( {url : url, transition: transition, title: title, pageUrl: pageUrl, role: role } );
urlHistory.activeIndex = urlHistory.stack.length - 1;
},
//wipe urls ahead of active index
clearForward: function() {
urlHistory.stack = urlHistory.stack.slice( 0, urlHistory.activeIndex + 1 );
},
directHashChange: function( opts ) {
var back , forward, newActiveIndex, prev = this.getActive();
// check if url isp in history and if it's ahead or behind current page
$.each( urlHistory.stack, function( i, historyEntry ) {
//if the url is in the stack, it's a forward or a back
if( opts.currentUrl === historyEntry.url ) {
//define back and forward by whether url is older or newer than current page
back = i < urlHistory.activeIndex;
forward = !back;
newActiveIndex = i;
}
});
// save new page index, null check to prevent falsey 0 result
this.activeIndex = newActiveIndex !== undefined ? newActiveIndex : this.activeIndex;
if( back ) {
( opts.either || opts.isBack )( true );
} else if( forward ) {
( opts.either || opts.isForward )( false );
}
},
//disable hashchange event listener internally to ignore one change
//toggled internally when location.hash is updated to match the url of a successful page load
ignoreNextHashChange: false
},
//define first selector to receive focus when a page is shown
focusable = "[tabindex],a,button:visible,select:visible,input",
//queue to hold simultanious page transitions
pageTransitionQueue = [],
//indicates whether or not page is in process of transitioning
isPageTransitioning = false,
//nonsense hash change key for dialogs, so they create a history entry
dialogHashKey = "&ui-state=dialog",
//existing base tag?
$base = $head.children( "base" ),
//tuck away the original document URL minus any fragment.
documentUrl = path.parseUrl( location.href ),
//if the document has an embedded base tag, documentBase is set to its
//initial value. If a base tag does not exist, then we default to the documentUrl.
documentBase = $base.length ? path.parseUrl( path.makeUrlAbsolute( $base.attr( "href" ), documentUrl.href ) ) : documentUrl,
//cache the comparison once.
documentBaseDiffers = ( documentUrl.hrefNoHash !== documentBase.hrefNoHash );
//base element management, defined depending on dynamic base tag support
var base = $.support.dynamicBaseTag ? {
//define base element, for use in routing asset urls that are referenced in Ajax-requested markup
element: ( $base.length ? $base : $( "<base>", { href: documentBase.hrefNoHash } ).prependTo( $head ) ),
//set the generated BASE element's href attribute to a new page's base path
set: function( href ) {
base.element.attr( "href", path.makeUrlAbsolute( href, documentBase ) );
},
//set the generated BASE element's href attribute to a new page's base path
reset: function() {
base.element.attr( "href", documentBase.hrefNoHash );
}
} : undefined;
/*
internal utility functions
--------------------------------------*/
//direct focus to the page title, or otherwise first focusable element
$.mobile.focusPage = function ( page ) {
var autofocus = page.find("[autofocus]"),
pageTitle = page.find( ".ui-title:eq(0)" );
if( autofocus.length ) {
autofocus.focus();
return;
}
if( pageTitle.length ) {
pageTitle.focus();
}
else{
page.focus();
}
}
//remove active classes after page transition or error
function removeActiveLinkClass( forceRemoval ) {
if( !!$activeClickedLink && ( !$activeClickedLink.closest( '.ui-page-active' ).length || forceRemoval ) ) {
$activeClickedLink.removeClass( $.mobile.activeBtnClass );
}
$activeClickedLink = null;
}
function releasePageTransitionLock() {
isPageTransitioning = false;
if( pageTransitionQueue.length > 0 ) {
$.mobile.changePage.apply( null, pageTransitionQueue.pop() );
}
}
// Save the last scroll distance per page, before it is hidden
var setLastScrollEnabled = true,
setLastScroll, delayedSetLastScroll;
setLastScroll = function() {
// this barrier prevents setting the scroll value based on the browser
// scrolling the window based on a hashchange
if( !setLastScrollEnabled ) {
return;
}
var active = $.mobile.urlHistory.getActive();
if( active ) {
var lastScroll = $window.scrollTop();
// Set active page's lastScroll prop.
// If the location we're scrolling to is less than minScrollBack, let it go.
active.lastScroll = lastScroll < $.mobile.minScrollBack ? $.mobile.defaultHomeScroll : lastScroll;
}
};
// bind to scrollstop to gather scroll position. The delay allows for the hashchange
// event to fire and disable scroll recording in the case where the browser scrolls
// to the hash targets location (sometimes the top of the page). once pagechange fires
// getLastScroll is again permitted to operate
delayedSetLastScroll = function() {
setTimeout( setLastScroll, 100 );
};
// disable an scroll setting when a hashchange has been fired, this only works
// because the recording of the scroll position is delayed for 100ms after
// the browser might have changed the position because of the hashchange
$window.bind( $.support.pushState ? "popstate" : "hashchange", function() {
setLastScrollEnabled = false;
});
// handle initial hashchange from chrome :(
$window.one( $.support.pushState ? "popstate" : "hashchange", function() {
setLastScrollEnabled = true;
});
// wait until the mobile page container has been determined to bind to pagechange
$window.one( "pagecontainercreate", function(){
// once the page has changed, re-enable the scroll recording
$.mobile.pageContainer.bind( "pagechange", function() {
setLastScrollEnabled = true;
// remove any binding that previously existed on the get scroll
// which may or may not be different than the scroll element determined for
// this page previously
$window.unbind( "scrollstop", delayedSetLastScroll );
// determine and bind to the current scoll element which may be the window
// or in the case of touch overflow the element with touch overflow
$window.bind( "scrollstop", delayedSetLastScroll );
});
});
// bind to scrollstop for the first page as "pagechange" won't be fired in that case
$window.bind( "scrollstop", delayedSetLastScroll );
//function for transitioning between two existing pages
function transitionPages( toPage, fromPage, transition, reverse ) {
if( fromPage ) {
//trigger before show/hide events
fromPage.data( "page" )._trigger( "beforehide", null, { nextPage: toPage } );
}
toPage.data( "page" )._trigger( "beforeshow", null, { prevPage: fromPage || $( "" ) } );
//clear page loader
$.mobile.hidePageLoadingMsg();
// If transition is defined, check if css 3D transforms are supported, and if not, if a fallback is specified
if( transition && !$.support.cssTransform3d && $.mobile.transitionFallbacks[ transition ] ){
transition = $.mobile.transitionFallbacks[ transition ];
}
//find the transition handler for the specified transition. If there
//isn't one in our transitionHandlers dictionary, use the default one.
//call the handler immediately to kick-off the transition.
var th = $.mobile.transitionHandlers[ transition || "default" ] || $.mobile.defaultTransitionHandler,
promise = th( transition, reverse, toPage, fromPage );
promise.done(function() {
//trigger show/hide events
if( fromPage ) {
fromPage.data( "page" )._trigger( "hide", null, { nextPage: toPage } );
}
//trigger pageshow, define prevPage as either fromPage or empty jQuery obj
toPage.data( "page" )._trigger( "show", null, { prevPage: fromPage || $( "" ) } );
});
return promise;
}
//simply set the active page's minimum height to screen height, depending on orientation
function getScreenHeight(){
// Native innerHeight returns more accurate value for this across platforms,
// jQuery version is here as a normalized fallback for platforms like Symbian
return window.innerHeight || $( window ).height();
}
$.mobile.getScreenHeight = getScreenHeight;
//simply set the active page's minimum height to screen height, depending on orientation
function resetActivePageHeight(){
var aPage = $( "." + $.mobile.activePageClass ),
aPagePadT = parseFloat( aPage.css( "padding-top" ) ),
aPagePadB = parseFloat( aPage.css( "padding-bottom" ) );
aPage.css( "min-height", getScreenHeight() - aPagePadT - aPagePadB );
}
//shared page enhancements
function enhancePage( $page, role ) {
// If a role was specified, make sure the data-role attribute
// on the page element is in sync.
if( role ) {
$page.attr( "data-" + $.mobile.ns + "role", role );
}
//run page plugin
$page.page();
}
/* exposed $.mobile methods */
//animation complete callback
$.fn.animationComplete = function( callback ) {
if( $.support.cssTransitions ) {
return $( this ).one( 'webkitAnimationEnd animationend', callback );
}
else{
// defer execution for consistency between webkit/non webkit
setTimeout( callback, 0 );
return $( this );
}
};
//expose path object on $.mobile
$.mobile.path = path;
//expose base object on $.mobile
$.mobile.base = base;
//history stack
$.mobile.urlHistory = urlHistory;
$.mobile.dialogHashKey = dialogHashKey;
//enable cross-domain page support
$.mobile.allowCrossDomainPages = false;
//return the original document url
$.mobile.getDocumentUrl = function(asParsedObject) {
return asParsedObject ? $.extend( {}, documentUrl ) : documentUrl.href;
};
//return the original document base url
$.mobile.getDocumentBase = function(asParsedObject) {
return asParsedObject ? $.extend( {}, documentBase ) : documentBase.href;
};
$.mobile._bindPageRemove = function() {
var page = $(this);
// when dom caching is not enabled or the page is embedded bind to remove the page on hide
if( !page.data("page").options.domCache
&& page.is(":jqmData(external-page='true')") ) {
page.bind( 'pagehide.remove', function() {
var $this = $( this ),
prEvent = new $.Event( "pageremove" );
$this.trigger( prEvent );
if( !prEvent.isDefaultPrevented() ){
$this.removeWithDependents();
}
});
}
};
// Load a page into the DOM.
$.mobile.loadPage = function( url, options ) {
// This function uses deferred notifications to let callers
// know when the page is done loading, or if an error has occurred.
var deferred = $.Deferred(),
// The default loadPage options with overrides specified by
// the caller.
settings = $.extend( {}, $.mobile.loadPage.defaults, options ),
// The DOM element for the page after it has been loaded.
page = null,
// If the reloadPage option is true, and the page is already
// in the DOM, dupCachedPage will be set to the page element
// so that it can be removed after the new version of the
// page is loaded off the network.
dupCachedPage = null,
// determine the current base url
findBaseWithDefault = function(){
var closestBase = ( $.mobile.activePage && getClosestBaseUrl( $.mobile.activePage ) );
return closestBase || documentBase.hrefNoHash;
},
// The absolute version of the URL passed into the function. This
// version of the URL may contain dialog/subpage params in it.
absUrl = path.makeUrlAbsolute( url, findBaseWithDefault() );
// If the caller provided data, and we're using "get" request,
// append the data to the URL.
if ( settings.data && settings.type === "get" ) {
absUrl = path.addSearchParams( absUrl, settings.data );
settings.data = undefined;
}
// If the caller is using a "post" request, reloadPage must be true
if( settings.data && settings.type === "post" ){
settings.reloadPage = true;
}
// The absolute version of the URL minus any dialog/subpage params.
// In otherwords the real URL of the page to be loaded.
var fileUrl = path.getFilePath( absUrl ),
// The version of the Url actually stored in the data-url attribute of
// the page. For embedded pages, it is just the id of the page. For pages
// within the same domain as the document base, it is the site relative
// path. For cross-domain pages (Phone Gap only) the entire absolute Url
// used to load the page.
dataUrl = path.convertUrlToDataUrl( absUrl );
// Make sure we have a pageContainer to work with.
settings.pageContainer = settings.pageContainer || $.mobile.pageContainer;
// Check to see if the page already exists in the DOM.
page = settings.pageContainer.children( ":jqmData(url='" + dataUrl + "')" );
// If we failed to find the page, check to see if the url is a
// reference to an embedded page. If so, it may have been dynamically
// injected by a developer, in which case it would be lacking a data-url
// attribute and in need of enhancement.
if ( page.length === 0 && dataUrl && !path.isPath( dataUrl ) ) {
page = settings.pageContainer.children( "#" + dataUrl )
.attr( "data-" + $.mobile.ns + "url", dataUrl );
}
// If we failed to find a page in the DOM, check the URL to see if it
// refers to the first page in the application. If it isn't a reference
// to the first page and refers to non-existent embedded page, error out.
if ( page.length === 0 ) {
if ( $.mobile.firstPage && path.isFirstPageUrl( fileUrl ) ) {
// Check to make sure our cached-first-page is actually
// in the DOM. Some user deployed apps are pruning the first
// page from the DOM for various reasons, we check for this
// case here because we don't want a first-page with an id
// falling through to the non-existent embedded page error
// case. If the first-page is not in the DOM, then we let
// things fall through to the ajax loading code below so
// that it gets reloaded.
if ( $.mobile.firstPage.parent().length ) {
page = $( $.mobile.firstPage );
}
} else if ( path.isEmbeddedPage( fileUrl ) ) {
deferred.reject( absUrl, options );
return deferred.promise();
}
}
// Reset base to the default document base.
if ( base ) {
base.reset();
}
// If the page we are interested in is already in the DOM,
// and the caller did not indicate that we should force a
// reload of the file, we are done. Otherwise, track the
// existing page as a duplicated.
if ( page.length ) {
if ( !settings.reloadPage ) {
enhancePage( page, settings.role );
deferred.resolve( absUrl, options, page );
return deferred.promise();
}
dupCachedPage = page;
}
var mpc = settings.pageContainer,
pblEvent = new $.Event( "pagebeforeload" ),
triggerData = { url: url, absUrl: absUrl, dataUrl: dataUrl, deferred: deferred, options: settings };
// Let listeners know we're about to load a page.
mpc.trigger( pblEvent, triggerData );
// If the default behavior is prevented, stop here!
if( pblEvent.isDefaultPrevented() ){
return deferred.promise();
}
if ( settings.showLoadMsg ) {
// This configurable timeout allows cached pages a brief delay to load without showing a message
var loadMsgDelay = setTimeout(function(){
$.mobile.showPageLoadingMsg();
}, settings.loadMsgDelay ),
// Shared logic for clearing timeout and removing message.
hideMsg = function(){
// Stop message show timer
clearTimeout( loadMsgDelay );
// Hide loading message
$.mobile.hidePageLoadingMsg();
};
}
if ( !( $.mobile.allowCrossDomainPages || path.isSameDomain( documentUrl, absUrl ) ) ) {
deferred.reject( absUrl, options );
} else {
// Load the new page.
$.ajax({
url: fileUrl,
type: settings.type,
data: settings.data,
dataType: "html",
success: function( html, textStatus, xhr ) {
//pre-parse html to check for a data-url,
//use it as the new fileUrl, base path, etc
var all = $( "<div></div>" ),
//page title regexp
newPageTitle = html.match( /<title[^>]*>([^<]*)/ ) && RegExp.$1,
// TODO handle dialogs again
pageElemRegex = new RegExp( "(<[^>]+\\bdata-" + $.mobile.ns + "role=[\"']?page[\"']?[^>]*>)" ),
dataUrlRegex = new RegExp( "\\bdata-" + $.mobile.ns + "url=[\"']?([^\"'>]*)[\"']?" );
// data-url must be provided for the base tag so resource requests can be directed to the
// correct url. loading into a temprorary element makes these requests immediately
if( pageElemRegex.test( html )
&& RegExp.$1
&& dataUrlRegex.test( RegExp.$1 )
&& RegExp.$1 ) {
url = fileUrl = path.getFilePath( RegExp.$1 );
}
if ( base ) {
base.set( fileUrl );
}
//workaround to allow scripts to execute when included in page divs
all.get( 0 ).innerHTML = html;
page = all.find( ":jqmData(role='page'), :jqmData(role='dialog')" ).first();
//if page elem couldn't be found, create one and insert the body element's contents
if( !page.length ){
page = $( "<div data-" + $.mobile.ns + "role='page'>" + html.split( /<\/?body[^>]*>/gmi )[1] + "</div>" );
}
if ( newPageTitle && !page.jqmData( "title" ) ) {
if ( ~newPageTitle.indexOf( "&" ) ) {
newPageTitle = $( "<div>" + newPageTitle + "</div>" ).text();
}
page.jqmData( "title", newPageTitle );
}
//rewrite src and href attrs to use a base url
if( !$.support.dynamicBaseTag ) {
var newPath = path.get( fileUrl );
page.find( "[src], link[href], a[rel='external'], :jqmData(ajax='false'), a[target]" ).each(function() {
var thisAttr = $( this ).is( '[href]' ) ? 'href' :
$(this).is('[src]') ? 'src' : 'action',
thisUrl = $( this ).attr( thisAttr );
// XXX_jblas: We need to fix this so that it removes the document
// base URL, and then prepends with the new page URL.
//if full path exists and is same, chop it - helps IE out
thisUrl = thisUrl.replace( location.protocol + '//' + location.host + location.pathname, '' );
if( !/^(\w+:|#|\/)/.test( thisUrl ) ) {
$( this ).attr( thisAttr, newPath + thisUrl );
}
});
}
//append to page and enhance
// TODO taging a page with external to make sure that embedded pages aren't removed
// by the various page handling code is bad. Having page handling code in many
// places is bad. Solutions post 1.0
page
.attr( "data-" + $.mobile.ns + "url", path.convertUrlToDataUrl( fileUrl ) )
.attr( "data-" + $.mobile.ns + "external-page", true )
.appendTo( settings.pageContainer );
// wait for page creation to leverage options defined on widget
page.one( 'pagecreate', $.mobile._bindPageRemove );
enhancePage( page, settings.role );
// Enhancing the page may result in new dialogs/sub pages being inserted
// into the DOM. If the original absUrl refers to a sub-page, that is the
// real page we are interested in.
if ( absUrl.indexOf( "&" + $.mobile.subPageUrlKey ) > -1 ) {
page = settings.pageContainer.children( ":jqmData(url='" + dataUrl + "')" );
}
//bind pageHide to removePage after it's hidden, if the page options specify to do so
// Remove loading message.
if ( settings.showLoadMsg ) {
hideMsg();
}
// Add the page reference and xhr to our triggerData.
triggerData.xhr = xhr;
triggerData.textStatus = textStatus;
triggerData.page = page;
// Let listeners know the page loaded successfully.
settings.pageContainer.trigger( "pageload", triggerData );
deferred.resolve( absUrl, options, page, dupCachedPage );
},
error: function( xhr, textStatus, errorThrown ) {
//set base back to current path
if( base ) {
base.set( path.get() );
}
// Add error info to our triggerData.
triggerData.xhr = xhr;
triggerData.textStatus = textStatus;
triggerData.errorThrown = errorThrown;
var plfEvent = new $.Event( "pageloadfailed" );
// Let listeners know the page load failed.
settings.pageContainer.trigger( plfEvent, triggerData );
// If the default behavior is prevented, stop here!
// Note that it is the responsibility of the listener/handler
// that called preventDefault(), to resolve/reject the
// deferred object within the triggerData.
if( plfEvent.isDefaultPrevented() ){
return;
}
// Remove loading message.
if ( settings.showLoadMsg ) {
// Remove loading message.
hideMsg();
// show error message
$.mobile.showPageLoadingMsg( $.mobile.pageLoadErrorMessageTheme, $.mobile.pageLoadErrorMessage, true );
// hide after delay
setTimeout( $.mobile.hidePageLoadingMsg, 1500 );
}
deferred.reject( absUrl, options );
}
});
}
return deferred.promise();
};
$.mobile.loadPage.defaults = {
type: "get",
data: undefined,
reloadPage: false,
role: undefined, // By default we rely on the role defined by the @data-role attribute.
showLoadMsg: false,
pageContainer: undefined,
loadMsgDelay: 50 // This delay allows loads that pull from browser cache to occur without showing the loading message.
};
// Show a specific page in the page container.
$.mobile.changePage = function( toPage, options ) {
// If we are in the midst of a transition, queue the current request.
// We'll call changePage() once we're done with the current transition to
// service the request.
if( isPageTransitioning ) {
pageTransitionQueue.unshift( arguments );
return;
}
var settings = $.extend( {}, $.mobile.changePage.defaults, options );
// Make sure we have a pageContainer to work with.
settings.pageContainer = settings.pageContainer || $.mobile.pageContainer;
// Make sure we have a fromPage.
settings.fromPage = settings.fromPage || $.mobile.activePage;
var mpc = settings.pageContainer,
pbcEvent = new $.Event( "pagebeforechange" ),
triggerData = { toPage: toPage, options: settings };
// Let listeners know we're about to change the current page.
mpc.trigger( pbcEvent, triggerData );
// If the default behavior is prevented, stop here!
if( pbcEvent.isDefaultPrevented() ){
return;
}
// We allow "pagebeforechange" observers to modify the toPage in the trigger
// data to allow for redirects. Make sure our toPage is updated.
toPage = triggerData.toPage;
// Set the isPageTransitioning flag to prevent any requests from
// entering this method while we are in the midst of loading a page
// or transitioning.
isPageTransitioning = true;
// If the caller passed us a url, call loadPage()
// to make sure it is loaded into the DOM. We'll listen
// to the promise object it returns so we know when
// it is done loading or if an error ocurred.
if ( typeof toPage == "string" ) {
$.mobile.loadPage( toPage, settings )
.done(function( url, options, newPage, dupCachedPage ) {
isPageTransitioning = false;
options.duplicateCachedPage = dupCachedPage;
$.mobile.changePage( newPage, options );
})
.fail(function( url, options ) {
isPageTransitioning = false;
//clear out the active button state
removeActiveLinkClass( true );
//release transition lock so navigation is free again
releasePageTransitionLock();
settings.pageContainer.trigger( "pagechangefailed", triggerData );
});
return;
}
// If we are going to the first-page of the application, we need to make
// sure settings.dataUrl is set to the application document url. This allows
// us to avoid generating a document url with an id hash in the case where the
// first-page of the document has an id attribute specified.
if ( toPage[ 0 ] === $.mobile.firstPage[ 0 ] && !settings.dataUrl ) {
settings.dataUrl = documentUrl.hrefNoHash;
}
// The caller passed us a real page DOM element. Update our
// internal state and then trigger a transition to the page.
var fromPage = settings.fromPage,
url = ( settings.dataUrl && path.convertUrlToDataUrl( settings.dataUrl ) ) || toPage.jqmData( "url" ),
// The pageUrl var is usually the same as url, except when url is obscured as a dialog url. pageUrl always contains the file path
pageUrl = url,
fileUrl = path.getFilePath( url ),
active = urlHistory.getActive(),
activeIsInitialPage = urlHistory.activeIndex === 0,
historyDir = 0,
pageTitle = document.title,
isDialog = settings.role === "dialog" || toPage.jqmData( "role" ) === "dialog";
// By default, we prevent changePage requests when the fromPage and toPage
// are the same element, but folks that generate content manually/dynamically
// and reuse pages want to be able to transition to the same page. To allow
// this, they will need to change the default value of allowSamePageTransition
// to true, *OR*, pass it in as an option when they manually call changePage().
// It should be noted that our default transition animations assume that the
// formPage and toPage are different elements, so they may behave unexpectedly.
// It is up to the developer that turns on the allowSamePageTransitiona option
// to either turn off transition animations, or make sure that an appropriate
// animation transition is used.
if( fromPage && fromPage[0] === toPage[0] && !settings.allowSamePageTransition ) {
isPageTransitioning = false;
mpc.trigger( "pagechange", triggerData );
return;
}
// We need to make sure the page we are given has already been enhanced.
enhancePage( toPage, settings.role );
// If the changePage request was sent from a hashChange event, check to see if the
// page is already within the urlHistory stack. If so, we'll assume the user hit
// the forward/back button and will try to match the transition accordingly.
if( settings.fromHashChange ) {
urlHistory.directHashChange({
currentUrl: url,
isBack: function() { historyDir = -1; },
isForward: function() { historyDir = 1; }
});
}
// Kill the keyboard.
// XXX_jblas: We need to stop crawling the entire document to kill focus. Instead,
// we should be tracking focus with a delegate() handler so we already have
// the element in hand at this point.
// Wrap this in a try/catch block since IE9 throw "Unspecified error" if document.activeElement
// is undefined when we are in an IFrame.
try {
if(document.activeElement && document.activeElement.nodeName.toLowerCase() != 'body') {
$(document.activeElement).blur();
} else {
$( "input:focus, textarea:focus, select:focus" ).blur();
}
} catch(e) {}
// If we're displaying the page as a dialog, we don't want the url
// for the dialog content to be used in the hash. Instead, we want
// to append the dialogHashKey to the url of the current page.
if ( isDialog && active ) {
// on the initial page load active.url is undefined and in that case should
// be an empty string. Moving the undefined -> empty string back into
// urlHistory.addNew seemed imprudent given undefined better represents
// the url state
url = ( active.url || "" ) + dialogHashKey;
}
// Set the location hash.
if( settings.changeHash !== false && url ) {
//disable hash listening temporarily
urlHistory.ignoreNextHashChange = true;
//update hash and history
path.set( url );
}
// if title element wasn't found, try the page div data attr too
// If this is a deep-link or a reload ( active === undefined ) then just use pageTitle
var newPageTitle = ( !active )? pageTitle : toPage.jqmData( "title" ) || toPage.children(":jqmData(role='header')").find(".ui-title" ).getEncodedText();
if( !!newPageTitle && pageTitle == document.title ) {
pageTitle = newPageTitle;
}
if ( !toPage.jqmData( "title" ) ) {
toPage.jqmData( "title", pageTitle );
}
// Make sure we have a transition defined.
settings.transition = settings.transition
|| ( ( historyDir && !activeIsInitialPage ) ? active.transition : undefined )
|| ( isDialog ? $.mobile.defaultDialogTransition : $.mobile.defaultPageTransition );
//add page to history stack if it's not back or forward
if( !historyDir ) {
urlHistory.addNew( url, settings.transition, pageTitle, pageUrl, settings.role );
}
//set page title
document.title = urlHistory.getActive().title;
//set "toPage" as activePage
$.mobile.activePage = toPage;
// If we're navigating back in the URL history, set reverse accordingly.
settings.reverse = settings.reverse || historyDir < 0;
transitionPages( toPage, fromPage, settings.transition, settings.reverse )
.done(function( name, reverse, $to, $from, alreadyFocused ) {
removeActiveLinkClass();
//if there's a duplicateCachedPage, remove it from the DOM now that it's hidden
if ( settings.duplicateCachedPage ) {
settings.duplicateCachedPage.remove();
}
// Send focus to the newly shown page. Moved from promise .done binding in transitionPages
// itself to avoid ie bug that reports offsetWidth as > 0 (core check for visibility)
// despite visibility: hidden addresses issue #2965
// https://github.com/jquery/jquery-mobile/issues/2965
if( !alreadyFocused ){
$.mobile.focusPage( toPage );
}
releasePageTransitionLock();
// Let listeners know we're all done changing the current page.
mpc.trigger( "pagechange", triggerData );
});
};
$.mobile.changePage.defaults = {
transition: undefined,
reverse: false,
changeHash: true,
fromHashChange: false,
role: undefined, // By default we rely on the role defined by the @data-role attribute.
duplicateCachedPage: undefined,
pageContainer: undefined,
showLoadMsg: true, //loading message shows by default when pages are being fetched during changePage
dataUrl: undefined,
fromPage: undefined,
allowSamePageTransition: false
};
/* Event Bindings - hashchange, submit, and click */
function findClosestLink( ele )
{
while ( ele ) {
// Look for the closest element with a nodeName of "a".
// Note that we are checking if we have a valid nodeName
// before attempting to access it. This is because the
// node we get called with could have originated from within
// an embedded SVG document where some symbol instance elements
// don't have nodeName defined on them, or strings are of type
// SVGAnimatedString.
if ( ( typeof ele.nodeName === "string" ) && ele.nodeName.toLowerCase() == "a" ) {
break;
}
ele = ele.parentNode;
}
return ele;
}
// The base URL for any given element depends on the page it resides in.
function getClosestBaseUrl( ele )
{
// Find the closest page and extract out its url.
var url = $( ele ).closest( ".ui-page" ).jqmData( "url" ),
base = documentBase.hrefNoHash;
if ( !url || !path.isPath( url ) ) {
url = base;
}
return path.makeUrlAbsolute( url, base);
}
//The following event bindings should be bound after mobileinit has been triggered
//the following function is called in the init file
$.mobile._registerInternalEvents = function(){
//bind to form submit events, handle with Ajax
$( document ).delegate( "form", "submit", function( event ) {
var $this = $( this );
if( !$.mobile.ajaxEnabled ||
// test that the form is, itself, ajax false
$this.is(":jqmData(ajax='false')") ||
// test that $.mobile.ignoreContentEnabled is set and
// the form or one of it's parents is ajax=false
!$this.jqmHijackable().length ) {
return;
}
var type = $this.attr( "method" ),
target = $this.attr( "target" ),
url = $this.attr( "action" );
// If no action is specified, browsers default to using the
// URL of the document containing the form. Since we dynamically
// pull in pages from external documents, the form should submit
// to the URL for the source document of the page containing
// the form.
if ( !url ) {
// Get the @data-url for the page containing the form.
url = getClosestBaseUrl( $this );
if ( url === documentBase.hrefNoHash ) {
// The url we got back matches the document base,
// which means the page must be an internal/embedded page,
// so default to using the actual document url as a browser
// would.
url = documentUrl.hrefNoSearch;
}
}
url = path.makeUrlAbsolute( url, getClosestBaseUrl($this) );
//external submits use regular HTTP
if( path.isExternal( url ) || target ) {
return;
}
$.mobile.changePage(
url,
{
type: type && type.length && type.toLowerCase() || "get",
data: $this.serialize(),
transition: $this.jqmData( "transition" ),
direction: $this.jqmData( "direction" ),
reloadPage: true
}
);
event.preventDefault();
});
//add active state on vclick
$( document ).bind( "vclick", function( event ) {
// if this isn't a left click we don't care. Its important to note
// that when the virtual event is generated it will create the which attr
if ( event.which > 1 || !$.mobile.linkBindingEnabled ) {
return;
}
var link = findClosestLink( event.target );
// split from the previous return logic to avoid find closest where possible
// TODO teach $.mobile.hijackable to operate on raw dom elements so the link wrapping
// can be avoided
if ( !$(link).jqmHijackable().length ) {
return;
}
if ( link ) {
if ( path.parseUrl( link.getAttribute( "href" ) || "#" ).hash !== "#" ) {
removeActiveLinkClass( true );
$activeClickedLink = $( link ).closest( ".ui-btn" ).not( ".ui-disabled" );
$activeClickedLink.addClass( $.mobile.activeBtnClass );
$( "." + $.mobile.activePageClass + " .ui-btn" ).not( link ).blur();
// By caching the href value to data and switching the href to a #, we can avoid address bar showing in iOS. The click handler resets the href during its initial steps if this data is present
$( link )
.jqmData( "href", $( link ).attr( "href" ) )
.attr( "href", "#" );
}
}
});
// click routing - direct to HTTP or Ajax, accordingly
$( document ).bind( "click", function( event ) {
if( !$.mobile.linkBindingEnabled ){
return;
}
var link = findClosestLink( event.target ), $link = $( link ), httpCleanup;
// If there is no link associated with the click or its not a left
// click we want to ignore the click
// TODO teach $.mobile.hijackable to operate on raw dom elements so the link wrapping
// can be avoided
if ( !link || event.which > 1 || !$link.jqmHijackable().length ) {
return;
}
//remove active link class if external (then it won't be there if you come back)
httpCleanup = function(){
window.setTimeout( function() { removeActiveLinkClass( true ); }, 200 );
};
// If there's data cached for the real href value, set the link's href back to it again. This pairs with an address bar workaround from the vclick handler
if( $link.jqmData( "href" ) ){
$link.attr( "href", $link.jqmData( "href" ) );
}
//if there's a data-rel=back attr, go back in history
if( $link.is( ":jqmData(rel='back')" ) ) {
window.history.back();
return false;
}
var baseUrl = getClosestBaseUrl( $link ),
//get href, if defined, otherwise default to empty hash
href = path.makeUrlAbsolute( $link.attr( "href" ) || "#", baseUrl );
//if ajax is disabled, exit early
if( !$.mobile.ajaxEnabled && !path.isEmbeddedPage( href ) ){
httpCleanup();
//use default click handling
return;
}
// XXX_jblas: Ideally links to application pages should be specified as
// an url to the application document with a hash that is either
// the site relative path or id to the page. But some of the
// internal code that dynamically generates sub-pages for nested
// lists and select dialogs, just write a hash in the link they
// create. This means the actual URL path is based on whatever
// the current value of the base tag is at the time this code
// is called. For now we are just assuming that any url with a
// hash in it is an application page reference.
if ( href.search( "#" ) != -1 ) {
href = href.replace( /[^#]*#/, "" );
if ( !href ) {
//link was an empty hash meant purely
//for interaction, so we ignore it.
event.preventDefault();
return;
} else if ( path.isPath( href ) ) {
//we have apath so make it the href we want to load.
href = path.makeUrlAbsolute( href, baseUrl );
} else {
//we have a simple id so use the documentUrl as its base.
href = path.makeUrlAbsolute( "#" + href, documentUrl.hrefNoHash );
}
}
// Should we handle this link, or let the browser deal with it?
var useDefaultUrlHandling = $link.is( "[rel='external']" ) || $link.is( ":jqmData(ajax='false')" ) || $link.is( "[target]" ),
// Some embedded browsers, like the web view in Phone Gap, allow cross-domain XHR
// requests if the document doing the request was loaded via the file:// protocol.
// This is usually to allow the application to "phone home" and fetch app specific
// data. We normally let the browser handle external/cross-domain urls, but if the
// allowCrossDomainPages option is true, we will allow cross-domain http/https
// requests to go through our page loading logic.
isCrossDomainPageLoad = ( $.mobile.allowCrossDomainPages && documentUrl.protocol === "file:" && href.search( /^https?:/ ) != -1 ),
//check for protocol or rel and its not an embedded page
//TODO overlap in logic from isExternal, rel=external check should be
// moved into more comprehensive isExternalLink
isExternal = useDefaultUrlHandling || ( path.isExternal( href ) && !isCrossDomainPageLoad );
if( isExternal ) {
httpCleanup();
//use default click handling
return;
}
//use ajax
var transition = $link.jqmData( "transition" ),
direction = $link.jqmData( "direction" ),
reverse = ( direction && direction === "reverse" ) ||
// deprecated - remove by 1.0
$link.jqmData( "back" ),
//this may need to be more specific as we use data-rel more
role = $link.attr( "data-" + $.mobile.ns + "rel" ) || undefined;
$.mobile.changePage( href, { transition: transition, reverse: reverse, role: role } );
event.preventDefault();
});
//prefetch pages when anchors with data-prefetch are encountered
$( document ).delegate( ".ui-page", "pageshow.prefetch", function() {
var urls = [];
$( this ).find( "a:jqmData(prefetch)" ).each(function(){
var $link = $(this),
url = $link.attr( "href" );
if ( url && $.inArray( url, urls ) === -1 ) {
urls.push( url );
$.mobile.loadPage( url, {role: $link.attr("data-" + $.mobile.ns + "rel")} );
}
});
});
$.mobile._handleHashChange = function( hash ) {
//find first page via hash
var to = path.stripHash( hash ),
//transition is false if it's the first page, undefined otherwise (and may be overridden by default)
transition = $.mobile.urlHistory.stack.length === 0 ? "none" : undefined,
// default options for the changPage calls made after examining the current state
// of the page and the hash
changePageOptions = {
transition: transition,
changeHash: false,
fromHashChange: true
};
//if listening is disabled (either globally or temporarily), or it's a dialog hash
if( !$.mobile.hashListeningEnabled || urlHistory.ignoreNextHashChange ) {
urlHistory.ignoreNextHashChange = false;
return;
}
// special case for dialogs
if( urlHistory.stack.length > 1 && to.indexOf( dialogHashKey ) > -1 ) {
// If current active page is not a dialog skip the dialog and continue
// in the same direction
if(!$.mobile.activePage.is( ".ui-dialog" )) {
//determine if we're heading forward or backward and continue accordingly past
//the current dialog
urlHistory.directHashChange({
currentUrl: to,
isBack: function() { window.history.back(); },
isForward: function() { window.history.forward(); }
});
// prevent changePage()
return;
} else {
// if the current active page is a dialog and we're navigating
// to a dialog use the dialog objected saved in the stack
urlHistory.directHashChange({
currentUrl: to,
// regardless of the direction of the history change
// do the following
either: function( isBack ) {
var active = $.mobile.urlHistory.getActive();
to = active.pageUrl;
// make sure to set the role, transition and reversal
// as most of this is lost by the domCache cleaning
$.extend( changePageOptions, {
role: active.role,
transition: active.transition,
reverse: isBack
});
}
});
}
}
//if to is defined, load it
if ( to ) {
// At this point, 'to' can be one of 3 things, a cached page element from
// a history stack entry, an id, or site-relative/absolute URL. If 'to' is
// an id, we need to resolve it against the documentBase, not the location.href,
// since the hashchange could've been the result of a forward/backward navigation
// that crosses from an external page/dialog to an internal page/dialog.
to = ( typeof to === "string" && !path.isPath( to ) ) ? ( path.makeUrlAbsolute( '#' + to, documentBase ) ) : to;
$.mobile.changePage( to, changePageOptions );
} else {
//there's no hash, go to the first page in the dom
$.mobile.changePage( $.mobile.firstPage, changePageOptions );
}
};
//hashchange event handler
$window.bind( "hashchange", function( e, triggered ) {
$.mobile._handleHashChange( location.hash );
});
//set page min-heights to be device specific
$( document ).bind( "pageshow", resetActivePageHeight );
$( window ).bind( "throttledresize", resetActivePageHeight );
};//_registerInternalEvents callback
})( jQuery );
( function( $, window ) {
// For now, let's Monkeypatch this onto the end of $.mobile._registerInternalEvents
// Scope self to pushStateHandler so we can reference it sanely within the
// methods handed off as event handlers
var pushStateHandler = {},
self = pushStateHandler,
$win = $( window ),
url = $.mobile.path.parseUrl( location.href );
$.extend( pushStateHandler, {
// TODO move to a path helper, this is rather common functionality
initialFilePath: (function() {
return url.pathname + url.search;
})(),
initialHref: url.hrefNoHash,
state: function() {
return {
hash: location.hash || "#" + self.initialFilePath,
title: document.title,
// persist across refresh
initialHref: self.initialHref
};
},
resetUIKeys: function( url ) {
var dialog = $.mobile.dialogHashKey,
subkey = "&" + $.mobile.subPageUrlKey,
dialogIndex = url.indexOf( dialog );
if( dialogIndex > -1 ) {
url = url.slice( 0, dialogIndex ) + "#" + url.slice( dialogIndex );
} else if( url.indexOf( subkey ) > -1 ) {
url = url.split( subkey ).join( "#" + subkey );
}
return url;
},
hashValueAfterReset: function( url ) {
var resetUrl = self.resetUIKeys( url );
return $.mobile.path.parseUrl( resetUrl ).hash;
},
// TODO sort out a single barrier to hashchange functionality
nextHashChangePrevented: function( value ) {
$.mobile.urlHistory.ignoreNextHashChange = value;
self.onHashChangeDisabled = value;
},
// on hash change we want to clean up the url
// NOTE this takes place *after* the vanilla navigation hash change
// handling has taken place and set the state of the DOM
onHashChange: function( e ) {
// disable this hash change
if( self.onHashChangeDisabled ){
return;
}
var href, state,
hash = location.hash,
isPath = $.mobile.path.isPath( hash ),
resolutionUrl = isPath ? location.href : $.mobile.getDocumentUrl();
hash = isPath ? hash.replace( "#", "" ) : hash;
// propulate the hash when its not available
state = self.state();
// make the hash abolute with the current href
href = $.mobile.path.makeUrlAbsolute( hash, resolutionUrl );
if ( isPath ) {
href = self.resetUIKeys( href );
}
// replace the current url with the new href and store the state
// Note that in some cases we might be replacing an url with the
// same url. We do this anyways because we need to make sure that
// all of our history entries have a state object associated with
// them. This allows us to work around the case where window.history.back()
// is called to transition from an external page to an embedded page.
// In that particular case, a hashchange event is *NOT* generated by the browser.
// Ensuring each history entry has a state object means that onPopState()
// will always trigger our hashchange callback even when a hashchange event
// is not fired.
history.replaceState( state, document.title, href );
},
// on popstate (ie back or forward) we need to replace the hash that was there previously
// cleaned up by the additional hash handling
onPopState: function( e ) {
var poppedState = e.originalEvent.state,
timeout, fromHash, toHash, hashChanged;
// if there's no state its not a popstate we care about, eg chrome's initial popstate
if( poppedState ) {
// the active url in the history stack will still be from the previous state
// so we can use it to verify if a hashchange will be fired from the popstate
fromHash = self.hashValueAfterReset( $.mobile.urlHistory.getActive().url );
// the hash stored in the state popped off the stack will be our currenturl or
// the url to which we wish to navigate
toHash = self.hashValueAfterReset( poppedState.hash.replace("#", "") );
// if the hashes of the urls are different we must assume that the browser
// will fire a hashchange
hashChanged = fromHash !== toHash;
// unlock hash handling once the hashchange caused be the popstate has fired
if( hashChanged ) {
$win.one( "hashchange.pushstate", function() {
self.nextHashChangePrevented( false );
});
}
// enable hash handling for the the _handleHashChange call
self.nextHashChangePrevented( false );
// change the page based on the hash
$.mobile._handleHashChange( poppedState.hash );
// only prevent another hash change handling if a hash change will be fired
// by the browser
if( hashChanged ) {
// disable hash handling until one of the above timers fires
self.nextHashChangePrevented( true );
}
}
},
init: function() {
$win.bind( "hashchange", self.onHashChange );
// Handle popstate events the occur through history changes
$win.bind( "popstate", self.onPopState );
// if there's no hash, we need to replacestate for returning to home
if ( location.hash === "" ) {
history.replaceState( self.state(), document.title, location.href );
}
}
});
$( function() {
if( $.mobile.pushStateEnabled && $.support.pushState ){
pushStateHandler.init();
}
});
})( jQuery, this );
/*
* fallback transition for pop in non-3D supporting browsers (which tend to handle complex transitions poorly in general
*/
(function( $, window, undefined ) {
$.mobile.transitionFallbacks.pop = "fade";
})( jQuery, this );
/*
* fallback transition for slide in non-3D supporting browsers (which tend to handle complex transitions poorly in general
*/
(function( $, window, undefined ) {
// Use the simultaneous transition handler for slide transitions
$.mobile.transitionHandlers.slide = $.mobile.transitionHandlers.simultaneous;
// Set the slide transition's fallback to "fade"
$.mobile.transitionFallbacks.slide = "fade";
})( jQuery, this );
/*
* fallback transition for slidedown in non-3D supporting browsers (which tend to handle complex transitions poorly in general
*/
(function( $, window, undefined ) {
$.mobile.transitionFallbacks.slidedown = "fade";
})( jQuery, this );
/*
* fallback transition for slideup in non-3D supporting browsers (which tend to handle complex transitions poorly in general
*/
(function( $, window, undefined ) {
$.mobile.transitionFallbacks.slideup = "fade";
})( jQuery, this );
/*
* fallback transition for flip in non-3D supporting browsers (which tend to handle complex transitions poorly in general
*/
(function( $, window, undefined ) {
$.mobile.transitionFallbacks.flip = "fade";
})( jQuery, this );
/*
* fallback transition for flow in non-3D supporting browsers (which tend to handle complex transitions poorly in general
*/
(function( $, window, undefined ) {
$.mobile.transitionFallbacks.flow = "fade";
})( jQuery, this );
/*
* fallback transition for turn in non-3D supporting browsers (which tend to handle complex transitions poorly in general
*/
(function( $, window, undefined ) {
$.mobile.transitionFallbacks.turn = "fade";
})( jQuery, this );
(function( $, undefined ) {
$.mobile.page.prototype.options.degradeInputs = {
color: false,
date: false,
datetime: false,
"datetime-local": false,
email: false,
month: false,
number: false,
range: "number",
search: "text",
tel: false,
time: false,
url: false,
week: false
};
//auto self-init widgets
$( document ).bind( "pagecreate create", function( e ){
var page = $.mobile.closestPageData($(e.target)), options;
if( !page ) {
return;
}
options = page.options;
// degrade inputs to avoid poorly implemented native functionality
$( e.target ).find( "input" ).not( page.keepNativeSelector() ).each(function() {
var $this = $( this ),
type = this.getAttribute( "type" ),
optType = options.degradeInputs[ type ] || "text";
if ( options.degradeInputs[ type ] ) {
var html = $( "<div>" ).html( $this.clone() ).html(),
// In IE browsers, the type sometimes doesn't exist in the cloned markup, so we replace the closing tag instead
hasType = html.indexOf( " type=" ) > -1,
findstr = hasType ? /\s+type=["']?\w+['"]?/ : /\/?>/,
repstr = " type=\"" + optType + "\" data-" + $.mobile.ns + "type=\"" + type + "\"" + ( hasType ? "" : ">" );
$this.replaceWith( html.replace( findstr, repstr ) );
}
});
});
})( jQuery );
(function( $, window, undefined ) {
$.widget( "mobile.dialog", $.mobile.widget, {
options: {
closeBtnText : "Close",
overlayTheme : "a",
initSelector : ":jqmData(role='dialog')"
},
_create: function() {
var self = this,
$el = this.element,
headerCloseButton = $( "<a href='#' data-" + $.mobile.ns + "icon='delete' data-" + $.mobile.ns + "iconpos='notext'>"+ this.options.closeBtnText + "</a>" ),
dialogWrap = $("<div/>", {
"role" : "dialog",
"class" : "ui-dialog-contain ui-corner-all ui-overlay-shadow"
});
$el.addClass( "ui-dialog ui-overlay-" + this.options.overlayTheme );
// Class the markup for dialog styling
// Set aria role
$el
.wrapInner( dialogWrap )
.children()
.find( ":jqmData(role='header')" )
.prepend( headerCloseButton )
.end()
.children( ':first-child')
.addClass( "ui-corner-top" )
.end()
.children( ":last-child" )
.addClass( "ui-corner-bottom" );
// this must be an anonymous function so that select menu dialogs can replace
// the close method. This is a change from previously just defining data-rel=back
// on the button and letting nav handle it
//
// Use click rather than vclick in order to prevent the possibility of unintentionally
// reopening the dialog if the dialog opening item was directly under the close button.
headerCloseButton.bind( "click", function() {
self.close();
});
/* bind events
- clicks and submits should use the closing transition that the dialog opened with
unless a data-transition is specified on the link/form
- if the click was on the close button, or the link has a data-rel="back" it'll go back in history naturally
*/
$el.bind( "vclick submit", function( event ) {
var $target = $( event.target ).closest( event.type === "vclick" ? "a" : "form" ),
active;
if ( $target.length && !$target.jqmData( "transition" ) ) {
active = $.mobile.urlHistory.getActive() || {};
$target.attr( "data-" + $.mobile.ns + "transition", ( active.transition || $.mobile.defaultDialogTransition ) )
.attr( "data-" + $.mobile.ns + "direction", "reverse" );
}
})
.bind( "pagehide", function( e, ui ) {
$( this ).find( "." + $.mobile.activeBtnClass ).removeClass( $.mobile.activeBtnClass );
})
// Override the theme set by the page plugin on pageshow
.bind( "pagebeforeshow", function(){
if( self.options.overlayTheme ){
self.element
.page( "removeContainerBackground" )
.page( "setContainerBackground", self.options.overlayTheme );
}
});
},
// Close method goes back in history
close: function() {
window.history.back();
}
});
//auto self-init widgets
$( document ).delegate( $.mobile.dialog.prototype.options.initSelector, "pagecreate", function(){
$.mobile.dialog.prototype.enhance( this );
});
})( jQuery, this );
(function( $, undefined ) {
$.fn.fieldcontain = function( options ) {
return this.addClass( "ui-field-contain ui-body ui-br" );
};
//auto self-init widgets
$( document ).bind( "pagecreate create", function( e ){
$( ":jqmData(role='fieldcontain')", e.target ).jqmEnhanceable().fieldcontain();
});
})( jQuery );
(function( $, undefined ) {
$.fn.grid = function( options ) {
return this.each(function() {
var $this = $( this ),
o = $.extend({
grid: null
},options),
$kids = $this.children(),
gridCols = {solo:1, a:2, b:3, c:4, d:5},
grid = o.grid,
iterator;
if ( !grid ) {
if ( $kids.length <= 5 ) {
for ( var letter in gridCols ) {
if ( gridCols[ letter ] === $kids.length ) {
grid = letter;
}
}
} else {
grid = "a";
}
}
iterator = gridCols[grid];
$this.addClass( "ui-grid-" + grid );
$kids.filter( ":nth-child(" + iterator + "n+1)" ).addClass( "ui-block-a" );
if ( iterator > 1 ) {
$kids.filter( ":nth-child(" + iterator + "n+2)" ).addClass( "ui-block-b" );
}
if ( iterator > 2 ) {
$kids.filter( ":nth-child(3n+3)" ).addClass( "ui-block-c" );
}
if ( iterator > 3 ) {
$kids.filter( ":nth-child(4n+4)" ).addClass( "ui-block-d" );
}
if ( iterator > 4 ) {
$kids.filter( ":nth-child(5n+5)" ).addClass( "ui-block-e" );
}
});
};
})( jQuery );
(function( $, undefined ) {
$( document ).bind( "pagecreate create", function( e ){
$( ":jqmData(role='nojs')", e.target ).addClass( "ui-nojs" );
});
})( jQuery );
( function( $, undefined ) {
$.fn.buttonMarkup = function( options ) {
var $workingSet = this;
// Enforce options to be of type string
options = ( options && ( $.type( options ) == "object" ) )? options : {};
for ( var i = 0; i < $workingSet.length; i++ ) {
var el = $workingSet.eq( i ),
e = el[ 0 ],
o = $.extend( {}, $.fn.buttonMarkup.defaults, {
icon: options.icon !== undefined ? options.icon : el.jqmData( "icon" ),
iconpos: options.iconpos !== undefined ? options.iconpos : el.jqmData( "iconpos" ),
theme: options.theme !== undefined ? options.theme : el.jqmData( "theme" ) || $.mobile.getInheritedTheme( el, "c" ),
inline: options.inline !== undefined ? options.inline : el.jqmData( "inline" ),
shadow: options.shadow !== undefined ? options.shadow : el.jqmData( "shadow" ),
corners: options.corners !== undefined ? options.corners : el.jqmData( "corners" ),
iconshadow: options.iconshadow !== undefined ? options.iconshadow : el.jqmData( "iconshadow" ),
mini: options.mini !== undefined ? options.mini : el.jqmData( "mini" )
}, options ),
// Classes Defined
innerClass = "ui-btn-inner",
textClass = "ui-btn-text",
buttonClass, iconClass,
// Button inner markup
buttonInner,
buttonText,
buttonIcon,
buttonElements;
$.each(o, function(key, value) {
e.setAttribute( "data-" + $.mobile.ns + key, value );
el.jqmData(key, value);
});
// Check if this element is already enhanced
buttonElements = $.data(((e.tagName === "INPUT" || e.tagName === "BUTTON") ? e.parentNode : e), "buttonElements");
if (buttonElements) {
e = buttonElements.outer;
el = $(e);
buttonInner = buttonElements.inner;
buttonText = buttonElements.text;
// We will recreate this icon below
$(buttonElements.icon).remove();
buttonElements.icon = null;
}
else {
buttonInner = document.createElement( o.wrapperEls );
buttonText = document.createElement( o.wrapperEls );
}
buttonIcon = o.icon ? document.createElement( "span" ) : null;
if ( attachEvents && !buttonElements) {
attachEvents();
}
// if not, try to find closest theme container
if ( !o.theme ) {
o.theme = $.mobile.getInheritedTheme( el, "c" );
}
buttonClass = "ui-btn ui-btn-up-" + o.theme;
buttonClass += o.inline ? " ui-btn-inline" : "";
buttonClass += o.shadow ? " ui-shadow" : "";
buttonClass += o.corners ? " ui-btn-corner-all" : "";
if ( o.mini !== undefined ) {
// Used to control styling in headers/footers, where buttons default to `mini` style.
buttonClass += o.mini ? " ui-mini" : " ui-fullsize";
}
if ( o.inline !== undefined ) {
// Used to control styling in headers/footers, where buttons default to `mini` style.
buttonClass += o.inline === false ? " ui-btn-block" : " ui-btn-inline";
}
if ( o.icon ) {
o.icon = "ui-icon-" + o.icon;
o.iconpos = o.iconpos || "left";
iconClass = "ui-icon " + o.icon;
if ( o.iconshadow ) {
iconClass += " ui-icon-shadow";
}
}
if ( o.iconpos ) {
buttonClass += " ui-btn-icon-" + o.iconpos;
if ( o.iconpos == "notext" && !el.attr( "title" ) ) {
el.attr( "title", el.getEncodedText() );
}
}
innerClass += o.corners ? " ui-btn-corner-all" : "";
if ( o.iconpos && o.iconpos === "notext" && !el.attr( "title" ) ) {
el.attr( "title", el.getEncodedText() );
}
if ( buttonElements ) {
el.removeClass( buttonElements.bcls || "" );
}
el.removeClass( "ui-link" ).addClass( buttonClass );
buttonInner.className = innerClass;
buttonText.className = textClass;
if ( !buttonElements ) {
buttonInner.appendChild( buttonText );
}
if ( buttonIcon ) {
buttonIcon.className = iconClass;
if ( !(buttonElements && buttonElements.icon) ) {
buttonIcon.appendChild( document.createTextNode("\u00a0") );
buttonInner.appendChild( buttonIcon );
}
}
while ( e.firstChild && !buttonElements) {
buttonText.appendChild( e.firstChild );
}
if ( !buttonElements ) {
e.appendChild( buttonInner );
}
// Assign a structure containing the elements of this button to the elements of this button. This
// will allow us to recognize this as an already-enhanced button in future calls to buttonMarkup().
buttonElements = {
bcls : buttonClass,
outer : e,
inner : buttonInner,
text : buttonText,
icon : buttonIcon
};
$.data(e, 'buttonElements', buttonElements);
$.data(buttonInner, 'buttonElements', buttonElements);
$.data(buttonText, 'buttonElements', buttonElements);
if (buttonIcon) {
$.data(buttonIcon, 'buttonElements', buttonElements);
}
}
return this;
};
$.fn.buttonMarkup.defaults = {
corners: true,
shadow: true,
iconshadow: true,
wrapperEls: "span"
};
function closestEnabledButton( element ) {
var cname;
while ( element ) {
// Note that we check for typeof className below because the element we
// handed could be in an SVG DOM where className on SVG elements is defined to
// be of a different type (SVGAnimatedString). We only operate on HTML DOM
// elements, so we look for plain "string".
cname = ( typeof element.className === 'string' ) && (element.className + ' ');
if ( cname && cname.indexOf("ui-btn ") > -1 && cname.indexOf("ui-disabled ") < 0 ) {
break;
}
element = element.parentNode;
}
return element;
}
var attachEvents = function() {
var hoverDelay = $.mobile.buttonMarkup.hoverDelay, hov, foc;
$( document ).bind( {
"vmousedown vmousecancel vmouseup vmouseover vmouseout focus blur scrollstart": function( event ) {
var theme,
$btn = $( closestEnabledButton( event.target ) ),
evt = event.type;
if ( $btn.length ) {
theme = $btn.attr( "data-" + $.mobile.ns + "theme" );
if ( evt === "vmousedown" ) {
if ( $.support.touch ) {
hov = setTimeout(function() {
$btn.removeClass( "ui-btn-up-" + theme ).addClass( "ui-btn-down-" + theme );
}, hoverDelay );
} else {
$btn.removeClass( "ui-btn-up-" + theme ).addClass( "ui-btn-down-" + theme );
}
} else if ( evt === "vmousecancel" || evt === "vmouseup" ) {
$btn.removeClass( "ui-btn-down-" + theme ).addClass( "ui-btn-up-" + theme );
} else if ( evt === "vmouseover" || evt === "focus" ) {
if ( $.support.touch ) {
foc = setTimeout(function() {
$btn.removeClass( "ui-btn-up-" + theme ).addClass( "ui-btn-hover-" + theme );
}, hoverDelay );
} else {
$btn.removeClass( "ui-btn-up-" + theme ).addClass( "ui-btn-hover-" + theme );
}
} else if ( evt === "vmouseout" || evt === "blur" || evt === "scrollstart" ) {
$btn.removeClass( "ui-btn-hover-" + theme + " ui-btn-down-" + theme ).addClass( "ui-btn-up-" + theme );
if ( hov ) {
clearTimeout( hov );
}
if ( foc ) {
clearTimeout( foc );
}
}
}
},
"focusin focus": function( event ){
$( closestEnabledButton( event.target ) ).addClass( $.mobile.focusClass );
},
"focusout blur": function( event ){
$( closestEnabledButton( event.target ) ).removeClass( $.mobile.focusClass );
}
});
attachEvents = null;
};
//links in bars, or those with data-role become buttons
//auto self-init widgets
$( document ).bind( "pagecreate create", function( e ){
$( ":jqmData(role='button'), .ui-bar > a, .ui-header > a, .ui-footer > a, .ui-bar > :jqmData(role='controlgroup') > a", e.target )
.not( ".ui-btn, :jqmData(role='none'), :jqmData(role='nojs')" )
.buttonMarkup();
});
})( jQuery );
(function( $, undefined ) {
$.mobile.page.prototype.options.backBtnText = "Back";
$.mobile.page.prototype.options.addBackBtn = false;
$.mobile.page.prototype.options.backBtnTheme = null;
$.mobile.page.prototype.options.headerTheme = "a";
$.mobile.page.prototype.options.footerTheme = "a";
$.mobile.page.prototype.options.contentTheme = null;
$( document ).delegate( ":jqmData(role='page'), :jqmData(role='dialog')", "pagecreate", function( e ) {
var $page = $( this ),
o = $page.data( "page" ).options,
pageRole = $page.jqmData( "role" ),
pageTheme = o.theme;
$( ":jqmData(role='header'), :jqmData(role='footer'), :jqmData(role='content')", this )
.jqmEnhanceable()
.each(function() {
var $this = $( this ),
role = $this.jqmData( "role" ),
theme = $this.jqmData( "theme" ),
contentTheme = theme || o.contentTheme || ( pageRole === "dialog" && pageTheme ),
$headeranchors,
leftbtn,
rightbtn,
backBtn;
$this.addClass( "ui-" + role );
//apply theming and markup modifications to page,header,content,footer
if ( role === "header" || role === "footer" ) {
var thisTheme = theme || ( role === "header" ? o.headerTheme : o.footerTheme ) || pageTheme;
$this
//add theme class
.addClass( "ui-bar-" + thisTheme )
// Add ARIA role
.attr( "role", role === "header" ? "banner" : "contentinfo" );
if( role === "header") {
// Right,left buttons
$headeranchors = $this.children( "a" );
leftbtn = $headeranchors.hasClass( "ui-btn-left" );
rightbtn = $headeranchors.hasClass( "ui-btn-right" );
leftbtn = leftbtn || $headeranchors.eq( 0 ).not( ".ui-btn-right" ).addClass( "ui-btn-left" ).length;
rightbtn = rightbtn || $headeranchors.eq( 1 ).addClass( "ui-btn-right" ).length;
}
// Auto-add back btn on pages beyond first view
if ( o.addBackBtn &&
role === "header" &&
$( ".ui-page" ).length > 1 &&
$page.jqmData( "url" ) !== $.mobile.path.stripHash( location.hash ) &&
!leftbtn ) {
backBtn = $( "<a href='#' class='ui-btn-left' data-"+ $.mobile.ns +"rel='back' data-"+ $.mobile.ns +"icon='arrow-l'>"+ o.backBtnText +"</a>" )
// If theme is provided, override default inheritance
.attr( "data-"+ $.mobile.ns +"theme", o.backBtnTheme || thisTheme )
.prependTo( $this );
}
// Page title
$this.children( "h1, h2, h3, h4, h5, h6" )
.addClass( "ui-title" )
// Regardless of h element number in src, it becomes h1 for the enhanced page
.attr({
"role": "heading",
"aria-level": "1"
});
} else if ( role === "content" ) {
if ( contentTheme ) {
$this.addClass( "ui-body-" + ( contentTheme ) );
}
// Add ARIA role
$this.attr( "role", "main" );
}
});
});
})( jQuery );
(function( $, undefined ) {
$.widget( "mobile.collapsible", $.mobile.widget, {
options: {
expandCueText: " click to expand contents",
collapseCueText: " click to collapse contents",
collapsed: true,
heading: "h1,h2,h3,h4,h5,h6,legend",
theme: null,
contentTheme: null,
iconTheme: "d",
mini: false,
initSelector: ":jqmData(role='collapsible')"
},
_create: function() {
var $el = this.element,
o = this.options,
collapsible = $el.addClass( "ui-collapsible" ),
collapsibleHeading = $el.children( o.heading ).first(),
collapsibleContent = collapsible.wrapInner( "<div class='ui-collapsible-content'></div>" ).find( ".ui-collapsible-content" ),
collapsibleSet = $el.closest( ":jqmData(role='collapsible-set')" ).addClass( "ui-collapsible-set" );
// Replace collapsibleHeading if it's a legend
if ( collapsibleHeading.is( "legend" ) ) {
collapsibleHeading = $( "<div role='heading'>"+ collapsibleHeading.html() +"</div>" ).insertBefore( collapsibleHeading );
collapsibleHeading.next().remove();
}
// If we are in a collapsible set
if ( collapsibleSet.length ) {
// Inherit the theme from collapsible-set
if ( !o.theme ) {
o.theme = collapsibleSet.jqmData("theme") || $.mobile.getInheritedTheme( collapsibleSet, "c" );
}
// Inherit the content-theme from collapsible-set
if ( !o.contentTheme ) {
o.contentTheme = collapsibleSet.jqmData( "content-theme" );
}
// Gets the preference icon position in the set
if ( !o.iconPos ) {
o.iconPos = collapsibleSet.jqmData( "iconpos" );
}
if( !o.mini ) {
o.mini = collapsibleSet.jqmData( "mini" );
}
}
collapsibleContent.addClass( ( o.contentTheme ) ? ( "ui-body-" + o.contentTheme ) : "");
collapsibleHeading
//drop heading in before content
.insertBefore( collapsibleContent )
//modify markup & attributes
.addClass( "ui-collapsible-heading" )
.append( "<span class='ui-collapsible-heading-status'></span>" )
.wrapInner( "<a href='#' class='ui-collapsible-heading-toggle'></a>" )
.find( "a" )
.first()
.buttonMarkup({
shadow: false,
corners: false,
iconpos: $el.jqmData( "iconpos" ) || o.iconPos || "left",
icon: "plus",
mini: o.mini,
theme: o.theme
})
.add( ".ui-btn-inner", $el )
.addClass( "ui-corner-top ui-corner-bottom" );
//events
collapsible
.bind( "expand collapse", function( event ) {
if ( !event.isDefaultPrevented() ) {
event.preventDefault();
var $this = $( this ),
isCollapse = ( event.type === "collapse" ),
contentTheme = o.contentTheme;
collapsibleHeading
.toggleClass( "ui-collapsible-heading-collapsed", isCollapse)
.find( ".ui-collapsible-heading-status" )
.text( isCollapse ? o.expandCueText : o.collapseCueText )
.end()
.find( ".ui-icon" )
.toggleClass( "ui-icon-minus", !isCollapse )
.toggleClass( "ui-icon-plus", isCollapse );
$this.toggleClass( "ui-collapsible-collapsed", isCollapse );
collapsibleContent.toggleClass( "ui-collapsible-content-collapsed", isCollapse ).attr( "aria-hidden", isCollapse );
if ( contentTheme && ( !collapsibleSet.length || collapsible.jqmData( "collapsible-last" ) ) ) {
collapsibleHeading
.find( "a" ).first().add( collapsibleHeading.find( ".ui-btn-inner" ) )
.toggleClass( "ui-corner-bottom", isCollapse );
collapsibleContent.toggleClass( "ui-corner-bottom", !isCollapse );
}
collapsibleContent.trigger( "updatelayout" );
}
})
.trigger( o.collapsed ? "collapse" : "expand" );
collapsibleHeading
.bind( "click", function( event ) {
var type = collapsibleHeading.is( ".ui-collapsible-heading-collapsed" ) ?
"expand" : "collapse";
collapsible.trigger( type );
event.preventDefault();
});
}
});
//auto self-init widgets
$( document ).bind( "pagecreate create", function( e ){
$.mobile.collapsible.prototype.enhanceWithin( e.target );
});
})( jQuery );
(function( $, undefined ) {
$.widget( "mobile.collapsibleset", $.mobile.widget, {
options: {
initSelector: ":jqmData(role='collapsible-set')"
},
_create: function() {
var $el = this.element.addClass( "ui-collapsible-set" ),
o = this.options;
// Inherit the theme from collapsible-set
if ( !o.theme ) {
o.theme = $.mobile.getInheritedTheme( $el, "c" );
}
// Inherit the content-theme from collapsible-set
if ( !o.contentTheme ) {
o.contentTheme = $el.jqmData( "content-theme" );
}
if ( !o.corners ) {
o.corners = $el.jqmData( "corners" ) === undefined ? true : false;
}
// Initialize the collapsible set if it's not already initialized
if ( !$el.jqmData( "collapsiblebound" ) ) {
$el
.jqmData( "collapsiblebound", true )
.bind( "expand collapse", function( event ) {
var isCollapse = ( event.type === "collapse" ),
collapsible = $( event.target ).closest( ".ui-collapsible" ),
widget = collapsible.data( "collapsible" ),
contentTheme = widget.options.contentTheme;
if ( contentTheme && collapsible.jqmData( "collapsible-last" ) ) {
collapsible.find( widget.options.heading ).first()
.find( "a" ).first()
.add( ".ui-btn-inner" )
.toggleClass( "ui-corner-bottom", isCollapse );
collapsible.find( ".ui-collapsible-content" ).toggleClass( "ui-corner-bottom", !isCollapse );
}
})
.bind( "expand", function( event ) {
$( event.target )
.closest( ".ui-collapsible" )
.siblings( ".ui-collapsible" )
.trigger( "collapse" );
});
}
},
_init: function() {
this.refresh();
},
refresh: function() {
var $el = this.element,
o = this.options,
collapsiblesInSet = $el.children( ":jqmData(role='collapsible')" );
$.mobile.collapsible.prototype.enhance( collapsiblesInSet.not( ".ui-collapsible" ) );
// clean up borders
collapsiblesInSet.each( function() {
$( this ).find( $.mobile.collapsible.prototype.options.heading )
.find( "a" ).first()
.add( ".ui-btn-inner" )
.removeClass( "ui-corner-top ui-corner-bottom" );
});
collapsiblesInSet.first()
.find( "a" )
.first()
.addClass( o.corners ? "ui-corner-top" : "" )
.find( ".ui-btn-inner" )
.addClass( "ui-corner-top" );
collapsiblesInSet.last()
.jqmData( "collapsible-last", true )
.find( "a" )
.first()
.addClass( o.corners ? "ui-corner-bottom" : "" )
.find( ".ui-btn-inner" )
.addClass( "ui-corner-bottom" );
}
});
//auto self-init widgets
$( document ).bind( "pagecreate create", function( e ){
$.mobile.collapsibleset.prototype.enhanceWithin( e.target );
});
})( jQuery );
(function( $, undefined ) {
$.widget( "mobile.navbar", $.mobile.widget, {
options: {
iconpos: "top",
grid: null,
initSelector: ":jqmData(role='navbar')"
},
_create: function(){
var $navbar = this.element,
$navbtns = $navbar.find( "a" ),
iconpos = $navbtns.filter( ":jqmData(icon)" ).length ?
this.options.iconpos : undefined;
$navbar.addClass( "ui-navbar" )
.attr( "role","navigation" )
.find( "ul" )
.jqmEnhanceable()
.grid({ grid: this.options.grid });
if ( !iconpos ) {
$navbar.addClass( "ui-navbar-noicons" );
}
$navbtns.buttonMarkup({
corners: false,
shadow: false,
inline: true,
iconpos: iconpos
});
$navbar.delegate( "a", "vclick", function( event ) {
if( !$(event.target).hasClass("ui-disabled") ) {
$navbtns.removeClass( $.mobile.activeBtnClass );
$( this ).addClass( $.mobile.activeBtnClass );
}
});
// Buttons in the navbar with ui-state-persist class should regain their active state before page show
$navbar.closest( ".ui-page" ).bind( "pagebeforeshow", function() {
$navbtns.filter( ".ui-state-persist" ).addClass( $.mobile.activeBtnClass );
});
}
});
//auto self-init widgets
$( document ).bind( "pagecreate create", function( e ){
$.mobile.navbar.prototype.enhanceWithin( e.target );
});
})( jQuery );
(function( $, undefined ) {
//Keeps track of the number of lists per page UID
//This allows support for multiple nested list in the same page
//https://github.com/jquery/jquery-mobile/issues/1617
var listCountPerPage = {};
$.widget( "mobile.listview", $.mobile.widget, {
options: {
theme: null,
countTheme: "c",
headerTheme: "b",
dividerTheme: "b",
splitIcon: "arrow-r",
splitTheme: "b",
mini: false,
inset: false,
initSelector: ":jqmData(role='listview')"
},
_create: function() {
var t = this,
listviewClasses = "";
listviewClasses += t.options.inset ? " ui-listview-inset ui-corner-all ui-shadow " : "";
listviewClasses += t.element.jqmData( "mini" ) || t.options.mini === true ? " ui-mini" : "";
// create listview markup
t.element.addClass(function( i, orig ) {
return orig + " ui-listview " + listviewClasses;
});
t.refresh( true );
},
_removeCorners: function( li, which ) {
var top = "ui-corner-top ui-corner-tr ui-corner-tl",
bot = "ui-corner-bottom ui-corner-br ui-corner-bl";
li = li.add( li.find( ".ui-btn-inner, .ui-li-link-alt, .ui-li-thumb" ) );
if ( which === "top" ) {
li.removeClass( top );
} else if ( which === "bottom" ) {
li.removeClass( bot );
} else {
li.removeClass( top + " " + bot );
}
},
_refreshCorners: function( create ) {
var $li,
$visibleli,
$topli,
$bottomli;
if ( this.options.inset ) {
$li = this.element.children( "li" );
// at create time the li are not visible yet so we need to rely on .ui-screen-hidden
$visibleli = create?$li.not( ".ui-screen-hidden" ):$li.filter( ":visible" );
this._removeCorners( $li );
// Select the first visible li element
$topli = $visibleli.first()
.addClass( "ui-corner-top" );
$topli.add( $topli.find( ".ui-btn-inner" )
.not( ".ui-li-link-alt span:first-child" ) )
.addClass( "ui-corner-top" )
.end()
.find( ".ui-li-link-alt, .ui-li-link-alt span:first-child" )
.addClass( "ui-corner-tr" )
.end()
.find( ".ui-li-thumb" )
.not(".ui-li-icon")
.addClass( "ui-corner-tl" );
// Select the last visible li element
$bottomli = $visibleli.last()
.addClass( "ui-corner-bottom" );
$bottomli.add( $bottomli.find( ".ui-btn-inner" ) )
.find( ".ui-li-link-alt" )
.addClass( "ui-corner-br" )
.end()
.find( ".ui-li-thumb" )
.not(".ui-li-icon")
.addClass( "ui-corner-bl" );
}
if ( !create ) {
this.element.trigger( "updatelayout" );
}
},
// This is a generic utility method for finding the first
// node with a given nodeName. It uses basic DOM traversal
// to be fast and is meant to be a substitute for simple
// $.fn.closest() and $.fn.children() calls on a single
// element. Note that callers must pass both the lowerCase
// and upperCase version of the nodeName they are looking for.
// The main reason for this is that this function will be
// called many times and we want to avoid having to lowercase
// the nodeName from the element every time to ensure we have
// a match. Note that this function lives here for now, but may
// be moved into $.mobile if other components need a similar method.
_findFirstElementByTagName: function( ele, nextProp, lcName, ucName )
{
var dict = {};
dict[ lcName ] = dict[ ucName ] = true;
while ( ele ) {
if ( dict[ ele.nodeName ] ) {
return ele;
}
ele = ele[ nextProp ];
}
return null;
},
_getChildrenByTagName: function( ele, lcName, ucName )
{
var results = [],
dict = {};
dict[ lcName ] = dict[ ucName ] = true;
ele = ele.firstChild;
while ( ele ) {
if ( dict[ ele.nodeName ] ) {
results.push( ele );
}
ele = ele.nextSibling;
}
return $( results );
},
_addThumbClasses: function( containers )
{
var i, img, len = containers.length;
for ( i = 0; i < len; i++ ) {
img = $( this._findFirstElementByTagName( containers[ i ].firstChild, "nextSibling", "img", "IMG" ) );
if ( img.length ) {
img.addClass( "ui-li-thumb" );
$( this._findFirstElementByTagName( img[ 0 ].parentNode, "parentNode", "li", "LI" ) ).addClass( img.is( ".ui-li-icon" ) ? "ui-li-has-icon" : "ui-li-has-thumb" );
}
}
},
refresh: function( create ) {
this.parentPage = this.element.closest( ".ui-page" );
this._createSubPages();
var o = this.options,
$list = this.element,
self = this,
dividertheme = $list.jqmData( "dividertheme" ) || o.dividerTheme,
listsplittheme = $list.jqmData( "splittheme" ),
listspliticon = $list.jqmData( "spliticon" ),
li = this._getChildrenByTagName( $list[ 0 ], "li", "LI" ),
counter = $.support.cssPseudoElement || !$.nodeName( $list[ 0 ], "ol" ) ? 0 : 1,
itemClassDict = {},
item, itemClass, itemTheme,
a, last, splittheme, countParent, icon, imgParents, img, linkIcon;
if ( counter ) {
$list.find( ".ui-li-dec" ).remove();
}
if ( !o.theme ) {
o.theme = $.mobile.getInheritedTheme( this.element, "c" );
}
for ( var pos = 0, numli = li.length; pos < numli; pos++ ) {
item = li.eq( pos );
itemClass = "ui-li";
// If we're creating the element, we update it regardless
if ( create || !item.hasClass( "ui-li" ) ) {
itemTheme = item.jqmData("theme") || o.theme;
a = this._getChildrenByTagName( item[ 0 ], "a", "A" );
if ( a.length ) {
icon = item.jqmData("icon");
item.buttonMarkup({
wrapperEls: "div",
shadow: false,
corners: false,
iconpos: "right",
icon: a.length > 1 || icon === false ? false : icon || "arrow-r",
theme: itemTheme
});
if ( ( icon != false ) && ( a.length == 1 ) ) {
item.addClass( "ui-li-has-arrow" );
}
a.first().removeClass( "ui-link" ).addClass( "ui-link-inherit" );
if ( a.length > 1 ) {
itemClass += " ui-li-has-alt";
last = a.last();
splittheme = listsplittheme || last.jqmData( "theme" ) || o.splitTheme;
linkIcon = last.jqmData("icon");
last.appendTo(item)
.attr( "title", last.getEncodedText() )
.addClass( "ui-li-link-alt" )
.empty()
.buttonMarkup({
shadow: false,
corners: false,
theme: itemTheme,
icon: false,
iconpos: false
})
.find( ".ui-btn-inner" )
.append(
$( document.createElement( "span" ) ).buttonMarkup({
shadow: true,
corners: true,
theme: splittheme,
iconpos: "notext",
// link icon overrides list item icon overrides ul element overrides options
icon: linkIcon || icon || listspliticon || o.splitIcon
})
);
}
} else if ( item.jqmData( "role" ) === "list-divider" ) {
itemClass += " ui-li-divider ui-bar-" + dividertheme;
item.attr( "role", "heading" );
//reset counter when a divider heading is encountered
if ( counter ) {
counter = 1;
}
} else {
itemClass += " ui-li-static ui-body-" + itemTheme;
}
}
if ( counter && itemClass.indexOf( "ui-li-divider" ) < 0 ) {
countParent = item.is( ".ui-li-static:first" ) ? item : item.find( ".ui-link-inherit" );
countParent.addClass( "ui-li-jsnumbering" )
.prepend( "<span class='ui-li-dec'>" + (counter++) + ". </span>" );
}
// Instead of setting item class directly on the list item and its
// btn-inner at this point in time, push the item into a dictionary
// that tells us what class to set on it so we can do this after this
// processing loop is finished.
if ( !itemClassDict[ itemClass ] ) {
itemClassDict[ itemClass ] = [];
}
itemClassDict[ itemClass ].push( item[ 0 ] );
}
// Set the appropriate listview item classes on each list item
// and their btn-inner elements. The main reason we didn't do this
// in the for-loop above is because we can eliminate per-item function overhead
// by calling addClass() and children() once or twice afterwards. This
// can give us a significant boost on platforms like WP7.5.
for ( itemClass in itemClassDict ) {
$( itemClassDict[ itemClass ] ).addClass( itemClass ).children( ".ui-btn-inner" ).addClass( itemClass );
}
$list.find( "h1, h2, h3, h4, h5, h6" ).addClass( "ui-li-heading" )
.end()
.find( "p, dl" ).addClass( "ui-li-desc" )
.end()
.find( ".ui-li-aside" ).each(function() {
var $this = $(this);
$this.prependTo( $this.parent() ); //shift aside to front for css float
})
.end()
.find( ".ui-li-count" ).each( function() {
$( this ).closest( "li" ).addClass( "ui-li-has-count" );
}).addClass( "ui-btn-up-" + ( $list.jqmData( "counttheme" ) || this.options.countTheme) + " ui-btn-corner-all" );
// The idea here is to look at the first image in the list item
// itself, and any .ui-link-inherit element it may contain, so we
// can place the appropriate classes on the image and list item.
// Note that we used to use something like:
//
// li.find(">img:eq(0), .ui-link-inherit>img:eq(0)").each( ... );
//
// But executing a find() like that on Windows Phone 7.5 took a
// really long time. Walking things manually with the code below
// allows the 400 listview item page to load in about 3 seconds as
// opposed to 30 seconds.
this._addThumbClasses( li );
this._addThumbClasses( $list.find( ".ui-link-inherit" ) );
this._refreshCorners( create );
},
//create a string for ID/subpage url creation
_idStringEscape: function( str ) {
return str.replace(/[^a-zA-Z0-9]/g, '-');
},
_createSubPages: function() {
var parentList = this.element,
parentPage = parentList.closest( ".ui-page" ),
parentUrl = parentPage.jqmData( "url" ),
parentId = parentUrl || parentPage[ 0 ][ $.expando ],
parentListId = parentList.attr( "id" ),
o = this.options,
dns = "data-" + $.mobile.ns,
self = this,
persistentFooterID = parentPage.find( ":jqmData(role='footer')" ).jqmData( "id" ),
hasSubPages;
if ( typeof listCountPerPage[ parentId ] === "undefined" ) {
listCountPerPage[ parentId ] = -1;
}
parentListId = parentListId || ++listCountPerPage[ parentId ];
$( parentList.find( "li>ul, li>ol" ).toArray().reverse() ).each(function( i ) {
var self = this,
list = $( this ),
listId = list.attr( "id" ) || parentListId + "-" + i,
parent = list.parent(),
nodeEls = $( list.prevAll().toArray().reverse() ),
nodeEls = nodeEls.length ? nodeEls : $( "<span>" + $.trim(parent.contents()[ 0 ].nodeValue) + "</span>" ),
title = nodeEls.first().getEncodedText(),//url limits to first 30 chars of text
id = ( parentUrl || "" ) + "&" + $.mobile.subPageUrlKey + "=" + listId,
theme = list.jqmData( "theme" ) || o.theme,
countTheme = list.jqmData( "counttheme" ) || parentList.jqmData( "counttheme" ) || o.countTheme,
newPage, anchor;
//define hasSubPages for use in later removal
hasSubPages = true;
newPage = list.detach()
.wrap( "<div " + dns + "role='page' " + dns + "url='" + id + "' " + dns + "theme='" + theme + "' " + dns + "count-theme='" + countTheme + "'><div " + dns + "role='content'></div></div>" )
.parent()
.before( "<div " + dns + "role='header' " + dns + "theme='" + o.headerTheme + "'><div class='ui-title'>" + title + "</div></div>" )
.after( persistentFooterID ? $( "<div " + dns + "role='footer' " + dns + "id='"+ persistentFooterID +"'>") : "" )
.parent()
.appendTo( $.mobile.pageContainer );
newPage.page();
anchor = parent.find('a:first');
if ( !anchor.length ) {
anchor = $( "<a/>" ).html( nodeEls || title ).prependTo( parent.empty() );
}
anchor.attr( "href", "#" + id );
}).listview();
// on pagehide, remove any nested pages along with the parent page, as long as they aren't active
// and aren't embedded
if( hasSubPages &&
parentPage.is( ":jqmData(external-page='true')" ) &&
parentPage.data("page").options.domCache === false ) {
var newRemove = function( e, ui ){
var nextPage = ui.nextPage, npURL;
if( ui.nextPage ){
npURL = nextPage.jqmData( "url" );
if( npURL.indexOf( parentUrl + "&" + $.mobile.subPageUrlKey ) !== 0 ){
self.childPages().remove();
parentPage.remove();
}
}
};
// unbind the original page remove and replace with our specialized version
parentPage
.unbind( "pagehide.remove" )
.bind( "pagehide.remove", newRemove);
}
},
// TODO sort out a better way to track sub pages of the listview this is brittle
childPages: function(){
var parentUrl = this.parentPage.jqmData( "url" );
return $( ":jqmData(url^='"+ parentUrl + "&" + $.mobile.subPageUrlKey +"')");
}
});
//auto self-init widgets
$( document ).bind( "pagecreate create", function( e ){
$.mobile.listview.prototype.enhanceWithin( e.target );
});
})( jQuery );
/*
* "checkboxradio" plugin
*/
(function( $, undefined ) {
$.widget( "mobile.checkboxradio", $.mobile.widget, {
options: {
theme: null,
initSelector: "input[type='checkbox'],input[type='radio']"
},
_create: function() {
var self = this,
input = this.element,
inheritAttr = function( input, dataAttr ) {
return input.jqmData( dataAttr ) || input.closest( "form,fieldset" ).jqmData( dataAttr )
},
// NOTE: Windows Phone could not find the label through a selector
// filter works though.
parentLabel = $( input ).closest( "label" ),
label = parentLabel.length ? parentLabel : $( input ).closest( "form,fieldset,:jqmData(role='page'),:jqmData(role='dialog')" ).find( "label" ).filter( "[for='" + input[0].id + "']" ),
inputtype = input[0].type,
mini = inheritAttr( input, "mini" ),
checkedState = inputtype + "-on",
uncheckedState = inputtype + "-off",
icon = input.parents( ":jqmData(type='horizontal')" ).length ? undefined : uncheckedState,
iconpos = inheritAttr( input, "iconpos" ),
activeBtn = icon ? "" : " " + $.mobile.activeBtnClass,
checkedClass = "ui-" + checkedState + activeBtn,
uncheckedClass = "ui-" + uncheckedState,
checkedicon = "ui-icon-" + checkedState,
uncheckedicon = "ui-icon-" + uncheckedState;
if ( inputtype !== "checkbox" && inputtype !== "radio" ) {
return;
}
// Expose for other methods
$.extend( this, {
label: label,
inputtype: inputtype,
checkedClass: checkedClass,
uncheckedClass: uncheckedClass,
checkedicon: checkedicon,
uncheckedicon: uncheckedicon
});
// If there's no selected theme check the data attr
if( !this.options.theme ) {
this.options.theme = $.mobile.getInheritedTheme( this.element, "c" );
}
label.buttonMarkup({
theme: this.options.theme,
icon: icon,
shadow: false,
mini: mini,
iconpos: iconpos
});
// Wrap the input + label in a div
var wrapper = document.createElement('div');
wrapper.className = 'ui-' + inputtype;
input.add( label ).wrapAll( wrapper );
label.bind({
vmouseover: function( event ) {
if ( $( this ).parent().is( ".ui-disabled" ) ) {
event.stopPropagation();
}
},
vclick: function( event ) {
if ( input.is( ":disabled" ) ) {
event.preventDefault();
return;
}
self._cacheVals();
input.prop( "checked", inputtype === "radio" && true || !input.prop( "checked" ) );
// trigger click handler's bound directly to the input as a substitute for
// how label clicks behave normally in the browsers
// TODO: it would be nice to let the browser's handle the clicks and pass them
// through to the associate input. we can swallow that click at the parent
// wrapper element level
input.triggerHandler( 'click' );
// Input set for common radio buttons will contain all the radio
// buttons, but will not for checkboxes. clearing the checked status
// of other radios ensures the active button state is applied properly
self._getInputSet().not( input ).prop( "checked", false );
self._updateAll();
return false;
}
});
input
.bind({
vmousedown: function() {
self._cacheVals();
},
vclick: function() {
var $this = $(this);
// Adds checked attribute to checked input when keyboard is used
if ( $this.is( ":checked" ) ) {
$this.prop( "checked", true);
self._getInputSet().not($this).prop( "checked", false );
} else {
$this.prop( "checked", false );
}
self._updateAll();
},
focus: function() {
label.addClass( $.mobile.focusClass );
},
blur: function() {
label.removeClass( $.mobile.focusClass );
}
});
this.refresh();
},
_cacheVals: function() {
this._getInputSet().each(function() {
$(this).jqmData( "cacheVal", this.checked );
});
},
//returns either a set of radios with the same name attribute, or a single checkbox
_getInputSet: function(){
if(this.inputtype === "checkbox") {
return this.element;
}
return this.element.closest( "form,fieldset,:jqmData(role='page')" )
.find( "input[name='"+ this.element[0].name +"'][type='"+ this.inputtype +"']" );
},
_updateAll: function() {
var self = this;
this._getInputSet().each(function() {
var $this = $(this);
if ( this.checked || self.inputtype === "checkbox" ) {
$this.trigger( "change" );
}
})
.checkboxradio( "refresh" );
},
refresh: function() {
var input = this.element[0],
label = this.label,
icon = label.find( ".ui-icon" );
if ( input.checked ) {
label.addClass( this.checkedClass ).removeClass( this.uncheckedClass );
icon.addClass( this.checkedicon ).removeClass( this.uncheckedicon );
} else {
label.removeClass( this.checkedClass ).addClass( this.uncheckedClass );
icon.removeClass( this.checkedicon ).addClass( this.uncheckedicon );
}
if ( input.disabled ) {
this.disable();
} else {
this.enable();
}
},
disable: function() {
this.element.prop( "disabled", true ).parent().addClass( "ui-disabled" );
},
enable: function() {
this.element.prop( "disabled", false ).parent().removeClass( "ui-disabled" );
}
});
//auto self-init widgets
$( document ).bind( "pagecreate create", function( e ){
$.mobile.checkboxradio.prototype.enhanceWithin( e.target, true );
});
})( jQuery );
(function( $, undefined ) {
$.widget( "mobile.button", $.mobile.widget, {
options: {
theme: null,
icon: null,
iconpos: null,
inline: false,
corners: true,
shadow: true,
iconshadow: true,
initSelector: "button, [type='button'], [type='submit'], [type='reset'], [type='image']",
mini: false
},
_create: function() {
var $el = this.element,
$button,
o = this.options,
type,
name,
classes = "",
$buttonPlaceholder;
// if this is a link, check if it's been enhanced and, if not, use the right function
if( $el[ 0 ].tagName === "A" ) {
!$el.hasClass( "ui-btn" ) && $el.buttonMarkup();
return;
}
// get the inherited theme
// TODO centralize for all widgets
if ( !this.options.theme ) {
this.options.theme = $.mobile.getInheritedTheme( this.element, "c" );
}
// TODO: Post 1.1--once we have time to test thoroughly--any classes manually applied to the original element should be carried over to the enhanced element, with an `-enhanced` suffix. See https://github.com/jquery/jquery-mobile/issues/3577
/* if( $el[0].className.length ) {
classes = $el[0].className;
} */
if( !!~$el[0].className.indexOf( "ui-btn-left" ) ) {
classes = "ui-btn-left";
}
if( !!~$el[0].className.indexOf( "ui-btn-right" ) ) {
classes = "ui-btn-right";
}
// Add ARIA role
this.button = $( "<div></div>" )
.text( $el.text() || $el.val() )
.insertBefore( $el )
.buttonMarkup({
theme: o.theme,
icon: o.icon,
iconpos: o.iconpos,
inline: o.inline,
corners: o.corners,
shadow: o.shadow,
iconshadow: o.iconshadow,
mini: o.mini
})
.addClass( classes )
.append( $el.addClass( "ui-btn-hidden" ) );
$button = this.button;
type = $el.attr( "type" );
name = $el.attr( "name" );
// Add hidden input during submit if input type="submit" has a name.
if ( type !== "button" && type !== "reset" && name ) {
$el.bind( "vclick", function() {
// Add hidden input if it doesn’t already exist.
if( $buttonPlaceholder === undefined ) {
$buttonPlaceholder = $( "<input>", {
type: "hidden",
name: $el.attr( "name" ),
value: $el.attr( "value" )
}).insertBefore( $el );
// Bind to doc to remove after submit handling
$( document ).one("submit", function(){
$buttonPlaceholder.remove();
// reset the local var so that the hidden input
// will be re-added on subsequent clicks
$buttonPlaceholder = undefined;
});
}
});
}
$el.bind({
focus: function() {
$button.addClass( $.mobile.focusClass );
},
blur: function() {
$button.removeClass( $.mobile.focusClass );
}
});
this.refresh();
},
enable: function() {
this.element.attr( "disabled", false );
this.button.removeClass( "ui-disabled" ).attr( "aria-disabled", false );
return this._setOption( "disabled", false );
},
disable: function() {
this.element.attr( "disabled", true );
this.button.addClass( "ui-disabled" ).attr( "aria-disabled", true );
return this._setOption( "disabled", true );
},
refresh: function() {
var $el = this.element;
if ( $el.prop("disabled") ) {
this.disable();
} else {
this.enable();
}
// Grab the button's text element from its implementation-independent data item
$( this.button.data( 'buttonElements' ).text ).text( $el.text() || $el.val() );
}
});
//auto self-init widgets
$( document ).bind( "pagecreate create", function( e ){
$.mobile.button.prototype.enhanceWithin( e.target, true );
});
})( jQuery );
(function( $, undefined ) {
$.fn.controlgroup = function( options ) {
function flipClasses( els, flCorners ) {
els.removeClass( "ui-btn-corner-all ui-shadow" )
.eq( 0 ).addClass( flCorners[ 0 ] )
.end()
.last().addClass( flCorners[ 1 ] ).addClass( "ui-controlgroup-last" );
}
return this.each(function() {
var $el = $( this ),
o = $.extend({
direction: $el.jqmData( "type" ) || "vertical",
shadow: false,
excludeInvisible: true,
mini: $el.jqmData( "mini" )
}, options ),
groupheading = $el.children( "legend" ),
flCorners = o.direction == "horizontal" ? [ "ui-corner-left", "ui-corner-right" ] : [ "ui-corner-top", "ui-corner-bottom" ],
type = $el.find( "input" ).first().attr( "type" );
// Replace legend with more stylable replacement div
if ( groupheading.length ) {
$el.wrapInner( "<div class='ui-controlgroup-controls'></div>" );
$( "<div role='heading' class='ui-controlgroup-label'>" + groupheading.html() + "</div>" ).insertBefore( $el.children(0) );
groupheading.remove();
}
$el.addClass( "ui-corner-all ui-controlgroup ui-controlgroup-" + o.direction );
flipClasses( $el.find( ".ui-btn" + ( o.excludeInvisible ? ":visible" : "" ) ).not('.ui-slider-handle'), flCorners );
flipClasses( $el.find( ".ui-btn-inner" ), flCorners );
if ( o.shadow ) {
$el.addClass( "ui-shadow" );
}
if ( o.mini ) {
$el.addClass( "ui-mini" );
}
});
};
// The pagecreate handler for controlgroup is in jquery.mobile.init because of the soft-dependency on the wrapped widgets
})(jQuery);
(function( $, undefined ) {
$( document ).bind( "pagecreate create", function( e ){
//links within content areas, tests included with page
$( e.target )
.find( "a" )
.jqmEnhanceable()
.not( ".ui-btn, .ui-link-inherit, :jqmData(role='none'), :jqmData(role='nojs')" )
.addClass( "ui-link" );
});
})( jQuery );
( function( $ ) {
var meta = $( "meta[name=viewport]" ),
initialContent = meta.attr( "content" ),
disabledZoom = initialContent + ",maximum-scale=1, user-scalable=no",
enabledZoom = initialContent + ",maximum-scale=10, user-scalable=yes",
disabledInitially = /(user-scalable[\s]*=[\s]*no)|(maximum-scale[\s]*=[\s]*1)[$,\s]/.test( initialContent );
$.mobile.zoom = $.extend( {}, {
enabled: !disabledInitially,
locked: false,
disable: function( lock ) {
if( !disabledInitially && !$.mobile.zoom.locked ){
meta.attr( "content", disabledZoom );
$.mobile.zoom.enabled = false;
$.mobile.zoom.locked = lock || false;
}
},
enable: function( unlock ) {
if( !disabledInitially && ( !$.mobile.zoom.locked || unlock === true ) ){
meta.attr( "content", enabledZoom );
$.mobile.zoom.enabled = true;
$.mobile.zoom.locked = false;
}
},
restore: function() {
if( !disabledInitially ){
meta.attr( "content", initialContent );
$.mobile.zoom.enabled = true;
}
}
});
}( jQuery ));
(function( $, undefined ) {
$.widget( "mobile.textinput", $.mobile.widget, {
options: {
theme: null,
// This option defaults to true on iOS devices.
preventFocusZoom: /iPhone|iPad|iPod/.test( navigator.platform ) && navigator.userAgent.indexOf( "AppleWebKit" ) > -1,
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])",
clearSearchButtonText: "clear text"
},
_create: function() {
var input = this.element,
o = this.options,
theme = o.theme || $.mobile.getInheritedTheme( this.element, "c" ),
themeclass = " ui-body-" + theme,
mini = input.jqmData("mini") == true,
miniclass = mini ? " ui-mini" : "",
focusedEl, clearbtn;
$( "label[for='" + input.attr( "id" ) + "']" ).addClass( "ui-input-text" );
focusedEl = input.addClass("ui-input-text ui-body-"+ theme );
// XXX: Temporary workaround for issue 785 (Apple bug 8910589).
// Turn off autocorrect and autocomplete on non-iOS 5 devices
// since the popup they use can't be dismissed by the user. Note
// that we test for the presence of the feature by looking for
// the autocorrect property on the input element. We currently
// have no test for iOS 5 or newer so we're temporarily using
// the touchOverflow support flag for jQM 1.0. Yes, I feel dirty. - jblas
if ( typeof input[0].autocorrect !== "undefined" && !$.support.touchOverflow ) {
// Set the attribute instead of the property just in case there
// is code that attempts to make modifications via HTML.
input[0].setAttribute( "autocorrect", "off" );
input[0].setAttribute( "autocomplete", "off" );
}
//"search" input widget
if ( input.is( "[type='search'],:jqmData(type='search')" ) ) {
focusedEl = input.wrap( "<div class='ui-input-search ui-shadow-inset ui-btn-corner-all ui-btn-shadow ui-icon-searchfield" + themeclass + miniclass + "'></div>" ).parent();
clearbtn = $( "<a href='#' class='ui-input-clear' title='" + o.clearSearchButtonText + "'>" + o.clearSearchButtonText + "</a>" )
.bind('click', function( event ) {
input
.val( "" )
.focus()
.trigger( "change" );
clearbtn.addClass( "ui-input-clear-hidden" );
event.preventDefault();
})
.appendTo( focusedEl )
.buttonMarkup({
icon: "delete",
iconpos: "notext",
corners: true,
shadow: true,
mini: mini
});
function toggleClear() {
setTimeout(function() {
clearbtn.toggleClass( "ui-input-clear-hidden", !input.val() );
}, 0);
}
toggleClear();
input.bind('paste cut keyup focus change blur', toggleClear);
} else {
input.addClass( "ui-corner-all ui-shadow-inset" + themeclass + miniclass );
}
input.focus(function() {
focusedEl.addClass( $.mobile.focusClass );
})
.blur(function(){
focusedEl.removeClass( $.mobile.focusClass );
})
// In many situations, iOS will zoom into the select upon tap, this prevents that from happening
.bind( "focus", function() {
if( o.preventFocusZoom ){
$.mobile.zoom.disable( true );
}
})
.bind( "blur", function() {
if( o.preventFocusZoom ){
$.mobile.zoom.enable( true );
}
});
// Autogrow
if ( input.is( "textarea" ) ) {
var extraLineHeight = 15,
keyupTimeoutBuffer = 100,
keyup = function() {
var scrollHeight = input[ 0 ].scrollHeight,
clientHeight = input[ 0 ].clientHeight;
if ( clientHeight < scrollHeight ) {
input.height(scrollHeight + extraLineHeight);
}
},
keyupTimeout;
input.keyup(function() {
clearTimeout( keyupTimeout );
keyupTimeout = setTimeout( keyup, keyupTimeoutBuffer );
});
// binding to pagechange here ensures that for pages loaded via
// ajax the height is recalculated without user input
$( document ).one( "pagechange", keyup );
// Issue 509: the browser is not providing scrollHeight properly until the styles load
if ( $.trim( input.val() ) ) {
// bind to the window load to make sure the height is calculated based on BOTH
// the DOM and CSS
$( window ).load( keyup );
}
}
},
disable: function(){
( this.element.attr( "disabled", true ).is( "[type='search'],:jqmData(type='search')" ) ?
this.element.parent() : this.element ).addClass( "ui-disabled" );
},
enable: function(){
( this.element.attr( "disabled", false).is( "[type='search'],:jqmData(type='search')" ) ?
this.element.parent() : this.element ).removeClass( "ui-disabled" );
}
});
//auto self-init widgets
$( document ).bind( "pagecreate create", function( e ){
$.mobile.textinput.prototype.enhanceWithin( e.target, true );
});
})( jQuery );
(function( $, undefined ) {
$.mobile.listview.prototype.options.filter = false;
$.mobile.listview.prototype.options.filterPlaceholder = "Filter items...";
$.mobile.listview.prototype.options.filterTheme = "c";
$.mobile.listview.prototype.options.filterCallback = function( text, searchValue ){
return text.toLowerCase().indexOf( searchValue ) === -1;
};
$( document ).delegate( ":jqmData(role='listview')", "listviewcreate", function() {
var list = $( this ),
listview = list.data( "listview" );
if ( !listview.options.filter ) {
return;
}
var wrapper = $( "<form>", {
"class": "ui-listview-filter ui-bar-" + listview.options.filterTheme,
"role": "search"
}),
search = $( "<input>", {
placeholder: listview.options.filterPlaceholder
})
.attr( "data-" + $.mobile.ns + "type", "search" )
.jqmData( "lastval", "" )
.bind( "keyup change", function() {
var $this = $(this),
val = this.value.toLowerCase(),
listItems = null,
lastval = $this.jqmData( "lastval" ) + "",
childItems = false,
itemtext = "",
item;
// Change val as lastval for next execution
$this.jqmData( "lastval" , val );
if ( val.length < lastval.length || val.indexOf(lastval) !== 0 ) {
// Removed chars or pasted something totally different, check all items
listItems = list.children();
} else {
// Only chars added, not removed, only use visible subset
listItems = list.children( ":not(.ui-screen-hidden)" );
}
if ( val ) {
// This handles hiding regular rows without the text we search for
// and any list dividers without regular rows shown under it
for ( var i = listItems.length - 1; i >= 0; i-- ) {
item = $( listItems[ i ] );
itemtext = item.jqmData( "filtertext" ) || item.text();
if ( item.is( "li:jqmData(role=list-divider)" ) ) {
item.toggleClass( "ui-filter-hidequeue" , !childItems );
// New bucket!
childItems = false;
} else if ( listview.options.filterCallback( itemtext, val ) ) {
//mark to be hidden
item.toggleClass( "ui-filter-hidequeue" , true );
} else {
// There's a shown item in the bucket
childItems = true;
}
}
// Show items, not marked to be hidden
listItems
.filter( ":not(.ui-filter-hidequeue)" )
.toggleClass( "ui-screen-hidden", false );
// Hide items, marked to be hidden
listItems
.filter( ".ui-filter-hidequeue" )
.toggleClass( "ui-screen-hidden", true )
.toggleClass( "ui-filter-hidequeue", false );
} else {
//filtervalue is empty => show all
listItems.toggleClass( "ui-screen-hidden", false );
}
listview._refreshCorners();
})
.appendTo( wrapper )
.textinput();
if ( listview.options.inset ) {
wrapper.addClass( "ui-listview-filter-inset" );
}
wrapper.bind( "submit", function() {
return false;
})
.insertBefore( list );
});
})( jQuery );
( function( $, undefined ) {
$.widget( "mobile.slider", $.mobile.widget, {
options: {
theme: null,
trackTheme: null,
disabled: false,
initSelector: "input[type='range'], :jqmData(type='range'), :jqmData(role='slider')",
mini: false
},
_create: function() {
// TODO: Each of these should have comments explain what they're for
var self = this,
control = this.element,
parentTheme = $.mobile.getInheritedTheme( control, "c" ),
theme = this.options.theme || parentTheme,
trackTheme = this.options.trackTheme || parentTheme,
cType = control[ 0 ].nodeName.toLowerCase(),
selectClass = ( cType == "select" ) ? "ui-slider-switch" : "",
controlID = control.attr( "id" ),
labelID = controlID + "-label",
label = $( "[for='"+ controlID +"']" ).attr( "id", labelID ),
val = function() {
return cType == "input" ? parseFloat( control.val() ) : control[0].selectedIndex;
},
min = cType == "input" ? parseFloat( control.attr( "min" ) ) : 0,
max = cType == "input" ? parseFloat( control.attr( "max" ) ) : control.find( "option" ).length-1,
step = window.parseFloat( control.attr( "step" ) || 1 ),
inlineClass = ( this.options.inline || control.jqmData("inline") == true ) ? " ui-slider-inline" : "",
miniClass = ( this.options.mini || control.jqmData("mini") ) ? " ui-slider-mini" : "",
domHandle = document.createElement('a'),
handle = $( domHandle ),
domSlider = document.createElement('div'),
slider = $( domSlider ),
valuebg = control.jqmData("highlight") && cType != "select" ? (function() {
var bg = document.createElement('div');
bg.className = 'ui-slider-bg ui-btn-active ui-btn-corner-all';
return $( bg ).prependTo( slider );
})() : false,
options;
domHandle.setAttribute( 'href', "#" );
domSlider.setAttribute('role','application');
domSlider.className = ['ui-slider ',selectClass," ui-btn-down-",trackTheme,' ui-btn-corner-all', inlineClass, miniClass].join("");
domHandle.className = 'ui-slider-handle';
domSlider.appendChild(domHandle);
handle.buttonMarkup({ corners: true, theme: theme, shadow: true })
.attr({
"role": "slider",
"aria-valuemin": min,
"aria-valuemax": max,
"aria-valuenow": val(),
"aria-valuetext": val(),
"title": val(),
"aria-labelledby": labelID
});
$.extend( this, {
slider: slider,
handle: handle,
valuebg: valuebg,
dragging: false,
beforeStart: null,
userModified: false,
mouseMoved: false
});
if ( cType == "select" ) {
var wrapper = document.createElement('div');
wrapper.className = 'ui-slider-inneroffset';
for(var j = 0,length = domSlider.childNodes.length;j < length;j++){
wrapper.appendChild(domSlider.childNodes[j]);
}
domSlider.appendChild(wrapper);
// slider.wrapInner( "<div class='ui-slider-inneroffset'></div>" );
// make the handle move with a smooth transition
handle.addClass( "ui-slider-handle-snapping" );
options = control.find( "option" );
for(var i = 0, optionsCount = options.length; i < optionsCount; i++){
var side = !i ? "b":"a",
sliderTheme = !i ? " ui-btn-down-" + trackTheme :( " " + $.mobile.activeBtnClass ),
sliderLabel = document.createElement('div'),
sliderImg = document.createElement('span');
sliderImg.className = ['ui-slider-label ui-slider-label-',side,sliderTheme," ui-btn-corner-all"].join("");
sliderImg.setAttribute('role','img');
sliderImg.appendChild(document.createTextNode(options[i].innerHTML));
$(sliderImg).prependTo( slider );
}
self._labels = $( ".ui-slider-label", slider );
}
label.addClass( "ui-slider" );
// monitor the input for updated values
control.addClass( cType === "input" ? "ui-slider-input" : "ui-slider-switch" )
.change( function() {
// if the user dragged the handle, the "change" event was triggered from inside refresh(); don't call refresh() again
if (!self.mouseMoved) {
self.refresh( val(), true );
}
})
.keyup( function() { // necessary?
self.refresh( val(), true, true );
})
.blur( function() {
self.refresh( val(), true );
});
// prevent screen drag when slider activated
$( document ).bind( "vmousemove", function( event ) {
if ( self.dragging ) {
// self.mouseMoved must be updated before refresh() because it will be used in the control "change" event
self.mouseMoved = true;
if ( cType === "select" ) {
// make the handle move in sync with the mouse
handle.removeClass( "ui-slider-handle-snapping" );
}
self.refresh( event );
// only after refresh() you can calculate self.userModified
self.userModified = self.beforeStart !== control[0].selectedIndex;
return false;
}
});
slider.bind( "vmousedown", function( event ) {
self.dragging = true;
self.userModified = false;
self.mouseMoved = false;
if ( cType === "select" ) {
self.beforeStart = control[0].selectedIndex;
}
self.refresh( event );
return false;
})
.bind( "vclick", false );
slider.add( document )
.bind( "vmouseup", function() {
if ( self.dragging ) {
self.dragging = false;
if ( cType === "select") {
// make the handle move with a smooth transition
handle.addClass( "ui-slider-handle-snapping" );
if ( self.mouseMoved ) {
// this is a drag, change the value only if user dragged enough
if ( self.userModified ) {
self.refresh( self.beforeStart == 0 ? 1 : 0 );
}
else {
self.refresh( self.beforeStart );
}
}
else {
// this is just a click, change the value
self.refresh( self.beforeStart == 0 ? 1 : 0 );
}
}
self.mouseMoved = false;
return false;
}
});
slider.insertAfter( control );
// Only add focus class to toggle switch, sliders get it automatically from ui-btn
if( cType == 'select' ) {
this.handle.bind({
focus: function() {
slider.addClass( $.mobile.focusClass );
},
blur: function() {
slider.removeClass( $.mobile.focusClass );
}
});
}
this.handle.bind({
// NOTE force focus on handle
vmousedown: function() {
$( this ).focus();
},
vclick: false,
keydown: function( event ) {
var index = val();
if ( self.options.disabled ) {
return;
}
// In all cases prevent the default and mark the handle as active
switch ( event.keyCode ) {
case $.mobile.keyCode.HOME:
case $.mobile.keyCode.END:
case $.mobile.keyCode.PAGE_UP:
case $.mobile.keyCode.PAGE_DOWN:
case $.mobile.keyCode.UP:
case $.mobile.keyCode.RIGHT:
case $.mobile.keyCode.DOWN:
case $.mobile.keyCode.LEFT:
event.preventDefault();
if ( !self._keySliding ) {
self._keySliding = true;
$( this ).addClass( "ui-state-active" );
}
break;
}
// move the slider according to the keypress
switch ( event.keyCode ) {
case $.mobile.keyCode.HOME:
self.refresh( min );
break;
case $.mobile.keyCode.END:
self.refresh( max );
break;
case $.mobile.keyCode.PAGE_UP:
case $.mobile.keyCode.UP:
case $.mobile.keyCode.RIGHT:
self.refresh( index + step );
break;
case $.mobile.keyCode.PAGE_DOWN:
case $.mobile.keyCode.DOWN:
case $.mobile.keyCode.LEFT:
self.refresh( index - step );
break;
}
}, // remove active mark
keyup: function( event ) {
if ( self._keySliding ) {
self._keySliding = false;
$( this ).removeClass( "ui-state-active" );
}
}
});
this.refresh(undefined, undefined, true);
},
refresh: function( val, isfromControl, preventInputUpdate ) {
if ( this.options.disabled || this.element.attr('disabled')) {
this.disable();
}
var control = this.element, percent,
cType = control[0].nodeName.toLowerCase(),
min = cType === "input" ? parseFloat( control.attr( "min" ) ) : 0,
max = cType === "input" ? parseFloat( control.attr( "max" ) ) : control.find( "option" ).length - 1,
step = (cType === "input" && parseFloat( control.attr( "step" ) ) > 0) ? parseFloat(control.attr("step")) : 1;
if ( typeof val === "object" ) {
var data = val,
// a slight tolerance helped get to the ends of the slider
tol = 8;
if ( !this.dragging ||
data.pageX < this.slider.offset().left - tol ||
data.pageX > this.slider.offset().left + this.slider.width() + tol ) {
return;
}
percent = Math.round( ( ( data.pageX - this.slider.offset().left ) / this.slider.width() ) * 100 );
} else {
if ( val == null ) {
val = cType === "input" ? parseFloat( control.val() || 0 ) : control[0].selectedIndex;
}
percent = ( parseFloat( val ) - min ) / ( max - min ) * 100;
}
if ( isNaN( percent ) ) {
return;
}
if ( percent < 0 ) {
percent = 0;
}
if ( percent > 100 ) {
percent = 100;
}
var newval = ( percent / 100 ) * ( max - min ) + min;
//from jQuery UI slider, the following source will round to the nearest step
var valModStep = ( newval - min ) % step;
var alignValue = newval - valModStep;
if ( Math.abs( valModStep ) * 2 >= step ) {
alignValue += ( valModStep > 0 ) ? step : ( -step );
}
// Since JavaScript has problems with large floats, round
// the final value to 5 digits after the decimal point (see jQueryUI: #4124)
newval = parseFloat( alignValue.toFixed(5) );
if ( newval < min ) {
newval = min;
}
if ( newval > max ) {
newval = max;
}
this.handle.css( "left", percent + "%" );
this.handle.attr( {
"aria-valuenow": cType === "input" ? newval : control.find( "option" ).eq( newval ).attr( "value" ),
"aria-valuetext": cType === "input" ? newval : control.find( "option" ).eq( newval ).getEncodedText(),
title: cType === "input" ? newval : control.find( "option" ).eq( newval ).getEncodedText()
});
this.valuebg && this.valuebg.css( "width", percent + "%" );
// drag the label widths
if ( this._labels ) {
var handlePercent = this.handle.width() / this.slider.width() * 100,
aPercent = percent && handlePercent + ( 100 - handlePercent ) * percent / 100,
bPercent = percent === 100 ? 0 : Math.min( handlePercent + 100 - aPercent, 100 );
this._labels.each(function(){
var ab = $(this).is( ".ui-slider-label-a" );
$( this ).width( ( ab ? aPercent : bPercent ) + "%" );
});
}
if ( !preventInputUpdate ) {
var valueChanged = false;
// update control"s value
if ( cType === "input" ) {
valueChanged = control.val() !== newval;
control.val( newval );
} else {
valueChanged = control[ 0 ].selectedIndex !== newval;
control[ 0 ].selectedIndex = newval;
}
if ( !isfromControl && valueChanged ) {
control.trigger( "change" );
}
}
},
enable: function() {
this.element.attr( "disabled", false );
this.slider.removeClass( "ui-disabled" ).attr( "aria-disabled", false );
return this._setOption( "disabled", false );
},
disable: function() {
this.element.attr( "disabled", true );
this.slider.addClass( "ui-disabled" ).attr( "aria-disabled", true );
return this._setOption( "disabled", true );
}
});
//auto self-init widgets
$( document ).bind( "pagecreate create", function( e ){
$.mobile.slider.prototype.enhanceWithin( e.target, true );
});
})( jQuery );
(function( $, undefined ) {
$.widget( "mobile.selectmenu", $.mobile.widget, {
options: {
theme: null,
disabled: false,
icon: "arrow-d",
iconpos: "right",
inline: false,
corners: true,
shadow: true,
iconshadow: true,
overlayTheme: "a",
hidePlaceholderMenuItems: true,
closeText: "Close",
nativeMenu: true,
// This option defaults to true on iOS devices.
preventFocusZoom: /iPhone|iPad|iPod/.test( navigator.platform ) && navigator.userAgent.indexOf( "AppleWebKit" ) > -1,
initSelector: "select:not(:jqmData(role='slider'))",
mini: false
},
_button: function(){
return $( "<div/>" );
},
_setDisabled: function( value ) {
this.element.attr( "disabled", value );
this.button.attr( "aria-disabled", value );
return this._setOption( "disabled", value );
},
_focusButton : function() {
var self = this;
setTimeout( function() {
self.button.focus();
}, 40);
},
_selectOptions: function() {
return this.select.find( "option" );
},
// setup items that are generally necessary for select menu extension
_preExtension: function(){
var classes = "";
// TODO: Post 1.1--once we have time to test thoroughly--any classes manually applied to the original element should be carried over to the enhanced element, with an `-enhanced` suffix. See https://github.com/jquery/jquery-mobile/issues/3577
/* if( $el[0].className.length ) {
classes = $el[0].className;
} */
if( !!~this.element[0].className.indexOf( "ui-btn-left" ) ) {
classes = " ui-btn-left";
}
if( !!~this.element[0].className.indexOf( "ui-btn-right" ) ) {
classes = " ui-btn-right";
}
this.select = this.element.wrap( "<div class='ui-select" + classes + "'>" );
this.selectID = this.select.attr( "id" );
this.label = $( "label[for='"+ this.selectID +"']" ).addClass( "ui-select" );
this.isMultiple = this.select[ 0 ].multiple;
if ( !this.options.theme ) {
this.options.theme = $.mobile.getInheritedTheme( this.select, "c" );
}
},
_create: function() {
this._preExtension();
// Allows for extension of the native select for custom selects and other plugins
// see select.custom for example extension
// TODO explore plugin registration
this._trigger( "beforeCreate" );
this.button = this._button();
var self = this,
options = this.options,
// IE throws an exception at options.item() function when
// there is no selected item
// select first in this case
selectedIndex = this.select[ 0 ].selectedIndex == -1 ? 0 : this.select[ 0 ].selectedIndex,
// TODO values buttonId and menuId are undefined here
button = this.button
.text( $( this.select[ 0 ].options.item( selectedIndex ) ).text() )
.insertBefore( this.select )
.buttonMarkup( {
theme: options.theme,
icon: options.icon,
iconpos: options.iconpos,
inline: options.inline,
corners: options.corners,
shadow: options.shadow,
iconshadow: options.iconshadow,
mini: options.mini
});
// Opera does not properly support opacity on select elements
// In Mini, it hides the element, but not its text
// On the desktop,it seems to do the opposite
// for these reasons, using the nativeMenu option results in a full native select in Opera
if ( options.nativeMenu && window.opera && window.opera.version ) {
this.select.addClass( "ui-select-nativeonly" );
}
// Add counter for multi selects
if ( this.isMultiple ) {
this.buttonCount = $( "<span>" )
.addClass( "ui-li-count ui-btn-up-c ui-btn-corner-all" )
.hide()
.appendTo( button.addClass('ui-li-has-count') );
}
// Disable if specified
if ( options.disabled || this.element.attr('disabled')) {
this.disable();
}
// Events on native select
this.select.change( function() {
self.refresh();
});
this.build();
},
build: function() {
var self = this;
this.select
.appendTo( self.button )
.bind( "vmousedown", function() {
// Add active class to button
self.button.addClass( $.mobile.activeBtnClass );
})
.bind( "focus", function() {
self.button.addClass( $.mobile.focusClass );
})
.bind( "blur", function() {
self.button.removeClass( $.mobile.focusClass );
})
.bind( "focus vmouseover", function() {
self.button.trigger( "vmouseover" );
})
.bind( "vmousemove", function() {
// Remove active class on scroll/touchmove
self.button.removeClass( $.mobile.activeBtnClass );
})
.bind( "change blur vmouseout", function() {
self.button.trigger( "vmouseout" )
.removeClass( $.mobile.activeBtnClass );
})
.bind( "change blur", function() {
self.button.removeClass( "ui-btn-down-" + self.options.theme );
});
// In many situations, iOS will zoom into the select upon tap, this prevents that from happening
self.button.bind( "vmousedown", function() {
if( self.options.preventFocusZoom ){
$.mobile.zoom.disable( true );
}
})
.bind( "mouseup", function() {
if( self.options.preventFocusZoom ){
$.mobile.zoom.enable( true );
}
});
},
selected: function() {
return this._selectOptions().filter( ":selected" );
},
selectedIndices: function() {
var self = this;
return this.selected().map( function() {
return self._selectOptions().index( this );
}).get();
},
setButtonText: function() {
var self = this, selected = this.selected();
this.button.find( ".ui-btn-text" ).text( function() {
if ( !self.isMultiple ) {
return selected.text();
}
return selected.length ? selected.map( function() {
return $( this ).text();
}).get().join( ", " ) : self.placeholder;
});
},
setButtonCount: function() {
var selected = this.selected();
// multiple count inside button
if ( this.isMultiple ) {
this.buttonCount[ selected.length > 1 ? "show" : "hide" ]().text( selected.length );
}
},
refresh: function() {
this.setButtonText();
this.setButtonCount();
},
// open and close preserved in native selects
// to simplify users code when looping over selects
open: $.noop,
close: $.noop,
disable: function() {
this._setDisabled( true );
this.button.addClass( "ui-disabled" );
},
enable: function() {
this._setDisabled( false );
this.button.removeClass( "ui-disabled" );
}
});
//auto self-init widgets
$( document ).bind( "pagecreate create", function( e ){
$.mobile.selectmenu.prototype.enhanceWithin( e.target, true );
});
})( jQuery );
/*
* custom "selectmenu" plugin
*/
(function( $, undefined ) {
var extendSelect = function( widget ){
var select = widget.select,
selectID = widget.selectID,
label = widget.label,
thisPage = widget.select.closest( ".ui-page" ),
screen = $( "<div>", {"class": "ui-selectmenu-screen ui-screen-hidden"} ).appendTo( thisPage ),
selectOptions = widget._selectOptions(),
isMultiple = widget.isMultiple = widget.select[ 0 ].multiple,
buttonId = selectID + "-button",
menuId = selectID + "-menu",
menuPage = $( "<div data-" + $.mobile.ns + "role='dialog' data-" +$.mobile.ns + "theme='"+ widget.options.theme +"' data-" +$.mobile.ns + "overlay-theme='"+ widget.options.overlayTheme +"'>" +
"<div data-" + $.mobile.ns + "role='header'>" +
"<div class='ui-title'>" + label.getEncodedText() + "</div>"+
"</div>"+
"<div data-" + $.mobile.ns + "role='content'></div>"+
"</div>" ),
listbox = $("<div>", { "class": "ui-selectmenu ui-selectmenu-hidden ui-overlay-shadow ui-corner-all ui-body-" + widget.options.overlayTheme + " " + $.mobile.defaultDialogTransition } ).insertAfter(screen),
list = $( "<ul>", {
"class": "ui-selectmenu-list",
"id": menuId,
"role": "listbox",
"aria-labelledby": buttonId
}).attr( "data-" + $.mobile.ns + "theme", widget.options.theme ).appendTo( listbox ),
header = $( "<div>", {
"class": "ui-header ui-bar-" + widget.options.theme
}).prependTo( listbox ),
headerTitle = $( "<h1>", {
"class": "ui-title"
}).appendTo( header ),
menuPageContent,
menuPageClose,
headerClose;
if( widget.isMultiple ) {
headerClose = $( "<a>", {
"text": widget.options.closeText,
"href": "#",
"class": "ui-btn-left"
}).attr( "data-" + $.mobile.ns + "iconpos", "notext" ).attr( "data-" + $.mobile.ns + "icon", "delete" ).appendTo( header ).buttonMarkup();
}
$.extend( widget, {
select: widget.select,
selectID: selectID,
buttonId: buttonId,
menuId: menuId,
thisPage: thisPage,
menuPage: menuPage,
label: label,
screen: screen,
selectOptions: selectOptions,
isMultiple: isMultiple,
theme: widget.options.theme,
listbox: listbox,
list: list,
header: header,
headerTitle: headerTitle,
headerClose: headerClose,
menuPageContent: menuPageContent,
menuPageClose: menuPageClose,
placeholder: "",
build: function() {
var self = this;
// Create list from select, update state
self.refresh();
self.select.attr( "tabindex", "-1" ).focus(function() {
$( this ).blur();
self.button.focus();
});
// Button events
self.button.bind( "vclick keydown" , function( event ) {
if ( event.type == "vclick" ||
event.keyCode && ( event.keyCode === $.mobile.keyCode.ENTER ||
event.keyCode === $.mobile.keyCode.SPACE ) ) {
self.open();
event.preventDefault();
}
});
// Events for list items
self.list.attr( "role", "listbox" )
.bind( "focusin", function( e ){
$( e.target )
.attr( "tabindex", "0" )
.trigger( "vmouseover" );
})
.bind( "focusout", function( e ){
$( e.target )
.attr( "tabindex", "-1" )
.trigger( "vmouseout" );
})
.delegate( "li:not(.ui-disabled, .ui-li-divider)", "click", function( event ) {
// index of option tag to be selected
var oldIndex = self.select[ 0 ].selectedIndex,
newIndex = self.list.find( "li:not(.ui-li-divider)" ).index( this ),
option = self._selectOptions().eq( newIndex )[ 0 ];
// toggle selected status on the tag for multi selects
option.selected = self.isMultiple ? !option.selected : true;
// toggle checkbox class for multiple selects
if ( self.isMultiple ) {
$( this ).find( ".ui-icon" )
.toggleClass( "ui-icon-checkbox-on", option.selected )
.toggleClass( "ui-icon-checkbox-off", !option.selected );
}
// trigger change if value changed
if ( self.isMultiple || oldIndex !== newIndex ) {
self.select.trigger( "change" );
}
//hide custom select for single selects only
if ( !self.isMultiple ) {
self.close();
}
event.preventDefault();
})
.keydown(function( event ) { //keyboard events for menu items
var target = $( event.target ),
li = target.closest( "li" ),
prev, next;
// switch logic based on which key was pressed
switch ( event.keyCode ) {
// up or left arrow keys
case 38:
prev = li.prev().not( ".ui-selectmenu-placeholder" );
if( prev.is( ".ui-li-divider" ) ) {
prev = prev.prev();
}
// if there's a previous option, focus it
if ( prev.length ) {
target
.blur()
.attr( "tabindex", "-1" );
prev.addClass( "ui-btn-down-" + widget.options.theme ).find( "a" ).first().focus();
}
return false;
break;
// down or right arrow keys
case 40:
next = li.next();
if( next.is( ".ui-li-divider" ) ) {
next = next.next();
}
// if there's a next option, focus it
if ( next.length ) {
target
.blur()
.attr( "tabindex", "-1" );
next.addClass( "ui-btn-down-" + widget.options.theme ).find( "a" ).first().focus();
}
return false;
break;
// If enter or space is pressed, trigger click
case 13:
case 32:
target.trigger( "click" );
return false;
break;
}
});
// button refocus ensures proper height calculation
// by removing the inline style and ensuring page inclusion
self.menuPage.bind( "pagehide", function() {
self.list.appendTo( self.listbox );
self._focusButton();
// TODO centralize page removal binding / handling in the page plugin.
// Suggestion from @jblas to do refcounting
//
// TODO extremely confusing dependency on the open method where the pagehide.remove
// bindings are stripped to prevent the parent page from disappearing. The way
// we're keeping pages in the DOM right now sucks
//
// rebind the page remove that was unbound in the open function
// to allow for the parent page removal from actions other than the use
// of a dialog sized custom select
//
// doing this here provides for the back button on the custom select dialog
$.mobile._bindPageRemove.call( self.thisPage );
});
// Events on "screen" overlay
self.screen.bind( "vclick", function( event ) {
self.close();
});
// Close button on small overlays
if( self.isMultiple ){
self.headerClose.click( function() {
if ( self.menuType == "overlay" ) {
self.close();
return false;
}
});
}
// track this dependency so that when the parent page
// is removed on pagehide it will also remove the menupage
self.thisPage.addDependents( this.menuPage );
},
_isRebuildRequired: function() {
var list = this.list.find( "li" ),
options = this._selectOptions();
// TODO exceedingly naive method to determine difference
// ignores value changes etc in favor of a forcedRebuild
// from the user in the refresh method
return options.text() !== list.text();
},
refresh: function( forceRebuild , foo ){
var self = this,
select = this.element,
isMultiple = this.isMultiple,
options = this._selectOptions(),
selected = this.selected(),
// return an array of all selected index's
indicies = this.selectedIndices();
if ( forceRebuild || this._isRebuildRequired() ) {
self._buildList();
}
self.setButtonText();
self.setButtonCount();
self.list.find( "li:not(.ui-li-divider)" )
.removeClass( $.mobile.activeBtnClass )
.attr( "aria-selected", false )
.each(function( i ) {
if ( $.inArray( i, indicies ) > -1 ) {
var item = $( this );
// Aria selected attr
item.attr( "aria-selected", true );
// Multiple selects: add the "on" checkbox state to the icon
if ( self.isMultiple ) {
item.find( ".ui-icon" ).removeClass( "ui-icon-checkbox-off" ).addClass( "ui-icon-checkbox-on" );
} else {
if( item.is( ".ui-selectmenu-placeholder" ) ) {
item.next().addClass( $.mobile.activeBtnClass );
} else {
item.addClass( $.mobile.activeBtnClass );
}
}
}
});
},
close: function() {
if ( this.options.disabled || !this.isOpen ) {
return;
}
var self = this;
if ( self.menuType == "page" ) {
// doesn't solve the possible issue with calling change page
// where the objects don't define data urls which prevents dialog key
// stripping - changePage has incoming refactor
window.history.back();
} else {
self.screen.addClass( "ui-screen-hidden" );
self.listbox.addClass( "ui-selectmenu-hidden" ).removeAttr( "style" ).removeClass( "in" );
self.list.appendTo( self.listbox );
self._focusButton();
}
// allow the dialog to be closed again
self.isOpen = false;
},
open: function() {
if ( this.options.disabled ) {
return;
}
var self = this,
$window = $( window ),
selfListParent = self.list.parent(),
menuHeight = selfListParent.outerHeight(),
menuWidth = selfListParent.outerWidth(),
activePage = $( ".ui-page-active" ),
tScrollElem = activePage,
scrollTop = $window.scrollTop(),
btnOffset = self.button.offset().top,
screenHeight = $window.height(),
screenWidth = $window.width();
//add active class to button
self.button.addClass( $.mobile.activeBtnClass );
//remove after delay
setTimeout( function() {
self.button.removeClass( $.mobile.activeBtnClass );
}, 300);
function focusMenuItem() {
self.list.find( "." + $.mobile.activeBtnClass + " a" ).focus();
}
if ( menuHeight > screenHeight - 80 || !$.support.scrollTop ) {
self.menuPage.appendTo( $.mobile.pageContainer ).page();
self.menuPageContent = menuPage.find( ".ui-content" );
self.menuPageClose = menuPage.find( ".ui-header a" );
// prevent the parent page from being removed from the DOM,
// otherwise the results of selecting a list item in the dialog
// fall into a black hole
self.thisPage.unbind( "pagehide.remove" );
//for WebOS/Opera Mini (set lastscroll using button offset)
if ( scrollTop == 0 && btnOffset > screenHeight ) {
self.thisPage.one( "pagehide", function() {
$( this ).jqmData( "lastScroll", btnOffset );
});
}
self.menuPage.one( "pageshow", function() {
focusMenuItem();
self.isOpen = true;
});
self.menuType = "page";
self.menuPageContent.append( self.list );
self.menuPage.find("div .ui-title").text(self.label.text());
$.mobile.changePage( self.menuPage, {
transition: $.mobile.defaultDialogTransition
});
} else {
self.menuType = "overlay";
self.screen.height( $(document).height() )
.removeClass( "ui-screen-hidden" );
// Try and center the overlay over the button
var roomtop = btnOffset - scrollTop,
roombot = scrollTop + screenHeight - btnOffset,
halfheight = menuHeight / 2,
maxwidth = parseFloat( self.list.parent().css( "max-width" ) ),
newtop, newleft;
if ( roomtop > menuHeight / 2 && roombot > menuHeight / 2 ) {
newtop = btnOffset + ( self.button.outerHeight() / 2 ) - halfheight;
} else {
// 30px tolerance off the edges
newtop = roomtop > roombot ? scrollTop + screenHeight - menuHeight - 30 : scrollTop + 30;
}
// If the menuwidth is smaller than the screen center is
if ( menuWidth < maxwidth ) {
newleft = ( screenWidth - menuWidth ) / 2;
} else {
//otherwise insure a >= 30px offset from the left
newleft = self.button.offset().left + self.button.outerWidth() / 2 - menuWidth / 2;
// 30px tolerance off the edges
if ( newleft < 30 ) {
newleft = 30;
} else if ( (newleft + menuWidth) > screenWidth ) {
newleft = screenWidth - menuWidth - 30;
}
}
self.listbox.append( self.list )
.removeClass( "ui-selectmenu-hidden" )
.css({
top: newtop,
left: newleft
})
.addClass( "in" );
focusMenuItem();
// duplicate with value set in page show for dialog sized selects
self.isOpen = true;
}
},
_buildList: function() {
var self = this,
o = this.options,
placeholder = this.placeholder,
needPlaceholder = true,
optgroups = [],
lis = [],
dataIcon = self.isMultiple ? "checkbox-off" : "false";
self.list.empty().filter( ".ui-listview" ).listview( "destroy" );
var $options = self.select.find("option"),
numOptions = $options.length,
select = this.select[ 0 ],
dataPrefix = 'data-' + $.mobile.ns,
dataIndexAttr = dataPrefix + 'option-index',
dataIconAttr = dataPrefix + 'icon',
dataRoleAttr = dataPrefix + 'role',
fragment = document.createDocumentFragment(),
optGroup;
for (var i = 0; i < numOptions;i++){
var option = $options[i],
$option = $(option),
parent = option.parentNode,
text = $option.text(),
anchor = document.createElement('a'),
classes = [];
anchor.setAttribute('href','#');
anchor.appendChild(document.createTextNode(text));
// Are we inside an optgroup?
if (parent !== select && parent.nodeName.toLowerCase() === "optgroup"){
var optLabel = parent.getAttribute('label');
if ( optLabel != optGroup) {
var divider = document.createElement('li');
divider.setAttribute(dataRoleAttr,'list-divider');
divider.setAttribute('role','option');
divider.setAttribute('tabindex','-1');
divider.appendChild(document.createTextNode(optLabel));
fragment.appendChild(divider);
optGroup = optLabel;
}
}
if (needPlaceholder && (!option.getAttribute( "value" ) || text.length == 0 || $option.jqmData( "placeholder" ))) {
needPlaceholder = false;
if ( o.hidePlaceholderMenuItems ) {
classes.push( "ui-selectmenu-placeholder" );
}
if (!placeholder) {
placeholder = self.placeholder = text;
}
}
var item = document.createElement('li');
if ( option.disabled ) {
classes.push( "ui-disabled" );
item.setAttribute('aria-disabled',true);
}
item.setAttribute(dataIndexAttr,i);
item.setAttribute(dataIconAttr,dataIcon);
item.className = classes.join(" ");
item.setAttribute('role','option');
anchor.setAttribute('tabindex','-1');
item.appendChild(anchor);
fragment.appendChild(item);
}
self.list[0].appendChild(fragment);
// Hide header if it's not a multiselect and there's no placeholder
if ( !this.isMultiple && !placeholder.length ) {
this.header.hide();
} else {
this.headerTitle.text( this.placeholder );
}
// Now populated, create listview
self.list.listview();
},
_button: function(){
return $( "<a>", {
"href": "#",
"role": "button",
// TODO value is undefined at creation
"id": this.buttonId,
"aria-haspopup": "true",
// TODO value is undefined at creation
"aria-owns": this.menuId
});
}
});
};
// issue #3894 - core doesn't triggered events on disabled delegates
$( document ).bind( "selectmenubeforecreate", function( event ){
var selectmenuWidget = $( event.target ).data( "selectmenu" );
if( !selectmenuWidget.options.nativeMenu ){
extendSelect( selectmenuWidget );
}
});
})( jQuery );
(function( $, undefined ) {
$.widget( "mobile.fixedtoolbar", $.mobile.widget, {
options: {
visibleOnPageShow: true,
disablePageZoom: true,
transition: "slide", //can be none, fade, slide (slide maps to slideup or slidedown)
fullscreen: false,
tapToggle: true,
tapToggleBlacklist: "a, input, select, textarea, .ui-header-fixed, .ui-footer-fixed",
hideDuringFocus: "input, textarea, select",
updatePagePadding: true,
trackPersistentToolbars: true,
// Browser detection! Weeee, here we go...
// Unfortunately, position:fixed is costly, not to mention probably impossible, to feature-detect accurately.
// Some tests exist, but they currently return false results in critical devices and browsers, which could lead to a broken experience.
// Testing fixed positioning is also pretty obtrusive to page load, requiring injected elements and scrolling the window
// The following function serves to rule out some popular browsers with known fixed-positioning issues
// This is a plugin option like any other, so feel free to improve or overwrite it
supportBlacklist: function(){
var w = window,
ua = navigator.userAgent,
platform = navigator.platform,
// Rendering engine is Webkit, and capture major version
wkmatch = ua.match( /AppleWebKit\/([0-9]+)/ ),
wkversion = !!wkmatch && wkmatch[ 1 ],
ffmatch = ua.match( /Fennec\/([0-9]+)/ ),
ffversion = !!ffmatch && ffmatch[ 1 ],
operammobilematch = ua.match( /Opera Mobi\/([0-9]+)/ ),
omversion = !!operammobilematch && operammobilematch[ 1 ];
if(
// iOS 4.3 and older : Platform is iPhone/Pad/Touch and Webkit version is less than 534 (ios5)
( ( platform.indexOf( "iPhone" ) > -1 || platform.indexOf( "iPad" ) > -1 || platform.indexOf( "iPod" ) > -1 ) && wkversion && wkversion < 534 )
||
// Opera Mini
( w.operamini && ({}).toString.call( w.operamini ) === "[object OperaMini]" )
||
( operammobilematch && omversion < 7458 )
||
//Android lte 2.1: Platform is Android and Webkit version is less than 533 (Android 2.2)
( ua.indexOf( "Android" ) > -1 && wkversion && wkversion < 533 )
||
// Firefox Mobile before 6.0 -
( ffversion && ffversion < 6 )
||
// WebOS less than 3
( "palmGetResource" in window && wkversion && wkversion < 534 )
||
// MeeGo
( ua.indexOf( "MeeGo" ) > -1 && ua.indexOf( "NokiaBrowser/8.5.0" ) > -1 )
){
return true;
}
return false;
},
initSelector: ":jqmData(position='fixed')"
},
_create: function() {
var self = this,
o = self.options,
$el = self.element,
tbtype = $el.is( ":jqmData(role='header')" ) ? "header" : "footer",
$page = $el.closest(".ui-page");
// Feature detecting support for
if( o.supportBlacklist() ){
self.destroy();
return;
}
$el.addClass( "ui-"+ tbtype +"-fixed" );
// "fullscreen" overlay positioning
if( o.fullscreen ){
$el.addClass( "ui-"+ tbtype +"-fullscreen" );
$page.addClass( "ui-page-" + tbtype + "-fullscreen" );
}
// If not fullscreen, add class to page to set top or bottom padding
else{
$page.addClass( "ui-page-" + tbtype + "-fixed" );
}
self._addTransitionClass();
self._bindPageEvents();
self._bindToggleHandlers();
},
_addTransitionClass: function(){
var tclass = this.options.transition;
if( tclass && tclass !== "none" ){
// use appropriate slide for header or footer
if( tclass === "slide" ){
tclass = this.element.is( ".ui-header" ) ? "slidedown" : "slideup";
}
this.element.addClass( tclass );
}
},
_bindPageEvents: function(){
var self = this,
o = self.options,
$el = self.element;
//page event bindings
// Fixed toolbars require page zoom to be disabled, otherwise usability issues crop up
// This method is meant to disable zoom while a fixed-positioned toolbar page is visible
$el.closest( ".ui-page" )
.bind( "pagebeforeshow", function(){
if( o.disablePageZoom ){
$.mobile.zoom.disable( true );
}
if( !o.visibleOnPageShow ){
self.hide( true );
}
} )
.bind( "webkitAnimationStart animationstart updatelayout", function(){
if( o.updatePagePadding ){
self.updatePagePadding();
}
})
.bind( "pageshow", function(){
self.updatePagePadding();
if( o.updatePagePadding ){
$( window ).bind( "throttledresize." + self.widgetName, function(){
self.updatePagePadding();
});
}
})
.bind( "pagebeforehide", function( e, ui ){
if( o.disablePageZoom ){
$.mobile.zoom.enable( true );
}
if( o.updatePagePadding ){
$( window ).unbind( "throttledresize." + self.widgetName );
}
if( o.trackPersistentToolbars ){
var thisFooter = $( ".ui-footer-fixed:jqmData(id)", this ),
thisHeader = $( ".ui-header-fixed:jqmData(id)", this ),
nextFooter = thisFooter.length && ui.nextPage && $( ".ui-footer-fixed:jqmData(id='" + thisFooter.jqmData( "id" ) + "')", ui.nextPage ),
nextHeader = thisHeader.length && ui.nextPage && $( ".ui-header-fixed:jqmData(id='" + thisHeader.jqmData( "id" ) + "')", ui.nextPage );
nextFooter = nextFooter || $();
if( nextFooter.length || nextHeader.length ){
nextFooter.add( nextHeader ).appendTo( $.mobile.pageContainer );
ui.nextPage.one( "pageshow", function(){
nextFooter.add( nextHeader ).appendTo( this );
});
}
}
});
},
_visible: true,
// This will set the content element's top or bottom padding equal to the toolbar's height
updatePagePadding: function() {
var $el = this.element,
header = $el.is( ".ui-header" );
// This behavior only applies to "fixed", not "fullscreen"
if( this.options.fullscreen ){ return; }
$el.closest( ".ui-page" ).css( "padding-" + ( header ? "top" : "bottom" ), $el.outerHeight() );
},
_useTransition: function( notransition ){
var $win = $( window ),
$el = this.element,
scroll = $win.scrollTop(),
elHeight = $el.height(),
pHeight = $el.closest( ".ui-page" ).height(),
viewportHeight = $.mobile.getScreenHeight(),
tbtype = $el.is( ":jqmData(role='header')" ) ? "header" : "footer";
return !notransition &&
( this.options.transition && this.options.transition !== "none" &&
(
( tbtype === "header" && !this.options.fullscreen && scroll > elHeight ) ||
( tbtype === "footer" && !this.options.fullscreen && scroll + viewportHeight < pHeight - elHeight )
) || this.options.fullscreen
);
},
show: function( notransition ){
var hideClass = "ui-fixed-hidden",
$el = this.element;
if( this._useTransition( notransition ) ){
$el
.removeClass( "out " + hideClass )
.addClass( "in" );
}
else {
$el.removeClass( hideClass );
}
this._visible = true;
},
hide: function( notransition ){
var hideClass = "ui-fixed-hidden",
$el = this.element,
// if it's a slide transition, our new transitions need the reverse class as well to slide outward
outclass = "out" + ( this.options.transition === "slide" ? " reverse" : "" );
if( this._useTransition( notransition ) ){
$el
.addClass( outclass )
.removeClass( "in" )
.animationComplete( function(){
$el.addClass( hideClass ).removeClass( outclass );
});
}
else {
$el.addClass( hideClass ).removeClass( outclass );
}
this._visible = false;
},
toggle: function(){
this[ this._visible ? "hide" : "show" ]();
},
_bindToggleHandlers: function(){
var self = this,
o = self.options,
$el = self.element;
// tap toggle
$el.closest( ".ui-page" )
.bind( "vclick", function( e ){
if( o.tapToggle && !$( e.target ).closest( o.tapToggleBlacklist ).length ){
self.toggle();
}
})
.bind( "focusin focusout", function( e ){
if( screen.width < 500 && $( e.target ).is( o.hideDuringFocus ) && !$( e.target ).closest( ".ui-header-fixed, .ui-footer-fixed" ).length ){
self[ ( e.type === "focusin" && self._visible ) ? "hide" : "show" ]();
}
});
},
destroy: function(){
this.element.removeClass( "ui-header-fixed ui-footer-fixed ui-header-fullscreen ui-footer-fullscreen in out fade slidedown slideup ui-fixed-hidden" );
this.element.closest( ".ui-page" ).removeClass( "ui-page-header-fixed ui-page-footer-fixed ui-page-header-fullscreen ui-page-footer-fullscreen" );
}
});
//auto self-init widgets
$( document )
.bind( "pagecreate create", function( e ){
// DEPRECATED in 1.1: support for data-fullscreen=true|false on the page element.
// This line ensures it still works, but we recommend moving the attribute to the toolbars themselves.
if( $( e.target ).jqmData( "fullscreen" ) ){
$( $.mobile.fixedtoolbar.prototype.options.initSelector, e.target ).not( ":jqmData(fullscreen)" ).jqmData( "fullscreen", true );
}
$.mobile.fixedtoolbar.prototype.enhanceWithin( e.target );
});
})( jQuery );
( function( $, window ) {
// This fix addresses an iOS bug, so return early if the UA claims it's something else.
if( !(/iPhone|iPad|iPod/.test( navigator.platform ) && navigator.userAgent.indexOf( "AppleWebKit" ) > -1 ) ){
return;
}
var zoom = $.mobile.zoom,
evt, x, y, z, aig;
function checkTilt( e ){
evt = e.originalEvent;
aig = evt.accelerationIncludingGravity;
x = Math.abs( aig.x );
y = Math.abs( aig.y );
z = Math.abs( aig.z );
// If portrait orientation and in one of the danger zones
if( !window.orientation && ( x > 7 || ( ( z > 6 && y < 8 || z < 8 && y > 6 ) && x > 5 ) ) ){
if( zoom.enabled ){
zoom.disable();
}
}
else if( !zoom.enabled ){
zoom.enable();
}
}
$( window )
.bind( "orientationchange.iosorientationfix", zoom.enable )
.bind( "devicemotion.iosorientationfix", checkTilt );
}( jQuery, this ));
( function( $, window, undefined ) {
var $html = $( "html" ),
$head = $( "head" ),
$window = $( window );
// trigger mobileinit event - useful hook for configuring $.mobile settings before they're used
$( window.document ).trigger( "mobileinit" );
// support conditions
// if device support condition(s) aren't met, leave things as they are -> a basic, usable experience,
// otherwise, proceed with the enhancements
if ( !$.mobile.gradeA() ) {
return;
}
// override ajaxEnabled on platforms that have known conflicts with hash history updates
// or generally work better browsing in regular http for full page refreshes (BB5, Opera Mini)
if ( $.mobile.ajaxBlacklist ) {
$.mobile.ajaxEnabled = false;
}
// Add mobile, initial load "rendering" classes to docEl
$html.addClass( "ui-mobile ui-mobile-rendering" );
// This is a fallback. If anything goes wrong (JS errors, etc), or events don't fire,
// this ensures the rendering class is removed after 5 seconds, so content is visible and accessible
setTimeout( hideRenderingClass, 5000 );
// loading div which appears during Ajax requests
// will not appear if $.mobile.loadingMessage is false
var loaderClass = "ui-loader",
$loader = $( "<div class='" + loaderClass + "'><span class='ui-icon ui-icon-loading'></span><h1></h1></div>" );
// For non-fixed supportin browsers. Position at y center (if scrollTop supported), above the activeBtn (if defined), or just 100px from top
function fakeFixLoader(){
var activeBtn = $( "." + $.mobile.activeBtnClass ).first();
$loader
.css({
top: $.support.scrollTop && $window.scrollTop() + $window.height() / 2 ||
activeBtn.length && activeBtn.offset().top || 100
});
}
// check position of loader to see if it appears to be "fixed" to center
// if not, use abs positioning
function checkLoaderPosition(){
var offset = $loader.offset(),
scrollTop = $window.scrollTop(),
screenHeight = $.mobile.getScreenHeight();
if( offset.top < scrollTop || (offset.top - scrollTop) > screenHeight ) {
$loader.addClass( "ui-loader-fakefix" );
fakeFixLoader();
$window
.unbind( "scroll", checkLoaderPosition )
.bind( "scroll", fakeFixLoader );
}
}
//remove initial build class (only present on first pageshow)
function hideRenderingClass(){
$html.removeClass( "ui-mobile-rendering" );
}
$.extend($.mobile, {
// turn on/off page loading message.
showPageLoadingMsg: function( theme, msgText, textonly ) {
$html.addClass( "ui-loading" );
if ( $.mobile.loadingMessage ) {
// text visibility from argument takes priority
var textVisible = textonly || $.mobile.loadingMessageTextVisible;
theme = theme || $.mobile.loadingMessageTheme,
$loader
.attr( "class", loaderClass + " ui-corner-all ui-body-" + ( theme || "a" ) + " ui-loader-" + ( textVisible ? "verbose" : "default" ) + ( textonly ? " ui-loader-textonly" : "" ) )
.find( "h1" )
.text( msgText || $.mobile.loadingMessage )
.end()
.appendTo( $.mobile.pageContainer );
checkLoaderPosition();
$window.bind( "scroll", checkLoaderPosition );
}
},
hidePageLoadingMsg: function() {
$html.removeClass( "ui-loading" );
if( $.mobile.loadingMessage ){
$loader.removeClass( "ui-loader-fakefix" );
}
$( window ).unbind( "scroll", fakeFixLoader );
$( window ).unbind( "scroll", checkLoaderPosition );
},
// find and enhance the pages in the dom and transition to the first page.
initializePage: function() {
// find present pages
var $pages = $( ":jqmData(role='page'), :jqmData(role='dialog')" );
// if no pages are found, create one with body's inner html
if ( !$pages.length ) {
$pages = $( "body" ).wrapInner( "<div data-" + $.mobile.ns + "role='page'></div>" ).children( 0 );
}
// add dialogs, set data-url attrs
$pages.each(function() {
var $this = $(this);
// unless the data url is already set set it to the pathname
if ( !$this.jqmData("url") ) {
$this.attr( "data-" + $.mobile.ns + "url", $this.attr( "id" ) || location.pathname + location.search );
}
});
// define first page in dom case one backs out to the directory root (not always the first page visited, but defined as fallback)
$.mobile.firstPage = $pages.first();
// define page container
$.mobile.pageContainer = $pages.first().parent().addClass( "ui-mobile-viewport" );
// alert listeners that the pagecontainer has been determined for binding
// to events triggered on it
$window.trigger( "pagecontainercreate" );
// cue page loading message
$.mobile.showPageLoadingMsg();
//remove initial build class (only present on first pageshow)
hideRenderingClass();
// if hashchange listening is disabled or there's no hash deeplink, change to the first page in the DOM
if ( !$.mobile.hashListeningEnabled || !$.mobile.path.stripHash( location.hash ) ) {
$.mobile.changePage( $.mobile.firstPage, { transition: "none", reverse: true, changeHash: false, fromHashChange: true } );
}
// otherwise, trigger a hashchange to load a deeplink
else {
$window.trigger( "hashchange", [ true ] );
}
}
});
// initialize events now, after mobileinit has occurred
$.mobile._registerInternalEvents();
// check which scrollTop value should be used by scrolling to 1 immediately at domready
// then check what the scroll top is. Android will report 0... others 1
// note that this initial scroll won't hide the address bar. It's just for the check.
$(function() {
window.scrollTo( 0, 1 );
// if defaultHomeScroll hasn't been set yet, see if scrollTop is 1
// it should be 1 in most browsers, but android treats 1 as 0 (for hiding addr bar)
// so if it's 1, use 0 from now on
$.mobile.defaultHomeScroll = ( !$.support.scrollTop || $(window).scrollTop() === 1 ) ? 0 : 1;
// TODO: Implement a proper registration mechanism with dependency handling in order to not have exceptions like the one below
//auto self-init widgets for those widgets that have a soft dependency on others
if ( $.fn.controlgroup ) {
$( document ).bind( "pagecreate create", function( e ){
$( ":jqmData(role='controlgroup')", e.target )
.jqmEnhanceable()
.controlgroup({ excludeInvisible: false });
});
}
//dom-ready inits
if( $.mobile.autoInitializePage ){
$.mobile.initializePage();
}
// window load event
// hide iOS browser chrome on load
$window.load( $.mobile.silentScroll );
});
}( jQuery, this ));
}));
| JavaScript |
if(!window.plugins)
{
window.plugins = {};
}
window.plugins.PGLoadingDialog=
{
show: function(options, callback)
{
window.PhoneGap.exec(callback,null,'PGLoadingDialog','showLoading', [options]);
},
hide: function(callback)
{
window.PhoneGap.exec(callback, null, 'PGLoadingDialog', 'hideLoading', [] );
}
};
| JavaScript |
/*$(function(){
var $li =$("#skin li");
$li.click(function(){
switchSkin( this.id );
});
if(window.localStorage){
var cookie_skin = localStorage.getItem("nowskin");
}else{
var cookie_skin = $.cookie( "nowskin");
}
if (cookie_skin) {
switchSkin( cookie_skin );
}
bindKeyDown();
});*/
function SetCookie(name, value) {
var argv = SetCookie.arguments;
var argc = SetCookie.arguments.length;
var expires = (2 < argc) ? argv[2] : null;
var path = (3 < argc) ? argv[3] : null;
var domain = (4 < argc) ? argv[4] : null;
var secure = (5 < argc) ? argv[5] : false;
document.cookie = name + "=" + escape(value) + ((expires == null) ? "" : ("; expires=" + expires.toGMTString()))
+ ((path == null) ? "" : ("; path=" + path)) + ((domain == null) ? "" : ("; domain=" + domain)) + ((secure == true) ? "; secure" : "");
}
function GetCookie(Name) {
var search = Name + "=";
var returnvalue = "";
if (document.cookie.length > 0) {
offset = document.cookie.indexOf(search);
if (offset != -1) {
offset += search.length;
end = document.cookie.indexOf(";", offset);
if (end == -1)
end = document.cookie.length;
returnvalue = unescape(document.cookie.substring(offset, end));
}
}
return returnvalue;
}
var thisskin, skin;
if (window.localStorage) {
thisskin = window.localStorage.getItem("nowskin");
} else {
thisskin = GetCookie("nowskin");
}
skin = document.getElementById("skin");
if (thisskin != "")
skin.href = thisskin;
else
skin.href = "css/blackstyle.css";
function changecss(url) {
if (url != "") {
skin.href = "css/" + url;
if (window.localStorage) {
alert(skin.href);
window.localStorage.setItem("nowskin", "css/" + url);
} else {
var expdate = new Date();
expdate.setTime(expdate.getTime() + (24 * 60 * 60 * 1000 * 30));
SetCookie("nowskin", url, expdate, "/", null, false);
}
}
$.mobile.changePage("index.html", {
transition : "none"
});
}
/*
* function switchSkin(skinName){ $("#"+skinName).addClass("selected")
* .siblings().removeClass("selected");
* $("#cssfile").attr("href",skinName+"/css/index.css");
* if(window.localStorage){ localStorage.setItem("MyCssSkin" , skinName); }else{
* $.cookie( "MyCssSkin" , skinName); } }
*/ | JavaScript |
//collapse page navs after use
$(function(){
$('body').delegate('.content-secondary .ui-collapsible-content', 'click', function(){
$(this).trigger("collapse");
});
});
// 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() {
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).bind( '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 ).bind( "mobileinit", function() {
$.mobile.ajaxEnabled = false;
var message = $( '<div>' , {
'class': "ui-footer ui-bar-e",
style: "overflow: auto; padding:10px 15px;",
'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, try a different browser or <a href='https://github.com/jquery/jquery-mobile/wiki/Downloadable-Docs-Help'>view help</a>.</p>" );
$( document ).bind( "pagecreate", function( event ) {
$( event.target ).append( message );
});
});
});
}
| JavaScript |
/* jFeed : jQuery feed parser plugin
* Copyright (C) 2007 Jean-François Hovinne - http://www.hovinne.com/
* Dual licensed under the MIT (MIT-license.txt)
* and GPL (GPL-license.txt) licenses.
*/
jQuery.getFeed = function(options) {
options = jQuery.extend({
url : null,
data : null,
cache : true,
success : null,
failure : null,
error : null,
global : true
}, options);
if (options.url) {
if (jQuery.isFunction(options.failure) && jQuery.type(options.error) === 'null') {
// Handle legacy failure option
options.error = function(xhr, msg, e) {
options.failure(msg, e);
}
} else if (jQuery.type(options.failure) === jQuery.type(options.error) === 'null') {
// Default error behavior if failure & error both unspecified
options.error = function(xhr, msg, e) {
window.console && console.log('getFeed failed to load feed', xhr, msg, e);
}
}
return $.ajax({
type : 'GET',
url : options.url,
data : options.data,
cache : options.cache,
dataType : (jQuery.browser.msie) ? "text" : "xml",
success : function(xml) {
var feed = new JFeed(xml);
if (jQuery.isFunction(options.success))
options.success(feed);
},
error : options.error,
global : options.global
});
}
};
function JFeed(xml) {
if (xml)
this.parse(xml);
};
JFeed.prototype = {
type : '',
version : '',
title : '',
link : '',
description : '',
parse : function(xml) {
if (jQuery.browser.msie) {
var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.loadXML(xml);
xml = xmlDoc;
}
if (jQuery('channel', xml).length == 1) {
this.type = 'rss';
var feedClass = new JRss(xml);
} else if (jQuery('feed', xml).length == 1) {
this.type = 'atom';
var feedClass = new JAtom(xml);
}
if (feedClass)
jQuery.extend(this, feedClass);
}
};
function JFeedItem() {
};
JFeedItem.prototype = {
title : '',
link : '',
description : '',
updated : '',
id : ''
};
function JAtom(xml) {
this._parse(xml);
};
JAtom.prototype = {
_parse : function(xml) {
var channel = jQuery('feed', xml).eq(0);
this.version = '1.0';
this.title = jQuery(channel).find('title:first').text();
this.link = jQuery(channel).find('link:first').attr('href');
this.description = jQuery(channel).find('subtitle:first').text();
this.language = jQuery(channel).attr('xml:lang');
this.updated = jQuery(channel).find('updated:first').text();
this.items = new Array();
var feed = this;
jQuery('entry', xml).each(function() {
var item = new JFeedItem();
item.title = jQuery(this).find('title').eq(0).text();
item.link = jQuery(this).find('link').eq(0).attr('href');
item.description = jQuery(this).find('content').eq(0).text();
item.updated = jQuery(this).find('updated').eq(0).text();
item.id = jQuery(this).find('id').eq(0).text();
feed.items.push(item);
});
}
};
function JRss(xml) {
this._parse(xml);
};
JRss.prototype = {
_parse : function(xml) {
if (jQuery('rss', xml).length == 0)
this.version = '1.0';
else
this.version = jQuery('rss', xml).eq(0).attr('version');
var channel = jQuery('channel', xml).eq(0);
this.title = jQuery(channel).find('title:first').text();
this.link = jQuery(channel).find('link:first').text();
this.description = jQuery(channel).find('description:first').text();
this.language = jQuery(channel).find('language:first').text();
this.updated = jQuery(channel).find('lastBuildDate:first').text();
this.items = new Array();
var feed = this;
jQuery('item', xml).each(function() {
var item = new JFeedItem();
item.title = jQuery(this).find('title').eq(0).text();
item.link = jQuery(this).find('link').eq(0).text();
item.description = jQuery(this).find('description').eq(0).text();
item.updated = jQuery(this).find('pubDate').eq(0).text();
item.id = jQuery(this).find('guid').eq(0).text();
feed.items.push(item);
});
}
};
| JavaScript |
function SetCookie(name, value) {
var argv = SetCookie.arguments;
var argc = SetCookie.arguments.length;
var expires = (2 < argc) ? argv[2] : null;
var path = (3 < argc) ? argv[3] : null;
var domain = (4 < argc) ? argv[4] : null;
var secure = (5 < argc) ? argv[5] : false;
document.cookie = name + "=" + escape(value) + ((expires == null) ? "" : ("; expires=" + expires.toGMTString()))
+ ((path == null) ? "" : ("; path=" + path)) + ((domain == null) ? "" : ("; domain=" + domain)) + ((secure == true) ? "; secure" : "");
}
function GetCookie(Name) {
var search = Name + "=";
var returnvalue = "";
if (document.cookie.length > 0) {
offset = document.cookie.indexOf(search);
if (offset != -1) {
offset += search.length;
end = document.cookie.indexOf(";", offset);
if (end == -1)
end = document.cookie.length;
returnvalue = unescape(document.cookie.substring(offset, end));
}
}
return returnvalue;
}
var thisskin, skin;
thisskin = GetCookie("nowskin");
skin = document.getElementById("skin");
if (thisskin != "")
skin.href = thisskin;
else
skin.href = "css/blackstyle.css";
function changecss(url) {
if (url != "") {
skin.href = "css/" + url;
var expdate = new Date();
expdate.setTime(expdate.getTime() + (24 * 60 * 60 * 1000 * 30));
// expdate=null;
// 以下设置COOKIES时间为1年,自己随便设置该时间.
SetCookie("nowskin", url, expdate, "/", null, false);
}
$.mobile.changePage("index.html", {
transition : "none"
});
}
| JavaScript |
function Coin(id, points, marker) {
this.id = id;
this.points = points;
this.marker = marker;
}
function Question(id, points, marker, question, option1, option2, option3, rightAnswer, associatedBonuses) {
this.id = id;
this.points = points;
this.marker = marker;
this.question = question;
this.option1 = option1;
this.option2 = option2;
this.option3 = option3;
this.rightAnswer = rightAnswer;
this.associatedBonuses = associatedBonuses;
this.getAssociatedBonuses = function() {
return jQuery.grep(this.associatedBonuses, function(n, i) {
return n != null;
})
}
}
function Bonus(id, points, marker, associatedQuestion) {
this.id = id;
this.points = points;
this.marker = marker;
this.associatedQuestion = associatedQuestion;
}
function Game(maxPlayers, latitude, longitude, city, pointsToWin) {
this.maxPlayers = maxPlayers;
this.latitude = latitude;
this.longitude = longitude;
this.city = city;
this.pointsToWin = pointsToWin;
this.items = new Array();
this.getItems = function() {
return jQuery.grep(this.items, function(n, i) {
return n != null;
})
}
} | JavaScript |
var map;
$(document).ready(function() {
/**
* Map initialization
*/
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(43.380126326682316, -8.392455154418936);
var myOptions = {
zoom: 12,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: true,
navigationControl: true,
navigationControlOptions: {
style: google.maps.NavigationControlStyle.ZOOM_PAN,
position: google.maps.ControlPosition.LEFT
},
}
map = new google.maps.Map(document.getElementById('mapCanvas'), myOptions);
}); | JavaScript |
var map;
var game;
var selectedItem;
var infowindow;
var geocoder;
var selectedCity;
var selectedLatitude;
var selectedLongitude;
var selectedOnClickAction;
/**
* Paths to item images
*/
var coinImage = '${COIN_IMG}';
var questionImage = '${QUESTION_IMG}';
var bonusImage = '${BONUS_IMG}';
var createURL = '${CREATE_URL}';
var viewURL = '${VIEW_URL}';
$(document).ready(function() {
game = new Game();
$('#addCoinButton').removeAttr('disabled');
$('#addQuestionButton').removeAttr('disabled');
$('#addBonusButton').attr('disabled', true);
/**
* Map initialization
*/
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(43.380126326682316, -8.392455154418936);
var myOptions = {
zoom: 12,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: true,
navigationControl: true,
navigationControlOptions: {
style: google.maps.NavigationControlStyle.ZOOM_PAN,
position: google.maps.ControlPosition.LEFT
},
}
map = new google.maps.Map(document.getElementById('mapCanvas'), myOptions);
google.maps.event.addListener(map, 'click', function(event) {
doOnClick(event);
});
infowindow = new google.maps.InfoWindow({
disableAutoPan : true
});
});
function doOnClick(event) {
if (selectedOnClickAction != null) {
selectedOnClickAction(event);
}
}
function selectOnClickAction(action) {
selectedOnClickAction = action;
}
function changeCityClicked() {
$('#citySpan').html('click anywhere on map');
$('#latitudeSpan').html('?');
$('#longitudeSpan').html('?');
$('#showCityOptions').hide();
elements = $('.gameLocationInfoSpan');
elements.removeClass('gameLocationInfoSpan');
elements.addClass('gameLocationInfoSpanGrey');
selectOnClickAction(showCityOptions);
}
function showCityOptions(event) {
if (geocoder) {
geocoder.geocode({'latLng': event.latLng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
$('#cityOptionsDiv').html('');
$('#cityOptionsDiv').append('<span id="cityOptionsNote">We found some posible city names. Please select the one you want to be displayed: </span><br/>');
selectedLatitude = event.latLng.lat();
selectedLongitude = event.latLng.lng();
for (var i in results[1].address_components) {
$('#cityOptionsDiv').append('<input id="selectedCityId_' + i + '" type="radio" onclick="selectCity(' + i + ')" value="' + results[1].address_components[i].long_name + '"/><span>' + results[1].address_components[i].long_name + '</span><br/>');
}
}
} else {
elements = $('.gameLocationInfoSpanGrey');
elements.removeClass('gameLocationInfoSpanGrey');
elements.addClass('gameLocationInfoSpan');
alert('Geocoder failed due to: ' + status);
$('#cityLabel').html(game.city);
}
});
}
else {
elements = $('.gameLocationInfoSpanGrey');
elements.removeClass('gameLocationInfoSpanGrey');
elements.addClass('gameLocationInfoSpan');
$('#cityLabel').html(game.city);
}
}
function selectCity(index) {
city = $('#selectedCityId_' + index).val();
$('#citySpan').html(city);
$('#latitudeSpan').html(selectedLatitude.toFixed(6));
$('#longitudeSpan').html(selectedLongitude.toFixed(6));
game.city = city;
game.latitude = selectedLatitude;
game.longitude = selectedLongitude;
elements = $('.gameLocationInfoSpanGrey');
elements.removeClass('gameLocationInfoSpanGrey');
elements.addClass('gameLocationInfoSpan');
$('#showCityOptions').show();
$('#cityOptionsDiv').html('');
selectOnClickAction();
}
function addCoin(event) {
id = game.items.length + 1;
marker = placeMarker(event.latLng, id, coinImage);
var item = new Coin(id,
10,
marker);
game.items[game.items.length] = item;
refreshItemsList();
selectItem(item);
}
function addQuestion(event) {
id = game.items.length + 1;
marker = placeMarker(event.latLng, id, questionImage);
var item = new Question(id,
10,
marker);
item.associatedBonuses = new Array();
game.items[game.items.length] = item;
refreshItemsList();
selectItem(item);
selectOnClickAction();
$('#addBonusButton').removeAttr('disabled');
}
function onAttachBonusClick(event) {
$('#addBonusButton').attr('disabled', true);
selectOnClickAction(addBonus);
}
function addBonus(event) {
id = game.items.length + 1;
marker = placeMarker(event.latLng, id, bonusImage);
var item = new Bonus(id,
10,
marker,
selectedItem);
selectedItem.associatedBonuses[selectedItem.associatedBonuses.length] = item;
game.items[game.items.length] = item;
refreshItemsList();
selectItem(selectedItem);
selectOnClickAction();
$('#addBonusButton').removeAttr('disabled');
$('#addCoinButton').removeAttr("disabled");
$('#addQuestionButton').removeAttr("disabled");
}
function placeMarker(position, itemId, image) {
var marker = new google.maps.Marker({
position : position,
draggable : true,
map : map,
clickable : true,
icon : image,
});
google.maps.event.addListener(marker, 'click', function() {
selectItem(getItem(game.items, itemId));
});
google.maps.event.addListener(marker, 'dragstart', function() {
item = getItem(game.items, itemId);
$('#row_' + itemId).html(getUneditableRowContentHtml(item));
});
google.maps.event.addListener(marker, 'drag', function() {
$('#lat_' + itemId).html(marker.position.lat().toFixed(6));
$('#lng_' + itemId).html(marker.position.lng().toFixed(6));
});
google.maps.event.addListener(marker, 'dragend', function() {
});
return marker;
}
function refreshItemsList() {
$('.itemRow').remove();
for (var i in game.items) {
if (game.items[i] != null) {
addItemToList(game.items[i]);
}
}
}
function getEditableRowContentHtml(item) {
return '<td onclick="selectItemById(' + item.id + ')">' + item.id + '</td>' +
'<td onclick="selectItemById(' + item.id + ')"><div class="itemIcon"><img src="' + item.marker.icon +'"/></div></td>' +
'<td onclick="selectItemById(' + item.id + ')"><input id="points_' + item.id + '" type="text" maxlength="6" class="itemInput" value="' + item.points +'"/></td>' +
'<td onclick="selectItemById(' + item.id + ')"><input id="lat_' + item.id + '" type="text" maxlength="8" class="itemInput" value="' + item.marker.position.lat().toFixed(6) +'"/></td>' +
'<td onclick="selectItemById(' + item.id + ')"><input id="lng_' + item.id + '" type="text" maxlength="8" class="itemInput" value="' + item.marker.position.lng().toFixed(6) +'"/></td>' +
'<td><div id="deleteItem_' + item.id + '" class="littleLink"><a href="#" onclick="deleteItem(' + item.id + ')">delete</a></div></td>' +
'<td><div id="saveItem_' + item.id + '" class="littleLink"><a href="#" onclick="saveItem(' + item.id + ')">save</a></div></td>';
}
function getUneditableRowContentHtml(item) {
return '<td onclick="selectItemById(' + item.id + ')">' + item.id + '</td>' +
'<td onclick="selectItemById(' + item.id + ')"><div class="itemIcon"><img src="' + item.marker.icon +'"/></div></td>' +
'<td onclick="selectItemById(' + item.id + ')" id="points_' + item.id + '"><span class="itemInfo">' + item.points +'</td>' +
'<td onclick="selectItemById(' + item.id + ')"><span id="lat_' + item.id + '" class="itemInfo">' + item.marker.position.lat().toFixed(6) +'</td>' +
'<td onclick="selectItemById(' + item.id + ')"><span id="lng_' + item.id + '" class="itemInfo">' + item.marker.position.lng().toFixed(6) +'</td>' +
'<td><div id="deleteItem_' + item.id + '" class="littleLink"><a href="#" onclick="deleteItem(' + item.id + ')">delete</a></div></td>' +
'<td><div id="editItem_' + item.id + '" class="littleLink"><a href="#" onclick="editItem(' + item.id + ')">edit</a></div></td>';
}
function addItemToList(item) {
$('#itemsTable').append(
'<tr class="itemRow unselected" id="row_' + item.id + '">' +
getUneditableRowContentHtml(item) + '</tr>');
}
function doDeleteItem(id) {
var item = getItem(game.items, id);
if (item instanceof Question) {
for (var i in item.associatedBonuses) {
if (item.associatedBonuses[i] != null) {
doDeleteItem(item.associatedBonuses[i].id);
item.associatedBonuses[i] = null;
}
}
$('#addBonusButton').attr("disabled", true);
$('#addCoinButton').removeAttr("disabled");
$('#addQuestionButton').removeAttr("disabled");
}
else if (item instanceof Bonus) {
for (var i in item.associatedQuestion.associatedBonuses) {
if (item.associatedQuestion.associatedBonuses[i] != null &&
item.associatedQuestion.associatedBonuses[i].id == item.id) {
item.associatedQuestion.associatedBonuses[i] = null;
}
}
}
item.marker.setMap(null);
for (var i in game.items) {
if (game.items[i] != null && game.items[i].id == item.id) {
game.items[i] = null;
}
}
item = null;
}
function deleteItem(id) {
if (confirm('Are you sure?')) {
doDeleteItem(id);
refreshItemsList();
}
}
function editItem(id) {
item = getItem(game.items, id);
$('#points_' + id).val(item.points);
$('#row_' + id).html(getEditableRowContentHtml(item));
$('#points_' + id).focus();
for (var i in game.items) {
if ($('#editItem_' + game.items[i].id) != null) {
$('#editItem_' + game.items[i].id + ' a').hide();
}
}
}
function saveItem(id) {
item = getItem(game.items, id);
item.points = $('#points_' + id).val();
$('#row_' + id).html(getUneditableRowContentHtml(item));
for (var i in game.items) {
if ($('#editItem_' + game.items[i].id) != null) {
$('#editItem_' + game.items[i].id + ' a').show();
}
}
}
/**
* Returns the item associated to a marker
*/
function getItem(items, id) {
return jQuery.grep(items, function(n, i) {
if (n != null) {
return n.id == id;
}
})[0];
}
function getLastQuestion() {
var questions = jQuery.grep(game.items, function(n, i) {
var result;
if (n != null && n instanceof Question) {
return n;
}
});
return questions[questions.length - 1];
}
function selectItemById(itemId) {
selectItem(getItem(game.items, itemId));
}
function selectItem(item) {
content = 'Points : ' + item.points;
infowindow.setContent(content);
infowindow.open(map, item.marker);
var elements = $('.itemRow');
elements.removeClass();
elements.addClass('itemRow');
elements.addClass('unselected');
selectedItem = item;
$('#row_' + selectedItem.id).addClass('selected');
if (item instanceof Question) {
$('#questionInfo').show();
$('#addCoinButton').attr('disabled', true);
$('#addQuestionButton').attr('disabled', true);
for (var i in selectedItem.getAssociatedBonuses()) {
$('#row_' + item.getAssociatedBonuses()[i].id).addClass('associatedBonus');
}
}
else {
if (item instanceof Bonus) {
$('#row_' + item.associatedQuestion.id).addClass('associatedQuestion');
}
$('#questionInfo').hide();
$('#addCoinButton').removeAttr("disabled");
$('#addQuestionButton').removeAttr("disabled");
}
}
function editGameInfo() {
$('.gameInfoSpan').hide();
$('#pointsToWinInput').val(game.pointsToWin);
$('#maxPlayersInput').val(game.maxPlayers);
$('#changeGamePointsToWin').html('');
$('#changeGamePointsToWin').append('<a href="#changeGamePointsToWin" onclick="saveGameInfo()">save</a>');
$('.gameInfoInput').show();
}
function saveGameInfo() {
game.pointsToWin = $('#pointsToWinInput').val();
game.maxPlayers = $('#maxPlayersInput').val();
$('#pointsToWinSpan').html(game.pointsToWin);
$('#maxPlayersSpan').html(game.maxPlayers);
$('.gameInfoInput').hide();
$('#changeGamePointsToWin a').html('');
$('#changeGamePointsToWin').append('(<a href="#changeGamePointsToWin" onclick="editGameInfo()">edit</a>)');
$('.gameInfoSpan').show();
}
function createGame() {
parameters = {};
for (var i in game.items) {
if (game.items[i] != null) {
item = game.items[i];
if (item instanceof Question) {
parameters['type_' + item.id] = 'QUE';
}
else if (item instanceof Bonus) {
parameters['type_' + item.id] = 'BON';
parameters['questionId_' + item.id] = item.associatedQuestion.id;
}
else {
parameters['type_' + item.id] = 'COI';
}
parameters['itemId_' + item.id] = item.id;
parameters['itemLatitude_' + item.id] = (item.marker.position.lat()*1000000).toFixed(0);
parameters['itemLongitude_' + item.id] = (item.marker.position.lng()*1000000).toFixed(0);
parameters['itemPoints_' + item.id] = item.points;
}
}
parameters['city'] = game.city;
parameters['latitude'] = (game.latitude*1000000).toFixed(0);
parameters['longitude'] = (game.longitude*1000000).toFixed(0);
parameters['maxPlayers'] = game.maxPlayers;
parameters['pointsToWin'] = game.pointsToWin;
parameters['numberOfItems'] = game.getItems().length;
$.ajax({
url : createURL,
type : 'POST',
data : parameters,
success: parseResult
});
}
function parseResult(data) {
window.location = viewURL + data;
} | JavaScript |
var map;
var game;
var image1Id = 2130837508;
var image2Id = 2130837508;
var image3Id = 2130837514;
/**
* Extending the Game Object
*
*/
function Player(login, points, imageId, numberOfItems, marker) {
this.login = login;
this.points = points;
this.imageId = imageId;
this.numberOfItems = numberOfItems;
this.marker = marker;
}
function Message(id, senderLogin, receiverLogin, messageBody) {
this.id = id;
this.senderLogin = senderLogin;
this.receiverLogin = receiverLogin;
this.messageBody = messageBody;
}
Game.prototype.players = new Array();
Game.prototype.getPlayer = function(login) {
$.each(game.players, function(n, player) {
if (player.login == login) {
return player;
}
});
};
var messageWindow;
/**
* Paths to item images
*/
var coinImage = '${COIN_IMG}';
var face1Image = '${FACE1_IMG}';
var face2Image = '${FACE2_IMG}';
var face3Image = '${FACE3_IMG}';
var questionImage = '${QUESTION_IMG}';
var bonusImage = '${BONUS_IMG}';
var latitude = '${LATITUDE}';
var longitude = '${LONGITUDE}';
var period = '${PERIOD}';
var watchURL = '${WATCH_URL}';
var messageWindows = new Array();
$(document).ready(function() {
/**
* Map initialization
*/
var latlng = new google.maps.LatLng(latitude/1000000, longitude/1000000);
var myOptions = {
zoom: 12,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: true,
navigationControl: true,
navigationControlOptions: {
style: google.maps.NavigationControlStyle.ZOOM_PAN,
position: google.maps.ControlPosition.LEFT
},
}
map = new google.maps.Map(document.getElementById('mapCanvas'), myOptions);
google.maps.event.addListener(map, 'click', function(event) {
doOnClick(event);
});
game = new Game();
aId = ${gameId};
cycle();
});
function cycle() {
$.ajax({
url : watchURL + aId,
type : 'GET',
dataType: "xml",
success: parseResponse
});
setTimeout(cycle, period);
}
function parseResponse(xml) {
removeItems();
removePlayers();
removeInfoWindows();
$(xml).find("item").each(function() {
id = $(this).find("itemId").text();
latitude = $(this).find("latitude").text();
longitude = $(this).find("longitude").text();
points = $(this).find("points").text();
type = $(this).find("type").text();
latLng = new google.maps.LatLng(latitude * 0.000001, longitude * 0.000001, true);
marker = placeMarker(latLng, type == 'COI' ? coinImage : (type == 'QUE' ? questionImage : bonusImage));
item = new Coin(id, points, marker);
game.items[game.items.length] = item;
game.items.length++;
});
$(xml).find("inGamePlayerInfo").each(function() {
login = $(this).find("login").text();
latitude = $(this).find("latitude").text();
longitude = $(this).find("longitude").text();
points = $(this).find("points").text();
numberOfItems = $(this).find("numberOfItems").text();
imageId = $(this).find("imageId").text();
latLng = new google.maps.LatLng(latitude * 0.000001, longitude * 0.000001, true);
marker = placeMarker(latLng, imageId == image1Id ? face1Image : imageId == image2Id ? face2Image : face3Image);
var player = new Player(login, points, imageId, numberOfItems, marker);
game.players[game.players.length] = player;
game.players.length++;
});
$(xml).find("message").each(function() {
id = $(this).find("messageId").text();
sender = $(this).find("senderLogin").text();
receiver = $(this).find("receiverLogin").text();
messageBody = $(this).find("body").text();
player = getPlayer(sender);
messageWindow = new google.maps.InfoWindow({
disableAutoPan : true
});
messageWindow.setContent(getMessageContentHtml(receiver, messageBody));
messageWindow.open(map, player.marker);
messageWindows[messageWindows.length] = messageWindow;
messageWindows.length++;
});
$(xml).find("gameInfo").each(function() {
city = $(this).find("city").text();
pointsToWin = $(this).find("pointsToWin").text();
maxPlayers = $(this).find("maxPlayers").text();
$('#citySpan').text(city);
$('#pointsToWinSpan').text(pointsToWin);
$('#activePlayersSpan').text(getNumberOfPlayers());
$('#maxPlayersSpan').text(maxPlayers);
});
updateRanking();
}
function updateRanking() {
$('.rankingTableRow').remove();
game.players.sort(function(a, b) {
var compA = a.points;
var compB = b.points;
return (compA < compB) ? -1 : (compA > compB) ? 1 : 0;
});
$.each(game.players, function(idx, player) {
if (player != null) {
$('#rankingTable').append(
'<tr class="rankingTableRow" id="row_' + player.login + '">' +
getPlayerRankingRowContentHtml(player) + '</tr>');
}
});
}
function getPlayerRankingRowContentHtml(player) {
return '<td>' + player.login + '<div class="itemIcon"><img src="' + player.marker.icon +'"/></div></td>' +
'<td>' + player.numberOfItems + '</td>' +
'<td>' + player.points + '</td>';
}
function removeNonPresentItems(presentItemIds) {
}
function getMessageContentHtml(receiverLogin, messageBody) {
result = '<div class="messageReceiver">To <span class="login" >' + receiverLogin + '</span> : </div>';
result = result + '<span class="messageBody">' + messageBody + '</span>';
return result;
}
function getPlayer(login) {
for (var i in game.players) {
if (game.players[i] != null && game.players[i].login == login) {
return game.players[i];
}
}
return null;
}
function getNumberOfPlayers() {
var result = 0;
for (var i in game.players) {
if (game.players[i] != null) {
result++;
}
}
return result;
}
function getItem(id) {
for (var i in game.items) {
if (game.items[i] != null && game.items[i].id == id) {
return game.items[i];
}
}
return null;
}
function removeInfoWindows() {
for (var i in messageWindows) {
if (messageWindows[i] != null) {
messageWindows[i].close();
messageWindows[i] = null;
}
}
messageWindows.length = 0;
}
function removePlayers() {
for (var i in game.players) {
game.players[i].marker.setMap(null);
game.players[i].marker = null;
game.players[i] = null;
}
game.players.length = 0;
}
function removeItems() {
for (var i in game.items) {
game.items[i].marker.setMap(null);
game.items[i].marker = null;
game.items[i] = null;
}
game.items.length = 0;
}
function updatePlayer(login, points, numberOfItems, marker) {
player = game.getPlayer(login);
player.points = points;
player.numberOfItems = numberOfItems;
player.marker = marker;
}
function doOnClick(event) {
}
function placeMarker(position, image) {
var marker = new google.maps.Marker({
position : position,
draggable : false,
map : map,
clickable : true,
icon : image,
});
google.maps.event.addListener(marker, 'click', function() {
});
return marker;
}
| JavaScript |
var T={"All":"Все",
"AlreadyExists":"Уже существует",
"Append":"Добавить",
"Battery":"Аккумулятор",
"Cancel":"Отмена",
"CanvasNotSupported":"Ваш браузер не поддерживает тега canvas",
"Charging":"Зарядка",
"Close":"Закрыть",
"CmdNote":"Внимание к типу команд <code>top</code>. Они могут длиться долгое время. ;-)",
"Cold":"Холодный",
"Command":"Команда",
"Confirm":"Подтвердить",
"ContactName":"Имя контакта",
"Contacts":"Контакты",
"Continue":"Продолжить",
"CPU":"Процессор",
"Create":"Создать",
"Discharging":"Разрядка",
"Dead":"Мертвый",
"Delete":"Удалить",
"Deleted":"Удален",
"DeletingFilesFrom":"Удаление файлов из ",
"Destination":"Цель",
"Details":"Подробнее",
"DoYouWantToDeleteTheContact":"Вы хотите удалить контакт?",
"DoYouWantToSaveTheContactsDetails":"Вы хотите сохранить контакт?",
"Edit":"Изменить",
"EMail":"Э-почта",
"Empty":"Пустой",
"EnterTheFoldersName":"Введите имя каталога",
"Events":"События",
"ExternalStorage":"Внешняя память",
"Failed":"Не удалось",
"files":"файлы",
"FilterProcess":"Фильтр",
"Finished":"Завершено",
"FM_Append":"-- Лечить существующих файлов неполных (завершить загрузку).",
"FM_NoSlicing":"Браузер не поддерживает фрагментацию файлов - продолжать? (Хорошо, если файл не является огромной)",
"FM_OverHead":"Некоторые файлы уже существуют на устройстве.",
"FM_Replace":"-- Заменять существующие файлы.",
"FM_Skip":"-- Не прикасаться существующим файлам.",
"Failure":"Ошибка",
"Files":"Файлы",
"Free":"Свободно",
"Full":"Заряженный",
"Good":"Хорошо",
"Group":"Группа",
"Health":"Состояние",
"Idle":"Холостой",
"ImplicitPassword":"Пароль по умолчанию",
"ImplicitPasswordExplaination":"Вы пользуетесь пароль по умолчанию. Каждый может подключиться к устройству. Пожалуйста, измените пароль в приложении",
"ImplicitPasswordWarning":"Установите пароль для устройства",
"Info":"Система",
"InternalStorage":"Внутренняя память",
"Invert":"Инверсия",
"ItemsToDelete":"Файлы для удаления: ",
"IO":"В/в",
"ItDot":"Эл.",
"LevelDot":"У.",
"Logcat":"Журнал",
"Message":"Сообщение",
"Name":"Имя",
"NewContact":"Новый",
"NewContactSelectGroup":"Выберите группу для нового контакта.",
"NewFolder":"Новый",
"Nick":"Прозвище",
"No":"Нет",
"NoSlicing":"Невозможно загрузить постепенно",
"Note":"Примечание",
"OK":"OK",
"Overheat":"Перегрев",
"Overvoltage":"Перенапр.",
"OverwriteFiles":"Заменить файлы",
"PasswordRequested":"Требуется пароль",
"Pause":"Пауза",
"Phone":"Телефон",
"Postal":"Почтовый",
"Process":"Процесс",
"Question":"Вопрос",
"RAM":"Системная память",
"Replace":"Заменить",
"Resume":"Продолжить",
"Revert":"Отменить",
"Save":"Сохранить",
"SelectFilesToUpload":"Выберите файлы для загрузки",
"SIP":"SIP",
"Skip":"Пропускать",
"SureQ":"Конечно?",
"Status":"Состояние",
"System":"Система",
"Tag":"Тег",
"Tasks":"Задачи",
"Temp":"Темп.",
"Time":"Время",
"Total":"Всего",
"Unknown":"???",
"Upload":"Загрузить",
"Uploading":"Загрузка",
"Update":"Обновить",
"User":"Пользователь",
"Voltage":"Напряжение",
"WaitDots":"Секундочку ...",
"WorkingDots":"Работаю ...",
"Yes":"Да"};
| JavaScript |
var fm_uploader;
function fm_uploadFiles(_dir, _input) {
files = _input.files;
_input.files = null;
if (files != null && files.length > 0) {
fm_uploader = new fm_Uploader(_dir, files);
setTimeout("fm_uploader.goBaby();", 10);
}
}
function fm_Uploader(_dir, _fileList) {
this.MAX_SLICE = 2048 * 1024;
this.MIN_SLICE = 2048;
this.SLICING_NONE = 1;
this.SLICING_WEBKIT = 2;
this.SLICING_MOZ = 3;
this.SLICING_PURE = 4
this.REPLACE = 1;
this.APPEND = 2;
this.SKIP = 3;
this.appendMode = 0;
this.slice;
this.fileIndex = 0;
this.sliceStart;
this.fileList = _fileList;
this.dir = _dir;
this.fileName;
this.fileSize;
this.fileUploaded;
this.file;
this.totalSize = 0;
this.totalUploaded = 0;
this.taskProgress;
this.errors = 0;
this.blob;
this.xhr;
this.slicing;
this.existings = new Array();
this.anyExistings = false;
this.adler32 = new Adler32();
this.sentTime = 0;
this.goBaby = function() {
var req = new XMLHttpRequest();
req.onreadystatechange = function() {
if (req.readyState == 4 && req.status == 200) {
addPing(new Date().getTime() - req.uploader.sentTime);
var lsDir = main_readJSONResponse(req);
var list = lsDir.ls;
for ( var item in list) {
var existing = list[item];
var index = existing.path.lastIndexOf("/");
var name = existing.path.substring(index + 1);
req.uploader.existings[name] = existing;
for ( var i = 0; i < req.uploader.fileList.length; i++) {
if (req.uploader.existings[req.uploader.fileList[i].name]) {
req.uploader.anyExistings = true;
} else {
req.uploader.existings[req.uploader.fileList[i].name] = null;
}
}
}
if (req.uploader.anyExistings) {
popup_show('Overwrite menu', fm_popupOverwrite,
'fm_overwrite');
} else {
fm_append = false;
req.uploader.startUpload();
}
}
}
req.uploader = this;
main_encryptReq(req, "fm", this.dir);
this.sentTime = new Date().getTime();
}
this.startReplace = function() {
this.appendMode = this.REPLACE;
this.startUpload();
}
this.startAppend = function() {
this.appendMode = this.APPEND;
this.startUpload();
}
this.startSkip = function() {
this.appendMode = this.SKIP;
this.startUpload();
}
this.startUpload = function() {
popup_hide('fm_overwrite');
for ( var i = 0; i < this.fileList.length; i++) {
this.totalSize += this.fileList[i].size;
}
var barCount = (this.fileList.length > 1) ? 2 : 1;
var title = "";
if (this.fileList.length > 1) {
title = _T("Uploading") + ": " + this.fileList.length + " " + _T("files")
+ ". " + _T("Destination") + ": " + this.dir;
} else {
title = _T("Uploading") + ": " + this.fileList[0].name + ". "
+ _T("Destination") + ": " + this.dir;
}
// FIXME THERE
this.taskProgress = new tasks_Task(title, barCount);
this.xhr = new XMLHttpRequest();
this.xhr.timeout = 30000;
this.xhr.addEventListener("timeout", this.handleTimeout, false);
this.xhr.addEventListener("load", this.handleLoad, false);
this.xhr.addEventListener("error", this.handleError, false);
this.xhr.addEventListener("abort", this.handleAbort, false);
this.xhr.uploader = this;
// HTML5 uniformity example ;-)
var testFile = this.fileList[0];
//testFile=new Object();
if (testFile.slice) {
this.slicing = this.SLICING_PURE;
} else if (testFile.webkitSlice) {
this.slicing = this.SLICING_WEBKIT;
} else if (testFile.mozSlice) {
this.slicing = this.SLICING_MOZ;
} else {
this.slicing = this.SLICING_NONE;
popup_show(_T("NoSlicing"), fm_popupNoSlicing,
'fm_noSlicingPopup', "20em");
}
this.uploadFile();
};
this.uploadFile = function() {
if (this.fileIndex < this.fileList.length) {
this.file = this.fileList[this.fileIndex];
this.fileName = this.dir + "/" + this.file.name;
this.fileSize = this.file.size;
this.sliceStart = 0;
this.fileUploaded = 0;
if ((this.appendMode != this.REPLACE) && this.anyExistings) {
if (this.existings[this.file.name] != null) {
if (this.appendMode == this.APPEND) {
this.sliceStart = this.existings[this.file.name].size;
} else {// SKIP
this.sliceStart = this.fileSize;
}
this.totalUploaded += this.sliceStart;
this.fileUploaded = this.sliceStart;
}
}
if (this.fileUploaded < this.fileSize) {
if (this.slicing != this.SLICING_NONE) {
this.slice = this.fileSize / 10;
this.slice = Math.min(this.MAX_SLICE, Math.max(
this.MIN_SLICE, this.slice));
this.nextSlice();
} else {
var p_file = "?file=" + this.fileName;
var p_position = "&position=0";
var p_adlerA = "&adlerA=-1";
var p_adlerB = "&adlerB=-1";
this.xhr.open("post", "/fm_clearupload" + p_file
+ p_position + p_adlerA + p_adlerB, true);
this.blob = this.file
this.xhr.send(this.blob);
}
} else {
this.taskProgress
.update([ [ this.fileSize, this.fileUploaded ],
[ this.totalSize, this.totalUploaded ] ],
this.fileName);
this.fileIndex++;
this.uploadFile();
}
} else {
this.taskProgress.update([ [ this.fileSize, this.fileUploaded ],
[ this.totalSize, this.totalUploaded ] ],
"<span style=\"color:#99ff99;\">" + _T("Finished") + "</span>");
}
};
this.nextSlice = function() {
// HTML5 uniformity example ;-)
if (this.slicing == this.SLICING_PURE) {
this.blob = this.file.slice(this.sliceStart, this.sliceStart
+ this.slice);
} else if (this.slicing == this.SLICING_WEBKIT) {
this.blob = this.file.webkitSlice(this.sliceStart, this.sliceStart
+ this.slice);
} else if (this.slicing == this.SLICING_MOZ) {
this.blob = this.file.mozSlice(this.sliceStart, this.sliceStart
+ this.slice);
}
var reader = new FileReader();
reader.uploader = this;
reader.onloadend = function() {
var ui8ArrayView = new Uint8Array(this.result);
this.uploader.sendSlice(ui8ArrayView);
};
reader.readAsArrayBuffer(this.blob);
}
this.sendSlice = function(_arrayView) {
this.adler32.reset();
this.adler32.update(_arrayView);
/*
* var data=new Object(); data.filename=this.fileName;
* data.position=this.sliceStart; data.adlerA=this.adler32.getValueA();
* data.adlerB=this.adler32.getValueB(); data.data=this.blob;
*/
var p_file = "?file=" + this.fileName;
var p_position = "&position=" + this.sliceStart;
var p_adlerA = "&adlerA=" + this.adler32.getValueA();
var p_adlerB = "&adlerB=" + this.adler32.getValueB();
this.xhr.open("post", "/fm_clearupload" + p_file + p_position
+ p_adlerA + p_adlerB, true);
// alert(debugObject(this.blob));
this.xhr.send(this.blob);
// main_encryptReq(xhr,"fm_upload",data);
}
this.handleLoad = function() {
var uploader = this.uploader;
var fileInfo = main_readJSONResponse(uploader.xhr);
uploader.totalUploaded+=fileInfo.file.size-uploader.fileUploaded;
//alert(uploader.totalUploaded);
uploader.fileUploaded = fileInfo.file.size;
uploader.sliceStart = uploader.fileUploaded;
uploader.blob = null;
uploader.taskProgress.update([
[ uploader.fileSize, uploader.fileUploaded ],
[ uploader.totalSize, uploader.totalUploaded ] ],
uploader.fileName);
if (fm_requiredPath == uploader.dir) {
fm_innerLs(fm_requiredPath);
}
if (uploader.sliceStart < uploader.fileSize) {
uploader.nextSlice();
} else {
uploader.fileIndex++;
uploader.uploadFile();
}
};
this.handleError = function() {
var uploader = this.uploader;
uploader.blob = null;
uploader.errors++;
// uploader.fileInfo = eval("(" + this.responseText + ")");
uploader.taskProgress.update([
[ uploader.fileSize, uploader.fileUploaded ],
[ uploader.totalSize, uploader.totalUploaded ] ],
"<span style=\"color:#ff9999;\">" + uploader.fileName + " "
+ _T("Failed") + "</span>");
};
this.handleTimeout = this.handleError;
this.handleAbort = this.handleError;
}
| JavaScript |
var contacts_rawDetailsSet = new Array();
var contacts_detailsPopup;
var contacts_confirmedData;
/*
* Container, which creates and holds all the values from the raw contact.
*/
function contacts_RawDetails(_json) {
// alert(debugObject(_json.availGroups));
this.editables = new Array();
this.simpleValue = function(_value) {
var value = document.createElement("input");
value.rawDetails = this;
value.readOnly = true;
value.type = "text";
if (_value != null && _value.trim() != "") {
value.value = _value;
} else {
value.value = _T("Empty");
value.className = "empty";
}
this.editables.push(value);
return value;
}
this.arrayValue = function(_values) {
var values = document.createElement("span");
if (_values != null && _values.length > 0) {
for ( var i = 0; i < _values.length; i++) {
var value = this.simpleValue(_values[i]);
value.isArrayValue = true;
values.appendChild(value);
}
} else {
var value = this.simpleValue("");
value.isArrayValue = true;
values.appendChild(value);
}
return values;
}
this.predefinedValue = function(_values, _definitions) {
definitions = _definitions.slice();
var select = document.createElement("select");
select.multiple = true;
for ( var i = 0; i < definitions.length; i++) {
for ( var j = 0; j < _values.length; j++) {
if (_values[j] == definitions[i]) {
var option = document.createElement("option");
option.textContent = definitions[i];
definitions[i] = null;
option.selected = true;
select.add(option);
}
}
}
for ( var i = 0; i < definitions.length; i++) {
if (definitions[i] != null) {
var option = document.createElement("option");
option.textContent = definitions[i];
select.add(option);
}
}
select.disabled = true;
this.editables.push(select);
return select;
}
this.setEditable = function() {
for ( var i = 0; i < this.editables.length; i++) {
var element = this.editables[i];
if (element.readOnly) {
element.readOnly = false;
element.setAttribute("onfocus", "contacts_startEdit(this);");
element.setAttribute("onblur", "contacts_stopEdit(this);");
}
if (element.disabled) {
element.disabled = false;
}
}
}
this.rawId = _json.idRaw;
this.contactId = _json.idContact;
this.deleted = _json.deleted;
this.photo = document.createElement("img");
this.photo.rawDetails = this;
this.photo.className = "contactPhoto";
if (_json.photo) {
this.photo.setAttribute("src", "data:image/png;base64," + _json.photo);
} else {
this.photo.setAttribute("src", "/none.png");
}
this.accountName = document.createElement("div");
this.accountName.textContent = _json.accountName;
this.accountType = document.createElement("div");
this.accountType.textContent = _json.accountType;
this.name = this.simpleValue(_json.name);
this.nick = this.simpleValue(_json.nick);
this.groups = this.predefinedValue(_json.groups, _json.availGroups);
this.emails = this.arrayValue(_json.emails);
this.phones = this.arrayValue(_json.phones);
this.sips = this.arrayValue(_json.sips);
this.postals = this.arrayValue(_json.postals);
this.events = this.arrayValue(_json.events);
this.note = this.simpleValue(_json.note);
this.getSimpleValue = function(_value) {
if (_value.className == "empty" || _value.value == null
|| _value.value.trim() == "") {
return "";
} else {
return _value.value;
}
}
this.getArrayValues = function(_values) {
var values = new Array();
var sources = _values.getElementsByTagName("input");
for ( var i = 0; i < sources.length; i++) {
var value = this.getSimpleValue(sources[i]);
if (value != null) {
values.push(value);
}
}
return values;
}
this.getPredefinedValues = function(_select) {
var values = new Array();
for ( var i = 0; i < _select.options.length; i++) {
var option = _select.options[i];
if (option.selected) {
values.push(option.textContent);
}
}
return values;
}
this.getValuesJSON = function() {
var result = new Object();
result.name = this.getSimpleValue(this.name);
result.nick = this.getSimpleValue(this.nick);
result.groups = this.getPredefinedValues(this.groups);
result.emails = this.getArrayValues(this.emails);
result.phones = this.getArrayValues(this.phones);
result.sips = this.getArrayValues(this.sips);
result.postals = this.getArrayValues(this.postals);
result.events = this.getArrayValues(this.events);
result.note = this.getSimpleValue(this.note);
return result;
}
}
/*
* Main "public" function
*/
function contacts_showDetails(_rawId) {
contacts_detailsPopup = popup_showWait("contacts_" + _rawId);
var req = new XMLHttpRequest();
req.onreadystatechange = function() {
if (req.readyState == 4) {
if (req.status == 200) {
addPing(new Date().getTime() - contactsReqSent);
details = main_readJSONResponse(req);
if(!details){
return;
}
var detailsDiv = document.createElement("div");
detailsDiv.appendChild(contacts_createRawDetails(details));
contacts_detailsPopup = popup_show(details.name + " - "
+ _T("Details"), detailsDiv, "contacts_" + _rawId);
}
}
};
main_encryptReq(req,"contactdetails",_rawId);
contactsReqSent = new Date().getTime();
}
function contacts_createRawDetails(_json) {
var rawDetails = new contacts_RawDetails(_json);
contacts_rawDetailsSet[_json.idRaw] = rawDetails;
var content = document.createElement("div");
// alert(rawContact.deleted);
if (rawDetails.deleted == "1") {
content.textContent = _T("Deleted");
return content;
}
var header = document.createElement("div");
header.setAttribute("class", "contactHeader");
header.appendChild(rawDetails.photo);
header.appendChild(rawDetails.accountName);
header.appendChild(rawDetails.accountType);
content.appendChild(header);
var table = document.createElement("table");
table.appendChild(contacts_createValueRow(_T("Name"), rawDetails.name));
table.appendChild(contacts_createValueRow(_T("Nick"), rawDetails.nick));
table.appendChild(contacts_createValueRow(_T("Group"), rawDetails.groups));
table.appendChild(contacts_createValueRow(_T("EMail"), rawDetails.emails));
table.appendChild(contacts_createValueRow(_T("Phone"), rawDetails.phones));
table.appendChild(contacts_createValueRow(_T("SIP"), rawDetails.sips));
table.appendChild(contacts_createValueRow(_T("Postal"), rawDetails.postals));
table.appendChild(contacts_createValueRow(_T("Events"), rawDetails.events));
table.appendChild(contacts_createValueRow(_T("Note"), rawDetails.note));
content.appendChild(table);
// Toolbar
var toolbar = document.createElement("div");
toolbar.style.textAlign = "right";
toolbar.appendChild(main_createButton(_T("Revert"), "contacts_showDetails('"
+ rawDetails.rawId + "')"));
toolbar.appendChild(main_createButton(_T("Save"), "contacts_save('"
+ rawDetails.rawId + "')"));
toolbar.appendChild(main_createButton(_T("Edit"), "contacts_edit('"
+ rawDetails.rawId + "')"));
toolbar.appendChild(main_createButton(_T("Delete"), "contacts_delete('"
+ rawDetails.rawId + "')"));
content.appendChild(toolbar);
return content;
}
function contacts_createValueRow(_label, _value) {
var tr = document.createElement("tr");
tr.style.border = "none";
var tdLabel = document.createElement("td");
tdLabel.style.border = "none";
var label = document.createElement("b");
label.textContent = _label + ": ";
tdLabel.appendChild(label);
var tdValue = document.createElement("td");
tdValue.style.border = "none";
tdValue.appendChild(_value);
tr.appendChild(tdLabel);
tr.appendChild(tdValue);
return tr;
}
/*
* Start of interface functions
*/
function contacts_edit(_rawId) {
contacts_rawDetailsSet[_rawId].setEditable();
}
function contacts_startEdit(_element) {
if (_element.className = "empty" && _element.value == _T("Empty")) {
_element.value = "";
}
_element.onkeypress = contacts_onKeyPress;
}
function contacts_stopEdit(_element) {
if (_element.value.trim() == "") {
_element.value = _T("Empty");
_element.className = "empty";
} else {
_element.className = "";
}
_element.onkeypress = null;
}
function contacts_onKeyPress(_event) {
var code = _event.keyCode;
var source = _event.currentTarget;
var rawDetails = source.rawDetails;
switch (code) {
case 13:
if (source.isArrayValue) {
var input = rawDetails.simpleValue("");
source.parentNode.appendChild(input);
rawDetails.setEditable();
} else {
return false;
}
break;
default:
return true;
}
return false;
}
/*
* Operations
*/
function contacts_delete(_rawId) {
contacts_doAction(_T("DoYouWantToDeleteTheContact"),"contactdelete",_rawId, _rawId);
}
function contacts_save(_rawId) {
var rawDetails = contacts_rawDetailsSet[_rawId];
var data=new Object();
data.rawId=_rawId;
data.data=rawDetails.getValuesJSON();
contacts_doAction(_T("DoYouWantToSaveTheContactsDetails"),"contactupdate", data, _rawId);
}
function contacts_doAction(_message, _area, _data, _rawId) {
contacts_confirmedData=new Object();
contacts_confirmedData.area=_area;
contacts_confirmedData.data=_data;
contacts_confirmedData.rawId=_rawId;
var content=document.createElement("div");
content.textContent=_message;
popup_showDialog(_T("Confirm"), content, "contacts_confirmedAction()", "");
}
function contacts_confirmedAction() {
var rawId=contacts_confirmedData.rawId;
popup_showWait("contacts_" + rawId);
var req = new XMLHttpRequest();
req.onreadystatechange = function() {
if (req.readyState == 4) {
if (req.status == 200) {
addPing(new Date().getTime() - contactsReqSent);
// contacts_showDetails(rawId);
contacts_dirty = true;
contacts_read();
popup_hide("contacts_" + rawId);
}
}
};
main_scrollTop=document.documentElement.scrollTop;
main_encryptReq(req,contacts_confirmedData.area,contacts_confirmedData.data);
contactsReqSent = new Date().getTime();
}
| JavaScript |
/*
* Commandline functions
*/
var cmd_sentTime;
var cmd_tab;
var cmd_content;
var cmd_output;
var cmd_command;
var cmd_history = new Array();
var cmd_historyIndex = -1;
function cmd_onKeyPress(event) {
var code = event.keyCode;
switch (code) {
case 9:
break;
case 13:
cmd_send();
break;
case 38:
cmd_displayHistory(1);
break;
case 40:
cmd_displayHistory(-1);
break;
default:
return true;
}
return false;
}
function cmd_displayHistory(_plus) {
var index=cmd_historyIndex+_plus
if (index >= 0 && index < cmd_history.length) {
cmd_command.value = cmd_history[index];
cmd_historyIndex=index;
} else {
if (index < 0) {
cmd_historyIndex=-1;
cmd_command.value = "";
}
}
}
function cmd_init() {
cmd_content = document.getElementById("cmd_content");
cmd_tab = main_createTab("cmd_content", _T("Command"));
main_contents.push(cmd_content);
var note = document.createElement("p");
note.style.fontStyle = "italic";
note.innerHTML = _T("CmdNote");
cmd_output = document.createElement("div");
cmd_command = document.createElement("input");
cmd_command.setAttribute("class", "cmd_command");
cmd_command.onkeypress = cmd_onKeyPress;
var label = document.createElement("div");
label.innerHTML = _T("Command");
cmd_content.appendChild(note);
cmd_content.appendChild(label);
cmd_content.appendChild(cmd_command);
cmd_content.appendChild(cmd_output);
}
function cmd_send() {
cmd_command.disabled = true;
var value = cmd_command.value;
if (cmd_history[0] != value) {
cmd_history.unshift(value);
}
cmd_historyIndex = -1;
cmd_command.value = _T("WaitDots");
var req = new XMLHttpRequest();
req.onreadystatechange = function() {
if (req.readyState == 4) {
cmd_command.disabled = false;
cmd_command.value = "";
addPing(new Date().getTime() - cmd_sentTime);
if (req.status == 200) {
var response=main_readJSONResponse(req);
if(!response){
return;
}
cmd_output.innerHTML = "<pre>" + response.output + "</pre>";
}
}
};
var re=/[ ]+/;
var cmdArray = value.split(re);
main_encryptReq(req,"command",cmdArray);
cmd_sentTime = new Date().getTime();
}
| JavaScript |
var fm_listingTable;
var fm_sentTime;
var fm_pendingListings = 0;
// Fm
var fm_content;
var fm_tab;
var fm_popupOverwrite;
var fm_popupNoSlicing;
var fm_popupFileSelect;
var fm_list;
var fm_legend;
var fm_bThrash;
var fm_bUp;
var fm_bInvert;
var fm_bNew;
var fm_currentList;
var fm_requiredPath;
var ic_folder = new Image();
ic_folder.src = "folder.png";
var ic_file = new Image();
ic_file.src = "file.png";
var selectedColor = "#009900";
var fm_newFolderInput;
/*
* File manager functions
*/
function fm_init() {
fm_content = document.getElementById("fm_content");
fm_tab = main_createTab("fm_content", _T("Files"));
main_contents.push(fm_content);
// Tools
fm_bThrash = main_createTool(_T("Delete"), "fm_deleteSelected();");
fm_bUp = main_createTool(_T("Upload"),
"popup_show('"+_T("SelectFilesToUpload")+"',fm_popupFileSelect,'fm_fileselect')");
fm_bNew = main_createTool(_T("NewFolder"), "fm_newFolder()");
fm_bInvert = main_createTool(_T("Invert"), "fm_invertSelection();");
// Popup - overwrite
fm_popupOverwrite = document.createElement("p");
var head = document.createElement("p");
head.appendChild(document.createTextNode(_T("FM_OverHead")));
fm_popupOverwrite.appendChild(head);
fm_popupOverwrite.appendChild(fm_createButton(_T("Replace"),
"fm_uploader.startReplace();", _T("FM_Replace")));
fm_popupOverwrite.appendChild(fm_createButton(_T("Append"),
"fm_uploader.startAppend();", _T("FM_Append")));
fm_popupOverwrite.appendChild(fm_createButton(_T("Skip"),
"fm_uploader.startSkip();", _T("FM_Skip")));
// Popup - no slicing
fm_popupNoSlicing = document.createElement("p");
var head = document.createElement("p");
head.appendChild(document.createTextNode(_T("FM_NoSlicing")));
fm_popupNoSlicing.appendChild(head);
fm_popupNoSlicing.appendChild(main_createButton(_T("Yes"),
"fm_uploader.uploadFile();"));
fm_popupNoSlicing.appendChild(main_createButton(_T("No"),
"popup_hide('fm_noSlicingPopup');"));
// Popup - select files
fm_popupFileSelect = document.createElement("p");
var input = document.createElement("input");
input.type = "file";
input.multiple = "true";
input
.setAttribute("onChange",
"popup_hide('fm_fileselect');fm_uploadFiles(fm_currentList.file.path,this)");
fm_popupFileSelect.appendChild(input);
// Legned and list
fm_legend = document.createElement("div");
fm_list = document.createElement("div");
fm_content.appendChild(fm_legend);
fm_content.appendChild(fm_list);
}
function fm_createButton(_title, _onClick, _desc) {
var p = document.createElement("p");
var button = main_createButton(_title, _onClick);
p.appendChild(button);
p.appendChild(document.createTextNode(_desc));
return p;
}
function fm_onShow() {
main_toolbar.appendChild(fm_bThrash);
main_toolbar.appendChild(fm_bUp);
main_toolbar.appendChild(fm_bNew);
main_toolbar.appendChild(fm_bInvert);
}
function fm_updateFm() {
fm_ls(fm_requiredPath);
}
function fm_ls(_path) {
fm_requiredPath = _path;
fm_innerLs(fm_requiredPath);
return false;
}
function fm_innerLs(_path) {
fm_pendingListings++;
var req = new XMLHttpRequest();
req.onreadystatechange = function() {
if (req.readyState == 4 && req.status == 200) {
addPing(new Date().getTime() - fm_sentTime);
fm_pendingListings--;
if (fm_pendingListings == 0) {
fm_currentList = main_readJSONResponse(req);
if(!fm_currentList){
return;
}
if (fm_currentList.file.path == fm_requiredPath) {
fm_fillFm();
}
}
}
};
main_encryptReq(req,"fm",_path);
fm_sentTime = new Date().getTime();
}
function fm_toggleSelection(_item) {
var path = _item.id;
path = path.substring(2);
row = document.getElementById(path);
if (fm_currentList.ls[path].selected) {
fm_currentList.ls[path].selected = false;
row.style.background = "";
} else {
fm_currentList.ls[path].selected = true;
row.style.background = selectedColor;
}
fm_updateToolbar();
}
/*
* Invert the selection
*/
function fm_invertSelection() {
for (item in fm_currentList.ls) {
fm_currentList.ls[item].selected = !fm_currentList.ls[item].selected;
var element = document.getElementById(item);
if (fm_currentList.ls[item].selected) {
element.style.background = selectedColor;
} else {
element.style.background = "";
}
}
fm_updateToolbar();
}
/*
* Create a new folder
*/
function fm_newFolder() {
var content = document.createElement("div");
var message = document.createElement("div");
message.textContent = _T("EnterTheFoldersName");
content.appendChild(message);
fm_newFolderInput = document.createElement("input");
fm_newFolderInput.value = _T("NewFolder");
content.appendChild(fm_newFolderInput);
popup_showDialog(_T("Confirm"), content, "fm_confirmedNewFolder()", "");
}
function fm_confirmedNewFolder() {
var name = fm_newFolderInput.value;
if (name == null || name.length < 1) {
return;
}
var dir = fm_currentList.file.path;
if (dir == "/") {
dir = "";
}
var path = dir + "/" + name;
for (item in fm_currentList.ls) {
if (fm_currentList.ls[item].path == path) {
alert(path + ": "+ _T("AlreadyExists"));
return;
}
}
var req = new XMLHttpRequest();
req.onreadystatechange = function() {
if (req.readyState == 4 && req.status == 200) {
var report=main_readJSONResponse(req);
if(!report){
return;
}
var path = report.file.path;
var index = path.lastIndexOf("/");
var parent = path.substring(0, index);
if (parent.length < 1) {
parent = "/";
}
if (fm_requiredPath == parent) {
fm_innerLs(fm_requiredPath);
}
}
};
main_encryptReq(x,"fm_mkdir",path);
}
function fm_updateToolbar() {
count = 0;
onlyFiles = true;
onlyDirs = true;
for (item in fm_currentList.ls) {
if (fm_currentList.ls[item].selected) {
count++;
if (fm_currentList.ls[item].isDir) {
onlyFiles = false;
} else {
onlyDirs = false;
}
}
}
fm_bInvert.style.display = "inline-block";
fm_bThrash.style.display = "none";
fm_bUp.style.display = "none";
fm_bNew.style.display = "none";
if (count < 1) {
fm_bNew.style.display = "inline-block";
}
if (count > 0) {
fm_bThrash.style.display = "inline-block";
}
if (count < 2 && onlyDirs) {
fm_bUp.style.display = "inline-block";
}
}
function fm_fillFm() {
var file = fm_currentList.file;
var list = fm_currentList.ls;
fm_legend.innerHTML = file.path;
while (fm_list.firstChild) {
fm_list.removeChild(fm_list.firstChild);
}
fm_listingTable = document.createElement("table");
if (file.path.length > 1) { // Not the '/'
fm_fillFile(file, true);
}
var sortedPaths = new Array();
for (path in list) {
sortedPaths.push(path);
}
sortedPaths.sort();
for ( var i = 0; i < sortedPaths.length; i++) {
fm_fillFile(list[sortedPaths[i]], false);
}
fm_list.appendChild(fm_listingTable);
fm_updateToolbar();
}
function fm_fillFile(_file, _isParent) {
var file = new fm_FmFile(_file);
var fileName = file.name;
var path = file.path;
var trClass = "";
var iconOnclick = "";
var aOnclick = "";
var aClass = "";
var aTarget = "";
var aHref = "";
if (_isParent) {
fileName = " • • ";
path = file.parent;
} else {
iconOnclick = "fm_toggleSelection(this);";
}
if (file.isDir) {
aHref = "#";
aOnclick = "fm_ls('" + path + "');";
aClass = "dir";
aTarget = "_self";
} else {
aHref = "fm" + path;
aClass = "file";
aTarget = "_blank";
}
if (!file.isDir || file.size != _T("Empty")) {
trClass = "fm";
} else {
trClass = "grayed";
}
var tr = document.createElement("tr");
tr.setAttribute("class", trClass);
tr.setAttribute("id", path);
var tdIcon = document.createElement("td");
tdIcon.setAttribute("id", "i_" + path);
tdIcon.setAttribute("onclick", iconOnclick);
tdIcon.setAttribute("class", "icon");
var imgIcon = document.createElement("img");
imgIcon.setAttribute("src", file.icon);
tdIcon.appendChild(imgIcon);
var tdName = document.createElement("td");
tdName.setAttribute("class", "name");
var aName = document.createElement("a");
aName.setAttribute("href", aHref);
aName.setAttribute("onclick", aOnclick+"return false;");
aName.setAttribute("target", aTarget);
aName.setAttribute("class", aClass);
aName.appendChild(document.createTextNode(fileName));
tdName.appendChild(aName);
var tdSize = document.createElement("td");
tdSize.setAttribute("class", "size");
tdSize.appendChild(document.createTextNode(file.size));
tr.appendChild(tdIcon);
tr.appendChild(tdName);
tr.appendChild(tdSize);
fm_listingTable.appendChild(tr);
}
function fm_FmFile(_file) {
this.index = _file.path.lastIndexOf("/");
this.path = _file.path;
this.parent = this.path.substring(0, this.index);
if (this.parent.length < 1) {
this.parent = "/";
}
this.name = this.path.substring(this.index + 1);
this.isDir = _file.isDir;
this.icon = null;
this.size = "???";
if (this.isDir) {
if (_file.size == 0) {
this.size = _T("Empty");
} else {
this.size = _file.size + _T("ItDot");
}
this.icon = "folder.png";
} else {
this.size = new Size(_file.size).string();
var suffix = this.name.substring(this.name.lastIndexOf(".") + 1)
.toLowerCase();
this.icon = fm_mimes[suffix];
if (this.icon == null) {
this.icon = "file.png";
}
}
}
| JavaScript |
/*
* background tasks
*/
var tasks_content;
var tasks_tab;
var tasks_tasks;
function tasks_init() {
tasks_content = document.getElementById("tasks_content");
tasks_tab = main_createTab("tasks_content", _T("Tasks"));
main_contents.push(tasks_content);
tasks_tasks = new Array();
}
function tasks_close(_index) {
tasks_content.removeChild(tasks_tasks[_index].listDiv);
tasks_tasks[_index] = null;
}
function tasks_Task(_name, _count) {
var _index = tasks_tasks.length;
tasks_tasks[_index] = this;
this.listDiv = document.createElement("div");
this.popupDiv = document.createElement("div");
this.fieldset = document.createElement("fieldset");
this.legend = document.createElement("legend");
this.legend.appendChild(document.createTextNode(_name));
this.bClose = document.createElement("div");
this.bClose.setAttribute("style",
"position: absolute; top: 0px; right: 0px;");
this.bClose.className = "button";
this.bClose.title = _T("Close");
this.bClose.setAttribute("onClick", "tasks_close(" + _index + ")");
this.bClose.appendChild(document.createTextNode("X"));
this.room = document.createElement("div");
this.listDesc = document.createElement("div");
this.listDesc.setAttribute("class", "caption");
this.listDesc.setAttribute("align", "right");
this.listDesc.textContent=_T("Unknown");
this.popupDesc = document.createElement("div");
this.popupDesc.setAttribute("class", "caption");
this.popupDesc.setAttribute("align", "right");
this.popupDesc.textContent=_T("Unknown");
this.fieldset.appendChild(this.legend);
this.fieldset.appendChild(this.bClose);
this.listBars = new Array();
this.popupBars = new Array();
for ( var i = 0; i < _count; i++) {
//list bars
var bar = document.createElement("canvas", false);
bar.setAttribute("height", "10px");
bar.setAttribute("width", (contentWidth - 20) + "px");
this.fieldset.appendChild(bar);
this.listBars.push(new ProgressBar(bar));
//popup bars
bar = document.createElement("canvas", false);
bar.setAttribute("height", "10px");
bar.setAttribute("width", (contentWidth - 50) + "px");
this.popupDiv.appendChild(bar);
this.popupBars.push(new ProgressBar(bar));
}
this.fieldset.appendChild(this.listDesc);
this.listDiv.appendChild(this.fieldset);
this.popupDiv.appendChild(this.popupDesc);
tasks_content.insertBefore(this.listDiv, tasks_content.firstChild);
popup_show(_T("WorkingDots"),this.popupDiv,"task_"+_index,(contentWidth-30)+"px");
this.update = function(_progress, _desc) {
this.updateMessage(_desc);
for ( var i = 0; i < this.listBars.length; i++) {
this.listBars[i].draw(_progress[i][0], _progress[i][1]);
}
for ( var i = 0; i < this.popupBars.length; i++) {
this.popupBars[i].draw(_progress[i][0], _progress[i][1]);
}
};
this.updateMessage = function(_desc) {
this.listDesc.innerHTML = _desc;
this.popupDesc.innerHTML = _desc;
};
} | JavaScript |
var T={"All":"Všechny",
"AlreadyExists":"Již existuje",
"Append":"Připojit",
"Battery":"Baterie",
"Cancel":"Storno",
"CanvasNotSupported":"Váš prohlížeč nepodporuje tag canvas",
"Charging":"Nabíjení",
"Close":"Zavřít",
"CmdNote":"Pozor na příkazy typu <code>top</code>. Může trvat dlouho než skončí ;-)",
"Cold":"Chladná",
"Command":"Přikaz",
"Confirm":"Potvrdit",
"ContactName":"Jméno kontaktu",
"Contacts":"Kontakty",
"Continue":"Pokračovat",
"CPU":"Procesor",
"Create":"Vytvořit",
"Discharging":"Vybíjení",
"Dead":"Po smrti",
"Delete":"Smazat",
"Deleted":"Smazáno",
"DeletingFilesFrom":"Odstraňování souborů z ",
"Destination":"Cíl",
"Details":"Detaily",
"DoYouWantToDeleteTheContact":"Přejete si odstranit kontakt?",
"DoYouWantToSaveTheContactsDetails":"Přejete si uložit detaily kontaktu?",
"Edit":"Upravit",
"EMail":"E-mail",
"Empty":"Prázdný",
"EnterTheFoldersName":"Zadejte jméno adresáře",
"Events":"Události",
"ExternalStorage":"Externí úložiště",
"Failed":"Selhalo",
"files":"soubory",
"FilterProcess":"Filtr",
"Finished":"Dokončeno",
"FM_Append":"-- Považovat existující soubory za části nahrávaných (dokončit upload).",
"FM_NoSlicing":"Nahrávání po částech není podporováno - pokračovat? (OK, pokud není soubor obrovský)",
"FM_OverHead":"Některé soubory už na zařízení existují. Co s nimi?",
"FM_Replace":"-- Přepsat existující soubory.",
"FM_Skip":"-- Nedotýkat se existujících souborů.",
"Failure":"Chyba",
"Files":"Soubory",
"Free":"Volno",
"Full":"Nabito",
"Good":"OK",
"Group":"Skupina",
"Health":"Kondice",
"Idle":"Nečinnost",
"ImplicitPassword":"Implicitní heslo",
"ImplicitPasswordExplaination":"Využíváte implicitní heslo. Kdokoliv se může k Vašemu zařízení připojit. Změňte prosím heslo v nastavení aplikace",
"ImplicitPasswordWarning":"Nastavte si heslo na Vašem zařízení",
"Info":"Hlavní",
"InternalStorage":"Interní úložiště",
"Invert":"Invertovat",
"ItemsToDelete":"Položky ke smazání: ",
"IO":"V/V",
"ItDot":"Pol.",
"LevelDot":"L.",
"Logcat":"Logcat",
"Message":"Zpráva",
"Name":"Jméno",
"NewContact":"Nový",
"NewContactSelectGroup":"Vyberte skupinu pro nový kontakt.",
"NewFolder":"Nový",
"Nick":"Přezdívka",
"No":"Ne",
"NoSlicing":"Nelze nahrát postupně",
"Note":"Poznámka",
"OK":"OK",
"Overheat":"Přehřátí",
"Overvoltage":"Přepětí",
"OverwriteFiles":"Přepsat soubory",
"PasswordRequested":"Je vyžadováno heslo",
"Pause":"Pauza",
"Phone":"Telefon",
"Postal":"Poštovní",
"Process":"Proces",
"Question":"Otázka",
"RAM":"Operační paměť",
"Replace":"Přepsat",
"Resume":"Spustit",
"Revert":"Vrátit",
"Save":"Uložit",
"SelectFilesToUpload":"Vyberte soubory k nahrání",
"SIP":"SIP",
"Skip":"Přeskočit",
"SureQ":"Určitě?",
"Status":"Stav",
"System":"Systém",
"Tag":"Tag",
"Tasks":"Úlohy",
"Temp":"Teplota",
"Time":"Čas",
"Total":"Celkem",
"Unknown":"???",
"Upload":"Nahrát",
"Uploading":"Nahrávání",
"Update":"Obnovit",
"User":"Uživatel",
"Voltage":"Napětí",
"WaitDots":"Moment ...",
"WorkingDots":"Pracuji ...",
"Yes":"Ano"};
| JavaScript |
var main_MAXW = 800;
var main_MAXH = 600;
var main_content;
var main_tabsdiv;
var contentWidth;
var notActivated = true;
var autorefresh;
var loadingMsg;
var main_toolbar;
var main_statusLine;
var main_tabs = new Array();
var main_contents = new Array();
var sizeUnits = new Array("B", "KB", "MB", "GB", "TB", "PB");
// Encoding utils
var main_base64;
var main_rc4;
var main_utf8;
// Ping
var pingStatistics;
var vitalInterval;
var pingSum = 0;
var pingCount = 0;
var checkReqSent;
var main_scrollTop=0;
/*
* Init function
*/
function init() {
// Size
contentWidth = Math.min(window.innerWidth, 800) - 20;
main_content = document.getElementById("main_content");
main_tabsbar = document.getElementById("main_tabsbar");
main_toolbar = document.getElementById("main_toolbar");
main_statusLine = document.getElementById("main_statusLine");
main_content.style.width = contentWidth + "px";
loadingMsg = document.getElementById("loading");
main_base64 = new Base64();
main_utf8 = new Utf8();
info_init();
fm_init();
logcat_init();
contacts_init();
cmd_init();
tasks_init();
main_anime();
}
function main_anime(){
main_rc4 = new RC4(login_password);
info_getInfo();
fm_ls("/");
logcat_readLogcat();
login_show();
}
function main_createTab(_content, _title) {
var tab = document.createElement("div");
tab.className = "tool";
tab.setAttribute("onClick", "main_activateTab(" + _content + ",this);");
tab.textContent = _title;
main_tabs.push(tab);
main_tabsbar.appendChild(tab);
return tab;
}
function main_createTool(_title, _onClick) {
var tool = document.createElement("div");
tool.className = "tool";
tool.textContent = _title;
tool.setAttribute("onClick", _onClick);
return tool;
}
function main_createButton(_title, _onclick) {
var button = document.createElement("div");
button.className = "button";
button.setAttribute("onclick", _onclick);
button.textContent = _title;
return button;
}
function main_activateTab(_content, _tab) {
clearInterval(autorefresh);
while (main_toolbar.firstChild) {
main_toolbar.removeChild(main_toolbar.firstChild);
}
for ( var i = 0; i < main_tabs.length; i++) {
main_tabs[i].setAttribute("class", "tool");
main_contents[i].style.display = 'none';
}
_content.style.display = 'block';
_tab.setAttribute("class", "activeTab");
if (_tab == info_tab) {
autorefresh = setInterval(info_getInfo, 2000);
} else if (_tab == logcat_tab) {
logcat_onShow();
autorefresh = setInterval(logcat_readLogcat, 2000);
} else if (_tab == contacts_tab) {
contacts_show();
} else if (_tab == fm_tab) {
fm_onShow();
}
}
function vitalCheck() {
var req = new XMLHttpRequest();
req.onreadystatechange = function() {
if (req.readyState == 4 && req.status == 200) {
addPing(new Date().getTime() - checkReqSent);
}
};
main_encryptReq(req,"vitalCheck");
checkReqSent = new Date().getTime();
}
/*
* Utilities
*/
function debugObject(_object) {
var output = '';
for (property in _object) {
output += property + ': ' + _object[property] + '; ';
}
return output;
}
function niceNumber(_value, _mask) {
return Math.round(_value * _mask) / _mask;
}
function Size(_bytes) {
this.size = _bytes;
this.exp = 0;
while (this.size >= 1024) {
this.size /= 1024;
this.exp++;
}
this.string = function() {
var mask = 10;
if (this.size < 10) {
mask = 100;
}
return niceNumber(this.size, mask) + sizeUnits[this.exp];
};
}
function ProgressBar(_canvas, _theLessTheBetter) {
this.canvas = _canvas;
this.g = this.canvas.getContext("2d");
this.draw = function(_max, _value) {
var div = _value / _max;
if (!_theLessTheBetter) {
div = 1 - div;
}
var red = Math.round(Math.min(255, 510 * div));
var green = Math.round(Math.min(255, 510 - 510 * div));
var fill = this.g.createLinearGradient(0, 0, 0, this.canvas.height);
fill.addColorStop(0, "white");
fill.addColorStop(1, "rgb(" + red + "," + green + ",0)");
this.g.fillStyle = fill;
var width = (this.canvas.width / _max) * _value;
this.g.clearRect(0, 0, this.canvas.width, this.canvas.height);
this.g.fillRect(0, 0, width, this.canvas.height);
};
}
function compareStrings(_s1, _s2) {
if (!_s1) {
return false;
}
if (!_s2) {
return true;
}
var s1 = _s1.toLowerCase();
var s2 = _s2.toLowerCase();
var length = Math.min(s1.length, s2.length);
for ( var i = 0; i < length; i++) {
s1Value = alphabet.indexOf(s1[i]);
s2Value = alphabet.indexOf(s2[i]);
if (s1Value < s2Value) {
return true;
} else if (s2Value < s1Value) {
return false;
}
}
if (s1.length < s2.length) {
return true;
} else {
return false;
}
}
function main_readJSONResponse(_req) {
var text = main_readTextResponse(_req);
if (text != null) {
return eval("(" + text + ")");
}
}
function main_readTextResponse(_req) {
var responseText = _req.responseText;
if (responseText == "login") {
login_login();
return null;
} else {
main_rc4.reset();
var cipher = main_base64.decode(responseText);
var data = main_rc4.proceed(cipher);
var text = main_utf8.decode(data);
return text;
}
return null;
}
function main_encryptReq(_req, _area, _data) {
_req.open("post", "rc4", true);
var data = new Object();
data.password = login_password;
data.area = _area;
if (_data) {
data.data = _data;
}
var dataString = JSON.stringify(data);
var dataArray = main_utf8.encode(dataString);
main_rc4.reset();
var cipher = main_rc4.proceed(dataArray);
var oArrayBuffer = new ArrayBuffer(cipher.length);
var oArray = new Uint8Array(oArrayBuffer);
for ( var i = 0; i < oArray.length; i++) {
oArray[i] = cipher[i];
}
//Really nice
try {
_req.send(oArray);
} catch(_) {
_req.send(oArrayBuffer);
}
}
function main_encryptText(_text) {
var data = main_utf8.encode(_text);
var cipher = main_rc4.proceed(data);
var base64 = main_base64.encode(cipher);
alert("rc4://" + base64);
return "rc4://" + base64;
}
function addPing(_ping) {
clearInterval(vitalInterval);
vitalInterval = setInterval(vitalCheck, 5000);
// pingSum+=_ping;
// pingCount ++;
// pingStatistics.innerHTML="Response delay[ms] (last/avg): "+_ping+" /
// "+Math.round(pingSum/pingCount);
}
function extractNumber(_value, _default) {
var n = parseInt(_value);
return n == null || isNaN(n) ? _default : n;
}
function _T(_key){
var text=T[_key];
if(text){
return text;
}else{
return "'"+_key+"'";
}
} | JavaScript |
/*
* Manipulate with popup windows
*/
var popup_windows = new Array();
var popup_positions = new Array();
var popup_mouseStartX;
var popup_mouseStartY;
var popup_windowStartX;
var popup_windowStartY;
var popup_dragged;
var popup_handle;
var popup_canResize;
var popup_resizing;
var popup_moving;
var popup_dialogActive;
var popup_messageActive;
function popup_Position(_left, _top, _width, _height) {
this.left = _left;
this.top = _top;
this.width = _width;
this.height = _height;
}
function popup_Popup(_title, _content, _id, _width, _height) {
this.setTitle = function(_title) {
this.title.textContent = _title;
this.title.appendChild(this.bClose);
}
this.setContent = function(_content) {
if (this.content != null) {
this.contentArea.removeChild(this.content);
}
this.content = _content;
this.contentArea.appendChild(this.content);
}
this.cropSize = function() {
var width = Math.min(window.innerWidth - 20, this.frame.offsetWidth);
var height = Math.min(window.innerHeight - 20, this.frame.offsetHeight);
this.frame.style.width = width + "px";
this.frame.style.height = height + "px";
return [ width, height ];
}
this.center = function() {
var wh = this.cropSize();
this.frame.style.left = (window.innerWidth - wh[0]) / 2 + "px";
this.frame.style.top = (window.innerHeight - wh[1]) / 2 + "px";
}
this.getPosition = function() {
var left = this.frame.style.left;
var top = this.frame.style.top;
var width = this.frame.style.width;
var height = this.frame.style.height;
return new popup_Position(left, top, width, height);
}
this.place = function() {
if (this.userPosition) {
this.frame.style.left = this.position.left;
this.frame.style.top = this.position.top;
this.frame.style.width = this.position.width;
this.frame.style.height = this.position.height;
} else {
this.frame.style.width = this.width;
this.frame.style.height = this.height;
this.center();
}
}
popup_windows[_id] = this;
this.frame = document.createElement("div");
this.frame.setAttribute("class", "popup");
this.frame.onmousemove = popup_selectHandle;
this.frame.onmousedown = popup_startResize;
this.frame.setAttribute("onMouseOut",
"document.body.style.cursor = 'default';");
this.frame.popup = this;
this.title = document.createElement("div");
this.title.setAttribute("class", "popupTitle");
this.title.setAttribute("onmousedown", "return false;");
this.title.onmousedown = popup_titleDown;
this.bClose = document.createElement("div");
this.bClose.setAttribute("onClick", "popup_hide('" + _id + "')");
this.bClose.setAttribute("onmousedown", "return false;");
this.bClose.textContent = "X";
this.bClose.className = "button";
this.bClose.style.position = "absolute";
this.bClose.style.right = "0.3em";
this.bClose.style.top = "0.3em";
this.bClose.title = _T("Close");
this.frame.appendChild(this.title);
this.contentArea = document.createElement("div");
this.contentArea.className = "popupContent";
this.frame.appendChild(this.contentArea);
this.setTitle(_title);
this.setContent(_content);
this.frame.appendChild(this.contentArea);
this.position = popup_positions[_id];
this.width="auto";
this.height="auto";
if(_width){
this.width=_width;
}
if(_height){
this.height=_height;
}
this.id=_id;
this.userPosition = (this.position);
}
function popup_hide(_id) {
var popup = popup_windows[_id];
if (popup != null) {
if (popup.userPosition) {
popup_positions[_id] = popup.getPosition();
}
document.body.removeChild(popup_windows[_id].frame);
popup_windows[_id] = null;
}
}
function popup_titleDown(_e) {
popup_dragged = _e.currentTarget.parentNode;
popup_windowStartX = popup_dragged.offsetLeft;
popup_windowStartY = popup_dragged.offsetTop;
popup_mouseStartX = _e.clientX;
popup_mouseStartY = _e.clientY;
document.onmousemove = popup_move;
document.onmouseup = popup_mouseUp;
document.body.style.cursor = "move";
popup_moving = true;
return false;
}
function popup_mouseUp(_e) {
document.onmousemove = null;
document.onmouseup = null;
popup_resizing = false;
popup_moving = false;
document.body.style.cursor = "default";
return false;
}
function popup_move(_e) {
popup_dragged.style.left = Math.max(0, popup_windowStartX
+ (_e.clientX - popup_mouseStartX))
+ "px";
popup_dragged.style.top = Math.max(0, popup_windowStartY
+ (_e.clientY - popup_mouseStartY))
+ "px";
popup_dragged.popup.userPosition = true;
return false;
}
function popup_selectHandle(_e) {
if (popup_resizing || popup_moving) {
return;
}
// alert(debugObject(_e.target));
var tolerance = 6;
popup_canResize = false;
var tresholdW = _e.currentTarget.offsetWidth - tolerance;
var tresholdH = _e.currentTarget.offsetHeight - tolerance;
var x = _e.clientX - _e.currentTarget.offsetLeft;
var y = _e.clientY - _e.currentTarget.offsetTop;
if (x > tresholdW && y > tresholdH) {
popup_canResize = true;
document.body.style.cursor = "se-resize";
} else {
document.body.style.cursor = "default";
}
}
function popup_startResize(_e) {
if (popup_canResize) {
popup_resizing = true;
popup_dragged = _e.currentTarget;
var left = popup_dragged.offsetLeft;
var top = popup_dragged.offsetTop;
popup_windowStartW = popup_dragged.offsetWidth;
popup_windowStartH = popup_dragged.offsetHeight;
popup_mouseStartX = _e.clientX;
popup_mouseStartY = _e.clientY;
document.onmousemove = popup_resize;
document.onmouseup = popup_mouseUp;
return false;
}
}
function popup_resize(_e) {
var changeX = _e.clientX - popup_mouseStartX;
var changeY = _e.clientY - popup_mouseStartY;
popup_dragged.style.width = (popup_windowStartW + changeX) + "px";
popup_dragged.style.height = (popup_windowStartH + changeY) + "px";
popup_dragged.popup.userPosition = true;
return false;
}
function popup_show(_title, _content, _id, _width, _height) {
popup_hide(_id);
var popup = new popup_Popup(_title, _content, _id, _width, _height);
document.body.appendChild(popup.frame);
popup.place();
return popup;
}
function popup_showWait(_id) {
var waitDiv = document.createElement("div");
waitDiv.appendChild(loadingMsg);
var popup = popup_show(_T("WaitDots"), waitDiv, _id);
return popup;
}
function popup_showDialog(_title,_content, _yesAction, _noAction, _width, _height) {
if(popup_dialogActive){
return;
}
popup_dialogActive=true;
var toolbar = document.createElement("p");
toolbar.style.textAlign="center";
var bYes = main_createButton(_T("Continue"),
"popup_hide('popup_dialogWindow');popup_dialogActive=false;"
+ _yesAction);
var bNo = main_createButton(_T("Cancel"),
"popup_hide('popup_dialogWindow');popup_dialogActive=false;"
+ _noAction);
toolbar.appendChild(bYes);
toolbar.appendChild(bNo);
var content = document.createElement("div");
content.appendChild(_content);
content.appendChild(toolbar);
var popup = popup_show(_title, content, "popup_dialogWindow", _width, _height);
return popup;
}
function popup_showMessage(_title,_content, _action, _width, _height) {
if(popup_messageActive){
return;
}
popup_messageActive=true;
var toolbar = document.createElement("p");
toolbar.style.textAlign="center";
toolbar.appendChild(main_createButton(_T("OK"),"popup_hide('popup_messageWindow');popup_messageActive=false;"
+_action));
var content = document.createElement("div");
content.appendChild(_content);
content.appendChild(toolbar);
var popup = popup_show(_title, content, "popup_messageWindow", _width, _height);
return popup;
}
| JavaScript |
var logcat_apps;
var logcat_sentTime;
var logcat_knownProcesses = [];
logcat_knownProcesses.all = true;
var logcat_selected = [];
logcat_selected.all = true;
var logcat_lock = false;
var logcat_paused = false;
var logcat_lastRow;
var logcat_content;
var logcat_sFilter;
var logcat_tab;
var logcat_table;
var logcat_bPause;
var logcat_bResume;
var logcat_bFilter;
var logcat_filterDiv;
var logcat_trHead;
var logcat_rowsNum = 0;
var logcat_maxRows = 100;
function logcat_init() {
logcat_content = document.getElementById("logcat_content");
logcat_tab = main_createTab("logcat_content", _T("Logcat"));
main_contents.push(logcat_content);
// Toolbar
logcat_bFilter = main_createTool(_T("FilterProcess"),
"popup_show('Select processes',logcat_filterDiv,'logcat_filterdiv')");
logcat_bPause = main_createTool(_T("Pause"), "logcat_pause();");
logcat_bResume = main_createTool(_T("Resume"), "logcat_resume();");
logcat_bResume.style.display = "none";
// Filter popup
logcat_filterDiv = document.createElement("p");
logcat_sFilter = document.createElement("select");
logcat_sFilter.setAttribute("multiple", true);
logcat_sFilter.setAttribute("onChange", "logcat_setFilter();");
var option = document.createElement("option");
option.setAttribute("value", "all");
option.appendChild(document.createTextNode(_T("All")));
logcat_sFilter.appendChild(option);
logcat_filterDiv.appendChild(logcat_sFilter);
// Table head
logcat_table = document.createElement("table");
logcat_trHead = document.createElement("tr");
var th = document.createElement("th");
th.appendChild(document.createTextNode(_T("LevelDot")));
th.style.width = "1.2em";
logcat_trHead.appendChild(th);
th = document.createElement("th");
th.appendChild(document.createTextNode(_T("Time")));
th.style.width = "8em";
logcat_trHead.appendChild(th);
th = document.createElement("th");
th.appendChild(document.createTextNode(_T("Process")));
logcat_trHead.appendChild(th);
th = document.createElement("th");
th.appendChild(document.createTextNode(_T("Tag")));
logcat_trHead.appendChild(th);
th = document.createElement("th");
th.appendChild(document.createTextNode(_T("Message")));
logcat_trHead.appendChild(th);
logcat_content.appendChild(logcat_table);
}
function logcat_onShow() {
main_toolbar.appendChild(logcat_bFilter);
main_toolbar.appendChild(logcat_bPause);
main_toolbar.appendChild(logcat_bResume);
}
function logcat_readLogcat() {
if (logcat_lock || logcat_paused) {
return;
}
logcat_lock = true;
var req = new XMLHttpRequest();
req.timeout = 5000;
req.onreadystatechange = function() {
if (req.readyState == 4 && req.status == 200 && !logcat_paused) {
if (req.responseText.length < 1) {
return;
}
var response = main_readJSONResponse(req);
if(!response){
return;
}
addPing(new Date().getTime() - logcat_sentTime);
logcat_apps = response.apps;
for (pid in logcat_apps) {
if (!logcat_knownProcesses[logcat_apps[pid]]) {
logcat_knownProcesses[logcat_apps[pid]] = true;
var newProcess = document.createElement("option");
newProcess.setAttribute("value", logcat_apps[pid]);
newProcess.appendChild(document
.createTextNode(logcat_apps[pid]));
logcat_sFilter.appendChild(newProcess);
logcat_sFilter.setAttribute("size", 10);
}
}
logcat_content.removeChild(logcat_table);
logcat_table = document.createElement("table");
logcat_table.appendChild(logcat_trHead);
logcat_lastRow = null;
var logs = response.logs;
if (logs != null) {
logcat_rowsNum = 0;
for ( var i = logs.length - 3; logcat_rowsNum < logcat_maxRows
&& i >= 0; i--) {
if (logs[i].length < 1) {
var header = logs[i + 1].split(" ");
var message = logs[i + 2];
logcat_writeRowDown(header, message);
i -= 2;
}
}
}
logcat_content.appendChild(logcat_table);
}
logcat_lock = false;
};
main_encryptReq(req,"logcat");
logcat_sentTime = new Date().getTime();
}
function logcat_writeRowDown(_header, _message) {
// alert("'"+_header+"' '"+_message+"'");
var time;
var pidPod;
var pid;
var levelTag;
var level;
var tag;
var fieldIndex = 0;
var fieldValue;
for ( var i = 1; i < _header.length; i++) {
fieldValue = _header[i];
if (fieldValue.length > 2) {
// alert(fieldIndex+": "+fieldValue);
switch (fieldIndex) {
case 1:
time = fieldValue;
break;
case 2:
pidPod = fieldValue.split(":");
pid = pidPod[0];
break;
case 3:
levelTag = fieldValue.split("/");
level = levelTag[0];
tag = levelTag[1];
break;
}
fieldIndex++;
}
}
var processNS = logcat_apps[pid];
if (logcat_selected.all || logcat_selected[processNS]) {
var process;
if (processNS) {
process = processNS.substring(processNS.lastIndexOf(".") + 1);
} else {
process = "PID "+ pid;
}
var tr = document.createElement("tr");
tr.className = level;
var tdLevel = document.createElement("td");
tdLevel.appendChild(document.createTextNode(level));
var tdTime = document.createElement("td");
tdTime.appendChild(document.createTextNode(time));
var tdProcess = document.createElement("td");
tdProcess.appendChild(document.createTextNode(process));
tdProcess.title = processNS;
var tdTag = document.createElement("td");
tdTag.appendChild(document.createTextNode(tag));
var tdMessage = document.createElement("td");
tdMessage.appendChild(document.createTextNode(_message));
tr.appendChild(tdLevel);
tr.appendChild(tdTime);
tr.appendChild(tdProcess);
tr.appendChild(tdTag);
tr.appendChild(tdMessage);
logcat_table.appendChild(tr);
logcat_rowsNum++;
}
}
function logcat_setFilter() {
for ( var i = 0; i < logcat_sFilter.length; i++) {
if (logcat_sFilter[i].selected) {
logcat_selected[logcat_sFilter[i].value] = true;
} else {
logcat_selected[logcat_sFilter[i].value] = false;
}
}
}
function logcat_toggleFilter() {
if (logcat_filterDiv.style.display != "block") {
logcat_filterDiv.style.display = "block";
} else {
logcat_filterDiv.style.display = "none";
}
}
function logcat_pause() {
logcat_bResume.style.display = "inline-block";
logcat_bPause.style.display = "none";
logcat_paused = true;
}
function logcat_resume() {
logcat_bPause.style.display = "inline-block";
logcat_bResume.style.display = "none";
logcat_paused = false;
}
| JavaScript |
var info_sentTime;
var info_content;
var info_tab;
var info_model;
var info_cpuUsage;
var info_ramUsage;
var info_intUsage;
var info_extUsage;
var info_battInfo;
var info_battDesc;
function info_init() {
info_tab = main_createTab("info_content",_T("Info"));
info_content = document.getElementById("info_content");
main_contents.push(info_content);
info_model = document.createElement("h3");
info_content.appendChild(info_model);
//CPU
var cpuBars = document.createElement("div");
var cpuCaption=info_createCaption();
info_cpuUsage=new info_CpuUsage(cpuBars,cpuCaption);
info_content.appendChild(info_createFieldset(_T("CPU"),cpuBars,cpuCaption));
//RAM
var ramCanvas = info_createBar();
var ramBar = new ProgressBar(ramCanvas, true);
var ramCaption=info_createCaption();
info_ramUsage = new info_DiskUsage(ramBar, ramCaption);
info_content.appendChild(info_createFieldset(_T("RAM"),ramCanvas,ramCaption));
//Internal
var intCanvas = info_createBar();
var intBar = new ProgressBar(intCanvas, true);
var intCaption=info_createCaption();
info_intUsage = new info_DiskUsage(intBar, intCaption);
info_content.appendChild(info_createFieldset(_T("InternalStorage"),intCanvas,intCaption));
//External
var extCanvas = info_createBar();
var extBar = new ProgressBar(extCanvas, true);
var extCaption=info_createCaption();
info_extUsage = new info_DiskUsage(extBar, extCaption);
info_content.appendChild(info_createFieldset(_T("ExternalStorage"),extCanvas,extCaption));
//Battery
var battCanvas = info_createBar();
var battBar = new ProgressBar(battCanvas, false);
var battCaption=info_createCaption();
info_battUsage = new info_BattInfo(battBar, battCaption);
info_content.appendChild(info_createFieldset(_T("Battery"),battCanvas,battCaption));
}
function info_createCaption(){
var caption=document.createElement("div");
caption.className="caption";
caption.style.textAlign="right";
caption.textContent="...";
return caption;
}
function info_createBar(){
var canvas = document.createElement("canvas");
canvas.setAttribute("height", "10px");
canvas.setAttribute("width", (contentWidth - 20) + "px");
canvas.appendChild(document.createTextNode(_T("CanvasNotSupported")));
return canvas;
}
function info_createFieldset(_title,_bars, _caption){
var fieldset=document.createElement("fieldset");
var legend=document.createElement("legend");
legend.appendChild(document.createTextNode(_title));
fieldset.appendChild(legend);
fieldset.appendChild(_bars);
fieldset.appendChild(_caption);
return fieldset;
}
function info_getInfo() {
var infoReq = new XMLHttpRequest();
infoReq.onreadystatechange = function() {
if (infoReq.readyState == 4 && infoReq.status == 200) {
addPing(new Date().getTime() - info_sentTime);
var info=main_readJSONResponse(infoReq);
if(!info){
return;
}
document.title = info.model;
info_model.innerHTML = info.model;
var stat = info.stat;
info_cpuUsage.update(stat);
info_ramUsage.update(info.ramTotal, info.ramFree);
info_extUsage.update(info.extTotal, info.extFree);
info_intUsage.update(info.intTotal, info.intFree);
info_battUsage.update(info);
if (notActivated) {
notActivated = false;
main_content.removeChild(loadingMsg);
main_activateTab(info_content, info_tab);
}
}
};
main_encryptReq(infoReq,"info");
info_sentTime = new Date().getTime();
}
function info_CpuStat(_cpuInfo) {
this.previous = _cpuInfo;
this.actual = new Array();
this.compute = function(_cpuInfo) {
for ( var key in _cpuInfo) {
if (key != "name") {
this.actual[key] = _cpuInfo[key] / 1 - this.previous[key] / 1;
}
}
this.previous = _cpuInfo;
}
}
function info_CpuUsage(_barsField, _caption){
this.cpuStats=null;
this.cpuBars=null;
this.barsField=_barsField;
this.caption=_caption;
this.update=function(_stat) {
if (this.cpuStats == null) {
this.cpuStats = new Array();
this.cpuBars = new Array();
for ( var i = 0; i < _stat.length; i++) {
var cpuStat = new info_CpuStat(_stat[i]);
this.cpuStats[_stat[i].name] = (cpuStat);
if (_stat[i].name != "cpu") {
var canvas=info_createBar();
this.barsField.appendChild(canvas);
this.cpuBars[_stat[i].name] = new ProgressBar(canvas, true);
}
}
} else {
for ( var i = 0; i < _stat.length; i++) {
var cpuStat = this.cpuStats[_stat[i].name];
cpuStat.compute(_stat[i]);
var actual = cpuStat.actual;
var total = actual.total;
if (_stat[i].name == "cpu") {
var userPercent = Math.round((actual.user / total) * 100);
var systemPercent = Math.round((actual.system / total) * 100);
var ioPercent = Math.round((actual.io / total) * 100);
this.caption.innerHTML = _T("User")+": " + userPercent
+ "%, "+_T("System")+": " + systemPercent + "%, "+_T("IO")+": " + ioPercent
+ "%";
} else {
var usage = actual.user + actual.system + actual.io;
this.cpuBars[_stat[i].name].draw(total, usage);
}
}
}
}
}
function info_DiskUsage(_bar, _label) {
this.bar = _bar;
this.label = _label;
this.totalValue = 0;
this.freeValue = 0;
this.update = function(_total, _free) {
this.dirty = false;
if (this.totalSize == null || this.totalValue != _total) {
this.totalSize = new Size(_total);
this.dirty = true;
}
if (this.freeSize == null || this.freeValue != _free) {
this.freeSize = new Size(_free);
this.dirty = true;
}
if (this.dirty) {
this.occ = _total - _free;
this.bar.draw(_total, this.occ);
this.label.innerHTML = _T("Total")+": " + this.totalSize.string()
+ "; "+_T("Free")+": " + this.freeSize.string();
}
};
}
function info_BattInfo(_bar, _desc) {
this.bar = _bar;
this.desc = _desc;
this.update = function(_info) {
this.bar.draw(_info.battScale, _info.battLevel);
var status = "???";
switch (_info.battStatus) {
case 1:
status = _T("Charging");
break;
case 2:
status = _T("Discharging");
break;
case 3:
status = _T("Full");
break;
case 4:
status = _T("Idle");
break;
}
var health = _T("Unknown");
switch (_info.battHealth) {
case 1:
health = _T("Cold");
break;
case 2:
health = _T("Dead");
break;
case 3:
health = _T("Good");
break;
case 4:
health = _T("Overvoltage");
break;
case 5:
health = _T("Overheat");
break;
case 7:
health = _T("Failure");
break;
}
var voltage = _info.battU;
if (voltage > 1000) {
voltage /= 1000;
}
var temperature = _info.battT;
if (temperature > 100) {
temperature /= 10;
}
this.desc.textContent=_T("Status")+": "+status+"; "+_T("Voltage")+": "+voltage+"V; "+
_T("Health")+": "+health+"; "+_T("Temp")+": "+temperature+"°C "
};
} | JavaScript |
var login_password = "implicit";
var login_input;
var login_lock;
var login_warning;
var login_animationInterval;
var login_popupId="";
function login_show() {
if (login_warning) {
main_statusLine.removeChild(login_warning);
clearInterval(login_animationInterval);
login_warning=null;
}
if (login_password == "implicit") {
login_warning = document.createElement("span");
login_warning.className = "loginWarning";
login_warning.title = _T("ImplicitPasswordWarning");
login_warning.textContent = "!!!!*";
login_warning.setAttribute("onClick","login_popup();");
login_warning.setAttribute("onMouseDown","return false;");
main_statusLine.appendChild(login_warning);
login_animationInterval = setInterval(login_animation, 1000);
}
}
function login_popup(){
var content=document.createElement("div");
var text=document.createElement("div");
text.textContent=_T("ImplicitPasswordExplaination");
content.appendChild(text);
popup_showMessage(_T("ImplicitPassword"),content, "" ,"20em")
}
function login_animation(){
var oldText=login_warning.textContent;
var first=oldText.substring(0,1);
var newText=oldText.substring(1);
login_warning.textContent=newText+first;
}
function login_login() {
if (!login_lock) {
login_lock = true;
login_input = document.createElement("input");
login_input.type = "password";
login_input.onkeypress=login_onKeyPress;
var content = document.createElement("div");
content.appendChild(login_input);
login_popupId=popup_showMessage(_T("PasswordRequested"), content,"login_savePassword();").id;
}
}
function login_onKeyPress(_event) {
var code = _event.keyCode;
switch (code) {
case 13:
login_savePassword();
break;
default:
return true;
}
return false;
}
function login_savePassword() {
login_password = login_input.value;
popup_hide(login_popupId);
login_lock = false;
main_anime();
} | JavaScript |
var contacts_sent;
var contacts_dirty = true;
var contacts_content;
var contacts_tab;
var contacts_bNew;
var contacts_bUpdate;
var contacts_accounts;
var contacts_newGroup;
var contacts_NEWPOPUP="contacts_newPopup";
function contacts_init() {
contacts_content = document.getElementById("contacts_content");
contacts_tab = main_createTab("contacts_content", _T("Contacts"));
main_contents.push(contacts_content);
contacts_bNew = main_createTool(_T("NewContact"), "contacts_newContact();");
contacts_bUpdate = main_createTool(_T("Update"), "contacts_dirty=true;contacts_read();");
}
function contacts_show() {
main_toolbar.appendChild(contacts_bNew);
main_toolbar.appendChild(contacts_bUpdate);
contacts_read();
}
function contacts_read(){
if (contacts_dirty) {
contacts_dirty = false;
contacts_content.innerHTML = _T("WaitDots");
var req = new XMLHttpRequest();
req.onreadystatechange = function() {
if (req.readyState == 4) {
if (req.status == 200) {
addPing(new Date().getTime() - contacts_sent);
contacts = main_readJSONResponse(req);
if(!contacts){
return;
}
contacts_accounts = contacts.accounts;
contacts_writeContacts(contacts.contacts);
window.scrollTo(0,main_scrollTop);
}
}
};
main_encryptReq(req,"contacts");
contacts_sent = new Date().getTime();
}
}
function contacts_writeContacts(_contacts) {
while (contacts_content.firstChild) {
contacts_content.removeChild(contacts_content.firstChild);
}
var table = document.createElement("table")
for ( var i = 0; i < _contacts.length; i++) {
var contact = _contacts[i];
var count = 0;
var tdContact = document.createElement("td");
//var theName = "";
//theName += _contacts.name;
tdContact.textContent = i+1;
for ( var rawContactId in contact.raws) {
count++;
var rawContact = contact.raws[rawContactId];
var trContact = document.createElement("tr");
if (count == 1) {
trContact.appendChild(tdContact);
}
// Name
var tdName = document.createElement("td");
var name = "";
if (rawContact.nick != null && rawContact.nick != "") {
name = "'" + rawContact.nick + "' ";
}
name += rawContact.name;
tdName.innerHTML = "<a class=\"file\" href=\"#\" onclick=\"contacts_showDetails('"
+ rawContactId + "'); return false;\">"+name+"</a>";
trContact.appendChild(tdName);
// Emails
var tdEmails = document.createElement("td");
contacts_arrayToDivs(tdEmails, rawContact.emails);
trContact.appendChild(tdEmails);
// Phones
var tdPhones = document.createElement("td");
contacts_arrayToDivs(tdPhones, rawContact.phones);
trContact.appendChild(tdPhones);
// alert(debugObject(trContact));
table.appendChild(trContact);
}
tdContact.setAttribute("rowspan", count);
}
contacts_content.appendChild(table);
}
function contacts_arrayToDivs(_parent, _array) {
if (_array) {
for ( var i = 0; i < _array.length; i++) {
var div = document.createElement("div");
div.appendChild(document.createTextNode(_array[i]));
_parent.appendChild(div);
}
}
}
function contacts_newContact() {
var content = document.createElement("div");
var textDiv=document.createElement("div");
textDiv.textContent=_T("NewContactSelectGroup");
content.appendChild(textDiv);
contacts_newGroup = document.createElement("select");
contacts_newGroup.multiple = false;
var preffered = 0;
for ( var i = 0; i < contacts_accounts.length; i++) {
var acc = contacts_accounts[i];
if ((acc.type = "com.google") && (acc.name.indexOf("@")>0)) {
preffered = i;
var option = document.createElement("option");
option.textContent = acc.name + " / " + acc.type;
option.selected = true;
contacts_newGroup.add(option);
break;
}
}
for ( var i = 0; i < contacts_accounts.length; i++) {
if (i != preffered) {
var acc = contacts_accounts[i];
var option = document.createElement("option");
option.textContent = acc.name + " / " + acc.type;
contacts_newGroup.add(option);
}
}
var selectDiv=document.createElement("div");
selectDiv.appendChild(contacts_newGroup);
content.appendChild(selectDiv);
// Toolbar
var toolbar = document.createElement("div");
toolbar.style.textAlign = "right";
toolbar.appendChild(main_createButton(_T("Create"),
"contacts_newContactCreate()"));
toolbar.appendChild(main_createButton(_T("Cancel"),
"popup_hide('"+contacts_NEWPOPUP+"')"));
content.appendChild(toolbar);
var popup=popup_show(_T("NewContact"),content,contacts_NEWPOPUP);
popup.frame.style.width=(selectDiv.offsetWidth+20)+"px";
}
function contacts_newContactCreate(){
main_scrollTop=document.documentElement.scrollTop;
var req = new XMLHttpRequest();
req.onreadystatechange = function() {
if (req.readyState == 4) {
if (req.status == 200) {
addPing(new Date().getTime() - contactsReqSent);
response = main_readJSONResponse(req);
if(!response){
return;
}
popup_hide(contacts_NEWPOPUP);
contacts_showDetails(response.rawId);
contacts_dirty = true;
contacts_read();
}
}
};
var acc=contacts_newGroup.options[contacts_newGroup.selectedIndex].textContent.split(" / ");
var spec=new Object();
spec.name=acc[0];
spec.type=acc[1];
main_encryptReq(req,"contactcreate",spec);
contactsReqSent = new Date().getTime();
} | JavaScript |
var fm_deleter;
var fm_filesToDelete;
function fm_deleteSelected() {
fm_filesToDelete = new Array();
for (item in fm_currentList.ls) {
if (fm_currentList.ls[item].selected) {
fm_filesToDelete.push(fm_currentList.ls[item].path);
}
}
var content = document.createElement("div");
content.textContent = _T("ItemsToDelete") + fm_filesToDelete.length + ". " + _T("SureQ");
popup_showDialog(_T("Confirm"), content, "fm_confirmedDelete()", "");
}
function fm_confirmedDelete() {
fm_deleter = new fm_Deleter(fm_currentList.file.path, fm_filesToDelete);
setTimeout("fm_deleter.goBaby();", 100);
}
function fm_Deleter(_dir, _fileList) {
this.fileList = _fileList;
this.dir = _dir;
this.fileName;
this.total = this.fileList.length;
this.taskProgress;
this.xhr;
this.goBaby = function() {
var title = _T("DeletingFilesFrom") + fm_currentList.file.path;
this.taskProgress = new tasks_Task(title, 1);
this.xhr = new XMLHttpRequest();
// xhr.addEventListener("progress", handleProgress, false);
this.xhr.addEventListener("load", this.handleLoad, false);
this.xhr.addEventListener("error", this.handleError, false);
this.xhr.addEventListener("abort", this.handleAbort, false);
this.xhr.deleter = this;
main_encryptReq(this.xhr,"fm_delete",this.fileList);
};
this.handleLoad = function(_e) {
var deleter = this.deleter;
var report = main_readJSONResponse(this);
if(!report){
return;
}
var message = _T("Finished");
if (report.errors > 0) {
message = _T("Failed");
alert(report.message);
}
deleter.taskProgress.update(
[ [ deleter.fileList.length, report.deleted ] ], message);
if (fm_requiredPath == deleter.dir) {
fm_innerLs(fm_requiredPath);
}
};
this.handleError = function(_e) {
var deleter = this.deleter;
deleter.taskProgress.update([ [ 2, 0 ] ], _T("Failed"));
if (fm_requiredPath == deleter.dir) {
fm_innerLs(fm_requiredPath);
}
};
this.handleAbort = this.handleError;
this.handleTimeout = this.handleError;
}
| JavaScript |
var T={"All":"All",
"AlreadyExists":"Already exists",
"Append":"Append",
"Battery":"Battery",
"Cancel":"Cancel",
"CanvasNotSupported":"Your browser does not support the HTML5 canvas tag.",
"Charging":"Charging",
"Close":"Close",
"CmdNote":"Beware of neverending commands such as the <code>top</code> is. They can take a lot of time to return ;-)",
"Cold":"Cold",
"Command":"Command",
"Confirm":"Confirm",
"ContactName":"Contact name",
"Contacts":"Contacts",
"Continue":"Continue",
"CPU":"Processor",
"Create":"Create",
"Discharging":"Discharging",
"Dead":"K.O.",
"Delete":"Delete",
"Deleted":"Deleted",
"DeletingFilesFrom":"Deleting files from ",
"Destination":"Destination",
"Details":"Details",
"DoYouWantToDeleteTheContact":"Do you want to delete the contact?",
"DoYouWantToSaveTheContactsDetails":"Do you want to save the contact's details?",
"Edit":"Edit",
"EMail":"E-mail",
"Empty":"Empty",
"EnterTheFoldersName":"Enter the folder's name",
"Events":"Events",
"ExternalStorage":"External storage",
"Failed":"Failed",
"Failure":"Failure",
"files":"files",
"FilterProcess":"Filter",
"Finished":"Finished",
"FM_Append":"-- Treat the existing files as they were a part of the uploaded (complete them).",
"FM_NoSlicing":"File slicing is not supported. Continue? (It's OK, if files are not huge)",
"FM_OverHead":"Some files already exist on the device. What you want to do with them?",
"FM_Replace":"-- Replace the existing files.",
"FM_Skip":"-- Do not touch existing files.",
"Files":"Files",
"Free":"Free",
"Full":"Full",
"Good":"OK",
"Group":"Group",
"Health":"Health",
"Idle":"Idle",
"ImplicitPassword":"Implicit password",
"ImplicitPasswordExplaination":"The apllication uses implicit password, which means, that anybody can connect to your device. Change the password in the android application settings.",
"ImplicitPasswordWarning":"Set the password on your device please",
"Info":"Info",
"InternalStorage":"Internal storage",
"Invert":"Invert",
"ItemsToDelete":"Items to delete: ",
"IO":"I/O",
"ItDot":"It.",
"LevelDot":"L.",
"Logcat":"Logcat",
"Message":"Message",
"Name":"Name",
"NewContact":"Create",
"NewContactSelectGroup":"Select a group for the new contact.",
"NewFolder":"New one",
"Nick":"Nick",
"No":"No",
"NoSlicing":"No slicing",
"Note":"Note",
"OK":"OK",
"Overheat":"Overheat",
"Overvoltage":"Overvoltage",
"OverwriteFiles":"Overwrite files",
"PasswordRequested":"Password requested",
"Pause":"Pause",
"Phone":"Phone",
"Postal":"Postal",
"Process":"Process",
"Question":"Question",
"RAM":"RAM",
"Replace":"Replace",
"Resume":"Resume",
"Revert":"Revert",
"Save":"Save",
"SelectFilesToUpload":"Select files to upload",
"SIP":"SIP",
"Skip":"Skip",
"SureQ":"Sure?",
"Status":"Status",
"System":"System",
"Tag":"Tag",
"Tasks":"Tasks",
"Temp":"Temp.",
"Time":"Time",
"Total":"Total",
"Unknown":"???",
"Upload":"Upload",
"Uploading":"Uploading",
"Update":"Update",
"User":"User",
"Voltage":"Voltage",
"WaitDots":"Wait ...",
"WorkingDots":"Working ...",
"Yes":"Yes"};
| JavaScript |
/*
* RC4, Adler32, Base64 and UTF-8 implementations. Simple and strong ;-)
*/
//RC4 Cipher algorithm
function RC4(_key) {
// Swap function
this.swapS = function(_i, _j) {
temp = this.s[_i];
this.s[_i] = this.s[_j];
this.s[_j] = temp;
}
// Encrypting/decrypting
this.proceed = function(_data) {
var result = new Array();
var i = 0;
var j = 0;
for ( var d = 0; d < _data.length; d++) {
i = (i + 1) % 256;
j = (j + this.s[i]) % 256;
this.swapS(i, j);
result.push(this.s[(this.s[i] + this.s[j]) % 256] ^ _data[d]);
}
return result;
}
this.reset=function(){
this.s=this.initialS.slice();
}
// Constructor - key-scheduling
this.s = new Array();
this.initialS;
var utf8=new Utf8();
this.key=utf8.encode(_key);
for ( var i = 0; i < 256; i++) {
this.s.push(i);
}
var j = 0;
for ( var i = 0; i < 256; i++) {
j = (j + this.s[i] + this.key[i % this.key.length]) % 256;
this.swapS(i, j);
}
this.initialS=this.s.slice();
}
// Adler32 checkusm algorithm
function Adler32() {
this.MOD_ADLER = 65521;
this.a = 1;
this.b = 0;
this.update = function(_data) {
for ( var i = 0; i < _data.length; i++) {
this.a = (this.a + _data[i]) % this.MOD_ADLER;
this.b = (this.b + this.a) % this.MOD_ADLER;
}
}
this.getValueA = function() {
return this.a;
}
this.getValueB = function() {
return this.b;
}
this.reset = function() {
this.a = 1;
this.b = 0;
}
}
// Base64
function Base64() {
this.codes = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
this.decode = function(_base64) {
var i = 0;
var binary = new Array();
if (_base64) {
while (i < _base64.length) {
var value = 0;
var shift = 18;
var number=0;
while (shift >= 0 && i < _base64.length) {
var code = this.codes.indexOf(_base64[i]);
i++;
if(code>=0){
if(code==64){
break;
}
value |= code << shift;
shift -= 6;
number++;
}
}
shift=16;
for(var j=0;j<(number-1);j++){
binary.push((value >> shift) & 0xFF);
shift-=8;
}
}
}
return binary;
}
this.encode = function(_binary) {
var base64 = "";
if (_binary) {
var i = 0;
while (i < _binary.length) {
var shift = 16;
var triplet = 0;
var readNumber = 0;
while (i < _binary.length && shift >= 0) {
triplet |= _binary[i] << shift;
i++;
readNumber++;
shift -= 8;
}
shift = 18;
for ( var j = 0; j <= readNumber; j++) {
var index = (triplet >> shift) & 0x3F;
base64 += this.codes[index];
shift -= 6;
}
for ( var j = 3; j > readNumber; j--) {
base64 += "=";
}
}
return base64;
}
}
}
// Utf8 encoder/decoder
function Utf8() {
this.firstMasks = [ 0, 0, 0x1F, 0xF, 0x7 ];
this.decode = function(_bytes) {
var utf8 = "";
var i = 0;
while (i < _bytes.length) {
if ((_bytes[i] & 0x80) < 1) {
utf8 += String.fromCharCode(_bytes[i]);
} else {
var numOfBytes = 2;
if (_bytes[i] >= 0xF0) {
numOfBytes = 4;
} else if (_bytes[i] >= 0xE0) {
numOfBytes = 3;
}
var shift = (numOfBytes - 1) * 6;
var value = (_bytes[i] & this.firstMasks[numOfBytes]) << shift;
while (shift > 0) {
i++;
shift -= 6;
value |= (_bytes[i] & 0x3F) << shift;
}
utf8 += String.fromCharCode(value);
}
i++;
}
return utf8;
}
this.encode = function(_utf8) {
var bytes = new Array();
for ( var i = 0; i < _utf8.length; i++) {
code = _utf8.charCodeAt(i);
if (code <= 0x7F) {
bytes.push(code);
} else {
var byte = 0xC0;
var numOfBytes = 2;
if (code > 0xFFFF) {
numOfBytes = 4;
byte = 0xF0;
} else if (code > 0x7FF) {
numOfBytes = 3;
byte = 0xE0;
}
shift = (6 * (numOfBytes - 1));
byte |= (code >> shift) & this.firstMasks[numOfBytes];
bytes.push(byte);
while (shift > 0) {
shift -= 6;
bytes.push(0x80 | (code >> shift) & 0x3F);
}
}
}
return bytes;
}
}
| JavaScript |
var fm_mimes=new Array();
fm_mimes['mp3']="ic_audio.png";
fm_mimes['wav']="ic_audio.png";
| JavaScript |
/**
* o------------------------------------------------------------------------------o
* | This file is part of the RGraph package - you can learn more at: |
* | |
* | http://www.rgraph.net |
* | |
* | This package is licensed under the RGraph license. For all kinds of business |
* | purposes there is a small one-time licensing fee to pay and for non |
* | commercial purposes it is free to use. You can read the full license here: |
* | |
* | http://www.rgraph.net/LICENSE.txt |
* o------------------------------------------------------------------------------o
*/
/**
* Initialise the various objects
*/
if (typeof(RGraph) == 'undefined') RGraph = {isRGraph:true,type:'common'};
RGraph.Registry = {};
RGraph.Registry.store = [];
RGraph.Registry.store['chart.event.handlers'] = [];
RGraph.background = {};
RGraph.objects = [];
RGraph.Resizing = {};
RGraph.events = [];
/**
* Returns five values which are used as a nice scale
*
* @param max int The maximum value of the graph
* @param obj object The graph object
* @return array An appropriate scale
*/
RGraph.getScale = function (max, obj)
{
/**
* Special case for 0
*/
if (max == 0) {
return ['0.2', '0.4', '0.6', '0.8', '1.0'];
}
var original_max = max;
/**
* Manually do decimals
*/
if (max <= 1) {
if (max > 0.5) {
return [0.2,0.4,0.6,0.8, Number(1).toFixed(1)];
} else if (max >= 0.1) {
return obj.Get('chart.scale.round') ? [0.2,0.4,0.6,0.8,1] : [0.1,0.2,0.3,0.4,0.5];
} else {
var tmp = max;
var exp = 0;
while (tmp < 1.01) {
exp += 1;
tmp *= 10;
}
var ret = ['2e-' + exp, '4e-' + exp, '6e-' + exp, '8e-' + exp, '10e-' + exp];
if (max <= ('5e-' + exp)) {
ret = ['1e-' + exp, '2e-' + exp, '3e-' + exp, '4e-' + exp, '5e-' + exp];
}
return ret;
}
}
// Take off any decimals
if (String(max).indexOf('.') > 0) {
max = String(max).replace(/\.\d+$/, '');
}
var interval = Math.pow(10, Number(String(Number(max)).length - 1));
var topValue = interval;
while (topValue < max) {
topValue += (interval / 2);
}
// Handles cases where the max is (for example) 50.5
if (Number(original_max) > Number(topValue)) {
topValue += (interval / 2);
}
// Custom if the max is greater than 5 and less than 10
if (max < 10) {
topValue = (Number(original_max) <= 5 ? 5 : 10);
}
/**
* Added 02/11/2010 to create "nicer" scales
*/
if (obj && typeof(obj.Get('chart.scale.round')) == 'boolean' && obj.Get('chart.scale.round')) {
topValue = 10 * interval;
}
return [topValue * 0.2, topValue * 0.4, topValue * 0.6, topValue * 0.8, topValue];
}
/**
* Returns the maximum numeric value which is in an array
*
* @param array arr The array
* @param int Whether to ignore signs (ie negative/positive)
* @return int The maximum value in the array
*/
RGraph.array_max = function (arr)
{
var max = null;
for (var i=0; i<arr.length; ++i) {
if (typeof(arr[i]) == 'number') {
var val = arguments[1] ? Math.abs(arr[i]) : arr[i];
if (typeof(max) == 'number') {
max = Math.max(max, val);
} else {
max = val;
}
}
}
return max;
}
/**
* Returns the maximum value which is in an array
*
* @param array arr The array
* @param int len The length to pad the array to
* @param mixed The value to use to pad the array (optional)
*/
RGraph.array_pad = function (arr, len)
{
if (arr.length < len) {
var val = arguments[2] ? arguments[2] : null;
for (var i=arr.length; i<len; ++i) {
arr[i] = val;
}
}
return arr;
}
/**
* An array sum function
*
* @param array arr The array to calculate the total of
* @return int The summed total of the arrays elements
*/
RGraph.array_sum = function (arr)
{
// Allow integers
if (typeof(arr) == 'number') {
return arr;
}
var i, sum;
var len = arr.length;
for(i=0,sum=0;i<len;sum+=arr[i++]);
return sum;
}
/**
* A simple is_array() function
*
* @param mixed obj The object you want to check
* @return bool Whether the object is an array or not
*/
RGraph.is_array = function (obj)
{
return obj != null && obj.constructor.toString().indexOf('Array') != -1;
}
/**
* Converts degrees to radians
*
* @param int degrees The number of degrees
* @return float The number of radians
*/
RGraph.degrees2Radians = function (degrees)
{
return degrees * (Math.PI / 180);
}
/**
* This function draws an angled line. The angle is cosidered to be clockwise
*
* @param obj ctxt The context object
* @param int x The X position
* @param int y The Y position
* @param int angle The angle in RADIANS
* @param int length The length of the line
*/
RGraph.lineByAngle = function (context, x, y, angle, length)
{
context.arc(x, y, length, angle, angle, false);
context.lineTo(x, y);
context.arc(x, y, length, angle, angle, false);
}
/**
* This is a useful function which is basically a shortcut for drawing left, right, top and bottom alligned text.
*
* @param object context The context
* @param string font The font
* @param int size The size of the text
* @param int x The X coordinate
* @param int y The Y coordinate
* @param string text The text to draw
* @parm string The vertical alignment. Can be null. "center" gives center aligned text, "top" gives top aligned text.
* Anything else produces bottom aligned text. Default is bottom.
* @param string The horizontal alignment. Can be null. "center" gives center aligned text, "right" gives right aligned text.
* Anything else produces left aligned text. Default is left.
* @param bool Whether to show a bounding box around the text. Defaults not to
* @param int The angle that the text should be rotate at (IN DEGREES)
* @param string Background color for the text
* @param bool Whether the text is bold or not
* @param bool Whether the bounding box has a placement indicator
*/
RGraph.Text = function (context, font, size, x, y, text)
{
/**
* This calls the text function recursively to accommodate multi-line text
*/
if (typeof(text) == 'string' && text.match(/\r\n/)) {
var arr = text.split('\r\n');
text = arr[0];
arr = RGraph.array_shift(arr);
var nextline = arr.join('\r\n')
RGraph.Text(context, font, size, arguments[9] == -90 ? (x + (size * 1.5)) : x, y + (size * 1.5), nextline, arguments[6] ? arguments[6] : null, 'center', arguments[8], arguments[9], arguments[10], arguments[11], arguments[12]);
}
// Accommodate MSIE
if (RGraph.isIE8()) {
y += 2;
}
context.font = (arguments[11] ? 'Bold ': '') + size + 'pt ' + font;
var i;
var origX = x;
var origY = y;
var originalFillStyle = context.fillStyle;
var originalLineWidth = context.lineWidth;
// Need these now the angle can be specified, ie defaults for the former two args
if (typeof(arguments[6]) == null) arguments[6] = 'bottom'; // Vertical alignment. Default to bottom/baseline
if (typeof(arguments[7]) == null) arguments[7] = 'left'; // Horizontal alignment. Default to left
if (typeof(arguments[8]) == null) arguments[8] = null; // Show a bounding box. Useful for positioning during development. Defaults to false
if (typeof(arguments[9]) == null) arguments[9] = 0; // Angle (IN DEGREES) that the text should be drawn at. 0 is middle right, and it goes clockwise
if (typeof(arguments[12]) == null) arguments[12] = true; // Whether the bounding box has the placement indicator
// The alignment is recorded here for purposes of Opera compatibility
if (navigator.userAgent.indexOf('Opera') != -1) {
context.canvas.__rgraph_valign__ = arguments[6];
context.canvas.__rgraph_halign__ = arguments[7];
}
// First, translate to x/y coords
context.save();
context.canvas.__rgraph_originalx__ = x;
context.canvas.__rgraph_originaly__ = y;
context.translate(x, y);
x = 0;
y = 0;
// Rotate the canvas if need be
if (arguments[9]) {
context.rotate(arguments[9] / 57.3);
}
// Vertical alignment - defaults to bottom
if (arguments[6]) {
var vAlign = arguments[6];
if (vAlign == 'center') {
context.translate(0, size / 2);
} else if (vAlign == 'top') {
context.translate(0, size);
}
}
// Hoeizontal alignment - defaults to left
if (arguments[7]) {
var hAlign = arguments[7];
var width = context.measureText(text).width;
if (hAlign) {
if (hAlign == 'center') {
context.translate(-1 * (width / 2), 0)
} else if (hAlign == 'right') {
context.translate(-1 * width, 0)
}
}
}
context.fillStyle = originalFillStyle;
/**
* Draw a bounding box if requested
*/
context.save();
context.fillText(text,0,0);
context.lineWidth = 0.5;
if (arguments[8]) {
var width = context.measureText(text).width;
var ieOffset = RGraph.isIE8() ? 2 : 0;
context.translate(x, y);
context.strokeRect(0 - 3, 0 - 3 - size - ieOffset, width + 6, 0 + size + 6);
/**
* If requested, draw a background for the text
*/
if (arguments[10]) {
var offset = 3;
var ieOffset = RGraph.isIE8() ? 2 : 0;
var width = context.measureText(text).width
//context.strokeStyle = 'gray';
context.fillStyle = arguments[10];
context.fillRect(x - offset, y - size - offset - ieOffset, width + (2 * offset), size + (2 * offset));
//context.strokeRect(x - offset, y - size - offset - ieOffset, width + (2 * offset), size + (2 * offset));
}
/**
* Do the actual drawing of the text
*/
context.fillStyle = originalFillStyle;
context.fillText(text,0,0);
if (arguments[12]) {
context.fillRect(
arguments[7] == 'left' ? 0 : (arguments[7] == 'center' ? width / 2 : width ) - 2,
arguments[6] == 'bottom' ? 0 : (arguments[6] == 'center' ? (0 - size) / 2 : 0 - size) - 2,
4,
4
);
}
}
context.restore();
// Reset the lineWidth
context.lineWidth = originalLineWidth;
context.restore();
}
/**
* Clears the canvas by setting the width. You can specify a colour if you wish.
*
* @param object canvas The canvas to clear
*/
RGraph.Clear = function (canvas)
{
var context = canvas.getContext('2d');
/**
* Can now clear the camnvas back to fully transparent
*/
if (arguments[1] && arguments[1] == 'transparent') {
context.fillStyle = 'rgba(0,0,0,0)';
context.globalCompositeOperation = 'source-in';
context = canvas.getContext('2d');
context.beginPath();
context.fillRect(-1000,-1000,canvas.width + 2000,canvas.height + 2000);
context.fill();
// Reset the globalCompositeOperation
context.globalCompositeOperation = 'source-over';
} else {
context.fillStyle = arguments[1] ? String(arguments[1]) : 'white';
context = canvas.getContext('2d');
context.beginPath();
context.fillRect(-100000,-100000,canvas.width + 200000,canvas.height + 200000);
context.fill();
}
// Don't do this as it also clears any translation that may have occurred
//canvas.width = canvas.width;
if (RGraph.ClearAnnotations) {
RGraph.ClearAnnotations(canvas.id);
}
}
/**
* Draws the title of the graph
*
* @param object canvas The canvas object
* @param string text The title to write
* @param integer gutter The size of the gutter
* @param integer The center X point (optional - if not given it will be generated from the canvas width)
* @param integer Size of the text. If not given it will be 14
*/
RGraph.DrawTitle = function (canvas, text, gutter)
{
var obj = canvas.__object__;
var context = canvas.getContext('2d');
var size = arguments[4] ? arguments[4] : 12;
var centerx = (arguments[3] ? arguments[3] : RGraph.GetWidth(obj) / 2);
var keypos = obj.Get('chart.key.position');
var vpos = gutter / 2;
var hpos = obj.Get('chart.title.hpos');
var bgcolor = obj.Get('chart.title.background');
// Account for 3D effect by faking the key position
if (obj.type == 'bar' && obj.Get('chart.variant') == '3d') {
keypos = 'gutter';
}
context.beginPath();
context.fillStyle = obj.Get('chart.text.color') ? obj.Get('chart.text.color') : 'black';
/**
* Vertically center the text if the key is not present
*/
if (keypos && keypos != 'gutter') {
var vCenter = 'center';
} else if (!keypos) {
var vCenter = 'center';
} else {
var vCenter = 'bottom';
}
// if chart.title.vpos does not equal 0.5, use that
if (typeof(obj.Get('chart.title.vpos')) == 'number') {
vpos = obj.Get('chart.title.vpos') * gutter;
}
// if chart.title.hpos is a number, use that. It's multiplied with the (entire) canvas width
if (typeof(hpos) == 'number') {
centerx = hpos * canvas.width;
}
// Set the colour
if (typeof(obj.Get('chart.title.color') != null)) {
var oldColor = context.fillStyle
var newColor = obj.Get('chart.title.color')
context.fillStyle = newColor ? newColor : 'black';
}
/**
* Default font is Verdana
*/
var font = obj.Get('chart.text.font');
/**
* Draw the title itself
*/
RGraph.Text(context, font, size, centerx, vpos, text, vCenter, 'center', bgcolor != null, null, bgcolor, true);
// Reset the fill colour
context.fillStyle = oldColor;
}
/**
* This function returns the mouse position in relation to the canvas
*
* @param object e The event object.
*/
RGraph.getMouseXY = function (e)
{
var obj = (RGraph.isIE8() ? event.srcElement : e.target);
var x;
var y;
if (RGraph.isIE8()) e = event;
// Browser with offsetX and offsetY
if (typeof(e.offsetX) == 'number' && typeof(e.offsetY) == 'number') {
x = e.offsetX;
y = e.offsetY;
// FF and other
} else {
x = 0;
y = 0;
while (obj != document.body && obj) {
x += obj.offsetLeft;
y += obj.offsetTop;
obj = obj.offsetParent;
}
x = e.pageX - x;
y = e.pageY - y;
}
return [x, y];
}
/**
* This function returns a two element array of the canvas x/y position in
* relation to the page
*
* @param object canvas
*/
RGraph.getCanvasXY = function (canvas)
{
var x = 0;
var y = 0;
var obj = canvas;
do {
x += obj.offsetLeft;
y += obj.offsetTop;
obj = obj.offsetParent;
} while (obj && obj.tagName.toLowerCase() != 'body');
return [x, y];
}
/**
* Registers a graph object (used when the canvas is redrawn)
*
* @param object obj The object to be registered
*/
RGraph.Register = function (obj)
{
var key = obj.id + '_' + obj.type;
RGraph.objects[key] = obj;
}
/**
* Causes all registered objects to be redrawn
*
* @param string An optional string indicating which canvas is not to be redrawn
* @param string An optional color to use to clear the canvas
*/
RGraph.Redraw = function ()
{
for (i in RGraph.objects) {
// TODO FIXME Maybe include more intense checking for whether the object is an RGraph object, eg obj.isRGraph == true ...?
if (
typeof(i) == 'string'
&& typeof(RGraph.objects[i]) == 'object'
&& typeof(RGraph.objects[i].type) == 'string'
&& RGraph.objects[i].isRGraph) {
if (!arguments[0] || arguments[0] != RGraph.objects[i].id) {
RGraph.Clear(RGraph.objects[i].canvas, arguments[1] ? arguments[1] : null);
RGraph.objects[i].Draw();
}
}
}
}
/**
* Loosly mimicks the PHP function print_r();
*/
RGraph.pr = function (obj)
{
var str = '';
var indent = (arguments[2] ? arguments[2] : '');
switch (typeof(obj)) {
case 'number':
if (indent == '') {
str+= 'Number: '
}
str += String(obj);
break;
case 'string':
if (indent == '') {
str+= 'String (' + obj.length + '):'
}
str += '"' + String(obj) + '"';
break;
case 'object':
// In case of null
if (obj == null) {
str += 'null';
break;
}
str += 'Object\n' + indent + '(\n';
for (var i=0; i<obj.length; ++i) {
str += indent + ' ' + i + ' => ' + RGraph.pr(obj[i], true, indent + ' ') + '\n';
}
var str = str + indent + ')';
break;
case 'function':
str += obj;
break;
case 'boolean':
str += 'Boolean: ' + (obj ? 'true' : 'false');
break;
}
/**
* Finished, now either return if we're in a recursed call, or alert()
* if we're not.
*/
if (arguments[1]) {
return str;
} else {
alert(str);
}
}
/**
* The RGraph registry Set() function
*
* @param string name The name of the key
* @param mixed value The value to set
* @return mixed Returns the same value as you pass it
*/
RGraph.Registry.Set = function (name, value)
{
// Store the setting
RGraph.Registry.store[name] = value;
// Don't really need to do this, but ho-hum
return value;
}
/**
* The RGraph registry Get() function
*
* @param string name The name of the particular setting to fetch
* @return mixed The value if exists, null otherwise
*/
RGraph.Registry.Get = function (name)
{
//return RGraph.Registry.store[name] == null ? null : RGraph.Registry.store[name];
return RGraph.Registry.store[name];
}
/**
* This function draws the background for the bar chart, line chart and scatter chart.
*
* @param object obj The graph object
*/
RGraph.background.Draw = function (obj)
{
var canvas = obj.canvas;
var context = obj.context;
var height = 0;
var gutter = obj.Get('chart.gutter');
var variant = obj.Get('chart.variant');
context.fillStyle = obj.Get('chart.text.color');
// If it's a bar and 3D variant, translate
if (variant == '3d') {
context.save();
context.translate(10, -5);
}
// X axis title
if (typeof(obj.Get('chart.title.xaxis')) == 'string' && obj.Get('chart.title.xaxis').length) {
var size = obj.Get('chart.text.size');
var font = obj.Get('chart.text.font');
context.beginPath();
RGraph.Text(context, font, size + 2, RGraph.GetWidth(obj) / 2, RGraph.GetHeight(obj) - (gutter * obj.Get('chart.title.xaxis.pos')), obj.Get('chart.title.xaxis'), 'center', 'center', false, false, false, true);
context.fill();
}
// Y axis title
if (typeof(obj.Get('chart.title.yaxis')) == 'string' && obj.Get('chart.title.yaxis').length) {
var size = obj.Get('chart.text.size');
var font = obj.Get('chart.text.font');
context.beginPath();
RGraph.Text(context, font, size + 2, gutter * obj.Get('chart.title.yaxis.pos'), RGraph.GetHeight(obj) / 2, obj.Get('chart.title.yaxis'), 'center', 'center', false, 270, false, true);
context.fill();
}
obj.context.beginPath();
// Draw the horizontal bars
context.fillStyle = obj.Get('chart.background.barcolor1');
height = (RGraph.GetHeight(obj) - obj.Get('chart.gutter'));
for (var i=gutter; i < height ; i+=80) {
obj.context.fillRect(gutter, i, RGraph.GetWidth(obj) - (gutter * 2), Math.min(40, RGraph.GetHeight(obj) - gutter - i) );
}
context.fillStyle = obj.Get('chart.background.barcolor2');
height = (RGraph.GetHeight(obj) - gutter);
for (var i= (40 + gutter); i < height; i+=80) {
obj.context.fillRect(gutter, i, RGraph.GetWidth(obj) - (gutter * 2), i + 40 > (RGraph.GetHeight(obj) - gutter) ? RGraph.GetHeight(obj) - (gutter + i) : 40);
}
context.stroke();
// Draw the background grid
if (obj.Get('chart.background.grid')) {
// If autofit is specified, use the .numhlines and .numvlines along with the width to work
// out the hsize and vsize
if (obj.Get('chart.background.grid.autofit')) {
/**
* Align the grid to the tickmarks
*/
if (obj.Get('chart.background.grid.autofit.align')) {
// Align the horizontal lines
obj.Set('chart.background.grid.autofit.numhlines', obj.Get('chart.ylabels.count'));
// Align the vertical lines for the line
if (obj.type == 'line') {
if (obj.Get('chart.labels') && obj.Get('chart.labels').length) {
obj.Set('chart.background.grid.autofit.numvlines', obj.Get('chart.labels').length - 1);
} else {
obj.Set('chart.background.grid.autofit.numvlines', obj.data[0].length - 1);
}
// Align the vertical lines for the bar
} else if (obj.type == 'bar' && obj.Get('chart.labels') && obj.Get('chart.labels').length) {
obj.Set('chart.background.grid.autofit.numvlines', obj.Get('chart.labels').length);
}
}
var vsize = (RGraph.GetWidth(obj) - (2 * obj.Get('chart.gutter')) - (obj.type == 'gantt' ? 2 * obj.Get('chart.gutter') : 0)) / obj.Get('chart.background.grid.autofit.numvlines');
var hsize = (RGraph.GetHeight(obj) - (2 * obj.Get('chart.gutter'))) / obj.Get('chart.background.grid.autofit.numhlines');
obj.Set('chart.background.grid.vsize', vsize);
obj.Set('chart.background.grid.hsize', hsize);
}
context.beginPath();
context.lineWidth = obj.Get('chart.background.grid.width') ? obj.Get('chart.background.grid.width') : 1;
context.strokeStyle = obj.Get('chart.background.grid.color');
// Draw the horizontal lines
if (obj.Get('chart.background.grid.hlines')) {
height = (RGraph.GetHeight(obj) - gutter)
for (y=gutter; y < height; y+=obj.Get('chart.background.grid.hsize')) {
context.moveTo(gutter, y);
context.lineTo(RGraph.GetWidth(obj) - gutter, y);
}
}
if (obj.Get('chart.background.grid.vlines')) {
// Draw the vertical lines
var width = (RGraph.GetWidth(obj) - gutter)
for (x=gutter + (obj.type == 'gantt' ? (2 * gutter) : 0); x<=width; x+=obj.Get('chart.background.grid.vsize')) {
context.moveTo(x, gutter);
context.lineTo(x, RGraph.GetHeight(obj) - gutter);
}
}
if (obj.Get('chart.background.grid.border')) {
// Make sure a rectangle, the same colour as the grid goes around the graph
context.strokeStyle = obj.Get('chart.background.grid.color');
context.strokeRect(gutter, gutter, RGraph.GetWidth(obj) - (2 * gutter), RGraph.GetHeight(obj) - (2 * gutter));
}
}
context.stroke();
// If it's a bar and 3D variant, translate
if (variant == '3d') {
context.restore();
}
// Draw the title if one is set
if ( typeof(obj.Get('chart.title')) == 'string') {
if (obj.type == 'gantt') {
gutter /= 2;
}
RGraph.DrawTitle(canvas, obj.Get('chart.title'), gutter, null, obj.Get('chart.text.size') + 2);
}
context.stroke();
}
/**
* Returns the day number for a particular date. Eg 1st February would be 32
*
* @param object obj A date object
* @return int The day number of the given date
*/
RGraph.GetDays = function (obj)
{
var year = obj.getFullYear();
var days = obj.getDate();
var month = obj.getMonth();
if (month == 0) return days;
if (month >= 1) days += 31;
if (month >= 2) days += 28;
// Leap years. Crude, but if this code is still being used
// when it stops working, then you have my permission to shoot
// me. Oh, you won't be able to - I'll be dead...
if (year >= 2008 && year % 4 == 0) days += 1;
if (month >= 3) days += 31;
if (month >= 4) days += 30;
if (month >= 5) days += 31;
if (month >= 6) days += 30;
if (month >= 7) days += 31;
if (month >= 8) days += 31;
if (month >= 9) days += 30;
if (month >= 10) days += 31;
if (month >= 11) days += 30;
return days;
}
/**
* Draws the graph key (used by various graphs)
*
* @param object obj The graph object
* @param array key An array of the texts to be listed in the key
* @param colors An array of the colors to be used
*/
RGraph.DrawKey = function (obj, key, colors)
{
var canvas = obj.canvas;
var context = obj.context;
context.lineWidth = 1;
context.beginPath();
/**
* Key positioned in the gutter
*/
var keypos = obj.Get('chart.key.position');
var textsize = obj.Get('chart.text.size');
var gutter = obj.Get('chart.gutter');
/**
* Change the older chart.key.vpos to chart.key.position.y
*/
if (typeof(obj.Get('chart.key.vpos')) == 'number') {
obj.Set('chart.key.position.y', obj.Get('chart.key.vpos') * gutter);
}
/**
* Account for null values in the key
*/
var key_non_null = [];
var colors_non_null = [];
for (var i=0; i<key.length; ++i) {
if (key[i] != null) {
colors_non_null.push(colors[i]);
key_non_null.push(key[i]);
}
}
key = key_non_null;
colors = colors_non_null;
if (keypos && keypos == 'gutter') {
RGraph.DrawKey_gutter(obj, key, colors);
/**
* In-graph style key
*/
} else if (keypos && keypos == 'graph') {
RGraph.DrawKey_graph(obj, key, colors);
} else {
alert('[COMMON] (' + obj.id + ') Unknown key position: ' + keypos);
}
}
/**
* This does the actual drawing of the key when it's in the graph
*
* @param object obj The graph object
* @param array key The key items to draw
* @param array colors An aray of colors that the key will use
*/
RGraph.DrawKey_graph = function (obj, key, colors)
{
var canvas = obj.canvas;
var context = obj.context;
var text_size = typeof(obj.Get('chart.key.text.size')) == 'number' ? obj.Get('chart.key.text.size') : obj.Get('chart.text.size');
var text_font = obj.Get('chart.text.font');
var gutter = obj.Get('chart.gutter');
var hpos = obj.Get('chart.yaxispos') == 'right' ? gutter + 10 : RGraph.GetWidth(obj) - gutter - 10;
var vpos = gutter + 10;
var title = obj.Get('chart.title');
var blob_size = text_size; // The blob of color
var hmargin = 8; // This is the size of the gaps between the blob of color and the text
var vmargin = 4; // This is the vertical margin of the key
var fillstyle = obj.Get('chart.key.background');
var strokestyle = 'black';
var height = 0;
var width = 0;
obj.coordsKey = [];
// Need to set this so that measuring the text works out OK
context.font = text_size + 'pt ' + obj.Get('chart.text.font');
// Work out the longest bit of text
for (i=0; i<key.length; ++i) {
width = Math.max(width, context.measureText(key[i]).width);
}
width += 5;
width += blob_size;
width += 5;
width += 5;
width += 5;
/**
* Now we know the width, we can move the key left more accurately
*/
if ( obj.Get('chart.yaxispos') == 'left'
|| (obj.type == 'pie' && !obj.Get('chart.yaxispos'))
|| (obj.type == 'hbar' && !obj.Get('chart.yaxispos'))
|| (obj.type == 'hbar' && obj.Get('chart.yaxispos') == 'center')
|| (obj.type == 'rscatter' && !obj.Get('chart.yaxispos'))
|| (obj.type == 'tradar' && !obj.Get('chart.yaxispos'))
|| (obj.type == 'rose' && !obj.Get('chart.yaxispos'))
|| (obj.type == 'funnel' && !obj.Get('chart.yaxispos'))
|| (obj.type == 'vprogress' && !obj.Get('chart.yaxispos'))
|| (obj.type == 'hprogress' && !obj.Get('chart.yaxispos'))
) {
hpos -= width;
}
/**
* Specific location coordinates
*/
if (typeof(obj.Get('chart.key.position.x')) == 'number') {
hpos = obj.Get('chart.key.position.x');
}
if (typeof(obj.Get('chart.key.position.y')) == 'number') {
vpos = obj.Get('chart.key.position.y');
}
// Stipulate the shadow for the key box
if (obj.Get('chart.key.shadow')) {
context.shadowColor = obj.Get('chart.key.shadow.color');
context.shadowBlur = obj.Get('chart.key.shadow.blur');
context.shadowOffsetX = obj.Get('chart.key.shadow.offsetx');
context.shadowOffsetY = obj.Get('chart.key.shadow.offsety');
}
// Draw the box that the key resides in
context.beginPath();
context.fillStyle = obj.Get('chart.key.background');
context.strokeStyle = 'black';
if (arguments[3] != false) {
context.lineWidth = obj.Get('chart.key.linewidth') ? obj.Get('chart.key.linewidth') : 1;
// The older square rectangled key
if (obj.Get('chart.key.rounded') == true) {
context.beginPath();
context.strokeStyle = strokestyle;
RGraph.strokedCurvyRect(context, hpos, vpos, width - 5, 5 + ( (text_size + 5) * RGraph.getKeyLength(key)),4);
context.stroke();
context.fill();
RGraph.NoShadow(obj);
} else {
context.strokeRect(hpos, vpos, width - 5, 5 + ( (text_size + 5) * RGraph.getKeyLength(key)));
context.fillRect(hpos, vpos, width - 5, 5 + ( (text_size + 5) * RGraph.getKeyLength(key)));
}
}
RGraph.NoShadow(obj);
context.beginPath();
// Draw the labels given
for (var i=key.length - 1; i>=0; i--) {
var j = Number(i) + 1;
// Draw the blob of color
if (obj.Get('chart.key.color.shape') == 'circle') {
context.beginPath();
context.strokeStyle = 'rgba(0,0,0,0)';
context.fillStyle = colors[i];
context.arc(hpos + 5 + (blob_size / 2), vpos + (5 * j) + (text_size * j) - text_size + (blob_size / 2), blob_size / 2, 0, 6.26, 0);
context.fill();
} else if (obj.Get('chart.key.color.shape') == 'line') {
context.beginPath();
context.strokeStyle = colors[i];
context.moveTo(hpos + 5, vpos + (5 * j) + (text_size * j) - text_size + (blob_size / 2));
context.lineTo(hpos + blob_size + 5, vpos + (5 * j) + (text_size * j) - text_size + (blob_size / 2));
context.stroke();
} else {
context.fillStyle = colors[i];
context.fillRect(hpos + 5, vpos + (5 * j) + (text_size * j) - text_size, text_size, text_size + 1);
}
context.beginPath();
context.fillStyle = 'black';
RGraph.Text(context,
text_font,
text_size,
hpos + blob_size + 5 + 5,
vpos + (5 * j) + (text_size * j),
key[i]);
if (obj.Get('chart.key.interactive')) {
var px = hpos + 5;
var py = vpos + (5 * j) + (text_size * j) - text_size;
var pw = width - 5 - 5 - 5;
var ph = text_size;
obj.coordsKey.push([px, py, pw, ph]);
}
}
context.fill();
/**
* Install the interactivity event handler
*/
if (obj.Get('chart.key.interactive')) {
RGraph.Register(obj);
var key_mousemove = function (e)
{
var obj = e.target.__object__;
var canvas = obj.canvas;
var context = obj.context;
var mouseCoords = RGraph.getMouseXY(e);
var mouseX = mouseCoords[0];
var mouseY = mouseCoords[1];
for (var i=0; i<obj.coordsKey.length; ++i) {
var px = obj.coordsKey[i][0];
var py = obj.coordsKey[i][1];
var pw = obj.coordsKey[i][2];
var ph = obj.coordsKey[i][3];
if ( mouseX > px && mouseX < (px + pw) && mouseY > py && mouseY < (py + ph) ) {
// Necessary?
//var index = obj.coordsKey.length - i - 1;
canvas.style.cursor = 'pointer';
return;
}
canvas.style.cursor = 'default';
}
}
canvas.addEventListener('mousemove', key_mousemove, false);
RGraph.AddEventListener(canvas.id, 'mousemove', key_mousemove);
var key_click = function (e)
{
RGraph.Redraw();
var obj = e.target.__object__;
var canvas = obj.canvas;
var context = obj.context;
var mouseCoords = RGraph.getMouseXY(e);
var mouseX = mouseCoords[0];
var mouseY = mouseCoords[1];
RGraph.DrawKey(obj, obj.Get('chart.key'), obj.Get('chart.colors'));
for (var i=0; i<obj.coordsKey.length; ++i) {
var px = obj.coordsKey[i][0];
var py = obj.coordsKey[i][1];
var pw = obj.coordsKey[i][2];
var ph = obj.coordsKey[i][3];
if ( mouseX > px && mouseX < (px + pw) && mouseY > py && mouseY < (py + ph) ) {
var index = obj.coordsKey.length - i - 1;
// HIGHLIGHT THE LINE HERE
context.beginPath();
context.strokeStyle = 'rgba(0,0,0,0.5)';
context.lineWidth = obj.Get('chart.linewidth') + 2;
for (var j=0; j<obj.coords2[index].length; ++j) {
var x = obj.coords2[index][j][0];
var y = obj.coords2[index][j][1];
if (j == 0) {
context.moveTo(x, y);
} else {
context.lineTo(x, y);
}
}
context.stroke();
context.lineWidth = 1;
context.beginPath();
context.strokeStyle = 'black';
context.fillStyle = 'white';
RGraph.SetShadow(obj, 'rgba(0,0,0,0.5)', 0,0,10);
context.strokeRect(px - 2, py - 2, pw + 4, ph + 4);
context.fillRect(px - 2, py - 2, pw + 4, ph + 4);
context.stroke();
context.fill();
RGraph.NoShadow(obj);
context.beginPath();
context.fillStyle = obj.Get('chart.colors')[obj.Get('chart.colors').length - i - 1];
context.fillRect(px, py, blob_size, blob_size);
context.fill();
context.beginPath();
context.fillStyle = obj.Get('chart.text.color');
RGraph.Text(context,
obj.Get('chart.text.font'),
obj.Get('chart.text.size'),
px + 5 + blob_size,
py + ph,
obj.Get('chart.key')[obj.Get('chart.key').length - i - 1]
);
context.fill();
canvas.style.cursor = 'pointer';
return;
}
canvas.style.cursor = 'default';
}
}
canvas.addEventListener('click', key_click, false);
RGraph.AddEventListener(canvas.id, 'click', key_click);
//var key_window_click = function (e)
//{
// RGraph.Redraw();
//}
//window.addEventListener('click', key_window_click, false);
//RGraph.AddEventListener(canvas.id, 'window_click', key_window_click);
}
}
/**
* This does the actual drawing of the key when it's in the gutter
*
* @param object obj The graph object
* @param array key The key items to draw
* @param array colors An aray of colors that the key will use
*/
RGraph.DrawKey_gutter = function (obj, key, colors)
{
var canvas = obj.canvas;
var context = obj.context;
var text_size = typeof(obj.Get('chart.key.text.size')) == 'number' ? obj.Get('chart.key.text.size') : obj.Get('chart.text.size');
var text_font = obj.Get('chart.text.font');
var gutter = obj.Get('chart.gutter');
var hpos = RGraph.GetWidth(obj) / 2;
var vpos = (gutter / 2) - 5;
var title = obj.Get('chart.title');
var blob_size = text_size; // The blob of color
var hmargin = 8; // This is the size of the gaps between the blob of color and the text
var vmargin = 4; // This is the vertical margin of the key
var fillstyle = obj.Get('chart.key.background');
var strokestyle = 'black';
var length = 0;
// Need to work out the length of the key first
context.font = text_size + 'pt ' + text_font;
for (i=0; i<key.length; ++i) {
length += hmargin;
length += blob_size;
length += hmargin;
length += context.measureText(key[i]).width;
}
length += hmargin;
/**
* Work out hpos since in the Pie it isn't necessarily dead center
*/
if (obj.type == 'pie') {
if (obj.Get('chart.align') == 'left') {
var hpos = obj.radius + obj.Get('chart.gutter');
} else if (obj.Get('chart.align') == 'right') {
var hpos = obj.canvas.width - obj.radius - obj.Get('chart.gutter');
} else {
hpos = canvas.width / 2;
}
}
/**
* This makes the key centered
*/
hpos -= (length / 2);
/**
* Override the horizontal/vertical positioning
*/
if (typeof(obj.Get('chart.key.position.x')) == 'number') {
hpos = obj.Get('chart.key.position.x');
}
if (typeof(obj.Get('chart.key.position.y')) == 'number') {
vpos = obj.Get('chart.key.position.y');
}
/**
* Draw the box that the key sits in
*/
if (obj.Get('chart.key.position.gutter.boxed')) {
if (obj.Get('chart.key.shadow')) {
context.shadowColor = obj.Get('chart.key.shadow.color');
context.shadowBlur = obj.Get('chart.key.shadow.blur');
context.shadowOffsetX = obj.Get('chart.key.shadow.offsetx');
context.shadowOffsetY = obj.Get('chart.key.shadow.offsety');
}
context.beginPath();
context.fillStyle = fillstyle;
context.strokeStyle = strokestyle;
if (obj.Get('chart.key.rounded')) {
RGraph.strokedCurvyRect(context, hpos, vpos - vmargin, length, text_size + vmargin + vmargin)
// Odd... RGraph.filledCurvyRect(context, hpos, vpos - vmargin, length, text_size + vmargin + vmargin);
} else {
context.strokeRect(hpos, vpos - vmargin, length, text_size + vmargin + vmargin);
context.fillRect(hpos, vpos - vmargin, length, text_size + vmargin + vmargin);
}
context.stroke();
context.fill();
RGraph.NoShadow(obj);
}
/**
* Draw the blobs of color and the text
*/
for (var i=0, pos=hpos; i<key.length; ++i) {
pos += hmargin;
// Draw the blob of color - line
if (obj.Get('chart.key.color.shape') =='line') {
context.beginPath();
context.strokeStyle = colors[i];
context.moveTo(pos, vpos + (blob_size / 2));
context.lineTo(pos + blob_size, vpos + (blob_size / 2));
context.stroke();
// Circle
} else if (obj.Get('chart.key.color.shape') == 'circle') {
context.beginPath();
context.fillStyle = colors[i];
context.moveTo(pos, vpos + (blob_size / 2));
context.arc(pos + (blob_size / 2), vpos + (blob_size / 2), (blob_size / 2), 0, 6.28, 0);
context.fill();
} else {
context.beginPath();
context.fillStyle = colors[i];
context.fillRect(pos, vpos, blob_size, blob_size);
context.fill();
}
pos += blob_size;
pos += hmargin;
context.beginPath();
context.fillStyle = 'black';
RGraph.Text(context, text_font, text_size, pos, vpos + text_size - 1, key[i]);
context.fill();
pos += context.measureText(key[i]).width;
}
}
/**
* Returns the key length, but accounts for null values
*
* @param array key The key elements
*/
RGraph.getKeyLength = function (key)
{
var len = 0;
for (var i=0; i<key.length; ++i) {
if (key[i] != null) {
++len;
}
}
return len;
}
/**
* A shortcut for RGraph.pr()
*/
function pd(variable)
{
RGraph.pr(variable);
}
function p(variable)
{
RGraph.pr(variable);
}
/**
* A shortcut for console.log - as used by Firebug and Chromes console
*/
function cl (variable)
{
return console.log(variable);
}
/**
* Makes a clone of an object
*
* @param obj val The object to clone
*/
RGraph.array_clone = function (obj)
{
if(obj == null || typeof(obj) != 'object') {
return obj;
}
var temp = [];
//var temp = new obj.constructor();
for(var i=0;i<obj.length; ++i) {
temp[i] = RGraph.array_clone(obj[i]);
}
return temp;
}
/**
* This function reverses an array
*/
RGraph.array_reverse = function (arr)
{
var newarr = [];
for (var i=arr.length - 1; i>=0; i--) {
newarr.push(arr[i]);
}
return newarr;
}
/**
* Formats a number with thousand seperators so it's easier to read
*
* @param integer num The number to format
* @param string The (optional) string to prepend to the string
* @param string The (optional) string to ap
* pend to the string
* @return string The formatted number
*/
RGraph.number_format = function (obj, num)
{
var i;
var prepend = arguments[2] ? String(arguments[2]) : '';
var append = arguments[3] ? String(arguments[3]) : '';
var output = '';
var decimal = '';
var decimal_seperator = obj.Get('chart.scale.point') ? obj.Get('chart.scale.point') : '.';
var thousand_seperator = obj.Get('chart.scale.thousand') ? obj.Get('chart.scale.thousand') : ',';
RegExp.$1 = '';
var i,j;
// Ignore the preformatted version of "1e-2"
if (String(num).indexOf('e') > 0) {
return String(prepend + String(num) + append);
}
// We need then number as a string
num = String(num);
// Take off the decimal part - we re-append it later
if (num.indexOf('.') > 0) {
num = num.replace(/\.(.*)/, '');
decimal = RegExp.$1;
}
// Thousand seperator
//var seperator = arguments[1] ? String(arguments[1]) : ',';
var seperator = thousand_seperator;
/**
* Work backwards adding the thousand seperators
*/
var foundPoint;
for (i=(num.length - 1),j=0; i>=0; j++,i--) {
var character = num.charAt(i);
if ( j % 3 == 0 && j != 0) {
output += seperator;
}
/**
* Build the output
*/
output += character;
}
/**
* Now need to reverse the string
*/
var rev = output;
output = '';
for (i=(rev.length - 1); i>=0; i--) {
output += rev.charAt(i);
}
// Tidy up
output = output.replace(/^-,/, '-');
// Reappend the decimal
if (decimal.length) {
output = output + decimal_seperator + decimal;
decimal = '';
RegExp.$1 = '';
}
// Minor bugette
if (output.charAt(0) == '-') {
output *= -1;
prepend = '-' + prepend;
}
return prepend + output + append;
}
/**
* Draws horizontal coloured bars on something like the bar, line or scatter
*/
RGraph.DrawBars = function (obj)
{
var hbars = obj.Get('chart.background.hbars');
/**
* Draws a horizontal bar
*/
obj.context.beginPath();
for (i=0; i<hbars.length; ++i) {
// If null is specified as the "height", set it to the upper max value
if (hbars[i][1] == null) {
hbars[i][1] = obj.max;
// If the first index plus the second index is greater than the max value, adjust accordingly
} else if (hbars[i][0] + hbars[i][1] > obj.max) {
hbars[i][1] = obj.max - hbars[i][0];
}
// If height is negative, and the abs() value is greater than .max, use a negative max instead
if (Math.abs(hbars[i][1]) > obj.max) {
hbars[i][1] = -1 * obj.max;
}
// If start point is greater than max, change it to max
if (Math.abs(hbars[i][0]) > obj.max) {
hbars[i][0] = obj.max;
}
// If start point plus height is less than negative max, use the negative max plus the start point
if (hbars[i][0] + hbars[i][1] < (-1 * obj.max) ) {
hbars[i][1] = -1 * (obj.max + hbars[i][0]);
}
// If the X axis is at the bottom, and a negative max is given, warn the user
if (obj.Get('chart.xaxispos') == 'bottom' && (hbars[i][0] < 0 || (hbars[i][1] + hbars[i][1] < 0)) ) {
alert('[' + obj.type.toUpperCase() + ' (ID: ' + obj.id + ') BACKGROUND HBARS] You have a negative value in one of your background hbars values, whilst the X axis is in the center');
}
var ystart = (obj.grapharea - ((hbars[i][0] / obj.max) * obj.grapharea));
var height = (Math.min(hbars[i][1], obj.max - hbars[i][0]) / obj.max) * obj.grapharea;
// Account for the X axis being in the center
if (obj.Get('chart.xaxispos') == 'center') {
ystart /= 2;
height /= 2;
}
ystart += obj.Get('chart.gutter')
var x = obj.Get('chart.gutter');
var y = ystart - height;
var w = obj.canvas.width - (2 * obj.Get('chart.gutter'));
var h = height;
// Accommodate Opera :-/
if (navigator.userAgent.indexOf('Opera') != -1 && obj.Get('chart.xaxispos') == 'center' && h < 0) {
h *= -1;
y = y - h;
}
obj.context.fillStyle = hbars[i][2];
obj.context.fillRect(x, y, w, h);
}
obj.context.fill();
}
/**
* Draws in-graph labels.
*
* @param object obj The graph object
*/
RGraph.DrawInGraphLabels = function (obj)
{
var canvas = obj.canvas;
var context = obj.context;
var labels = obj.Get('chart.labels.ingraph');
var labels_processed = [];
// Defaults
var fgcolor = 'black';
var bgcolor = 'white';
var direction = 1;
if (!labels) {
return;
}
/**
* Preprocess the labels array. Numbers are expanded
*/
for (var i=0; i<labels.length; ++i) {
if (typeof(labels[i]) == 'number') {
for (var j=0; j<labels[i]; ++j) {
labels_processed.push(null);
}
} else if (typeof(labels[i]) == 'string' || typeof(labels[i]) == 'object') {
labels_processed.push(labels[i]);
} else {
labels_processed.push('');
}
}
/**
* Turn off any shadow
*/
RGraph.NoShadow(obj);
if (labels_processed && labels_processed.length > 0) {
for (var i=0; i<labels_processed.length; ++i) {
if (labels_processed[i]) {
var coords = obj.coords[i];
if (coords && coords.length > 0) {
var x = (obj.type == 'bar' ? coords[0] + (coords[2] / 2) : coords[0]);
var y = (obj.type == 'bar' ? coords[1] + (coords[3] / 2) : coords[1]);
var length = typeof(labels_processed[i][4]) == 'number' ? labels_processed[i][4] : 25;
context.beginPath();
context.fillStyle = 'black';
context.strokeStyle = 'black';
if (obj.type == 'bar') {
if (obj.Get('chart.variant') == 'dot') {
context.moveTo(x, obj.coords[i][1] - 5);
context.lineTo(x, obj.coords[i][1] - 5 - length);
var text_x = x;
var text_y = obj.coords[i][1] - 5 - length;
} else if (obj.Get('chart.variant') == 'arrow') {
context.moveTo(x, obj.coords[i][1] - 5);
context.lineTo(x, obj.coords[i][1] - 5 - length);
var text_x = x;
var text_y = obj.coords[i][1] - 5 - length;
} else {
context.arc(x, y, 2.5, 0, 6.28, 0);
context.moveTo(x, y);
context.lineTo(x, y - length);
var text_x = x;
var text_y = y - length;
}
context.stroke();
context.fill();
} else if (obj.type == 'line') {
if (
typeof(labels_processed[i]) == 'object' &&
typeof(labels_processed[i][3]) == 'number' &&
labels_processed[i][3] == -1
) {
context.moveTo(x, y + 5);
context.lineTo(x, y + 5 + length);
context.stroke();
context.beginPath();
// This draws the arrow
context.moveTo(x, y + 5);
context.lineTo(x - 3, y + 10);
context.lineTo(x + 3, y + 10);
context.closePath();
var text_x = x;
var text_y = y + 5 + length;
} else {
var text_x = x;
var text_y = y - 5 - length;
context.moveTo(x, y - 5);
context.lineTo(x, y - 5 - length);
context.stroke();
context.beginPath();
// This draws the arrow
context.moveTo(x, y - 5);
context.lineTo(x - 3, y - 10);
context.lineTo(x + 3, y - 10);
context.closePath();
}
context.fill();
}
// Taken out on the 10th Nov 2010 - unnecessary
//var width = context.measureText(labels[i]).width;
context.beginPath();
// Fore ground color
context.fillStyle = (typeof(labels_processed[i]) == 'object' && typeof(labels_processed[i][1]) == 'string') ? labels_processed[i][1] : 'black';
RGraph.Text(context,
obj.Get('chart.text.font'),
obj.Get('chart.text.size'),
text_x,
text_y,
(typeof(labels_processed[i]) == 'object' && typeof(labels_processed[i][0]) == 'string') ? labels_processed[i][0] : labels_processed[i],
'bottom',
'center',
true,
null,
(typeof(labels_processed[i]) == 'object' && typeof(labels_processed[i][2]) == 'string') ? labels_processed[i][2] : 'white');
context.fill();
}
}
}
}
}
/**
* This function "fills in" key missing properties that various implementations lack
*
* @param object e The event object
*/
RGraph.FixEventObject = function (e)
{
if (RGraph.isIE8()) {
var e = event;
e.pageX = (event.clientX + document.body.scrollLeft);
e.pageY = (event.clientY + document.body.scrollTop);
e.target = event.srcElement;
if (!document.body.scrollTop && document.documentElement.scrollTop) {
e.pageX += parseInt(document.documentElement.scrollLeft);
e.pageY += parseInt(document.documentElement.scrollTop);
}
}
// This is mainly for FF which doesn't provide offsetX
if (typeof(e.offsetX) == 'undefined' && typeof(e.offsetY) == 'undefined') {
var coords = RGraph.getMouseXY(e);
e.offsetX = coords[0];
e.offsetY = coords[1];
}
// Any browser that doesn't implement stopPropagation() (MSIE)
if (!e.stopPropagation) {
e.stopPropagation = function () {window.event.cancelBubble = true;}
}
return e;
}
/**
* Draw crosshairs if enabled
*
* @param object obj The graph object (from which we can get the context and canvas as required)
*/
RGraph.DrawCrosshairs = function (obj)
{
if (obj.Get('chart.crosshairs')) {
var canvas = obj.canvas;
var context = obj.context;
// 5th November 2010 - removed now that tooltips are DOM2 based.
//if (obj.Get('chart.tooltips') && obj.Get('chart.tooltips').length > 0) {
//alert('[' + obj.type.toUpperCase() + '] Sorry - you cannot have crosshairs enabled with tooltips! Turning off crosshairs...');
//obj.Set('chart.crosshairs', false);
//return;
//}
canvas.onmousemove = function (e)
{
var e = RGraph.FixEventObject(e);
var canvas = obj.canvas;
var context = obj.context;
var gutter = obj.Get('chart.gutter');
var width = canvas.width;
var height = canvas.height;
var adjustments = obj.Get('chart.tooltips.coords.adjust');
var mouseCoords = RGraph.getMouseXY(e);
var x = mouseCoords[0];
var y = mouseCoords[1];
if (typeof(adjustments) == 'object' && adjustments[0] && adjustments[1]) {
x = x - adjustments[0];
y = y - adjustments[1];
}
RGraph.Clear(canvas);
obj.Draw();
if ( x >= gutter
&& y >= gutter
&& x <= (width - gutter)
&& y <= (height - gutter)
) {
var linewidth = obj.Get('chart.crosshairs.linewidth');
context.lineWidth = linewidth ? linewidth : 1;
context.beginPath();
context.strokeStyle = obj.Get('chart.crosshairs.color');
// Draw a top vertical line
context.moveTo(x, gutter);
context.lineTo(x, height - gutter);
// Draw a horizontal line
context.moveTo(gutter, y);
context.lineTo(width - gutter, y);
context.stroke();
/**
* Need to show the coords?
*/
if (obj.Get('chart.crosshairs.coords')) {
if (obj.type == 'scatter') {
var xCoord = (((x - obj.Get('chart.gutter')) / (obj.canvas.width - (2 * obj.Get('chart.gutter')))) * (obj.Get('chart.xmax') - obj.Get('chart.xmin'))) + obj.Get('chart.xmin');
xCoord = xCoord.toFixed(obj.Get('chart.scale.decimals'));
var yCoord = obj.max - (((y - obj.Get('chart.gutter')) / (obj.canvas.height - (2 * obj.Get('chart.gutter')))) * obj.max);
if (obj.type == 'scatter' && obj.Get('chart.xaxispos') == 'center') {
yCoord = (yCoord - (obj.max / 2)) * 2;
}
yCoord = yCoord.toFixed(obj.Get('chart.scale.decimals'));
var div = RGraph.Registry.Get('chart.coordinates.coords.div');
var mouseCoords = RGraph.getMouseXY(e);
var canvasXY = RGraph.getCanvasXY(canvas);
if (!div) {
div = document.createElement('DIV');
div.__object__ = obj;
div.style.position = 'absolute';
div.style.backgroundColor = 'white';
div.style.border = '1px solid black';
div.style.fontFamily = 'Arial, Verdana, sans-serif';
div.style.fontSize = '10pt'
div.style.padding = '2px';
div.style.opacity = 1;
div.style.WebkitBorderRadius = '3px';
div.style.borderRadius = '3px';
div.style.MozBorderRadius = '3px';
document.body.appendChild(div);
RGraph.Registry.Set('chart.coordinates.coords.div', div);
}
// Convert the X/Y pixel coords to correspond to the scale
div.style.opacity = 1;
div.style.display = 'inline';
if (!obj.Get('chart.crosshairs.coords.fixed')) {
div.style.left = Math.max(2, (e.pageX - div.offsetWidth - 3)) + 'px';
div.style.top = Math.max(2, (e.pageY - div.offsetHeight - 3)) + 'px';
} else {
div.style.left = canvasXY[0] + obj.Get('chart.gutter') + 3 + 'px';
div.style.top = canvasXY[1] + obj.Get('chart.gutter') + 3 + 'px';
}
div.innerHTML = '<span style="color: #666">' + obj.Get('chart.crosshairs.coords.labels.x') + ':</span> ' + xCoord + '<br><span style="color: #666">' + obj.Get('chart.crosshairs.coords.labels.y') + ':</span> ' + yCoord;
canvas.addEventListener('mouseout', RGraph.HideCrosshairCoords, false);
} else {
alert('[RGRAPH] Showing crosshair coordinates is only supported on the Scatter chart');
}
}
} else {
RGraph.HideCrosshairCoords();
}
}
}
}
/**
* Thisz function hides the crosshairs coordinates
*/
RGraph.HideCrosshairCoords = function ()
{
var div = RGraph.Registry.Get('chart.coordinates.coords.div');
if ( div
&& div.style.opacity == 1
&& div.__object__.Get('chart.crosshairs.coords.fadeout')
) {
setTimeout(function() {RGraph.Registry.Get('chart.coordinates.coords.div').style.opacity = 0.9;}, 50);
setTimeout(function() {RGraph.Registry.Get('chart.coordinates.coords.div').style.opacity = 0.8;}, 100);
setTimeout(function() {RGraph.Registry.Get('chart.coordinates.coords.div').style.opacity = 0.7;}, 150);
setTimeout(function() {RGraph.Registry.Get('chart.coordinates.coords.div').style.opacity = 0.6;}, 200);
setTimeout(function() {RGraph.Registry.Get('chart.coordinates.coords.div').style.opacity = 0.5;}, 250);
setTimeout(function() {RGraph.Registry.Get('chart.coordinates.coords.div').style.opacity = 0.4;}, 300);
setTimeout(function() {RGraph.Registry.Get('chart.coordinates.coords.div').style.opacity = 0.3;}, 350);
setTimeout(function() {RGraph.Registry.Get('chart.coordinates.coords.div').style.opacity = 0.2;}, 400);
setTimeout(function() {RGraph.Registry.Get('chart.coordinates.coords.div').style.opacity = 0.1;}, 450);
setTimeout(function() {RGraph.Registry.Get('chart.coordinates.coords.div').style.opacity = 0;}, 500);
setTimeout(function() {RGraph.Registry.Get('chart.coordinates.coords.div').style.display = 'none';}, 550);
}
}
/**
* Trims the right hand side of a string. Removes SPACE, TAB
* CR and LF.
*
* @param string str The string to trim
*/
RGraph.rtrim = function (str)
{
return str.replace(/( |\n|\r|\t)+$/, '');
}
/**
* Draws the3D axes/background
*/
RGraph.Draw3DAxes = function (obj)
{
var gutter = obj.Get('chart.gutter');
var context = obj.context;
var canvas = obj.canvas;
context.strokeStyle = '#aaa';
context.fillStyle = '#ddd';
// Draw the vertical left side
context.beginPath();
context.moveTo(gutter, gutter);
context.lineTo(gutter + 10, gutter - 5);
context.lineTo(gutter + 10, canvas.height - gutter - 5);
context.lineTo(gutter, canvas.height - gutter);
context.closePath();
context.stroke();
context.fill();
// Draw the bottom floor
context.beginPath();
context.moveTo(gutter, canvas.height - gutter);
context.lineTo(gutter + 10, canvas.height - gutter - 5);
context.lineTo(canvas.width - gutter + 10, canvas.height - gutter - 5);
context.lineTo(canvas.width - gutter, canvas.height - gutter);
context.closePath();
context.stroke();
context.fill();
}
/**
* Turns off any shadow
*
* @param object obj The graph object
*/
RGraph.NoShadow = function (obj)
{
obj.context.shadowColor = 'rgba(0,0,0,0)';
obj.context.shadowBlur = 0;
obj.context.shadowOffsetX = 0;
obj.context.shadowOffsetY = 0;
}
/**
* Sets the four shadow properties - a shortcut function
*
* @param object obj Your graph object
* @param string color The shadow color
* @param number offsetx The shadows X offset
* @param number offsety The shadows Y offset
* @param number blur The blurring effect applied to the shadow
*/
RGraph.SetShadow = function (obj, color, offsetx, offsety, blur)
{
obj.context.shadowColor = color;
obj.context.shadowOffsetX = offsetx;
obj.context.shadowOffsetY = offsety;
obj.context.shadowBlur = blur;
}
/**
* This function attempts to "fill in" missing functions from the canvas
* context object. Only two at the moment - measureText() nd fillText().
*
* @param object context The canvas 2D context
*/
RGraph.OldBrowserCompat = function (context)
{
if (!context.measureText) {
// This emulates the measureText() function
context.measureText = function (text)
{
var textObj = document.createElement('DIV');
textObj.innerHTML = text;
textObj.style.backgroundColor = 'white';
textObj.style.position = 'absolute';
textObj.style.top = -100
textObj.style.left = 0;
document.body.appendChild(textObj);
var width = {width: textObj.offsetWidth};
textObj.style.display = 'none';
return width;
}
}
if (!context.fillText) {
// This emulates the fillText() method
context.fillText = function (text, targetX, targetY)
{
return false;
}
}
// If IE8, add addEventListener()
if (!context.canvas.addEventListener) {
window.addEventListener = function (ev, func, bubble)
{
return this.attachEvent('on' + ev, func);
}
context.canvas.addEventListener = function (ev, func, bubble)
{
return this.attachEvent('on' + ev, func);
}
}
}
/**
* This function is for use with circular graph types, eg the Pie or Radar. Pass it your event object
* and it will pass you back the corresponding segment details as an array:
*
* [x, y, r, startAngle, endAngle]
*
* Angles are measured in degrees, and are measured from the "east" axis (just like the canvas).
*
* @param object e Your event object
*/
RGraph.getSegment = function (e)
{
RGraph.FixEventObject(e);
// The optional arg provides a way of allowing some accuracy (pixels)
var accuracy = arguments[1] ? arguments[1] : 0;
var obj = e.target.__object__;
var canvas = obj.canvas;
var context = obj.context;
var mouseCoords = RGraph.getMouseXY(e);
var x = mouseCoords[0] - obj.centerx;
var y = mouseCoords[1] - obj.centery;
var r = obj.radius;
var theta = Math.atan(y / x); // RADIANS
var hyp = y / Math.sin(theta);
var angles = obj.angles;
var ret = [];
var hyp = (hyp < 0) ? hyp + accuracy : hyp - accuracy;
// Put theta in DEGREES
theta *= 57.3
// hyp should not be greater than radius if it's a Rose chart
if (obj.type == 'rose') {
if ( (isNaN(hyp) && Math.abs(mouseCoords[0]) < (obj.centerx - r) )
|| (isNaN(hyp) && Math.abs(mouseCoords[0]) > (obj.centerx + r))
|| (!isNaN(hyp) && Math.abs(hyp) > r)) {
return;
}
}
/**
* Account for the correct quadrant
*/
if (x < 0 && y >= 0) {
theta += 180;
} else if (x < 0 && y < 0) {
theta += 180;
} else if (x > 0 && y < 0) {
theta += 360;
}
/**
* Account for the rose chart
*/
if (obj.type == 'rose') {
theta += 90;
}
if (theta > 360) {
theta -= 360;
}
for (var i=0; i<angles.length; ++i) {
if (theta >= angles[i][0] && theta < angles[i][1]) {
hyp = Math.abs(hyp);
if (obj.type == 'rose' && hyp > angles[i][2]) {
return null;
}
if (!hyp || (obj.type == 'pie' && obj.radius && hyp > obj.radius) ) {
return null;
}
if (obj.type == 'pie' && obj.Get('chart.variant') == 'donut' && (hyp > obj.radius || hyp < (obj.radius / 2) ) ) {
return null;
}
ret[0] = obj.centerx;
ret[1] = obj.centery;
ret[2] = (obj.type == 'rose') ? angles[i][2] : obj.radius;
ret[3] = angles[i][0];
ret[4] = angles[i][1];
ret[5] = i;
if (obj.type == 'rose') {
ret[3] -= 90;
ret[4] -= 90;
if (x > 0 && y < 0) {
ret[3] += 360;
ret[4] += 360;
}
}
if (ret[3] < 0) ret[3] += 360;
if (ret[4] > 360) ret[4] -= 360;
return ret;
}
}
return null;
}
/**
* This is a function that can be used to run code asynchronously, which can
* be used to speed up the loading of you pages.
*
* @param string func This is the code to run. It can also be a function pointer.
* The front page graphs show this function in action. Basically
* each graphs code is made in a function, and that function is
* passed to this function to run asychronously.
*/
RGraph.Async = function (func)
{
return setTimeout(func, arguments[1] ? arguments[1] : 1);
}
/**
* A custom random number function
*
* @param number min The minimum that the number should be
* @param number max The maximum that the number should be
* @param number How many decimal places there should be. Default for this is 0
*/
RGraph.random = function (min, max)
{
var dp = arguments[2] ? arguments[2] : 0;
var r = Math.random();
return Number((((max - min) * r) + min).toFixed(dp));
}
/**
* Draws a rectangle with curvy corners
*
* @param context object The context
* @param x number The X coordinate (top left of the square)
* @param y number The Y coordinate (top left of the square)
* @param w number The width of the rectangle
* @param h number The height of the rectangle
* @param number The radius of the curved corners
* @param boolean Whether the top left corner is curvy
* @param boolean Whether the top right corner is curvy
* @param boolean Whether the bottom right corner is curvy
* @param boolean Whether the bottom left corner is curvy
*/
RGraph.strokedCurvyRect = function (context, x, y, w, h)
{
// The corner radius
var r = arguments[5] ? arguments[5] : 3;
// The corners
var corner_tl = (arguments[6] || arguments[6] == null) ? true : false;
var corner_tr = (arguments[7] || arguments[7] == null) ? true : false;
var corner_br = (arguments[8] || arguments[8] == null) ? true : false;
var corner_bl = (arguments[9] || arguments[9] == null) ? true : false;
context.beginPath();
// Top left side
context.moveTo(x + (corner_tl ? r : 0), y);
context.lineTo(x + w - (corner_tr ? r : 0), y);
// Top right corner
if (corner_tr) {
context.arc(x + w - r, y + r, r, Math.PI * 1.5, Math.PI * 2, false);
}
// Top right side
context.lineTo(x + w, y + h - (corner_br ? r : 0) );
// Bottom right corner
if (corner_br) {
context.arc(x + w - r, y - r + h, r, Math.PI * 2, Math.PI * 0.5, false);
}
// Bottom right side
context.lineTo(x + (corner_bl ? r : 0), y + h);
// Bottom left corner
if (corner_bl) {
context.arc(x + r, y - r + h, r, Math.PI * 0.5, Math.PI, false);
}
// Bottom left side
context.lineTo(x, y + (corner_tl ? r : 0) );
// Top left corner
if (corner_tl) {
context.arc(x + r, y + r, r, Math.PI, Math.PI * 1.5, false);
}
context.stroke();
}
/**
* Draws a filled rectangle with curvy corners
*
* @param context object The context
* @param x number The X coordinate (top left of the square)
* @param y number The Y coordinate (top left of the square)
* @param w number The width of the rectangle
* @param h number The height of the rectangle
* @param number The radius of the curved corners
* @param boolean Whether the top left corner is curvy
* @param boolean Whether the top right corner is curvy
* @param boolean Whether the bottom right corner is curvy
* @param boolean Whether the bottom left corner is curvy
*/
RGraph.filledCurvyRect = function (context, x, y, w, h)
{
// The corner radius
var r = arguments[5] ? arguments[5] : 3;
// The corners
var corner_tl = (arguments[6] || arguments[6] == null) ? true : false;
var corner_tr = (arguments[7] || arguments[7] == null) ? true : false;
var corner_br = (arguments[8] || arguments[8] == null) ? true : false;
var corner_bl = (arguments[9] || arguments[9] == null) ? true : false;
context.beginPath();
// First draw the corners
// Top left corner
if (corner_tl) {
context.moveTo(x + r, y + r);
context.arc(x + r, y + r, r, Math.PI, 1.5 * Math.PI, false);
} else {
context.fillRect(x, y, r, r);
}
// Top right corner
if (corner_tr) {
context.moveTo(x + w - r, y + r);
context.arc(x + w - r, y + r, r, 1.5 * Math.PI, 0, false);
} else {
context.moveTo(x + w - r, y);
context.fillRect(x + w - r, y, r, r);
}
// Bottom right corner
if (corner_br) {
context.moveTo(x + w - r, y + h - r);
context.arc(x + w - r, y - r + h, r, 0, Math.PI / 2, false);
} else {
context.moveTo(x + w - r, y + h - r);
context.fillRect(x + w - r, y + h - r, r, r);
}
// Bottom left corner
if (corner_bl) {
context.moveTo(x + r, y + h - r);
context.arc(x + r, y - r + h, r, Math.PI / 2, Math.PI, false);
} else {
context.moveTo(x, y + h - r);
context.fillRect(x, y + h - r, r, r);
}
// Now fill it in
context.fillRect(x + r, y, w - r - r, h);
context.fillRect(x, y + r, r + 1, h - r - r);
context.fillRect(x + w - r - 1, y + r, r + 1, h - r - r);
context.fill();
}
/**
* A crude timing function
*
* @param string label The label to use for the time
*/
RGraph.Timer = function (label)
{
var d = new Date();
// This uses the Firebug console
console.log(label + ': ' + d.getSeconds() + '.' + d.getMilliseconds());
}
/**
* Hides the palette if it's visible
*/
RGraph.HidePalette = function ()
{
var div = RGraph.Registry.Get('palette');
if (typeof(div) == 'object' && div) {
div.style.visibility = 'hidden';
div.style.display = 'none';
RGraph.Registry.Set('palette', null);
}
}
/**
* Hides the zoomed canvas
*/
RGraph.HideZoomedCanvas = function ()
{
if (typeof(__zoomedimage__) == 'object') {
obj = __zoomedimage__.obj;
} else {
return;
}
if (obj.Get('chart.zoom.fade.out')) {
for (var i=10,j=1; i>=0; --i, ++j) {
if (typeof(__zoomedimage__) == 'object') {
setTimeout("__zoomedimage__.style.opacity = " + String(i / 10), j * 30);
}
}
if (typeof(__zoomedbackground__) == 'object') {
setTimeout("__zoomedbackground__.style.opacity = " + String(i / 10), j * 30);
}
}
if (typeof(__zoomedimage__) == 'object') {
setTimeout("__zoomedimage__.style.display = 'none'", obj.Get('chart.zoom.fade.out') ? 310 : 0);
}
if (typeof(__zoomedbackground__) == 'object') {
setTimeout("__zoomedbackground__.style.display = 'none'", obj.Get('chart.zoom.fade.out') ? 310 : 0);
}
}
/**
* Adds an event handler
*
* @param object obj The graph object
* @param string event The name of the event, eg ontooltip
* @param object func The callback function
*/
RGraph.AddCustomEventListener = function (obj, name, func)
{
if (typeof(RGraph.events[obj.id]) == 'undefined') {
RGraph.events[obj.id] = [];
}
RGraph.events[obj.id].push([obj, name, func]);
return RGraph.events[obj.id].length - 1;
}
/**
* Used to fire one of the RGraph custom events
*
* @param object obj The graph object that fires the event
* @param string event The name of the event to fire
*/
RGraph.FireCustomEvent = function (obj, name)
{
var id = obj.id;
if ( typeof(id) == 'string'
&& typeof(RGraph.events) == 'object'
&& typeof(RGraph.events[id]) == 'object'
&& RGraph.events[id].length > 0) {
for(var j=0; j<RGraph.events[id].length; ++j) {
if (RGraph.events[id][j] && RGraph.events[id][j][1] == name) {
RGraph.events[id][j][2](obj);
}
}
}
}
/**
* Checks the browser for traces of MSIE8
*/
RGraph.isIE8 = function ()
{
return navigator.userAgent.indexOf('MSIE 8') > 0;
}
/**
* Checks the browser for traces of MSIE9
*/
RGraph.isIE9 = function ()
{
return navigator.userAgent.indexOf('MSIE 9') > 0;
}
/**
* Checks the browser for traces of MSIE9
*/
RGraph.isIE9up = function ()
{
navigator.userAgent.match(/MSIE (\d+)/);
return Number(RegExp.$1) >= 9;
}
/**
* This clears a canvases event handlers. Used at the start of each graphs .Draw() method.
*
* @param string id The ID of the canvas whose event handlers will be cleared
*/
RGraph.ClearEventListeners = function (id)
{
for (var i=0; i<RGraph.Registry.Get('chart.event.handlers').length; ++i) {
var el = RGraph.Registry.Get('chart.event.handlers')[i];
if (el && (el[0] == id || el[0] == ('window_' + id)) ) {
if (el[0].substring(0, 7) == 'window_') {
window.removeEventListener(el[1], el[2], false);
} else {
document.getElementById(id).removeEventListener(el[1], el[2], false);
}
RGraph.Registry.Get('chart.event.handlers')[i] = null;
}
}
}
/**
*
*/
RGraph.AddEventListener = function (id, e, func)
{
RGraph.Registry.Get('chart.event.handlers').push([id, e, func]);
}
/**
* This function suggests a gutter size based on the widest left label. Given that the bottom
* labels may be longer, this may be a little out.
*
* @param object obj The graph object
* @param array data An array of graph data
* @return int A suggested gutter setting
*/
RGraph.getGutterSuggest = function (obj, data)
{
var str = RGraph.number_format(obj, RGraph.array_max(RGraph.getScale(RGraph.array_max(data), obj)), obj.Get('chart.units.pre'), obj.Get('chart.units.post'));
// Take into account the HBar
if (obj.type == 'hbar') {
var str = '';
var len = 0;
for (var i=0; i<obj.Get('chart.labels').length; ++i) {
str = (obj.Get('chart.labels').length > str.length ? obj.Get('chart.labels')[i] : str);
}
}
obj.context.font = obj.Get('chart.text.size') + 'pt ' + obj.Get('chart.text.font');
len = obj.context.measureText(str).width + 5;
return (obj.type == 'hbar' ? len / 3 : len);
}
/**
* A basic Array shift gunction
*
* @param object The numerical array to work on
* @return The new array
*/
RGraph.array_shift = function (arr)
{
var ret = [];
for (var i=1; i<arr.length; ++i) ret.push(arr[i]);
return ret;
}
/**
* If you prefer, you can use the SetConfig() method to set the configuration information
* for your chart. You may find that setting the configuration this way eases reuse.
*
* @param object obj The graph object
* @param object config The graph configuration information
*/
RGraph.SetConfig = function (obj, c)
{
for (i in c) {
if (typeof(i) == 'string') {
obj.Set(i, c[i]);
}
}
return obj;
}
/**
* This function gets the canvas height. Defaults to the actual
* height but this can be changed by setting chart.height.
*
* @param object obj The graph object
*/
RGraph.GetHeight = function (obj)
{
var height = obj.Get('chart.height');
return height ? height : obj.canvas.height;
}
/**
* This function gets the canvas width. Defaults to the actual
* width but this can be changed by setting chart.width.
*
* @param object obj The graph object
*/
RGraph.GetWidth = function (obj)
{
var width = obj.Get('chart.width');
return width ? width : obj.canvas.width;
}
/**
* Clears all the custom event listeners that have been registered
*
* @param string Limits the clearing to this object ID
*/
RGraph.RemoveAllCustomEventListeners = function ()
{
var id = arguments[0];
if (id && RGraph.events[id]) {
RGraph.events[id] = [];
} else {
RGraph.events = [];
}
}
/**
* Clears a particular custom event listener
*
* @param object obj The graph object
* @param number i This is the index that is return by .AddCustomEventListener()
*/
RGraph.RemoveCustomEventListener = function (obj, i)
{
if ( typeof(RGraph.events) == 'object'
&& typeof(RGraph.events[obj.id]) == 'object'
&& typeof(RGraph.events[obj.id][i]) == 'object') {
RGraph.events[obj.id][i] = null;
}
} | JavaScript |
/**
* o------------------------------------------------------------------------------o
* | This file is part of the RGraph package - you can learn more at: |
* | |
* | http://www.rgraph.net |
* | |
* | This package is licensed under the RGraph license. For all kinds of business |
* | purposes there is a small one-time licensing fee to pay and for non |
* | commercial purposes it is free to use. You can read the full license here: |
* | |
* | http://www.rgraph.net/LICENSE.txt |
* o------------------------------------------------------------------------------o
*/
if (typeof(RGraph) == 'undefined') RGraph = {};
/**
* The pie chart constructor
*
* @param data array The data to be represented on the pie chart
*/
RGraph.Pie = function (id, data)
{
this.id = id;
this.canvas = document.getElementById(id);
this.context = this.canvas.getContext("2d");
this.canvas.__object__ = this;
this.total = 0;
this.subTotal = 0;
this.angles = [];
this.data = data;
this.properties = [];
this.type = 'pie';
this.isRGraph = true;
/**
* Compatibility with older browsers
*/
RGraph.OldBrowserCompat(this.context);
this.properties = {
'chart.width': null,
'chart.height': null,
'chart.colors': ['rgb(255,0,0)', '#ddd', 'rgb(0,255,0)', 'rgb(0,0,255)', 'pink', 'yellow', 'red', 'rgb(0,255,255)', 'black', 'white'],
'chart.strokestyle': '#999',
'chart.linewidth': 1,
'chart.labels': [],
'chart.labels.sticks': false,
'chart.labels.sticks.color': '#aaa',
'chart.segments': [],
'chart.gutter': 25,
'chart.title': '',
'chart.title.background': null,
'chart.title.hpos': null,
'chart.title.vpos': null,
'chart.shadow': false,
'chart.shadow.color': 'rgba(0,0,0,0.5)',
'chart.shadow.offsetx': 3,
'chart.shadow.offsety': 3,
'chart.shadow.blur': 3,
'chart.text.size': 10,
'chart.text.color': 'black',
'chart.text.font': 'Verdana',
'chart.contextmenu': null,
'chart.tooltips': [],
'chart.tooltips.event': 'onclick',
'chart.tooltips.effect': 'fade',
'chart.tooltips.css.class': 'RGraph_tooltip',
'chart.tooltips.highlight': true,
'chart.highlight.style': '3d',
'chart.highlight.style.2d.fill': 'rgba(255,255,255,0.5)',
'chart.highlight.style.2d.stroke': 'rgba(255,255,255,0)',
'chart.radius': null,
'chart.border': false,
'chart.border.color': 'rgba(255,255,255,0.5)',
'chart.key': null,
'chart.key.background': 'white',
'chart.key.position': 'graph',
'chart.key.shadow': false,
'chart.key.shadow.color': '#666',
'chart.key.shadow.blur': 3,
'chart.key.shadow.offsetx': 2,
'chart.key.shadow.offsety': 2,
'chart.key.position.gutter.boxed': true,
'chart.key.position.x': null,
'chart.key.position.y': null,
'chart.key.color.shape': 'square',
'chart.key.rounded': true,
'chart.key.linewidth': 1,
'chart.annotatable': false,
'chart.annotate.color': 'black',
'chart.align': 'center',
'chart.zoom.factor': 1.5,
'chart.zoom.fade.in': true,
'chart.zoom.fade.out': true,
'chart.zoom.hdir': 'right',
'chart.zoom.vdir': 'down',
'chart.zoom.frames': 10,
'chart.zoom.delay': 50,
'chart.zoom.shadow': true,
'chart.zoom.mode': 'canvas',
'chart.zoom.thumbnail.width': 75,
'chart.zoom.thumbnail.height': 75,
'chart.zoom.background': true,
'chart.zoom.action': 'zoom',
'chart.resizable': false,
'chart.resize.handle.adjust': [0,0],
'chart.resize.handle.background': null,
'chart.variant': 'pie'
}
/**
* Calculate the total
*/
for (var i=0,len=data.length; i<len; i++) {
this.total += data[i];
}
// Check the common library has been included
if (typeof(RGraph) == 'undefined') {
alert('[PIE] Fatal error: The common library does not appear to have been included');
}
}
/**
* A generic setter
*/
RGraph.Pie.prototype.Set = function (name, value)
{
if (name == 'chart.highlight.style.2d.color') {
name = 'chart.highlight.style.2d.fill';
}
this.properties[name] = value;
}
/**
* A generic getter
*/
RGraph.Pie.prototype.Get = function (name)
{
if (name == 'chart.highlight.style.2d.color') {
name = 'chart.highlight.style.2d.fill';
}
return this.properties[name];
}
/**
* This draws the pie chart
*/
RGraph.Pie.prototype.Draw = function ()
{
/**
* Fire the onbeforedraw event
*/
RGraph.FireCustomEvent(this, 'onbeforedraw');
/**
* Clear all of this canvases event handlers (the ones installed by RGraph)
*/
RGraph.ClearEventListeners(this.id);
this.diameter = Math.min(RGraph.GetHeight(this), RGraph.GetWidth(this)) - (2 * this.Get('chart.gutter'));
this.radius = this.Get('chart.radius') ? this.Get('chart.radius') : this.diameter / 2;
// this.centerx now defined below
this.centery = RGraph.GetHeight(this) / 2;
this.subTotal = 0;
this.angles = [];
/**
* Alignment (Pie is center aligned by default) Only if centerx is not defined - donut defines the centerx
*/
if (this.Get('chart.align') == 'left') {
this.centerx = this.radius + this.Get('chart.gutter');
} else if (this.Get('chart.align') == 'right') {
this.centerx = RGraph.GetWidth(this) - (this.radius + this.Get('chart.gutter'));
} else {
this.centerx = RGraph.GetWidth(this) / 2;
}
/**
* Draw the shadow if required
*/
if (this.Get('chart.shadow')) {
var offsetx = document.all ? this.Get('chart.shadow.offsetx') : 0;
var offsety = document.all ? this.Get('chart.shadow.offsety') : 0;
this.context.beginPath();
this.context.fillStyle = this.Get('chart.shadow.color');
this.context.shadowColor = this.Get('chart.shadow.color');
this.context.shadowBlur = this.Get('chart.shadow.blur');
this.context.shadowOffsetX = this.Get('chart.shadow.offsetx');
this.context.shadowOffsetY = this.Get('chart.shadow.offsety');
this.context.arc(this.centerx + offsetx, this.centery + offsety, this.radius, 0, 6.28, 0);
this.context.fill();
// Now turn off the shadow
RGraph.NoShadow(this);
}
/**
* The total of the array of values
*/
this.total = RGraph.array_sum(this.data);
for (var i=0,len=this.data.length; i<len; i++) {
var angle = (this.data[i] / this.total) * 360;
this.DrawSegment(angle,
this.Get('chart.colors')[i],
i == (this.data.length - 1));
}
/**
* Redraw the seperating lines
*/
if (this.Get('chart.linewidth') > 0) {
this.context.beginPath();
this.context.lineWidth = this.Get('chart.linewidth');
this.context.strokeStyle = this.Get('chart.strokestyle');
for (var i=0,len=this.angles.length; i<len; ++i) {
this.context.moveTo(this.centerx, this.centery);
this.context.arc(this.centerx, this.centery, this.radius, this.angles[i][0] / 57.3, (this.angles[i][0] + 0.01) / 57.3, 0);
}
this.context.stroke();
/**
* And finally redraw the border
*/
this.context.beginPath();
this.context.moveTo(this.centerx, this.centery);
this.context.arc(this.centerx, this.centery, this.radius, 0, 6.28, 0);
this.context.stroke();
}
/**
* Draw label sticks
*/
if (this.Get('chart.labels.sticks')) {
this.DrawSticks();
// Redraw the border going around the Pie chart if the stroke style is NOT white
if (
this.Get('chart.strokestyle') != 'white'
&& this.Get('chart.strokestyle') != '#fff'
&& this.Get('chart.strokestyle') != '#fffffff'
&& this.Get('chart.strokestyle') != 'rgb(255,255,255)'
&& this.Get('chart.strokestyle') != 'rgba(255,255,255,0)'
) {
this.context.beginPath();
this.context.strokeStyle = this.Get('chart.strokestyle');
this.context.lineWidth = this.Get('chart.linewidth');
this.context.arc(this.centerx, this.centery, this.radius, 0, 6.28, false);
this.context.stroke();
}
}
/**
* Draw the labels
*/
this.DrawLabels();
/**
* Draw the title
*/
if (this.Get('chart.align') == 'left') {
var centerx = this.radius + this.Get('chart.gutter');
} else if (this.Get('chart.align') == 'right') {
var centerx = RGraph.GetWidth(this) - (this.radius + this.Get('chart.gutter'));
} else {
var centerx = null;
}
RGraph.DrawTitle(this.canvas, this.Get('chart.title'), this.Get('chart.gutter'), centerx, this.Get('chart.text.size') + 2);
/**
* Setup the context menu if required
*/
if (this.Get('chart.contextmenu')) {
RGraph.ShowContext(this);
}
/**
* Tooltips
*/
if (this.Get('chart.tooltips').length) {
/**
* Register this object for redrawing
*/
RGraph.Register(this);
/**
* The onclick event
*/
//this.canvas.onclick = function (e)
var canvas_onclick_func = function (e)
{
RGraph.HideZoomedCanvas();
e = RGraph.FixEventObject(e);
var mouseCoords = RGraph.getMouseXY(e);
var canvas = e.target;
var context = canvas.getContext('2d');
var obj = e.target.__object__;
var x = mouseCoords[0] - obj.centerx;
var y = mouseCoords[1] - obj.centery;
var theta = Math.atan(y / x); // RADIANS
var hyp = y / Math.sin(theta);
/**
* If it's actually a donut make sure the hyp is bigger
* than the size of the hole in the middle
*/
if (obj.Get('chart.variant') == 'donut' && Math.abs(hyp) < (obj.radius / 2)) {
return;
}
/**
* The angles for each segment are stored in "angles",
* so go through that checking if the mouse position corresponds
*/
var isDonut = obj.Get('chart.variant') == 'donut';
var hStyle = obj.Get('chart.highlight.style');
var segment = RGraph.getSegment(e);
if (segment) {
if (RGraph.Registry.Get('chart.tooltip') && segment[5] == RGraph.Registry.Get('chart.tooltip').__index__) {
return;
} else {
RGraph.Redraw();
}
if (isDonut || hStyle == '2d') {
context.beginPath();
context.strokeStyle = obj.Get('chart.highlight.style.2d.stroke');
context.fillStyle = obj.Get('chart.highlight.style.2d.fill');
context.moveTo(obj.centerx, obj.centery);
context.arc(obj.centerx, obj.centery, obj.radius, RGraph.degrees2Radians(obj.angles[segment[5]][0]), RGraph.degrees2Radians(obj.angles[segment[5]][1]), 0);
context.lineTo(obj.centerx, obj.centery);
context.closePath();
context.stroke();
context.fill();
//Removed 7th December 2010
//context.stroke();
} else {
context.lineWidth = 2;
/**
* Draw a white segment where the one that has been clicked on was
*/
context.fillStyle = 'white';
context.strokeStyle = 'white';
context.beginPath();
context.moveTo(obj.centerx, obj.centery);
context.arc(obj.centerx, obj.centery, obj.radius, obj.angles[segment[5]][0] / 57.3, obj.angles[segment[5]][1] / 57.3, 0);
context.stroke();
context.fill();
context.lineWidth = 1;
context.shadowColor = '#666';
context.shadowBlur = 3;
context.shadowOffsetX = 3;
context.shadowOffsetY = 3;
// Draw the new segment
context.beginPath();
context.fillStyle = obj.Get('chart.colors')[segment[5]];
context.strokeStyle = 'rgba(0,0,0,0)';
context.moveTo(obj.centerx - 3, obj.centery - 3);
context.arc(obj.centerx - 3, obj.centery - 3, obj.radius, RGraph.degrees2Radians(obj.angles[segment[5]][0]), RGraph.degrees2Radians(obj.angles[segment[5]][1]), 0);
context.lineTo(obj.centerx - 3, obj.centery - 3);
context.closePath();
context.stroke();
context.fill();
// Turn off the shadow
RGraph.NoShadow(obj);
/**
* If a border is defined, redraw that
*/
if (obj.Get('chart.border')) {
context.beginPath();
context.strokeStyle = obj.Get('chart.border.color');
context.lineWidth = 5;
context.arc(obj.centerx - 3, obj.centery - 3, obj.radius - 2, RGraph.degrees2Radians(obj.angles[i][0]), RGraph.degrees2Radians(obj.angles[i][1]), 0);
context.stroke();
}
}
/**
* If a tooltip is defined, show it
*/
/**
* Get the tooltip text
*/
if (typeof(obj.Get('chart.tooltips')) == 'function') {
var text = String(obj.Get('chart.tooltips')(segment[5]));
} else if (typeof(obj.Get('chart.tooltips')) == 'object' && typeof(obj.Get('chart.tooltips')[segment[5]]) == 'function') {
var text = String(obj.Get('chart.tooltips')[segment[5]](segment[5]));
} else if (typeof(obj.Get('chart.tooltips')) == 'object') {
var text = String(obj.Get('chart.tooltips')[segment[5]]);
} else {
var text = '';
}
if (text) {
RGraph.Tooltip(canvas, text, e.pageX, e.pageY, segment[5]);
}
/**
* Need to redraw the key?
*/
if (obj.Get('chart.key') && obj.Get('chart.key').length && obj.Get('chart.key.position') == 'graph') {
RGraph.DrawKey(obj, obj.Get('chart.key'), obj.Get('chart.colors'));
}
e.stopPropagation();
return;
}
}
var event_name = this.Get('chart.tooltips.event') == 'onmousemove' ? 'mousemove' : 'click';
this.canvas.addEventListener(event_name, canvas_onclick_func, false);
RGraph.AddEventListener(this.id, event_name, canvas_onclick_func);
/**
* The onmousemove event for changing the cursor
*/
//this.canvas.onmousemove = function (e)
var canvas_onmousemove_func = function (e)
{
RGraph.HideZoomedCanvas();
e = RGraph.FixEventObject(e);
var segment = RGraph.getSegment(e);
if (segment) {
e.target.style.cursor = 'pointer';
return;
}
/**
* Put the cursor back to null
*/
e.target.style.cursor = 'default';
}
this.canvas.addEventListener('mousemove', canvas_onmousemove_func, false);
RGraph.AddEventListener(this.id, 'mousemove', canvas_onmousemove_func);
}
/**
* If a border is pecified, draw it
*/
if (this.Get('chart.border')) {
this.context.beginPath();
this.context.lineWidth = 5;
this.context.strokeStyle = this.Get('chart.border.color');
this.context.arc(this.centerx,
this.centery,
this.radius - 2,
0,
6.28,
0);
this.context.stroke();
}
/**
* Draw the kay if desired
*/
if (this.Get('chart.key') != null) {
//this.Set('chart.key.position', 'graph');
RGraph.DrawKey(this, this.Get('chart.key'), this.Get('chart.colors'));
}
/**
* If this is actually a donut, draw a big circle in the middle
*/
if (this.Get('chart.variant') == 'donut') {
this.context.beginPath();
this.context.strokeStyle = this.Get('chart.strokestyle');
this.context.fillStyle = 'white';//this.Get('chart.fillstyle');
this.context.arc(this.centerx, this.centery, this.radius / 2, 0, 6.28, 0);
this.context.stroke();
this.context.fill();
}
RGraph.NoShadow(this);
/**
* If the canvas is annotatable, do install the event handlers
*/
if (this.Get('chart.annotatable')) {
RGraph.Annotate(this);
}
/**
* This bit shows the mini zoom window if requested
*/
if (this.Get('chart.zoom.mode') == 'thumbnail' || this.Get('chart.zoom.mode') == 'area') {
RGraph.ShowZoomWindow(this);
}
/**
* This function enables resizing
*/
if (this.Get('chart.resizable')) {
RGraph.AllowResizing(this);
}
/**
* Fire the RGraph ondraw event
*/
RGraph.FireCustomEvent(this, 'ondraw');
}
/**
* Draws a single segment of the pie chart
*
* @param int degrees The number of degrees for this segment
*/
RGraph.Pie.prototype.DrawSegment = function (degrees, color, last)
{
var context = this.context;
var canvas = this.canvas;
var subTotal = this.subTotal;
context.beginPath();
context.fillStyle = color;
context.strokeStyle = this.Get('chart.strokestyle');
context.lineWidth = 0;
context.arc(this.centerx,
this.centery,
this.radius,
subTotal / 57.3,
(last ? 360 : subTotal + degrees) / 57.3,
0);
context.lineTo(this.centerx, this.centery);
// Keep hold of the angles
this.angles.push([subTotal, subTotal + degrees])
this.context.closePath();
this.context.fill();
/**
* Calculate the segment angle
*/
this.Get('chart.segments').push([subTotal, subTotal + degrees]);
this.subTotal += degrees;
}
/**
* Draws the graphs labels
*/
RGraph.Pie.prototype.DrawLabels = function ()
{
var hAlignment = 'left';
var vAlignment = 'center';
var labels = this.Get('chart.labels');
var context = this.context;
/**
* Turn the shadow off
*/
RGraph.NoShadow(this);
context.fillStyle = 'black';
context.beginPath();
/**
* Draw the key (ie. the labels)
*/
if (labels && labels.length) {
var text_size = this.Get('chart.text.size');
for (i=0; i<labels.length; ++i) {
/**
* T|his ensures that if we're given too many labels, that we don't get an error
*/
if (typeof(this.Get('chart.segments')[i]) == 'undefined') {
continue;
}
// Move to the centre
context.moveTo(this.centerx,this.centery);
var a = this.Get('chart.segments')[i][0] + ((this.Get('chart.segments')[i][1] - this.Get('chart.segments')[i][0]) / 2);
/**
* Alignment
*/
if (a < 90) {
hAlignment = 'left';
vAlignment = 'center';
} else if (a < 180) {
hAlignment = 'right';
vAlignment = 'center';
} else if (a < 270) {
hAlignment = 'right';
vAlignment = 'center';
} else if (a < 360) {
hAlignment = 'left';
vAlignment = 'center';
}
context.fillStyle = this.Get('chart.text.color');
RGraph.Text(context,
this.Get('chart.text.font'),
text_size,
this.centerx + ((this.radius + 10)* Math.cos(a / 57.3)) + (this.Get('chart.labels.sticks') ? (a < 90 || a > 270 ? 2 : -2) : 0),
this.centery + (((this.radius + 10) * Math.sin(a / 57.3))),
labels[i],
vAlignment,
hAlignment);
}
context.fill();
}
}
/**
* This function draws the pie chart sticks (for the labels)
*/
RGraph.Pie.prototype.DrawSticks = function ()
{
var context = this.context;
var segments = this.Get('chart.segments');
var offset = this.Get('chart.linewidth') / 2;
for (var i=0; i<segments.length; ++i) {
var degrees = segments[i][1] - segments[i][0];
context.beginPath();
context.strokeStyle = this.Get('chart.labels.sticks.color');
context.lineWidth = 1;
var midpoint = (segments[i][0] + (degrees / 2)) / 57.3;
context.arc(this.centerx,
this.centery,
this.radius + 7,
midpoint,
midpoint + 0.01,
0);
context.arc(this.centerx,
this.centery,
this.radius - offset,
midpoint,
midpoint + 0.01,
0);
context.stroke();
}
} | JavaScript |
// --------------
function myDrawPie( title , labels , values){
var pie = new RGraph.Pie('pie', values);
pie.Set('chart.colors', ['#009933','#ff3300','#3333FF']);
pie.Set('chart.key', labels);
pie.Set('chart.key.position', 'gutter');
pie.Set('chart.gutter', 20);
pie.Set('chart.linewidth', 2);
pie.Set('chart.shadow', true);
pie.Set('chart.strokestyle', '#FFF');
pie.Draw();
}
function myDrawLine(principalData , interestData , paymentData, commissionData ,xLabels , legend){
var line = new RGraph.Line("line", [principalData,interestData,paymentData,commissionData]);
line.Set('chart.background.grid.width', 0.5);
line.Set('chart.colors', ['#009933','#ff3300','#FF00FF','#3333FF']);
line.Set('chart.linewidth', 3);
line.Set('chart.hmargin', 2);
line.Set('chart.labels', xLabels);
line.Set('chart.gutter', 40);
line.Set('chart.text.size', 8);
line.Set('chart.key', legend);
line.Set('chart.key.shadow', true);
line.Draw();
}
function myDrayAll(){
try{
myDrawPie(
window.schedule.getPieTitle(),
JSON.parse( window.schedule.getPieLabels()),
JSON.parse( window.schedule.getPieValues())
);
myDrawLine(
JSON.parse(window.schedule.getPrincipalPointsData()),
JSON.parse(window.schedule.getInterestPointsData()),
JSON.parse(window.schedule.getPaymentPointsData()),
JSON.parse(window.schedule.getCommissionPointsData()),
JSON.parse(window.schedule.getXLabels()),
JSON.parse(window.schedule.getLegend())
);
}catch( err ){
}
}
window.onload = function (){
myDrayAll();
};
| JavaScript |
/**
* o------------------------------------------------------------------------------o
* | This file is part of the RGraph package - you can learn more at: |
* | |
* | http://www.rgraph.net |
* | |
* | This package is licensed under the RGraph license. For all kinds of business |
* | purposes there is a small one-time licensing fee to pay and for non |
* | commercial purposes it is free to use. You can read the full license here: |
* | |
* | http://www.rgraph.net/LICENSE.txt |
* o------------------------------------------------------------------------------o
*/
if (typeof(RGraph) == 'undefined') RGraph = {};
/**
* The line chart constructor
*
* @param object canvas The cxanvas object
* @param array data The chart data
* @param array ... Other lines to plot
*/
RGraph.Line = function (id)
{
// Get the canvas and context objects
this.id = id;
this.canvas = document.getElementById(id);
this.context = this.canvas.getContext ? this.canvas.getContext("2d") : null;
this.canvas.__object__ = this;
this.type = 'line';
this.max = 0;
this.coords = [];
this.coords2 = [];
this.coords.key = [];
this.hasnegativevalues = false;
this.isRGraph = true;
/**
* Compatibility with older browsers
*/
RGraph.OldBrowserCompat(this.context);
// Various config type stuff
this.properties = {
'chart.width': null,
'chart.height': null,
'chart.background.barcolor1': 'rgba(0,0,0,0)',
'chart.background.barcolor2': 'rgba(0,0,0,0)',
'chart.background.grid': 1,
'chart.background.grid.width': 1,
'chart.background.grid.hsize': 25,
'chart.background.grid.vsize': 25,
'chart.background.grid.color': '#ddd',
'chart.background.grid.vlines': true,
'chart.background.grid.hlines': true,
'chart.background.grid.border': true,
'chart.background.grid.autofit': false,
'chart.background.grid.autofit.align': false,
'chart.background.grid.autofit.numhlines': 7,
'chart.background.grid.autofit.numvlines': 20,
'chart.background.hbars': null,
'chart.labels': null,
'chart.labels.ingraph': null,
'chart.labels.above': false,
'chart.labels.above.size': 8,
'chart.xtickgap': 20,
'chart.smallxticks': 3,
'chart.largexticks': 5,
'chart.ytickgap': 20,
'chart.smallyticks': 3,
'chart.largeyticks': 5,
'chart.linewidth': 1,
'chart.colors': ['red', '#0f0', '#00f', '#f0f', '#ff0', '#0ff'],
'chart.hmargin': 0,
'chart.tickmarks.dot.color': 'white',
'chart.tickmarks': null,
'chart.ticksize': 3,
'chart.gutter': 25,
'chart.tickdirection': -1,
'chart.yaxispoints': 5,
'chart.fillstyle': null,
'chart.xaxispos': 'bottom',
'chart.yaxispos': 'left',
'chart.xticks': null,
'chart.text.size': 10,
'chart.text.angle': 0,
'chart.text.color': 'black',
'chart.text.font': 'Verdana',
'chart.ymin': null,
'chart.ymax': null,
'chart.title': '',
'chart.title.background': null,
'chart.title.hpos': null,
'chart.title.vpos': null,
'chart.title.xaxis': '',
'chart.title.yaxis': '',
'chart.title.xaxis.pos': 0.25,
'chart.title.yaxis.pos': 0.25,
'chart.shadow': false,
'chart.shadow.offsetx': 2,
'chart.shadow.offsety': 2,
'chart.shadow.blur': 3,
'chart.shadow.color': 'rgba(0,0,0,0.5)',
'chart.tooltips': null,
'chart.tooltips.effect': 'fade',
'chart.tooltips.css.class': 'RGraph_tooltip',
'chart.tooltips.coords.adjust': [0,0],
'chart.tooltips.highlight': true,
'chart.highlight.stroke': '#999',
'chart.highlight.fill': 'white',
'chart.stepped': false,
'chart.key': [],
'chart.key.background': 'white',
'chart.key.position': 'graph',
'chart.key.shadow': false,
'chart.key.shadow.color': '#666',
'chart.key.shadow.blur': 3,
'chart.key.shadow.offsetx': 2,
'chart.key.shadow.offsety': 2,
'chart.key.position.gutter.boxed': true,
'chart.key.position.x': null,
'chart.key.position.y': null,
'chart.key.color.shape': 'square',
'chart.key.rounded': true,
'chart.key.linewidth': 1,
'chart.contextmenu': null,
'chart.ylabels': true,
'chart.ylabels.count': 5,
'chart.ylabels.inside': false,
'chart.ylabels.invert': false,
'chart.ylabels.specific': null,
'chart.xlabels.inside': false,
'chart.xlabels.inside.color': 'rgba(255,255,255,0.5)',
'chart.noaxes': false,
'chart.noyaxis': false,
'chart.noxaxis': false,
'chart.noendxtick': false,
'chart.units.post': '',
'chart.units.pre': '',
'chart.scale.decimals': null,
'chart.scale.point': '.',
'chart.scale.thousand': ',',
'chart.crosshairs': false,
'chart.crosshairs.color': '#333',
'chart.annotatable': false,
'chart.annotate.color': 'black',
'chart.axesontop': false,
'chart.filled.range': false,
'chart.variant': null,
'chart.axis.color': 'black',
'chart.zoom.factor': 1.5,
'chart.zoom.fade.in': true,
'chart.zoom.fade.out': true,
'chart.zoom.hdir': 'right',
'chart.zoom.vdir': 'down',
'chart.zoom.frames': 15,
'chart.zoom.delay': 33,
'chart.zoom.shadow': true,
'chart.zoom.mode': 'canvas',
'chart.zoom.thumbnail.width': 75,
'chart.zoom.thumbnail.height': 75,
'chart.zoom.background': true,
'chart.zoom.action': 'zoom',
'chart.backdrop': false,
'chart.backdrop.size': 30,
'chart.backdrop.alpha': 0.2,
'chart.resizable': false,
'chart.resize.handle.adjust': [0,0],
'chart.resize.handle.background': null,
'chart.adjustable': false,
'chart.noredraw': false,
'chart.outofbounds': false,
'chart.chromefix': true
}
/**
* Change null arguments to empty arrays
*/
for (var i=1; i<arguments.length; ++i) {
if (typeof(arguments[i]) == 'null' || !arguments[i]) {
arguments[i] = [];
}
}
// Check the common library has been included
if (typeof(RGraph) == 'undefined') {
alert('[LINE] Fatal error: The common library does not appear to have been included');
}
/**
* Store the original data. Thiss also allows for giving arguments as one big array.
*/
this.original_data = [];
for (var i=1; i<arguments.length; ++i) {
if (arguments[1] && typeof(arguments[1]) == 'object' && arguments[1][0] && typeof(arguments[1][0]) == 'object' && arguments[1][0].length) {
var tmp = [];
for (var i=0; i<arguments[1].length; ++i) {
tmp[i] = RGraph.array_clone(arguments[1][i]);
}
for (var j=0; j<tmp.length; ++j) {
this.original_data[j] = RGraph.array_clone(tmp[j]);
}
} else {
this.original_data[i - 1] = RGraph.array_clone(arguments[i]);
}
}
// Check for support
if (!this.canvas) {
alert('[LINE] Fatal error: no canvas support');
return;
}
/**
* Store the data here as one big array
*/
this.data_arr = [];
for (var i=1; i<arguments.length; ++i) {
for (var j=0; j<arguments[i].length; ++j) {
this.data_arr.push(arguments[i][j]);
}
}
}
/**
* An all encompassing accessor
*
* @param string name The name of the property
* @param mixed value The value of the property
*/
RGraph.Line.prototype.Set = function (name, value)
{
// Consolidate the tooltips
if (name == 'chart.tooltips') {
var tooltips = [];
for (var i=1; i<arguments.length; i++) {
if (typeof(arguments[i]) == 'object' && arguments[i][0]) {
for (var j=0; j<arguments[i].length; j++) {
tooltips.push(arguments[i][j]);
}
} else if (typeof(arguments[i]) == 'function') {
tooltips = arguments[i];
} else {
tooltips.push(arguments[i]);
}
}
// Because "value" is used further down at the end of this function, set it to the expanded array os tooltips
value = tooltips;
}
/**
* Reverse the tickmarks to make them correspond to the right line
*/
if (name == 'chart.tickmarks' && typeof(value) == 'object' && value) {
value = RGraph.array_reverse(value);
}
/**
* Inverted Y axis should show the bottom end of the scale
*/
if (name == 'chart.ylabels.invert' && value && this.Get('chart.ymin') == null) {
this.Set('chart.ymin', 0);
}
/**
* If (buggy) Chrome and the linewidth is 1, change it to 1.01
*/
if (name == 'chart.linewidth' && navigator.userAgent.match(/Chrome/) && value == 1) {
value = 1.01;
}
this.properties[name] = value;
}
/**
* An all encompassing accessor
*
* @param string name The name of the property
*/
RGraph.Line.prototype.Get = function (name)
{
return this.properties[name];
}
/**
* The function you call to draw the line chart
*/
RGraph.Line.prototype.Draw = function ()
{
/**
* Fire the onbeforedraw event
*/
RGraph.FireCustomEvent(this, 'onbeforedraw');
/**
* Clear all of this canvases event handlers (the ones installed by RGraph)
*/
RGraph.ClearEventListeners(this.id);
/**
* Check for Chrome 6 and shadow
*
* TODO Remove once it's been fixed (for a while)
* SEARCH TAGS: CHROME FIX SHADOW BUG
*/
if ( this.Get('chart.shadow')
&& navigator.userAgent.match(/Chrome/)
&& this.Get('chart.linewidth') <= 1
&& this.Get('chart.chromefix')
&& this.Get('chart.shadow.blur') > 0) {
alert('[RGRAPH WARNING] Chrome 6 has a shadow bug, meaning you should increase the linewidth to at least 1.01');
}
// Cache the gutter as an object variable
this.gutter = this.Get('chart.gutter');
// Reset the data back to that which was initially supplied
this.data = RGraph.array_clone(this.original_data);
// Reset the max value
this.max = 0;
/**
* Reverse the datasets so that the data and the labels tally
*/
this.data = RGraph.array_reverse(this.data);
if (this.Get('chart.filled') && !this.Get('chart.filled.range') && this.data.length > 1) {
var accumulation = [];
for (var set=0; set<this.data.length; ++set) {
for (var point=0; point<this.data[set].length; ++point) {
this.data[set][point] = Number(accumulation[point] ? accumulation[point] : 0) + this.data[set][point];
accumulation[point] = this.data[set][point];
}
}
}
/**
* Get the maximum Y scale value
*/
if (this.Get('chart.ymax')) {
this.max = this.Get('chart.ymax');
this.min = this.Get('chart.ymin') ? this.Get('chart.ymin') : 0;
this.scale = [
( ((this.max - this.min) * (1/5)) + this.min).toFixed(this.Get('chart.scale.decimals')),
( ((this.max - this.min) * (2/5)) + this.min).toFixed(this.Get('chart.scale.decimals')),
( ((this.max - this.min) * (3/5)) + this.min).toFixed(this.Get('chart.scale.decimals')),
( ((this.max - this.min) * (4/5)) + this.min).toFixed(this.Get('chart.scale.decimals')),
this.max.toFixed(this.Get('chart.scale.decimals'))
];
// Check for negative values
if (!this.Get('chart.outofbounds')) {
for (dataset=0; dataset<this.data.length; ++dataset) {
for (var datapoint=0; datapoint<this.data[dataset].length; datapoint++) {
// Check for negative values
this.hasnegativevalues = (this.data[dataset][datapoint] < 0) || this.hasnegativevalues;
}
}
}
} else {
this.min = this.Get('chart.ymin') ? this.Get('chart.ymin') : 0;
// Work out the max Y value
for (dataset=0; dataset<this.data.length; ++dataset) {
for (var datapoint=0; datapoint<this.data[dataset].length; datapoint++) {
this.max = Math.max(this.max, this.data[dataset][datapoint] ? Math.abs(parseFloat(this.data[dataset][datapoint])) : 0);
// Check for negative values
if (!this.Get('chart.outofbounds')) {
this.hasnegativevalues = (this.data[dataset][datapoint] < 0) || this.hasnegativevalues;
}
}
}
// 20th April 2009 - moved out of the above loop
this.scale = RGraph.getScale(Math.abs(parseFloat(this.max)), this);
this.max = this.scale[4] ? this.scale[4] : 0;
if (this.Get('chart.ymin')) {
this.scale[0] = ((this.max - this.Get('chart.ymin')) * (1/5)) + this.Get('chart.ymin');
this.scale[1] = ((this.max - this.Get('chart.ymin')) * (2/5)) + this.Get('chart.ymin');
this.scale[2] = ((this.max - this.Get('chart.ymin')) * (3/5)) + this.Get('chart.ymin');
this.scale[3] = ((this.max - this.Get('chart.ymin')) * (4/5)) + this.Get('chart.ymin');
this.scale[4] = ((this.max - this.Get('chart.ymin')) * (5/5)) + this.Get('chart.ymin');
}
if (typeof(this.Get('chart.scale.decimals')) == 'number') {
this.scale[0] = Number(this.scale[0]).toFixed(this.Get('chart.scale.decimals'));
this.scale[1] = Number(this.scale[1]).toFixed(this.Get('chart.scale.decimals'));
this.scale[2] = Number(this.scale[2]).toFixed(this.Get('chart.scale.decimals'));
this.scale[3] = Number(this.scale[3]).toFixed(this.Get('chart.scale.decimals'));
this.scale[4] = Number(this.scale[4]).toFixed(this.Get('chart.scale.decimals'));
}
}
/**
* Setup the context menu if required
*/
if (this.Get('chart.contextmenu')) {
RGraph.ShowContext(this);
}
/**
* Reset the coords array otherwise it will keep growing
*/
this.coords = [];
/**
* Work out a few things. They need to be here because they depend on things you can change before you
* call Draw() but after you instantiate the object
*/
this.grapharea = RGraph.GetHeight(this) - ( (2 * this.gutter));
this.halfgrapharea = this.grapharea / 2;
this.halfTextHeight = this.Get('chart.text.size') / 2;
// Check the combination of the X axis position and if there any negative values
//
// 19th Dec 2010 - removed for Opera since it can be reported incorrectly whn there
// are multiple graphs on the page
if (this.Get('chart.xaxispos') == 'bottom' && this.hasnegativevalues && navigator.userAgent.indexOf('Opera') == -1) {
alert('[LINE] You have negative values and the X axis is at the bottom. This is not good...');
}
if (this.Get('chart.variant') == '3d') {
RGraph.Draw3DAxes(this);
}
// Progressively Draw the chart
RGraph.background.Draw(this);
/**
* Draw any horizontal bars that have been defined
*/
if (this.Get('chart.background.hbars') && this.Get('chart.background.hbars').length > 0) {
RGraph.DrawBars(this);
}
if (this.Get('chart.axesontop') == false) {
this.DrawAxes();
}
/**
* Handle the appropriate shadow color. This now facilitates an array of differing
* shadow colors
*/
var shadowColor = this.Get('chart.shadow.color');
if (typeof(shadowColor) == 'object') {
shadowColor = RGraph.array_reverse(RGraph.array_clone(this.Get('chart.shadow.color')));
}
for (var i=(this.data.length - 1), j=0; i>=0; i--, j++) {
this.context.beginPath();
/**
* Turn on the shadow if required
*/
if (this.Get('chart.shadow') && !this.Get('chart.filled')) {
/**
* Accommodate an array of shadow colors as well as a single string
*/
if (typeof(shadowColor) == 'object' && shadowColor[i - 1]) {
this.context.shadowColor = shadowColor[i];
} else if (typeof(shadowColor) == 'object') {
this.context.shadowColor = shadowColor[0];
} else if (typeof(shadowColor) == 'string') {
this.context.shadowColor = shadowColor;
}
this.context.shadowBlur = this.Get('chart.shadow.blur');
this.context.shadowOffsetX = this.Get('chart.shadow.offsetx');
this.context.shadowOffsetY = this.Get('chart.shadow.offsety');
} else if (this.Get('chart.filled') && this.Get('chart.shadow')) {
alert('[LINE] Shadows are not permitted when the line is filled');
}
/**
* Draw the line
*/
if (this.Get('chart.fillstyle')) {
if (typeof(this.Get('chart.fillstyle')) == 'object' && this.Get('chart.fillstyle')[j]) {
var fill = this.Get('chart.fillstyle')[j];
} else if (typeof(this.Get('chart.fillstyle')) == 'string') {
var fill = this.Get('chart.fillstyle');
} else {
alert('[LINE] Warning: chart.fillstyle must be either a string or an array with the same number of elements as you have sets of data');
}
} else if (this.Get('chart.filled')) {
var fill = this.Get('chart.colors')[j];
} else {
var fill = null;
}
/**
* Figure out the tickmark to use
*/
if (this.Get('chart.tickmarks') && typeof(this.Get('chart.tickmarks')) == 'object') {
var tickmarks = this.Get('chart.tickmarks')[i];
} else if (this.Get('chart.tickmarks') && typeof(this.Get('chart.tickmarks')) == 'string') {
var tickmarks = this.Get('chart.tickmarks');
} else if (this.Get('chart.tickmarks') && typeof(this.Get('chart.tickmarks')) == 'function') {
var tickmarks = this.Get('chart.tickmarks');
} else {
var tickmarks = null;
}
this.DrawLine(this.data[i],
this.Get('chart.colors')[j],
fill,
this.GetLineWidth(j),
tickmarks,
this.data.length - i - 1);
this.context.stroke();
}
/**
* If tooltips are defined, handle them
*/
if (this.Get('chart.tooltips') && (this.Get('chart.tooltips').length || typeof(this.Get('chart.tooltips')) == 'function')) {
// Need to register this object for redrawing
if (this.Get('chart.tooltips.highlight')) {
RGraph.Register(this);
}
canvas_onmousemove_func = function (e)
{
e = RGraph.FixEventObject(e);
var canvas = e.target;
var context = canvas.getContext('2d');
var obj = canvas.__object__;
var point = obj.getPoint(e);
if (obj.Get('chart.tooltips.highlight')) {
RGraph.Register(obj);
}
if ( point
&& typeof(point[0]) == 'object'
&& typeof(point[1]) == 'number'
&& typeof(point[2]) == 'number'
&& typeof(point[3]) == 'number'
) {
// point[0] is the graph object
var xCoord = point[1];
var yCoord = point[2];
var idx = point[3];
if ((obj.Get('chart.tooltips')[idx] || typeof(obj.Get('chart.tooltips')) == 'function')) {
// Get the tooltip text
if (typeof(obj.Get('chart.tooltips')) == 'function') {
var text = obj.Get('chart.tooltips')(idx);
} else if (typeof(obj.Get('chart.tooltips')) == 'object' && typeof(obj.Get('chart.tooltips')[idx]) == 'function') {
var text = obj.Get('chart.tooltips')[idx](idx);
} else if (typeof(obj.Get('chart.tooltips')) == 'object') {
var text = String(obj.Get('chart.tooltips')[idx]);
} else {
var text = '';
}
// No tooltip text - do nada
if (text.match(/^id:(.*)$/) && RGraph.getTooltipText(text).substring(0,3) == 'id:') {
return;
}
// Chnage the pointer to a hand
canvas.style.cursor = 'pointer';
/**
* If the tooltip is the same one as is currently visible (going by the array index), don't do squat and return.
*/
if (RGraph.Registry.Get('chart.tooltip') && RGraph.Registry.Get('chart.tooltip').__index__ == idx && RGraph.Registry.Get('chart.tooltip').__canvas__.id == canvas.id) {
return;
}
/**
* Redraw the graph
*/
if (obj.Get('chart.tooltips.highlight')) {
// Redraw the graph
RGraph.Redraw();
}
// SHOW THE CORRECT TOOLTIP
RGraph.Tooltip(canvas, text, e.pageX, e.pageY, idx);
// Store the tooltip index on the tooltip object
RGraph.Registry.Get('chart.tooltip').__index__ = Number(idx);
/**
* Highlight the graph
*/
if (obj.Get('chart.tooltips.highlight')) {
context.beginPath();
context.moveTo(xCoord, yCoord);
context.arc(xCoord, yCoord, 2, 0, 6.28, 0);
context.strokeStyle = obj.Get('chart.highlight.stroke');
context.fillStyle = obj.Get('chart.highlight.fill');
context.stroke();
context.fill();
}
e.stopPropagation();
return;
}
}
/**
* Not over a hotspot?
*/
canvas.style.cursor = 'default';
}
this.canvas.addEventListener('mousemove', canvas_onmousemove_func, false);
RGraph.AddEventListener(this.id, 'mousemove', canvas_onmousemove_func);
}
/**
* If the axes have been requested to be on top, do that
*/
if (this.Get('chart.axesontop')) {
this.DrawAxes();
}
/**
* Draw the labels
*/
this.DrawLabels();
/**
* Draw the range if necessary
*/
this.DrawRange();
// Draw a key if necessary
if (this.Get('chart.key').length) {
RGraph.DrawKey(this, this.Get('chart.key'), this.Get('chart.colors'));
}
/**
* Draw " above" labels if enabled
*/
if (this.Get('chart.labels.above')) {
this.DrawAboveLabels();
}
/**
* Draw the "in graph" labels
*/
RGraph.DrawInGraphLabels(this);
/**
* Draw crosschairs
*/
RGraph.DrawCrosshairs(this);
/**
* If the canvas is annotatable, do install the event handlers
*/
if (this.Get('chart.annotatable')) {
RGraph.Annotate(this);
}
/**
* Redraw the lines if a filled range is on the cards
*/
if (this.Get('chart.filled') && this.Get('chart.filled.range') && this.data.length == 2) {
this.context.beginPath();
var len = this.coords.length / 2;
this.context.lineWidth = this.Get('chart.linewidth');
this.context.strokeStyle = this.Get('chart.colors')[0];
for (var i=0; i<len; ++i) {
if (i == 0) {
this.context.moveTo(this.coords[i][0], this.coords[i][1]);
} else {
this.context.lineTo(this.coords[i][0], this.coords[i][1]);
}
}
this.context.stroke();
this.context.beginPath();
if (this.Get('chart.colors')[1]) {
this.context.strokeStyle = this.Get('chart.colors')[1];
}
for (var i=this.coords.length - 1; i>=len; --i) {
if (i == (this.coords.length - 1) ) {
this.context.moveTo(this.coords[i][0], this.coords[i][1]);
} else {
this.context.lineTo(this.coords[i][0], this.coords[i][1]);
}
}
this.context.stroke();
} else if (this.Get('chart.filled') && this.Get('chart.filled.range')) {
alert('[LINE] You must have only two sets of data for a filled range chart');
}
/**
* This bit shows the mini zoom window if requested
*/
if (this.Get('chart.zoom.mode') == 'thumbnail') {
RGraph.ShowZoomWindow(this);
}
/**
* This function enables the zoom in area mode
*/
if (this.Get('chart.zoom.mode') == 'area') {
RGraph.ZoomArea(this);
}
/**
* This function enables resizing
*/
if (this.Get('chart.resizable')) {
RGraph.AllowResizing(this);
}
/**
* This function enables adjustments
*/
if (this.Get('chart.adjustable')) {
RGraph.AllowAdjusting(this);
}
/**
* Fire the RGraph ondraw event
*/
RGraph.FireCustomEvent(this, 'ondraw');
}
/**
* Draws the axes
*/
RGraph.Line.prototype.DrawAxes = function ()
{
var gutter = this.gutter;
// Don't draw the axes?
if (this.Get('chart.noaxes')) {
return;
}
// Turn any shadow off
RGraph.NoShadow(this);
this.context.lineWidth = 1;
this.context.strokeStyle = this.Get('chart.axis.color');
this.context.beginPath();
// Draw the X axis
if (this.Get('chart.noxaxis') == false) {
if (this.Get('chart.xaxispos') == 'center') {
this.context.moveTo(gutter, this.grapharea / 2 + gutter);
this.context.lineTo(RGraph.GetWidth(this) - gutter, this.grapharea / 2 + gutter);
} else {
this.context.moveTo(gutter, RGraph.GetHeight(this) - gutter);
this.context.lineTo(RGraph.GetWidth(this) - gutter, RGraph.GetHeight(this) - gutter);
}
}
// Draw the Y axis
if (this.Get('chart.noyaxis') == false) {
if (this.Get('chart.yaxispos') == 'left') {
this.context.moveTo(gutter, gutter);
this.context.lineTo(gutter, RGraph.GetHeight(this) - (gutter) );
} else {
this.context.moveTo(RGraph.GetWidth(this) - gutter, gutter);
this.context.lineTo(RGraph.GetWidth(this) - gutter, RGraph.GetHeight(this) - gutter );
}
}
/**
* Draw the X tickmarks
*/
if (this.Get('chart.noxaxis') == false) {
var xTickInterval = (RGraph.GetWidth(this) - (2 * gutter)) / (this.Get('chart.xticks') ? this.Get('chart.xticks') : (this.data[0].length - 1));
for (x=gutter + (this.Get('chart.yaxispos') == 'left' ? xTickInterval : 0); x<=(RGraph.GetWidth(this) - gutter + 1 ); x+=xTickInterval) {
if (this.Get('chart.yaxispos') == 'right' && x >= (RGraph.GetWidth(this) - gutter - 1) ) {
break;
}
// If the last tick is not desired...
if (this.Get('chart.noendxtick')) {
if (this.Get('chart.yaxispos') == 'left' && x >= (RGraph.GetWidth(this) - gutter)) {
break;
} else if (this.Get('chart.yaxispos') == 'right' && x == gutter) {
continue;
}
}
var yStart = this.Get('chart.xaxispos') == 'center' ? (RGraph.GetHeight(this) / 2) - 3 : RGraph.GetHeight(this) - gutter;
var yEnd = this.Get('chart.xaxispos') == 'center' ? yStart + 6 : RGraph.GetHeight(this) - gutter - (x % 60 == 0 ? this.Get('chart.largexticks') * this.Get('chart.tickdirection') : this.Get('chart.smallxticks') * this.Get('chart.tickdirection'));
this.context.moveTo(x, yStart);
this.context.lineTo(x, yEnd);
}
// Draw an extra tickmark if there is no X axis, but there IS a Y axis
} else if (this.Get('chart.noyaxis') == false) {
if (this.Get('chart.yaxispos') == 'left') {
this.context.moveTo(this.Get('chart.gutter'), RGraph.GetHeight(this) - this.Get('chart.gutter'));
this.context.lineTo(this.Get('chart.gutter') - this.Get('chart.smallyticks'), RGraph.GetHeight(this) - this.Get('chart.gutter'));
} else {
this.context.moveTo(RGraph.GetWidth(this) - this.Get('chart.gutter'), RGraph.GetHeight(this) - this.Get('chart.gutter'));
this.context.lineTo(RGraph.GetWidth(this) - this.Get('chart.gutter') + this.Get('chart.smallyticks'), RGraph.GetHeight(this) - this.Get('chart.gutter'));
}
}
/**
* Draw the Y tickmarks
*/
if (this.Get('chart.noyaxis') == false) {
var counter = 0;
var adjustment = 0;
if (this.Get('chart.yaxispos') == 'right') {
adjustment = (RGraph.GetWidth(this) - (2 * gutter));
}
if (this.Get('chart.xaxispos') == 'center') {
var interval = (this.grapharea / 10);
var lineto = (this.Get('chart.yaxispos') == 'left' ? gutter : RGraph.GetWidth(this) - gutter + this.Get('chart.smallyticks'));
// Draw the upper halves Y tick marks
for (y=gutter; y < (this.grapharea / 2) + gutter; y+=interval) {
this.context.moveTo((this.Get('chart.yaxispos') == 'left' ? gutter - this.Get('chart.smallyticks') : RGraph.GetWidth(this) - gutter), y);
this.context.lineTo(lineto, y);
}
// Draw the lower halves Y tick marks
for (y=gutter + (this.halfgrapharea) + interval; y <= this.grapharea + gutter; y+=interval) {
this.context.moveTo((this.Get('chart.yaxispos') == 'left' ? gutter - this.Get('chart.smallyticks') : RGraph.GetWidth(this) - gutter), y);
this.context.lineTo(lineto, y);
}
} else {
var lineto = (this.Get('chart.yaxispos') == 'left' ? gutter - this.Get('chart.smallyticks') : RGraph.GetWidth(this) - gutter + this.Get('chart.smallyticks'));
for (y=gutter; y < (RGraph.GetHeight(this) - gutter) && counter < 10; y+=( (RGraph.GetHeight(this) - (2 * gutter)) / 10) ) {
this.context.moveTo(gutter + adjustment, y);
this.context.lineTo(lineto, y);
var counter = counter +1;
}
}
// Draw an extra X tickmark
} else if (this.Get('chart.noxaxis') == false) {
if (this.Get('chart.yaxispos') == 'left') {
this.context.moveTo(this.Get('chart.gutter'), RGraph.GetHeight(this) - this.Get('chart.gutter'));
this.context.lineTo(this.Get('chart.gutter'), RGraph.GetHeight(this) - this.Get('chart.gutter') + this.Get('chart.smallxticks'));
} else {
this.context.moveTo(RGraph.GetWidth(this) - this.Get('chart.gutter'), RGraph.GetHeight(this) - this.Get('chart.gutter'));
this.context.lineTo(RGraph.GetWidth(this) - this.Get('chart.gutter'), RGraph.GetHeight(this) - this.Get('chart.gutter') + this.Get('chart.smallxticks'));
}
}
this.context.stroke();
}
/**
* Draw the text labels for the axes
*/
RGraph.Line.prototype.DrawLabels = function ()
{
this.context.strokeStyle = 'black';
this.context.fillStyle = this.Get('chart.text.color');
this.context.lineWidth = 1;
// Turn off any shadow
RGraph.NoShadow(this);
// This needs to be here
var font = this.Get('chart.text.font');
var gutter = this.Get('chart.gutter');
var text_size = this.Get('chart.text.size');
var context = this.context;
var canvas = this.canvas;
// Draw the Y axis labels
if (this.Get('chart.ylabels') && this.Get('chart.ylabels.specific') == null) {
var units_pre = this.Get('chart.units.pre');
var units_post = this.Get('chart.units.post');
var xpos = this.Get('chart.yaxispos') == 'left' ? gutter - 5 : RGraph.GetWidth(this) - gutter + 5;
var align = this.Get('chart.yaxispos') == 'left' ? 'right' : 'left';
var numYLabels = this.Get('chart.ylabels.count');
var bounding = false;
var bgcolor = this.Get('chart.ylabels.inside') ? this.Get('chart.ylabels.inside.color') : null;
/**
* If the Y labels are inside the Y axis, invert the alignment
*/
if (this.Get('chart.ylabels.inside') == true && align == 'left') {
xpos -= 10;
align = 'right';
bounding = true;
} else if (this.Get('chart.ylabels.inside') == true && align == 'right') {
xpos += 10;
align = 'left';
bounding = true;
}
if (this.Get('chart.xaxispos') == 'center') {
var half = this.grapharea / 2;
if (numYLabels == 1 || numYLabels == 3 || numYLabels == 5) {
// Draw the upper halves labels
RGraph.Text(context, font, text_size, xpos, gutter + ( (0/5) * half ) + this.halfTextHeight, RGraph.number_format(this, this.scale[4], units_pre, units_post), null, align, bounding, null, bgcolor);
if (numYLabels == 5) {
RGraph.Text(context, font, text_size, xpos, gutter + ( (1/5) * half ) + this.halfTextHeight, RGraph.number_format(this, this.scale[3], units_pre, units_post), null, align, bounding, null, bgcolor);
RGraph.Text(context, font, text_size, xpos, gutter + ( (3/5) * half ) + this.halfTextHeight, RGraph.number_format(this, this.scale[1], units_pre, units_post), null, align, bounding, null, bgcolor);
}
if (numYLabels >= 3) {
RGraph.Text(context, font, text_size, xpos, gutter + ( (2/5) * half ) + this.halfTextHeight, RGraph.number_format(this, this.scale[2], units_pre, units_post), null, align, bounding, null, bgcolor);
RGraph.Text(context, font, text_size, xpos, gutter + ( (4/5) * half ) + this.halfTextHeight, RGraph.number_format(this, this.scale[0], units_pre, units_post), null, align, bounding, null, bgcolor);
}
// Draw the lower halves labels
if (numYLabels >= 3) {
RGraph.Text(context, font, text_size, xpos, gutter + ( (6/5) * half ) + this.halfTextHeight, '-' + RGraph.number_format(this, this.scale[0], units_pre, units_post), null, align, bounding, null, bgcolor);
RGraph.Text(context, font, text_size, xpos, gutter + ( (8/5) * half ) + this.halfTextHeight, '-' + RGraph.number_format(this, this.scale[2], units_pre, units_post), null, align, bounding, null, bgcolor);
}
if (numYLabels == 5) {
RGraph.Text(context, font, text_size, xpos, gutter + ( (7/5) * half ) + this.halfTextHeight, '-' + RGraph.number_format(this, this.scale[1], units_pre, units_post), null, align, bounding, null, bgcolor);
RGraph.Text(context, font, text_size, xpos, gutter + ( (9/5) * half ) + this.halfTextHeight, '-' + RGraph.number_format(this, this.scale[3], units_pre, units_post), null, align, bounding, null, bgcolor);
}
RGraph.Text(context, font, text_size, xpos, gutter + ( (10/5) * half ) + this.halfTextHeight, '-' + RGraph.number_format(this, (this.scale[4] == '1.0' ? '1.0' : this.scale[4]), units_pre, units_post), null, align, bounding, null, bgcolor);
} else if (numYLabels == 10) {
// 10 Y labels
var interval = (this.grapharea / numYLabels) / 2;
for (var i=0; i<numYLabels; ++i) {
// This draws the upper halves labels
RGraph.Text(context,font, text_size, xpos, gutter + this.halfTextHeight + ((i/20) * (this.grapharea) ), RGraph.number_format(this, ((this.scale[4] / numYLabels) * (numYLabels - i)).toFixed((this.Get('chart.scale.decimals'))),units_pre, units_post), null, align, bounding, null, bgcolor);
// And this draws the lower halves labels
RGraph.Text(context, font, text_size, xpos,
gutter + this.halfTextHeight + ((i/20) * this.grapharea) + (this.grapharea / 2) + (this.grapharea / 20),
'-' + RGraph.number_format(this, (this.scale[4] - ((this.scale[4] / numYLabels) * (numYLabels - i - 1))).toFixed((this.Get('chart.scale.decimals'))),units_pre, units_post), null, align, bounding, null, bgcolor);
}
} else {
alert('[LINE SCALE] The number of Y labels must be 1/3/5/10');
}
// Draw the lower limit if chart.ymin is specified
if (typeof(this.Get('chart.ymin')) == 'number') {
RGraph.Text(context, font, text_size, xpos, RGraph.GetHeight(this) / 2, RGraph.number_format(this, this.Get('chart.ymin').toFixed(this.Get('chart.scale.decimals')), units_pre, units_post), 'center', align, bounding, null, bgcolor);
}
// No X axis - so draw 0
if (this.Get('chart.noxaxis') == true) {
RGraph.Text(context,font,text_size,xpos,gutter + ( (5/5) * half ) + this.halfTextHeight,'0',null, align, bounding, null, bgcolor);
}
} else {
/**
* Accommodate reversing the Y labels
*/
if (this.Get('chart.ylabels.invert')) {
this.scale = RGraph.array_reverse(this.scale);
this.context.translate(0, this.grapharea * 0.2);
if (typeof(this.Get('chart.ymin')) == null) {
this.Set('chart.ymin', 0);
}
}
if (numYLabels == 1 || numYLabels == 3 || numYLabels == 5) {
RGraph.Text(context, font, text_size, xpos, gutter + this.halfTextHeight + ((0/5) * (this.grapharea ) ), RGraph.number_format(this, this.scale[4], units_pre, units_post), null, align, bounding, null, bgcolor);
if (numYLabels == 5) {
RGraph.Text(context, font, text_size, xpos, gutter + this.halfTextHeight + ((3/5) * (this.grapharea) ), RGraph.number_format(this, this.scale[1], units_pre, units_post), null, align, bounding, null, bgcolor);
RGraph.Text(context, font, text_size, xpos, gutter + this.halfTextHeight + ((1/5) * (this.grapharea) ), RGraph.number_format(this, this.scale[3], units_pre, units_post), null, align, bounding, null, bgcolor);
}
if (numYLabels >= 3) {
RGraph.Text(context, font, text_size, xpos, gutter + this.halfTextHeight + ((2/5) * (this.grapharea ) ), RGraph.number_format(this, this.scale[2], units_pre, units_post), null, align, bounding, null, bgcolor);
RGraph.Text(context, font, text_size, xpos, gutter + this.halfTextHeight + ((4/5) * (this.grapharea) ), RGraph.number_format(this, this.scale[0], units_pre, units_post), null, align, bounding, null, bgcolor);
}
} else if (numYLabels == 10) {
// 10 Y labels
var interval = (this.grapharea / numYLabels) / 2;
for (var i=0; i<numYLabels; ++i) {
RGraph.Text(context,font,text_size,xpos,gutter + this.halfTextHeight + ((i/10) * (this.grapharea) ),RGraph.number_format(this,((this.scale[4] / numYLabels) * (numYLabels - i)).toFixed((this.Get('chart.scale.decimals'))),units_pre,units_post),null,align,bounding,null,bgcolor);
}
} else {
alert('[LINE SCALE] The number of Y labels must be 1/3/5/10');
}
/**
* Accommodate translating back after reversing the labels
*/
if (this.Get('chart.ylabels.invert')) {
this.context.translate(0, 0 - (this.grapharea * 0.2));
}
// Draw the lower limit if chart.ymin is specified
if (typeof(this.Get('chart.ymin')) == 'number') {
RGraph.Text(context,font,text_size,xpos,this.Get('chart.ylabels.invert') ? gutter : RGraph.GetHeight(this) - gutter,RGraph.number_format(this, this.Get('chart.ymin').toFixed(this.Get('chart.scale.decimals')), units_pre, units_post),'center',align,bounding,null,bgcolor);
}
}
// No X axis - so draw 0
if ( this.Get('chart.noxaxis') == true
&& this.Get('chart.ymin') == null
) {
RGraph.Text(context,font,text_size,xpos,RGraph.GetHeight(this) - gutter + this.halfTextHeight,'0',null, align, bounding, null, bgcolor);
}
} else if (this.Get('chart.ylabels') && typeof(this.Get('chart.ylabels.specific')) == 'object') {
// A few things
var gap = this.grapharea / this.Get('chart.ylabels.specific').length;
var halign = this.Get('chart.yaxispos') == 'left' ? 'right' : 'left';
var bounding = false;
var bgcolor = null;
// Figure out the X coord based on the position of the axis
if (this.Get('chart.yaxispos') == 'left') {
var x = gutter - 5;
if (this.Get('chart.ylabels.inside')) {
x += 10;
halign = 'left';
bounding = true;
bgcolor = 'rgba(255,255,255,0.5)';
}
} else if (this.Get('chart.yaxispos') == 'right') {
var x = RGraph.GetWidth(this) - gutter + 5;
if (this.Get('chart.ylabels.inside')) {
x -= 10;
halign = 'right';
bounding = true;
bgcolor = 'rgba(255,255,255,0.5)';
}
}
// Draw the labels
if (this.Get('chart.xaxispos') == 'center') {
// Draw the top halfs labels
for (var i=0; i<this.Get('chart.ylabels.specific').length; ++i) {
var y = gutter + ((this.grapharea / (this.Get('chart.ylabels.specific').length * 2) ) * i);
RGraph.Text(context, font, text_size,x,y,String(this.Get('chart.ylabels.specific')[i]), 'center', halign, bounding, 0, bgcolor);
}
// Now reverse the labels and draw the bottom half
var reversed_labels = RGraph.array_reverse(this.Get('chart.ylabels.specific'));
// Draw the bottom halfs labels
for (var i=0; i<reversed_labels.length; ++i) {
var y = (this.grapharea / 2) + gutter + ((this.grapharea / (reversed_labels.length * 2) ) * (i + 1));
RGraph.Text(context, font, text_size,x,y,String(reversed_labels[i]), 'center', halign, bounding, 0, bgcolor);
}
} else {
for (var i=0; i<this.Get('chart.ylabels.specific').length; ++i) {
var y = gutter + ((this.grapharea / this.Get('chart.ylabels.specific').length) * i);
RGraph.Text(context, font, text_size,x,y,String(this.Get('chart.ylabels.specific')[i]), 'center', halign, bounding, 0, bgcolor);
}
}
}
// Draw the X axis labels
if (this.Get('chart.labels') && this.Get('chart.labels').length > 0) {
var yOffset = 13;
var bordered = false;
var bgcolor = null;
if (this.Get('chart.xlabels.inside')) {
yOffset = -5;
bordered = true;
bgcolor = this.Get('chart.xlabels.inside.color');
}
/**
* Text angle
*/
var angle = 0;
var valign = null;
var halign = 'center';
if (typeof(this.Get('chart.text.angle')) == 'number' && this.Get('chart.text.angle') > 0) {
angle = -1 * this.Get('chart.text.angle');
valign = 'center';
halign = 'right';
yOffset = 5
}
this.context.fillStyle = this.Get('chart.text.color');
var numLabels = this.Get('chart.labels').length;
for (i=0; i<numLabels; ++i) {
// Changed 8th Nov 2010 to be not reliant on the coords
//if (this.Get('chart.labels')[i] && this.coords && this.coords[i] && this.coords[i][0]) {
if (this.Get('chart.labels')[i]) {
var labelX = ((RGraph.GetWidth(this) - (2 * this.Get('chart.gutter')) - (2 * this.Get('chart.hmargin'))) / (numLabels - 1) ) * i;
labelX += this.Get('chart.gutter') + this.Get('chart.hmargin');
/**
* Account for an unrelated number of labels
*/
if (this.Get('chart.labels').length != this.data[0].length) {
labelX = this.gutter + this.Get('chart.hmargin') + ((RGraph.GetWidth(this) - (2 * this.gutter) - (2 * this.Get('chart.hmargin'))) * (i / (this.Get('chart.labels').length - 1)));
}
// This accounts for there only being one point on the chart
if (!labelX) {
labelX = this.gutter + this.Get('chart.hmargin');
}
RGraph.Text(context, font,text_size,labelX,(RGraph.GetHeight(this) - gutter) + yOffset,String(this.Get('chart.labels')[i]),valign,halign,bordered,angle,bgcolor);
}
}
}
this.context.stroke();
this.context.fill();
}
/**
* Draws the line
*/
RGraph.Line.prototype.DrawLine = function (lineData, color, fill, linewidth, tickmarks, index)
{
var penUp = false;
var yPos = 0;
var xPos = 0;
this.context.lineWidth = 1;
var lineCoords = [];
var gutter = this.Get('chart.gutter');
// Work out the X interval
var xInterval = (RGraph.GetWidth(this) - (2 * this.Get('chart.hmargin')) - ( (2 * this.gutter)) ) / (lineData.length - 1);
// Loop thru each value given, plotting the line
for (i=0; i<lineData.length; i++) {
yPos = RGraph.GetHeight(this) - ( ( (lineData[i] - (lineData[i] > 0 ? this.Get('chart.ymin') : (-1 * this.Get('chart.ymin')) ) ) / (this.max - this.min) ) * ((RGraph.GetHeight(this) - (2 * this.gutter)) ));
if (this.Get('chart.ylabels.invert')) {
yPos -= gutter;
yPos -= gutter;
yPos = RGraph.GetHeight(this) - yPos;
}
// Make adjustments depending on the X axis position
if (this.Get('chart.xaxispos') == 'center') {
yPos /= 2;
} else if (this.Get('chart.xaxispos') == 'bottom') {
yPos -= this.gutter; // Without this the line is out of place due to the gutter
}
// Null data points
if (lineData[i] == null) {
yPos = null;
}
// Not always very noticeable, but it does have an effect
// with thick lines
this.context.lineCap = 'round';
this.context.lineJoin = 'round';
// Plot the line if we're at least on the second iteration
if (i > 0) {
xPos = xPos + xInterval;
} else {
xPos = this.Get('chart.hmargin') + gutter; // Might need to be this.gutter - 27th August 2010
}
/**
* Add the coords to an array
*/
this.coords.push([xPos, yPos]);
lineCoords.push([xPos, yPos]);
}
this.context.stroke();
// Store the coords in another format, indexed by line number
this.coords2[index] = lineCoords;
/**
* For IE only: Draw the shadow ourselves as ExCanvas doesn't produce shadows
*/
if (RGraph.isIE8() && this.Get('chart.shadow')) {
this.DrawIEShadow(lineCoords, this.context.shadowColor);
}
/**
* Now draw the actual line [FORMERLY SECOND]
*/
this.context.beginPath();
this.context.strokeStyle = 'rgba(240,240,240,0.9)'; // Almost transparent - changed on 10th May 2010
//this.context.strokeStyle = fill;
if (fill) this.context.fillStyle = fill;
var isStepped = this.Get('chart.stepped');
var isFilled = this.Get('chart.filled');
for (var i=0; i<lineCoords.length; ++i) {
xPos = lineCoords[i][0];
yPos = lineCoords[i][1];
var prevY = (lineCoords[i - 1] ? lineCoords[i - 1][1] : null);
var isLast = (i + 1) == lineCoords.length;
/**
* This nullifys values which are out-of-range
*/
if (prevY < this.Get('chart.gutter') || prevY > (RGraph.GetHeight(this) - this.Get('chart.gutter')) ) {
penUp = true;
}
if (i == 0 || penUp || !yPos || !prevY || prevY < this.gutter) {
if (this.Get('chart.filled') && !this.Get('chart.filled.range')) {
this.context.moveTo(xPos + 1, RGraph.GetHeight(this) - this.gutter - (this.Get('chart.xaxispos') == 'center' ? (RGraph.GetHeight(this) - (2 * this.gutter)) / 2 : 0) -1);
this.context.lineTo(xPos + 1, yPos);
} else {
this.context.moveTo(xPos, yPos);
}
penUp = false;
} else {
// Draw the stepped part of stepped lines
if (isStepped) {
this.context.lineTo(xPos, lineCoords[i - 1][1]);
}
if ((yPos >= this.gutter && yPos <= (RGraph.GetHeight(this) - this.gutter)) || this.Get('chart.outofbounds')) {
if (isLast && this.Get('chart.filled') && !this.Get('chart.filled.range') && this.Get('chart.yaxispos') == 'right') {
xPos -= 1;
}
// Added 8th September 2009
if (!isStepped || !isLast) {
this.context.lineTo(xPos, yPos);
if (isFilled && lineCoords[i+1] && lineCoords[i+1][1] == null) {
this.context.lineTo(xPos, RGraph.GetHeight(this) - this.gutter);
}
// Added August 2010
} else if (isStepped && isLast) {
this.context.lineTo(xPos,yPos);
}
penUp = false;
} else {
penUp = true;
}
}
}
if (this.Get('chart.filled') && !this.Get('chart.filled.range')) {
var fillStyle = this.Get('chart.fillstyle');
this.context.lineTo(xPos, RGraph.GetHeight(this) - this.gutter - 1 - + (this.Get('chart.xaxispos') == 'center' ? (RGraph.GetHeight(this) - (2 * this.gutter)) / 2 : 0));
this.context.fillStyle = fill;
this.context.fill();
this.context.beginPath();
}
/**
* FIXME this may need removing when Chrome is fixed
* SEARCH TAGS: CHROME SHADOW BUG
*/
if (navigator.userAgent.match(/Chrome/) && this.Get('chart.shadow') && this.Get('chart.chromefix') && this.Get('chart.shadow.blur') > 0) {
for (var i=lineCoords.length - 1; i>=0; --i) {
if (
typeof(lineCoords[i][1]) != 'number'
|| (typeof(lineCoords[i+1]) == 'object' && typeof(lineCoords[i+1][1]) != 'number')
) {
this.context.moveTo(lineCoords[i][0],lineCoords[i][1]);
} else {
this.context.lineTo(lineCoords[i][0],lineCoords[i][1]);
}
}
}
this.context.stroke();
if (this.Get('chart.backdrop')) {
this.DrawBackdrop(lineCoords, color);
}
// Now redraw the lines with the correct line width
this.RedrawLine(lineCoords, color, linewidth);
this.context.stroke();
// Draw the tickmarks
for (var i=0; i<lineCoords.length; ++i) {
i = Number(i);
if (isStepped && i == (lineCoords.length - 1)) {
this.context.beginPath();
//continue;
}
if (
(
tickmarks != 'endcircle'
&& tickmarks != 'endsquare'
&& tickmarks != 'filledendsquare'
&& tickmarks != 'endtick'
&& tickmarks != 'arrow'
&& tickmarks != 'filledarrow'
)
|| (i == 0 && tickmarks != 'arrow' && tickmarks != 'filledarrow')
|| i == (lineCoords.length - 1)
) {
var prevX = (i <= 0 ? null : lineCoords[i - 1][0]);
var prevY = (i <= 0 ? null : lineCoords[i - 1][1]);
this.DrawTick(lineData, lineCoords[i][0], lineCoords[i][1], color, false, prevX, prevY, tickmarks, i);
// Draws tickmarks on the stepped bits of stepped charts. Takend out 14th July 2010
//
//if (this.Get('chart.stepped') && lineCoords[i + 1] && this.Get('chart.tickmarks') != 'endsquare' && this.Get('chart.tickmarks') != 'endcircle' && this.Get('chart.tickmarks') != 'endtick') {
// this.DrawTick(lineCoords[i + 1][0], lineCoords[i][1], color);
//}
}
}
// Draw something off canvas to skirt an annoying bug
this.context.beginPath();
this.context.arc(RGraph.GetWidth(this) + 50000, RGraph.GetHeight(this) + 50000, 2, 0, 6.38, 1);
}
/**
* This functions draws a tick mark on the line
*
* @param xPos int The x position of the tickmark
* @param yPos int The y position of the tickmark
* @param color str The color of the tickmark
* @param bool Whether the tick is a shadow. If it is, it gets offset by the shadow offset
*/
RGraph.Line.prototype.DrawTick = function (lineData, xPos, yPos, color, isShadow, prevX, prevY, tickmarks, index)
{
var gutter = this.Get('chart.gutter');
// If the yPos is null - no tick
if ((yPos == null || yPos > (RGraph.GetHeight(this) - gutter) || yPos < gutter) && !this.Get('chart.outofbounds')) {
return;
}
this.context.beginPath();
var offset = 0;
// Reset the stroke and lineWidth back to the same as what they were when the line was drawm
this.context.lineWidth = this.Get('chart.linewidth');
this.context.strokeStyle = isShadow ? this.Get('chart.shadow.color') : this.context.strokeStyle;
this.context.fillStyle = isShadow ? this.Get('chart.shadow.color') : this.context.strokeStyle;
// Cicular tick marks
if ( tickmarks == 'circle'
|| tickmarks == 'filledcircle'
|| tickmarks == 'endcircle') {
if (tickmarks == 'circle'|| tickmarks == 'filledcircle' || (tickmarks == 'endcircle') ) {
this.context.beginPath();
this.context.arc(xPos + offset, yPos + offset, this.Get('chart.ticksize'), 0, 360 / (180 / Math.PI), false);
if (tickmarks == 'filledcircle') {
this.context.fillStyle = isShadow ? this.Get('chart.shadow.color') : this.context.strokeStyle;
} else {
this.context.fillStyle = isShadow ? this.Get('chart.shadow.color') : 'white';
}
this.context.fill();
this.context.stroke();
}
// Halfheight "Line" style tick marks
} else if (tickmarks == 'halftick') {
this.context.beginPath();
this.context.moveTo(xPos, yPos);
this.context.lineTo(xPos, yPos + this.Get('chart.ticksize'));
this.context.stroke();
// Tick style tickmarks
} else if (tickmarks == 'tick') {
this.context.beginPath();
this.context.moveTo(xPos, yPos - this.Get('chart.ticksize'));
this.context.lineTo(xPos, yPos + this.Get('chart.ticksize'));
this.context.stroke();
// Endtick style tickmarks
} else if (tickmarks == 'endtick') {
this.context.beginPath();
this.context.moveTo(xPos, yPos - this.Get('chart.ticksize'));
this.context.lineTo(xPos, yPos + this.Get('chart.ticksize'));
this.context.stroke();
// "Cross" style tick marks
} else if (tickmarks == 'cross') {
this.context.beginPath();
this.context.moveTo(xPos - this.Get('chart.ticksize'), yPos - this.Get('chart.ticksize'));
this.context.lineTo(xPos + this.Get('chart.ticksize'), yPos + this.Get('chart.ticksize'));
this.context.moveTo(xPos + this.Get('chart.ticksize'), yPos - this.Get('chart.ticksize'));
this.context.lineTo(xPos - this.Get('chart.ticksize'), yPos + this.Get('chart.ticksize'));
this.context.stroke();
// A white bordered circle
} else if (tickmarks == 'borderedcircle' || tickmarks == 'dot') {
this.context.lineWidth = 1;
this.context.strokeStyle = this.Get('chart.tickmarks.dot.color');
this.context.fillStyle = this.Get('chart.tickmarks.dot.color');
// The outer white circle
this.context.beginPath();
this.context.arc(xPos, yPos, this.Get('chart.ticksize'), 0, 360 / (180 / Math.PI), false);
this.context.closePath();
this.context.fill();
this.context.stroke();
// Now do the inners
this.context.beginPath();
this.context.fillStyle = color;
this.context.strokeStyle = color;
this.context.arc(xPos, yPos, this.Get('chart.ticksize') - 2, 0, 360 / (180 / Math.PI), false);
this.context.closePath();
this.context.fill();
this.context.stroke();
} else if ( tickmarks == 'square'
|| tickmarks == 'filledsquare'
|| (tickmarks == 'endsquare')
|| (tickmarks == 'filledendsquare') ) {
this.context.fillStyle = 'white';
this.context.strokeStyle = this.context.strokeStyle; // FIXME Is this correct?
this.context.beginPath();
this.context.strokeRect(xPos - this.Get('chart.ticksize'), yPos - this.Get('chart.ticksize'), this.Get('chart.ticksize') * 2, this.Get('chart.ticksize') * 2);
// Fillrect
if (tickmarks == 'filledsquare' || tickmarks == 'filledendsquare') {
this.context.fillStyle = isShadow ? this.Get('chart.shadow.color') : this.context.strokeStyle;
this.context.fillRect(xPos - this.Get('chart.ticksize'), yPos - this.Get('chart.ticksize'), this.Get('chart.ticksize') * 2, this.Get('chart.ticksize') * 2);
} else if (tickmarks == 'square' || tickmarks == 'endsquare') {
this.context.fillStyle = isShadow ? this.Get('chart.shadow.color') : 'white';
this.context.fillRect((xPos - this.Get('chart.ticksize')) + 1, (yPos - this.Get('chart.ticksize')) + 1, (this.Get('chart.ticksize') * 2) - 2, (this.Get('chart.ticksize') * 2) - 2);
}
this.context.stroke();
this.context.fill();
/**
* FILLED arrowhead
*/
} else if (tickmarks == 'filledarrow') {
var x = Math.abs(xPos - prevX);
var y = Math.abs(yPos - prevY);
if (yPos < prevY) {
var a = Math.atan(x / y) + 1.57;
} else {
var a = Math.atan(y / x) + 3.14;
}
this.context.beginPath();
this.context.moveTo(xPos, yPos);
this.context.arc(xPos, yPos, 7, a - 0.5, a + 0.5, false);
this.context.closePath();
this.context.stroke();
this.context.fill();
/**
* Arrow head, NOT filled
*/
} else if (tickmarks == 'arrow') {
var x = Math.abs(xPos - prevX);
var y = Math.abs(yPos - prevY);
if (yPos < prevY) {
var a = Math.atan(x / y) + 1.57;
} else {
var a = Math.atan(y / x) + 3.14;
}
this.context.beginPath();
this.context.moveTo(xPos, yPos);
this.context.arc(xPos, yPos, 7, a - 0.5 - (document.all ? 0.1 : 0.01), a - 0.4, false);
this.context.moveTo(xPos, yPos);
this.context.arc(xPos, yPos, 7, a + 0.5 + (document.all ? 0.1 : 0.01), a + 0.5, true);
this.context.stroke();
/**
* Custom tick drawing function
*/
} else if (typeof(tickmarks) == 'function') {
tickmarks(this, lineData, lineData[index], index, xPos, yPos, color, prevX, prevY);
}
}
/**
* Draws a filled range if necessary
*/
RGraph.Line.prototype.DrawRange = function ()
{
/**
* Fill the range if necessary
*/
if (this.Get('chart.filled.range') && this.Get('chart.filled')) {
this.context.beginPath();
this.context.fillStyle = this.Get('chart.fillstyle');
this.context.strokeStyle = this.Get('chart.fillstyle');
this.context.lineWidth = 1;
var len = (this.coords.length / 2);
for (var i=0; i<len; ++i) {
if (i == 0) {
this.context.moveTo(this.coords[i][0], this.coords[i][1])
} else {
this.context.lineTo(this.coords[i][0], this.coords[i][1])
}
}
for (var i=this.coords.length - 1; i>=len; --i) {
this.context.lineTo(this.coords[i][0], this.coords[i][1])
}
this.context.stroke();
this.context.fill();
}
}
/**
* Redraws the line with the correct line width etc
*
* @param array coords The coordinates of the line
*/
RGraph.Line.prototype.RedrawLine = function (coords, color, linewidth)
{
if (this.Get('chart.noredraw')) {
return;
}
this.context.beginPath();
this.context.strokeStyle = (typeof(color) == 'object' && color ? color[0] : color);
this.context.lineWidth = linewidth;
var len = coords.length;
var gutter = this.gutter;
var width = RGraph.GetWidth(this);
var height = RGraph.GetHeight(this);
var penUp = false;
for (var i=0; i<len; ++i) {
var xPos = coords[i][0];
var yPos = coords[i][1];
if (i > 0) {
var prevX = coords[i - 1][0];
var prevY = coords[i - 1][1];
}
if ((
(i == 0 && coords[i])
|| (yPos < gutter)
|| (prevY < gutter)
|| (yPos > (height - gutter))
|| (i > 0 && prevX > (width - gutter))
|| (i > 0 && prevY > (height - gutter))
|| prevY == null
|| penUp == true
) && !this.Get('chart.outofbounds')) {
this.context.moveTo(coords[i][0], coords[i][1]);
penUp = false;
} else {
if (this.Get('chart.stepped') && i > 0) {
this.context.lineTo(coords[i][0], coords[i - 1][1]);
}
// Don't draw the last bit of a stepped chart. Now DO
//if (!this.Get('chart.stepped') || i < (coords.length - 1)) {
this.context.lineTo(coords[i][0], coords[i][1]);
//}
penUp = false;
}
}
/**
* If two colors are specified instead of one, go over the up bits
*/
if (this.Get('chart.colors.alternate') && typeof(color) == 'object' && color[0] && color[1]) {
for (var i=1; i<len; ++i) {
var prevX = coords[i - 1][0];
var prevY = coords[i - 1][1];
this.context.beginPath();
this.context.strokeStyle = color[coords[i][1] < prevY ? 0 : 1];
this.context.lineWidth = this.Get('chart.linewidth');
this.context.moveTo(prevX, prevY);
this.context.lineTo(coords[i][0], coords[i][1]);
this.context.stroke();
}
}
}
/**
* This function is used by MSIE only to manually draw the shadow
*
* @param array coords The coords for the line
*/
RGraph.Line.prototype.DrawIEShadow = function (coords, color)
{
var offsetx = this.Get('chart.shadow.offsetx');
var offsety = this.Get('chart.shadow.offsety');
this.context.lineWidth = this.Get('chart.linewidth');
this.context.strokeStyle = color;
this.context.beginPath();
for (var i=0; i<coords.length; ++i) {
if (i == 0) {
this.context.moveTo(coords[i][0] + offsetx, coords[i][1] + offsety);
} else {
this.context.lineTo(coords[i][0] + offsetx, coords[i][1] + offsety);
}
}
this.context.stroke();
}
/**
* Draw the backdrop
*/
RGraph.Line.prototype.DrawBackdrop = function (coords, color)
{
var size = this.Get('chart.backdrop.size');
this.context.lineWidth = size;
this.context.globalAlpha = this.Get('chart.backdrop.alpha');
this.context.strokeStyle = color;
this.context.lineJoin = 'miter';
this.context.beginPath();
this.context.moveTo(coords[0][0], coords[0][1]);
for (var j=1; j<coords.length; ++j) {
this.context.lineTo(coords[j][0], coords[j][1]);
}
this.context.stroke();
// Reset the alpha value
this.context.globalAlpha = 1;
this.context.lineJoin = 'round';
RGraph.NoShadow(this);
}
/**
* Returns the linewidth
*/
RGraph.Line.prototype.GetLineWidth = function (i)
{
var linewidth = this.Get('chart.linewidth');
if (typeof(linewidth) == 'number') {
return linewidth;
} else if (typeof(linewidth) == 'object') {
if (linewidth[i]) {
return linewidth[i];
} else {
return linewidth[0];
}
alert('[LINE] Error! chart.linewidth should be a single number or an array of one or more numbers');
}
}
/**
* The getPoint() method - used to get the point the mouse is currently over, if any
*
* @param object e The event object
*/
RGraph.Line.prototype.getPoint = function (e)
{
var canvas = e.target;
var context = canvas.getContext('2d');
var obj = e.target.__object__;
var mouseXY = RGraph.getMouseXY(e);
var mouseX = mouseXY[0];
var mouseY = mouseXY[1];
for (var i=0; i<obj.coords.length; ++i) {
var xCoord = obj.coords[i][0];
var yCoord = obj.coords[i][1];
if ( mouseX <= (xCoord + 5 + obj.Get('chart.tooltips.coords.adjust')[0])
&& mouseX >= (xCoord - 5 + obj.Get('chart.tooltips.coords.adjust')[0])
&& mouseY <= (yCoord + 5 + obj.Get('chart.tooltips.coords.adjust')[1])
&& mouseY >= (yCoord - 5 + obj.Get('chart.tooltips.coords.adjust')[1])) {
return [obj, xCoord, yCoord, i];
}
}
}
/**
* Draws the above line labels
*/
RGraph.Line.prototype.DrawAboveLabels = function ()
{
var context = this.context;
var size = this.Get('chart.labels.above.size');
var font = this.Get('chart.text.font');
var units_pre = this.Get('chart.units.pre');
var units_post = this.Get('chart.units.post');
context.beginPath();
// Don't need to check that chart.labels.above is enabled here, it's been done already
for (var i=0; i<this.coords.length; ++i) {
var coords = this.coords[i];
RGraph.Text(context, font, size, coords[0], coords[1] - 5 - size, RGraph.number_format(this, this.data_arr[i], units_pre, units_post), 'center', 'center', true, null, 'rgba(255, 255, 255, 0.7)');
}
context.fill();
}
| JavaScript |
/**
* Creates a new level control.
* @constructor
* @param {IoMap} iomap the IO map controller.
* @param {Array.<string>} levels the levels to create switchers for.
*/
function LevelControl(iomap, levels) {
var that = this;
this.iomap_ = iomap;
this.el_ = this.initDom_(levels);
google.maps.event.addListener(iomap, 'level_changed', function() {
that.changeLevel_(iomap.get('level'));
});
}
/**
* Gets the DOM element for the control.
* @return {Element}
*/
LevelControl.prototype.getElement = function() {
return this.el_;
};
/**
* Creates the necessary DOM for the control.
* @return {Element}
*/
LevelControl.prototype.initDom_ = function(levelDefinition) {
var controlDiv = document.createElement('DIV');
controlDiv.setAttribute('id', 'levels-wrapper');
var levels = document.createElement('DIV');
levels.setAttribute('id', 'levels');
controlDiv.appendChild(levels);
var levelSelect = this.levelSelect_ = document.createElement('DIV');
levelSelect.setAttribute('id', 'level-select');
levels.appendChild(levelSelect);
this.levelDivs_ = [];
var that = this;
for (var i = 0, level; level = levelDefinition[i]; i++) {
var div = document.createElement('DIV');
div.innerHTML = 'Level ' + level;
div.setAttribute('id', 'level-' + level);
div.className = 'level';
levels.appendChild(div);
this.levelDivs_.push(div);
google.maps.event.addDomListener(div, 'click', function(e) {
var id = e.currentTarget.getAttribute('id');
var level = parseInt(id.replace('level-', ''), 10);
that.iomap_.setHash('level' + level);
});
}
controlDiv.index = 1;
return controlDiv;
};
/**
* Changes the highlighted level in the control.
* @param {number} level the level number to select.
*/
LevelControl.prototype.changeLevel_ = function(level) {
if (this.currentLevelDiv_) {
this.currentLevelDiv_.className =
this.currentLevelDiv_.className.replace(' level-selected', '');
}
var h = 25;
if (window['ioEmbed']) {
h = (window.screen.availWidth > 600) ? 34 : 24;
}
this.levelSelect_.style.top = 9 + ((level - 1) * h) + 'px';
var div = this.levelDivs_[level - 1];
div.className += ' level-selected';
this.currentLevelDiv_ = div;
};
| JavaScript |
// Copyright 2011 Google
/**
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* The Google IO Map
* @constructor
*/
var IoMap = function() {
var moscone = new google.maps.LatLng(37.78313383211993, -122.40394949913025);
/** @type {Node} */
this.mapDiv_ = document.getElementById(this.MAP_ID);
var ioStyle = [
{
'featureType': 'road',
stylers: [
{ hue: '#00aaff' },
{ gamma: 1.67 },
{ saturation: -24 },
{ lightness: -38 }
]
},{
'featureType': 'road',
'elementType': 'labels',
stylers: [
{ invert_lightness: true }
]
}];
/** @type {boolean} */
this.ready_ = false;
/** @type {google.maps.Map} */
this.map_ = new google.maps.Map(this.mapDiv_, {
zoom: 18,
center: moscone,
navigationControl: true,
mapTypeControl: false,
scaleControl: true,
mapTypeId: 'io',
streetViewControl: false
});
var style = /** @type {*} */(new google.maps.StyledMapType(ioStyle));
this.map_.mapTypes.set('io', /** @type {google.maps.MapType} */(style));
google.maps.event.addListenerOnce(this.map_, 'tilesloaded', function() {
if (window['MAP_CONTAINER'] !== undefined) {
window['MAP_CONTAINER']['onMapReady']();
}
});
/** @type {Array.<Floor>} */
this.floors_ = [];
for (var i = 0; i < this.LEVELS_.length; i++) {
this.floors_.push(new Floor(this.map_));
}
this.addLevelControl_();
this.addMapOverlay_();
this.loadMapContent_();
this.initLocationHashWatcher_();
if (!document.location.hash) {
this.showLevel(1, true);
}
}
IoMap.prototype = new google.maps.MVCObject;
/**
* The id of the Element to add the map to.
*
* @type {string}
* @const
*/
IoMap.prototype.MAP_ID = 'map-canvas';
/**
* The levels of the Moscone Center.
*
* @type {Array.<string>}
* @private
*/
IoMap.prototype.LEVELS_ = ['1', '2', '3'];
/**
* Location where the tiles are hosted.
*
* @type {string}
* @private
*/
IoMap.prototype.BASE_TILE_URL_ =
'http://www.gstatic.com/io2010maps/tiles/5/';
/**
* The minimum zoom level to show the overlay.
*
* @type {number}
* @private
*/
IoMap.prototype.MIN_ZOOM_ = 16;
/**
* The maximum zoom level to show the overlay.
*
* @type {number}
* @private
*/
IoMap.prototype.MAX_ZOOM_ = 20;
/**
* The template for loading tiles. Replace {L} with the level, {Z} with the
* zoom level, {X} and {Y} with respective tile coordinates.
*
* @type {string}
* @private
*/
IoMap.prototype.TILE_TEMPLATE_URL_ = IoMap.prototype.BASE_TILE_URL_ +
'L{L}_{Z}_{X}_{Y}.png';
/**
* @type {string}
* @private
*/
IoMap.prototype.SIMPLE_TILE_TEMPLATE_URL_ =
IoMap.prototype.BASE_TILE_URL_ + '{Z}_{X}_{Y}.png';
/**
* The extent of the overlay at certain zoom levels.
*
* @type {Object.<string, Array.<Array.<number>>>}
* @private
*/
IoMap.prototype.RESOLUTION_BOUNDS_ = {
16: [[10484, 10485], [25328, 25329]],
17: [[20969, 20970], [50657, 50658]],
18: [[41939, 41940], [101315, 101317]],
19: [[83878, 83881], [202631, 202634]],
20: [[167757, 167763], [405263, 405269]]
};
/**
* The previous hash to compare against.
*
* @type {string?}
* @private
*/
IoMap.prototype.prevHash_ = null;
/**
* Initialise the location hash watcher.
*
* @private
*/
IoMap.prototype.initLocationHashWatcher_ = function() {
var that = this;
if ('onhashchange' in window) {
window.addEventListener('hashchange', function() {
that.parseHash_();
}, true);
} else {
var that = this
window.setInterval(function() {
that.parseHash_();
}, 100);
}
this.parseHash_();
};
/**
* Called from Android.
*
* @param {Number} x A percentage to pan left by.
*/
IoMap.prototype.panLeft = function(x) {
var div = this.map_.getDiv();
var left = div.clientWidth * x;
this.map_.panBy(left, 0);
};
IoMap.prototype['panLeft'] = IoMap.prototype.panLeft;
/**
* Adds the level switcher to the top left of the map.
*
* @private
*/
IoMap.prototype.addLevelControl_ = function() {
var control = new LevelControl(this, this.LEVELS_).getElement();
this.map_.controls[google.maps.ControlPosition.TOP_LEFT].push(control);
};
/**
* Shows a floor based on the content of location.hash.
*
* @private
*/
IoMap.prototype.parseHash_ = function() {
var hash = document.location.hash;
if (hash == this.prevHash_) {
return;
}
this.prevHash_ = hash;
var level = 1;
if (hash) {
var match = hash.match(/level(\d)(?:\:([\w-]+))?/);
if (match && match[1]) {
level = parseInt(match[1], 10);
}
}
this.showLevel(level, true);
};
/**
* Updates location.hash based on the currently shown floor.
*
* @param {string?} opt_hash
*/
IoMap.prototype.setHash = function(opt_hash) {
var hash = document.location.hash.substring(1);
if (hash == opt_hash) {
return;
}
if (opt_hash) {
document.location.hash = opt_hash;
} else {
document.location.hash = 'level' + this.get('level');
}
};
IoMap.prototype['setHash'] = IoMap.prototype.setHash;
/**
* Called from spreadsheets.
*/
IoMap.prototype.loadSandboxCallback = function(json) {
var updated = json['feed']['updated']['$t'];
var contentItems = [];
var ids = {};
var entries = json['feed']['entry'];
for (var i = 0, entry; entry = entries[i]; i++) {
var item = {};
item.companyName = entry['gsx$companyname']['$t'];
item.companyUrl = entry['gsx$companyurl']['$t'];
var p = entry['gsx$companypod']['$t'];
item.pod = p;
p = p.toLowerCase().replace(/\s+/, '');
item.sessionRoom = p;
contentItems.push(item);
};
this.sandboxItems_ = contentItems;
this.ready_ = true;
this.addMapContent_();
};
/**
* Called from spreadsheets.
*
* @param {Object} json The json feed from the spreadsheet.
*/
IoMap.prototype.loadSessionsCallback = function(json) {
var updated = json['feed']['updated']['$t'];
var contentItems = [];
var ids = {};
var entries = json['feed']['entry'];
for (var i = 0, entry; entry = entries[i]; i++) {
var item = {};
item.sessionDate = entry['gsx$sessiondate']['$t'];
item.sessionAbstract = entry['gsx$sessionabstract']['$t'];
item.sessionHashtag = entry['gsx$sessionhashtag']['$t'];
item.sessionLevel = entry['gsx$sessionlevel']['$t'];
item.sessionTitle = entry['gsx$sessiontitle']['$t'];
item.sessionTrack = entry['gsx$sessiontrack']['$t'];
item.sessionUrl = entry['gsx$sessionurl']['$t'];
item.sessionYoutubeUrl = entry['gsx$sessionyoutubeurl']['$t'];
item.sessionTime = entry['gsx$sessiontime']['$t'];
item.sessionRoom = entry['gsx$sessionroom']['$t'];
item.sessionTags = entry['gsx$sessiontags']['$t'];
item.sessionSpeakers = entry['gsx$sessionspeakers']['$t'];
if (item.sessionDate.indexOf('10') != -1) {
item.sessionDay = 10;
} else {
item.sessionDay = 11;
}
var timeParts = item.sessionTime.split('-');
item.sessionStart = this.convertTo24Hour_(timeParts[0]);
item.sessionEnd = this.convertTo24Hour_(timeParts[1]);
contentItems.push(item);
}
this.sessionItems_ = contentItems;
};
/**
* Converts the time in the spread sheet to 24 hour time.
*
* @param {string} time The time like 10:42am.
*/
IoMap.prototype.convertTo24Hour_ = function(time) {
var pm = time.indexOf('pm') != -1;
time = time.replace(/[am|pm]/ig, '');
if (pm) {
var bits = time.split(':');
var hr = parseInt(bits[0], 10);
if (hr < 12) {
time = (hr + 12) + ':' + bits[1];
}
}
return time;
};
/**
* Loads the map content from Google Spreadsheets.
*
* @private
*/
IoMap.prototype.loadMapContent_ = function() {
// Initiate a JSONP request.
var that = this;
// Add a exposed call back function
window['loadSessionsCallback'] = function(json) {
that.loadSessionsCallback(json);
}
// Add a exposed call back function
window['loadSandboxCallback'] = function(json) {
that.loadSandboxCallback(json);
}
var key = 'tmaLiaNqIWYYtuuhmIyG0uQ';
var worksheetIDs = {
sessions: 'od6',
sandbox: 'od4'
};
var jsonpUrl = 'http://spreadsheets.google.com/feeds/list/' +
key + '/' + worksheetIDs.sessions + '/public/values' +
'?alt=json-in-script&callback=loadSessionsCallback';
var script = document.createElement('script');
script.setAttribute('src', jsonpUrl);
script.setAttribute('type', 'text/javascript');
document.documentElement.firstChild.appendChild(script);
var jsonpUrl = 'http://spreadsheets.google.com/feeds/list/' +
key + '/' + worksheetIDs.sandbox + '/public/values' +
'?alt=json-in-script&callback=loadSandboxCallback';
var script = document.createElement('script');
script.setAttribute('src', jsonpUrl);
script.setAttribute('type', 'text/javascript');
document.documentElement.firstChild.appendChild(script);
};
/**
* Called from Android.
*
* @param {string} roomId The id of the room to load.
*/
IoMap.prototype.showLocationById = function(roomId) {
var locations = this.LOCATIONS_;
for (var level in locations) {
var levelId = level.replace('LEVEL', '');
for (var loc in locations[level]) {
var room = locations[level][loc];
if (loc == roomId) {
var pos = new google.maps.LatLng(room.lat, room.lng);
this.map_.panTo(pos);
this.map_.setZoom(19);
this.showLevel(levelId);
if (room.marker_) {
room.marker_.setAnimation(google.maps.Animation.BOUNCE);
// Disable the animation after 5 seconds.
window.setTimeout(function() {
room.marker_.setAnimation();
}, 5000);
}
return;
}
}
}
};
IoMap.prototype['showLocationById'] = IoMap.prototype.showLocationById;
/**
* Called when the level is changed. Hides and shows floors.
*/
IoMap.prototype['level_changed'] = function() {
var level = this.get('level');
if (this.infoWindow_) {
this.infoWindow_.setMap(null);
}
for (var i = 1, floor; floor = this.floors_[i - 1]; i++) {
if (i == level) {
floor.show();
} else {
floor.hide();
}
}
this.setHash('level' + level);
};
/**
* Shows a particular floor.
*
* @param {string} level The level to show.
* @param {boolean=} opt_force if true, changes the floor even if it's already
* the current floor.
*/
IoMap.prototype.showLevel = function(level, opt_force) {
if (!opt_force && level == this.get('level')) {
return;
}
this.set('level', level);
};
IoMap.prototype['showLevel'] = IoMap.prototype.showLevel;
/**
* Create a marker with the content item's correct icon.
*
* @param {Object} item The content item for the marker.
* @return {google.maps.Marker} The new marker.
* @private
*/
IoMap.prototype.createContentMarker_ = function(item) {
if (!item.icon) {
item.icon = 'generic';
}
var image;
var shadow;
switch(item.icon) {
case 'generic':
case 'info':
case 'media':
var image = new google.maps.MarkerImage(
'marker-' + item.icon + '.png',
new google.maps.Size(30, 28),
new google.maps.Point(0, 0),
new google.maps.Point(13, 26));
var shadow = new google.maps.MarkerImage(
'marker-shadow.png',
new google.maps.Size(30, 28),
new google.maps.Point(0,0),
new google.maps.Point(13, 26));
break;
case 'toilets':
var image = new google.maps.MarkerImage(
item.icon + '.png',
new google.maps.Size(35, 35),
new google.maps.Point(0, 0),
new google.maps.Point(17, 17));
break;
case 'elevator':
var image = new google.maps.MarkerImage(
item.icon + '.png',
new google.maps.Size(48, 26),
new google.maps.Point(0, 0),
new google.maps.Point(24, 13));
break;
}
var inactive = item.type == 'inactive';
var latLng = new google.maps.LatLng(item.lat, item.lng);
var marker = new SmartMarker({
position: latLng,
shadow: shadow,
icon: image,
title: item.title,
minZoom: inactive ? 19 : 18,
clickable: !inactive
});
marker['type_'] = item.type;
if (!inactive) {
var that = this;
google.maps.event.addListener(marker, 'click', function() {
that.openContentInfo_(item);
});
}
return marker;
};
/**
* Create a label with the content item's title atribute, if it exists.
*
* @param {Object} item The content item for the marker.
* @return {MapLabel?} The new label.
* @private
*/
IoMap.prototype.createContentLabel_ = function(item) {
if (!item.title || item.suppressLabel) {
return null;
}
var latLng = new google.maps.LatLng(item.lat, item.lng);
return new MapLabel({
'text': item.title,
'position': latLng,
'minZoom': item.labelMinZoom || 18,
'align': item.labelAlign || 'center',
'fontColor': item.labelColor,
'fontSize': item.labelSize || 12
});
}
/**
* Open a info window a content item.
*
* @param {Object} item A content item with content and a marker.
*/
IoMap.prototype.openContentInfo_ = function(item) {
if (window['MAP_CONTAINER'] !== undefined) {
window['MAP_CONTAINER']['openContentInfo'](item.room);
return;
}
var sessionBase = 'http://www.google.com/events/io/2011/sessions.html';
var now = new Date();
var may11 = new Date('May 11, 2011');
var day = now < may11 ? 10 : 11;
var type = item.type;
var id = item.id;
var title = item.title;
var content = ['<div class="infowindow">'];
var sessions = [];
var empty = true;
if (item.type == 'session') {
if (day == 10) {
content.push('<h3>' + title + ' - Tuesday May 10</h3>');
} else {
content.push('<h3>' + title + ' - Wednesday May 11</h3>');
}
for (var i = 0, session; session = this.sessionItems_[i]; i++) {
if (session.sessionRoom == item.room && session.sessionDay == day) {
sessions.push(session);
empty = false;
}
}
sessions.sort(this.sortSessions_);
for (var i = 0, session; session = sessions[i]; i++) {
content.push('<div class="session"><div class="session-time">' +
session.sessionTime + '</div><div class="session-title"><a href="' +
session.sessionUrl + '">' +
session.sessionTitle + '</a></div></div>');
}
}
if (item.type == 'sandbox') {
var sandboxName;
for (var i = 0, sandbox; sandbox = this.sandboxItems_[i]; i++) {
if (sandbox.sessionRoom == item.room) {
if (!sandboxName) {
sandboxName = sandbox.pod;
content.push('<h3>' + sandbox.pod + '</h3>');
content.push('<div class="sandbox">');
}
content.push('<div class="sandbox-items"><a href="http://' +
sandbox.companyUrl + '">' + sandbox.companyName + '</a></div>');
empty = false;
}
}
content.push('</div>');
empty = false;
}
if (empty) {
return;
}
content.push('</div>');
var pos = new google.maps.LatLng(item.lat, item.lng);
if (!this.infoWindow_) {
this.infoWindow_ = new google.maps.InfoWindow();
}
this.infoWindow_.setContent(content.join(''));
this.infoWindow_.setPosition(pos);
this.infoWindow_.open(this.map_);
};
/**
* A custom sort function to sort the sessions by start time.
*
* @param {string} a SessionA<enter description here>.
* @param {string} b SessionB.
* @return {boolean} True if sessionA is after sessionB.
*/
IoMap.prototype.sortSessions_ = function(a, b) {
var aStart = parseInt(a.sessionStart.replace(':', ''), 10);
var bStart = parseInt(b.sessionStart.replace(':', ''), 10);
return aStart > bStart;
};
/**
* Adds all overlays (markers, labels) to the map.
*/
IoMap.prototype.addMapContent_ = function() {
if (!this.ready_) {
return;
}
for (var i = 0, level; level = this.LEVELS_[i]; i++) {
var floor = this.floors_[i];
var locations = this.LOCATIONS_['LEVEL' + level];
for (var roomId in locations) {
var room = locations[roomId];
if (room.room == undefined) {
room.room = roomId;
}
if (room.type != 'label') {
var marker = this.createContentMarker_(room);
floor.addOverlay(marker);
room.marker_ = marker;
}
var label = this.createContentLabel_(room);
floor.addOverlay(label);
}
}
};
/**
* Gets the correct tile url for the coordinates and zoom.
*
* @param {google.maps.Point} coord The coordinate of the tile.
* @param {Number} zoom The current zoom level.
* @return {string} The url to the tile.
*/
IoMap.prototype.getTileUrl = function(coord, zoom) {
// Ensure that the requested resolution exists for this tile layer.
if (this.MIN_ZOOM_ > zoom || zoom > this.MAX_ZOOM_) {
return '';
}
// Ensure that the requested tile x,y exists.
if ((this.RESOLUTION_BOUNDS_[zoom][0][0] > coord.x ||
coord.x > this.RESOLUTION_BOUNDS_[zoom][0][1]) ||
(this.RESOLUTION_BOUNDS_[zoom][1][0] > coord.y ||
coord.y > this.RESOLUTION_BOUNDS_[zoom][1][1])) {
return '';
}
var template = this.TILE_TEMPLATE_URL_;
if (16 <= zoom && zoom <= 17) {
template = this.SIMPLE_TILE_TEMPLATE_URL_;
}
return template
.replace('{L}', /** @type string */(this.get('level')))
.replace('{Z}', /** @type string */(zoom))
.replace('{X}', /** @type string */(coord.x))
.replace('{Y}', /** @type string */(coord.y));
};
/**
* Add the floor overlay to the map.
*
* @private
*/
IoMap.prototype.addMapOverlay_ = function() {
var that = this;
var overlay = new google.maps.ImageMapType({
getTileUrl: function(coord, zoom) {
return that.getTileUrl(coord, zoom);
},
tileSize: new google.maps.Size(256, 256)
});
google.maps.event.addListener(this, 'level_changed', function() {
var overlays = that.map_.overlayMapTypes;
if (overlays.length) {
overlays.removeAt(0);
}
overlays.push(overlay);
});
};
/**
* All the features of the map.
* @type {Object.<string, Object.<string, Object.<string, *>>>}
*/
IoMap.prototype.LOCATIONS_ = {
'LEVEL1': {
'northentrance': {
lat: 37.78381535905965,
lng: -122.40362226963043,
title: 'Entrance',
type: 'label',
labelColor: '#006600',
labelAlign: 'left',
labelSize: 10
},
'eastentrance': {
lat: 37.78328434094279,
lng: -122.40319311618805,
title: 'Entrance',
type: 'label',
labelColor: '#006600',
labelAlign: 'left',
labelSize: 10
},
'lunchroom': {
lat: 37.783112633669575,
lng: -122.40407556295395,
title: 'Lunch Room'
},
'restroom1a': {
lat: 37.78372420652042,
lng: -122.40396961569786,
icon: 'toilets',
type: 'inactive',
title: 'Restroom',
suppressLabel: true
},
'elevator1a': {
lat: 37.783669090977035,
lng: -122.40389987826347,
icon: 'elevator',
type: 'inactive',
title: 'Elevators',
suppressLabel: true
},
'gearpickup': {
lat: 37.78367863020862,
lng: -122.4037617444992,
title: 'Gear Pickup',
type: 'label'
},
'checkin': {
lat: 37.78334369645064,
lng: -122.40335404872894,
title: 'Check In',
type: 'label'
},
'escalators1': {
lat: 37.78353872135503,
lng: -122.40336209535599,
title: 'Escalators',
type: 'label',
labelAlign: 'left'
}
},
'LEVEL2': {
'escalators2': {
lat: 37.78353872135503,
lng: -122.40336209535599,
title: 'Escalators',
type: 'label',
labelAlign: 'left',
labelMinZoom: 19
},
'press': {
lat: 37.78316774962791,
lng: -122.40360751748085,
title: 'Press Room',
type: 'label'
},
'restroom2a': {
lat: 37.7835334217721,
lng: -122.40386635065079,
icon: 'toilets',
type: 'inactive',
title: 'Restroom',
suppressLabel: true
},
'restroom2b': {
lat: 37.78250317562106,
lng: -122.40423113107681,
icon: 'toilets',
type: 'inactive',
title: 'Restroom',
suppressLabel: true
},
'elevator2a': {
lat: 37.783669090977035,
lng: -122.40389987826347,
icon: 'elevator',
type: 'inactive',
title: 'Elevators',
suppressLabel: true
},
'1': {
lat: 37.78346240732338,
lng: -122.40415401756763,
icon: 'media',
title: 'Room 1',
type: 'session',
room: '1'
},
'2': {
lat: 37.78335005596647,
lng: -122.40431495010853,
icon: 'media',
title: 'Room 2',
type: 'session',
room: '2'
},
'3': {
lat: 37.783215446097124,
lng: -122.404490634799,
icon: 'media',
title: 'Room 3',
type: 'session',
room: '3'
},
'4': {
lat: 37.78332461789977,
lng: -122.40381203591824,
icon: 'media',
title: 'Room 4',
type: 'session',
room: '4'
},
'5': {
lat: 37.783186828219335,
lng: -122.4039850383997,
icon: 'media',
title: 'Room 5',
type: 'session',
room: '5'
},
'6': {
lat: 37.783013000871364,
lng: -122.40420497953892,
icon: 'media',
title: 'Room 6',
type: 'session',
room: '6'
},
'7': {
lat: 37.7828783903882,
lng: -122.40438133478165,
icon: 'media',
title: 'Room 7',
type: 'session',
room: '7'
},
'8': {
lat: 37.78305009820564,
lng: -122.40378588438034,
icon: 'media',
title: 'Room 8',
type: 'session',
room: '8'
},
'9': {
lat: 37.78286673120095,
lng: -122.40402393043041,
icon: 'media',
title: 'Room 9',
type: 'session',
room: '9'
},
'10': {
lat: 37.782719401312626,
lng: -122.40420028567314,
icon: 'media',
title: 'Room 10',
type: 'session',
room: '10'
},
'appengine': {
lat: 37.783362774996625,
lng: -122.40335941314697,
type: 'sandbox',
icon: 'generic',
labelMinZoom: 19,
labelAlign: 'right',
title: 'App Engine'
},
'chrome': {
lat: 37.783730566003555,
lng: -122.40378990769386,
type: 'sandbox',
icon: 'generic',
title: 'Chrome'
},
'googleapps': {
lat: 37.783303419504094,
lng: -122.40320384502411,
type: 'sandbox',
icon: 'generic',
labelMinZoom: 19,
title: 'Apps'
},
'geo': {
lat: 37.783365954753805,
lng: -122.40314483642578,
type: 'sandbox',
icon: 'generic',
labelMinZoom: 19,
title: 'Geo'
},
'accessibility': {
lat: 37.783414711013485,
lng: -122.40342646837234,
type: 'sandbox',
icon: 'generic',
labelMinZoom: 19,
labelAlign: 'right',
title: 'Accessibility'
},
'developertools': {
lat: 37.783457107734876,
lng: -122.40347877144814,
type: 'sandbox',
icon: 'generic',
labelMinZoom: 19,
labelAlign: 'right',
title: 'Dev Tools'
},
'commerce': {
lat: 37.78349102509448,
lng: -122.40351900458336,
type: 'sandbox',
icon: 'generic',
labelMinZoom: 19,
labelAlign: 'right',
title: 'Commerce'
},
'youtube': {
lat: 37.783537661438515,
lng: -122.40358605980873,
type: 'sandbox',
icon: 'generic',
labelMinZoom: 19,
labelAlign: 'right',
title: 'YouTube'
},
'officehoursfloor2a': {
lat: 37.78249045644304,
lng: -122.40410104393959,
title: 'Office Hours',
type: 'label'
},
'officehoursfloor2': {
lat: 37.78266852473624,
lng: -122.40387573838234,
title: 'Office Hours',
type: 'label'
},
'officehoursfloor2b': {
lat: 37.782844472747406,
lng: -122.40365579724312,
title: 'Office Hours',
type: 'label'
}
},
'LEVEL3': {
'escalators3': {
lat: 37.78353872135503,
lng: -122.40336209535599,
title: 'Escalators',
type: 'label',
labelAlign: 'left'
},
'restroom3a': {
lat: 37.78372420652042,
lng: -122.40396961569786,
icon: 'toilets',
type: 'inactive',
title: 'Restroom',
suppressLabel: true
},
'restroom3b': {
lat: 37.78250317562106,
lng: -122.40423113107681,
icon: 'toilets',
type: 'inactive',
title: 'Restroom',
suppressLabel: true
},
'elevator3a': {
lat: 37.783669090977035,
lng: -122.40389987826347,
icon: 'elevator',
type: 'inactive',
title: 'Elevators',
suppressLabel: true
},
'keynote': {
lat: 37.783250423488326,
lng: -122.40417748689651,
icon: 'media',
title: 'Keynote',
type: 'label'
},
'11': {
lat: 37.78283069370135,
lng: -122.40408763289452,
icon: 'media',
title: 'Room 11',
type: 'session',
room: '11'
},
'googletv': {
lat: 37.7837125474666,
lng: -122.40362092852592,
type: 'sandbox',
icon: 'generic',
title: 'Google TV'
},
'android': {
lat: 37.783530242022124,
lng: -122.40358874201775,
type: 'sandbox',
icon: 'generic',
title: 'Android'
},
'officehoursfloor3': {
lat: 37.782843412820846,
lng: -122.40365579724312,
title: 'Office Hours',
type: 'label'
},
'officehoursfloor3a': {
lat: 37.78267170452323,
lng: -122.40387842059135,
title: 'Office Hours',
type: 'label'
}
}
};
google.maps.event.addDomListener(window, 'load', function() {
window['IoMap'] = new IoMap();
});
| JavaScript |
/**
* Creates a new Floor.
* @constructor
* @param {google.maps.Map=} opt_map
*/
function Floor(opt_map) {
/**
* @type Array.<google.maps.MVCObject>
*/
this.overlays_ = [];
/**
* @type boolean
*/
this.shown_ = true;
if (opt_map) {
this.setMap(opt_map);
}
}
/**
* @param {google.maps.Map} map
*/
Floor.prototype.setMap = function(map) {
this.map_ = map;
};
/**
* @param {google.maps.MVCObject} overlay For example, a Marker or MapLabel.
* Requires a setMap method.
*/
Floor.prototype.addOverlay = function(overlay) {
if (!overlay) return;
this.overlays_.push(overlay);
overlay.setMap(this.shown_ ? this.map_ : null);
};
/**
* Sets the map on all the overlays
* @param {google.maps.Map} map The map to set.
*/
Floor.prototype.setMapAll_ = function(map) {
this.shown_ = !!map;
for (var i = 0, overlay; overlay = this.overlays_[i]; i++) {
overlay.setMap(map);
}
};
/**
* Hides the floor and all associated overlays.
*/
Floor.prototype.hide = function() {
this.setMapAll_(null);
};
/**
* Shows the floor and all associated overlays.
*/
Floor.prototype.show = function() {
this.setMapAll_(this.map_);
};
| JavaScript |
/**
* @license
*
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview SmartMarker.
*
* @author Chris Broadfoot (cbro@google.com)
*/
/**
* A google.maps.Marker that has some smarts about the zoom levels it should be
* shown.
*
* Options are the same as google.maps.Marker, with the addition of minZoom and
* maxZoom. These zoom levels are inclusive. That is, a SmartMarker with
* a minZoom and maxZoom of 13 will only be shown at zoom level 13.
* @constructor
* @extends google.maps.Marker
* @param {Object=} opts Same as MarkerOptions, plus minZoom and maxZoom.
*/
function SmartMarker(opts) {
var marker = new google.maps.Marker;
// default min/max Zoom - shows the marker all the time.
marker.setValues({
'minZoom': 0,
'maxZoom': Infinity
});
// the current listener (if any), triggered on map zoom_changed
var mapZoomListener;
google.maps.event.addListener(marker, 'map_changed', function() {
if (mapZoomListener) {
google.maps.event.removeListener(mapZoomListener);
}
var map = marker.getMap();
if (map) {
var listener = SmartMarker.newZoomListener_(marker);
mapZoomListener = google.maps.event.addListener(map, 'zoom_changed',
listener);
// Call the listener straight away. The map may already be initialized,
// so it will take user input for zoom_changed to be fired.
listener();
}
});
marker.setValues(opts);
return marker;
}
window['SmartMarker'] = SmartMarker;
/**
* Creates a new listener to be triggered on 'zoom_changed' event.
* Hides and shows the target Marker based on the map's zoom level.
* @param {google.maps.Marker} marker The target marker.
* @return Function
*/
SmartMarker.newZoomListener_ = function(marker) {
var map = marker.getMap();
return function() {
var zoom = map.getZoom();
var minZoom = Number(marker.get('minZoom'));
var maxZoom = Number(marker.get('maxZoom'));
marker.setVisible(zoom >= minZoom && zoom <= maxZoom);
};
};
| JavaScript |
var Android = function() {
this._callbacks = [],
this._id = 0,
this._call = function(method, params) {
this._id += 1;
var request = JSON.stringify({'id': this._id, 'method': method, 'params': params});
var response = _rpc_wrapper.call(request);
return eval("(" + response + ")");
},
this.registerCallback = function(event, receiver) {
var id = this._callbacks.push(receiver) - 1;
_callback_wrapper.register(event, id);
},
this._callback = function(id, data) {
var receiver = this._callbacks[id];
receiver(data);
},
this.dismiss = function() {
_rpc_wrapper.dismiss();
}
};
| JavaScript |
var deviceInfo = function() {
document.getElementById("platform").innerHTML = device.platform;
document.getElementById("version").innerHTML = device.version;
document.getElementById("uuid").innerHTML = device.uuid;
document.getElementById("name").innerHTML = device.name;
document.getElementById("width").innerHTML = screen.width;
document.getElementById("height").innerHTML = screen.height;
document.getElementById("colorDepth").innerHTML = screen.colorDepth;
};
var getLocation = function() {
var suc = function(p) {
alert(p.coords.latitude + " " + p.coords.longitude);
};
var locFail = function() {
};
navigator.geolocation.getCurrentPosition(suc, locFail);
};
var beep = function() {
navigator.notification.beep(2);
};
var vibrate = function() {
navigator.notification.vibrate(0);
};
function roundNumber(num) {
var dec = 3;
var result = Math.round(num * Math.pow(10, dec)) / Math.pow(10, dec);
return result;
}
var accelerationWatch = null;
function updateAcceleration(a) {
document.getElementById('x').innerHTML = roundNumber(a.x);
document.getElementById('y').innerHTML = roundNumber(a.y);
document.getElementById('z').innerHTML = roundNumber(a.z);
}
var toggleAccel = function() {
if (accelerationWatch !== null) {
navigator.accelerometer.clearWatch(accelerationWatch);
updateAcceleration({
x : "",
y : "",
z : ""
});
accelerationWatch = null;
} else {
var options = {};
options.frequency = 1000;
accelerationWatch = navigator.accelerometer.watchAcceleration(
updateAcceleration, function(ex) {
alert("accel fail (" + ex.name + ": " + ex.message + ")");
}, options);
}
};
var preventBehavior = function(e) {
e.preventDefault();
};
function dump_pic(data) {
var viewport = document.getElementById('viewport');
console.log(data);
viewport.style.display = "";
viewport.style.position = "absolute";
viewport.style.top = "10px";
viewport.style.left = "10px";
document.getElementById("test_img").src = "data:image/jpeg;base64," + data;
}
function fail(msg) {
alert(msg);
}
function show_pic() {
navigator.camera.getPicture(dump_pic, fail, {
quality : 50
});
}
function close() {
var viewport = document.getElementById('viewport');
viewport.style.position = "relative";
viewport.style.display = "none";
}
function contacts_success(contacts) {
alert(contacts.length
+ ' contacts returned.'
+ (contacts[2] && contacts[2].name ? (' Third contact is ' + contacts[2].name.formatted)
: ''));
}
function get_contacts() {
var obj = new ContactFindOptions();
obj.filter = "";
obj.multiple = true;
navigator.contacts.find(
[ "displayName", "name" ], contacts_success,
fail, obj);
}
function check_network() {
var networkState = navigator.network.connection.type;
var states = {};
states[Connection.UNKNOWN] = 'Unknown connection';
states[Connection.ETHERNET] = 'Ethernet connection';
states[Connection.WIFI] = 'WiFi connection';
states[Connection.CELL_2G] = 'Cell 2G connection';
states[Connection.CELL_3G] = 'Cell 3G connection';
states[Connection.CELL_4G] = 'Cell 4G connection';
states[Connection.NONE] = 'No network connection';
confirm('Connection type:\n ' + states[networkState]);
}
function init() {
// the next line makes it impossible to see Contacts on the HTC Evo since it
// doesn't have a scroll button
// document.addEventListener("touchmove", preventBehavior, false);
document.addEventListener("deviceready", deviceInfo, true);
} | JavaScript |
/*
* PhoneGap is available under *either* the terms of the modified BSD license *or* the
* MIT License (2008). See http://opensource.org/licenses/alphabetical for full text.
*
* Copyright (c) 2005-2010, Nitobi Software Inc.
* Copyright (c) 2010-2011, IBM Corporation
*/
if (typeof PhoneGap === "undefined") {
/**
* The order of events during page load and PhoneGap startup is as follows:
*
* onDOMContentLoaded Internal event that is received when the web page is loaded and parsed.
* window.onload Body onload event.
* onNativeReady Internal event that indicates the PhoneGap native side is ready.
* onPhoneGapInit Internal event that kicks off creation of all PhoneGap JavaScript objects (runs constructors).
* onPhoneGapReady Internal event fired when all PhoneGap JavaScript objects have been created
* onPhoneGapInfoReady Internal event fired when device properties are available
* onDeviceReady User event fired to indicate that PhoneGap is ready
* onResume User event fired to indicate a start/resume lifecycle event
* onPause User event fired to indicate a pause lifecycle event
* onDestroy Internal event fired when app is being destroyed (User should use window.onunload event, not this one).
*
* The only PhoneGap events that user code should register for are:
* onDeviceReady
* onResume
*
* Listeners can be registered as:
* document.addEventListener("deviceready", myDeviceReadyListener, false);
* document.addEventListener("resume", myResumeListener, false);
* document.addEventListener("pause", myPauseListener, false);
*/
if (typeof(DeviceInfo) !== 'object') {
var DeviceInfo = {};
}
/**
* This represents the PhoneGap API itself, and provides a global namespace for accessing
* information about the state of PhoneGap.
* @class
*/
var PhoneGap = {
queue: {
ready: true,
commands: [],
timer: null
}
};
/**
* List of resource files loaded by PhoneGap.
* This is used to ensure JS and other files are loaded only once.
*/
PhoneGap.resources = {base: true};
/**
* Determine if resource has been loaded by PhoneGap
*
* @param name
* @return
*/
PhoneGap.hasResource = function(name) {
return PhoneGap.resources[name];
};
/**
* Add a resource to list of loaded resources by PhoneGap
*
* @param name
*/
PhoneGap.addResource = function(name) {
PhoneGap.resources[name] = true;
};
/**
* Custom pub-sub channel that can have functions subscribed to it
* @constructor
*/
PhoneGap.Channel = function (type)
{
this.type = type;
this.handlers = {};
this.guid = 0;
this.fired = false;
this.enabled = true;
};
/**
* Subscribes the given function to the channel. Any time that
* Channel.fire is called so too will the function.
* Optionally specify an execution context for the function
* and a guid that can be used to stop subscribing to the channel.
* Returns the guid.
*/
PhoneGap.Channel.prototype.subscribe = function(f, c, g) {
// need a function to call
if (f === null) { return; }
var func = f;
if (typeof c === "object" && typeof f === "function") { func = PhoneGap.close(c, f); }
g = g || func.observer_guid || f.observer_guid || this.guid++;
func.observer_guid = g;
f.observer_guid = g;
this.handlers[g] = func;
return g;
};
/**
* Like subscribe but the function is only called once and then it
* auto-unsubscribes itself.
*/
PhoneGap.Channel.prototype.subscribeOnce = function(f, c) {
var g = null;
var _this = this;
var m = function() {
f.apply(c || null, arguments);
_this.unsubscribe(g);
};
if (this.fired) {
if (typeof c === "object" && typeof f === "function") { f = PhoneGap.close(c, f); }
f.apply(this, this.fireArgs);
} else {
g = this.subscribe(m);
}
return g;
};
/**
* Unsubscribes the function with the given guid from the channel.
*/
PhoneGap.Channel.prototype.unsubscribe = function(g) {
if (typeof g === "function") { g = g.observer_guid; }
this.handlers[g] = null;
delete this.handlers[g];
};
/**
* Calls all functions subscribed to this channel.
*/
PhoneGap.Channel.prototype.fire = function(e) {
if (this.enabled) {
var fail = false;
var item, handler, rv;
for (item in this.handlers) {
if (this.handlers.hasOwnProperty(item)) {
handler = this.handlers[item];
if (typeof handler === "function") {
rv = (handler.apply(this, arguments) === false);
fail = fail || rv;
}
}
}
this.fired = true;
this.fireArgs = arguments;
return !fail;
}
return true;
};
/**
* Calls the provided function only after all of the channels specified
* have been fired.
*/
PhoneGap.Channel.join = function(h, c) {
var i = c.length;
var f = function() {
if (!(--i)) {
h();
}
};
var len = i;
var j;
for (j=0; j<len; j++) {
if (!c[j].fired) {
c[j].subscribeOnce(f);
}
else {
i--;
}
}
if (!i) {
h();
}
};
/**
* Boolean flag indicating if the PhoneGap API is available and initialized.
*/ // TODO: Remove this, it is unused here ... -jm
PhoneGap.available = DeviceInfo.uuid !== undefined;
/**
* Add an initialization function to a queue that ensures it will run and initialize
* application constructors only once PhoneGap has been initialized.
* @param {Function} func The function callback you want run once PhoneGap is initialized
*/
PhoneGap.addConstructor = function(func) {
PhoneGap.onPhoneGapInit.subscribeOnce(function() {
try {
func();
} catch(e) {
console.log("Failed to run constructor: " + e);
}
});
};
/**
* Plugins object
*/
if (!window.plugins) {
window.plugins = {};
}
/**
* Adds a plugin object to window.plugins.
* The plugin is accessed using window.plugins.<name>
*
* @param name The plugin name
* @param obj The plugin object
*/
PhoneGap.addPlugin = function(name, obj) {
if (!window.plugins[name]) {
window.plugins[name] = obj;
}
else {
console.log("Error: Plugin "+name+" already exists.");
}
};
/**
* onDOMContentLoaded channel is fired when the DOM content
* of the page has been parsed.
*/
PhoneGap.onDOMContentLoaded = new PhoneGap.Channel('onDOMContentLoaded');
/**
* onNativeReady channel is fired when the PhoneGap native code
* has been initialized.
*/
PhoneGap.onNativeReady = new PhoneGap.Channel('onNativeReady');
/**
* onPhoneGapInit channel is fired when the web page is fully loaded and
* PhoneGap native code has been initialized.
*/
PhoneGap.onPhoneGapInit = new PhoneGap.Channel('onPhoneGapInit');
/**
* onPhoneGapReady channel is fired when the JS PhoneGap objects have been created.
*/
PhoneGap.onPhoneGapReady = new PhoneGap.Channel('onPhoneGapReady');
/**
* onPhoneGapInfoReady channel is fired when the PhoneGap device properties
* has been set.
*/
PhoneGap.onPhoneGapInfoReady = new PhoneGap.Channel('onPhoneGapInfoReady');
/**
* onPhoneGapConnectionReady channel is fired when the PhoneGap connection properties
* has been set.
*/
PhoneGap.onPhoneGapConnectionReady = new PhoneGap.Channel('onPhoneGapConnectionReady');
/**
* onResume channel is fired when the PhoneGap native code
* resumes.
*/
PhoneGap.onResume = new PhoneGap.Channel('onResume');
/**
* onPause channel is fired when the PhoneGap native code
* pauses.
*/
PhoneGap.onPause = new PhoneGap.Channel('onPause');
/**
* onDestroy channel is fired when the PhoneGap native code
* is destroyed. It is used internally.
* Window.onunload should be used by the user.
*/
PhoneGap.onDestroy = new PhoneGap.Channel('onDestroy');
PhoneGap.onDestroy.subscribeOnce(function() {
PhoneGap.shuttingDown = true;
});
PhoneGap.shuttingDown = false;
// _nativeReady is global variable that the native side can set
// to signify that the native code is ready. It is a global since
// it may be called before any PhoneGap JS is ready.
if (typeof _nativeReady !== 'undefined') { PhoneGap.onNativeReady.fire(); }
/**
* onDeviceReady is fired only after all PhoneGap objects are created and
* the device properties are set.
*/
PhoneGap.onDeviceReady = new PhoneGap.Channel('onDeviceReady');
// Array of channels that must fire before "deviceready" is fired
PhoneGap.deviceReadyChannelsArray = [ PhoneGap.onPhoneGapReady, PhoneGap.onPhoneGapInfoReady, PhoneGap.onPhoneGapConnectionReady];
// Hashtable of user defined channels that must also fire before "deviceready" is fired
PhoneGap.deviceReadyChannelsMap = {};
/**
* Indicate that a feature needs to be initialized before it is ready to be used.
* This holds up PhoneGap's "deviceready" event until the feature has been initialized
* and PhoneGap.initComplete(feature) is called.
*
* @param feature {String} The unique feature name
*/
PhoneGap.waitForInitialization = function(feature) {
if (feature) {
var channel = new PhoneGap.Channel(feature);
PhoneGap.deviceReadyChannelsMap[feature] = channel;
PhoneGap.deviceReadyChannelsArray.push(channel);
}
};
/**
* Indicate that initialization code has completed and the feature is ready to be used.
*
* @param feature {String} The unique feature name
*/
PhoneGap.initializationComplete = function(feature) {
var channel = PhoneGap.deviceReadyChannelsMap[feature];
if (channel) {
channel.fire();
}
};
/**
* Create all PhoneGap objects once page has fully loaded and native side is ready.
*/
PhoneGap.Channel.join(function() {
// Start listening for XHR callbacks
setTimeout(function() {
if (PhoneGap.UsePolling) {
PhoneGap.JSCallbackPolling();
}
else {
var polling = prompt("usePolling", "gap_callbackServer:");
PhoneGap.UsePolling = polling;
if (polling == "true") {
PhoneGap.UsePolling = true;
PhoneGap.JSCallbackPolling();
}
else {
PhoneGap.UsePolling = false;
PhoneGap.JSCallback();
}
}
}, 1);
// Run PhoneGap constructors
PhoneGap.onPhoneGapInit.fire();
// Fire event to notify that all objects are created
PhoneGap.onPhoneGapReady.fire();
// Fire onDeviceReady event once all constructors have run and PhoneGap info has been
// received from native side, and any user defined initialization channels.
PhoneGap.Channel.join(function() {
PhoneGap.onDeviceReady.fire();
// Fire the onresume event, since first one happens before JavaScript is loaded
PhoneGap.onResume.fire();
}, PhoneGap.deviceReadyChannelsArray);
}, [ PhoneGap.onDOMContentLoaded, PhoneGap.onNativeReady ]);
// Listen for DOMContentLoaded and notify our channel subscribers
document.addEventListener('DOMContentLoaded', function() {
PhoneGap.onDOMContentLoaded.fire();
}, false);
// Intercept calls to document.addEventListener and watch for deviceready
PhoneGap.m_document_addEventListener = document.addEventListener;
document.addEventListener = function(evt, handler, capture) {
var e = evt.toLowerCase();
if (e === 'deviceready') {
PhoneGap.onDeviceReady.subscribeOnce(handler);
} else if (e === 'resume') {
PhoneGap.onResume.subscribe(handler);
if (PhoneGap.onDeviceReady.fired) {
PhoneGap.onResume.fire();
}
} else if (e === 'pause') {
PhoneGap.onPause.subscribe(handler);
}
else {
// If subscribing to Android backbutton
if (e === 'backbutton') {
PhoneGap.exec(null, null, "App", "overrideBackbutton", [true]);
}
PhoneGap.m_document_addEventListener.call(document, evt, handler, capture);
}
};
// Intercept calls to document.removeEventListener and watch for events that
// are generated by PhoneGap native code
PhoneGap.m_document_removeEventListener = document.removeEventListener;
document.removeEventListener = function(evt, handler, capture) {
var e = evt.toLowerCase();
// If unsubscribing to Android backbutton
if (e === 'backbutton') {
PhoneGap.exec(null, null, "App", "overrideBackbutton", [false]);
}
PhoneGap.m_document_removeEventListener.call(document, evt, handler, capture);
};
/**
* Method to fire event from native code
*/
PhoneGap.fireEvent = function(type) {
var e = document.createEvent('Events');
e.initEvent(type);
document.dispatchEvent(e);
};
/**
* If JSON not included, use our own stringify. (Android 1.6)
* The restriction on ours is that it must be an array of simple types.
*
* @param args
* @return {String}
*/
PhoneGap.stringify = function(args) {
if (typeof JSON === "undefined") {
var s = "[";
var i, type, start, name, nameType, a;
for (i = 0; i < args.length; i++) {
if (args[i] !== null) {
if (i > 0) {
s = s + ",";
}
type = typeof args[i];
if ((type === "number") || (type === "boolean")) {
s = s + args[i];
} else if (args[i] instanceof Array) {
s = s + "[" + args[i] + "]";
} else if (args[i] instanceof Object) {
start = true;
s = s + '{';
for (name in args[i]) {
if (args[i][name] !== null) {
if (!start) {
s = s + ',';
}
s = s + '"' + name + '":';
nameType = typeof args[i][name];
if ((nameType === "number") || (nameType === "boolean")) {
s = s + args[i][name];
} else if ((typeof args[i][name]) === 'function') {
// don't copy the functions
s = s + '""';
} else if (args[i][name] instanceof Object) {
s = s + PhoneGap.stringify(args[i][name]);
} else {
s = s + '"' + args[i][name] + '"';
}
start = false;
}
}
s = s + '}';
} else {
a = args[i].replace(/\\/g, '\\\\');
a = a.replace(/"/g, '\\"');
s = s + '"' + a + '"';
}
}
}
s = s + "]";
return s;
} else {
return JSON.stringify(args);
}
};
/**
* Does a deep clone of the object.
*
* @param obj
* @return {Object}
*/
PhoneGap.clone = function(obj) {
var i, retVal;
if(!obj) {
return obj;
}
if(obj instanceof Array){
retVal = [];
for(i = 0; i < obj.length; ++i){
retVal.push(PhoneGap.clone(obj[i]));
}
return retVal;
}
if (typeof obj === "function") {
return obj;
}
if(!(obj instanceof Object)){
return obj;
}
if (obj instanceof Date) {
return obj;
}
retVal = {};
for(i in obj){
if(!(i in retVal) || retVal[i] !== obj[i]) {
retVal[i] = PhoneGap.clone(obj[i]);
}
}
return retVal;
};
PhoneGap.callbackId = 0;
PhoneGap.callbacks = {};
PhoneGap.callbackStatus = {
NO_RESULT: 0,
OK: 1,
CLASS_NOT_FOUND_EXCEPTION: 2,
ILLEGAL_ACCESS_EXCEPTION: 3,
INSTANTIATION_EXCEPTION: 4,
MALFORMED_URL_EXCEPTION: 5,
IO_EXCEPTION: 6,
INVALID_ACTION: 7,
JSON_EXCEPTION: 8,
ERROR: 9
};
/**
* Execute a PhoneGap command. It is up to the native side whether this action is synch or async.
* The native side can return:
* Synchronous: PluginResult object as a JSON string
* Asynchrounous: Empty string ""
* If async, the native side will PhoneGap.callbackSuccess or PhoneGap.callbackError,
* depending upon the result of the action.
*
* @param {Function} success The success callback
* @param {Function} fail The fail callback
* @param {String} service The name of the service to use
* @param {String} action Action to be run in PhoneGap
* @param {Array.<String>} [args] Zero or more arguments to pass to the method
*/
PhoneGap.exec = function(success, fail, service, action, args) {
try {
var callbackId = service + PhoneGap.callbackId++;
if (success || fail) {
PhoneGap.callbacks[callbackId] = {success:success, fail:fail};
}
var r = prompt(PhoneGap.stringify(args), "gap:"+PhoneGap.stringify([service, action, callbackId, true]));
// If a result was returned
if (r.length > 0) {
eval("var v="+r+";");
// If status is OK, then return value back to caller
if (v.status === PhoneGap.callbackStatus.OK) {
// If there is a success callback, then call it now with
// returned value
if (success) {
try {
success(v.message);
} catch (e) {
console.log("Error in success callback: " + callbackId + " = " + e);
}
// Clear callback if not expecting any more results
if (!v.keepCallback) {
delete PhoneGap.callbacks[callbackId];
}
}
return v.message;
}
// If no result
else if (v.status === PhoneGap.callbackStatus.NO_RESULT) {
// Clear callback if not expecting any more results
if (!v.keepCallback) {
delete PhoneGap.callbacks[callbackId];
}
}
// If error, then display error
else {
console.log("Error: Status="+v.status+" Message="+v.message);
// If there is a fail callback, then call it now with returned value
if (fail) {
try {
fail(v.message);
}
catch (e1) {
console.log("Error in error callback: "+callbackId+" = "+e1);
}
// Clear callback if not expecting any more results
if (!v.keepCallback) {
delete PhoneGap.callbacks[callbackId];
}
}
return null;
}
}
} catch (e2) {
console.log("Error: "+e2);
}
};
/**
* Called by native code when returning successful result from an action.
*
* @param callbackId
* @param args
*/
PhoneGap.callbackSuccess = function(callbackId, args) {
if (PhoneGap.callbacks[callbackId]) {
// If result is to be sent to callback
if (args.status === PhoneGap.callbackStatus.OK) {
try {
if (PhoneGap.callbacks[callbackId].success) {
PhoneGap.callbacks[callbackId].success(args.message);
}
}
catch (e) {
console.log("Error in success callback: "+callbackId+" = "+e);
}
}
// Clear callback if not expecting any more results
if (!args.keepCallback) {
delete PhoneGap.callbacks[callbackId];
}
}
};
/**
* Called by native code when returning error result from an action.
*
* @param callbackId
* @param args
*/
PhoneGap.callbackError = function(callbackId, args) {
if (PhoneGap.callbacks[callbackId]) {
try {
if (PhoneGap.callbacks[callbackId].fail) {
PhoneGap.callbacks[callbackId].fail(args.message);
}
}
catch (e) {
console.log("Error in error callback: "+callbackId+" = "+e);
}
// Clear callback if not expecting any more results
if (!args.keepCallback) {
delete PhoneGap.callbacks[callbackId];
}
}
};
/**
* Internal function used to dispatch the request to PhoneGap. It processes the
* command queue and executes the next command on the list. If one of the
* arguments is a JavaScript object, it will be passed on the QueryString of the
* url, which will be turned into a dictionary on the other end.
* @private
*/
// TODO: Is this used?
PhoneGap.run_command = function() {
if (!PhoneGap.available || !PhoneGap.queue.ready) {
return;
}
PhoneGap.queue.ready = false;
var args = PhoneGap.queue.commands.shift();
if (PhoneGap.queue.commands.length === 0) {
clearInterval(PhoneGap.queue.timer);
PhoneGap.queue.timer = null;
}
var uri = [];
var dict = null;
var i;
for (i = 1; i < args.length; i++) {
var arg = args[i];
if (arg === undefined || arg === null) {
arg = '';
}
if (typeof(arg) === 'object') {
dict = arg;
} else {
uri.push(encodeURIComponent(arg));
}
}
var url = "gap://" + args[0] + "/" + uri.join("/");
if (dict !== null) {
var name;
var query_args = [];
for (name in dict) {
if (dict.hasOwnProperty(name) && (typeof (name) === 'string')) {
query_args.push(encodeURIComponent(name) + "=" + encodeURIComponent(dict[name]));
}
}
if (query_args.length > 0) {
url += "?" + query_args.join("&");
}
}
document.location = url;
};
PhoneGap.JSCallbackPort = null;
PhoneGap.JSCallbackToken = null;
/**
* This is only for Android.
*
* Internal function that uses XHR to call into PhoneGap Java code and retrieve
* any JavaScript code that needs to be run. This is used for callbacks from
* Java to JavaScript.
*/
PhoneGap.JSCallback = function() {
// Exit if shutting down app
if (PhoneGap.shuttingDown) {
return;
}
// If polling flag was changed, start using polling from now on
if (PhoneGap.UsePolling) {
PhoneGap.JSCallbackPolling();
return;
}
var xmlhttp = new XMLHttpRequest();
// Callback function when XMLHttpRequest is ready
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState === 4){
// Exit if shutting down app
if (PhoneGap.shuttingDown) {
return;
}
// If callback has JavaScript statement to execute
if (xmlhttp.status === 200) {
// Need to url decode the response
var msg = decodeURIComponent(xmlhttp.responseText);
setTimeout(function() {
try {
var t = eval(msg);
}
catch (e) {
// If we're getting an error here, seeing the message will help in debugging
console.log("JSCallback: Message from Server: " + msg);
console.log("JSCallback Error: "+e);
}
}, 1);
setTimeout(PhoneGap.JSCallback, 1);
}
// If callback ping (used to keep XHR request from timing out)
else if (xmlhttp.status === 404) {
setTimeout(PhoneGap.JSCallback, 10);
}
// If security error
else if (xmlhttp.status === 403) {
console.log("JSCallback Error: Invalid token. Stopping callbacks.");
}
// If server is stopping
else if (xmlhttp.status === 503) {
console.log("JSCallback Error: Service unavailable. Stopping callbacks.");
}
// If request wasn't GET
else if (xmlhttp.status === 400) {
console.log("JSCallback Error: Bad request. Stopping callbacks.");
}
// If error, revert to polling
else {
console.log("JSCallback Error: Request failed.");
PhoneGap.UsePolling = true;
PhoneGap.JSCallbackPolling();
}
}
};
if (PhoneGap.JSCallbackPort === null) {
PhoneGap.JSCallbackPort = prompt("getPort", "gap_callbackServer:");
}
if (PhoneGap.JSCallbackToken === null) {
PhoneGap.JSCallbackToken = prompt("getToken", "gap_callbackServer:");
}
xmlhttp.open("GET", "http://127.0.0.1:"+PhoneGap.JSCallbackPort+"/"+PhoneGap.JSCallbackToken , true);
xmlhttp.send();
};
/**
* The polling period to use with JSCallbackPolling.
* This can be changed by the application. The default is 50ms.
*/
PhoneGap.JSCallbackPollingPeriod = 50;
/**
* Flag that can be set by the user to force polling to be used or force XHR to be used.
*/
PhoneGap.UsePolling = false; // T=use polling, F=use XHR
/**
* This is only for Android.
*
* Internal function that uses polling to call into PhoneGap Java code and retrieve
* any JavaScript code that needs to be run. This is used for callbacks from
* Java to JavaScript.
*/
PhoneGap.JSCallbackPolling = function() {
// Exit if shutting down app
if (PhoneGap.shuttingDown) {
return;
}
// If polling flag was changed, stop using polling from now on
if (!PhoneGap.UsePolling) {
PhoneGap.JSCallback();
return;
}
var msg = prompt("", "gap_poll:");
if (msg) {
setTimeout(function() {
try {
var t = eval(""+msg);
}
catch (e) {
console.log("JSCallbackPolling: Message from Server: " + msg);
console.log("JSCallbackPolling Error: "+e);
}
}, 1);
setTimeout(PhoneGap.JSCallbackPolling, 1);
}
else {
setTimeout(PhoneGap.JSCallbackPolling, PhoneGap.JSCallbackPollingPeriod);
}
};
/**
* Create a UUID
*
* @return {String}
*/
PhoneGap.createUUID = function() {
return PhoneGap.UUIDcreatePart(4) + '-' +
PhoneGap.UUIDcreatePart(2) + '-' +
PhoneGap.UUIDcreatePart(2) + '-' +
PhoneGap.UUIDcreatePart(2) + '-' +
PhoneGap.UUIDcreatePart(6);
};
PhoneGap.UUIDcreatePart = function(length) {
var uuidpart = "";
var i, uuidchar;
for (i=0; i<length; i++) {
uuidchar = parseInt((Math.random() * 256),0).toString(16);
if (uuidchar.length === 1) {
uuidchar = "0" + uuidchar;
}
uuidpart += uuidchar;
}
return uuidpart;
};
PhoneGap.close = function(context, func, params) {
if (typeof params === 'undefined') {
return function() {
return func.apply(context, arguments);
};
} else {
return function() {
return func.apply(context, params);
};
}
};
/**
* Load a JavaScript file after page has loaded.
*
* @param {String} jsfile The url of the JavaScript file to load.
* @param {Function} successCallback The callback to call when the file has been loaded.
*/
PhoneGap.includeJavascript = function(jsfile, successCallback) {
var id = document.getElementsByTagName("head")[0];
var el = document.createElement('script');
el.type = 'text/javascript';
if (typeof successCallback === 'function') {
el.onload = successCallback;
}
el.src = jsfile;
id.appendChild(el);
};
}
/*
* PhoneGap is available under *either* the terms of the modified BSD license *or* the
* MIT License (2008). See http://opensource.org/licenses/alphabetical for full text.
*
* Copyright (c) 2005-2010, Nitobi Software Inc.
* Copyright (c) 2010-2011, IBM Corporation
*/
if (!PhoneGap.hasResource("accelerometer")) {
PhoneGap.addResource("accelerometer");
/** @constructor */
var Acceleration = function(x, y, z) {
this.x = x;
this.y = y;
this.z = z;
this.timestamp = new Date().getTime();
};
/**
* This class provides access to device accelerometer data.
* @constructor
*/
var Accelerometer = function() {
/**
* The last known acceleration. type=Acceleration()
*/
this.lastAcceleration = null;
/**
* List of accelerometer watch timers
*/
this.timers = {};
};
Accelerometer.ERROR_MSG = ["Not running", "Starting", "", "Failed to start"];
/**
* Asynchronously aquires the current acceleration.
*
* @param {Function} successCallback The function to call when the acceleration data is available
* @param {Function} errorCallback The function to call when there is an error getting the acceleration data. (OPTIONAL)
* @param {AccelerationOptions} options The options for getting the accelerometer data such as timeout. (OPTIONAL)
*/
Accelerometer.prototype.getCurrentAcceleration = function(successCallback, errorCallback, options) {
// successCallback required
if (typeof successCallback !== "function") {
console.log("Accelerometer Error: successCallback is not a function");
return;
}
// errorCallback optional
if (errorCallback && (typeof errorCallback !== "function")) {
console.log("Accelerometer Error: errorCallback is not a function");
return;
}
// Get acceleration
PhoneGap.exec(successCallback, errorCallback, "Accelerometer", "getAcceleration", []);
};
/**
* Asynchronously aquires the acceleration repeatedly at a given interval.
*
* @param {Function} successCallback The function to call each time the acceleration data is available
* @param {Function} errorCallback The function to call when there is an error getting the acceleration data. (OPTIONAL)
* @param {AccelerationOptions} options The options for getting the accelerometer data such as timeout. (OPTIONAL)
* @return String The watch id that must be passed to #clearWatch to stop watching.
*/
Accelerometer.prototype.watchAcceleration = function(successCallback, errorCallback, options) {
// Default interval (10 sec)
var frequency = (options !== undefined)? options.frequency : 10000;
// successCallback required
if (typeof successCallback !== "function") {
console.log("Accelerometer Error: successCallback is not a function");
return;
}
// errorCallback optional
if (errorCallback && (typeof errorCallback !== "function")) {
console.log("Accelerometer Error: errorCallback is not a function");
return;
}
// Make sure accelerometer timeout > frequency + 10 sec
PhoneGap.exec(
function(timeout) {
if (timeout < (frequency + 10000)) {
PhoneGap.exec(null, null, "Accelerometer", "setTimeout", [frequency + 10000]);
}
},
function(e) { }, "Accelerometer", "getTimeout", []);
// Start watch timer
var id = PhoneGap.createUUID();
navigator.accelerometer.timers[id] = setInterval(function() {
PhoneGap.exec(successCallback, errorCallback, "Accelerometer", "getAcceleration", []);
}, (frequency ? frequency : 1));
return id;
};
/**
* Clears the specified accelerometer watch.
*
* @param {String} id The id of the watch returned from #watchAcceleration.
*/
Accelerometer.prototype.clearWatch = function(id) {
// Stop javascript timer & remove from timer list
if (id && navigator.accelerometer.timers[id] !== undefined) {
clearInterval(navigator.accelerometer.timers[id]);
delete navigator.accelerometer.timers[id];
}
};
PhoneGap.addConstructor(function() {
if (typeof navigator.accelerometer === "undefined") {
navigator.accelerometer = new Accelerometer();
}
});
}
/*
* PhoneGap is available under *either* the terms of the modified BSD license *or* the
* MIT License (2008). See http://opensource.org/licenses/alphabetical for full text.
*
* Copyright (c) 2005-2010, Nitobi Software Inc.
* Copyright (c) 2010-2011, IBM Corporation
*/
if (!PhoneGap.hasResource("app")) {
PhoneGap.addResource("app");
(function() {
/**
* Constructor
* @constructor
*/
var App = function() {};
/**
* Clear the resource cache.
*/
App.prototype.clearCache = function() {
PhoneGap.exec(null, null, "App", "clearCache", []);
};
/**
* Load the url into the webview.
*
* @param url The URL to load
* @param props Properties that can be passed in to the activity:
* wait: int => wait msec before loading URL
* loadingDialog: "Title,Message" => display a native loading dialog
* hideLoadingDialogOnPage: boolean => hide loadingDialog when page loaded instead of when deviceready event occurs.
* loadInWebView: boolean => cause all links on web page to be loaded into existing web view, instead of being loaded into new browser.
* loadUrlTimeoutValue: int => time in msec to wait before triggering a timeout error
* errorUrl: URL => URL to load if there's an error loading specified URL with loadUrl(). Should be a local URL such as file:///android_asset/www/error.html");
* keepRunning: boolean => enable app to keep running in background
*
* Example:
* App app = new App();
* app.loadUrl("http://server/myapp/index.html", {wait:2000, loadingDialog:"Wait,Loading App", loadUrlTimeoutValue: 60000});
*/
App.prototype.loadUrl = function(url, props) {
PhoneGap.exec(null, null, "App", "loadUrl", [url, props]);
};
/**
* Cancel loadUrl that is waiting to be loaded.
*/
App.prototype.cancelLoadUrl = function() {
PhoneGap.exec(null, null, "App", "cancelLoadUrl", []);
};
/**
* Clear web history in this web view.
* Instead of BACK button loading the previous web page, it will exit the app.
*/
App.prototype.clearHistory = function() {
PhoneGap.exec(null, null, "App", "clearHistory", []);
};
/**
* Override the default behavior of the Android back button.
* If overridden, when the back button is pressed, the "backKeyDown" JavaScript event will be fired.
*
* Note: The user should not have to call this method. Instead, when the user
* registers for the "backbutton" event, this is automatically done.
*
* @param override T=override, F=cancel override
*/
App.prototype.overrideBackbutton = function(override) {
PhoneGap.exec(null, null, "App", "overrideBackbutton", [override]);
};
/**
* Exit and terminate the application.
*/
App.prototype.exitApp = function() {
return PhoneGap.exec(null, null, "App", "exitApp", []);
};
PhoneGap.addConstructor(function() {
navigator.app = new App();
});
}());
}
/*
* PhoneGap is available under *either* the terms of the modified BSD license *or* the
* MIT License (2008). See http://opensource.org/licenses/alphabetical for full text.
*
* Copyright (c) 2005-2010, Nitobi Software Inc.
* Copyright (c) 2010-2011, IBM Corporation
*/
if (!PhoneGap.hasResource("camera")) {
PhoneGap.addResource("camera");
/**
* This class provides access to the device camera.
*
* @constructor
*/
var Camera = function() {
this.successCallback = null;
this.errorCallback = null;
this.options = null;
};
/**
* Format of image that returned from getPicture.
*
* Example: navigator.camera.getPicture(success, fail,
* { quality: 80,
* destinationType: Camera.DestinationType.DATA_URL,
* sourceType: Camera.PictureSourceType.PHOTOLIBRARY})
*/
Camera.DestinationType = {
DATA_URL: 0, // Return base64 encoded string
FILE_URI: 1 // Return file uri (content://media/external/images/media/2 for Android)
};
Camera.prototype.DestinationType = Camera.DestinationType;
/**
* Encoding of image returned from getPicture.
*
* Example: navigator.camera.getPicture(success, fail,
* { quality: 80,
* destinationType: Camera.DestinationType.DATA_URL,
* sourceType: Camera.PictureSourceType.CAMERA,
* encodingType: Camera.EncodingType.PNG})
*/
Camera.EncodingType = {
JPEG: 0, // Return JPEG encoded image
PNG: 1 // Return PNG encoded image
};
Camera.prototype.EncodingType = Camera.EncodingType;
/**
* Source to getPicture from.
*
* Example: navigator.camera.getPicture(success, fail,
* { quality: 80,
* destinationType: Camera.DestinationType.DATA_URL,
* sourceType: Camera.PictureSourceType.PHOTOLIBRARY})
*/
Camera.PictureSourceType = {
PHOTOLIBRARY : 0, // Choose image from picture library (same as SAVEDPHOTOALBUM for Android)
CAMERA : 1, // Take picture from camera
SAVEDPHOTOALBUM : 2 // Choose image from picture library (same as PHOTOLIBRARY for Android)
};
Camera.prototype.PictureSourceType = Camera.PictureSourceType;
/**
* Gets a picture from source defined by "options.sourceType", and returns the
* image as defined by the "options.destinationType" option.
* The defaults are sourceType=CAMERA and destinationType=DATA_URL.
*
* @param {Function} successCallback
* @param {Function} errorCallback
* @param {Object} options
*/
Camera.prototype.getPicture = function(successCallback, errorCallback, options) {
// successCallback required
if (typeof successCallback !== "function") {
console.log("Camera Error: successCallback is not a function");
return;
}
// errorCallback optional
if (errorCallback && (typeof errorCallback !== "function")) {
console.log("Camera Error: errorCallback is not a function");
return;
}
this.options = options;
var quality = 80;
if (options.quality) {
quality = this.options.quality;
}
var maxResolution = 0;
if (options.maxResolution) {
maxResolution = this.options.maxResolution;
}
var destinationType = Camera.DestinationType.DATA_URL;
if (this.options.destinationType) {
destinationType = this.options.destinationType;
}
var sourceType = Camera.PictureSourceType.CAMERA;
if (typeof this.options.sourceType === "number") {
sourceType = this.options.sourceType;
}
var encodingType = Camera.EncodingType.JPEG;
if (typeof options.encodingType == "number") {
encodingType = this.options.encodingType;
}
var targetWidth = -1;
if (typeof options.targetWidth == "number") {
targetWidth = options.targetWidth;
} else if (typeof options.targetWidth == "string") {
var width = new Number(options.targetWidth);
if (isNaN(width) === false) {
targetWidth = width.valueOf();
}
}
var targetHeight = -1;
if (typeof options.targetHeight == "number") {
targetHeight = options.targetHeight;
} else if (typeof options.targetHeight == "string") {
var height = new Number(options.targetHeight);
if (isNaN(height) === false) {
targetHeight = height.valueOf();
}
}
PhoneGap.exec(successCallback, errorCallback, "Camera", "takePicture", [quality, destinationType, sourceType, targetWidth, targetHeight, encodingType]);
};
PhoneGap.addConstructor(function() {
if (typeof navigator.camera === "undefined") {
navigator.camera = new Camera();
}
});
}
/*
* PhoneGap is available under *either* the terms of the modified BSD license *or* the
* MIT License (2008). See http://opensource.org/licenses/alphabetical for full text.
*
* Copyright (c) 2005-2010, Nitobi Software Inc.
* Copyright (c) 2010-2011, IBM Corporation
*/
if (!PhoneGap.hasResource("capture")) {
PhoneGap.addResource("capture");
/**
* Represents a single file.
*
* name {DOMString} name of the file, without path information
* fullPath {DOMString} the full path of the file, including the name
* type {DOMString} mime type
* lastModifiedDate {Date} last modified date
* size {Number} size of the file in bytes
*/
var MediaFile = function(name, fullPath, type, lastModifiedDate, size){
this.name = name || null;
this.fullPath = fullPath || null;
this.type = type || null;
this.lastModifiedDate = lastModifiedDate || null;
this.size = size || 0;
};
/**
* Launch device camera application for recording video(s).
*
* @param {Function} successCB
* @param {Function} errorCB
*/
MediaFile.prototype.getFormatData = function(successCallback, errorCallback){
PhoneGap.exec(successCallback, errorCallback, "Capture", "getFormatData", [this.fullPath, this.type]);
};
/**
* MediaFileData encapsulates format information of a media file.
*
* @param {DOMString} codecs
* @param {long} bitrate
* @param {long} height
* @param {long} width
* @param {float} duration
*/
var MediaFileData = function(codecs, bitrate, height, width, duration){
this.codecs = codecs || null;
this.bitrate = bitrate || 0;
this.height = height || 0;
this.width = width || 0;
this.duration = duration || 0;
};
/**
* The CaptureError interface encapsulates all errors in the Capture API.
*/
var CaptureError = function(){
this.code = null;
};
// Capture error codes
CaptureError.CAPTURE_INTERNAL_ERR = 0;
CaptureError.CAPTURE_APPLICATION_BUSY = 1;
CaptureError.CAPTURE_INVALID_ARGUMENT = 2;
CaptureError.CAPTURE_NO_MEDIA_FILES = 3;
CaptureError.CAPTURE_NOT_SUPPORTED = 20;
/**
* The Capture interface exposes an interface to the camera and microphone of the hosting device.
*/
var Capture = function(){
this.supportedAudioModes = [];
this.supportedImageModes = [];
this.supportedVideoModes = [];
};
/**
* Launch audio recorder application for recording audio clip(s).
*
* @param {Function} successCB
* @param {Function} errorCB
* @param {CaptureAudioOptions} options
*/
Capture.prototype.captureAudio = function(successCallback, errorCallback, options){
PhoneGap.exec(successCallback, errorCallback, "Capture", "captureAudio", [options]);
};
/**
* Launch camera application for taking image(s).
*
* @param {Function} successCB
* @param {Function} errorCB
* @param {CaptureImageOptions} options
*/
Capture.prototype.captureImage = function(successCallback, errorCallback, options){
PhoneGap.exec(successCallback, errorCallback, "Capture", "captureImage", [options]);
};
/**
* Launch camera application for taking image(s).
*
* @param {Function} successCB
* @param {Function} errorCB
* @param {CaptureImageOptions} options
*/
Capture.prototype._castMediaFile = function(pluginResult){
var mediaFiles = [];
var i;
for (i = 0; i < pluginResult.message.length; i++) {
var mediaFile = new MediaFile();
mediaFile.name = pluginResult.message[i].name;
mediaFile.fullPath = pluginResult.message[i].fullPath;
mediaFile.type = pluginResult.message[i].type;
mediaFile.lastModifiedDate = pluginResult.message[i].lastModifiedDate;
mediaFile.size = pluginResult.message[i].size;
mediaFiles.push(mediaFile);
}
pluginResult.message = mediaFiles;
return pluginResult;
};
/**
* Launch device camera application for recording video(s).
*
* @param {Function} successCB
* @param {Function} errorCB
* @param {CaptureVideoOptions} options
*/
Capture.prototype.captureVideo = function(successCallback, errorCallback, options){
PhoneGap.exec(successCallback, errorCallback, "Capture", "captureVideo", [options]);
};
/**
* Encapsulates a set of parameters that the capture device supports.
*/
var ConfigurationData = function(){
// The ASCII-encoded string in lower case representing the media type.
this.type = null;
// The height attribute represents height of the image or video in pixels.
// In the case of a sound clip this attribute has value 0.
this.height = 0;
// The width attribute represents width of the image or video in pixels.
// In the case of a sound clip this attribute has value 0
this.width = 0;
};
/**
* Encapsulates all image capture operation configuration options.
*/
var CaptureImageOptions = function(){
// Upper limit of images user can take. Value must be equal or greater than 1.
this.limit = 1;
// The selected image mode. Must match with one of the elements in supportedImageModes array.
this.mode = null;
};
/**
* Encapsulates all video capture operation configuration options.
*/
var CaptureVideoOptions = function(){
// Upper limit of videos user can record. Value must be equal or greater than 1.
this.limit = 1;
// Maximum duration of a single video clip in seconds.
this.duration = 0;
// The selected video mode. Must match with one of the elements in supportedVideoModes array.
this.mode = null;
};
/**
* Encapsulates all audio capture operation configuration options.
*/
var CaptureAudioOptions = function(){
// Upper limit of sound clips user can record. Value must be equal or greater than 1.
this.limit = 1;
// Maximum duration of a single sound clip in seconds.
this.duration = 0;
// The selected audio mode. Must match with one of the elements in supportedAudioModes array.
this.mode = null;
};
PhoneGap.addConstructor(function(){
if (typeof navigator.device === "undefined") {
navigator.device = window.device = new Device();
}
if (typeof navigator.device.capture === "undefined") {
navigator.device.capture = window.device.capture = new Capture();
}
});
}
/*
* PhoneGap is available under *either* the terms of the modified BSD license *or* the
* MIT License (2008). See http://opensource.org/licenses/alphabetical for full text.
*
* Copyright (c) 2005-2010, Nitobi Software Inc.
* Copyright (c) 2010-2011, IBM Corporation
*/
if (!PhoneGap.hasResource("compass")) {
PhoneGap.addResource("compass");
/**
* This class provides access to device Compass data.
* @constructor
*/
var Compass = function() {
/**
* The last known Compass position.
*/
this.lastHeading = null;
/**
* List of compass watch timers
*/
this.timers = {};
};
Compass.ERROR_MSG = ["Not running", "Starting", "", "Failed to start"];
/**
* Asynchronously aquires the current heading.
*
* @param {Function} successCallback The function to call when the heading data is available
* @param {Function} errorCallback The function to call when there is an error getting the heading data. (OPTIONAL)
* @param {PositionOptions} options The options for getting the heading data such as timeout. (OPTIONAL)
*/
Compass.prototype.getCurrentHeading = function(successCallback, errorCallback, options) {
// successCallback required
if (typeof successCallback !== "function") {
console.log("Compass Error: successCallback is not a function");
return;
}
// errorCallback optional
if (errorCallback && (typeof errorCallback !== "function")) {
console.log("Compass Error: errorCallback is not a function");
return;
}
// Get heading
PhoneGap.exec(successCallback, errorCallback, "Compass", "getHeading", []);
};
/**
* Asynchronously aquires the heading repeatedly at a given interval.
*
* @param {Function} successCallback The function to call each time the heading data is available
* @param {Function} errorCallback The function to call when there is an error getting the heading data. (OPTIONAL)
* @param {HeadingOptions} options The options for getting the heading data such as timeout and the frequency of the watch. (OPTIONAL)
* @return String The watch id that must be passed to #clearWatch to stop watching.
*/
Compass.prototype.watchHeading= function(successCallback, errorCallback, options) {
// Default interval (100 msec)
var frequency = (options !== undefined) ? options.frequency : 100;
// successCallback required
if (typeof successCallback !== "function") {
console.log("Compass Error: successCallback is not a function");
return;
}
// errorCallback optional
if (errorCallback && (typeof errorCallback !== "function")) {
console.log("Compass Error: errorCallback is not a function");
return;
}
// Make sure compass timeout > frequency + 10 sec
PhoneGap.exec(
function(timeout) {
if (timeout < (frequency + 10000)) {
PhoneGap.exec(null, null, "Compass", "setTimeout", [frequency + 10000]);
}
},
function(e) { }, "Compass", "getTimeout", []);
// Start watch timer to get headings
var id = PhoneGap.createUUID();
navigator.compass.timers[id] = setInterval(
function() {
PhoneGap.exec(successCallback, errorCallback, "Compass", "getHeading", []);
}, (frequency ? frequency : 1));
return id;
};
/**
* Clears the specified heading watch.
*
* @param {String} id The ID of the watch returned from #watchHeading.
*/
Compass.prototype.clearWatch = function(id) {
// Stop javascript timer & remove from timer list
if (id && navigator.compass.timers[id]) {
clearInterval(navigator.compass.timers[id]);
delete navigator.compass.timers[id];
}
};
PhoneGap.addConstructor(function() {
if (typeof navigator.compass === "undefined") {
navigator.compass = new Compass();
}
});
}
/*
* PhoneGap is available under *either* the terms of the modified BSD license *or* the
* MIT License (2008). See http://opensource.org/licenses/alphabetical for full text.
*
* Copyright (c) 2005-2010, Nitobi Software Inc.
* Copyright (c) 2010-2011, IBM Corporation
*/
if (!PhoneGap.hasResource("contact")) {
PhoneGap.addResource("contact");
/**
* Contains information about a single contact.
* @constructor
* @param {DOMString} id unique identifier
* @param {DOMString} displayName
* @param {ContactName} name
* @param {DOMString} nickname
* @param {Array.<ContactField>} phoneNumbers array of phone numbers
* @param {Array.<ContactField>} emails array of email addresses
* @param {Array.<ContactAddress>} addresses array of addresses
* @param {Array.<ContactField>} ims instant messaging user ids
* @param {Array.<ContactOrganization>} organizations
* @param {DOMString} birthday contact's birthday
* @param {DOMString} note user notes about contact
* @param {Array.<ContactField>} photos
* @param {Array.<ContactField>} categories
* @param {Array.<ContactField>} urls contact's web sites
*/
var Contact = function (id, displayName, name, nickname, phoneNumbers, emails, addresses,
ims, organizations, birthday, note, photos, categories, urls) {
this.id = id || null;
this.rawId = null;
this.displayName = displayName || null;
this.name = name || null; // ContactName
this.nickname = nickname || null;
this.phoneNumbers = phoneNumbers || null; // ContactField[]
this.emails = emails || null; // ContactField[]
this.addresses = addresses || null; // ContactAddress[]
this.ims = ims || null; // ContactField[]
this.organizations = organizations || null; // ContactOrganization[]
this.birthday = birthday || null;
this.note = note || null;
this.photos = photos || null; // ContactField[]
this.categories = categories || null; // ContactField[]
this.urls = urls || null; // ContactField[]
};
/**
* ContactError.
* An error code assigned by an implementation when an error has occurreds
* @constructor
*/
var ContactError = function() {
this.code=null;
};
/**
* Error codes
*/
ContactError.UNKNOWN_ERROR = 0;
ContactError.INVALID_ARGUMENT_ERROR = 1;
ContactError.TIMEOUT_ERROR = 2;
ContactError.PENDING_OPERATION_ERROR = 3;
ContactError.IO_ERROR = 4;
ContactError.NOT_SUPPORTED_ERROR = 5;
ContactError.PERMISSION_DENIED_ERROR = 20;
/**
* Removes contact from device storage.
* @param successCB success callback
* @param errorCB error callback
*/
Contact.prototype.remove = function(successCB, errorCB) {
if (this.id === null) {
var errorObj = new ContactError();
errorObj.code = ContactError.UNKNOWN_ERROR;
errorCB(errorObj);
}
else {
PhoneGap.exec(successCB, errorCB, "Contacts", "remove", [this.id]);
}
};
/**
* Creates a deep copy of this Contact.
* With the contact ID set to null.
* @return copy of this Contact
*/
Contact.prototype.clone = function() {
var clonedContact = PhoneGap.clone(this);
var i;
clonedContact.id = null;
clonedContact.rawId = null;
// Loop through and clear out any id's in phones, emails, etc.
if (clonedContact.phoneNumbers) {
for (i = 0; i < clonedContact.phoneNumbers.length; i++) {
clonedContact.phoneNumbers[i].id = null;
}
}
if (clonedContact.emails) {
for (i = 0; i < clonedContact.emails.length; i++) {
clonedContact.emails[i].id = null;
}
}
if (clonedContact.addresses) {
for (i = 0; i < clonedContact.addresses.length; i++) {
clonedContact.addresses[i].id = null;
}
}
if (clonedContact.ims) {
for (i = 0; i < clonedContact.ims.length; i++) {
clonedContact.ims[i].id = null;
}
}
if (clonedContact.organizations) {
for (i = 0; i < clonedContact.organizations.length; i++) {
clonedContact.organizations[i].id = null;
}
}
if (clonedContact.tags) {
for (i = 0; i < clonedContact.tags.length; i++) {
clonedContact.tags[i].id = null;
}
}
if (clonedContact.photos) {
for (i = 0; i < clonedContact.photos.length; i++) {
clonedContact.photos[i].id = null;
}
}
if (clonedContact.urls) {
for (i = 0; i < clonedContact.urls.length; i++) {
clonedContact.urls[i].id = null;
}
}
return clonedContact;
};
/**
* Persists contact to device storage.
* @param successCB success callback
* @param errorCB error callback
*/
Contact.prototype.save = function(successCB, errorCB) {
PhoneGap.exec(successCB, errorCB, "Contacts", "save", [this]);
};
/**
* Contact name.
* @constructor
* @param formatted
* @param familyName
* @param givenName
* @param middle
* @param prefix
* @param suffix
*/
var ContactName = function(formatted, familyName, givenName, middle, prefix, suffix) {
this.formatted = formatted || null;
this.familyName = familyName || null;
this.givenName = givenName || null;
this.middleName = middle || null;
this.honorificPrefix = prefix || null;
this.honorificSuffix = suffix || null;
};
/**
* Generic contact field.
* @constructor
* @param {DOMString} id unique identifier, should only be set by native code
* @param type
* @param value
* @param pref
*/
var ContactField = function(type, value, pref) {
this.id = null;
this.type = type || null;
this.value = value || null;
this.pref = pref || null;
};
/**
* Contact address.
* @constructor
* @param {DOMString} id unique identifier, should only be set by native code
* @param formatted
* @param streetAddress
* @param locality
* @param region
* @param postalCode
* @param country
*/
var ContactAddress = function(pref, type, formatted, streetAddress, locality, region, postalCode, country) {
this.id = null;
this.pref = pref || null;
this.type = type || null;
this.formatted = formatted || null;
this.streetAddress = streetAddress || null;
this.locality = locality || null;
this.region = region || null;
this.postalCode = postalCode || null;
this.country = country || null;
};
/**
* Contact organization.
* @constructor
* @param {DOMString} id unique identifier, should only be set by native code
* @param name
* @param dept
* @param title
* @param startDate
* @param endDate
* @param location
* @param desc
*/
var ContactOrganization = function(pref, type, name, dept, title) {
this.id = null;
this.pref = pref || null;
this.type = type || null;
this.name = name || null;
this.department = dept || null;
this.title = title || null;
};
/**
* Represents a group of Contacts.
* @constructor
*/
var Contacts = function() {
this.inProgress = false;
this.records = [];
};
/**
* Returns an array of Contacts matching the search criteria.
* @param fields that should be searched
* @param successCB success callback
* @param errorCB error callback
* @param {ContactFindOptions} options that can be applied to contact searching
* @return array of Contacts matching search criteria
*/
Contacts.prototype.find = function(fields, successCB, errorCB, options) {
if (successCB === null) {
throw new TypeError("You must specify a success callback for the find command.");
}
if (fields === null || fields === "undefined" || fields.length === "undefined" || fields.length <= 0) {
if (typeof errorCB === "function") {
errorCB({"code": ContactError.INVALID_ARGUMENT_ERROR});
}
} else {
PhoneGap.exec(successCB, errorCB, "Contacts", "search", [fields, options]);
}
};
/**
* This function creates a new contact, but it does not persist the contact
* to device storage. To persist the contact to device storage, invoke
* contact.save().
* @param properties an object who's properties will be examined to create a new Contact
* @returns new Contact object
*/
Contacts.prototype.create = function(properties) {
var i;
var contact = new Contact();
for (i in properties) {
if (contact[i] !== 'undefined') {
contact[i] = properties[i];
}
}
return contact;
};
/**
* This function returns and array of contacts. It is required as we need to convert raw
* JSON objects into concrete Contact objects. Currently this method is called after
* navigator.contacts.find but before the find methods success call back.
*
* @param jsonArray an array of JSON Objects that need to be converted to Contact objects.
* @returns an array of Contact objects
*/
Contacts.prototype.cast = function(pluginResult) {
var contacts = [];
var i;
for (i=0; i<pluginResult.message.length; i++) {
contacts.push(navigator.contacts.create(pluginResult.message[i]));
}
pluginResult.message = contacts;
return pluginResult;
};
/**
* ContactFindOptions.
* @constructor
* @param filter used to match contacts against
* @param multiple boolean used to determine if more than one contact should be returned
*/
var ContactFindOptions = function(filter, multiple) {
this.filter = filter || '';
this.multiple = multiple || false;
};
/**
* Add the contact interface into the browser.
*/
PhoneGap.addConstructor(function() {
if(typeof navigator.contacts === "undefined") {
navigator.contacts = new Contacts();
}
});
}
/*
* PhoneGap is available under *either* the terms of the modified BSD license *or* the
* MIT License (2008). See http://opensource.org/licenses/alphabetical for full text.
*
* Copyright (c) 2005-2010, Nitobi Software Inc.
* Copyright (c) 2010-2011, IBM Corporation
*/
// TODO: Needs to be commented
if (!PhoneGap.hasResource("crypto")) {
PhoneGap.addResource("crypto");
/**
* @constructor
*/
var Crypto = function() {
};
Crypto.prototype.encrypt = function(seed, string, callback) {
this.encryptWin = callback;
PhoneGap.exec(null, null, "Crypto", "encrypt", [seed, string]);
};
Crypto.prototype.decrypt = function(seed, string, callback) {
this.decryptWin = callback;
PhoneGap.exec(null, null, "Crypto", "decrypt", [seed, string]);
};
Crypto.prototype.gotCryptedString = function(string) {
this.encryptWin(string);
};
Crypto.prototype.getPlainString = function(string) {
this.decryptWin(string);
};
PhoneGap.addConstructor(function() {
if (typeof navigator.Crypto === "undefined") {
navigator.Crypto = new Crypto();
}
});
}
/*
* PhoneGap is available under *either* the terms of the modified BSD license *or* the
* MIT License (2008). See http://opensource.org/licenses/alphabetical for full text.
*
* Copyright (c) 2005-2010, Nitobi Software Inc.
* Copyright (c) 2010-2011, IBM Corporation
*/
if (!PhoneGap.hasResource("device")) {
PhoneGap.addResource("device");
/**
* This represents the mobile device, and provides properties for inspecting the model, version, UUID of the
* phone, etc.
* @constructor
*/
var Device = function() {
this.available = PhoneGap.available;
this.platform = null;
this.version = null;
this.name = null;
this.uuid = null;
this.phonegap = null;
var me = this;
this.getInfo(
function(info) {
me.available = true;
me.platform = info.platform;
me.version = info.version;
me.name = info.name;
me.uuid = info.uuid;
me.phonegap = info.phonegap;
PhoneGap.onPhoneGapInfoReady.fire();
},
function(e) {
me.available = false;
console.log("Error initializing PhoneGap: " + e);
alert("Error initializing PhoneGap: "+e);
});
};
/**
* Get device info
*
* @param {Function} successCallback The function to call when the heading data is available
* @param {Function} errorCallback The function to call when there is an error getting the heading data. (OPTIONAL)
*/
Device.prototype.getInfo = function(successCallback, errorCallback) {
// successCallback required
if (typeof successCallback !== "function") {
console.log("Device Error: successCallback is not a function");
return;
}
// errorCallback optional
if (errorCallback && (typeof errorCallback !== "function")) {
console.log("Device Error: errorCallback is not a function");
return;
}
// Get info
PhoneGap.exec(successCallback, errorCallback, "Device", "getDeviceInfo", []);
};
/*
* DEPRECATED
* This is only for Android.
*
* You must explicitly override the back button.
*/
Device.prototype.overrideBackButton = function() {
console.log("Device.overrideBackButton() is deprecated. Use App.overrideBackbutton(true).");
navigator.app.overrideBackbutton(true);
};
/*
* DEPRECATED
* This is only for Android.
*
* This resets the back button to the default behaviour
*/
Device.prototype.resetBackButton = function() {
console.log("Device.resetBackButton() is deprecated. Use App.overrideBackbutton(false).");
navigator.app.overrideBackbutton(false);
};
/*
* DEPRECATED
* This is only for Android.
*
* This terminates the activity!
*/
Device.prototype.exitApp = function() {
console.log("Device.exitApp() is deprecated. Use App.exitApp().");
navigator.app.exitApp();
};
PhoneGap.addConstructor(function() {
if (typeof navigator.device === "undefined") {
navigator.device = window.device = new Device();
}
});
}
/*
* PhoneGap is available under *either* the terms of the modified BSD license *or* the
* MIT License (2008). See http://opensource.org/licenses/alphabetical for full text.
*
* Copyright (c) 2005-2010, Nitobi Software Inc.
* Copyright (c) 2010-2011, IBM Corporation
*/
if (!PhoneGap.hasResource("file")) {
PhoneGap.addResource("file");
/**
* This class provides some useful information about a file.
* This is the fields returned when navigator.fileMgr.getFileProperties()
* is called.
* @constructor
*/
var FileProperties = function(filePath) {
this.filePath = filePath;
this.size = 0;
this.lastModifiedDate = null;
};
/**
* Represents a single file.
*
* @constructor
* @param name {DOMString} name of the file, without path information
* @param fullPath {DOMString} the full path of the file, including the name
* @param type {DOMString} mime type
* @param lastModifiedDate {Date} last modified date
* @param size {Number} size of the file in bytes
*/
var File = function(name, fullPath, type, lastModifiedDate, size) {
this.name = name || null;
this.fullPath = fullPath || null;
this.type = type || null;
this.lastModifiedDate = lastModifiedDate || null;
this.size = size || 0;
};
/** @constructor */
var FileError = function() {
this.code = null;
};
// File error codes
// Found in DOMException
FileError.NOT_FOUND_ERR = 1;
FileError.SECURITY_ERR = 2;
FileError.ABORT_ERR = 3;
// Added by this specification
FileError.NOT_READABLE_ERR = 4;
FileError.ENCODING_ERR = 5;
FileError.NO_MODIFICATION_ALLOWED_ERR = 6;
FileError.INVALID_STATE_ERR = 7;
FileError.SYNTAX_ERR = 8;
FileError.INVALID_MODIFICATION_ERR = 9;
FileError.QUOTA_EXCEEDED_ERR = 10;
FileError.TYPE_MISMATCH_ERR = 11;
FileError.PATH_EXISTS_ERR = 12;
//-----------------------------------------------------------------------------
// File manager
//-----------------------------------------------------------------------------
/** @constructor */
var FileMgr = function() {
};
FileMgr.prototype.getFileProperties = function(filePath) {
return PhoneGap.exec(null, null, "File", "getFileProperties", [filePath]);
};
FileMgr.prototype.getFileBasePaths = function() {
};
FileMgr.prototype.testSaveLocationExists = function(successCallback, errorCallback) {
return PhoneGap.exec(successCallback, errorCallback, "File", "testSaveLocationExists", []);
};
FileMgr.prototype.testFileExists = function(fileName, successCallback, errorCallback) {
return PhoneGap.exec(successCallback, errorCallback, "File", "testFileExists", [fileName]);
};
FileMgr.prototype.testDirectoryExists = function(dirName, successCallback, errorCallback) {
return PhoneGap.exec(successCallback, errorCallback, "File", "testDirectoryExists", [dirName]);
};
FileMgr.prototype.getFreeDiskSpace = function(successCallback, errorCallback) {
return PhoneGap.exec(successCallback, errorCallback, "File", "getFreeDiskSpace", []);
};
FileMgr.prototype.write = function(fileName, data, position, successCallback, errorCallback) {
PhoneGap.exec(successCallback, errorCallback, "File", "write", [fileName, data, position]);
};
FileMgr.prototype.truncate = function(fileName, size, successCallback, errorCallback) {
PhoneGap.exec(successCallback, errorCallback, "File", "truncate", [fileName, size]);
};
FileMgr.prototype.readAsText = function(fileName, encoding, successCallback, errorCallback) {
PhoneGap.exec(successCallback, errorCallback, "File", "readAsText", [fileName, encoding]);
};
FileMgr.prototype.readAsDataURL = function(fileName, successCallback, errorCallback) {
PhoneGap.exec(successCallback, errorCallback, "File", "readAsDataURL", [fileName]);
};
PhoneGap.addConstructor(function() {
if (typeof navigator.fileMgr === "undefined") {
navigator.fileMgr = new FileMgr();
}
});
//-----------------------------------------------------------------------------
// File Reader
//-----------------------------------------------------------------------------
// TODO: All other FileMgr function operate on the SD card as root. However,
// for FileReader & FileWriter the root is not SD card. Should this be changed?
/**
* This class reads the mobile device file system.
*
* For Android:
* The root directory is the root of the file system.
* To read from the SD card, the file name is "sdcard/my_file.txt"
* @constructor
*/
var FileReader = function() {
this.fileName = "";
this.readyState = 0;
// File data
this.result = null;
// Error
this.error = null;
// Event handlers
this.onloadstart = null; // When the read starts.
this.onprogress = null; // While reading (and decoding) file or fileBlob data, and reporting partial file data (progess.loaded/progress.total)
this.onload = null; // When the read has successfully completed.
this.onerror = null; // When the read has failed (see errors).
this.onloadend = null; // When the request has completed (either in success or failure).
this.onabort = null; // When the read has been aborted. For instance, by invoking the abort() method.
};
// States
FileReader.EMPTY = 0;
FileReader.LOADING = 1;
FileReader.DONE = 2;
/**
* Abort reading file.
*/
FileReader.prototype.abort = function() {
var evt;
this.readyState = FileReader.DONE;
this.result = null;
// set error
var error = new FileError();
error.code = error.ABORT_ERR;
this.error = error;
// If error callback
if (typeof this.onerror === "function") {
this.onerror({"type":"error", "target":this});
}
// If abort callback
if (typeof this.onabort === "function") {
this.onabort({"type":"abort", "target":this});
}
// If load end callback
if (typeof this.onloadend === "function") {
this.onloadend({"type":"loadend", "target":this});
}
};
/**
* Read text file.
*
* @param file {File} File object containing file properties
* @param encoding [Optional] (see http://www.iana.org/assignments/character-sets)
*/
FileReader.prototype.readAsText = function(file, encoding) {
this.fileName = "";
if (typeof file.fullPath === "undefined") {
this.fileName = file;
} else {
this.fileName = file.fullPath;
}
// LOADING state
this.readyState = FileReader.LOADING;
// If loadstart callback
if (typeof this.onloadstart === "function") {
this.onloadstart({"type":"loadstart", "target":this});
}
// Default encoding is UTF-8
var enc = encoding ? encoding : "UTF-8";
var me = this;
// Read file
navigator.fileMgr.readAsText(this.fileName, enc,
// Success callback
function(r) {
var evt;
// If DONE (cancelled), then don't do anything
if (me.readyState === FileReader.DONE) {
return;
}
// Save result
me.result = r;
// If onload callback
if (typeof me.onload === "function") {
me.onload({"type":"load", "target":me});
}
// DONE state
me.readyState = FileReader.DONE;
// If onloadend callback
if (typeof me.onloadend === "function") {
me.onloadend({"type":"loadend", "target":me});
}
},
// Error callback
function(e) {
var evt;
// If DONE (cancelled), then don't do anything
if (me.readyState === FileReader.DONE) {
return;
}
// Save error
me.error = e;
// If onerror callback
if (typeof me.onerror === "function") {
me.onerror({"type":"error", "target":me});
}
// DONE state
me.readyState = FileReader.DONE;
// If onloadend callback
if (typeof me.onloadend === "function") {
me.onloadend({"type":"loadend", "target":me});
}
}
);
};
/**
* Read file and return data as a base64 encoded data url.
* A data url is of the form:
* data:[<mediatype>][;base64],<data>
*
* @param file {File} File object containing file properties
*/
FileReader.prototype.readAsDataURL = function(file) {
this.fileName = "";
if (typeof file.fullPath === "undefined") {
this.fileName = file;
} else {
this.fileName = file.fullPath;
}
// LOADING state
this.readyState = FileReader.LOADING;
// If loadstart callback
if (typeof this.onloadstart === "function") {
this.onloadstart({"type":"loadstart", "target":this});
}
var me = this;
// Read file
navigator.fileMgr.readAsDataURL(this.fileName,
// Success callback
function(r) {
var evt;
// If DONE (cancelled), then don't do anything
if (me.readyState === FileReader.DONE) {
return;
}
// Save result
me.result = r;
// If onload callback
if (typeof me.onload === "function") {
me.onload({"type":"load", "target":me});
}
// DONE state
me.readyState = FileReader.DONE;
// If onloadend callback
if (typeof me.onloadend === "function") {
me.onloadend({"type":"loadend", "target":me});
}
},
// Error callback
function(e) {
var evt;
// If DONE (cancelled), then don't do anything
if (me.readyState === FileReader.DONE) {
return;
}
// Save error
me.error = e;
// If onerror callback
if (typeof me.onerror === "function") {
me.onerror({"type":"error", "target":me});
}
// DONE state
me.readyState = FileReader.DONE;
// If onloadend callback
if (typeof me.onloadend === "function") {
me.onloadend({"type":"loadend", "target":me});
}
}
);
};
/**
* Read file and return data as a binary data.
*
* @param file {File} File object containing file properties
*/
FileReader.prototype.readAsBinaryString = function(file) {
// TODO - Can't return binary data to browser.
this.fileName = file;
};
/**
* Read file and return data as a binary data.
*
* @param file {File} File object containing file properties
*/
FileReader.prototype.readAsArrayBuffer = function(file) {
// TODO - Can't return binary data to browser.
this.fileName = file;
};
//-----------------------------------------------------------------------------
// File Writer
//-----------------------------------------------------------------------------
/**
* This class writes to the mobile device file system.
*
* For Android:
* The root directory is the root of the file system.
* To write to the SD card, the file name is "sdcard/my_file.txt"
*
* @constructor
* @param file {File} File object containing file properties
* @param append if true write to the end of the file, otherwise overwrite the file
*/
var FileWriter = function(file) {
this.fileName = "";
this.length = 0;
if (file) {
this.fileName = file.fullPath || file;
this.length = file.size || 0;
}
// default is to write at the beginning of the file
this.position = 0;
this.readyState = 0; // EMPTY
this.result = null;
// Error
this.error = null;
// Event handlers
this.onwritestart = null; // When writing starts
this.onprogress = null; // While writing the file, and reporting partial file data
this.onwrite = null; // When the write has successfully completed.
this.onwriteend = null; // When the request has completed (either in success or failure).
this.onabort = null; // When the write has been aborted. For instance, by invoking the abort() method.
this.onerror = null; // When the write has failed (see errors).
};
// States
FileWriter.INIT = 0;
FileWriter.WRITING = 1;
FileWriter.DONE = 2;
/**
* Abort writing file.
*/
FileWriter.prototype.abort = function() {
// check for invalid state
if (this.readyState === FileWriter.DONE || this.readyState === FileWriter.INIT) {
throw FileError.INVALID_STATE_ERR;
}
// set error
var error = new FileError(), evt;
error.code = error.ABORT_ERR;
this.error = error;
// If error callback
if (typeof this.onerror === "function") {
this.onerror({"type":"error", "target":this});
}
// If abort callback
if (typeof this.onabort === "function") {
this.onabort({"type":"abort", "target":this});
}
this.readyState = FileWriter.DONE;
// If write end callback
if (typeof this.onwriteend == "function") {
this.onwriteend({"type":"writeend", "target":this});
}
};
/**
* Writes data to the file
*
* @param text to be written
*/
FileWriter.prototype.write = function(text) {
// Throw an exception if we are already writing a file
if (this.readyState === FileWriter.WRITING) {
throw FileError.INVALID_STATE_ERR;
}
// WRITING state
this.readyState = FileWriter.WRITING;
var me = this;
// If onwritestart callback
if (typeof me.onwritestart === "function") {
me.onwritestart({"type":"writestart", "target":me});
}
// Write file
navigator.fileMgr.write(this.fileName, text, this.position,
// Success callback
function(r) {
var evt;
// If DONE (cancelled), then don't do anything
if (me.readyState === FileWriter.DONE) {
return;
}
// position always increases by bytes written because file would be extended
me.position += r;
// The length of the file is now where we are done writing.
me.length = me.position;
// If onwrite callback
if (typeof me.onwrite === "function") {
me.onwrite({"type":"write", "target":me});
}
// DONE state
me.readyState = FileWriter.DONE;
// If onwriteend callback
if (typeof me.onwriteend === "function") {
me.onwriteend({"type":"writeend", "target":me});
}
},
// Error callback
function(e) {
var evt;
// If DONE (cancelled), then don't do anything
if (me.readyState === FileWriter.DONE) {
return;
}
// Save error
me.error = e;
// If onerror callback
if (typeof me.onerror === "function") {
me.onerror({"type":"error", "target":me});
}
// DONE state
me.readyState = FileWriter.DONE;
// If onwriteend callback
if (typeof me.onwriteend === "function") {
me.onwriteend({"type":"writeend", "target":me});
}
}
);
};
/**
* Moves the file pointer to the location specified.
*
* If the offset is a negative number the position of the file
* pointer is rewound. If the offset is greater than the file
* size the position is set to the end of the file.
*
* @param offset is the location to move the file pointer to.
*/
FileWriter.prototype.seek = function(offset) {
// Throw an exception if we are already writing a file
if (this.readyState === FileWriter.WRITING) {
throw FileError.INVALID_STATE_ERR;
}
if (!offset) {
return;
}
// See back from end of file.
if (offset < 0) {
this.position = Math.max(offset + this.length, 0);
}
// Offset is bigger then file size so set position
// to the end of the file.
else if (offset > this.length) {
this.position = this.length;
}
// Offset is between 0 and file size so set the position
// to start writing.
else {
this.position = offset;
}
};
/**
* Truncates the file to the size specified.
*
* @param size to chop the file at.
*/
FileWriter.prototype.truncate = function(size) {
// Throw an exception if we are already writing a file
if (this.readyState === FileWriter.WRITING) {
throw FileError.INVALID_STATE_ERR;
}
// WRITING state
this.readyState = FileWriter.WRITING;
var me = this;
// If onwritestart callback
if (typeof me.onwritestart === "function") {
me.onwritestart({"type":"writestart", "target":this});
}
// Write file
navigator.fileMgr.truncate(this.fileName, size,
// Success callback
function(r) {
var evt;
// If DONE (cancelled), then don't do anything
if (me.readyState === FileWriter.DONE) {
return;
}
// Update the length of the file
me.length = r;
me.position = Math.min(me.position, r);
// If onwrite callback
if (typeof me.onwrite === "function") {
me.onwrite({"type":"write", "target":me});
}
// DONE state
me.readyState = FileWriter.DONE;
// If onwriteend callback
if (typeof me.onwriteend === "function") {
me.onwriteend({"type":"writeend", "target":me});
}
},
// Error callback
function(e) {
var evt;
// If DONE (cancelled), then don't do anything
if (me.readyState === FileWriter.DONE) {
return;
}
// Save error
me.error = e;
// If onerror callback
if (typeof me.onerror === "function") {
me.onerror({"type":"error", "target":me});
}
// DONE state
me.readyState = FileWriter.DONE;
// If onwriteend callback
if (typeof me.onwriteend === "function") {
me.onwriteend({"type":"writeend", "target":me});
}
}
);
};
/**
* Information about the state of the file or directory
*
* @constructor
* {Date} modificationTime (readonly)
*/
var Metadata = function() {
this.modificationTime=null;
};
/**
* Supplies arguments to methods that lookup or create files and directories
*
* @constructor
* @param {boolean} create file or directory if it doesn't exist
* @param {boolean} exclusive if true the command will fail if the file or directory exists
*/
var Flags = function(create, exclusive) {
this.create = create || false;
this.exclusive = exclusive || false;
};
/**
* An interface representing a file system
*
* @constructor
* {DOMString} name the unique name of the file system (readonly)
* {DirectoryEntry} root directory of the file system (readonly)
*/
var FileSystem = function() {
this.name = null;
this.root = null;
};
/**
* An interface that lists the files and directories in a directory.
* @constructor
*/
var DirectoryReader = function(fullPath){
this.fullPath = fullPath || null;
};
/**
* Returns a list of entries from a directory.
*
* @param {Function} successCallback is called with a list of entries
* @param {Function} errorCallback is called with a FileError
*/
DirectoryReader.prototype.readEntries = function(successCallback, errorCallback) {
PhoneGap.exec(successCallback, errorCallback, "File", "readEntries", [this.fullPath]);
};
/**
* An interface representing a directory on the file system.
*
* @constructor
* {boolean} isFile always false (readonly)
* {boolean} isDirectory always true (readonly)
* {DOMString} name of the directory, excluding the path leading to it (readonly)
* {DOMString} fullPath the absolute full path to the directory (readonly)
* {FileSystem} filesystem on which the directory resides (readonly)
*/
var DirectoryEntry = function() {
this.isFile = false;
this.isDirectory = true;
this.name = null;
this.fullPath = null;
this.filesystem = null;
};
/**
* Copies a directory to a new location
*
* @param {DirectoryEntry} parent the directory to which to copy the entry
* @param {DOMString} newName the new name of the entry, defaults to the current name
* @param {Function} successCallback is called with the new entry
* @param {Function} errorCallback is called with a FileError
*/
DirectoryEntry.prototype.copyTo = function(parent, newName, successCallback, errorCallback) {
PhoneGap.exec(successCallback, errorCallback, "File", "copyTo", [this.fullPath, parent, newName]);
};
/**
* Looks up the metadata of the entry
*
* @param {Function} successCallback is called with a Metadata object
* @param {Function} errorCallback is called with a FileError
*/
DirectoryEntry.prototype.getMetadata = function(successCallback, errorCallback) {
PhoneGap.exec(successCallback, errorCallback, "File", "getMetadata", [this.fullPath]);
};
/**
* Gets the parent of the entry
*
* @param {Function} successCallback is called with a parent entry
* @param {Function} errorCallback is called with a FileError
*/
DirectoryEntry.prototype.getParent = function(successCallback, errorCallback) {
PhoneGap.exec(successCallback, errorCallback, "File", "getParent", [this.fullPath]);
};
/**
* Moves a directory to a new location
*
* @param {DirectoryEntry} parent the directory to which to move the entry
* @param {DOMString} newName the new name of the entry, defaults to the current name
* @param {Function} successCallback is called with the new entry
* @param {Function} errorCallback is called with a FileError
*/
DirectoryEntry.prototype.moveTo = function(parent, newName, successCallback, errorCallback) {
PhoneGap.exec(successCallback, errorCallback, "File", "moveTo", [this.fullPath, parent, newName]);
};
/**
* Removes the entry
*
* @param {Function} successCallback is called with no parameters
* @param {Function} errorCallback is called with a FileError
*/
DirectoryEntry.prototype.remove = function(successCallback, errorCallback) {
PhoneGap.exec(successCallback, errorCallback, "File", "remove", [this.fullPath]);
};
/**
* Returns a URI that can be used to identify this entry.
*
* @param {DOMString} mimeType for a FileEntry, the mime type to be used to interpret the file, when loaded through this URI.
* @return uri
*/
DirectoryEntry.prototype.toURI = function(mimeType) {
return "file://" + this.fullPath;
};
/**
* Creates a new DirectoryReader to read entries from this directory
*/
DirectoryEntry.prototype.createReader = function(successCallback, errorCallback) {
return new DirectoryReader(this.fullPath);
};
/**
* Creates or looks up a directory
*
* @param {DOMString} path either a relative or absolute path from this directory in which to look up or create a directory
* @param {Flags} options to create or excluively create the directory
* @param {Function} successCallback is called with the new entry
* @param {Function} errorCallback is called with a FileError
*/
DirectoryEntry.prototype.getDirectory = function(path, options, successCallback, errorCallback) {
PhoneGap.exec(successCallback, errorCallback, "File", "getDirectory", [this.fullPath, path, options]);
};
/**
* Creates or looks up a file
*
* @param {DOMString} path either a relative or absolute path from this directory in which to look up or create a file
* @param {Flags} options to create or excluively create the file
* @param {Function} successCallback is called with the new entry
* @param {Function} errorCallback is called with a FileError
*/
DirectoryEntry.prototype.getFile = function(path, options, successCallback, errorCallback) {
PhoneGap.exec(successCallback, errorCallback, "File", "getFile", [this.fullPath, path, options]);
};
/**
* Deletes a directory and all of it's contents
*
* @param {Function} successCallback is called with no parameters
* @param {Function} errorCallback is called with a FileError
*/
DirectoryEntry.prototype.removeRecursively = function(successCallback, errorCallback) {
PhoneGap.exec(successCallback, errorCallback, "File", "removeRecursively", [this.fullPath]);
};
/**
* An interface representing a directory on the file system.
*
* @constructor
* {boolean} isFile always true (readonly)
* {boolean} isDirectory always false (readonly)
* {DOMString} name of the file, excluding the path leading to it (readonly)
* {DOMString} fullPath the absolute full path to the file (readonly)
* {FileSystem} filesystem on which the directory resides (readonly)
*/
var FileEntry = function() {
this.isFile = true;
this.isDirectory = false;
this.name = null;
this.fullPath = null;
this.filesystem = null;
};
/**
* Copies a file to a new location
*
* @param {DirectoryEntry} parent the directory to which to copy the entry
* @param {DOMString} newName the new name of the entry, defaults to the current name
* @param {Function} successCallback is called with the new entry
* @param {Function} errorCallback is called with a FileError
*/
FileEntry.prototype.copyTo = function(parent, newName, successCallback, errorCallback) {
PhoneGap.exec(successCallback, errorCallback, "File", "copyTo", [this.fullPath, parent, newName]);
};
/**
* Looks up the metadata of the entry
*
* @param {Function} successCallback is called with a Metadata object
* @param {Function} errorCallback is called with a FileError
*/
FileEntry.prototype.getMetadata = function(successCallback, errorCallback) {
PhoneGap.exec(successCallback, errorCallback, "File", "getMetadata", [this.fullPath]);
};
/**
* Gets the parent of the entry
*
* @param {Function} successCallback is called with a parent entry
* @param {Function} errorCallback is called with a FileError
*/
FileEntry.prototype.getParent = function(successCallback, errorCallback) {
PhoneGap.exec(successCallback, errorCallback, "File", "getParent", [this.fullPath]);
};
/**
* Moves a directory to a new location
*
* @param {DirectoryEntry} parent the directory to which to move the entry
* @param {DOMString} newName the new name of the entry, defaults to the current name
* @param {Function} successCallback is called with the new entry
* @param {Function} errorCallback is called with a FileError
*/
FileEntry.prototype.moveTo = function(parent, newName, successCallback, errorCallback) {
PhoneGap.exec(successCallback, errorCallback, "File", "moveTo", [this.fullPath, parent, newName]);
};
/**
* Removes the entry
*
* @param {Function} successCallback is called with no parameters
* @param {Function} errorCallback is called with a FileError
*/
FileEntry.prototype.remove = function(successCallback, errorCallback) {
PhoneGap.exec(successCallback, errorCallback, "File", "remove", [this.fullPath]);
};
/**
* Returns a URI that can be used to identify this entry.
*
* @param {DOMString} mimeType for a FileEntry, the mime type to be used to interpret the file, when loaded through this URI.
* @return uri
*/
FileEntry.prototype.toURI = function(mimeType) {
return "file://" + this.fullPath;
};
/**
* Creates a new FileWriter associated with the file that this FileEntry represents.
*
* @param {Function} successCallback is called with the new FileWriter
* @param {Function} errorCallback is called with a FileError
*/
FileEntry.prototype.createWriter = function(successCallback, errorCallback) {
this.file(function(filePointer) {
var writer = new FileWriter(filePointer);
if (writer.fileName === null || writer.fileName === "") {
if (typeof errorCallback == "function") {
errorCallback({
"code": FileError.INVALID_STATE_ERR
});
}
}
if (typeof successCallback == "function") {
successCallback(writer);
}
}, errorCallback);
};
/**
* Returns a File that represents the current state of the file that this FileEntry represents.
*
* @param {Function} successCallback is called with the new File object
* @param {Function} errorCallback is called with a FileError
*/
FileEntry.prototype.file = function(successCallback, errorCallback) {
PhoneGap.exec(successCallback, errorCallback, "File", "getFileMetadata", [this.fullPath]);
};
/** @constructor */
var LocalFileSystem = function() {
};
// File error codes
LocalFileSystem.TEMPORARY = 0;
LocalFileSystem.PERSISTENT = 1;
LocalFileSystem.RESOURCE = 2;
LocalFileSystem.APPLICATION = 3;
/**
* Requests a filesystem in which to store application data.
*
* @param {int} type of file system being requested
* @param {Function} successCallback is called with the new FileSystem
* @param {Function} errorCallback is called with a FileError
*/
LocalFileSystem.prototype.requestFileSystem = function(type, size, successCallback, errorCallback) {
if (type < 0 || type > 3) {
if (typeof errorCallback == "function") {
errorCallback({
"code": FileError.SYNTAX_ERR
});
}
}
else {
PhoneGap.exec(successCallback, errorCallback, "File", "requestFileSystem", [type, size]);
}
};
/**
*
* @param {DOMString} uri referring to a local file in a filesystem
* @param {Function} successCallback is called with the new entry
* @param {Function} errorCallback is called with a FileError
*/
LocalFileSystem.prototype.resolveLocalFileSystemURI = function(uri, successCallback, errorCallback) {
PhoneGap.exec(successCallback, errorCallback, "File", "resolveLocalFileSystemURI", [uri]);
};
/**
* This function returns and array of contacts. It is required as we need to convert raw
* JSON objects into concrete Contact objects. Currently this method is called after
* navigator.service.contacts.find but before the find methods success call back.
*
* @param a JSON Objects that need to be converted to DirectoryEntry or FileEntry objects.
* @returns an entry
*/
LocalFileSystem.prototype._castFS = function(pluginResult) {
var entry = null;
entry = new DirectoryEntry();
entry.isDirectory = pluginResult.message.root.isDirectory;
entry.isFile = pluginResult.message.root.isFile;
entry.name = pluginResult.message.root.name;
entry.fullPath = pluginResult.message.root.fullPath;
pluginResult.message.root = entry;
return pluginResult;
};
LocalFileSystem.prototype._castEntry = function(pluginResult) {
var entry = null;
if (pluginResult.message.isDirectory) {
console.log("This is a dir");
entry = new DirectoryEntry();
}
else if (pluginResult.message.isFile) {
console.log("This is a file");
entry = new FileEntry();
}
entry.isDirectory = pluginResult.message.isDirectory;
entry.isFile = pluginResult.message.isFile;
entry.name = pluginResult.message.name;
entry.fullPath = pluginResult.message.fullPath;
pluginResult.message = entry;
return pluginResult;
};
LocalFileSystem.prototype._castEntries = function(pluginResult) {
var entries = pluginResult.message;
var retVal = [];
for (var i=0; i<entries.length; i++) {
retVal.push(window.localFileSystem._createEntry(entries[i]));
}
pluginResult.message = retVal;
return pluginResult;
};
LocalFileSystem.prototype._createEntry = function(castMe) {
var entry = null;
if (castMe.isDirectory) {
console.log("This is a dir");
entry = new DirectoryEntry();
}
else if (castMe.isFile) {
console.log("This is a file");
entry = new FileEntry();
}
entry.isDirectory = castMe.isDirectory;
entry.isFile = castMe.isFile;
entry.name = castMe.name;
entry.fullPath = castMe.fullPath;
return entry;
};
LocalFileSystem.prototype._castDate = function(pluginResult) {
if (pluginResult.message.modificationTime) {
var modTime = new Date(pluginResult.message.modificationTime);
pluginResult.message.modificationTime = modTime;
}
else if (pluginResult.message.lastModifiedDate) {
var file = new File();
file.size = pluginResult.message.size;
file.type = pluginResult.message.type;
file.name = pluginResult.message.name;
file.fullPath = pluginResult.message.fullPath;
file.lastModifiedDate = new Date(pluginResult.message.lastModifiedDate);
pluginResult.message = file;
}
return pluginResult;
};
/**
* Add the FileSystem interface into the browser.
*/
PhoneGap.addConstructor(function() {
var pgLocalFileSystem = new LocalFileSystem();
// Needed for cast methods
if(typeof window.localFileSystem == "undefined") window.localFileSystem = pgLocalFileSystem;
if(typeof window.requestFileSystem == "undefined") window.requestFileSystem = pgLocalFileSystem.requestFileSystem;
if(typeof window.resolveLocalFileSystemURI == "undefined") window.resolveLocalFileSystemURI = pgLocalFileSystem.resolveLocalFileSystemURI;
});
}
/*
* PhoneGap is available under *either* the terms of the modified BSD license *or* the
* MIT License (2008). See http://opensource.org/licenses/alphabetical for full text.
*
* Copyright (c) 2005-2010, Nitobi Software Inc.
* Copyright (c) 2010-2011, IBM Corporation
*/
if (!PhoneGap.hasResource("filetransfer")) {
PhoneGap.addResource("filetransfer");
/**
* FileTransfer uploads a file to a remote server.
* @constructor
*/
var FileTransfer = function() {};
/**
* FileUploadResult
* @constructor
*/
var FileUploadResult = function() {
this.bytesSent = 0;
this.responseCode = null;
this.response = null;
};
/**
* FileTransferError
* @constructor
*/
var FileTransferError = function() {
this.code = null;
};
FileTransferError.FILE_NOT_FOUND_ERR = 1;
FileTransferError.INVALID_URL_ERR = 2;
FileTransferError.CONNECTION_ERR = 3;
/**
* Given an absolute file path, uploads a file on the device to a remote server
* using a multipart HTTP request.
* @param filePath {String} Full path of the file on the device
* @param server {String} URL of the server to receive the file
* @param successCallback (Function} Callback to be invoked when upload has completed
* @param errorCallback {Function} Callback to be invoked upon error
* @param options {FileUploadOptions} Optional parameters such as file name and mimetype
*/
FileTransfer.prototype.upload = function(filePath, server, successCallback, errorCallback, options, debug) {
// check for options
var fileKey = null;
var fileName = null;
var mimeType = null;
var params = null;
if (options) {
fileKey = options.fileKey;
fileName = options.fileName;
mimeType = options.mimeType;
if (options.params) {
params = options.params;
}
else {
params = {};
}
}
PhoneGap.exec(successCallback, errorCallback, 'FileTransfer', 'upload', [filePath, server, fileKey, fileName, mimeType, params, debug]);
};
/**
* Options to customize the HTTP request used to upload files.
* @constructor
* @param fileKey {String} Name of file request parameter.
* @param fileName {String} Filename to be used by the server. Defaults to image.jpg.
* @param mimeType {String} Mimetype of the uploaded file. Defaults to image/jpeg.
* @param params {Object} Object with key: value params to send to the server.
*/
var FileUploadOptions = function(fileKey, fileName, mimeType, params) {
this.fileKey = fileKey || null;
this.fileName = fileName || null;
this.mimeType = mimeType || null;
this.params = params || null;
};
}
/*
* PhoneGap is available under *either* the terms of the modified BSD license *or* the
* MIT License (2008). See http://opensource.org/licenses/alphabetical for full text.
*
* Copyright (c) 2005-2010, Nitobi Software Inc.
* Copyright (c) 2010-2011, IBM Corporation
*/
if (!PhoneGap.hasResource("geolocation")) {
PhoneGap.addResource("geolocation");
/**
* This class provides access to device GPS data.
* @constructor
*/
var Geolocation = function() {
// The last known GPS position.
this.lastPosition = null;
// Geolocation listeners
this.listeners = {};
};
/**
* Position error object
*
* @constructor
* @param code
* @param message
*/
var PositionError = function(code, message) {
this.code = code;
this.message = message;
};
PositionError.PERMISSION_DENIED = 1;
PositionError.POSITION_UNAVAILABLE = 2;
PositionError.TIMEOUT = 3;
/**
* Asynchronously aquires the current position.
*
* @param {Function} successCallback The function to call when the position data is available
* @param {Function} errorCallback The function to call when there is an error getting the heading position. (OPTIONAL)
* @param {PositionOptions} options The options for getting the position data. (OPTIONAL)
*/
Geolocation.prototype.getCurrentPosition = function(successCallback, errorCallback, options) {
if (navigator._geo.listeners.global) {
console.log("Geolocation Error: Still waiting for previous getCurrentPosition() request.");
try {
errorCallback(new PositionError(PositionError.TIMEOUT, "Geolocation Error: Still waiting for previous getCurrentPosition() request."));
} catch (e) {
}
return;
}
var maximumAge = 10000;
var enableHighAccuracy = false;
var timeout = 10000;
if (typeof options !== "undefined") {
if (typeof options.maximumAge !== "undefined") {
maximumAge = options.maximumAge;
}
if (typeof options.enableHighAccuracy !== "undefined") {
enableHighAccuracy = options.enableHighAccuracy;
}
if (typeof options.timeout !== "undefined") {
timeout = options.timeout;
}
}
navigator._geo.listeners.global = {"success" : successCallback, "fail" : errorCallback };
PhoneGap.exec(null, null, "Geolocation", "getCurrentLocation", [enableHighAccuracy, timeout, maximumAge]);
};
/**
* Asynchronously watches the geolocation for changes to geolocation. When a change occurs,
* the successCallback is called with the new location.
*
* @param {Function} successCallback The function to call each time the location data is available
* @param {Function} errorCallback The function to call when there is an error getting the location data. (OPTIONAL)
* @param {PositionOptions} options The options for getting the location data such as frequency. (OPTIONAL)
* @return String The watch id that must be passed to #clearWatch to stop watching.
*/
Geolocation.prototype.watchPosition = function(successCallback, errorCallback, options) {
var maximumAge = 10000;
var enableHighAccuracy = false;
var timeout = 10000;
if (typeof options !== "undefined") {
if (typeof options.frequency !== "undefined") {
maximumAge = options.frequency;
}
if (typeof options.maximumAge !== "undefined") {
maximumAge = options.maximumAge;
}
if (typeof options.enableHighAccuracy !== "undefined") {
enableHighAccuracy = options.enableHighAccuracy;
}
if (typeof options.timeout !== "undefined") {
timeout = options.timeout;
}
}
var id = PhoneGap.createUUID();
navigator._geo.listeners[id] = {"success" : successCallback, "fail" : errorCallback };
PhoneGap.exec(null, null, "Geolocation", "start", [id, enableHighAccuracy, timeout, maximumAge]);
return id;
};
/*
* Native callback when watch position has a new position.
* PRIVATE METHOD
*
* @param {String} id
* @param {Number} lat
* @param {Number} lng
* @param {Number} alt
* @param {Number} altacc
* @param {Number} head
* @param {Number} vel
* @param {Number} stamp
*/
Geolocation.prototype.success = function(id, lat, lng, alt, altacc, head, vel, stamp) {
var coords = new Coordinates(lat, lng, alt, altacc, head, vel);
var loc = new Position(coords, stamp);
try {
if (lat === "undefined" || lng === "undefined") {
navigator._geo.listeners[id].fail(new PositionError(PositionError.POSITION_UNAVAILABLE, "Lat/Lng are undefined."));
}
else {
navigator._geo.lastPosition = loc;
navigator._geo.listeners[id].success(loc);
}
}
catch (e) {
console.log("Geolocation Error: Error calling success callback function.");
}
if (id === "global") {
delete navigator._geo.listeners.global;
}
};
/**
* Native callback when watch position has an error.
* PRIVATE METHOD
*
* @param {String} id The ID of the watch
* @param {Number} code The error code
* @param {String} msg The error message
*/
Geolocation.prototype.fail = function(id, code, msg) {
try {
navigator._geo.listeners[id].fail(new PositionError(code, msg));
}
catch (e) {
console.log("Geolocation Error: Error calling error callback function.");
}
};
/**
* Clears the specified heading watch.
*
* @param {String} id The ID of the watch returned from #watchPosition
*/
Geolocation.prototype.clearWatch = function(id) {
PhoneGap.exec(null, null, "Geolocation", "stop", [id]);
delete navigator._geo.listeners[id];
};
/**
* Force the PhoneGap geolocation to be used instead of built-in.
*/
Geolocation.usingPhoneGap = false;
Geolocation.usePhoneGap = function() {
if (Geolocation.usingPhoneGap) {
return;
}
Geolocation.usingPhoneGap = true;
// Set built-in geolocation methods to our own implementations
// (Cannot replace entire geolocation, but can replace individual methods)
navigator.geolocation.setLocation = navigator._geo.setLocation;
navigator.geolocation.getCurrentPosition = navigator._geo.getCurrentPosition;
navigator.geolocation.watchPosition = navigator._geo.watchPosition;
navigator.geolocation.clearWatch = navigator._geo.clearWatch;
navigator.geolocation.start = navigator._geo.start;
navigator.geolocation.stop = navigator._geo.stop;
};
PhoneGap.addConstructor(function() {
navigator._geo = new Geolocation();
// No native geolocation object for Android 1.x, so use PhoneGap geolocation
if (typeof navigator.geolocation === 'undefined') {
navigator.geolocation = navigator._geo;
Geolocation.usingPhoneGap = true;
}
});
}
/*
* PhoneGap is available under *either* the terms of the modified BSD license *or* the
* MIT License (2008). See http://opensource.org/licenses/alphabetical for full text.
*
* Copyright (c) 2005-2010, Nitobi Software Inc.
* Copyright (c) 2010, IBM Corporation
*/
/*
* PhoneGap is available under *either* the terms of the modified BSD license *or* the
* MIT License (2008). See http://opensource.org/licenses/alphabetical for full text.
*
* Copyright (c) 2005-2010, Nitobi Software Inc.
* Copyright (c) 2010-2011, IBM Corporation
*/
if (!PhoneGap.hasResource("media")) {
PhoneGap.addResource("media");
/**
* This class provides access to the device media, interfaces to both sound and video
*
* @constructor
* @param src The file name or url to play
* @param successCallback The callback to be called when the file is done playing or recording.
* successCallback() - OPTIONAL
* @param errorCallback The callback to be called if there is an error.
* errorCallback(int errorCode) - OPTIONAL
* @param statusCallback The callback to be called when media status has changed.
* statusCallback(int statusCode) - OPTIONAL
* @param positionCallback The callback to be called when media position has changed.
* positionCallback(long position) - OPTIONAL
*/
var Media = function(src, successCallback, errorCallback, statusCallback, positionCallback) {
// successCallback optional
if (successCallback && (typeof successCallback !== "function")) {
console.log("Media Error: successCallback is not a function");
return;
}
// errorCallback optional
if (errorCallback && (typeof errorCallback !== "function")) {
console.log("Media Error: errorCallback is not a function");
return;
}
// statusCallback optional
if (statusCallback && (typeof statusCallback !== "function")) {
console.log("Media Error: statusCallback is not a function");
return;
}
// statusCallback optional
if (positionCallback && (typeof positionCallback !== "function")) {
console.log("Media Error: positionCallback is not a function");
return;
}
this.id = PhoneGap.createUUID();
PhoneGap.mediaObjects[this.id] = this;
this.src = src;
this.successCallback = successCallback;
this.errorCallback = errorCallback;
this.statusCallback = statusCallback;
this.positionCallback = positionCallback;
this._duration = -1;
this._position = -1;
};
// Media messages
Media.MEDIA_STATE = 1;
Media.MEDIA_DURATION = 2;
Media.MEDIA_POSITION = 3;
Media.MEDIA_ERROR = 9;
// Media states
Media.MEDIA_NONE = 0;
Media.MEDIA_STARTING = 1;
Media.MEDIA_RUNNING = 2;
Media.MEDIA_PAUSED = 3;
Media.MEDIA_STOPPED = 4;
Media.MEDIA_MSG = ["None", "Starting", "Running", "Paused", "Stopped"];
// TODO: Will MediaError be used?
/**
* This class contains information about any Media errors.
* @constructor
*/
var MediaError = function() {
this.code = null;
this.message = "";
};
MediaError.MEDIA_ERR_ABORTED = 1;
MediaError.MEDIA_ERR_NETWORK = 2;
MediaError.MEDIA_ERR_DECODE = 3;
MediaError.MEDIA_ERR_NONE_SUPPORTED = 4;
/**
* Start or resume playing audio file.
*/
Media.prototype.play = function() {
PhoneGap.exec(null, null, "Media", "startPlayingAudio", [this.id, this.src]);
};
/**
* Stop playing audio file.
*/
Media.prototype.stop = function() {
return PhoneGap.exec(null, null, "Media", "stopPlayingAudio", [this.id]);
};
/**
* Seek or jump to a new time in the track..
*/
Media.prototype.seekTo = function(milliseconds) {
PhoneGap.exec(null, null, "Media", "seekToAudio", [this.id, milliseconds]);
};
/**
* Pause playing audio file.
*/
Media.prototype.pause = function() {
PhoneGap.exec(null, null, "Media", "pausePlayingAudio", [this.id]);
};
/**
* Get duration of an audio file.
* The duration is only set for audio that is playing, paused or stopped.
*
* @return duration or -1 if not known.
*/
Media.prototype.getDuration = function() {
return this._duration;
};
/**
* Get position of audio.
*/
Media.prototype.getCurrentPosition = function(success, fail) {
PhoneGap.exec(success, fail, "Media", "getCurrentPositionAudio", [this.id]);
};
/**
* Start recording audio file.
*/
Media.prototype.startRecord = function() {
PhoneGap.exec(null, null, "Media", "startRecordingAudio", [this.id, this.src]);
};
/**
* Stop recording audio file.
*/
Media.prototype.stopRecord = function() {
PhoneGap.exec(null, null, "Media", "stopRecordingAudio", [this.id]);
};
/**
* Release the resources.
*/
Media.prototype.release = function() {
PhoneGap.exec(null, null, "Media", "release", [this.id]);
};
/**
* List of media objects.
* PRIVATE
*/
PhoneGap.mediaObjects = {};
/**
* Object that receives native callbacks.
* PRIVATE
* @constructor
*/
PhoneGap.Media = function() {};
/**
* Get the media object.
* PRIVATE
*
* @param id The media object id (string)
*/
PhoneGap.Media.getMediaObject = function(id) {
return PhoneGap.mediaObjects[id];
};
/**
* Audio has status update.
* PRIVATE
*
* @param id The media object id (string)
* @param status The status code (int)
* @param msg The status message (string)
*/
PhoneGap.Media.onStatus = function(id, msg, value) {
var media = PhoneGap.mediaObjects[id];
// If state update
if (msg === Media.MEDIA_STATE) {
if (value === Media.MEDIA_STOPPED) {
if (media.successCallback) {
media.successCallback();
}
}
if (media.statusCallback) {
media.statusCallback(value);
}
}
else if (msg === Media.MEDIA_DURATION) {
media._duration = value;
}
else if (msg === Media.MEDIA_ERROR) {
if (media.errorCallback) {
media.errorCallback(value);
}
}
else if (msg == Media.MEDIA_POSITION) {
media._position = value;
}
};
}
/*
* PhoneGap is available under *either* the terms of the modified BSD license *or* the
* MIT License (2008). See http://opensource.org/licenses/alphabetical for full text.
*
* Copyright (c) 2005-2010, Nitobi Software Inc.
* Copyright (c) 2010-2011, IBM Corporation
*/
if (!PhoneGap.hasResource("network")) {
PhoneGap.addResource("network");
/**
* This class contains information about the current network Connection.
* @constructor
*/
var Connection = function() {
this.type = null;
this._firstRun = true;
this._timer = null;
this.timeout = 500;
var me = this;
this.getInfo(
function(type) {
// Need to send events if we are on or offline
if (type == "none") {
// set a timer if still offline at the end of timer send the offline event
me._timer = setTimeout(function(){
me.type = type;
PhoneGap.fireEvent('offline');
me._timer = null;
}, me.timeout);
} else {
// If there is a current offline event pending clear it
if (me._timer != null) {
clearTimeout(me._timer);
me._timer = null;
}
me.type = type;
PhoneGap.fireEvent('online');
}
// should only fire this once
if (me._firstRun) {
me._firstRun = false;
PhoneGap.onPhoneGapConnectionReady.fire();
}
},
function(e) {
console.log("Error initializing Network Connection: " + e);
});
};
Connection.UNKNOWN = "unknown";
Connection.ETHERNET = "ethernet";
Connection.WIFI = "wifi";
Connection.CELL_2G = "2g";
Connection.CELL_3G = "3g";
Connection.CELL_4G = "4g";
Connection.NONE = "none";
/**
* Get connection info
*
* @param {Function} successCallback The function to call when the Connection data is available
* @param {Function} errorCallback The function to call when there is an error getting the Connection data. (OPTIONAL)
*/
Connection.prototype.getInfo = function(successCallback, errorCallback) {
// Get info
PhoneGap.exec(successCallback, errorCallback, "Network Status", "getConnectionInfo", []);
};
PhoneGap.addConstructor(function() {
if (typeof navigator.network === "undefined") {
navigator.network = new Object();
}
if (typeof navigator.network.connection === "undefined") {
navigator.network.connection = new Connection();
}
});
}
/*
* PhoneGap is available under *either* the terms of the modified BSD license *or* the
* MIT License (2008). See http://opensource.org/licenses/alphabetical for full text.
*
* Copyright (c) 2005-2010, Nitobi Software Inc.
* Copyright (c) 2010-2011, IBM Corporation
*/
if (!PhoneGap.hasResource("notification")) {
PhoneGap.addResource("notification");
/**
* This class provides access to notifications on the device.
* @constructor
*/
var Notification = function() {
};
/**
* Open a native alert dialog, with a customizable title and button text.
*
* @param {String} message Message to print in the body of the alert
* @param {Function} completeCallback The callback that is called when user clicks on a button.
* @param {String} title Title of the alert dialog (default: Alert)
* @param {String} buttonLabel Label of the close button (default: OK)
*/
Notification.prototype.alert = function(message, completeCallback, title, buttonLabel) {
var _title = (title || "Alert");
var _buttonLabel = (buttonLabel || "OK");
PhoneGap.exec(completeCallback, null, "Notification", "alert", [message,_title,_buttonLabel]);
};
/**
* Open a native confirm dialog, with a customizable title and button text.
* The result that the user selects is returned to the result callback.
*
* @param {String} message Message to print in the body of the alert
* @param {Function} resultCallback The callback that is called when user clicks on a button.
* @param {String} title Title of the alert dialog (default: Confirm)
* @param {String} buttonLabels Comma separated list of the labels of the buttons (default: 'OK,Cancel')
*/
Notification.prototype.confirm = function(message, resultCallback, title, buttonLabels) {
var _title = (title || "Confirm");
var _buttonLabels = (buttonLabels || "OK,Cancel");
PhoneGap.exec(resultCallback, null, "Notification", "confirm", [message,_title,_buttonLabels]);
};
/**
* Start spinning the activity indicator on the statusbar
*/
Notification.prototype.activityStart = function() {
PhoneGap.exec(null, null, "Notification", "activityStart", ["Busy","Please wait..."]);
};
/**
* Stop spinning the activity indicator on the statusbar, if it's currently spinning
*/
Notification.prototype.activityStop = function() {
PhoneGap.exec(null, null, "Notification", "activityStop", []);
};
/**
* Display a progress dialog with progress bar that goes from 0 to 100.
*
* @param {String} title Title of the progress dialog.
* @param {String} message Message to display in the dialog.
*/
Notification.prototype.progressStart = function(title, message) {
PhoneGap.exec(null, null, "Notification", "progressStart", [title, message]);
};
/**
* Set the progress dialog value.
*
* @param {Number} value 0-100
*/
Notification.prototype.progressValue = function(value) {
PhoneGap.exec(null, null, "Notification", "progressValue", [value]);
};
/**
* Close the progress dialog.
*/
Notification.prototype.progressStop = function() {
PhoneGap.exec(null, null, "Notification", "progressStop", []);
};
/**
* Causes the device to blink a status LED.
*
* @param {Integer} count The number of blinks.
* @param {String} colour The colour of the light.
*/
Notification.prototype.blink = function(count, colour) {
// NOT IMPLEMENTED
};
/**
* Causes the device to vibrate.
*
* @param {Integer} mills The number of milliseconds to vibrate for.
*/
Notification.prototype.vibrate = function(mills) {
PhoneGap.exec(null, null, "Notification", "vibrate", [mills]);
};
/**
* Causes the device to beep.
* On Android, the default notification ringtone is played "count" times.
*
* @param {Integer} count The number of beeps.
*/
Notification.prototype.beep = function(count) {
PhoneGap.exec(null, null, "Notification", "beep", [count]);
};
PhoneGap.addConstructor(function() {
if (typeof navigator.notification === "undefined") {
navigator.notification = new Notification();
}
});
}
/*
* PhoneGap is available under *either* the terms of the modified BSD license *or* the
* MIT License (2008). See http://opensource.org/licenses/alphabetical for full text.
*
* Copyright (c) 2005-2010, Nitobi Software Inc.
* Copyright (c) 2010-2011, IBM Corporation
*/
if (!PhoneGap.hasResource("position")) {
PhoneGap.addResource("position");
/**
* This class contains position information.
* @param {Object} lat
* @param {Object} lng
* @param {Object} acc
* @param {Object} alt
* @param {Object} altacc
* @param {Object} head
* @param {Object} vel
* @constructor
*/
var Position = function(coords, timestamp) {
this.coords = coords;
this.timestamp = (timestamp !== 'undefined') ? timestamp : new Date().getTime();
};
/** @constructor */
var Coordinates = function(lat, lng, alt, acc, head, vel, altacc) {
/**
* The latitude of the position.
*/
this.latitude = lat;
/**
* The longitude of the position,
*/
this.longitude = lng;
/**
* The accuracy of the position.
*/
this.accuracy = acc;
/**
* The altitude of the position.
*/
this.altitude = alt;
/**
* The direction the device is moving at the position.
*/
this.heading = head;
/**
* The velocity with which the device is moving at the position.
*/
this.speed = vel;
/**
* The altitude accuracy of the position.
*/
this.altitudeAccuracy = (altacc !== 'undefined') ? altacc : null;
};
/**
* This class specifies the options for requesting position data.
* @constructor
*/
var PositionOptions = function() {
/**
* Specifies the desired position accuracy.
*/
this.enableHighAccuracy = true;
/**
* The timeout after which if position data cannot be obtained the errorCallback
* is called.
*/
this.timeout = 10000;
};
/**
* This class contains information about any GSP errors.
* @constructor
*/
var PositionError = function() {
this.code = null;
this.message = "";
};
PositionError.UNKNOWN_ERROR = 0;
PositionError.PERMISSION_DENIED = 1;
PositionError.POSITION_UNAVAILABLE = 2;
PositionError.TIMEOUT = 3;
}
/*
* PhoneGap is available under *either* the terms of the modified BSD license *or* the
* MIT License (2008). See http://opensource.org/licenses/alphabetical for full text.
*
* Copyright (c) 2005-2010, Nitobi Software Inc.
* Copyright (c) 2010-2011, IBM Corporation
*/
/*
* This is purely for the Android 1.5/1.6 HTML 5 Storage
* I was hoping that Android 2.0 would deprecate this, but given the fact that
* most manufacturers ship with Android 1.5 and do not do OTA Updates, this is required
*/
if (!PhoneGap.hasResource("storage")) {
PhoneGap.addResource("storage");
/**
* SQL result set object
* PRIVATE METHOD
* @constructor
*/
var DroidDB_Rows = function() {
this.resultSet = []; // results array
this.length = 0; // number of rows
};
/**
* Get item from SQL result set
*
* @param row The row number to return
* @return The row object
*/
DroidDB_Rows.prototype.item = function(row) {
return this.resultSet[row];
};
/**
* SQL result set that is returned to user.
* PRIVATE METHOD
* @constructor
*/
var DroidDB_Result = function() {
this.rows = new DroidDB_Rows();
};
/**
* Storage object that is called by native code when performing queries.
* PRIVATE METHOD
* @constructor
*/
var DroidDB = function() {
this.queryQueue = {};
};
/**
* Callback from native code when query is complete.
* PRIVATE METHOD
*
* @param id Query id
*/
DroidDB.prototype.completeQuery = function(id, data) {
var query = this.queryQueue[id];
if (query) {
try {
delete this.queryQueue[id];
// Get transaction
var tx = query.tx;
// If transaction hasn't failed
// Note: We ignore all query results if previous query
// in the same transaction failed.
if (tx && tx.queryList[id]) {
// Save query results
var r = new DroidDB_Result();
r.rows.resultSet = data;
r.rows.length = data.length;
try {
if (typeof query.successCallback === 'function') {
query.successCallback(query.tx, r);
}
} catch (ex) {
console.log("executeSql error calling user success callback: "+ex);
}
tx.queryComplete(id);
}
} catch (e) {
console.log("executeSql error: "+e);
}
}
};
/**
* Callback from native code when query fails
* PRIVATE METHOD
*
* @param reason Error message
* @param id Query id
*/
DroidDB.prototype.fail = function(reason, id) {
var query = this.queryQueue[id];
if (query) {
try {
delete this.queryQueue[id];
// Get transaction
var tx = query.tx;
// If transaction hasn't failed
// Note: We ignore all query results if previous query
// in the same transaction failed.
if (tx && tx.queryList[id]) {
tx.queryList = {};
try {
if (typeof query.errorCallback === 'function') {
query.errorCallback(query.tx, reason);
}
} catch (ex) {
console.log("executeSql error calling user error callback: "+ex);
}
tx.queryFailed(id, reason);
}
} catch (e) {
console.log("executeSql error: "+e);
}
}
};
/**
* SQL query object
* PRIVATE METHOD
*
* @constructor
* @param tx The transaction object that this query belongs to
*/
var DroidDB_Query = function(tx) {
// Set the id of the query
this.id = PhoneGap.createUUID();
// Add this query to the queue
droiddb.queryQueue[this.id] = this;
// Init result
this.resultSet = [];
// Set transaction that this query belongs to
this.tx = tx;
// Add this query to transaction list
this.tx.queryList[this.id] = this;
// Callbacks
this.successCallback = null;
this.errorCallback = null;
};
/**
* Transaction object
* PRIVATE METHOD
* @constructor
*/
var DroidDB_Tx = function() {
// Set the id of the transaction
this.id = PhoneGap.createUUID();
// Callbacks
this.successCallback = null;
this.errorCallback = null;
// Query list
this.queryList = {};
};
/**
* Mark query in transaction as complete.
* If all queries are complete, call the user's transaction success callback.
*
* @param id Query id
*/
DroidDB_Tx.prototype.queryComplete = function(id) {
delete this.queryList[id];
// If no more outstanding queries, then fire transaction success
if (this.successCallback) {
var count = 0;
var i;
for (i in this.queryList) {
if (this.queryList.hasOwnProperty(i)) {
count++;
}
}
if (count === 0) {
try {
this.successCallback();
} catch(e) {
console.log("Transaction error calling user success callback: " + e);
}
}
}
};
/**
* Mark query in transaction as failed.
*
* @param id Query id
* @param reason Error message
*/
DroidDB_Tx.prototype.queryFailed = function(id, reason) {
// The sql queries in this transaction have already been run, since
// we really don't have a real transaction implemented in native code.
// However, the user callbacks for the remaining sql queries in transaction
// will not be called.
this.queryList = {};
if (this.errorCallback) {
try {
this.errorCallback(reason);
} catch(e) {
console.log("Transaction error calling user error callback: " + e);
}
}
};
/**
* Execute SQL statement
*
* @param sql SQL statement to execute
* @param params Statement parameters
* @param successCallback Success callback
* @param errorCallback Error callback
*/
DroidDB_Tx.prototype.executeSql = function(sql, params, successCallback, errorCallback) {
// Init params array
if (typeof params === 'undefined') {
params = [];
}
// Create query and add to queue
var query = new DroidDB_Query(this);
droiddb.queryQueue[query.id] = query;
// Save callbacks
query.successCallback = successCallback;
query.errorCallback = errorCallback;
// Call native code
PhoneGap.exec(null, null, "Storage", "executeSql", [sql, params, query.id]);
};
var DatabaseShell = function() {
};
/**
* Start a transaction.
* Does not support rollback in event of failure.
*
* @param process {Function} The transaction function
* @param successCallback {Function}
* @param errorCallback {Function}
*/
DatabaseShell.prototype.transaction = function(process, errorCallback, successCallback) {
var tx = new DroidDB_Tx();
tx.successCallback = successCallback;
tx.errorCallback = errorCallback;
try {
process(tx);
} catch (e) {
console.log("Transaction error: "+e);
if (tx.errorCallback) {
try {
tx.errorCallback(e);
} catch (ex) {
console.log("Transaction error calling user error callback: "+e);
}
}
}
};
/**
* Open database
*
* @param name Database name
* @param version Database version
* @param display_name Database display name
* @param size Database size in bytes
* @return Database object
*/
var DroidDB_openDatabase = function(name, version, display_name, size) {
PhoneGap.exec(null, null, "Storage", "openDatabase", [name, version, display_name, size]);
var db = new DatabaseShell();
return db;
};
/**
* For browsers with no localStorage we emulate it with SQLite. Follows the w3c api.
* TODO: Do similar for sessionStorage.
*/
/**
* @constructor
*/
var CupcakeLocalStorage = function() {
try {
this.db = openDatabase('localStorage', '1.0', 'localStorage', 2621440);
var storage = {};
this.length = 0;
function setLength (length) {
this.length = length;
localStorage.length = length;
}
this.db.transaction(
function (transaction) {
var i;
transaction.executeSql('CREATE TABLE IF NOT EXISTS storage (id NVARCHAR(40) PRIMARY KEY, body NVARCHAR(255))');
transaction.executeSql('SELECT * FROM storage', [], function(tx, result) {
for(var i = 0; i < result.rows.length; i++) {
storage[result.rows.item(i)['id']] = result.rows.item(i)['body'];
}
setLength(result.rows.length);
PhoneGap.initializationComplete("cupcakeStorage");
});
},
function (err) {
alert(err.message);
}
);
this.setItem = function(key, val) {
if (typeof(storage[key])=='undefined') {
this.length++;
}
storage[key] = val;
this.db.transaction(
function (transaction) {
transaction.executeSql('CREATE TABLE IF NOT EXISTS storage (id NVARCHAR(40) PRIMARY KEY, body NVARCHAR(255))');
transaction.executeSql('REPLACE INTO storage (id, body) values(?,?)', [key,val]);
}
);
};
this.getItem = function(key) {
return storage[key];
};
this.removeItem = function(key) {
delete storage[key];
this.length--;
this.db.transaction(
function (transaction) {
transaction.executeSql('CREATE TABLE IF NOT EXISTS storage (id NVARCHAR(40) PRIMARY KEY, body NVARCHAR(255))');
transaction.executeSql('DELETE FROM storage where id=?', [key]);
}
);
};
this.clear = function() {
storage = {};
this.length = 0;
this.db.transaction(
function (transaction) {
transaction.executeSql('CREATE TABLE IF NOT EXISTS storage (id NVARCHAR(40) PRIMARY KEY, body NVARCHAR(255))');
transaction.executeSql('DELETE FROM storage', []);
}
);
};
this.key = function(index) {
var i = 0;
for (var j in storage) {
if (i==index) {
return j;
} else {
i++;
}
}
return null;
};
} catch(e) {
alert("Database error "+e+".");
return;
}
};
PhoneGap.addConstructor(function() {
var setupDroidDB = function() {
navigator.openDatabase = window.openDatabase = DroidDB_openDatabase;
window.droiddb = new DroidDB();
}
if (typeof window.openDatabase === "undefined") {
setupDroidDB();
} else {
window.openDatabase_orig = window.openDatabase;
window.openDatabase = function(name, version, desc, size){
// Some versions of Android will throw a SECURITY_ERR so we need
// to catch the exception and seutp our own DB handling.
var db = null;
try {
db = window.openDatabase_orig(name, version, desc, size);
}
catch (ex) {
db = null;
}
if (db == null) {
setupDroidDB();
return DroidDB_openDatabase(name, version, desc, size);
}
else {
return db;
}
}
}
if (typeof window.localStorage === "undefined") {
navigator.localStorage = window.localStorage = new CupcakeLocalStorage();
PhoneGap.waitForInitialization("cupcakeStorage");
}
});
}
| JavaScript |
/*
* artDialog 3.0.6
* Date: 2010-05-31
* http://code.google.com/p/artdialog/
* (c) 2009-2010 TangBin, http://www.planeArt.cn
*
* This is licensed under the GNU LGPL, version 2.1 or later.
* For details, see: http://creativecommons.org/licenses/LGPL/2.1/
*/
//-------------“art” 微型DOM引擎模块
(function(){
var $ = function (selector, content) {
return new $.fn.init(selector, content);
},
readyBound = false,
readyList = [],
DOMContentLoaded;
$.fn = $.prototype = {
init: function (selector, content) {
if (!selector) return this;
this[0] = typeof selector === 'string' ?
$.selector(selector, content) : selector;
if (typeof selector === 'function') return $().ready(selector);
return this;
},
// dom 就绪
ready: function(fn){
$.bindReady();
if ($.isReady) {
fn.call(document, $);
} else if (readyList) {
readyList.push(fn);
};
return this;
},
// 判断样式类是否存在
hasClass: function(name){
var reg = new RegExp('(\\s|^)' + name + '(\\s|$)');
return this[0].className.match(reg) ? true : false;;
},
// 添加样式类
addClass: function (name) {
if(!this.hasClass(name)) this[0].className += ' ' + name;
return this;
},
// 移除样式类
removeClass: function (name) {
var elem = this[0];
if (!name) {
elem.className = '';
} else
if (this.hasClass(name)){
elem.className = elem.className.replace(name, ' ');
};
return this;
},
// 读写样式
// css(name) 访问第一个匹配元素的样式属性
// css(properties) 把一个"名/值对"对象设置为所有匹配元素的样式属性
// css(name, value) 在所有匹配的元素中,设置一个样式属性的值
css: function(name, value) {
var elem = this[0];
if (typeof name === 'string') {
if (value === undefined) {
return elem.currentStyle ?
elem.currentStyle[name] :
document.defaultView.getComputedStyle(elem, false)[name];
} else {
elem.style[name] = value;
};
} else {
for (var i in name) elem.style[i] = name[i];
};
return this;
},
// 向每个匹配的元素内部追加内容
// @param {String}
// @return {Object}
append: function(content){
var elem = this[0];
if (elem.insertAdjacentHTML) {
elem.insertAdjacentHTML('beforeEnd', content);
} else {
var range = elem.ownerDocument.createRange(),
frag;
if (elem.lastChild) {
range.setStartAfter(elem.lastChild);
frag = range.createContextualFragment(content);
elem.appendChild(frag);
} else {
elem.innerHTML = content;
};
};
return this;
},
// 移除节点
// remove() 从DOM中删除所有匹配的元素
// @return {undefined}
remove: function() {
var elem = this[0];
$.each(elem.getElementsByTagName('*'), function(i, val){
val = null;
});
elem.parentNode.removeChild(elem);
elem = null;
window.CollectGarbage && CollectGarbage();// IE私有函数释放内存
},
// 事件绑定
// @param {String} 类型
// @param {Function} 要绑定的事件
// @return {Object}
bind: function (type, fn) {
var elem = this[0];
if (elem.addEventListener) {
elem.addEventListener(type, fn, false);
} else {
elem['$e' + type + fn] = fn;
elem[type + fn] = function(){elem['$e' + type + fn](window.event)};
elem.attachEvent('on' + type, elem[type + fn]);
};
return this;
},
// 事件代理
// @param {String} 类型
// @param {Function} 要绑定的事件. 注意此时this指向触发事件的元素
// @return {Object}
live: function(type, fn){
this.bind(type, function(event){
var et = event.target || event.srcElement;
fn.call(et, event);
return this;
});
},
// 移除事件
// @param {String} 类型
// @param {Function} 要卸载的事件
// @return {Object}
unbind: function (type, fn) {
var elem = this[0];
if (elem.removeEventListener) {
elem.removeEventListener(type, fn, false);
} else {
elem.detachEvent('on' + type, elem[type + fn]);
elem[type + fn] = null;
};
return this;
},
// offset() 获取相对文档的坐标
// @return {Object} 返回left、top的数值
offset: function(){
var elem = this[0],
box = elem.getBoundingClientRect(),
doc = elem.ownerDocument,
body = doc.body,
docElem = doc.documentElement,
clientTop = docElem.clientTop || body.clientTop || 0,
clientLeft = docElem.clientLeft || body.clientLeft || 0,
top = box.top + (self.pageYOffset || docElem.scrollTop) - clientTop,
left = box.left + (self.pageXOffset || docElem.scrollLeft) - clientLeft;
return {
left : left,
top : top
};
}
};
$.fn.init.prototype = $.fn;
// 单一元素选择
// @param {String} id, tag
// @param {HTMLElement} 上下文,默认document
// @return {HTMLElement}
$.selector = function(selector, content){
content = content || document;
if (/^#(\w+)$/.test(selector)) return content.getElementById(RegExp.$1);
if (/^\w+$/.test(selector)) return content.getElementsByTagName(selector)[0];
};
// 遍历
// @param {Object}
// @param {Function}
// @return {undefined}
$.each = function(obj, fn){
var name, i = 0,
length = obj.length,
isObj = length === undefined;
if (isObj) {
for (name in obj) {
if (fn.call(obj[name], name, obj[name]) === false) {
break;
};
};
} else {
for (var value = obj[0]; i < length &&
fn.call(value, i, value) !== false; value = obj[++i]) {};
};
};
// DOM就绪 感谢jQuery
$.isReady = false;
$.ready = function() {
if (!$.isReady) {
if (!document.body) {
return setTimeout($.ready, 13);
};
$.isReady = true;
if (readyList) {
var fn, i = 0;
while ((fn = readyList[ i++ ])) {
fn.call(document, $);
};
readyList = null;
};
};
};
$.bindReady = function() {
if (readyBound) {
return;
};
readyBound = true;
if (document.readyState === 'complete') {
return $.ready();
};
if (document.addEventListener) {
document.addEventListener('DOMContentLoaded', DOMContentLoaded, false);
window.addEventListener('load', $.ready, false);
} else if (document.attachEvent) {
document.attachEvent('onreadystatechange', DOMContentLoaded);
window.attachEvent('onload', $.ready);
var toplevel = false;
try {
toplevel = window.frameElement == null;
} catch(e) {};
if (document.documentElement.doScroll && toplevel) {
doScrollCheck();
};
};
};
if (document.addEventListener) {
DOMContentLoaded = function() {
document.removeEventListener('DOMContentLoaded', DOMContentLoaded, false);
$.ready();
};
} else if (document.attachEvent) {
DOMContentLoaded = function() {
if (document.readyState === 'complete') {
document.detachEvent('onreadystatechange', DOMContentLoaded);
$.ready();
};
};
};
function doScrollCheck() {
if ($.isReady) {
return;
};
try {
document.documentElement.doScroll('left');
} catch(error) {
setTimeout(doScrollCheck, 1);
return;
};
$.ready();
};
// 元素判定
// @param {Object}
// @return {Boolean}
$.isElem = function(obj) {
return obj && obj.nodeType === 1;
};
// 数组判定
$.isArray = function(obj) {
return Object.prototype.toString.call(obj) === '[object Array]';
};
// 页面编码
$.charset = function(){
var d = document;
return d.characterSet || d.charset;
}();
// 浏览器判定
$.isIE = !-[1,];
$.isIE6 = $.isIE && !window.XMLHttpRequest;
// 动态加载外部CSS文件
// @param {String} CSS路径
// @param {Function} 回调函数
// @param {Object} 文档对象,默认为当前文档
// @return {undefined}
$.getStyle = function(href, fn, doc){
doc = doc || document;
var link = document.createElement('link');
link.charset = $.charset;
link.rel = 'stylesheet';
link.type = 'text/css';
link.href = href;
doc.getElementsByTagName('head')[0].appendChild(link);
var styles = doc.styleSheets,
load = function(){
for (var i = 0; i < styles.length; i++){
if (link === (styles[i].ownerNode || styles[i].owningElement)) return fn();
};
setTimeout(arguments.callee, 5);
};
fn && load();
};
// 向head添加CSS
// @param {String} CSS内容
// @param {Object} 文档对象,默认为当前文档
// @return {undefined}
var _style = {};
$.addHeadStyle = function(content, doc) {
doc = doc || document;
var style = _style[doc];
if(!style){
style = _style[doc] = doc.createElement('style');
style.setAttribute('type', 'text/css');
$('head')[0].appendChild(style);
};
style.styleSheet && (style.styleSheet.cssText += content) || style.appendChild(doc.createTextNode(content));
};
// 动态加载外部javaScript文件
// @param {String} 文件路径
// @param {Function} 回调函数
// @param {Object} 文档对象,默认为当前文档
// @return {undefined}
$.getScript = function(src, fn, doc) {
doc = doc || document;
var script = doc.createElement('script');
script.language = "javascript";
script.charset = $.charset;
script.type = 'text/javascript';
// 读取完后的操作
script.onload = script.onreadystatechange = function() {
if (!script.readyState || 'loaded' === script.readyState ||'complete' === script.readyState) {
fn && fn();
script.onload = script.onreadystatechange = null;
script.parentNode.removeChild(script);
};
};
script.src = src;
// 不插入head是为了保证script标签在DOM中的顺序,以免获取自身scr路径的方法出错
doc.body.appendChild(script);
};
var _path = document.getElementsByTagName('script');
_path = _path[_path.length-1].src.replace(/\\/g, '/');
// 当前外链js所在路径
$.getPath = _path.lastIndexOf('/') < 0 ? '.' : _path.substring(0, _path.lastIndexOf('/'));
// 当前外链js地址
$.getUrl = _path.split('?')[0];
// 当前外链js地址参数
$.getArgs = _path.split('?')[1] || '';
// 阻止事件冒泡
// @param {Object}
// @return {undefined}
$.stopBubble = function(event){
event.stopPropagation ? event.stopPropagation() : event.cancelBubble = true;
};
// 阻止浏览器默认行为
// @param {Object}
// @return {undefined}
$.stopDefault = function(event){
event.preventDefault ? event.preventDefault() : event.returnValue = false;
};
(function(){
var dd, db, dom,
get = function(win){
dd = win ? win.document.documentElement : document.documentElement;
db = win ? win.document.body : document.body;
dom = dd || db;
};
// 获取页面相关属性
$.doc = function(win){
get(win);
return {
width: Math.max(dom.clientWidth, dom.scrollWidth), // 页面宽度
height: Math.max(dom.clientHeight, dom.scrollHeight), // 页面长度
left: Math.max(dd.scrollLeft, db.scrollLeft), // 被滚动条卷去的文档宽度
top: Math.max(dd.scrollTop, db.scrollTop) // 被滚动条卷去的文档高度
};
};
// 获取浏览器视口大小
$.win = function(win){
get(win);
return {
width: dom.clientWidth,
height: dom.clientHeight
};
};
})();
// 微型模板引擎
// Simple JavaScript Templating
// Copyright (c) John Resig
// MIT Licensed
// http://ejohn.org/
// @param {String} 可以是模板字符串也可以是装载模板HTML标签的ID
// @param {Object} 给模板附加数据
// @return {String} 解析好的模板
(function(){
var cache = {};
$.tmpl = function tmpl(str, data){
var fn = !/\W/.test(str) ?
cache[str] = cache[str] ||
tmpl(document.getElementById(str).innerHTML) :
new Function("obj",
"var p=[],print=function(){p.push.apply(p,arguments);};" +
"with(obj){p.push('" +
str
.replace(/[\r\t\n]/g, " ")
.split("<%").join("\t")
.replace(/((^|%>)[^\t]*)'/g, "$1\r")
.replace(/\t=(.*?)%>/g, "',$1,'")
.split("\t").join("');")
.split("%>").join("p.push('")
.split("\r").join("\\'")
+ "');}return p.join('');");
return data ? fn( data ) : fn;
};
})();
// 微型动画引擎
// @param {HTMLElement} 元素
// @param {Number} 开始数值
// @param {Number} 结束数值
// @param {Function} 运动中不断执行设置元素状态的函数. “this”指针指向变化的数值
// @param {Function} 执行完毕后的函数
// @param {Number} 速度. 默认300
// @return {undefined}
$.effect = function(elem, start, end, change, callback, speed){
speed = speed || 300;
var sTime = + new Date(),
eTime,
val,
iTimer = setInterval(function() {
eTime = (+ new Date() - sTime) / speed;
if (eTime >= 1) {
change.call(end);
callback && callback.call(elem);
return clearInterval(iTimer);
};
val = start + (end - start) * ((- Math.cos(eTime * Math.PI) / 2) + 0.5);
change.call(val);
}, 1);
};
if (!window.art) window.art = $;
//-------------end
})();
//-------------Dialog应用模块
(function($){
// 透明渐变动画
// @param {Number} 结束的透明度
// @param {Function} 回调函数
// @param {Number} 速度
// @return {Object}
$.fn.opacityFlash = function(end, fn, speed){
var elem = this[0],
start = end === 0 ? 1 : 0,
change = elem.filters ? function(){
elem.filters.alpha.opacity = this * 100;
} : function(){
elem.style.opacity = this;
};
$.effect(elem, start, end, change, fn, speed);
return this;
};
// CSS常规动画
// @param {String} CSS属性名
// @param {Number} 结束的值
// @param {Function} 回调函数
// @param {Number} 速度. 默认300
// @return {Object}
$.fn.cssFlash = function(name, end, fn, speed){
var elem = this[0],
start = parseInt(this.css(name)),
end = parseInt(end),
change = function(){
try {
elem.style[name] = this + 'px';
} catch (_){
};
};
$.effect(elem, start, end, change, fn, speed);
return this;
};
// 清除文本选择
$.clsSelect = window.getSelection ?
function(){
try{
window.getSelection().removeAllRanges()
}catch(_){};
} :
function(){
try{
document.selection.empty();
}catch(_){};
};
// 元素可挪动边界算法
// @param {Boolean} 是否静止定位,默认否
// @param {Number} 指定其他宽度
// @param {Number} 指定其他高度
// @return {Object} 将返回最小、最大的Left与Top的值与居中的Left、Top值
$.fn.limit = function(fixed, width, height){
var minX, minY, maxX, maxY, centerX, centerY;
var win = $.win(),
doc = $.doc();
var winWidth = win.width,
winHeight = win.height,
docLeft = doc.left,
docTop = doc.top,
boxWidth = width || this[0].offsetWidth,
boxHeight = height || this[0].offsetHeight;
if (fixed) {
minX = 0;
maxX = winWidth - boxWidth;
centerX = maxX / 2;
minY = 0;
maxY = winHeight - boxHeight;
var hc = winHeight * 0.382 - boxHeight / 2;// 黄金比例垂直居中
centerY = (boxHeight < 4 * winHeight / 7) ? hc : maxY / 2;
} else {
minX = docLeft;
maxX = winWidth + minX - boxWidth;
centerX = maxX / 2;
minY = docTop;
maxY = winHeight + minY - boxHeight;
var hc = winHeight * 0.382 - boxHeight / 2 + minY;// 黄金比例垂直居中
centerY = (boxHeight < 4 * winHeight / 7) ? hc : (maxY + minY) / 2;
};
if (centerX < 0) centerX = 0;
if (centerY < 0) centerY = 0;
return {minX: minX, minY: minY, maxX: maxX, maxY: maxY, centerX: centerX, centerY: centerY};
};
(function(){
var regular, zIndex = 0;
// 元素拖动模块
// @param {Object}
// @return {Object}
$.fn.drag = function(options){
var data = options,
defaults = $.fn.drag.defaults,
limit, cache, isTemp, isDown, $move, $elem = this;
// 合并默认配置
for (var i in defaults) {
if (data[i] === undefined) data[i] = defaults[i];
};
// 设置触点
var on = data.on || this;
// 按下
var down = function(event){
isDown = true;
data.downFn && data.downFn();
// 叠加高度
var old = $elem[0].style.zIndex || data.zIndex;
zIndex = old > zIndex ? old : zIndex;
zIndex ++;
// 缓存拖动相关的数据
if (data.limit) limit = $elem.limit(data.fixed);
// 被移动元素的属性缓存
cache = function(){
var doc = $.doc();
return {
x: event.clientX,
y: event.clientY,
left: parseInt($elem[0].style.left),
top: parseInt($elem[0].style.top),
zIndex: zIndex,
width: $elem[0].offsetWidth,
height: $elem[0].offsetHeight,
docLeft: doc.left,
docTop: doc.top
};
}();
// 对于超过预设尺寸的用替身代替拖动,保证流畅
if(cache.width * cache.height >= data.showTemp) {
isTemp = true;
data.temp.css({
'width': cache.width - 2 + 'px',
'height': cache.height - 2 + 'px',
'left': cache.left + 'px',
'top': cache.top + 'px',
'zIndex': cache.zIndex,
'display': 'block'
});
};
$.clsSelect();
regular = setInterval($.clsSelect, 20);
document.body.setCapture && $elem[0].setCapture();// IE下鼠标超出视口仍可被监听
$(document).bind('mousemove', move).bind('mouseup', up);
};
on.bind('mousedown', down);
// 移动
var move = function(event){
if (isDown === false) return;
$move = isTemp ? data.temp : $elem;
var doc = $.doc();
var x = event.clientX,
y = event.clientY,
l = cache.left - cache.x + x - cache.docLeft + doc.left,
t = cache.top - cache.y + y - cache.docTop + doc.top;
if (limit) {
if (l > limit.maxX) l = limit.maxX;
if (l < limit.minX) l = limit.minX;
if (t > limit.maxY) t = limit.maxY;
if (t < limit.minY) t = limit.minY;
};
$move.css({
'left': l + 'px',
'top': t + 'px'
});
};
// 松开移动
var up = function(){
isDown = false;
$(document).unbind('mousemove', move).unbind('mouseup', up);
document.body.releaseCapture && $elem[0].releaseCapture();// IE释放鼠标监控
clearInterval(regular);
if (isTemp) {
$elem.cssFlash('left', data.temp.css('left'), null, 150).
cssFlash('top', data.temp.css('top'), function(){
data.upFn && data.upFn();
}, 150);
data.temp.css('display', 'none');
isTemp = false;
} else {
data.upFn && data.upFn();
};
};
return this;
};
$.fn.drag.defaults = {
on: null, // 触点
downFn: null, // 按下后的回调函数
upFn: null, // 松开后的回调函数
fixed: false, // 是否静止定位
limit: true, // 是否限制挪动范围
zIndex: 1, // 初始叠加高度
temp: null, // 拖动用的替身元素
showTemp: 100000 // 超过此面积的层使用替身代替拖动
};
})();
// IE6 Fixed 支持模块
var position;
$(function(){
// 给IE6 fixed 提供一个"不抖动的环境"
// 只需要 html 与 body 标签其一使用背景静止定位即可让IE6下滚动条拖动元素也不会抖动
// 注意:IE6如果 body 已经设置了背景图像静止定位后还给 html 标签设置会让 body 设置的背景静止(fixed)失效
$.isIE6 && $('body').css('backgroundAttachment') !== 'fixed' && $('html').css({
backgroundImage: 'url(about:blank)',
backgroundAttachment: 'fixed'
});
position = {
fixed: $.isIE6 ?
function(elem){
var style = elem.style,
doc = $.doc(),
de = document.documentElement,
de2 = '(document.documentElement)',
left = parseInt(style.left) - de.scrollLeft,
top = parseInt(style.top) - de.scrollTop;
this.absolute(elem);
style.setExpression('left', 'eval(' + de2 + '.scrollLeft + ' + left + ') + "px"');
style.setExpression('top', 'eval(' + de2 + '.scrollTop + ' + top + ') + "px"');
} :
function(elem){
elem.style.position = 'fixed';
},
absolute: $.isIE6 ?
function(elem){
var style = elem.style;
style.position = 'absolute';
style.removeExpression('left');
style.removeExpression('top');
} :
function(elem){
elem.style.position = 'absolute';
}
};
});
// 锁屏遮罩 && 对话框替身 && iframe遮罩
// 防止IE6锁屏遮罩被下拉控件穿透
// 防止拖动时光标落入iframe导致指针捕获异常
var publicTemplate = '\
<div id="aui_iframe_mask"></div>\
<div id="aui_overlay"><div>\
<!--[if IE 6]><iframe src="about:blank"></iframe><![endif]-->\
</div></div>\
<div id="aui_temp_wrap"><div id="aui_temp">\
<!--[if IE 6]><iframe src="about:blank"></iframe><![endif]-->\
</div></div>\
';
// 能自适应的artDialog模板
var template = '\
<div id="<%=id%>" class="aui_dialog_wrap <%="aui_" + skin%>">\
<% var _css = "aui_dialog art_focus";\
if (!border) _css += " art_no_border";\
if (!title) _css += " art_no_title";\
if (!drag) _css += " art_no_drag";\
%>\
<div id="<%=id%>dialog" class="<%=_css%>">\
<% if (border) { %>\
<table class="aui_table">\
<tr>\
<td class="aui_border aui_left_top"></td>\
<td class="aui_border aui_top"></td>\
<td class="aui_border aui_right_top"></td>\
</tr>\
<tr>\
<td class="aui_border aui_left"></td>\
<td class="aui_center">\
<% } %>\
<table class="aui_table aui_content_table">\
<% if (title) { %>\
<tr>\
<td <% if (icon) { %>colspan="2"<% } %> class="aui_td_title">\
<div class="aui_title_wrap">\
<div id="<%=id%>title" class="aui_title">\
<span class="aui_title_icon"></span><%=title%>\
</div>\
<a id="<%=id%>close" class="aui_close" href="#"><%=closeText%></a>\
</div>\
</td>\
</tr>\
<% } %>\
<tr>\
<% if (title && icon) { %>\
<td class="aui_td_icon"><div class="aui_icon art_<%=icon%>"></div></td>\
<% } %>\
<td id="<%=id%>td_content" class="aui_td_content" style="width:<%=width%>;height:<%=height%>">\
<div class="aui_content_wrap">\
<div id="<%=id%>content" class="aui_content">\
<% if (content) { %>\
<%=content%>\
<% } else { %>\
<div class="aui_noContent"></div>\
<% } %>\
</div>\
<div class="aui_content_mask"></div>\
<div class="aui_loading_tip"><%=loadingTip%></div>\
</div>\
</td>\
</tr>\
<% if (yesFn || noFn) { %>\
<tr>\
<td <% if (icon) { %>colspan="2"<% } %> class="aui_td_buttons">\
<div class="aui_buttons_wrap">\
<% if (yesFn) { %><span class="aui_yes"><button id="<%=id%>yes"><%=yesText%></button></span><% } %>\
<% if (noFn) { %><span class="aui_no"><button id="<%=id%>no"><%=noText%></button></span><% } %>\
</div>\
</td>\
</tr>\
<% } %>\
</table>\
<% if (border) { %>\
</td>\
<td class="aui_border aui_right"></td>\
</tr>\
<tr>\
<td class="aui_border aui_left_bottom"></td>\
<td class="aui_border aui_bottom"></td>\
<td class="aui_border aui_right_bottom"></td>\
</tr>\
</table>\
<% } %>\
<!--[if IE 6]><iframe id="<%=id%>ie6_select_mask" class="aui_ie6_select_mask" src="about:blank"></iframe><![endif]-->\
</div>\
</div>\
';
var count = 0,
loadList = [],
lockList = [],
dialogList = {},
$html = $('html'),
isFilters = ('filters' in document.documentElement),
lockMouse = ['DOMMouseScroll', 'mousewheel', 'scroll', 'contextmenu'],
$iframe_mask, $temp_wrap, $temp, $overlay, topBoxApi, lockBoxApi, lockClick,
topBox, zIndex, dialogReady, docMouse, docKey;
// 对话框核心
// @param {Object}
// @param {Object}
// @return {Object}
var dialog = function(data){
// 解析模板并插入文档
data.tmpl && (data.content = $.tmpl(data.tmpl, data.content));
var html = $.tmpl(template, data);
$('body').append(html);
// 获取DOM
var id = '#' + data.id;
var ui = {
wrap: $(id), // 外套
dialog: $(id + 'dialog'), // 对话框
td_content: $(id + 'td_content'), // 内容区外套
title: $(id + 'title'), // 标题拖动触点
content: $(id + 'content'), // 内容
yesBtn: $(id + 'yes'), // 确定按钮
noBtn: $(id + 'no'), // 取消按钮
closeBtn: $(id + 'close'), // 关闭按钮
ie6_select_mask: $(id + 'ie6_select_mask') // IE6 下拉控件遮罩
};
// 缓存属性
var winWidth, winHeight, docLeft, docTop, boxWidth, boxHeight,
boxLeft, boxTop;
var refreshCache = function(){
var win = $.win(),
doc = $.doc();
winWidth = win.width;
winHeight = win.height;
docLeft = doc.left;
docTop = doc.top;
boxWidth = ui.dialog[0].offsetWidth;
boxHeight = ui.dialog[0].offsetHeight;
};
refreshCache();
var isInstall, timer, ie6SelectMask, $follow = null;
// 锁屏
var lock = {
on: function(){
lockList.push(api);
position.fixed(ui.dialog[0]);
lock.zIndex();
// 限制按键
if (!docKey) docKey = function(event){
var key = event.keyCode;
// 切换按钮焦点
(key === 37 || key === 39 || key === 9) && lockBoxApi.focus();
if ((event.ctrlKey && key === 82) ||
(event.ctrlKey && key === 65) ||
key === 116 || key === 9 || key === 38 || key === 40 || key === 8) {
docMouse(event);
lockBoxApi.position().focus();
try{
event.keyCode = 0;// IE
}catch(_){};
$.stopDefault(event);
};
};
// 遮罩点击
if (!lockClick) lockClick = function(event){
data.lockClick ? lockBoxApi.close && lockBoxApi.close() : docMouse(event);
};
// 限制鼠标
if (!docMouse) docMouse = function(event){
//lockBoxApi.focus(); // iPad 下焦点会自动弹出
//scroll(docLeft, docTop); // iPad 对话框会移位
$.stopBubble(event);
$.stopDefault(event);
};
if (lockList.length === 1) {
// 绑定全局事件中断用户操作
$(document).bind('keydown', docKey);
$.each(lockMouse, function(i, name){
$(document).bind(name, docMouse);
});
// 绑定遮罩点击事件
$overlay.bind('click', lockClick);
// 针对移动设备对fixed支持不完整可能带来遮罩无法全部覆盖的问题
if ('ontouchend' in document) {
var docSize = $.doc();
$overlay.css({
width: docSize.width + 'px',
height: docSize.height + 'px'
});
};
// 对现代浏览器优雅的消除滚动条实现全屏锁定
var noCenter = $('body').css('backgroundPosition');
noCenter = noCenter && noCenter.split(' ')[0];
noCenter = noCenter !== 'center' && noCenter !== '50%';
noCenter && $.doc().height > winHeight && $html.addClass('art_page_full');
// 显示遮罩
data.effect && !isFilters ?
$overlay.addClass('art_opacity').opacityFlash(1) :
$overlay.removeClass('art_opacity');
$html.addClass('art_page_lock');
};
// 对话框中部分操作不受全局的限制
ui.dialog.bind('contextmenu', function(event){
$.stopBubble(event);
});
ui.dialog.bind('keydown', function(event){
var key = event.keyCode;
if (key === 116) return;
$.stopBubble(event);
});
lockBoxApi = api;
},
// 关闭锁屏
off: function(fn){
lockList.splice(lockList.length - 1, 1);
var out = function(){
if (lockList.length === 0) {// 只有一个对话框在调用锁屏
$html.removeClass('art_page_lock');
$html.removeClass('art_page_full');
$.each(lockMouse, function(i, name) {
$(document).unbind(name, docMouse); // 解除页面鼠标操作限制
});
$(document).unbind('keydown', docKey); // 解除屏蔽的按键
docKey = docMouse = null;
lockList = [];
} else {
// 多个调用锁屏的对话框支持ESC键连续使用
lockBoxApi = topBoxApi = lockList[lockList.length - 1].zIndex();
};
fn && fn();
};
data.effect && lockList.length === 0 && !isFilters ?
$overlay.opacityFlash(0, out) : out();
},
// 叠加高度
zIndex: function(){
$overlay.css('zIndex', zIndex);
$iframe_mask.css('zIndex', zIndex);
}
};
// 控制接口
// 每个对话框实例都会返回此接口
// 按钮回调函数的"this"指向此接口
// 调用存在id名称对话框不会执行,而是返回此接口
var api = {
// 内容
content: function(content){
if (content === undefined) {
return ui.content[0];
} else {
api.loading.off().zIndex().focus();
ui.content[0].innerHTML = content;
return api;
};
},
// 重置对话框大小
size: function(width, height, fn){
var td = ui.td_content,
ready = function(){
ie6SelectMask();
fn && fn.call(api);
};
data.width = width;
data.height = height;
if (data.effect) {
td.cssFlash('width', width).
cssFlash('height', height, ready)
} else {
td.css({
'width': width + 'px',
'height': height + 'px'
});
ready();
};
return api;
},
// 坐标定位
position: function(left, top, fixed) {
fixed = fixed || data.fixed || false;
isInstall && refreshCache();
// 防止Firefox、Opera在domReady调用对话框时候获取对象宽度不正确,
// 导致对话框left参数失效
ui.dialog[0].style.position = 'absolute';
var limit = ui.dialog.limit($.isIE6 ? false : fixed);
if (left === undefined || left === 'center') {
boxLeft = limit.centerX;
} else if (left === 'left'){
boxLeft = limit.minX;
} else if (left === 'right'){
boxLeft = limit.maxX;
} else if (typeof left === 'number') {
if (data.limit) {
left = left > limit.maxX ? limit.maxX : left;
left = left < limit.minX ? limit.minX : left;
};
boxLeft = left;
};
if (top === undefined || top === 'center') {
boxTop = limit.centerY;
} else if (top === 'top'){
boxTop = limit.minY;
} else if (top === 'bottom'){
boxTop = limit.maxY;
} else if (typeof top === 'number') {
if (data.limit) {
top = top > limit.maxY ? limit.maxY : top;
top = top < limit.minY ? limit.minY : top;
};
boxTop = top;
};
data.left = left;
data.top = top;
if (data.effect && isInstall) {
ui.dialog.cssFlash('left', boxLeft).
cssFlash('top', boxTop);
} else {
ui.dialog.css({
'left': boxLeft + 'px',
'top': boxTop + 'px'
});
};
fixed && position.fixed(ui.dialog[0]);
return api;
},
// 跟随元素
follow: function(elem){
if (!elem) return api;
if (typeof elem === 'string') elem = $(elem)[0] || $('#' + elem)[0];
// 删除旧的安装标记
$follow && $follow[0].artDialog && ($follow[0].artDialog = null);
// 给元素做个新的安装标记
elem.artDialog = data.id;
$follow = $(elem);
data.follow = elem;
// 刷新缓存
isInstall && refreshCache();
// 适应页边距
var w = (boxWidth - $follow[0].offsetWidth) / 2,
h = $follow[0].offsetHeight,
p = $follow.offset(),
l = p.left,
t = p.top;
if (w > l) w = 0;
if (t + h > docTop + winHeight - boxHeight) h = 0 - boxHeight;
return api.position(l + docLeft - w, t + h);
},
// 加载提示
loading: {
on: function(){
ui.dialog.addClass('art_loading');
return api;
},
off: function(){
ui.dialog.removeClass('art_loading');
return api;
}
},
// 置顶对话框
zIndex: function(){
zIndex ++;
ui.dialog.css('zIndex', zIndex);
lockList.length === 0 && $iframe_mask.css('zIndex', zIndex);
// IE6与Opera叠加高度受具有绝对或者相对定位的父元素z-index控制
ui.wrap.css('zIndex', zIndex);
$temp_wrap.css('zIndex', zIndex + 1);
// 点亮顶层对话框
topBox && topBox.removeClass('art_focus');
topBox = ui.dialog;
topBox.addClass('art_focus');
// 保存顶层对话框的AIP
topBoxApi = api;
return api;
},
// 元素焦点处理
focus: function(elem){
if (typeof elem === 'string') elem = $(elem)[0] || $('#' + elem)[0];
elem = ($.isElem(elem) && elem) || ui.noBtn[0] || ui.yesBtn[0] || ui.closeBtn[0];
// 延时可防止Opera会让页面滚动的问题
// try可以防止IE下不可见元素设置焦点报错的问题
setTimeout(function(){
try{
elem.focus();
}catch (_){};
}, 40);
return api;
},
// 显示对话框
show: function(fn){
// 对原生支持opacity浏览器使用特效
// IE7、8浏览器仍然对PNG启用滤镜“伪”支持,如果再使用透明滤镜会造成PNG黑边
// 想支持IE透明褪色?忍痛割爱不使用PNG做皮肤即可
data.effect && !isFilters ?
ui.dialog.addClass('art_opacity').opacityFlash(1, fn, 150) :
fn && fn();
ui.wrap.css('visibility', 'visible');
return api;
},
// 隐藏对话框
hide: function(fn){
var fn2 = function(){
var o = ui.dialog[0].style.opacity;
if (o) o = null;
ui.wrap.css('visibility', 'hidden');
fn && fn();
};
data.effect && !isFilters ?
ui.dialog.removeClass('art_opacity').opacityFlash(0, fn2, 150) :
fn2();
return api;
},
// 关闭对话框
close: function() {
if (!dialogList[data.id]) return null;
// 停止计时器
api.time();
dialogList && dialogList[data.id] && delete(dialogList[data.id]);
data.lock && ui.dialog.css('visibility', 'hidden');
var closeFn = function(){
if ($follow && $follow[0]) $follow[0].artDialog = null;
if (api === topBoxApi) topBoxApi = null;
if (topBox === ui.dialog) topBox = null;
// 在文档中删除对话框所有节点与引用
var remove = function(){
// 执行关闭回调函数
data.closeFn && data.closeFn.call(api, window);
// 从文档中移除对话框节点
ui.wrap.remove();
$.each(api, function(name){
delete api[name];
});
api = null;
};
api.hide(remove);
};
data.lock ? lock.off(closeFn) : closeFn();
return null;
},
// 定时器关闭对话框
time: function(second) {
timer && clearTimeout(timer);
if (second) timer = setTimeout(function(){
api.closeFn();
clearTimeout(timer);
}, 1000 * second);
return api;
},
// 确定按钮行为
yesFn: function(){
return typeof data.yesFn !== 'function' || data.yesFn.call(api, window) !== false ?
api.close() : api;
},
// 取消按钮行为
noFn: function(){
return typeof data.noFn !== 'function' || data.noFn.call(api, window) !== false ?
api.close() : api;
},
// 关闭按钮行为
closeFn: function(event){
event && $.stopDefault(event);
var fn = data.noFn;
return typeof fn !== 'function' || fn.call(api, window) !== false ?
api.close() : api;
},
// {供外部插件访问}
ui: ui, // 结构
data: data // 配置
};
if (data.lock) {
data.fixed = true;
data.follow = null;
};
if (data.follow || 'ontouchend' in document) data.fixed = false; // 移动设备对fixed支持有限
api.zIndex();
data.time && api.time(data.time);
data.lock && lock.on();
!data.content && api.loading.on();
data.follow ? api.follow(data.follow) : api.position(data.left, data.top, data.fixed);
// 监听对话框中鼠标的点击
ui.dialog.live('click', function(event){
var node = this.nodeName.toLowerCase();
switch (this) {
case ui.yesBtn[0]: // 确定按钮
api.yesFn();
break;
case ui.noBtn[0]: // 取消按钮
api.noFn();
break;
case ui.closeBtn[0]: // 关闭按钮
api.closeFn(event);
break;
default: // 其他元素
node === 'td' || node === 'div' && api.zIndex();
ie6SelectMask();
break;
};
});
// 给确定按钮添加一个 Ctrl + Enter 快捷键
// 只对消息内容有按键交互操作的对话框生效
ui.content.bind('keyup', function(event){
event.keyCode === 27 && $.stopBubble(event); // 防止输入的过程中按ESC退出
event.ctrlKey && (event.keyCode === 13) && api.yesFn();
});
// 固化对话框
// 防止自适应结构遇到边界会自动瘦身
// 副作用:固化后对异步写入的内容自适应机制可能会异常
!data.limit && ui.dialog.css({
width: ui.dialog[0].clientWidth + 'px',
height: ui.dialog[0].clientHeight + 'px'
});
// 启用拖动支持
data.drag && ui.title[0] && ui.dialog.drag({
on: ui.title, // 触点
fixed: $.isIE6 ? false : data.fixed, // 是否静止定位
temp: $temp, // 替身
showTemp: data.showTemp, // 超过此面积采用替身
zIndex: data.zIndex, // 初始叠加高度
limit: data.limit, // 限制挪动范围
downFn: function(){ // 按下
data.fixed && position.fixed($temp[0]);
if (data.lock) lockBoxApi = api;
api.zIndex().focus();
ui.dialog.addClass('art_move');
$html.addClass('art_page_move');
},
upFn: function(){ // 松开
$.isIE6 && data.fixed && position.fixed(ui.dialog[0]);
position.absolute($temp[0]);
ui.dialog.removeClass('art_move');
$html.removeClass('art_page_move');
}
});
// 让IE6支持PNG背景
// IE6 无法原生支持具有阿尔法通道的PNG格式图片,但可以采用滤镜来解决
// 使用滤镜比较麻烦的地方在于它CSS中定义的图片路径是针对HTML文档,所以最好采用绝对路径
if ($.isIE6) {
var list = ui.wrap[0].getElementsByTagName('*');
$.each(list, function(i, elem){
// 获取皮肤CSS文件定义的“ie6png”属性
var png = $(elem).css('ie6png'),
pngPath = $.dialog.defaults.path + '/skin/' + png;
if (png) {
elem.style.backgroundImage = 'none';
elem.runtimeStyle.filter = "progid:DXImageTransform.Microsoft." +
"AlphaImageLoader(src='" + pngPath + "',sizingMethod='crop')";
};
png = pngPath = null;
});
};
// 显示对话框
data.show && api.show();
// IE6覆盖下拉控件的遮罩
// 原理:每个对话框下使用一个同等大小的iframe强制遮盖下拉控件
ie6SelectMask = function(){
ui.ie6_select_mask[0] && ui.ie6_select_mask.css({
'width': ui.dialog[0].offsetWidth,
'height': ui.dialog[0].offsetHeight
});
};
ie6SelectMask();
setTimeout(ie6SelectMask, 40);// 有时候IE6还得重新执行一次才有效
// 智能定位按钮焦点
data.focus && api.focus(data.focus);
// 执行定义的初始化函数
data.initFn && data.initFn.call(api, window);
// 设置安装标记
isInstall = true;
$(window).bind('unload', function(){
if (!api) return;
data.effect = false;
api.close;
});
return api;
};
// 对话框入口代理
// @param {Object}
// @param {Function}
// @param {Function}
// @return {Object}
$.fn.dialog = function(options, yesFn, noFn){
// 调用其他窗口的对话框
var win = options.window || $.dialog.defaults.window;
if (typeof win === 'string' && win !== 'self') win = window[win];
// IE8要注意:
// window.top === window 为 false
// window.top == window 为 true
if (win && window != win && win.art && win.art.dialog) {
options.window = false;
return win.art.dialog(options, yesFn, noFn);
};
var data = options || {},
defaults = $.dialog.defaults;
// 判断参数类型
if (typeof data === 'string') data = {content: data, fixed: true};
if (typeof data.width === 'number') data.width = data.width + 'px';
if (typeof data.height === 'number') data.height = data.height + 'px';
if (document.compatMode === 'BackCompat') return alert(data.content);
// 整合跟随模式到主配置
data.follow = this[0] || data.follow;
// 整合按钮回调函数到主配置
data.yesFn = data.yesFn || yesFn;
data.noFn = data.noFn || noFn;
// 如果此时对话框相关文件未就绪则储存参数,等待就绪后再统一执行
if (!dialogReady) return loadList.push(data);
// 返回同名ID对话框API
if (dialogList[data.id]) return dialogList[data.id].zIndex().show().focus();
// 返回跟随模式重复的调用
if (data.follow) {
var elem = data.follow;
if (typeof elem === 'string') elem = $('#' + elem)[0];
if (elem.artDialog) return dialogList[elem.artDialog].
follow(elem).zIndex().show().focus();
};
// 生成唯一标识
count ++;
data.id = data.id || 'artDialog' + count;
// 合并默认配置
for (var i in defaults) {
if (data[i] === undefined) data[i] = defaults[i];
};
// 获取多个对话框中zIndex最大的
zIndex = zIndex || data.zIndex;
// 使用第一个皮肤
if ($.isArray(data.skin)) data.skin = data.skin[0];
return dialogList[data.id] = dialog(data);
};
$.dialog = $().dialog;
// 对外暴露默认配置
var defaults = {
// {模板需要的}
title: '\u63D0\u793A', // 标题. 默认'提示'
tmpl: null, // 供插件定义内容模板 [*]
content: null, // 内容
yesFn: null, // 确定按钮回调函数
noFn: null, // 取消按钮回调函数
yesText: '\u786E\u5B9A', // 确定按钮文本. 默认'确定'
noText: '\u53D6\u6D88', // 取消按钮文本. 默认'取消'
width: 'auto', // 宽度
height: 'auto', // 高度
skin: 'default', // 皮肤
icon: null, // 消息图标
border: true, // 是否有边框
loadingTip: 'Loading..', // 加载状态的提示
closeText: '\xd7', // 关闭按钮文本. 默认'×'
// {逻辑需要的}
fixed: false, // 是否静止定位
focus: true, // 是否自动聚焦
window: 'self', // 设定弹出的窗口 [*]
esc: true, // 是否支持Esc键关闭
effect: true, // 是否开启特效
lock: false, // 是否锁屏
lockClick: false, // 点击锁屏遮罩是否关闭对话框
left: 'center', // X轴坐标
top: 'center', // Y轴坐标
time: null, // 自动关闭时间
initFn: null, // 对话框初始化后执行的函数
closeFn: null, // 对话框关闭执行的函数
follow: null, // 跟随某元素
drag: true, // 是否支持拖动
limit: true, // 是否限制位置
loadBg: true, // 预先加载皮肤背景
path: $.getPath, // 当前JS路径. 供插件调用其他文件 [*]
show: true, // 是否显示
zIndex: 1987, // 对话框最低叠加高度值(重要:此值不能过高,否则会导致Opera、Chrome等浏览器表现异常) [*]
showTemp: 100000 // 指定超过此面积的对话框拖动的时候用替身 [*]
};
$.fn.dialog.defaults = window.artDialogDefaults || defaults;
// 开启IE6 CSS背景图片缓存,防止它耗费服务器HTTP链接资源
try{
document.execCommand('BackgroundImageCache', false, true);
} catch (_){};
// 预缓存皮肤背景,给用户一个快速响应的感觉
// 这里通过插入隐秘对话框触发浏览器提前下载CSS中定义的背景图
// @param {String, Array} 皮肤名称
// @param {Boolean} 是否提前下载背景图片。默认true
// @return {undefined}
var _loadSkin = {};
$.fn.dialog.loadSkin = function(skin, bg){
var load = function(name){
if (_loadSkin[name]) return;
$.getStyle($.dialog.defaults.path + '/skin/' + name + '.css');
bg !== false && $.dialog({
skin: name,
time: 9,
limit: false,
focus: false,
lock: false,
fixed: false,
type: false,
icon: 'alert',
left: -9999,
yesFn: true,
noFn: true
});
_loadSkin[name] = true;
};
if (typeof skin === 'string') {
load(skin);
} else {
$.each(skin, function(i, name){
load(name);
});
};
};
// DOM就绪后才执行的方法
var allReady = function(){
// 载入核心CSS文件
if (!dialogReady) return $.getStyle($.dialog.defaults.path + '/core/art.dialog.css', function(){
dialogReady = true;
allReady();
});
// 插入公用层
$('body').append(publicTemplate);
$iframe_mask = $('#aui_iframe_mask');
$overlay = $('#aui_overlay');
$temp_wrap = $('#aui_temp_wrap');
$temp = $('#aui_temp');
// 监听全局键盘
var esc = function(event){
event.keyCode === 27 && topBoxApi && topBoxApi.data.esc &&
topBoxApi.closeFn();// Esc
};
$(document).bind('keyup', esc);
if (!('ontouchend' in document)) {
// 监听浏览器窗口变化
// 调节浏览器窗口后自动重置位置
// 通过延时控制各个浏览器的调用频率
var delayed,
docH = $.doc();
var winResize = function(){
delayed && clearTimeout(delayed);
// 防止IE 页面大小变化也导致执行onresize的BUG
var o = docH;
docH = $.doc();
if (Math.abs(o.height - docH.height) > 0 ||
Math.abs(o.width - docH.width) === 17) return clearTimeout(delayed);
delayed = setTimeout(function(){
$.each(dialogList, function(name, val){
val.data.follow ?
val.follow(val.data.follow) :
(typeof val.data.left === 'string' ||
typeof val.data.top === 'string') &&
val.position(val.data.left, val.data.top);
});
clearTimeout(delayed);
}, 150);
};
$(window).bind('resize', winResize);
};
// 缓存皮肤
$.dialog.loadSkin($.dialog.defaults.skin, $.dialog.defaults.loadBg);
// 批量执行文档未就绪前的请求
if (loadList.length > 0) {
$.each(loadList, function(i, name){
$.dialog(name);
});
loadList = null;
};
};
$(allReady);
// 指定窗口植入自身
$.fn.dialog.inner = function(win, fn){
// iframe跨域没有权限操作
try {
win.document;
} catch (_){
return;
};
// frameset
if (win.document.getElementsByTagName('frameset').length !== 0)
return win.parent.document.getElementsByTagName('frameset').length === 0 ? $.fn.dialog.inner(win.parent, fn) : false;
$(function(){
// IE8要注意:
// window.top === window 为false
// window.top == window 为true
if (win == window) return;
if (win.art) {
fn && fn();
} else {
win.artDialogDefaults = $.fn.dialog.defaults;
win.artDialogDefaults.loadBg = false;
var url = $.getArgs === '' ? $.getUrl : $.getUrl + '?' + $.getArgs;
$.getScript(url, fn, win.document);
};
});
};
$.dialog.inner(window.parent);
$.fn.dialog.dialogList = dialogList;
})(art);
//-------------end
//-------------dialog扩展包[此部分是独立的,不需要可以删除]
(function($, jq){
var _alert = window.alert,
_name = 'artPlus',
_html = jq ?
// jQuery html()方法可以解析script标签
function(elem, content){
jq(elem).html(content);
} :
// 原生方法
function(elem, content){
elem.innerHTML = content;
},
_load = jq ?
// 如果引入了jQuery则使用强大的jQuery.ajax
function(url, fn, cache){
jq.ajax({
url: url,
success: function(data){
fn && fn(data);
},
cache: cache
});
} :
// 仅提供基本AJAX支持
function(url, fn, cache){
var ajax = window.XMLHttpRequest ?
new XMLHttpRequest() :
new ActiveXObject('Microsoft.XMLHTTP');
ajax.onreadystatechange = function() {
if (ajax.readyState === 4 && ajax.status === 200) {
fn && fn(ajax.responseText);
ajax.onreadystatechange = null;
};
};
ajax.open('GET', url, 1);
!cache && ajax.setRequestHeader('If-Modified-Since', '0');
ajax.send(null);
};
// 警告
// @param {String} 消息内容
// @return {Object} 对话框操控接口
$.fn.dialog.alert = function(content){
return typeof content !== 'string' ?
_alert(content) :
$.dialog({
id: _name + 'Alert',
icon: 'alert',
lock: true,
window: 'top',
content: content,
yesFn: true
});
};
// 确认
// @param {String} 消息内容
// @param {Function} 确定按钮回调函数
// @param {Function} 取消按钮回调函数
// @return {Object} 对话框操控接口
$.fn.dialog.confirm = function(content, yes, no){
return $.dialog({
id: _name + 'Confirm',
icon: 'confirm',
fixed: true,
window: 'top',
content: content,
yesFn: function(here){
return yes.call(this, here);
},
noFn: function(here){
return no && no.call(this, here);
}
});
};
// 提问
// @param {String} 提问内容
// @param {Function} 回调函数. 接收参数:输入值
// @param {String} 默认值
// @return {Object} 对话框操控接口
$.fn.dialog.prompt = function(content, yes, value){
value = value || '';
var input = _name + 'promptInput';
return $.dialog({
id: _name + 'Prompt',
icon: 'prompt',
fixed: true,
window: 'top',
content: '\
<div>' + content + '</div>\
<div>\
<input id="' + input + '" value="' + value + '" type="txt" style="width:20em;padding:3px" />\
</div>\
',
focus: input,
yesFn: function(here){
return yes && yes.call(this, here.art('#' + input)[0].value, here);
},
noFn: true
});
};
// 提示
// @param {String} 提示内容
// @param {Number} 显示时间
// @return {Object} 对话框操控接口
$.fn.dialog.tips = function(content, time){
return $.dialog({
id: _name + 'tips',
icon: 'tips',
skin: 'default',
fixed: true,
window: 'top',
title: false,
content: content,
time: time || 2
});
};
// 弹窗
// @param {String} iframe地址
// @param {Object} 配置参数. 这里传入的回调函数接收的第1个参数为iframe内部window对象
// @return {Object} 对话框操控接口
$.fn.dialog.open = function(url, options){
var load, $iframe, iwin,
opt = options,
id = _name + 'Open',
data = {
window: 'top',
content: {url: url},
tmpl: '<iframe class="' + id + '" src="<%=url%>" frameborder="0" allowtransparency="true"></iframe>',
initFn: function(here){
var api = this;
$iframe = $('iframe', api.ui.content[0]);
iwin = $iframe[0].contentWindow;
api.loading.on();
load = function(){
// 植入artDialog文件
$.dialog.inner(iwin, function(){
// 给当前对话框iframe里面扩展一个关闭方法
iwin.art.fn.dialog.close = function(){
api.close();
};
// 传递来源window对象
iwin.art.fn.dialog.parent = window;
});
api.data.effect = false;
// 探测iframe内部是否可以被获取,通常只有跨域的下获取会失败
// google chrome 浏览器本地运行调用iframe也被认为跨域
if (api.data.width === 'auto' && api.data.height === 'auto') try{
var doc = $.doc(iwin);
api.size(doc.width, doc.height);
}catch (_){};
// IE6、7获取iframe大小后才能使用百分百大小
api.ui.content.addClass('art_full');
$iframe.css({
'width': '100%',
'height': '100%'
});
api.data.left === 'center' && api.data.top === 'center' && api.position('center', 'center');
api.loading.off();
opt.initFn && opt.initFn.call(api, here);
};
$iframe.bind('load', load);
},
closeFn: function(here){
$iframe.unbind('load', load);
// 重要!需要重置iframe地址,否则下次出现的对话框在IE6、7无法聚焦input
// IE删除iframe后,iframe仍然会留在内存中出现上述问题,置换src是最容易解决的方法
$iframe[0].src = 'about:blank';
opt.closeFn && opt.closeFn.call(this, here);
}
};
// 回调函数第二个参数指向iframe内部window对象
if (opt.yesFn) data.yesFn = function(here){
return opt.yesFn.call(this, iwin, here);
};
if (opt.noFn) data.noFn = function(here){
return opt.noFn.call(this, iwin, here);
};
for (var i in opt) {
if (data[i] === undefined) data[i] = opt[i];
};
$.dialog(data);
return iwin;
};
$.fn.dialog.close = function(){};
$.fn.dialog.parent = window;
// Ajax生成内容
// @param {String} url
// @param {Object, String} 配置参数. 传入字符串表示使用模板引擎解析JSON生产内容
// @param {Boolean} 是否允许缓存. 默认true
// @return {Object} 对话框操控接口
$.fn.dialog.load = function(url, options, cache){
cache = cache || false;
var opt = options || {},
tmpl = typeof opt === 'string' ? opt : null,
ajaxLoad,
data = {
window: 'top',
content: 'loading..',
initFn: function(here){
var api = this;
api.loading.on();
_load(url, function(content){
api.data.effect = false;
if (tmpl) content = $.tmpl(tmpl,
window.JSON && JSON.parse ?
JSON.parse(content) :
eval('(' + content + ')'));
_html(api.ui.content[0], content);
api.data.left === 'center' && api.data.top === 'center' && api.position('center', 'center');
api.loading.off();
opt.initFn && opt.initFn.call(api, here);
}, cache);
},
closeFn: function(here){
opt.closeFn && opt.closeFn.call(this, here);
}
};
if (opt.tmpl) {
tmpl = opt.tmpl;
opt.tmpl = null;
};
for (var i in opt) {
if (data[i] === undefined) data[i] = opt[i];
};
var dig = $.dialog(data);
};
// 获取指定对话框API
$.fn.dialog.get = function(id, win){
win = win || window;
return win.art.dialog.dialogList[id];
};
// 替换内置alert函数[可选]
// 引入js带上'plus'参数即可开启:artDialog.js?plus
if ($.getArgs === 'plus') window.alert = $.fn.dialog.alert;
// 给jQuery增加"dialog"插件
if (jq && !jq.dialog && !jq.fn.dialog) {
jq.extend({
dialog : art.dialog
});
jq.fn.dialog = function(options, yesFn, noFn){
return art(this[0]).dialog(options, yesFn, noFn);
};
};
})(art, window.jQuery);
//-------------end | JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* Configuration settings used by the XHTML 1.1 sample page (sample14.html).
*/
// Our intention is force all formatting features to use CSS classes or
// semantic aware elements.
// Load our custom CSS files for this sample.
// We are using "BasePath" just for this sample convenience. In normal
// situations it would be just pointed to the file directly,
// like "/css/myfile.css".
FCKConfig.EditorAreaCSS = FCKConfig.BasePath + '../_samples/html/assets/sample14.styles.css' ;
/**
* Core styles.
*/
FCKConfig.CoreStyles.Bold = { Element : 'span', Attributes : { 'class' : 'Bold' } } ;
FCKConfig.CoreStyles.Italic = { Element : 'span', Attributes : { 'class' : 'Italic' } } ;
FCKConfig.CoreStyles.Underline = { Element : 'span', Attributes : { 'class' : 'Underline' } } ;
FCKConfig.CoreStyles.StrikeThrough = { Element : 'span', Attributes : { 'class' : 'StrikeThrough' } } ;
/**
* Font face
*/
// List of fonts available in the toolbar combo. Each font definition is
// separated by a semi-colon (;). We are using class names here, so each font
// is defined by {Class Name}/{Combo Label}.
FCKConfig.FontNames = 'FontComic/Comic Sans MS;FontCourier/Courier New;FontTimes/Times New Roman' ;
// Define the way font elements will be applied to the document. The "span"
// element will be used. When a font is selected, the font name defined in the
// above list is passed to this definition with the name "Font", being it
// injected in the "class" attribute.
// We must also instruct the editor to replace span elements that are used to
// set the font (Overrides).
FCKConfig.CoreStyles.FontFace =
{
Element : 'span',
Attributes : { 'class' : '#("Font")' },
Overrides : [ { Element : 'span', Attributes : { 'class' : /^Font(?:Comic|Courier|Times)$/ } } ]
} ;
/**
* Font sizes.
*/
FCKConfig.FontSizes = 'FontSmaller/Smaller;FontLarger/Larger;FontSmall/8pt;FontBig/14pt;FontDouble/Double Size' ;
FCKConfig.CoreStyles.Size =
{
Element : 'span',
Attributes : { 'class' : '#("Size")' },
Overrides : [ { Element : 'span', Attributes : { 'class' : /^Font(?:Smaller|Larger|Small|Big|Double)$/ } } ]
} ;
/**
* Font colors.
*/
FCKConfig.EnableMoreFontColors = false ;
FCKConfig.FontColors = 'ff9900/FontColor1,0066cc/FontColor2,ff0000/FontColor3' ;
FCKConfig.CoreStyles.Color =
{
Element : 'span',
Attributes : { 'class' : '#("Color")' },
Overrides : [ { Element : 'span', Attributes : { 'class' : /^FontColor(?:1|2|3)$/ } } ]
} ;
FCKConfig.CoreStyles.BackColor =
{
Element : 'span',
Attributes : { 'class' : '#("Color")BG' },
Overrides : [ { Element : 'span', Attributes : { 'class' : /^FontColor(?:1|2|3)BG$/ } } ]
} ;
/**
* Indentation.
*/
FCKConfig.IndentClasses = [ 'Indent1', 'Indent2', 'Indent3' ] ;
/**
* Paragraph justification.
*/
FCKConfig.JustifyClasses = [ 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyFull' ] ;
/**
* Styles combo.
*/
FCKConfig.StylesXmlPath = '' ;
FCKConfig.CustomStyles =
{
'Strong Emphasis' : { Element : 'strong' },
'Emphasis' : { Element : 'em' },
'Computer Code' : { Element : 'code' },
'Keyboard Phrase' : { Element : 'kbd' },
'Sample Text' : { Element : 'samp' },
'Variable' : { Element : 'var' },
'Deleted Text' : { Element : 'del' },
'Inserted Text' : { Element : 'ins' },
'Cited Work' : { Element : 'cite' },
'Inline Quotation' : { Element : 'q' }
} ;
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* Sample custom configuration settings used in the plugin sample page (sample06).
*/
// Set our sample toolbar.
FCKConfig.ToolbarSets['PluginTest'] = [
['SourceSimple'],
['My_Find','My_Replace','-','Placeholder'],
['StyleSimple','FontFormatSimple','FontNameSimple','FontSizeSimple'],
['Table','-','TableInsertRowAfter','TableDeleteRows','TableInsertColumnAfter','TableDeleteColumns','TableInsertCellAfter','TableDeleteCells','TableMergeCells','TableHorizontalSplitCell','TableCellProp'],
['Bold','Italic','-','OrderedList','UnorderedList','-','Link','Unlink'],
'/',
['My_BigStyle','-','Smiley','-','About']
] ;
// Change the default plugin path.
FCKConfig.PluginsPath = FCKConfig.BasePath.substr(0, FCKConfig.BasePath.length - 7) + '_samples/_plugins/' ;
// Add our plugin to the plugins list.
// FCKConfig.Plugins.Add( pluginName, availableLanguages )
// pluginName: The plugin name. The plugin directory must match this name.
// availableLanguages: a list of available language files for the plugin (separated by a comma).
FCKConfig.Plugins.Add( 'findreplace', 'en,fr,it' ) ;
FCKConfig.Plugins.Add( 'samples' ) ;
// If you want to use plugins found on other directories, just use the third parameter.
var sOtherPluginPath = FCKConfig.BasePath.substr(0, FCKConfig.BasePath.length - 7) + 'editor/plugins/' ;
FCKConfig.Plugins.Add( 'placeholder', 'de,en,es,fr,it,pl', sOtherPluginPath ) ;
FCKConfig.Plugins.Add( 'tablecommands', null, sOtherPluginPath ) ;
FCKConfig.Plugins.Add( 'simplecommands', null, sOtherPluginPath ) ;
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* Configuration settings used by the XHTML 1.1 sample page (sample14.html).
*/
// Our intention is force all formatting features to use CSS classes or
// semantic aware elements.
/**
* Core styles.
*/
FCKConfig.CoreStyles.Bold = { Element : 'b' } ;
FCKConfig.CoreStyles.Italic = { Element : 'i' } ;
FCKConfig.CoreStyles.Underline = { Element : 'u' } ;
FCKConfig.CoreStyles.StrikeThrough = { Element : 'strike' } ;
/**
* Font face
*/
// Define the way font elements will be applied to the document. The "span"
// element will be used. When a font is selected, the font name defined in the
// above list is passed to this definition with the name "Font", being it
// injected in the "class" attribute.
// We must also instruct the editor to replace span elements that are used to
// set the font (Overrides).
FCKConfig.CoreStyles.FontFace =
{
Element : 'font',
Attributes : { 'face' : '#("Font")' }
} ;
/**
* Font sizes.
*/
FCKConfig.FontSizes = '1/xx-small;2/x-small;3/small;4/medium;5/large;6/x-large;7/xx-large' ;
FCKConfig.CoreStyles.Size =
{
Element : 'font',
Attributes : { 'size' : '#("Size")' }
} ;
/**
* Font colors.
*/
FCKConfig.EnableMoreFontColors = true ;
FCKConfig.CoreStyles.Color =
{
Element : 'font',
Attributes : { 'color' : '#("Color")' }
} ;
FCKConfig.CoreStyles.BackColor =
{
Element : 'font',
Styles : { 'background-color' : '#("Color","color")' }
} ;
/**
* Styles combo.
*/
FCKConfig.StylesXmlPath = '' ;
FCKConfig.CustomStyles =
{
'Computer Code' : { Element : 'code' },
'Keyboard Phrase' : { Element : 'kbd' },
'Sample Text' : { Element : 'samp' },
'Variable' : { Element : 'var' },
'Deleted Text' : { Element : 'del' },
'Inserted Text' : { Element : 'ins' },
'Cited Work' : { Element : 'cite' },
'Inline Quotation' : { Element : 'q' }
} ;
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* Configuration settings used by the XHTML 1.1 sample page (sample14.html).
*/
// Our intention is force all formatting features to use CSS classes or
// semantic aware elements.
/**
* Core styles.
*/
FCKConfig.CoreStyles.Bold = { Element : 'b' } ;
FCKConfig.CoreStyles.Italic = { Element : 'i' } ;
FCKConfig.CoreStyles.Underline = { Element : 'u' } ;
/**
* Font face
*/
// Define the way font elements will be applied to the document. The "span"
// element will be used. When a font is selected, the font name defined in the
// above list is passed to this definition with the name "Font", being it
// injected in the "class" attribute.
// We must also instruct the editor to replace span elements that are used to
// set the font (Overrides).
FCKConfig.CoreStyles.FontFace =
{
Element : 'font',
Attributes : { 'face' : '#("Font")' }
} ;
/**
* Font sizes.
* The CSS part of the font sizes isn't used by Flash, it is there to get the
* font rendered correctly in FCKeditor.
*/
FCKConfig.FontSizes = '8/8px;9/9px;10/10px;11/11px;12/12px;14/14px;16/16px;18/18px;20/20px;22/22px;24/24px;26/26px;28/28px;36/36px;48/48px;72/72px' ;
FCKConfig.CoreStyles.Size =
{
Element : 'font',
Attributes : { 'size' : '#("Size")' },
Styles : { 'font-size' : '#("Size","fontSize")' }
} ;
/**
* Font colors.
*/
FCKConfig.EnableMoreFontColors = true ;
FCKConfig.CoreStyles.Color =
{
Element : 'font',
Attributes : { 'color' : '#("Color")' }
} ;
/**
* Styles combo.
*/
FCKConfig.StylesXmlPath = '' ;
FCKConfig.CustomStyles =
{
} ;
/**
* Toolbar set for Flash HTML editing.
*/
FCKConfig.ToolbarSets['Flash'] = [
['Source','-','Bold','Italic','Underline','-','UnorderedList','-','Link','Unlink'],
['FontName','FontSize','-','About']
] ;
/**
* Flash specific formatting settings.
*/
FCKConfig.EditorAreaStyles = 'p, ol, ul {margin-top: 0px; margin-bottom: 0px;}' ;
FCKConfig.FormatSource = false ;
FCKConfig.FormatOutput = false ;
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* This is a sample plugin definition file.
*/
// Here we define our custom Style combo, with custom widths.
var oMyBigStyleCombo = new FCKToolbarStyleCombo() ;
oMyBigStyleCombo.FieldWidth = 250 ;
oMyBigStyleCombo.PanelWidth = 300 ;
FCKToolbarItems.RegisterItem( 'My_BigStyle', oMyBigStyleCombo ) ;
// ##### Defining a custom context menu entry.
// ## 1. Define the command to be executed when selecting the context menu item.
var oMyCMCommand = new Object() ;
oMyCMCommand.Name = 'OpenImage' ;
// This is the standard function used to execute the command (called when clicking in the context menu item).
oMyCMCommand.Execute = function()
{
// This command is called only when an image element is selected (IMG).
// Get image URL (src).
var sUrl = FCKSelection.GetSelectedElement().src ;
// Open the URL in a new window.
window.top.open( sUrl ) ;
}
// This is the standard function used to retrieve the command state (it could be disabled for some reason).
oMyCMCommand.GetState = function()
{
// Let's make it always enabled.
return FCK_TRISTATE_OFF ;
}
// ## 2. Register our custom command.
FCKCommands.RegisterCommand( 'OpenImage', oMyCMCommand ) ;
// ## 3. Define the context menu "listener".
var oMyContextMenuListener = new Object() ;
// This is the standard function called right before sowing the context menu.
oMyContextMenuListener.AddItems = function( contextMenu, tag, tagName )
{
// Let's show our custom option only for images.
if ( tagName == 'IMG' )
{
contextMenu.AddSeparator() ;
contextMenu.AddItem( 'OpenImage', 'Open image in a new window (Custom)' ) ;
}
}
// ## 4. Register our context menu listener.
FCK.ContextMenu.RegisterListener( oMyContextMenuListener ) ;
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* This is the sample plugin definition file.
*/
// Register the related commands.
FCKCommands.RegisterCommand( 'My_Find' , new FCKDialogCommand( FCKLang['DlgMyFindTitle'] , FCKLang['DlgMyFindTitle'] , FCKConfig.PluginsPath + 'findreplace/find.html' , 340, 170 ) ) ;
FCKCommands.RegisterCommand( 'My_Replace' , new FCKDialogCommand( FCKLang['DlgMyReplaceTitle'], FCKLang['DlgMyReplaceTitle'] , FCKConfig.PluginsPath + 'findreplace/replace.html', 340, 200 ) ) ;
// Create the "Find" toolbar button.
var oFindItem = new FCKToolbarButton( 'My_Find', FCKLang['DlgMyFindTitle'] ) ;
oFindItem.IconPath = FCKConfig.PluginsPath + 'findreplace/find.gif' ;
FCKToolbarItems.RegisterItem( 'My_Find', oFindItem ) ; // 'My_Find' is the name used in the Toolbar config.
// Create the "Replace" toolbar button.
var oReplaceItem = new FCKToolbarButton( 'My_Replace', FCKLang['DlgMyReplaceTitle'] ) ;
oReplaceItem.IconPath = FCKConfig.PluginsPath + 'findreplace/replace.gif' ;
FCKToolbarItems.RegisterItem( 'My_Replace', oReplaceItem ) ; // 'My_Replace' is the name used in the Toolbar config.
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* Italian language file for the sample plugin.
*/
FCKLang['DlgMyReplaceTitle'] = 'Plugin - Sostituisci' ;
FCKLang['DlgMyReplaceFindLbl'] = 'Trova:' ;
FCKLang['DlgMyReplaceReplaceLbl'] = 'Sostituisci con:' ;
FCKLang['DlgMyReplaceCaseChk'] = 'Maiuscole/minuscole' ;
FCKLang['DlgMyReplaceReplaceBtn'] = 'Sostituisci' ;
FCKLang['DlgMyReplaceReplAllBtn'] = 'Sostituisci tutto' ;
FCKLang['DlgMyReplaceWordChk'] = 'Parola intera' ;
FCKLang['DlgMyFindTitle'] = 'Plugin - Cerca' ;
FCKLang['DlgMyFindFindBtn'] = 'Cerca' ;
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* French language file for the sample plugin.
*/
FCKLang['DlgMyReplaceTitle'] = 'Plugin - Remplacer' ;
FCKLang['DlgMyReplaceFindLbl'] = 'Chercher:' ;
FCKLang['DlgMyReplaceReplaceLbl'] = 'Remplacer par:' ;
FCKLang['DlgMyReplaceCaseChk'] = 'Respecter la casse' ;
FCKLang['DlgMyReplaceReplaceBtn'] = 'Remplacer' ;
FCKLang['DlgMyReplaceReplAllBtn'] = 'Remplacer Tout' ;
FCKLang['DlgMyReplaceWordChk'] = 'Mot entier' ;
FCKLang['DlgMyFindTitle'] = 'Plugin - Chercher' ;
FCKLang['DlgMyFindFindBtn'] = 'Chercher' ;
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* English language file for the sample plugin.
*/
FCKLang['DlgMyReplaceTitle'] = 'Plugin - Replace' ;
FCKLang['DlgMyReplaceFindLbl'] = 'Find what:' ;
FCKLang['DlgMyReplaceReplaceLbl'] = 'Replace with:' ;
FCKLang['DlgMyReplaceCaseChk'] = 'Match case' ;
FCKLang['DlgMyReplaceReplaceBtn'] = 'Replace' ;
FCKLang['DlgMyReplaceReplAllBtn'] = 'Replace All' ;
FCKLang['DlgMyReplaceWordChk'] = 'Match whole word' ;
FCKLang['DlgMyFindTitle'] = 'Plugin - Find' ;
FCKLang['DlgMyFindFindBtn'] = 'Find' ;
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* Extensions to the JavaScript Core.
*
* All custom extensions functions are PascalCased to differ from the standard
* camelCased ones.
*/
String.prototype.Contains = function( textToCheck )
{
return ( this.indexOf( textToCheck ) > -1 ) ;
}
String.prototype.Equals = function()
{
var aArgs = arguments ;
// The arguments could also be a single array.
if ( aArgs.length == 1 && aArgs[0].pop )
aArgs = aArgs[0] ;
for ( var i = 0 ; i < aArgs.length ; i++ )
{
if ( this == aArgs[i] )
return true ;
}
return false ;
}
String.prototype.IEquals = function()
{
var thisUpper = this.toUpperCase() ;
var aArgs = arguments ;
// The arguments could also be a single array.
if ( aArgs.length == 1 && aArgs[0].pop )
aArgs = aArgs[0] ;
for ( var i = 0 ; i < aArgs.length ; i++ )
{
if ( thisUpper == aArgs[i].toUpperCase() )
return true ;
}
return false ;
}
String.prototype.ReplaceAll = function( searchArray, replaceArray )
{
var replaced = this ;
for ( var i = 0 ; i < searchArray.length ; i++ )
{
replaced = replaced.replace( searchArray[i], replaceArray[i] ) ;
}
return replaced ;
}
String.prototype.StartsWith = function( value )
{
return ( this.substr( 0, value.length ) == value ) ;
}
// Extends the String object, creating a "EndsWith" method on it.
String.prototype.EndsWith = function( value, ignoreCase )
{
var L1 = this.length ;
var L2 = value.length ;
if ( L2 > L1 )
return false ;
if ( ignoreCase )
{
var oRegex = new RegExp( value + '$' , 'i' ) ;
return oRegex.test( this ) ;
}
else
return ( L2 == 0 || this.substr( L1 - L2, L2 ) == value ) ;
}
String.prototype.Remove = function( start, length )
{
var s = '' ;
if ( start > 0 )
s = this.substring( 0, start ) ;
if ( start + length < this.length )
s += this.substring( start + length , this.length ) ;
return s ;
}
String.prototype.Trim = function()
{
// We are not using \s because we don't want "non-breaking spaces to be caught".
return this.replace( /(^[ \t\n\r]*)|([ \t\n\r]*$)/g, '' ) ;
}
String.prototype.LTrim = function()
{
// We are not using \s because we don't want "non-breaking spaces to be caught".
return this.replace( /^[ \t\n\r]*/g, '' ) ;
}
String.prototype.RTrim = function()
{
// We are not using \s because we don't want "non-breaking spaces to be caught".
return this.replace( /[ \t\n\r]*$/g, '' ) ;
}
String.prototype.ReplaceNewLineChars = function( replacement )
{
return this.replace( /\n/g, replacement ) ;
}
String.prototype.Replace = function( regExp, replacement, thisObj )
{
if ( typeof replacement == 'function' )
{
return this.replace( regExp,
function()
{
return replacement.apply( thisObj || this, arguments ) ;
} ) ;
}
else
return this.replace( regExp, replacement ) ;
}
Array.prototype.AddItem = function( item )
{
var i = this.length ;
this[ i ] = item ;
return i ;
}
Array.prototype.IndexOf = function( value )
{
for ( var i = 0 ; i < this.length ; i++ )
{
if ( this[i] == value )
return i ;
}
return -1 ;
}
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* FCKStyleCommand Class: represents the "Spell Check" command.
* (Gecko specific implementation)
*/
var FCKSpellCheckCommand = function()
{
this.Name = 'SpellCheck' ;
this.IsEnabled = ( FCKConfig.SpellChecker == 'SpellerPages' ) ;
}
FCKSpellCheckCommand.prototype.Execute = function()
{
FCKDialog.OpenDialog( 'FCKDialog_SpellCheck', 'Spell Check', 'dialog/fck_spellerpages.html', 440, 480 ) ;
}
FCKSpellCheckCommand.prototype.GetState = function()
{
if ( FCK.EditMode != FCK_EDITMODE_WYSIWYG )
return FCK_TRISTATE_DISABLED ;
return this.IsEnabled ? FCK_TRISTATE_OFF : FCK_TRISTATE_DISABLED ;
}
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* FCKStyleCommand Class: represents the "Style" command.
*/
var FCKStyleCommand = function()
{}
FCKStyleCommand.prototype =
{
Name : 'Style',
Execute : function( styleName, styleComboItem )
{
FCKUndo.SaveUndoStep() ;
if ( styleComboItem.Selected )
FCK.Styles.RemoveStyle( styleComboItem.Style ) ;
else
FCK.Styles.ApplyStyle( styleComboItem.Style ) ;
FCKUndo.SaveUndoStep() ;
FCK.Focus() ;
FCK.Events.FireEvent( 'OnSelectionChange' ) ;
},
GetState : function()
{
if ( FCK.EditMode != FCK_EDITMODE_WYSIWYG || !FCK.EditorDocument )
return FCK_TRISTATE_DISABLED ;
if ( FCKSelection.GetType() == 'Control' )
{
var el = FCKSelection.GetSelectedElement() ;
if ( !el || !FCKStyles.CheckHasObjectStyle( el.nodeName.toLowerCase() ) )
return FCK_TRISTATE_DISABLED ;
}
return FCK_TRISTATE_OFF ;
}
};
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* FCKNamedCommand Class: represents an internal browser command.
*/
var FCKNamedCommand = function( commandName )
{
this.Name = commandName ;
}
FCKNamedCommand.prototype.Execute = function()
{
FCK.ExecuteNamedCommand( this.Name ) ;
}
FCKNamedCommand.prototype.GetState = function()
{
if ( FCK.EditMode != FCK_EDITMODE_WYSIWYG )
return FCK_TRISTATE_DISABLED ;
return FCK.GetNamedCommandState( this.Name ) ;
}
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* FCKRemoveFormatCommand Class: controls the execution of a core style. Core
* styles are usually represented as buttons in the toolbar., like Bold and
* Italic.
*/
var FCKRemoveFormatCommand = function()
{
this.Name = 'RemoveFormat' ;
}
FCKRemoveFormatCommand.prototype =
{
Execute : function()
{
FCKStyles.RemoveAll() ;
FCK.Focus() ;
FCK.Events.FireEvent( 'OnSelectionChange' ) ;
},
GetState : function()
{
return FCK.EditorWindow ? FCK_TRISTATE_OFF : FCK_TRISTATE_DISABLED ;
}
};
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* FCKStyleCommand Class: represents the "Spell Check" command.
* (IE specific implementation)
*/
var FCKSpellCheckCommand = function()
{
this.Name = 'SpellCheck' ;
this.IsEnabled = ( FCKConfig.SpellChecker == 'ieSpell' || FCKConfig.SpellChecker == 'SpellerPages' ) ;
}
FCKSpellCheckCommand.prototype.Execute = function()
{
switch ( FCKConfig.SpellChecker )
{
case 'ieSpell' :
this._RunIeSpell() ;
break ;
case 'SpellerPages' :
FCKDialog.OpenDialog( 'FCKDialog_SpellCheck', 'Spell Check', 'dialog/fck_spellerpages.html', 440, 480 ) ;
break ;
}
}
FCKSpellCheckCommand.prototype._RunIeSpell = function()
{
try
{
var oIeSpell = new ActiveXObject( "ieSpell.ieSpellExtension" ) ;
oIeSpell.CheckAllLinkedDocuments( FCK.EditorDocument ) ;
}
catch( e )
{
if( e.number == -2146827859 )
{
if ( confirm( FCKLang.IeSpellDownload ) )
window.open( FCKConfig.IeSpellDownloadUrl , 'IeSpellDownload' ) ;
}
else
alert( 'Error Loading ieSpell: ' + e.message + ' (' + e.number + ')' ) ;
}
}
FCKSpellCheckCommand.prototype.GetState = function()
{
if ( FCK.EditMode != FCK_EDITMODE_WYSIWYG )
return FCK_TRISTATE_DISABLED ;
return this.IsEnabled ? FCK_TRISTATE_OFF : FCK_TRISTATE_DISABLED ;
}
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* FCKShowBlockCommand Class: the "Show Blocks" command.
*/
var FCKShowBlockCommand = function( name, defaultState )
{
this.Name = name ;
if ( defaultState != undefined )
this._SavedState = defaultState ;
else
this._SavedState = null ;
}
FCKShowBlockCommand.prototype.Execute = function()
{
var state = this.GetState() ;
if ( state == FCK_TRISTATE_DISABLED )
return ;
var body = FCK.EditorDocument.body ;
if ( state == FCK_TRISTATE_ON )
body.className = body.className.replace( /(^| )FCK__ShowBlocks/g, '' ) ;
else
body.className += ' FCK__ShowBlocks' ;
if ( FCKBrowserInfo.IsIE )
{
try
{
FCK.EditorDocument.selection.createRange().select() ;
}
catch ( e )
{}
}
else
{
var focus = FCK.EditorWindow.getSelection().focusNode ;
if ( focus.nodeType != 1 )
focus = focus.parentNode ;
FCKDomTools.ScrollIntoView( focus, false ) ;
}
FCK.Events.FireEvent( 'OnSelectionChange' ) ;
}
FCKShowBlockCommand.prototype.GetState = function()
{
if ( FCK.EditMode != FCK_EDITMODE_WYSIWYG )
return FCK_TRISTATE_DISABLED ;
// On some cases FCK.EditorDocument.body is not yet available
if ( !FCK.EditorDocument )
return FCK_TRISTATE_OFF ;
if ( /FCK__ShowBlocks(?:\s|$)/.test( FCK.EditorDocument.body.className ) )
return FCK_TRISTATE_ON ;
return FCK_TRISTATE_OFF ;
}
FCKShowBlockCommand.prototype.SaveState = function()
{
this._SavedState = this.GetState() ;
}
FCKShowBlockCommand.prototype.RestoreState = function()
{
if ( this._SavedState != null && this.GetState() != this._SavedState )
this.Execute() ;
}
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* FCKPastePlainTextCommand Class: represents the
* "Paste as Plain Text" command.
*/
var FCKPastePlainTextCommand = function()
{
this.Name = 'PasteText' ;
}
FCKPastePlainTextCommand.prototype.Execute = function()
{
FCK.PasteAsPlainText() ;
}
FCKPastePlainTextCommand.prototype.GetState = function()
{
if ( FCK.EditMode != FCK_EDITMODE_WYSIWYG )
return FCK_TRISTATE_DISABLED ;
return FCK.GetNamedCommandState( 'Paste' ) ;
}
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* Stretch the editor to full window size and back.
*/
var FCKFitWindow = function()
{
this.Name = 'FitWindow' ;
}
FCKFitWindow.prototype.Execute = function()
{
var eEditorFrame = window.frameElement ;
var eEditorFrameStyle = eEditorFrame.style ;
var eMainWindow = parent ;
var eDocEl = eMainWindow.document.documentElement ;
var eBody = eMainWindow.document.body ;
var eBodyStyle = eBody.style ;
var eParent ;
// Save the current selection and scroll position.
var oRange = new FCKDomRange( FCK.EditorWindow ) ;
oRange.MoveToSelection() ;
var oEditorScrollPos = FCKTools.GetScrollPosition( FCK.EditorWindow ) ;
// No original style properties known? Go fullscreen.
if ( !this.IsMaximized )
{
// Registering an event handler when the window gets resized.
if( FCKBrowserInfo.IsIE )
eMainWindow.attachEvent( 'onresize', FCKFitWindow_Resize ) ;
else
eMainWindow.addEventListener( 'resize', FCKFitWindow_Resize, true ) ;
// Save the scrollbars position.
this._ScrollPos = FCKTools.GetScrollPosition( eMainWindow ) ;
// Save and reset the styles for the entire node tree. They could interfere in the result.
eParent = eEditorFrame ;
// The extra () is to avoid a warning with strict error checking. This is ok.
while( (eParent = eParent.parentNode) )
{
if ( eParent.nodeType == 1 )
{
eParent._fckSavedStyles = FCKTools.SaveStyles( eParent ) ;
eParent.style.zIndex = FCKConfig.FloatingPanelsZIndex - 1 ;
}
}
// Hide IE scrollbars (in strict mode).
if ( FCKBrowserInfo.IsIE )
{
this.documentElementOverflow = eDocEl.style.overflow ;
eDocEl.style.overflow = 'hidden' ;
eBodyStyle.overflow = 'hidden' ;
}
else
{
// Hide the scroolbars in Firefox.
eBodyStyle.overflow = 'hidden' ;
eBodyStyle.width = '0px' ;
eBodyStyle.height = '0px' ;
}
// Save the IFRAME styles.
this._EditorFrameStyles = FCKTools.SaveStyles( eEditorFrame ) ;
// Resize.
var oViewPaneSize = FCKTools.GetViewPaneSize( eMainWindow ) ;
eEditorFrameStyle.position = "absolute";
eEditorFrame.offsetLeft ; // Kludge for Safari 3.1 browser bug, do not remove. See #2066.
eEditorFrameStyle.zIndex = FCKConfig.FloatingPanelsZIndex - 1;
eEditorFrameStyle.left = "0px";
eEditorFrameStyle.top = "0px";
eEditorFrameStyle.width = oViewPaneSize.Width + "px";
eEditorFrameStyle.height = oViewPaneSize.Height + "px";
// Giving the frame some (huge) borders on his right and bottom
// side to hide the background that would otherwise show when the
// editor is in fullsize mode and the window is increased in size
// not for IE, because IE immediately adapts the editor on resize,
// without showing any of the background oddly in firefox, the
// editor seems not to fill the whole frame, so just setting the
// background of it to white to cover the page laying behind it anyway.
if ( !FCKBrowserInfo.IsIE )
{
eEditorFrameStyle.borderRight = eEditorFrameStyle.borderBottom = "9999px solid white" ;
eEditorFrameStyle.backgroundColor = "white";
}
// Scroll to top left.
eMainWindow.scrollTo(0, 0);
// Is the editor still not on the top left? Let's find out and fix that as well. (Bug #174)
var editorPos = FCKTools.GetWindowPosition( eMainWindow, eEditorFrame ) ;
if ( editorPos.x != 0 )
eEditorFrameStyle.left = ( -1 * editorPos.x ) + "px" ;
if ( editorPos.y != 0 )
eEditorFrameStyle.top = ( -1 * editorPos.y ) + "px" ;
this.IsMaximized = true ;
}
else // Resize to original size.
{
// Remove the event handler of window resizing.
if( FCKBrowserInfo.IsIE )
eMainWindow.detachEvent( "onresize", FCKFitWindow_Resize ) ;
else
eMainWindow.removeEventListener( "resize", FCKFitWindow_Resize, true ) ;
// Restore the CSS position for the entire node tree.
eParent = eEditorFrame ;
// The extra () is to avoid a warning with strict error checking. This is ok.
while( (eParent = eParent.parentNode) )
{
if ( eParent._fckSavedStyles )
{
FCKTools.RestoreStyles( eParent, eParent._fckSavedStyles ) ;
eParent._fckSavedStyles = null ;
}
}
// Restore IE scrollbars
if ( FCKBrowserInfo.IsIE )
eDocEl.style.overflow = this.documentElementOverflow ;
// Restore original size
FCKTools.RestoreStyles( eEditorFrame, this._EditorFrameStyles ) ;
// Restore the window scroll position.
eMainWindow.scrollTo( this._ScrollPos.X, this._ScrollPos.Y ) ;
this.IsMaximized = false ;
}
FCKToolbarItems.GetItem('FitWindow').RefreshState() ;
// It seams that Firefox restarts the editing area when making this changes.
// On FF 1.0.x, the area is not anymore editable. On FF 1.5+, the special
//configuration, like DisableFFTableHandles and DisableObjectResizing get
//lost, so we must reset it. Also, the cursor position and selection are
//also lost, even if you comment the following line (MakeEditable).
// if ( FCKBrowserInfo.IsGecko10 ) // Initially I thought it was a FF 1.0 only problem.
if ( FCK.EditMode == FCK_EDITMODE_WYSIWYG )
FCK.EditingArea.MakeEditable() ;
FCK.Focus() ;
// Restore the selection and scroll position of inside the document.
oRange.Select() ;
FCK.EditorWindow.scrollTo( oEditorScrollPos.X, oEditorScrollPos.Y ) ;
}
FCKFitWindow.prototype.GetState = function()
{
if ( FCKConfig.ToolbarLocation != 'In' )
return FCK_TRISTATE_DISABLED ;
else
return ( this.IsMaximized ? FCK_TRISTATE_ON : FCK_TRISTATE_OFF );
}
function FCKFitWindow_Resize()
{
var oViewPaneSize = FCKTools.GetViewPaneSize( parent ) ;
var eEditorFrameStyle = window.frameElement.style ;
eEditorFrameStyle.width = oViewPaneSize.Width + 'px' ;
eEditorFrameStyle.height = oViewPaneSize.Height + 'px' ;
}
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* FCKJustifyCommand Class: controls block justification.
*/
var FCKJustifyCommand = function( alignValue )
{
this.AlignValue = alignValue ;
// Detect whether this is the instance for the default alignment.
var contentDir = FCKConfig.ContentLangDirection.toLowerCase() ;
this.IsDefaultAlign = ( alignValue == 'left' && contentDir == 'ltr' ) ||
( alignValue == 'right' && contentDir == 'rtl' ) ;
// Get the class name to be used by this instance.
var cssClassName = this._CssClassName = ( function()
{
var classes = FCKConfig.JustifyClasses ;
if ( classes )
{
switch ( alignValue )
{
case 'left' :
return classes[0] || null ;
case 'center' :
return classes[1] || null ;
case 'right' :
return classes[2] || null ;
case 'justify' :
return classes[3] || null ;
}
}
return null ;
} )() ;
if ( cssClassName && cssClassName.length > 0 )
this._CssClassRegex = new RegExp( '(?:^|\\s+)' + cssClassName + '(?=$|\\s)' ) ;
}
FCKJustifyCommand._GetClassNameRegex = function()
{
var regex = FCKJustifyCommand._ClassRegex ;
if ( regex != undefined )
return regex ;
var names = [] ;
var classes = FCKConfig.JustifyClasses ;
if ( classes )
{
for ( var i = 0 ; i < 4 ; i++ )
{
var className = classes[i] ;
if ( className && className.length > 0 )
names.push( className ) ;
}
}
if ( names.length > 0 )
regex = new RegExp( '(?:^|\\s+)(?:' + names.join( '|' ) + ')(?=$|\\s)' ) ;
else
regex = null ;
return FCKJustifyCommand._ClassRegex = regex ;
}
FCKJustifyCommand.prototype =
{
Execute : function()
{
// Save an undo snapshot before doing anything.
FCKUndo.SaveUndoStep() ;
var range = new FCKDomRange( FCK.EditorWindow ) ;
range.MoveToSelection() ;
var currentState = this.GetState() ;
if ( currentState == FCK_TRISTATE_DISABLED )
return ;
// Store a bookmark of the selection since the paragraph iterator might
// change the DOM tree and break selections.
var bookmark = range.CreateBookmark() ;
var cssClassName = this._CssClassName ;
// Apply alignment setting for each paragraph.
var iterator = new FCKDomRangeIterator( range ) ;
var block ;
while ( ( block = iterator.GetNextParagraph() ) )
{
block.removeAttribute( 'align' ) ;
if ( cssClassName )
{
// Remove the any of the alignment classes from the className.
var className = block.className.replace( FCKJustifyCommand._GetClassNameRegex(), '' ) ;
// Append the desired class name.
if ( currentState == FCK_TRISTATE_OFF )
{
if ( className.length > 0 )
className += ' ' ;
block.className = className + cssClassName ;
}
else if ( className.length == 0 )
FCKDomTools.RemoveAttribute( block, 'class' ) ;
}
else
{
var style = block.style ;
if ( currentState == FCK_TRISTATE_OFF )
style.textAlign = this.AlignValue ;
else
{
style.textAlign = '' ;
if ( style.cssText.length == 0 )
block.removeAttribute( 'style' ) ;
}
}
}
// Restore previous selection.
range.MoveToBookmark( bookmark ) ;
range.Select() ;
FCK.Focus() ;
FCK.Events.FireEvent( 'OnSelectionChange' ) ;
},
GetState : function()
{
// Disabled if not WYSIWYG.
if ( FCK.EditMode != FCK_EDITMODE_WYSIWYG || ! FCK.EditorWindow )
return FCK_TRISTATE_DISABLED ;
// Retrieve the first selected block.
var path = new FCKElementPath( FCKSelection.GetBoundaryParentElement( true ) ) ;
var firstBlock = path.Block || path.BlockLimit ;
if ( !firstBlock || firstBlock.nodeName.toLowerCase() == 'body' )
return FCK_TRISTATE_OFF ;
// Check if the desired style is already applied to the block.
var currentAlign ;
if ( FCKBrowserInfo.IsIE )
currentAlign = firstBlock.currentStyle.textAlign ;
else
currentAlign = FCK.EditorWindow.getComputedStyle( firstBlock, '' ).getPropertyValue( 'text-align' );
currentAlign = currentAlign.replace( /(-moz-|-webkit-|start|auto)/i, '' );
if ( ( !currentAlign && this.IsDefaultAlign ) || currentAlign == this.AlignValue )
return FCK_TRISTATE_ON ;
return FCK_TRISTATE_OFF ;
}
} ;
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* FCKIndentCommand Class: controls block indentation.
*/
var FCKIndentCommand = function( name, offset )
{
this.Name = name ;
this.Offset = offset ;
this.IndentCSSProperty = FCKConfig.ContentLangDirection.IEquals( 'ltr' ) ? 'marginLeft' : 'marginRight' ;
}
FCKIndentCommand._InitIndentModeParameters = function()
{
if ( FCKConfig.IndentClasses && FCKConfig.IndentClasses.length > 0 )
{
this._UseIndentClasses = true ;
this._IndentClassMap = {} ;
for ( var i = 0 ; i < FCKConfig.IndentClasses.length ;i++ )
this._IndentClassMap[FCKConfig.IndentClasses[i]] = i + 1 ;
this._ClassNameRegex = new RegExp( '(?:^|\\s+)(' + FCKConfig.IndentClasses.join( '|' ) + ')(?=$|\\s)' ) ;
}
else
this._UseIndentClasses = false ;
}
FCKIndentCommand.prototype =
{
Execute : function()
{
// Save an undo snapshot before doing anything.
FCKUndo.SaveUndoStep() ;
var range = new FCKDomRange( FCK.EditorWindow ) ;
range.MoveToSelection() ;
var bookmark = range.CreateBookmark() ;
// Two cases to handle here: either we're in a list, or not.
// If we're in a list, then the indent/outdent operations would be done on the list nodes.
// Otherwise, apply the operation on the nearest block nodes.
var nearestListBlock = FCKDomTools.GetCommonParentNode( range.StartNode || range.StartContainer ,
range.EndNode || range.EndContainer,
['ul', 'ol'] ) ;
if ( nearestListBlock )
this._IndentList( range, nearestListBlock ) ;
else
this._IndentBlock( range ) ;
range.MoveToBookmark( bookmark ) ;
range.Select() ;
FCK.Focus() ;
FCK.Events.FireEvent( 'OnSelectionChange' ) ;
},
GetState : function()
{
// Disabled if not WYSIWYG.
if ( FCK.EditMode != FCK_EDITMODE_WYSIWYG || ! FCK.EditorWindow )
return FCK_TRISTATE_DISABLED ;
// Initialize parameters if not already initialzed.
if ( FCKIndentCommand._UseIndentClasses == undefined )
FCKIndentCommand._InitIndentModeParameters() ;
// If we're not in a list, and the starting block's indentation is zero, and the current
// command is the outdent command, then we should return FCK_TRISTATE_DISABLED.
var startContainer = FCKSelection.GetBoundaryParentElement( true ) ;
var endContainer = FCKSelection.GetBoundaryParentElement( false ) ;
var listNode = FCKDomTools.GetCommonParentNode( startContainer, endContainer, ['ul','ol'] ) ;
if ( listNode )
{
if ( this.Name.IEquals( 'outdent' ) )
return FCK_TRISTATE_OFF ;
var firstItem = FCKTools.GetElementAscensor( startContainer, 'li' ) ;
if ( !firstItem || !firstItem.previousSibling )
return FCK_TRISTATE_DISABLED ;
return FCK_TRISTATE_OFF ;
}
if ( ! FCKIndentCommand._UseIndentClasses && this.Name.IEquals( 'indent' ) )
return FCK_TRISTATE_OFF;
var path = new FCKElementPath( startContainer ) ;
var firstBlock = path.Block || path.BlockLimit ;
if ( !firstBlock )
return FCK_TRISTATE_DISABLED ;
if ( FCKIndentCommand._UseIndentClasses )
{
var indentClass = firstBlock.className.match( FCKIndentCommand._ClassNameRegex ) ;
var indentStep = 0 ;
if ( indentClass != null )
{
indentClass = indentClass[1] ;
indentStep = FCKIndentCommand._IndentClassMap[indentClass] ;
}
if ( ( this.Name == 'outdent' && indentStep == 0 ) ||
( this.Name == 'indent' && indentStep == FCKConfig.IndentClasses.length ) )
return FCK_TRISTATE_DISABLED ;
return FCK_TRISTATE_OFF ;
}
else
{
var indent = parseInt( firstBlock.style[this.IndentCSSProperty], 10 ) ;
if ( isNaN( indent ) )
indent = 0 ;
if ( indent <= 0 )
return FCK_TRISTATE_DISABLED ;
return FCK_TRISTATE_OFF ;
}
},
_IndentBlock : function( range )
{
var iterator = new FCKDomRangeIterator( range ) ;
iterator.EnforceRealBlocks = true ;
range.Expand( 'block_contents' ) ;
var commonParents = FCKDomTools.GetCommonParents( range.StartContainer, range.EndContainer ) ;
var nearestParent = commonParents[commonParents.length - 1] ;
var block ;
while ( ( block = iterator.GetNextParagraph() ) )
{
// We don't want to indent subtrees recursively, so only perform the indent operation
// if the block itself is the nearestParent, or the block's parent is the nearestParent.
if ( ! ( block == nearestParent || block.parentNode == nearestParent ) )
continue ;
if ( FCKIndentCommand._UseIndentClasses )
{
// Transform current class name to indent step index.
var indentClass = block.className.match( FCKIndentCommand._ClassNameRegex ) ;
var indentStep = 0 ;
if ( indentClass != null )
{
indentClass = indentClass[1] ;
indentStep = FCKIndentCommand._IndentClassMap[indentClass] ;
}
// Operate on indent step index, transform indent step index back to class name.
if ( this.Name.IEquals( 'outdent' ) )
indentStep-- ;
else if ( this.Name.IEquals( 'indent' ) )
indentStep++ ;
indentStep = Math.min( indentStep, FCKConfig.IndentClasses.length ) ;
indentStep = Math.max( indentStep, 0 ) ;
var className = block.className.replace( FCKIndentCommand._ClassNameRegex, '' ) ;
if ( indentStep < 1 )
block.className = className ;
else
block.className = ( className.length > 0 ? className + ' ' : '' ) +
FCKConfig.IndentClasses[indentStep - 1] ;
}
else
{
// Offset distance is assumed to be in pixels for now.
var currentOffset = parseInt( block.style[this.IndentCSSProperty], 10 ) ;
if ( isNaN( currentOffset ) )
currentOffset = 0 ;
currentOffset += this.Offset ;
currentOffset = Math.max( currentOffset, 0 ) ;
currentOffset = Math.ceil( currentOffset / this.Offset ) * this.Offset ;
block.style[this.IndentCSSProperty] = currentOffset ? currentOffset + FCKConfig.IndentUnit : '' ;
if ( block.getAttribute( 'style' ) == '' )
block.removeAttribute( 'style' ) ;
}
}
},
_IndentList : function( range, listNode )
{
// Our starting and ending points of the range might be inside some blocks under a list item...
// So before playing with the iterator, we need to expand the block to include the list items.
var startContainer = range.StartContainer ;
var endContainer = range.EndContainer ;
while ( startContainer && startContainer.parentNode != listNode )
startContainer = startContainer.parentNode ;
while ( endContainer && endContainer.parentNode != listNode )
endContainer = endContainer.parentNode ;
if ( ! startContainer || ! endContainer )
return ;
// Now we can iterate over the individual items on the same tree depth.
var block = startContainer ;
var itemsToMove = [] ;
var stopFlag = false ;
while ( stopFlag == false )
{
if ( block == endContainer )
stopFlag = true ;
itemsToMove.push( block ) ;
block = block.nextSibling ;
}
if ( itemsToMove.length < 1 )
return ;
// Do indent or outdent operations on the array model of the list, not the list's DOM tree itself.
// The array model demands that it knows as much as possible about the surrounding lists, we need
// to feed it the further ancestor node that is still a list.
var listParents = FCKDomTools.GetParents( listNode ) ;
for ( var i = 0 ; i < listParents.length ; i++ )
{
if ( listParents[i].nodeName.IEquals( ['ul', 'ol'] ) )
{
listNode = listParents[i] ;
break ;
}
}
var indentOffset = this.Name.IEquals( 'indent' ) ? 1 : -1 ;
var startItem = itemsToMove[0] ;
var lastItem = itemsToMove[ itemsToMove.length - 1 ] ;
var markerObj = {} ;
// Convert the list DOM tree into a one dimensional array.
var listArray = FCKDomTools.ListToArray( listNode, markerObj ) ;
// Apply indenting or outdenting on the array.
var baseIndent = listArray[lastItem._FCK_ListArray_Index].indent ;
for ( var i = startItem._FCK_ListArray_Index ; i <= lastItem._FCK_ListArray_Index ; i++ )
listArray[i].indent += indentOffset ;
for ( var i = lastItem._FCK_ListArray_Index + 1 ; i < listArray.length && listArray[i].indent > baseIndent ; i++ )
listArray[i].indent += indentOffset ;
/* For debug use only
var PrintArray = function( listArray, doc )
{
var s = [] ;
for ( var i = 0 ; i < listArray.length ; i++ )
{
for ( var j in listArray[i] )
{
if ( j != 'contents' )
s.push( j + ":" + listArray[i][j] + "; " ) ;
else
{
var docFrag = doc.createDocumentFragment() ;
var tmpNode = doc.createElement( 'span' ) ;
for ( var k = 0 ; k < listArray[i][j].length ; k++ )
docFrag.appendChild( listArray[i][j][k].cloneNode( true ) ) ;
tmpNode.appendChild( docFrag ) ;
s.push( j + ":" + tmpNode.innerHTML + "; ") ;
}
}
s.push( '\n' ) ;
}
alert( s.join('') ) ;
}
PrintArray( listArray, FCK.EditorDocument ) ;
*/
// Convert the array back to a DOM forest (yes we might have a few subtrees now).
// And replace the old list with the new forest.
var newList = FCKDomTools.ArrayToList( listArray ) ;
if ( newList )
listNode.parentNode.replaceChild( newList.listNode, listNode ) ;
// Clean up the markers.
FCKDomTools.ClearAllMarkers( markerObj ) ;
}
} ;
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* FCKBlockQuoteCommand Class: adds or removes blockquote tags.
*/
var FCKBlockQuoteCommand = function()
{
}
FCKBlockQuoteCommand.prototype =
{
Execute : function()
{
FCKUndo.SaveUndoStep() ;
var state = this.GetState() ;
var range = new FCKDomRange( FCK.EditorWindow ) ;
range.MoveToSelection() ;
var bookmark = range.CreateBookmark() ;
// Kludge for #1592: if the bookmark nodes are in the beginning of
// blockquote, then move them to the nearest block element in the
// blockquote.
if ( FCKBrowserInfo.IsIE )
{
var bStart = range.GetBookmarkNode( bookmark, true ) ;
var bEnd = range.GetBookmarkNode( bookmark, false ) ;
var cursor ;
if ( bStart
&& bStart.parentNode.nodeName.IEquals( 'blockquote' )
&& !bStart.previousSibling )
{
cursor = bStart ;
while ( ( cursor = cursor.nextSibling ) )
{
if ( FCKListsLib.BlockElements[ cursor.nodeName.toLowerCase() ] )
FCKDomTools.MoveNode( bStart, cursor, true ) ;
}
}
if ( bEnd
&& bEnd.parentNode.nodeName.IEquals( 'blockquote' )
&& !bEnd.previousSibling )
{
cursor = bEnd ;
while ( ( cursor = cursor.nextSibling ) )
{
if ( FCKListsLib.BlockElements[ cursor.nodeName.toLowerCase() ] )
{
if ( cursor.firstChild == bStart )
FCKDomTools.InsertAfterNode( bStart, bEnd ) ;
else
FCKDomTools.MoveNode( bEnd, cursor, true ) ;
}
}
}
}
var iterator = new FCKDomRangeIterator( range ) ;
var block ;
if ( state == FCK_TRISTATE_OFF )
{
iterator.EnforceRealBlocks = true ;
var paragraphs = [] ;
while ( ( block = iterator.GetNextParagraph() ) )
paragraphs.push( block ) ;
// If no paragraphs, create one from the current selection position.
if ( paragraphs.length < 1 )
{
para = range.Window.document.createElement( FCKConfig.EnterMode.IEquals( 'p' ) ? 'p' : 'div' ) ;
range.InsertNode( para ) ;
para.appendChild( range.Window.document.createTextNode( '\ufeff' ) ) ;
range.MoveToBookmark( bookmark ) ;
range.MoveToNodeContents( para ) ;
range.Collapse( true ) ;
bookmark = range.CreateBookmark() ;
paragraphs.push( para ) ;
}
// Make sure all paragraphs have the same parent.
var commonParent = paragraphs[0].parentNode ;
var tmp = [] ;
for ( var i = 0 ; i < paragraphs.length ; i++ )
{
block = paragraphs[i] ;
commonParent = FCKDomTools.GetCommonParents( block.parentNode, commonParent ).pop() ;
}
var lastBlock = null ;
while ( paragraphs.length > 0 )
{
block = paragraphs.shift() ;
while ( block.parentNode != commonParent )
block = block.parentNode ;
if ( block != lastBlock )
tmp.push( block ) ;
lastBlock = block ;
}
// If any of the selected blocks is a blockquote, remove it to prevent nested blockquotes.
while ( tmp.length > 0 )
{
block = tmp.shift() ;
if ( block.nodeName.IEquals( 'blockquote' ) )
{
var docFrag = FCKTools.GetElementDocument( block ).createDocumentFragment() ;
while ( block.firstChild )
{
docFrag.appendChild( block.removeChild( block.firstChild ) ) ;
paragraphs.push( docFrag.lastChild ) ;
}
block.parentNode.replaceChild( docFrag, block ) ;
}
else
paragraphs.push( block ) ;
}
// Now we have all the blocks to be included in a new blockquote node.
var bqBlock = range.Window.document.createElement( 'blockquote' ) ;
commonParent.insertBefore( bqBlock, paragraphs[0] ) ;
while ( paragraphs.length > 0 )
{
block = paragraphs.shift() ;
bqBlock.appendChild( block ) ;
}
}
else if ( state == FCK_TRISTATE_ON )
{
var moveOutNodes = [] ;
while ( ( block = iterator.GetNextParagraph() ) )
{
var bqParent = null ;
var bqChild = null ;
while ( block.parentNode )
{
if ( block.parentNode.nodeName.IEquals( 'blockquote' ) )
{
bqParent = block.parentNode ;
bqChild = block ;
break ;
}
block = block.parentNode ;
}
if ( bqParent && bqChild )
moveOutNodes.push( bqChild ) ;
}
var movedNodes = [] ;
while ( moveOutNodes.length > 0 )
{
var node = moveOutNodes.shift() ;
var bqBlock = node.parentNode ;
// If the node is located at the beginning or the end, just take it out without splitting.
// Otherwise, split the blockquote node and move the paragraph in between the two blockquote nodes.
if ( node == node.parentNode.firstChild )
{
bqBlock.parentNode.insertBefore( bqBlock.removeChild( node ), bqBlock ) ;
if ( ! bqBlock.firstChild )
bqBlock.parentNode.removeChild( bqBlock ) ;
}
else if ( node == node.parentNode.lastChild )
{
bqBlock.parentNode.insertBefore( bqBlock.removeChild( node ), bqBlock.nextSibling ) ;
if ( ! bqBlock.firstChild )
bqBlock.parentNode.removeChild( bqBlock ) ;
}
else
FCKDomTools.BreakParent( node, node.parentNode, range ) ;
movedNodes.push( node ) ;
}
if ( FCKConfig.EnterMode.IEquals( 'br' ) )
{
while ( movedNodes.length )
{
var node = movedNodes.shift() ;
var firstTime = true ;
if ( node.nodeName.IEquals( 'div' ) )
{
var docFrag = FCKTools.GetElementDocument( node ).createDocumentFragment() ;
var needBeginBr = firstTime && node.previousSibling &&
!FCKListsLib.BlockBoundaries[node.previousSibling.nodeName.toLowerCase()] ;
if ( firstTime && needBeginBr )
docFrag.appendChild( FCKTools.GetElementDocument( node ).createElement( 'br' ) ) ;
var needEndBr = node.nextSibling &&
!FCKListsLib.BlockBoundaries[node.nextSibling.nodeName.toLowerCase()] ;
while ( node.firstChild )
docFrag.appendChild( node.removeChild( node.firstChild ) ) ;
if ( needEndBr )
docFrag.appendChild( FCKTools.GetElementDocument( node ).createElement( 'br' ) ) ;
node.parentNode.replaceChild( docFrag, node ) ;
firstTime = false ;
}
}
}
}
range.MoveToBookmark( bookmark ) ;
range.Select() ;
FCK.Focus() ;
FCK.Events.FireEvent( 'OnSelectionChange' ) ;
},
GetState : function()
{
// Disabled if not WYSIWYG.
if ( FCK.EditMode != FCK_EDITMODE_WYSIWYG || ! FCK.EditorWindow )
return FCK_TRISTATE_DISABLED ;
var path = new FCKElementPath( FCKSelection.GetBoundaryParentElement( true ) ) ;
var firstBlock = path.Block || path.BlockLimit ;
if ( !firstBlock || firstBlock.nodeName.toLowerCase() == 'body' )
return FCK_TRISTATE_OFF ;
// See if the first block has a blockquote parent.
for ( var i = 0 ; i < path.Elements.length ; i++ )
{
if ( path.Elements[i].nodeName.IEquals( 'blockquote' ) )
return FCK_TRISTATE_ON ;
}
return FCK_TRISTATE_OFF ;
}
} ;
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* Definition of other commands that are not available internaly in the
* browser (see FCKNamedCommand).
*/
// ### General Dialog Box Commands.
var FCKDialogCommand = function( name, title, url, width, height, getStateFunction, getStateParam, customValue )
{
this.Name = name ;
this.Title = title ;
this.Url = url ;
this.Width = width ;
this.Height = height ;
this.CustomValue = customValue ;
this.GetStateFunction = getStateFunction ;
this.GetStateParam = getStateParam ;
this.Resizable = false ;
}
FCKDialogCommand.prototype.Execute = function()
{
FCKDialog.OpenDialog( 'FCKDialog_' + this.Name , this.Title, this.Url, this.Width, this.Height, this.CustomValue, null, this.Resizable ) ;
}
FCKDialogCommand.prototype.GetState = function()
{
if ( this.GetStateFunction )
return this.GetStateFunction( this.GetStateParam ) ;
else
return FCK.EditMode == FCK_EDITMODE_WYSIWYG ? FCK_TRISTATE_OFF : FCK_TRISTATE_DISABLED ;
}
// Generic Undefined command (usually used when a command is under development).
var FCKUndefinedCommand = function()
{
this.Name = 'Undefined' ;
}
FCKUndefinedCommand.prototype.Execute = function()
{
alert( FCKLang.NotImplemented ) ;
}
FCKUndefinedCommand.prototype.GetState = function()
{
return FCK_TRISTATE_OFF ;
}
// ### FormatBlock
var FCKFormatBlockCommand = function()
{}
FCKFormatBlockCommand.prototype =
{
Name : 'FormatBlock',
Execute : FCKStyleCommand.prototype.Execute,
GetState : function()
{
return FCK.EditorDocument ? FCK_TRISTATE_OFF : FCK_TRISTATE_DISABLED ;
}
};
// ### FontName
var FCKFontNameCommand = function()
{}
FCKFontNameCommand.prototype =
{
Name : 'FontName',
Execute : FCKStyleCommand.prototype.Execute,
GetState : FCKFormatBlockCommand.prototype.GetState
};
// ### FontSize
var FCKFontSizeCommand = function()
{}
FCKFontSizeCommand.prototype =
{
Name : 'FontSize',
Execute : FCKStyleCommand.prototype.Execute,
GetState : FCKFormatBlockCommand.prototype.GetState
};
// ### Preview
var FCKPreviewCommand = function()
{
this.Name = 'Preview' ;
}
FCKPreviewCommand.prototype.Execute = function()
{
FCK.Preview() ;
}
FCKPreviewCommand.prototype.GetState = function()
{
return FCK_TRISTATE_OFF ;
}
// ### Save
var FCKSaveCommand = function()
{
this.Name = 'Save' ;
}
FCKSaveCommand.prototype.Execute = function()
{
// Get the linked field form.
var oForm = FCK.GetParentForm() ;
if ( typeof( oForm.onsubmit ) == 'function' )
{
var bRet = oForm.onsubmit() ;
if ( bRet != null && bRet === false )
return ;
}
// Submit the form.
// If there's a button named "submit" then the form.submit() function is masked and
// can't be called in Mozilla, so we call the click() method of that button.
if ( typeof( oForm.submit ) == 'function' )
oForm.submit() ;
else
oForm.submit.click() ;
}
FCKSaveCommand.prototype.GetState = function()
{
return FCK_TRISTATE_OFF ;
}
// ### NewPage
var FCKNewPageCommand = function()
{
this.Name = 'NewPage' ;
}
FCKNewPageCommand.prototype.Execute = function()
{
FCKUndo.SaveUndoStep() ;
FCK.SetData( '' ) ;
FCKUndo.Typing = true ;
FCK.Focus() ;
}
FCKNewPageCommand.prototype.GetState = function()
{
return FCK_TRISTATE_OFF ;
}
// ### Source button
var FCKSourceCommand = function()
{
this.Name = 'Source' ;
}
FCKSourceCommand.prototype.Execute = function()
{
if ( FCKConfig.SourcePopup ) // Until v2.2, it was mandatory for FCKBrowserInfo.IsGecko.
{
var iWidth = FCKConfig.ScreenWidth * 0.65 ;
var iHeight = FCKConfig.ScreenHeight * 0.65 ;
FCKDialog.OpenDialog( 'FCKDialog_Source', FCKLang.Source, 'dialog/fck_source.html', iWidth, iHeight, null, null, true ) ;
}
else
FCK.SwitchEditMode() ;
}
FCKSourceCommand.prototype.GetState = function()
{
return ( FCK.EditMode == FCK_EDITMODE_WYSIWYG ? FCK_TRISTATE_OFF : FCK_TRISTATE_ON ) ;
}
// ### Undo
var FCKUndoCommand = function()
{
this.Name = 'Undo' ;
}
FCKUndoCommand.prototype.Execute = function()
{
FCKUndo.Undo() ;
}
FCKUndoCommand.prototype.GetState = function()
{
if ( FCK.EditMode != FCK_EDITMODE_WYSIWYG )
return FCK_TRISTATE_DISABLED ;
return ( FCKUndo.CheckUndoState() ? FCK_TRISTATE_OFF : FCK_TRISTATE_DISABLED ) ;
}
// ### Redo
var FCKRedoCommand = function()
{
this.Name = 'Redo' ;
}
FCKRedoCommand.prototype.Execute = function()
{
FCKUndo.Redo() ;
}
FCKRedoCommand.prototype.GetState = function()
{
if ( FCK.EditMode != FCK_EDITMODE_WYSIWYG )
return FCK_TRISTATE_DISABLED ;
return ( FCKUndo.CheckRedoState() ? FCK_TRISTATE_OFF : FCK_TRISTATE_DISABLED ) ;
}
// ### Page Break
var FCKPageBreakCommand = function()
{
this.Name = 'PageBreak' ;
}
FCKPageBreakCommand.prototype.Execute = function()
{
// Take an undo snapshot before changing the document
FCKUndo.SaveUndoStep() ;
// var e = FCK.EditorDocument.createElement( 'CENTER' ) ;
// e.style.pageBreakAfter = 'always' ;
// Tidy was removing the empty CENTER tags, so the following solution has
// been found. It also validates correctly as XHTML 1.0 Strict.
var e = FCK.EditorDocument.createElement( 'DIV' ) ;
e.style.pageBreakAfter = 'always' ;
e.innerHTML = '<span style="DISPLAY:none"> </span>' ;
var oFakeImage = FCKDocumentProcessor_CreateFakeImage( 'FCK__PageBreak', e ) ;
var oRange = new FCKDomRange( FCK.EditorWindow ) ;
oRange.MoveToSelection() ;
var oSplitInfo = oRange.SplitBlock() ;
oRange.InsertNode( oFakeImage ) ;
FCK.Events.FireEvent( 'OnSelectionChange' ) ;
}
FCKPageBreakCommand.prototype.GetState = function()
{
if ( FCK.EditMode != FCK_EDITMODE_WYSIWYG )
return FCK_TRISTATE_DISABLED ;
return 0 ; // FCK_TRISTATE_OFF
}
// FCKUnlinkCommand - by Johnny Egeland (johnny@coretrek.com)
var FCKUnlinkCommand = function()
{
this.Name = 'Unlink' ;
}
FCKUnlinkCommand.prototype.Execute = function()
{
// Take an undo snapshot before changing the document
FCKUndo.SaveUndoStep() ;
if ( FCKBrowserInfo.IsGeckoLike )
{
var oLink = FCK.Selection.MoveToAncestorNode( 'A' ) ;
// The unlink command can generate a span in Firefox, so let's do it our way. See #430
if ( oLink )
FCKTools.RemoveOuterTags( oLink ) ;
return ;
}
FCK.ExecuteNamedCommand( this.Name ) ;
}
FCKUnlinkCommand.prototype.GetState = function()
{
if ( FCK.EditMode != FCK_EDITMODE_WYSIWYG )
return FCK_TRISTATE_DISABLED ;
var state = FCK.GetNamedCommandState( this.Name ) ;
// Check that it isn't an anchor
if ( state == FCK_TRISTATE_OFF && FCK.EditMode == FCK_EDITMODE_WYSIWYG )
{
var oLink = FCKSelection.MoveToAncestorNode( 'A' ) ;
var bIsAnchor = ( oLink && oLink.name.length > 0 && oLink.href.length == 0 ) ;
if ( bIsAnchor )
state = FCK_TRISTATE_DISABLED ;
}
return state ;
}
FCKVisitLinkCommand = function()
{
this.Name = 'VisitLink';
}
FCKVisitLinkCommand.prototype =
{
GetState : function()
{
if ( FCK.EditMode != FCK_EDITMODE_WYSIWYG )
return FCK_TRISTATE_DISABLED ;
var state = FCK.GetNamedCommandState( 'Unlink' ) ;
if ( state == FCK_TRISTATE_OFF )
{
var el = FCKSelection.MoveToAncestorNode( 'A' ) ;
if ( !el.href )
state = FCK_TRISTATE_DISABLED ;
}
return state ;
},
Execute : function()
{
var el = FCKSelection.MoveToAncestorNode( 'A' ) ;
var url = el.getAttribute( '_fcksavedurl' ) || el.getAttribute( 'href', 2 ) ;
// Check if it's a full URL.
// If not full URL, we'll need to apply the BaseHref setting.
if ( ! /:\/\//.test( url ) )
{
var baseHref = FCKConfig.BaseHref ;
var parentWindow = FCK.GetInstanceObject( 'parent' ) ;
if ( !baseHref )
{
baseHref = parentWindow.document.location.href ;
baseHref = baseHref.substring( 0, baseHref.lastIndexOf( '/' ) + 1 ) ;
}
if ( /^\//.test( url ) )
{
try
{
baseHref = baseHref.match( /^.*:\/\/+[^\/]+/ )[0] ;
}
catch ( e )
{
baseHref = parentWindow.document.location.protocol + '://' + parentWindow.parent.document.location.host ;
}
}
url = baseHref + url ;
}
if ( !window.open( url, '_blank' ) )
alert( FCKLang.VisitLinkBlocked ) ;
}
} ;
// FCKSelectAllCommand
var FCKSelectAllCommand = function()
{
this.Name = 'SelectAll' ;
}
FCKSelectAllCommand.prototype.Execute = function()
{
if ( FCK.EditMode == FCK_EDITMODE_WYSIWYG )
{
FCK.ExecuteNamedCommand( 'SelectAll' ) ;
}
else
{
// Select the contents of the textarea
var textarea = FCK.EditingArea.Textarea ;
if ( FCKBrowserInfo.IsIE )
{
textarea.createTextRange().execCommand( 'SelectAll' ) ;
}
else
{
textarea.selectionStart = 0 ;
textarea.selectionEnd = textarea.value.length ;
}
textarea.focus() ;
}
}
FCKSelectAllCommand.prototype.GetState = function()
{
if ( FCK.EditMode != FCK_EDITMODE_WYSIWYG )
return FCK_TRISTATE_DISABLED ;
return FCK_TRISTATE_OFF ;
}
// FCKPasteCommand
var FCKPasteCommand = function()
{
this.Name = 'Paste' ;
}
FCKPasteCommand.prototype =
{
Execute : function()
{
if ( FCKBrowserInfo.IsIE )
FCK.Paste() ;
else
FCK.ExecuteNamedCommand( 'Paste' ) ;
},
GetState : function()
{
if ( FCK.EditMode != FCK_EDITMODE_WYSIWYG )
return FCK_TRISTATE_DISABLED ;
return FCK.GetNamedCommandState( 'Paste' ) ;
}
} ;
// FCKRuleCommand
var FCKRuleCommand = function()
{
this.Name = 'Rule' ;
}
FCKRuleCommand.prototype =
{
Execute : function()
{
FCKUndo.SaveUndoStep() ;
FCK.InsertElement( 'hr' ) ;
},
GetState : function()
{
if ( FCK.EditMode != FCK_EDITMODE_WYSIWYG )
return FCK_TRISTATE_DISABLED ;
return FCK.GetNamedCommandState( 'InsertHorizontalRule' ) ;
}
} ;
// FCKCutCopyCommand
var FCKCutCopyCommand = function( isCut )
{
this.Name = isCut ? 'Cut' : 'Copy' ;
}
FCKCutCopyCommand.prototype =
{
Execute : function()
{
var enabled = false ;
if ( FCKBrowserInfo.IsIE )
{
// The following seems to be the only reliable way to detect that
// cut/copy is enabled in IE. It will fire the oncut/oncopy event
// only if the security settings enabled the command to execute.
var onEvent = function()
{
enabled = true ;
} ;
var eventName = 'on' + this.Name.toLowerCase() ;
FCK.EditorDocument.body.attachEvent( eventName, onEvent ) ;
FCK.ExecuteNamedCommand( this.Name ) ;
FCK.EditorDocument.body.detachEvent( eventName, onEvent ) ;
}
else
{
try
{
// Other browsers throw an error if the command is disabled.
FCK.ExecuteNamedCommand( this.Name ) ;
enabled = true ;
}
catch(e){}
}
if ( !enabled )
alert( FCKLang[ 'PasteError' + this.Name ] ) ;
},
GetState : function()
{
// Strangely, the Cut command happens to have the correct states for
// both Copy and Cut in all browsers.
return FCK.EditMode != FCK_EDITMODE_WYSIWYG ?
FCK_TRISTATE_DISABLED :
FCK.GetNamedCommandState( 'Cut' ) ;
}
};
var FCKAnchorDeleteCommand = function()
{
this.Name = 'AnchorDelete' ;
}
FCKAnchorDeleteCommand.prototype =
{
Execute : function()
{
if (FCK.Selection.GetType() == 'Control')
{
FCK.Selection.Delete();
}
else
{
var oFakeImage = FCK.Selection.GetSelectedElement() ;
if ( oFakeImage )
{
if ( oFakeImage.tagName == 'IMG' && oFakeImage.getAttribute('_fckanchor') )
oAnchor = FCK.GetRealElement( oFakeImage ) ;
else
oFakeImage = null ;
}
//Search for a real anchor
if ( !oFakeImage )
{
oAnchor = FCK.Selection.MoveToAncestorNode( 'A' ) ;
if ( oAnchor )
FCK.Selection.SelectNode( oAnchor ) ;
}
// If it's also a link, then just remove the name and exit
if ( oAnchor.href.length != 0 )
{
oAnchor.removeAttribute( 'name' ) ;
// Remove temporary class for IE
if ( FCKBrowserInfo.IsIE )
oAnchor.className = oAnchor.className.replace( FCKRegexLib.FCK_Class, '' ) ;
return ;
}
// We need to remove the anchor
// If we got a fake image, then just remove it and we're done
if ( oFakeImage )
{
oFakeImage.parentNode.removeChild( oFakeImage ) ;
return ;
}
// Empty anchor, so just remove it
if ( oAnchor.innerHTML.length == 0 )
{
oAnchor.parentNode.removeChild( oAnchor ) ;
return ;
}
// Anchor with content, leave the content
FCKTools.RemoveOuterTags( oAnchor ) ;
}
if ( FCKBrowserInfo.IsGecko )
FCK.Selection.Collapse( true ) ;
},
GetState : function()
{
if ( FCK.EditMode != FCK_EDITMODE_WYSIWYG )
return FCK_TRISTATE_DISABLED ;
return FCK.GetNamedCommandState( 'Unlink') ;
}
};
var FCKDeleteDivCommand = function()
{
}
FCKDeleteDivCommand.prototype =
{
GetState : function()
{
if ( FCK.EditMode != FCK_EDITMODE_WYSIWYG )
return FCK_TRISTATE_DISABLED ;
var node = FCKSelection.GetParentElement() ;
var path = new FCKElementPath( node ) ;
return path.BlockLimit && path.BlockLimit.nodeName.IEquals( 'div' ) ? FCK_TRISTATE_OFF : FCK_TRISTATE_DISABLED ;
},
Execute : function()
{
// Create an undo snapshot before doing anything.
FCKUndo.SaveUndoStep() ;
// Find out the nodes to delete.
var nodes = FCKDomTools.GetSelectedDivContainers() ;
// Remember the current selection position.
var range = new FCKDomRange( FCK.EditorWindow ) ;
range.MoveToSelection() ;
var bookmark = range.CreateBookmark() ;
// Delete the container DIV node.
for ( var i = 0 ; i < nodes.length ; i++)
FCKDomTools.RemoveNode( nodes[i], true ) ;
// Restore selection.
range.MoveToBookmark( bookmark ) ;
range.Select() ;
}
} ;
// FCKRuleCommand
var FCKNbsp = function()
{
this.Name = 'Non Breaking Space' ;
}
FCKNbsp.prototype =
{
Execute : function()
{
FCK.InsertHtml( ' ' ) ;
},
GetState : function()
{
return ( FCK.EditMode != FCK_EDITMODE_WYSIWYG ? FCK_TRISTATE_DISABLED : FCK_TRISTATE_OFF ) ;
}
} ;
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* Implementation for the "Insert/Remove Ordered/Unordered List" commands.
*/
var FCKListCommand = function( name, tagName )
{
this.Name = name ;
this.TagName = tagName ;
}
FCKListCommand.prototype =
{
GetState : function()
{
// Disabled if not WYSIWYG.
if ( FCK.EditMode != FCK_EDITMODE_WYSIWYG || ! FCK.EditorWindow )
return FCK_TRISTATE_DISABLED ;
// We'll use the style system's convention to determine list state here...
// If the starting block is a descendant of an <ol> or <ul> node, then we're in a list.
var startContainer = FCKSelection.GetBoundaryParentElement( true ) ;
var listNode = startContainer ;
while ( listNode )
{
if ( listNode.nodeName.IEquals( [ 'ul', 'ol' ] ) )
break ;
listNode = listNode.parentNode ;
}
if ( listNode && listNode.nodeName.IEquals( this.TagName ) )
return FCK_TRISTATE_ON ;
else
return FCK_TRISTATE_OFF ;
},
Execute : function()
{
FCKUndo.SaveUndoStep() ;
var doc = FCK.EditorDocument ;
var range = new FCKDomRange( FCK.EditorWindow ) ;
range.MoveToSelection() ;
var state = this.GetState() ;
// Midas lists rule #1 says we can create a list even in an empty document.
// But FCKDomRangeIterator wouldn't run if the document is really empty.
// So create a paragraph if the document is empty and we're going to create a list.
if ( state == FCK_TRISTATE_OFF )
{
FCKDomTools.TrimNode( doc.body ) ;
if ( ! doc.body.firstChild )
{
var paragraph = doc.createElement( 'p' ) ;
doc.body.appendChild( paragraph ) ;
range.MoveToNodeContents( paragraph ) ;
}
}
var bookmark = range.CreateBookmark() ;
// Group the blocks up because there are many cases where multiple lists have to be created,
// or multiple lists have to be cancelled.
var listGroups = [] ;
var markerObj = {} ;
var iterator = new FCKDomRangeIterator( range ) ;
var block ;
iterator.ForceBrBreak = ( state == FCK_TRISTATE_OFF ) ;
var nextRangeExists = true ;
var rangeQueue = null ;
while ( nextRangeExists )
{
while ( ( block = iterator.GetNextParagraph() ) )
{
var path = new FCKElementPath( block ) ;
var listNode = null ;
var processedFlag = false ;
var blockLimit = path.BlockLimit ;
// First, try to group by a list ancestor.
for ( var i = path.Elements.length - 1 ; i >= 0 ; i-- )
{
var el = path.Elements[i] ;
if ( el.nodeName.IEquals( ['ol', 'ul'] ) )
{
// If we've encountered a list inside a block limit
// The last group object of the block limit element should
// no longer be valid. Since paragraphs after the list
// should belong to a different group of paragraphs before
// the list. (Bug #1309)
if ( blockLimit._FCK_ListGroupObject )
blockLimit._FCK_ListGroupObject = null ;
var groupObj = el._FCK_ListGroupObject ;
if ( groupObj )
groupObj.contents.push( block ) ;
else
{
groupObj = { 'root' : el, 'contents' : [ block ] } ;
listGroups.push( groupObj ) ;
FCKDomTools.SetElementMarker( markerObj, el, '_FCK_ListGroupObject', groupObj ) ;
}
processedFlag = true ;
break ;
}
}
if ( processedFlag )
continue ;
// No list ancestor? Group by block limit.
var root = blockLimit ;
if ( root._FCK_ListGroupObject )
root._FCK_ListGroupObject.contents.push( block ) ;
else
{
var groupObj = { 'root' : root, 'contents' : [ block ] } ;
FCKDomTools.SetElementMarker( markerObj, root, '_FCK_ListGroupObject', groupObj ) ;
listGroups.push( groupObj ) ;
}
}
if ( FCKBrowserInfo.IsIE )
nextRangeExists = false ;
else
{
if ( rangeQueue == null )
{
rangeQueue = [] ;
var selectionObject = FCKSelection.GetSelection() ;
if ( selectionObject && listGroups.length == 0 )
rangeQueue.push( selectionObject.getRangeAt( 0 ) ) ;
for ( var i = 1 ; selectionObject && i < selectionObject.rangeCount ; i++ )
rangeQueue.push( selectionObject.getRangeAt( i ) ) ;
}
if ( rangeQueue.length < 1 )
nextRangeExists = false ;
else
{
var internalRange = FCKW3CRange.CreateFromRange( doc, rangeQueue.shift() ) ;
range._Range = internalRange ;
range._UpdateElementInfo() ;
if ( range.StartNode.nodeName.IEquals( 'td' ) )
range.SetStart( range.StartNode, 1 ) ;
if ( range.EndNode.nodeName.IEquals( 'td' ) )
range.SetEnd( range.EndNode, 2 ) ;
iterator = new FCKDomRangeIterator( range ) ;
iterator.ForceBrBreak = ( state == FCK_TRISTATE_OFF ) ;
}
}
}
// Now we have two kinds of list groups, groups rooted at a list, and groups rooted at a block limit element.
// We either have to build lists or remove lists, for removing a list does not makes sense when we are looking
// at the group that's not rooted at lists. So we have three cases to handle.
var listsCreated = [] ;
while ( listGroups.length > 0 )
{
var groupObj = listGroups.shift() ;
if ( state == FCK_TRISTATE_OFF )
{
if ( groupObj.root.nodeName.IEquals( ['ul', 'ol'] ) )
this._ChangeListType( groupObj, markerObj, listsCreated ) ;
else
this._CreateList( groupObj, listsCreated ) ;
}
else if ( state == FCK_TRISTATE_ON && groupObj.root.nodeName.IEquals( ['ul', 'ol'] ) )
this._RemoveList( groupObj, markerObj ) ;
}
// For all new lists created, merge adjacent, same type lists.
for ( var i = 0 ; i < listsCreated.length ; i++ )
{
var listNode = listsCreated[i] ;
var stopFlag = false ;
var currentNode = listNode ;
while ( ! stopFlag )
{
currentNode = currentNode.nextSibling ;
if ( currentNode && currentNode.nodeType == 3 && currentNode.nodeValue.search( /^[\n\r\t ]*$/ ) == 0 )
continue ;
stopFlag = true ;
}
if ( currentNode && currentNode.nodeName.IEquals( this.TagName ) )
{
currentNode.parentNode.removeChild( currentNode ) ;
while ( currentNode.firstChild )
listNode.appendChild( currentNode.removeChild( currentNode.firstChild ) ) ;
}
stopFlag = false ;
currentNode = listNode ;
while ( ! stopFlag )
{
currentNode = currentNode.previousSibling ;
if ( currentNode && currentNode.nodeType == 3 && currentNode.nodeValue.search( /^[\n\r\t ]*$/ ) == 0 )
continue ;
stopFlag = true ;
}
if ( currentNode && currentNode.nodeName.IEquals( this.TagName ) )
{
currentNode.parentNode.removeChild( currentNode ) ;
while ( currentNode.lastChild )
listNode.insertBefore( currentNode.removeChild( currentNode.lastChild ),
listNode.firstChild ) ;
}
}
// Clean up, restore selection and update toolbar button states.
FCKDomTools.ClearAllMarkers( markerObj ) ;
range.MoveToBookmark( bookmark ) ;
range.Select() ;
FCK.Focus() ;
FCK.Events.FireEvent( 'OnSelectionChange' ) ;
},
_ChangeListType : function( groupObj, markerObj, listsCreated )
{
// This case is easy...
// 1. Convert the whole list into a one-dimensional array.
// 2. Change the list type by modifying the array.
// 3. Recreate the whole list by converting the array to a list.
// 4. Replace the original list with the recreated list.
var listArray = FCKDomTools.ListToArray( groupObj.root, markerObj ) ;
var selectedListItems = [] ;
for ( var i = 0 ; i < groupObj.contents.length ; i++ )
{
var itemNode = groupObj.contents[i] ;
itemNode = FCKTools.GetElementAscensor( itemNode, 'li' ) ;
if ( ! itemNode || itemNode._FCK_ListItem_Processed )
continue ;
selectedListItems.push( itemNode ) ;
FCKDomTools.SetElementMarker( markerObj, itemNode, '_FCK_ListItem_Processed', true ) ;
}
var fakeParent = FCKTools.GetElementDocument( groupObj.root ).createElement( this.TagName ) ;
for ( var i = 0 ; i < selectedListItems.length ; i++ )
{
var listIndex = selectedListItems[i]._FCK_ListArray_Index ;
listArray[listIndex].parent = fakeParent ;
}
var newList = FCKDomTools.ArrayToList( listArray, markerObj ) ;
for ( var i = 0 ; i < newList.listNode.childNodes.length ; i++ )
{
if ( newList.listNode.childNodes[i].nodeName.IEquals( this.TagName ) )
listsCreated.push( newList.listNode.childNodes[i] ) ;
}
groupObj.root.parentNode.replaceChild( newList.listNode, groupObj.root ) ;
},
_CreateList : function( groupObj, listsCreated )
{
var contents = groupObj.contents ;
var doc = FCKTools.GetElementDocument( groupObj.root ) ;
var listContents = [] ;
// It is possible to have the contents returned by DomRangeIterator to be the same as the root.
// e.g. when we're running into table cells.
// In such a case, enclose the childNodes of contents[0] into a <div>.
if ( contents.length == 1 && contents[0] == groupObj.root )
{
var divBlock = doc.createElement( 'div' );
while ( contents[0].firstChild )
divBlock.appendChild( contents[0].removeChild( contents[0].firstChild ) ) ;
contents[0].appendChild( divBlock ) ;
contents[0] = divBlock ;
}
// Calculate the common parent node of all content blocks.
var commonParent = groupObj.contents[0].parentNode ;
for ( var i = 0 ; i < contents.length ; i++ )
commonParent = FCKDomTools.GetCommonParents( commonParent, contents[i].parentNode ).pop() ;
// We want to insert things that are in the same tree level only, so calculate the contents again
// by expanding the selected blocks to the same tree level.
for ( var i = 0 ; i < contents.length ; i++ )
{
var contentNode = contents[i] ;
while ( contentNode.parentNode )
{
if ( contentNode.parentNode == commonParent )
{
listContents.push( contentNode ) ;
break ;
}
contentNode = contentNode.parentNode ;
}
}
if ( listContents.length < 1 )
return ;
// Insert the list to the DOM tree.
var insertAnchor = listContents[listContents.length - 1].nextSibling ;
var listNode = doc.createElement( this.TagName ) ;
listsCreated.push( listNode ) ;
while ( listContents.length )
{
var contentBlock = listContents.shift() ;
var docFrag = doc.createDocumentFragment() ;
while ( contentBlock.firstChild )
docFrag.appendChild( contentBlock.removeChild( contentBlock.firstChild ) ) ;
contentBlock.parentNode.removeChild( contentBlock ) ;
var listItem = doc.createElement( 'li' ) ;
listItem.appendChild( docFrag ) ;
listNode.appendChild( listItem ) ;
}
commonParent.insertBefore( listNode, insertAnchor ) ;
},
_RemoveList : function( groupObj, markerObj )
{
// This is very much like the change list type operation.
// Except that we're changing the selected items' indent to -1 in the list array.
var listArray = FCKDomTools.ListToArray( groupObj.root, markerObj ) ;
var selectedListItems = [] ;
for ( var i = 0 ; i < groupObj.contents.length ; i++ )
{
var itemNode = groupObj.contents[i] ;
itemNode = FCKTools.GetElementAscensor( itemNode, 'li' ) ;
if ( ! itemNode || itemNode._FCK_ListItem_Processed )
continue ;
selectedListItems.push( itemNode ) ;
FCKDomTools.SetElementMarker( markerObj, itemNode, '_FCK_ListItem_Processed', true ) ;
}
var lastListIndex = null ;
for ( var i = 0 ; i < selectedListItems.length ; i++ )
{
var listIndex = selectedListItems[i]._FCK_ListArray_Index ;
listArray[listIndex].indent = -1 ;
lastListIndex = listIndex ;
}
// After cutting parts of the list out with indent=-1, we still have to maintain the array list
// model's nextItem.indent <= currentItem.indent + 1 invariant. Otherwise the array model of the
// list cannot be converted back to a real DOM list.
for ( var i = lastListIndex + 1; i < listArray.length ; i++ )
{
if ( listArray[i].indent > listArray[i-1].indent + 1 )
{
var indentOffset = listArray[i-1].indent + 1 - listArray[i].indent ;
var oldIndent = listArray[i].indent ;
while ( listArray[i] && listArray[i].indent >= oldIndent)
{
listArray[i].indent += indentOffset ;
i++ ;
}
i-- ;
}
}
var newList = FCKDomTools.ArrayToList( listArray, markerObj ) ;
// If groupObj.root is the last element in its parent, or its nextSibling is a <br>, then we should
// not add a <br> after the final item. So, check for the cases and trim the <br>.
if ( groupObj.root.nextSibling == null || groupObj.root.nextSibling.nodeName.IEquals( 'br' ) )
{
if ( newList.listNode.lastChild.nodeName.IEquals( 'br' ) )
newList.listNode.removeChild( newList.listNode.lastChild ) ;
}
groupObj.root.parentNode.replaceChild( newList.listNode, groupObj.root ) ;
}
};
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* FCKCoreStyleCommand Class: controls the execution of a core style. Core
* styles are usually represented as buttons in the toolbar., like Bold and
* Italic.
*/
var FCKCoreStyleCommand = function( coreStyleName )
{
this.Name = 'CoreStyle' ;
this.StyleName = '_FCK_' + coreStyleName ;
this.IsActive = false ;
FCKStyles.AttachStyleStateChange( this.StyleName, this._OnStyleStateChange, this ) ;
}
FCKCoreStyleCommand.prototype =
{
Execute : function()
{
FCKUndo.SaveUndoStep() ;
if ( this.IsActive )
FCKStyles.RemoveStyle( this.StyleName ) ;
else
FCKStyles.ApplyStyle( this.StyleName ) ;
FCK.Focus() ;
FCK.Events.FireEvent( 'OnSelectionChange' ) ;
},
GetState : function()
{
if ( FCK.EditMode != FCK_EDITMODE_WYSIWYG )
return FCK_TRISTATE_DISABLED ;
return this.IsActive ? FCK_TRISTATE_ON : FCK_TRISTATE_OFF ;
},
_OnStyleStateChange : function( styleName, isActive )
{
this.IsActive = isActive ;
}
};
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* FCKPastePlainTextCommand Class: represents the
* "Paste as Plain Text" command.
*/
var FCKTableCommand = function( command )
{
this.Name = command ;
}
FCKTableCommand.prototype.Execute = function()
{
FCKUndo.SaveUndoStep() ;
if ( ! FCKBrowserInfo.IsGecko )
{
switch ( this.Name )
{
case 'TableMergeRight' :
return FCKTableHandler.MergeRight() ;
case 'TableMergeDown' :
return FCKTableHandler.MergeDown() ;
}
}
switch ( this.Name )
{
case 'TableInsertRowAfter' :
return FCKTableHandler.InsertRow( false ) ;
case 'TableInsertRowBefore' :
return FCKTableHandler.InsertRow( true ) ;
case 'TableDeleteRows' :
return FCKTableHandler.DeleteRows() ;
case 'TableInsertColumnAfter' :
return FCKTableHandler.InsertColumn( false ) ;
case 'TableInsertColumnBefore' :
return FCKTableHandler.InsertColumn( true ) ;
case 'TableDeleteColumns' :
return FCKTableHandler.DeleteColumns() ;
case 'TableInsertCellAfter' :
return FCKTableHandler.InsertCell( null, false ) ;
case 'TableInsertCellBefore' :
return FCKTableHandler.InsertCell( null, true ) ;
case 'TableDeleteCells' :
return FCKTableHandler.DeleteCells() ;
case 'TableMergeCells' :
return FCKTableHandler.MergeCells() ;
case 'TableHorizontalSplitCell' :
return FCKTableHandler.HorizontalSplitCell() ;
case 'TableVerticalSplitCell' :
return FCKTableHandler.VerticalSplitCell() ;
case 'TableDelete' :
return FCKTableHandler.DeleteTable() ;
default :
return alert( FCKLang.UnknownCommand.replace( /%1/g, this.Name ) ) ;
}
}
FCKTableCommand.prototype.GetState = function()
{
if ( FCK.EditorDocument != null && FCKSelection.HasAncestorNode( 'TABLE' ) )
{
switch ( this.Name )
{
case 'TableHorizontalSplitCell' :
case 'TableVerticalSplitCell' :
if ( FCKTableHandler.GetSelectedCells().length == 1 )
return FCK_TRISTATE_OFF ;
else
return FCK_TRISTATE_DISABLED ;
case 'TableMergeCells' :
if ( FCKTableHandler.CheckIsSelectionRectangular()
&& FCKTableHandler.GetSelectedCells().length > 1 )
return FCK_TRISTATE_OFF ;
else
return FCK_TRISTATE_DISABLED ;
case 'TableMergeRight' :
return FCKTableHandler.GetMergeRightTarget() ? FCK_TRISTATE_OFF : FCK_TRISTATE_DISABLED ;
case 'TableMergeDown' :
return FCKTableHandler.GetMergeDownTarget() ? FCK_TRISTATE_OFF : FCK_TRISTATE_DISABLED ;
default :
return FCK_TRISTATE_OFF ;
}
}
else
return FCK_TRISTATE_DISABLED;
}
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* FCKTextColorCommand Class: represents the text color comand. It shows the
* color selection panel.
*/
// FCKTextColorCommand Constructor
// type: can be 'ForeColor' or 'BackColor'.
var FCKTextColorCommand = function( type )
{
this.Name = type == 'ForeColor' ? 'TextColor' : 'BGColor' ;
this.Type = type ;
var oWindow ;
if ( FCKBrowserInfo.IsIE )
oWindow = window ;
else if ( FCK.ToolbarSet._IFrame )
oWindow = FCKTools.GetElementWindow( FCK.ToolbarSet._IFrame ) ;
else
oWindow = window.parent ;
this._Panel = new FCKPanel( oWindow ) ;
this._Panel.AppendStyleSheet( FCKConfig.SkinEditorCSS ) ;
this._Panel.MainNode.className = 'FCK_Panel' ;
this._CreatePanelBody( this._Panel.Document, this._Panel.MainNode ) ;
FCK.ToolbarSet.ToolbarItems.GetItem( this.Name ).RegisterPanel( this._Panel ) ;
FCKTools.DisableSelection( this._Panel.Document.body ) ;
}
FCKTextColorCommand.prototype.Execute = function( panelX, panelY, relElement )
{
// Show the Color Panel at the desired position.
this._Panel.Show( panelX, panelY, relElement ) ;
}
FCKTextColorCommand.prototype.SetColor = function( color )
{
FCKUndo.SaveUndoStep() ;
var style = FCKStyles.GetStyle( '_FCK_' +
( this.Type == 'ForeColor' ? 'Color' : 'BackColor' ) ) ;
if ( !color || color.length == 0 )
FCK.Styles.RemoveStyle( style ) ;
else
{
style.SetVariable( 'Color', color ) ;
FCKStyles.ApplyStyle( style ) ;
}
FCKUndo.SaveUndoStep() ;
FCK.Focus() ;
FCK.Events.FireEvent( 'OnSelectionChange' ) ;
}
FCKTextColorCommand.prototype.GetState = function()
{
if ( FCK.EditMode != FCK_EDITMODE_WYSIWYG )
return FCK_TRISTATE_DISABLED ;
return FCK_TRISTATE_OFF ;
}
function FCKTextColorCommand_OnMouseOver()
{
this.className = 'ColorSelected' ;
}
function FCKTextColorCommand_OnMouseOut()
{
this.className = 'ColorDeselected' ;
}
function FCKTextColorCommand_OnClick( ev, command, color )
{
this.className = 'ColorDeselected' ;
command.SetColor( color ) ;
command._Panel.Hide() ;
}
function FCKTextColorCommand_AutoOnClick( ev, command )
{
this.className = 'ColorDeselected' ;
command.SetColor( '' ) ;
command._Panel.Hide() ;
}
function FCKTextColorCommand_MoreOnClick( ev, command )
{
this.className = 'ColorDeselected' ;
command._Panel.Hide() ;
FCKDialog.OpenDialog( 'FCKDialog_Color', FCKLang.DlgColorTitle, 'dialog/fck_colorselector.html', 410, 320,
FCKTools.Bind( command, command.SetColor ) ) ;
}
FCKTextColorCommand.prototype._CreatePanelBody = function( targetDocument, targetDiv )
{
function CreateSelectionDiv()
{
var oDiv = targetDocument.createElement( "DIV" ) ;
oDiv.className = 'ColorDeselected' ;
FCKTools.AddEventListenerEx( oDiv, 'mouseover', FCKTextColorCommand_OnMouseOver ) ;
FCKTools.AddEventListenerEx( oDiv, 'mouseout', FCKTextColorCommand_OnMouseOut ) ;
return oDiv ;
}
// Create the Table that will hold all colors.
var oTable = targetDiv.appendChild( targetDocument.createElement( "TABLE" ) ) ;
oTable.className = 'ForceBaseFont' ; // Firefox 1.5 Bug.
oTable.style.tableLayout = 'fixed' ;
oTable.cellPadding = 0 ;
oTable.cellSpacing = 0 ;
oTable.border = 0 ;
oTable.width = 150 ;
var oCell = oTable.insertRow(-1).insertCell(-1) ;
oCell.colSpan = 8 ;
// Create the Button for the "Automatic" color selection.
var oDiv = oCell.appendChild( CreateSelectionDiv() ) ;
oDiv.innerHTML =
'<table cellspacing="0" cellpadding="0" width="100%" border="0">\
<tr>\
<td><div class="ColorBoxBorder"><div class="ColorBox" style="background-color: #000000"></div></div></td>\
<td nowrap width="100%" align="center">' + FCKLang.ColorAutomatic + '</td>\
</tr>\
</table>' ;
FCKTools.AddEventListenerEx( oDiv, 'click', FCKTextColorCommand_AutoOnClick, this ) ;
// Dirty hack for Opera, Safari and Firefox 3.
if ( !FCKBrowserInfo.IsIE )
oDiv.style.width = '96%' ;
// Create an array of colors based on the configuration file.
var aColors = FCKConfig.FontColors.toString().split(',') ;
// Create the colors table based on the array.
var iCounter = 0 ;
while ( iCounter < aColors.length )
{
var oRow = oTable.insertRow(-1) ;
for ( var i = 0 ; i < 8 ; i++, iCounter++ )
{
// The div will be created even if no more colors are available.
// Extra divs will be hidden later in the code. (#1597)
if ( iCounter < aColors.length )
{
var colorParts = aColors[iCounter].split('/') ;
var colorValue = '#' + colorParts[0] ;
var colorName = colorParts[1] || colorValue ;
}
oDiv = oRow.insertCell(-1).appendChild( CreateSelectionDiv() ) ;
oDiv.innerHTML = '<div class="ColorBoxBorder"><div class="ColorBox" style="background-color: ' + colorValue + '"></div></div>' ;
if ( iCounter >= aColors.length )
oDiv.style.visibility = 'hidden' ;
else
FCKTools.AddEventListenerEx( oDiv, 'click', FCKTextColorCommand_OnClick, [ this, colorName ] ) ;
}
}
// Create the Row and the Cell for the "More Colors..." button.
if ( FCKConfig.EnableMoreFontColors )
{
oCell = oTable.insertRow(-1).insertCell(-1) ;
oCell.colSpan = 8 ;
oDiv = oCell.appendChild( CreateSelectionDiv() ) ;
oDiv.innerHTML = '<table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td nowrap align="center">' + FCKLang.ColorMoreColors + '</td></tr></table>' ;
FCKTools.AddEventListenerEx( oDiv, 'click', FCKTextColorCommand_MoreOnClick, this ) ;
}
// Dirty hack for Opera, Safari and Firefox 3.
if ( !FCKBrowserInfo.IsIE )
oDiv.style.width = '96%' ;
}
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* FCKPasteWordCommand Class: represents the "Paste from Word" command.
*/
var FCKPasteWordCommand = function()
{
this.Name = 'PasteWord' ;
}
FCKPasteWordCommand.prototype.Execute = function()
{
FCK.PasteFromWord() ;
}
FCKPasteWordCommand.prototype.GetState = function()
{
if ( FCK.EditMode != FCK_EDITMODE_WYSIWYG || FCKConfig.ForcePasteAsPlainText )
return FCK_TRISTATE_DISABLED ;
else
return FCK.GetNamedCommandState( 'Paste' ) ;
}
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* Defines the FCKLanguageManager object that is used for language
* operations.
*/
var FCKLanguageManager = FCK.Language =
{
AvailableLanguages :
{
af : 'Afrikaans',
ar : 'Arabic',
bg : 'Bulgarian',
bn : 'Bengali/Bangla',
bs : 'Bosnian',
ca : 'Catalan',
cs : 'Czech',
da : 'Danish',
de : 'German',
el : 'Greek',
en : 'English',
'en-au' : 'English (Australia)',
'en-ca' : 'English (Canadian)',
'en-uk' : 'English (United Kingdom)',
eo : 'Esperanto',
es : 'Spanish',
et : 'Estonian',
eu : 'Basque',
fa : 'Persian',
fi : 'Finnish',
fo : 'Faroese',
fr : 'French',
'fr-ca' : 'French (Canada)',
gl : 'Galician',
gu : 'Gujarati',
he : 'Hebrew',
hi : 'Hindi',
hr : 'Croatian',
hu : 'Hungarian',
it : 'Italian',
ja : 'Japanese',
km : 'Khmer',
ko : 'Korean',
lt : 'Lithuanian',
lv : 'Latvian',
mn : 'Mongolian',
ms : 'Malay',
nb : 'Norwegian Bokmal',
nl : 'Dutch',
no : 'Norwegian',
pl : 'Polish',
pt : 'Portuguese (Portugal)',
'pt-br' : 'Portuguese (Brazil)',
ro : 'Romanian',
ru : 'Russian',
sk : 'Slovak',
sl : 'Slovenian',
sr : 'Serbian (Cyrillic)',
'sr-latn' : 'Serbian (Latin)',
sv : 'Swedish',
th : 'Thai',
tr : 'Turkish',
uk : 'Ukrainian',
vi : 'Vietnamese',
zh : 'Chinese Traditional',
'zh-cn' : 'Chinese Simplified'
},
GetActiveLanguage : function()
{
if ( FCKConfig.AutoDetectLanguage )
{
var sUserLang ;
// IE accepts "navigator.userLanguage" while Gecko "navigator.language".
if ( navigator.userLanguage )
sUserLang = navigator.userLanguage.toLowerCase() ;
else if ( navigator.language )
sUserLang = navigator.language.toLowerCase() ;
else
{
// Firefox 1.0 PR has a bug: it doens't support the "language" property.
return FCKConfig.DefaultLanguage ;
}
// Some language codes are set in 5 characters,
// like "pt-br" for Brazilian Portuguese.
if ( sUserLang.length >= 5 )
{
sUserLang = sUserLang.substr(0,5) ;
if ( this.AvailableLanguages[sUserLang] ) return sUserLang ;
}
// If the user's browser is set to, for example, "pt-br" but only the
// "pt" language file is available then get that file.
if ( sUserLang.length >= 2 )
{
sUserLang = sUserLang.substr(0,2) ;
if ( this.AvailableLanguages[sUserLang] ) return sUserLang ;
}
}
return this.DefaultLanguage ;
},
TranslateElements : function( targetDocument, tag, propertyToSet, encode )
{
var e = targetDocument.getElementsByTagName(tag) ;
var sKey, s ;
for ( var i = 0 ; i < e.length ; i++ )
{
// The extra () is to avoid a warning with strict error checking. This is ok.
if ( (sKey = e[i].getAttribute( 'fckLang' )) )
{
// The extra () is to avoid a warning with strict error checking. This is ok.
if ( (s = FCKLang[ sKey ]) )
{
if ( encode )
s = FCKTools.HTMLEncode( s ) ;
e[i][ propertyToSet ] = s ;
}
}
}
},
TranslatePage : function( targetDocument )
{
this.TranslateElements( targetDocument, 'INPUT', 'value' ) ;
this.TranslateElements( targetDocument, 'SPAN', 'innerHTML' ) ;
this.TranslateElements( targetDocument, 'LABEL', 'innerHTML' ) ;
this.TranslateElements( targetDocument, 'OPTION', 'innerHTML', true ) ;
this.TranslateElements( targetDocument, 'LEGEND', 'innerHTML' ) ;
},
Initialize : function()
{
if ( this.AvailableLanguages[ FCKConfig.DefaultLanguage ] )
this.DefaultLanguage = FCKConfig.DefaultLanguage ;
else
this.DefaultLanguage = 'en' ;
this.ActiveLanguage = new Object() ;
this.ActiveLanguage.Code = this.GetActiveLanguage() ;
this.ActiveLanguage.Name = this.AvailableLanguages[ this.ActiveLanguage.Code ] ;
}
} ;
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* Advanced document processors.
*/
var FCKDocumentProcessor = new Object() ;
FCKDocumentProcessor._Items = new Array() ;
FCKDocumentProcessor.AppendNew = function()
{
var oNewItem = new Object() ;
this._Items.AddItem( oNewItem ) ;
return oNewItem ;
}
FCKDocumentProcessor.Process = function( document )
{
var bIsDirty = FCK.IsDirty() ;
var oProcessor, i = 0 ;
while( ( oProcessor = this._Items[i++] ) )
oProcessor.ProcessDocument( document ) ;
if ( !bIsDirty )
FCK.ResetIsDirty() ;
}
var FCKDocumentProcessor_CreateFakeImage = function( fakeClass, realElement )
{
var oImg = FCKTools.GetElementDocument( realElement ).createElement( 'IMG' ) ;
oImg.className = fakeClass ;
oImg.src = FCKConfig.BasePath + 'images/spacer.gif' ;
oImg.setAttribute( '_fckfakelement', 'true', 0 ) ;
oImg.setAttribute( '_fckrealelement', FCKTempBin.AddElement( realElement ), 0 ) ;
return oImg ;
}
// Link Anchors
if ( FCKBrowserInfo.IsIE || FCKBrowserInfo.IsOpera )
{
var FCKAnchorsProcessor = FCKDocumentProcessor.AppendNew() ;
FCKAnchorsProcessor.ProcessDocument = function( document )
{
var aLinks = document.getElementsByTagName( 'A' ) ;
var oLink ;
var i = aLinks.length - 1 ;
while ( i >= 0 && ( oLink = aLinks[i--] ) )
{
// If it is anchor. Doesn't matter if it's also a link (even better: we show that it's both a link and an anchor)
if ( oLink.name.length > 0 )
{
//if the anchor has some content then we just add a temporary class
if ( oLink.innerHTML !== '' )
{
if ( FCKBrowserInfo.IsIE )
oLink.className += ' FCK__AnchorC' ;
}
else
{
var oImg = FCKDocumentProcessor_CreateFakeImage( 'FCK__Anchor', oLink.cloneNode(true) ) ;
oImg.setAttribute( '_fckanchor', 'true', 0 ) ;
oLink.parentNode.insertBefore( oImg, oLink ) ;
oLink.parentNode.removeChild( oLink ) ;
}
}
}
}
}
// Page Breaks
var FCKPageBreaksProcessor = FCKDocumentProcessor.AppendNew() ;
FCKPageBreaksProcessor.ProcessDocument = function( document )
{
var aDIVs = document.getElementsByTagName( 'DIV' ) ;
var eDIV ;
var i = aDIVs.length - 1 ;
while ( i >= 0 && ( eDIV = aDIVs[i--] ) )
{
if ( eDIV.style.pageBreakAfter == 'always' && eDIV.childNodes.length == 1 && eDIV.childNodes[0].style && eDIV.childNodes[0].style.display == 'none' )
{
var oFakeImage = FCKDocumentProcessor_CreateFakeImage( 'FCK__PageBreak', eDIV.cloneNode(true) ) ;
eDIV.parentNode.insertBefore( oFakeImage, eDIV ) ;
eDIV.parentNode.removeChild( eDIV ) ;
}
}
/*
var aCenters = document.getElementsByTagName( 'CENTER' ) ;
var oCenter ;
var i = aCenters.length - 1 ;
while ( i >= 0 && ( oCenter = aCenters[i--] ) )
{
if ( oCenter.style.pageBreakAfter == 'always' && oCenter.innerHTML.Trim().length == 0 )
{
var oFakeImage = FCKDocumentProcessor_CreateFakeImage( 'FCK__PageBreak', oCenter.cloneNode(true) ) ;
oCenter.parentNode.insertBefore( oFakeImage, oCenter ) ;
oCenter.parentNode.removeChild( oCenter ) ;
}
}
*/
}
// EMBED and OBJECT tags.
FCKEmbedAndObjectProcessor = (function()
{
var customProcessors = [] ;
var processElement = function( el )
{
var clone = el.cloneNode( true ) ;
var replaceElement ;
var fakeImg = replaceElement = FCKDocumentProcessor_CreateFakeImage( 'FCK__UnknownObject', clone ) ;
FCKEmbedAndObjectProcessor.RefreshView( fakeImg, el ) ;
for ( var i = 0 ; i < customProcessors.length ; i++ )
replaceElement = customProcessors[i]( el, replaceElement ) || replaceElement ;
if ( replaceElement != fakeImg )
FCKTempBin.RemoveElement( fakeImg.getAttribute( '_fckrealelement' ) ) ;
el.parentNode.replaceChild( replaceElement, el ) ;
}
var processElementsByName = function( elementName, doc )
{
var aObjects = doc.getElementsByTagName( elementName );
for ( var i = aObjects.length - 1 ; i >= 0 ; i-- )
processElement( aObjects[i] ) ;
}
var processObjectAndEmbed = function( doc )
{
processElementsByName( 'object', doc );
processElementsByName( 'embed', doc );
}
return FCKTools.Merge( FCKDocumentProcessor.AppendNew(),
{
ProcessDocument : function( doc )
{
// Firefox 3 would sometimes throw an unknown exception while accessing EMBEDs and OBJECTs
// without the setTimeout().
if ( FCKBrowserInfo.IsGecko )
FCKTools.RunFunction( processObjectAndEmbed, this, [ doc ] ) ;
else
processObjectAndEmbed( doc ) ;
},
RefreshView : function( placeHolder, original )
{
if ( original.getAttribute( 'width' ) > 0 )
placeHolder.style.width = FCKTools.ConvertHtmlSizeToStyle( original.getAttribute( 'width' ) ) ;
if ( original.getAttribute( 'height' ) > 0 )
placeHolder.style.height = FCKTools.ConvertHtmlSizeToStyle( original.getAttribute( 'height' ) ) ;
},
AddCustomHandler : function( func )
{
customProcessors.push( func ) ;
}
} ) ;
} )() ;
FCK.GetRealElement = function( fakeElement )
{
var e = FCKTempBin.Elements[ fakeElement.getAttribute('_fckrealelement') ] ;
if ( fakeElement.getAttribute('_fckflash') )
{
if ( fakeElement.style.width.length > 0 )
e.width = FCKTools.ConvertStyleSizeToHtml( fakeElement.style.width ) ;
if ( fakeElement.style.height.length > 0 )
e.height = FCKTools.ConvertStyleSizeToHtml( fakeElement.style.height ) ;
}
return e ;
}
// HR Processor.
// This is a IE only (tricky) thing. We protect all HR tags before loading them
// (see FCK.ProtectTags). Here we put the HRs back.
if ( FCKBrowserInfo.IsIE )
{
FCKDocumentProcessor.AppendNew().ProcessDocument = function( document )
{
var aHRs = document.getElementsByTagName( 'HR' ) ;
var eHR ;
var i = aHRs.length - 1 ;
while ( i >= 0 && ( eHR = aHRs[i--] ) )
{
// Create the replacement HR.
var newHR = document.createElement( 'hr' ) ;
newHR.mergeAttributes( eHR, true ) ;
// We must insert the new one after it. insertBefore will not work in all cases.
FCKDomTools.InsertAfterNode( eHR, newHR ) ;
eHR.parentNode.removeChild( eHR ) ;
}
}
}
// INPUT:hidden Processor.
FCKDocumentProcessor.AppendNew().ProcessDocument = function( document )
{
var aInputs = document.getElementsByTagName( 'INPUT' ) ;
var oInput ;
var i = aInputs.length - 1 ;
while ( i >= 0 && ( oInput = aInputs[i--] ) )
{
if ( oInput.type == 'hidden' )
{
var oImg = FCKDocumentProcessor_CreateFakeImage( 'FCK__InputHidden', oInput.cloneNode(true) ) ;
oImg.setAttribute( '_fckinputhidden', 'true', 0 ) ;
oInput.parentNode.insertBefore( oImg, oInput ) ;
oInput.parentNode.removeChild( oInput ) ;
}
}
}
// Flash handler.
FCKEmbedAndObjectProcessor.AddCustomHandler( function( el, fakeImg )
{
if ( ! ( el.nodeName.IEquals( 'embed' ) && ( el.type == 'application/x-shockwave-flash' || /\.swf($|#|\?)/i.test( el.src ) ) ) )
return ;
fakeImg.className = 'FCK__Flash' ;
fakeImg.setAttribute( '_fckflash', 'true', 0 );
} ) ;
// Buggy <span class="Apple-style-span"> tags added by Safari.
if ( FCKBrowserInfo.IsSafari )
{
FCKDocumentProcessor.AppendNew().ProcessDocument = function( doc )
{
var spans = doc.getElementsByClassName ?
doc.getElementsByClassName( 'Apple-style-span' ) :
Array.prototype.filter.call(
doc.getElementsByTagName( 'span' ),
function( item ){ return item.className == 'Apple-style-span' ; }
) ;
for ( var i = spans.length - 1 ; i >= 0 ; i-- )
FCKDomTools.RemoveNode( spans[i], true ) ;
}
}
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* Creation and initialization of the "FCK" object. This is the main object
* that represents an editor instance.
*/
// FCK represents the active editor instance.
var FCK =
{
Name : FCKURLParams[ 'InstanceName' ],
Status : FCK_STATUS_NOTLOADED,
EditMode : FCK_EDITMODE_WYSIWYG,
Toolbar : null,
HasFocus : false,
DataProcessor : new FCKDataProcessor(),
GetInstanceObject : (function()
{
var w = window ;
return function( name )
{
return w[name] ;
}
})(),
AttachToOnSelectionChange : function( functionPointer )
{
this.Events.AttachEvent( 'OnSelectionChange', functionPointer ) ;
},
GetLinkedFieldValue : function()
{
return this.LinkedField.value ;
},
GetParentForm : function()
{
return this.LinkedField.form ;
} ,
// # START : IsDirty implementation
StartupValue : '',
IsDirty : function()
{
if ( this.EditMode == FCK_EDITMODE_SOURCE )
return ( this.StartupValue != this.EditingArea.Textarea.value ) ;
else
{
// It can happen switching between design and source mode in Gecko
if ( ! this.EditorDocument )
return false ;
return ( this.StartupValue != this.EditorDocument.body.innerHTML ) ;
}
},
ResetIsDirty : function()
{
if ( this.EditMode == FCK_EDITMODE_SOURCE )
this.StartupValue = this.EditingArea.Textarea.value ;
else if ( this.EditorDocument.body )
this.StartupValue = this.EditorDocument.body.innerHTML ;
},
// # END : IsDirty implementation
StartEditor : function()
{
this.TempBaseTag = FCKConfig.BaseHref.length > 0 ? '<base href="' + FCKConfig.BaseHref + '" _fcktemp="true"></base>' : '' ;
// Setup the keystroke handler.
var oKeystrokeHandler = FCK.KeystrokeHandler = new FCKKeystrokeHandler() ;
oKeystrokeHandler.OnKeystroke = _FCK_KeystrokeHandler_OnKeystroke ;
// Set the config keystrokes.
oKeystrokeHandler.SetKeystrokes( FCKConfig.Keystrokes ) ;
// In IE7, if the editor tries to access the clipboard by code, a dialog is
// shown to the user asking if the application is allowed to access or not.
// Due to the IE implementation of it, the KeystrokeHandler will not work
//well in this case, so we must leave the pasting keys to have their default behavior.
if ( FCKBrowserInfo.IsIE7 )
{
if ( ( CTRL + 86 /*V*/ ) in oKeystrokeHandler.Keystrokes )
oKeystrokeHandler.SetKeystrokes( [ CTRL + 86, true ] ) ;
if ( ( SHIFT + 45 /*INS*/ ) in oKeystrokeHandler.Keystrokes )
oKeystrokeHandler.SetKeystrokes( [ SHIFT + 45, true ] ) ;
}
// Retain default behavior for Ctrl-Backspace. (Bug #362)
oKeystrokeHandler.SetKeystrokes( [ CTRL + 8, true ] ) ;
this.EditingArea = new FCKEditingArea( document.getElementById( 'xEditingArea' ) ) ;
this.EditingArea.FFSpellChecker = FCKConfig.FirefoxSpellChecker ;
// Set the editor's startup contents.
this.SetData( this.GetLinkedFieldValue(), true ) ;
// Tab key handling for source mode.
FCKTools.AddEventListener( document, "keydown", this._TabKeyHandler ) ;
// Add selection change listeners. They must be attached only once.
this.AttachToOnSelectionChange( _FCK_PaddingNodeListener ) ;
if ( FCKBrowserInfo.IsGecko )
this.AttachToOnSelectionChange( this._ExecCheckEmptyBlock ) ;
},
Focus : function()
{
FCK.EditingArea.Focus() ;
},
SetStatus : function( newStatus )
{
this.Status = newStatus ;
if ( newStatus == FCK_STATUS_ACTIVE )
{
FCKFocusManager.AddWindow( window, true ) ;
if ( FCKBrowserInfo.IsIE )
FCKFocusManager.AddWindow( window.frameElement, true ) ;
// Force the focus in the editor.
if ( FCKConfig.StartupFocus )
FCK.Focus() ;
}
this.Events.FireEvent( 'OnStatusChange', newStatus ) ;
},
// Fixes the body by moving all inline and text nodes to appropriate block
// elements.
FixBody : function()
{
var sBlockTag = FCKConfig.EnterMode ;
// In 'br' mode, no fix must be done.
if ( sBlockTag != 'p' && sBlockTag != 'div' )
return ;
var oDocument = this.EditorDocument ;
if ( !oDocument )
return ;
var oBody = oDocument.body ;
if ( !oBody )
return ;
FCKDomTools.TrimNode( oBody ) ;
var oNode = oBody.firstChild ;
var oNewBlock ;
while ( oNode )
{
var bMoveNode = false ;
switch ( oNode.nodeType )
{
// Element Node.
case 1 :
var nodeName = oNode.nodeName.toLowerCase() ;
if ( !FCKListsLib.BlockElements[ nodeName ] &&
nodeName != 'li' &&
!oNode.getAttribute('_fckfakelement') &&
oNode.getAttribute('_moz_dirty') == null )
bMoveNode = true ;
break ;
// Text Node.
case 3 :
// Ignore space only or empty text.
if ( oNewBlock || oNode.nodeValue.Trim().length > 0 )
bMoveNode = true ;
break;
// Comment Node
case 8 :
if ( oNewBlock )
bMoveNode = true ;
break;
}
if ( bMoveNode )
{
var oParent = oNode.parentNode ;
if ( !oNewBlock )
oNewBlock = oParent.insertBefore( oDocument.createElement( sBlockTag ), oNode ) ;
oNewBlock.appendChild( oParent.removeChild( oNode ) ) ;
oNode = oNewBlock.nextSibling ;
}
else
{
if ( oNewBlock )
{
FCKDomTools.TrimNode( oNewBlock ) ;
oNewBlock = null ;
}
oNode = oNode.nextSibling ;
}
}
if ( oNewBlock )
FCKDomTools.TrimNode( oNewBlock ) ;
},
GetData : function( format )
{
// We assume that if the user is in source editing, the editor value must
// represent the exact contents of the source, as the user wanted it to be.
if ( FCK.EditMode == FCK_EDITMODE_SOURCE )
return FCK.EditingArea.Textarea.value ;
this.FixBody() ;
var oDoc = FCK.EditorDocument ;
if ( !oDoc )
return null ;
var isFullPage = FCKConfig.FullPage ;
// Call the Data Processor to generate the output data.
var data = FCK.DataProcessor.ConvertToDataFormat(
isFullPage ? oDoc.documentElement : oDoc.body,
!isFullPage,
FCKConfig.IgnoreEmptyParagraphValue,
format ) ;
// Restore protected attributes.
data = FCK.ProtectEventsRestore( data ) ;
if ( FCKBrowserInfo.IsIE )
data = data.replace( FCKRegexLib.ToReplace, '$1' ) ;
if ( isFullPage )
{
if ( FCK.DocTypeDeclaration && FCK.DocTypeDeclaration.length > 0 )
data = FCK.DocTypeDeclaration + '\n' + data ;
if ( FCK.XmlDeclaration && FCK.XmlDeclaration.length > 0 )
data = FCK.XmlDeclaration + '\n' + data ;
}
return FCKConfig.ProtectedSource.Revert( data ) ;
},
UpdateLinkedField : function()
{
var value = FCK.GetXHTML( FCKConfig.FormatOutput ) ;
if ( FCKConfig.HtmlEncodeOutput )
value = FCKTools.HTMLEncode( value ) ;
FCK.LinkedField.value = value ;
FCK.Events.FireEvent( 'OnAfterLinkedFieldUpdate' ) ;
},
RegisteredDoubleClickHandlers : new Object(),
OnDoubleClick : function( element )
{
var oCalls = FCK.RegisteredDoubleClickHandlers[ element.tagName.toUpperCase() ] ;
if ( oCalls )
{
for ( var i = 0 ; i < oCalls.length ; i++ )
oCalls[ i ]( element ) ;
}
// Generic handler for any element
oCalls = FCK.RegisteredDoubleClickHandlers[ '*' ] ;
if ( oCalls )
{
for ( var i = 0 ; i < oCalls.length ; i++ )
oCalls[ i ]( element ) ;
}
},
// Register objects that can handle double click operations.
RegisterDoubleClickHandler : function( handlerFunction, tag )
{
var nodeName = tag || '*' ;
nodeName = nodeName.toUpperCase() ;
var aTargets ;
if ( !( aTargets = FCK.RegisteredDoubleClickHandlers[ nodeName ] ) )
FCK.RegisteredDoubleClickHandlers[ nodeName ] = [ handlerFunction ] ;
else
{
// Check that the event handler isn't already registered with the same listener
// It doesn't detect function pointers belonging to an object (at least in Gecko)
if ( aTargets.IndexOf( handlerFunction ) == -1 )
aTargets.push( handlerFunction ) ;
}
},
OnAfterSetHTML : function()
{
FCKDocumentProcessor.Process( FCK.EditorDocument ) ;
FCKUndo.SaveUndoStep() ;
FCK.Events.FireEvent( 'OnSelectionChange' ) ;
FCK.Events.FireEvent( 'OnAfterSetHTML' ) ;
},
// Saves URLs on links and images on special attributes, so they don't change when
// moving around.
ProtectUrls : function( html )
{
// <A> href
html = html.replace( FCKRegexLib.ProtectUrlsA , '$& _fcksavedurl=$1' ) ;
// <IMG> src
html = html.replace( FCKRegexLib.ProtectUrlsImg , '$& _fcksavedurl=$1' ) ;
// <AREA> href
html = html.replace( FCKRegexLib.ProtectUrlsArea , '$& _fcksavedurl=$1' ) ;
return html ;
},
// Saves event attributes (like onclick) so they don't get executed while
// editing.
ProtectEvents : function( html )
{
return html.replace( FCKRegexLib.TagsWithEvent, _FCK_ProtectEvents_ReplaceTags ) ;
},
ProtectEventsRestore : function( html )
{
return html.replace( FCKRegexLib.ProtectedEvents, _FCK_ProtectEvents_RestoreEvents ) ;
},
ProtectTags : function( html )
{
var sTags = FCKConfig.ProtectedTags ;
// IE doesn't support <abbr> and it breaks it. Let's protect it.
if ( FCKBrowserInfo.IsIE )
sTags += sTags.length > 0 ? '|ABBR|XML|EMBED|OBJECT' : 'ABBR|XML|EMBED|OBJECT' ;
var oRegex ;
if ( sTags.length > 0 )
{
oRegex = new RegExp( '<(' + sTags + ')(?!\w|:)', 'gi' ) ;
html = html.replace( oRegex, '<FCK:$1' ) ;
oRegex = new RegExp( '<\/(' + sTags + ')>', 'gi' ) ;
html = html.replace( oRegex, '<\/FCK:$1>' ) ;
}
// Protect some empty elements. We must do it separately because the
// original tag may not contain the closing slash, like <hr>:
// - <meta> tags get executed, so if you have a redirect meta, the
// content will move to the target page.
// - <hr> may destroy the document structure if not well
// positioned. The trick is protect it here and restore them in
// the FCKDocumentProcessor.
sTags = 'META' ;
if ( FCKBrowserInfo.IsIE )
sTags += '|HR' ;
oRegex = new RegExp( '<((' + sTags + ')(?=\\s|>|/)[\\s\\S]*?)/?>', 'gi' ) ;
html = html.replace( oRegex, '<FCK:$1 />' ) ;
return html ;
},
SetData : function( data, resetIsDirty )
{
this.EditingArea.Mode = FCK.EditMode ;
// If there was an onSelectionChange listener in IE we must remove it to avoid crashes #1498
if ( FCKBrowserInfo.IsIE && FCK.EditorDocument )
{
FCK.EditorDocument.detachEvent("onselectionchange", Doc_OnSelectionChange ) ;
}
FCKTempBin.Reset();
if ( FCK.EditMode == FCK_EDITMODE_WYSIWYG )
{
// Save the resetIsDirty for later use (async)
this._ForceResetIsDirty = ( resetIsDirty === true ) ;
// Protect parts of the code that must remain untouched (and invisible)
// during editing.
data = FCKConfig.ProtectedSource.Protect( data ) ;
// Call the Data Processor to transform the data.
data = FCK.DataProcessor.ConvertToHtml( data ) ;
// Fix for invalid self-closing tags (see #152).
data = data.replace( FCKRegexLib.InvalidSelfCloseTags, '$1></$2>' ) ;
// Protect event attributes (they could get fired in the editing area).
data = FCK.ProtectEvents( data ) ;
// Protect some things from the browser itself.
data = FCK.ProtectUrls( data ) ;
data = FCK.ProtectTags( data ) ;
// Insert the base tag (FCKConfig.BaseHref), if not exists in the source.
// The base must be the first tag in the HEAD, to get relative
// links on styles, for example.
if ( FCK.TempBaseTag.length > 0 && !FCKRegexLib.HasBaseTag.test( data ) )
data = data.replace( FCKRegexLib.HeadOpener, '$&' + FCK.TempBaseTag ) ;
// Build the HTML for the additional things we need on <head>.
var sHeadExtra = '' ;
if ( !FCKConfig.FullPage )
sHeadExtra += _FCK_GetEditorAreaStyleTags() ;
if ( FCKBrowserInfo.IsIE )
sHeadExtra += FCK._GetBehaviorsStyle() ;
else if ( FCKConfig.ShowBorders )
sHeadExtra += FCKTools.GetStyleHtml( FCK_ShowTableBordersCSS, true ) ;
sHeadExtra += FCKTools.GetStyleHtml( FCK_InternalCSS, true ) ;
// Attention: do not change it before testing it well (sample07)!
// This is tricky... if the head ends with <meta ... content type>,
// Firefox will break. But, it works if we place our extra stuff as
// the last elements in the HEAD.
data = data.replace( FCKRegexLib.HeadCloser, sHeadExtra + '$&' ) ;
// Load the HTML in the editing area.
this.EditingArea.OnLoad = _FCK_EditingArea_OnLoad ;
this.EditingArea.Start( data ) ;
}
else
{
// Remove the references to the following elements, as the editing area
// IFRAME will be removed.
FCK.EditorWindow = null ;
FCK.EditorDocument = null ;
FCKDomTools.PaddingNode = null ;
this.EditingArea.OnLoad = null ;
this.EditingArea.Start( data ) ;
// Enables the context menu in the textarea.
this.EditingArea.Textarea._FCKShowContextMenu = true ;
// Removes the enter key handler.
FCK.EnterKeyHandler = null ;
if ( resetIsDirty )
this.ResetIsDirty() ;
// Listen for keystroke events.
FCK.KeystrokeHandler.AttachToElement( this.EditingArea.Textarea ) ;
this.EditingArea.Textarea.focus() ;
FCK.Events.FireEvent( 'OnAfterSetHTML' ) ;
}
if ( FCKBrowserInfo.IsGecko )
window.onresize() ;
},
// This collection is used by the browser specific implementations to tell
// which named commands must be handled separately.
RedirectNamedCommands : new Object(),
ExecuteNamedCommand : function( commandName, commandParameter, noRedirect, noSaveUndo )
{
if ( !noSaveUndo )
FCKUndo.SaveUndoStep() ;
if ( !noRedirect && FCK.RedirectNamedCommands[ commandName ] != null )
FCK.ExecuteRedirectedNamedCommand( commandName, commandParameter ) ;
else
{
FCK.Focus() ;
FCK.EditorDocument.execCommand( commandName, false, commandParameter ) ;
FCK.Events.FireEvent( 'OnSelectionChange' ) ;
}
if ( !noSaveUndo )
FCKUndo.SaveUndoStep() ;
},
GetNamedCommandState : function( commandName )
{
try
{
// Bug #50 : Safari never returns positive state for the Paste command, override that.
if ( FCKBrowserInfo.IsSafari && FCK.EditorWindow && commandName.IEquals( 'Paste' ) )
return FCK_TRISTATE_OFF ;
if ( !FCK.EditorDocument.queryCommandEnabled( commandName ) )
return FCK_TRISTATE_DISABLED ;
else
{
return FCK.EditorDocument.queryCommandState( commandName ) ? FCK_TRISTATE_ON : FCK_TRISTATE_OFF ;
}
}
catch ( e )
{
return FCK_TRISTATE_OFF ;
}
},
GetNamedCommandValue : function( commandName )
{
var sValue = '' ;
var eState = FCK.GetNamedCommandState( commandName ) ;
if ( eState == FCK_TRISTATE_DISABLED )
return null ;
try
{
sValue = this.EditorDocument.queryCommandValue( commandName ) ;
}
catch(e) {}
return sValue ? sValue : '' ;
},
Paste : function( _callListenersOnly )
{
// First call 'OnPaste' listeners.
if ( FCK.Status != FCK_STATUS_COMPLETE || !FCK.Events.FireEvent( 'OnPaste' ) )
return false ;
// Then call the default implementation.
return _callListenersOnly || FCK._ExecPaste() ;
},
PasteFromWord : function()
{
FCKDialog.OpenDialog( 'FCKDialog_Paste', FCKLang.PasteFromWord, 'dialog/fck_paste.html', 400, 330, 'Word' ) ;
},
Preview : function()
{
var sHTML ;
if ( FCKConfig.FullPage )
{
if ( FCK.TempBaseTag.length > 0 )
sHTML = FCK.TempBaseTag + FCK.GetXHTML() ;
else
sHTML = FCK.GetXHTML() ;
}
else
{
sHTML =
FCKConfig.DocType +
'<html dir="' + FCKConfig.ContentLangDirection + '">' +
'<head>' +
FCK.TempBaseTag +
'<title>' + FCKLang.Preview + '</title>' +
_FCK_GetEditorAreaStyleTags() +
'</head><body' + FCKConfig.GetBodyAttributes() + '>' +
FCK.GetXHTML() +
'</body></html>' ;
}
var iWidth = FCKConfig.ScreenWidth * 0.8 ;
var iHeight = FCKConfig.ScreenHeight * 0.7 ;
var iLeft = ( FCKConfig.ScreenWidth - iWidth ) / 2 ;
var sOpenUrl = '' ;
if ( FCK_IS_CUSTOM_DOMAIN && FCKBrowserInfo.IsIE)
{
window._FCKHtmlToLoad = sHTML ;
sOpenUrl = 'javascript:void( (function(){' +
'document.open() ;' +
'document.domain="' + document.domain + '" ;' +
'document.write( window.opener._FCKHtmlToLoad );' +
'document.close() ;' +
'window.opener._FCKHtmlToLoad = null ;' +
'})() )' ;
}
var oWindow = window.open( sOpenUrl, null, 'toolbar=yes,location=no,status=yes,menubar=yes,scrollbars=yes,resizable=yes,width=' + iWidth + ',height=' + iHeight + ',left=' + iLeft ) ;
if ( !FCK_IS_CUSTOM_DOMAIN || !FCKBrowserInfo.IsIE)
{
oWindow.document.write( sHTML );
oWindow.document.close();
}
},
SwitchEditMode : function( noUndo )
{
var bIsWysiwyg = ( FCK.EditMode == FCK_EDITMODE_WYSIWYG ) ;
// Save the current IsDirty state, so we may restore it after the switch.
var bIsDirty = FCK.IsDirty() ;
var sHtml ;
// Update the HTML in the view output to show, also update
// FCKTempBin for IE to avoid #2263.
if ( bIsWysiwyg )
{
FCKCommands.GetCommand( 'ShowBlocks' ).SaveState() ;
if ( !noUndo && FCKBrowserInfo.IsIE )
FCKUndo.SaveUndoStep() ;
sHtml = FCK.GetXHTML( FCKConfig.FormatSource ) ;
if ( FCKBrowserInfo.IsIE )
FCKTempBin.ToHtml() ;
if ( sHtml == null )
return false ;
}
else
sHtml = this.EditingArea.Textarea.value ;
FCK.EditMode = bIsWysiwyg ? FCK_EDITMODE_SOURCE : FCK_EDITMODE_WYSIWYG ;
FCK.SetData( sHtml, !bIsDirty ) ;
// Set the Focus.
FCK.Focus() ;
// Update the toolbar (Running it directly causes IE to fail).
FCKTools.RunFunction( FCK.ToolbarSet.RefreshModeState, FCK.ToolbarSet ) ;
return true ;
},
InsertElement : function( element )
{
// The parameter may be a string (element name), so transform it in an element.
if ( typeof element == 'string' )
element = this.EditorDocument.createElement( element ) ;
var elementName = element.nodeName.toLowerCase() ;
FCKSelection.Restore() ;
// Create a range for the selection. V3 will have a new selection
// object that may internally supply this feature.
var range = new FCKDomRange( this.EditorWindow ) ;
// Move to the selection and delete it.
range.MoveToSelection() ;
range.DeleteContents() ;
if ( FCKListsLib.BlockElements[ elementName ] != null )
{
if ( range.StartBlock )
{
if ( range.CheckStartOfBlock() )
range.MoveToPosition( range.StartBlock, 3 ) ;
else if ( range.CheckEndOfBlock() )
range.MoveToPosition( range.StartBlock, 4 ) ;
else
range.SplitBlock() ;
}
range.InsertNode( element ) ;
var next = FCKDomTools.GetNextSourceElement( element, false, null, [ 'hr','br','param','img','area','input' ], true ) ;
// Be sure that we have something after the new element, so we can move the cursor there.
if ( !next && FCKConfig.EnterMode != 'br')
{
next = this.EditorDocument.body.appendChild( this.EditorDocument.createElement( FCKConfig.EnterMode ) ) ;
if ( FCKBrowserInfo.IsGeckoLike )
FCKTools.AppendBogusBr( next ) ;
}
if ( FCKListsLib.EmptyElements[ elementName ] == null )
range.MoveToElementEditStart( element ) ;
else if ( next )
range.MoveToElementEditStart( next ) ;
else
range.MoveToPosition( element, 4 ) ;
if ( FCKBrowserInfo.IsGeckoLike )
{
if ( next )
FCKDomTools.ScrollIntoView( next, false );
FCKDomTools.ScrollIntoView( element, false );
}
}
else
{
// Insert the node.
range.InsertNode( element ) ;
// Move the selection right after the new element.
// DISCUSSION: Should we select the element instead?
range.SetStart( element, 4 ) ;
range.SetEnd( element, 4 ) ;
}
range.Select() ;
range.Release() ;
// REMOVE IT: The focus should not really be set here. It is up to the
// calling code to reset the focus if needed.
this.Focus() ;
return element ;
},
_InsertBlockElement : function( blockElement )
{
},
_IsFunctionKey : function( keyCode )
{
// keys that are captured but do not change editor contents
if ( keyCode >= 16 && keyCode <= 20 )
// shift, ctrl, alt, pause, capslock
return true ;
if ( keyCode == 27 || ( keyCode >= 33 && keyCode <= 40 ) )
// esc, page up, page down, end, home, left, up, right, down
return true ;
if ( keyCode == 45 )
// insert, no effect on FCKeditor, yet
return true ;
return false ;
},
_KeyDownListener : function( evt )
{
if (! evt)
evt = FCK.EditorWindow.event ;
if ( FCK.EditorWindow )
{
if ( !FCK._IsFunctionKey(evt.keyCode) // do not capture function key presses, like arrow keys or shift/alt/ctrl
&& !(evt.ctrlKey || evt.metaKey) // do not capture Ctrl hotkeys, as they have their snapshot capture logic
&& !(evt.keyCode == 46) ) // do not capture Del, it has its own capture logic in fckenterkey.js
FCK._KeyDownUndo() ;
}
return true ;
},
_KeyDownUndo : function()
{
if ( !FCKUndo.Typing )
{
FCKUndo.SaveUndoStep() ;
FCKUndo.Typing = true ;
FCK.Events.FireEvent( "OnSelectionChange" ) ;
}
FCKUndo.TypesCount++ ;
FCKUndo.Changed = 1 ;
if ( FCKUndo.TypesCount > FCKUndo.MaxTypes )
{
FCKUndo.TypesCount = 0 ;
FCKUndo.SaveUndoStep() ;
}
},
_TabKeyHandler : function( evt )
{
if ( ! evt )
evt = window.event ;
var keystrokeValue = evt.keyCode ;
// Pressing <Tab> in source mode should produce a tab space in the text area, not
// changing the focus to something else.
if ( keystrokeValue == 9 && FCK.EditMode != FCK_EDITMODE_WYSIWYG )
{
if ( FCKBrowserInfo.IsIE )
{
var range = document.selection.createRange() ;
if ( range.parentElement() != FCK.EditingArea.Textarea )
return true ;
range.text = '\t' ;
range.select() ;
}
else
{
var a = [] ;
var el = FCK.EditingArea.Textarea ;
var selStart = el.selectionStart ;
var selEnd = el.selectionEnd ;
a.push( el.value.substr(0, selStart ) ) ;
a.push( '\t' ) ;
a.push( el.value.substr( selEnd ) ) ;
el.value = a.join( '' ) ;
el.setSelectionRange( selStart + 1, selStart + 1 ) ;
}
if ( evt.preventDefault )
return evt.preventDefault() ;
return evt.returnValue = false ;
}
return true ;
}
} ;
FCK.Events = new FCKEvents( FCK ) ;
// DEPRECATED in favor or "GetData".
FCK.GetHTML = FCK.GetXHTML = FCK.GetData ;
// DEPRECATED in favor of "SetData".
FCK.SetHTML = FCK.SetData ;
// InsertElementAndGetIt and CreateElement are Deprecated : returns the same value as InsertElement.
FCK.InsertElementAndGetIt = FCK.CreateElement = FCK.InsertElement ;
// Replace all events attributes (like onclick).
function _FCK_ProtectEvents_ReplaceTags( tagMatch )
{
return tagMatch.replace( FCKRegexLib.EventAttributes, _FCK_ProtectEvents_ReplaceEvents ) ;
}
// Replace an event attribute with its respective __fckprotectedatt attribute.
// The original event markup will be encoded and saved as the value of the new
// attribute.
function _FCK_ProtectEvents_ReplaceEvents( eventMatch, attName )
{
return ' ' + attName + '_fckprotectedatt="' + encodeURIComponent( eventMatch ) + '"' ;
}
function _FCK_ProtectEvents_RestoreEvents( match, encodedOriginal )
{
return decodeURIComponent( encodedOriginal ) ;
}
function _FCK_MouseEventsListener( evt )
{
if ( ! evt )
evt = window.event ;
if ( evt.type == 'mousedown' )
FCK.MouseDownFlag = true ;
else if ( evt.type == 'mouseup' )
FCK.MouseDownFlag = false ;
else if ( evt.type == 'mousemove' )
FCK.Events.FireEvent( 'OnMouseMove', evt ) ;
}
function _FCK_PaddingNodeListener()
{
if ( FCKConfig.EnterMode.IEquals( 'br' ) )
return ;
FCKDomTools.EnforcePaddingNode( FCK.EditorDocument, FCKConfig.EnterMode ) ;
if ( ! FCKBrowserInfo.IsIE && FCKDomTools.PaddingNode )
{
// Prevent the caret from going between the body and the padding node in Firefox.
// i.e. <body>|<p></p></body>
var sel = FCKSelection.GetSelection() ;
if ( sel && sel.rangeCount == 1 )
{
var range = sel.getRangeAt( 0 ) ;
if ( range.collapsed && range.startContainer == FCK.EditorDocument.body && range.startOffset == 0 )
{
range.selectNodeContents( FCKDomTools.PaddingNode ) ;
range.collapse( true ) ;
sel.removeAllRanges() ;
sel.addRange( range ) ;
}
}
}
else if ( FCKDomTools.PaddingNode )
{
// Prevent the caret from going into an empty body but not into the padding node in IE.
// i.e. <body><p></p>|</body>
var parentElement = FCKSelection.GetParentElement() ;
var paddingNode = FCKDomTools.PaddingNode ;
if ( parentElement && parentElement.nodeName.IEquals( 'body' ) )
{
if ( FCK.EditorDocument.body.childNodes.length == 1
&& FCK.EditorDocument.body.firstChild == paddingNode )
{
/*
* Bug #1764: Don't move the selection if the
* current selection isn't in the editor
* document.
*/
if ( FCKSelection._GetSelectionDocument( FCK.EditorDocument.selection ) != FCK.EditorDocument )
return ;
var range = FCK.EditorDocument.body.createTextRange() ;
var clearContents = false ;
if ( !paddingNode.childNodes.firstChild )
{
paddingNode.appendChild( FCKTools.GetElementDocument( paddingNode ).createTextNode( '\ufeff' ) ) ;
clearContents = true ;
}
range.moveToElementText( paddingNode ) ;
range.select() ;
if ( clearContents )
range.pasteHTML( '' ) ;
}
}
}
}
function _FCK_EditingArea_OnLoad()
{
// Get the editor's window and document (DOM)
FCK.EditorWindow = FCK.EditingArea.Window ;
FCK.EditorDocument = FCK.EditingArea.Document ;
if ( FCKBrowserInfo.IsIE )
FCKTempBin.ToElements() ;
FCK.InitializeBehaviors() ;
// Listen for mousedown and mouseup events for tracking drag and drops.
FCK.MouseDownFlag = false ;
FCKTools.AddEventListener( FCK.EditorDocument, 'mousemove', _FCK_MouseEventsListener ) ;
FCKTools.AddEventListener( FCK.EditorDocument, 'mousedown', _FCK_MouseEventsListener ) ;
FCKTools.AddEventListener( FCK.EditorDocument, 'mouseup', _FCK_MouseEventsListener ) ;
// Most of the CTRL key combos do not work under Safari for onkeydown and onkeypress (See #1119)
// But we can use the keyup event to override some of these...
if ( FCKBrowserInfo.IsSafari )
{
var undoFunc = function( evt )
{
if ( ! ( evt.ctrlKey || evt.metaKey ) )
return ;
if ( FCK.EditMode != FCK_EDITMODE_WYSIWYG )
return ;
switch ( evt.keyCode )
{
case 89:
FCKUndo.Redo() ;
break ;
case 90:
FCKUndo.Undo() ;
break ;
}
}
FCKTools.AddEventListener( FCK.EditorDocument, 'keyup', undoFunc ) ;
}
// Create the enter key handler
FCK.EnterKeyHandler = new FCKEnterKey( FCK.EditorWindow, FCKConfig.EnterMode, FCKConfig.ShiftEnterMode, FCKConfig.TabSpaces ) ;
// Listen for keystroke events.
FCK.KeystrokeHandler.AttachToElement( FCK.EditorDocument ) ;
if ( FCK._ForceResetIsDirty )
FCK.ResetIsDirty() ;
// This is a tricky thing for IE. In some cases, even if the cursor is
// blinking in the editing, the keystroke handler doesn't catch keyboard
// events. We must activate the editing area to make it work. (#142).
if ( FCKBrowserInfo.IsIE && FCK.HasFocus )
FCK.EditorDocument.body.setActive() ;
FCK.OnAfterSetHTML() ;
// Restore show blocks status.
FCKCommands.GetCommand( 'ShowBlocks' ).RestoreState() ;
// Check if it is not a startup call, otherwise complete the startup.
if ( FCK.Status != FCK_STATUS_NOTLOADED )
return ;
FCK.SetStatus( FCK_STATUS_ACTIVE ) ;
}
function _FCK_GetEditorAreaStyleTags()
{
return FCKTools.GetStyleHtml( FCKConfig.EditorAreaCSS ) +
FCKTools.GetStyleHtml( FCKConfig.EditorAreaStyles ) ;
}
function _FCK_KeystrokeHandler_OnKeystroke( keystroke, keystrokeValue )
{
if ( FCK.Status != FCK_STATUS_COMPLETE )
return false ;
if ( FCK.EditMode == FCK_EDITMODE_WYSIWYG )
{
switch ( keystrokeValue )
{
case 'Paste' :
return !FCK.Paste() ;
case 'Cut' :
FCKUndo.SaveUndoStep() ;
return false ;
}
}
else
{
// In source mode, some actions must have their default behavior.
if ( keystrokeValue.Equals( 'Paste', 'Undo', 'Redo', 'SelectAll', 'Cut' ) )
return false ;
}
// The return value indicates if the default behavior of the keystroke must
// be cancelled. Let's do that only if the Execute() call explicitly returns "false".
var oCommand = FCK.Commands.GetCommand( keystrokeValue ) ;
// If the command is disabled then ignore the keystroke
if ( oCommand.GetState() == FCK_TRISTATE_DISABLED )
return false ;
return ( oCommand.Execute.apply( oCommand, FCKTools.ArgumentsToArray( arguments, 2 ) ) !== false ) ;
}
// Set the FCK.LinkedField reference to the field that will be used to post the
// editor data.
(function()
{
// There is a bug on IE... getElementById returns any META tag that has the
// name set to the ID you are looking for. So the best way in to get the array
// by names and look for the correct one.
// As ASP.Net generates a ID that is different from the Name, we must also
// look for the field based on the ID (the first one is the ID).
var oDocument = window.parent.document ;
// Try to get the field using the ID.
var eLinkedField = oDocument.getElementById( FCK.Name ) ;
var i = 0;
while ( eLinkedField || i == 0 )
{
if ( eLinkedField && eLinkedField.tagName.toLowerCase().Equals( 'input', 'textarea' ) )
{
FCK.LinkedField = eLinkedField ;
break ;
}
eLinkedField = oDocument.getElementsByName( FCK.Name )[i++] ;
}
})() ;
var FCKTempBin =
{
Elements : new Array(),
AddElement : function( element )
{
var iIndex = this.Elements.length ;
this.Elements[ iIndex ] = element ;
return iIndex ;
},
RemoveElement : function( index )
{
var e = this.Elements[ index ] ;
this.Elements[ index ] = null ;
return e ;
},
Reset : function()
{
var i = 0 ;
while ( i < this.Elements.length )
this.Elements[ i++ ] = null ;
this.Elements.length = 0 ;
},
ToHtml : function()
{
for ( var i = 0 ; i < this.Elements.length ; i++ )
{
this.Elements[i] = '<div> ' + this.Elements[i].outerHTML + '</div>' ;
this.Elements[i].isHtml = true ;
}
},
ToElements : function()
{
var node = FCK.EditorDocument.createElement( 'div' ) ;
for ( var i = 0 ; i < this.Elements.length ; i++ )
{
if ( this.Elements[i].isHtml )
{
node.innerHTML = this.Elements[i] ;
this.Elements[i] = node.firstChild.removeChild( node.firstChild.lastChild ) ;
}
}
}
} ;
// # Focus Manager: Manages the focus in the editor.
var FCKFocusManager = FCK.FocusManager =
{
IsLocked : false,
AddWindow : function( win, sendToEditingArea )
{
var oTarget ;
if ( FCKBrowserInfo.IsIE )
oTarget = win.nodeType == 1 ? win : win.frameElement ? win.frameElement : win.document ;
else if ( FCKBrowserInfo.IsSafari )
oTarget = win ;
else
oTarget = win.document ;
FCKTools.AddEventListener( oTarget, 'blur', FCKFocusManager_Win_OnBlur ) ;
FCKTools.AddEventListener( oTarget, 'focus', sendToEditingArea ? FCKFocusManager_Win_OnFocus_Area : FCKFocusManager_Win_OnFocus ) ;
},
RemoveWindow : function( win )
{
if ( FCKBrowserInfo.IsIE )
oTarget = win.nodeType == 1 ? win : win.frameElement ? win.frameElement : win.document ;
else
oTarget = win.document ;
FCKTools.RemoveEventListener( oTarget, 'blur', FCKFocusManager_Win_OnBlur ) ;
FCKTools.RemoveEventListener( oTarget, 'focus', FCKFocusManager_Win_OnFocus_Area ) ;
FCKTools.RemoveEventListener( oTarget, 'focus', FCKFocusManager_Win_OnFocus ) ;
},
Lock : function()
{
this.IsLocked = true ;
},
Unlock : function()
{
if ( this._HasPendingBlur )
FCKFocusManager._Timer = window.setTimeout( FCKFocusManager_FireOnBlur, 100 ) ;
this.IsLocked = false ;
},
_ResetTimer : function()
{
this._HasPendingBlur = false ;
if ( this._Timer )
{
window.clearTimeout( this._Timer ) ;
delete this._Timer ;
}
}
} ;
function FCKFocusManager_Win_OnBlur()
{
if ( typeof(FCK) != 'undefined' && FCK.HasFocus )
{
FCKFocusManager._ResetTimer() ;
FCKFocusManager._Timer = window.setTimeout( FCKFocusManager_FireOnBlur, 100 ) ;
}
}
function FCKFocusManager_FireOnBlur()
{
if ( FCKFocusManager.IsLocked )
FCKFocusManager._HasPendingBlur = true ;
else
{
FCK.HasFocus = false ;
FCK.Events.FireEvent( "OnBlur" ) ;
}
}
function FCKFocusManager_Win_OnFocus_Area()
{
// Check if we are already focusing the editor (to avoid loops).
if ( FCKFocusManager._IsFocusing )
return ;
FCKFocusManager._IsFocusing = true ;
FCK.Focus() ;
FCKFocusManager_Win_OnFocus() ;
// The above FCK.Focus() call may trigger other focus related functions.
// So, to avoid a loop, we delay the focusing mark removal, so it get
// executed after all othre functions have been run.
FCKTools.RunFunction( function()
{
delete FCKFocusManager._IsFocusing ;
} ) ;
}
function FCKFocusManager_Win_OnFocus()
{
FCKFocusManager._ResetTimer() ;
if ( !FCK.HasFocus && !FCKFocusManager.IsLocked )
{
FCK.HasFocus = true ;
FCK.Events.FireEvent( "OnFocus" ) ;
}
}
/*
* #1633 : Protect the editor iframe from external styles.
* Notice that we can't use FCKTools.ResetStyles here since FCKTools isn't
* loaded yet.
*/
(function()
{
var el = window.frameElement ;
var width = el.width ;
var height = el.height ;
if ( /^\d+$/.test( width ) ) width += 'px' ;
if ( /^\d+$/.test( height ) ) height += 'px' ;
var style = el.style ;
style.border = style.padding = style.margin = 0 ;
style.backgroundColor = 'transparent';
style.backgroundImage = 'none';
style.width = width ;
style.height = height ;
})() ;
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* Active selection functions. (IE specific implementation)
*/
// Get the selection type.
FCKSelection.GetType = function()
{
// It is possible that we can still get a text range object even when type=='None' is returned by IE.
// So we'd better check the object returned by createRange() rather than by looking at the type.
try
{
var ieType = FCKSelection.GetSelection().type ;
if ( ieType == 'Control' || ieType == 'Text' )
return ieType ;
if ( this.GetSelection().createRange().parentElement )
return 'Text' ;
}
catch(e)
{
// Nothing to do, it will return None properly.
}
return 'None' ;
} ;
// Retrieves the selected element (if any), just in the case that a single
// element (object like and image or a table) is selected.
FCKSelection.GetSelectedElement = function()
{
if ( this.GetType() == 'Control' )
{
var oRange = this.GetSelection().createRange() ;
if ( oRange && oRange.item )
return this.GetSelection().createRange().item(0) ;
}
return null ;
} ;
FCKSelection.GetParentElement = function()
{
switch ( this.GetType() )
{
case 'Control' :
var el = FCKSelection.GetSelectedElement() ;
return el ? el.parentElement : null ;
case 'None' :
return null ;
default :
return this.GetSelection().createRange().parentElement() ;
}
} ;
FCKSelection.GetBoundaryParentElement = function( startBoundary )
{
switch ( this.GetType() )
{
case 'Control' :
var el = FCKSelection.GetSelectedElement() ;
return el ? el.parentElement : null ;
case 'None' :
return null ;
default :
var doc = FCK.EditorDocument ;
var range = doc.selection.createRange() ;
range.collapse( startBoundary !== false ) ;
var el = range.parentElement() ;
// It may happen that range is comming from outside "doc", so we
// must check it (#1204).
return FCKTools.GetElementDocument( el ) == doc ? el : null ;
}
} ;
FCKSelection.SelectNode = function( node )
{
FCK.Focus() ;
this.GetSelection().empty() ;
var oRange ;
try
{
// Try to select the node as a control.
oRange = FCK.EditorDocument.body.createControlRange() ;
oRange.addElement( node ) ;
}
catch(e)
{
// If failed, select it as a text range.
oRange = FCK.EditorDocument.body.createTextRange() ;
oRange.moveToElementText( node ) ;
}
oRange.select() ;
} ;
FCKSelection.Collapse = function( toStart )
{
FCK.Focus() ;
if ( this.GetType() == 'Text' )
{
var oRange = this.GetSelection().createRange() ;
oRange.collapse( toStart == null || toStart === true ) ;
oRange.select() ;
}
} ;
// The "nodeTagName" parameter must be Upper Case.
FCKSelection.HasAncestorNode = function( nodeTagName )
{
var oContainer ;
if ( this.GetSelection().type == "Control" )
{
oContainer = this.GetSelectedElement() ;
}
else
{
var oRange = this.GetSelection().createRange() ;
oContainer = oRange.parentElement() ;
}
while ( oContainer )
{
if ( oContainer.nodeName.IEquals( nodeTagName ) ) return true ;
oContainer = oContainer.parentNode ;
}
return false ;
} ;
// The "nodeTagName" parameter must be UPPER CASE.
FCKSelection.MoveToAncestorNode = function( nodeTagName )
{
var oNode, oRange ;
if ( ! FCK.EditorDocument )
return null ;
if ( this.GetSelection().type == "Control" )
{
oRange = this.GetSelection().createRange() ;
for ( i = 0 ; i < oRange.length ; i++ )
{
if (oRange(i).parentNode)
{
oNode = oRange(i).parentNode ;
break ;
}
}
}
else
{
oRange = this.GetSelection().createRange() ;
oNode = oRange.parentElement() ;
}
while ( oNode && oNode.nodeName != nodeTagName )
oNode = oNode.parentNode ;
return oNode ;
} ;
FCKSelection.Delete = function()
{
// Gets the actual selection.
var oSel = this.GetSelection() ;
// Deletes the actual selection contents.
if ( oSel.type.toLowerCase() != "none" )
{
oSel.clear() ;
}
return oSel ;
} ;
/**
* Returns the native selection object.
*/
FCKSelection.GetSelection = function()
{
this.Restore() ;
return FCK.EditorDocument.selection ;
}
FCKSelection.Save = function( noFocus )
{
// Ensures the editor has the selection focus. (#1801)
if ( !noFocus )
FCK.Focus() ;
var editorDocument = FCK.EditorDocument ;
if ( !editorDocument )
return ;
var selection = editorDocument.selection ;
var range ;
if ( selection )
{
range = selection.createRange() ;
// Ensure that the range comes from the editor document.
if ( range )
{
if ( range.parentElement && FCKTools.GetElementDocument( range.parentElement() ) != editorDocument )
range = null ;
else if ( range.item && FCKTools.GetElementDocument( range.item(0) )!= editorDocument )
range = null ;
}
}
this.SelectionData = range ;
}
FCKSelection._GetSelectionDocument = function( selection )
{
var range = selection.createRange() ;
if ( !range )
return null;
else if ( range.item )
return FCKTools.GetElementDocument( range.item( 0 ) ) ;
else
return FCKTools.GetElementDocument( range.parentElement() ) ;
}
FCKSelection.Restore = function()
{
if ( this.SelectionData )
{
FCK.IsSelectionChangeLocked = true ;
try
{
// Don't repeat the restore process if the editor document is already selected.
if ( String( this._GetSelectionDocument( FCK.EditorDocument.selection ).body.contentEditable ) == 'true' )
{
FCK.IsSelectionChangeLocked = false ;
return ;
}
this.SelectionData.select() ;
}
catch ( e ) {}
FCK.IsSelectionChangeLocked = false ;
}
}
FCKSelection.Release = function()
{
delete this.SelectionData ;
}
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* Active selection functions.
*/
var FCKSelection = FCK.Selection =
{
GetParentBlock : function()
{
var retval = this.GetParentElement() ;
while ( retval )
{
if ( FCKListsLib.BlockBoundaries[retval.nodeName.toLowerCase()] )
break ;
retval = retval.parentNode ;
}
return retval ;
},
ApplyStyle : function( styleDefinition )
{
FCKStyles.ApplyStyle( new FCKStyle( styleDefinition ) ) ;
}
} ;
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* Defines the FCK.ContextMenu object that is responsible for all
* Context Menu operations in the editing area.
*/
FCK.ContextMenu = new Object() ;
FCK.ContextMenu.Listeners = new Array() ;
FCK.ContextMenu.RegisterListener = function( listener )
{
if ( listener )
this.Listeners.push( listener ) ;
}
function FCK_ContextMenu_Init()
{
var oInnerContextMenu = FCK.ContextMenu._InnerContextMenu = new FCKContextMenu( FCKBrowserInfo.IsIE ? window : window.parent, FCKLang.Dir ) ;
oInnerContextMenu.CtrlDisable = FCKConfig.BrowserContextMenuOnCtrl ;
oInnerContextMenu.OnBeforeOpen = FCK_ContextMenu_OnBeforeOpen ;
oInnerContextMenu.OnItemClick = FCK_ContextMenu_OnItemClick ;
// Get the registering function.
var oMenu = FCK.ContextMenu ;
// Register all configured context menu listeners.
for ( var i = 0 ; i < FCKConfig.ContextMenu.length ; i++ )
oMenu.RegisterListener( FCK_ContextMenu_GetListener( FCKConfig.ContextMenu[i] ) ) ;
}
function FCK_ContextMenu_GetListener( listenerName )
{
switch ( listenerName )
{
case 'Generic' :
return {
AddItems : function( menu, tag, tagName )
{
menu.AddItem( 'Cut' , FCKLang.Cut , 7, FCKCommands.GetCommand( 'Cut' ).GetState() == FCK_TRISTATE_DISABLED ) ;
menu.AddItem( 'Copy' , FCKLang.Copy , 8, FCKCommands.GetCommand( 'Copy' ).GetState() == FCK_TRISTATE_DISABLED ) ;
menu.AddItem( 'Paste' , FCKLang.Paste , 9, FCKCommands.GetCommand( 'Paste' ).GetState() == FCK_TRISTATE_DISABLED ) ;
}} ;
case 'Table' :
return {
AddItems : function( menu, tag, tagName )
{
var bIsTable = ( tagName == 'TABLE' ) ;
var bIsCell = ( !bIsTable && FCKSelection.HasAncestorNode( 'TABLE' ) ) ;
if ( bIsCell )
{
menu.AddSeparator() ;
var oItem = menu.AddItem( 'Cell' , FCKLang.CellCM ) ;
oItem.AddItem( 'TableInsertCellBefore' , FCKLang.InsertCellBefore, 69 ) ;
oItem.AddItem( 'TableInsertCellAfter' , FCKLang.InsertCellAfter, 58 ) ;
oItem.AddItem( 'TableDeleteCells' , FCKLang.DeleteCells, 59 ) ;
if ( FCKBrowserInfo.IsGecko )
oItem.AddItem( 'TableMergeCells' , FCKLang.MergeCells, 60,
FCKCommands.GetCommand( 'TableMergeCells' ).GetState() == FCK_TRISTATE_DISABLED ) ;
else
{
oItem.AddItem( 'TableMergeRight' , FCKLang.MergeRight, 60,
FCKCommands.GetCommand( 'TableMergeRight' ).GetState() == FCK_TRISTATE_DISABLED ) ;
oItem.AddItem( 'TableMergeDown' , FCKLang.MergeDown, 60,
FCKCommands.GetCommand( 'TableMergeDown' ).GetState() == FCK_TRISTATE_DISABLED ) ;
}
oItem.AddItem( 'TableHorizontalSplitCell' , FCKLang.HorizontalSplitCell, 61,
FCKCommands.GetCommand( 'TableHorizontalSplitCell' ).GetState() == FCK_TRISTATE_DISABLED ) ;
oItem.AddItem( 'TableVerticalSplitCell' , FCKLang.VerticalSplitCell, 61,
FCKCommands.GetCommand( 'TableVerticalSplitCell' ).GetState() == FCK_TRISTATE_DISABLED ) ;
oItem.AddSeparator() ;
oItem.AddItem( 'TableCellProp' , FCKLang.CellProperties, 57,
FCKCommands.GetCommand( 'TableCellProp' ).GetState() == FCK_TRISTATE_DISABLED ) ;
menu.AddSeparator() ;
oItem = menu.AddItem( 'Row' , FCKLang.RowCM ) ;
oItem.AddItem( 'TableInsertRowBefore' , FCKLang.InsertRowBefore, 70 ) ;
oItem.AddItem( 'TableInsertRowAfter' , FCKLang.InsertRowAfter, 62 ) ;
oItem.AddItem( 'TableDeleteRows' , FCKLang.DeleteRows, 63 ) ;
menu.AddSeparator() ;
oItem = menu.AddItem( 'Column' , FCKLang.ColumnCM ) ;
oItem.AddItem( 'TableInsertColumnBefore', FCKLang.InsertColumnBefore, 71 ) ;
oItem.AddItem( 'TableInsertColumnAfter' , FCKLang.InsertColumnAfter, 64 ) ;
oItem.AddItem( 'TableDeleteColumns' , FCKLang.DeleteColumns, 65 ) ;
}
if ( bIsTable || bIsCell )
{
menu.AddSeparator() ;
menu.AddItem( 'TableDelete' , FCKLang.TableDelete ) ;
menu.AddItem( 'TableProp' , FCKLang.TableProperties, 39 ) ;
}
}} ;
case 'Link' :
return {
AddItems : function( menu, tag, tagName )
{
var bInsideLink = ( tagName == 'A' || FCKSelection.HasAncestorNode( 'A' ) ) ;
if ( bInsideLink || FCK.GetNamedCommandState( 'Unlink' ) != FCK_TRISTATE_DISABLED )
{
// Go up to the anchor to test its properties
var oLink = FCKSelection.MoveToAncestorNode( 'A' ) ;
var bIsAnchor = ( oLink && oLink.name.length > 0 && oLink.href.length == 0 ) ;
// If it isn't a link then don't add the Link context menu
if ( bIsAnchor )
return ;
menu.AddSeparator() ;
menu.AddItem( 'VisitLink', FCKLang.VisitLink ) ;
menu.AddSeparator() ;
if ( bInsideLink )
menu.AddItem( 'Link', FCKLang.EditLink , 34 ) ;
menu.AddItem( 'Unlink' , FCKLang.RemoveLink , 35 ) ;
}
}} ;
case 'Image' :
return {
AddItems : function( menu, tag, tagName )
{
if ( tagName == 'IMG' && !tag.getAttribute( '_fckfakelement' ) )
{
menu.AddSeparator() ;
menu.AddItem( 'Image', FCKLang.ImageProperties, 37 ) ;
}
}} ;
case 'Anchor' :
return {
AddItems : function( menu, tag, tagName )
{
// Go up to the anchor to test its properties
var oLink = FCKSelection.MoveToAncestorNode( 'A' ) ;
var bIsAnchor = ( oLink && oLink.name.length > 0 ) ;
if ( bIsAnchor || ( tagName == 'IMG' && tag.getAttribute( '_fckanchor' ) ) )
{
menu.AddSeparator() ;
menu.AddItem( 'Anchor', FCKLang.AnchorProp, 36 ) ;
menu.AddItem( 'AnchorDelete', FCKLang.AnchorDelete ) ;
}
}} ;
case 'Flash' :
return {
AddItems : function( menu, tag, tagName )
{
if ( tagName == 'IMG' && tag.getAttribute( '_fckflash' ) )
{
menu.AddSeparator() ;
menu.AddItem( 'Flash', FCKLang.FlashProperties, 38 ) ;
}
}} ;
case 'Form' :
return {
AddItems : function( menu, tag, tagName )
{
if ( FCKSelection.HasAncestorNode('FORM') )
{
menu.AddSeparator() ;
menu.AddItem( 'Form', FCKLang.FormProp, 48 ) ;
}
}} ;
case 'Checkbox' :
return {
AddItems : function( menu, tag, tagName )
{
if ( tagName == 'INPUT' && tag.type == 'checkbox' )
{
menu.AddSeparator() ;
menu.AddItem( 'Checkbox', FCKLang.CheckboxProp, 49 ) ;
}
}} ;
case 'Radio' :
return {
AddItems : function( menu, tag, tagName )
{
if ( tagName == 'INPUT' && tag.type == 'radio' )
{
menu.AddSeparator() ;
menu.AddItem( 'Radio', FCKLang.RadioButtonProp, 50 ) ;
}
}} ;
case 'TextField' :
return {
AddItems : function( menu, tag, tagName )
{
if ( tagName == 'INPUT' && ( tag.type == 'text' || tag.type == 'password' ) )
{
menu.AddSeparator() ;
menu.AddItem( 'TextField', FCKLang.TextFieldProp, 51 ) ;
}
}} ;
case 'HiddenField' :
return {
AddItems : function( menu, tag, tagName )
{
if ( tagName == 'IMG' && tag.getAttribute( '_fckinputhidden' ) )
{
menu.AddSeparator() ;
menu.AddItem( 'HiddenField', FCKLang.HiddenFieldProp, 56 ) ;
}
}} ;
case 'ImageButton' :
return {
AddItems : function( menu, tag, tagName )
{
if ( tagName == 'INPUT' && tag.type == 'image' )
{
menu.AddSeparator() ;
menu.AddItem( 'ImageButton', FCKLang.ImageButtonProp, 55 ) ;
}
}} ;
case 'Button' :
return {
AddItems : function( menu, tag, tagName )
{
if ( tagName == 'INPUT' && ( tag.type == 'button' || tag.type == 'submit' || tag.type == 'reset' ) )
{
menu.AddSeparator() ;
menu.AddItem( 'Button', FCKLang.ButtonProp, 54 ) ;
}
}} ;
case 'Select' :
return {
AddItems : function( menu, tag, tagName )
{
if ( tagName == 'SELECT' )
{
menu.AddSeparator() ;
menu.AddItem( 'Select', FCKLang.SelectionFieldProp, 53 ) ;
}
}} ;
case 'Textarea' :
return {
AddItems : function( menu, tag, tagName )
{
if ( tagName == 'TEXTAREA' )
{
menu.AddSeparator() ;
menu.AddItem( 'Textarea', FCKLang.TextareaProp, 52 ) ;
}
}} ;
case 'BulletedList' :
return {
AddItems : function( menu, tag, tagName )
{
if ( FCKSelection.HasAncestorNode('UL') )
{
menu.AddSeparator() ;
menu.AddItem( 'BulletedList', FCKLang.BulletedListProp, 27 ) ;
}
}} ;
case 'NumberedList' :
return {
AddItems : function( menu, tag, tagName )
{
if ( FCKSelection.HasAncestorNode('OL') )
{
menu.AddSeparator() ;
menu.AddItem( 'NumberedList', FCKLang.NumberedListProp, 26 ) ;
}
}} ;
case 'DivContainer':
return {
AddItems : function( menu, tag, tagName )
{
var currentBlocks = FCKDomTools.GetSelectedDivContainers() ;
if ( currentBlocks.length > 0 )
{
menu.AddSeparator() ;
menu.AddItem( 'EditDiv', FCKLang.EditDiv, 75 ) ;
menu.AddItem( 'DeleteDiv', FCKLang.DeleteDiv, 76 ) ;
}
}} ;
}
return null ;
}
function FCK_ContextMenu_OnBeforeOpen()
{
// Update the UI.
FCK.Events.FireEvent( 'OnSelectionChange' ) ;
// Get the actual selected tag (if any).
var oTag, sTagName ;
// The extra () is to avoid a warning with strict error checking. This is ok.
if ( (oTag = FCKSelection.GetSelectedElement()) )
sTagName = oTag.tagName ;
// Cleanup the current menu items.
var oMenu = FCK.ContextMenu._InnerContextMenu ;
oMenu.RemoveAllItems() ;
// Loop through the listeners.
var aListeners = FCK.ContextMenu.Listeners ;
for ( var i = 0 ; i < aListeners.length ; i++ )
aListeners[i].AddItems( oMenu, oTag, sTagName ) ;
}
function FCK_ContextMenu_OnItemClick( item )
{
FCK.Focus() ;
FCKCommands.GetCommand( item.Name ).Execute( item.CustomData ) ;
}
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* Defines the FCKPlugins object that is responsible for loading the Plugins.
*/
var FCKPlugins = FCK.Plugins = new Object() ;
FCKPlugins.ItemsCount = 0 ;
FCKPlugins.Items = new Object() ;
FCKPlugins.Load = function()
{
var oItems = FCKPlugins.Items ;
// build the plugins collection.
for ( var i = 0 ; i < FCKConfig.Plugins.Items.length ; i++ )
{
var oItem = FCKConfig.Plugins.Items[i] ;
var oPlugin = oItems[ oItem[0] ] = new FCKPlugin( oItem[0], oItem[1], oItem[2] ) ;
FCKPlugins.ItemsCount++ ;
}
// Load all items in the plugins collection.
for ( var s in oItems )
oItems[s].Load() ;
// This is a self destroyable function (must be called once).
FCKPlugins.Load = null ;
}
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*/
var FCKUndo = new Object() ;
FCKUndo.SavedData = new Array() ;
FCKUndo.CurrentIndex = -1 ;
FCKUndo.TypesCount = 0 ;
FCKUndo.Changed = false ; // Is the document changed in respect to its initial image?
FCKUndo.MaxTypes = 25 ;
FCKUndo.Typing = false ;
FCKUndo.SaveLocked = false ;
FCKUndo._GetBookmark = function()
{
FCKSelection.Restore() ;
var range = new FCKDomRange( FCK.EditorWindow ) ;
try
{
// There are some tricky cases where this might fail (e.g. having a lone empty table in IE)
range.MoveToSelection() ;
}
catch ( e )
{
return null ;
}
if ( FCKBrowserInfo.IsIE )
{
var bookmark = range.CreateBookmark() ;
var dirtyHtml = FCK.EditorDocument.body.innerHTML ;
range.MoveToBookmark( bookmark ) ;
return [ bookmark, dirtyHtml ] ;
}
return range.CreateBookmark2() ;
}
FCKUndo._SelectBookmark = function( bookmark )
{
if ( ! bookmark )
return ;
var range = new FCKDomRange( FCK.EditorWindow ) ;
if ( bookmark instanceof Object )
{
if ( FCKBrowserInfo.IsIE )
range.MoveToBookmark( bookmark[0] ) ;
else
range.MoveToBookmark2( bookmark ) ;
try
{
// this does not always succeed, there are still some tricky cases where it fails
// e.g. add a special character at end of document, undo, redo -> error
range.Select() ;
}
catch ( e )
{
// if select restore fails, put the caret at the end of the document
range.MoveToPosition( FCK.EditorDocument.body, 4 ) ;
range.Select() ;
}
}
}
FCKUndo._CompareCursors = function( cursor1, cursor2 )
{
for ( var i = 0 ; i < Math.min( cursor1.length, cursor2.length ) ; i++ )
{
if ( cursor1[i] < cursor2[i] )
return -1;
else if (cursor1[i] > cursor2[i] )
return 1;
}
if ( cursor1.length < cursor2.length )
return -1;
else if (cursor1.length > cursor2.length )
return 1;
return 0;
}
FCKUndo._CheckIsBookmarksEqual = function( bookmark1, bookmark2 )
{
if ( ! ( bookmark1 && bookmark2 ) )
return false ;
if ( FCKBrowserInfo.IsIE )
{
var startOffset1 = bookmark1[1].search( bookmark1[0].StartId ) ;
var startOffset2 = bookmark2[1].search( bookmark2[0].StartId ) ;
var endOffset1 = bookmark1[1].search( bookmark1[0].EndId ) ;
var endOffset2 = bookmark2[1].search( bookmark2[0].EndId ) ;
return startOffset1 == startOffset2 && endOffset1 == endOffset2 ;
}
else
{
return this._CompareCursors( bookmark1.Start, bookmark2.Start ) == 0
&& this._CompareCursors( bookmark1.End, bookmark2.End ) == 0 ;
}
}
FCKUndo.SaveUndoStep = function()
{
if ( FCK.EditMode != FCK_EDITMODE_WYSIWYG || this.SaveLocked )
return ;
// Assume the editor content is changed when SaveUndoStep() is called after the first time.
// This also enables the undo button in toolbar.
if ( this.SavedData.length )
this.Changed = true ;
// Get the HTML content.
var sHtml = FCK.EditorDocument.body.innerHTML ;
var bookmark = this._GetBookmark() ;
// Shrink the array to the current level.
this.SavedData = this.SavedData.slice( 0, this.CurrentIndex + 1 ) ;
// Cancel operation if the new step is identical to the previous one.
if ( this.CurrentIndex > 0
&& sHtml == this.SavedData[ this.CurrentIndex ][0]
&& this._CheckIsBookmarksEqual( bookmark, this.SavedData[ this.CurrentIndex ][1] ) )
return ;
// Save the selection and caret position in the first undo level for the first change.
else if ( this.CurrentIndex == 0 && this.SavedData.length && sHtml == this.SavedData[0][0] )
{
this.SavedData[0][1] = bookmark ;
return ;
}
// If we reach the Maximum number of undo levels, we must remove the first
// entry of the list shifting all elements.
if ( this.CurrentIndex + 1 >= FCKConfig.MaxUndoLevels )
this.SavedData.shift() ;
else
this.CurrentIndex++ ;
// Save the new level in front of the actual position.
this.SavedData[ this.CurrentIndex ] = [ sHtml, bookmark ] ;
FCK.Events.FireEvent( "OnSelectionChange" ) ;
}
FCKUndo.CheckUndoState = function()
{
return ( this.Changed || this.CurrentIndex > 0 ) ;
}
FCKUndo.CheckRedoState = function()
{
return ( this.CurrentIndex < ( this.SavedData.length - 1 ) ) ;
}
FCKUndo.Undo = function()
{
if ( this.CheckUndoState() )
{
// If it is the first step.
if ( this.CurrentIndex == ( this.SavedData.length - 1 ) )
{
// Save the actual state for a possible "Redo" call.
this.SaveUndoStep() ;
}
// Go a step back.
this._ApplyUndoLevel( --this.CurrentIndex ) ;
FCK.Events.FireEvent( "OnSelectionChange" ) ;
}
}
FCKUndo.Redo = function()
{
if ( this.CheckRedoState() )
{
// Go a step forward.
this._ApplyUndoLevel( ++this.CurrentIndex ) ;
FCK.Events.FireEvent( "OnSelectionChange" ) ;
}
}
FCKUndo._ApplyUndoLevel = function( level )
{
var oData = this.SavedData[ level ] ;
if ( !oData )
return ;
// Update the editor contents with that step data.
if ( FCKBrowserInfo.IsIE )
{
if ( oData[1] && oData[1][1] )
FCK.SetInnerHtml( oData[1][1] ) ;
else
FCK.SetInnerHtml( oData[0] ) ;
}
else
FCK.EditorDocument.body.innerHTML = oData[0] ;
// Restore the selection
this._SelectBookmark( oData[1] ) ;
this.TypesCount = 0 ;
this.Changed = false ;
this.Typing = false ;
}
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* Defines the FCKXHtml object, responsible for the XHTML operations.
* IE specific.
*/
FCKXHtml._GetMainXmlString = function()
{
return this.MainNode.xml ;
}
FCKXHtml._AppendAttributes = function( xmlNode, htmlNode, node, nodeName )
{
var aAttributes = htmlNode.attributes,
bHasStyle ;
for ( var n = 0 ; n < aAttributes.length ; n++ )
{
var oAttribute = aAttributes[n] ;
if ( oAttribute.specified )
{
var sAttName = oAttribute.nodeName.toLowerCase() ;
var sAttValue ;
// Ignore any attribute starting with "_fck".
if ( sAttName.StartsWith( '_fck' ) )
continue ;
// The following must be done because of a bug on IE regarding the style
// attribute. It returns "null" for the nodeValue.
else if ( sAttName == 'style' )
{
// Just mark it to do it later in this function.
bHasStyle = true ;
continue ;
}
// There are two cases when the oAttribute.nodeValue must be used:
// - for the "class" attribute
// - for events attributes (on IE only).
else if ( sAttName == 'class' )
{
sAttValue = oAttribute.nodeValue.replace( FCKRegexLib.FCK_Class, '' ) ;
if ( sAttValue.length == 0 )
continue ;
}
else if ( sAttName.indexOf('on') == 0 )
sAttValue = oAttribute.nodeValue ;
else if ( nodeName == 'body' && sAttName == 'contenteditable' )
continue ;
// XHTML doens't support attribute minimization like "CHECKED". It must be transformed to checked="checked".
else if ( oAttribute.nodeValue === true )
sAttValue = sAttName ;
else
{
// We must use getAttribute to get it exactly as it is defined.
// There are some rare cases that IE throws an error here, so we must try/catch.
try
{
sAttValue = htmlNode.getAttribute( sAttName, 2 ) ;
}
catch (e) {}
}
this._AppendAttribute( node, sAttName, sAttValue || oAttribute.nodeValue ) ;
}
}
// IE loses the style attribute in JavaScript-created elements tags. (#2390)
if ( bHasStyle || htmlNode.style.cssText.length > 0 )
{
var data = FCKTools.ProtectFormStyles( htmlNode ) ;
var sStyleValue = htmlNode.style.cssText.replace( FCKRegexLib.StyleProperties, FCKTools.ToLowerCase ) ;
FCKTools.RestoreFormStyles( htmlNode, data ) ;
this._AppendAttribute( node, 'style', sStyleValue ) ;
}
}
// On very rare cases, IE is loosing the "align" attribute for DIV. (right align and apply bulleted list)
FCKXHtml.TagProcessors['div'] = function( node, htmlNode )
{
if ( htmlNode.align.length > 0 )
FCKXHtml._AppendAttribute( node, 'align', htmlNode.align ) ;
node = FCKXHtml._AppendChildNodes( node, htmlNode, true ) ;
return node ;
}
// IE automatically changes <FONT> tags to <FONT size=+0>.
FCKXHtml.TagProcessors['font'] = function( node, htmlNode )
{
if ( node.attributes.length == 0 )
node = FCKXHtml.XML.createDocumentFragment() ;
node = FCKXHtml._AppendChildNodes( node, htmlNode ) ;
return node ;
}
FCKXHtml.TagProcessors['form'] = function( node, htmlNode )
{
if ( htmlNode.acceptCharset && htmlNode.acceptCharset.length > 0 && htmlNode.acceptCharset != 'UNKNOWN' )
FCKXHtml._AppendAttribute( node, 'accept-charset', htmlNode.acceptCharset ) ;
// IE has a bug and htmlNode.attributes['name'].specified=false if there is
// no element with id="name" inside the form (#360 and SF-BUG-1155726).
var nameAtt = htmlNode.attributes['name'] ;
if ( nameAtt && nameAtt.value.length > 0 )
FCKXHtml._AppendAttribute( node, 'name', nameAtt.value ) ;
node = FCKXHtml._AppendChildNodes( node, htmlNode, true ) ;
return node ;
}
// IE doens't see the value attribute as an attribute for the <INPUT> tag.
FCKXHtml.TagProcessors['input'] = function( node, htmlNode )
{
if ( htmlNode.name )
FCKXHtml._AppendAttribute( node, 'name', htmlNode.name ) ;
if ( htmlNode.value && !node.attributes.getNamedItem( 'value' ) )
FCKXHtml._AppendAttribute( node, 'value', htmlNode.value ) ;
if ( !node.attributes.getNamedItem( 'type' ) )
FCKXHtml._AppendAttribute( node, 'type', 'text' ) ;
return node ;
}
FCKXHtml.TagProcessors['label'] = function( node, htmlNode )
{
if ( htmlNode.htmlFor.length > 0 )
FCKXHtml._AppendAttribute( node, 'for', htmlNode.htmlFor ) ;
node = FCKXHtml._AppendChildNodes( node, htmlNode ) ;
return node ;
}
// Fix behavior for IE, it doesn't read back the .name on newly created maps
FCKXHtml.TagProcessors['map'] = function( node, htmlNode )
{
if ( ! node.attributes.getNamedItem( 'name' ) )
{
var name = htmlNode.name ;
if ( name )
FCKXHtml._AppendAttribute( node, 'name', name ) ;
}
node = FCKXHtml._AppendChildNodes( node, htmlNode, true ) ;
return node ;
}
FCKXHtml.TagProcessors['meta'] = function( node, htmlNode )
{
var oHttpEquiv = node.attributes.getNamedItem( 'http-equiv' ) ;
if ( oHttpEquiv == null || oHttpEquiv.value.length == 0 )
{
// Get the http-equiv value from the outerHTML.
var sHttpEquiv = htmlNode.outerHTML.match( FCKRegexLib.MetaHttpEquiv ) ;
if ( sHttpEquiv )
{
sHttpEquiv = sHttpEquiv[1] ;
FCKXHtml._AppendAttribute( node, 'http-equiv', sHttpEquiv ) ;
}
}
return node ;
}
// IE ignores the "SELECTED" attribute so we must add it manually.
FCKXHtml.TagProcessors['option'] = function( node, htmlNode )
{
if ( htmlNode.selected && !node.attributes.getNamedItem( 'selected' ) )
FCKXHtml._AppendAttribute( node, 'selected', 'selected' ) ;
node = FCKXHtml._AppendChildNodes( node, htmlNode ) ;
return node ;
}
// IE doens't hold the name attribute as an attribute for the <TEXTAREA> and <SELECT> tags.
FCKXHtml.TagProcessors['textarea'] = FCKXHtml.TagProcessors['select'] = function( node, htmlNode )
{
if ( htmlNode.name )
FCKXHtml._AppendAttribute( node, 'name', htmlNode.name ) ;
node = FCKXHtml._AppendChildNodes( node, htmlNode ) ;
return node ;
}
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* Defines the FCKToolbarSet object that is used to load and draw the
* toolbar.
*/
function FCKToolbarSet_Create( overhideLocation )
{
var oToolbarSet ;
var sLocation = overhideLocation || FCKConfig.ToolbarLocation ;
switch ( sLocation )
{
case 'In' :
document.getElementById( 'xToolbarRow' ).style.display = '' ;
oToolbarSet = new FCKToolbarSet( document ) ;
break ;
case 'None' :
oToolbarSet = new FCKToolbarSet( document ) ;
break ;
// case 'OutTop' :
// Not supported.
default :
FCK.Events.AttachEvent( 'OnBlur', FCK_OnBlur ) ;
FCK.Events.AttachEvent( 'OnFocus', FCK_OnFocus ) ;
var eToolbarTarget ;
// Out:[TargetWindow]([TargetId])
var oOutMatch = sLocation.match( /^Out:(.+)\((\w+)\)$/ ) ;
if ( oOutMatch )
{
if ( FCKBrowserInfo.IsAIR )
FCKAdobeAIR.ToolbarSet_GetOutElement( window, oOutMatch ) ;
else
eToolbarTarget = eval( 'parent.' + oOutMatch[1] ).document.getElementById( oOutMatch[2] ) ;
}
else
{
// Out:[TargetId]
oOutMatch = sLocation.match( /^Out:(\w+)$/ ) ;
if ( oOutMatch )
eToolbarTarget = parent.document.getElementById( oOutMatch[1] ) ;
}
if ( !eToolbarTarget )
{
alert( 'Invalid value for "ToolbarLocation"' ) ;
return arguments.callee( 'In' );
}
// If it is a shared toolbar, it may be already available in the target element.
oToolbarSet = eToolbarTarget.__FCKToolbarSet ;
if ( oToolbarSet )
break ;
// Create the IFRAME that will hold the toolbar inside the target element.
var eToolbarIFrame = FCKTools.GetElementDocument( eToolbarTarget ).createElement( 'iframe' ) ;
eToolbarIFrame.src = 'javascript:void(0)' ;
eToolbarIFrame.frameBorder = 0 ;
eToolbarIFrame.width = '100%' ;
eToolbarIFrame.height = '10' ;
eToolbarTarget.appendChild( eToolbarIFrame ) ;
eToolbarIFrame.unselectable = 'on' ;
// Write the basic HTML for the toolbar (copy from the editor main page).
var eTargetDocument = eToolbarIFrame.contentWindow.document ;
// Workaround for Safari 12256. Ticket #63
var sBase = '' ;
if ( FCKBrowserInfo.IsSafari )
sBase = '<base href="' + window.document.location + '">' ;
// Initialize the IFRAME document body.
eTargetDocument.open() ;
eTargetDocument.write( '<html><head>' + sBase + '<script type="text/javascript"> var adjust = function() { window.frameElement.height = document.body.scrollHeight ; }; '
+ 'window.onresize = window.onload = '
+ 'function(){' // poll scrollHeight until it no longer changes for 1 sec.
+ 'var timer = null;'
+ 'var lastHeight = -1;'
+ 'var lastChange = 0;'
+ 'var poller = function(){'
+ 'var currentHeight = document.body.scrollHeight || 0;'
+ 'var currentTime = (new Date()).getTime();'
+ 'if (currentHeight != lastHeight){'
+ 'lastChange = currentTime;'
+ 'adjust();'
+ 'lastHeight = document.body.scrollHeight;'
+ '}'
+ 'if (lastChange < currentTime - 1000) clearInterval(timer);'
+ '};'
+ 'timer = setInterval(poller, 100);'
+ '}'
+ '</script></head><body style="overflow: hidden">' + document.getElementById( 'xToolbarSpace' ).innerHTML + '</body></html>' ) ;
eTargetDocument.close() ;
if( FCKBrowserInfo.IsAIR )
FCKAdobeAIR.ToolbarSet_InitOutFrame( eTargetDocument ) ;
FCKTools.AddEventListener( eTargetDocument, 'contextmenu', FCKTools.CancelEvent ) ;
// Load external resources (must be done here, otherwise Firefox will not
// have the document DOM ready to be used right away.
FCKTools.AppendStyleSheet( eTargetDocument, FCKConfig.SkinEditorCSS ) ;
oToolbarSet = eToolbarTarget.__FCKToolbarSet = new FCKToolbarSet( eTargetDocument ) ;
oToolbarSet._IFrame = eToolbarIFrame ;
if ( FCK.IECleanup )
FCK.IECleanup.AddItem( eToolbarTarget, FCKToolbarSet_Target_Cleanup ) ;
}
oToolbarSet.CurrentInstance = FCK ;
if ( !oToolbarSet.ToolbarItems )
oToolbarSet.ToolbarItems = FCKToolbarItems ;
FCK.AttachToOnSelectionChange( oToolbarSet.RefreshItemsState ) ;
return oToolbarSet ;
}
function FCK_OnBlur( editorInstance )
{
var eToolbarSet = editorInstance.ToolbarSet ;
if ( eToolbarSet.CurrentInstance == editorInstance )
eToolbarSet.Disable() ;
}
function FCK_OnFocus( editorInstance )
{
var oToolbarset = editorInstance.ToolbarSet ;
var oInstance = editorInstance || FCK ;
// Unregister the toolbar window from the current instance.
oToolbarset.CurrentInstance.FocusManager.RemoveWindow( oToolbarset._IFrame.contentWindow ) ;
// Set the new current instance.
oToolbarset.CurrentInstance = oInstance ;
// Register the toolbar window in the current instance.
oInstance.FocusManager.AddWindow( oToolbarset._IFrame.contentWindow, true ) ;
oToolbarset.Enable() ;
}
function FCKToolbarSet_Cleanup()
{
this._TargetElement = null ;
this._IFrame = null ;
}
function FCKToolbarSet_Target_Cleanup()
{
this.__FCKToolbarSet = null ;
}
var FCKToolbarSet = function( targetDocument )
{
this._Document = targetDocument ;
// Get the element that will hold the elements structure.
this._TargetElement = targetDocument.getElementById( 'xToolbar' ) ;
// Setup the expand and collapse handlers.
var eExpandHandle = targetDocument.getElementById( 'xExpandHandle' ) ;
var eCollapseHandle = targetDocument.getElementById( 'xCollapseHandle' ) ;
eExpandHandle.title = FCKLang.ToolbarExpand ;
FCKTools.AddEventListener( eExpandHandle, 'click', FCKToolbarSet_Expand_OnClick ) ;
eCollapseHandle.title = FCKLang.ToolbarCollapse ;
FCKTools.AddEventListener( eCollapseHandle, 'click', FCKToolbarSet_Collapse_OnClick ) ;
// Set the toolbar state at startup.
if ( !FCKConfig.ToolbarCanCollapse || FCKConfig.ToolbarStartExpanded )
this.Expand() ;
else
this.Collapse() ;
// Enable/disable the collapse handler
eCollapseHandle.style.display = FCKConfig.ToolbarCanCollapse ? '' : 'none' ;
if ( FCKConfig.ToolbarCanCollapse )
eCollapseHandle.style.display = '' ;
else
targetDocument.getElementById( 'xTBLeftBorder' ).style.display = '' ;
// Set the default properties.
this.Toolbars = new Array() ;
this.IsLoaded = false ;
if ( FCK.IECleanup )
FCK.IECleanup.AddItem( this, FCKToolbarSet_Cleanup ) ;
}
function FCKToolbarSet_Expand_OnClick()
{
FCK.ToolbarSet.Expand() ;
}
function FCKToolbarSet_Collapse_OnClick()
{
FCK.ToolbarSet.Collapse() ;
}
FCKToolbarSet.prototype.Expand = function()
{
this._ChangeVisibility( false ) ;
}
FCKToolbarSet.prototype.Collapse = function()
{
this._ChangeVisibility( true ) ;
}
FCKToolbarSet.prototype._ChangeVisibility = function( collapse )
{
this._Document.getElementById( 'xCollapsed' ).style.display = collapse ? '' : 'none' ;
this._Document.getElementById( 'xExpanded' ).style.display = collapse ? 'none' : '' ;
if ( FCKBrowserInfo.IsGecko )
{
// I had to use "setTimeout" because Gecko was not responding in a right
// way when calling window.onresize() directly.
FCKTools.RunFunction( window.onresize ) ;
}
}
FCKToolbarSet.prototype.Load = function( toolbarSetName )
{
this.Name = toolbarSetName ;
this.Items = new Array() ;
// Reset the array of toolbar items that are active only on WYSIWYG mode.
this.ItemsWysiwygOnly = new Array() ;
// Reset the array of toolbar items that are sensitive to the cursor position.
this.ItemsContextSensitive = new Array() ;
// Cleanup the target element.
this._TargetElement.innerHTML = '' ;
var ToolbarSet = FCKConfig.ToolbarSets[toolbarSetName] ;
if ( !ToolbarSet )
{
alert( FCKLang.UnknownToolbarSet.replace( /%1/g, toolbarSetName ) ) ;
return ;
}
this.Toolbars = new Array() ;
for ( var x = 0 ; x < ToolbarSet.length ; x++ )
{
var oToolbarItems = ToolbarSet[x] ;
// If the configuration for the toolbar is missing some element or has any extra comma
// this item won't be valid, so skip it and keep on processing.
if ( !oToolbarItems )
continue ;
var oToolbar ;
if ( typeof( oToolbarItems ) == 'string' )
{
if ( oToolbarItems == '/' )
oToolbar = new FCKToolbarBreak() ;
}
else
{
oToolbar = new FCKToolbar() ;
for ( var j = 0 ; j < oToolbarItems.length ; j++ )
{
var sItem = oToolbarItems[j] ;
if ( sItem == '-')
oToolbar.AddSeparator() ;
else
{
var oItem = FCKToolbarItems.GetItem( sItem ) ;
if ( oItem )
{
oToolbar.AddItem( oItem ) ;
this.Items.push( oItem ) ;
if ( !oItem.SourceView )
this.ItemsWysiwygOnly.push( oItem ) ;
if ( oItem.ContextSensitive )
this.ItemsContextSensitive.push( oItem ) ;
}
}
}
// oToolbar.AddTerminator() ;
}
oToolbar.Create( this._TargetElement ) ;
this.Toolbars[ this.Toolbars.length ] = oToolbar ;
}
FCKTools.DisableSelection( this._Document.getElementById( 'xCollapseHandle' ).parentNode ) ;
if ( FCK.Status != FCK_STATUS_COMPLETE )
FCK.Events.AttachEvent( 'OnStatusChange', this.RefreshModeState ) ;
else
this.RefreshModeState() ;
this.IsLoaded = true ;
this.IsEnabled = true ;
FCKTools.RunFunction( this.OnLoad ) ;
}
FCKToolbarSet.prototype.Enable = function()
{
if ( this.IsEnabled )
return ;
this.IsEnabled = true ;
var aItems = this.Items ;
for ( var i = 0 ; i < aItems.length ; i++ )
aItems[i].RefreshState() ;
}
FCKToolbarSet.prototype.Disable = function()
{
if ( !this.IsEnabled )
return ;
this.IsEnabled = false ;
var aItems = this.Items ;
for ( var i = 0 ; i < aItems.length ; i++ )
aItems[i].Disable() ;
}
FCKToolbarSet.prototype.RefreshModeState = function( editorInstance )
{
if ( FCK.Status != FCK_STATUS_COMPLETE )
return ;
var oToolbarSet = editorInstance ? editorInstance.ToolbarSet : this ;
var aItems = oToolbarSet.ItemsWysiwygOnly ;
if ( FCK.EditMode == FCK_EDITMODE_WYSIWYG )
{
// Enable all buttons that are available on WYSIWYG mode only.
for ( var i = 0 ; i < aItems.length ; i++ )
aItems[i].Enable() ;
// Refresh the buttons state.
oToolbarSet.RefreshItemsState( editorInstance ) ;
}
else
{
// Refresh the buttons state.
oToolbarSet.RefreshItemsState( editorInstance ) ;
// Disable all buttons that are available on WYSIWYG mode only.
for ( var j = 0 ; j < aItems.length ; j++ )
aItems[j].Disable() ;
}
}
FCKToolbarSet.prototype.RefreshItemsState = function( editorInstance )
{
var aItems = ( editorInstance ? editorInstance.ToolbarSet : this ).ItemsContextSensitive ;
for ( var i = 0 ; i < aItems.length ; i++ )
aItems[i].RefreshState() ;
}
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* Format the HTML.
*/
var FCKCodeFormatter = new Object() ;
FCKCodeFormatter.Init = function()
{
var oRegex = this.Regex = new Object() ;
// Regex for line breaks.
oRegex.BlocksOpener = /\<(P|DIV|H1|H2|H3|H4|H5|H6|ADDRESS|PRE|OL|UL|LI|TITLE|META|LINK|BASE|SCRIPT|LINK|TD|TH|AREA|OPTION)[^\>]*\>/gi ;
oRegex.BlocksCloser = /\<\/(P|DIV|H1|H2|H3|H4|H5|H6|ADDRESS|PRE|OL|UL|LI|TITLE|META|LINK|BASE|SCRIPT|LINK|TD|TH|AREA|OPTION)[^\>]*\>/gi ;
oRegex.NewLineTags = /\<(BR|HR)[^\>]*\>/gi ;
oRegex.MainTags = /\<\/?(HTML|HEAD|BODY|FORM|TABLE|TBODY|THEAD|TR)[^\>]*\>/gi ;
oRegex.LineSplitter = /\s*\n+\s*/g ;
// Regex for indentation.
oRegex.IncreaseIndent = /^\<(HTML|HEAD|BODY|FORM|TABLE|TBODY|THEAD|TR|UL|OL)[ \/\>]/i ;
oRegex.DecreaseIndent = /^\<\/(HTML|HEAD|BODY|FORM|TABLE|TBODY|THEAD|TR|UL|OL)[ \>]/i ;
oRegex.FormatIndentatorRemove = new RegExp( '^' + FCKConfig.FormatIndentator ) ;
oRegex.ProtectedTags = /(<PRE[^>]*>)([\s\S]*?)(<\/PRE>)/gi ;
}
FCKCodeFormatter._ProtectData = function( outer, opener, data, closer )
{
return opener + '___FCKpd___' + FCKCodeFormatter.ProtectedData.AddItem( data ) + closer ;
}
FCKCodeFormatter.Format = function( html )
{
if ( !this.Regex )
this.Init() ;
// Protected content that remain untouched during the
// process go in the following array.
FCKCodeFormatter.ProtectedData = new Array() ;
var sFormatted = html.replace( this.Regex.ProtectedTags, FCKCodeFormatter._ProtectData ) ;
// Line breaks.
sFormatted = sFormatted.replace( this.Regex.BlocksOpener, '\n$&' ) ;
sFormatted = sFormatted.replace( this.Regex.BlocksCloser, '$&\n' ) ;
sFormatted = sFormatted.replace( this.Regex.NewLineTags, '$&\n' ) ;
sFormatted = sFormatted.replace( this.Regex.MainTags, '\n$&\n' ) ;
// Indentation.
var sIndentation = '' ;
var asLines = sFormatted.split( this.Regex.LineSplitter ) ;
sFormatted = '' ;
for ( var i = 0 ; i < asLines.length ; i++ )
{
var sLine = asLines[i] ;
if ( sLine.length == 0 )
continue ;
if ( this.Regex.DecreaseIndent.test( sLine ) )
sIndentation = sIndentation.replace( this.Regex.FormatIndentatorRemove, '' ) ;
sFormatted += sIndentation + sLine + '\n' ;
if ( this.Regex.IncreaseIndent.test( sLine ) )
sIndentation += FCKConfig.FormatIndentator ;
}
// Now we put back the protected data.
for ( var j = 0 ; j < FCKCodeFormatter.ProtectedData.length ; j++ )
{
var oRegex = new RegExp( '___FCKpd___' + j ) ;
sFormatted = sFormatted.replace( oRegex, FCKCodeFormatter.ProtectedData[j].replace( /\$/g, '$$$$' ) ) ;
}
return sFormatted.Trim() ;
}
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* Dialog windows operations.
*/
var FCKDialog = ( function()
{
var topDialog ;
var baseZIndex ;
var cover ;
// The document that holds the dialog.
var topWindow = window.parent ;
while ( topWindow.parent && topWindow.parent != topWindow )
{
try
{
if ( topWindow.parent.document.domain != document.domain )
break ;
if ( topWindow.parent.document.getElementsByTagName( 'frameset' ).length > 0 )
break ;
}
catch ( e )
{
break ;
}
topWindow = topWindow.parent ;
}
var topDocument = topWindow.document ;
var getZIndex = function()
{
if ( !baseZIndex )
baseZIndex = FCKConfig.FloatingPanelsZIndex + 999 ;
return ++baseZIndex ;
}
// TODO : This logic is not actually working when reducing the window, only
// when enlarging it.
var resizeHandler = function()
{
if ( !cover )
return ;
var relElement = FCKTools.IsStrictMode( topDocument ) ? topDocument.documentElement : topDocument.body ;
FCKDomTools.SetElementStyles( cover,
{
'width' : Math.max( relElement.scrollWidth,
relElement.clientWidth,
topDocument.scrollWidth || 0 ) - 1 + 'px',
'height' : Math.max( relElement.scrollHeight,
relElement.clientHeight,
topDocument.scrollHeight || 0 ) - 1 + 'px'
} ) ;
}
return {
/**
* Opens a dialog window using the standard dialog template.
*/
OpenDialog : function( dialogName, dialogTitle, dialogPage, width, height, customValue, parentWindow, resizable )
{
if ( !topDialog )
this.DisplayMainCover() ;
// Setup the dialog info to be passed to the dialog.
var dialogInfo =
{
Title : dialogTitle,
Page : dialogPage,
Editor : window,
CustomValue : customValue, // Optional
TopWindow : topWindow
}
FCK.ToolbarSet.CurrentInstance.Selection.Save() ;
// Calculate the dialog position, centering it on the screen.
var viewSize = FCKTools.GetViewPaneSize( topWindow ) ;
var scrollPosition = { 'X' : 0, 'Y' : 0 } ;
var useAbsolutePosition = FCKBrowserInfo.IsIE && ( !FCKBrowserInfo.IsIE7 || !FCKTools.IsStrictMode( topWindow.document ) ) ;
if ( useAbsolutePosition )
scrollPosition = FCKTools.GetScrollPosition( topWindow ) ;
var iTop = Math.max( scrollPosition.Y + ( viewSize.Height - height - 20 ) / 2, 0 ) ;
var iLeft = Math.max( scrollPosition.X + ( viewSize.Width - width - 20 ) / 2, 0 ) ;
// Setup the IFRAME that will hold the dialog.
var dialog = topDocument.createElement( 'iframe' ) ;
FCKTools.ResetStyles( dialog ) ;
dialog.src = FCKConfig.BasePath + 'fckdialog.html' ;
// Dummy URL for testing whether the code in fckdialog.js alone leaks memory.
// dialog.src = 'about:blank';
dialog.frameBorder = 0 ;
dialog.allowTransparency = true ;
FCKDomTools.SetElementStyles( dialog,
{
'position' : ( useAbsolutePosition ) ? 'absolute' : 'fixed',
'top' : iTop + 'px',
'left' : iLeft + 'px',
'width' : width + 'px',
'height' : height + 'px',
'zIndex' : getZIndex()
} ) ;
// Save the dialog info to be used by the dialog page once loaded.
dialog._DialogArguments = dialogInfo ;
// Append the IFRAME to the target document.
topDocument.body.appendChild( dialog ) ;
// Keep record of the dialog's parent/child relationships.
dialog._ParentDialog = topDialog ;
topDialog = dialog ;
},
/**
* (For internal use)
* Called when the top dialog is closed.
*/
OnDialogClose : function( dialogWindow )
{
var dialog = dialogWindow.frameElement ;
FCKDomTools.RemoveNode( dialog ) ;
if ( dialog._ParentDialog ) // Nested Dialog.
{
topDialog = dialog._ParentDialog ;
dialog._ParentDialog.contentWindow.SetEnabled( true ) ;
}
else // First Dialog.
{
// Set the Focus in the browser, so the "OnBlur" event is not
// fired. In IE, there is no need to do that because the dialog
// already moved the selection to the editing area before
// closing (EnsureSelection). Also, the Focus() call here
// causes memory leak on IE7 (weird).
if ( !FCKBrowserInfo.IsIE )
FCK.Focus() ;
this.HideMainCover() ;
// Bug #1918: Assigning topDialog = null directly causes IE6 to crash.
setTimeout( function(){ topDialog = null ; }, 0 ) ;
// Release the previously saved selection.
FCK.ToolbarSet.CurrentInstance.Selection.Release() ;
}
},
DisplayMainCover : function()
{
// Setup the DIV that will be used to cover.
cover = topDocument.createElement( 'div' ) ;
FCKTools.ResetStyles( cover ) ;
FCKDomTools.SetElementStyles( cover,
{
'position' : 'absolute',
'zIndex' : getZIndex(),
'top' : '0px',
'left' : '0px',
'backgroundColor' : FCKConfig.BackgroundBlockerColor
} ) ;
FCKDomTools.SetOpacity( cover, FCKConfig.BackgroundBlockerOpacity ) ;
// For IE6-, we need to fill the cover with a transparent IFRAME,
// to properly block <select> fields.
if ( FCKBrowserInfo.IsIE && !FCKBrowserInfo.IsIE7 )
{
var iframe = topDocument.createElement( 'iframe' ) ;
FCKTools.ResetStyles( iframe ) ;
iframe.hideFocus = true ;
iframe.frameBorder = 0 ;
iframe.src = FCKTools.GetVoidUrl() ;
FCKDomTools.SetElementStyles( iframe,
{
'width' : '100%',
'height' : '100%',
'position' : 'absolute',
'left' : '0px',
'top' : '0px',
'filter' : 'progid:DXImageTransform.Microsoft.Alpha(opacity=0)'
} ) ;
cover.appendChild( iframe ) ;
}
// We need to manually adjust the cover size on resize.
FCKTools.AddEventListener( topWindow, 'resize', resizeHandler ) ;
resizeHandler() ;
topDocument.body.appendChild( cover ) ;
FCKFocusManager.Lock() ;
// Prevent the user from refocusing the disabled
// editing window by pressing Tab. (Bug #2065)
var el = FCK.ToolbarSet.CurrentInstance.GetInstanceObject( 'frameElement' ) ;
el._fck_originalTabIndex = el.tabIndex ;
el.tabIndex = -1 ;
},
HideMainCover : function()
{
FCKDomTools.RemoveNode( cover ) ;
FCKFocusManager.Unlock() ;
// Revert the tab index hack. (Bug #2065)
var el = FCK.ToolbarSet.CurrentInstance.GetInstanceObject( 'frameElement' ) ;
el.tabIndex = el._fck_originalTabIndex ;
FCKDomTools.ClearElementJSProperty( el, '_fck_originalTabIndex' ) ;
},
GetCover : function()
{
return cover ;
}
} ;
} )() ;
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* Utility functions. (IE version).
*/
FCKTools.CancelEvent = function( e )
{
return false ;
}
// Appends one or more CSS files to a document.
FCKTools._AppendStyleSheet = function( documentElement, cssFileUrl )
{
return documentElement.createStyleSheet( cssFileUrl ).owningElement ;
}
// Appends a CSS style string to a document.
FCKTools.AppendStyleString = function( documentElement, cssStyles )
{
if ( !cssStyles )
return null ;
var s = documentElement.createStyleSheet( "" ) ;
s.cssText = cssStyles ;
return s ;
}
// Removes all attributes and values from the element.
FCKTools.ClearElementAttributes = function( element )
{
element.clearAttributes() ;
}
FCKTools.GetAllChildrenIds = function( parentElement )
{
var aIds = new Array() ;
for ( var i = 0 ; i < parentElement.all.length ; i++ )
{
var sId = parentElement.all[i].id ;
if ( sId && sId.length > 0 )
aIds[ aIds.length ] = sId ;
}
return aIds ;
}
FCKTools.RemoveOuterTags = function( e )
{
e.insertAdjacentHTML( 'beforeBegin', e.innerHTML ) ;
e.parentNode.removeChild( e ) ;
}
FCKTools.CreateXmlObject = function( object )
{
var aObjs ;
switch ( object )
{
case 'XmlHttp' :
// Try the native XMLHttpRequest introduced with IE7.
if ( document.location.protocol != 'file:' )
try { return new XMLHttpRequest() ; } catch (e) {}
aObjs = [ 'MSXML2.XmlHttp', 'Microsoft.XmlHttp' ] ;
break ;
case 'DOMDocument' :
aObjs = [ 'MSXML2.DOMDocument', 'Microsoft.XmlDom' ] ;
break ;
}
for ( var i = 0 ; i < 2 ; i++ )
{
try { return new ActiveXObject( aObjs[i] ) ; }
catch (e)
{}
}
if ( FCKLang.NoActiveX )
{
alert( FCKLang.NoActiveX ) ;
FCKLang.NoActiveX = null ;
}
return null ;
}
FCKTools.DisableSelection = function( element )
{
element.unselectable = 'on' ;
var e, i = 0 ;
// The extra () is to avoid a warning with strict error checking. This is ok.
while ( (e = element.all[ i++ ]) )
{
switch ( e.tagName )
{
case 'IFRAME' :
case 'TEXTAREA' :
case 'INPUT' :
case 'SELECT' :
/* Ignore the above tags */
break ;
default :
e.unselectable = 'on' ;
}
}
}
FCKTools.GetScrollPosition = function( relativeWindow )
{
var oDoc = relativeWindow.document ;
// Try with the doc element.
var oPos = { X : oDoc.documentElement.scrollLeft, Y : oDoc.documentElement.scrollTop } ;
if ( oPos.X > 0 || oPos.Y > 0 )
return oPos ;
// If no scroll, try with the body.
return { X : oDoc.body.scrollLeft, Y : oDoc.body.scrollTop } ;
}
FCKTools.AddEventListener = function( sourceObject, eventName, listener )
{
sourceObject.attachEvent( 'on' + eventName, listener ) ;
}
FCKTools.RemoveEventListener = function( sourceObject, eventName, listener )
{
sourceObject.detachEvent( 'on' + eventName, listener ) ;
}
// Listeners attached with this function cannot be detached.
FCKTools.AddEventListenerEx = function( sourceObject, eventName, listener, paramsArray )
{
// Ok... this is a closures party, but is the only way to make it clean of memory leaks.
var o = new Object() ;
o.Source = sourceObject ;
o.Params = paramsArray || [] ; // Memory leak if we have DOM objects here.
o.Listener = function( ev )
{
return listener.apply( o.Source, [ ev ].concat( o.Params ) ) ;
}
if ( FCK.IECleanup )
FCK.IECleanup.AddItem( null, function() { o.Source = null ; o.Params = null ; } ) ;
sourceObject.attachEvent( 'on' + eventName, o.Listener ) ;
sourceObject = null ; // Memory leak cleaner (because of the above closure).
paramsArray = null ; // Memory leak cleaner (because of the above closure).
}
// Returns and object with the "Width" and "Height" properties.
FCKTools.GetViewPaneSize = function( win )
{
var oSizeSource ;
var oDoc = win.document.documentElement ;
if ( oDoc && oDoc.clientWidth ) // IE6 Strict Mode
oSizeSource = oDoc ;
else
oSizeSource = win.document.body ; // Other IEs
if ( oSizeSource )
return { Width : oSizeSource.clientWidth, Height : oSizeSource.clientHeight } ;
else
return { Width : 0, Height : 0 } ;
}
FCKTools.SaveStyles = function( element )
{
var data = FCKTools.ProtectFormStyles( element ) ;
var oSavedStyles = new Object() ;
if ( element.className.length > 0 )
{
oSavedStyles.Class = element.className ;
element.className = '' ;
}
var sInlineStyle = element.style.cssText ;
if ( sInlineStyle.length > 0 )
{
oSavedStyles.Inline = sInlineStyle ;
element.style.cssText = '' ;
}
FCKTools.RestoreFormStyles( element, data ) ;
return oSavedStyles ;
}
FCKTools.RestoreStyles = function( element, savedStyles )
{
var data = FCKTools.ProtectFormStyles( element ) ;
element.className = savedStyles.Class || '' ;
element.style.cssText = savedStyles.Inline || '' ;
FCKTools.RestoreFormStyles( element, data ) ;
}
FCKTools.RegisterDollarFunction = function( targetWindow )
{
targetWindow.$ = targetWindow.document.getElementById ;
}
FCKTools.AppendElement = function( target, elementName )
{
return target.appendChild( this.GetElementDocument( target ).createElement( elementName ) ) ;
}
// This function may be used by Regex replacements.
FCKTools.ToLowerCase = function( strValue )
{
return strValue.toLowerCase() ;
}
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* Toolbar items definitions.
*/
var FCKToolbarItems = new Object() ;
FCKToolbarItems.LoadedItems = new Object() ;
FCKToolbarItems.RegisterItem = function( itemName, item )
{
this.LoadedItems[ itemName ] = item ;
}
FCKToolbarItems.GetItem = function( itemName )
{
var oItem = FCKToolbarItems.LoadedItems[ itemName ] ;
if ( oItem )
return oItem ;
switch ( itemName )
{
case 'Source' : oItem = new FCKToolbarButton( 'Source' , FCKLang.Source, null, FCK_TOOLBARITEM_ICONTEXT, true, true, 1 ) ; break ;
case 'DocProps' : oItem = new FCKToolbarButton( 'DocProps' , FCKLang.DocProps, null, null, null, null, 2 ) ; break ;
case 'Save' : oItem = new FCKToolbarButton( 'Save' , FCKLang.Save, null, null, true, null, 3 ) ; break ;
case 'NewPage' : oItem = new FCKToolbarButton( 'NewPage' , FCKLang.NewPage, null, null, true, null, 4 ) ; break ;
case 'Preview' : oItem = new FCKToolbarButton( 'Preview' , FCKLang.Preview, null, null, true, null, 5 ) ; break ;
case 'Templates' : oItem = new FCKToolbarButton( 'Templates' , FCKLang.Templates, null, null, null, null, 6 ) ; break ;
case 'About' : oItem = new FCKToolbarButton( 'About' , FCKLang.About, null, null, true, null, 47 ) ; break ;
case 'Cut' : oItem = new FCKToolbarButton( 'Cut' , FCKLang.Cut, null, null, false, true, 7 ) ; break ;
case 'Copy' : oItem = new FCKToolbarButton( 'Copy' , FCKLang.Copy, null, null, false, true, 8 ) ; break ;
case 'Paste' : oItem = new FCKToolbarButton( 'Paste' , FCKLang.Paste, null, null, false, true, 9 ) ; break ;
case 'PasteText' : oItem = new FCKToolbarButton( 'PasteText' , FCKLang.PasteText, null, null, false, true, 10 ) ; break ;
case 'PasteWord' : oItem = new FCKToolbarButton( 'PasteWord' , FCKLang.PasteWord, null, null, false, true, 11 ) ; break ;
case 'Print' : oItem = new FCKToolbarButton( 'Print' , FCKLang.Print, null, null, false, true, 12 ) ; break ;
case 'SpellCheck' : oItem = new FCKToolbarButton( 'SpellCheck', FCKLang.SpellCheck, null, null, null, null, 13 ) ; break ;
case 'Undo' : oItem = new FCKToolbarButton( 'Undo' , FCKLang.Undo, null, null, false, true, 14 ) ; break ;
case 'Redo' : oItem = new FCKToolbarButton( 'Redo' , FCKLang.Redo, null, null, false, true, 15 ) ; break ;
case 'SelectAll' : oItem = new FCKToolbarButton( 'SelectAll' , FCKLang.SelectAll, null, null, true, null, 18 ) ; break ;
case 'RemoveFormat' : oItem = new FCKToolbarButton( 'RemoveFormat', FCKLang.RemoveFormat, null, null, false, true, 19 ) ; break ;
case 'FitWindow' : oItem = new FCKToolbarButton( 'FitWindow' , FCKLang.FitWindow, null, null, true, true, 66 ) ; break ;
case 'Bold' : oItem = new FCKToolbarButton( 'Bold' , FCKLang.Bold, null, null, false, true, 20 ) ; break ;
case 'Italic' : oItem = new FCKToolbarButton( 'Italic' , FCKLang.Italic, null, null, false, true, 21 ) ; break ;
case 'Underline' : oItem = new FCKToolbarButton( 'Underline' , FCKLang.Underline, null, null, false, true, 22 ) ; break ;
case 'StrikeThrough' : oItem = new FCKToolbarButton( 'StrikeThrough' , FCKLang.StrikeThrough, null, null, false, true, 23 ) ; break ;
case 'Subscript' : oItem = new FCKToolbarButton( 'Subscript' , FCKLang.Subscript, null, null, false, true, 24 ) ; break ;
case 'Superscript' : oItem = new FCKToolbarButton( 'Superscript' , FCKLang.Superscript, null, null, false, true, 25 ) ; break ;
case 'OrderedList' : oItem = new FCKToolbarButton( 'InsertOrderedList' , FCKLang.NumberedListLbl, FCKLang.NumberedList, null, false, true, 26 ) ; break ;
case 'UnorderedList' : oItem = new FCKToolbarButton( 'InsertUnorderedList' , FCKLang.BulletedListLbl, FCKLang.BulletedList, null, false, true, 27 ) ; break ;
case 'Outdent' : oItem = new FCKToolbarButton( 'Outdent' , FCKLang.DecreaseIndent, null, null, false, true, 28 ) ; break ;
case 'Indent' : oItem = new FCKToolbarButton( 'Indent' , FCKLang.IncreaseIndent, null, null, false, true, 29 ) ; break ;
case 'Blockquote' : oItem = new FCKToolbarButton( 'Blockquote' , FCKLang.Blockquote, null, null, false, true, 73 ) ; break ;
case 'CreateDiv' : oItem = new FCKToolbarButton( 'CreateDiv' , FCKLang.CreateDiv, null, null, false, true, 74 ) ; break ;
case 'Link' : oItem = new FCKToolbarButton( 'Link' , FCKLang.InsertLinkLbl, FCKLang.InsertLink, null, false, true, 34 ) ; break ;
case 'Unlink' : oItem = new FCKToolbarButton( 'Unlink' , FCKLang.RemoveLink, null, null, false, true, 35 ) ; break ;
case 'Anchor' : oItem = new FCKToolbarButton( 'Anchor' , FCKLang.Anchor, null, null, null, null, 36 ) ; break ;
case 'Image' : oItem = new FCKToolbarButton( 'Image' , FCKLang.InsertImageLbl, FCKLang.InsertImage, null, false, true, 37 ) ; break ;
case 'Flash' : oItem = new FCKToolbarButton( 'Flash' , FCKLang.InsertFlashLbl, FCKLang.InsertFlash, null, false, true, 38 ) ; break ;
case 'Table' : oItem = new FCKToolbarButton( 'Table' , FCKLang.InsertTableLbl, FCKLang.InsertTable, null, false, true, 39 ) ; break ;
case 'SpecialChar' : oItem = new FCKToolbarButton( 'SpecialChar' , FCKLang.InsertSpecialCharLbl, FCKLang.InsertSpecialChar, null, false, true, 42 ) ; break ;
case 'Smiley' : oItem = new FCKToolbarButton( 'Smiley' , FCKLang.InsertSmileyLbl, FCKLang.InsertSmiley, null, false, true, 41 ) ; break ;
case 'PageBreak' : oItem = new FCKToolbarButton( 'PageBreak' , FCKLang.PageBreakLbl, FCKLang.PageBreak, null, false, true, 43 ) ; break ;
case 'Rule' : oItem = new FCKToolbarButton( 'Rule' , FCKLang.InsertLineLbl, FCKLang.InsertLine, null, false, true, 40 ) ; break ;
case 'JustifyLeft' : oItem = new FCKToolbarButton( 'JustifyLeft' , FCKLang.LeftJustify, null, null, false, true, 30 ) ; break ;
case 'JustifyCenter' : oItem = new FCKToolbarButton( 'JustifyCenter' , FCKLang.CenterJustify, null, null, false, true, 31 ) ; break ;
case 'JustifyRight' : oItem = new FCKToolbarButton( 'JustifyRight' , FCKLang.RightJustify, null, null, false, true, 32 ) ; break ;
case 'JustifyFull' : oItem = new FCKToolbarButton( 'JustifyFull' , FCKLang.BlockJustify, null, null, false, true, 33 ) ; break ;
case 'Style' : oItem = new FCKToolbarStyleCombo() ; break ;
case 'FontName' : oItem = new FCKToolbarFontsCombo() ; break ;
case 'FontSize' : oItem = new FCKToolbarFontSizeCombo() ; break ;
case 'FontFormat' : oItem = new FCKToolbarFontFormatCombo() ; break ;
case 'TextColor' : oItem = new FCKToolbarPanelButton( 'TextColor', FCKLang.TextColor, null, null, 45 ) ; break ;
case 'BGColor' : oItem = new FCKToolbarPanelButton( 'BGColor' , FCKLang.BGColor, null, null, 46 ) ; break ;
case 'Find' : oItem = new FCKToolbarButton( 'Find' , FCKLang.Find, null, null, null, null, 16 ) ; break ;
case 'Replace' : oItem = new FCKToolbarButton( 'Replace' , FCKLang.Replace, null, null, null, null, 17 ) ; break ;
case 'Form' : oItem = new FCKToolbarButton( 'Form' , FCKLang.Form, null, null, null, null, 48 ) ; break ;
case 'Checkbox' : oItem = new FCKToolbarButton( 'Checkbox' , FCKLang.Checkbox, null, null, null, null, 49 ) ; break ;
case 'Radio' : oItem = new FCKToolbarButton( 'Radio' , FCKLang.RadioButton, null, null, null, null, 50 ) ; break ;
case 'TextField' : oItem = new FCKToolbarButton( 'TextField' , FCKLang.TextField, null, null, null, null, 51 ) ; break ;
case 'Textarea' : oItem = new FCKToolbarButton( 'Textarea' , FCKLang.Textarea, null, null, null, null, 52 ) ; break ;
case 'HiddenField' : oItem = new FCKToolbarButton( 'HiddenField' , FCKLang.HiddenField, null, null, null, null, 56 ) ; break ;
case 'Button' : oItem = new FCKToolbarButton( 'Button' , FCKLang.Button, null, null, null, null, 54 ) ; break ;
case 'Select' : oItem = new FCKToolbarButton( 'Select' , FCKLang.SelectionField, null, null, null, null, 53 ) ; break ;
case 'ImageButton' : oItem = new FCKToolbarButton( 'ImageButton' , FCKLang.ImageButton, null, null, null, null, 55 ) ; break ;
case 'ShowBlocks' : oItem = new FCKToolbarButton( 'ShowBlocks' , FCKLang.ShowBlocks, null, null, null, true, 72 ) ; break ;
default:
alert( FCKLang.UnknownToolbarItem.replace( /%1/g, itemName ) ) ;
return null ;
}
FCKToolbarItems.LoadedItems[ itemName ] = oItem ;
return oItem ;
}
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* Defines the FCKXHtml object, responsible for the XHTML operations.
*/
var FCKXHtml = new Object() ;
FCKXHtml.CurrentJobNum = 0 ;
FCKXHtml.GetXHTML = function( node, includeNode, format )
{
FCKDomTools.CheckAndRemovePaddingNode( FCKTools.GetElementDocument( node ), FCKConfig.EnterMode ) ;
FCKXHtmlEntities.Initialize() ;
// Set the correct entity to use for empty blocks.
this._NbspEntity = ( FCKConfig.ProcessHTMLEntities? 'nbsp' : '#160' ) ;
// Save the current IsDirty state. The XHTML processor may change the
// original HTML, dirtying it.
var bIsDirty = FCK.IsDirty() ;
// Special blocks are blocks of content that remain untouched during the
// process. It is used for SCRIPTs and STYLEs.
FCKXHtml.SpecialBlocks = new Array() ;
// Create the XML DOMDocument object.
this.XML = FCKTools.CreateXmlObject( 'DOMDocument' ) ;
// Add a root element that holds all child nodes.
this.MainNode = this.XML.appendChild( this.XML.createElement( 'xhtml' ) ) ;
FCKXHtml.CurrentJobNum++ ;
// var dTimer = new Date() ;
if ( includeNode )
this._AppendNode( this.MainNode, node ) ;
else
this._AppendChildNodes( this.MainNode, node, false ) ;
// Get the resulting XHTML as a string.
var sXHTML = this._GetMainXmlString() ;
// alert( 'Time: ' + ( ( ( new Date() ) - dTimer ) ) + ' ms' ) ;
this.XML = null ;
// Safari adds xmlns="http://www.w3.org/1999/xhtml" to the root node (#963)
if ( FCKBrowserInfo.IsSafari )
sXHTML = sXHTML.replace( /^<xhtml.*?>/, '<xhtml>' ) ;
// Strip the "XHTML" root node.
sXHTML = sXHTML.substr( 7, sXHTML.length - 15 ).Trim() ;
// According to the doctype set the proper end for self-closing tags
// HTML: <br>
// XHTML: Add a space, like <br/> -> <br />
if (FCKConfig.DocType.length > 0 && FCKRegexLib.HtmlDocType.test( FCKConfig.DocType ) )
sXHTML = sXHTML.replace( FCKRegexLib.SpaceNoClose, '>');
else
sXHTML = sXHTML.replace( FCKRegexLib.SpaceNoClose, ' />');
if ( FCKConfig.ForceSimpleAmpersand )
sXHTML = sXHTML.replace( FCKRegexLib.ForceSimpleAmpersand, '&' ) ;
if ( format )
sXHTML = FCKCodeFormatter.Format( sXHTML ) ;
// Now we put back the SpecialBlocks contents.
for ( var i = 0 ; i < FCKXHtml.SpecialBlocks.length ; i++ )
{
var oRegex = new RegExp( '___FCKsi___' + i ) ;
sXHTML = sXHTML.replace( oRegex, FCKXHtml.SpecialBlocks[i] ) ;
}
// Replace entities marker with the ampersand.
sXHTML = sXHTML.replace( FCKRegexLib.GeckoEntitiesMarker, '&' ) ;
// Restore the IsDirty state if it was not dirty.
if ( !bIsDirty )
FCK.ResetIsDirty() ;
FCKDomTools.EnforcePaddingNode( FCKTools.GetElementDocument( node ), FCKConfig.EnterMode ) ;
return sXHTML ;
}
FCKXHtml._AppendAttribute = function( xmlNode, attributeName, attributeValue )
{
try
{
if ( attributeValue == undefined || attributeValue == null )
attributeValue = '' ;
else if ( attributeValue.replace )
{
if ( FCKConfig.ForceSimpleAmpersand )
attributeValue = attributeValue.replace( /&/g, '___FCKAmp___' ) ;
// Entities must be replaced in the attribute values.
attributeValue = attributeValue.replace( FCKXHtmlEntities.EntitiesRegex, FCKXHtml_GetEntity ) ;
}
// Create the attribute.
var oXmlAtt = this.XML.createAttribute( attributeName ) ;
oXmlAtt.value = attributeValue ;
// Set the attribute in the node.
xmlNode.attributes.setNamedItem( oXmlAtt ) ;
}
catch (e)
{}
}
FCKXHtml._AppendChildNodes = function( xmlNode, htmlNode, isBlockElement )
{
var oNode = htmlNode.firstChild ;
while ( oNode )
{
this._AppendNode( xmlNode, oNode ) ;
oNode = oNode.nextSibling ;
}
// Trim block elements. This is also needed to avoid Firefox leaving extra
// BRs at the end of them.
if ( isBlockElement && htmlNode.tagName && htmlNode.tagName.toLowerCase() != 'pre' )
{
FCKDomTools.TrimNode( xmlNode ) ;
if ( FCKConfig.FillEmptyBlocks )
{
var lastChild = xmlNode.lastChild ;
if ( lastChild && lastChild.nodeType == 1 && lastChild.nodeName == 'br' )
this._AppendEntity( xmlNode, this._NbspEntity ) ;
}
}
// If the resulting node is empty.
if ( xmlNode.childNodes.length == 0 )
{
if ( isBlockElement && FCKConfig.FillEmptyBlocks )
{
this._AppendEntity( xmlNode, this._NbspEntity ) ;
return xmlNode ;
}
var sNodeName = xmlNode.nodeName ;
// Some inline elements are required to have something inside (span, strong, etc...).
if ( FCKListsLib.InlineChildReqElements[ sNodeName ] )
return null ;
// We can't use short representation of empty elements that are not marked
// as empty in th XHTML DTD.
if ( !FCKListsLib.EmptyElements[ sNodeName ] )
xmlNode.appendChild( this.XML.createTextNode('') ) ;
}
return xmlNode ;
}
FCKXHtml._AppendNode = function( xmlNode, htmlNode )
{
if ( !htmlNode )
return false ;
switch ( htmlNode.nodeType )
{
// Element Node.
case 1 :
// If we detect a <br> inside a <pre> in Gecko, turn it into a line break instead.
// This is a workaround for the Gecko bug here: https://bugzilla.mozilla.org/show_bug.cgi?id=92921
if ( FCKBrowserInfo.IsGecko
&& htmlNode.tagName.toLowerCase() == 'br'
&& htmlNode.parentNode.tagName.toLowerCase() == 'pre' )
{
var val = '\r' ;
if ( htmlNode == htmlNode.parentNode.firstChild )
val += '\r' ;
return FCKXHtml._AppendNode( xmlNode, this.XML.createTextNode( val ) ) ;
}
// Here we found an element that is not the real element, but a
// fake one (like the Flash placeholder image), so we must get the real one.
if ( htmlNode.getAttribute('_fckfakelement') )
return FCKXHtml._AppendNode( xmlNode, FCK.GetRealElement( htmlNode ) ) ;
// Ignore bogus BR nodes in the DOM.
if ( FCKBrowserInfo.IsGecko &&
( htmlNode.hasAttribute('_moz_editor_bogus_node') || htmlNode.getAttribute( 'type' ) == '_moz' ) )
{
if ( htmlNode.nextSibling )
return false ;
else
{
htmlNode.removeAttribute( '_moz_editor_bogus_node' ) ;
htmlNode.removeAttribute( 'type' ) ;
}
}
// This is for elements that are instrumental to FCKeditor and
// must be removed from the final HTML.
if ( htmlNode.getAttribute('_fcktemp') )
return false ;
// Get the element name.
var sNodeName = htmlNode.tagName.toLowerCase() ;
if ( FCKBrowserInfo.IsIE )
{
// IE doens't include the scope name in the nodeName. So, add the namespace.
if ( htmlNode.scopeName && htmlNode.scopeName != 'HTML' && htmlNode.scopeName != 'FCK' )
sNodeName = htmlNode.scopeName.toLowerCase() + ':' + sNodeName ;
}
else
{
if ( sNodeName.StartsWith( 'fck:' ) )
sNodeName = sNodeName.Remove( 0,4 ) ;
}
// Check if the node name is valid, otherwise ignore this tag.
// If the nodeName starts with a slash, it is a orphan closing tag.
// On some strange cases, the nodeName is empty, even if the node exists.
if ( !FCKRegexLib.ElementName.test( sNodeName ) )
return false ;
// The already processed nodes must be marked to avoid then to be duplicated (bad formatted HTML).
// So here, the "mark" is checked... if the element is Ok, then mark it.
if ( htmlNode._fckxhtmljob && htmlNode._fckxhtmljob == FCKXHtml.CurrentJobNum )
return false ;
var oNode = this.XML.createElement( sNodeName ) ;
// Add all attributes.
FCKXHtml._AppendAttributes( xmlNode, htmlNode, oNode, sNodeName ) ;
htmlNode._fckxhtmljob = FCKXHtml.CurrentJobNum ;
// Tag specific processing.
var oTagProcessor = FCKXHtml.TagProcessors[ sNodeName ] ;
if ( oTagProcessor )
oNode = oTagProcessor( oNode, htmlNode, xmlNode ) ;
else
oNode = this._AppendChildNodes( oNode, htmlNode, Boolean( FCKListsLib.NonEmptyBlockElements[ sNodeName ] ) ) ;
if ( !oNode )
return false ;
xmlNode.appendChild( oNode ) ;
break ;
// Text Node.
case 3 :
if ( htmlNode.parentNode && htmlNode.parentNode.nodeName.IEquals( 'pre' ) )
return this._AppendTextNode( xmlNode, htmlNode.nodeValue ) ;
return this._AppendTextNode( xmlNode, htmlNode.nodeValue.ReplaceNewLineChars(' ') ) ;
// Comment
case 8 :
// IE catches the <!DOTYPE ... > as a comment, but it has no
// innerHTML, so we can catch it, and ignore it.
if ( FCKBrowserInfo.IsIE && !htmlNode.innerHTML )
break ;
try { xmlNode.appendChild( this.XML.createComment( htmlNode.nodeValue ) ) ; }
catch (e) { /* Do nothing... probably this is a wrong format comment. */ }
break ;
// Unknown Node type.
default :
xmlNode.appendChild( this.XML.createComment( "Element not supported - Type: " + htmlNode.nodeType + " Name: " + htmlNode.nodeName ) ) ;
break ;
}
return true ;
}
// Append an item to the SpecialBlocks array and returns the tag to be used.
FCKXHtml._AppendSpecialItem = function( item )
{
return '___FCKsi___' + FCKXHtml.SpecialBlocks.AddItem( item ) ;
}
FCKXHtml._AppendEntity = function( xmlNode, entity )
{
xmlNode.appendChild( this.XML.createTextNode( '#?-:' + entity + ';' ) ) ;
}
FCKXHtml._AppendTextNode = function( targetNode, textValue )
{
var bHadText = textValue.length > 0 ;
if ( bHadText )
targetNode.appendChild( this.XML.createTextNode( textValue.replace( FCKXHtmlEntities.EntitiesRegex, FCKXHtml_GetEntity ) ) ) ;
return bHadText ;
}
// Retrieves a entity (internal format) for a given character.
function FCKXHtml_GetEntity( character )
{
// We cannot simply place the entities in the text, because the XML parser
// will translate & to &. So we use a temporary marker which is replaced
// in the end of the processing.
var sEntity = FCKXHtmlEntities.Entities[ character ] || ( '#' + character.charCodeAt(0) ) ;
return '#?-:' + sEntity + ';' ;
}
// An object that hold tag specific operations.
FCKXHtml.TagProcessors =
{
a : function( node, htmlNode )
{
// Firefox may create empty tags when deleting the selection in some special cases (SF-BUG 1556878).
if ( htmlNode.innerHTML.Trim().length == 0 && !htmlNode.name )
return false ;
var sSavedUrl = htmlNode.getAttribute( '_fcksavedurl' ) ;
if ( sSavedUrl != null )
FCKXHtml._AppendAttribute( node, 'href', sSavedUrl ) ;
// Anchors with content has been marked with an additional class, now we must remove it.
if ( FCKBrowserInfo.IsIE )
{
// Buggy IE, doesn't copy the name of changed anchors.
if ( htmlNode.name )
FCKXHtml._AppendAttribute( node, 'name', htmlNode.name ) ;
}
node = FCKXHtml._AppendChildNodes( node, htmlNode, false ) ;
return node ;
},
area : function( node, htmlNode )
{
var sSavedUrl = htmlNode.getAttribute( '_fcksavedurl' ) ;
if ( sSavedUrl != null )
FCKXHtml._AppendAttribute( node, 'href', sSavedUrl ) ;
// IE ignores the "COORDS" and "SHAPE" attribute so we must add it manually.
if ( FCKBrowserInfo.IsIE )
{
if ( ! node.attributes.getNamedItem( 'coords' ) )
{
var sCoords = htmlNode.getAttribute( 'coords', 2 ) ;
if ( sCoords && sCoords != '0,0,0' )
FCKXHtml._AppendAttribute( node, 'coords', sCoords ) ;
}
if ( ! node.attributes.getNamedItem( 'shape' ) )
{
var sShape = htmlNode.getAttribute( 'shape', 2 ) ;
if ( sShape && sShape.length > 0 )
FCKXHtml._AppendAttribute( node, 'shape', sShape.toLowerCase() ) ;
}
}
return node ;
},
body : function( node, htmlNode )
{
node = FCKXHtml._AppendChildNodes( node, htmlNode, false ) ;
// Remove spellchecker attributes added for Firefox when converting to HTML code (Bug #1351).
node.removeAttribute( 'spellcheck' ) ;
return node ;
},
// IE loses contents of iframes, and Gecko does give it back HtmlEncoded
// Note: Opera does lose the content and doesn't provide it in the innerHTML string
iframe : function( node, htmlNode )
{
var sHtml = htmlNode.innerHTML ;
// Gecko does give back the encoded html
if ( FCKBrowserInfo.IsGecko )
sHtml = FCKTools.HTMLDecode( sHtml );
// Remove the saved urls here as the data won't be processed as nodes
sHtml = sHtml.replace( /\s_fcksavedurl="[^"]*"/g, '' ) ;
node.appendChild( FCKXHtml.XML.createTextNode( FCKXHtml._AppendSpecialItem( sHtml ) ) ) ;
return node ;
},
img : function( node, htmlNode )
{
// The "ALT" attribute is required in XHTML.
if ( ! node.attributes.getNamedItem( 'alt' ) )
FCKXHtml._AppendAttribute( node, 'alt', '' ) ;
var sSavedUrl = htmlNode.getAttribute( '_fcksavedurl' ) ;
if ( sSavedUrl != null )
FCKXHtml._AppendAttribute( node, 'src', sSavedUrl ) ;
// Bug #768 : If the width and height are defined inline CSS,
// don't define it again in the HTML attributes.
if ( htmlNode.style.width )
node.removeAttribute( 'width' ) ;
if ( htmlNode.style.height )
node.removeAttribute( 'height' ) ;
return node ;
},
// Fix orphaned <li> nodes (Bug #503).
li : function( node, htmlNode, targetNode )
{
// If the XML parent node is already a <ul> or <ol>, then add the <li> as usual.
if ( targetNode.nodeName.IEquals( ['ul', 'ol'] ) )
return FCKXHtml._AppendChildNodes( node, htmlNode, true ) ;
var newTarget = FCKXHtml.XML.createElement( 'ul' ) ;
// Reset the _fckxhtmljob so the HTML node is processed again.
htmlNode._fckxhtmljob = null ;
// Loop through all sibling LIs, adding them to the <ul>.
do
{
FCKXHtml._AppendNode( newTarget, htmlNode ) ;
// Look for the next element following this <li>.
do
{
htmlNode = FCKDomTools.GetNextSibling( htmlNode ) ;
} while ( htmlNode && htmlNode.nodeType == 3 && htmlNode.nodeValue.Trim().length == 0 )
} while ( htmlNode && htmlNode.nodeName.toLowerCase() == 'li' )
return newTarget ;
},
// Fix nested <ul> and <ol>.
ol : function( node, htmlNode, targetNode )
{
if ( htmlNode.innerHTML.Trim().length == 0 )
return false ;
var ePSibling = targetNode.lastChild ;
if ( ePSibling && ePSibling.nodeType == 3 )
ePSibling = ePSibling.previousSibling ;
if ( ePSibling && ePSibling.nodeName.toUpperCase() == 'LI' )
{
htmlNode._fckxhtmljob = null ;
FCKXHtml._AppendNode( ePSibling, htmlNode ) ;
return false ;
}
node = FCKXHtml._AppendChildNodes( node, htmlNode ) ;
return node ;
},
pre : function ( node, htmlNode )
{
var firstChild = htmlNode.firstChild ;
if ( firstChild && firstChild.nodeType == 3 )
node.appendChild( FCKXHtml.XML.createTextNode( FCKXHtml._AppendSpecialItem( '\r\n' ) ) ) ;
FCKXHtml._AppendChildNodes( node, htmlNode, true ) ;
return node ;
},
script : function( node, htmlNode )
{
// The "TYPE" attribute is required in XHTML.
if ( ! node.attributes.getNamedItem( 'type' ) )
FCKXHtml._AppendAttribute( node, 'type', 'text/javascript' ) ;
node.appendChild( FCKXHtml.XML.createTextNode( FCKXHtml._AppendSpecialItem( htmlNode.text ) ) ) ;
return node ;
},
span : function( node, htmlNode )
{
// Firefox may create empty tags when deleting the selection in some special cases (SF-BUG 1084404).
if ( htmlNode.innerHTML.length == 0 )
return false ;
node = FCKXHtml._AppendChildNodes( node, htmlNode, false ) ;
return node ;
},
style : function( node, htmlNode )
{
// The "TYPE" attribute is required in XHTML.
if ( ! node.attributes.getNamedItem( 'type' ) )
FCKXHtml._AppendAttribute( node, 'type', 'text/css' ) ;
var cssText = htmlNode.innerHTML ;
if ( FCKBrowserInfo.IsIE ) // Bug #403 : IE always appends a \r\n to the beginning of StyleNode.innerHTML
cssText = cssText.replace( /^(\r\n|\n|\r)/, '' ) ;
node.appendChild( FCKXHtml.XML.createTextNode( FCKXHtml._AppendSpecialItem( cssText ) ) ) ;
return node ;
},
title : function( node, htmlNode )
{
node.appendChild( FCKXHtml.XML.createTextNode( FCK.EditorDocument.title ) ) ;
return node ;
}
} ;
FCKXHtml.TagProcessors.ul = FCKXHtml.TagProcessors.ol ;
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* Creates and initializes the FCKConfig object.
*/
var FCKConfig = FCK.Config = new Object() ;
/*
For the next major version (probably 3.0) we should move all this stuff to
another dedicated object and leave FCKConfig as a holder object for settings only).
*/
// Editor Base Path
if ( document.location.protocol == 'file:' )
{
FCKConfig.BasePath = decodeURIComponent( document.location.pathname.substr(1) ) ;
FCKConfig.BasePath = FCKConfig.BasePath.replace( /\\/gi, '/' ) ;
// The way to address local files is different according to the OS.
// In Windows it is file:// but in MacOs it is file:/// so let's get it automatically
var sFullProtocol = document.location.href.match( /^(file\:\/{2,3})/ )[1] ;
// #945 Opera does strange things with files loaded from the disk, and it fails in Mac to load xml files
if ( FCKBrowserInfo.IsOpera )
sFullProtocol += 'localhost/' ;
FCKConfig.BasePath = sFullProtocol + FCKConfig.BasePath.substring( 0, FCKConfig.BasePath.lastIndexOf( '/' ) + 1) ;
}
else
FCKConfig.BasePath = document.location.protocol + '//' + document.location.host +
document.location.pathname.substring( 0, document.location.pathname.lastIndexOf( '/' ) + 1) ;
FCKConfig.FullBasePath = FCKConfig.BasePath ;
FCKConfig.EditorPath = FCKConfig.BasePath.replace( /editor\/$/, '' ) ;
// There is a bug in Gecko. If the editor is hidden on startup, an error is
// thrown when trying to get the screen dimensions.
try
{
FCKConfig.ScreenWidth = screen.width ;
FCKConfig.ScreenHeight = screen.height ;
}
catch (e)
{
FCKConfig.ScreenWidth = 800 ;
FCKConfig.ScreenHeight = 600 ;
}
// Override the actual configuration values with the values passed throw the
// hidden field "<InstanceName>___Config".
FCKConfig.ProcessHiddenField = function()
{
this.PageConfig = new Object() ;
// Get the hidden field.
var oConfigField = window.parent.document.getElementById( FCK.Name + '___Config' ) ;
// Do nothing if the config field was not defined.
if ( ! oConfigField ) return ;
var aCouples = oConfigField.value.split('&') ;
for ( var i = 0 ; i < aCouples.length ; i++ )
{
if ( aCouples[i].length == 0 )
continue ;
var aConfig = aCouples[i].split( '=' ) ;
var sKey = decodeURIComponent( aConfig[0] ) ;
var sVal = decodeURIComponent( aConfig[1] ) ;
if ( sKey == 'CustomConfigurationsPath' ) // The Custom Config File path must be loaded immediately.
FCKConfig[ sKey ] = sVal ;
else if ( sVal.toLowerCase() == "true" ) // If it is a boolean TRUE.
this.PageConfig[ sKey ] = true ;
else if ( sVal.toLowerCase() == "false" ) // If it is a boolean FALSE.
this.PageConfig[ sKey ] = false ;
else if ( sVal.length > 0 && !isNaN( sVal ) ) // If it is a number.
this.PageConfig[ sKey ] = parseInt( sVal, 10 ) ;
else // In any other case it is a string.
this.PageConfig[ sKey ] = sVal ;
}
}
function FCKConfig_LoadPageConfig()
{
var oPageConfig = FCKConfig.PageConfig ;
for ( var sKey in oPageConfig )
FCKConfig[ sKey ] = oPageConfig[ sKey ] ;
}
function FCKConfig_PreProcess()
{
var oConfig = FCKConfig ;
// Force debug mode if fckdebug=true in the QueryString (main page).
if ( oConfig.AllowQueryStringDebug )
{
try
{
if ( (/fckdebug=true/i).test( window.top.location.search ) )
oConfig.Debug = true ;
}
catch (e) { /* Ignore it. Much probably we are inside a FRAME where the "top" is in another domain (security error). */ }
}
// Certifies that the "PluginsPath" configuration ends with a slash.
if ( !oConfig.PluginsPath.EndsWith('/') )
oConfig.PluginsPath += '/' ;
// If no ToolbarComboPreviewCSS, point it to EditorAreaCSS.
var sComboPreviewCSS = oConfig.ToolbarComboPreviewCSS ;
if ( !sComboPreviewCSS || sComboPreviewCSS.length == 0 )
oConfig.ToolbarComboPreviewCSS = oConfig.EditorAreaCSS ;
// Turn the attributes that will be removed in the RemoveFormat from a string to an array
oConfig.RemoveAttributesArray = (oConfig.RemoveAttributes || '').split( ',' );
if ( !FCKConfig.SkinEditorCSS || FCKConfig.SkinEditorCSS.length == 0 )
FCKConfig.SkinEditorCSS = FCKConfig.SkinPath + 'fck_editor.css' ;
if ( !FCKConfig.SkinDialogCSS || FCKConfig.SkinDialogCSS.length == 0 )
FCKConfig.SkinDialogCSS = FCKConfig.SkinPath + 'fck_dialog.css' ;
}
// Define toolbar sets collection.
FCKConfig.ToolbarSets = new Object() ;
// Defines the plugins collection.
FCKConfig.Plugins = new Object() ;
FCKConfig.Plugins.Items = new Array() ;
FCKConfig.Plugins.Add = function( name, langs, path )
{
FCKConfig.Plugins.Items.AddItem( [name, langs, path] ) ;
}
// FCKConfig.ProtectedSource: object that holds a collection of Regular
// Expressions that defined parts of the raw HTML that must remain untouched
// like custom tags, scripts, server side code, etc...
FCKConfig.ProtectedSource = new Object() ;
// Generates a string used to identify and locate the Protected Tags comments.
FCKConfig.ProtectedSource._CodeTag = (new Date()).valueOf() ;
// Initialize the regex array with the default ones.
FCKConfig.ProtectedSource.RegexEntries = [
// First of any other protection, we must protect all comments to avoid
// loosing them (of course, IE related).
/<!--[\s\S]*?-->/g ,
// Script tags will also be forced to be protected, otherwise IE will execute them.
/<script[\s\S]*?<\/script>/gi,
// <noscript> tags (get lost in IE and messed up in FF).
/<noscript[\s\S]*?<\/noscript>/gi
] ;
FCKConfig.ProtectedSource.Add = function( regexPattern )
{
this.RegexEntries.AddItem( regexPattern ) ;
}
FCKConfig.ProtectedSource.Protect = function( html )
{
var codeTag = this._CodeTag ;
function _Replace( protectedSource )
{
var index = FCKTempBin.AddElement( protectedSource ) ;
return '<!--{' + codeTag + index + '}-->' ;
}
for ( var i = 0 ; i < this.RegexEntries.length ; i++ )
{
html = html.replace( this.RegexEntries[i], _Replace ) ;
}
return html ;
}
FCKConfig.ProtectedSource.Revert = function( html, clearBin )
{
function _Replace( m, opener, index )
{
var protectedValue = clearBin ? FCKTempBin.RemoveElement( index ) : FCKTempBin.Elements[ index ] ;
// There could be protected source inside another one.
return FCKConfig.ProtectedSource.Revert( protectedValue, clearBin ) ;
}
var regex = new RegExp( "(<|<)!--\\{" + this._CodeTag + "(\\d+)\\}--(>|>)", "g" ) ;
return html.replace( regex, _Replace ) ;
}
// Returns a string with the attributes that must be appended to the body
FCKConfig.GetBodyAttributes = function()
{
var bodyAttributes = '' ;
// Add id and class to the body.
if ( this.BodyId && this.BodyId.length > 0 )
bodyAttributes += ' id="' + this.BodyId + '"' ;
if ( this.BodyClass && this.BodyClass.length > 0 )
bodyAttributes += ' class="' + this.BodyClass + '"' ;
return bodyAttributes ;
}
// Sets the body attributes directly on the node
FCKConfig.ApplyBodyAttributes = function( oBody )
{
// Add ID and Class to the body
if ( this.BodyId && this.BodyId.length > 0 )
oBody.id = FCKConfig.BodyId ;
if ( this.BodyClass && this.BodyClass.length > 0 )
oBody.className += ' ' + FCKConfig.BodyClass ;
}
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* Manage table operations (non-IE).
*/
FCKTableHandler.GetSelectedCells = function()
{
var aCells = new Array() ;
var oSelection = FCKSelection.GetSelection() ;
// If the selection is a text.
if ( oSelection.rangeCount == 1 && oSelection.anchorNode.nodeType == 3 )
{
var oParent = FCKTools.GetElementAscensor( oSelection.anchorNode, 'TD,TH' ) ;
if ( oParent )
aCells[0] = oParent ;
return aCells ;
}
for ( var i = 0 ; i < oSelection.rangeCount ; i++ )
{
var oRange = oSelection.getRangeAt(i) ;
var oCell ;
if ( oRange.startContainer.tagName.Equals( 'TD', 'TH' ) )
oCell = oRange.startContainer ;
else
oCell = oRange.startContainer.childNodes[ oRange.startOffset ] ;
if ( oCell.tagName.Equals( 'TD', 'TH' ) )
aCells[aCells.length] = oCell ;
}
return aCells ;
}
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* These are some Regular Expressions used by the editor.
*/
var FCKRegexLib =
{
// This is the Regular expression used by the SetData method for the "'" entity.
AposEntity : /'/gi ,
// Used by the Styles combo to identify styles that can't be applied to text.
ObjectElements : /^(?:IMG|TABLE|TR|TD|TH|INPUT|SELECT|TEXTAREA|HR|OBJECT|A|UL|OL|LI)$/i ,
// List all named commands (commands that can be interpreted by the browser "execCommand" method.
NamedCommands : /^(?:Cut|Copy|Paste|Print|SelectAll|RemoveFormat|Unlink|Undo|Redo|Bold|Italic|Underline|StrikeThrough|Subscript|Superscript|JustifyLeft|JustifyCenter|JustifyRight|JustifyFull|Outdent|Indent|InsertOrderedList|InsertUnorderedList|InsertHorizontalRule)$/i ,
BeforeBody : /(^[\s\S]*\<body[^\>]*\>)/i,
AfterBody : /(\<\/body\>[\s\S]*$)/i,
// Temporary text used to solve some browser specific limitations.
ToReplace : /___fcktoreplace:([\w]+)/ig ,
// Get the META http-equiv attribute from the tag.
MetaHttpEquiv : /http-equiv\s*=\s*["']?([^"' ]+)/i ,
HasBaseTag : /<base /i ,
HasBodyTag : /<body[\s|>]/i ,
HtmlOpener : /<html\s?[^>]*>/i ,
HeadOpener : /<head\s?[^>]*>/i ,
HeadCloser : /<\/head\s*>/i ,
// Temporary classes (Tables without border, Anchors with content) used in IE
FCK_Class : /\s*FCK__[^ ]*(?=\s+|$)/ ,
// Validate element names (it must be in lowercase).
ElementName : /(^[a-z_:][\w.\-:]*\w$)|(^[a-z_]$)/ ,
// Used in conjunction with the FCKConfig.ForceSimpleAmpersand configuration option.
ForceSimpleAmpersand : /___FCKAmp___/g ,
// Get the closing parts of the tags with no closing tags, like <br/>... gets the "/>" part.
SpaceNoClose : /\/>/g ,
// Empty elements may be <p></p> or even a simple opening <p> (see #211).
EmptyParagraph : /^<(p|div|address|h\d|center)(?=[ >])[^>]*>\s*(<\/\1>)?$/ ,
EmptyOutParagraph : /^<(p|div|address|h\d|center)(?=[ >])[^>]*>(?:\s*| )(<\/\1>)?$/ ,
TagBody : /></ ,
GeckoEntitiesMarker : /#\?-\:/g ,
// We look for the "src" and href attribute with the " or ' or without one of
// them. We have to do all in one, otherwise we will have problems with URLs
// like "thumbnail.php?src=someimage.jpg" (SF-BUG 1554141).
ProtectUrlsImg : /<img(?=\s).*?\ssrc=((?:(?:\s*)("|').*?\2)|(?:[^"'][^ >]+))/gi ,
ProtectUrlsA : /<a(?=\s).*?\shref=((?:(?:\s*)("|').*?\2)|(?:[^"'][^ >]+))/gi ,
ProtectUrlsArea : /<area(?=\s).*?\shref=((?:(?:\s*)("|').*?\2)|(?:[^"'][^ >]+))/gi ,
Html4DocType : /HTML 4\.0 Transitional/i ,
DocTypeTag : /<!DOCTYPE[^>]*>/i ,
HtmlDocType : /DTD HTML/ ,
// These regex are used to save the original event attributes in the HTML.
TagsWithEvent : /<[^\>]+ on\w+[\s\r\n]*=[\s\r\n]*?('|")[\s\S]+?\>/g ,
EventAttributes : /\s(on\w+)[\s\r\n]*=[\s\r\n]*?('|")([\s\S]*?)\2/g,
ProtectedEvents : /\s\w+_fckprotectedatt="([^"]+)"/g,
StyleProperties : /\S+\s*:/g,
// [a-zA-Z0-9:]+ seams to be more efficient than [\w:]+
InvalidSelfCloseTags : /(<(?!base|meta|link|hr|br|param|img|area|input)([a-zA-Z0-9:]+)[^>]*)\/>/gi,
// All variables defined in a style attribute or style definition. The variable
// name is returned with $2.
StyleVariableAttName : /#\(\s*("|')(.+?)\1[^\)]*\s*\)/g,
RegExp : /^\/(.*)\/([gim]*)$/,
HtmlTag : /<[^\s<>](?:"[^"]*"|'[^']*'|[^<])*>/
} ;
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* Manage table operations (IE specific).
*/
FCKTableHandler.GetSelectedCells = function()
{
if ( FCKSelection.GetType() == 'Control' )
{
var td = FCKSelection.MoveToAncestorNode( 'TD' ) ;
return td ? [ td ] : [] ;
}
var aCells = new Array() ;
var oRange = FCKSelection.GetSelection().createRange() ;
// var oParent = oRange.parentElement() ;
var oParent = FCKSelection.GetParentElement() ;
if ( oParent && oParent.tagName.Equals( 'TD', 'TH' ) )
aCells[0] = oParent ;
else
{
oParent = FCKSelection.MoveToAncestorNode( 'TABLE' ) ;
if ( oParent )
{
// Loops throw all cells checking if the cell is, or part of it, is inside the selection
// and then add it to the selected cells collection.
for ( var i = 0 ; i < oParent.cells.length ; i++ )
{
var oCellRange = FCK.EditorDocument.body.createTextRange() ;
oCellRange.moveToElementText( oParent.cells[i] ) ;
if ( oRange.inRange( oCellRange )
|| ( oRange.compareEndPoints('StartToStart',oCellRange) >= 0 && oRange.compareEndPoints('StartToEnd',oCellRange) <= 0 )
|| ( oRange.compareEndPoints('EndToStart',oCellRange) >= 0 && oRange.compareEndPoints('EndToEnd',oCellRange) <= 0 ) )
{
aCells[aCells.length] = oParent.cells[i] ;
}
}
}
}
return aCells ;
}
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* Utility functions to work with the DOM.
*/
var FCKDomTools =
{
/**
* Move all child nodes from one node to another.
*/
MoveChildren : function( source, target, toTargetStart )
{
if ( source == target )
return ;
var eChild ;
if ( toTargetStart )
{
while ( (eChild = source.lastChild) )
target.insertBefore( source.removeChild( eChild ), target.firstChild ) ;
}
else
{
while ( (eChild = source.firstChild) )
target.appendChild( source.removeChild( eChild ) ) ;
}
},
MoveNode : function( source, target, toTargetStart )
{
if ( toTargetStart )
target.insertBefore( FCKDomTools.RemoveNode( source ), target.firstChild ) ;
else
target.appendChild( FCKDomTools.RemoveNode( source ) ) ;
},
// Remove blank spaces from the beginning and the end of the contents of a node.
TrimNode : function( node )
{
this.LTrimNode( node ) ;
this.RTrimNode( node ) ;
},
LTrimNode : function( node )
{
var eChildNode ;
while ( (eChildNode = node.firstChild) )
{
if ( eChildNode.nodeType == 3 )
{
var sTrimmed = eChildNode.nodeValue.LTrim() ;
var iOriginalLength = eChildNode.nodeValue.length ;
if ( sTrimmed.length == 0 )
{
node.removeChild( eChildNode ) ;
continue ;
}
else if ( sTrimmed.length < iOriginalLength )
{
eChildNode.splitText( iOriginalLength - sTrimmed.length ) ;
node.removeChild( node.firstChild ) ;
}
}
break ;
}
},
RTrimNode : function( node )
{
var eChildNode ;
while ( (eChildNode = node.lastChild) )
{
if ( eChildNode.nodeType == 3 )
{
var sTrimmed = eChildNode.nodeValue.RTrim() ;
var iOriginalLength = eChildNode.nodeValue.length ;
if ( sTrimmed.length == 0 )
{
// If the trimmed text node is empty, just remove it.
// Use "eChildNode.parentNode" instead of "node" to avoid IE bug (#81).
eChildNode.parentNode.removeChild( eChildNode ) ;
continue ;
}
else if ( sTrimmed.length < iOriginalLength )
{
// If the trimmed text length is less than the original
// length, strip all spaces from the end by splitting
// the text and removing the resulting useless node.
eChildNode.splitText( sTrimmed.length ) ;
// Use "node.lastChild.parentNode" instead of "node" to avoid IE bug (#81).
node.lastChild.parentNode.removeChild( node.lastChild ) ;
}
}
break ;
}
if ( !FCKBrowserInfo.IsIE && !FCKBrowserInfo.IsOpera )
{
eChildNode = node.lastChild ;
if ( eChildNode && eChildNode.nodeType == 1 && eChildNode.nodeName.toLowerCase() == 'br' )
{
// Use "eChildNode.parentNode" instead of "node" to avoid IE bug (#324).
eChildNode.parentNode.removeChild( eChildNode ) ;
}
}
},
RemoveNode : function( node, excludeChildren )
{
if ( excludeChildren )
{
// Move all children before the node.
var eChild ;
while ( (eChild = node.firstChild) )
node.parentNode.insertBefore( node.removeChild( eChild ), node ) ;
}
return node.parentNode.removeChild( node ) ;
},
GetFirstChild : function( node, childNames )
{
// If childNames is a string, transform it in a Array.
if ( typeof ( childNames ) == 'string' )
childNames = [ childNames ] ;
var eChild = node.firstChild ;
while( eChild )
{
if ( eChild.nodeType == 1 && eChild.tagName.Equals.apply( eChild.tagName, childNames ) )
return eChild ;
eChild = eChild.nextSibling ;
}
return null ;
},
GetLastChild : function( node, childNames )
{
// If childNames is a string, transform it in a Array.
if ( typeof ( childNames ) == 'string' )
childNames = [ childNames ] ;
var eChild = node.lastChild ;
while( eChild )
{
if ( eChild.nodeType == 1 && ( !childNames || eChild.tagName.Equals( childNames ) ) )
return eChild ;
eChild = eChild.previousSibling ;
}
return null ;
},
/*
* Gets the previous element (nodeType=1) in the source order. Returns
* "null" If no element is found.
* @param {Object} currentNode The node to start searching from.
* @param {Boolean} ignoreSpaceTextOnly Sets how text nodes will be
* handled. If set to "true", only white spaces text nodes
* will be ignored, while non white space text nodes will stop
* the search, returning null. If "false" or omitted, all
* text nodes are ignored.
* @param {string[]} stopSearchElements An array of element names that
* will cause the search to stop when found, returning null.
* May be omitted (or null).
* @param {string[]} ignoreElements An array of element names that
* must be ignored during the search.
*/
GetPreviousSourceElement : function( currentNode, ignoreSpaceTextOnly, stopSearchElements, ignoreElements )
{
if ( !currentNode )
return null ;
if ( stopSearchElements && currentNode.nodeType == 1 && currentNode.nodeName.IEquals( stopSearchElements ) )
return null ;
if ( currentNode.previousSibling )
currentNode = currentNode.previousSibling ;
else
return this.GetPreviousSourceElement( currentNode.parentNode, ignoreSpaceTextOnly, stopSearchElements, ignoreElements ) ;
while ( currentNode )
{
if ( currentNode.nodeType == 1 )
{
if ( stopSearchElements && currentNode.nodeName.IEquals( stopSearchElements ) )
break ;
if ( !ignoreElements || !currentNode.nodeName.IEquals( ignoreElements ) )
return currentNode ;
}
else if ( ignoreSpaceTextOnly && currentNode.nodeType == 3 && currentNode.nodeValue.RTrim().length > 0 )
break ;
if ( currentNode.lastChild )
currentNode = currentNode.lastChild ;
else
return this.GetPreviousSourceElement( currentNode, ignoreSpaceTextOnly, stopSearchElements, ignoreElements ) ;
}
return null ;
},
/*
* Gets the next element (nodeType=1) in the source order. Returns
* "null" If no element is found.
* @param {Object} currentNode The node to start searching from.
* @param {Boolean} ignoreSpaceTextOnly Sets how text nodes will be
* handled. If set to "true", only white spaces text nodes
* will be ignored, while non white space text nodes will stop
* the search, returning null. If "false" or omitted, all
* text nodes are ignored.
* @param {string[]} stopSearchElements An array of element names that
* will cause the search to stop when found, returning null.
* May be omitted (or null).
* @param {string[]} ignoreElements An array of element names that
* must be ignored during the search.
*/
GetNextSourceElement : function( currentNode, ignoreSpaceTextOnly, stopSearchElements, ignoreElements, startFromSibling )
{
while( ( currentNode = this.GetNextSourceNode( currentNode, startFromSibling ) ) ) // Only one "=".
{
if ( currentNode.nodeType == 1 )
{
if ( stopSearchElements && currentNode.nodeName.IEquals( stopSearchElements ) )
break ;
if ( ignoreElements && currentNode.nodeName.IEquals( ignoreElements ) )
return this.GetNextSourceElement( currentNode, ignoreSpaceTextOnly, stopSearchElements, ignoreElements ) ;
return currentNode ;
}
else if ( ignoreSpaceTextOnly && currentNode.nodeType == 3 && currentNode.nodeValue.RTrim().length > 0 )
break ;
}
return null ;
},
/*
* Get the next DOM node available in source order.
*/
GetNextSourceNode : function( currentNode, startFromSibling, nodeType, stopSearchNode )
{
if ( !currentNode )
return null ;
var node ;
if ( !startFromSibling && currentNode.firstChild )
node = currentNode.firstChild ;
else
{
if ( stopSearchNode && currentNode == stopSearchNode )
return null ;
node = currentNode.nextSibling ;
if ( !node && ( !stopSearchNode || stopSearchNode != currentNode.parentNode ) )
return this.GetNextSourceNode( currentNode.parentNode, true, nodeType, stopSearchNode ) ;
}
if ( nodeType && node && node.nodeType != nodeType )
return this.GetNextSourceNode( node, false, nodeType, stopSearchNode ) ;
return node ;
},
/*
* Get the next DOM node available in source order.
*/
GetPreviousSourceNode : function( currentNode, startFromSibling, nodeType, stopSearchNode )
{
if ( !currentNode )
return null ;
var node ;
if ( !startFromSibling && currentNode.lastChild )
node = currentNode.lastChild ;
else
{
if ( stopSearchNode && currentNode == stopSearchNode )
return null ;
node = currentNode.previousSibling ;
if ( !node && ( !stopSearchNode || stopSearchNode != currentNode.parentNode ) )
return this.GetPreviousSourceNode( currentNode.parentNode, true, nodeType, stopSearchNode ) ;
}
if ( nodeType && node && node.nodeType != nodeType )
return this.GetPreviousSourceNode( node, false, nodeType, stopSearchNode ) ;
return node ;
},
// Inserts a element after a existing one.
InsertAfterNode : function( existingNode, newNode )
{
return existingNode.parentNode.insertBefore( newNode, existingNode.nextSibling ) ;
},
GetParents : function( node )
{
var parents = new Array() ;
while ( node )
{
parents.unshift( node ) ;
node = node.parentNode ;
}
return parents ;
},
GetCommonParents : function( node1, node2 )
{
var p1 = this.GetParents( node1 ) ;
var p2 = this.GetParents( node2 ) ;
var retval = [] ;
for ( var i = 0 ; i < p1.length ; i++ )
{
if ( p1[i] == p2[i] )
retval.push( p1[i] ) ;
}
return retval ;
},
GetCommonParentNode : function( node1, node2, tagList )
{
var tagMap = {} ;
if ( ! tagList.pop )
tagList = [ tagList ] ;
while ( tagList.length > 0 )
tagMap[tagList.pop().toLowerCase()] = 1 ;
var commonParents = this.GetCommonParents( node1, node2 ) ;
var currentParent = null ;
while ( ( currentParent = commonParents.pop() ) )
{
if ( tagMap[currentParent.nodeName.toLowerCase()] )
return currentParent ;
}
return null ;
},
GetIndexOf : function( node )
{
var currentNode = node.parentNode ? node.parentNode.firstChild : null ;
var currentIndex = -1 ;
while ( currentNode )
{
currentIndex++ ;
if ( currentNode == node )
return currentIndex ;
currentNode = currentNode.nextSibling ;
}
return -1 ;
},
PaddingNode : null,
EnforcePaddingNode : function( doc, tagName )
{
// In IE it can happen when the page is reloaded that doc or doc.body is null, so exit here
try
{
if ( !doc || !doc.body )
return ;
}
catch (e)
{
return ;
}
this.CheckAndRemovePaddingNode( doc, tagName, true ) ;
try
{
if ( doc.body.lastChild && ( doc.body.lastChild.nodeType != 1
|| doc.body.lastChild.tagName.toLowerCase() == tagName.toLowerCase() ) )
return ;
}
catch (e)
{
return ;
}
var node = doc.createElement( tagName ) ;
if ( FCKBrowserInfo.IsGecko && FCKListsLib.NonEmptyBlockElements[ tagName ] )
FCKTools.AppendBogusBr( node ) ;
this.PaddingNode = node ;
if ( doc.body.childNodes.length == 1
&& doc.body.firstChild.nodeType == 1
&& doc.body.firstChild.tagName.toLowerCase() == 'br'
&& ( doc.body.firstChild.getAttribute( '_moz_dirty' ) != null
|| doc.body.firstChild.getAttribute( 'type' ) == '_moz' ) )
doc.body.replaceChild( node, doc.body.firstChild ) ;
else
doc.body.appendChild( node ) ;
},
CheckAndRemovePaddingNode : function( doc, tagName, dontRemove )
{
var paddingNode = this.PaddingNode ;
if ( ! paddingNode )
return ;
// If the padding node is changed, remove its status as a padding node.
try
{
if ( paddingNode.parentNode != doc.body
|| paddingNode.tagName.toLowerCase() != tagName
|| ( paddingNode.childNodes.length > 1 )
|| ( paddingNode.firstChild && paddingNode.firstChild.nodeValue != '\xa0'
&& String(paddingNode.firstChild.tagName).toLowerCase() != 'br' ) )
{
this.PaddingNode = null ;
return ;
}
}
catch (e)
{
this.PaddingNode = null ;
return ;
}
// Now we're sure the padding node exists, and it is unchanged, and it
// isn't the only node in doc.body, remove it.
if ( !dontRemove )
{
if ( paddingNode.parentNode.childNodes.length > 1 )
paddingNode.parentNode.removeChild( paddingNode ) ;
this.PaddingNode = null ;
}
},
HasAttribute : function( element, attributeName )
{
if ( element.hasAttribute )
return element.hasAttribute( attributeName ) ;
else
{
var att = element.attributes[ attributeName ] ;
return ( att != undefined && att.specified ) ;
}
},
/**
* Checks if an element has "specified" attributes.
*/
HasAttributes : function( element )
{
var attributes = element.attributes ;
for ( var i = 0 ; i < attributes.length ; i++ )
{
if ( FCKBrowserInfo.IsIE && attributes[i].nodeName == 'class' )
{
// IE has a strange bug. If calling removeAttribute('className'),
// the attributes collection will still contain the "class"
// attribute, which will be marked as "specified", even if the
// outerHTML of the element is not displaying the class attribute.
// Note : I was not able to reproduce it outside the editor,
// but I've faced it while working on the TC of #1391.
if ( element.className.length > 0 )
return true ;
}
else if ( attributes[i].specified )
return true ;
}
return false ;
},
/**
* Remove an attribute from an element.
*/
RemoveAttribute : function( element, attributeName )
{
if ( FCKBrowserInfo.IsIE && attributeName.toLowerCase() == 'class' )
attributeName = 'className' ;
return element.removeAttribute( attributeName, 0 ) ;
},
/**
* Removes an array of attributes from an element
*/
RemoveAttributes : function (element, aAttributes )
{
for ( var i = 0 ; i < aAttributes.length ; i++ )
this.RemoveAttribute( element, aAttributes[i] );
},
GetAttributeValue : function( element, att )
{
var attName = att ;
if ( typeof att == 'string' )
att = element.attributes[ att ] ;
else
attName = att.nodeName ;
if ( att && att.specified )
{
// IE returns "null" for the nodeValue of a "style" attribute.
if ( attName == 'style' )
return element.style.cssText ;
// There are two cases when the nodeValue must be used:
// - for the "class" attribute (all browsers).
// - for events attributes (IE only).
else if ( attName == 'class' || attName.indexOf('on') == 0 )
return att.nodeValue ;
else
{
// Use getAttribute to get its value exactly as it is
// defined.
return element.getAttribute( attName, 2 ) ;
}
}
return null ;
},
/**
* Checks whether one element contains the other.
*/
Contains : function( mainElement, otherElement )
{
// IE supports contains, but only for element nodes.
if ( mainElement.contains && otherElement.nodeType == 1 )
return mainElement.contains( otherElement ) ;
while ( ( otherElement = otherElement.parentNode ) ) // Only one "="
{
if ( otherElement == mainElement )
return true ;
}
return false ;
},
/**
* Breaks a parent element in the position of one of its contained elements.
* For example, in the following case:
* <b>This <i>is some<span /> sample</i> test text</b>
* If element = <span />, we have these results:
* <b>This <i>is some</i><span /><i> sample</i> test text</b> (If parent = <i>)
* <b>This <i>is some</i></b><span /><b><i> sample</i> test text</b> (If parent = <b>)
*/
BreakParent : function( element, parent, reusableRange )
{
var range = reusableRange || new FCKDomRange( FCKTools.GetElementWindow( element ) ) ;
// We'll be extracting part of this element, so let's use our
// range to get the correct piece.
range.SetStart( element, 4 ) ;
range.SetEnd( parent, 4 ) ;
// Extract it.
var docFrag = range.ExtractContents() ;
// Move the element outside the broken element.
range.InsertNode( element.parentNode.removeChild( element ) ) ;
// Re-insert the extracted piece after the element.
docFrag.InsertAfterNode( element ) ;
range.Release( !!reusableRange ) ;
},
/**
* Retrieves a uniquely identifiable tree address of a DOM tree node.
* The tree address returns is an array of integers, with each integer
* indicating a child index from a DOM tree node, starting from
* document.documentElement.
*
* For example, assuming <body> is the second child from <html> (<head>
* being the first), and we'd like to address the third child under the
* fourth child of body, the tree address returned would be:
* [1, 3, 2]
*
* The tree address cannot be used for finding back the DOM tree node once
* the DOM tree structure has been modified.
*/
GetNodeAddress : function( node, normalized )
{
var retval = [] ;
while ( node && node != FCKTools.GetElementDocument( node ).documentElement )
{
var parentNode = node.parentNode ;
var currentIndex = -1 ;
for( var i = 0 ; i < parentNode.childNodes.length ; i++ )
{
var candidate = parentNode.childNodes[i] ;
if ( normalized === true &&
candidate.nodeType == 3 &&
candidate.previousSibling &&
candidate.previousSibling.nodeType == 3 )
continue;
currentIndex++ ;
if ( parentNode.childNodes[i] == node )
break ;
}
retval.unshift( currentIndex ) ;
node = node.parentNode ;
}
return retval ;
},
/**
* The reverse transformation of FCKDomTools.GetNodeAddress(). This
* function returns the DOM node pointed to by its index address.
*/
GetNodeFromAddress : function( doc, addr, normalized )
{
var cursor = doc.documentElement ;
for ( var i = 0 ; i < addr.length ; i++ )
{
var target = addr[i] ;
if ( ! normalized )
{
cursor = cursor.childNodes[target] ;
continue ;
}
var currentIndex = -1 ;
for (var j = 0 ; j < cursor.childNodes.length ; j++ )
{
var candidate = cursor.childNodes[j] ;
if ( normalized === true &&
candidate.nodeType == 3 &&
candidate.previousSibling &&
candidate.previousSibling.nodeType == 3 )
continue ;
currentIndex++ ;
if ( currentIndex == target )
{
cursor = candidate ;
break ;
}
}
}
return cursor ;
},
CloneElement : function( element )
{
element = element.cloneNode( false ) ;
// The "id" attribute should never be cloned to avoid duplication.
element.removeAttribute( 'id', false ) ;
return element ;
},
ClearElementJSProperty : function( element, attrName )
{
if ( FCKBrowserInfo.IsIE )
element.removeAttribute( attrName ) ;
else
delete element[attrName] ;
},
SetElementMarker : function ( markerObj, element, attrName, value)
{
var id = String( parseInt( Math.random() * 0xffffffff, 10 ) ) ;
element._FCKMarkerId = id ;
element[attrName] = value ;
if ( ! markerObj[id] )
markerObj[id] = { 'element' : element, 'markers' : {} } ;
markerObj[id]['markers'][attrName] = value ;
},
ClearElementMarkers : function( markerObj, element, clearMarkerObj )
{
var id = element._FCKMarkerId ;
if ( ! id )
return ;
this.ClearElementJSProperty( element, '_FCKMarkerId' ) ;
for ( var j in markerObj[id]['markers'] )
this.ClearElementJSProperty( element, j ) ;
if ( clearMarkerObj )
delete markerObj[id] ;
},
ClearAllMarkers : function( markerObj )
{
for ( var i in markerObj )
this.ClearElementMarkers( markerObj, markerObj[i]['element'], true ) ;
},
/**
* Convert a DOM list tree into a data structure that is easier to
* manipulate. This operation should be non-intrusive in the sense that it
* does not change the DOM tree, with the exception that it may add some
* markers to the list item nodes when markerObj is specified.
*/
ListToArray : function( listNode, markerObj, baseArray, baseIndentLevel, grandparentNode )
{
if ( ! listNode.nodeName.IEquals( ['ul', 'ol'] ) )
return [] ;
if ( ! baseIndentLevel )
baseIndentLevel = 0 ;
if ( ! baseArray )
baseArray = [] ;
// Iterate over all list items to get their contents and look for inner lists.
for ( var i = 0 ; i < listNode.childNodes.length ; i++ )
{
var listItem = listNode.childNodes[i] ;
if ( ! listItem.nodeName.IEquals( 'li' ) )
continue ;
var itemObj = { 'parent' : listNode, 'indent' : baseIndentLevel, 'contents' : [] } ;
if ( ! grandparentNode )
{
itemObj.grandparent = listNode.parentNode ;
if ( itemObj.grandparent && itemObj.grandparent.nodeName.IEquals( 'li' ) )
itemObj.grandparent = itemObj.grandparent.parentNode ;
}
else
itemObj.grandparent = grandparentNode ;
if ( markerObj )
this.SetElementMarker( markerObj, listItem, '_FCK_ListArray_Index', baseArray.length ) ;
baseArray.push( itemObj ) ;
for ( var j = 0 ; j < listItem.childNodes.length ; j++ )
{
var child = listItem.childNodes[j] ;
if ( child.nodeName.IEquals( ['ul', 'ol'] ) )
// Note the recursion here, it pushes inner list items with
// +1 indentation in the correct order.
this.ListToArray( child, markerObj, baseArray, baseIndentLevel + 1, itemObj.grandparent ) ;
else
itemObj.contents.push( child ) ;
}
}
return baseArray ;
},
// Convert our internal representation of a list back to a DOM forest.
ArrayToList : function( listArray, markerObj, baseIndex )
{
if ( baseIndex == undefined )
baseIndex = 0 ;
if ( ! listArray || listArray.length < baseIndex + 1 )
return null ;
var doc = FCKTools.GetElementDocument( listArray[baseIndex].parent ) ;
var retval = doc.createDocumentFragment() ;
var rootNode = null ;
var currentIndex = baseIndex ;
var indentLevel = Math.max( listArray[baseIndex].indent, 0 ) ;
var currentListItem = null ;
while ( true )
{
var item = listArray[currentIndex] ;
if ( item.indent == indentLevel )
{
if ( ! rootNode || listArray[currentIndex].parent.nodeName != rootNode.nodeName )
{
rootNode = listArray[currentIndex].parent.cloneNode( false ) ;
retval.appendChild( rootNode ) ;
}
currentListItem = doc.createElement( 'li' ) ;
rootNode.appendChild( currentListItem ) ;
for ( var i = 0 ; i < item.contents.length ; i++ )
currentListItem.appendChild( item.contents[i].cloneNode( true ) ) ;
currentIndex++ ;
}
else if ( item.indent == Math.max( indentLevel, 0 ) + 1 )
{
var listData = this.ArrayToList( listArray, null, currentIndex ) ;
currentListItem.appendChild( listData.listNode ) ;
currentIndex = listData.nextIndex ;
}
else if ( item.indent == -1 && baseIndex == 0 && item.grandparent )
{
var currentListItem ;
if ( item.grandparent.nodeName.IEquals( ['ul', 'ol'] ) )
currentListItem = doc.createElement( 'li' ) ;
else
{
if ( FCKConfig.EnterMode.IEquals( ['div', 'p'] ) && ! item.grandparent.nodeName.IEquals( 'td' ) )
currentListItem = doc.createElement( FCKConfig.EnterMode ) ;
else
currentListItem = doc.createDocumentFragment() ;
}
for ( var i = 0 ; i < item.contents.length ; i++ )
currentListItem.appendChild( item.contents[i].cloneNode( true ) ) ;
if ( currentListItem.nodeType == 11 )
{
if ( currentListItem.lastChild &&
currentListItem.lastChild.getAttribute &&
currentListItem.lastChild.getAttribute( 'type' ) == '_moz' )
currentListItem.removeChild( currentListItem.lastChild );
currentListItem.appendChild( doc.createElement( 'br' ) ) ;
}
if ( currentListItem.nodeName.IEquals( FCKConfig.EnterMode ) && currentListItem.firstChild )
{
this.TrimNode( currentListItem ) ;
if ( FCKListsLib.BlockBoundaries[currentListItem.firstChild.nodeName.toLowerCase()] )
{
var tmp = doc.createDocumentFragment() ;
while ( currentListItem.firstChild )
tmp.appendChild( currentListItem.removeChild( currentListItem.firstChild ) ) ;
currentListItem = tmp ;
}
}
if ( FCKBrowserInfo.IsGeckoLike && currentListItem.nodeName.IEquals( ['div', 'p'] ) )
FCKTools.AppendBogusBr( currentListItem ) ;
retval.appendChild( currentListItem ) ;
rootNode = null ;
currentIndex++ ;
}
else
return null ;
if ( listArray.length <= currentIndex || Math.max( listArray[currentIndex].indent, 0 ) < indentLevel )
{
break ;
}
}
// Clear marker attributes for the new list tree made of cloned nodes, if any.
if ( markerObj )
{
var currentNode = retval.firstChild ;
while ( currentNode )
{
if ( currentNode.nodeType == 1 )
this.ClearElementMarkers( markerObj, currentNode ) ;
currentNode = this.GetNextSourceNode( currentNode ) ;
}
}
return { 'listNode' : retval, 'nextIndex' : currentIndex } ;
},
/**
* Get the next sibling node for a node. If "includeEmpties" is false,
* only element or non empty text nodes are returned.
*/
GetNextSibling : function( node, includeEmpties )
{
node = node.nextSibling ;
while ( node && !includeEmpties && node.nodeType != 1 && ( node.nodeType != 3 || node.nodeValue.length == 0 ) )
node = node.nextSibling ;
return node ;
},
/**
* Get the previous sibling node for a node. If "includeEmpties" is false,
* only element or non empty text nodes are returned.
*/
GetPreviousSibling : function( node, includeEmpties )
{
node = node.previousSibling ;
while ( node && !includeEmpties && node.nodeType != 1 && ( node.nodeType != 3 || node.nodeValue.length == 0 ) )
node = node.previousSibling ;
return node ;
},
/**
* Checks if an element has no "useful" content inside of it
* node tree. No "useful" content means empty text node or a signle empty
* inline node.
* elementCheckCallback may point to a function that returns a boolean
* indicating that a child element must be considered in the element check.
*/
CheckIsEmptyElement : function( element, elementCheckCallback )
{
var child = element.firstChild ;
var elementChild ;
while ( child )
{
if ( child.nodeType == 1 )
{
if ( elementChild || !FCKListsLib.InlineNonEmptyElements[ child.nodeName.toLowerCase() ] )
return false ;
if ( !elementCheckCallback || elementCheckCallback( child ) === true )
elementChild = child ;
}
else if ( child.nodeType == 3 && child.nodeValue.length > 0 )
return false ;
child = child.nextSibling ;
}
return elementChild ? this.CheckIsEmptyElement( elementChild, elementCheckCallback ) : true ;
},
SetElementStyles : function( element, styleDict )
{
var style = element.style ;
for ( var styleName in styleDict )
style[ styleName ] = styleDict[ styleName ] ;
},
SetOpacity : function( element, opacity )
{
if ( FCKBrowserInfo.IsIE )
{
opacity = Math.round( opacity * 100 ) ;
element.style.filter = ( opacity > 100 ? '' : 'progid:DXImageTransform.Microsoft.Alpha(opacity=' + opacity + ')' ) ;
}
else
element.style.opacity = opacity ;
},
GetCurrentElementStyle : function( element, propertyName )
{
if ( FCKBrowserInfo.IsIE )
return element.currentStyle[ propertyName ] ;
else
return element.ownerDocument.defaultView.getComputedStyle( element, '' ).getPropertyValue( propertyName ) ;
},
GetPositionedAncestor : function( element )
{
var currentElement = element ;
while ( currentElement != FCKTools.GetElementDocument( currentElement ).documentElement )
{
if ( this.GetCurrentElementStyle( currentElement, 'position' ) != 'static' )
return currentElement ;
if ( currentElement == FCKTools.GetElementDocument( currentElement ).documentElement
&& currentWindow != w )
currentElement = currentWindow.frameElement ;
else
currentElement = currentElement.parentNode ;
}
return null ;
},
/**
* Current implementation for ScrollIntoView (due to #1462 and #2279). We
* don't have a complete implementation here, just the things that fit our
* needs.
*/
ScrollIntoView : function( element, alignTop )
{
// Get the element window.
var window = FCKTools.GetElementWindow( element ) ;
var windowHeight = FCKTools.GetViewPaneSize( window ).Height ;
// Starts the offset that will be scrolled with the negative value of
// the visible window height.
var offset = windowHeight * -1 ;
// Appends the height it we are about to align the bottoms.
if ( alignTop === false )
{
offset += element.offsetHeight || 0 ;
// Consider the margin in the scroll, which is ok for our current
// needs, but needs investigation if we will be using this function
// in other places.
offset += parseInt( this.GetCurrentElementStyle( element, 'marginBottom' ) || 0, 10 ) || 0 ;
}
// Appends the offsets for the entire element hierarchy.
var elementPosition = FCKTools.GetDocumentPosition( window, element ) ;
offset += elementPosition.y ;
// Scroll the window to the desired position, if not already visible.
var currentScroll = FCKTools.GetScrollPosition( window ).Y ;
if ( offset > 0 && ( offset > currentScroll || offset < currentScroll - windowHeight ) )
window.scrollTo( 0, offset ) ;
},
/**
* Check if the element can be edited inside the browser.
*/
CheckIsEditable : function( element )
{
// Get the element name.
var nodeName = element.nodeName.toLowerCase() ;
// Get the element DTD (defaults to span for unknown elements).
var childDTD = FCK.DTD[ nodeName ] || FCK.DTD.span ;
// In the DTD # == text node.
return ( childDTD['#'] && !FCKListsLib.NonEditableElements[ nodeName ] ) ;
},
GetSelectedDivContainers : function()
{
var currentBlocks = [] ;
var range = new FCKDomRange( FCK.EditorWindow ) ;
range.MoveToSelection() ;
var startNode = range.GetTouchedStartNode() ;
var endNode = range.GetTouchedEndNode() ;
var currentNode = startNode ;
if ( startNode == endNode )
{
while ( endNode.nodeType == 1 && endNode.lastChild )
endNode = endNode.lastChild ;
endNode = FCKDomTools.GetNextSourceNode( endNode ) ;
}
while ( currentNode && currentNode != endNode )
{
if ( currentNode.nodeType != 3 || !/^[ \t\n]*$/.test( currentNode.nodeValue ) )
{
var path = new FCKElementPath( currentNode ) ;
var blockLimit = path.BlockLimit ;
if ( blockLimit && blockLimit.nodeName.IEquals( 'div' ) && currentBlocks.IndexOf( blockLimit ) == -1 )
currentBlocks.push( blockLimit ) ;
}
currentNode = FCKDomTools.GetNextSourceNode( currentNode ) ;
}
return currentBlocks ;
}
} ;
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* Utility functions. (Gecko version).
*/
FCKTools.CancelEvent = function( e )
{
if ( e )
e.preventDefault() ;
}
FCKTools.DisableSelection = function( element )
{
if ( FCKBrowserInfo.IsGecko )
element.style.MozUserSelect = 'none' ; // Gecko only.
else if ( FCKBrowserInfo.IsSafari )
element.style.KhtmlUserSelect = 'none' ; // WebKit only.
else
element.style.userSelect = 'none' ; // CSS3 (not supported yet).
}
// Appends a CSS file to a document.
FCKTools._AppendStyleSheet = function( documentElement, cssFileUrl )
{
var e = documentElement.createElement( 'LINK' ) ;
e.rel = 'stylesheet' ;
e.type = 'text/css' ;
e.href = cssFileUrl ;
documentElement.getElementsByTagName("HEAD")[0].appendChild( e ) ;
return e ;
}
// Appends a CSS style string to a document.
FCKTools.AppendStyleString = function( documentElement, cssStyles )
{
if ( !cssStyles )
return null ;
var e = documentElement.createElement( "STYLE" ) ;
e.appendChild( documentElement.createTextNode( cssStyles ) ) ;
documentElement.getElementsByTagName( "HEAD" )[0].appendChild( e ) ;
return e ;
}
// Removes all attributes and values from the element.
FCKTools.ClearElementAttributes = function( element )
{
// Loop throw all attributes in the element
for ( var i = 0 ; i < element.attributes.length ; i++ )
{
// Remove the element by name.
element.removeAttribute( element.attributes[i].name, 0 ) ; // 0 : Case Insensitive
}
}
// Returns an Array of strings with all defined in the elements inside another element.
FCKTools.GetAllChildrenIds = function( parentElement )
{
// Create the array that will hold all Ids.
var aIds = new Array() ;
// Define a recursive function that search for the Ids.
var fGetIds = function( parent )
{
for ( var i = 0 ; i < parent.childNodes.length ; i++ )
{
var sId = parent.childNodes[i].id ;
// Check if the Id is defined for the element.
if ( sId && sId.length > 0 ) aIds[ aIds.length ] = sId ;
// Recursive call.
fGetIds( parent.childNodes[i] ) ;
}
}
// Start the recursive calls.
fGetIds( parentElement ) ;
return aIds ;
}
// Replaces a tag with its contents. For example "<span>My <b>tag</b></span>"
// will be replaced with "My <b>tag</b>".
FCKTools.RemoveOuterTags = function( e )
{
var oFragment = e.ownerDocument.createDocumentFragment() ;
for ( var i = 0 ; i < e.childNodes.length ; i++ )
oFragment.appendChild( e.childNodes[i].cloneNode(true) ) ;
e.parentNode.replaceChild( oFragment, e ) ;
}
FCKTools.CreateXmlObject = function( object )
{
switch ( object )
{
case 'XmlHttp' :
return new XMLHttpRequest() ;
case 'DOMDocument' :
// Originaly, we were had the following here:
// return document.implementation.createDocument( '', '', null ) ;
// But that doesn't work if we're running under domain relaxation mode, so we need a workaround.
// See http://ajaxian.com/archives/xml-messages-with-cross-domain-json about the trick we're using.
var doc = ( new DOMParser() ).parseFromString( '<tmp></tmp>', 'text/xml' ) ;
FCKDomTools.RemoveNode( doc.firstChild ) ;
return doc ;
}
return null ;
}
FCKTools.GetScrollPosition = function( relativeWindow )
{
return { X : relativeWindow.pageXOffset, Y : relativeWindow.pageYOffset } ;
}
FCKTools.AddEventListener = function( sourceObject, eventName, listener )
{
sourceObject.addEventListener( eventName, listener, false ) ;
}
FCKTools.RemoveEventListener = function( sourceObject, eventName, listener )
{
sourceObject.removeEventListener( eventName, listener, false ) ;
}
// Listeners attached with this function cannot be detached.
FCKTools.AddEventListenerEx = function( sourceObject, eventName, listener, paramsArray )
{
sourceObject.addEventListener(
eventName,
function( e )
{
listener.apply( sourceObject, [ e ].concat( paramsArray || [] ) ) ;
},
false
) ;
}
// Returns and object with the "Width" and "Height" properties.
FCKTools.GetViewPaneSize = function( win )
{
return { Width : win.innerWidth, Height : win.innerHeight } ;
}
FCKTools.SaveStyles = function( element )
{
var data = FCKTools.ProtectFormStyles( element ) ;
var oSavedStyles = new Object() ;
if ( element.className.length > 0 )
{
oSavedStyles.Class = element.className ;
element.className = '' ;
}
var sInlineStyle = element.getAttribute( 'style' ) ;
if ( sInlineStyle && sInlineStyle.length > 0 )
{
oSavedStyles.Inline = sInlineStyle ;
element.setAttribute( 'style', '', 0 ) ; // 0 : Case Insensitive
}
FCKTools.RestoreFormStyles( element, data ) ;
return oSavedStyles ;
}
FCKTools.RestoreStyles = function( element, savedStyles )
{
var data = FCKTools.ProtectFormStyles( element ) ;
element.className = savedStyles.Class || '' ;
if ( savedStyles.Inline )
element.setAttribute( 'style', savedStyles.Inline, 0 ) ; // 0 : Case Insensitive
else
element.removeAttribute( 'style', 0 ) ;
FCKTools.RestoreFormStyles( element, data ) ;
}
FCKTools.RegisterDollarFunction = function( targetWindow )
{
targetWindow.$ = function( id )
{
return targetWindow.document.getElementById( id ) ;
} ;
}
FCKTools.AppendElement = function( target, elementName )
{
return target.appendChild( target.ownerDocument.createElement( elementName ) ) ;
}
// Get the coordinates of an element.
// @el : The element to get the position.
// @relativeWindow: The window to which we want the coordinates relative to.
FCKTools.GetElementPosition = function( el, relativeWindow )
{
// Initializes the Coordinates object that will be returned by the function.
var c = { X:0, Y:0 } ;
var oWindow = relativeWindow || window ;
var oOwnerWindow = FCKTools.GetElementWindow( el ) ;
var previousElement = null ;
// Loop throw the offset chain.
while ( el )
{
var sPosition = oOwnerWindow.getComputedStyle(el, '').position ;
// Check for non "static" elements.
// 'FCKConfig.FloatingPanelsZIndex' -- Submenus are under a positioned IFRAME.
if ( sPosition && sPosition != 'static' && el.style.zIndex != FCKConfig.FloatingPanelsZIndex )
break ;
/*
FCKDebug.Output( el.tagName + ":" + "offset=" + el.offsetLeft + "," + el.offsetTop + " "
+ "scroll=" + el.scrollLeft + "," + el.scrollTop ) ;
*/
c.X += el.offsetLeft - el.scrollLeft ;
c.Y += el.offsetTop - el.scrollTop ;
// Backtrack due to offsetParent's calculation by the browser ignores scrollLeft and scrollTop.
// Backtracking is not needed for Opera
if ( ! FCKBrowserInfo.IsOpera )
{
var scrollElement = previousElement ;
while ( scrollElement && scrollElement != el )
{
c.X -= scrollElement.scrollLeft ;
c.Y -= scrollElement.scrollTop ;
scrollElement = scrollElement.parentNode ;
}
}
previousElement = el ;
if ( el.offsetParent )
el = el.offsetParent ;
else
{
if ( oOwnerWindow != oWindow )
{
el = oOwnerWindow.frameElement ;
previousElement = null ;
if ( el )
oOwnerWindow = FCKTools.GetElementWindow( el ) ;
}
else
{
c.X += el.scrollLeft ;
c.Y += el.scrollTop ;
break ;
}
}
}
// Return the Coordinates object
return c ;
}
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* Contains browser detection information.
*/
var s = navigator.userAgent.toLowerCase() ;
var FCKBrowserInfo =
{
IsIE : /*@cc_on!@*/false,
IsIE7 : /*@cc_on!@*/false && ( parseInt( s.match( /msie (\d+)/ )[1], 10 ) >= 7 ),
IsIE6 : /*@cc_on!@*/false && ( parseInt( s.match( /msie (\d+)/ )[1], 10 ) >= 6 ),
IsSafari : s.Contains(' applewebkit/'), // Read "IsWebKit"
IsOpera : !!window.opera,
IsAIR : s.Contains(' adobeair/'),
IsMac : s.Contains('macintosh')
} ;
// Completes the browser info with further Gecko information.
(function( browserInfo )
{
browserInfo.IsGecko = ( navigator.product == 'Gecko' ) && !browserInfo.IsSafari && !browserInfo.IsOpera ;
browserInfo.IsGeckoLike = ( browserInfo.IsGecko || browserInfo.IsSafari || browserInfo.IsOpera ) ;
if ( browserInfo.IsGecko )
{
var geckoMatch = s.match( /rv:(\d+\.\d+)/ ) ;
var geckoVersion = geckoMatch && parseFloat( geckoMatch[1] ) ;
// Actually "10" refers to Gecko versions before Firefox 1.5, when
// Gecko 1.8 (build 20051111) has been released.
// Some browser (like Mozilla 1.7.13) may have a Gecko build greater
// than 20051111, so we must also check for the revision number not to
// be 1.7 (we are assuming that rv < 1.7 will not have build > 20051111).
if ( geckoVersion )
{
browserInfo.IsGecko10 = ( geckoVersion < 1.8 ) ;
browserInfo.IsGecko19 = ( geckoVersion > 1.8 ) ;
}
}
})(FCKBrowserInfo) ;
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* Defines the FCKURLParams object that is used to get all parameters
* passed by the URL QueryString (after the "?").
*/
// #### URLParams: holds all URL passed parameters (like ?Param1=Value1&Param2=Value2)
var FCKURLParams = new Object() ;
(function()
{
var aParams = document.location.search.substr(1).split('&') ;
for ( var i = 0 ; i < aParams.length ; i++ )
{
var aParam = aParams[i].split('=') ;
var sParamName = decodeURIComponent( aParam[0] ) ;
var sParamValue = decodeURIComponent( aParam[1] ) ;
FCKURLParams[ sParamName ] = sParamValue ;
}
})();
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* Utility functions.
*/
var FCKTools = new Object() ;
FCKTools.CreateBogusBR = function( targetDocument )
{
var eBR = targetDocument.createElement( 'br' ) ;
// eBR.setAttribute( '_moz_editor_bogus_node', 'TRUE' ) ;
eBR.setAttribute( 'type', '_moz' ) ;
return eBR ;
}
/**
* Fixes relative URL entries defined inside CSS styles by appending a prefix
* to them.
* @param (String) cssStyles The CSS styles definition possibly containing url()
* paths.
* @param (String) urlFixPrefix The prefix to append to relative URLs.
*/
FCKTools.FixCssUrls = function( urlFixPrefix, cssStyles )
{
if ( !urlFixPrefix || urlFixPrefix.length == 0 )
return cssStyles ;
return cssStyles.replace( /url\s*\(([\s'"]*)(.*?)([\s"']*)\)/g, function( match, opener, path, closer )
{
if ( /^\/|^\w?:/.test( path ) )
return match ;
else
return 'url(' + opener + urlFixPrefix + path + closer + ')' ;
} ) ;
}
FCKTools._GetUrlFixedCss = function( cssStyles, urlFixPrefix )
{
var match = cssStyles.match( /^([^|]+)\|([\s\S]*)/ ) ;
if ( match )
return FCKTools.FixCssUrls( match[1], match[2] ) ;
else
return cssStyles ;
}
/**
* Appends a <link css> or <style> element to the document.
* @param (Object) documentElement The DOM document object to which append the
* stylesheet.
* @param (Variant) cssFileOrDef A String pointing to the CSS file URL or an
* Array with many CSS file URLs or the CSS definitions for the <style>
* element.
* @return {Array} An array containing all elements created in the target
* document. It may include <link> or <style> elements, depending on the
* value passed with cssFileOrDef.
*/
FCKTools.AppendStyleSheet = function( domDocument, cssFileOrArrayOrDef )
{
if ( !cssFileOrArrayOrDef )
return [] ;
if ( typeof( cssFileOrArrayOrDef ) == 'string' )
{
// Test if the passed argument is an URL.
if ( /[\\\/\.][^{}]*$/.test( cssFileOrArrayOrDef ) )
{
// The string may have several URLs separated by comma.
return this.AppendStyleSheet( domDocument, cssFileOrArrayOrDef.split(',') ) ;
}
else
return [ this.AppendStyleString( domDocument, FCKTools._GetUrlFixedCss( cssFileOrArrayOrDef ) ) ] ;
}
else
{
var styles = [] ;
for ( var i = 0 ; i < cssFileOrArrayOrDef.length ; i++ )
styles.push( this._AppendStyleSheet( domDocument, cssFileOrArrayOrDef[i] ) ) ;
return styles ;
}
}
FCKTools.GetStyleHtml = (function()
{
var getStyle = function( styleDef, markTemp )
{
if ( styleDef.length == 0 )
return '' ;
var temp = markTemp ? ' _fcktemp="true"' : '' ;
return '<' + 'style type="text/css"' + temp + '>' + styleDef + '<' + '/style>' ;
}
var getLink = function( cssFileUrl, markTemp )
{
if ( cssFileUrl.length == 0 )
return '' ;
var temp = markTemp ? ' _fcktemp="true"' : '' ;
return '<' + 'link href="' + cssFileUrl + '" type="text/css" rel="stylesheet" ' + temp + '/>' ;
}
return function( cssFileOrArrayOrDef, markTemp )
{
if ( !cssFileOrArrayOrDef )
return '' ;
if ( typeof( cssFileOrArrayOrDef ) == 'string' )
{
// Test if the passed argument is an URL.
if ( /[\\\/\.][^{}]*$/.test( cssFileOrArrayOrDef ) )
{
// The string may have several URLs separated by comma.
return this.GetStyleHtml( cssFileOrArrayOrDef.split(','), markTemp ) ;
}
else
return getStyle( this._GetUrlFixedCss( cssFileOrArrayOrDef ), markTemp ) ;
}
else
{
var html = '' ;
for ( var i = 0 ; i < cssFileOrArrayOrDef.length ; i++ )
html += getLink( cssFileOrArrayOrDef[i], markTemp ) ;
return html ;
}
}
})() ;
FCKTools.GetElementDocument = function ( element )
{
return element.ownerDocument || element.document ;
}
// Get the window object where the element is placed in.
FCKTools.GetElementWindow = function( element )
{
return this.GetDocumentWindow( this.GetElementDocument( element ) ) ;
}
FCKTools.GetDocumentWindow = function( document )
{
// With Safari, there is not way to retrieve the window from the document, so we must fix it.
if ( FCKBrowserInfo.IsSafari && !document.parentWindow )
this.FixDocumentParentWindow( window.top ) ;
return document.parentWindow || document.defaultView ;
}
/*
This is a Safari specific function that fix the reference to the parent
window from the document object.
*/
FCKTools.FixDocumentParentWindow = function( targetWindow )
{
if ( targetWindow.document )
targetWindow.document.parentWindow = targetWindow ;
for ( var i = 0 ; i < targetWindow.frames.length ; i++ )
FCKTools.FixDocumentParentWindow( targetWindow.frames[i] ) ;
}
FCKTools.HTMLEncode = function( text )
{
if ( !text )
return '' ;
text = text.replace( /&/g, '&' ) ;
text = text.replace( /</g, '<' ) ;
text = text.replace( />/g, '>' ) ;
return text ;
}
FCKTools.HTMLDecode = function( text )
{
if ( !text )
return '' ;
text = text.replace( />/g, '>' ) ;
text = text.replace( /</g, '<' ) ;
text = text.replace( /&/g, '&' ) ;
return text ;
}
FCKTools._ProcessLineBreaksForPMode = function( oEditor, text, liState, node, strArray )
{
var closeState = 0 ;
var blockStartTag = "<p>" ;
var blockEndTag = "</p>" ;
var lineBreakTag = "<br />" ;
if ( liState )
{
blockStartTag = "<li>" ;
blockEndTag = "</li>" ;
closeState = 1 ;
}
// Are we currently inside a <p> tag now?
// If yes, close it at the next double line break.
while ( node && node != oEditor.FCK.EditorDocument.body )
{
if ( node.tagName.toLowerCase() == 'p' )
{
closeState = 1 ;
break;
}
node = node.parentNode ;
}
for ( var i = 0 ; i < text.length ; i++ )
{
var c = text.charAt( i ) ;
if ( c == '\r' )
continue ;
if ( c != '\n' )
{
strArray.push( c ) ;
continue ;
}
// Now we have encountered a line break.
// Check if the next character is also a line break.
var n = text.charAt( i + 1 ) ;
if ( n == '\r' )
{
i++ ;
n = text.charAt( i + 1 ) ;
}
if ( n == '\n' )
{
i++ ; // ignore next character - we have already processed it.
if ( closeState )
strArray.push( blockEndTag ) ;
strArray.push( blockStartTag ) ;
closeState = 1 ;
}
else
strArray.push( lineBreakTag ) ;
}
}
FCKTools._ProcessLineBreaksForDivMode = function( oEditor, text, liState, node, strArray )
{
var closeState = 0 ;
var blockStartTag = "<div>" ;
var blockEndTag = "</div>" ;
if ( liState )
{
blockStartTag = "<li>" ;
blockEndTag = "</li>" ;
closeState = 1 ;
}
// Are we currently inside a <div> tag now?
// If yes, close it at the next double line break.
while ( node && node != oEditor.FCK.EditorDocument.body )
{
if ( node.tagName.toLowerCase() == 'div' )
{
closeState = 1 ;
break ;
}
node = node.parentNode ;
}
for ( var i = 0 ; i < text.length ; i++ )
{
var c = text.charAt( i ) ;
if ( c == '\r' )
continue ;
if ( c != '\n' )
{
strArray.push( c ) ;
continue ;
}
if ( closeState )
{
if ( strArray[ strArray.length - 1 ] == blockStartTag )
{
// A div tag must have some contents inside for it to be visible.
strArray.push( " " ) ;
}
strArray.push( blockEndTag ) ;
}
strArray.push( blockStartTag ) ;
closeState = 1 ;
}
if ( closeState )
strArray.push( blockEndTag ) ;
}
FCKTools._ProcessLineBreaksForBrMode = function( oEditor, text, liState, node, strArray )
{
var closeState = 0 ;
var blockStartTag = "<br />" ;
var blockEndTag = "" ;
if ( liState )
{
blockStartTag = "<li>" ;
blockEndTag = "</li>" ;
closeState = 1 ;
}
for ( var i = 0 ; i < text.length ; i++ )
{
var c = text.charAt( i ) ;
if ( c == '\r' )
continue ;
if ( c != '\n' )
{
strArray.push( c ) ;
continue ;
}
if ( closeState && blockEndTag.length )
strArray.push ( blockEndTag ) ;
strArray.push( blockStartTag ) ;
closeState = 1 ;
}
}
FCKTools.ProcessLineBreaks = function( oEditor, oConfig, text )
{
var enterMode = oConfig.EnterMode.toLowerCase() ;
var strArray = [] ;
// Is the caret or selection inside an <li> tag now?
var liState = 0 ;
var range = new oEditor.FCKDomRange( oEditor.FCK.EditorWindow ) ;
range.MoveToSelection() ;
var node = range._Range.startContainer ;
while ( node && node.nodeType != 1 )
node = node.parentNode ;
if ( node && node.tagName.toLowerCase() == 'li' )
liState = 1 ;
if ( enterMode == 'p' )
this._ProcessLineBreaksForPMode( oEditor, text, liState, node, strArray ) ;
else if ( enterMode == 'div' )
this._ProcessLineBreaksForDivMode( oEditor, text, liState, node, strArray ) ;
else if ( enterMode == 'br' )
this._ProcessLineBreaksForBrMode( oEditor, text, liState, node, strArray ) ;
return strArray.join( "" ) ;
}
/**
* Adds an option to a SELECT element.
*/
FCKTools.AddSelectOption = function( selectElement, optionText, optionValue )
{
var oOption = FCKTools.GetElementDocument( selectElement ).createElement( "OPTION" ) ;
oOption.text = optionText ;
oOption.value = optionValue ;
selectElement.options.add(oOption) ;
return oOption ;
}
FCKTools.RunFunction = function( func, thisObject, paramsArray, timerWindow )
{
if ( func )
this.SetTimeout( func, 0, thisObject, paramsArray, timerWindow ) ;
}
FCKTools.SetTimeout = function( func, milliseconds, thisObject, paramsArray, timerWindow )
{
return ( timerWindow || window ).setTimeout(
function()
{
if ( paramsArray )
func.apply( thisObject, [].concat( paramsArray ) ) ;
else
func.apply( thisObject ) ;
},
milliseconds ) ;
}
FCKTools.SetInterval = function( func, milliseconds, thisObject, paramsArray, timerWindow )
{
return ( timerWindow || window ).setInterval(
function()
{
func.apply( thisObject, paramsArray || [] ) ;
},
milliseconds ) ;
}
FCKTools.ConvertStyleSizeToHtml = function( size )
{
return size.EndsWith( '%' ) ? size : parseInt( size, 10 ) ;
}
FCKTools.ConvertHtmlSizeToStyle = function( size )
{
return size.EndsWith( '%' ) ? size : ( size + 'px' ) ;
}
// START iCM MODIFICATIONS
// Amended to accept a list of one or more ascensor tag names
// Amended to check the element itself before working back up through the parent hierarchy
FCKTools.GetElementAscensor = function( element, ascensorTagNames )
{
// var e = element.parentNode ;
var e = element ;
var lstTags = "," + ascensorTagNames.toUpperCase() + "," ;
while ( e )
{
if ( lstTags.indexOf( "," + e.nodeName.toUpperCase() + "," ) != -1 )
return e ;
e = e.parentNode ;
}
return null ;
}
// END iCM MODIFICATIONS
FCKTools.CreateEventListener = function( func, params )
{
var f = function()
{
var aAllParams = [] ;
for ( var i = 0 ; i < arguments.length ; i++ )
aAllParams.push( arguments[i] ) ;
func.apply( this, aAllParams.concat( params ) ) ;
}
return f ;
}
FCKTools.IsStrictMode = function( document )
{
// There is no compatMode in Safari, but it seams that it always behave as
// CSS1Compat, so let's assume it as the default for that browser.
return ( 'CSS1Compat' == ( document.compatMode || ( FCKBrowserInfo.IsSafari ? 'CSS1Compat' : null ) ) ) ;
}
// Transforms a "arguments" object to an array.
FCKTools.ArgumentsToArray = function( args, startIndex, maxLength )
{
startIndex = startIndex || 0 ;
maxLength = maxLength || args.length ;
var argsArray = new Array() ;
for ( var i = startIndex ; i < startIndex + maxLength && i < args.length ; i++ )
argsArray.push( args[i] ) ;
return argsArray ;
}
FCKTools.CloneObject = function( sourceObject )
{
var fCloneCreator = function() {} ;
fCloneCreator.prototype = sourceObject ;
return new fCloneCreator ;
}
// Appends a bogus <br> at the end of the element, if not yet available.
FCKTools.AppendBogusBr = function( element )
{
if ( !element )
return ;
var eLastChild = this.GetLastItem( element.getElementsByTagName('br') ) ;
if ( !eLastChild || ( eLastChild.getAttribute( 'type', 2 ) != '_moz' && eLastChild.getAttribute( '_moz_dirty' ) == null ) )
{
var doc = this.GetElementDocument( element ) ;
if ( FCKBrowserInfo.IsOpera )
element.appendChild( doc.createTextNode('') ) ;
else
element.appendChild( this.CreateBogusBR( doc ) ) ;
}
}
FCKTools.GetLastItem = function( list )
{
if ( list.length > 0 )
return list[ list.length - 1 ] ;
return null ;
}
FCKTools.GetDocumentPosition = function( w, node )
{
var x = 0 ;
var y = 0 ;
var curNode = node ;
var prevNode = null ;
var curWindow = FCKTools.GetElementWindow( curNode ) ;
while ( curNode && !( curWindow == w && ( curNode == w.document.body || curNode == w.document.documentElement ) ) )
{
x += curNode.offsetLeft - curNode.scrollLeft ;
y += curNode.offsetTop - curNode.scrollTop ;
if ( ! FCKBrowserInfo.IsOpera )
{
var scrollNode = prevNode ;
while ( scrollNode && scrollNode != curNode )
{
x -= scrollNode.scrollLeft ;
y -= scrollNode.scrollTop ;
scrollNode = scrollNode.parentNode ;
}
}
prevNode = curNode ;
if ( curNode.offsetParent )
curNode = curNode.offsetParent ;
else
{
if ( curWindow != w )
{
curNode = curWindow.frameElement ;
prevNode = null ;
if ( curNode )
curWindow = curNode.contentWindow.parent ;
}
else
curNode = null ;
}
}
// document.body is a special case when it comes to offsetTop and offsetLeft values.
// 1. It matters if document.body itself is a positioned element;
// 2. It matters is when we're in IE and the element has no positioned ancestor.
// Otherwise the values should be ignored.
if ( FCKDomTools.GetCurrentElementStyle( w.document.body, 'position') != 'static'
|| ( FCKBrowserInfo.IsIE && FCKDomTools.GetPositionedAncestor( node ) == null ) )
{
x += w.document.body.offsetLeft ;
y += w.document.body.offsetTop ;
}
return { "x" : x, "y" : y } ;
}
FCKTools.GetWindowPosition = function( w, node )
{
var pos = this.GetDocumentPosition( w, node ) ;
var scroll = FCKTools.GetScrollPosition( w ) ;
pos.x -= scroll.X ;
pos.y -= scroll.Y ;
return pos ;
}
FCKTools.ProtectFormStyles = function( formNode )
{
if ( !formNode || formNode.nodeType != 1 || formNode.tagName.toLowerCase() != 'form' )
return [] ;
var hijackRecord = [] ;
var hijackNames = [ 'style', 'className' ] ;
for ( var i = 0 ; i < hijackNames.length ; i++ )
{
var name = hijackNames[i] ;
if ( formNode.elements.namedItem( name ) )
{
var hijackNode = formNode.elements.namedItem( name ) ;
hijackRecord.push( [ hijackNode, hijackNode.nextSibling ] ) ;
formNode.removeChild( hijackNode ) ;
}
}
return hijackRecord ;
}
FCKTools.RestoreFormStyles = function( formNode, hijackRecord )
{
if ( !formNode || formNode.nodeType != 1 || formNode.tagName.toLowerCase() != 'form' )
return ;
if ( hijackRecord.length > 0 )
{
for ( var i = hijackRecord.length - 1 ; i >= 0 ; i-- )
{
var node = hijackRecord[i][0] ;
var sibling = hijackRecord[i][1] ;
if ( sibling )
formNode.insertBefore( node, sibling ) ;
else
formNode.appendChild( node ) ;
}
}
}
// Perform a one-step DFS walk.
FCKTools.GetNextNode = function( node, limitNode )
{
if ( node.firstChild )
return node.firstChild ;
else if ( node.nextSibling )
return node.nextSibling ;
else
{
var ancestor = node.parentNode ;
while ( ancestor )
{
if ( ancestor == limitNode )
return null ;
if ( ancestor.nextSibling )
return ancestor.nextSibling ;
else
ancestor = ancestor.parentNode ;
}
}
return null ;
}
FCKTools.GetNextTextNode = function( textnode, limitNode, checkStop )
{
node = this.GetNextNode( textnode, limitNode ) ;
if ( checkStop && node && checkStop( node ) )
return null ;
while ( node && node.nodeType != 3 )
{
node = this.GetNextNode( node, limitNode ) ;
if ( checkStop && node && checkStop( node ) )
return null ;
}
return node ;
}
/**
* Merge all objects passed by argument into a single object.
*/
FCKTools.Merge = function()
{
var args = arguments ;
var o = args[0] ;
for ( var i = 1 ; i < args.length ; i++ )
{
var arg = args[i] ;
for ( var p in arg )
o[p] = arg[p] ;
}
return o ;
}
/**
* Check if the passed argument is a real Array. It may not working when
* calling it cross windows.
*/
FCKTools.IsArray = function( it )
{
return ( it instanceof Array ) ;
}
/**
* Appends a "length" property to an object, containing the number of
* properties available on it, excluded the append property itself.
*/
FCKTools.AppendLengthProperty = function( targetObject, propertyName )
{
var counter = 0 ;
for ( var n in targetObject )
counter++ ;
return targetObject[ propertyName || 'length' ] = counter ;
}
/**
* Gets the browser parsed version of a css text (style attribute value). On
* some cases, the browser makes changes to the css text, returning a different
* value. For example, hexadecimal colors get transformed to rgb().
*/
FCKTools.NormalizeCssText = function( unparsedCssText )
{
// Injects the style in a temporary span object, so the browser parses it,
// retrieving its final format.
var tempSpan = document.createElement( 'span' ) ;
tempSpan.style.cssText = unparsedCssText ;
return tempSpan.style.cssText ;
}
/**
* Binding the "this" reference to an object for a function.
*/
FCKTools.Bind = function( subject, func )
{
return function(){ return func.apply( subject, arguments ) ; } ;
}
/**
* Retrieve the correct "empty iframe" URL for the current browser, which
* causes the minimum fuzz (e.g. security warnings in HTTPS, DNS error in
* IE5.5, etc.) for that browser, making the iframe ready to DOM use whithout
* having to loading an external file.
*/
FCKTools.GetVoidUrl = function()
{
if ( FCK_IS_CUSTOM_DOMAIN )
return "javascript: void( function(){" +
"document.open();" +
"document.write('<html><head><title></title></head><body></body></html>');" +
"document.domain = '" + FCK_RUNTIME_DOMAIN + "';" +
"document.close();" +
"}() ) ;";
if ( FCKBrowserInfo.IsIE )
{
if ( FCKBrowserInfo.IsIE7 || !FCKBrowserInfo.IsIE6 )
return "" ; // IE7+ / IE5.5
else
return "javascript: '';" ; // IE6+
}
return "javascript: void(0);" ; // All other browsers.
}
FCKTools.ResetStyles = function( element )
{
element.style.cssText = 'margin:0;' +
'padding:0;' +
'border:0;' +
'background-color:transparent;' +
'background-image:none;' ;
}
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* Defines the FCKXHtml object, responsible for the XHTML operations.
* Gecko specific.
*/
FCKXHtml._GetMainXmlString = function()
{
return ( new XMLSerializer() ).serializeToString( this.MainNode ) ;
}
FCKXHtml._AppendAttributes = function( xmlNode, htmlNode, node )
{
var aAttributes = htmlNode.attributes ;
for ( var n = 0 ; n < aAttributes.length ; n++ )
{
var oAttribute = aAttributes[n] ;
if ( oAttribute.specified )
{
var sAttName = oAttribute.nodeName.toLowerCase() ;
var sAttValue ;
// Ignore any attribute starting with "_fck".
if ( sAttName.StartsWith( '_fck' ) )
continue ;
// There is a bug in Mozilla that returns '_moz_xxx' attributes as specified.
else if ( sAttName.indexOf( '_moz' ) == 0 )
continue ;
// There are one cases (on Gecko) when the oAttribute.nodeValue must be used:
// - for the "class" attribute
else if ( sAttName == 'class' )
{
sAttValue = oAttribute.nodeValue.replace( FCKRegexLib.FCK_Class, '' ) ;
if ( sAttValue.length == 0 )
continue ;
}
// XHTML doens't support attribute minimization like "CHECKED". It must be transformed to checked="checked".
else if ( oAttribute.nodeValue === true )
sAttValue = sAttName ;
else
sAttValue = htmlNode.getAttribute( sAttName, 2 ) ; // We must use getAttribute to get it exactly as it is defined.
this._AppendAttribute( node, sAttName, sAttValue ) ;
}
}
}
if ( FCKBrowserInfo.IsOpera )
{
// Opera moves the <FCK:meta> element outside head (#1166).
// Save a reference to the XML <head> node, so we can use it for
// orphan <meta>s.
FCKXHtml.TagProcessors['head'] = function( node, htmlNode )
{
FCKXHtml.XML._HeadElement = node ;
node = FCKXHtml._AppendChildNodes( node, htmlNode, true ) ;
return node ;
}
// Check whether a <meta> element is outside <head>, and move it to the
// proper place.
FCKXHtml.TagProcessors['meta'] = function( node, htmlNode, xmlNode )
{
if ( htmlNode.parentNode.nodeName.toLowerCase() != 'head' )
{
var headElement = FCKXHtml.XML._HeadElement ;
if ( headElement && xmlNode != headElement )
{
delete htmlNode._fckxhtmljob ;
FCKXHtml._AppendNode( headElement, htmlNode ) ;
return null ;
}
}
return node ;
}
}
if ( FCKBrowserInfo.IsGecko )
{
// #2162, some Firefox extensions might add references to internal links
FCKXHtml.TagProcessors['link'] = function( node, htmlNode )
{
if ( htmlNode.href.substr(0, 9).toLowerCase() == 'chrome://' )
return false ;
return node ;
}
}
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* Manage table operations.
*/
var FCKTableHandler = new Object() ;
FCKTableHandler.InsertRow = function( insertBefore )
{
// Get the row where the selection is placed in.
var oRow = FCKSelection.MoveToAncestorNode( 'TR' ) ;
if ( !oRow ) return ;
// Create a clone of the row.
var oNewRow = oRow.cloneNode( true ) ;
// Insert the new row (copy) before of it.
oRow.parentNode.insertBefore( oNewRow, oRow ) ;
// Clean one of the rows to produce the illusion of inserting an empty row before or after.
FCKTableHandler.ClearRow( insertBefore ? oNewRow : oRow ) ;
}
FCKTableHandler.DeleteRows = function( row )
{
// If no row has been passed as a parameter,
// then get the row( s ) containing the cells where the selection is placed in.
// If user selected multiple rows ( by selecting multiple cells ), walk
// the selected cell list and delete the rows containing the selected cells
if ( ! row )
{
var aCells = FCKTableHandler.GetSelectedCells() ;
var aRowsToDelete = new Array() ;
//queue up the rows -- it's possible ( and likely ) that we may get duplicates
for ( var i = 0; i < aCells.length; i++ )
{
var oRow = FCKTools.GetElementAscensor( aCells[i],'TR' ) ;
aRowsToDelete[oRow.rowIndex] = oRow ;
}
for ( var i = aRowsToDelete.length; i >= 0; i-- )
{
if ( aRowsToDelete[i] )
FCKTableHandler.DeleteRows( aRowsToDelete[i] );
}
return ;
}
// Get the row's table.
var oTable = FCKTools.GetElementAscensor( row, 'TABLE' ) ;
// If just one row is available then delete the entire table.
if ( oTable.rows.length == 1 )
{
FCKTableHandler.DeleteTable( oTable ) ;
return ;
}
// Delete the row.
row.parentNode.removeChild( row ) ;
}
FCKTableHandler.DeleteTable = function( table )
{
// If no table has been passed as a parameter,
// then get the table where the selection is placed in.
if ( !table )
{
table = FCKSelection.GetSelectedElement() ;
if ( !table || table.tagName != 'TABLE' )
table = FCKSelection.MoveToAncestorNode( 'TABLE' ) ;
}
if ( !table ) return ;
// Delete the table.
FCKSelection.SelectNode( table ) ;
FCKSelection.Collapse();
// if the table is wrapped with a singleton <p> ( or something similar ), remove
// the surrounding tag -- which likely won't show after deletion anyway
if ( table.parentNode.childNodes.length == 1 )
table.parentNode.parentNode.removeChild( table.parentNode );
else
table.parentNode.removeChild( table ) ;
}
FCKTableHandler.InsertColumn = function( insertBefore )
{
// Get the cell where the selection is placed in.
var oCell = null ;
var nodes = this.GetSelectedCells() ;
if ( nodes && nodes.length )
oCell = nodes[ insertBefore ? 0 : ( nodes.length - 1 ) ] ;
if ( ! oCell )
return ;
// Get the cell's table.
var oTable = FCKTools.GetElementAscensor( oCell, 'TABLE' ) ;
var iIndex = oCell.cellIndex ;
// Loop throw all rows available in the table.
for ( var i = 0 ; i < oTable.rows.length ; i++ )
{
// Get the row.
var oRow = oTable.rows[i] ;
// If the row doens't have enough cells, ignore it.
if ( oRow.cells.length < ( iIndex + 1 ) )
continue ;
oCell = oRow.cells[iIndex].cloneNode(false) ;
if ( FCKBrowserInfo.IsGeckoLike )
FCKTools.AppendBogusBr( oCell ) ;
// Get back the currently selected cell.
var oBaseCell = oRow.cells[iIndex] ;
if ( insertBefore )
oRow.insertBefore( oCell, oBaseCell ) ;
else if ( oBaseCell.nextSibling )
oRow.insertBefore( oCell, oBaseCell.nextSibling ) ;
else
oRow.appendChild( oCell ) ;
}
}
FCKTableHandler.DeleteColumns = function( oCell )
{
// if user selected multiple cols ( by selecting multiple cells ), walk
// the selected cell list and delete the rows containing the selected cells
if ( !oCell )
{
var aColsToDelete = FCKTableHandler.GetSelectedCells();
for ( var i = aColsToDelete.length; i >= 0; i-- )
{
if ( aColsToDelete[i] )
FCKTableHandler.DeleteColumns( aColsToDelete[i] );
}
return;
}
if ( !oCell ) return ;
// Get the cell's table.
var oTable = FCKTools.GetElementAscensor( oCell, 'TABLE' ) ;
// Get the cell index.
var iIndex = oCell.cellIndex ;
// Loop throw all rows (from down to up, because it's possible that some
// rows will be deleted).
for ( var i = oTable.rows.length - 1 ; i >= 0 ; i-- )
{
// Get the row.
var oRow = oTable.rows[i] ;
// If the cell to be removed is the first one and the row has just one cell.
if ( iIndex == 0 && oRow.cells.length == 1 )
{
// Remove the entire row.
FCKTableHandler.DeleteRows( oRow ) ;
continue ;
}
// If the cell to be removed exists the delete it.
if ( oRow.cells[iIndex] )
oRow.removeChild( oRow.cells[iIndex] ) ;
}
}
FCKTableHandler.InsertCell = function( cell, insertBefore )
{
// Get the cell where the selection is placed in.
var oCell = null ;
var nodes = this.GetSelectedCells() ;
if ( nodes && nodes.length )
oCell = nodes[ insertBefore ? 0 : ( nodes.length - 1 ) ] ;
if ( ! oCell )
return null ;
// Create the new cell element to be added.
var oNewCell = FCK.EditorDocument.createElement( 'TD' ) ;
if ( FCKBrowserInfo.IsGeckoLike )
FCKTools.AppendBogusBr( oNewCell ) ;
if ( !insertBefore && oCell.cellIndex == oCell.parentNode.cells.length - 1 )
oCell.parentNode.appendChild( oNewCell ) ;
else
oCell.parentNode.insertBefore( oNewCell, insertBefore ? oCell : oCell.nextSibling ) ;
return oNewCell ;
}
FCKTableHandler.DeleteCell = function( cell )
{
// If this is the last cell in the row.
if ( cell.parentNode.cells.length == 1 )
{
// Delete the entire row.
FCKTableHandler.DeleteRows( FCKTools.GetElementAscensor( cell, 'TR' ) ) ;
return ;
}
// Delete the cell from the row.
cell.parentNode.removeChild( cell ) ;
}
FCKTableHandler.DeleteCells = function()
{
var aCells = FCKTableHandler.GetSelectedCells() ;
for ( var i = aCells.length - 1 ; i >= 0 ; i-- )
{
FCKTableHandler.DeleteCell( aCells[i] ) ;
}
}
FCKTableHandler._MarkCells = function( cells, label )
{
for ( var i = 0 ; i < cells.length ; i++ )
cells[i][label] = true ;
}
FCKTableHandler._UnmarkCells = function( cells, label )
{
for ( var i = 0 ; i < cells.length ; i++ )
{
if ( FCKBrowserInfo.IsIE )
cells[i].removeAttribute( label ) ;
else
delete cells[i][label] ;
}
}
FCKTableHandler._ReplaceCellsByMarker = function( tableMap, marker, substitute )
{
for ( var i = 0 ; i < tableMap.length ; i++ )
{
for ( var j = 0 ; j < tableMap[i].length ; j++ )
{
if ( tableMap[i][j][marker] )
tableMap[i][j] = substitute ;
}
}
}
FCKTableHandler._GetMarkerGeometry = function( tableMap, rowIdx, colIdx, markerName )
{
var selectionWidth = 0 ;
var selectionHeight = 0 ;
var cellsLeft = 0 ;
var cellsUp = 0 ;
for ( var i = colIdx ; tableMap[rowIdx][i] && tableMap[rowIdx][i][markerName] ; i++ )
selectionWidth++ ;
for ( var i = colIdx - 1 ; tableMap[rowIdx][i] && tableMap[rowIdx][i][markerName] ; i-- )
{
selectionWidth++ ;
cellsLeft++ ;
}
for ( var i = rowIdx ; tableMap[i] && tableMap[i][colIdx] && tableMap[i][colIdx][markerName] ; i++ )
selectionHeight++ ;
for ( var i = rowIdx - 1 ; tableMap[i] && tableMap[i][colIdx] && tableMap[i][colIdx][markerName] ; i-- )
{
selectionHeight++ ;
cellsUp++ ;
}
return { 'width' : selectionWidth, 'height' : selectionHeight, 'x' : cellsLeft, 'y' : cellsUp } ;
}
FCKTableHandler.CheckIsSelectionRectangular = function()
{
// If every row and column in an area on a plane are of the same width and height,
// Then the area is a rectangle.
var cells = FCKTableHandler.GetSelectedCells() ;
if ( cells.length < 1 )
return false ;
this._MarkCells( cells, '_CellSelected' ) ;
var tableMap = this._CreateTableMap( cells[0].parentNode.parentNode ) ;
var rowIdx = cells[0].parentNode.rowIndex ;
var colIdx = this._GetCellIndexSpan( tableMap, rowIdx, cells[0] ) ;
var geometry = this._GetMarkerGeometry( tableMap, rowIdx, colIdx, '_CellSelected' ) ;
var baseColIdx = colIdx - geometry.x ;
var baseRowIdx = rowIdx - geometry.y ;
if ( geometry.width >= geometry.height )
{
for ( colIdx = baseColIdx ; colIdx < baseColIdx + geometry.width ; colIdx++ )
{
rowIdx = baseRowIdx + ( colIdx - baseColIdx ) % geometry.height ;
if ( ! tableMap[rowIdx] || ! tableMap[rowIdx][colIdx] )
{
this._UnmarkCells( cells, '_CellSelected' ) ;
return false ;
}
var g = this._GetMarkerGeometry( tableMap, rowIdx, colIdx, '_CellSelected' ) ;
if ( g.width != geometry.width || g.height != geometry.height )
{
this._UnmarkCells( cells, '_CellSelected' ) ;
return false ;
}
}
}
else
{
for ( rowIdx = baseRowIdx ; rowIdx < baseRowIdx + geometry.height ; rowIdx++ )
{
colIdx = baseColIdx + ( rowIdx - baseRowIdx ) % geometry.width ;
if ( ! tableMap[rowIdx] || ! tableMap[rowIdx][colIdx] )
{
this._UnmarkCells( cells, '_CellSelected' ) ;
return false ;
}
var g = this._GetMarkerGeometry( tableMap, rowIdx, colIdx, '_CellSelected' ) ;
if ( g.width != geometry.width || g.height != geometry.height )
{
this._UnmarkCells( cells, '_CellSelected' ) ;
return false ;
}
}
}
this._UnmarkCells( cells, '_CellSelected' ) ;
return true ;
}
FCKTableHandler.MergeCells = function()
{
// Get all selected cells.
var cells = this.GetSelectedCells() ;
if ( cells.length < 2 )
return ;
// Assume the selected cells are already in a rectangular geometry.
// Because the checking is already done by FCKTableCommand.
var refCell = cells[0] ;
var tableMap = this._CreateTableMap( refCell.parentNode.parentNode ) ;
var rowIdx = refCell.parentNode.rowIndex ;
var colIdx = this._GetCellIndexSpan( tableMap, rowIdx, refCell ) ;
this._MarkCells( cells, '_SelectedCells' ) ;
var selectionGeometry = this._GetMarkerGeometry( tableMap, rowIdx, colIdx, '_SelectedCells' ) ;
var baseColIdx = colIdx - selectionGeometry.x ;
var baseRowIdx = rowIdx - selectionGeometry.y ;
var cellContents = FCKTools.GetElementDocument( refCell ).createDocumentFragment() ;
for ( var i = 0 ; i < selectionGeometry.height ; i++ )
{
var rowChildNodesCount = 0 ;
for ( var j = 0 ; j < selectionGeometry.width ; j++ )
{
var currentCell = tableMap[baseRowIdx + i][baseColIdx + j] ;
while ( currentCell.childNodes.length > 0 )
{
var node = currentCell.removeChild( currentCell.firstChild ) ;
if ( node.nodeType != 1
|| ( node.getAttribute( 'type', 2 ) != '_moz' && node.getAttribute( '_moz_dirty' ) != null ) )
{
cellContents.appendChild( node ) ;
rowChildNodesCount++ ;
}
}
}
if ( rowChildNodesCount > 0 )
cellContents.appendChild( FCKTools.GetElementDocument( refCell ).createElement( 'br' ) ) ;
}
this._ReplaceCellsByMarker( tableMap, '_SelectedCells', refCell ) ;
this._UnmarkCells( cells, '_SelectedCells' ) ;
this._InstallTableMap( tableMap, refCell.parentNode.parentNode ) ;
refCell.appendChild( cellContents ) ;
if ( FCKBrowserInfo.IsGeckoLike && ( ! refCell.firstChild ) )
FCKTools.AppendBogusBr( refCell ) ;
this._MoveCaretToCell( refCell, false ) ;
}
FCKTableHandler.MergeRight = function()
{
var target = this.GetMergeRightTarget() ;
if ( target == null )
return ;
var refCell = target.refCell ;
var tableMap = target.tableMap ;
var nextCell = target.nextCell ;
var cellContents = FCK.EditorDocument.createDocumentFragment() ;
while ( nextCell && nextCell.childNodes && nextCell.childNodes.length > 0 )
cellContents.appendChild( nextCell.removeChild( nextCell.firstChild ) ) ;
nextCell.parentNode.removeChild( nextCell ) ;
refCell.appendChild( cellContents ) ;
this._MarkCells( [nextCell], '_Replace' ) ;
this._ReplaceCellsByMarker( tableMap, '_Replace', refCell ) ;
this._InstallTableMap( tableMap, refCell.parentNode.parentNode ) ;
this._MoveCaretToCell( refCell, false ) ;
}
FCKTableHandler.MergeDown = function()
{
var target = this.GetMergeDownTarget() ;
if ( target == null )
return ;
var refCell = target.refCell ;
var tableMap = target.tableMap ;
var nextCell = target.nextCell ;
var cellContents = FCKTools.GetElementDocument( refCell ).createDocumentFragment() ;
while ( nextCell && nextCell.childNodes && nextCell.childNodes.length > 0 )
cellContents.appendChild( nextCell.removeChild( nextCell.firstChild ) ) ;
if ( cellContents.firstChild )
cellContents.insertBefore( FCKTools.GetElementDocument( nextCell ).createElement( 'br' ), cellContents.firstChild ) ;
refCell.appendChild( cellContents ) ;
this._MarkCells( [nextCell], '_Replace' ) ;
this._ReplaceCellsByMarker( tableMap, '_Replace', refCell ) ;
this._InstallTableMap( tableMap, refCell.parentNode.parentNode ) ;
this._MoveCaretToCell( refCell, false ) ;
}
FCKTableHandler.HorizontalSplitCell = function()
{
var cells = FCKTableHandler.GetSelectedCells() ;
if ( cells.length != 1 )
return ;
var refCell = cells[0] ;
var tableMap = this._CreateTableMap( refCell.parentNode.parentNode ) ;
var rowIdx = refCell.parentNode.rowIndex ;
var colIdx = FCKTableHandler._GetCellIndexSpan( tableMap, rowIdx, refCell ) ;
var cellSpan = isNaN( refCell.colSpan ) ? 1 : refCell.colSpan ;
if ( cellSpan > 1 )
{
// Splittng a multi-column cell - original cell gets ceil(colSpan/2) columns,
// new cell gets floor(colSpan/2).
var newCellSpan = Math.ceil( cellSpan / 2 ) ;
var newCell = FCKTools.GetElementDocument( refCell ).createElement( 'td' ) ;
if ( FCKBrowserInfo.IsGeckoLike )
FCKTools.AppendBogusBr( newCell ) ;
var startIdx = colIdx + newCellSpan ;
var endIdx = colIdx + cellSpan ;
var rowSpan = isNaN( refCell.rowSpan ) ? 1 : refCell.rowSpan ;
for ( var r = rowIdx ; r < rowIdx + rowSpan ; r++ )
{
for ( var i = startIdx ; i < endIdx ; i++ )
tableMap[r][i] = newCell ;
}
}
else
{
// Splitting a single-column cell - add a new cell, and expand
// cells crossing the same column.
var newTableMap = [] ;
for ( var i = 0 ; i < tableMap.length ; i++ )
{
var newRow = tableMap[i].slice( 0, colIdx ) ;
if ( tableMap[i].length <= colIdx )
{
newTableMap.push( newRow ) ;
continue ;
}
if ( tableMap[i][colIdx] == refCell )
{
newRow.push( refCell ) ;
newRow.push( FCKTools.GetElementDocument( refCell ).createElement( 'td' ) ) ;
if ( FCKBrowserInfo.IsGeckoLike )
FCKTools.AppendBogusBr( newRow[newRow.length - 1] ) ;
}
else
{
newRow.push( tableMap[i][colIdx] ) ;
newRow.push( tableMap[i][colIdx] ) ;
}
for ( var j = colIdx + 1 ; j < tableMap[i].length ; j++ )
newRow.push( tableMap[i][j] ) ;
newTableMap.push( newRow ) ;
}
tableMap = newTableMap ;
}
this._InstallTableMap( tableMap, refCell.parentNode.parentNode ) ;
}
FCKTableHandler.VerticalSplitCell = function()
{
var cells = FCKTableHandler.GetSelectedCells() ;
if ( cells.length != 1 )
return ;
var currentCell = cells[0] ;
var tableMap = this._CreateTableMap( currentCell.parentNode.parentNode ) ;
var cellIndex = FCKTableHandler._GetCellIndexSpan( tableMap, currentCell.parentNode.rowIndex, currentCell ) ;
var currentRowSpan = currentCell.rowSpan ;
var currentRowIndex = currentCell.parentNode.rowIndex ;
if ( isNaN( currentRowSpan ) )
currentRowSpan = 1 ;
if ( currentRowSpan > 1 )
{
// 1. Set the current cell's rowSpan to 1.
currentCell.rowSpan = Math.ceil( currentRowSpan / 2 ) ;
// 2. Find the appropriate place to insert a new cell at the next row.
var newCellRowIndex = currentRowIndex + Math.ceil( currentRowSpan / 2 ) ;
var insertMarker = null ;
for ( var i = cellIndex+1 ; i < tableMap[newCellRowIndex].length ; i++ )
{
if ( tableMap[newCellRowIndex][i].parentNode.rowIndex == newCellRowIndex )
{
insertMarker = tableMap[newCellRowIndex][i] ;
break ;
}
}
// 3. Insert the new cell to the indicated place, with the appropriate rowSpan, next row.
var newCell = FCK.EditorDocument.createElement( 'td' ) ;
newCell.rowSpan = Math.floor( currentRowSpan / 2 ) ;
if ( FCKBrowserInfo.IsGeckoLike )
FCKTools.AppendBogusBr( newCell ) ;
currentCell.parentNode.parentNode.rows[newCellRowIndex].insertBefore( newCell, insertMarker ) ;
}
else
{
// 1. Insert a new row.
var newCellRowIndex = currentRowIndex + 1 ;
var newRow = FCK.EditorDocument.createElement( 'tr' ) ;
var tBody = currentCell.parentNode.parentNode ;
if ( tBody.rows.length > newCellRowIndex )
tBody.insertBefore( newRow, tBody.rows[newCellRowIndex] ) ;
else
tBody.appendChild( newRow ) ;
// 2. +1 to rowSpan for all cells crossing currentCell's row.
for ( var i = 0 ; i < tableMap[currentRowIndex].length ; )
{
var colSpan = tableMap[currentRowIndex][i].colSpan ;
if ( isNaN( colSpan ) || colSpan < 1 )
colSpan = 1 ;
if ( i == cellIndex )
{
i += colSpan ;
continue ;
}
var rowSpan = tableMap[currentRowIndex][i].rowSpan ;
if ( isNaN( rowSpan ) )
rowSpan = 1 ;
tableMap[currentRowIndex][i].rowSpan = rowSpan + 1 ;
i += colSpan ;
}
// 3. Insert a new cell to new row.
var newCell = FCK.EditorDocument.createElement( 'td' ) ;
if ( FCKBrowserInfo.IsGeckoLike )
FCKTools.AppendBogusBr( newCell ) ;
newRow.appendChild( newCell ) ;
}
}
// Get the cell index from a TableMap.
FCKTableHandler._GetCellIndexSpan = function( tableMap, rowIndex, cell )
{
if ( tableMap.length < rowIndex + 1 )
return null ;
var oRow = tableMap[ rowIndex ] ;
for ( var c = 0 ; c < oRow.length ; c++ )
{
if ( oRow[c] == cell )
return c ;
}
return null ;
}
// Get the cell location from a TableMap. Returns an array with an [x,y] location
FCKTableHandler._GetCellLocation = function( tableMap, cell )
{
for ( var i = 0 ; i < tableMap.length; i++ )
{
for ( var c = 0 ; c < tableMap[i].length ; c++ )
{
if ( tableMap[i][c] == cell ) return [i,c];
}
}
return null ;
}
// Get the cells available in a column of a TableMap.
FCKTableHandler._GetColumnCells = function( tableMap, columnIndex )
{
var aCollCells = new Array() ;
for ( var r = 0 ; r < tableMap.length ; r++ )
{
var oCell = tableMap[r][columnIndex] ;
if ( oCell && ( aCollCells.length == 0 || aCollCells[ aCollCells.length - 1 ] != oCell ) )
aCollCells[ aCollCells.length ] = oCell ;
}
return aCollCells ;
}
// This function is quite hard to explain. It creates a matrix representing all cells in a table.
// The difference here is that the "spanned" cells (colSpan and rowSpan) are duplicated on the matrix
// cells that are "spanned". For example, a row with 3 cells where the second cell has colSpan=2 and rowSpan=3
// will produce a bi-dimensional matrix with the following values (representing the cells):
// Cell1, Cell2, Cell2, Cell 3
// Cell4, Cell2, Cell2, Cell 5
FCKTableHandler._CreateTableMap = function( table )
{
var aRows = table.rows ;
// Row and Column counters.
var r = -1 ;
var aMap = new Array() ;
for ( var i = 0 ; i < aRows.length ; i++ )
{
r++ ;
if ( !aMap[r] )
aMap[r] = new Array() ;
var c = -1 ;
for ( var j = 0 ; j < aRows[i].cells.length ; j++ )
{
var oCell = aRows[i].cells[j] ;
c++ ;
while ( aMap[r][c] )
c++ ;
var iColSpan = isNaN( oCell.colSpan ) ? 1 : oCell.colSpan ;
var iRowSpan = isNaN( oCell.rowSpan ) ? 1 : oCell.rowSpan ;
for ( var rs = 0 ; rs < iRowSpan ; rs++ )
{
if ( !aMap[r + rs] )
aMap[r + rs] = new Array() ;
for ( var cs = 0 ; cs < iColSpan ; cs++ )
{
aMap[r + rs][c + cs] = aRows[i].cells[j] ;
}
}
c += iColSpan - 1 ;
}
}
return aMap ;
}
// This function is the inverse of _CreateTableMap - it takes in a table map and converts it to an HTML table.
FCKTableHandler._InstallTableMap = function( tableMap, table )
{
// Workaround for #1917 : MSIE will always report a cell's rowSpan as 1 as long
// as the cell is not attached to a row. So we'll need an alternative attribute
// for storing the calculated rowSpan in IE.
var rowSpanAttr = FCKBrowserInfo.IsIE ? "_fckrowspan" : "rowSpan" ;
// Clear the table of all rows first.
while ( table.rows.length > 0 )
{
var row = table.rows[0] ;
row.parentNode.removeChild( row ) ;
}
// Disconnect all the cells in tableMap from their parents, set all colSpan and rowSpan attributes to 1.
for ( var i = 0 ; i < tableMap.length ; i++ )
{
for ( var j = 0 ; j < tableMap[i].length ; j++ )
{
var cell = tableMap[i][j] ;
if ( cell.parentNode )
cell.parentNode.removeChild( cell ) ;
cell.colSpan = cell[rowSpanAttr] = 1 ;
}
}
// Scan by rows and set colSpan.
var maxCol = 0 ;
for ( var i = 0 ; i < tableMap.length ; i++ )
{
for ( var j = 0 ; j < tableMap[i].length ; j++ )
{
var cell = tableMap[i][j] ;
if ( ! cell)
continue ;
if ( j > maxCol )
maxCol = j ;
if ( cell._colScanned === true )
continue ;
if ( tableMap[i][j-1] == cell )
cell.colSpan++ ;
if ( tableMap[i][j+1] != cell )
cell._colScanned = true ;
}
}
// Scan by columns and set rowSpan.
for ( var i = 0 ; i <= maxCol ; i++ )
{
for ( var j = 0 ; j < tableMap.length ; j++ )
{
if ( ! tableMap[j] )
continue ;
var cell = tableMap[j][i] ;
if ( ! cell || cell._rowScanned === true )
continue ;
if ( tableMap[j-1] && tableMap[j-1][i] == cell )
cell[rowSpanAttr]++ ;
if ( ! tableMap[j+1] || tableMap[j+1][i] != cell )
cell._rowScanned = true ;
}
}
// Clear all temporary flags.
for ( var i = 0 ; i < tableMap.length ; i++ )
{
for ( var j = 0 ; j < tableMap[i].length ; j++)
{
var cell = tableMap[i][j] ;
if ( FCKBrowserInfo.IsIE )
{
cell.removeAttribute( '_colScanned' ) ;
cell.removeAttribute( '_rowScanned' ) ;
}
else
{
delete cell._colScanned ;
delete cell._rowScanned ;
}
}
}
// Insert physical rows and columns to the table.
for ( var i = 0 ; i < tableMap.length ; i++ )
{
var rowObj = FCKTools.GetElementDocument( table ).createElement( 'tr' ) ;
for ( var j = 0 ; j < tableMap[i].length ; )
{
var cell = tableMap[i][j] ;
if ( tableMap[i-1] && tableMap[i-1][j] == cell )
{
j += cell.colSpan ;
continue ;
}
rowObj.appendChild( cell ) ;
if ( rowSpanAttr != 'rowSpan' )
{
cell.rowSpan = cell[rowSpanAttr] ;
cell.removeAttribute( rowSpanAttr ) ;
}
j += cell.colSpan ;
if ( cell.colSpan == 1 )
cell.removeAttribute( 'colspan' ) ;
if ( cell.rowSpan == 1 )
cell.removeAttribute( 'rowspan' ) ;
}
table.appendChild( rowObj ) ;
}
}
FCKTableHandler._MoveCaretToCell = function ( refCell, toStart )
{
var range = new FCKDomRange( FCK.EditorWindow ) ;
range.MoveToNodeContents( refCell ) ;
range.Collapse( toStart ) ;
range.Select() ;
}
FCKTableHandler.ClearRow = function( tr )
{
// Get the array of row's cells.
var aCells = tr.cells ;
// Replace the contents of each cell with "nothing".
for ( var i = 0 ; i < aCells.length ; i++ )
{
aCells[i].innerHTML = '' ;
if ( FCKBrowserInfo.IsGeckoLike )
FCKTools.AppendBogusBr( aCells[i] ) ;
}
}
FCKTableHandler.GetMergeRightTarget = function()
{
var cells = this.GetSelectedCells() ;
if ( cells.length != 1 )
return null ;
var refCell = cells[0] ;
var tableMap = this._CreateTableMap( refCell.parentNode.parentNode ) ;
var rowIdx = refCell.parentNode.rowIndex ;
var colIdx = this._GetCellIndexSpan( tableMap, rowIdx, refCell ) ;
var nextColIdx = colIdx + ( isNaN( refCell.colSpan ) ? 1 : refCell.colSpan ) ;
var nextCell = tableMap[rowIdx][nextColIdx] ;
if ( ! nextCell )
return null ;
// The two cells must have the same vertical geometry, otherwise merging does not make sense.
this._MarkCells( [refCell, nextCell], '_SizeTest' ) ;
var refGeometry = this._GetMarkerGeometry( tableMap, rowIdx, colIdx, '_SizeTest' ) ;
var nextGeometry = this._GetMarkerGeometry( tableMap, rowIdx, nextColIdx, '_SizeTest' ) ;
this._UnmarkCells( [refCell, nextCell], '_SizeTest' ) ;
if ( refGeometry.height != nextGeometry.height || refGeometry.y != nextGeometry.y )
return null ;
return { 'refCell' : refCell, 'nextCell' : nextCell, 'tableMap' : tableMap } ;
}
FCKTableHandler.GetMergeDownTarget = function()
{
var cells = this.GetSelectedCells() ;
if ( cells.length != 1 )
return null ;
var refCell = cells[0] ;
var tableMap = this._CreateTableMap( refCell.parentNode.parentNode ) ;
var rowIdx = refCell.parentNode.rowIndex ;
var colIdx = this._GetCellIndexSpan( tableMap, rowIdx, refCell ) ;
var newRowIdx = rowIdx + ( isNaN( refCell.rowSpan ) ? 1 : refCell.rowSpan ) ;
if ( ! tableMap[newRowIdx] )
return null ;
var nextCell = tableMap[newRowIdx][colIdx] ;
if ( ! nextCell )
return null ;
// The two cells must have the same horizontal geometry, otherwise merging does not makes sense.
this._MarkCells( [refCell, nextCell], '_SizeTest' ) ;
var refGeometry = this._GetMarkerGeometry( tableMap, rowIdx, colIdx, '_SizeTest' ) ;
var nextGeometry = this._GetMarkerGeometry( tableMap, newRowIdx, colIdx, '_SizeTest' ) ;
this._UnmarkCells( [refCell, nextCell], '_SizeTest' ) ;
if ( refGeometry.width != nextGeometry.width || refGeometry.x != nextGeometry.x )
return null ;
return { 'refCell' : refCell, 'nextCell' : nextCell, 'tableMap' : tableMap } ;
}
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* Creation and initialization of the "FCK" object. This is the main
* object that represents an editor instance.
* (Gecko specific implementations)
*/
FCK.Description = "FCKeditor for Gecko Browsers" ;
FCK.InitializeBehaviors = function()
{
// When calling "SetData", the editing area IFRAME gets a fixed height. So we must recalculate it.
if ( window.onresize ) // Not for Safari/Opera.
window.onresize() ;
FCKFocusManager.AddWindow( this.EditorWindow ) ;
this.ExecOnSelectionChange = function()
{
FCK.Events.FireEvent( "OnSelectionChange" ) ;
}
this._ExecDrop = function( evt )
{
if ( FCK.MouseDownFlag )
{
FCK.MouseDownFlag = false ;
return ;
}
if ( FCKConfig.ForcePasteAsPlainText )
{
if ( evt.dataTransfer )
{
var text = evt.dataTransfer.getData( 'Text' ) ;
text = FCKTools.HTMLEncode( text ) ;
text = FCKTools.ProcessLineBreaks( window, FCKConfig, text ) ;
FCK.InsertHtml( text ) ;
}
else if ( FCKConfig.ShowDropDialog )
FCK.PasteAsPlainText() ;
evt.preventDefault() ;
evt.stopPropagation() ;
}
}
this._ExecCheckCaret = function( evt )
{
if ( FCK.EditMode != FCK_EDITMODE_WYSIWYG )
return ;
if ( evt.type == 'keypress' )
{
var keyCode = evt.keyCode ;
// ignore if positioning key is not pressed.
// left or up arrow keys need to be processed as well, since <a> links can be expanded in Gecko's editor
// when the caret moved left or up from another block element below.
if ( keyCode < 33 || keyCode > 40 )
return ;
}
var blockEmptyStop = function( node )
{
if ( node.nodeType != 1 )
return false ;
var tag = node.tagName.toLowerCase() ;
return ( FCKListsLib.BlockElements[tag] || FCKListsLib.EmptyElements[tag] ) ;
}
var moveCursor = function()
{
var selection = FCKSelection.GetSelection() ;
var range = selection.getRangeAt(0) ;
if ( ! range || ! range.collapsed )
return ;
var node = range.endContainer ;
// only perform the patched behavior if we're at the end of a text node.
if ( node.nodeType != 3 )
return ;
if ( node.nodeValue.length != range.endOffset )
return ;
// only perform the patched behavior if we're in an <a> tag, or the End key is pressed.
var parentTag = node.parentNode.tagName.toLowerCase() ;
if ( ! ( parentTag == 'a' || ( !FCKBrowserInfo.IsOpera && String(node.parentNode.contentEditable) == 'false' ) ||
( ! ( FCKListsLib.BlockElements[parentTag] || FCKListsLib.NonEmptyBlockElements[parentTag] )
&& keyCode == 35 ) ) )
return ;
// our caret has moved to just after the last character of a text node under an unknown tag, how to proceed?
// first, see if there are other text nodes by DFS walking from this text node.
// - if the DFS has scanned all nodes under my parent, then go the next step.
// - if there is a text node after me but still under my parent, then do nothing and return.
var nextTextNode = FCKTools.GetNextTextNode( node, node.parentNode, blockEmptyStop ) ;
if ( nextTextNode )
return ;
// we're pretty sure we need to move the caret forcefully from here.
range = FCK.EditorDocument.createRange() ;
nextTextNode = FCKTools.GetNextTextNode( node, node.parentNode.parentNode, blockEmptyStop ) ;
if ( nextTextNode )
{
// Opera thinks the dummy empty text node we append beyond the end of <a> nodes occupies a caret
// position. So if the user presses the left key and we reset the caret position here, the user
// wouldn't be able to go back.
if ( FCKBrowserInfo.IsOpera && keyCode == 37 )
return ;
// now we want to get out of our current parent node, adopt the next parent, and move the caret to
// the appropriate text node under our new parent.
// our new parent might be our current parent's siblings if we are lucky.
range.setStart( nextTextNode, 0 ) ;
range.setEnd( nextTextNode, 0 ) ;
}
else
{
// no suitable next siblings under our grandparent! what to do next?
while ( node.parentNode
&& node.parentNode != FCK.EditorDocument.body
&& node.parentNode != FCK.EditorDocument.documentElement
&& node == node.parentNode.lastChild
&& ( ! FCKListsLib.BlockElements[node.parentNode.tagName.toLowerCase()]
&& ! FCKListsLib.NonEmptyBlockElements[node.parentNode.tagName.toLowerCase()] ) )
node = node.parentNode ;
if ( FCKListsLib.BlockElements[ parentTag ]
|| FCKListsLib.EmptyElements[ parentTag ]
|| node == FCK.EditorDocument.body )
{
// if our parent is a block node, move to the end of our parent.
range.setStart( node, node.childNodes.length ) ;
range.setEnd( node, node.childNodes.length ) ;
}
else
{
// things are a little bit more interesting if our parent is not a block node
// due to the weired ways how Gecko's caret acts...
var stopNode = node.nextSibling ;
// find out the next block/empty element at our grandparent, we'll
// move the caret just before it.
while ( stopNode )
{
if ( stopNode.nodeType != 1 )
{
stopNode = stopNode.nextSibling ;
continue ;
}
var stopTag = stopNode.tagName.toLowerCase() ;
if ( FCKListsLib.BlockElements[stopTag] || FCKListsLib.EmptyElements[stopTag]
|| FCKListsLib.NonEmptyBlockElements[stopTag] )
break ;
stopNode = stopNode.nextSibling ;
}
// note that the dummy marker below is NEEDED, otherwise the caret's behavior will
// be broken in Gecko.
var marker = FCK.EditorDocument.createTextNode( '' ) ;
if ( stopNode )
node.parentNode.insertBefore( marker, stopNode ) ;
else
node.parentNode.appendChild( marker ) ;
range.setStart( marker, 0 ) ;
range.setEnd( marker, 0 ) ;
}
}
selection.removeAllRanges() ;
selection.addRange( range ) ;
FCK.Events.FireEvent( "OnSelectionChange" ) ;
}
setTimeout( moveCursor, 1 ) ;
}
this.ExecOnSelectionChangeTimer = function()
{
if ( FCK.LastOnChangeTimer )
window.clearTimeout( FCK.LastOnChangeTimer ) ;
FCK.LastOnChangeTimer = window.setTimeout( FCK.ExecOnSelectionChange, 100 ) ;
}
this.EditorDocument.addEventListener( 'mouseup', this.ExecOnSelectionChange, false ) ;
// On Gecko, firing the "OnSelectionChange" event on every key press started to be too much
// slow. So, a timer has been implemented to solve performance issues when typing to quickly.
this.EditorDocument.addEventListener( 'keyup', this.ExecOnSelectionChangeTimer, false ) ;
this._DblClickListener = function( e )
{
FCK.OnDoubleClick( e.target ) ;
e.stopPropagation() ;
}
this.EditorDocument.addEventListener( 'dblclick', this._DblClickListener, true ) ;
// Record changes for the undo system when there are key down events.
this.EditorDocument.addEventListener( 'keydown', this._KeyDownListener, false ) ;
// Hooks for data object drops
if ( FCKBrowserInfo.IsGecko )
{
this.EditorWindow.addEventListener( 'dragdrop', this._ExecDrop, true ) ;
}
else if ( FCKBrowserInfo.IsSafari )
{
var cancelHandler = function( evt ){ if ( ! FCK.MouseDownFlag ) evt.returnValue = false ; }
this.EditorDocument.addEventListener( 'dragenter', cancelHandler, true ) ;
this.EditorDocument.addEventListener( 'dragover', cancelHandler, true ) ;
this.EditorDocument.addEventListener( 'drop', this._ExecDrop, true ) ;
this.EditorDocument.addEventListener( 'mousedown',
function( ev )
{
var element = ev.srcElement ;
if ( element.nodeName.IEquals( 'IMG', 'HR', 'INPUT', 'TEXTAREA', 'SELECT' ) )
{
FCKSelection.SelectNode( element ) ;
}
}, true ) ;
this.EditorDocument.addEventListener( 'mouseup',
function( ev )
{
if ( ev.srcElement.nodeName.IEquals( 'INPUT', 'TEXTAREA', 'SELECT' ) )
ev.preventDefault()
}, true ) ;
this.EditorDocument.addEventListener( 'click',
function( ev )
{
if ( ev.srcElement.nodeName.IEquals( 'INPUT', 'TEXTAREA', 'SELECT' ) )
ev.preventDefault()
}, true ) ;
}
// Kludge for buggy Gecko caret positioning logic (Bug #393 and #1056)
if ( FCKBrowserInfo.IsGecko || FCKBrowserInfo.IsOpera )
{
this.EditorDocument.addEventListener( 'keypress', this._ExecCheckCaret, false ) ;
this.EditorDocument.addEventListener( 'click', this._ExecCheckCaret, false ) ;
}
// Reset the context menu.
FCK.ContextMenu._InnerContextMenu.SetMouseClickWindow( FCK.EditorWindow ) ;
FCK.ContextMenu._InnerContextMenu.AttachToElement( FCK.EditorDocument ) ;
}
FCK.MakeEditable = function()
{
this.EditingArea.MakeEditable() ;
}
// Disable the context menu in the editor (outside the editing area).
function Document_OnContextMenu( e )
{
if ( !e.target._FCKShowContextMenu )
e.preventDefault() ;
}
document.oncontextmenu = Document_OnContextMenu ;
// GetNamedCommandState overload for Gecko.
FCK._BaseGetNamedCommandState = FCK.GetNamedCommandState ;
FCK.GetNamedCommandState = function( commandName )
{
switch ( commandName )
{
case 'Unlink' :
return FCKSelection.HasAncestorNode('A') ? FCK_TRISTATE_OFF : FCK_TRISTATE_DISABLED ;
default :
return FCK._BaseGetNamedCommandState( commandName ) ;
}
}
// Named commands to be handled by this browsers specific implementation.
FCK.RedirectNamedCommands =
{
Print : true,
Paste : true
} ;
// ExecuteNamedCommand overload for Gecko.
FCK.ExecuteRedirectedNamedCommand = function( commandName, commandParameter )
{
switch ( commandName )
{
case 'Print' :
FCK.EditorWindow.print() ;
break ;
case 'Paste' :
try
{
// Force the paste dialog for Safari (#50).
if ( FCKBrowserInfo.IsSafari )
throw '' ;
if ( FCK.Paste() )
FCK.ExecuteNamedCommand( 'Paste', null, true ) ;
}
catch (e) { FCKDialog.OpenDialog( 'FCKDialog_Paste', FCKLang.Paste, 'dialog/fck_paste.html', 400, 330, 'Security' ) ; }
break ;
default :
FCK.ExecuteNamedCommand( commandName, commandParameter ) ;
}
}
FCK._ExecPaste = function()
{
// Save a snapshot for undo before actually paste the text
FCKUndo.SaveUndoStep() ;
if ( FCKConfig.ForcePasteAsPlainText )
{
FCK.PasteAsPlainText() ;
return false ;
}
/* For now, the AutoDetectPasteFromWord feature is IE only. */
return true ;
}
//**
// FCK.InsertHtml: Inserts HTML at the current cursor location. Deletes the
// selected content if any.
FCK.InsertHtml = function( html )
{
var doc = FCK.EditorDocument,
range;
html = FCKConfig.ProtectedSource.Protect( html ) ;
html = FCK.ProtectEvents( html ) ;
html = FCK.ProtectUrls( html ) ;
html = FCK.ProtectTags( html ) ;
// Save an undo snapshot first.
FCKUndo.SaveUndoStep() ;
if ( FCKBrowserInfo.IsGecko )
{
html = html.replace( / $/, '$&<span _fcktemp="1"/>' ) ;
var docFrag = new FCKDocumentFragment( this.EditorDocument ) ;
docFrag.AppendHtml( html ) ;
var lastNode = docFrag.RootNode.lastChild ;
range = new FCKDomRange( this.EditorWindow ) ;
range.MoveToSelection() ;
range.DeleteContents() ;
range.InsertNode( docFrag.RootNode ) ;
range.MoveToPosition( lastNode, 4 ) ;
}
else
doc.execCommand( 'inserthtml', false, html ) ;
this.Focus() ;
// Save the caret position before calling document processor.
if ( !range )
{
range = new FCKDomRange( this.EditorWindow ) ;
range.MoveToSelection() ;
}
var bookmark = range.CreateBookmark() ;
FCKDocumentProcessor.Process( doc ) ;
// Restore caret position, ignore any errors in case the document
// processor removed the bookmark <span>s for some reason.
try
{
range.MoveToBookmark( bookmark ) ;
range.Select() ;
}
catch ( e ) {}
// For some strange reason the SaveUndoStep() call doesn't activate the undo button at the first InsertHtml() call.
this.Events.FireEvent( "OnSelectionChange" ) ;
}
FCK.PasteAsPlainText = function()
{
// TODO: Implement the "Paste as Plain Text" code.
// If the function is called immediately Firefox 2 does automatically paste the contents as soon as the new dialog is created
// so we run it in a Timeout and the paste event can be cancelled
FCKTools.RunFunction( FCKDialog.OpenDialog, FCKDialog, ['FCKDialog_Paste', FCKLang.PasteAsText, 'dialog/fck_paste.html', 400, 330, 'PlainText'] ) ;
/*
var sText = FCKTools.HTMLEncode( clipboardData.getData("Text") ) ;
sText = sText.replace( /\n/g, '<BR>' ) ;
this.InsertHtml( sText ) ;
*/
}
/*
FCK.PasteFromWord = function()
{
// TODO: Implement the "Paste as Plain Text" code.
FCKDialog.OpenDialog( 'FCKDialog_Paste', FCKLang.PasteFromWord, 'dialog/fck_paste.html', 400, 330, 'Word' ) ;
// FCK.CleanAndPaste( FCK.GetClipboardHTML() ) ;
}
*/
FCK.GetClipboardHTML = function()
{
return '' ;
}
FCK.CreateLink = function( url, noUndo )
{
// Creates the array that will be returned. It contains one or more created links (see #220).
var aCreatedLinks = new Array() ;
// Only for Safari, a collapsed selection may create a link. All other
// browser will have no links created. So, we check it here and return
// immediatelly, having the same cross browser behavior.
if ( FCKSelection.GetSelection().isCollapsed )
return aCreatedLinks ;
FCK.ExecuteNamedCommand( 'Unlink', null, false, !!noUndo ) ;
if ( url.length > 0 )
{
// Generate a temporary name for the link.
var sTempUrl = 'javascript:void(0);/*' + ( new Date().getTime() ) + '*/' ;
// Use the internal "CreateLink" command to create the link.
FCK.ExecuteNamedCommand( 'CreateLink', sTempUrl, false, !!noUndo ) ;
// Retrieve the just created links using XPath.
var oLinksInteractor = this.EditorDocument.evaluate("//a[@href='" + sTempUrl + "']", this.EditorDocument.body, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null) ;
// Add all links to the returning array.
for ( var i = 0 ; i < oLinksInteractor.snapshotLength ; i++ )
{
var oLink = oLinksInteractor.snapshotItem( i ) ;
oLink.href = url ;
aCreatedLinks.push( oLink ) ;
}
}
return aCreatedLinks ;
}
FCK._FillEmptyBlock = function( emptyBlockNode )
{
if ( ! emptyBlockNode || emptyBlockNode.nodeType != 1 )
return ;
var nodeTag = emptyBlockNode.tagName.toLowerCase() ;
if ( nodeTag != 'p' && nodeTag != 'div' )
return ;
if ( emptyBlockNode.firstChild )
return ;
FCKTools.AppendBogusBr( emptyBlockNode ) ;
}
FCK._ExecCheckEmptyBlock = function()
{
FCK._FillEmptyBlock( FCK.EditorDocument.body.firstChild ) ;
var sel = FCKSelection.GetSelection() ;
if ( !sel || sel.rangeCount < 1 )
return ;
var range = sel.getRangeAt( 0 );
FCK._FillEmptyBlock( range.startContainer ) ;
}
| JavaScript |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.